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 143
static char *url_canonize(char *d, char const *s, size_t n,
			  char const allowed[]);
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 *s, size_t n, 
Pekka Pessi's avatar
Pekka Pessi committed
306 307 308 309 310
		    unsigned m32, unsigned m64, unsigned m96)
{
  char const *s0 = s;

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

315
  for (;*s && s - s0 < n; d++, s++) {
316
    unsigned char c = *s, 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[1], h2 = s[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)) {
Pekka Pessi's avatar
Pekka Pessi committed
336
      *d = c, s += 2;
337 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;

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

  return d;
}

357

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

  if (d == s)
    for (;*s && s - s0 < (unsigned)n; d++, s++) 
      if (*s == '%')
	break;

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

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

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

392
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
Pekka Pessi's avatar
Pekka Pessi committed
393
      *d = c, s += 2;
394 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;

    d +=2, s += 2;
Pekka Pessi's avatar
Pekka Pessi committed
406 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
#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
436
  case url_msrps:  return "msrps";
Pekka Pessi's avatar
Pekka Pessi committed
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 466 467 468
  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
469
enum url_type_e url_get_type(char const *scheme, size_t len)
Pekka Pessi's avatar
Pekka Pessi committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
{
#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
486
    test_scheme(msrp); test_scheme(msrps); break;
Pekka Pessi's avatar
Pekka Pessi committed
487 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
  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)
{
526
  size_t n;
Pekka Pessi's avatar
Pekka Pessi committed
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  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;

546
    if (!(scheme = url_canonize(scheme, scheme, SIZE_MAX, "+")))
Pekka Pessi's avatar
Pekka Pessi committed
547 548 549 550 551 552 553
      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);
554 555
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    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
576 577
  }
  else if (net_path && host[0] == '/') {
Pekka Pessi's avatar
Pekka Pessi committed
578 579 580 581 582 583 584 585
    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
586 587
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
588 589 590 591 592 593 594 595 596 597 598
    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;
599 600
    }
    else if ((atsign = strchr(host, '@'))) {
Pekka Pessi's avatar
Pekka Pessi committed
601 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
      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:
	  
642
	  if (!url_canonize2(port, port, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
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 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
	    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;
707
    if (s && !url_canonize(s, s, SIZE_MAX, SIP_USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
708 709 710 711
      return -1;

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

  } else {

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

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

  s = (char *)url->url_host;
  if (s && !url_canonize2(s, s, -1, RESERVED_MASK))
    return -1;

  /* port is canonized by _url_d() */

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

  /* Allow all URI characters but ? */
# define PARAMS_UNRESERVED ";" PATH_UNRESERVED
  s = (char *)url->url_params;
743
  if (s && !url_canonize(s, s, SIZE_MAX, PARAMS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    return -1;
  
  /* Unhex alphanumeric and unreserved URI characters */
  s = (char *)url->url_headers;
  if (s && !url_canonize3(s, s, -1, RESERVED_MASK))
    return -1;

  /* Allow all URI characters (including reserved ones) */
  s = (char *)url->url_fragment;
  if (s && !url_canonize2(s, s, -1, URIC_MASK))
    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 
770
 * Return the number of bytes in the encoding.  
Pekka Pessi's avatar
Pekka Pessi committed
771 772 773 774 775
 *
 * @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.
 */
776
issize_t url_e(char buffer[], isize_t n, url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
777
{
778
  size_t i;
Pekka Pessi's avatar
Pekka Pessi committed
779
  char *b = buffer;
780
  size_t m = n;
Pekka Pessi's avatar
Pekka Pessi committed
781 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
  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];
879
    size_t j;
Pekka Pessi's avatar
Pekka Pessi committed
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 909 910 911 912 913

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

  assert(b - buffer == m - n);
  
  /* This follows the snprintf(C99) return value, 
   * Number of characters written (excluding NUL)
   */
  return b - buffer;
}


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

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

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

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

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

  return xtra;
Pekka Pessi's avatar
Pekka Pessi committed
975 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
}

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.
 *
1014
 * @return Number of characters required for
Pekka Pessi's avatar
Pekka Pessi committed
1015 1016 1017
 * duplicating the strings in @a str, or -1 if an error
 * occurred.
 */
1018
issize_t url_dup(char *buf, isize_t bufsize, url_t *dst, url_t const *src)
Pekka Pessi's avatar
Pekka Pessi committed
1019 1020 1021 1022
{
  if (!src && !dst)
    return -1;
  else if (URL_STRING_P(src)) {
1023
    size_t n = strlen((char *)src) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
1024 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
    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) {
1123
    size_t len = sizeof(*src) + url_xtra(src), actual;
Pekka Pessi's avatar
Pekka Pessi committed
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 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
    url_t *dst = su_alloc(home, len);
    if (dst) {
      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.
 */
1207 1208 1209
isize_t url_param(char const *params, 
		  char const *tag, 
		  char value[], isize_t vlen)
Pekka Pessi's avatar
Pekka Pessi committed
1210
{
Pekka Pessi's avatar
Pekka Pessi committed
1211
  size_t n, tlen, flen;
Pekka Pessi's avatar
Pekka Pessi committed
1212
  char *p;
Pekka Pessi's avatar
Pekka Pessi committed
1213

Pekka Pessi's avatar
Pekka Pessi committed
1214 1215 1216
  if (!params)
    return 0;

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

Pekka Pessi's avatar
Pekka Pessi committed
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 1246 1247 1248 1249 1250 1251 1252
  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().
 */
1253
isize_t url_have_param(char const *params, char const *tag)
Pekka Pessi's avatar
Pekka Pessi committed
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
{
  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
1267
  /* XXX - should remove existing parameters with same name? */
1268 1269
  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
1270 1271 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
  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
1366
 * The @a url must be a pointer to a URL structure. It is stripped in-place.
Pekka Pessi's avatar
Pekka Pessi committed
1367 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
 *
 * @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
1399 1400 1401 1402 1403 1404 1405
/**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
1406 1407 1408
 *
 * @note
 * The @a a and @a b must be pointers to URL structures.
1409 1410 1411
 *
 * @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
1412
 * impossible. 
Pekka Pessi's avatar
Pekka Pessi committed
1413 1414 1415 1416
 */
int url_cmp(url_t const *a, url_t const *b)
{
  int rv;
Pekka Pessi's avatar
Pekka Pessi committed
1417
  int url_type;
Pekka Pessi's avatar
Pekka Pessi committed
1418 1419 1420 1421 1422 1423 1424 1425

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

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

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

  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
1459 1460
    if (url_type != url_sip && url_type != url_sips)
      a_port = b_port = url_port_default(url_type);
1461
    else if (host_is_ip_address(a->url_host))
Pekka Pessi's avatar
Pekka Pessi committed
1462
      a_port = b_port = url_port_default(url_type);
Pekka Pessi's avatar
Pekka Pessi committed
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    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
1476 1477 1478 1479 1480 1481 1482 1483 1484
    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
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
      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
1500 1501 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
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</