util: Drop superfluous conditionals around g_free()
[qemu/ar7.git] / util / uri.c
blob01dc09effb0000e44180f3c1bd6e39293b63cd6d
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 <glib.h>
55 #include <string.h>
56 #include <stdio.h>
58 #include "qemu/uri.h"
60 static void uri_clean(URI *uri);
63 * Old rule from 2396 used in legacy handling code
64 * alpha = lowalpha | upalpha
66 #define IS_ALPHA(x) (IS_LOWALPHA(x) || IS_UPALPHA(x))
70 * lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" |
71 * "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" |
72 * "u" | "v" | "w" | "x" | "y" | "z"
75 #define IS_LOWALPHA(x) (((x) >= 'a') && ((x) <= 'z'))
78 * upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" |
79 * "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" |
80 * "U" | "V" | "W" | "X" | "Y" | "Z"
82 #define IS_UPALPHA(x) (((x) >= 'A') && ((x) <= 'Z'))
84 #ifdef IS_DIGIT
85 #undef IS_DIGIT
86 #endif
88 * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
90 #define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9'))
93 * alphanum = alpha | digit
96 #define IS_ALPHANUM(x) (IS_ALPHA(x) || IS_DIGIT(x))
99 * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
102 #define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') || \
103 ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') || \
104 ((x) == '(') || ((x) == ')'))
107 * unwise = "{" | "}" | "|" | "\" | "^" | "`"
110 #define IS_UNWISE(p) \
111 (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) || \
112 ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) || \
113 ((*(p) == ']')) || ((*(p) == '`')))
115 * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
116 * "[" | "]"
119 #define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') || \
120 ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') || \
121 ((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \
122 ((x) == ']'))
125 * unreserved = alphanum | mark
128 #define IS_UNRESERVED(x) (IS_ALPHANUM(x) || IS_MARK(x))
131 * Skip to next pointer char, handle escaped sequences
134 #define NEXT(p) ((*p == '%')? p += 3 : p++)
137 * Productions from the spec.
139 * authority = server | reg_name
140 * reg_name = 1*( unreserved | escaped | "$" | "," |
141 * ";" | ":" | "@" | "&" | "=" | "+" )
143 * path = [ abs_path | opaque_part ]
147 /************************************************************************
149 * RFC 3986 parser *
151 ************************************************************************/
153 #define ISA_DIGIT(p) ((*(p) >= '0') && (*(p) <= '9'))
154 #define ISA_ALPHA(p) (((*(p) >= 'a') && (*(p) <= 'z')) || \
155 ((*(p) >= 'A') && (*(p) <= 'Z')))
156 #define ISA_HEXDIG(p) \
157 (ISA_DIGIT(p) || ((*(p) >= 'a') && (*(p) <= 'f')) || \
158 ((*(p) >= 'A') && (*(p) <= 'F')))
161 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
162 * / "*" / "+" / "," / ";" / "="
164 #define ISA_SUB_DELIM(p) \
165 (((*(p) == '!')) || ((*(p) == '$')) || ((*(p) == '&')) || \
166 ((*(p) == '(')) || ((*(p) == ')')) || ((*(p) == '*')) || \
167 ((*(p) == '+')) || ((*(p) == ',')) || ((*(p) == ';')) || \
168 ((*(p) == '=')) || ((*(p) == '\'')))
171 * gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
173 #define ISA_GEN_DELIM(p) \
174 (((*(p) == ':')) || ((*(p) == '/')) || ((*(p) == '?')) || \
175 ((*(p) == '#')) || ((*(p) == '[')) || ((*(p) == ']')) || \
176 ((*(p) == '@')))
179 * reserved = gen-delims / sub-delims
181 #define ISA_RESERVED(p) (ISA_GEN_DELIM(p) || (ISA_SUB_DELIM(p)))
184 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
186 #define ISA_UNRESERVED(p) \
187 ((ISA_ALPHA(p)) || (ISA_DIGIT(p)) || ((*(p) == '-')) || \
188 ((*(p) == '.')) || ((*(p) == '_')) || ((*(p) == '~')))
191 * pct-encoded = "%" HEXDIG HEXDIG
193 #define ISA_PCT_ENCODED(p) \
194 ((*(p) == '%') && (ISA_HEXDIG(p + 1)) && (ISA_HEXDIG(p + 2)))
197 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
199 #define ISA_PCHAR(p) \
200 (ISA_UNRESERVED(p) || ISA_PCT_ENCODED(p) || ISA_SUB_DELIM(p) || \
201 ((*(p) == ':')) || ((*(p) == '@')))
204 * rfc3986_parse_scheme:
205 * @uri: pointer to an URI structure
206 * @str: pointer to the string to analyze
208 * Parse an URI scheme
210 * ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
212 * Returns 0 or the error code
214 static int
215 rfc3986_parse_scheme(URI *uri, const char **str) {
216 const char *cur;
218 if (str == NULL)
219 return(-1);
221 cur = *str;
222 if (!ISA_ALPHA(cur))
223 return(2);
224 cur++;
225 while (ISA_ALPHA(cur) || ISA_DIGIT(cur) ||
226 (*cur == '+') || (*cur == '-') || (*cur == '.')) cur++;
227 if (uri != NULL) {
228 g_free(uri->scheme);
229 uri->scheme = g_strndup(*str, cur - *str);
231 *str = cur;
232 return(0);
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
251 rfc3986_parse_fragment(URI *uri, const char **str)
253 const char *cur;
255 if (str == NULL)
256 return (-1);
258 cur = *str;
260 while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
261 (*cur == '[') || (*cur == ']') ||
262 ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
263 NEXT(cur);
264 if (uri != NULL) {
265 g_free(uri->fragment);
266 if (uri->cleanup & 2)
267 uri->fragment = g_strndup(*str, cur - *str);
268 else
269 uri->fragment = uri_string_unescape(*str, cur - *str, NULL);
271 *str = cur;
272 return (0);
276 * rfc3986_parse_query:
277 * @uri: pointer to an URI structure
278 * @str: pointer to the string to analyze
280 * Parse the query part of an URI
282 * query = *uric
284 * Returns 0 or the error code
286 static int
287 rfc3986_parse_query(URI *uri, const char **str)
289 const char *cur;
291 if (str == NULL)
292 return (-1);
294 cur = *str;
296 while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
297 ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
298 NEXT(cur);
299 if (uri != NULL) {
300 g_free(uri->query);
301 uri->query = g_strndup (*str, cur - *str);
303 *str = cur;
304 return (0);
308 * rfc3986_parse_port:
309 * @uri: pointer to an URI structure
310 * @str: the string to analyze
312 * Parse a port part and fills in the appropriate fields
313 * of the @uri structure
315 * port = *DIGIT
317 * Returns 0 or the error code
319 static int
320 rfc3986_parse_port(URI *uri, const char **str)
322 const char *cur = *str;
324 if (ISA_DIGIT(cur)) {
325 if (uri != NULL)
326 uri->port = 0;
327 while (ISA_DIGIT(cur)) {
328 if (uri != NULL)
329 uri->port = uri->port * 10 + (*cur - '0');
330 cur++;
332 *str = cur;
333 return(0);
335 return(1);
339 * rfc3986_parse_user_info:
340 * @uri: pointer to an URI structure
341 * @str: the string to analyze
343 * Parse an user informations part and fills in the appropriate fields
344 * of the @uri structure
346 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
348 * Returns 0 or the error code
350 static int
351 rfc3986_parse_user_info(URI *uri, const char **str)
353 const char *cur;
355 cur = *str;
356 while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) ||
357 ISA_SUB_DELIM(cur) || (*cur == ':'))
358 NEXT(cur);
359 if (*cur == '@') {
360 if (uri != NULL) {
361 g_free(uri->user);
362 if (uri->cleanup & 2)
363 uri->user = g_strndup(*str, cur - *str);
364 else
365 uri->user = uri_string_unescape(*str, cur - *str, NULL);
367 *str = cur;
368 return(0);
370 return(1);
374 * rfc3986_parse_dec_octet:
375 * @str: the string to analyze
377 * dec-octet = DIGIT ; 0-9
378 * / %x31-39 DIGIT ; 10-99
379 * / "1" 2DIGIT ; 100-199
380 * / "2" %x30-34 DIGIT ; 200-249
381 * / "25" %x30-35 ; 250-255
383 * Skip a dec-octet.
385 * Returns 0 if found and skipped, 1 otherwise
387 static int
388 rfc3986_parse_dec_octet(const char **str) {
389 const char *cur = *str;
391 if (!(ISA_DIGIT(cur)))
392 return(1);
393 if (!ISA_DIGIT(cur+1))
394 cur++;
395 else if ((*cur != '0') && (ISA_DIGIT(cur + 1)) && (!ISA_DIGIT(cur+2)))
396 cur += 2;
397 else if ((*cur == '1') && (ISA_DIGIT(cur + 1)) && (ISA_DIGIT(cur + 2)))
398 cur += 3;
399 else if ((*cur == '2') && (*(cur + 1) >= '0') &&
400 (*(cur + 1) <= '4') && (ISA_DIGIT(cur + 2)))
401 cur += 3;
402 else if ((*cur == '2') && (*(cur + 1) == '5') &&
403 (*(cur + 2) >= '0') && (*(cur + 1) <= '5'))
404 cur += 3;
405 else
406 return(1);
407 *str = cur;
408 return(0);
411 * rfc3986_parse_host:
412 * @uri: pointer to an URI structure
413 * @str: the string to analyze
415 * Parse an host part and fills in the appropriate fields
416 * of the @uri structure
418 * host = IP-literal / IPv4address / reg-name
419 * IP-literal = "[" ( IPv6address / IPvFuture ) "]"
420 * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
421 * reg-name = *( unreserved / pct-encoded / sub-delims )
423 * Returns 0 or the error code
425 static int
426 rfc3986_parse_host(URI *uri, const char **str)
428 const char *cur = *str;
429 const char *host;
431 host = cur;
433 * IPv6 and future addressing scheme are enclosed between brackets
435 if (*cur == '[') {
436 cur++;
437 while ((*cur != ']') && (*cur != 0))
438 cur++;
439 if (*cur != ']')
440 return(1);
441 cur++;
442 goto found;
445 * try to parse an IPv4
447 if (ISA_DIGIT(cur)) {
448 if (rfc3986_parse_dec_octet(&cur) != 0)
449 goto not_ipv4;
450 if (*cur != '.')
451 goto not_ipv4;
452 cur++;
453 if (rfc3986_parse_dec_octet(&cur) != 0)
454 goto not_ipv4;
455 if (*cur != '.')
456 goto not_ipv4;
457 if (rfc3986_parse_dec_octet(&cur) != 0)
458 goto not_ipv4;
459 if (*cur != '.')
460 goto not_ipv4;
461 if (rfc3986_parse_dec_octet(&cur) != 0)
462 goto not_ipv4;
463 goto found;
464 not_ipv4:
465 cur = *str;
468 * then this should be a hostname which can be empty
470 while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) || ISA_SUB_DELIM(cur))
471 NEXT(cur);
472 found:
473 if (uri != NULL) {
474 g_free(uri->authority);
475 uri->authority = NULL;
476 g_free(uri->server);
477 if (cur != host) {
478 if (uri->cleanup & 2)
479 uri->server = g_strndup(host, cur - host);
480 else
481 uri->server = uri_string_unescape(host, cur - host, NULL);
482 } else
483 uri->server = NULL;
485 *str = cur;
486 return(0);
490 * rfc3986_parse_authority:
491 * @uri: pointer to an URI structure
492 * @str: the string to analyze
494 * Parse an authority part and fills in the appropriate fields
495 * of the @uri structure
497 * authority = [ userinfo "@" ] host [ ":" port ]
499 * Returns 0 or the error code
501 static int
502 rfc3986_parse_authority(URI *uri, const char **str)
504 const char *cur;
505 int ret;
507 cur = *str;
509 * try to parse an userinfo and check for the trailing @
511 ret = rfc3986_parse_user_info(uri, &cur);
512 if ((ret != 0) || (*cur != '@'))
513 cur = *str;
514 else
515 cur++;
516 ret = rfc3986_parse_host(uri, &cur);
517 if (ret != 0) return(ret);
518 if (*cur == ':') {
519 cur++;
520 ret = rfc3986_parse_port(uri, &cur);
521 if (ret != 0) return(ret);
523 *str = cur;
524 return(0);
528 * rfc3986_parse_segment:
529 * @str: the string to analyze
530 * @forbid: an optional forbidden character
531 * @empty: allow an empty segment
533 * Parse a segment and fills in the appropriate fields
534 * of the @uri structure
536 * segment = *pchar
537 * segment-nz = 1*pchar
538 * segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
539 * ; non-zero-length segment without any colon ":"
541 * Returns 0 or the error code
543 static int
544 rfc3986_parse_segment(const char **str, char forbid, int empty)
546 const char *cur;
548 cur = *str;
549 if (!ISA_PCHAR(cur)) {
550 if (empty)
551 return(0);
552 return(1);
554 while (ISA_PCHAR(cur) && (*cur != forbid))
555 NEXT(cur);
556 *str = cur;
557 return (0);
561 * rfc3986_parse_path_ab_empty:
562 * @uri: pointer to an URI structure
563 * @str: the string to analyze
565 * Parse an path absolute or empty and fills in the appropriate fields
566 * of the @uri structure
568 * path-abempty = *( "/" segment )
570 * Returns 0 or the error code
572 static int
573 rfc3986_parse_path_ab_empty(URI *uri, const char **str)
575 const char *cur;
576 int ret;
578 cur = *str;
580 while (*cur == '/') {
581 cur++;
582 ret = rfc3986_parse_segment(&cur, 0, 1);
583 if (ret != 0) return(ret);
585 if (uri != NULL) {
586 g_free(uri->path);
587 if (*str != cur) {
588 if (uri->cleanup & 2)
589 uri->path = g_strndup(*str, cur - *str);
590 else
591 uri->path = uri_string_unescape(*str, cur - *str, NULL);
592 } else {
593 uri->path = NULL;
596 *str = cur;
597 return (0);
601 * rfc3986_parse_path_absolute:
602 * @uri: pointer to an URI structure
603 * @str: the string to analyze
605 * Parse an path absolute and fills in the appropriate fields
606 * of the @uri structure
608 * path-absolute = "/" [ segment-nz *( "/" segment ) ]
610 * Returns 0 or the error code
612 static int
613 rfc3986_parse_path_absolute(URI *uri, const char **str)
615 const char *cur;
616 int ret;
618 cur = *str;
620 if (*cur != '/')
621 return(1);
622 cur++;
623 ret = rfc3986_parse_segment(&cur, 0, 0);
624 if (ret == 0) {
625 while (*cur == '/') {
626 cur++;
627 ret = rfc3986_parse_segment(&cur, 0, 1);
628 if (ret != 0) return(ret);
631 if (uri != NULL) {
632 g_free(uri->path);
633 if (cur != *str) {
634 if (uri->cleanup & 2)
635 uri->path = g_strndup(*str, cur - *str);
636 else
637 uri->path = uri_string_unescape(*str, cur - *str, NULL);
638 } else {
639 uri->path = NULL;
642 *str = cur;
643 return (0);
647 * rfc3986_parse_path_rootless:
648 * @uri: pointer to an URI structure
649 * @str: the string to analyze
651 * Parse an path without root and fills in the appropriate fields
652 * of the @uri structure
654 * path-rootless = segment-nz *( "/" segment )
656 * Returns 0 or the error code
658 static int
659 rfc3986_parse_path_rootless(URI *uri, const char **str)
661 const char *cur;
662 int ret;
664 cur = *str;
666 ret = rfc3986_parse_segment(&cur, 0, 0);
667 if (ret != 0) return(ret);
668 while (*cur == '/') {
669 cur++;
670 ret = rfc3986_parse_segment(&cur, 0, 1);
671 if (ret != 0) return(ret);
673 if (uri != NULL) {
674 g_free(uri->path);
675 if (cur != *str) {
676 if (uri->cleanup & 2)
677 uri->path = g_strndup(*str, cur - *str);
678 else
679 uri->path = uri_string_unescape(*str, cur - *str, NULL);
680 } else {
681 uri->path = NULL;
684 *str = cur;
685 return (0);
689 * rfc3986_parse_path_no_scheme:
690 * @uri: pointer to an URI structure
691 * @str: the string to analyze
693 * Parse an path which is not a scheme and fills in the appropriate fields
694 * of the @uri structure
696 * path-noscheme = segment-nz-nc *( "/" segment )
698 * Returns 0 or the error code
700 static int
701 rfc3986_parse_path_no_scheme(URI *uri, const char **str)
703 const char *cur;
704 int ret;
706 cur = *str;
708 ret = rfc3986_parse_segment(&cur, ':', 0);
709 if (ret != 0) return(ret);
710 while (*cur == '/') {
711 cur++;
712 ret = rfc3986_parse_segment(&cur, 0, 1);
713 if (ret != 0) return(ret);
715 if (uri != NULL) {
716 g_free(uri->path);
717 if (cur != *str) {
718 if (uri->cleanup & 2)
719 uri->path = g_strndup(*str, cur - *str);
720 else
721 uri->path = uri_string_unescape(*str, cur - *str, NULL);
722 } else {
723 uri->path = NULL;
726 *str = cur;
727 return (0);
731 * rfc3986_parse_hier_part:
732 * @uri: pointer to an URI structure
733 * @str: the string to analyze
735 * Parse an hierarchical part and fills in the appropriate fields
736 * of the @uri structure
738 * hier-part = "//" authority path-abempty
739 * / path-absolute
740 * / path-rootless
741 * / path-empty
743 * Returns 0 or the error code
745 static int
746 rfc3986_parse_hier_part(URI *uri, const char **str)
748 const char *cur;
749 int ret;
751 cur = *str;
753 if ((*cur == '/') && (*(cur + 1) == '/')) {
754 cur += 2;
755 ret = rfc3986_parse_authority(uri, &cur);
756 if (ret != 0) return(ret);
757 ret = rfc3986_parse_path_ab_empty(uri, &cur);
758 if (ret != 0) return(ret);
759 *str = cur;
760 return(0);
761 } else if (*cur == '/') {
762 ret = rfc3986_parse_path_absolute(uri, &cur);
763 if (ret != 0) return(ret);
764 } else if (ISA_PCHAR(cur)) {
765 ret = rfc3986_parse_path_rootless(uri, &cur);
766 if (ret != 0) return(ret);
767 } else {
768 /* path-empty is effectively empty */
769 if (uri != NULL) {
770 g_free(uri->path);
771 uri->path = NULL;
774 *str = cur;
775 return (0);
779 * rfc3986_parse_relative_ref:
780 * @uri: pointer to an URI structure
781 * @str: the string to analyze
783 * Parse an URI string and fills in the appropriate fields
784 * of the @uri structure
786 * relative-ref = relative-part [ "?" query ] [ "#" fragment ]
787 * relative-part = "//" authority path-abempty
788 * / path-absolute
789 * / path-noscheme
790 * / path-empty
792 * Returns 0 or the error code
794 static int
795 rfc3986_parse_relative_ref(URI *uri, const char *str) {
796 int ret;
798 if ((*str == '/') && (*(str + 1) == '/')) {
799 str += 2;
800 ret = rfc3986_parse_authority(uri, &str);
801 if (ret != 0) return(ret);
802 ret = rfc3986_parse_path_ab_empty(uri, &str);
803 if (ret != 0) return(ret);
804 } else if (*str == '/') {
805 ret = rfc3986_parse_path_absolute(uri, &str);
806 if (ret != 0) return(ret);
807 } else if (ISA_PCHAR(str)) {
808 ret = rfc3986_parse_path_no_scheme(uri, &str);
809 if (ret != 0) return(ret);
810 } else {
811 /* path-empty is effectively empty */
812 if (uri != NULL) {
813 g_free(uri->path);
814 uri->path = NULL;
818 if (*str == '?') {
819 str++;
820 ret = rfc3986_parse_query(uri, &str);
821 if (ret != 0) return(ret);
823 if (*str == '#') {
824 str++;
825 ret = rfc3986_parse_fragment(uri, &str);
826 if (ret != 0) return(ret);
828 if (*str != 0) {
829 uri_clean(uri);
830 return(1);
832 return(0);
837 * rfc3986_parse:
838 * @uri: pointer to an URI structure
839 * @str: the string to analyze
841 * Parse an URI string and fills in the appropriate fields
842 * of the @uri structure
844 * scheme ":" hier-part [ "?" query ] [ "#" fragment ]
846 * Returns 0 or the error code
848 static int
849 rfc3986_parse(URI *uri, const char *str) {
850 int ret;
852 ret = rfc3986_parse_scheme(uri, &str);
853 if (ret != 0) return(ret);
854 if (*str != ':') {
855 return(1);
857 str++;
858 ret = rfc3986_parse_hier_part(uri, &str);
859 if (ret != 0) return(ret);
860 if (*str == '?') {
861 str++;
862 ret = rfc3986_parse_query(uri, &str);
863 if (ret != 0) return(ret);
865 if (*str == '#') {
866 str++;
867 ret = rfc3986_parse_fragment(uri, &str);
868 if (ret != 0) return(ret);
870 if (*str != 0) {
871 uri_clean(uri);
872 return(1);
874 return(0);
878 * rfc3986_parse_uri_reference:
879 * @uri: pointer to an URI structure
880 * @str: the string to analyze
882 * Parse an URI reference string and fills in the appropriate fields
883 * of the @uri structure
885 * URI-reference = URI / relative-ref
887 * Returns 0 or the error code
889 static int
890 rfc3986_parse_uri_reference(URI *uri, const char *str) {
891 int ret;
893 if (str == NULL)
894 return(-1);
895 uri_clean(uri);
898 * Try first to parse absolute refs, then fallback to relative if
899 * it fails.
901 ret = rfc3986_parse(uri, str);
902 if (ret != 0) {
903 uri_clean(uri);
904 ret = rfc3986_parse_relative_ref(uri, str);
905 if (ret != 0) {
906 uri_clean(uri);
907 return(ret);
910 return(0);
914 * uri_parse:
915 * @str: the URI string to analyze
917 * Parse an URI based on RFC 3986
919 * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
921 * Returns a newly built URI or NULL in case of error
923 URI *
924 uri_parse(const char *str) {
925 URI *uri;
926 int ret;
928 if (str == NULL)
929 return(NULL);
930 uri = uri_new();
931 if (uri != NULL) {
932 ret = rfc3986_parse_uri_reference(uri, str);
933 if (ret) {
934 uri_free(uri);
935 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 (uri != NULL) {
978 if (raw) {
979 uri->cleanup |= 2;
981 ret = uri_parse_into(uri, str);
982 if (ret) {
983 uri_free(uri);
984 return(NULL);
987 return(uri);
990 /************************************************************************
992 * Generic URI structure functions *
994 ************************************************************************/
997 * uri_new:
999 * Simply creates an empty URI
1001 * Returns the new structure or NULL in case of error
1003 URI *
1004 uri_new(void) {
1005 URI *ret;
1007 ret = (URI *) g_malloc(sizeof(URI));
1008 memset(ret, 0, sizeof(URI));
1009 return(ret);
1013 * realloc2n:
1015 * Function to handle properly a reallocation when saving an URI
1016 * Also imposes some limit on the length of an URI string output
1018 static char *
1019 realloc2n(char *ret, int *max) {
1020 char *temp;
1021 int tmp;
1023 tmp = *max * 2;
1024 temp = g_realloc(ret, (tmp + 1));
1025 *max = tmp;
1026 return(temp);
1030 * uri_to_string:
1031 * @uri: pointer to an URI
1033 * Save the URI as an escaped string
1035 * Returns a new string (to be deallocated by caller)
1037 char *
1038 uri_to_string(URI *uri) {
1039 char *ret = NULL;
1040 char *temp;
1041 const char *p;
1042 int len;
1043 int max;
1045 if (uri == NULL) return(NULL);
1048 max = 80;
1049 ret = g_malloc(max + 1);
1050 len = 0;
1052 if (uri->scheme != NULL) {
1053 p = uri->scheme;
1054 while (*p != 0) {
1055 if (len >= max) {
1056 temp = realloc2n(ret, &max);
1057 if (temp == NULL) goto mem_error;
1058 ret = temp;
1060 ret[len++] = *p++;
1062 if (len >= max) {
1063 temp = realloc2n(ret, &max);
1064 if (temp == NULL) goto mem_error;
1065 ret = temp;
1067 ret[len++] = ':';
1069 if (uri->opaque != NULL) {
1070 p = uri->opaque;
1071 while (*p != 0) {
1072 if (len + 3 >= max) {
1073 temp = realloc2n(ret, &max);
1074 if (temp == NULL) goto mem_error;
1075 ret = temp;
1077 if (IS_RESERVED(*(p)) || IS_UNRESERVED(*(p)))
1078 ret[len++] = *p++;
1079 else {
1080 int val = *(unsigned char *)p++;
1081 int hi = val / 0x10, lo = val % 0x10;
1082 ret[len++] = '%';
1083 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1084 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1087 } else {
1088 if (uri->server != NULL) {
1089 if (len + 3 >= max) {
1090 temp = realloc2n(ret, &max);
1091 if (temp == NULL) goto mem_error;
1092 ret = temp;
1094 ret[len++] = '/';
1095 ret[len++] = '/';
1096 if (uri->user != NULL) {
1097 p = uri->user;
1098 while (*p != 0) {
1099 if (len + 3 >= max) {
1100 temp = realloc2n(ret, &max);
1101 if (temp == NULL) goto mem_error;
1102 ret = temp;
1104 if ((IS_UNRESERVED(*(p))) ||
1105 ((*(p) == ';')) || ((*(p) == ':')) ||
1106 ((*(p) == '&')) || ((*(p) == '=')) ||
1107 ((*(p) == '+')) || ((*(p) == '$')) ||
1108 ((*(p) == ',')))
1109 ret[len++] = *p++;
1110 else {
1111 int val = *(unsigned char *)p++;
1112 int hi = val / 0x10, lo = val % 0x10;
1113 ret[len++] = '%';
1114 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1115 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1118 if (len + 3 >= max) {
1119 temp = realloc2n(ret, &max);
1120 if (temp == NULL) goto mem_error;
1121 ret = temp;
1123 ret[len++] = '@';
1125 p = uri->server;
1126 while (*p != 0) {
1127 if (len >= max) {
1128 temp = realloc2n(ret, &max);
1129 if (temp == NULL) goto mem_error;
1130 ret = temp;
1132 ret[len++] = *p++;
1134 if (uri->port > 0) {
1135 if (len + 10 >= max) {
1136 temp = realloc2n(ret, &max);
1137 if (temp == NULL) goto mem_error;
1138 ret = temp;
1140 len += snprintf(&ret[len], max - len, ":%d", uri->port);
1142 } else if (uri->authority != NULL) {
1143 if (len + 3 >= max) {
1144 temp = realloc2n(ret, &max);
1145 if (temp == NULL) goto mem_error;
1146 ret = temp;
1148 ret[len++] = '/';
1149 ret[len++] = '/';
1150 p = uri->authority;
1151 while (*p != 0) {
1152 if (len + 3 >= max) {
1153 temp = realloc2n(ret, &max);
1154 if (temp == NULL) goto mem_error;
1155 ret = temp;
1157 if ((IS_UNRESERVED(*(p))) ||
1158 ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) ||
1159 ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1160 ((*(p) == '=')) || ((*(p) == '+')))
1161 ret[len++] = *p++;
1162 else {
1163 int val = *(unsigned char *)p++;
1164 int hi = val / 0x10, lo = val % 0x10;
1165 ret[len++] = '%';
1166 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1167 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1170 } else if (uri->scheme != NULL) {
1171 if (len + 3 >= max) {
1172 temp = realloc2n(ret, &max);
1173 if (temp == NULL) goto mem_error;
1174 ret = temp;
1176 ret[len++] = '/';
1177 ret[len++] = '/';
1179 if (uri->path != NULL) {
1180 p = uri->path;
1182 * the colon in file:///d: should not be escaped or
1183 * Windows accesses fail later.
1185 if ((uri->scheme != NULL) &&
1186 (p[0] == '/') &&
1187 (((p[1] >= 'a') && (p[1] <= 'z')) ||
1188 ((p[1] >= 'A') && (p[1] <= 'Z'))) &&
1189 (p[2] == ':') &&
1190 (!strcmp(uri->scheme, "file"))) {
1191 if (len + 3 >= max) {
1192 temp = realloc2n(ret, &max);
1193 if (temp == NULL) goto mem_error;
1194 ret = temp;
1196 ret[len++] = *p++;
1197 ret[len++] = *p++;
1198 ret[len++] = *p++;
1200 while (*p != 0) {
1201 if (len + 3 >= max) {
1202 temp = realloc2n(ret, &max);
1203 if (temp == NULL) goto mem_error;
1204 ret = temp;
1206 if ((IS_UNRESERVED(*(p))) || ((*(p) == '/')) ||
1207 ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1208 ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||
1209 ((*(p) == ',')))
1210 ret[len++] = *p++;
1211 else {
1212 int val = *(unsigned char *)p++;
1213 int hi = val / 0x10, lo = val % 0x10;
1214 ret[len++] = '%';
1215 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1216 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1220 if (uri->query != NULL) {
1221 if (len + 1 >= max) {
1222 temp = realloc2n(ret, &max);
1223 if (temp == NULL) goto mem_error;
1224 ret = temp;
1226 ret[len++] = '?';
1227 p = uri->query;
1228 while (*p != 0) {
1229 if (len + 1 >= max) {
1230 temp = realloc2n(ret, &max);
1231 if (temp == NULL) goto mem_error;
1232 ret = temp;
1234 ret[len++] = *p++;
1238 if (uri->fragment != NULL) {
1239 if (len + 3 >= max) {
1240 temp = realloc2n(ret, &max);
1241 if (temp == NULL) goto mem_error;
1242 ret = temp;
1244 ret[len++] = '#';
1245 p = uri->fragment;
1246 while (*p != 0) {
1247 if (len + 3 >= max) {
1248 temp = realloc2n(ret, &max);
1249 if (temp == NULL) goto mem_error;
1250 ret = temp;
1252 if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p))))
1253 ret[len++] = *p++;
1254 else {
1255 int val = *(unsigned char *)p++;
1256 int hi = val / 0x10, lo = val % 0x10;
1257 ret[len++] = '%';
1258 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1259 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1263 if (len >= max) {
1264 temp = realloc2n(ret, &max);
1265 if (temp == NULL) goto mem_error;
1266 ret = temp;
1268 ret[len] = 0;
1269 return(ret);
1271 mem_error:
1272 g_free(ret);
1273 return(NULL);
1277 * uri_clean:
1278 * @uri: pointer to an URI
1280 * Make sure the URI struct is free of content
1282 static void
1283 uri_clean(URI *uri) {
1284 if (uri == NULL) return;
1286 g_free(uri->scheme);
1287 uri->scheme = NULL;
1288 g_free(uri->server);
1289 uri->server = NULL;
1290 g_free(uri->user);
1291 uri->user = NULL;
1292 g_free(uri->path);
1293 uri->path = NULL;
1294 g_free(uri->fragment);
1295 uri->fragment = NULL;
1296 g_free(uri->opaque);
1297 uri->opaque = NULL;
1298 g_free(uri->authority);
1299 uri->authority = NULL;
1300 g_free(uri->query);
1301 uri->query = NULL;
1305 * uri_free:
1306 * @uri: pointer to an URI
1308 * Free up the URI struct
1310 void
1311 uri_free(URI *uri) {
1312 uri_clean(uri);
1313 g_free(uri);
1316 /************************************************************************
1318 * Helper functions *
1320 ************************************************************************/
1323 * normalize_uri_path:
1324 * @path: pointer to the path string
1326 * Applies the 5 normalization steps to a path string--that is, RFC 2396
1327 * Section 5.2, steps 6.c through 6.g.
1329 * Normalization occurs directly on the string, no new allocation is done
1331 * Returns 0 or an error code
1333 static int
1334 normalize_uri_path(char *path) {
1335 char *cur, *out;
1337 if (path == NULL)
1338 return(-1);
1340 /* Skip all initial "/" chars. We want to get to the beginning of the
1341 * first non-empty segment.
1343 cur = path;
1344 while (cur[0] == '/')
1345 ++cur;
1346 if (cur[0] == '\0')
1347 return(0);
1349 /* Keep everything we've seen so far. */
1350 out = cur;
1353 * Analyze each segment in sequence for cases (c) and (d).
1355 while (cur[0] != '\0') {
1357 * c) All occurrences of "./", where "." is a complete path segment,
1358 * are removed from the buffer string.
1360 if ((cur[0] == '.') && (cur[1] == '/')) {
1361 cur += 2;
1362 /* '//' normalization should be done at this point too */
1363 while (cur[0] == '/')
1364 cur++;
1365 continue;
1369 * d) If the buffer string ends with "." as a complete path segment,
1370 * that "." is removed.
1372 if ((cur[0] == '.') && (cur[1] == '\0'))
1373 break;
1375 /* Otherwise keep the segment. */
1376 while (cur[0] != '/') {
1377 if (cur[0] == '\0')
1378 goto done_cd;
1379 (out++)[0] = (cur++)[0];
1381 /* nomalize // */
1382 while ((cur[0] == '/') && (cur[1] == '/'))
1383 cur++;
1385 (out++)[0] = (cur++)[0];
1387 done_cd:
1388 out[0] = '\0';
1390 /* Reset to the beginning of the first segment for the next sequence. */
1391 cur = path;
1392 while (cur[0] == '/')
1393 ++cur;
1394 if (cur[0] == '\0')
1395 return(0);
1398 * Analyze each segment in sequence for cases (e) and (f).
1400 * e) All occurrences of "<segment>/../", where <segment> is a
1401 * complete path segment not equal to "..", are removed from the
1402 * buffer string. Removal of these path segments is performed
1403 * iteratively, removing the leftmost matching pattern on each
1404 * iteration, until no matching pattern remains.
1406 * f) If the buffer string ends with "<segment>/..", where <segment>
1407 * is a complete path segment not equal to "..", that
1408 * "<segment>/.." is removed.
1410 * To satisfy the "iterative" clause in (e), we need to collapse the
1411 * string every time we find something that needs to be removed. Thus,
1412 * we don't need to keep two pointers into the string: we only need a
1413 * "current position" pointer.
1415 while (1) {
1416 char *segp, *tmp;
1418 /* At the beginning of each iteration of this loop, "cur" points to
1419 * the first character of the segment we want to examine.
1422 /* Find the end of the current segment. */
1423 segp = cur;
1424 while ((segp[0] != '/') && (segp[0] != '\0'))
1425 ++segp;
1427 /* If this is the last segment, we're done (we need at least two
1428 * segments to meet the criteria for the (e) and (f) cases).
1430 if (segp[0] == '\0')
1431 break;
1433 /* If the first segment is "..", or if the next segment _isn't_ "..",
1434 * keep this segment and try the next one.
1436 ++segp;
1437 if (((cur[0] == '.') && (cur[1] == '.') && (segp == cur+3))
1438 || ((segp[0] != '.') || (segp[1] != '.')
1439 || ((segp[2] != '/') && (segp[2] != '\0')))) {
1440 cur = segp;
1441 continue;
1444 /* If we get here, remove this segment and the next one and back up
1445 * to the previous segment (if there is one), to implement the
1446 * "iteratively" clause. It's pretty much impossible to back up
1447 * while maintaining two pointers into the buffer, so just compact
1448 * the whole buffer now.
1451 /* If this is the end of the buffer, we're done. */
1452 if (segp[2] == '\0') {
1453 cur[0] = '\0';
1454 break;
1456 /* Valgrind complained, strcpy(cur, segp + 3); */
1457 /* string will overlap, do not use strcpy */
1458 tmp = cur;
1459 segp += 3;
1460 while ((*tmp++ = *segp++) != 0)
1463 /* If there are no previous segments, then keep going from here. */
1464 segp = cur;
1465 while ((segp > path) && ((--segp)[0] == '/'))
1467 if (segp == path)
1468 continue;
1470 /* "segp" is pointing to the end of a previous segment; find it's
1471 * start. We need to back up to the previous segment and start
1472 * over with that to handle things like "foo/bar/../..". If we
1473 * don't do this, then on the first pass we'll remove the "bar/..",
1474 * but be pointing at the second ".." so we won't realize we can also
1475 * remove the "foo/..".
1477 cur = segp;
1478 while ((cur > path) && (cur[-1] != '/'))
1479 --cur;
1481 out[0] = '\0';
1484 * g) If the resulting buffer string still begins with one or more
1485 * complete path segments of "..", then the reference is
1486 * considered to be in error. Implementations may handle this
1487 * error by retaining these components in the resolved path (i.e.,
1488 * treating them as part of the final URI), by removing them from
1489 * the resolved path (i.e., discarding relative levels above the
1490 * root), or by avoiding traversal of the reference.
1492 * We discard them from the final path.
1494 if (path[0] == '/') {
1495 cur = path;
1496 while ((cur[0] == '/') && (cur[1] == '.') && (cur[2] == '.')
1497 && ((cur[3] == '/') || (cur[3] == '\0')))
1498 cur += 3;
1500 if (cur != path) {
1501 out = path;
1502 while (cur[0] != '\0')
1503 (out++)[0] = (cur++)[0];
1504 out[0] = 0;
1508 return(0);
1511 static int is_hex(char c) {
1512 if (((c >= '0') && (c <= '9')) ||
1513 ((c >= 'a') && (c <= 'f')) ||
1514 ((c >= 'A') && (c <= 'F')))
1515 return(1);
1516 return(0);
1521 * uri_string_unescape:
1522 * @str: the string to unescape
1523 * @len: the length in bytes to unescape (or <= 0 to indicate full string)
1524 * @target: optional destination buffer
1526 * Unescaping routine, but does not check that the string is an URI. The
1527 * output is a direct unsigned char translation of %XX values (no encoding)
1528 * Note that the length of the result can only be smaller or same size as
1529 * the input string.
1531 * Returns a copy of the string, but unescaped, will return NULL only in case
1532 * of error
1534 char *
1535 uri_string_unescape(const char *str, int len, char *target) {
1536 char *ret, *out;
1537 const char *in;
1539 if (str == NULL)
1540 return(NULL);
1541 if (len <= 0) len = strlen(str);
1542 if (len < 0) return(NULL);
1544 if (target == NULL) {
1545 ret = g_malloc(len + 1);
1546 } else
1547 ret = target;
1548 in = str;
1549 out = ret;
1550 while(len > 0) {
1551 if ((len > 2) && (*in == '%') && (is_hex(in[1])) && (is_hex(in[2]))) {
1552 in++;
1553 if ((*in >= '0') && (*in <= '9'))
1554 *out = (*in - '0');
1555 else if ((*in >= 'a') && (*in <= 'f'))
1556 *out = (*in - 'a') + 10;
1557 else if ((*in >= 'A') && (*in <= 'F'))
1558 *out = (*in - 'A') + 10;
1559 in++;
1560 if ((*in >= '0') && (*in <= '9'))
1561 *out = *out * 16 + (*in - '0');
1562 else if ((*in >= 'a') && (*in <= 'f'))
1563 *out = *out * 16 + (*in - 'a') + 10;
1564 else if ((*in >= 'A') && (*in <= 'F'))
1565 *out = *out * 16 + (*in - 'A') + 10;
1566 in++;
1567 len -= 3;
1568 out++;
1569 } else {
1570 *out++ = *in++;
1571 len--;
1574 *out = 0;
1575 return(ret);
1579 * uri_string_escape:
1580 * @str: string to escape
1581 * @list: exception list string of chars not to escape
1583 * This routine escapes a string to hex, ignoring reserved characters (a-z)
1584 * and the characters in the exception list.
1586 * Returns a new escaped string or NULL in case of error.
1588 char *
1589 uri_string_escape(const char *str, const char *list) {
1590 char *ret, ch;
1591 char *temp;
1592 const char *in;
1593 int len, out;
1595 if (str == NULL)
1596 return(NULL);
1597 if (str[0] == 0)
1598 return(g_strdup(str));
1599 len = strlen(str);
1600 if (!(len > 0)) return(NULL);
1602 len += 20;
1603 ret = g_malloc(len);
1604 in = str;
1605 out = 0;
1606 while(*in != 0) {
1607 if (len - out <= 3) {
1608 temp = realloc2n(ret, &len);
1609 ret = temp;
1612 ch = *in;
1614 if ((ch != '@') && (!IS_UNRESERVED(ch)) && (!strchr(list, ch))) {
1615 unsigned char val;
1616 ret[out++] = '%';
1617 val = ch >> 4;
1618 if (val <= 9)
1619 ret[out++] = '0' + val;
1620 else
1621 ret[out++] = 'A' + val - 0xA;
1622 val = ch & 0xF;
1623 if (val <= 9)
1624 ret[out++] = '0' + val;
1625 else
1626 ret[out++] = 'A' + val - 0xA;
1627 in++;
1628 } else {
1629 ret[out++] = *in++;
1633 ret[out] = 0;
1634 return(ret);
1637 /************************************************************************
1639 * Public functions *
1641 ************************************************************************/
1644 * uri_resolve:
1645 * @URI: the URI instance found in the document
1646 * @base: the base value
1648 * Computes he final URI of the reference done by checking that
1649 * the given URI is valid, and building the final URI using the
1650 * base URI. This is processed according to section 5.2 of the
1651 * RFC 2396
1653 * 5.2. Resolving Relative References to Absolute Form
1655 * Returns a new URI string (to be freed by the caller) or NULL in case
1656 * of error.
1658 char *
1659 uri_resolve(const char *uri, const char *base) {
1660 char *val = NULL;
1661 int ret, len, indx, cur, out;
1662 URI *ref = NULL;
1663 URI *bas = NULL;
1664 URI *res = NULL;
1667 * 1) The URI reference is parsed into the potential four components and
1668 * fragment identifier, as described in Section 4.3.
1670 * NOTE that a completely empty URI is treated by modern browsers
1671 * as a reference to "." rather than as a synonym for the current
1672 * URI. Should we do that here?
1674 if (uri == NULL)
1675 ret = -1;
1676 else {
1677 if (*uri) {
1678 ref = uri_new();
1679 if (ref == NULL)
1680 goto done;
1681 ret = uri_parse_into(ref, uri);
1683 else
1684 ret = 0;
1686 if (ret != 0)
1687 goto done;
1688 if ((ref != NULL) && (ref->scheme != NULL)) {
1690 * The URI is absolute don't modify.
1692 val = g_strdup(uri);
1693 goto done;
1695 if (base == NULL)
1696 ret = -1;
1697 else {
1698 bas = uri_new();
1699 if (bas == NULL)
1700 goto done;
1701 ret = uri_parse_into(bas, base);
1703 if (ret != 0) {
1704 if (ref)
1705 val = uri_to_string(ref);
1706 goto done;
1708 if (ref == NULL) {
1710 * the base fragment must be ignored
1712 g_free(bas->fragment);
1713 bas->fragment = NULL;
1714 val = uri_to_string(bas);
1715 goto done;
1719 * 2) If the path component is empty and the scheme, authority, and
1720 * query components are undefined, then it is a reference to the
1721 * current document and we are done. Otherwise, the reference URI's
1722 * query and fragment components are defined as found (or not found)
1723 * within the URI reference and not inherited from the base URI.
1725 * NOTE that in modern browsers, the parsing differs from the above
1726 * in the following aspect: the query component is allowed to be
1727 * defined while still treating this as a reference to the current
1728 * document.
1730 res = uri_new();
1731 if (res == NULL)
1732 goto done;
1733 if ((ref->scheme == NULL) && (ref->path == NULL) &&
1734 ((ref->authority == NULL) && (ref->server == NULL))) {
1735 res->scheme = g_strdup(bas->scheme);
1736 if (bas->authority != NULL)
1737 res->authority = g_strdup(bas->authority);
1738 else if (bas->server != NULL) {
1739 res->server = g_strdup(bas->server);
1740 res->user = g_strdup(bas->user);
1741 res->port = bas->port;
1743 res->path = g_strdup(bas->path);
1744 if (ref->query != NULL) {
1745 res->query = g_strdup (ref->query);
1746 } else {
1747 res->query = g_strdup(bas->query);
1749 res->fragment = g_strdup(ref->fragment);
1750 goto step_7;
1754 * 3) If the scheme component is defined, indicating that the reference
1755 * starts with a scheme name, then the reference is interpreted as an
1756 * absolute URI and we are done. Otherwise, the reference URI's
1757 * scheme is inherited from the base URI's scheme component.
1759 if (ref->scheme != NULL) {
1760 val = uri_to_string(ref);
1761 goto done;
1763 res->scheme = g_strdup(bas->scheme);
1765 res->query = g_strdup(ref->query);
1766 res->fragment = g_strdup(ref->fragment);
1769 * 4) If the authority component is defined, then the reference is a
1770 * network-path and we skip to step 7. Otherwise, the reference
1771 * URI's authority is inherited from the base URI's authority
1772 * component, which will also be undefined if the URI scheme does not
1773 * use an authority component.
1775 if ((ref->authority != NULL) || (ref->server != NULL)) {
1776 if (ref->authority != NULL)
1777 res->authority = g_strdup(ref->authority);
1778 else {
1779 res->server = g_strdup(ref->server);
1780 res->user = g_strdup(ref->user);
1781 res->port = ref->port;
1783 res->path = g_strdup(ref->path);
1784 goto step_7;
1786 if (bas->authority != NULL)
1787 res->authority = g_strdup(bas->authority);
1788 else if (bas->server != NULL) {
1789 res->server = g_strdup(bas->server);
1790 res->user = g_strdup(bas->user);
1791 res->port = bas->port;
1795 * 5) If the path component begins with a slash character ("/"), then
1796 * the reference is an absolute-path and we skip to step 7.
1798 if ((ref->path != NULL) && (ref->path[0] == '/')) {
1799 res->path = g_strdup(ref->path);
1800 goto step_7;
1805 * 6) If this step is reached, then we are resolving a relative-path
1806 * reference. The relative path needs to be merged with the base
1807 * URI's path. Although there are many ways to do this, we will
1808 * describe a simple method using a separate string buffer.
1810 * Allocate a buffer large enough for the result string.
1812 len = 2; /* extra / and 0 */
1813 if (ref->path != NULL)
1814 len += strlen(ref->path);
1815 if (bas->path != NULL)
1816 len += strlen(bas->path);
1817 res->path = g_malloc(len);
1818 res->path[0] = 0;
1821 * a) All but the last segment of the base URI's path component is
1822 * copied to the buffer. In other words, any characters after the
1823 * last (right-most) slash character, if any, are excluded.
1825 cur = 0;
1826 out = 0;
1827 if (bas->path != NULL) {
1828 while (bas->path[cur] != 0) {
1829 while ((bas->path[cur] != 0) && (bas->path[cur] != '/'))
1830 cur++;
1831 if (bas->path[cur] == 0)
1832 break;
1834 cur++;
1835 while (out < cur) {
1836 res->path[out] = bas->path[out];
1837 out++;
1841 res->path[out] = 0;
1844 * b) The reference's path component is appended to the buffer
1845 * string.
1847 if (ref->path != NULL && ref->path[0] != 0) {
1848 indx = 0;
1850 * Ensure the path includes a '/'
1852 if ((out == 0) && (bas->server != NULL))
1853 res->path[out++] = '/';
1854 while (ref->path[indx] != 0) {
1855 res->path[out++] = ref->path[indx++];
1858 res->path[out] = 0;
1861 * Steps c) to h) are really path normalization steps
1863 normalize_uri_path(res->path);
1865 step_7:
1868 * 7) The resulting URI components, including any inherited from the
1869 * base URI, are recombined to give the absolute form of the URI
1870 * reference.
1872 val = uri_to_string(res);
1874 done:
1875 if (ref != NULL)
1876 uri_free(ref);
1877 if (bas != NULL)
1878 uri_free(bas);
1879 if (res != NULL)
1880 uri_free(res);
1881 return(val);
1885 * uri_resolve_relative:
1886 * @URI: the URI reference under consideration
1887 * @base: the base value
1889 * Expresses the URI of the reference in terms relative to the
1890 * base. Some examples of this operation include:
1891 * base = "http://site1.com/docs/book1.html"
1892 * URI input URI returned
1893 * docs/pic1.gif pic1.gif
1894 * docs/img/pic1.gif img/pic1.gif
1895 * img/pic1.gif ../img/pic1.gif
1896 * http://site1.com/docs/pic1.gif pic1.gif
1897 * http://site2.com/docs/pic1.gif http://site2.com/docs/pic1.gif
1899 * base = "docs/book1.html"
1900 * URI input URI returned
1901 * docs/pic1.gif pic1.gif
1902 * docs/img/pic1.gif img/pic1.gif
1903 * img/pic1.gif ../img/pic1.gif
1904 * http://site1.com/docs/pic1.gif http://site1.com/docs/pic1.gif
1907 * Note: if the URI reference is really weird or complicated, it may be
1908 * worthwhile to first convert it into a "nice" one by calling
1909 * uri_resolve (using 'base') before calling this routine,
1910 * since this routine (for reasonable efficiency) assumes URI has
1911 * already been through some validation.
1913 * Returns a new URI string (to be freed by the caller) or NULL in case
1914 * error.
1916 char *
1917 uri_resolve_relative (const char *uri, const char * base)
1919 char *val = NULL;
1920 int ret;
1921 int ix;
1922 int pos = 0;
1923 int nbslash = 0;
1924 int len;
1925 URI *ref = NULL;
1926 URI *bas = NULL;
1927 char *bptr, *uptr, *vptr;
1928 int remove_path = 0;
1930 if ((uri == NULL) || (*uri == 0))
1931 return NULL;
1934 * First parse URI into a standard form
1936 ref = uri_new ();
1937 if (ref == NULL)
1938 return NULL;
1939 /* If URI not already in "relative" form */
1940 if (uri[0] != '.') {
1941 ret = uri_parse_into (ref, uri);
1942 if (ret != 0)
1943 goto done; /* Error in URI, return NULL */
1944 } else
1945 ref->path = g_strdup(uri);
1948 * Next parse base into the same standard form
1950 if ((base == NULL) || (*base == 0)) {
1951 val = g_strdup (uri);
1952 goto done;
1954 bas = uri_new ();
1955 if (bas == NULL)
1956 goto done;
1957 if (base[0] != '.') {
1958 ret = uri_parse_into (bas, base);
1959 if (ret != 0)
1960 goto done; /* Error in base, return NULL */
1961 } else
1962 bas->path = g_strdup(base);
1965 * If the scheme / server on the URI differs from the base,
1966 * just return the URI
1968 if ((ref->scheme != NULL) &&
1969 ((bas->scheme == NULL) ||
1970 (strcmp (bas->scheme, ref->scheme)) ||
1971 (strcmp (bas->server, ref->server)))) {
1972 val = g_strdup (uri);
1973 goto done;
1975 if (!strcmp(bas->path, ref->path)) {
1976 val = g_strdup("");
1977 goto done;
1979 if (bas->path == NULL) {
1980 val = g_strdup(ref->path);
1981 goto done;
1983 if (ref->path == NULL) {
1984 ref->path = (char *) "/";
1985 remove_path = 1;
1989 * At this point (at last!) we can compare the two paths
1991 * First we take care of the special case where either of the
1992 * two path components may be missing (bug 316224)
1994 if (bas->path == NULL) {
1995 if (ref->path != NULL) {
1996 uptr = ref->path;
1997 if (*uptr == '/')
1998 uptr++;
1999 /* exception characters from uri_to_string */
2000 val = uri_string_escape(uptr, "/;&=+$,");
2002 goto done;
2004 bptr = bas->path;
2005 if (ref->path == NULL) {
2006 for (ix = 0; bptr[ix] != 0; ix++) {
2007 if (bptr[ix] == '/')
2008 nbslash++;
2010 uptr = NULL;
2011 len = 1; /* this is for a string terminator only */
2012 } else {
2014 * Next we compare the two strings and find where they first differ
2016 if ((ref->path[pos] == '.') && (ref->path[pos+1] == '/'))
2017 pos += 2;
2018 if ((*bptr == '.') && (bptr[1] == '/'))
2019 bptr += 2;
2020 else if ((*bptr == '/') && (ref->path[pos] != '/'))
2021 bptr++;
2022 while ((bptr[pos] == ref->path[pos]) && (bptr[pos] != 0))
2023 pos++;
2025 if (bptr[pos] == ref->path[pos]) {
2026 val = g_strdup("");
2027 goto done; /* (I can't imagine why anyone would do this) */
2031 * In URI, "back up" to the last '/' encountered. This will be the
2032 * beginning of the "unique" suffix of URI
2034 ix = pos;
2035 if ((ref->path[ix] == '/') && (ix > 0))
2036 ix--;
2037 else if ((ref->path[ix] == 0) && (ix > 1) && (ref->path[ix - 1] == '/'))
2038 ix -= 2;
2039 for (; ix > 0; ix--) {
2040 if (ref->path[ix] == '/')
2041 break;
2043 if (ix == 0) {
2044 uptr = ref->path;
2045 } else {
2046 ix++;
2047 uptr = &ref->path[ix];
2051 * In base, count the number of '/' from the differing point
2053 if (bptr[pos] != ref->path[pos]) {/* check for trivial URI == base */
2054 for (; bptr[ix] != 0; ix++) {
2055 if (bptr[ix] == '/')
2056 nbslash++;
2059 len = strlen (uptr) + 1;
2062 if (nbslash == 0) {
2063 if (uptr != NULL)
2064 /* exception characters from uri_to_string */
2065 val = uri_string_escape(uptr, "/;&=+$,");
2066 goto done;
2070 * Allocate just enough space for the returned string -
2071 * length of the remainder of the URI, plus enough space
2072 * for the "../" groups, plus one for the terminator
2074 val = g_malloc (len + 3 * nbslash);
2075 vptr = val;
2077 * Put in as many "../" as needed
2079 for (; nbslash>0; nbslash--) {
2080 *vptr++ = '.';
2081 *vptr++ = '.';
2082 *vptr++ = '/';
2085 * Finish up with the end of the URI
2087 if (uptr != NULL) {
2088 if ((vptr > val) && (len > 0) &&
2089 (uptr[0] == '/') && (vptr[-1] == '/')) {
2090 memcpy (vptr, uptr + 1, len - 1);
2091 vptr[len - 2] = 0;
2092 } else {
2093 memcpy (vptr, uptr, len);
2094 vptr[len - 1] = 0;
2096 } else {
2097 vptr[len - 1] = 0;
2100 /* escape the freshly-built path */
2101 vptr = val;
2102 /* exception characters from uri_to_string */
2103 val = uri_string_escape(vptr, "/;&=+$,");
2104 g_free(vptr);
2106 done:
2108 * Free the working variables
2110 if (remove_path != 0)
2111 ref->path = NULL;
2112 if (ref != NULL)
2113 uri_free (ref);
2114 if (bas != NULL)
2115 uri_free (bas);
2117 return val;
2121 * Utility functions to help parse and assemble query strings.
2124 struct QueryParams *
2125 query_params_new (int init_alloc)
2127 struct QueryParams *ps;
2129 if (init_alloc <= 0) init_alloc = 1;
2131 ps = g_new(QueryParams, 1);
2132 ps->n = 0;
2133 ps->alloc = init_alloc;
2134 ps->p = g_new(QueryParam, ps->alloc);
2136 return ps;
2139 /* Ensure there is space to store at least one more parameter
2140 * at the end of the set.
2142 static int
2143 query_params_append (struct QueryParams *ps,
2144 const char *name, const char *value)
2146 if (ps->n >= ps->alloc) {
2147 ps->p = g_renew(QueryParam, ps->p, ps->alloc * 2);
2148 ps->alloc *= 2;
2151 ps->p[ps->n].name = g_strdup(name);
2152 ps->p[ps->n].value = g_strdup(value);
2153 ps->p[ps->n].ignore = 0;
2154 ps->n++;
2156 return 0;
2159 void
2160 query_params_free (struct QueryParams *ps)
2162 int i;
2164 for (i = 0; i < ps->n; ++i) {
2165 g_free (ps->p[i].name);
2166 g_free (ps->p[i].value);
2168 g_free (ps->p);
2169 g_free (ps);
2172 struct QueryParams *
2173 query_params_parse (const char *query)
2175 struct QueryParams *ps;
2176 const char *end, *eq;
2178 ps = query_params_new (0);
2179 if (!query || query[0] == '\0') return ps;
2181 while (*query) {
2182 char *name = NULL, *value = NULL;
2184 /* Find the next separator, or end of the string. */
2185 end = strchr (query, '&');
2186 if (!end)
2187 end = strchr (query, ';');
2188 if (!end)
2189 end = query + strlen (query);
2191 /* Find the first '=' character between here and end. */
2192 eq = strchr (query, '=');
2193 if (eq && eq >= end) eq = NULL;
2195 /* Empty section (eg. "&&"). */
2196 if (end == query)
2197 goto next;
2199 /* If there is no '=' character, then we have just "name"
2200 * and consistent with CGI.pm we assume value is "".
2202 else if (!eq) {
2203 name = uri_string_unescape (query, end - query, NULL);
2204 value = NULL;
2206 /* Or if we have "name=" here (works around annoying
2207 * problem when calling uri_string_unescape with len = 0).
2209 else if (eq+1 == end) {
2210 name = uri_string_unescape (query, eq - query, NULL);
2211 value = g_new0(char, 1);
2213 /* If the '=' character is at the beginning then we have
2214 * "=value" and consistent with CGI.pm we _ignore_ this.
2216 else if (query == eq)
2217 goto next;
2219 /* Otherwise it's "name=value". */
2220 else {
2221 name = uri_string_unescape (query, eq - query, NULL);
2222 value = uri_string_unescape (eq+1, end - (eq+1), NULL);
2225 /* Append to the parameter set. */
2226 query_params_append (ps, name, value);
2227 g_free(name);
2228 g_free(value);
2230 next:
2231 query = end;
2232 if (*query) query ++; /* skip '&' separator */
2235 return ps;