2 * Sherlock Library -- URL Functions
4 * (c) 1997--2004 Martin Mares <mj@ucw.cz>
5 * (c) 2001 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.
14 * o Parsing a relative URL "x" wrt. base "http://hell.org?y"
15 * gives an error, which might be wrong. However, I failed
16 * to find any rule applying to this case in the RFC.
21 #include "lib/chartype.h"
31 static uns url_ignore_spaces;
32 static uns url_ignore_underflow;
33 static byte *url_component_separators = "";
34 static uns url_min_repeat_count = 0x7fffffff;
35 static uns url_max_repeat_length = 0;
37 static struct cfitem url_config[] = {
38 { "URL", CT_SECTION, NULL },
39 { "IgnoreSpaces", CT_INT, &url_ignore_spaces },
40 { "IgnoreUnderflow", CT_INT, &url_ignore_underflow },
41 { "ComponentSeparators", CT_STRING, &url_component_separators },
42 { "MinRepeatCount", CT_INT, &url_min_repeat_count },
43 { "MaxRepeatLength", CT_INT, &url_max_repeat_length },
44 { NULL, CT_STOP, NULL }
47 static void CONSTRUCTOR url_init_config(void)
49 cf_register(url_config);
52 /* Escaping and de-escaping */
57 return (x<10) ? (x + '0') : (x - 10 + 'A');
61 url_deescape(byte *s, byte *d)
64 byte *end = d + MAX_URL_SIZE - 10;
68 return URL_ERR_TOO_LONG;
72 if (!Cxdigit(s[1]) || !Cxdigit(s[2]))
73 return URL_ERR_INVALID_ESCAPE;
74 val = Cxvalue(s[1])*16 + Cxvalue(s[2]);
76 return URL_ERR_INVALID_ESCAPED_CHAR;
80 val = NCC_SEMICOLON; break;
82 val = NCC_SLASH; break;
84 val = NCC_QUEST; break;
86 val = NCC_COLON; break;
90 val = NCC_EQUAL; break;
94 val = NCC_HASH; break;
106 if (!url_ignore_spaces || !(!*s || d == dstart))
111 return URL_ERR_TOO_LONG;
117 return URL_ERR_INVALID_CHAR;
124 url_enescape(byte *s, byte *d)
126 byte *end = d + MAX_URL_SIZE - 10;
132 return URL_ERR_TOO_LONG;
133 if (Calnum(c) || /* RFC 1738(2.2): Only alphanumerics ... */
134 c == '$' || c == '-' || c == '_' || c == '.' || c == '+' || /* ... and several other exceptions ... */
135 c == '!' || c == '*' || c == '\'' || c == '(' || c == ')' ||
137 c == '/' || c == '?' || c == ':' || c == '@' || /* ... and reserved chars used for reserved purpose */
138 c == '=' || c == '&' || c == '#' || c == ';')
142 uns val = (*s < NCC_MAX) ? NCC_CHARS[*s] : *s;
144 *d++ = enhex(val >> 4);
145 *d++ = enhex(val & 0x0f);
153 /* Split an URL (several parts may be copied to the destination buffer) */
155 byte *url_proto_names[URL_PROTO_MAX] = URL_PNAMES;
156 static int url_proto_path_flags[URL_PROTO_MAX] = URL_PATH_FLAGS;
159 identify_protocol(byte *p)
163 for(i=1; i<URL_PROTO_MAX; i++)
164 if (!strcasecmp(p, url_proto_names[i]))
166 return URL_PROTO_UNKNOWN;
170 url_split(byte *s, struct url *u, byte *d)
172 bzero(u, sizeof(struct url));
174 u->bufend = d + MAX_URL_SIZE - 10;
176 if (s[0] != '/') /* Seek for "protocol:" */
179 while (*p && Calnum(*p))
181 if (p != s && *p == ':')
187 u->protoid = identify_protocol(u->protocol);
189 if (url_proto_path_flags[u->protoid] && (s[0] != '/' || s[1] != '/'))
191 /* The protocol requires complete host spec, but it's missing -> treat as a relative path instead */
192 int len = d - u->protocol;
201 if (s[0] == '/') /* Host spec or absolute path */
203 if (s[1] == '/') /* Host spec */
210 while (*s && *s != '/' && *s != '?') /* Copy user:passwd@host:port */
214 if (w) /* user:passwd present */
218 if (e = strchr(q, ':'))
227 if (e) /* host:port present */
231 p = strtoul(e, &ep, 10);
232 if (ep && *ep || p > 65535)
233 return URL_ERR_INVALID_PORT;
234 else if (p) /* Port 0 (e.g. in :/) is treated as default port */
246 /* Normalization according to given base URL */
248 static uns std_ports[] = URL_DEFPORTS; /* Default port numbers */
251 relpath_merge(struct url *u, struct url *b)
259 if (a[0] == '/') /* Absolute path => OK */
261 if (o[0] != '/' && o[0] != '?')
262 return URL_PATH_UNDERFLOW;
264 if (!a[0]) /* Empty URL -> inherit everything */
270 u->rest = d; /* We know we'll need to copy the path somewhere else */
272 if (a[0] == '#') /* Another fragment */
274 for(p=o; *p && *p != '#'; p++)
278 if (a[0] == '?') /* New query */
280 for(p=o; *p && *p != '#' && *p != '?'; p++)
284 if (a[0] == ';') /* Change parameters */
286 for(p=o; *p && *p != ';' && *p != '?' && *p != '#'; p++)
291 p = NULL; /* Copy original path and find the last slash */
292 while (*o && *o != ';' && *o != '?' && *o != '#')
295 return URL_ERR_TOO_LONG;
296 if ((*d++ = *o++) == '/')
300 return URL_ERR_REL_NOTHING;
307 if (a[1] == '/' || !a[1]) /* Skip "./" and ".$" */
314 else if (a[1] == '.' && (a[2] == '/' || !a[2])) /* "../" */
322 * RFC 1808 says we should leave ".." as a path segment, but
323 * we intentionally break the rule and refuse the URL.
325 if (!url_ignore_underflow)
326 return URL_PATH_UNDERFLOW;
330 d--; /* Discard trailing slash */
337 while (a[0] && a[0] != '/')
340 return URL_ERR_TOO_LONG;
352 copy: /* Combine part of old URL with the new one */
357 return URL_ERR_TOO_LONG;
362 return URL_ERR_TOO_LONG;
367 url_normalize(struct url *u, struct url *b)
372 if (url_proto_path_flags[u->protoid] && !u->host ||
373 u->host && !*u->host ||
374 !u->host && u->user ||
375 !u->user && u->pass ||
377 return URL_SYNTAX_ERROR;
381 /* Now we know it's a relative URL. Do we have any base? */
382 if (!b || !url_proto_path_flags[b->protoid])
383 return URL_ERR_REL_NOTHING;
384 u->protocol = b->protocol;
385 u->protoid = b->protoid;
387 /* Reference to the same host */
394 if (err = relpath_merge(u, b))
399 /* Fill in missing info */
401 u->port = std_ports[u->protoid];
406 /* Name canonicalization */
414 if (*b >= 'A' && *b <= 'Z')
421 kill_end_dot(byte *b)
427 k = b + strlen(b) - 1;
428 while (k > b && *k == '.')
434 url_canonicalize(struct url *u)
438 lowercase(u->protocol);
440 kill_end_dot(u->host);
441 if ((!u->rest || !*u->rest) && url_proto_path_flags[u->protoid])
443 if (u->rest && (c = strchr(u->rest, '#'))) /* Kill fragment reference */
448 /* Pack a broken-down URL */
451 append(byte *d, byte *s, byte *e)
464 url_pack(struct url *u, byte *d)
466 byte *e = d + MAX_URL_SIZE - 10;
470 d = append(d, u->protocol, e);
471 d = append(d, ":", e);
472 u->protoid = identify_protocol(u->protocol);
476 d = append(d, "//", e);
479 d = append(d, u->user, e);
482 d = append(d, ":", e);
483 d = append(d, u->pass, e);
485 d = append(d, "@", e);
487 d = append(d, u->host, e);
488 if (u->port != std_ports[u->protoid] && u->port != ~0U)
491 sprintf(z, "%d", u->port);
492 d = append(d, ":", e);
497 d = append(d, u->rest, e);
499 return URL_ERR_TOO_LONG;
506 static char *errmsg[] = {
507 "Something is wrong",
511 "Invalid escaped character",
512 "Invalid port number",
513 "Relative URL not allowed",
522 if (err >= sizeof(errmsg) / sizeof(char *))
527 /* Standard cookbook recipes */
530 url_canon_split(byte *u, byte *buf1, byte *buf2, struct url *url)
534 if (err = url_deescape(u, buf1))
536 if (err = url_split(buf1, url, buf2))
538 if (err = url_normalize(url, NULL))
540 return url_canonicalize(url);
544 url_auto_canonicalize(byte *src, byte *dst)
546 byte buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE];
550 (void)((err = url_canon_split(src, buf1, buf2, &ur)) ||
551 (err = url_pack(&ur, buf3)) ||
552 (err = url_enescape(buf3, dst)));
560 int main(int argc, char **argv)
562 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE], buf4[MAX_URL_SIZE];
564 struct url url, url0;
565 char *base = "http://mj@www.hell.org/123/sub_dir/index.html;param?query&zzz/subquery#fragment";
567 if (argc != 2 && argc != 3)
571 if (err = url_deescape(argv[1], buf1))
573 printf("deesc: error %d\n", err);
576 printf("deesc: %s\n", buf1);
577 if (err = url_split(buf1, &url, buf2))
579 printf("split: error %d\n", err);
582 printf("split: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
583 if (err = url_split(base, &url0, buf3))
585 printf("split base: error %d\n", err);
588 if (err = url_normalize(&url0, NULL))
590 printf("normalize base: error %d\n", err);
593 printf("base: @%s@%s@%s@%s@%d@%s\n", url0.protocol, url0.user, url0.pass, url0.host, url0.port, url0.rest);
594 if (err = url_normalize(&url, &url0))
596 printf("normalize: error %d\n", err);
599 printf("normalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
600 if (err = url_canonicalize(&url))
602 printf("canonicalize: error %d\n", err);
605 printf("canonicalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
606 if (err = url_pack(&url, buf4))
608 printf("pack: error %d\n", err);
611 printf("pack: %s\n", buf4);
612 if (err = url_enescape(buf4, buf2))
614 printf("enesc: error %d\n", err);
617 printf("enesc: %s\n", buf2);
630 hashf(byte *start, int length)
634 hf = (hf << 8 | hf >> 24) ^ *start++;
639 repeat_count(struct component *comp, uns count, uns len)
641 struct component *orig_comp = comp;
651 for (i=0; i<len; i++)
652 if (comp[i].hash != orig_comp[i].hash
653 || comp[i].length != orig_comp[i].length
654 || memcmp(comp[i].start, orig_comp[i].start, comp[i].length))
660 url_has_repeated_component(byte *url)
662 struct component *comp;
663 uns comps, comp_len, rep_prefix;
667 for (comps=0, c=url; c; comps++)
669 c = strpbrk(c, url_component_separators);
673 if (comps < url_min_repeat_count)
675 comp = alloca(comps * sizeof(struct component));
676 for (i=0, c=url; c; i++)
679 c = strpbrk(c, url_component_separators);
682 comp[i].length = c - comp[i].start;
686 comp[i].length = strlen(comp[i].start);
689 for (i=0; i<comps; i++)
690 comp[i].hash = hashf(comp[i].start, comp[i].length);
691 for (comp_len = 1; comp_len <= url_max_repeat_length && comp_len <= comps; comp_len++)
692 for (rep_prefix = 0; rep_prefix <= comps - comp_len; rep_prefix++)
693 if (repeat_count(comp + rep_prefix, comps - rep_prefix, comp_len) >= url_min_repeat_count)