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 * XXX: The buffer handling in this module is really horrible, but it works.
15 #include "ucw/chartype.h"
17 #include "ucw/prime.h"
26 static uns url_ignore_spaces;
27 static uns url_ignore_underflow;
28 static char *url_component_separators = "";
29 static uns url_min_repeat_count = 0x7fffffff;
30 static uns url_max_repeat_length = 0;
31 static uns url_max_occurences = ~0U;
33 static struct cf_section url_config = {
35 CF_UNS("IgnoreSpaces", &url_ignore_spaces),
36 CF_UNS("IgnoreUnderflow", &url_ignore_underflow),
37 CF_STRING("ComponentSeparators", &url_component_separators),
38 CF_UNS("MinRepeatCount", &url_min_repeat_count),
39 CF_UNS("MaxRepeatLength", &url_max_repeat_length),
40 CF_UNS("MaxOccurences", &url_max_occurences),
45 static void CONSTRUCTOR url_init_config(void)
47 cf_declare_section("URL", &url_config, 0);
50 /* Escaping and de-escaping */
55 return (x<10) ? (x + '0') : (x - 10 + 'A');
59 url_deescape(const char *s, char *d)
62 char *end = d + MAX_URL_SIZE - 10;
66 return URL_ERR_TOO_LONG;
70 if (!Cxdigit(s[1]) || !Cxdigit(s[2]))
71 return URL_ERR_INVALID_ESCAPE;
72 val = Cxvalue(s[1])*16 + Cxvalue(s[2]);
74 return URL_ERR_INVALID_ESCAPED_CHAR;
78 val = NCC_SEMICOLON; break;
80 val = NCC_SLASH; break;
82 val = NCC_QUEST; break;
84 val = NCC_COLON; break;
88 val = NCC_EQUAL; break;
92 val = NCC_HASH; break;
94 val = NCC_DOLLAR; break;
96 val = NCC_PLUS; break;
98 val = NCC_COMMA; break;
103 else if ((byte) *s > 0x20)
110 if (!url_ignore_spaces || !(!*s || d == dstart))
115 return URL_ERR_TOO_LONG;
121 return URL_ERR_INVALID_CHAR;
128 url_enescape(const char *s, char *d)
130 char *end = d + MAX_URL_SIZE - 10;
136 return URL_ERR_TOO_LONG;
137 if (Calnum(c) || /* RFC 2396 (2.1-2.3): Only alphanumerics ... */
138 c == '-' || c == '_' || c == '.' || c == '+' || c == '~' || /* ... and several other exceptions ... */
139 c == '!' || c == '*' || c == '\'' || c == '(' || c == ')' ||
140 c == '/' || c == '?' || c == ':' || c == '@' || /* ... and reserved chars used for reserved purpose */
141 c == '=' || c == '&' || c == '#' || c == ';' ||
142 c == '$' || c == '+' || c == ',')
146 uns val = ((byte)*s < NCC_MAX) ? NCC_CHARS[(byte)*s] : *s;
148 *d++ = enhex(val >> 4);
149 *d++ = enhex(val & 0x0f);
158 url_enescape_friendly(const char *src, char *dest)
160 char *end = dest + MAX_URL_SIZE - 10;
161 const byte *srcb = src;
165 return URL_ERR_TOO_LONG;
167 *dest++ = NCC_CHARS[*srcb++];
168 else if (*srcb >= 0x20 && *srcb < 0x7f)
173 *dest++ = enhex(*srcb >> 4);
174 *dest++ = enhex(*srcb++ & 0x0f);
181 /* Split an URL (several parts may be copied to the destination buffer) */
183 char *url_proto_names[URL_PROTO_MAX] = URL_PNAMES;
184 static int url_proto_path_flags[URL_PROTO_MAX] = URL_PATH_FLAGS;
187 url_identify_protocol(const char *p)
191 for(i=1; i<URL_PROTO_MAX; i++)
192 if (!strcasecmp(p, url_proto_names[i]))
194 return URL_PROTO_UNKNOWN;
198 url_split(char *s, struct url *u, char *d)
200 bzero(u, sizeof(struct url));
202 u->bufend = d + MAX_URL_SIZE - 10;
204 if (s[0] != '/') /* Seek for "protocol:" */
207 while (*p && Calnum(*p))
209 if (p != s && *p == ':')
215 u->protoid = url_identify_protocol(u->protocol);
217 if (url_proto_path_flags[u->protoid] && (s[0] != '/' || s[1] != '/'))
219 /* The protocol requires complete host spec, but it's missing -> treat as a relative path instead */
220 int len = d - u->protocol;
229 if (s[0] == '/') /* Host spec or absolute path */
231 if (s[1] == '/') /* Host spec */
239 while (*s && *s != '/' && *s != '?') /* Copy user:passwd@host:port */
248 else /* This shouldn't happen with sane URL's, but we need to be sure */
253 if (at) /* user:passwd present */
256 if (e = strchr(q, ':'))
265 if (e) /* host:port present */
269 p = strtoul(e, &ep, 10);
270 if (ep && *ep || p > 65535)
271 return URL_ERR_INVALID_PORT;
272 else if (p) /* Port 0 (e.g. in :/) is treated as default port */
284 /* Normalization according to given base URL */
286 static uns std_ports[] = URL_DEFPORTS; /* Default port numbers */
289 relpath_merge(struct url *u, struct url *b)
297 if (a[0] == '/') /* Absolute path => OK */
299 if (o[0] != '/' && o[0] != '?')
300 return URL_PATH_UNDERFLOW;
302 if (!a[0]) /* Empty URL -> inherit everything */
308 u->rest = d; /* We know we'll need to copy the path somewhere else */
310 if (a[0] == '#') /* Another fragment */
312 for(p=o; *p && *p != '#'; p++)
316 if (a[0] == '?') /* New query */
318 for(p=o; *p && *p != '#' && *p != '?'; p++)
323 p = NULL; /* Copy original path and find the last slash */
324 while (*o && *o != '?' && *o != '#')
327 return URL_ERR_TOO_LONG;
328 if ((*d++ = *o++) == '/')
332 return URL_ERR_REL_NOTHING;
339 if (a[1] == '/' || !a[1]) /* Skip "./" and ".$" */
346 else if (a[1] == '.' && (a[2] == '/' || !a[2])) /* "../" */
354 * RFC 1808 says we should leave ".." as a path segment, but
355 * we intentionally break the rule and refuse the URL.
357 if (!url_ignore_underflow)
358 return URL_PATH_UNDERFLOW;
362 d--; /* Discard trailing slash */
369 while (a[0] && a[0] != '/')
372 return URL_ERR_TOO_LONG;
384 copy: /* Combine part of old URL with the new one */
389 return URL_ERR_TOO_LONG;
394 return URL_ERR_TOO_LONG;
399 url_normalize(struct url *u, struct url *b)
404 if (url_proto_path_flags[u->protoid] && (!u->host || !*u->host) ||
405 !u->host && u->user ||
406 !u->user && u->pass ||
408 return URL_SYNTAX_ERROR;
412 /* Now we know it's a relative URL. Do we have any base? */
413 if (!b || !url_proto_path_flags[b->protoid])
414 return URL_ERR_REL_NOTHING;
415 u->protocol = b->protocol;
416 u->protoid = b->protoid;
418 /* Reference to the same host */
425 if (err = relpath_merge(u, b))
430 /* Change path "?" to "/?" because it's the true meaning */
431 if (u->rest[0] == '?')
433 int l = strlen(u->rest);
434 if (u->bufend - u->buf < l+1)
435 return URL_ERR_TOO_LONG;
437 memcpy(u->buf+1, u->rest, l+1);
442 /* Fill in missing info */
444 u->port = std_ports[u->protoid];
449 /* Name canonicalization */
457 if (*b >= 'A' && *b <= 'Z')
464 kill_end_dot(char *b)
470 k = b + strlen(b) - 1;
471 while (k > b && *k == '.')
477 url_canonicalize(struct url *u)
481 lowercase(u->protocol);
483 kill_end_dot(u->host);
484 if ((!u->rest || !*u->rest) && url_proto_path_flags[u->protoid])
486 if (u->rest && (c = strchr(u->rest, '#'))) /* Kill fragment reference */
491 /* Pack a broken-down URL */
494 append(char *d, const char *s, char *e)
507 url_pack(struct url *u, char *d)
509 char *e = d + MAX_URL_SIZE - 10;
513 d = append(d, u->protocol, e);
514 d = append(d, ":", e);
515 u->protoid = url_identify_protocol(u->protocol);
519 d = append(d, "//", e);
522 d = append(d, u->user, e);
525 d = append(d, ":", e);
526 d = append(d, u->pass, e);
528 d = append(d, "@", e);
530 d = append(d, u->host, e);
531 if (u->port != std_ports[u->protoid] && u->port != ~0U)
534 sprintf(z, "%d", u->port);
535 d = append(d, ":", e);
540 d = append(d, u->rest, e);
542 return URL_ERR_TOO_LONG;
549 static char *errmsg[] = {
550 "Something is wrong",
554 "Invalid escaped character",
555 "Invalid port number",
556 "Relative URL not allowed",
565 if (err >= sizeof(errmsg) / sizeof(char *))
570 /* Standard cookbook recipes */
573 url_canon_split_rel(const char *u, char *buf1, char *buf2, struct url *url, struct url *base)
577 if (err = url_deescape(u, buf1))
579 if (err = url_split(buf1, url, buf2))
581 if (err = url_normalize(url, base))
583 return url_canonicalize(url);
587 url_auto_canonicalize_rel(const char *src, char *dst, struct url *base)
589 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE];
593 (void)((err = url_canon_split_rel(src, buf1, buf2, &ur, base)) ||
594 (err = url_pack(&ur, buf3)) ||
595 (err = url_enescape(buf3, dst)));
603 int main(int argc, char **argv)
605 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE], buf4[MAX_URL_SIZE];
607 struct url url, url0;
608 char *base = "http://mj@www.hell.org/123/sub_dir;param/index.html;param?query&zzz/sub;query+#fragment?";
610 if (argc != 2 && argc != 3)
614 if (err = url_deescape(argv[1], buf1))
616 printf("deesc: error %d\n", err);
619 printf("deesc: %s\n", buf1);
620 if (err = url_split(buf1, &url, buf2))
622 printf("split: error %d\n", err);
625 printf("split: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
626 if (err = url_split(base, &url0, buf3))
628 printf("split base: error %d\n", err);
631 if (err = url_normalize(&url0, NULL))
633 printf("normalize base: error %d\n", err);
636 printf("base: @%s@%s@%s@%s@%d@%s\n", url0.protocol, url0.user, url0.pass, url0.host, url0.port, url0.rest);
637 if (err = url_normalize(&url, &url0))
639 printf("normalize: error %d\n", err);
642 printf("normalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
643 if (err = url_canonicalize(&url))
645 printf("canonicalize: error %d\n", err);
648 printf("canonicalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
649 if (err = url_pack(&url, buf4))
651 printf("pack: error %d\n", err);
654 printf("pack: %s\n", buf4);
655 if (err = url_enescape(buf4, buf2))
657 printf("enesc: error %d\n", err);
660 printf("enesc: %s\n", buf2);
674 hashf(const char *start, int length)
678 hf = (hf << 8 | hf >> 24) ^ *start++;
683 repeat_count(struct component *comp, uns count, uns len)
685 struct component *orig_comp = comp;
695 for (i=0; i<len; i++)
696 if (comp[i].hash != orig_comp[i].hash
697 || comp[i].length != orig_comp[i].length
698 || memcmp(comp[i].start, orig_comp[i].start, comp[i].length))
704 url_has_repeated_component(const char *url)
706 struct component *comp;
707 uns comps, comp_len, rep_prefix, hash_size, *hash, *next;
711 for (comps=0, c=url; c; comps++)
713 c = strpbrk(c, url_component_separators);
717 if (comps < url_min_repeat_count && comps <= url_max_occurences)
719 comp = alloca(comps * sizeof(*comp));
720 for (i=0, c=url; c; i++)
723 c = strpbrk(c, url_component_separators);
726 comp[i].length = c - comp[i].start;
730 comp[i].length = strlen(comp[i].start);
733 for (i=0; i<comps; i++)
734 comp[i].hash = hashf(comp[i].start, comp[i].length);
735 if (comps > url_max_occurences)
737 hash_size = next_table_prime(comps);
738 hash = alloca(hash_size * sizeof(*hash));
739 next = alloca(comps * sizeof(*next));
740 memset(hash, 255, hash_size * sizeof(*hash));
741 for (i=0; i<comps; i++)
743 j = comp[i].hash % hash_size;
744 for (k = hash[j]; ~k && (comp[i].hash != comp[k].hash || comp[i].length != comp[k].length ||
745 memcmp(comp[k].start, comp[i].start, comp[i].length)); k = next[k]);
754 if (comp[k].count++ >= url_max_occurences)
759 for (comp_len = 1; comp_len <= url_max_repeat_length && comp_len <= comps; comp_len++)
760 for (rep_prefix = 0; rep_prefix <= comps - comp_len; rep_prefix++)
761 if (repeat_count(comp + rep_prefix, comps - rep_prefix, comp_len) >= url_min_repeat_count)