url.c 49.5 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1
2
3
4
5
6
7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

25
/**@CFILE url.c
Pekka Pessi's avatar
Pekka Pessi committed
26
27
28
29
30
31
32
33
34
35
 *
 * Implementation of basic URL parsing and handling.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 *
 * @date Created: Thu Jun 29 22:44:37 2000 ppessi
 */

#include "config.h"

36
37
#include <sofia-sip/su_alloc.h>
#include <sofia-sip/bnf.h>
38
#include <sofia-sip/hostdomain.h>
39
#include <sofia-sip/url.h>
Pekka Pessi's avatar
Pekka Pessi committed
40

41
42
#include <sofia-sip/string0.h>

Pekka Pessi's avatar
Pekka Pessi committed
43
44
45
46
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
47
#include <limits.h>
Pekka Pessi's avatar
Pekka Pessi committed
48

Pekka Pessi's avatar
Pekka Pessi committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**@def URL_PRINT_FORMAT
 * Format string used when printing url with printf().
 *
 * The macro URL_PRINT_FORMAT is used in format string of printf() or
 * similar printing functions.  A URL can be printed like this:
 * @code
 *   printf("%s received URL " URL_PRINT_FORMAT "\n", 
 *          my_name, URL_PRINT_ARGS(url));
 * @endcode
 */

/** @def URL_PRINT_ARGS(u)
 * Argument list used when printing url with printf().
 *
 * The macro URL_PRINT_ARGS() is used to create a stdarg list for printf()
 * or similar printing functions.  Using it, a URL can be printed like this:
 *
 * @code
 *   printf("%s received URL " URL_PRINT_FORMAT "\n", 
 *          my_name, URL_PRINT_ARGS(url));
 * @endcode
 */

#define RESERVED        ";/?:@&=+$,"
#define DELIMS          "<>#%\""
#define UNWISE		"{}|\\^[]`"

#define EXCLUDED	RESERVED DELIMS UNWISE

#define UNRESERVED    	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
                      	"abcdefghijklmnopqrstuvwxyz" \
                      	"0123456789" \
                      	"-_.!~*'()"

#define IS_EXCLUDED(u, m32, m64, m96)			\
  (u <= ' '						\
   || u >= '\177'					\
   || (u < 64 ? (m32 & (1 << (63 - u)))			\
       : (u < 96 ? (m64 & (1 << (95 - u)))		\
88
	  : /*u < 128*/ (m96 & (1 << (127 - u))))) != 0)
Pekka Pessi's avatar
Pekka Pessi committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

#define MASKS_WITH_RESERVED(reserved, m32, m64, m96)		\
  if (reserved == NULL) {					\
    m32 = 0xbe19003f, m64 = 0x8000001e, m96 = 0x8000001d;	\
  } else do {							\
    m32 = 0xb400000a, m64 = 0x0000001e, m96 = 0x8000001d;	\
    								\
    for (;reserved[0]; reserved++) {				\
      unsigned r = reserved[0];					\
      RESERVE(r, m32, m64, m96);				\
    }								\
  } while (0)

#define RESERVE(reserved, m32, m64, m96)				\
  if (r < 32)								\
    ;									\
  else if (r < 64)							\
    m32 |= 1U << (63 - r);						\
  else if (r < 96)							\
    m64 |= 1U << (95 - r);						\
  else if (r < 128)							\
    m96 |= 1U << (127 - r)

#define MASKS_WITH_ALLOWED(allowed, mask32, mask64, mask96)	\
  do {								\
    if (allowed) {						\
      for (;allowed[0]; allowed++) {				\
	unsigned a = allowed[0];				\
	ALLOW(a, mask32, mask64, mask96);			\
      }								\
    }								\
  } while (0)

#define ALLOW(a, mask32, mask64, mask96)	\
  if (a < 32)					\
    ;						\
  else if (a < 64)				\
    mask32 &= ~(1U << (63 - a));		\
  else if (a < 96)				\
    mask64 &= ~(1U << (95 - a));		\
  else if (a < 128)				\
    mask96 &= ~(1U << (127 - a))

Pekka Pessi's avatar
Pekka Pessi committed
132
133
134
135
136

#define RMASK1 0xbe19003f
#define RMASK2 0x8000001e
#define RMASK3 0x8000001d

Pekka Pessi's avatar
Pekka Pessi committed
137
138
139
140
141
#define RESERVED_MASK 0xbe19003f, 0x8000001e, 0x8000001d
#define URIC_MASK     0xb400000a, 0x0000001e, 0x8000001d

#define IS_EXCLUDED_MASK(u, m) IS_EXCLUDED(u, m)

Pekka Pessi's avatar
Pekka Pessi committed
142
/* Internal prototypes */
143
144
static char *url_canonize(char *d, char const *s, size_t n,
			  char const allowed[]);
145
static char *url_canonize2(char *d, char const *s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
146
147
148
			   unsigned m32, unsigned m64, unsigned m96);
static int url_tel_cmp_numbers(char const *A, char const *B);

Pekka Pessi's avatar
Pekka Pessi committed
149
/**Test if string contains excluded or url-reserved characters. 
150
151
 *
 * 
Pekka Pessi's avatar
Pekka Pessi committed
152
153
154
155
 *
 * @param s  string to be searched
 *
 * @retval 0 if no reserved characters were found.
156
 * @retval l if a reserved character was found.
Pekka Pessi's avatar
Pekka Pessi committed
157
158
159
160
161
162
163
 */
int url_reserved_p(char const *s)
{
  if (s) 
    while (*s) {
      unsigned char u = *s++;

Pekka Pessi's avatar
Pekka Pessi committed
164
      if (IS_EXCLUDED(u, RMASK1, RMASK2, RMASK3))
Pekka Pessi's avatar
Pekka Pessi committed
165
166
167
168
169
170
	return 1;
    }

  return 0;
}

171
/** Calculate length of string when escaped with %-notation.
Pekka Pessi's avatar
Pekka Pessi committed
172
 *
173
174
 * Calculate the length of string @a s when the excluded or reserved
 * characters in it have been escaped.
Pekka Pessi's avatar
Pekka Pessi committed
175
176
177
178
179
 * 
 * @param s         String with reserved URL characters. [IN
 * @param reserved  Optional array of reserved characters [IN]
 *
 * @return 
180
 * The number of characters in corresponding but escaped string.
Pekka Pessi's avatar
Pekka Pessi committed
181
182
183
184
185
186
187
188
189
190
191
192
 *
 * You can handle a part of URL with reserved characters like this:
 * @code
 * if (url_reserved_p(s))  {
 *   n = malloc(url_esclen(s, NULL) + 1);
 *   if (n) url_escape(n, s);
 * } else {
 *   n = malloc(strlen(s) + 1);
 *   if (n) strcpy(n, s);
 * }
 * @endcode
 */
193
isize_t url_esclen(char const *s, char const reserved[])
Pekka Pessi's avatar
Pekka Pessi committed
194
{
195
  size_t n;
Pekka Pessi's avatar
Pekka Pessi committed
196
197
198
199
200
201
202
203
204
205
206
  unsigned mask32, mask64, mask96;

  MASKS_WITH_RESERVED(reserved, mask32, mask64, mask96);

  for (n = 0; s && *s; n++) {
    unsigned char u = *s++;

    if (IS_EXCLUDED(u, mask32, mask64, mask96))
      n += 2;
  }

207
  return (isize_t)n;
Pekka Pessi's avatar
Pekka Pessi committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
}

/** Escape a string.
 *
 * The function url_escape() copies the string pointed by @a s to the array
 * pointed by @a d, @b excluding the terminating \\0 character.  All reserved
 * characters in @a s are copied in hexadecimal format, for instance, @c
 * "$%#" is copied as @c "%24%25%23".  The destination array @a d must be
 * large enough to receive the escaped copy.
 *
 * @param d         Destination buffer [OUT]
 * @param s         String to be copied [IN]
 * @param reserved  Array of reserved characters [IN]
 *
 * @return Pointer to the destination array.
 */
