migration: Document handling of bdrv_is_allocated() errors
[qemu/ar7.git] / util / uri.c
blob21b18281703aa3356e562099efee4fd2a715b9d1
1 /**
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.
29 * daniel@veillard.com
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
49 * Authors:
50 * Richard W.M. Jones <rjones@redhat.com>
54 #include "qemu/osdep.h"
56 #include "qemu/uri.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))
68 * lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" |
69 * "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" |
70 * "u" | "v" | "w" | "x" | "y" | "z"
73 #define IS_LOWALPHA(x) (((x) >= 'a') && ((x) <= 'z'))
76 * upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" |
77 * "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" |
78 * "U" | "V" | "W" | "X" | "Y" | "Z"
80 #define IS_UPALPHA(x) (((x) >= 'A') && ((x) <= 'Z'))
82 #ifdef IS_DIGIT
83 #undef IS_DIGIT
84 #endif
86 * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
88 #define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9'))
91 * alphanum = alpha | digit
94 #define IS_ALPHANUM(x) (IS_ALPHA(x) || IS_DIGIT(x))
97 * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
100 #define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') || \
101 ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') || \
102 ((x) == '(') || ((x) == ')'))
105 * unwise = "{" | "}" | "|" | "\" | "^" | "`"
108 #define IS_UNWISE(p) \
109 (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) || \
110 ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) || \
111 ((*(p) == ']')) || ((*(p) == '`')))
113 * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
114 * "[" | "]"
117 #define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') || \
118 ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') || \
119 ((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \
120 ((x) == ']'))
123 * unreserved = alphanum | mark
126 #define IS_UNRESERVED(x) (IS_ALPHANUM(x) || IS_MARK(x))
129 * Skip to next pointer char, handle escaped sequences
132 #define NEXT(p) ((*p == '%')? p += 3 : p++)
135 * Productions from the spec.
137 * authority = server | reg_name
138 * reg_name = 1*( unreserved | escaped | "$" | "," |
139 * ";" | ":" | "@" | "&" | "=" | "+" )
141 * path = [ abs_path | opaque_part ]
145 /************************************************************************
147 * RFC 3986 parser *
149 ************************************************************************/
151 #define ISA_DIGIT(p) ((*(p) >= '0') && (*(p) <= '9'))
152 #define ISA_ALPHA(p) (((*(p) >= 'a') && (*(p) <= 'z')) || \
153 ((*(p) >= 'A') && (*(p) <= 'Z')))
154 #define ISA_HEXDIG(p) \
155 (ISA_DIGIT(p) || ((*(p) >= 'a') && (*(p) <= 'f')) || \
156 ((*(p) >= 'A') && (*(p) <= 'F')))
159 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
160 * / "*" / "+" / "," / ";" / "="
162 #define ISA_SUB_DELIM(p) \
163 (((*(p) == '!')) || ((*(p) == '$')) || ((*(p) == '&')) || \
164 ((*(p) == '(')) || ((*(p) == ')')) || ((*(p) == '*')) || \
165 ((*(p) == '+')) || ((*(p) == ',')) || ((*(p) == ';')) || \
166 ((*(p) == '=')) || ((*(p) == '\'')))
169 * gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
171 #define ISA_GEN_DELIM(p) \
172 (((*(p) == ':')) || ((*(p) == '/')) || ((*(p) == '?')) || \
173 ((*(p) == '#')) || ((*(p) == '[')) || ((*(p) == ']')) || \
174 ((*(p) == '@')))
177 * reserved = gen-delims / sub-delims
179 #define ISA_RESERVED(p) (ISA_GEN_DELIM(p) || (ISA_SUB_DELIM(p)))
182 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
184 #define ISA_UNRESERVED(p) \
185 ((ISA_ALPHA(p)) || (ISA_DIGIT(p)) || ((*(p) == '-')) || \
186 ((*(p) == '.')) || ((*(p) == '_')) || ((*(p) == '~')))
189 * pct-encoded = "%" HEXDIG HEXDIG
191 #define ISA_PCT_ENCODED(p) \
192 ((*(p) == '%') && (ISA_HEXDIG(p + 1)) && (ISA_HEXDIG(p + 2)))
195 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
197 #define ISA_PCHAR(p) \
198 (ISA_UNRESERVED(p) || ISA_PCT_ENCODED(p) || ISA_SUB_DELIM(p) || \
199 ((*(p) == ':')) || ((*(p) == '@')))
202 * rfc3986_parse_scheme:
203 * @uri: pointer to an URI structure
204 * @str: pointer to the string to analyze
206 * Parse an URI scheme
208 * ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
210 * Returns 0 or the error code
212 static int
213 rfc3986_parse_scheme(URI *uri, const char **str) {
214 const char *cur;
216 if (str == NULL)
217 return(-1);
219 cur = *str;
220 if (!ISA_ALPHA(cur))
221 return(2);
222 cur++;
223 while (ISA_ALPHA(cur) || ISA_DIGIT(cur) ||
224 (*cur == '+') || (*cur == '-') || (*cur == '.')) cur++;
225 if (uri != NULL) {
226 g_free(uri->scheme);
227 uri->scheme = g_strndup(*str, cur - *str);
229 *str = cur;
230 return(0);
234 * rfc3986_parse_fragment:
235 * @uri: pointer to an URI structure
236 * @str: pointer to the string to analyze
238 * Parse the query part of an URI
240 * fragment = *( pchar / "/" / "?" )
241 * NOTE: the strict syntax as defined by 3986 does not allow '[' and ']'
242 * in the fragment identifier but this is used very broadly for
243 * xpointer scheme selection, so we are allowing it here to not break
244 * for example all the DocBook processing chains.
246 * Returns 0 or the error code
248 static int
249 rfc3986_parse_fragment(URI *uri, const char **str)
251 const char *cur;
253 if (str == NULL)
254 return (-1);
256 cur = *str;
258 while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
259 (*cur == '[') || (*cur == ']') ||
260 ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
261 NEXT(cur);
262 if (uri != NULL) {
263 g_free(uri->fragment);
264 if (uri->cleanup & 2)
265 uri->fragment = g_strndup(*str, cur - *str);
266 else
267 uri->fragment = uri_string_unescape(*str, cur - *str, NULL);
269 *str = cur;
270 return (0);
274 * rfc3986_parse_query:
275 * @uri: pointer to an URI structure
276 * @str: pointer to the string to analyze
278 * Parse the query part of an URI
280 * query = *uric
282 * Returns 0 or the error code
284 static int
285 rfc3986_parse_query(URI *uri, const char **str)
287 const char *cur;
289 if (str == NULL)
290 return (-1);
292 cur = *str;
294 while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
295 ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
296 NEXT(cur);
297 if (uri != NULL) {
298 g_free(uri->query);
299 uri->query = g_strndup (*str, cur - *str);
301 *str = cur;
302 return (0);
306 * rfc3986_parse_port:
307 * @uri: pointer to an URI structure
308 * @str: the string to analyze
310 * Parse a port part and fills in the appropriate fields
311 * of the @uri structure
313 * port = *DIGIT
315 * Returns 0 or the error code
317 static int
318 rfc3986_parse_port(URI *uri, const char **str)
320 const char *cur = *str;
321 int port = 0;
323 if (ISA_DIGIT(cur)) {
324 while (ISA_DIGIT(cur)) {
325 port = port * 10 + (*cur - '0');
326 if (port > 65535) {
327 return 1;
329 cur++;
331 if (uri) {
332 uri->port = port;
334 *str = cur;
335 return 0;
337 return 1;
341 * rfc3986_parse_user_info:
342 * @uri: pointer to an URI structure
343 * @str: the string to analyze
345 * Parse a user information part and fill in the appropriate fields
346 * of the @uri structure
348 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
350 * Returns 0 or the error code
352 static int
353 rfc3986_parse_user_info(URI *uri, const char **str)
355 const char *cur;
357 cur = *str;
358 while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) ||
359 ISA_SUB_DELIM(cur) || (*cur == ':'))
360 NEXT(cur);
361 if (*cur == '@') {
362 if (uri != NULL) {
363 g_free(uri->user);
364 if (uri->cleanup & 2)
365 uri->user = g_strndup(*str, cur - *str);
366 else
367 uri->user = uri_string_unescape(*str, cur - *str, NULL);
369 *str = cur;
370 return(0);
372 return(1);
376 * rfc3986_parse_dec_octet:
377 * @str: the string to analyze
379 * dec-octet = DIGIT ; 0-9
380 * / %x31-39 DIGIT ; 10-99
381 * / "1" 2DIGIT ; 100-199
382 * / "2" %x30-34 DIGIT ; 200-249
383 * / "25" %x30-35 ; 250-255
385 * Skip a dec-octet.
387 * Returns 0 if found and skipped, 1 otherwise
389 static int
390 rfc3986_parse_dec_octet(const char **str) {
391 const char *cur = *str;
393 if (!(ISA_DIGIT(cur)))
394 return(1);
395 if (!ISA_DIGIT(cur+1))
396 cur++;
397 else if ((*cur != '0') && (ISA_DIGIT(cur + 1)) && (!ISA_DIGIT(cur+2)))
398 cur += 2;
399 else if ((*cur == '1') && (ISA_DIGIT(cur + 1)) && (ISA_DIGIT(cur + 2)))
400 cur += 3;
401 else if ((*cur == '2') && (*(cur + 1) >= '0') &&
402 (*(cur + 1) <= '4') && (ISA_DIGIT(cur + 2)))
403 cur += 3;
404 else if ((*cur == '2') && (*(cur + 1) == '5') &&
405 (*(cur + 2) >= '0') && (*(cur + 1) <= '5'))
406 cur += 3;
407 else
408 return(1);
409 *str = cur;
410 return(0);
413 * rfc3986_parse_host:
414 * @uri: pointer to an URI structure
415 * @str: the string to analyze
417 * Parse an host part and fills in the appropriate fields
418 * of the @uri structure
420 * host = IP-literal / IPv4address / reg-name
421 * IP-literal = "[" ( IPv6address / IPvFuture ) "]"
422 * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
423 * reg-name = *( unreserved / pct-encoded / sub-delims )
425 * Returns 0 or the error code
427 static int
428 rfc3986_parse_host(URI *uri, const char **str)
430 const char *cur = *str;
431 const char *host;
433 host = cur;
435 * IPv6 and future addressing scheme are enclosed between brackets
437 if (*cur == '[') {
438 cur++;
439 while ((*cur != ']') && (*cur != 0))
440 cur++;
441 if (*cur != ']')
442 return(1);
443 cur++;
444 goto found;
447 * try to parse an IPv4
449 if (ISA_DIGIT(cur)) {
450 if (rfc3986_parse_dec_octet(&cur) != 0)
451 goto not_ipv4;
452 if (*cur != '.')
453 goto not_ipv4;
454 cur++;
455 if (rfc3986_parse_dec_octet(&cur) != 0)
456 goto not_ipv4;
457 if (*cur != '.')
458 goto not_ipv4;
459 if (rfc3986_parse_dec_octet(&cur) != 0)
460 goto not_ipv4;
461 if (*cur != '.')
462 goto not_ipv4;
463 if (rfc3986_parse_dec_octet(&cur) != 0)
464 goto not_ipv4;
465 goto found;
466 not_ipv4:
467 cur = *str;
470 * then this should be a hostname which can be empty
472 while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) || ISA_SUB_DELIM(cur))
473 NEXT(cur);
474 found:
475 if (uri != NULL) {
476 g_free(uri->authority);
477 uri->authority = NULL;
478 g_free(uri->server);
479 if (cur != host) {
480 if (uri->cleanup & 2)
481 uri->server = g_strndup(host, cur - host);
482 else
483 uri->server = uri_string_unescape(host, cur - host, NULL);
484 } else
485 uri->server = NULL;
487 *str = cur;
488 return(0);
492 * rfc3986_parse_authority:
493 * @uri: pointer to an URI structure
494 * @str: the string to analyze
496 * Parse an authority part and fills in the appropriate fields
497 * of the @uri structure
499 * authority = [ userinfo "@" ] host [ ":" port ]
501 * Returns 0 or the error code
503 static int
504 rfc3986_parse_authority(URI *uri, const char **str)
506 const char *cur;
507 int ret;
509 cur = *str;
511 * try to parse a userinfo and check for the trailing @
513 ret = rfc3986_parse_user_info(uri, &cur);
514 if ((ret != 0) || (*cur != '@'))
515 cur = *str;
516 else
517 cur++;
518 ret = rfc3986_parse_host(uri, &cur);
519 if (ret != 0) return(ret);
520 if (*cur == ':') {
521 cur++;
522 ret = rfc3986_parse_port(uri, &cur);
523 if (ret != 0) return(ret);
525 *str = cur;
526 return(0);
530 * rfc3986_parse_segment:
531 * @str: the string to analyze
532 * @forbid: an optional forbidden character
533 * @empty: allow an empty segment
535 * Parse a segment and fills in the appropriate fields
536 * of the @uri structure
538 * segment = *pchar
539 * segment-nz = 1*pchar
540 * segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
541 * ; non-zero-length segment without any colon ":"
543 * Returns 0 or the error code
545 static int
546 rfc3986_parse_segment(const char **str, char forbid, int empty)
548 const char *cur;
550 cur = *str;
551 if (!ISA_PCHAR(cur)) {
552 if (empty)
553 return(0);
554 return(1);
556 while (ISA_PCHAR(cur) && (*cur != forbid))
557 NEXT(cur);
558 *str = cur;
559 return (0);
563 * rfc3986_parse_path_ab_empty:
564 * @uri: pointer to an URI structure
565 * @str: the string to analyze
567 * Parse an path absolute or empty and fills in the appropriate fields
568 * of the @uri structure
570 * path-abempty = *( "/" segment )
572 * Returns 0 or the error code
574 static int
575 rfc3986_parse_path_ab_empty(URI *uri, const char **str)
577 const char *cur;
578 int ret;
580 cur = *str;
582 while (*cur == '/') {
583 cur++;
584 ret = rfc3986_parse_segment(&cur, 0, 1);
585 if (ret != 0) return(ret);
587 if (uri != NULL) {
588 g_free(uri->path);
589 if (*str != cur) {
590 if (uri->cleanup & 2)
591 uri->path = g_strndup(*str, cur - *str);
592 else
593 uri->path = uri_string_unescape(*str, cur - *str, NULL);
594 } else {
595 uri->path = NULL;
598 *str = cur;
599 return (0);
603 * rfc3986_parse_path_absolute:
604 * @uri: pointer to an URI structure
605 * @str: the string to analyze
607 * Parse an path absolute and fills in the appropriate fields
608 * of the @uri structure
610 * path-absolute = "/" [ segment-nz *( "/" segment ) ]
612 * Returns 0 or the error code
614 static int
615 rfc3986_parse_path_absolute(URI *uri, const char **str)
617 const char *cur;
618 int ret;
620 cur = *str;
622 if (*cur != '/')
623 return(1);
624 cur++;
625 ret = rfc3986_parse_segment(&cur, 0, 0);
626 if (ret == 0) {
627 while (*cur == '/') {
628 cur++;
629 ret = rfc3986_parse_segment(&cur, 0, 1);
630 if (ret != 0) return(ret);
633 if (uri != NULL) {
634 g_free(uri->path);
635 if (cur != *str) {
636 if (uri->cleanup & 2)
637 uri->path = g_strndup(*str, cur - *str);
638 else
639 uri->path = uri_string_unescape(*str, cur - *str, NULL);
640 } else {
641 uri->path = NULL;
644 *str = cur;
645 return (0);
649 * rfc3986_parse_path_rootless:
650 * @uri: pointer to an URI structure
651 * @str: the string to analyze
653 * Parse an path without root and fills in the appropriate fields
654 * of the @uri structure
656 * path-rootless = segment-nz *( "/" segment )
658 * Returns 0 or the error code
660 static int
661 rfc3986_parse_path_rootless(URI *uri, const char **str)
663 const char *cur;
664 int ret;
666 cur = *str;
668 ret = rfc3986_parse_segment(&cur, 0, 0);
669 if (ret != 0) return(ret);
670 while (*cur == '/') {
671 cur++;
672 ret = rfc3986_parse_segment(&cur, 0, 1);
673 if (ret != 0) return(ret);
675 if (uri != NULL) {
676 g_free(uri->path);
677 if (cur != *str) {
678 if (uri->cleanup & 2)
679 uri->path = g_strndup(*str, cur - *str);
680 else
681 uri->path = uri_string_unescape(*str, cur - *str, NULL);
682 } else {
683 uri->path = NULL;
686 *str = cur;
687 return (0);
691 * rfc3986_parse_path_no_scheme:
692 * @uri: pointer to an URI structure
693 * @str: the string to analyze
695 * Parse an path which is not a scheme and fills in the appropriate fields
696 * of the @uri structure
698 * path-noscheme = segment-nz-nc *( "/" segment )
700 * Returns 0 or the error code
702 static int
703 rfc3986_parse_path_no_scheme(URI *uri, const char **str)
705 const char *cur;
706 int ret;
708 cur = *str;
710 ret = rfc3986_parse_segment(&cur, ':', 0);
711 if (ret != 0) return(ret);
712 while (*cur == '/') {
713 cur++;
714 ret = rfc3986_parse_segment(&cur, 0, 1);
715 if (ret != 0) return(ret);
717 if (uri != NULL) {
718 g_free(uri->path);
719 if (cur != *str) {
720 if (uri->cleanup & 2)
721 uri->path = g_strndup(*str, cur - *str);
722 else
723 uri->path = uri_string_unescape(*str, cur - *str, NULL);
724 } else {
725 uri->path = NULL;
728 *str = cur;
729 return (0);
733 * rfc3986_parse_hier_part:
734 * @uri: pointer to an URI structure
735 * @str: the string to analyze
737 * Parse an hierarchical part and fills in the appropriate fields
738 * of the @uri structure
740 * hier-part = "//" authority path-abempty
741 * / path-absolute
742 * / path-rootless
743 * / path-empty
745 * Returns 0 or the error code
747 static int
748 rfc3986_parse_hier_part(URI *uri, const char **str)
750 const char *cur;
751 int ret;
753 cur = *str;
755 if ((*cur == '/') && (*(cur + 1) == '/')) {
756 cur += 2;
757 ret = rfc3986_parse_authority(uri, &cur);
758 if (ret != 0) return(ret);
759 ret = rfc3986_parse_path_ab_empty(uri, &cur);
760 if (ret != 0) return(ret);
761 *str = cur;
762 return(0);
763 } else if (*cur == '/') {
764 ret = rfc3986_parse_path_absolute(uri, &cur);
765 if (ret != 0) return(ret);
766 } else if (ISA_PCHAR(cur)) {
767 ret = rfc3986_parse_path_rootless(uri, &cur);
768 if (ret != 0) return(ret);
769 } else {
770 /* path-empty is effectively empty */
771 if (uri != NULL) {
772 g_free(uri->path);
773 uri->path = NULL;
776 *str = cur;
777 return (0);
781 * rfc3986_parse_relative_ref:
782 * @uri: pointer to an URI structure
783 * @str: the string to analyze
785 * Parse an URI string and fills in the appropriate fields
786 * of the @uri structure
788 * relative-ref = relative-part [ "?" query ] [ "#" fragment ]
789 * relative-part = "//" authority path-abempty
790 * / path-absolute
791 * / path-noscheme
792 * / path-empty
794 * Returns 0 or the error code
796 static int
797 rfc3986_parse_relative_ref(URI *uri, const char *str) {
798 int ret;
800 if ((*str == '/') && (*(str + 1) == '/')) {
801 str += 2;
802 ret = rfc3986_parse_authority(uri, &str);
803 if (ret != 0) return(ret);
804 ret = rfc3986_parse_path_ab_empty(uri, &str);
805 if (ret != 0) return(ret);
806 } else if (*str == '/') {
807 ret = rfc3986_parse_path_absolute(uri, &str);
808 if (ret != 0) return(ret);
809 } else if (ISA_PCHAR(str)) {
810 ret = rfc3986_parse_path_no_scheme(uri, &str);
811 if (ret != 0) return(ret);
812 } else {
813 /* path-empty is effectively empty */
814 if (uri != NULL) {
815 g_free(uri->path);
816 uri->path = NULL;
820 if (*str == '?') {
821 str++;
822 ret = rfc3986_parse_query(uri, &str);
823 if (ret != 0) return(ret);
825 if (*str == '#') {
826 str++;
827 ret = rfc3986_parse_fragment(uri, &str);
828 if (ret != 0) return(ret);
830 if (*str != 0) {
831 uri_clean(uri);
832 return(1);
834 return(0);
839 * rfc3986_parse:
840 * @uri: pointer to an URI structure
841 * @str: the string to analyze
843 * Parse an URI string and fills in the appropriate fields
844 * of the @uri structure
846 * scheme ":" hier-part [ "?" query ] [ "#" fragment ]
848 * Returns 0 or the error code
850 static int
851 rfc3986_parse(URI *uri, const char *str) {
852 int ret;
854 ret = rfc3986_parse_scheme(uri, &str);
855 if (ret != 0) return(ret);
856 if (*str != ':') {
857 return(1);
859 str++;
860 ret = rfc3986_parse_hier_part(uri, &str);
861 if (ret != 0) return(ret);
862 if (*str == '?') {
863 str++;
864 ret = rfc3986_parse_query(uri, &str);
865 if (ret != 0) return(ret);
867 if (*str == '#') {
868 str++;
869 ret = rfc3986_parse_fragment(uri, &str);
870 if (ret != 0) return(ret);
872 if (*str != 0) {
873 uri_clean(uri);
874 return(1);
876 return(0);
880 * rfc3986_parse_uri_reference:
881 * @uri: pointer to an URI structure
882 * @str: the string to analyze
884 * Parse an URI reference string and fills in the appropriate fields
885 * of the @uri structure
887 * URI-reference = URI / relative-ref
889 * Returns 0 or the error code
891 static int
892 rfc3986_parse_uri_reference(URI *uri, const char *str) {
893 int ret;
895 if (str == NULL)
896 return(-1);
897 uri_clean(uri);
900 * Try first to parse absolute refs, then fallback to relative if
901 * it fails.
903 ret = rfc3986_parse(uri, str);
904 if (ret != 0) {
905 uri_clean(uri);
906 ret = rfc3986_parse_relative_ref(uri, str);
907 if (ret != 0) {
908 uri_clean(uri);
909 return(ret);
912 return(0);
916 * uri_parse:
917 * @str: the URI string to analyze
919 * Parse an URI based on RFC 3986
921 * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
923 * Returns a newly built URI or NULL in case of error
925 URI *
926 uri_parse(const char *str) {
927 URI *uri;
928 int ret;
930 if (str == NULL)
931 return(NULL);
932 uri = uri_new();
933 ret = rfc3986_parse_uri_reference(uri, str);
934 if (ret) {
935 uri_free(uri);
936 return(NULL);
938 return(uri);
942 * uri_parse_into:
943 * @uri: pointer to an URI structure
944 * @str: the string to analyze
946 * Parse an URI reference string based on RFC 3986 and fills in the
947 * appropriate fields of the @uri structure
949 * URI-reference = URI / relative-ref
951 * Returns 0 or the error code
954 uri_parse_into(URI *uri, const char *str) {
955 return(rfc3986_parse_uri_reference(uri, str));
959 * uri_parse_raw:
960 * @str: the URI string to analyze
961 * @raw: if 1 unescaping of URI pieces are disabled
963 * Parse an URI but allows to keep intact the original fragments.
965 * URI-reference = URI / relative-ref
967 * Returns a newly built URI or NULL in case of error
969 URI *
970 uri_parse_raw(const char *str, int raw) {
971 URI *uri;
972 int ret;
974 if (str == NULL)
975 return(NULL);
976 uri = uri_new();
977 if (raw) {
978 uri->cleanup |= 2;
980 ret = uri_parse_into(uri, str);
981 if (ret) {
982 uri_free(uri);
983 return(NULL);
985 return(uri);
988 /************************************************************************
990 * Generic URI structure functions *
992 ************************************************************************/
995 * uri_new:
997 * Simply creates an empty URI
999 * Returns the new structure or NULL in case of error
1001 URI *
1002 uri_new(void) {
1003 URI *ret;
1005 ret = g_new0(URI, 1);
1006 return(ret);
1010 * realloc2n:
1012 * Function to handle properly a reallocation when saving an URI
1013 * Also imposes some limit on the length of an URI string output
1015 static char *
1016 realloc2n(char *ret, int *max) {
1017 char *temp;
1018 int tmp;
1020 tmp = *max * 2;
1021 temp = g_realloc(ret, (tmp + 1));
1022 *max = tmp;
1023 return(temp);
1027 * uri_to_string:
1028 * @uri: pointer to an URI
1030 * Save the URI as an escaped string
1032 * Returns a new string (to be deallocated by caller)
1034 char *
1035 uri_to_string(URI *uri) {
1036 char *ret = NULL;
1037 char *temp;
1038 const char *p;
1039 int len;
1040 int max;
1042 if (uri == NULL) return(NULL);
1045 max = 80;
1046 ret = g_malloc(max + 1);
1047 len = 0;
1049 if (uri->scheme != NULL) {
1050 p = uri->scheme;
1051 while (*p != 0) {
1052 if (len >= max) {
1053 temp = realloc2n(ret, &max);
1054 ret = temp;
1056 ret[len++] = *p++;
1058 if (len >= max) {
1059 temp = realloc2n(ret, &max);
1060 ret = temp;
1062 ret[len++] = ':';
1064 if (uri->opaque != NULL) {
1065 p = uri->opaque;
1066 while (*p != 0) {
1067 if (len + 3 >= max) {
1068 temp = realloc2n(ret, &max);
1069 ret = temp;
1071 if (IS_RESERVED(*(p)) || IS_UNRESERVED(*(p)))
1072 ret[len++] = *p++;
1073 else {
1074 int val = *(unsigned char *)p++;
1075 int hi = val / 0x10, lo = val % 0x10;
1076 ret[len++] = '%';
1077 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1078 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1081 } else {
1082 if (uri->server != NULL) {
1083 if (len + 3 >= max) {
1084 temp = realloc2n(ret, &max);
1085 ret = temp;
1087 ret[len++] = '/';
1088 ret[len++] = '/';
1089 if (uri->user != NULL) {
1090 p = uri->user;
1091 while (*p != 0) {
1092 if (len + 3 >= max) {
1093 temp = realloc2n(ret, &max);
1094 ret = temp;
1096 if ((IS_UNRESERVED(*(p))) ||
1097 ((*(p) == ';')) || ((*(p) == ':')) ||
1098 ((*(p) == '&')) || ((*(p) == '=')) ||
1099 ((*(p) == '+')) || ((*(p) == '$')) ||
1100 ((*(p) == ',')))
1101 ret[len++] = *p++;
1102 else {
1103 int val = *(unsigned char *)p++;
1104 int hi = val / 0x10, lo = val % 0x10;
1105 ret[len++] = '%';
1106 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1107 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1110 if (len + 3 >= max) {
1111 temp = realloc2n(ret, &max);
1112 ret = temp;
1114 ret[len++] = '@';
1116 p = uri->server;
1117 while (*p != 0) {
1118 if (len >= max) {
1119 temp = realloc2n(ret, &max);
1120 ret = temp;
1122 ret[len++] = *p++;
1124 if (uri->port > 0) {
1125 if (len + 10 >= max) {
1126 temp = realloc2n(ret, &max);
1127 ret = temp;
1129 len += snprintf(&ret[len], max - len, ":%d", uri->port);
1131 } else if (uri->authority != NULL) {
1132 if (len + 3 >= max) {
1133 temp = realloc2n(ret, &max);
1134 ret = temp;
1136 ret[len++] = '/';
1137 ret[len++] = '/';
1138 p = uri->authority;
1139 while (*p != 0) {
1140 if (len + 3 >= max) {
1141 temp = realloc2n(ret, &max);
1142 ret = temp;
1144 if ((IS_UNRESERVED(*(p))) ||
1145 ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) ||
1146 ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1147 ((*(p) == '=')) || ((*(p) == '+')))
1148 ret[len++] = *p++;
1149 else {
1150 int val = *(unsigned char *)p++;
1151 int hi = val / 0x10, lo = val % 0x10;
1152 ret[len++] = '%';
1153 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1154 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1157 } else if (uri->scheme != NULL) {
1158 if (len + 3 >= max) {
1159 temp = realloc2n(ret, &max);
1160 ret = temp;
1162 ret[len++] = '/';
1163 ret[len++] = '/';
1165 if (uri->path != NULL) {
1166 p = uri->path;
1168 * the colon in file:///d: should not be escaped or
1169 * Windows accesses fail later.
1171 if ((uri->scheme != NULL) &&
1172 (p[0] == '/') &&
1173 (((p[1] >= 'a') && (p[1] <= 'z')) ||
1174 ((p[1] >= 'A') && (p[1] <= 'Z'))) &&
1175 (p[2] == ':') &&
1176 (!strcmp(uri->scheme, "file"))) {
1177 if (len + 3 >= max) {
1178 temp = realloc2n(ret, &max);
1179 ret = temp;
1181 ret[len++] = *p++;
1182 ret[len++] = *p++;
1183 ret[len++] = *p++;
1185 while (*p != 0) {
1186 if (len + 3 >= max) {
1187 temp = realloc2n(ret, &max);
1188 ret = temp;
1190 if ((IS_UNRESERVED(*(p))) || ((*(p) == '/')) ||
1191 ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1192 ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||
1193 ((*(p) == ',')))
1194 ret[len++] = *p++;
1195 else {
1196 int val = *(unsigned char *)p++;
1197 int hi = val / 0x10, lo = val % 0x10;
1198 ret[len++] = '%';
1199 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1200 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1204 if (uri->query != NULL) {
1205 if (len + 1 >= max) {
1206 temp = realloc2n(ret, &max);
1207 ret = temp;
1209 ret[len++] = '?';
1210 p = uri->query;
1211 while (*p != 0) {
1212 if (len + 1 >= max) {
1213 temp = realloc2n(ret, &max);
1214 ret = temp;
1216 ret[len++] = *p++;
1220 if (uri->fragment != NULL) {
1221 if (len + 3 >= max) {
1222 temp = realloc2n(ret, &max);
1223 ret = temp;
1225 ret[len++] = '#';
1226 p = uri->fragment;
1227 while (*p != 0) {
1228 if (len + 3 >= max) {
1229 temp = realloc2n(ret, &max);
1230 ret = temp;
1232 if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p))))
1233 ret[len++] = *p++;
1234 else {
1235 int val = *(unsigned char *)p++;
1236 int hi = val / 0x10, lo = val % 0x10;
1237 ret[len++] = '%';
1238 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1239 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1243 if (len >= max) {
1244 temp = realloc2n(ret, &max);
1245 ret = temp;
1247 ret[len] = 0;
1248 return(ret);
1252 * uri_clean:
1253 * @uri: pointer to an URI
1255 * Make sure the URI struct is free of content
1257 static void
1258 uri_clean(URI *uri) {
1259 if (uri == NULL) return;
1261 g_free(uri->scheme);
1262 uri->scheme = NULL;
1263 g_free(uri->server);
1264 uri->server = NULL;
1265 g_free(uri->user);
1266 uri->user = NULL;
1267 g_free(uri->path);
1268 uri->path = NULL;
1269 g_free(uri->fragment);
1270 uri->fragment = NULL;
1271 g_free(uri->opaque);
1272 uri->opaque = NULL;
1273 g_free(uri->authority);
1274 uri->authority = NULL;
1275 g_free(uri->query);
1276 uri->query = NULL;
1280 * uri_free:
1281 * @uri: pointer to an URI
1283 * Free up the URI struct
1285 void
1286 uri_free(URI *uri) {
1287 uri_clean(uri);
1288 g_free(uri);
1291 /************************************************************************
1293 * Helper functions *
1295 ************************************************************************/
1298 * normalize_uri_path:
1299 * @path: pointer to the path string
1301 * Applies the 5 normalization steps to a path string--that is, RFC 2396
1302 * Section 5.2, steps 6.c through 6.g.
1304 * Normalization occurs directly on the string, no new allocation is done
1306 * Returns 0 or an error code
1308 static int
1309 normalize_uri_path(char *path) {
1310 char *cur, *out;
1312 if (path == NULL)
1313 return(-1);
1315 /* Skip all initial "/" chars. We want to get to the beginning of the
1316 * first non-empty segment.
1318 cur = path;
1319 while (cur[0] == '/')
1320 ++cur;
1321 if (cur[0] == '\0')
1322 return(0);
1324 /* Keep everything we've seen so far. */
1325 out = cur;
1328 * Analyze each segment in sequence for cases (c) and (d).
1330 while (cur[0] != '\0') {
1332 * c) All occurrences of "./", where "." is a complete path segment,
1333 * are removed from the buffer string.
1335 if ((cur[0] == '.') && (cur[1] == '/')) {
1336 cur += 2;
1337 /* '//' normalization should be done at this point too */
1338 while (cur[0] == '/')
1339 cur++;
1340 continue;
1344 * d) If the buffer string ends with "." as a complete path segment,
1345 * that "." is removed.
1347 if ((cur[0] == '.') && (cur[1] == '\0'))
1348 break;
1350 /* Otherwise keep the segment. */
1351 while (cur[0] != '/') {
1352 if (cur[0] == '\0')
1353 goto done_cd;
1354 (out++)[0] = (cur++)[0];
1356 /* nomalize // */
1357 while ((cur[0] == '/') && (cur[1] == '/'))
1358 cur++;
1360 (out++)[0] = (cur++)[0];
1362 done_cd:
1363 out[0] = '\0';
1365 /* Reset to the beginning of the first segment for the next sequence. */
1366 cur = path;
1367 while (cur[0] == '/')
1368 ++cur;
1369 if (cur[0] == '\0')
1370 return(0);
1373 * Analyze each segment in sequence for cases (e) and (f).
1375 * e) All occurrences of "<segment>/../", where <segment> is a
1376 * complete path segment not equal to "..", are removed from the
1377 * buffer string. Removal of these path segments is performed
1378 * iteratively, removing the leftmost matching pattern on each
1379 * iteration, until no matching pattern remains.
1381 * f) If the buffer string ends with "<segment>/..", where <segment>
1382 * is a complete path segment not equal to "..", that
1383 * "<segment>/.." is removed.
1385 * To satisfy the "iterative" clause in (e), we need to collapse the
1386 * string every time we find something that needs to be removed. Thus,
1387 * we don't need to keep two pointers into the string: we only need a
1388 * "current position" pointer.
1390 while (1) {
1391 char *segp, *tmp;
1393 /* At the beginning of each iteration of this loop, "cur" points to
1394 * the first character of the segment we want to examine.
1397 /* Find the end of the current segment. */
1398 segp = cur;
1399 while ((segp[0] != '/') && (segp[0] != '\0'))
1400 ++segp;
1402 /* If this is the last segment, we're done (we need at least two
1403 * segments to meet the criteria for the (e) and (f) cases).
1405 if (segp[0] == '\0')
1406 break;
1408 /* If the first segment is "..", or if the next segment _isn't_ "..",
1409 * keep this segment and try the next one.
1411 ++segp;
1412 if (((cur[0] == '.') && (cur[1] == '.') && (segp == cur+3))
1413 || ((segp[0] != '.') || (segp[1] != '.')
1414 || ((segp[2] != '/') && (segp[2] != '\0')))) {
1415 cur = segp;
1416 continue;
1419 /* If we get here, remove this segment and the next one and back up
1420 * to the previous segment (if there is one), to implement the
1421 * "iteratively" clause. It's pretty much impossible to back up
1422 * while maintaining two pointers into the buffer, so just compact
1423 * the whole buffer now.
1426 /* If this is the end of the buffer, we're done. */
1427 if (segp[2] == '\0') {
1428 cur[0] = '\0';
1429 break;
1431 /* Valgrind complained, strcpy(cur, segp + 3); */
1432 /* string will overlap, do not use strcpy */
1433 tmp = cur;
1434 segp += 3;
1435 while ((*tmp++ = *segp++) != 0)
1438 /* If there are no previous segments, then keep going from here. */
1439 segp = cur;
1440 while ((segp > path) && ((--segp)[0] == '/'))
1442 if (segp == path)
1443 continue;
1445 /* "segp" is pointing to the end of a previous segment; find it's
1446 * start. We need to back up to the previous segment and start
1447 * over with that to handle things like "foo/bar/../..". If we
1448 * don't do this, then on the first pass we'll remove the "bar/..",
1449 * but be pointing at the second ".." so we won't realize we can also
1450 * remove the "foo/..".
1452 cur = segp;
1453 while ((cur > path) && (cur[-1] != '/'))
1454 --cur;
1456 out[0] = '\0';
1459 * g) If the resulting buffer string still begins with one or more
1460 * complete path segments of "..", then the reference is
1461 * considered to be in error. Implementations may handle this
1462 * error by retaining these components in the resolved path (i.e.,
1463 * treating them as part of the final URI), by removing them from
1464 * the resolved path (i.e., discarding relative levels above the
1465 * root), or by avoiding traversal of the reference.
1467 * We discard them from the final path.
1469 if (path[0] == '/') {
1470 cur = path;
1471 while ((cur[0] == '/') && (cur[1] == '.') && (cur[2] == '.')
1472 && ((cur[3] == '/') || (cur[3] == '\0')))
1473 cur += 3;
1475 if (cur != path) {
1476 out = path;
1477 while (cur[0] != '\0')
1478 (out++)[0] = (cur++)[0];
1479 out[0] = 0;
1483 return(0);
1486 static int is_hex(char c) {
1487 if (((c >= '0') && (c <= '9')) ||
1488 ((c >= 'a') && (c <= 'f')) ||
1489 ((c >= 'A') && (c <= 'F')))
1490 return(1);
1491 return(0);
1496 * uri_string_unescape:
1497 * @str: the string to unescape
1498 * @len: the length in bytes to unescape (or <= 0 to indicate full string)
1499 * @target: optional destination buffer
1501 * Unescaping routine, but does not check that the string is an URI. The
1502 * output is a direct unsigned char translation of %XX values (no encoding)
1503 * Note that the length of the result can only be smaller or same size as
1504 * the input string.
1506 * Returns a copy of the string, but unescaped, will return NULL only in case
1507 * of error
1509 char *
1510 uri_string_unescape(const char *str, int len, char *target) {
1511 char *ret, *out;
1512 const char *in;
1514 if (str == NULL)
1515 return(NULL);
1516 if (len <= 0) len = strlen(str);
1517 if (len < 0) return(NULL);
1519 if (target == NULL) {
1520 ret = g_malloc(len + 1);
1521 } else
1522 ret = target;
1523 in = str;
1524 out = ret;
1525 while(len > 0) {
1526 if ((len > 2) && (*in == '%') && (is_hex(in[1])) && (is_hex(in[2]))) {
1527 in++;
1528 if ((*in >= '0') && (*in <= '9'))
1529 *out = (*in - '0');
1530 else if ((*in >= 'a') && (*in <= 'f'))
1531 *out = (*in - 'a') + 10;
1532 else if ((*in >= 'A') && (*in <= 'F'))
1533 *out = (*in - 'A') + 10;
1534 in++;
1535 if ((*in >= '0') && (*in <= '9'))
1536 *out = *out * 16 + (*in - '0');
1537 else if ((*in >= 'a') && (*in <= 'f'))
1538 *out = *out * 16 + (*in - 'a') + 10;
1539 else if ((*in >= 'A') && (*in <= 'F'))
1540 *out = *out * 16 + (*in - 'A') + 10;
1541 in++;
1542 len -= 3;
1543 out++;
1544 } else {
1545 *out++ = *in++;
1546 len--;
1549 *out = 0;
1550 return(ret);
1554 * uri_string_escape:
1555 * @str: string to escape
1556 * @list: exception list string of chars not to escape
1558 * This routine escapes a string to hex, ignoring reserved characters (a-z)
1559 * and the characters in the exception list.
1561 * Returns a new escaped string or NULL in case of error.
1563 char *
1564 uri_string_escape(const char *str, const char *list) {
1565 char *ret, ch;
1566 char *temp;
1567 const char *in;
1568 int len, out;
1570 if (str == NULL)
1571 return(NULL);
1572 if (str[0] == 0)
1573 return(g_strdup(str));
1574 len = strlen(str);
1575 if (!(len > 0)) return(NULL);
1577 len += 20;
1578 ret = g_malloc(len);
1579 in = str;
1580 out = 0;
1581 while(*in != 0) {
1582 if (len - out <= 3) {
1583 temp = realloc2n(ret, &len);
1584 ret = temp;
1587 ch = *in;
1589 if ((ch != '@') && (!IS_UNRESERVED(ch)) && (!strchr(list, ch))) {
1590 unsigned char val;
1591 ret[out++] = '%';
1592 val = ch >> 4;
1593 if (val <= 9)
1594 ret[out++] = '0' + val;
1595 else
1596 ret[out++] = 'A' + val - 0xA;
1597 val = ch & 0xF;
1598 if (val <= 9)
1599 ret[out++] = '0' + val;
1600 else
1601 ret[out++] = 'A' + val - 0xA;
1602 in++;
1603 } else {
1604 ret[out++] = *in++;
1608 ret[out] = 0;
1609 return(ret);
1612 /************************************************************************
1614 * Public functions *
1616 ************************************************************************/
1619 * uri_resolve:
1620 * @URI: the URI instance found in the document
1621 * @base: the base value
1623 * Computes he final URI of the reference done by checking that
1624 * the given URI is valid, and building the final URI using the
1625 * base URI. This is processed according to section 5.2 of the
1626 * RFC 2396
1628 * 5.2. Resolving Relative References to Absolute Form
1630 * Returns a new URI string (to be freed by the caller) or NULL in case
1631 * of error.
1633 char *
1634 uri_resolve(const char *uri, const char *base) {
1635 char *val = NULL;
1636 int ret, len, indx, cur, out;
1637 URI *ref = NULL;
1638 URI *bas = NULL;
1639 URI *res = NULL;
1642 * 1) The URI reference is parsed into the potential four components and
1643 * fragment identifier, as described in Section 4.3.
1645 * NOTE that a completely empty URI is treated by modern browsers
1646 * as a reference to "." rather than as a synonym for the current
1647 * URI. Should we do that here?
1649 if (uri == NULL)
1650 ret = -1;
1651 else {
1652 if (*uri) {
1653 ref = uri_new();
1654 ret = uri_parse_into(ref, uri);
1656 else
1657 ret = 0;
1659 if (ret != 0)
1660 goto done;
1661 if ((ref != NULL) && (ref->scheme != NULL)) {
1663 * The URI is absolute don't modify.
1665 val = g_strdup(uri);
1666 goto done;
1668 if (base == NULL)
1669 ret = -1;
1670 else {
1671 bas = uri_new();
1672 ret = uri_parse_into(bas, base);
1674 if (ret != 0) {
1675 if (ref)
1676 val = uri_to_string(ref);
1677 goto done;
1679 if (ref == NULL) {
1681 * the base fragment must be ignored
1683 g_free(bas->fragment);
1684 bas->fragment = NULL;
1685 val = uri_to_string(bas);
1686 goto done;
1690 * 2) If the path component is empty and the scheme, authority, and
1691 * query components are undefined, then it is a reference to the
1692 * current document and we are done. Otherwise, the reference URI's
1693 * query and fragment components are defined as found (or not found)
1694 * within the URI reference and not inherited from the base URI.
1696 * NOTE that in modern browsers, the parsing differs from the above
1697 * in the following aspect: the query component is allowed to be
1698 * defined while still treating this as a reference to the current
1699 * document.
1701 res = uri_new();
1702 if ((ref->scheme == NULL) && (ref->path == NULL) &&
1703 ((ref->authority == NULL) && (ref->server == NULL))) {
1704 res->scheme = g_strdup(bas->scheme);
1705 if (bas->authority != NULL)
1706 res->authority = g_strdup(bas->authority);
1707 else if (bas->server != NULL) {
1708 res->server = g_strdup(bas->server);
1709 res->user = g_strdup(bas->user);
1710 res->port = bas->port;
1712 res->path = g_strdup(bas->path);
1713 if (ref->query != NULL) {
1714 res->query = g_strdup (ref->query);
1715 } else {
1716 res->query = g_strdup(bas->query);
1718 res->fragment = g_strdup(ref->fragment);
1719 goto step_7;
1723 * 3) If the scheme component is defined, indicating that the reference
1724 * starts with a scheme name, then the reference is interpreted as an
1725 * absolute URI and we are done. Otherwise, the reference URI's
1726 * scheme is inherited from the base URI's scheme component.
1728 if (ref->scheme != NULL) {
1729 val = uri_to_string(ref);
1730 goto done;
1732 res->scheme = g_strdup(bas->scheme);
1734 res->query = g_strdup(ref->query);
1735 res->fragment = g_strdup(ref->fragment);
1738 * 4) If the authority component is defined, then the reference is a
1739 * network-path and we skip to step 7. Otherwise, the reference
1740 * URI's authority is inherited from the base URI's authority
1741 * component, which will also be undefined if the URI scheme does not
1742 * use an authority component.
1744 if ((ref->authority != NULL) || (ref->server != NULL)) {
1745 if (ref->authority != NULL)
1746 res->authority = g_strdup(ref->authority);
1747 else {
1748 res->server = g_strdup(ref->server);
1749 res->user = g_strdup(ref->user);
1750 res->port = ref->port;
1752 res->path = g_strdup(ref->path);
1753 goto step_7;
1755 if (bas->authority != NULL)
1756 res->authority = g_strdup(bas->authority);
1757 else if (bas->server != NULL) {
1758 res->server = g_strdup(bas->server);
1759 res->user = g_strdup(bas->user);
1760 res->port = bas->port;
1764 * 5) If the path component begins with a slash character ("/"), then
1765 * the reference is an absolute-path and we skip to step 7.
1767 if ((ref->path != NULL) && (ref->path[0] == '/')) {
1768 res->path = g_strdup(ref->path);
1769 goto step_7;
1774 * 6) If this step is reached, then we are resolving a relative-path
1775 * reference. The relative path needs to be merged with the base
1776 * URI's path. Although there are many ways to do this, we will
1777 * describe a simple method using a separate string buffer.
1779 * Allocate a buffer large enough for the result string.
1781 len = 2; /* extra / and 0 */
1782 if (ref->path != NULL)
1783 len += strlen(ref->path);
1784 if (bas->path != NULL)
1785 len += strlen(bas->path);
1786 res->path = g_malloc(len);
1787 res->path[0] = 0;
1790 * a) All but the last segment of the base URI's path component is
1791 * copied to the buffer. In other words, any characters after the
1792 * last (right-most) slash character, if any, are excluded.
1794 cur = 0;
1795 out = 0;
1796 if (bas->path != NULL) {
1797 while (bas->path[cur] != 0) {
1798 while ((bas->path[cur] != 0) && (bas->path[cur] != '/'))
1799 cur++;
1800 if (bas->path[cur] == 0)
1801 break;
1803 cur++;
1804 while (out < cur) {
1805 res->path[out] = bas->path[out];
1806 out++;
1810 res->path[out] = 0;
1813 * b) The reference's path component is appended to the buffer
1814 * string.
1816 if (ref->path != NULL && ref->path[0] != 0) {
1817 indx = 0;
1819 * Ensure the path includes a '/'
1821 if ((out == 0) && (bas->server != NULL))
1822 res->path[out++] = '/';
1823 while (ref->path[indx] != 0) {
1824 res->path[out++] = ref->path[indx++];
1827 res->path[out] = 0;
1830 * Steps c) to h) are really path normalization steps
1832 normalize_uri_path(res->path);
1834 step_7:
1837 * 7) The resulting URI components, including any inherited from the
1838 * base URI, are recombined to give the absolute form of the URI
1839 * reference.
1841 val = uri_to_string(res);
1843 done:
1844 if (ref != NULL)
1845 uri_free(ref);
1846 if (bas != NULL)
1847 uri_free(bas);
1848 if (res != NULL)
1849 uri_free(res);
1850 return(val);
1854 * uri_resolve_relative:
1855 * @URI: the URI reference under consideration
1856 * @base: the base value
1858 * Expresses the URI of the reference in terms relative to the
1859 * base. Some examples of this operation include:
1860 * base = "http://site1.com/docs/book1.html"
1861 * URI input URI returned
1862 * docs/pic1.gif pic1.gif
1863 * docs/img/pic1.gif img/pic1.gif
1864 * img/pic1.gif ../img/pic1.gif
1865 * http://site1.com/docs/pic1.gif pic1.gif
1866 * http://site2.com/docs/pic1.gif http://site2.com/docs/pic1.gif
1868 * base = "docs/book1.html"
1869 * URI input URI returned
1870 * docs/pic1.gif pic1.gif
1871 * docs/img/pic1.gif img/pic1.gif
1872 * img/pic1.gif ../img/pic1.gif
1873 * http://site1.com/docs/pic1.gif http://site1.com/docs/pic1.gif
1876 * Note: if the URI reference is really weird or complicated, it may be
1877 * worthwhile to first convert it into a "nice" one by calling
1878 * uri_resolve (using 'base') before calling this routine,
1879 * since this routine (for reasonable efficiency) assumes URI has
1880 * already been through some validation.
1882 * Returns a new URI string (to be freed by the caller) or NULL in case
1883 * error.
1885 char *
1886 uri_resolve_relative (const char *uri, const char * base)
1888 char *val = NULL;
1889 int ret;
1890 int ix;
1891 int pos = 0;
1892 int nbslash = 0;
1893 int len;
1894 URI *ref = NULL;
1895 URI *bas = NULL;
1896 char *bptr, *uptr, *vptr;
1897 int remove_path = 0;
1899 if ((uri == NULL) || (*uri == 0))
1900 return NULL;
1903 * First parse URI into a standard form
1905 ref = uri_new ();
1906 /* If URI not already in "relative" form */
1907 if (uri[0] != '.') {
1908 ret = uri_parse_into (ref, uri);
1909 if (ret != 0)
1910 goto done; /* Error in URI, return NULL */
1911 } else
1912 ref->path = g_strdup(uri);
1915 * Next parse base into the same standard form
1917 if ((base == NULL) || (*base == 0)) {
1918 val = g_strdup (uri);
1919 goto done;
1921 bas = uri_new ();
1922 if (base[0] != '.') {
1923 ret = uri_parse_into (bas, base);
1924 if (ret != 0)
1925 goto done; /* Error in base, return NULL */
1926 } else
1927 bas->path = g_strdup(base);
1930 * If the scheme / server on the URI differs from the base,
1931 * just return the URI
1933 if ((ref->scheme != NULL) &&
1934 ((bas->scheme == NULL) ||
1935 (strcmp (bas->scheme, ref->scheme)) ||
1936 (strcmp (bas->server, ref->server)))) {
1937 val = g_strdup (uri);
1938 goto done;
1940 if (bas->path == ref->path ||
1941 (bas->path && ref->path && !strcmp(bas->path, ref->path))) {
1942 val = g_strdup("");
1943 goto done;
1945 if (bas->path == NULL) {
1946 val = g_strdup(ref->path);
1947 goto done;
1949 if (ref->path == NULL) {
1950 ref->path = (char *) "/";
1951 remove_path = 1;
1955 * At this point (at last!) we can compare the two paths
1957 * First we take care of the special case where either of the
1958 * two path components may be missing (bug 316224)
1960 if (bas->path == NULL) {
1961 if (ref->path != NULL) {
1962 uptr = ref->path;
1963 if (*uptr == '/')
1964 uptr++;
1965 /* exception characters from uri_to_string */
1966 val = uri_string_escape(uptr, "/;&=+$,");
1968 goto done;
1970 bptr = bas->path;
1971 if (ref->path == NULL) {
1972 for (ix = 0; bptr[ix] != 0; ix++) {
1973 if (bptr[ix] == '/')
1974 nbslash++;
1976 uptr = NULL;
1977 len = 1; /* this is for a string terminator only */
1978 } else {
1980 * Next we compare the two strings and find where they first differ
1982 if ((ref->path[pos] == '.') && (ref->path[pos+1] == '/'))
1983 pos += 2;
1984 if ((*bptr == '.') && (bptr[1] == '/'))
1985 bptr += 2;
1986 else if ((*bptr == '/') && (ref->path[pos] != '/'))
1987 bptr++;
1988 while ((bptr[pos] == ref->path[pos]) && (bptr[pos] != 0))
1989 pos++;
1991 if (bptr[pos] == ref->path[pos]) {
1992 val = g_strdup("");
1993 goto done; /* (I can't imagine why anyone would do this) */
1997 * In URI, "back up" to the last '/' encountered. This will be the
1998 * beginning of the "unique" suffix of URI
2000 ix = pos;
2001 if ((ref->path[ix] == '/') && (ix > 0))
2002 ix--;
2003 else if ((ref->path[ix] == 0) && (ix > 1) && (ref->path[ix - 1] == '/'))
2004 ix -= 2;
2005 for (; ix > 0; ix--) {
2006 if (ref->path[ix] == '/')
2007 break;
2009 if (ix == 0) {
2010 uptr = ref->path;
2011 } else {
2012 ix++;
2013 uptr = &ref->path[ix];
2017 * In base, count the number of '/' from the differing point
2019 if (bptr[pos] != ref->path[pos]) {/* check for trivial URI == base */
2020 for (; bptr[ix] != 0; ix++) {
2021 if (bptr[ix] == '/')
2022 nbslash++;
2025 len = strlen (uptr) + 1;
2028 if (nbslash == 0) {
2029 if (uptr != NULL)
2030 /* exception characters from uri_to_string */
2031 val = uri_string_escape(uptr, "/;&=+$,");
2032 goto done;
2036 * Allocate just enough space for the returned string -
2037 * length of the remainder of the URI, plus enough space
2038 * for the "../" groups, plus one for the terminator
2040 val = g_malloc (len + 3 * nbslash);
2041 vptr = val;
2043 * Put in as many "../" as needed
2045 for (; nbslash>0; nbslash--) {
2046 *vptr++ = '.';
2047 *vptr++ = '.';
2048 *vptr++ = '/';
2051 * Finish up with the end of the URI
2053 if (uptr != NULL) {
2054 if ((vptr > val) && (len > 0) &&
2055 (uptr[0] == '/') && (vptr[-1] == '/')) {
2056 memcpy (vptr, uptr + 1, len - 1);
2057 vptr[len - 2] = 0;
2058 } else {
2059 memcpy (vptr, uptr, len);
2060 vptr[len - 1] = 0;
2062 } else {
2063 vptr[len - 1] = 0;
2066 /* escape the freshly-built path */
2067 vptr = val;
2068 /* exception characters from uri_to_string */
2069 val = uri_string_escape(vptr, "/;&=+$,");
2070 g_free(vptr);
2072 done:
2074 * Free the working variables
2076 if (remove_path != 0)
2077 ref->path = NULL;
2078 if (ref != NULL)
2079 uri_free (ref);
2080 if (bas != NULL)
2081 uri_free (bas);
2083 return val;
2087 * Utility functions to help parse and assemble query strings.
2090 struct QueryParams *
2091 query_params_new (int init_alloc)
2093 struct QueryParams *ps;
2095 if (init_alloc <= 0) init_alloc = 1;
2097 ps = g_new(QueryParams, 1);
2098 ps->n = 0;
2099 ps->alloc = init_alloc;
2100 ps->p = g_new(QueryParam, ps->alloc);
2102 return ps;
2105 /* Ensure there is space to store at least one more parameter
2106 * at the end of the set.
2108 static int
2109 query_params_append (struct QueryParams *ps,
2110 const char *name, const char *value)
2112 if (ps->n >= ps->alloc) {
2113 ps->p = g_renew(QueryParam, ps->p, ps->alloc * 2);
2114 ps->alloc *= 2;
2117 ps->p[ps->n].name = g_strdup(name);
2118 ps->p[ps->n].value = g_strdup(value);
2119 ps->p[ps->n].ignore = 0;
2120 ps->n++;
2122 return 0;
2125 void
2126 query_params_free (struct QueryParams *ps)
2128 int i;
2130 for (i = 0; i < ps->n; ++i) {
2131 g_free (ps->p[i].name);
2132 g_free (ps->p[i].value);
2134 g_free (ps->p);
2135 g_free (ps);
2138 struct QueryParams *
2139 query_params_parse (const char *query)
2141 struct QueryParams *ps;
2142 const char *end, *eq;
2144 ps = query_params_new (0);
2145 if (!query || query[0] == '\0') return ps;
2147 while (*query) {
2148 char *name = NULL, *value = NULL;
2150 /* Find the next separator, or end of the string. */
2151 end = strchr (query, '&');
2152 if (!end)
2153 end = strchr (query, ';');
2154 if (!end)
2155 end = query + strlen (query);
2157 /* Find the first '=' character between here and end. */
2158 eq = strchr (query, '=');
2159 if (eq && eq >= end) eq = NULL;
2161 /* Empty section (eg. "&&"). */
2162 if (end == query)
2163 goto next;
2165 /* If there is no '=' character, then we have just "name"
2166 * and consistent with CGI.pm we assume value is "".
2168 else if (!eq) {
2169 name = uri_string_unescape (query, end - query, NULL);
2170 value = NULL;
2172 /* Or if we have "name=" here (works around annoying
2173 * problem when calling uri_string_unescape with len = 0).
2175 else if (eq+1 == end) {
2176 name = uri_string_unescape (query, eq - query, NULL);
2177 value = g_new0(char, 1);
2179 /* If the '=' character is at the beginning then we have
2180 * "=value" and consistent with CGI.pm we _ignore_ this.
2182 else if (query == eq)
2183 goto next;
2185 /* Otherwise it's "name=value". */
2186 else {
2187 name = uri_string_unescape (query, eq - query, NULL);
2188 value = uri_string_unescape (eq+1, end - (eq+1), NULL);
2191 /* Append to the parameter set. */
2192 query_params_append (ps, name, value);
2193 g_free(name);
2194 g_free(value);
2196 next:
2197 query = end;
2198 if (*query) query ++; /* skip '&' separator */
2201 return ps;