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

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

#include "config.h"

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

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

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

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

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

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

#define EXCLUDED	RESERVED DELIMS UNWISE

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

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

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

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

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

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

132 133
#define NUL '\0'
#define NULNULNUL '\0', '\0', '\0'
Pekka Pessi's avatar
Pekka Pessi committed
134 135 136 137 138

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

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

Pekka Pessi's avatar
Pekka Pessi committed
168
      if (IS_EXCLUDED(u, RMASK1, RMASK2, RMASK3))
Pekka Pessi's avatar
Pekka Pessi committed
169 170 171 172 173 174
	return 1;
    }

  return 0;
}

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

211
  return (isize_t)n;
Pekka Pessi's avatar
Pekka Pessi committed
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
}

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


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

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
  if (s == NULL)
    return 0;

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

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

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

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

    if (c == '%' && i + 1 < n && IS_HEX(s[i]) && IS_HEX(s[i + 1])) {
Pekka Pessi's avatar
Pekka Pessi committed
293
#define   UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
294
      c = (UNHEX(s[i]) << 4) | UNHEX(s[i + 1]);
Pekka Pessi's avatar
Pekka Pessi committed
295
#undef    UNHEX
296
      i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
297
    }
298 299 300 301

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

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  return j;
}

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

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

  MASKS_WITH_ALLOWED(allowed, mask32, mask64, mask96);

337
  return url_canonize2(d, s, n, syn33, mask32, mask64, mask96);
Pekka Pessi's avatar
Pekka Pessi committed
338 339
}

340 341
#define SYN33(c) (1U << (c - 33))
#define IS_SYN33(syn33, c) ((syn33 & (1U << (c - 33))) != 0)
342

Pekka Pessi's avatar
Pekka Pessi committed
343 344
/** Canonize a URL component (with precomputed mask) */
static
345
char *url_canonize2(char *d, char const * const s, size_t n,
346
		    unsigned syn33,
Pekka Pessi's avatar
Pekka Pessi committed
347 348
		    unsigned m32, unsigned m64, unsigned m96)
{
349
  size_t i = 0;
Pekka Pessi's avatar
Pekka Pessi committed
350 351

  if (d == s)
352 353
    for (;s[i] && i < n; d++, i++) 
      if (s[i] == '%')
Pekka Pessi's avatar
Pekka Pessi committed
354 355
	break;

356 357
  for (;s[i] && i < n; d++, i++) {
    unsigned char c = s[i], h1, h2;
Pekka Pessi's avatar
Pekka Pessi committed
358 359

    if (c != '%') {
360
      if (!IS_SYN33(syn33, c) && IS_EXCLUDED(c, m32, m64, m96))
Pekka Pessi's avatar
Pekka Pessi committed
361 362 363 364
	return NULL;
      *d = c;
      continue;
    }
365

366
    h1 = s[i + 1], h2 = s[i + 2];
Pekka Pessi's avatar
Pekka Pessi committed
367
    
368
    if (!IS_HEX(h1) || !IS_HEX(h2)) {
Pekka Pessi's avatar
Pekka Pessi committed
369 370 371 372 373
      *d = '\0';
      return NULL;
    }
    
#define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
374
    c = (UNHEX(h1) << 4) | UNHEX(h2);
Pekka Pessi's avatar
Pekka Pessi committed
375

376
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
377 378
      /* Convert hex to normal character */
      *d = c, i += 2;
379 380 381 382 383 384 385 386 387 388 389
      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;

390
    d +=2, i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
391 392 393 394 395 396 397 398
#undef    UNHEX
  }
  
  *d = '\0';

  return d;
}

399