char *url_escape(char *d, char const *s, char const reserved[])
{
  char *retval = d;
  unsigned mask32, mask64, mask96;
 
  MASKS_WITH_RESERVED(reserved, mask32, mask64, mask96);

  while (s && *s) {
    unsigned char u = *s++;

    if (IS_EXCLUDED(u, mask32, mask64, mask96)) {
#     define URL_HEXIFY(u) ((u) + '0' + ((u) >= 10 ? 'A' - '0' - 10 : 0))

      *d++ = '%';
      *d++ = URL_HEXIFY(u >> 4);
      *d++ = URL_HEXIFY(u & 15);

#     undef URL_HEXIFY
    }
    else {
      *d++ = u;
    }
  }

  *d = '\0';
  
  return retval;
}


254
/**Unescape url-escaped string fragment.
Pekka Pessi's avatar
Pekka Pessi committed
255
 *
256
257
258
259
260
 * Unescape @a n characters from string @a s to the buffer @a d, including
 * the terminating \\0 character. All %-escaped triplets in @a s are
 * unescaped, for instance, @c "%40%25%23" is copied as @c "@%#". The
 * destination array @a d must be large enough to receive the escaped copy
 * (@a n bytes is always enough).
Pekka Pessi's avatar
Pekka Pessi committed
261
262
 *
 * @param d  destination buffer
263
264
 * @param s  string to be unescaped
 * @param n  maximum number of characters to unescape
Pekka Pessi's avatar
Pekka Pessi committed
265
 *
266
 * @return Length of unescaped string
Pekka Pessi's avatar
Pekka Pessi committed
267
 */
268
size_t url_unescape_to(char *d, char const *s, size_t n)
Pekka Pessi's avatar
Pekka Pessi committed
269
{
270
  size_t i = 0, j = 0;
Pekka Pessi's avatar
Pekka Pessi committed
271

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
  if (s == NULL)
    return 0;

  i = j = strncspn(s, n, "%");

  if (d && d != s)
    memmove(d, s, i);

  for (; i < n;) {
    char c = s[i++];

    if (c == '\0')
      break;

    if (c == '%' && i + 1 < n && IS_HEX(s[i]) && IS_HEX(s[i + 1])) {
Pekka Pessi's avatar
Pekka Pessi committed
287
#define   UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
288
      c = (UNHEX(s[i]) << 4) | UNHEX(s[i + 1]);
Pekka Pessi's avatar
Pekka Pessi committed
289
#undef    UNHEX
290
      i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
291
    }
292
293
294
295

    if (d)
      d[j] = c;
    j++;
Pekka Pessi's avatar
Pekka Pessi committed
296
297
  }

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
  return j;
}

/**Unescape url-escaped string.
 *
 * Unescape string @a s to the buffer @a d, including the terminating \\0
 * character. All %-escaped triplets in @a s are unescaped, for instance, @c
 * "%40%25%23" is copied as @c "@%#". The destination array @a d must be
 * large enough to receive the escaped copy.
 *
 * @param d  destination buffer
 * @param s  string to be copied
 *
 * @return Pointer to the destination buffer.
 */
char *url_unescape(char *d, char const *s)
{
  size_t n = url_unescape_to(d, s, SIZE_MAX);
  if (d)
    d[n] = '\0';
  return d;
Pekka Pessi's avatar
Pekka Pessi committed
319
320
321
322
}

/** Canonize a URL component */
static
323
char *url_canonize(char *d, char const *s, size_t n, char const allowed[])
Pekka Pessi's avatar
Pekka Pessi committed
324
325
326
327
328
329
330
331
332
333
{
  unsigned mask32 = 0xbe19003f, mask64 = 0x8000001e, mask96 = 0x8000001d;

  MASKS_WITH_ALLOWED(allowed, mask32, mask64, mask96);

  return url_canonize2(d, s, n, mask32, mask64, mask96);
}

/** Canonize a URL component (with precomputed mask) */
static
334
char *url_canonize2(char *d, char const * const s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
335
336
		    unsigned m32, unsigned m64, unsigned m96)
{
337
  size_t i = 0;
Pekka Pessi's avatar
Pekka Pessi committed
338
339

  if (d == s)
340
341
    for (;s[i] && i < n; d++, i++) 
      if (s[i] == '%')
Pekka Pessi's avatar
Pekka Pessi committed
342
343
	break;

344
345
  for (;s[i] && i < n; d++, i++) {
    unsigned char c = s[i], h1, h2;
Pekka Pessi's avatar
Pekka Pessi committed
346
347
348
349
350
351
352

    if (c != '%') {
      if (IS_EXCLUDED(c, m32, m64, m96))
	return NULL;
      *d = c;
      continue;
    }
353

354
    h1 = s[i + 1], h2 = s[i + 2];
Pekka Pessi's avatar
Pekka Pessi committed
355
    
356
    if (!IS_HEX(h1) || !IS_HEX(h2)) {
Pekka Pessi's avatar
Pekka Pessi committed
357
358
359
360
361
      *d = '\0';
      return NULL;
    }
    
#define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
362
    c = (UNHEX(h1) << 4) | UNHEX(h2);
Pekka Pessi's avatar
Pekka Pessi committed
363

364
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
365
366
      /* Convert hex to normal character */
      *d = c, i += 2;
367
368
369
370
371
372
373
374
375
376
377
      continue;
    }

    /* Convert hex to uppercase */
    if (h1 >= 'a' /* && h1 <= 'f' */)
      h1 = h1 - 'a' + 'A';
    if (h2 >= 'a' /* && h2 <= 'f' */)
      h2 = h2 - 'a' + 'A';

    d[0] = '%', d[1] = h1, d[2] = h2;

378
    d +=2, i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
379
380
381
382
383
384
385
386
#undef    UNHEX
  }
  
  *d = '\0';

  return d;
}

387

388
389
390
391
392
/** Canonize a URL component (with precomputed mask).
 *
 * This version does not flag error if *s contains character that should 
 * be escaped.
 */
Pekka Pessi's avatar
Pekka Pessi committed
393
static
394
char *url_canonize3(char *d, char const * const s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
395
396
		    unsigned m32, unsigned m64, unsigned m96)
{
397
  size_t i = 0;
Pekka Pessi's avatar
Pekka Pessi committed
398
399

  if (d == s)
400
401
    for (;s[i] && i < n; d++, i++) 
      if (s[i] == '%')
Pekka Pessi's avatar
Pekka Pessi committed
402
403
	break;

404
405
  for (;s[i] && i < n; d++, i++) {
    unsigned char c = s[i], h1, h2;
Pekka Pessi's avatar
Pekka Pessi committed
406
407
408
409
410

    if (c != '%') {
      *d = c;
      continue;
    }
411

412
    h1 = s[i + 1], h2 = s[i + 2];
Pekka Pessi's avatar
Pekka Pessi committed
413
    
414
    if (!IS_HEX(h1) || !IS_HEX(h2)) {
Pekka Pessi's avatar
Pekka Pessi committed
415
416
417
418
419
      *d = '\0';
      return NULL;
    }
    
#define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
420
    c = (UNHEX(h1) << 4) | UNHEX(h2);
Pekka Pessi's avatar
Pekka Pessi committed
421

422
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
423
      *d = c, i += 2;
424
425
426
427
428
429
430
431
432
433
434
      continue;
    }

    /* Convert hex to uppercase */
    if (h1 >= 'a' /* && h1 <= 'f' */)
      h1 = h1 - 'a' + 'A';
    if (h2 >= 'a' /* && h2 <= 'f' */)
      h2 = h2 - 'a' + 'A';

    d[0] = '%', d[1] = h1, d[2] = h2;

435
    d +=2, i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#undef    UNHEX
  }
  
  *d = '\0';

  return d;
}


