url.c 45.7 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

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

Pekka Pessi's avatar
Pekka Pessi committed
47
48
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
88
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
/**@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)))		\
	  : /*u < 128*/ (m96 & (1 << (127 - u))))))

#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
130
131
132
133
134

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

Pekka Pessi's avatar
Pekka Pessi committed
135
136
137
138
139
#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
140
/* Internal prototypes */
141
142
static char *url_canonize(char *d, char const *s, size_t n,
			  char const allowed[]);
143
static char *url_canonize2(char *d, char const *s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
144
145
146
			   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
147
/**Test if string contains excluded or url-reserved characters. 
148
149
 *
 * 
Pekka Pessi's avatar
Pekka Pessi committed
150
151
152
153
154
155
156
157
158
159
160
161
 *
 * @param s  string to be searched
 *
 * @retval 0 if no reserved characters were found.
 * @retval 1 if a reserved character was found.
 */
int url_reserved_p(char const *s)
{
  if (s) 
    while (*s) {
      unsigned char u = *s++;

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

  return 0;
}

169
/** Calculate length of string when escaped with %-notation.
Pekka Pessi's avatar
Pekka Pessi committed
170
 *
171
172
 * 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
173
174
175
176
177
 * 
 * @param s         String with reserved URL characters. [IN
 * @param reserved  Optional array of reserved characters [IN]
 *
 * @return 
178
 * The number of characters in corresponding but escaped string.
Pekka Pessi's avatar
Pekka Pessi committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
254
255
256
257
258
259
260
261
262
 *
 * 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
 */
int url_esclen(char const *s, char const reserved[])
{
  int n;
  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;
  }

  return n;
}

/** 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;
}


/**Unescape an string.
 *
 * The function url_unescape() copies the string pointed by @a s to the
 * array pointed by @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
 *
263
 * @return Pointer to the destination buffer.
Pekka Pessi's avatar
Pekka Pessi committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
 */
char *url_unescape(char *d, char const *s)
{
  char *r = d;

  if (s) {
    if (d == s)
      s = d = strchr(d, '%');
    
    if (d) {
      for (;IS_NON_LWS(*s); d++, s++) {
	if (*s == '%' && IS_HEX(s[1]) && IS_HEX(s[2])) {
#define   UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
	  *d = (UNHEX(s[1]) << 4) | UNHEX(s[2]);
#undef    UNHEX
	  s += 2;
	}
	else {
	  *d = *s;
	}
      }
    }
  }
  if (d) *d = '\0';

  return r;
}

/** Canonize a URL component */
static
294
char *url_canonize(char *d, char const *s, size_t n, char const allowed[])
Pekka Pessi's avatar
Pekka Pessi committed
295
296
297
298
299
300
301
302
303
304
{
  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
305
char *url_canonize2(char *d, char const * const s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
306
307
		    unsigned m32, unsigned m64, unsigned m96)
{
308
  size_t i = 0;
Pekka Pessi's avatar
Pekka Pessi committed
309
310

  if (d == s)
311
312
    for (;s[i] && i < n; d++, i++) 
      if (s[i] == '%')
Pekka Pessi's avatar
Pekka Pessi committed
313
314
	break;

315
316
  for (;s[i] && i < n; d++, i++) {
    unsigned char c = s[i], h1, h2;
Pekka Pessi's avatar
Pekka Pessi committed
317
318
319
320
321
322
323

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

325
    h1 = s[i + 1], h2 = s[i + 2];
Pekka Pessi's avatar
Pekka Pessi committed
326
    
327
    if (!IS_HEX(h1) || !IS_HEX(h2)) {
Pekka Pessi's avatar
Pekka Pessi committed
328
329
330
331
332
      *d = '\0';
      return NULL;
    }
    
#define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
333
    c = (UNHEX(h1) << 4) | UNHEX(h2);
Pekka Pessi's avatar
Pekka Pessi committed
334

335
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
336
337
      /* Convert hex to normal character */
      *d = c, i += 2;
338
339
340
341
342
343
344
345
346
347
348
      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;

349
    d +=2, i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
350
351
352
353
354
355
356
357
#undef    UNHEX
  }
  
  *d = '\0';

  return d;
}

358

359
360
361
362
363
/** 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
364
static
365
char *url_canonize3(char *d, char const * const s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
366
367
		    unsigned m32, unsigned m64, unsigned m96)
{
368
  size_t i = 0;
Pekka Pessi's avatar
Pekka Pessi committed
369
370

  if (d == s)
371
372
    for (;s[i] && i < n; d++, i++) 
      if (s[i] == '%')
Pekka Pessi's avatar
Pekka Pessi committed
373
374
	break;

375
376
  for (;s[i] && i < n; d++, i++) {
    unsigned char c = s[i], h1, h2;
Pekka Pessi's avatar
Pekka Pessi committed
377
378
379
380
381

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

383
    h1 = s[i + 1], h2 = s[i + 2];
Pekka Pessi's avatar
Pekka Pessi committed
384
    
385
    if (!IS_HEX(h1) || !IS_HEX(h2)) {
Pekka Pessi's avatar
Pekka Pessi committed
386
387
388
389
390
      *d = '\0';
      return NULL;
    }
    
#define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
391
    c = (UNHEX(h1) << 4) | UNHEX(h2);
Pekka Pessi's avatar
Pekka Pessi committed
392

393
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
394
      *d = c, i += 2;
395
396
397
398
399
400
401
402
403
404
405
      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;

406
    d +=2, i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#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
437
  case url_msrps:  return "msrps";
Pekka Pessi's avatar
Pekka Pessi committed
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
466
467
468
469
  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
470
enum url_type_e url_get_type(char const *scheme, size_t len)
Pekka Pessi's avatar
Pekka Pessi committed
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
{
#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
487
    test_scheme(msrp); test_scheme(msrps); break;
Pekka Pessi's avatar
Pekka Pessi committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  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)
{
527
  size_t n;
Pekka Pessi's avatar
Pekka Pessi committed
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
  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;

547
    if (!(scheme = url_canonize(scheme, scheme, SIZE_MAX, "+")))
Pekka Pessi's avatar
Pekka Pessi committed
548
549
550
551
552
553
554
      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);
555
556
  }
  else {
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
576
    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
577
578
  }
  else if (net_path && host[0] == '/') {
Pekka Pessi's avatar
Pekka Pessi committed
579
580
581
582
583
584
585
586
    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
587
588
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
589
590
591
592
593
594
595
596
597
598
599
    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;
600
601
    }
    else if ((atsign = strchr(host, '@'))) {
Pekka Pessi's avatar
Pekka Pessi committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
      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:
	  
643
	  if (!url_canonize2(port, port, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
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
672
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
	    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;
708
    if (s && !url_canonize(s, s, SIZE_MAX, SIP_USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
709
710
711
712
      return -1;

#   define SIP_PASS_UNRESERVED "&=+$,"
    s = (char *)url->url_password;
713
    if (s && !url_canonize(s, s, SIZE_MAX, SIP_PASS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
714
715
716
717
718
719
      return -1;

  } else {

#   define USER_UNRESERVED "&=+$,;"
    s = (char *)url->url_user;
720
    if (s && !url_canonize(s, s, SIZE_MAX, USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
721
722
723
724
      return -1;

#   define PASS_UNRESERVED "&=+$,;:"
    s = (char *)url->url_password;
725
    if (s && !url_canonize(s, s, SIZE_MAX, PASS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
726
727
728
729
      return -1;
  }

  s = (char *)url->url_host;
730
  if (s && !url_canonize2(s, s, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
731
732
733
734
735
736
737
    return -1;

  /* port is canonized by _url_d() */

  /* Allow all URI characters but ? and ; */
# define PATH_UNRESERVED "/:@&=+$,"
  s = (char *)url->url_path;
738
  if (s && !url_canonize(s, s, SIZE_MAX, PATH_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
739
740
741
742
743
    return -1;

  /* Allow all URI characters but ? */
# define PARAMS_UNRESERVED ";" PATH_UNRESERVED
  s = (char *)url->url_params;
744
  if (s && !url_canonize(s, s, SIZE_MAX, PARAMS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
745
746
747
748
    return -1;
  
  /* Unhex alphanumeric and unreserved URI characters */
  s = (char *)url->url_headers;
749
  if (s && !url_canonize3(s, s, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
750
751
752
753
    return -1;

  /* Allow all URI characters (including reserved ones) */
  s = (char *)url->url_fragment;
754
  if (s && !url_canonize2(s, s, SIZE_MAX, URIC_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    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 
771
 * Return the number of bytes in the encoding.  
Pekka Pessi's avatar
Pekka Pessi committed
772
773
774
775
776
 *
 * @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.
 */
777
issize_t url_e(char buffer[], isize_t n, url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
778
{
779
  size_t i;
Pekka Pessi's avatar
Pekka Pessi committed
780
  char *b = buffer;
781
  size_t m = n;
Pekka Pessi's avatar
Pekka Pessi committed
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
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
  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];
880
    size_t j;
Pekka Pessi's avatar
Pekka Pessi committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902

    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';

903
  assert((size_t)(b - buffer) == (size_t)(m - n));
Pekka Pessi's avatar
Pekka Pessi committed
904
905
906
907
908
909
910
911
912
913
914
  
  /* This follows the snprintf(C99) return value, 
   * Number of characters written (excluding NUL)
   */
  return b - buffer;
}


/** Calculate the lengh of URL when encoded. 
 *
 */
915
isize_t url_len(url_t const * url)
Pekka Pessi's avatar
Pekka Pessi committed
916
{
917
  size_t rv = 0;
Pekka Pessi's avatar
Pekka Pessi committed
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935

  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
936
/**@def URL_E(buf, end, url)
Pekka Pessi's avatar
Pekka Pessi committed
937
 * Encode an URL: use @a buf up to @a end. 
Pekka Pessi's avatar
Pekka Pessi committed
938
 * @hideinitializer
Pekka Pessi's avatar
Pekka Pessi committed
939
940
941
942
943
944
945
946
 */

/** 
 * 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
 */
947
isize_t url_xtra(url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
948
{
949
950
  size_t xtra;

Pekka Pessi's avatar
Pekka Pessi committed
951
  if (URL_STRING_P(url)) {
952
    xtra = strlen((char const *)url) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
953
954
  }
  else {
955
    size_t len_scheme, len_user, len_password,
Pekka Pessi's avatar
Pekka Pessi committed
956
957
958
959
960
961
962
963
964
965
966
967
968
969
      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;

970
    xtra =
Pekka Pessi's avatar
Pekka Pessi committed
971
972
973
      len_scheme + len_user + len_password + len_host + len_port +
      len_path + len_params + len_headers + len_fragment;
  }
974
975

  return xtra;
Pekka Pessi's avatar
Pekka Pessi committed
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
}

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.
 *
1015
 * @return Number of characters required for
Pekka Pessi's avatar
Pekka Pessi committed
1016
1017
1018
 * duplicating the strings in @a str, or -1 if an error
 * occurred.
 */
1019
issize_t url_dup(char *buf, isize_t bufsize, url_t *dst, url_t const *src)
Pekka Pessi's avatar
Pekka Pessi committed
1020
1021
1022
1023
{
  if (!src && !dst)
    return -1;
  else if (URL_STRING_P(src)) {
1024
    size_t n = strlen((char *)src) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
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
    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) {
1124
    size_t len = sizeof(*src) + url_xtra(src);
Pekka Pessi's avatar
Pekka Pessi committed
1125
1126
    url_t *dst = su_alloc(home, len);
    if (dst) {
1127
      ssize_t actual;
Pekka Pessi's avatar
Pekka Pessi committed
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
1153
1154
1155
1156
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
1200
1201
1202
1203
1204
1205
1206
1207
1208
      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;
}


/** Convert @a url to a string allocated from @a home */
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.
 */
1209
1210
1211
isize_t url_param(char const *params, 
		  char const *tag, 
		  char value[], isize_t vlen)
Pekka Pessi's avatar
Pekka Pessi committed
1212
{
Pekka Pessi's avatar
Pekka Pessi committed
1213
  size_t n, tlen, flen;
Pekka Pessi's avatar
Pekka Pessi committed
1214
  char *p;
Pekka Pessi's avatar
Pekka Pessi committed
1215

Pekka Pessi's avatar
Pekka Pessi committed
1216
1217
1218
  if (!params)
    return 0;

Pekka Pessi's avatar
Pekka Pessi committed
1219
1220
1221
1222
  tlen = strlen(tag);
  if (tlen && tag[tlen - 1] == '=')
    tlen--;

Pekka Pessi's avatar
Pekka Pessi committed
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
  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().
 */
1255
isize_t url_have_param(char const *params, char const *tag)
Pekka Pessi's avatar
Pekka Pessi committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
{
  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
1269
  /* XXX - should remove existing parameters with same name? */
1270
1271
  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
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
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
  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;
}

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;
	memcpy(d, p, n + 1);
      }
    }
    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
1368
 * The @a url must be a pointer to a URL structure. It is stripped in-place.
Pekka Pessi's avatar
Pekka Pessi committed
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
 *
 * @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
1401
1402
1403
1404
1405
1406
1407
/**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
1408
1409
1410
 *
 * @note
 * The @a a and @a b must be pointers to URL structures.
1411
1412
1413
 *
 * @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
1414
 * impossible. 
Pekka Pessi's avatar
Pekka Pessi committed
1415
1416
1417
1418
 */
int url_cmp(url_t const *a, url_t const *b)
{
  int rv;
Pekka Pessi's avatar
Pekka Pessi committed
1419
  int url_type;
Pekka Pessi's avatar
Pekka Pessi committed
1420
1421
1422
1423
1424
1425
1426
1427

  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
1428
#if 0
Pekka Pessi's avatar
Pekka Pessi committed
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
    /* 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
1440
#endif
Pekka Pessi's avatar
Pekka Pessi committed
1441
1442
1443
      return rv;
  }

Pekka Pessi's avatar
Pekka Pessi committed
1444
1445
1446
  url_type = a->url_type;	/* Or b->url_type, they are equal! */

  if (url_type <= url_unknown && 
1447
1448
1449
1450
      ((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
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460

  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
1461
1462
    if (url_type != url_sip && url_type != url_sips)
      a_port = b_port = url_port_default(url_type);
1463
    else if (host_is_ip_address(a->url_host))
Pekka Pessi's avatar
Pekka Pessi committed
1464
      a_port = b_port = url_port_default(url_type);
Pekka Pessi's avatar
Pekka Pessi committed
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
    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
1478
1479
1480
1481
1482
1483
1484
1485
1486
    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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
      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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
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
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
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
/** 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
1667
  case url_msrps:
Pekka Pessi's avatar
Pekka Pessi committed
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
    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
1706
1707
  case url_msrps:
    return "tls";
Pekka Pessi's avatar
Pekka Pessi committed
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728

  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
1729
  else if (u->url_port && u->url_port[0])
Pekka Pessi's avatar
Pekka Pessi committed
1730
    return u->url_port;
Pekka Pessi's avatar
Pekka Pessi committed
1731
1732
1733
1734
1735
1736

  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
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
}

/** 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;
}

1775
#include <sofia-sip/su_md5.h>
Pekka Pessi's avatar
Pekka Pessi committed
1776
1777

static
1778
void canon_update(su_md5_t *md5, char const *s, size_t n, char const *allow)
Pekka Pessi's avatar
Pekka Pessi committed
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
{
  char const *s0 = s, *b = s;

  for (;*s && s - s0 < n; s++) {
    char c;

    if (*s == '%' && IS_HEX(s[1]) && IS_HEX(s[2]) && s - s0 + 2 < n) {
#define   UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
      c = (UNHEX(s[1]) << 4) | UNHEX(s[2]);
#undef    UNHEX
      if (c != '%' && c > ' ' && c < '\177' && 
	  (!strchr(EXCLUDED, c) || strchr(allow, c))) {
	if (b != s)
	  su_md5_iupdate(md5, b, s - b);
	su_md5_iupdate(md5, &c, 1);
	b = s + 3;
      }
      s += 2;
    }
  }
  if (b != s)
    su_md5_iupdate(md5, b, s - b);
}

/** Update MD5 sum with url-string contents */
static
void url_string_update(su_md5_t *md5, char const *s)
{
1807
  size_t n;
Pekka Pessi's avatar
Pekka Pessi committed
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
  int hostpart = 1;
  enum url_type_e type = url_any;
  char const *at, *colon;
  char schema[48];

  if (s == NULL || strlen(s) == 0 || strcmp(s, "*") == 0) {
    su_md5_update(md5, "*\0\0*", 4);
    return;
  }

  n = strcspn(s, ":/?#");
  if (n >= sizeof schema) {
    su_md5_update(md5, ":", 1);
1821
1822
  }
  else if (n && s[n] == ':' ) {
Pekka Pessi's avatar
Pekka Pessi committed
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
    at = url_canonize(schema, s, n, "+");

    type = url_get_type(schema, at - schema);
    su_md5_iupdate(md5, schema, at - schema);

    hostpart = !url_type_is_opaque(type);
    s += n + 1;
  }
  else {
    su_md5_update(md5, "", 1);
  }
  
  if (type == url_sip || type == url_sips) {
    n = strcspn(s, "@#");	/* Opaque part */
    if (s[n] != '@')
      n = 0;
    n += strcspn(s + n, "/;?#");
  }
1841
1842
1843
1844
1845
  else if (type == url_wv) {    /* WV URL may have / in user part */
    n = strcspn(s, "@#?;");
    if (s[n] == '@')
      n += strcspn(s + n, ";?#");
  }
Pekka Pessi's avatar
Pekka Pessi committed
1846
1847
1848
1849
1850
  else if (!hostpart || s[0] != '/') {
    n = strcspn(s, "/;?#");	/* Opaque part */
  }
  else if (s[1] == '/') {
    s += 2;
1851
    n = strcspn(s, "/;?#");	/* Until host, path, query or fragment */
Pekka Pessi's avatar
Pekka Pessi committed
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
  }
  else {
    /* foo:/bar */
    su_md5_update(md5, "\0\0", 2); /* user, host */
    su_md5_striupdate(md5, url_port_default(type));
    return;
  }
  
  if (!hostpart) {
    char const *colon = memchr(s, ':', n);
    
    if (colon) n = colon - s;
    canon_update(md5, s, n, ""); /* user */
    su_md5_update(md5, "\0", 1); /* host, no port */
    su_md5_striupdate(md5, url_port_default(type));
    return;
  }

  at = memchr(s, '@', n);

  if (at) {
    char const *allow = 
      (type == url_sip || type == url_sips) 
      ? SIP_USER_UNRESERVED
      : USER_UNRESERVED;
1877
1878

    colon = type == url_unknown ? NULL : memchr(s, ':', at - s);
Pekka Pessi's avatar
Pekka Pessi committed
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940

    /* Updated only user part */
    if (colon)
      canon_update(md5, s, colon - s, allow);
    else
      canon_update(md5, s, at - s, allow);
    n = n - (at + 1 - s);
    s = at + 1;
  }
  else
    su_md5_iupdate(md5, "", 1);	/* user */

  colon = memchr(s, ':', n);	/* XXX - IPv6! */
  if (colon) {
    canon_update(md5, s, colon - s, ""); /* host */
    canon_update(md5, colon + 1, (s + n) - (colon + 1), "");
  }
  else {
    canon_update(md5, s, n, ""); /* host */
    su_md5_strupdate(md5, url_port_default(type));	/* port */
  }

  /* ignore parameters/path/headers.... */
}


/** Update md5 digest with contents of URL.
 *
 */
void url_update(su_md5_t *md5, url_t const *url)
{
  if (url_string_p((url_string_t *)url)) {
    url_string_update(md5, (char const *)url);
  }
  else {
    SU_MD5_STRI0UPDATE(md5, url->url_scheme);
    SU_MD5_STRI0UPDATE(md5, url->url_user);
    SU_MD5_STRI0UPDATE(md5, url->url_host);
    su_md5_striupdate(md5, URL_PORT(url));
    /* XXX - parameters/path.... */
    /* SU_MD5_STRI0UPDATE(md5, url->url_path); */
  }
}

/** Calculate a digest from URL contents. */
void url_digest(void *hash, int hsize, url_t const *url, char const *key)
{
  su_md5_t md5[1];
  uint8_t digest[SU_MD5_DIGEST_SIZE];

  su_md5_init(md5);
  if (key) su_md5_strupdate(md5, key);
  url_update(md5, url);
  su_md5_digest(md5, digest);

  if (hsize > SU_MD5_DIGEST_SIZE) {
    memset((char *)hash + SU_MD5_DIGEST_SIZE, 0, hsize - SU_MD5_DIGEST_SIZE);
    hsize = SU_MD5_DIGEST_SIZE;
  }

  memcpy(hash, digest, hsize);
}