]> Git Repo - qemu.git/blob - util/uri.c
iotests: Fix 051's reference output
[qemu.git] / util / uri.c
1 /**
2  * uri.c: set of generic URI related routines
3  *
4  * Reference: RFCs 3986, 2732 and 2373
5  *
6  * Copyright (C) 1998-2003 Daniel Veillard.  All Rights Reserved.
7  *
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:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
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.
24  *
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.
28  *
29  * [email protected]
30  *
31  **
32  *
33  * Copyright (C) 2007, 2009-2010 Red Hat, Inc.
34  *
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.
39  *
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.
44  *
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
48  *
49  * Authors:
50  *    Richard W.M. Jones <[email protected]>
51  *
52  */
53
54 #include <glib.h>
55 #include <string.h>
56 #include <stdio.h>
57
58 #include "qemu/uri.h"
59
60 static void uri_clean(URI *uri);
61
62 /*
63  * Old rule from 2396 used in legacy handling code
64  * alpha    = lowalpha | upalpha
65  */
66 #define IS_ALPHA(x) (IS_LOWALPHA(x) || IS_UPALPHA(x))
67
68
69 /*
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"
73  */
74
75 #define IS_LOWALPHA(x) (((x) >= 'a') && ((x) <= 'z'))
76
77 /*
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"
81  */
82 #define IS_UPALPHA(x) (((x) >= 'A') && ((x) <= 'Z'))
83
84 #ifdef IS_DIGIT
85 #undef IS_DIGIT
86 #endif
87 /*
88  * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
89  */
90 #define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9'))
91
92 /*
93  * alphanum = alpha | digit
94  */
95
96 #define IS_ALPHANUM(x) (IS_ALPHA(x) || IS_DIGIT(x))
97
98 /*
99  * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
100  */
101
102 #define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') ||     \
103     ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') ||    \
104     ((x) == '(') || ((x) == ')'))
105
106 /*
107  * unwise = "{" | "}" | "|" | "\" | "^" | "`"
108  */
109
110 #define IS_UNWISE(p)                                                    \
111       (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) ||         \
112        ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) ||        \
113        ((*(p) == ']')) || ((*(p) == '`')))
114 /*
115  * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
116  *            "[" | "]"
117  */
118
119 #define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') || \
120         ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') || \
121         ((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \
122         ((x) == ']'))
123
124 /*
125  * unreserved = alphanum | mark
126  */
127
128 #define IS_UNRESERVED(x) (IS_ALPHANUM(x) || IS_MARK(x))
129
130 /*
131  * Skip to next pointer char, handle escaped sequences
132  */
133
134 #define NEXT(p) ((*p == '%')? p += 3 : p++)
135
136 /*
137  * Productions from the spec.
138  *
139  *    authority     = server | reg_name
140  *    reg_name      = 1*( unreserved | escaped | "$" | "," |
141  *                        ";" | ":" | "@" | "&" | "=" | "+" )
142  *
143  * path          = [ abs_path | opaque_part ]
144  */
145
146
147 /************************************************************************
148  *                                                                      *
149  *                         RFC 3986 parser                              *
150  *                                                                      *
151  ************************************************************************/
152
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')))
159
160 /*
161  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
162  *                     / "*" / "+" / "," / ";" / "="
163  */
164 #define ISA_SUB_DELIM(p)                                                \
165       (((*(p) == '!')) || ((*(p) == '$')) || ((*(p) == '&')) ||         \
166        ((*(p) == '(')) || ((*(p) == ')')) || ((*(p) == '*')) ||         \
167        ((*(p) == '+')) || ((*(p) == ',')) || ((*(p) == ';')) ||         \
168        ((*(p) == '=')) || ((*(p) == '\'')))
169
170 /*
171  *    gen-delims    = ":" / "/" / "?" / "#" / "[" / "]" / "@"
172  */
173 #define ISA_GEN_DELIM(p)                                                \
174       (((*(p) == ':')) || ((*(p) == '/')) || ((*(p) == '?')) ||         \
175        ((*(p) == '#')) || ((*(p) == '[')) || ((*(p) == ']')) ||         \
176        ((*(p) == '@')))
177
178 /*
179  *    reserved      = gen-delims / sub-delims
180  */
181 #define ISA_RESERVED(p) (ISA_GEN_DELIM(p) || (ISA_SUB_DELIM(p)))
182
183 /*
184  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
185  */
186 #define ISA_UNRESERVED(p)                                               \
187       ((ISA_ALPHA(p)) || (ISA_DIGIT(p)) || ((*(p) == '-')) ||           \
188        ((*(p) == '.')) || ((*(p) == '_')) || ((*(p) == '~')))
189
190 /*
191  *    pct-encoded   = "%" HEXDIG HEXDIG
192  */
193 #define ISA_PCT_ENCODED(p)                                              \
194      ((*(p) == '%') && (ISA_HEXDIG(p + 1)) && (ISA_HEXDIG(p + 2)))
195
196 /*
197  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
198  */
199 #define ISA_PCHAR(p)                                                    \
200      (ISA_UNRESERVED(p) || ISA_PCT_ENCODED(p) || ISA_SUB_DELIM(p) ||    \
201       ((*(p) == ':')) || ((*(p) == '@')))
202
203 /**
204  * rfc3986_parse_scheme:
205  * @uri:  pointer to an URI structure
206  * @str:  pointer to the string to analyze
207  *
208  * Parse an URI scheme
209  *
210  * ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
211  *
212  * Returns 0 or the error code
213  */
214 static int
215 rfc3986_parse_scheme(URI *uri, const char **str) {
216     const char *cur;
217
218     if (str == NULL)
219         return(-1);
220
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);
230     }
231     *str = cur;
232     return(0);
233 }
234
235 /**
236  * rfc3986_parse_fragment:
237  * @uri:  pointer to an URI structure
238  * @str:  pointer to the string to analyze
239  *
240  * Parse the query part of an URI
241  *
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.
247  *
248  * Returns 0 or the error code
249  */
250 static int
251 rfc3986_parse_fragment(URI *uri, const char **str)
252 {
253     const char *cur;
254
255     if (str == NULL)
256         return (-1);
257
258     cur = *str;
259
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);
270     }
271     *str = cur;
272     return (0);
273 }
274
275 /**
276  * rfc3986_parse_query:
277  * @uri:  pointer to an URI structure
278  * @str:  pointer to the string to analyze
279  *
280  * Parse the query part of an URI
281  *
282  * query = *uric
283  *
284  * Returns 0 or the error code
285  */
286 static int
287 rfc3986_parse_query(URI *uri, const char **str)
288 {
289     const char *cur;
290
291     if (str == NULL)
292         return (-1);
293
294     cur = *str;
295
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);
302     }
303     *str = cur;
304     return (0);
305 }
306
307 /**
308  * rfc3986_parse_port:
309  * @uri:  pointer to an URI structure
310  * @str:  the string to analyze
311  *
312  * Parse a port  part and fills in the appropriate fields
313  * of the @uri structure
314  *
315  * port          = *DIGIT
316  *
317  * Returns 0 or the error code
318  */
319 static int
320 rfc3986_parse_port(URI *uri, const char **str)
321 {
322     const char *cur = *str;
323
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++;
331         }
332         *str = cur;
333         return(0);
334     }
335     return(1);
336 }
337
338 /**
339  * rfc3986_parse_user_info:
340  * @uri:  pointer to an URI structure
341  * @str:  the string to analyze
342  *
343  * Parse an user informations part and fills in the appropriate fields
344  * of the @uri structure
345  *
346  * userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
347  *
348  * Returns 0 or the error code
349  */
350 static int
351 rfc3986_parse_user_info(URI *uri, const char **str)
352 {
353     const char *cur;
354
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);
366         }
367         *str = cur;
368         return(0);
369     }
370     return(1);
371 }
372
373 /**
374  * rfc3986_parse_dec_octet:
375  * @str:  the string to analyze
376  *
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
382  *
383  * Skip a dec-octet.
384  *
385  * Returns 0 if found and skipped, 1 otherwise
386  */
387 static int
388 rfc3986_parse_dec_octet(const char **str) {
389     const char *cur = *str;
390
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);
409 }
410 /**
411  * rfc3986_parse_host:
412  * @uri:  pointer to an URI structure
413  * @str:  the string to analyze
414  *
415  * Parse an host part and fills in the appropriate fields
416  * of the @uri structure
417  *
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 )
422  *
423  * Returns 0 or the error code
424  */
425 static int
426 rfc3986_parse_host(URI *uri, const char **str)
427 {
428     const char *cur = *str;
429     const char *host;
430
431     host = cur;
432     /*
433      * IPv6 and future addressing scheme are enclosed between brackets
434      */
435     if (*cur == '[') {
436         cur++;
437         while ((*cur != ']') && (*cur != 0))
438             cur++;
439         if (*cur != ']')
440             return(1);
441         cur++;
442         goto found;
443     }
444     /*
445      * try to parse an IPv4
446      */
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;
466     }
467     /*
468      * then this should be a hostname which can be empty
469      */
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;
484     }
485     *str = cur;
486     return(0);
487 }
488
489 /**
490  * rfc3986_parse_authority:
491  * @uri:  pointer to an URI structure
492  * @str:  the string to analyze
493  *
494  * Parse an authority part and fills in the appropriate fields
495  * of the @uri structure
496  *
497  * authority     = [ userinfo "@" ] host [ ":" port ]
498  *
499  * Returns 0 or the error code
500  */
501 static int
502 rfc3986_parse_authority(URI *uri, const char **str)
503 {
504     const char *cur;
505     int ret;
506
507     cur = *str;
508     /*
509      * try to parse an userinfo and check for the trailing @
510      */
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);
522     }
523     *str = cur;
524     return(0);
525 }
526
527 /**
528  * rfc3986_parse_segment:
529  * @str:  the string to analyze
530  * @forbid: an optional forbidden character
531  * @empty: allow an empty segment
532  *
533  * Parse a segment and fills in the appropriate fields
534  * of the @uri structure
535  *
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 ":"
540  *
541  * Returns 0 or the error code
542  */
543 static int
544 rfc3986_parse_segment(const char **str, char forbid, int empty)
545 {
546     const char *cur;
547
548     cur = *str;
549     if (!ISA_PCHAR(cur)) {
550         if (empty)
551             return(0);
552         return(1);
553     }
554     while (ISA_PCHAR(cur) && (*cur != forbid))
555         NEXT(cur);
556     *str = cur;
557     return (0);
558 }
559
560 /**
561  * rfc3986_parse_path_ab_empty:
562  * @uri:  pointer to an URI structure
563  * @str:  the string to analyze
564  *
565  * Parse an path absolute or empty and fills in the appropriate fields
566  * of the @uri structure
567  *
568  * path-abempty  = *( "/" segment )
569  *
570  * Returns 0 or the error code
571  */
572 static int
573 rfc3986_parse_path_ab_empty(URI *uri, const char **str)
574 {
575     const char *cur;
576     int ret;
577
578     cur = *str;
579
580     while (*cur == '/') {
581         cur++;
582         ret = rfc3986_parse_segment(&cur, 0, 1);
583         if (ret != 0) return(ret);
584     }
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;
594         }
595     }
596     *str = cur;
597     return (0);
598 }
599
600 /**
601  * rfc3986_parse_path_absolute:
602  * @uri:  pointer to an URI structure
603  * @str:  the string to analyze
604  *
605  * Parse an path absolute and fills in the appropriate fields
606  * of the @uri structure
607  *
608  * path-absolute = "/" [ segment-nz *( "/" segment ) ]
609  *
610  * Returns 0 or the error code
611  */
612 static int
613 rfc3986_parse_path_absolute(URI *uri, const char **str)
614 {
615     const char *cur;
616     int ret;
617
618     cur = *str;
619
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);
629         }
630     }
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;
640         }
641     }
642     *str = cur;
643     return (0);
644 }
645
646 /**
647  * rfc3986_parse_path_rootless:
648  * @uri:  pointer to an URI structure
649  * @str:  the string to analyze
650  *
651  * Parse an path without root and fills in the appropriate fields
652  * of the @uri structure
653  *
654  * path-rootless = segment-nz *( "/" segment )
655  *
656  * Returns 0 or the error code
657  */
658 static int
659 rfc3986_parse_path_rootless(URI *uri, const char **str)
660 {
661     const char *cur;
662     int ret;
663
664     cur = *str;
665
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);
672     }
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;
682         }
683     }
684     *str = cur;
685     return (0);
686 }
687
688 /**
689  * rfc3986_parse_path_no_scheme:
690  * @uri:  pointer to an URI structure
691  * @str:  the string to analyze
692  *
693  * Parse an path which is not a scheme and fills in the appropriate fields
694  * of the @uri structure
695  *
696  * path-noscheme = segment-nz-nc *( "/" segment )
697  *
698  * Returns 0 or the error code
699  */
700 static int
701 rfc3986_parse_path_no_scheme(URI *uri, const char **str)
702 {
703     const char *cur;
704     int ret;
705
706     cur = *str;
707
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);
714     }
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;
724         }
725     }
726     *str = cur;
727     return (0);
728 }
729
730 /**
731  * rfc3986_parse_hier_part:
732  * @uri:  pointer to an URI structure
733  * @str:  the string to analyze
734  *
735  * Parse an hierarchical part and fills in the appropriate fields
736  * of the @uri structure
737  *
738  * hier-part     = "//" authority path-abempty
739  *                / path-absolute
740  *                / path-rootless
741  *                / path-empty
742  *
743  * Returns 0 or the error code
744  */
745 static int
746 rfc3986_parse_hier_part(URI *uri, const char **str)
747 {
748     const char *cur;
749     int ret;
750
751     cur = *str;
752
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;
772         }
773     }
774     *str = cur;
775     return (0);
776 }
777
778 /**
779  * rfc3986_parse_relative_ref:
780  * @uri:  pointer to an URI structure
781  * @str:  the string to analyze
782  *
783  * Parse an URI string and fills in the appropriate fields
784  * of the @uri structure
785  *
786  * relative-ref  = relative-part [ "?" query ] [ "#" fragment ]
787  * relative-part = "//" authority path-abempty
788  *               / path-absolute
789  *               / path-noscheme
790  *               / path-empty
791  *
792  * Returns 0 or the error code
793  */
794 static int
795 rfc3986_parse_relative_ref(URI *uri, const char *str) {
796     int ret;
797
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;
815         }
816     }
817
818     if (*str == '?') {
819         str++;
820         ret = rfc3986_parse_query(uri, &str);
821         if (ret != 0) return(ret);
822     }
823     if (*str == '#') {
824         str++;
825         ret = rfc3986_parse_fragment(uri, &str);
826         if (ret != 0) return(ret);
827     }
828     if (*str != 0) {
829         uri_clean(uri);
830         return(1);
831     }
832     return(0);
833 }
834
835
836 /**
837  * rfc3986_parse:
838  * @uri:  pointer to an URI structure
839  * @str:  the string to analyze
840  *
841  * Parse an URI string and fills in the appropriate fields
842  * of the @uri structure
843  *
844  * scheme ":" hier-part [ "?" query ] [ "#" fragment ]
845  *
846  * Returns 0 or the error code
847  */
848 static int
849 rfc3986_parse(URI *uri, const char *str) {
850     int ret;
851
852     ret = rfc3986_parse_scheme(uri, &str);
853     if (ret != 0) return(ret);
854     if (*str != ':') {
855         return(1);
856     }
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);
864     }
865     if (*str == '#') {
866         str++;
867         ret = rfc3986_parse_fragment(uri, &str);
868         if (ret != 0) return(ret);
869     }
870     if (*str != 0) {
871         uri_clean(uri);
872         return(1);
873     }
874     return(0);
875 }
876
877 /**
878  * rfc3986_parse_uri_reference:
879  * @uri:  pointer to an URI structure
880  * @str:  the string to analyze
881  *
882  * Parse an URI reference string and fills in the appropriate fields
883  * of the @uri structure
884  *
885  * URI-reference = URI / relative-ref
886  *
887  * Returns 0 or the error code
888  */
889 static int
890 rfc3986_parse_uri_reference(URI *uri, const char *str) {
891     int ret;
892
893     if (str == NULL)
894         return(-1);
895     uri_clean(uri);
896
897     /*
898      * Try first to parse absolute refs, then fallback to relative if
899      * it fails.
900      */
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);
908         }
909     }
910     return(0);
911 }
912
913 /**
914  * uri_parse:
915  * @str:  the URI string to analyze
916  *
917  * Parse an URI based on RFC 3986
918  *
919  * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
920  *
921  * Returns a newly built URI or NULL in case of error
922  */
923 URI *
924 uri_parse(const char *str) {
925     URI *uri;
926     int ret;
927
928     if (str == NULL)
929         return(NULL);
930     uri = uri_new();
931     ret = rfc3986_parse_uri_reference(uri, str);
932     if (ret) {
933         uri_free(uri);
934         return(NULL);
935     }
936     return(uri);
937 }
938
939 /**
940  * uri_parse_into:
941  * @uri:  pointer to an URI structure
942  * @str:  the string to analyze
943  *
944  * Parse an URI reference string based on RFC 3986 and fills in the
945  * appropriate fields of the @uri structure
946  *
947  * URI-reference = URI / relative-ref
948  *
949  * Returns 0 or the error code
950  */
951 int
952 uri_parse_into(URI *uri, const char *str) {
953     return(rfc3986_parse_uri_reference(uri, str));
954 }
955
956 /**
957  * uri_parse_raw:
958  * @str:  the URI string to analyze
959  * @raw:  if 1 unescaping of URI pieces are disabled
960  *
961  * Parse an URI but allows to keep intact the original fragments.
962  *
963  * URI-reference = URI / relative-ref
964  *
965  * Returns a newly built URI or NULL in case of error
966  */
967 URI *
968 uri_parse_raw(const char *str, int raw) {
969     URI *uri;
970     int ret;
971
972     if (str == NULL)
973         return(NULL);
974     uri = uri_new();
975     if (raw) {
976         uri->cleanup |= 2;
977     }
978     ret = uri_parse_into(uri, str);
979     if (ret) {
980         uri_free(uri);
981         return(NULL);
982     }
983     return(uri);
984 }
985
986 /************************************************************************
987  *                                                                      *
988  *                      Generic URI structure functions                 *
989  *                                                                      *
990  ************************************************************************/
991
992 /**
993  * uri_new:
994  *
995  * Simply creates an empty URI
996  *
997  * Returns the new structure or NULL in case of error
998  */
999 URI *
1000 uri_new(void) {
1001     URI *ret;
1002
1003     ret = g_new0(URI, 1);
1004     return(ret);
1005 }
1006
1007 /**
1008  * realloc2n:
1009  *
1010  * Function to handle properly a reallocation when saving an URI
1011  * Also imposes some limit on the length of an URI string output
1012  */
1013 static char *
1014 realloc2n(char *ret, int *max) {
1015     char *temp;
1016     int tmp;
1017
1018     tmp = *max * 2;
1019     temp = g_realloc(ret, (tmp + 1));
1020     *max = tmp;
1021     return(temp);
1022 }
1023
1024 /**
1025  * uri_to_string:
1026  * @uri:  pointer to an URI
1027  *
1028  * Save the URI as an escaped string
1029  *
1030  * Returns a new string (to be deallocated by caller)
1031  */
1032 char *
1033 uri_to_string(URI *uri) {
1034     char *ret = NULL;
1035     char *temp;
1036     const char *p;
1037     int len;
1038     int max;
1039
1040     if (uri == NULL) return(NULL);
1041
1042
1043     max = 80;
1044     ret = g_malloc(max + 1);
1045     len = 0;
1046
1047     if (uri->scheme != NULL) {
1048         p = uri->scheme;
1049         while (*p != 0) {
1050             if (len >= max) {
1051                 temp = realloc2n(ret, &max);
1052                 ret = temp;
1053             }
1054             ret[len++] = *p++;
1055         }
1056         if (len >= max) {
1057             temp = realloc2n(ret, &max);
1058             ret = temp;
1059         }
1060         ret[len++] = ':';
1061     }
1062     if (uri->opaque != NULL) {
1063         p = uri->opaque;
1064         while (*p != 0) {
1065             if (len + 3 >= max) {
1066                 temp = realloc2n(ret, &max);
1067                 ret = temp;
1068             }
1069             if (IS_RESERVED(*(p)) || IS_UNRESERVED(*(p)))
1070                 ret[len++] = *p++;
1071             else {
1072                 int val = *(unsigned char *)p++;
1073                 int hi = val / 0x10, lo = val % 0x10;
1074                 ret[len++] = '%';
1075                 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1076                 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1077             }
1078         }
1079     } else {
1080         if (uri->server != NULL) {
1081             if (len + 3 >= max) {
1082                 temp = realloc2n(ret, &max);
1083                 ret = temp;
1084             }
1085             ret[len++] = '/';
1086             ret[len++] = '/';
1087             if (uri->user != NULL) {
1088                 p = uri->user;
1089                 while (*p != 0) {
1090                     if (len + 3 >= max) {
1091                         temp = realloc2n(ret, &max);
1092                         ret = temp;
1093                     }
1094                     if ((IS_UNRESERVED(*(p))) ||
1095                         ((*(p) == ';')) || ((*(p) == ':')) ||
1096                         ((*(p) == '&')) || ((*(p) == '=')) ||
1097                         ((*(p) == '+')) || ((*(p) == '$')) ||
1098                         ((*(p) == ',')))
1099                         ret[len++] = *p++;
1100                     else {
1101                         int val = *(unsigned char *)p++;
1102                         int hi = val / 0x10, lo = val % 0x10;
1103                         ret[len++] = '%';
1104                         ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1105                         ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1106                     }
1107                 }
1108                 if (len + 3 >= max) {
1109                     temp = realloc2n(ret, &max);
1110                     ret = temp;
1111                 }
1112                 ret[len++] = '@';
1113             }
1114             p = uri->server;
1115             while (*p != 0) {
1116                 if (len >= max) {
1117                     temp = realloc2n(ret, &max);
1118                     ret = temp;
1119                 }
1120                 ret[len++] = *p++;
1121             }
1122             if (uri->port > 0) {
1123                 if (len + 10 >= max) {
1124                     temp = realloc2n(ret, &max);
1125                     ret = temp;
1126                 }
1127                 len += snprintf(&ret[len], max - len, ":%d", uri->port);
1128             }
1129         } else if (uri->authority != NULL) {
1130             if (len + 3 >= max) {
1131                 temp = realloc2n(ret, &max);
1132                 ret = temp;
1133             }
1134             ret[len++] = '/';
1135             ret[len++] = '/';
1136             p = uri->authority;
1137             while (*p != 0) {
1138                 if (len + 3 >= max) {
1139                     temp = realloc2n(ret, &max);
1140                     ret = temp;
1141                 }
1142                 if ((IS_UNRESERVED(*(p))) ||
1143                     ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) ||
1144                     ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1145                     ((*(p) == '=')) || ((*(p) == '+')))
1146                     ret[len++] = *p++;
1147                 else {
1148                     int val = *(unsigned char *)p++;
1149                     int hi = val / 0x10, lo = val % 0x10;
1150                     ret[len++] = '%';
1151                     ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1152                     ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1153                 }
1154             }
1155         } else if (uri->scheme != NULL) {
1156             if (len + 3 >= max) {
1157                 temp = realloc2n(ret, &max);
1158                 ret = temp;
1159             }
1160             ret[len++] = '/';
1161             ret[len++] = '/';
1162         }
1163         if (uri->path != NULL) {
1164             p = uri->path;
1165             /*
1166              * the colon in file:///d: should not be escaped or
1167              * Windows accesses fail later.
1168              */
1169             if ((uri->scheme != NULL) &&
1170                 (p[0] == '/') &&
1171                 (((p[1] >= 'a') && (p[1] <= 'z')) ||
1172                  ((p[1] >= 'A') && (p[1] <= 'Z'))) &&
1173                 (p[2] == ':') &&
1174                 (!strcmp(uri->scheme, "file"))) {
1175                 if (len + 3 >= max) {
1176                     temp = realloc2n(ret, &max);
1177                     ret = temp;
1178                 }
1179                 ret[len++] = *p++;
1180                 ret[len++] = *p++;
1181                 ret[len++] = *p++;
1182             }
1183             while (*p != 0) {
1184                 if (len + 3 >= max) {
1185                     temp = realloc2n(ret, &max);
1186                     ret = temp;
1187                 }
1188                 if ((IS_UNRESERVED(*(p))) || ((*(p) == '/')) ||
1189                     ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) ||
1190                     ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||
1191                     ((*(p) == ',')))
1192                     ret[len++] = *p++;
1193                 else {
1194                     int val = *(unsigned char *)p++;
1195                     int hi = val / 0x10, lo = val % 0x10;
1196                     ret[len++] = '%';
1197                     ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1198                     ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1199                 }
1200             }
1201         }
1202         if (uri->query != NULL) {
1203             if (len + 1 >= max) {
1204                 temp = realloc2n(ret, &max);
1205                 ret = temp;
1206             }
1207             ret[len++] = '?';
1208             p = uri->query;
1209             while (*p != 0) {
1210                 if (len + 1 >= max) {
1211                     temp = realloc2n(ret, &max);
1212                     ret = temp;
1213                 }
1214                 ret[len++] = *p++;
1215             }
1216         }
1217     }
1218     if (uri->fragment != NULL) {
1219         if (len + 3 >= max) {
1220             temp = realloc2n(ret, &max);
1221             ret = temp;
1222         }
1223         ret[len++] = '#';
1224         p = uri->fragment;
1225         while (*p != 0) {
1226             if (len + 3 >= max) {
1227                 temp = realloc2n(ret, &max);
1228                 ret = temp;
1229             }
1230             if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p))))
1231                 ret[len++] = *p++;
1232             else {
1233                 int val = *(unsigned char *)p++;
1234                 int hi = val / 0x10, lo = val % 0x10;
1235                 ret[len++] = '%';
1236                 ret[len++] = hi + (hi > 9? 'A'-10 : '0');
1237                 ret[len++] = lo + (lo > 9? 'A'-10 : '0');
1238             }
1239         }
1240     }
1241     if (len >= max) {
1242         temp = realloc2n(ret, &max);
1243         ret = temp;
1244     }
1245     ret[len] = 0;
1246     return(ret);
1247 }
1248
1249 /**
1250  * uri_clean:
1251  * @uri:  pointer to an URI
1252  *
1253  * Make sure the URI struct is free of content
1254  */
1255 static void
1256 uri_clean(URI *uri) {
1257     if (uri == NULL) return;
1258
1259     g_free(uri->scheme);
1260     uri->scheme = NULL;
1261     g_free(uri->server);
1262     uri->server = NULL;
1263     g_free(uri->user);
1264     uri->user = NULL;
1265     g_free(uri->path);
1266     uri->path = NULL;
1267     g_free(uri->fragment);
1268     uri->fragment = NULL;
1269     g_free(uri->opaque);
1270     uri->opaque = NULL;
1271     g_free(uri->authority);
1272     uri->authority = NULL;
1273     g_free(uri->query);
1274     uri->query = NULL;
1275 }
1276
1277 /**
1278  * uri_free:
1279  * @uri:  pointer to an URI
1280  *
1281  * Free up the URI struct
1282  */
1283 void
1284 uri_free(URI *uri) {
1285     uri_clean(uri);
1286     g_free(uri);
1287 }
1288
1289 /************************************************************************
1290  *                                                                      *
1291  *                      Helper functions                                *
1292  *                                                                      *
1293  ************************************************************************/
1294
1295 /**
1296  * normalize_uri_path:
1297  * @path:  pointer to the path string
1298  *
1299  * Applies the 5 normalization steps to a path string--that is, RFC 2396
1300  * Section 5.2, steps 6.c through 6.g.
1301  *
1302  * Normalization occurs directly on the string, no new allocation is done
1303  *
1304  * Returns 0 or an error code
1305  */
1306 static int
1307 normalize_uri_path(char *path) {
1308     char *cur, *out;
1309
1310     if (path == NULL)
1311         return(-1);
1312
1313     /* Skip all initial "/" chars.  We want to get to the beginning of the
1314      * first non-empty segment.
1315      */
1316     cur = path;
1317     while (cur[0] == '/')
1318       ++cur;
1319     if (cur[0] == '\0')
1320       return(0);
1321
1322     /* Keep everything we've seen so far.  */
1323     out = cur;
1324
1325     /*
1326      * Analyze each segment in sequence for cases (c) and (d).
1327      */
1328     while (cur[0] != '\0') {
1329         /*
1330          * c) All occurrences of "./", where "." is a complete path segment,
1331          *    are removed from the buffer string.
1332          */
1333         if ((cur[0] == '.') && (cur[1] == '/')) {
1334             cur += 2;
1335             /* '//' normalization should be done at this point too */
1336             while (cur[0] == '/')
1337                 cur++;
1338             continue;
1339         }
1340
1341         /*
1342          * d) If the buffer string ends with "." as a complete path segment,
1343          *    that "." is removed.
1344          */
1345         if ((cur[0] == '.') && (cur[1] == '\0'))
1346             break;
1347
1348         /* Otherwise keep the segment.  */
1349         while (cur[0] != '/') {
1350             if (cur[0] == '\0')
1351               goto done_cd;
1352             (out++)[0] = (cur++)[0];
1353         }
1354         /* nomalize // */
1355         while ((cur[0] == '/') && (cur[1] == '/'))
1356             cur++;
1357
1358         (out++)[0] = (cur++)[0];
1359     }
1360  done_cd:
1361     out[0] = '\0';
1362
1363     /* Reset to the beginning of the first segment for the next sequence.  */
1364     cur = path;
1365     while (cur[0] == '/')
1366       ++cur;
1367     if (cur[0] == '\0')
1368         return(0);
1369
1370     /*
1371      * Analyze each segment in sequence for cases (e) and (f).
1372      *
1373      * e) All occurrences of "<segment>/../", where <segment> is a
1374      *    complete path segment not equal to "..", are removed from the
1375      *    buffer string.  Removal of these path segments is performed
1376      *    iteratively, removing the leftmost matching pattern on each
1377      *    iteration, until no matching pattern remains.
1378      *
1379      * f) If the buffer string ends with "<segment>/..", where <segment>
1380      *    is a complete path segment not equal to "..", that
1381      *    "<segment>/.." is removed.
1382      *
1383      * To satisfy the "iterative" clause in (e), we need to collapse the
1384      * string every time we find something that needs to be removed.  Thus,
1385      * we don't need to keep two pointers into the string: we only need a
1386      * "current position" pointer.
1387      */
1388     while (1) {
1389         char *segp, *tmp;
1390
1391         /* At the beginning of each iteration of this loop, "cur" points to
1392          * the first character of the segment we want to examine.
1393          */
1394
1395         /* Find the end of the current segment.  */
1396         segp = cur;
1397         while ((segp[0] != '/') && (segp[0] != '\0'))
1398           ++segp;
1399
1400         /* If this is the last segment, we're done (we need at least two
1401          * segments to meet the criteria for the (e) and (f) cases).
1402          */
1403         if (segp[0] == '\0')
1404           break;
1405
1406         /* If the first segment is "..", or if the next segment _isn't_ "..",
1407          * keep this segment and try the next one.
1408          */
1409         ++segp;
1410         if (((cur[0] == '.') && (cur[1] == '.') && (segp == cur+3))
1411             || ((segp[0] != '.') || (segp[1] != '.')
1412                 || ((segp[2] != '/') && (segp[2] != '\0')))) {
1413           cur = segp;
1414           continue;
1415         }
1416
1417         /* If we get here, remove this segment and the next one and back up
1418          * to the previous segment (if there is one), to implement the
1419          * "iteratively" clause.  It's pretty much impossible to back up
1420          * while maintaining two pointers into the buffer, so just compact
1421          * the whole buffer now.
1422          */
1423
1424         /* If this is the end of the buffer, we're done.  */
1425         if (segp[2] == '\0') {
1426           cur[0] = '\0';
1427           break;
1428         }
1429         /* Valgrind complained, strcpy(cur, segp + 3); */
1430         /* string will overlap, do not use strcpy */
1431         tmp = cur;
1432         segp += 3;
1433         while ((*tmp++ = *segp++) != 0)
1434           ;
1435
1436         /* If there are no previous segments, then keep going from here.  */
1437         segp = cur;
1438         while ((segp > path) && ((--segp)[0] == '/'))
1439           ;
1440         if (segp == path)
1441           continue;
1442
1443         /* "segp" is pointing to the end of a previous segment; find it's
1444          * start.  We need to back up to the previous segment and start
1445          * over with that to handle things like "foo/bar/../..".  If we
1446          * don't do this, then on the first pass we'll remove the "bar/..",
1447          * but be pointing at the second ".." so we won't realize we can also
1448          * remove the "foo/..".
1449          */
1450         cur = segp;
1451         while ((cur > path) && (cur[-1] != '/'))
1452           --cur;
1453     }
1454     out[0] = '\0';
1455
1456     /*
1457      * g) If the resulting buffer string still begins with one or more
1458      *    complete path segments of "..", then the reference is
1459      *    considered to be in error. Implementations may handle this
1460      *    error by retaining these components in the resolved path (i.e.,
1461      *    treating them as part of the final URI), by removing them from
1462      *    the resolved path (i.e., discarding relative levels above the
1463      *    root), or by avoiding traversal of the reference.
1464      *
1465      * We discard them from the final path.
1466      */
1467     if (path[0] == '/') {
1468       cur = path;
1469       while ((cur[0] == '/') && (cur[1] == '.') && (cur[2] == '.')
1470              && ((cur[3] == '/') || (cur[3] == '\0')))
1471         cur += 3;
1472
1473       if (cur != path) {
1474         out = path;
1475         while (cur[0] != '\0')
1476           (out++)[0] = (cur++)[0];
1477         out[0] = 0;
1478       }
1479     }
1480
1481     return(0);
1482 }
1483
1484 static int is_hex(char c) {
1485     if (((c >= '0') && (c <= '9')) ||
1486         ((c >= 'a') && (c <= 'f')) ||
1487         ((c >= 'A') && (c <= 'F')))
1488         return(1);
1489     return(0);
1490 }
1491
1492
1493 /**
1494  * uri_string_unescape:
1495  * @str:  the string to unescape
1496  * @len:   the length in bytes to unescape (or <= 0 to indicate full string)
1497  * @target:  optional destination buffer
1498  *
1499  * Unescaping routine, but does not check that the string is an URI. The
1500  * output is a direct unsigned char translation of %XX values (no encoding)
1501  * Note that the length of the result can only be smaller or same size as
1502  * the input string.
1503  *
1504  * Returns a copy of the string, but unescaped, will return NULL only in case
1505  * of error
1506  */
1507 char *
1508 uri_string_unescape(const char *str, int len, char *target) {
1509     char *ret, *out;
1510     const char *in;
1511
1512     if (str == NULL)
1513         return(NULL);
1514     if (len <= 0) len = strlen(str);
1515     if (len < 0) return(NULL);
1516
1517     if (target == NULL) {
1518         ret = g_malloc(len + 1);
1519     } else
1520         ret = target;
1521     in = str;
1522     out = ret;
1523     while(len > 0) {
1524         if ((len > 2) && (*in == '%') && (is_hex(in[1])) && (is_hex(in[2]))) {
1525             in++;
1526             if ((*in >= '0') && (*in <= '9'))
1527                 *out = (*in - '0');
1528             else if ((*in >= 'a') && (*in <= 'f'))
1529                 *out = (*in - 'a') + 10;
1530             else if ((*in >= 'A') && (*in <= 'F'))
1531                 *out = (*in - 'A') + 10;
1532             in++;
1533             if ((*in >= '0') && (*in <= '9'))
1534                 *out = *out * 16 + (*in - '0');
1535             else if ((*in >= 'a') && (*in <= 'f'))
1536                 *out = *out * 16 + (*in - 'a') + 10;
1537             else if ((*in >= 'A') && (*in <= 'F'))
1538                 *out = *out * 16 + (*in - 'A') + 10;
1539             in++;
1540             len -= 3;
1541             out++;
1542         } else {
1543             *out++ = *in++;
1544             len--;
1545         }
1546     }
1547     *out = 0;
1548     return(ret);
1549 }
1550
1551 /**
1552  * uri_string_escape:
1553  * @str:  string to escape
1554  * @list: exception list string of chars not to escape
1555  *
1556  * This routine escapes a string to hex, ignoring reserved characters (a-z)
1557  * and the characters in the exception list.
1558  *
1559  * Returns a new escaped string or NULL in case of error.
1560  */
1561 char *
1562 uri_string_escape(const char *str, const char *list) {
1563     char *ret, ch;
1564     char *temp;
1565     const char *in;
1566     int len, out;
1567
1568     if (str == NULL)
1569         return(NULL);
1570     if (str[0] == 0)
1571         return(g_strdup(str));
1572     len = strlen(str);
1573     if (!(len > 0)) return(NULL);
1574
1575     len += 20;
1576     ret = g_malloc(len);
1577     in = str;
1578     out = 0;
1579     while(*in != 0) {
1580         if (len - out <= 3) {
1581             temp = realloc2n(ret, &len);
1582             ret = temp;
1583         }
1584
1585         ch = *in;
1586
1587         if ((ch != '@') && (!IS_UNRESERVED(ch)) && (!strchr(list, ch))) {
1588             unsigned char val;
1589             ret[out++] = '%';
1590             val = ch >> 4;
1591             if (val <= 9)
1592                 ret[out++] = '0' + val;
1593             else
1594                 ret[out++] = 'A' + val - 0xA;
1595             val = ch & 0xF;
1596             if (val <= 9)
1597                 ret[out++] = '0' + val;
1598             else
1599                 ret[out++] = 'A' + val - 0xA;
1600             in++;
1601         } else {
1602             ret[out++] = *in++;
1603         }
1604
1605     }
1606     ret[out] = 0;
1607     return(ret);
1608 }
1609
1610 /************************************************************************
1611  *                                                                      *
1612  *                      Public functions                                *
1613  *                                                                      *
1614  ************************************************************************/
1615
1616 /**
1617  * uri_resolve:
1618  * @URI:  the URI instance found in the document
1619  * @base:  the base value
1620  *
1621  * Computes he final URI of the reference done by checking that
1622  * the given URI is valid, and building the final URI using the
1623  * base URI. This is processed according to section 5.2 of the
1624  * RFC 2396
1625  *
1626  * 5.2. Resolving Relative References to Absolute Form
1627  *
1628  * Returns a new URI string (to be freed by the caller) or NULL in case
1629  *         of error.
1630  */
1631 char *
1632 uri_resolve(const char *uri, const char *base) {
1633     char *val = NULL;
1634     int ret, len, indx, cur, out;
1635     URI *ref = NULL;
1636     URI *bas = NULL;
1637     URI *res = NULL;
1638
1639     /*
1640      * 1) The URI reference is parsed into the potential four components and
1641      *    fragment identifier, as described in Section 4.3.
1642      *
1643      *    NOTE that a completely empty URI is treated by modern browsers
1644      *    as a reference to "." rather than as a synonym for the current
1645      *    URI.  Should we do that here?
1646      */
1647     if (uri == NULL)
1648         ret = -1;
1649     else {
1650         if (*uri) {
1651             ref = uri_new();
1652             ret = uri_parse_into(ref, uri);
1653         }
1654         else
1655             ret = 0;
1656     }
1657     if (ret != 0)
1658         goto done;
1659     if ((ref != NULL) && (ref->scheme != NULL)) {
1660         /*
1661          * The URI is absolute don't modify.
1662          */
1663         val = g_strdup(uri);
1664         goto done;
1665     }
1666     if (base == NULL)
1667         ret = -1;
1668     else {
1669         bas = uri_new();
1670         ret = uri_parse_into(bas, base);
1671     }
1672     if (ret != 0) {
1673         if (ref)
1674             val = uri_to_string(ref);
1675         goto done;
1676     }
1677     if (ref == NULL) {
1678         /*
1679          * the base fragment must be ignored
1680          */
1681         g_free(bas->fragment);
1682         bas->fragment = NULL;
1683         val = uri_to_string(bas);
1684         goto done;
1685     }
1686
1687     /*
1688      * 2) If the path component is empty and the scheme, authority, and
1689      *    query components are undefined, then it is a reference to the
1690      *    current document and we are done.  Otherwise, the reference URI's
1691      *    query and fragment components are defined as found (or not found)
1692      *    within the URI reference and not inherited from the base URI.
1693      *
1694      *    NOTE that in modern browsers, the parsing differs from the above
1695      *    in the following aspect:  the query component is allowed to be
1696      *    defined while still treating this as a reference to the current
1697      *    document.
1698      */
1699     res = uri_new();
1700     if ((ref->scheme == NULL) && (ref->path == NULL) &&
1701         ((ref->authority == NULL) && (ref->server == NULL))) {
1702         res->scheme = g_strdup(bas->scheme);
1703         if (bas->authority != NULL)
1704             res->authority = g_strdup(bas->authority);
1705         else if (bas->server != NULL) {
1706             res->server = g_strdup(bas->server);
1707             res->user = g_strdup(bas->user);
1708             res->port = bas->port;
1709         }
1710         res->path = g_strdup(bas->path);
1711         if (ref->query != NULL) {
1712             res->query = g_strdup (ref->query);
1713         } else {
1714             res->query = g_strdup(bas->query);
1715         }
1716         res->fragment = g_strdup(ref->fragment);
1717         goto step_7;
1718     }
1719
1720     /*
1721      * 3) If the scheme component is defined, indicating that the reference
1722      *    starts with a scheme name, then the reference is interpreted as an
1723      *    absolute URI and we are done.  Otherwise, the reference URI's
1724      *    scheme is inherited from the base URI's scheme component.
1725      */
1726     if (ref->scheme != NULL) {
1727         val = uri_to_string(ref);
1728         goto done;
1729     }
1730     res->scheme = g_strdup(bas->scheme);
1731
1732     res->query = g_strdup(ref->query);
1733     res->fragment = g_strdup(ref->fragment);
1734
1735     /*
1736      * 4) If the authority component is defined, then the reference is a
1737      *    network-path and we skip to step 7.  Otherwise, the reference
1738      *    URI's authority is inherited from the base URI's authority
1739      *    component, which will also be undefined if the URI scheme does not
1740      *    use an authority component.
1741      */
1742     if ((ref->authority != NULL) || (ref->server != NULL)) {
1743         if (ref->authority != NULL)
1744             res->authority = g_strdup(ref->authority);
1745         else {
1746             res->server = g_strdup(ref->server);
1747             res->user = g_strdup(ref->user);
1748             res->port = ref->port;
1749         }
1750         res->path = g_strdup(ref->path);
1751         goto step_7;
1752     }
1753     if (bas->authority != NULL)
1754         res->authority = g_strdup(bas->authority);
1755     else if (bas->server != NULL) {
1756         res->server = g_strdup(bas->server);
1757         res->user = g_strdup(bas->user);
1758         res->port = bas->port;
1759     }
1760
1761     /*
1762      * 5) If the path component begins with a slash character ("/"), then
1763      *    the reference is an absolute-path and we skip to step 7.
1764      */
1765     if ((ref->path != NULL) && (ref->path[0] == '/')) {
1766         res->path = g_strdup(ref->path);
1767         goto step_7;
1768     }
1769
1770
1771     /*
1772      * 6) If this step is reached, then we are resolving a relative-path
1773      *    reference.  The relative path needs to be merged with the base
1774      *    URI's path.  Although there are many ways to do this, we will
1775      *    describe a simple method using a separate string buffer.
1776      *
1777      * Allocate a buffer large enough for the result string.
1778      */
1779     len = 2; /* extra / and 0 */
1780     if (ref->path != NULL)
1781         len += strlen(ref->path);
1782     if (bas->path != NULL)
1783         len += strlen(bas->path);
1784     res->path = g_malloc(len);
1785     res->path[0] = 0;
1786
1787     /*
1788      * a) All but the last segment of the base URI's path component is
1789      *    copied to the buffer.  In other words, any characters after the
1790      *    last (right-most) slash character, if any, are excluded.
1791      */
1792     cur = 0;
1793     out = 0;
1794     if (bas->path != NULL) {
1795         while (bas->path[cur] != 0) {
1796             while ((bas->path[cur] != 0) && (bas->path[cur] != '/'))
1797                 cur++;
1798             if (bas->path[cur] == 0)
1799                 break;
1800
1801             cur++;
1802             while (out < cur) {
1803                 res->path[out] = bas->path[out];
1804                 out++;
1805             }
1806         }
1807     }
1808     res->path[out] = 0;
1809
1810     /*
1811      * b) The reference's path component is appended to the buffer
1812      *    string.
1813      */
1814     if (ref->path != NULL && ref->path[0] != 0) {
1815         indx = 0;
1816         /*
1817          * Ensure the path includes a '/'
1818          */
1819         if ((out == 0) && (bas->server != NULL))
1820             res->path[out++] = '/';
1821         while (ref->path[indx] != 0) {
1822             res->path[out++] = ref->path[indx++];
1823         }
1824     }
1825     res->path[out] = 0;
1826
1827     /*
1828      * Steps c) to h) are really path normalization steps
1829      */
1830     normalize_uri_path(res->path);
1831
1832 step_7:
1833
1834     /*
1835      * 7) The resulting URI components, including any inherited from the
1836      *    base URI, are recombined to give the absolute form of the URI
1837      *    reference.
1838      */
1839     val = uri_to_string(res);
1840
1841 done:
1842     if (ref != NULL)
1843         uri_free(ref);
1844     if (bas != NULL)
1845         uri_free(bas);
1846     if (res != NULL)
1847         uri_free(res);
1848     return(val);
1849 }
1850
1851 /**
1852  * uri_resolve_relative:
1853  * @URI:  the URI reference under consideration
1854  * @base:  the base value
1855  *
1856  * Expresses the URI of the reference in terms relative to the
1857  * base.  Some examples of this operation include:
1858  *     base = "http://site1.com/docs/book1.html"
1859  *        URI input                        URI returned
1860  *     docs/pic1.gif                    pic1.gif
1861  *     docs/img/pic1.gif                img/pic1.gif
1862  *     img/pic1.gif                     ../img/pic1.gif
1863  *     http://site1.com/docs/pic1.gif   pic1.gif
1864  *     http://site2.com/docs/pic1.gif   http://site2.com/docs/pic1.gif
1865  *
1866  *     base = "docs/book1.html"
1867  *        URI input                        URI returned
1868  *     docs/pic1.gif                    pic1.gif
1869  *     docs/img/pic1.gif                img/pic1.gif
1870  *     img/pic1.gif                     ../img/pic1.gif
1871  *     http://site1.com/docs/pic1.gif   http://site1.com/docs/pic1.gif
1872  *
1873  *
1874  * Note: if the URI reference is really weird or complicated, it may be
1875  *       worthwhile to first convert it into a "nice" one by calling
1876  *       uri_resolve (using 'base') before calling this routine,
1877  *       since this routine (for reasonable efficiency) assumes URI has
1878  *       already been through some validation.
1879  *
1880  * Returns a new URI string (to be freed by the caller) or NULL in case
1881  * error.
1882  */
1883 char *
1884 uri_resolve_relative (const char *uri, const char * base)
1885 {
1886     char *val = NULL;
1887     int ret;
1888     int ix;
1889     int pos = 0;
1890     int nbslash = 0;
1891     int len;
1892     URI *ref = NULL;
1893     URI *bas = NULL;
1894     char *bptr, *uptr, *vptr;
1895     int remove_path = 0;
1896
1897     if ((uri == NULL) || (*uri == 0))
1898         return NULL;
1899
1900     /*
1901      * First parse URI into a standard form
1902      */
1903     ref = uri_new ();
1904     /* If URI not already in "relative" form */
1905     if (uri[0] != '.') {
1906         ret = uri_parse_into (ref, uri);
1907         if (ret != 0)
1908             goto done;          /* Error in URI, return NULL */
1909     } else
1910         ref->path = g_strdup(uri);
1911
1912     /*
1913      * Next parse base into the same standard form
1914      */
1915     if ((base == NULL) || (*base == 0)) {
1916         val = g_strdup (uri);
1917         goto done;
1918     }
1919     bas = uri_new ();
1920     if (base[0] != '.') {
1921         ret = uri_parse_into (bas, base);
1922         if (ret != 0)
1923             goto done;          /* Error in base, return NULL */
1924     } else
1925         bas->path = g_strdup(base);
1926
1927     /*
1928      * If the scheme / server on the URI differs from the base,
1929      * just return the URI
1930      */
1931     if ((ref->scheme != NULL) &&
1932         ((bas->scheme == NULL) ||
1933          (strcmp (bas->scheme, ref->scheme)) ||
1934          (strcmp (bas->server, ref->server)))) {
1935         val = g_strdup (uri);
1936         goto done;
1937     }
1938     if (bas->path == ref->path ||
1939         (bas->path && ref->path && !strcmp(bas->path, ref->path))) {
1940         val = g_strdup("");
1941         goto done;
1942     }
1943     if (bas->path == NULL) {
1944         val = g_strdup(ref->path);
1945         goto done;
1946     }
1947     if (ref->path == NULL) {
1948         ref->path = (char *) "/";
1949         remove_path = 1;
1950     }
1951
1952     /*
1953      * At this point (at last!) we can compare the two paths
1954      *
1955      * First we take care of the special case where either of the
1956      * two path components may be missing (bug 316224)
1957      */
1958     if (bas->path == NULL) {
1959         if (ref->path != NULL) {
1960             uptr = ref->path;
1961             if (*uptr == '/')
1962                 uptr++;
1963             /* exception characters from uri_to_string */
1964             val = uri_string_escape(uptr, "/;&=+$,");
1965         }
1966         goto done;
1967     }
1968     bptr = bas->path;
1969     if (ref->path == NULL) {
1970         for (ix = 0; bptr[ix] != 0; ix++) {
1971             if (bptr[ix] == '/')
1972                 nbslash++;
1973         }
1974         uptr = NULL;
1975         len = 1;        /* this is for a string terminator only */
1976     } else {
1977     /*
1978      * Next we compare the two strings and find where they first differ
1979      */
1980         if ((ref->path[pos] == '.') && (ref->path[pos+1] == '/'))
1981             pos += 2;
1982         if ((*bptr == '.') && (bptr[1] == '/'))
1983             bptr += 2;
1984         else if ((*bptr == '/') && (ref->path[pos] != '/'))
1985             bptr++;
1986         while ((bptr[pos] == ref->path[pos]) && (bptr[pos] != 0))
1987             pos++;
1988
1989         if (bptr[pos] == ref->path[pos]) {
1990             val = g_strdup("");
1991             goto done;          /* (I can't imagine why anyone would do this) */
1992         }
1993
1994         /*
1995          * In URI, "back up" to the last '/' encountered.  This will be the
1996          * beginning of the "unique" suffix of URI
1997          */
1998         ix = pos;
1999         if ((ref->path[ix] == '/') && (ix > 0))
2000             ix--;
2001         else if ((ref->path[ix] == 0) && (ix > 1) && (ref->path[ix - 1] == '/'))
2002             ix -= 2;
2003         for (; ix > 0; ix--) {
2004             if (ref->path[ix] == '/')
2005                 break;
2006         }
2007         if (ix == 0) {
2008             uptr = ref->path;
2009         } else {
2010             ix++;
2011             uptr = &ref->path[ix];
2012         }
2013
2014         /*
2015          * In base, count the number of '/' from the differing point
2016          */
2017         if (bptr[pos] != ref->path[pos]) {/* check for trivial URI == base */
2018             for (; bptr[ix] != 0; ix++) {
2019                 if (bptr[ix] == '/')
2020                     nbslash++;
2021             }
2022         }
2023         len = strlen (uptr) + 1;
2024     }
2025
2026     if (nbslash == 0) {
2027         if (uptr != NULL)
2028             /* exception characters from uri_to_string */
2029             val = uri_string_escape(uptr, "/;&=+$,");
2030         goto done;
2031     }
2032
2033     /*
2034      * Allocate just enough space for the returned string -
2035      * length of the remainder of the URI, plus enough space
2036      * for the "../" groups, plus one for the terminator
2037      */
2038     val = g_malloc (len + 3 * nbslash);
2039     vptr = val;
2040     /*
2041      * Put in as many "../" as needed
2042      */
2043     for (; nbslash>0; nbslash--) {
2044         *vptr++ = '.';
2045         *vptr++ = '.';
2046         *vptr++ = '/';
2047     }
2048     /*
2049      * Finish up with the end of the URI
2050      */
2051     if (uptr != NULL) {
2052         if ((vptr > val) && (len > 0) &&
2053             (uptr[0] == '/') && (vptr[-1] == '/')) {
2054             memcpy (vptr, uptr + 1, len - 1);
2055             vptr[len - 2] = 0;
2056         } else {
2057             memcpy (vptr, uptr, len);
2058             vptr[len - 1] = 0;
2059         }
2060     } else {
2061         vptr[len - 1] = 0;
2062     }
2063
2064     /* escape the freshly-built path */
2065     vptr = val;
2066         /* exception characters from uri_to_string */
2067     val = uri_string_escape(vptr, "/;&=+$,");
2068     g_free(vptr);
2069
2070 done:
2071     /*
2072      * Free the working variables
2073      */
2074     if (remove_path != 0)
2075         ref->path = NULL;
2076     if (ref != NULL)
2077         uri_free (ref);
2078     if (bas != NULL)
2079         uri_free (bas);
2080
2081     return val;
2082 }
2083
2084 /*
2085  * Utility functions to help parse and assemble query strings.
2086  */
2087
2088 struct QueryParams *
2089 query_params_new (int init_alloc)
2090 {
2091     struct QueryParams *ps;
2092
2093     if (init_alloc <= 0) init_alloc = 1;
2094
2095     ps = g_new(QueryParams, 1);
2096     ps->n = 0;
2097     ps->alloc = init_alloc;
2098     ps->p = g_new(QueryParam, ps->alloc);
2099
2100     return ps;
2101 }
2102
2103 /* Ensure there is space to store at least one more parameter
2104  * at the end of the set.
2105  */
2106 static int
2107 query_params_append (struct QueryParams *ps,
2108                const char *name, const char *value)
2109 {
2110     if (ps->n >= ps->alloc) {
2111         ps->p = g_renew(QueryParam, ps->p, ps->alloc * 2);
2112         ps->alloc *= 2;
2113     }
2114
2115     ps->p[ps->n].name = g_strdup(name);
2116     ps->p[ps->n].value = g_strdup(value);
2117     ps->p[ps->n].ignore = 0;
2118     ps->n++;
2119
2120     return 0;
2121 }
2122
2123 void
2124 query_params_free (struct QueryParams *ps)
2125 {
2126     int i;
2127
2128     for (i = 0; i < ps->n; ++i) {
2129         g_free (ps->p[i].name);
2130         g_free (ps->p[i].value);
2131     }
2132     g_free (ps->p);
2133     g_free (ps);
2134 }
2135
2136 struct QueryParams *
2137 query_params_parse (const char *query)
2138 {
2139     struct QueryParams *ps;
2140     const char *end, *eq;
2141
2142     ps = query_params_new (0);
2143     if (!query || query[0] == '\0') return ps;
2144
2145     while (*query) {
2146         char *name = NULL, *value = NULL;
2147
2148         /* Find the next separator, or end of the string. */
2149         end = strchr (query, '&');
2150         if (!end)
2151             end = strchr (query, ';');
2152         if (!end)
2153             end = query + strlen (query);
2154
2155         /* Find the first '=' character between here and end. */
2156         eq = strchr (query, '=');
2157         if (eq && eq >= end) eq = NULL;
2158
2159         /* Empty section (eg. "&&"). */
2160         if (end == query)
2161             goto next;
2162
2163         /* If there is no '=' character, then we have just "name"
2164          * and consistent with CGI.pm we assume value is "".
2165          */
2166         else if (!eq) {
2167             name = uri_string_unescape (query, end - query, NULL);
2168             value = NULL;
2169         }
2170         /* Or if we have "name=" here (works around annoying
2171          * problem when calling uri_string_unescape with len = 0).
2172          */
2173         else if (eq+1 == end) {
2174             name = uri_string_unescape (query, eq - query, NULL);
2175             value = g_new0(char, 1);
2176         }
2177         /* If the '=' character is at the beginning then we have
2178          * "=value" and consistent with CGI.pm we _ignore_ this.
2179          */
2180         else if (query == eq)
2181             goto next;
2182
2183         /* Otherwise it's "name=value". */
2184         else {
2185             name = uri_string_unescape (query, eq - query, NULL);
2186             value = uri_string_unescape (eq+1, end - (eq+1), NULL);
2187         }
2188
2189         /* Append to the parameter set. */
2190         query_params_append (ps, name, value);
2191         g_free(name);
2192         g_free(value);
2193
2194     next:
2195         query = end;
2196         if (*query) query ++; /* skip '&' separator */
2197     }
2198
2199     return ps;
2200 }
This page took 0.149702 seconds and 4 git commands to generate.