/** Get URL scheme. */
char const* url_scheme(enum url_type_e url_type)
{
  switch (url_type) {
  case url_any:    return "*";
  case url_sip:    return "sip";
  case url_sips:   return "sips";
  case url_tel:    return "tel";
  case url_fax:    return "fax";
  case url_modem:  return "modem";
  case url_http:   return "http";
  case url_https:  return "https";
  case url_ftp:    return "ftp";
  case url_file:   return "file";
  case url_rtsp:   return "rtsp";
  case url_rtspu:  return "rtspu";
  case url_mailto: return "mailto";
  case url_im:     return "im";
  case url_pres:   return "pres";
  case url_cid:    return "cid";
  case url_msrp:   return "msrp";
Remi Denis-Courmont's avatar
Remi Denis-Courmont committed
466
  case url_msrps:  return "msrps";
Pekka Pessi's avatar
Pekka Pessi committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
  case url_wv:     return "wv";
  default:       
    assert(url_type == url_unknown);
    return NULL;
  }
}

static inline
int url_type_is_opaque(enum url_type_e url_type)
{
  return 
    url_type == url_invalid ||
    url_type == url_tel || 
    url_type == url_modem || 
    url_type == url_fax ||
    url_type == url_cid;
}

/** Init an url as given type */
void url_init(url_t *url, enum url_type_e type)
{
  memset(url, 0, sizeof(*url));
  url->url_type = type;
  if (type > url_unknown) {
    char const *scheme = url_scheme(url->url_type);
    if (scheme)
      url->url_scheme = scheme;
  }
}

