2 * UCW Library -- URL Functions
4 * (c) 1997--2004 Martin Mares <mj@ucw.cz>
5 * (c) 2001--2005 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
10 * The URL syntax corresponds to RFC 2396 with several exceptions:
12 * o Interpretation of path parameters follows RFC 1808.
14 * XXX: The buffer handling in this module is really horrible, but it works.
19 #include "ucw/chartype.h"
21 #include "ucw/prime.h"
30 static uns url_ignore_spaces;
31 static uns url_ignore_underflow;
32 static char *url_component_separators = "";
33 static uns url_min_repeat_count = 0x7fffffff;
34 static uns url_max_repeat_length = 0;
35 static uns url_max_occurences = ~0U;
37 static struct cf_section url_config = {
39 CF_UNS("IgnoreSpaces", &url_ignore_spaces),
40 CF_UNS("IgnoreUnderflow", &url_ignore_underflow),
41 CF_STRING("ComponentSeparators", &url_component_separators),
42 CF_UNS("MinRepeatCount", &url_min_repeat_count),
43 CF_UNS("MaxRepeatLength", &url_max_repeat_length),
44 CF_UNS("MaxOccurences", &url_max_occurences),
49 static void CONSTRUCTOR url_init_config(void)
51 cf_declare_section("URL", &url_config, 0);
54 /* Escaping and de-escaping */
59 return (x<10) ? (x + '0') : (x - 10 + 'A');
63 url_deescape(const char *s, char *d)
66 char *end = d + MAX_URL_SIZE - 10;
70 return URL_ERR_TOO_LONG;
74 if (!Cxdigit(s[1]) || !Cxdigit(s[2]))
75 return URL_ERR_INVALID_ESCAPE;
76 val = Cxvalue(s[1])*16 + Cxvalue(s[2]);
78 return URL_ERR_INVALID_ESCAPED_CHAR;
82 val = NCC_SEMICOLON; break;
84 val = NCC_SLASH; break;
86 val = NCC_QUEST; break;
88 val = NCC_COLON; break;
92 val = NCC_EQUAL; break;
96 val = NCC_HASH; break;
98 val = NCC_DOLLAR; break;
100 val = NCC_PLUS; break;
102 val = NCC_COMMA; break;
107 else if ((byte) *s > 0x20)
114 if (!url_ignore_spaces || !(!*s || d == dstart))
119 return URL_ERR_TOO_LONG;
125 return URL_ERR_INVALID_CHAR;
132 url_enescape(const char *s, char *d)
134 char *end = d + MAX_URL_SIZE - 10;
140 return URL_ERR_TOO_LONG;
141 if (Calnum(c) || /* RFC 2396 (2.1-2.3): Only alphanumerics ... */
142 c == '-' || c == '_' || c == '.' || c == '+' || c == '~' || /* ... and several other exceptions ... */
143 c == '!' || c == '*' || c == '\'' || c == '(' || c == ')' ||
144 c == '/' || c == '?' || c == ':' || c == '@' || /* ... and reserved chars used for reserved purpose */
145 c == '=' || c == '&' || c == '#' || c == ';' ||
146 c == '$' || c == '+' || c == ',')
150 uns val = ((byte)*s < NCC_MAX) ? NCC_CHARS[(byte)*s] : *s;
152 *d++ = enhex(val >> 4);
153 *d++ = enhex(val & 0x0f);
162 url_enescape_friendly(const char *src, char *dest)
164 char *end = dest + MAX_URL_SIZE - 10;
165 const byte *srcb = src;
169 return URL_ERR_TOO_LONG;
171 *dest++ = NCC_CHARS[*srcb++];
172 else if (*srcb >= 0x20 && *srcb < 0x7f)
177 *dest++ = enhex(*srcb >> 4);
178 *dest++ = enhex(*srcb++ & 0x0f);
185 /* Split an URL (several parts may be copied to the destination buffer) */
187 char *url_proto_names[URL_PROTO_MAX] = URL_PNAMES;
188 static int url_proto_path_flags[URL_PROTO_MAX] = URL_PATH_FLAGS;
191 identify_protocol(const char *p)
195 for(i=1; i<URL_PROTO_MAX; i++)
196 if (!strcasecmp(p, url_proto_names[i]))
198 return URL_PROTO_UNKNOWN;
202 url_split(char *s, struct url *u, char *d)
204 bzero(u, sizeof(struct url));
206 u->bufend = d + MAX_URL_SIZE - 10;
208 if (s[0] != '/') /* Seek for "protocol:" */
211 while (*p && Calnum(*p))
213 if (p != s && *p == ':')
219 u->protoid = identify_protocol(u->protocol);
221 if (url_proto_path_flags[u->protoid] && (s[0] != '/' || s[1] != '/'))
223 /* The protocol requires complete host spec, but it's missing -> treat as a relative path instead */
224 int len = d - u->protocol;
233 if (s[0] == '/') /* Host spec or absolute path */
235 if (s[1] == '/') /* Host spec */
243 while (*s && *s != '/' && *s != '?') /* Copy user:passwd@host:port */
252 else /* This shouldn't happen with sane URL's, but we need to be sure */
257 if (at) /* user:passwd present */
260 if (e = strchr(q, ':'))
269 if (e) /* host:port present */
273 p = strtoul(e, &ep, 10);
274 if (ep && *ep || p > 65535)
275 return URL_ERR_INVALID_PORT;
276 else if (p) /* Port 0 (e.g. in :/) is treated as default port */
288 /* Normalization according to given base URL */
290 static uns std_ports[] = URL_DEFPORTS; /* Default port numbers */
293 relpath_merge(struct url *u, struct url *b)
301 if (a[0] == '/') /* Absolute path => OK */
303 if (o[0] != '/' && o[0] != '?')
304 return URL_PATH_UNDERFLOW;
306 if (!a[0]) /* Empty URL -> inherit everything */
312 u->rest = d; /* We know we'll need to copy the path somewhere else */
314 if (a[0] == '#') /* Another fragment */
316 for(p=o; *p && *p != '#'; p++)
320 if (a[0] == '?') /* New query */
322 for(p=o; *p && *p != '#' && *p != '?'; p++)
326 if (a[0] == ';') /* Change parameters */
328 for(p=o; *p && *p != ';' && *p != '?' && *p != '#'; p++)
333 p = NULL; /* Copy original path and find the last slash */
334 while (*o && *o != ';' && *o != '?' && *o != '#')
337 return URL_ERR_TOO_LONG;
338 if ((*d++ = *o++) == '/')
342 return URL_ERR_REL_NOTHING;
349 if (a[1] == '/' || !a[1]) /* Skip "./" and ".$" */
356 else if (a[1] == '.' && (a[2] == '/' || !a[2])) /* "../" */
364 * RFC 1808 says we should leave ".." as a path segment, but
365 * we intentionally break the rule and refuse the URL.
367 if (!url_ignore_underflow)
368 return URL_PATH_UNDERFLOW;
372 d--; /* Discard trailing slash */
379 while (a[0] && a[0] != '/')
382 return URL_ERR_TOO_LONG;
394 copy: /* Combine part of old URL with the new one */
399 return URL_ERR_TOO_LONG;
404 return URL_ERR_TOO_LONG;
409 url_normalize(struct url *u, struct url *b)
414 if (url_proto_path_flags[u->protoid] && (!u->host || !*u->host) ||
415 !u->host && u->user ||
416 !u->user && u->pass ||
418 return URL_SYNTAX_ERROR;
422 /* Now we know it's a relative URL. Do we have any base? */
423 if (!b || !url_proto_path_flags[b->protoid])
424 return URL_ERR_REL_NOTHING;
425 u->protocol = b->protocol;
426 u->protoid = b->protoid;
428 /* Reference to the same host */
435 if (err = relpath_merge(u, b))
440 /* Change path "?" to "/?" because it's the true meaning */
441 if (u->rest[0] == '?')
443 int l = strlen(u->rest);
444 if (u->bufend - u->buf < l+1)
445 return URL_ERR_TOO_LONG;
447 memcpy(u->buf+1, u->rest, l+1);
452 /* Fill in missing info */
454 u->port = std_ports[u->protoid];
459 /* Name canonicalization */
467 if (*b >= 'A' && *b <= 'Z')
474 kill_end_dot(char *b)
480 k = b + strlen(b) - 1;
481 while (k > b && *k == '.')
487 url_canonicalize(struct url *u)
491 lowercase(u->protocol);
493 kill_end_dot(u->host);
494 if ((!u->rest || !*u->rest) && url_proto_path_flags[u->protoid])
496 if (u->rest && (c = strchr(u->rest, '#'))) /* Kill fragment reference */
501 /* Pack a broken-down URL */
504 append(char *d, const char *s, char *e)
517 url_pack(struct url *u, char *d)
519 char *e = d + MAX_URL_SIZE - 10;
523 d = append(d, u->protocol, e);
524 d = append(d, ":", e);
525 u->protoid = identify_protocol(u->protocol);
529 d = append(d, "//", e);
532 d = append(d, u->user, e);
535 d = append(d, ":", e);
536 d = append(d, u->pass, e);
538 d = append(d, "@", e);
540 d = append(d, u->host, e);
541 if (u->port != std_ports[u->protoid] && u->port != ~0U)
544 sprintf(z, "%d", u->port);
545 d = append(d, ":", e);
550 d = append(d, u->rest, e);
552 return URL_ERR_TOO_LONG;
559 static char *errmsg[] = {
560 "Something is wrong",
564 "Invalid escaped character",
565 "Invalid port number",
566 "Relative URL not allowed",
575 if (err >= sizeof(errmsg) / sizeof(char *))
580 /* Standard cookbook recipes */
583 url_canon_split_rel(const char *u, char *buf1, char *buf2, struct url *url, struct url *base)
587 if (err = url_deescape(u, buf1))
589 if (err = url_split(buf1, url, buf2))
591 if (err = url_normalize(url, base))
593 return url_canonicalize(url);
597 url_auto_canonicalize_rel(const char *src, char *dst, struct url *base)
599 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE];
603 (void)((err = url_canon_split_rel(src, buf1, buf2, &ur, base)) ||
604 (err = url_pack(&ur, buf3)) ||
605 (err = url_enescape(buf3, dst)));
613 int main(int argc, char **argv)
615 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE], buf4[MAX_URL_SIZE];
617 struct url url, url0;
618 char *base = "http://mj@www.hell.org/123/sub_dir/index.html;param?query&zzz/subquery#fragment";
620 if (argc != 2 && argc != 3)
624 if (err = url_deescape(argv[1], buf1))
626 printf("deesc: error %d\n", err);
629 printf("deesc: %s\n", buf1);
630 if (err = url_split(buf1, &url, buf2))
632 printf("split: error %d\n", err);
635 printf("split: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
636 if (err = url_split(base, &url0, buf3))
638 printf("split base: error %d\n", err);
641 if (err = url_normalize(&url0, NULL))
643 printf("normalize base: error %d\n", err);
646 printf("base: @%s@%s@%s@%s@%d@%s\n", url0.protocol, url0.user, url0.pass, url0.host, url0.port, url0.rest);
647 if (err = url_normalize(&url, &url0))
649 printf("normalize: error %d\n", err);
652 printf("normalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
653 if (err = url_canonicalize(&url))
655 printf("canonicalize: error %d\n", err);
658 printf("canonicalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
659 if (err = url_pack(&url, buf4))
661 printf("pack: error %d\n", err);
664 printf("pack: %s\n", buf4);
665 if (err = url_enescape(buf4, buf2))
667 printf("enesc: error %d\n", err);
670 printf("enesc: %s\n", buf2);
684 hashf(const char *start, int length)
688 hf = (hf << 8 | hf >> 24) ^ *start++;
693 repeat_count(struct component *comp, uns count, uns len)
695 struct component *orig_comp = comp;
705 for (i=0; i<len; i++)
706 if (comp[i].hash != orig_comp[i].hash
707 || comp[i].length != orig_comp[i].length
708 || memcmp(comp[i].start, orig_comp[i].start, comp[i].length))
714 url_has_repeated_component(const char *url)
716 struct component *comp;
717 uns comps, comp_len, rep_prefix, hash_size, *hash, *next;
721 for (comps=0, c=url; c; comps++)
723 c = strpbrk(c, url_component_separators);
727 if (comps < url_min_repeat_count && comps <= url_max_occurences)
729 comp = alloca(comps * sizeof(*comp));
730 for (i=0, c=url; c; i++)
733 c = strpbrk(c, url_component_separators);
736 comp[i].length = c - comp[i].start;
740 comp[i].length = strlen(comp[i].start);
743 for (i=0; i<comps; i++)
744 comp[i].hash = hashf(comp[i].start, comp[i].length);
745 if (comps > url_max_occurences)
747 hash_size = next_table_prime(comps);
748 hash = alloca(hash_size * sizeof(*hash));
749 next = alloca(comps * sizeof(*next));
750 memset(hash, 255, hash_size * sizeof(*hash));
751 for (i=0; i<comps; i++)
753 j = comp[i].hash % hash_size;
754 for (k = hash[j]; ~k && (comp[i].hash != comp[k].hash || comp[i].length != comp[k].length ||
755 memcmp(comp[k].start, comp[i].start, comp[i].length)); k = next[k]);
764 if (comp[k].count++ >= url_max_occurences)
769 for (comp_len = 1; comp_len <= url_max_repeat_length && comp_len <= comps; comp_len++)
770 for (rep_prefix = 0; rep_prefix <= comps - comp_len; rep_prefix++)
771 if (repeat_count(comp + rep_prefix, comps - rep_prefix, comp_len) >= url_min_repeat_count)