400 401 402 403 404
/** 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
405
static
406
char *url_canonize3(char *d, char const * const s, size_t n,
Pekka Pessi's avatar
Pekka Pessi committed
407 408
		    unsigned m32, unsigned m64, unsigned m96)
{
409
  size_t i = 0;
Pekka Pessi's avatar
Pekka Pessi committed
410 411

  if (d == s)
412 413
    for (;s[i] && i < n; d++, i++) 
      if (s[i] == '%')
Pekka Pessi's avatar
Pekka Pessi committed
414 415
	break;

416 417
  for (;s[i] && i < n; d++, i++) {
    unsigned char c = s[i], h1, h2;
Pekka Pessi's avatar
Pekka Pessi committed
418 419 420 421 422

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

424
    h1 = s[i + 1], h2 = s[i + 2];
Pekka Pessi's avatar
Pekka Pessi committed
425
    
426
    if (!IS_HEX(h1) || !IS_HEX(h2)) {
Pekka Pessi's avatar
Pekka Pessi committed
427 428 429 430 431
      *d = '\0';
      return NULL;
    }
    
#define UNHEX(a) (a - (a >= 'a' ? 'a' - 10 : (a >= 'A' ? 'A' - 10 : '0')))
432
    c = (UNHEX(h1) << 4) | UNHEX(h2);
Pekka Pessi's avatar
Pekka Pessi committed
433

434
    if (!IS_EXCLUDED(c, m32, m64, m96)) {
435
      *d = c, i += 2;
436 437 438 439 440 441 442 443 444 445 446
      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;

447
    d +=2, i += 2;
Pekka Pessi's avatar
Pekka Pessi committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
#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
478
  case url_msrps:  return "msrps";
Pekka Pessi's avatar
Pekka Pessi committed
479 480 481 482 483 484 485
  case url_wv:     return "wv";
  default:       
    assert(url_type == url_unknown);
    return NULL;
  }
}

486
su_inline
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
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 */
510
su_inline
511
enum url_type_e url_get_type(char const *scheme, size_t len)
Pekka Pessi's avatar
Pekka Pessi committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
{
#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
528
    test_scheme(msrp); test_scheme(msrps); break;
Pekka Pessi's avatar
Pekka Pessi committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  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)
{
568
  size_t n, p;
569 570
  char *s0, rest_c, *host, *user;
  int have_authority = 1;
Pekka Pessi's avatar
Pekka Pessi committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

  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;

588
    if (!(scheme = url_canonize(scheme, scheme, SIZE_MAX, 0, "+")))
Pekka Pessi's avatar
Pekka Pessi committed
589 590 591 592 593 594
      return -1;

    n = scheme - url->url_scheme;

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

595
    have_authority = !url_type_is_opaque(url->url_type);
596 597
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
598 599 600
    url->url_type = url_unknown;
  }

601
  user = NULL, host = s;
Pekka Pessi's avatar
Pekka Pessi committed
602 603

  if (url->url_type == url_sip || url->url_type == url_sips) {
604 605
    /* SIP URL may have /;? in user part but no path */
    /* user-unreserved  =  "&" / "=" / "+" / "$" / "," / ";" / "?" / "/" */
606
    /* Some #*@#* phones include unescaped # there, too */
607 608 609 610 611 612
    n = strcspn(s, "@/;?#");
    p = strcspn(s + n, "@");
    if (s[n + p] == '@') {
      n += p;
      user = s;
      host = s + n + 1;
613
    }
614

Pekka Pessi's avatar
Pekka Pessi committed
615 616
    n += strcspn(s + n, "/;?#");
  }
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
  else if (have_authority) {
    if (url->url_type == url_wv) {
      /* WV URL may have / in user part */
      n = strcspn(s, "@#?;");
      if (s[n] == '@') {
	user = s;
	host = s + n + 1;
	n += strcspn(s + n, ";?#");
      }
    }
    else if (host[0] == '/' && host[1] != '/') {
      /* foo:/bar or /bar - no authority, just path */
      url->url_root = '/';	/* Absolute path */
      host = NULL, n = 0;
    }
    else {
      if (host[0] == '/' && host[1] == '/') {
	/* We have authority, / / foo or foo */
	host += 2; s += 2, url->url_root = '/';
	n = strcspn(s, "/?#@[]");
      }
      else 
	n = strcspn(s, "@;/?#");

      if (s[n] == '@')
	user = host, host = user + n + 1;
Pekka Pessi's avatar
Pekka Pessi committed
643

644
      n += strcspn(s + n, ";/?#");	/* Find path, query and/or fragment */
Pekka Pessi's avatar
Pekka Pessi committed
645
    }
Pekka Pessi's avatar
Pekka Pessi committed
646
  }
647 648 649 650 651 652
  else /* !have_authority */ {
    user = host, host = NULL;
    if (url->url_type != url_invalid)
      n = strcspn(s, "/;?#");	/* Find params, query and/or fragment */
    else
      n = strcspn(s, "#");
Pekka Pessi's avatar
Pekka Pessi committed
653 654 655 656
  }

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

657 658 659 660 661 662 663 664 665
  if (user) {
    if (host) host[-1] = '\0';
    url->url_user = user;
    if (url->url_type != url_unknown) {
      n = strcspn(user, ":");
      if (user[n]) {
	user[n] = '\0';
	url->url_password = user + n + 1;
      }
666
    }
667
  }
Pekka Pessi's avatar
Pekka Pessi committed
668

