2 * This is a URL parser, written to parse "Common Internet Scheme" URL
3 * syntax as described in RFC1738 and updated by RFC2396. Only absolute URLs
4 * are supported, using "server-based" naming authorities in the schemes.
5 * Support for literal IPv6 addresses is included, per RFC2732.
7 * Current "known" schemes: http, ftp, file.
9 * We can do all the parsing operations without Runes since URLs are
10 * defined to be composed of US-ASCII printable characters.
11 * See RFC1738, RFC2396.
27 /* If set, relative paths with leading ".." segments will have them trimmed */
28 #define RemoveExtraRelDotDots 0
29 #define ExpandCurrentDocUrls 1
46 for(i=0; i<nelem(schemestrtab); i++)
47 if(schemestrtab[i] && strcmp(s, schemestrtab[i])==0)
53 * URI splitting regexp is from RFC2396, Appendix B:
54 * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
57 * Example: "http://www.ics.uci.edu/pub/ietf/uri/#Related"
59 * $4 = authority "www.ics.uci.edu"
60 * $5 = path "/pub/ietf/uri/"
61 * $7 = query <undefined>
62 * $9 = fragment "Related"
66 * RFC2396, Sec 3.1, contains:
68 * Scheme names consist of a sequence of characters beginning with a
69 * lower case letter and followed by any combination of lower case
70 * letters, digits, plus ("+"), period ("."), or hyphen ("-"). For
71 * resiliency, programs interpreting URI should treat upper case letters
72 * as equivalent to lower case in scheme names (e.g., allow "HTTP" as
77 * For server-based naming authorities (RFC2396 Sec 3.2.2):
78 * server = [ [ userinfo "@" ] hostport ]
79 * userinfo = *( unreserved | escaped |
80 * ";" | ":" | "&" | "=" | "+" | "$" | "," )
81 * hostport = host [ ":" port ]
82 * host = hostname | IPv4address
83 * hostname = *( domainlabel "." ) toplabel [ "." ]
84 * domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
85 * toplabel = alpha | alpha *( alphanum | "-" ) alphanum
86 * IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit
89 * The host is a domain name of a network host, or its IPv4 address as a
90 * set of four decimal digit groups separated by ".". Literal IPv6
91 * addresses are not supported.
93 * Note that literal IPv6 address support is outlined in RFC2732:
94 * host = hostname | IPv4address | IPv6reference
95 * ipv6reference = "[" IPv6address "]" (RFC2373)
97 * Since hostnames and numbers will have to be resolved by the OS anyway,
98 * we don't have to parse them too pedantically (counting '.'s, checking
99 * for well-formed literal IP addresses, etc.).
101 * In FTP/file paths, we reject most ";param"s and querys. In HTTP paths,
102 * we just pass them through.
104 * Instead of letting a "path" be 0-or-more characters as RFC2396 suggests,
105 * we'll say it's 1-or-more characters, 0-or-1 times. This way, an absent
106 * path yields a nil substring match, instead of an empty one.
108 * We're more restrictive than RFC2396 indicates with "userinfo" strings,
109 * insisting they have the form "[user[:password]]". This may need to
110 * change at some point, however.
113 /* RE character-class components -- these go in brackets */
114 #define PUNCT "\\-_.!~*'()"
115 #define RES ";/?:@&=+$,"
116 #define ALNUM "a-zA-Z0-9"
117 #define HEX "0-9a-fA-F"
118 #define UNRES ALNUM PUNCT
120 /* RE components; _N => has N parenthesized subexpressions when expanded */
121 #define ESCAPED_1 "(%[" HEX "][" HEX "])"
122 #define URIC_2 "([" RES UNRES "]|" ESCAPED_1 ")"
123 #define URICNOSLASH_2 "([" UNRES ";?:@&=+$,]|" ESCAPED_1 ")"
124 #define USERINFO_2 "([" UNRES ";:&=+$,]|" ESCAPED_1 ")"
125 #define PCHAR_2 "([" UNRES ":@&=+$,]|" ESCAPED_1 ")"
126 #define PSEGCHAR_3 "([/;]|" PCHAR_2 ")"
128 typedef struct Retab Retab;
155 Retab retab[] = /* view in constant width Font */
158 "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]+)?(\\?([^#]*))?(#(.*))?$", nil, 0,
159 /* |-scheme-| |-auth.-| |path--| |query| |--|frag */
163 "^[a-z][a-z0-9+-.]*$", nil, 0,
167 "^" URICNOSLASH_2 URIC_2 "*$", nil, 0,
171 "^(((" USERINFO_2 "*)@)?(((\\[[^\\]@]+\\])|([^:\\[@]+))(:([0-9]*))?)?)?$", nil, 0,
172 /* |----user info-----| |--------host----------------| |-port-| */
176 "^(([a-zA-Z0-9\\-.]+)|(\\[([a-fA-F0-9.:]+)\\]))$", nil, 0,
177 /* |--regular host--| |-IPv6 literal-| */
181 "^(([^:]*)(:([^:]*))?)$", nil, 0,
182 /* |user-| |pass-| */
186 "^/" PSEGCHAR_3 "*$", nil, 0,
190 "^" URIC_2 "*$", nil, 0,
194 "^" URIC_2 "*$", nil, 0,
202 "^(.+)(;[tT][yY][pP][eE]=([aAiIdD]))?$", nil, 0,
203 /*|--|-path |ftptype-| */
212 countleftparen(char *s)
228 for(i=0; i<nelem(retab); i++){
229 retab[i].prog = regcomp(retab[i].str);
230 if(retab[i].prog == nil)
231 sysfatal("recomp(%s): %r", retab[i].str);
232 retab[i].size = countleftparen(retab[i].str)+1;
233 for(j=0; j<nelem(retab[i].ind); j++)
234 if(retab[i].ind[j] >= retab[i].size)
235 sysfatal("bad index in regexp table: retab[%d].ind[%d] = %d >= %d",
236 i, j, retab[i].ind[j], retab[i].size);
237 if(MaxResub < retab[i].size)
238 sysfatal("MaxResub too small: %d < %d", MaxResub, retab[i].size);
242 typedef struct SplitUrl SplitUrl;
248 } url, scheme, authority, path, query, fragment;
252 * Implements the algorithm in RFC2396 sec 5.2 step 6.
253 * Returns number of chars written, excluding NUL terminator.
254 * dest is known to be >= strlen(base)+rel_len.
257 merge_relative_path(char *base, char *rel_st, int rel_len, char *dest)
259 char *s, *p, *e, *pdest;
263 /* 6a: start with base, discard last segment */
265 /* Empty paths don't match in our scheme; 'base' should be nil */
266 assert(base[0] == '/');
267 e = strrchr(base, '/');
269 memmove(pdest, base, e-base);
272 /* Artistic license on my part */
276 /* 6b: append relative component */
278 memmove(pdest, rel_st, rel_len);
282 /* 6c: remove any occurrences of "./" as a complete segment */
285 while(e = strstr(s, "./")){
286 if((e == dest) || (*(e-1) == '/')){
287 memmove(e, e+2, pdest+1-(e+2)); /* +1 for NUL */
293 /* 6d: remove a trailing "." as a complete segment */
294 if(pdest>dest && *(pdest-1)=='.' &&
295 (pdest==dest+1 || *(pdest-2)=='/'))
298 /* 6e: remove occurences of "seg/../", where seg != "..", left->right */
300 while(e = strstr(s, "/../")){
302 while(p >= dest && *p != '/')
304 if(memcmp(p, "/../", 4) != 0){
305 memmove(p+1, e+4, pdest+1-(e+4));
306 pdest -= (e+4) - (p+1);
311 /* 6f: remove a trailing "seg/..", where seg isn't ".." */
312 if(pdest-3 > dest && memcmp(pdest-3, "/..", 3)==0){
314 while(p >= dest && *p != '/')
316 if(memcmp(p, "/../", 4) != 0){
322 /* 6g: leading ".." segments are errors -- we'll just blat them out. */
323 if(RemoveExtraRelDotDots){
328 while(s[0]=='.' && s[1]=='.' && (s[2]==0 || s[2]=='/'))
331 memmove(p, s, pdest+1-s);
338 fprint(2, "merge_relative_path: '%s' + '%.*s' -> '%s'\n", base, rel_len,
343 * See RFC2396 sec 5.2 for info on resolving relative URIs to absolute form.
345 * If successful, this just ends up freeing and replacing "u->url".
348 resolve_relative(SplitUrl *su, Url *base, Url *u)
352 int currentdoc, ulen, plen;
355 werrstr("relative URI given without base");
358 if(base->scheme == nil){
359 werrstr("relative URI given with no scheme");
362 if(base->ischeme == USunknown){
363 werrstr("relative URI given with unknown scheme");
366 if(base->ischeme == UScurrent){
367 werrstr("relative URI given with incomplete base");
370 assert(su->scheme.s == nil);
374 if(su->path.s==nil && su->scheme.s==nil && su->authority.s==nil && su->query.s==nil){
375 /* Reference is to current document */
377 fprint(2, "url %s is relative to current document\n", u->url);
378 u->ischeme = UScurrent;
379 if(!ExpandCurrentDocUrls)
384 /* Over-estimate the maximum lengths, for allocation purposes */
385 /* (constants are for separators) */
388 plen += strlen(base->path);
390 plen += 1 + (su->path.e - su->path.s);
393 ulen += strlen(base->scheme) + 1;
395 ulen += 2 + (su->authority.e - su->authority.s);
397 ulen += 2 + ((base->authority) ? strlen(base->authority) : 0);
400 ulen += 1 + (su->query.e - su->query.s);
401 else if(currentdoc && base->query)
402 ulen += 1 + strlen(base->query);
404 ulen += 1 + (su->fragment.e - su->fragment.s);
405 else if(currentdoc && base->fragment)
406 ulen += 1 + strlen(base->fragment);
407 url = emalloc(ulen+1);
408 path = emalloc(plen+1);
415 if(su->authority.s || (su->path.s && (su->path.s[0] == '/'))){
416 /* Is a "network-path" or "absolute-path"; don't merge with base path */
417 /* Sec 5.2 steps 4,5 */
419 memmove(ppath, su->path.s, su->path.e - su->path.s);
420 ppath += su->path.e - su->path.s;
423 }else if(currentdoc){
424 /* Is a current-doc reference; just copy the path from the base URL */
426 strcpy(ppath, base->path);
427 ppath += strlen(ppath);
431 /* Is a relative-path reference; we have to merge it */
433 merge_relative_path(base->path,
434 su->path.s, su->path.e - su->path.s, ppath);
437 /* Build new URL from pieces, inheriting from base where needed */
438 strcpy(purl, base->scheme);
439 purl += strlen(purl);
443 purl += strlen(purl);
444 memmove(purl, su->authority.s, su->authority.e - su->authority.s);
445 purl += su->authority.e - su->authority.s;
446 }else if(base->authority){
448 purl += strlen(purl);
449 strcpy(purl, base->authority);
450 purl += strlen(purl);
452 assert((path[0] == '\0') || (path[0] == '/'));
454 purl += strlen(purl);
457 * The query and fragment are not inherited from the base,
458 * except in case of "current document" URLs, which inherit any query
459 * and may inherit the fragment.
463 memmove(purl, su->query.s, su->query.e - su->query.s);
464 purl += su->query.e - su->query.s;
465 }else if(currentdoc && base->query){
467 strcpy(purl, base->query);
468 purl += strlen(purl);
473 memmove(purl, su->query.s, su->query.e - su->query.s);
474 purl += su->fragment.e - su->fragment.s;
475 }else if(currentdoc && base->fragment){
477 strcpy(purl, base->fragment);
478 purl += strlen(purl);
483 fprint(2, "resolve_relative: '%s' + '%s' -> '%s'\n", base->url, u->url, url);
491 regx(Reprog *prog, char *s, Resub *m, int nm)
496 s = m[0].sp; /* why is this necessary? */
498 i = regexec(prog, s, m, nm);
502 fprint(2, "match%d: %.*s\n", j, utfnlen(m[j].sp, m[j].ep-m[j].sp), m[j].sp);
508 ismatch(int i, char *s, char *desc)
512 m[0].sp = m[0].ep = nil;
513 if(!regx(retab[i].prog, s, m, 1)){
514 werrstr("malformed %s: %q", desc, s);
521 spliturl(char *url, SplitUrl *su)
527 * Newlines are not valid in a URI, but regexp(2) treats them specially
528 * so it's best to make sure there are none before proceeding.
530 if(strchr(url, '\n')){
531 werrstr("newline in URI");
536 * Because we use NUL-terminated strings, as do many client and server
537 * implementations, an escaped NUL ("%00") will quite likely cause problems
538 * when unescaped. We can check for such a sequence once before examining
539 * the components because, per RFC2396 sec. 2.4.1 - 2.4.2, '%' is reserved
540 * in URIs to _always_ indicate escape sequences. Something like "%2500"
541 * will still get by, but that's legitimate, and if it ends up causing
542 * a NUL then someone is unescaping too many times.
544 if(strstr(url, "%00")){
545 werrstr("escaped NUL in URI");
549 m[0].sp = m[0].ep = nil;
551 if(!regx(t->prog, url, m, t->size)){
552 werrstr("malformed URI: %q", url);
558 su->scheme.s = m[t->ind[0]].sp;
559 su->scheme.e = m[t->ind[0]].ep;
560 su->authority.s = m[t->ind[1]].sp;
561 su->authority.e = m[t->ind[1]].ep;
562 su->path.s = m[t->ind[2]].sp;
563 su->path.e = m[t->ind[2]].ep;
564 su->query.s = m[t->ind[3]].sp;
565 su->query.e = m[t->ind[3]].ep;
566 su->fragment.s = m[t->ind[4]].sp;
567 su->fragment.e = m[t->ind[4]].ep;
570 fprint(2, "split url %s into %.*q %.*q %.*q %.*q %.*q %.*q\n",
572 su->url.s ? utfnlen(su->url.s, su->url.e-su->url.s) : 10, su->url.s ? su->url.s : "",
573 su->scheme.s ? utfnlen(su->scheme.s, su->scheme.e-su->scheme.s) : 10, su->scheme.s ? su->scheme.s : "",
574 su->authority.s ? utfnlen(su->authority.s, su->authority.e-su->authority.s) : 10, su->authority.s ? su->authority.s : "",
575 su->path.s ? utfnlen(su->path.s, su->path.e-su->path.s) : 10, su->path.s ? su->path.s : "",
576 su->query.s ? utfnlen(su->query.s, su->query.e-su->query.s) : 10, su->query.s ? su->query.s : "",
577 su->fragment.s ? utfnlen(su->fragment.s, su->fragment.e-su->fragment.s) : 10, su->fragment.s ? su->fragment.s : "");
583 parse_scheme(SplitUrl *su, Url *u)
585 if(su->scheme.s == nil){
586 werrstr("missing scheme");
589 u->scheme = estredup(su->scheme.s, su->scheme.e);
592 if(!ismatch(REscheme, u->scheme, "scheme"))
595 u->ischeme = ischeme(u->scheme);
597 fprint(2, "parse_scheme %s => %d\n", u->scheme, u->ischeme);
602 parse_unknown_part(SplitUrl *su, Url *u)
606 assert(u->ischeme == USunknown);
607 assert(su->scheme.e[0] == ':');
611 e = su->fragment.s-1;
616 u->schemedata = estredup(s, e);
617 if(!ismatch(REunknowndata, u->schemedata, "unknown scheme data"))
623 parse_userinfo(char *s, char *e, Url *u)
630 t = &retab[REuserinfo];
631 if(!regx(t->prog, nil, m, t->size)){
632 werrstr("malformed userinfo: %.*q", utfnlen(s, e-s), s);
636 u->user = estredup(m[t->ind[0]].sp, m[t->ind[0]].ep);
638 u->user = estredup(m[t->ind[1]].sp, m[t->ind[1]].ep);
643 parse_host(char *s, char *e, Url *u)
651 if(!regx(t->prog, nil, m, t->size)){
652 werrstr("malformed host: %.*q", utfnlen(s, e-s), s);
656 assert(m[t->ind[0]].sp || m[t->ind[1]].sp);
658 if(m[t->ind[0]].sp) /* regular */
659 u->host = estredup(m[t->ind[0]].sp, m[t->ind[0]].ep);
661 u->host = estredup(m[t->ind[1]].sp, m[t->ind[1]].ep);
666 parse_authority(SplitUrl *su, Url *u)
673 if(su->authority.s == nil)
676 u->authority = estredup(su->authority.s, su->authority.e);
677 m[0].sp = m[0].ep = nil;
678 t = &retab[REauthority];
679 if(!regx(t->prog, u->authority, m, t->size)){
680 werrstr("malformed authority: %q", u->authority);
685 if(parse_userinfo(m[t->ind[0]].sp, m[t->ind[0]].ep, u) < 0)
688 if(parse_host(m[t->ind[1]].sp, m[t->ind[1]].ep, u) < 0)
691 u->port = estredup(m[t->ind[2]].sp, m[t->ind[2]].ep);
695 userinfo = estredup(m[t->ind[0]].sp, m[t->ind[0]].ep);
696 host = estredup(m[t->ind[1]].sp, m[t->ind[1]].ep);
697 fprint(2, "port: %q, authority %q\n", u->port, u->authority);
698 fprint(2, "host %q, userinfo %q\n", host, userinfo);
706 parse_abspath(SplitUrl *su, Url *u)
708 if(su->path.s == nil)
710 u->path = estredup(su->path.s, su->path.e);
711 if(!ismatch(REabspath, u->path, "absolute path"))
717 parse_query(SplitUrl *su, Url *u)
719 if(su->query.s == nil)
721 u->query = estredup(su->query.s, su->query.e);
722 if(!ismatch(REquery, u->query, "query"))
728 parse_fragment(SplitUrl *su, Url *u)
730 if(su->fragment.s == nil)
732 u->fragment = estredup(su->fragment.s, su->fragment.e);
733 if(!ismatch(REfragment, u->fragment, "fragment"))
739 postparse_http(Url *u)
743 u->close = httpclose;
745 if(u->authority==nil){
746 werrstr("missing authority (hostname, port, etc.)");
750 werrstr("missing host specification");
755 u->http.page_spec = estrdup("/");
759 if(!ismatch(REhttppath, u->path, "http path"))
762 u->http.page_spec = emalloc(strlen(u->path)+1+strlen(u->query)+1);
763 strcpy(u->http.page_spec, u->path);
764 strcat(u->http.page_spec, "?");
765 strcat(u->http.page_spec, u->query);
767 u->http.page_spec = estrdup(u->path);
773 postparse_ftp(Url *u)
778 if(u->authority==nil){
779 werrstr("missing authority (hostname, port, etc.)");
783 werrstr("unexpected \"?query\" in ftp path");
787 werrstr("missing host specification");
792 u->ftp.path_spec = estrdup("/");
796 m[0].sp = m[0].ep = nil;
797 t = &retab[REftppath];
798 if(!regx(t->prog, u->path, m, t->size)){
799 werrstr("malformed ftp path: %q", u->path);
804 u->ftp.path_spec = estredup(m[t->ind[0]].sp, m[t->ind[0]].ep);
805 if(strchr(u->ftp.path_spec, ';')){
806 werrstr("unexpected \";param\" in ftp path");
810 u->ftp.path_spec = estrdup("/");
813 u->ftp.type = estredup(m[t->ind[1]].sp, m[t->ind[1]].ep);
814 strlower(u->ftp.type);
820 postparse_file(Url *u)
822 if(u->user || u->passwd){
823 werrstr("user information not valid with file scheme");
827 werrstr("unexpected \"?query\" in file path");
831 werrstr("port not valid with file scheme");
835 werrstr("missing path in file scheme");
838 if(strchr(u->path, ';')){
839 werrstr("unexpected \";param\" in file path");
843 if(!ismatch(REfilepath, u->path, "file path"))
846 /* "localhost" is equivalent to no host spec, we'll chose the latter */
847 if(u->host && cistrcmp(u->host, "localhost") == 0){
854 static int (*postparse[])(Url*) = {
863 parseurl(char *url, Url *base)
869 fprint(2, "parseurl %s with base %s\n", url, base ? base->url : "<none>");
871 u = emalloc(sizeof(Url));
872 u->url = estrdup(url);
873 if(spliturl(u->url, &su) < 0){
879 /* RFC2396 sec 3.1 says relative URIs are distinguished by absent scheme */
880 if(su.scheme.s==nil){
882 fprint(2, "parseurl has nil scheme\n");
883 if(resolve_relative(&su, base, u) < 0 || spliturl(u->url, &su) < 0)
885 if(u->ischeme == UScurrent){
886 /* 'u.url' refers to current document; set fragment and return */
887 if(parse_fragment(&su, u) < 0)
893 if(parse_scheme(&su, u) < 0
894 || parse_fragment(&su, u) < 0)
897 if(u->ischeme == USunknown){
898 if(parse_unknown_part(&su, u) < 0)
903 if(parse_query(&su, u) < 0
904 || parse_authority(&su, u) < 0
905 || parse_abspath(&su, u) < 0)
908 if(u->ischeme < nelem(postparse) && postparse[u->ischeme])
909 if((*postparse[u->ischeme])(u) < 0)
912 setmalloctag(u, getcallerpc(&url));
934 free(u->http.page_spec);
937 free(u->ftp.path_spec);
950 s = estrmanydup(u->scheme, ":", u->schemedata, nil);
952 s = estrmanydup(u->scheme, "://",
953 u->user ? u->user : "",
954 u->passwd ? ":" : "", u->passwd ? u->passwd : "",
955 u->user ? "@" : "", u->host ? u->host : "",
956 u->port ? ":" : "", u->port ? u->port : "",
958 u->query ? "?" : "", u->query ? u->query : "",
959 u->fragment ? "#" : "", u->fragment ? u->fragment : "",
966 seturlquery(Url *u, char *query)
974 if(!ismatch(REquery, query, "query"))
978 u->query = estrdup(query);
994 v = emalloc(sizeof(Url));
998 dupp(&v->schemedata);
1010 dupp(&v->http.page_spec);
1013 dupp(&v->ftp.path_spec);
1023 if('0' <= c && c <= '9')
1025 if('a' <= c && c <= 'f')
1027 if('A' <= c && c <= 'F')
1033 escapeurl(char *s, int (*needesc)(int))
1038 static char *hex = "0123456789abcdef";
1045 u = emalloc(strlen(s)+2*n+1);
1048 s += chartorune(&r, s);
1050 werrstr("URLs cannot contain Runes > 0xFF");
1056 *u++ = hex[(r>>4)&0xF];
1066 unescapeurl(char *s)
1072 for(r=w=s; *r; r++){
1075 if(!isxdigit(r[0]) || !isxdigit(r[1])){
1076 werrstr("bad escape sequence '%.3s' in URL", r);
1079 if(r[0]=='0' && r[2]=='0'){
1080 werrstr("escaped NUL in URL");
1083 rune = (dhex(r[0])<<4)|dhex(r[1]); /* latin1 */
1084 w += runetochar(w, &rune);