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 Escaping of special characters still follows RFC 1738.
13 * o Interpretation of path parameters follows RFC 1808.
15 * XXX: The buffer handling in this module is really horrible, but it works.
20 #include "ucw/chartype.h"
22 #include "ucw/prime.h"
31 static uns url_ignore_spaces;
32 static uns url_ignore_underflow;
33 static char *url_component_separators = "";
34 static uns url_min_repeat_count = 0x7fffffff;
35 static uns url_max_repeat_length = 0;
36 static uns url_max_occurences = ~0U;
38 static struct cf_section url_config = {
40 CF_UNS("IgnoreSpaces", &url_ignore_spaces),
41 CF_UNS("IgnoreUnderflow", &url_ignore_underflow),
42 CF_STRING("ComponentSeparators", &url_component_separators),
43 CF_UNS("MinRepeatCount", &url_min_repeat_count),
44 CF_UNS("MaxRepeatLength", &url_max_repeat_length),
45 CF_UNS("MaxOccurences", &url_max_occurences),
50 static void CONSTRUCTOR url_init_config(void)
52 cf_declare_section("URL", &url_config, 0);
55 /* Escaping and de-escaping */
60 return (x<10) ? (x + '0') : (x - 10 + 'A');
64 url_deescape(const char *s, char *d)
67 char *end = d + MAX_URL_SIZE - 10;
71 return URL_ERR_TOO_LONG;
75 if (!Cxdigit(s[1]) || !Cxdigit(s[2]))
76 return URL_ERR_INVALID_ESCAPE;
77 val = Cxvalue(s[1])*16 + Cxvalue(s[2]);
79 return URL_ERR_INVALID_ESCAPED_CHAR;
83 val = NCC_SEMICOLON; break;
85 val = NCC_SLASH; break;
87 val = NCC_QUEST; break;
89 val = NCC_COLON; break;
93 val = NCC_EQUAL; break;
97 val = NCC_HASH; break;
102 else if ((byte) *s > 0x20)
109 if (!url_ignore_spaces || !(!*s || d == dstart))
114 return URL_ERR_TOO_LONG;
120 return URL_ERR_INVALID_CHAR;
127 url_enescape(const char *s, char *d)
129 char *end = d + MAX_URL_SIZE - 10;
135 return URL_ERR_TOO_LONG;
136 if (Calnum(c) || /* RFC 1738(2.2): Only alphanumerics ... */
137 c == '$' || c == '-' || c == '_' || c == '.' || c == '+' || /* ... and several other exceptions ... */
138 c == '!' || c == '*' || c == '\'' || c == '(' || c == ')' ||
140 c == '/' || c == '?' || c == ':' || c == '@' || /* ... and reserved chars used for reserved purpose */
141 c == '=' || c == '&' || c == '#' || c == ';')
145 uns val = ((byte)*s < NCC_MAX) ? NCC_CHARS[(byte)*s] : *s;
147 *d++ = enhex(val >> 4);
148 *d++ = enhex(val & 0x0f);
157 url_enescape_friendly(const char *src, char *dest)
159 char *end = dest + MAX_URL_SIZE - 10;
160 const byte *srcb = src;
164 return URL_ERR_TOO_LONG;
166 *dest++ = NCC_CHARS[*srcb++];
167 else if (*srcb >= 0x20 && *srcb < 0x7f)
172 *dest++ = enhex(*srcb >> 4);
173 *dest++ = enhex(*srcb++ & 0x0f);
180 /* Split an URL (several parts may be copied to the destination buffer) */
182 char *url_proto_names[URL_PROTO_MAX] = URL_PNAMES;
183 static int url_proto_path_flags[URL_PROTO_MAX] = URL_PATH_FLAGS;
186 identify_protocol(const char *p)
190 for(i=1; i<URL_PROTO_MAX; i++)
191 if (!strcasecmp(p, url_proto_names[i]))
193 return URL_PROTO_UNKNOWN;
197 url_split(char *s, struct url *u, char *d)
199 bzero(u, sizeof(struct url));
201 u->bufend = d + MAX_URL_SIZE - 10;
203 if (s[0] != '/') /* Seek for "protocol:" */
206 while (*p && Calnum(*p))
208 if (p != s && *p == ':')
214 u->protoid = identify_protocol(u->protocol);
216 if (url_proto_path_flags[u->protoid] && (s[0] != '/' || s[1] != '/'))
218 /* The protocol requires complete host spec, but it's missing -> treat as a relative path instead */
219 int len = d - u->protocol;
228 if (s[0] == '/') /* Host spec or absolute path */
230 if (s[1] == '/') /* Host spec */
238 while (*s && *s != '/' && *s != '?') /* Copy user:passwd@host:port */
247 else /* This shouldn't happen with sane URL's, but we need to be sure */
252 if (at) /* user:passwd present */
255 if (e = strchr(q, ':'))
264 if (e) /* host:port present */
268 p = strtoul(e, &ep, 10);
269 if (ep && *ep || p > 65535)
270 return URL_ERR_INVALID_PORT;
271 else if (p) /* Port 0 (e.g. in :/) is treated as default port */
283 /* Normalization according to given base URL */
285 static uns std_ports[] = URL_DEFPORTS; /* Default port numbers */
288 relpath_merge(struct url *u, struct url *b)
296 if (a[0] == '/') /* Absolute path => OK */
298 if (o[0] != '/' && o[0] != '?')
299 return URL_PATH_UNDERFLOW;
301 if (!a[0]) /* Empty URL -> inherit everything */
307 u->rest = d; /* We know we'll need to copy the path somewhere else */
309 if (a[0] == '#') /* Another fragment */
311 for(p=o; *p && *p != '#'; p++)
315 if (a[0] == '?') /* New query */
317 for(p=o; *p && *p != '#' && *p != '?'; p++)
321 if (a[0] == ';') /* Change parameters */
323 for(p=o; *p && *p != ';' && *p != '?' && *p != '#'; p++)
328 p = NULL; /* Copy original path and find the last slash */
329 while (*o && *o != ';' && *o != '?' && *o != '#')
332 return URL_ERR_TOO_LONG;
333 if ((*d++ = *o++) == '/')
337 return URL_ERR_REL_NOTHING;
344 if (a[1] == '/' || !a[1]) /* Skip "./" and ".$" */
351 else if (a[1] == '.' && (a[2] == '/' || !a[2])) /* "../" */
359 * RFC 1808 says we should leave ".." as a path segment, but
360 * we intentionally break the rule and refuse the URL.
362 if (!url_ignore_underflow)
363 return URL_PATH_UNDERFLOW;
367 d--; /* Discard trailing slash */
374 while (a[0] && a[0] != '/')
377 return URL_ERR_TOO_LONG;
389 copy: /* Combine part of old URL with the new one */
394 return URL_ERR_TOO_LONG;
399 return URL_ERR_TOO_LONG;
404 url_normalize(struct url *u, struct url *b)
409 if (url_proto_path_flags[u->protoid] && (!u->host || !*u->host) ||
410 !u->host && u->user ||
411 !u->user && u->pass ||
413 return URL_SYNTAX_ERROR;
417 /* Now we know it's a relative URL. Do we have any base? */
418 if (!b || !url_proto_path_flags[b->protoid])
419 return URL_ERR_REL_NOTHING;
420 u->protocol = b->protocol;
421 u->protoid = b->protoid;
423 /* Reference to the same host */
430 if (err = relpath_merge(u, b))
435 /* Change path "?" to "/?" because it's the true meaning */
436 if (u->rest[0] == '?')
438 int l = strlen(u->rest);
439 if (u->bufend - u->buf < l+1)
440 return URL_ERR_TOO_LONG;
442 memcpy(u->buf+1, u->rest, l+1);
447 /* Fill in missing info */
449 u->port = std_ports[u->protoid];
454 /* Name canonicalization */
462 if (*b >= 'A' && *b <= 'Z')
469 kill_end_dot(char *b)
475 k = b + strlen(b) - 1;
476 while (k > b && *k == '.')
482 url_canonicalize(struct url *u)
486 lowercase(u->protocol);
488 kill_end_dot(u->host);
489 if ((!u->rest || !*u->rest) && url_proto_path_flags[u->protoid])
491 if (u->rest && (c = strchr(u->rest, '#'))) /* Kill fragment reference */
496 /* Pack a broken-down URL */
499 append(char *d, const char *s, char *e)
512 url_pack(struct url *u, char *d)
514 char *e = d + MAX_URL_SIZE - 10;
518 d = append(d, u->protocol, e);
519 d = append(d, ":", e);
520 u->protoid = identify_protocol(u->protocol);
524 d = append(d, "//", e);
527 d = append(d, u->user, e);
530 d = append(d, ":", e);
531 d = append(d, u->pass, e);
533 d = append(d, "@", e);
535 d = append(d, u->host, e);
536 if (u->port != std_ports[u->protoid] && u->port != ~0U)
539 sprintf(z, "%d", u->port);
540 d = append(d, ":", e);
545 d = append(d, u->rest, e);
547 return URL_ERR_TOO_LONG;
554 static char *errmsg[] = {
555 "Something is wrong",
559 "Invalid escaped character",
560 "Invalid port number",
561 "Relative URL not allowed",
570 if (err >= sizeof(errmsg) / sizeof(char *))
575 /* Standard cookbook recipes */
578 url_canon_split_rel(const char *u, char *buf1, char *buf2, struct url *url, struct url *base)
582 if (err = url_deescape(u, buf1))
584 if (err = url_split(buf1, url, buf2))
586 if (err = url_normalize(url, base))
588 return url_canonicalize(url);
592 url_auto_canonicalize_rel(const char *src, char *dst, struct url *base)
594 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE];
598 (void)((err = url_canon_split_rel(src, buf1, buf2, &ur, base)) ||
599 (err = url_pack(&ur, buf3)) ||
600 (err = url_enescape(buf3, dst)));
608 int main(int argc, char **argv)
610 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE], buf4[MAX_URL_SIZE];
612 struct url url, url0;
613 char *base = "http://mj@www.hell.org/123/sub_dir/index.html;param?query&zzz/subquery#fragment";
615 if (argc != 2 && argc != 3)
619 if (err = url_deescape(argv[1], buf1))
621 printf("deesc: error %d\n", err);
624 printf("deesc: %s\n", buf1);
625 if (err = url_split(buf1, &url, buf2))
627 printf("split: error %d\n", err);
630 printf("split: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
631 if (err = url_split(base, &url0, buf3))
633 printf("split base: error %d\n", err);
636 if (err = url_normalize(&url0, NULL))
638 printf("normalize base: error %d\n", err);
641 printf("base: @%s@%s@%s@%s@%d@%s\n", url0.protocol, url0.user, url0.pass, url0.host, url0.port, url0.rest);
642 if (err = url_normalize(&url, &url0))
644 printf("normalize: error %d\n", err);
647 printf("normalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
648 if (err = url_canonicalize(&url))
650 printf("canonicalize: error %d\n", err);
653 printf("canonicalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
654 if (err = url_pack(&url, buf4))
656 printf("pack: error %d\n", err);
659 printf("pack: %s\n", buf4);
660 if (err = url_enescape(buf4, buf2))
662 printf("enesc: error %d\n", err);
665 printf("enesc: %s\n", buf2);
679 hashf(const char *start, int length)
683 hf = (hf << 8 | hf >> 24) ^ *start++;
688 repeat_count(struct component *comp, uns count, uns len)
690 struct component *orig_comp = comp;
700 for (i=0; i<len; i++)
701 if (comp[i].hash != orig_comp[i].hash
702 || comp[i].length != orig_comp[i].length
703 || memcmp(comp[i].start, orig_comp[i].start, comp[i].length))
709 url_has_repeated_component(const char *url)
711 struct component *comp;
712 uns comps, comp_len, rep_prefix, hash_size, *hash, *next;
716 for (comps=0, c=url; c; comps++)
718 c = strpbrk(c, url_component_separators);
722 if (comps < url_min_repeat_count && comps <= url_max_occurences)
724 comp = alloca(comps * sizeof(*comp));
725 for (i=0, c=url; c; i++)
728 c = strpbrk(c, url_component_separators);
731 comp[i].length = c - comp[i].start;
735 comp[i].length = strlen(comp[i].start);
738 for (i=0; i<comps; i++)
739 comp[i].hash = hashf(comp[i].start, comp[i].length);
740 if (comps > url_max_occurences)
742 hash_size = next_table_prime(comps);
743 hash = alloca(hash_size * sizeof(*hash));
744 next = alloca(comps * sizeof(*next));
745 memset(hash, 255, hash_size * sizeof(*hash));
746 for (i=0; i<comps; i++)
748 j = comp[i].hash % hash_size;
749 for (k = hash[j]; ~k && (comp[i].hash != comp[k].hash || comp[i].length != comp[k].length ||
750 memcmp(comp[k].start, comp[i].start, comp[i].length)); k = next[k]);
759 if (comp[k].count++ >= url_max_occurences)
764 for (comp_len = 1; comp_len <= url_max_repeat_length && comp_len <= comps; comp_len++)
765 for (rep_prefix = 0; rep_prefix <= comps - comp_len; rep_prefix++)
766 if (repeat_count(comp + rep_prefix, comps - rep_prefix, comp_len) >= url_min_repeat_count)