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"
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;
101 else if ((byte) *s > 0x20)
108 if (!url_ignore_spaces || !(!*s || d == dstart))
113 return URL_ERR_TOO_LONG;
119 return URL_ERR_INVALID_CHAR;
126 url_enescape(const char *s, char *d)
128 char *end = d + MAX_URL_SIZE - 10;
134 return URL_ERR_TOO_LONG;
135 if (Calnum(c) || /* RFC 1738(2.2): Only alphanumerics ... */
136 c == '$' || c == '-' || c == '_' || c == '.' || c == '+' || /* ... and several other exceptions ... */
137 c == '!' || c == '*' || c == '\'' || c == '(' || c == ')' ||
139 c == '/' || c == '?' || c == ':' || c == '@' || /* ... and reserved chars used for reserved purpose */
140 c == '=' || c == '&' || c == '#' || c == ';')
144 uns val = ((byte)*s < NCC_MAX) ? NCC_CHARS[(byte)*s] : *s;
146 *d++ = enhex(val >> 4);
147 *d++ = enhex(val & 0x0f);
156 url_enescape_friendly(const char *src, char *dest)
158 char *end = dest + MAX_URL_SIZE - 10;
159 const byte *srcb = src;
163 return URL_ERR_TOO_LONG;
165 *dest++ = NCC_CHARS[*srcb++];
166 else if (*srcb >= 0x20 && *srcb < 0x7f)
171 *dest++ = enhex(*srcb >> 4);
172 *dest++ = enhex(*srcb++ & 0x0f);
179 /* Split an URL (several parts may be copied to the destination buffer) */
181 char *url_proto_names[URL_PROTO_MAX] = URL_PNAMES;
182 static int url_proto_path_flags[URL_PROTO_MAX] = URL_PATH_FLAGS;
185 identify_protocol(const char *p)
189 for(i=1; i<URL_PROTO_MAX; i++)
190 if (!strcasecmp(p, url_proto_names[i]))
192 return URL_PROTO_UNKNOWN;
196 url_split(char *s, struct url *u, char *d)
198 bzero(u, sizeof(struct url));
200 u->bufend = d + MAX_URL_SIZE - 10;
202 if (s[0] != '/') /* Seek for "protocol:" */
205 while (*p && Calnum(*p))
207 if (p != s && *p == ':')
213 u->protoid = identify_protocol(u->protocol);
215 if (url_proto_path_flags[u->protoid] && (s[0] != '/' || s[1] != '/'))
217 /* The protocol requires complete host spec, but it's missing -> treat as a relative path instead */
218 int len = d - u->protocol;
227 if (s[0] == '/') /* Host spec or absolute path */
229 if (s[1] == '/') /* Host spec */
237 while (*s && *s != '/' && *s != '?') /* Copy user:passwd@host:port */
246 else /* This shouldn't happen with sane URL's, but we need to be sure */
251 if (at) /* user:passwd present */
254 if (e = strchr(q, ':'))
263 if (e) /* host:port present */
267 p = strtoul(e, &ep, 10);
268 if (ep && *ep || p > 65535)
269 return URL_ERR_INVALID_PORT;
270 else if (p) /* Port 0 (e.g. in :/) is treated as default port */
282 /* Normalization according to given base URL */
284 static uns std_ports[] = URL_DEFPORTS; /* Default port numbers */
287 relpath_merge(struct url *u, struct url *b)
295 if (a[0] == '/') /* Absolute path => OK */
297 if (o[0] != '/' && o[0] != '?')
298 return URL_PATH_UNDERFLOW;
300 if (!a[0]) /* Empty URL -> inherit everything */
306 u->rest = d; /* We know we'll need to copy the path somewhere else */
308 if (a[0] == '#') /* Another fragment */
310 for(p=o; *p && *p != '#'; p++)
314 if (a[0] == '?') /* New query */
316 for(p=o; *p && *p != '#' && *p != '?'; p++)
320 if (a[0] == ';') /* Change parameters */
322 for(p=o; *p && *p != ';' && *p != '?' && *p != '#'; p++)
327 p = NULL; /* Copy original path and find the last slash */
328 while (*o && *o != ';' && *o != '?' && *o != '#')
331 return URL_ERR_TOO_LONG;
332 if ((*d++ = *o++) == '/')
336 return URL_ERR_REL_NOTHING;
343 if (a[1] == '/' || !a[1]) /* Skip "./" and ".$" */
350 else if (a[1] == '.' && (a[2] == '/' || !a[2])) /* "../" */
358 * RFC 1808 says we should leave ".." as a path segment, but
359 * we intentionally break the rule and refuse the URL.
361 if (!url_ignore_underflow)
362 return URL_PATH_UNDERFLOW;
366 d--; /* Discard trailing slash */
373 while (a[0] && a[0] != '/')
376 return URL_ERR_TOO_LONG;
388 copy: /* Combine part of old URL with the new one */
393 return URL_ERR_TOO_LONG;
398 return URL_ERR_TOO_LONG;
403 url_normalize(struct url *u, struct url *b)
408 if (url_proto_path_flags[u->protoid] && (!u->host || !*u->host) ||
409 !u->host && u->user ||
410 !u->user && u->pass ||
412 return URL_SYNTAX_ERROR;
416 /* Now we know it's a relative URL. Do we have any base? */
417 if (!b || !url_proto_path_flags[b->protoid])
418 return URL_ERR_REL_NOTHING;
419 u->protocol = b->protocol;
420 u->protoid = b->protoid;
422 /* Reference to the same host */
429 if (err = relpath_merge(u, b))
434 /* Change path "?" to "/?" because it's the true meaning */
435 if (u->rest[0] == '?')
437 int l = strlen(u->rest);
438 if (u->bufend - u->buf < l+1)
439 return URL_ERR_TOO_LONG;
441 memcpy(u->buf+1, u->rest, l+1);
446 /* Fill in missing info */
448 u->port = std_ports[u->protoid];
453 /* Name canonicalization */
461 if (*b >= 'A' && *b <= 'Z')
468 kill_end_dot(char *b)
474 k = b + strlen(b) - 1;
475 while (k > b && *k == '.')
481 url_canonicalize(struct url *u)
485 lowercase(u->protocol);
487 kill_end_dot(u->host);
488 if ((!u->rest || !*u->rest) && url_proto_path_flags[u->protoid])
490 if (u->rest && (c = strchr(u->rest, '#'))) /* Kill fragment reference */
495 /* Pack a broken-down URL */
498 append(char *d, const char *s, char *e)
511 url_pack(struct url *u, char *d)
513 char *e = d + MAX_URL_SIZE - 10;
517 d = append(d, u->protocol, e);
518 d = append(d, ":", e);
519 u->protoid = identify_protocol(u->protocol);
523 d = append(d, "//", e);
526 d = append(d, u->user, e);
529 d = append(d, ":", e);
530 d = append(d, u->pass, e);
532 d = append(d, "@", e);
534 d = append(d, u->host, e);
535 if (u->port != std_ports[u->protoid] && u->port != ~0U)
538 sprintf(z, "%d", u->port);
539 d = append(d, ":", e);
544 d = append(d, u->rest, e);
546 return URL_ERR_TOO_LONG;
553 static char *errmsg[] = {
554 "Something is wrong",
558 "Invalid escaped character",
559 "Invalid port number",
560 "Relative URL not allowed",
569 if (err >= sizeof(errmsg) / sizeof(char *))
574 /* Standard cookbook recipes */
577 url_canon_split_rel(const char *u, char *buf1, char *buf2, struct url *url, struct url *base)
581 if (err = url_deescape(u, buf1))
583 if (err = url_split(buf1, url, buf2))
585 if (err = url_normalize(url, base))
587 return url_canonicalize(url);
591 url_auto_canonicalize_rel(const char *src, char *dst, struct url *base)
593 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE];
597 (void)((err = url_canon_split_rel(src, buf1, buf2, &ur, base)) ||
598 (err = url_pack(&ur, buf3)) ||
599 (err = url_enescape(buf3, dst)));
607 int main(int argc, char **argv)
609 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE], buf4[MAX_URL_SIZE];
611 struct url url, url0;
612 char *base = "http://mj@www.hell.org/123/sub_dir/index.html;param?query&zzz/subquery#fragment";
614 if (argc != 2 && argc != 3)
618 if (err = url_deescape(argv[1], buf1))
620 printf("deesc: error %d\n", err);
623 printf("deesc: %s\n", buf1);
624 if (err = url_split(buf1, &url, buf2))
626 printf("split: error %d\n", err);
629 printf("split: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
630 if (err = url_split(base, &url0, buf3))
632 printf("split base: error %d\n", err);
635 if (err = url_normalize(&url0, NULL))
637 printf("normalize base: error %d\n", err);
640 printf("base: @%s@%s@%s@%s@%d@%s\n", url0.protocol, url0.user, url0.pass, url0.host, url0.port, url0.rest);
641 if (err = url_normalize(&url, &url0))
643 printf("normalize: error %d\n", err);
646 printf("normalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
647 if (err = url_canonicalize(&url))
649 printf("canonicalize: error %d\n", err);
652 printf("canonicalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
653 if (err = url_pack(&url, buf4))
655 printf("pack: error %d\n", err);
658 printf("pack: %s\n", buf4);
659 if (err = url_enescape(buf4, buf2))
661 printf("enesc: error %d\n", err);
664 printf("enesc: %s\n", buf2);
678 hashf(const char *start, int length)
682 hf = (hf << 8 | hf >> 24) ^ *start++;
687 repeat_count(struct component *comp, uns count, uns len)
689 struct component *orig_comp = comp;
699 for (i=0; i<len; i++)
700 if (comp[i].hash != orig_comp[i].hash
701 || comp[i].length != orig_comp[i].length
702 || memcmp(comp[i].start, orig_comp[i].start, comp[i].length))
708 url_has_repeated_component(const char *url)
710 struct component *comp;
711 uns comps, comp_len, rep_prefix, hash_size, *hash, *next;
715 for (comps=0, c=url; c; comps++)
717 c = strpbrk(c, url_component_separators);
721 if (comps < url_min_repeat_count && comps <= url_max_occurences)
723 comp = alloca(comps * sizeof(*comp));
724 for (i=0, c=url; c; i++)
727 c = strpbrk(c, url_component_separators);
730 comp[i].length = c - comp[i].start;
734 comp[i].length = strlen(comp[i].start);
737 for (i=0; i<comps; i++)
738 comp[i].hash = hashf(comp[i].start, comp[i].length);
739 if (comps > url_max_occurences)
741 hash_size = next_table_prime(comps);
742 hash = alloca(hash_size * sizeof(*hash));
743 next = alloca(comps * sizeof(*next));
744 memset(hash, 255, hash_size * sizeof(*hash));
745 for (i=0; i<comps; i++)
747 j = comp[i].hash % hash_size;
748 for (k = hash[j]; ~k && (comp[i].hash != comp[k].hash || comp[i].length != comp[k].length ||
749 memcmp(comp[k].start, comp[i].start, comp[i].length)); k = next[k]);
758 if (comp[k].count++ >= url_max_occurences)
763 for (comp_len = 1; comp_len <= url_max_repeat_length && comp_len <= comps; comp_len++)
764 for (rep_prefix = 0; rep_prefix <= comps - comp_len; rep_prefix++)
765 if (repeat_count(comp + rep_prefix, comps - rep_prefix, comp_len) >= url_min_repeat_count)