669 670 671 672 673 674 675 676 677 678 679 680
  if (host) {
    url->url_host = host;
    /* IPv6 (and in some cases, IPv4) addresses are quoted with [] */
    if (host[0] == '[') {
      n = strcspn(host, "]");
      if (host[n] && (host[n + 1] == '\0' || host[n + 1] == ':'))
	n++;
      else
	n = 0;
    }
    else {
      n = strcspn(host, ":");
Pekka Pessi's avatar
Pekka Pessi committed
681 682
    }

683 684 685 686 687 688 689 690 691 692 693
    /* We allow empty host by default */
    if (n == 0) switch (url->url_type) {
    case url_sip:
    case url_sips:
    case url_im:
    case url_pres:
      return -1;
    default:
      break;
    }
    
694 695 696 697 698 699 700 701 702 703 704 705 706
    if (host[n] == ':') {
      char *port = host + n + 1;
      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:
707
	if (!url_canonize2(port, port, SIZE_MAX, 0, RESERVED_MASK))
708 709 710 711 712 713 714 715 716
	  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] != '*' || port[1] != '\0'))
Pekka Pessi's avatar
Pekka Pessi committed
717 718
	  return -1;
      }
719
      host[n] = 0;
Pekka Pessi's avatar
Pekka Pessi committed
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 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 770
    }
  }

  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;
