2 * uri.c: set of generic URI related routines
4 * Reference: RFCs 3986, 2732 and 2373
6 * Copyright (C) 1998-2003 Daniel Veillard. All Rights Reserved.
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * DANIEL VEILLARD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
22 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 * Except as contained in this notice, the name of Daniel Veillard shall not
26 * be used in advertising or otherwise to promote the sale, use or other
27 * dealings in this Software without prior written authorization from him.
33 * Copyright (C) 2007, 2009-2010 Red Hat, Inc.
35 * This library is free software; you can redistribute it and/or
36 * modify it under the terms of the GNU Lesser General Public
37 * License as published by the Free Software Foundation; either
38 * version 2.1 of the License, or (at your option) any later version.
40 * This library is distributed in the hope that it will be useful,
41 * but WITHOUT ANY WARRANTY; without even the implied warranty of
42 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
43 * Lesser General Public License for more details.
45 * You should have received a copy of the GNU Lesser General Public
46 * License along with this library; if not, write to the Free Software
47 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
54 #include "qemu/osdep.h"
58 static void uri_clean(URI *uri);
61 * Old rule from 2396 used in legacy handling code
62 * alpha = lowalpha | upalpha
64 #define IS_ALPHA(x) (IS_LOWALPHA(x) || IS_UPALPHA(x))
67 * lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" |
68 * "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" |
69 * "u" | "v" | "w" | "x" | "y" | "z"
72 #define IS_LOWALPHA(x) (((x) >= 'a') && ((x) <= 'z'))
75 * upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" |
76 * "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" |
77 * "U" | "V" | "W" | "X" | "Y" | "Z"
79 #define IS_UPALPHA(x) (((x) >= 'A') && ((x) <= 'Z'))
85 * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
87 #define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9'))
90 * alphanum = alpha | digit
93 #define IS_ALPHANUM(x) (IS_ALPHA(x) || IS_DIGIT(x))
96 * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
99 #define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') || \
100 ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') || \
101 ((x) == '(') || ((x) == ')'))
104 * unwise = "{" | "}" | "|" | "\" | "^" | "`"
107 #define IS_UNWISE(p) \
108 (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) || \
109 ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) || \
110 ((*(p) == ']')) || ((*(p) == '`')))
112 * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
116 #define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') || \
117 ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') || \
118 ((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \
122 * unreserved = alphanum | mark
125 #define IS_UNRESERVED(x) (IS_ALPHANUM(x) || IS_MARK(x))
128 * Skip to next pointer char, handle escaped sequences
131 #define NEXT(p) ((*p == '%') ? p += 3 : p++)
134 * Productions from the spec.
136 * authority = server | reg_name
137 * reg_name = 1*( unreserved | escaped | "$" | "," |
138 * ";" | ":" | "@" | "&" | "=" | "+" )
140 * path = [ abs_path | opaque_part ]
143 /************************************************************************
147 ************************************************************************/
149 #define ISA_DIGIT(p) ((*(p) >= '0') && (*(p) <= '9'))
150 #define ISA_ALPHA(p) (((*(p) >= 'a') && (*(p) <= 'z')) || \
151 ((*(p) >= 'A') && (*(p) <= 'Z')))
152 #define ISA_HEXDIG(p) \
153 (ISA_DIGIT(p) || ((*(p) >= 'a') && (*(p) <= 'f')) || \
154 ((*(p) >= 'A') && (*(p) <= 'F')))
157 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
158 * / "*" / "+" / "," / ";" / "="
160 #define ISA_SUB_DELIM(p) \
161 (((*(p) == '!')) || ((*(p) == '$')) || ((*(p) == '&')) || \
162 ((*(p) == '(')) || ((*(p) == ')')) || ((*(p) == '*')) || \
163 ((*(p) == '+')) || ((*(p) == ',')) || ((*(p) == ';')) || \
164 ((*(p) == '=')) || ((*(p) == '\'')))
167 * gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
169 #define ISA_GEN_DELIM(p) \
170 (((*(p) == ':')) || ((*(p) == '/')) || ((*(p) == '?')) || \
171 ((*(p) == '#')) || ((*(p) == '[')) || ((*(p) == ']')) || \
175 * reserved = gen-delims / sub-delims
177 #define ISA_RESERVED(p) (ISA_GEN_DELIM(p) || (ISA_SUB_DELIM(p)))
180 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
182 #define ISA_UNRESERVED(p) \
183 ((ISA_ALPHA(p)) || (ISA_DIGIT(p)) || ((*(p) == '-')) || \
184 ((*(p) == '.')) || ((*(p) == '_')) || ((*(p) == '~')))
187 * pct-encoded = "%" HEXDIG HEXDIG
189 #define ISA_PCT_ENCODED(p) \
190 ((*(p) == '%') && (ISA_HEXDIG(p + 1)) && (ISA_HEXDIG(p + 2)))
193 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
195 #define ISA_PCHAR(p) \
196 (ISA_UNRESERVED(p) || ISA_PCT_ENCODED(p) || ISA_SUB_DELIM(p) || \
197 ((*(p) == ':')) || ((*(p) == '@')))
200 * rfc3986_parse_scheme:
201 * @uri: pointer to an URI structure
202 * @str: pointer to the string to analyze
204 * Parse an URI scheme
206 * ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
208 * Returns 0 or the error code
210 static int rfc3986_parse_scheme(URI *uri, const char **str)
219 if (!ISA_ALPHA(cur)) {
223 while (ISA_ALPHA(cur) || ISA_DIGIT(cur) || (*cur == '+') || (*cur == '-') ||
229 uri->scheme = g_strndup(*str, cur - *str);
236 * rfc3986_parse_fragment:
237 * @uri: pointer to an URI structure
238 * @str: pointer to the string to analyze
240 * Parse the query part of an URI
242 * fragment = *( pchar / "/" / "?" )
243 * NOTE: the strict syntax as defined by 3986 does not allow '[' and ']'
244 * in the fragment identifier but this is used very broadly for
245 * xpointer scheme selection, so we are allowing it here to not break
246 * for example all the DocBook processing chains.
248 * Returns 0 or the error code
250 static int rfc3986_parse_fragment(URI *uri, const char **str)
260 while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
261 (*cur == '[') || (*cur == ']') ||
262 ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) {
266 g_free(uri->fragment);
267 if (uri->cleanup & 2) {
268 uri->fragment = g_strndup(*str, cur - *str);
270 uri->fragment = uri_string_unescape(*str, cur - *str, NULL);
278 * rfc3986_parse_query:
279 * @uri: pointer to an URI structure
280 * @str: pointer to the string to analyze
282 * Parse the query part of an URI
286 * Returns 0 or the error code
288 static int rfc3986_parse_query(URI *uri, const char **str)
298 while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
299 ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur)))) {
304 uri->query = g_strndup(*str, cur - *str);
311 * rfc3986_parse_port:
312 * @uri: pointer to an URI structure
313 * @str: the string to analyze
315 * Parse a port part and fills in the appropriate fields
316 * of the @uri structure
320 * Returns 0 or the error code
322 static int rfc3986_parse_port(URI *uri, const char **str)
324 const char *cur = *str;
327 if (ISA_DIGIT(cur)) {
328 while (ISA_DIGIT(cur)) {
329 port = port * 10 + (*cur - '0');
345 * rfc3986_parse_user_info:
346 * @uri: pointer to an URI structure
347 * @str: the string to analyze
349 * Parse a user information part and fill in the appropriate fields
350 * of the @uri structure
352 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
354 * Returns 0 or the error code
356 static int rfc3986_parse_user_info(URI *uri, const char **str)
361 while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) || ISA_SUB_DELIM(cur) ||
368 if (uri->cleanup & 2) {
369 uri->user = g_strndup(*str, cur - *str);
371 uri->user = uri_string_unescape(*str, cur - *str, NULL);
381 * rfc3986_parse_dec_octet:
382 * @str: the string to analyze
384 * dec-octet = DIGIT ; 0-9
385 * / %x31-39 DIGIT ; 10-99
386 * / "1" 2DIGIT ; 100-199
387 * / "2" %x30-34 DIGIT ; 200-249
388 * / "25" %x30-35 ; 250-255
392 * Returns 0 if found and skipped, 1 otherwise
394 static int rfc3986_parse_dec_octet(const char **str)
396 const char *cur = *str;
398 if (!(ISA_DIGIT(cur))) {
401 if (!ISA_DIGIT(cur + 1)) {
403 } else if ((*cur != '0') && (ISA_DIGIT(cur + 1)) && (!ISA_DIGIT(cur + 2))) {
405 } else if ((*cur == '1') && (ISA_DIGIT(cur + 1)) && (ISA_DIGIT(cur + 2))) {
407 } else if ((*cur == '2') && (*(cur + 1) >= '0') && (*(cur + 1) <= '4') &&
408 (ISA_DIGIT(cur + 2))) {
410 } else if ((*cur == '2') && (*(cur + 1) == '5') && (*(cur + 2) >= '0') &&
411 (*(cur + 1) <= '5')) {
420 * rfc3986_parse_host:
421 * @uri: pointer to an URI structure
422 * @str: the string to analyze
424 * Parse an host part and fills in the appropriate fields
425 * of the @uri structure
427 * host = IP-literal / IPv4address / reg-name
428 * IP-literal = "[" ( IPv6address / IPvFuture ) "]"
429 * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
430 * reg-name = *( unreserved / pct-encoded / sub-delims )
432 * Returns 0 or the error code
434 static int rfc3986_parse_host(URI *uri, const char **str)
436 const char *cur = *str;
441 * IPv6 and future addressing scheme are enclosed between brackets
445 while ((*cur != ']') && (*cur != 0)) {
455 * try to parse an IPv4
457 if (ISA_DIGIT(cur)) {
458 if (rfc3986_parse_dec_octet(&cur) != 0) {
465 if (rfc3986_parse_dec_octet(&cur) != 0) {
471 if (rfc3986_parse_dec_octet(&cur) != 0) {
477 if (rfc3986_parse_dec_octet(&cur) != 0) {
485 * then this should be a hostname which can be empty
487 while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) || ISA_SUB_DELIM(cur)) {
492 g_free(uri->authority);
493 uri->authority = NULL;
496 if (uri->cleanup & 2) {
497 uri->server = g_strndup(host, cur - host);
499 uri->server = uri_string_unescape(host, cur - host, NULL);
510 * rfc3986_parse_authority:
511 * @uri: pointer to an URI structure
512 * @str: the string to analyze
514 * Parse an authority part and fills in the appropriate fields
515 * of the @uri structure
517 * authority = [ userinfo "@" ] host [ ":" port ]
519 * Returns 0 or the error code
521 static int rfc3986_parse_authority(URI *uri, const char **str)
528 * try to parse a userinfo and check for the trailing @
530 ret = rfc3986_parse_user_info(uri, &cur);
531 if ((ret != 0) || (*cur != '@')) {
536 ret = rfc3986_parse_host(uri, &cur);
542 ret = rfc3986_parse_port(uri, &cur);
552 * rfc3986_parse_segment:
553 * @str: the string to analyze
554 * @forbid: an optional forbidden character
555 * @empty: allow an empty segment
557 * Parse a segment and fills in the appropriate fields
558 * of the @uri structure
561 * segment-nz = 1*pchar
562 * segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
563 * ; non-zero-length segment without any colon ":"
565 * Returns 0 or the error code
567 static int rfc3986_parse_segment(const char **str, char forbid, int empty)
572 if (!ISA_PCHAR(cur)) {
578 while (ISA_PCHAR(cur) && (*cur != forbid)) {
586 * rfc3986_parse_path_ab_empty:
587 * @uri: pointer to an URI structure
588 * @str: the string to analyze
590 * Parse an path absolute or empty and fills in the appropriate fields
591 * of the @uri structure
593 * path-abempty = *( "/" segment )
595 * Returns 0 or the error code
597 static int rfc3986_parse_path_ab_empty(URI *uri, const char **str)
604 while (*cur == '/') {
606 ret = rfc3986_parse_segment(&cur, 0, 1);
614 if (uri->cleanup & 2) {
615 uri->path = g_strndup(*str, cur - *str);
617 uri->path = uri_string_unescape(*str, cur - *str, NULL);
628 * rfc3986_parse_path_absolute:
629 * @uri: pointer to an URI structure
630 * @str: the string to analyze
632 * Parse an path absolute and fills in the appropriate fields
633 * of the @uri structure
635 * path-absolute = "/" [ segment-nz *( "/" segment ) ]
637 * Returns 0 or the error code
639 static int rfc3986_parse_path_absolute(URI *uri, const char **str)
650 ret = rfc3986_parse_segment(&cur, 0, 0);
652 while (*cur == '/') {
654 ret = rfc3986_parse_segment(&cur, 0, 1);
663 if (uri->cleanup & 2) {
664 uri->path = g_strndup(*str, cur - *str);
666 uri->path = uri_string_unescape(*str, cur - *str, NULL);
677 * rfc3986_parse_path_rootless:
678 * @uri: pointer to an URI structure
679 * @str: the string to analyze
681 * Parse an path without root and fills in the appropriate fields
682 * of the @uri structure
684 * path-rootless = segment-nz *( "/" segment )
686 * Returns 0 or the error code
688 static int rfc3986_parse_path_rootless(URI *uri, const char **str)
695 ret = rfc3986_parse_segment(&cur, 0, 0);
699 while (*cur == '/') {
701 ret = rfc3986_parse_segment(&cur, 0, 1);
709 if (uri->cleanup & 2) {
710 uri->path = g_strndup(*str, cur - *str);
712 uri->path = uri_string_unescape(*str, cur - *str, NULL);
723 * rfc3986_parse_path_no_scheme:
724 * @uri: pointer to an URI structure
725 * @str: the string to analyze
727 * Parse an path which is not a scheme and fills in the appropriate fields
728 * of the @uri structure
730 * path-noscheme = segment-nz-nc *( "/" segment )
732 * Returns 0 or the error code
734 static int rfc3986_parse_path_no_scheme(URI *uri, const char **str)
741 ret = rfc3986_parse_segment(&cur, ':', 0);
745 while (*cur == '/') {
747 ret = rfc3986_parse_segment(&cur, 0, 1);
755 if (uri->cleanup & 2) {
756 uri->path = g_strndup(*str, cur - *str);
758 uri->path = uri_string_unescape(*str, cur - *str, NULL);
769 * rfc3986_parse_hier_part:
770 * @uri: pointer to an URI structure
771 * @str: the string to analyze
773 * Parse an hierarchical part and fills in the appropriate fields
774 * of the @uri structure
776 * hier-part = "//" authority path-abempty
781 * Returns 0 or the error code
783 static int rfc3986_parse_hier_part(URI *uri, const char **str)
790 if ((*cur == '/') && (*(cur + 1) == '/')) {
792 ret = rfc3986_parse_authority(uri, &cur);
796 ret = rfc3986_parse_path_ab_empty(uri, &cur);
802 } else if (*cur == '/') {
803 ret = rfc3986_parse_path_absolute(uri, &cur);
807 } else if (ISA_PCHAR(cur)) {
808 ret = rfc3986_parse_path_rootless(uri, &cur);
813 /* path-empty is effectively empty */
824 * rfc3986_parse_relative_ref:
825 * @uri: pointer to an URI structure
826 * @str: the string to analyze
828 * Parse an URI string and fills in the appropriate fields
829 * of the @uri structure
831 * relative-ref = relative-part [ "?" query ] [ "#" fragment ]
832 * relative-part = "//" authority path-abempty
837 * Returns 0 or the error code
839 static int rfc3986_parse_relative_ref(URI *uri, const char *str)
843 if ((*str == '/') && (*(str + 1) == '/')) {
845 ret = rfc3986_parse_authority(uri, &str);
849 ret = rfc3986_parse_path_ab_empty(uri, &str);
853 } else if (*str == '/') {
854 ret = rfc3986_parse_path_absolute(uri, &str);
858 } else if (ISA_PCHAR(str)) {
859 ret = rfc3986_parse_path_no_scheme(uri, &str);
864 /* path-empty is effectively empty */
873 ret = rfc3986_parse_query(uri, &str);
880 ret = rfc3986_parse_fragment(uri, &str);
894 * @uri: pointer to an URI structure
895 * @str: the string to analyze
897 * Parse an URI string and fills in the appropriate fields
898 * of the @uri structure
900 * scheme ":" hier-part [ "?" query ] [ "#" fragment ]
902 * Returns 0 or the error code
904 static int rfc3986_parse(URI *uri, const char *str)
908 ret = rfc3986_parse_scheme(uri, &str);
916 ret = rfc3986_parse_hier_part(uri, &str);
922 ret = rfc3986_parse_query(uri, &str);
929 ret = rfc3986_parse_fragment(uri, &str);
942 * rfc3986_parse_uri_reference:
943 * @uri: pointer to an URI structure
944 * @str: the string to analyze
946 * Parse an URI reference string and fills in the appropriate fields
947 * of the @uri structure
949 * URI-reference = URI / relative-ref
951 * Returns 0 or the error code
953 static int rfc3986_parse_uri_reference(URI *uri, const char *str)
963 * Try first to parse absolute refs, then fallback to relative if
966 ret = rfc3986_parse(uri, str);
969 ret = rfc3986_parse_relative_ref(uri, str);
980 * @str: the URI string to analyze
982 * Parse an URI based on RFC 3986
984 * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
986 * Returns a newly built URI or NULL in case of error
988 URI *uri_parse(const char *str)
997 ret = rfc3986_parse_uri_reference(uri, str);
1007 * @uri: pointer to an URI structure
1008 * @str: the string to analyze
1010 * Parse an URI reference string based on RFC 3986 and fills in the
1011 * appropriate fields of the @uri structure
1013 * URI-reference = URI / relative-ref
1015 * Returns 0 or the error code
1017 int uri_parse_into(URI *uri, const char *str)
1019 return rfc3986_parse_uri_reference(uri, str);
1024 * @str: the URI string to analyze
1025 * @raw: if 1 unescaping of URI pieces are disabled
1027 * Parse an URI but allows to keep intact the original fragments.
1029 * URI-reference = URI / relative-ref
1031 * Returns a newly built URI or NULL in case of error
1033 URI *uri_parse_raw(const char *str, int raw)
1045 ret = uri_parse_into(uri, str);
1053 /************************************************************************
1055 * Generic URI structure functions *
1057 ************************************************************************/
1062 * Simply creates an empty URI
1064 * Returns the new structure or NULL in case of error
1070 ret = g_new0(URI, 1);
1077 * Function to handle properly a reallocation when saving an URI
1078 * Also imposes some limit on the length of an URI string output
1080 static char *realloc2n(char *ret, int *max)
1086 temp = g_realloc(ret, (tmp + 1));
1093 * @uri: pointer to an URI
1095 * Save the URI as an escaped string
1097 * Returns a new string (to be deallocated by caller)
1099 char *uri_to_string(URI *uri)
1112 ret = g_malloc(max + 1);
1115 if (uri->scheme != NULL) {
1119 temp = realloc2n(ret, &max);
1125 temp = realloc2n(ret, &max);
1130 if (uri->opaque != NULL) {
1133 if (len + 3 >= max) {
1134 temp = realloc2n(ret, &max);
1137 if (IS_RESERVED(*(p)) || IS_UNRESERVED(*(p))) {
1140 int val = *(unsigned char *)p++;
1141 int hi = val / 0x10, lo = val % 0x10;
1143 ret[len++] = hi + (hi > 9 ? 'A' - 10 : '0');
1144 ret[len++] = lo + (lo > 9 ? 'A' - 10 : '0');
1148 if (uri->server != NULL) {
1149 if (len + 3 >= max) {
1150 temp = realloc2n(ret, &max);
1155 if (uri->user != NULL) {
1158 if (len + 3 >= max) {
1159 temp = realloc2n(ret, &max);
1162 if ((IS_UNRESERVED(*(p))) || ((*(p) == ';')) ||
1163 ((*(p) == ':')) || ((*(p) == '&')) || ((*(p) == '=')) ||
1164 ((*(p) == '+')) || ((*(p) == '$')) || ((*(p) == ','))) {
1167 int val = *(unsigned char *)p++;
1168 int hi = val / 0x10, lo = val % 0x10;
1170 ret[len++] = hi + (hi > 9 ? 'A' - 10 : '0');
1171 ret[len++] = lo + (lo > 9 ? 'A' - 10 : '0');
1174 if (len + 3 >= max) {
1175 temp = realloc2n(ret, &max);
1183 temp = realloc2n(ret, &max);
1188 if (uri->port > 0) {
1189 if (len + 10 >= max) {
1190 temp = realloc2n(ret, &max);
1193 len += snprintf(&ret[len], max - len, ":%d", uri->port);
1195 } else if (uri->authority != NULL) {
1196 if (len + 3 >= max) {
1197 temp = realloc2n(ret, &max);
1204 if (len + 3 >= max) {
1205 temp = realloc2n(ret, &max);
1208 if ((IS_UNRESERVED(*(p))) || ((*(p) == '$')) ||
1209 ((*(p) == ',')) || ((*(p) == ';')) || ((*(p) == ':')) ||
1210 ((*(p) == '@')) || ((*(p) == '&')) || ((*(p) == '=')) ||
1214 int val = *(unsigned char *)p++;
1215 int hi = val / 0x10, lo = val % 0x10;
1217 ret[len++] = hi + (hi > 9 ? 'A' - 10 : '0');
1218 ret[len++] = lo + (lo > 9 ? 'A' - 10 : '0');
1221 } else if (uri->scheme != NULL) {
1222 if (len + 3 >= max) {
1223 temp = realloc2n(ret, &max);
1229 if (uri->path != NULL) {
1232 * the colon in file:///d: should not be escaped or
1233 * Windows accesses fail later.
1235 if ((uri->scheme != NULL) && (p[0] == '/') &&
1236 (((p[1] >= 'a') && (p[1] <= 'z')) ||
1237 ((p[1] >= 'A') && (p[1] <= 'Z'))) &&
1238 (p[2] == ':') && (!strcmp(uri->scheme, "file"))) {
1239 if (len + 3 >= max) {
1240 temp = realloc2n(ret, &max);
1248 if (len + 3 >= max) {
1249 temp = realloc2n(ret, &max);
1252 if ((IS_UNRESERVED(*(p))) || ((*(p) == '/')) ||
1253 ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1254 ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||
1258 int val = *(unsigned char *)p++;
1259 int hi = val / 0x10, lo = val % 0x10;
1261 ret[len++] = hi + (hi > 9 ? 'A' - 10 : '0');
1262 ret[len++] = lo + (lo > 9 ? 'A' - 10 : '0');
1266 if (uri->query != NULL) {
1267 if (len + 1 >= max) {
1268 temp = realloc2n(ret, &max);
1274 if (len + 1 >= max) {
1275 temp = realloc2n(ret, &max);
1282 if (uri->fragment != NULL) {
1283 if (len + 3 >= max) {
1284 temp = realloc2n(ret, &max);
1290 if (len + 3 >= max) {
1291 temp = realloc2n(ret, &max);
1294 if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p)))) {
1297 int val = *(unsigned char *)p++;
1298 int hi = val / 0x10, lo = val % 0x10;
1300 ret[len++] = hi + (hi > 9 ? 'A' - 10 : '0');
1301 ret[len++] = lo + (lo > 9 ? 'A' - 10 : '0');
1306 temp = realloc2n(ret, &max);
1315 * @uri: pointer to an URI
1317 * Make sure the URI struct is free of content
1319 static void uri_clean(URI *uri)
1325 g_free(uri->scheme);
1327 g_free(uri->server);
1333 g_free(uri->fragment);
1334 uri->fragment = NULL;
1335 g_free(uri->opaque);
1337 g_free(uri->authority);
1338 uri->authority = NULL;
1345 * @uri: pointer to an URI
1347 * Free up the URI struct
1349 void uri_free(URI *uri)
1355 /************************************************************************
1357 * Helper functions *
1359 ************************************************************************/
1362 * normalize_uri_path:
1363 * @path: pointer to the path string
1365 * Applies the 5 normalization steps to a path string--that is, RFC 2396
1366 * Section 5.2, steps 6.c through 6.g.
1368 * Normalization occurs directly on the string, no new allocation is done
1370 * Returns 0 or an error code
1372 static int normalize_uri_path(char *path)
1380 /* Skip all initial "/" chars. We want to get to the beginning of the
1381 * first non-empty segment.
1384 while (cur[0] == '/') {
1387 if (cur[0] == '\0') {
1391 /* Keep everything we've seen so far. */
1395 * Analyze each segment in sequence for cases (c) and (d).
1397 while (cur[0] != '\0') {
1399 * c) All occurrences of "./", where "." is a complete path segment,
1400 * are removed from the buffer string.
1402 if ((cur[0] == '.') && (cur[1] == '/')) {
1404 /* '//' normalization should be done at this point too */
1405 while (cur[0] == '/') {
1412 * d) If the buffer string ends with "." as a complete path segment,
1413 * that "." is removed.
1415 if ((cur[0] == '.') && (cur[1] == '\0')) {
1419 /* Otherwise keep the segment. */
1420 while (cur[0] != '/') {
1421 if (cur[0] == '\0') {
1424 (out++)[0] = (cur++)[0];
1427 while ((cur[0] == '/') && (cur[1] == '/')) {
1431 (out++)[0] = (cur++)[0];
1436 /* Reset to the beginning of the first segment for the next sequence. */
1438 while (cur[0] == '/') {
1441 if (cur[0] == '\0') {
1446 * Analyze each segment in sequence for cases (e) and (f).
1448 * e) All occurrences of "<segment>/../", where <segment> is a
1449 * complete path segment not equal to "..", are removed from the
1450 * buffer string. Removal of these path segments is performed
1451 * iteratively, removing the leftmost matching pattern on each
1452 * iteration, until no matching pattern remains.
1454 * f) If the buffer string ends with "<segment>/..", where <segment>
1455 * is a complete path segment not equal to "..", that
1456 * "<segment>/.." is removed.
1458 * To satisfy the "iterative" clause in (e), we need to collapse the
1459 * string every time we find something that needs to be removed. Thus,
1460 * we don't need to keep two pointers into the string: we only need a
1461 * "current position" pointer.
1466 /* At the beginning of each iteration of this loop, "cur" points to
1467 * the first character of the segment we want to examine.
1470 /* Find the end of the current segment. */
1472 while ((segp[0] != '/') && (segp[0] != '\0')) {
1476 /* If this is the last segment, we're done (we need at least two
1477 * segments to meet the criteria for the (e) and (f) cases).
1479 if (segp[0] == '\0') {
1483 /* If the first segment is "..", or if the next segment _isn't_ "..",
1484 * keep this segment and try the next one.
1487 if (((cur[0] == '.') && (cur[1] == '.') && (segp == cur + 3)) ||
1488 ((segp[0] != '.') || (segp[1] != '.') ||
1489 ((segp[2] != '/') && (segp[2] != '\0')))) {
1494 /* If we get here, remove this segment and the next one and back up
1495 * to the previous segment (if there is one), to implement the
1496 * "iteratively" clause. It's pretty much impossible to back up
1497 * while maintaining two pointers into the buffer, so just compact
1498 * the whole buffer now.
1501 /* If this is the end of the buffer, we're done. */
1502 if (segp[2] == '\0') {
1506 /* Valgrind complained, strcpy(cur, segp + 3); */
1507 /* string will overlap, do not use strcpy */
1510 while ((*tmp++ = *segp++) != 0) {
1511 /* No further work */
1514 /* If there are no previous segments, then keep going from here. */
1516 while ((segp > path) && ((--segp)[0] == '/')) {
1517 /* No further work */
1523 /* "segp" is pointing to the end of a previous segment; find it's
1524 * start. We need to back up to the previous segment and start
1525 * over with that to handle things like "foo/bar/../..". If we
1526 * don't do this, then on the first pass we'll remove the "bar/..",
1527 * but be pointing at the second ".." so we won't realize we can also
1528 * remove the "foo/..".
1531 while ((cur > path) && (cur[-1] != '/')) {
1538 * g) If the resulting buffer string still begins with one or more
1539 * complete path segments of "..", then the reference is
1540 * considered to be in error. Implementations may handle this
1541 * error by retaining these components in the resolved path (i.e.,
1542 * treating them as part of the final URI), by removing them from
1543 * the resolved path (i.e., discarding relative levels above the
1544 * root), or by avoiding traversal of the reference.
1546 * We discard them from the final path.
1548 if (path[0] == '/') {
1550 while ((cur[0] == '/') && (cur[1] == '.') && (cur[2] == '.') &&
1551 ((cur[3] == '/') || (cur[3] == '\0'))) {
1557 while (cur[0] != '\0') {
1558 (out++)[0] = (cur++)[0];
1567 static int is_hex(char c)
1569 if (((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'f')) ||
1570 ((c >= 'A') && (c <= 'F'))) {
1577 * uri_string_unescape:
1578 * @str: the string to unescape
1579 * @len: the length in bytes to unescape (or <= 0 to indicate full string)
1580 * @target: optional destination buffer
1582 * Unescaping routine, but does not check that the string is an URI. The
1583 * output is a direct unsigned char translation of %XX values (no encoding)
1584 * Note that the length of the result can only be smaller or same size as
1587 * Returns a copy of the string, but unescaped, will return NULL only in case
1590 char *uri_string_unescape(const char *str, int len, char *target)
1605 if (target == NULL) {
1606 ret = g_malloc(len + 1);
1613 if ((len > 2) && (*in == '%') && (is_hex(in[1])) && (is_hex(in[2]))) {
1615 if ((*in >= '0') && (*in <= '9')) {
1617 } else if ((*in >= 'a') && (*in <= 'f')) {
1618 *out = (*in - 'a') + 10;
1619 } else if ((*in >= 'A') && (*in <= 'F')) {
1620 *out = (*in - 'A') + 10;
1623 if ((*in >= '0') && (*in <= '9')) {
1624 *out = *out * 16 + (*in - '0');
1625 } else if ((*in >= 'a') && (*in <= 'f')) {
1626 *out = *out * 16 + (*in - 'a') + 10;
1627 } else if ((*in >= 'A') && (*in <= 'F')) {
1628 *out = *out * 16 + (*in - 'A') + 10;
1643 * uri_string_escape:
1644 * @str: string to escape
1645 * @list: exception list string of chars not to escape
1647 * This routine escapes a string to hex, ignoring reserved characters (a-z)
1648 * and the characters in the exception list.
1650 * Returns a new escaped string or NULL in case of error.
1652 char *uri_string_escape(const char *str, const char *list)
1663 return g_strdup(str);
1671 ret = g_malloc(len);
1675 if (len - out <= 3) {
1676 temp = realloc2n(ret, &len);
1682 if ((ch != '@') && (!IS_UNRESERVED(ch)) && (!strchr(list, ch))) {
1687 ret[out++] = '0' + val;
1689 ret[out++] = 'A' + val - 0xA;
1693 ret[out++] = '0' + val;
1695 ret[out++] = 'A' + val - 0xA;
1706 /************************************************************************
1708 * Public functions *
1710 ************************************************************************/
1714 * @URI: the URI instance found in the document
1715 * @base: the base value
1717 * Computes he final URI of the reference done by checking that
1718 * the given URI is valid, and building the final URI using the
1719 * base URI. This is processed according to section 5.2 of the
1722 * 5.2. Resolving Relative References to Absolute Form
1724 * Returns a new URI string (to be freed by the caller) or NULL in case
1727 char *uri_resolve(const char *uri, const char *base)
1730 int ret, len, indx, cur, out;
1736 * 1) The URI reference is parsed into the potential four components and
1737 * fragment identifier, as described in Section 4.3.
1739 * NOTE that a completely empty URI is treated by modern browsers
1740 * as a reference to "." rather than as a synonym for the current
1741 * URI. Should we do that here?
1748 ret = uri_parse_into(ref, uri);
1756 if ((ref != NULL) && (ref->scheme != NULL)) {
1758 * The URI is absolute don't modify.
1760 val = g_strdup(uri);
1767 ret = uri_parse_into(bas, base);
1771 val = uri_to_string(ref);
1777 * the base fragment must be ignored
1779 g_free(bas->fragment);
1780 bas->fragment = NULL;
1781 val = uri_to_string(bas);
1786 * 2) If the path component is empty and the scheme, authority, and
1787 * query components are undefined, then it is a reference to the
1788 * current document and we are done. Otherwise, the reference URI's
1789 * query and fragment components are defined as found (or not found)
1790 * within the URI reference and not inherited from the base URI.
1792 * NOTE that in modern browsers, the parsing differs from the above
1793 * in the following aspect: the query component is allowed to be
1794 * defined while still treating this as a reference to the current
1798 if ((ref->scheme == NULL) && (ref->path == NULL) &&
1799 ((ref->authority == NULL) && (ref->server == NULL))) {
1800 res->scheme = g_strdup(bas->scheme);
1801 if (bas->authority != NULL) {
1802 res->authority = g_strdup(bas->authority);
1803 } else if (bas->server != NULL) {
1804 res->server = g_strdup(bas->server);
1805 res->user = g_strdup(bas->user);
1806 res->port = bas->port;
1808 res->path = g_strdup(bas->path);
1809 if (ref->query != NULL) {
1810 res->query = g_strdup(ref->query);
1812 res->query = g_strdup(bas->query);
1814 res->fragment = g_strdup(ref->fragment);
1819 * 3) If the scheme component is defined, indicating that the reference
1820 * starts with a scheme name, then the reference is interpreted as an
1821 * absolute URI and we are done. Otherwise, the reference URI's
1822 * scheme is inherited from the base URI's scheme component.
1824 if (ref->scheme != NULL) {
1825 val = uri_to_string(ref);
1828 res->scheme = g_strdup(bas->scheme);
1830 res->query = g_strdup(ref->query);
1831 res->fragment = g_strdup(ref->fragment);
1834 * 4) If the authority component is defined, then the reference is a
1835 * network-path and we skip to step 7. Otherwise, the reference
1836 * URI's authority is inherited from the base URI's authority
1837 * component, which will also be undefined if the URI scheme does not
1838 * use an authority component.
1840 if ((ref->authority != NULL) || (ref->server != NULL)) {
1841 if (ref->authority != NULL) {
1842 res->authority = g_strdup(ref->authority);
1844 res->server = g_strdup(ref->server);
1845 res->user = g_strdup(ref->user);
1846 res->port = ref->port;
1848 res->path = g_strdup(ref->path);
1851 if (bas->authority != NULL) {
1852 res->authority = g_strdup(bas->authority);
1853 } else if (bas->server != NULL) {
1854 res->server = g_strdup(bas->server);
1855 res->user = g_strdup(bas->user);
1856 res->port = bas->port;
1860 * 5) If the path component begins with a slash character ("/"), then
1861 * the reference is an absolute-path and we skip to step 7.
1863 if ((ref->path != NULL) && (ref->path[0] == '/')) {
1864 res->path = g_strdup(ref->path);
1869 * 6) If this step is reached, then we are resolving a relative-path
1870 * reference. The relative path needs to be merged with the base
1871 * URI's path. Although there are many ways to do this, we will
1872 * describe a simple method using a separate string buffer.
1874 * Allocate a buffer large enough for the result string.
1876 len = 2; /* extra / and 0 */
1877 if (ref->path != NULL) {
1878 len += strlen(ref->path);
1880 if (bas->path != NULL) {
1881 len += strlen(bas->path);
1883 res->path = g_malloc(len);
1887 * a) All but the last segment of the base URI's path component is
1888 * copied to the buffer. In other words, any characters after the
1889 * last (right-most) slash character, if any, are excluded.
1893 if (bas->path != NULL) {
1894 while (bas->path[cur] != 0) {
1895 while ((bas->path[cur] != 0) && (bas->path[cur] != '/')) {
1898 if (bas->path[cur] == 0) {
1904 res->path[out] = bas->path[out];
1912 * b) The reference's path component is appended to the buffer
1915 if (ref->path != NULL && ref->path[0] != 0) {
1918 * Ensure the path includes a '/'
1920 if ((out == 0) && (bas->server != NULL)) {
1921 res->path[out++] = '/';
1923 while (ref->path[indx] != 0) {
1924 res->path[out++] = ref->path[indx++];
1930 * Steps c) to h) are really path normalization steps
1932 normalize_uri_path(res->path);
1937 * 7) The resulting URI components, including any inherited from the
1938 * base URI, are recombined to give the absolute form of the URI
1941 val = uri_to_string(res);
1957 * uri_resolve_relative:
1958 * @URI: the URI reference under consideration
1959 * @base: the base value
1961 * Expresses the URI of the reference in terms relative to the
1962 * base. Some examples of this operation include:
1963 * base = "http://site1.com/docs/book1.html"
1964 * URI input URI returned
1965 * docs/pic1.gif pic1.gif
1966 * docs/img/pic1.gif img/pic1.gif
1967 * img/pic1.gif ../img/pic1.gif
1968 * http://site1.com/docs/pic1.gif pic1.gif
1969 * http://site2.com/docs/pic1.gif http://site2.com/docs/pic1.gif
1971 * base = "docs/book1.html"
1972 * URI input URI returned
1973 * docs/pic1.gif pic1.gif
1974 * docs/img/pic1.gif img/pic1.gif
1975 * img/pic1.gif ../img/pic1.gif
1976 * http://site1.com/docs/pic1.gif http://site1.com/docs/pic1.gif
1979 * Note: if the URI reference is really weird or complicated, it may be
1980 * worthwhile to first convert it into a "nice" one by calling
1981 * uri_resolve (using 'base') before calling this routine,
1982 * since this routine (for reasonable efficiency) assumes URI has
1983 * already been through some validation.
1985 * Returns a new URI string (to be freed by the caller) or NULL in case
1988 char *uri_resolve_relative(const char *uri, const char *base)
1998 char *bptr, *uptr, *vptr;
1999 int remove_path = 0;
2001 if ((uri == NULL) || (*uri == 0)) {
2006 * First parse URI into a standard form
2009 /* If URI not already in "relative" form */
2010 if (uri[0] != '.') {
2011 ret = uri_parse_into(ref, uri);
2013 goto done; /* Error in URI, return NULL */
2016 ref->path = g_strdup(uri);
2020 * Next parse base into the same standard form
2022 if ((base == NULL) || (*base == 0)) {
2023 val = g_strdup(uri);
2027 if (base[0] != '.') {
2028 ret = uri_parse_into(bas, base);
2030 goto done; /* Error in base, return NULL */
2033 bas->path = g_strdup(base);
2037 * If the scheme / server on the URI differs from the base,
2038 * just return the URI
2040 if ((ref->scheme != NULL) &&
2041 ((bas->scheme == NULL) || (strcmp(bas->scheme, ref->scheme)) ||
2042 (strcmp(bas->server, ref->server)))) {
2043 val = g_strdup(uri);
2046 if (bas->path == ref->path ||
2047 (bas->path && ref->path && !strcmp(bas->path, ref->path))) {
2051 if (bas->path == NULL) {
2052 val = g_strdup(ref->path);
2055 if (ref->path == NULL) {
2056 ref->path = (char *)"/";
2061 * At this point (at last!) we can compare the two paths
2063 * First we take care of the special case where either of the
2064 * two path components may be missing (bug 316224)
2066 if (bas->path == NULL) {
2067 if (ref->path != NULL) {
2072 /* exception characters from uri_to_string */
2073 val = uri_string_escape(uptr, "/;&=+$,");
2078 if (ref->path == NULL) {
2079 for (ix = 0; bptr[ix] != 0; ix++) {
2080 if (bptr[ix] == '/') {
2085 len = 1; /* this is for a string terminator only */
2088 * Next we compare the two strings and find where they first differ
2090 if ((ref->path[pos] == '.') && (ref->path[pos + 1] == '/')) {
2093 if ((*bptr == '.') && (bptr[1] == '/')) {
2095 } else if ((*bptr == '/') && (ref->path[pos] != '/')) {
2098 while ((bptr[pos] == ref->path[pos]) && (bptr[pos] != 0)) {
2102 if (bptr[pos] == ref->path[pos]) {
2104 goto done; /* (I can't imagine why anyone would do this) */
2108 * In URI, "back up" to the last '/' encountered. This will be the
2109 * beginning of the "unique" suffix of URI
2112 if ((ref->path[ix] == '/') && (ix > 0)) {
2114 } else if ((ref->path[ix] == 0) && (ix > 1)
2115 && (ref->path[ix - 1] == '/')) {
2118 for (; ix > 0; ix--) {
2119 if (ref->path[ix] == '/') {
2127 uptr = &ref->path[ix];
2131 * In base, count the number of '/' from the differing point
2133 if (bptr[pos] != ref->path[pos]) { /* check for trivial URI == base */
2134 for (; bptr[ix] != 0; ix++) {
2135 if (bptr[ix] == '/') {
2140 len = strlen(uptr) + 1;
2145 /* exception characters from uri_to_string */
2146 val = uri_string_escape(uptr, "/;&=+$,");
2152 * Allocate just enough space for the returned string -
2153 * length of the remainder of the URI, plus enough space
2154 * for the "../" groups, plus one for the terminator
2156 val = g_malloc(len + 3 * nbslash);
2159 * Put in as many "../" as needed
2161 for (; nbslash > 0; nbslash--) {
2167 * Finish up with the end of the URI
2170 if ((vptr > val) && (len > 0) && (uptr[0] == '/') &&
2171 (vptr[-1] == '/')) {
2172 memcpy(vptr, uptr + 1, len - 1);
2175 memcpy(vptr, uptr, len);
2182 /* escape the freshly-built path */
2184 /* exception characters from uri_to_string */
2185 val = uri_string_escape(vptr, "/;&=+$,");
2190 * Free the working variables
2192 if (remove_path != 0) {
2206 * Utility functions to help parse and assemble query strings.
2209 struct QueryParams *query_params_new(int init_alloc)
2211 struct QueryParams *ps;
2213 if (init_alloc <= 0) {
2217 ps = g_new(QueryParams, 1);
2219 ps->alloc = init_alloc;
2220 ps->p = g_new(QueryParam, ps->alloc);
2225 /* Ensure there is space to store at least one more parameter
2226 * at the end of the set.
2228 static int query_params_append(struct QueryParams *ps, const char *name,
2231 if (ps->n >= ps->alloc) {
2232 ps->p = g_renew(QueryParam, ps->p, ps->alloc * 2);
2236 ps->p[ps->n].name = g_strdup(name);
2237 ps->p[ps->n].value = g_strdup(value);
2238 ps->p[ps->n].ignore = 0;
2244 void query_params_free(struct QueryParams *ps)
2248 for (i = 0; i < ps->n; ++i) {
2249 g_free(ps->p[i].name);
2250 g_free(ps->p[i].value);
2256 struct QueryParams *query_params_parse(const char *query)
2258 struct QueryParams *ps;
2259 const char *end, *eq;
2261 ps = query_params_new(0);
2262 if (!query || query[0] == '\0') {
2267 char *name = NULL, *value = NULL;
2269 /* Find the next separator, or end of the string. */
2270 end = strchr(query, '&');
2272 end = strchr(query, ';');
2275 end = query + strlen(query);
2278 /* Find the first '=' character between here and end. */
2279 eq = strchr(query, '=');
2280 if (eq && eq >= end) {
2284 /* Empty section (eg. "&&"). */
2289 /* If there is no '=' character, then we have just "name"
2290 * and consistent with CGI.pm we assume value is "".
2293 name = uri_string_unescape(query, end - query, NULL);
2296 /* Or if we have "name=" here (works around annoying
2297 * problem when calling uri_string_unescape with len = 0).
2299 else if (eq + 1 == end) {
2300 name = uri_string_unescape(query, eq - query, NULL);
2301 value = g_new0(char, 1);
2303 /* If the '=' character is at the beginning then we have
2304 * "=value" and consistent with CGI.pm we _ignore_ this.
2306 else if (query == eq) {
2310 /* Otherwise it's "name=value". */
2312 name = uri_string_unescape(query, eq - query, NULL);
2313 value = uri_string_unescape(eq + 1, end - (eq + 1), NULL);
2316 /* Append to the parameter set. */
2317 query_params_append(ps, name, value);
2324 query++; /* skip '&' separator */