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 "lib/chartype.h"
30 static uns url_ignore_spaces;
31 static uns url_ignore_underflow;
32 static byte *url_component_separators = "";
33 static uns url_min_repeat_count = 0x7fffffff;
34 static uns url_max_repeat_length = 0;
36 static struct cfitem url_config[] = {
37 { "URL", CT_SECTION, NULL },
38 { "IgnoreSpaces", CT_INT, &url_ignore_spaces },
39 { "IgnoreUnderflow", CT_INT, &url_ignore_underflow },
40 { "ComponentSeparators", CT_STRING, &url_component_separators },
41 { "MinRepeatCount", CT_INT, &url_min_repeat_count },
42 { "MaxRepeatLength", CT_INT, &url_max_repeat_length },
43 { NULL, CT_STOP, NULL }
46 static void CONSTRUCTOR url_init_config(void)
48 cf_register(url_config);
51 /* Escaping and de-escaping */
56 return (x<10) ? (x + '0') : (x - 10 + 'A');
60 url_deescape(byte *s, byte *d)
63 byte *end = d + MAX_URL_SIZE - 10;
67 return URL_ERR_TOO_LONG;
71 if (!Cxdigit(s[1]) || !Cxdigit(s[2]))
72 return URL_ERR_INVALID_ESCAPE;
73 val = Cxvalue(s[1])*16 + Cxvalue(s[2]);
75 return URL_ERR_INVALID_ESCAPED_CHAR;
79 val = NCC_SEMICOLON; break;
81 val = NCC_SLASH; break;
83 val = NCC_QUEST; break;
85 val = NCC_COLON; break;
89 val = NCC_EQUAL; break;
93 val = NCC_HASH; break;
105 if (!url_ignore_spaces || !(!*s || d == dstart))
110 return URL_ERR_TOO_LONG;
116 return URL_ERR_INVALID_CHAR;
123 url_enescape(byte *s, byte *d)
125 byte *end = d + MAX_URL_SIZE - 10;
131 return URL_ERR_TOO_LONG;
132 if (Calnum(c) || /* RFC 1738(2.2): Only alphanumerics ... */
133 c == '$' || c == '-' || c == '_' || c == '.' || c == '+' || /* ... and several other exceptions ... */
134 c == '!' || c == '*' || c == '\'' || c == '(' || c == ')' ||
136 c == '/' || c == '?' || c == ':' || c == '@' || /* ... and reserved chars used for reserved purpose */
137 c == '=' || c == '&' || c == '#' || c == ';')
141 uns val = (*s < NCC_MAX) ? NCC_CHARS[*s] : *s;
143 *d++ = enhex(val >> 4);
144 *d++ = enhex(val & 0x0f);
153 url_enescape_friendly(byte *src, byte *dest)
155 byte *end = dest + MAX_URL_SIZE - 10;
159 return URL_ERR_TOO_LONG;
161 *dest++ = NCC_CHARS[*src++];
162 else if (*src >= 0x20 && *src < 0x7f)
167 *dest++ = enhex(*src >> 4);
168 *dest++ = enhex(*src++ & 0x0f);
175 /* Split an URL (several parts may be copied to the destination buffer) */
177 byte *url_proto_names[URL_PROTO_MAX] = URL_PNAMES;
178 static int url_proto_path_flags[URL_PROTO_MAX] = URL_PATH_FLAGS;
181 identify_protocol(byte *p)
185 for(i=1; i<URL_PROTO_MAX; i++)
186 if (!strcasecmp(p, url_proto_names[i]))
188 return URL_PROTO_UNKNOWN;
192 url_split(byte *s, struct url *u, byte *d)
194 bzero(u, sizeof(struct url));
196 u->bufend = d + MAX_URL_SIZE - 10;
198 if (s[0] != '/') /* Seek for "protocol:" */
201 while (*p && Calnum(*p))
203 if (p != s && *p == ':')
209 u->protoid = identify_protocol(u->protocol);
211 if (url_proto_path_flags[u->protoid] && (s[0] != '/' || s[1] != '/'))
213 /* The protocol requires complete host spec, but it's missing -> treat as a relative path instead */
214 int len = d - u->protocol;
223 if (s[0] == '/') /* Host spec or absolute path */
225 if (s[1] == '/') /* Host spec */
232 while (*s && *s != '/' && *s != '?') /* Copy user:passwd@host:port */
236 if (w) /* user:passwd present */
240 if (e = strchr(q, ':'))
249 if (e) /* host:port present */
253 p = strtoul(e, &ep, 10);
254 if (ep && *ep || p > 65535)
255 return URL_ERR_INVALID_PORT;
256 else if (p) /* Port 0 (e.g. in :/) is treated as default port */
268 /* Normalization according to given base URL */
270 static uns std_ports[] = URL_DEFPORTS; /* Default port numbers */
273 relpath_merge(struct url *u, struct url *b)
281 if (a[0] == '/') /* Absolute path => OK */
283 if (o[0] != '/' && o[0] != '?')
284 return URL_PATH_UNDERFLOW;
286 if (!a[0]) /* Empty URL -> inherit everything */
292 u->rest = d; /* We know we'll need to copy the path somewhere else */
294 if (a[0] == '#') /* Another fragment */
296 for(p=o; *p && *p != '#'; p++)
300 if (a[0] == '?') /* New query */
302 for(p=o; *p && *p != '#' && *p != '?'; p++)
306 if (a[0] == ';') /* Change parameters */
308 for(p=o; *p && *p != ';' && *p != '?' && *p != '#'; p++)
313 p = NULL; /* Copy original path and find the last slash */
314 while (*o && *o != ';' && *o != '?' && *o != '#')
317 return URL_ERR_TOO_LONG;
318 if ((*d++ = *o++) == '/')
322 return URL_ERR_REL_NOTHING;
329 if (a[1] == '/' || !a[1]) /* Skip "./" and ".$" */
336 else if (a[1] == '.' && (a[2] == '/' || !a[2])) /* "../" */
344 * RFC 1808 says we should leave ".." as a path segment, but
345 * we intentionally break the rule and refuse the URL.
347 if (!url_ignore_underflow)
348 return URL_PATH_UNDERFLOW;
352 d--; /* Discard trailing slash */
359 while (a[0] && a[0] != '/')
362 return URL_ERR_TOO_LONG;
374 copy: /* Combine part of old URL with the new one */
379 return URL_ERR_TOO_LONG;
384 return URL_ERR_TOO_LONG;
389 url_normalize(struct url *u, struct url *b)
394 if (url_proto_path_flags[u->protoid] && (!u->host || !*u->host) ||
395 !u->host && u->user ||
396 !u->user && u->pass ||
398 return URL_SYNTAX_ERROR;
402 /* Now we know it's a relative URL. Do we have any base? */
403 if (!b || !url_proto_path_flags[b->protoid])
404 return URL_ERR_REL_NOTHING;
405 u->protocol = b->protocol;
406 u->protoid = b->protoid;
408 /* Reference to the same host */
415 if (err = relpath_merge(u, b))
420 /* Change path "?" to "/?" because it's the true meaning */
421 if (u->rest[0] == '?')
423 int l = strlen(u->rest);
424 if (u->bufend - u->buf < l+1)
425 return URL_ERR_TOO_LONG;
427 memcpy(u->buf+1, u->rest, l+1);
432 /* Fill in missing info */
434 u->port = std_ports[u->protoid];
439 /* Name canonicalization */
447 if (*b >= 'A' && *b <= 'Z')
454 kill_end_dot(byte *b)
460 k = b + strlen(b) - 1;
461 while (k > b && *k == '.')
467 url_canonicalize(struct url *u)
471 lowercase(u->protocol);
473 kill_end_dot(u->host);
474 if ((!u->rest || !*u->rest) && url_proto_path_flags[u->protoid])
476 if (u->rest && (c = strchr(u->rest, '#'))) /* Kill fragment reference */
481 /* Pack a broken-down URL */
484 append(byte *d, byte *s, byte *e)
497 url_pack(struct url *u, byte *d)
499 byte *e = d + MAX_URL_SIZE - 10;
503 d = append(d, u->protocol, e);
504 d = append(d, ":", e);
505 u->protoid = identify_protocol(u->protocol);
509 d = append(d, "//", e);
512 d = append(d, u->user, e);
515 d = append(d, ":", e);
516 d = append(d, u->pass, e);
518 d = append(d, "@", e);
520 d = append(d, u->host, e);
521 if (u->port != std_ports[u->protoid] && u->port != ~0U)
524 sprintf(z, "%d", u->port);
525 d = append(d, ":", e);
530 d = append(d, u->rest, e);
532 return URL_ERR_TOO_LONG;
539 static char *errmsg[] = {
540 "Something is wrong",
544 "Invalid escaped character",
545 "Invalid port number",
546 "Relative URL not allowed",
555 if (err >= sizeof(errmsg) / sizeof(char *))
560 /* Standard cookbook recipes */
563 url_canon_split_rel(byte *u, byte *buf1, byte *buf2, struct url *url, struct url *base)
567 if (err = url_deescape(u, buf1))
569 if (err = url_split(buf1, url, buf2))
571 if (err = url_normalize(url, base))
573 return url_canonicalize(url);
577 url_auto_canonicalize_rel(byte *src, byte *dst, struct url *base)
579 byte buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE];
583 (void)((err = url_canon_split_rel(src, buf1, buf2, &ur, base)) ||
584 (err = url_pack(&ur, buf3)) ||
585 (err = url_enescape(buf3, dst)));
593 int main(int argc, char **argv)
595 char buf1[MAX_URL_SIZE], buf2[MAX_URL_SIZE], buf3[MAX_URL_SIZE], buf4[MAX_URL_SIZE];
597 struct url url, url0;
598 char *base = "http://mj@www.hell.org/123/sub_dir/index.html;param?query&zzz/subquery#fragment";
600 if (argc != 2 && argc != 3)
604 if (err = url_deescape(argv[1], buf1))
606 printf("deesc: error %d\n", err);
609 printf("deesc: %s\n", buf1);
610 if (err = url_split(buf1, &url, buf2))
612 printf("split: error %d\n", err);
615 printf("split: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
616 if (err = url_split(base, &url0, buf3))
618 printf("split base: error %d\n", err);
621 if (err = url_normalize(&url0, NULL))
623 printf("normalize base: error %d\n", err);
626 printf("base: @%s@%s@%s@%s@%d@%s\n", url0.protocol, url0.user, url0.pass, url0.host, url0.port, url0.rest);
627 if (err = url_normalize(&url, &url0))
629 printf("normalize: error %d\n", err);
632 printf("normalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
633 if (err = url_canonicalize(&url))
635 printf("canonicalize: error %d\n", err);
638 printf("canonicalize: @%s@%s@%s@%s@%d@%s\n", url.protocol, url.user, url.pass, url.host, url.port, url.rest);
639 if (err = url_pack(&url, buf4))
641 printf("pack: error %d\n", err);
644 printf("pack: %s\n", buf4);
645 if (err = url_enescape(buf4, buf2))
647 printf("enesc: error %d\n", err);
650 printf("enesc: %s\n", buf2);
663 hashf(byte *start, int length)
667 hf = (hf << 8 | hf >> 24) ^ *start++;
672 repeat_count(struct component *comp, uns count, uns len)
674 struct component *orig_comp = comp;
684 for (i=0; i<len; i++)
685 if (comp[i].hash != orig_comp[i].hash
686 || comp[i].length != orig_comp[i].length
687 || memcmp(comp[i].start, orig_comp[i].start, comp[i].length))
693 url_has_repeated_component(byte *url)
695 struct component *comp;
696 uns comps, comp_len, rep_prefix;
700 for (comps=0, c=url; c; comps++)
702 c = strpbrk(c, url_component_separators);
706 if (comps < url_min_repeat_count)
708 comp = alloca(comps * sizeof(struct component));
709 for (i=0, c=url; c; i++)
712 c = strpbrk(c, url_component_separators);
715 comp[i].length = c - comp[i].start;
719 comp[i].length = strlen(comp[i].start);
722 for (i=0; i<comps; i++)
723 comp[i].hash = hashf(comp[i].start, comp[i].length);
724 for (comp_len = 1; comp_len <= url_max_repeat_length && comp_len <= comps; comp_len++)
725 for (rep_prefix = 0; rep_prefix <= comps - comp_len; rep_prefix++)
726 if (repeat_count(comp + rep_prefix, comps - rep_prefix, comp_len) >= url_min_repeat_count)