771
    if (s && !url_canonize(s, s, SIZE_MAX, 0, SIP_USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
772 773
      return -1;

774 775
    /* Having different charset in user and password does not make sense */
    /* but that is how it is defined in RFC 3261 */
Pekka Pessi's avatar
Pekka Pessi committed
776 777
#   define SIP_PASS_UNRESERVED "&=+$,"
    s = (char *)url->url_password;
778
    if (s && !url_canonize(s, s, SIZE_MAX, 0, SIP_PASS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
779 780
      return -1;

781 782
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
783 784 785

#   define USER_UNRESERVED "&=+$,;"
    s = (char *)url->url_user;
786
    if (s && !url_canonize(s, s, SIZE_MAX, 0, USER_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
787 788 789 790
      return -1;

#   define PASS_UNRESERVED "&=+$,;:"
    s = (char *)url->url_password;
791
    if (s && !url_canonize(s, s, SIZE_MAX, 0, PASS_UNRESERVED))
Pekka Pessi's avatar
Pekka Pessi committed
792 793 794 795
      return -1;
  }

  s = (char *)url->url_host;
796
  if (s && !url_canonize2(s, s, SIZE_MAX, 0, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
797 798 799 800
    return -1;

  /* port is canonized by _url_d() */
  s = (char *)url->url_path;
801 802 803 804 805 806 807
  if (s && !url_canonize(s, s, SIZE_MAX, 
			 /* Allow all URI characters but ? */
			 /* Allow unescaped /;?@, - but do not convert */
			 SYN33('/') | SYN33(';') | SYN33('=') | SYN33('@') |
			 SYN33(','),
			 /* Convert escaped :&+$ to unescaped */
			 ":&+$"))
Pekka Pessi's avatar
Pekka Pessi committed
808 809 810
    return -1;

  s = (char *)url->url_params;
811 812 813 814 815 816
  if (s && !url_canonize(s, s, SIZE_MAX,
			 /* Allow all URI characters but ? */
			 /* Allow unescaped ;=@, - but do not convert */
			 SYN33(';') | SYN33('=') | SYN33('@') | SYN33(','),
			 /* Convert escaped /:&+$ to unescaped */
			 "/:&+$"))
Pekka Pessi's avatar
Pekka Pessi committed
817 818 819 820
    return -1;
  
  /* Unhex alphanumeric and unreserved URI characters */
  s = (char *)url->url_headers;
821
  if (s && !url_canonize3(s, s, SIZE_MAX, RESERVED_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
822 823 824 825
    return -1;

  /* Allow all URI characters (including reserved ones) */
  s = (char *)url->url_fragment;
826
  if (s && !url_canonize2(s, s, SIZE_MAX, 0, URIC_MASK))
Pekka Pessi's avatar
Pekka Pessi committed
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
    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 
843
 * Return the number of bytes in the encoding.  
Pekka Pessi's avatar
Pekka Pessi committed
844 845 846 847 848
 *
 * @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.
 */
849
issize_t url_e(char buffer[], isize_t n, url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
850
{
851
  size_t i;
Pekka Pessi's avatar
Pekka Pessi committed
852
  char *b = buffer;
853
  size_t m = n;
Pekka Pessi's avatar
Pekka Pessi committed
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
  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];
952
    size_t j;
Pekka Pessi's avatar
Pekka Pessi committed
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

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

975
  assert((size_t)(b - buffer) == (size_t)(m - n));
Pekka Pessi's avatar
Pekka Pessi committed
976 977 978 979 980 981 982 983
  
  /* This follows the snprintf(C99) return value, 
   * Number of characters written (excluding NUL)
   */
  return b - buffer;
}


984
/** Calculate the length of URL when encoded. 
Pekka Pessi's avatar
Pekka Pessi committed
985 986
 *
 */
987
isize_t url_len(url_t const * url)
Pekka Pessi's avatar
Pekka Pessi committed
988
{
989
  size_t rv = 0;
Pekka Pessi's avatar
Pekka Pessi committed
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007

  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
1008
/**@def URL_E(buf, end, url)
Pekka Pessi's avatar
Pekka Pessi committed
1009
 * Encode an URL: use @a buf up to @a end. 
Pekka Pessi's avatar
Pekka Pessi committed
1010
 * @hideinitializer
Pekka Pessi's avatar
Pekka Pessi committed
1011 1012 1013 1014 1015 1016 1017 1018
 */

/** 
 * 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
 */
1019
isize_t url_xtra(url_t const *url)
Pekka Pessi's avatar
Pekka Pessi committed
1020
{
1021 1022
  size_t xtra;

Pekka Pessi's avatar
Pekka Pessi committed
1023
  if (URL_STRING_P(url)) {
1024
    xtra = strlen((char const *)url) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
1025 1026
  }
  else {
1027
    size_t len_scheme, len_user, len_password,
Pekka Pessi's avatar
Pekka Pessi committed
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
      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;

1042
    xtra =
Pekka Pessi's avatar
Pekka Pessi committed
1043 1044 1045
      len_scheme + len_user + len_password + len_host + len_port +
      len_path + len_params + len_headers + len_fragment;
  }
1046 1047

  return xtra;
Pekka Pessi's avatar
Pekka Pessi committed
1048 1049
}

1050
su_inline
Pekka Pessi's avatar
Pekka Pessi committed
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
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.
 *
1087
 * @return Number of characters required for
Pekka Pessi's avatar
Pekka Pessi committed
1088 1089 1090
 * duplicating the strings in @a str, or -1 if an error
 * occurred.
 */
1091
issize_t url_dup(char *buf, isize_t bufsize, url_t *dst, url_t const *src)
Pekka Pessi's avatar
Pekka Pessi committed
1092 1093 1094 1095
{
  if (!src && !dst)
    return -1;
  else if (URL_STRING_P(src)) {
1096
    size_t n = strlen((char *)src) + 1;
Pekka Pessi's avatar
Pekka Pessi committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 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
    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) {
1196
    size_t len = sizeof(*src) + url_xtra(src);
Pekka Pessi's avatar
Pekka Pessi committed
1197 1198
    url_t *dst = su_alloc(home, len);
    if (dst) {
1199
      ssize_t actual;
Pekka Pessi's avatar
Pekka Pessi committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
      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;
}


1243 1244 1245 1246 1247 1248 1249 1250 1251
/** Convert @a url to a string allocated from @a home.
 *
 * @param home memory home to allocate the new string
 * @param url  url to convert to string
 *
 * The @a url can be a string, too.
 *
 * @return Newly allocated conversion result, or NULL upon an error.
 */
Pekka Pessi's avatar
Pekka Pessi committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
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.
 */
1289 1290 1291
isize_t url_param(char const *params, 
		  char const *tag, 
		  char value[], isize_t vlen)
Pekka Pessi's avatar
Pekka Pessi committed
1292
{
Pekka Pessi's avatar
Pekka Pessi committed
1293
  size_t n, tlen, flen;
Pekka Pessi's avatar
Pekka Pessi committed
1294
  char *p;
Pekka Pessi's avatar
Pekka Pessi committed
1295

Pekka Pessi's avatar
Pekka Pessi committed
1296 1297 1298
  if (!params)
    return 0;

Pekka Pessi's avatar
Pekka Pessi committed
1299 1300 1301 1302
  tlen = strlen(tag);
  if (tlen && tag[tlen - 1] == '=')
    tlen--;

Pekka Pessi's avatar
Pekka Pessi committed
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
  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().
 */
1335
isize_t url_have_param(char const *params, char const *tag)
Pekka Pessi's avatar
Pekka Pessi committed
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
{
  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
1349
  /* XXX - should remove existing parameters with same name? */
1350 1351
  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
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
  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;
}

1365 1366 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 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
/** Remove a named parameter from url_param string.
 *
 * Remove a named parameter and its possible value from the URL parameter
 * string (url_s##url_param).
 *
 * @return Pointer to modified string, or NULL if nothing is left in there.
 */
char *url_strip_param_string(char *params, char const *name)
{
  if (params && name) {
    size_t i, n = strlen(name), remove, rest;
    
    for (i = 0; params[i];) {
      if (strncasecmp(params + i, name, n) ||
	  (params[i + n] != '=' && params[i + n] != ';' && params[i + n])) {
	i = i + strcspn(params + i, ";");
	if (!params[i++])
	  break;<