/** Get url type */
static inline
499
enum url_type_e url_get_type(char const *scheme, size_t len)
Pekka Pessi's avatar
Pekka Pessi committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
{
#define test_scheme(s) \
   if (len == strlen(#s) && !strncasecmp(scheme, #s, len)) return url_##s
  
  switch (scheme[0]) {
  case '*': if (strcmp(scheme, "*") == 0) return url_any;
  case 'c': case 'C': 
    test_scheme(cid); break;
  case 'f': case 'F': 
    test_scheme(ftp); test_scheme(file); test_scheme(fax); break;
  case 'h': case 'H': 
    test_scheme(http); test_scheme(https); break;
  case 'i': case 'I': 
    test_scheme(im); break;
  case 'm': case 'M': 
    test_scheme(mailto); test_scheme(modem); 
Remi Denis-Courmont's avatar
Remi Denis-Courmont committed
516
    test_scheme(msrp); test_scheme(msrps); break;
Pekka Pessi's avatar
Pekka Pessi committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
  case 'p': case 'P': 
    test_scheme(pres); break;
  case 'r': case 'R': 
    test_scheme(rtsp); test_scheme(rtspu); break;
  case 's': case 'S': 
    test_scheme(sip); test_scheme(sips); break;
  case 't': case 'T': 
    test_scheme(tel); break;
  case 'w': case 'W': 
    test_scheme(wv); break;


  default: break;
  }

#undef test_scheme

  if (len != span_unreserved(scheme))
    return url_invalid;
  else
    return url_unknown;
}

/**
 * Decode a URL.
 *
 * This function decodes a (SIP) URL string to a url_t structure.
 *
 * @param url structure to store the parsing result
 * @param s   NUL-terminated string to be parsed
 *
 * @note The parsed string @a s will be modified when parsing it.
 *
 * @retval 0 if successful, 
 * @retval -1 otherwise.
 */
static
int _url_d(url_t *url, char *s)
{
556
  size_t n;
Pekka Pessi's avatar
Pekka Pessi committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
  char *s0, rest_c, *host;
  int net_path = 1;

  memset(url, 0, sizeof(*url));
  
  if (strcmp(s, "*") == 0) {
    url->url_type = url_any;
    url->url_scheme = "*";
    return 0;
  }

  s0 = s;

  n = strcspn(s, ":/?#");

  if (n && s[n] == ':') {
    char *scheme;
    url->url_scheme = scheme = s; s[n] = '\0'; s = s + n + 1;

576
    if (!(scheme = url_canonize(scheme, scheme, SIZE_MAX, "+")))
Pekka Pessi's avatar
Pekka Pessi committed
577
578
579
580
581
582
583
      return -1;

    n = scheme - url->url_scheme;

    url->url_type = url_get_type(url->url_scheme, n);

    net_path = !url_type_is_opaque(url->url_type);
584
585
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
    url->url_type = url_unknown;
  }

  host = s;

  if (url->url_type == url_sip || url->url_type == url_sips) {
    /* SIP URL may have /; in user part */
    n = strcspn(s, "@#");	/* Opaque part */
    if (s[n] != '@')
      n = 0;
    n += strcspn(s + n, "/;?#");
  }
  else if (url->url_type == url_wv) {
    /* WV URL may have / in user part */
    n = strcspn(s, "@#?;");
    if (s[n] == '@')
      n += strcspn(s + n, ";?#");
  }
  else if (url->url_type == url_invalid) {
    n = strcspn(s, "#");
Pekka Pessi's avatar
Pekka Pessi committed
606
607
  }
  else if (net_path && host[0] == '/') {
Pekka Pessi's avatar
Pekka Pessi committed
608
609
610
611
612
613
614
615
    url->url_root = host[0];	/* Absolute path */

    if (host[1] == '/') {	/* We have host-part */
      host += 2; s += 2;
    }
    else 
      host = NULL;
    n = strcspn(s, "/;?#");	/* Find path, query and/or fragment */
Pekka Pessi's avatar
Pekka Pessi committed
616
617
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
618
619
620
621
622
623
624
625
626
627
628
    n = strcspn(s, "/;?#");	/* Find params, query and/or fragment */
  }

  rest_c = s[n]; s[n] = 0; s = rest_c ? s + n + 1 : NULL;

  if (host) {
    char *atsign, *port;

    if (!net_path) {
      url->url_user = host;
      host = NULL;
629
630
    }
    else if ((atsign = strchr(host, '@'))) {
Pekka Pessi's avatar
Pekka Pessi committed
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
      char *user;

      url->url_user = user = host;

      if (atsign)
	*atsign++ = '\0';
      host = atsign;

      if (url->url_type != url_unknown) {
	char *colon = strchr(user, ':');
	if (colon)
	  *colon++ = '\0';
	url->url_password = colon;
      }
    }

    if ((url->url_host = host)) {
      /* IPv6 (and in some cases, IPv4) addresses are quoted with [] */
      if (host[0] == '[') {
	port = strchr(host, ']');
	if (!port)
	  return -1;
	port = strchr(port + 1, ':');
      }
      else 
	port = strchr(host, ':');

      if (port) {
	*port++ = '\0';
	url->url_port = port;
	switch (url->url_type) {
	case url_any:
	case url_sip:
	case url_sips:
	case url_http:
	case url_https:
	case url_ftp:
	case url_file:
	case url_rtsp:
	case url_rtspu:
	  
672
	  if (!url_canonize2(port, port, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
	    return -1;

	  /* Check that port is really numeric or wildcard */
	  /* Port can be *digit, empty string or "*" */
	  while (*port >= '0' && *port <= '9')
	    port++;
	  if (port != url->url_port 
	      ? port[0] != '\0' 
	      : port[0] != '\0'
	      && (port[0] != '*' || port[1] != '\0'))
	    return -1;
	}
      }
    }
  }

  if (rest_c == '/') {
    url->url_path = s; n = strcspn(s, "?#");
    rest_c = s[n]; s[n] = 0; s = rest_c ? s + n + 1 : NULL;
  }
  if (rest_c == ';') {
    url->url_params = s; n = strcspn(s, "?#");
    rest_c = s[n]; s[n] = 0; s = rest_c ? s + n + 1 : NULL;
  }
  if (rest_c == '?') {
    url->url_headers = s; n = strcspn(s, "#");
    rest_c = s[n]; s[n] = 0; s = rest_c ? s + n + 1 : NULL;
  }
  if (rest_c == '#') {
    url->url_fragment = s;
    rest_c = '\0';
  }
  if (rest_c)
    return -1;

  return 0;
}

/* Unreserved things */

/**
 * Decode a URL.
 *
 * This function decodes a URL string to a url_t structure.
 *
 * @param url structure to store the parsing result
 * @param s   NUL-terminated string to be parsed
 *
 * @note The parsed string @a s will be modified when parsing it.
 *
 * @retval 0 if successful, 
 * @retval -1 otherwise.
 */
int url_d(url_t *url, char *s)
{
  if (url == NULL || _url_d(url, s) < 0)
    return -1;

  /* Canonize  URL */
  /* scheme is canonized by _url_d() */
  if (url->url_type == url_sip || url->url_type == url_sips) {

#   define SIP_USER_UNRESERVED "&=+$,;?/"
    s = (char *)url->url_user;
737
    if (s && !url_canonize(s, s, SIZE_MAX, SIP_USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
738
739
740
741
      return -1;

#   define SIP_PASS_UNRESERVED "&=+$,"
    s = (char *)url->url_password;
742
    if (s && !url_canonize(s, s, SIZE_MAX, SIP_PASS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
743
744
745
746
747
748
      return -1;

  } else {

#   define USER_UNRESERVED "&=+$,;"
    s = (char *)url->url_user;
749
    if (s && !url_canonize(s, s, SIZE_MAX, USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
750
751
752
753
      return -1;

#   define PASS_UNRESERVED "&=+$,;:"
    s = (char *)url->url_password;
754
    if (s && !url_canonize(s, s, SIZE_MAX, PASS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
755
756
757
758
      return -1;
  }

  s = (char *)url->url_host;
759
  if (s && !url_canonize2(s, s, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
760
761
762
763
764
765
766
    return -1;

  /* port is canonized by _url_d() */

  /* Allow all URI characters but ? and ; */
# define PATH_UNRESERVED "/:@&=+$,"
  s = (char *)url->url_path;
767
  if (s && !url_canonize(s, s, SIZE_MAX, PATH_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
768
769
770
771
772
    return -1;

  /* Allow all URI characters but ? */
# define PARAMS_UNRESERVED ";" PATH_UNRESERVED
  s = (char *)url->url_params;
773
  if (s && !url_canonize(s, s, SIZE_MAX, PARAMS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
774
775
776
777
    return -1;
  
  /* Unhex alphanumeric and unreserved URI characters */
  s = (char *)url->url_headers;
778
  if (s && !url_canonize3(s, s, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
779
780
781
782
    return -1;

  /* Allow all URI characters (including reserved ones) */
  s = (char *)url->url_fragment;
783
  if (s && !url_canonize2(s, s, SIZE_MAX, URIC_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
    return -1;

  return 0;
}

/** Encode an URL. 
 * 
 * The function url_e() combines a URL from substrings in url_t structure
 * according the @ref url_syntax "URL syntax" presented above.  The encoded
 * @a url is stored in a @a buffer of @a n bytes.
 *
 * @param buffer memory area to store the encoded @a url.
 * @param n      size of @a buffer.
 * @param url    URL to be encoded.
 *
 * @return 
800
 * Return the number of bytes in the encoding.  
Pekka Pessi's avatar
Pekka Pessi committed
801
802
803
804
805
 *
 * @note The function follows the convention set by C99 snprintf().  Even if
 * the result does not fit into the @a buffer and it is truncated, the
 * function returns the number of bytes in an untruncated encoding.
 */
806
issize_t url_e(char buffer[], isize_t n, url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
807
{
808
  size_t i;
Pekka Pessi's avatar
Pekka Pessi committed
809
  char *b = buffer;
810
  size_t m = n;
Pekka Pessi's avatar
Pekka Pessi committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
  int do_copy = n > 0;

  if (url == NULL)
    return -1;

  if (URL_STRING_P(url)) {
    char const *u = (char *)url;
    i = strlen(u);
    if (!buffer)
      return i;

    if (i >= n) {
      memcpy(buffer, u, n - 2);
      buffer[n - 1] = '\0';
    } else {
      memcpy(buffer, u, i + 1);
    }

    return i;
  }


  if (url->url_type == url_any) {
    if (b && m > 0) {
      if (m > 1) strcpy(b, "*"); else b[0] = '\0';
    }
    return 1;
  }

  if (url->url_scheme && url->url_scheme[0]) {
    i = strlen(url->url_scheme) + 1;
    if (do_copy && (do_copy = i <= n)) {
      memcpy(b, url->url_scheme, i - 1);
      b[i - 1] = ':';
    }
    b += i; n -= i;
  }

  if (url->url_root && (url->url_host || url->url_user)) {
    if (do_copy && (do_copy = 2 <= n))
      memcpy(b, "//", 2);
    b += 2; n -= 2;
  }

  if (url->url_user) {
    i = strlen(url->url_user);
    if (do_copy && (do_copy = i <= n))
      memcpy(b, url->url_user, i);
    b += i; n -= i;

    if (url->url_password) {
      if (do_copy && (do_copy = 1 <= n))
	*b = ':'; 
      b++; n--;
      i = strlen(url->url_password);
      if (do_copy && (do_copy = i <= n))
	memcpy(b, url->url_password, i);
      b += i; n -= i;
    }

    if (url->url_host) {
      if (do_copy && (do_copy = 1 <= n))
	*b = '@'; 
      b++; n--;
    }
  }

  if (url->url_host) {
    i = strlen(url->url_host);
    if (do_copy && (do_copy = i <= n))
      memcpy(b, url->url_host, i);
    b += i; n -= i;

    if (url->url_port) {
      i = strlen(url->url_port) + 1;
      if (do_copy && (do_copy = i <= n)) {
	b[0] = ':';
	memcpy(b + 1, url->url_port, i - 1);
      } 
      b += i; n -= i;
    }
  }

  if (url->url_path) {
    if (url->url_root) {
      if (do_copy && (do_copy = 1 <= n))
	b[0] = '/';
      b++, n--;
    }
    i = strlen(url->url_path);
    if (do_copy && (do_copy = i < n))
      memcpy(b, url->url_path, i);
    b += i; n -= i;
  }
  
  {
    static char const sep[] = ";?#";
    char const *pp[3];
909
    size_t j;
Pekka Pessi's avatar
Pekka Pessi committed
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931

    pp[0] = url->url_params;
    pp[1] = url->url_headers;
    pp[2] = url->url_fragment;

    for (j = 0; j < 3; j++) {
      char const *p = pp[j];
      if (!p) continue;
      i = strlen(p) + 1;
      if (do_copy && (do_copy = i <= n)) {
	*b = sep[j];
	memcpy(b + 1, p, i - 1);
      }
      b += i; n -= i;
    }
  }

  if (do_copy && (do_copy = 1 <= n))
    *b = '\0';
  else if (buffer && m > 0)
    buffer[m - 1] = '\0';

932
  assert((size_t)(b - buffer) == (size_t)(m - n));
Pekka Pessi's avatar
Pekka Pessi committed
933
934
935
936
937
938
939
940
941
942
943
  
  /* This follows the snprintf(C99) return value, 
   * Number of characters written (excluding NUL)
   */
  return b - buffer;
}


/** Calculate the lengh of URL when encoded. 
 *
 */
944
isize_t url_len(url_t const * url)
Pekka Pessi's avatar
Pekka Pessi committed
945
{
946
  size_t rv = 0;
Pekka Pessi's avatar
Pekka Pessi committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964

  if (url->url_scheme) rv += strlen(url->url_scheme) + 1; /* plus ':' */
  if (url->url_user) {
    rv += strlen(url->url_user);
    if (url->url_password) 
      rv += strlen(url->url_password) + 1;   /* plus ':' */
    rv += url->url_host != NULL;  /* plus '@' */
  }
  if (url->url_host) rv += strlen(url->url_host);
  if (url->url_port) rv += strlen(url->url_port) + 1;	        /* plus ':' */
  if (url->url_path) rv += strlen(url->url_path) + 1;     /* plus initial / */
  if (url->url_params) rv += strlen(url->url_params) + 1; /* plus initial ; */
  if (url->url_headers) rv += strlen(url->url_headers) + 1;	/* plus '?' */
  if (url->url_fragment) rv += strlen(url->url_fragment) + 1;   /* plus '#' */

  return rv;
}

Pekka Pessi's avatar
Pekka Pessi committed
965
/**@def URL_E(buf, end, url)
Pekka Pessi's avatar
Pekka Pessi committed
966
 * Encode an URL: use @a buf up to @a end. 
Pekka Pessi's avatar
Pekka Pessi committed
967
 * @hideinitializer
Pekka Pessi's avatar
Pekka Pessi committed
968
969
970
971
972
973
974
975
 */

/** 
 * Calculate the size of strings associated with a #url_t sructure.
 *
 * @param url pointer to a #url_t structure or string
 * @return Number of bytes for URL
 */
976
isize_t url_xtra(url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
977
{
978
979
  size_t xtra;

Pekka Pessi's avatar
Pekka Pessi committed
980
  if (URL_STRING_P(url)) {
981
    xtra = strlen((char const *)url) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
982
983
  }
  else {
984
    size_t len_scheme, len_user, len_password,
Pekka Pessi's avatar
Pekka Pessi committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
      len_host, len_port, len_path, len_params, 
      len_headers, len_fragment;

    len_scheme = (url->url_type <= url_unknown && url->url_scheme) ?
      strlen(url->url_scheme) + 1 : 0;
    len_user = url->url_user ? strlen(url->url_user) + 1 : 0;
    len_password = url->url_password ? strlen(url->url_password) + 1 : 0;
    len_host = url->url_host ? strlen(url->url_host) + 1 : 0;
    len_port = url->url_port ? strlen(url->url_port) + 1 : 0;
    len_path = url->url_path ? strlen(url->url_path) + 1 : 0;
    len_params = url->url_params ? strlen(url->url_params) + 1 : 0;
    len_headers = url->url_headers ? strlen(url->url_headers) + 1 : 0;
    len_fragment = url->url_fragment ? strlen(url->url_fragment) + 1 : 0;

999
    xtra =
Pekka Pessi's avatar
Pekka Pessi committed
1000
1001
1002
      len_scheme + len_user + len_password + len_host + len_port +
      len_path + len_params + len_headers + len_fragment;
  }
1003
1004

  return xtra;
Pekka Pessi's avatar
Pekka Pessi committed
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
}

static inline
char *copy(char *buf, char *end, char const *src)
{
#if HAVE_MEMCCPY
  char *b = memccpy(buf, src, '\0', end - buf);
  if (b)
    return b;
  else
    return end + strlen(src + (end - buf)) + 1;
#else
  for (; buf < end && (*buf = *src); buf++, src++)
    ;

  if (buf >= end) 
    while (*src++)
      buf++;

  return buf + 1;
#endif
}

/** 
 * Duplicate the url.
 * 
 * The function url_dup() copies the url structure @a src and the strings
 * attached to it to @a url.  The non-constant strings in @a src are copied
 * to @a buf.  If the size of duplicated strings exceed @a bufsize, the 
 * corresponding string fields in @a url are set to NULL.
 *
 * The calling function can calculate the size of buffer required by calling
 * url_dup() with zero as @a bufsize and NULL as @a dst.

 * @param buf     Buffer for non-constant strings copied from @a src.
 * @param bufsize Size of @a buf.
 * @param dst     Destination URL structure.
 * @param src     Source URL structure.
 *
1044
 * @return Number of characters required for
Pekka Pessi's avatar
Pekka Pessi committed
1045
1046
1047
 * duplicating the strings in @a str, or -1 if an error
 * occurred.
 */
1048
issize_t url_dup(char *buf, isize_t bufsize, url_t *dst, url_t const *src)
Pekka Pessi's avatar
Pekka Pessi committed
1049
1050
1051
1052
{
  if (!src && !dst)
    return -1;
  else if (URL_STRING_P(src)) {
1053
    size_t n = strlen((char *)src) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
    if (n > bufsize || dst == NULL)
      return n;

    strcpy(buf, (char *)src);
    memset(dst, 0, sizeof(*dst));
    if (url_d(dst, buf) < 0)
      return -1;

    return n;
  }
  else {
    char *b = buf;
    char *end = b + bufsize;
    char const **dstp; 
    char const * const *srcp;
    url_t dst0[1];

    if (dst == NULL)
      dst = dst0;

    memset(dst, 0, sizeof(*dst));

    if (!src)
      return 0;

    memset(dst->url_pad, 0, sizeof dst->url_pad);
    dst->url_type = src->url_type;
    dst->url_root = src->url_root;

    dstp = &dst->url_scheme;
    srcp = &src->url_scheme;

    if (dst->url_type > url_unknown)
      *dstp = url_scheme(dst->url_type);

    if (*dstp != NULL)
      dstp++, srcp++;	/* Skip scheme if it is constant */

    if (dst != dst0 && buf != NULL && bufsize != 0)
      for (; srcp <= &src->url_fragment; srcp++, dstp++)
	if (*srcp) {
	  char *next = copy(b, end, *srcp);

	  if (next > end)
	    break;

	  *dstp = b, b = next;
	}

    for (; srcp <= &src->url_fragment; srcp++)
      if (*srcp) {
	b += strlen(*srcp) + 1;
      }

    return b - buf;
  }
}

/**@def URL_DUP(buf, end, dst, src)
 *  Duplicate the url: use @a buf up to @a end. @HI 
 *
 * The macro URL_DUP() duplicates the url.  The non-constant strings in @a
 * src are copied to @a buf.  However, no strings are copied past @a end.
 * In other words, the size of buffer is @a end - @a buf.
 *
 * The macro updates the buffer pointer @a buf, so that it points to the
 * first unused byte in the buffer.  The buffer pointer @a buf is updated,
 * even if the buffer is too small for the duplicated strings.
 *
 * @param buf     Buffer for non-constant strings copied from @a src.
 * @param end     End of @a buf.
 * @param dst     Destination URL structure.
 * @param src     Source URL structure.
 *
 * @return 
 * The macro URL_DUP() returns pointer to first unused byte in the 
 * buffer @a buf.
 */

/** Duplicate the url to memory allocated via home.
 *
 * The function url_hdup() duplicates (deep copies) an #url_t structure. 
 * Alternatively, it can be passed a string; string is then copied and
 * parsed to the #url_t structure.
 *
 * The function url_hdup() allocates the destination structure from @a home
 * as a single memory block. It is possible to free the copied url structure
 * and all the associated strings using a single call to su_free().
 *
 * @param home memory home used to allocate new url object
 * @param src  pointer to URL (or string)
 *
 * @return
 * The function url_hdup() returns a pointer to the newly allocated #url_t
 * structure, or NULL upon an error.
 */ 
url_t *url_hdup(su_home_t *home, url_t const *src)
{
  if (src) {
1153
    size_t len = sizeof(*src) + url_xtra(src);
Pekka Pessi's avatar
Pekka Pessi committed
1154
1155
    url_t *dst = su_alloc(home, len);
    if (dst) {
1156
      ssize_t actual;
Pekka Pessi's avatar
Pekka Pessi committed
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
      actual = url_dup((char *)(dst + 1), len - sizeof(*src), dst, src);
      if (actual < 0)
	su_free(home, dst), dst = NULL;
      else
	assert(len == sizeof(*src) + actual);
    }
    return dst;
  }
  else
    return NULL;
}


/** Convert an string to an url */ 
url_t *url_make(su_home_t *h, char const *str)
{
  return url_hdup(h, URL_STRING_MAKE(str)->us_url);
}

/** Print an URL */ 
url_t *url_format(su_home_t *h, char const *fmt, ...)
{
  url_t *url;
  char *us;
  va_list ap;

  va_start(ap, fmt);

  us = su_vsprintf(h, fmt, ap);

  va_end(ap);

  if (us == NULL)
    return NULL;

  url = url_hdup(h, URL_STRING_MAKE(us)->us_url);

  su_free(h, us);

  return url;
}


1200
1201
1202
1203
1204
1205
1206
1207
1208
/** Convert @a url to a string allocated from @a home.
 *
 * @param home memory home to allocate the new string
 * @param url  url to convert to string
 *
 * The @a url can be a string, too.
 *
 * @return Newly allocated conversion result, or NULL upon an error.
 */
Pekka Pessi's avatar
Pekka Pessi committed
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
char *url_as_string(su_home_t *home, url_t const *url)
{
  if (url) {
    int len = url_e(NULL, 0, url);
    char *b = su_alloc(home, len + 1);
    url_e(b, len + 1, url);
    return b;
  } else {
    return NULL;
  }
}


/** Test if param @a tag matches to parameter string @a p. 
 */
#define URL_PARAM_MATCH(p, tag) \
 (strncasecmp(p, tag, strlen(tag)) == 0 && \
  (p[strlen(tag)] == '\0' || p[strlen(tag)] == ';' || p[strlen(tag)] == '='))

/**
 * Search for a parameter.
 *
 * This function searches for a parameter from a parameter list.
 *
 * If you want to test if there is parameter @b user=phone, 
 * call this function like 
 * @code if (url_param(url->url_param, "user=phone", NULL, 0))
 * @endcode
 *
 * @param params URL parameter string (excluding first semicolon)
 * @param tag    parameter name
 * @param value  string to which the parameter value is copied
 * @param vlen   length of string reserved for value
 *
 * @retval positive length of parameter value (including final NUL) if found
 * @retval zero     if not found.
 */
1246
1247
1248
isize_t url_param(char const *params, 
		  char const *tag, 
		  char value[], isize_t vlen)
Pekka Pessi's avatar
Pekka Pessi committed
1249
{
Pekka Pessi's avatar
Pekka Pessi committed
1250
  size_t n, tlen, flen;
Pekka Pessi's avatar
Pekka Pessi committed
1251
  char *p;
Pekka Pessi's avatar
Pekka Pessi committed
1252

Pekka Pessi's avatar
Pekka Pessi committed
1253
1254
1255
  if (!params)
    return 0;

Pekka Pessi's avatar
Pekka Pessi committed
1256
1257
1258
1259
  tlen = strlen(tag);
  if (tlen && tag[tlen - 1] == '=')
    tlen--;

Pekka Pessi's avatar
Pekka Pessi committed
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
  for (p = (char *)params; *p; p += n + 1) {
    n = strcspn(p, ";");
    if (n < tlen) {
      if (p[n]) continue; else break;
    }
    if (strncasecmp(p, tag, tlen) == 0) {
      if (n == tlen) {
	if (vlen > 0)
	  value[0] = '\0';	
	return 1;
      }
      if (p[tlen] != '=')
	continue;
      flen = n - tlen - 1;
      if (flen >= (size_t)vlen)
	return flen + 1;
      memcpy(value, p + tlen + 1, flen);
      value[flen] = '\0';
      return flen + 1;
    }
    if (!p[n])
      break;
  }

  return 0;
}

/** Check for a parameter. 
 *
 * @deprecated 
 * Bad grammar. Use url_has_param().
 */
1292
isize_t url_have_param(char const *params, char const *tag)
Pekka Pessi's avatar
Pekka Pessi committed
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
{
  return url_param(params, tag, NULL, 0);
}

/** Check for a parameter. */
int url_has_param(url_t const *url, char const *tag)
{
  return url && url->url_params && url_param(url->url_params, tag, NULL, 0);
}

/** Add an parameter. */
int url_param_add(su_home_t *h, url_t *url, char const *param)
{
Pekka Pessi's avatar
Pekka Pessi committed
1306
  /* XXX - should remove existing parameters with same name? */
1307
1308
  size_t n = url->url_params ? strlen(url->url_params) + 1: 0;
  size_t nn = strlen(param) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
  char *s = su_alloc(h, n + nn);

  if (!s)
    return -1;
  
  if (url->url_params)
    strcpy(s, url->url_params)[n - 1] = ';';
  strcpy(s + n, param);
  url->url_params = s;

  return 0;
}

1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
/** Remove a named parameter from url_param string.
 *
 * Remove a named parameter and its possible value from the URL parameter
 * string (url_s##url_param).
 *
 * @return Pointer to modified string, or NULL if nothing is left in there.
 */
char *url_strip_param_string(char *params, char const *name)
{
  if (params && name) {
    size_t i, n = strlen(name), remove, rest;
    
    for (i = 0; params[i];) {
      if (strncasecmp(params + i, name, n) ||
	  (params[i + n] != '=' && params[i + n] != ';' && params[i + n])) {
	i = i + strcspn(params + i, ";");
	if (!params[i++])
	  break;
	continue;
      }
      remove = n + strcspn(params + i + n, ";");
      if (params[i + remove] == ';')
	remove++;

      if (i == 0) {
	params += remove;
	continue;
      }

      rest = strlen(params + i + remove);
      if (!rest) {
	if (i == 0)
	  return NULL;		/* removed everything */
	params[i - 1] = '\0';
	break;
      }
      memmove(params + i, params + i + remove, rest + 1);
    }

    if (!params[0])
      return NULL;
  }

  return params;
}

Pekka Pessi's avatar
Pekka Pessi committed
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
int url_string_p(url_string_t const *url)
{
  return URL_STRING_P(url);
}

int url_is_string(url_string_t const *url)
{
  return URL_IS_STRING(url);
}

/** Strip transport-specific stuff. */
static
int url_strip_transport2(url_t *url, int modify)
{
  char *p, *d;
  size_t n;
  int semi;

  if (url->url_type != url_sip && url->url_type != url_sips)
    return 0;
  
  if (url->url_port != NULL) {
    if (!modify)
      return 1;
    url->url_port = NULL;
  }

  if (!url->url_params)
    return 0;

  for (d = p = (char *)url->url_params; *p; p += n + semi) {
    n = strcspn(p, ";");
    semi = (p[n] != '\0');

    if (modify && n == 0)
      continue;
    if (URL_PARAM_MATCH(p, "method"))
      continue;
    if (URL_PARAM_MATCH(p, "maddr"))
      continue;
    if (URL_PARAM_MATCH(p, "ttl"))
      continue;
    if (URL_PARAM_MATCH(p, "transport"))
      continue;

    if (p != d) {
      if (d != url->url_params)
	d++;
      if (p != d) {
	if (!modify)
	  return 1;
1419
	memmove(d, p, n + 1);
Pekka Pessi's avatar
Pekka Pessi committed
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
      }
    }
    d += n;
  }

  if (d == p)
    return 0;
  else if (d + 1 == p)		/* empty param */
    return 0;
  else if (!modify)
    return 1;

  if (d != url->url_params)
    *d = '\0';
  else 
    url->url_params = NULL;

  return 1;
}

/** Strip transport-specific stuff. 
 *
 * The function url_strip_transport() removes transport-specific parameters
 * from a SIP or SIPS URI.  These parameters include:
 * - the port number
 * - "maddr=" parameter
 * - "transport=" parameter
 * - "ttl=" parameter
 * - "method=" parameter
 *
 * @note
1451
 * The @a url must be a pointer to a URL structure. It is stripped in-place.
Pekka Pessi's avatar
Pekka Pessi committed
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
 *
 * @note
 * If the parameter string contains empty parameters, they are stripped, too.
 *
 * @return 
 * The function url_strip_transport() returns @e true, if the URL was
 * modified, @e false otherwise.
 */
int url_strip_transport(url_t *url)
{
  return url_strip_transport2(url, 1);
}

/** Check for transport-specific stuff. 
 *
 * The function url_have_transport() tests if there are transport-specific
 * parameters in a SIP or SIPS URI. These parameters include:
 * - the port number
 * - "maddr=" parameters
 * - "transport=" parameters
 * 
 * @note
 * The @a url must be a pointer to a URL structure.
 *
 * @return The function url_have_transport() returns @e true, if the URL
 * contains transport parameters, @e false otherwise.
 */
int url_have_transport(url_t const *url)
{
  return url_strip_transport2((url_t *)url, 0);
}

Pekka Pessi's avatar
Pekka Pessi committed
1484
1485
1486
1487
1488
1489
1490
/**Lazily compare two URLs.
 *
 * Compare essential parts of URLs: schema, host, port, and username.
 *
 * any_url compares 0 with any other URL.
 *
 * pres: and im: URIs compares 0 with SIP URIs.
Pekka Pessi's avatar
Pekka Pessi committed
1491
1492
1493
 *
 * @note
 * The @a a and @a b must be pointers to URL structures.
1494
1495
1496
 *
 * @note Currently, the url parameters are not compared. This is because the
 * url_cmp() is used to sort URLs: taking parameters into account makes that
Pekka Pessi's avatar
Pekka Pessi committed
1497
 * impossible. 
Pekka Pessi's avatar
Pekka Pessi committed
1498
1499
1500
1501
 */
int url_cmp(url_t const *a, url_t const *b)
{
  int rv;
Pekka Pessi's avatar
Pekka Pessi committed
1502
  int url_type;
Pekka Pessi's avatar
Pekka Pessi committed
1503
1504
1505
1506
1507
1508
1509
1510

  if ((a && a->url_type == url_any) || (b && b->url_type == url_any))
    return 0;

  if (!a || !b)
    return (a != NULL) - (b != NULL);

  if ((rv = a->url_type - b->url_type)) {
Pekka Pessi's avatar
Pekka Pessi committed
1511
#if 0
Pekka Pessi's avatar
Pekka Pessi committed
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
    /* presence and instant messaging URLs match magically with SIP */
    enum url_type_e a_type = a->url_type;
    enum url_type_e b_type = b->url_type;
    
    if (a_type == url_im || a_type == url_pres)
      a_type = url_sip;

    if (b_type == url_im || b_type == url_pres)
      b_type = url_sip;

    if (a_type != b_type)
Pekka Pessi's avatar
Pekka Pessi committed
1523
#endif
Pekka Pessi's avatar
Pekka Pessi committed
1524
1525
1526
      return rv;
  }

Pekka Pessi's avatar
Pekka Pessi committed
1527
1528
1529
  url_type = a->url_type;	/* Or b->url_type, they are equal! */

  if (url_type <= url_unknown && 
1530
1531
1532
1533
      ((rv = !a->url_scheme - !b->url_scheme) ||
       (a->url_scheme && b->url_scheme &&
	(rv = strcasecmp(a->url_scheme, b->url_scheme)))))
    return rv;
Pekka Pessi's avatar
Pekka Pessi committed
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543

  if (a->url_host != b->url_host && 
      ((rv = !a->url_host - !b->url_host) ||
       (rv = strcasecmp(a->url_host, b->url_host))))
    return rv;

  if (a->url_port != b->url_port) {
    char const *a_port;
    char const *b_port;

Pekka Pessi's avatar
Pekka Pessi committed
1544
1545
    if (url_type != url_sip && url_type != url_sips)
      a_port = b_port = url_port_default(url_type);
1546
    else if (host_is_ip_address(a->url_host))
Pekka Pessi's avatar
Pekka Pessi committed
1547
      a_port = b_port = url_port_default(url_type);
Pekka Pessi's avatar
Pekka Pessi committed
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
    else
      a_port = b_port = "";
    
    if (a->url_port) a_port = a->url_port;
    if (b->url_port) b_port = b->url_port;

    if ((rv = strcmp(a_port, b_port)))
      return rv;
  }

  if (a->url_user != b->url_user) {
    if (a->url_user == NULL) return -1;
    if (b->url_user == NULL) return +1;
Pekka Pessi's avatar
Pekka Pessi committed
1561
1562
1563
1564
1565
1566
1567
1568
1569
    switch (url_type) {
    case url_tel: case url_modem: case url_fax:
      rv = url_tel_cmp_numbers(a->url_user, b->url_user);
      break;
    default:
      rv = strcmp(a->url_user, b->url_user);
      break;
    }
    if (rv)
Pekka Pessi's avatar
Pekka Pessi committed
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
      return rv;
  }

#if 0
  if (a->url_path != b->url_path) {
    if (a->url_path == NULL) return -1;
    if (b->url_path == NULL) return +1;
    if ((rv = strcmp(a->url_path, b->url_path)))
      return rv;
  }
#endif

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
static
int url_tel_cmp_numbers(char const *A, char const *B)
{
  char a, b;
  int rv;

  while (*A && *B) {
    #define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
    /* Skip visual-separators */
    do {
      a = *A++;
      if (a == '%' && IS_HEX(A[0]) && IS_HEX(A[1])) 
	a = (UNHEX(A[0]) << 4) | UNHEX(A[1]), A +=2;
    } while (a == ' ' || a == '-' || a == '.' || a == '(' || a == ')');

    if (isupper(a))
      a = tolower(a);

    do {
      b = *B++;
      if (b == '%' && IS_HEX(B[0]) && IS_HEX(B[1])) 
	b = (UNHEX(B[0]) << 4) | UNHEX(B[1]), B +=2;
    } while (b == ' ' || b == '-' || b == '.' || b == '(' || b == ')');

    if (isupper(b))
      b = tolower(b);

    if ((rv = a - b))
      return rv;
  }

  return (int)*A - (int)*B;
}

/**Conservative comparison of urls.
 *
 * Compare all parts of URLs.
 *
 * @note
 * The @a a and @a b must be pointers to URL structures.
 *
 */
int url_cmp_all(url_t const *a, url_t const *b)
{
  int rv, url_type;

  if (!a || !b)
    return (a != NULL) - (b != NULL);

  if ((rv = a->url_type - b->url_type))
    return rv;

  url_type = a->url_type;	/* Or b->url_type, they are equal! */

  if (url_type <= url_unknown && 
      ((rv = !a->url_scheme - !b->url_scheme) ||
       (a->url_scheme && b->url_scheme &&
	(rv = strcasecmp(a->url_scheme, b->url_scheme)))))
    return rv;

  if ((rv = a->url_root - b->url_root))
    return rv;

  if (a->url_host != b->url_host && 
      ((rv = !a->url_host - !b->url_host) ||
       (rv = strcasecmp(a->url_host, b->url_host))))
    return rv;

  if (a->url_port != b->url_port) {
    char const *a_port;
    char const *b_port;

    if (url_type != url_sip && url_type != url_sips)
      a_port = b_port = url_port_default(url_type);
    else if (host_is_ip_address(a->url_host))
      a_port = b_port = url_port_default(url_type);
    else
      a_port = b_port = "";
    
    if (a->url_port) a_port = a->url_port;
    if (b->url_port) b_port = b->url_port;

    if ((rv = strcmp(a_port, b_port)))
      return rv;
  }

  if (a->url_user != b->url_user) {
    if (a->url_user == NULL) return -1;
    if (b->url_user == NULL) return +1;

    switch (url_type) {
    case url_tel: case url_modem: case url_fax:
      rv = url_tel_cmp_numbers(a->url_user, b->url_user);
      break;
    default:
      rv = strcmp(a->url_user, b->url_user);
      break;
    }
    if (rv)
      return rv;
  }

  if (a->url_path != b->url_path) {
    if (a->url_path == NULL) return -1;
    if (b->url_path == NULL) return +1;
    if ((rv = strcmp(a->url_path, b->url_path)))
      return rv;
  }

  if (a->url_params != b->url_params) {
    if (a->url_params == NULL) return -1;
    if (b->url_params == NULL) return +1;
    if ((rv = strcmp(a->url_params, b->url_params)))
      return rv;
  }

  if (a->url_headers != b->url_headers) {
    if (a->url_headers == NULL) return -1;
    if (b->url_headers == NULL) return +1;
    if ((rv = strcmp(a->url_headers, b->url_headers)))
      return rv;
  }

  if (a->url_headers != b->url_headers) {
    if (a->url_headers == NULL) return -1;
    if (b->url_headers == NULL) return +1;
    if ((rv = strcmp(a->url_headers, b->url_headers)))
      return rv;
  }

  if (a->url_fragment != b->url_fragment) {
    if (a->url_fragment == NULL) return -1;
    if (b->url_fragment == NULL) return +1;
    if ((rv = strcmp(a->url_fragment, b->url_fragment)))
      return rv;
  }

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
/** Return default port number corresponding to the url type */
char const *url_port_default(enum url_type_e url_type)
{
  switch (url_type) {
  case url_sip:			/* "sip:" */
    return "5060";
  case url_sips:		/* "sips:" */
    return "5061";
  case url_http:		/* "http:" */
    return "80";
  case url_https:		/* "https:" */
    return "443";
  case url_ftp:			/* "ftp:" */
  case url_file:		/* "file:" */
    return "21";
  case url_rtsp:		/* "rtsp:" */
  case url_rtspu:		/* "rtspu:" */
    return "554";
  case url_mailto:		/* "mailto:" */
    return "25";

  case url_any:			/* "*" */
    return "*";

  case url_msrp:
Remi Denis-Courmont's avatar
Remi Denis-Courmont committed
1750
  case url_msrps:
Pekka Pessi's avatar
Pekka Pessi committed
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
    return "9999";		/* XXXX */

  case url_tel:	
  case url_fax:	
  case url_modem:
  case url_im:	
  case url_pres:
  case url_cid:
  case url_wv:

  default:			/* Unknown scheme */
    return "";
  }
}

/** Return default transport name corresponding to the url type */
char const *url_tport_default(enum url_type_e url_type)
{
  switch (url_type) {
  case url_sip:
    return "*";
  case url_sips:
    return "tls";
  case url_http:
    return "tcp";
  case url_https:
    return "tls";
  case url_ftp:
  case url_file:
    return "tcp";
  case url_rtsp:
    return "tcp";
  case url_rtspu:
    return "udp";
  case url_mailto:
    return "tcp";
  case url_msrp:
    return "tcp";
Remi Denis-Courmont's avatar
Remi Denis-Courmont committed
1789
1790
  case url_msrps:
    return "tls";
Pekka Pessi's avatar
Pekka Pessi committed
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811

  case url_any:			/* "*" */
  case url_tel:
  case url_fax:
  case url_modem:
  case url_im:
  case url_pres:
  case url_cid:
  case url_wv:

  default:			/* Unknown scheme */
    return "*";
  }
}


/** Return the URL port string */
char const *url_port(url_t const *u)
{
  if (!u)
    return "";
Pekka Pessi's avatar
Pekka Pessi committed
1812
  else if (u->url_port && u->url_port[0])
Pekka Pessi's avatar
Pekka Pessi committed
1813
    return u->url_port;
Pekka Pessi's avatar
Pekka Pessi committed
1814
1815
1816
1817
1818
1819

  if (u->url_type == url_sips || u->url_type == url_sip)
    if (!host_is_ip_address(u->url_host))
      return "";

  return url_port_default(u->url_type);
Pekka Pessi's avatar
Pekka Pessi committed
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
}

/** Sanitize URL.
 *
 * The function url_sanitize() adds a scheme to an incomplete URL.  It
 * modifies its parameter structure @a url.  Currently, the function follows
 * simple heuristics:
 *
 * - URL with host name starting with @c ftp. is an FTP URL
 * - URL with host name starting with @c www. is an HTTP URL
 * - URL with host and path, e.g., @c host/foo;bar, is an HTTP URL
 * - URL with host name, no path is a SIP URL.
 *
 * @param url pointer to URL struct to be sanitized (IN/OUT)
 *
 * @return
 * The function url_sanitize() returns 0 if it considers URL to be
 * sane, and -1 otherwise.
 */
int url_sanitize(url_t *url)
{
  if (!url)
    return -1;
  else if (url->url_scheme != NULL)
    /* xyzzy */;
  else if (url->url_host == NULL)
    return -1;
  else if (strncasecmp(url->url_host, "ftp.", strlen("ftp.")) == 0)
    url->url_type = url_ftp, url->url_scheme = "ftp", url->url_root = '/';
  else if (strncasecmp(url->url_host, "www.", strlen("www.")) == 0
	   || url->url_path)
    url->url_type = url_http, url->url_scheme = "http", url->url_root = '/';
  else
    url->url_type = url_sip, url->url_scheme = "sip";

  return 0;
}

1858
#include <sofia-sip/su_md5.h>
Pekka Pessi's avatar
Pekka Pessi committed
1859
1860

static
1861
void canon_update(su_md5_t *md5, char const *s, size_t n, char const *allow)
Pekka Pessi's avatar
Pekka Pessi committed
1862
{
1863
  size_t i, j;
Pekka Pessi's avatar
Pekka Pessi committed
1864

1865
  for (i = 0, j = 0; i < n && s[i]; i++) {
Pekka Pessi's avatar
Pekka Pessi committed
1866
1867
    char c;

1868
    if (s[i] == '%' && i + 2 < n && IS_HEX(s[i+1]) && IS_HEX(s[i+2])) {
Pekka Pessi's avatar
Pekka Pessi committed
1869
#define   UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
1870
      c = (UNHEX(s[i+1]) << 4) | UNHEX(s[i+2]);
Pekka Pessi's avatar
Pekka Pessi committed
1871
1872
1873
#undef    UNHEX
      if (c != '%' && c > ' ' && c < '\177' && 
	  (!strchr(EXCLUDED, c) || strchr(allow, c))) {
1874
1875
	if (i != j)
	  su_md5_iupdate(md5, s + j, i - j);
Pekka Pessi's avatar
Pekka Pessi committed
1876
	su_md5_iupdate(md5, &c, 1);
1877
	j = i + 3;
Pekka Pessi's avatar
Pekka Pessi committed
1878
      }
1879
      i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
1880
1881
    }
  }
1882
1883
1884

  if (i != j)
    su_md5_iupdate(md5, s + j, i - j);
Pekka Pessi's avatar
Pekka Pessi committed
1885
1886
1887
1888
1889
1890
}

/** Update MD5 sum with url-string contents */
static
void url_string_update(su_md5_t *md5, char const