2 Copyright (C) 1995, 1996, 1997, 2000, 2001, 2003, 2003
3 Free Software Foundation, Inc.
5 This file is part of GNU Wget.
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or (at
10 your option) any later version.
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Wget; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 In addition, as a special exception, the Free Software Foundation
22 gives permission to link the code of its release of Wget with the
23 OpenSSL project's "OpenSSL" library (or with modified versions of it
24 that use the same license as the "OpenSSL" library), and distribute
25 the linked executables. You must obey the GNU General Public License
26 in all respects for all of the code used other than "OpenSSL". If you
27 modify this file, you may extend this exception to your version of the
28 file, but you are not obligated to do so. If you do not wish to do
29 so, delete this exception statement from your version. */
40 #include <sys/types.h>
62 /* Supported schemes: */
63 static struct scheme_data supported_schemes[] =
65 { "http://", DEFAULT_HTTP_PORT, 1 },
67 { "https://", DEFAULT_HTTPS_PORT, 1 },
69 { "ftp://", DEFAULT_FTP_PORT, 1 },
75 /* Forward declarations: */
77 static int path_simplify PARAMS ((char *));
79 /* Support for escaping and unescaping of URL strings. */
81 /* Table of "reserved" and "unsafe" characters. Those terms are
82 rfc1738-speak, as such largely obsoleted by rfc2396 and later
83 specs, but the general idea remains.
85 A reserved character is the one that you can't decode without
86 changing the meaning of the URL. For example, you can't decode
87 "/foo/%2f/bar" into "/foo///bar" because the number and contents of
88 path components is different. Non-reserved characters can be
89 changed, so "/foo/%78/bar" is safe to change to "/foo/x/bar". Wget
90 uses the rfc1738 set of reserved characters, plus "$" and ",", as
91 recommended by rfc2396.
93 An unsafe characters is the one that should be encoded when URLs
94 are placed in foreign environments. E.g. space and newline are
95 unsafe in HTTP contexts because HTTP uses them as separator and
96 terminator, so they must be encoded to %20 and %0A respectively.
97 "*" is unsafe in shell context, etc.
99 We determine whether a character is unsafe through static table
100 lookup. This code assumes ASCII character set and 8-bit chars. */
103 /* rfc1738 reserved chars + "$" and ",". */
106 /* rfc1738 unsafe chars, plus non-printables. */
110 #define urlchr_test(c, mask) (urlchr_table[(unsigned char)(c)] & (mask))
111 #define URL_RESERVED_CHAR(c) urlchr_test(c, urlchr_reserved)
112 #define URL_UNSAFE_CHAR(c) urlchr_test(c, urlchr_unsafe)
114 /* Shorthands for the table: */
115 #define R urlchr_reserved
116 #define U urlchr_unsafe
119 const static unsigned char urlchr_table[256] =
121 U, U, U, U, U, U, U, U, /* NUL SOH STX ETX EOT ENQ ACK BEL */
122 U, U, U, U, U, U, U, U, /* BS HT LF VT FF CR SO SI */
123 U, U, U, U, U, U, U, U, /* DLE DC1 DC2 DC3 DC4 NAK SYN ETB */
124 U, U, U, U, U, U, U, U, /* CAN EM SUB ESC FS GS RS US */
125 U, 0, U, RU, R, U, R, 0, /* SP ! " # $ % & ' */
126 0, 0, 0, R, R, 0, 0, R, /* ( ) * + , - . / */
127 0, 0, 0, 0, 0, 0, 0, 0, /* 0 1 2 3 4 5 6 7 */
128 0, 0, RU, R, U, R, U, R, /* 8 9 : ; < = > ? */
129 RU, 0, 0, 0, 0, 0, 0, 0, /* @ A B C D E F G */
130 0, 0, 0, 0, 0, 0, 0, 0, /* H I J K L M N O */
131 0, 0, 0, 0, 0, 0, 0, 0, /* P Q R S T U V W */
132 0, 0, 0, RU, U, RU, U, 0, /* X Y Z [ \ ] ^ _ */
133 U, 0, 0, 0, 0, 0, 0, 0, /* ` a b c d e f g */
134 0, 0, 0, 0, 0, 0, 0, 0, /* h i j k l m n o */
135 0, 0, 0, 0, 0, 0, 0, 0, /* p q r s t u v w */
136 0, 0, 0, U, U, U, U, U, /* x y z { | } ~ DEL */
138 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
139 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
140 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
141 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
143 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
144 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
145 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
146 U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
152 /* URL-unescape the string S.
154 This is done by transforming the sequences "%HH" to the character
155 represented by the hexadecimal digits HH. If % is not followed by
156 two hexadecimal digits, it is inserted literally.
158 The transformation is done in place. If you need the original
159 string intact, make a copy before calling this function. */
162 url_unescape (char *s)
164 char *t = s; /* t - tortoise */
165 char *h = s; /* h - hare */
176 /* Do nothing if '%' is not followed by two hex digits. */
177 if (!h[1] || !h[2] || !(ISXDIGIT (h[1]) && ISXDIGIT (h[2])))
179 *t = X2DIGITS_TO_NUM (h[1], h[2]);
186 /* The core of url_escape_* functions. Escapes the characters that
187 match the provided mask in urlchr_table.
189 If ALLOW_PASSTHROUGH is non-zero, a string with no unsafe chars
190 will be returned unchanged. If ALLOW_PASSTHROUGH is zero, a
191 freshly allocated string will be returned in all cases. */
194 url_escape_1 (const char *s, unsigned char mask, int allow_passthrough)
201 for (p1 = s; *p1; p1++)
202 if (urlchr_test (*p1, mask))
203 addition += 2; /* Two more characters (hex digits) */
206 return allow_passthrough ? (char *)s : xstrdup (s);
208 newlen = (p1 - s) + addition;
209 newstr = (char *)xmalloc (newlen + 1);
215 /* Quote the characters that match the test mask. */
216 if (urlchr_test (*p1, mask))
218 unsigned char c = *p1++;
220 *p2++ = XNUM_TO_DIGIT (c >> 4);
221 *p2++ = XNUM_TO_DIGIT (c & 0xf);
226 assert (p2 - newstr == newlen);
232 /* URL-escape the unsafe characters (see urlchr_table) in a given
233 string, returning a freshly allocated string. */
236 url_escape (const char *s)
238 return url_escape_1 (s, urlchr_unsafe, 0);
241 /* URL-escape the unsafe characters (see urlchr_table) in a given
242 string. If no characters are unsafe, S is returned. */
245 url_escape_allow_passthrough (const char *s)
247 return url_escape_1 (s, urlchr_unsafe, 1);
250 enum copy_method { CM_DECODE, CM_ENCODE, CM_PASSTHROUGH };
252 /* Decide whether to encode, decode, or pass through the char at P.
253 This used to be a macro, but it got a little too convoluted. */
254 static inline enum copy_method
255 decide_copy_method (const char *p)
259 if (ISXDIGIT (*(p + 1)) && ISXDIGIT (*(p + 2)))
261 /* %xx sequence: decode it, unless it would decode to an
262 unsafe or a reserved char; in that case, leave it as
264 char preempt = X2DIGITS_TO_NUM (*(p + 1), *(p + 2));
265 if (URL_UNSAFE_CHAR (preempt) || URL_RESERVED_CHAR (preempt))
266 return CM_PASSTHROUGH;
271 /* Garbled %.. sequence: encode `%'. */
274 else if (URL_UNSAFE_CHAR (*p) && !URL_RESERVED_CHAR (*p))
277 return CM_PASSTHROUGH;
280 /* Translate a %-escaped (but possibly non-conformant) input string S
281 into a %-escaped (and conformant) output string. If no characters
282 are encoded or decoded, return the same string S; otherwise, return
283 a freshly allocated string with the new contents.
285 After a URL has been run through this function, the protocols that
286 use `%' as the quote character can use the resulting string as-is,
287 while those that don't call url_unescape() to get to the intended
288 data. This function is also stable: after an input string is
289 transformed the first time, all further transformations of the
290 result yield the same result string.
292 Let's discuss why this function is needed.
294 Imagine Wget is to retrieve `http://abc.xyz/abc def'. Since a raw
295 space character would mess up the HTTP request, it needs to be
298 GET /abc%20def HTTP/1.0
300 It appears that the unsafe chars need to be quoted, for example
301 with url_escape. But what if we're requested to download
302 `abc%20def'? url_escape transforms "%" to "%25", which would leave
303 us with `abc%2520def'. This is incorrect -- since %-escapes are
304 part of URL syntax, "%20" is the correct way to denote a literal
305 space on the Wget command line. This leaves us in the conclusion
306 that in that case Wget should not call url_escape, but leave the
309 And what if the requested URI is `abc%20 def'? If we call
310 url_escape, we end up with `/abc%2520%20def', which is almost
311 certainly not intended. If we don't call url_escape, we are left
312 with the embedded space and cannot complete the request. What the
313 user meant was for Wget to request `/abc%20%20def', and this is
314 where reencode_escapes kicks in.
316 Wget used to solve this by first decoding %-quotes, and then
317 encoding all the "unsafe" characters found in the resulting string.
318 This was wrong because it didn't preserve certain URL special
319 (reserved) characters. For instance, URI containing "a%2B+b" (0x2b
320 == '+') would get translated to "a%2B%2Bb" or "a++b" depending on
321 whether we considered `+' reserved (it is). One of these results
322 is inevitable because by the second step we would lose information
323 on whether the `+' was originally encoded or not. Both results
324 were wrong because in CGI parameters + means space, while %2B means
325 literal plus. reencode_escapes correctly translates the above to
326 "a%2B+b", i.e. returns the original string.
328 This function uses an algorithm proposed by Anon Sricharoenchai:
330 1. Encode all URL_UNSAFE and the "%" that are not followed by 2
333 2. Decode all "%XX" except URL_UNSAFE, URL_RESERVED (";/?:@=&") and
336 ...except that this code conflates the two steps, and decides
337 whether to encode, decode, or pass through each character in turn.
338 The function still uses two passes, but their logic is the same --
339 the first pass exists merely for the sake of allocation. Another
340 small difference is that we include `+' to URL_RESERVED.
344 "http://abc.xyz/%20%3F%%36%31%25aa% a?a=%61+a%2Ba&b=b%26c%3Dc"
346 "http://abc.xyz/%20%3F%2561%25aa%25%20a?a=a+a%2Ba&b=b%26c%3Dc"
350 "foo bar" -> "foo%20bar"
351 "foo%20bar" -> "foo%20bar"
352 "foo %20bar" -> "foo%20%20bar"
353 "foo%%20bar" -> "foo%25%20bar" (0x25 == '%')
354 "foo%25%20bar" -> "foo%25%20bar"
355 "foo%2%20bar" -> "foo%252%20bar"
356 "foo+bar" -> "foo+bar" (plus is reserved!)
357 "foo%2b+bar" -> "foo%2b+bar" */
360 reencode_escapes (const char *s)
366 int encode_count = 0;
367 int decode_count = 0;
369 /* First, pass through the string to see if there's anything to do,
370 and to calculate the new length. */
371 for (p1 = s; *p1; p1++)
373 switch (decide_copy_method (p1))
386 if (!encode_count && !decode_count)
387 /* The string is good as it is. */
388 return (char *)s; /* C const model sucks. */
391 /* Each encoding adds two characters (hex digits), while each
392 decoding removes two characters. */
393 newlen = oldlen + 2 * (encode_count - decode_count);
394 newstr = xmalloc (newlen + 1);
401 switch (decide_copy_method (p1))
405 unsigned char c = *p1++;
407 *p2++ = XNUM_TO_DIGIT (c >> 4);
408 *p2++ = XNUM_TO_DIGIT (c & 0xf);
412 *p2++ = X2DIGITS_TO_NUM (p1[1], p1[2]);
413 p1 += 3; /* skip %xx */
420 assert (p2 - newstr == newlen);
424 /* Returns the scheme type if the scheme is supported, or
425 SCHEME_INVALID if not. */
428 url_scheme (const char *url)
432 for (i = 0; supported_schemes[i].leading_string; i++)
433 if (0 == strncasecmp (url, supported_schemes[i].leading_string,
434 strlen (supported_schemes[i].leading_string)))
436 if (supported_schemes[i].enabled)
437 return (enum url_scheme) i;
439 return SCHEME_INVALID;
442 return SCHEME_INVALID;
445 #define SCHEME_CHAR(ch) (ISALNUM (ch) || (ch) == '-' || (ch) == '+')
447 /* Return 1 if the URL begins with any "scheme", 0 otherwise. As
448 currently implemented, it returns true if URL begins with
452 url_has_scheme (const char *url)
456 /* The first char must be a scheme char. */
457 if (!*p || !SCHEME_CHAR (*p))
460 /* Followed by 0 or more scheme chars. */
461 while (*p && SCHEME_CHAR (*p))
463 /* Terminated by ':'. */
468 scheme_default_port (enum url_scheme scheme)
470 return supported_schemes[scheme].default_port;
474 scheme_disable (enum url_scheme scheme)
476 supported_schemes[scheme].enabled = 0;
479 /* Skip the username and password, if present here. The function
480 should *not* be called with the complete URL, but with the part
481 right after the scheme.
483 If no username and password are found, return 0. */
486 url_skip_credentials (const char *url)
488 /* Look for '@' that comes before terminators, such as '/', '?',
490 const char *p = (const char *)strpbrk (url, "@/?#;");
496 /* Parse credentials contained in [BEG, END). The region is expected
497 to have come from a URL and is unescaped. */
500 parse_credentials (const char *beg, const char *end, char **user, char **passwd)
506 return 0; /* empty user name */
508 colon = memchr (beg, ':', end - beg);
510 return 0; /* again empty user name */
514 *passwd = strdupdelim (colon + 1, end);
516 url_unescape (*passwd);
523 *user = strdupdelim (beg, userend);
524 url_unescape (*user);
528 /* Used by main.c: detect URLs written using the "shorthand" URL forms
529 popularized by Netscape and NcFTP. HTTP shorthands look like this:
531 www.foo.com[:port]/dir/file -> http://www.foo.com[:port]/dir/file
532 www.foo.com[:port] -> http://www.foo.com[:port]
534 FTP shorthands look like this:
536 foo.bar.com:dir/file -> ftp://foo.bar.com/dir/file
537 foo.bar.com:/absdir/file -> ftp://foo.bar.com//absdir/file
539 If the URL needs not or cannot be rewritten, return NULL. */
542 rewrite_shorthand_url (const char *url)
546 if (url_has_scheme (url))
549 /* Look for a ':' or '/'. The former signifies NcFTP syntax, the
551 for (p = url; *p && *p != ':' && *p != '/'; p++)
561 /* If the characters after the colon and before the next slash
562 or end of string are all digits, it's HTTP. */
564 for (pp = p + 1; ISDIGIT (*pp); pp++)
566 if (digits > 0 && (*pp == '/' || *pp == '\0'))
569 /* Prepend "ftp://" to the entire URL... */
570 res = xmalloc (6 + strlen (url) + 1);
571 sprintf (res, "ftp://%s", url);
572 /* ...and replace ':' with '/'. */
573 res[6 + (p - url)] = '/';
580 /* Just prepend "http://" to what we have. */
581 res = xmalloc (7 + strlen (url) + 1);
582 sprintf (res, "http://%s", url);
587 static void split_path PARAMS ((const char *, char **, char **));
589 /* Like strpbrk, with the exception that it returns the pointer to the
590 terminating zero (end-of-string aka "eos") if no matching character
593 Although I normally balk at Gcc-specific optimizations, it probably
594 makes sense here: glibc has optimizations that detect strpbrk being
595 called with literal string as ACCEPT and inline the search. That
596 optimization is defeated if strpbrk is hidden within the call to
597 another function. (And no, making strpbrk_or_eos inline doesn't
598 help because the check for literal accept is in the
603 #define strpbrk_or_eos(s, accept) ({ \
604 char *SOE_p = strpbrk (s, accept); \
606 SOE_p = (char *)s + strlen (s); \
610 #else /* not __GNUC__ */
613 strpbrk_or_eos (const char *s, const char *accept)
615 char *p = strpbrk (s, accept);
617 p = (char *)s + strlen (s);
622 /* Turn STR into lowercase; return non-zero if a character was
626 lowercase_str (char *str)
633 *str = TOLOWER (*str);
638 static char *parse_errors[] = {
639 #define PE_NO_ERROR 0
641 #define PE_UNSUPPORTED_SCHEME 1
642 N_("Unsupported scheme"),
643 #define PE_EMPTY_HOST 2
645 #define PE_BAD_PORT_NUMBER 3
646 N_("Bad port number"),
647 #define PE_INVALID_USER_NAME 4
648 N_("Invalid user name"),
649 #define PE_UNTERMINATED_IPV6_ADDRESS 5
650 N_("Unterminated IPv6 numeric address"),
651 #define PE_IPV6_NOT_SUPPORTED 6
652 N_("IPv6 addresses not supported"),
653 #define PE_INVALID_IPV6_ADDRESS 7
654 N_("Invalid IPv6 numeric address")
658 /* The following two functions were adapted from glibc. */
661 is_valid_ipv4_address (const char *str, const char *end)
671 if (ch >= '0' && ch <= '9')
673 val = val * 10 + (ch - '0');
684 else if (ch == '.' && saw_digit == 1)
701 is_valid_ipv6_address (const char *str, const char *end)
721 /* Leading :: requires some special handling. */
725 if (str == end || *str != ':')
737 /* if ch is a number, add it to val. */
741 val |= XDIGIT_TO_NUM (ch);
748 /* if ch is a colon ... */
761 if (tp > NS_IN6ADDRSZ - NS_INT16SZ)
769 /* if ch is a dot ... */
770 if (ch == '.' && (tp <= NS_IN6ADDRSZ - NS_INADDRSZ)
771 && is_valid_ipv4_address (curtok, end) == 1)
783 if (tp > NS_IN6ADDRSZ - NS_INT16SZ)
790 if (tp == NS_IN6ADDRSZ)
795 if (tp != NS_IN6ADDRSZ)
804 Return a new struct url if successful, NULL on error. In case of
805 error, and if ERROR is not NULL, also set *ERROR to the appropriate
808 url_parse (const char *url, int *error)
812 int path_modified, host_modified;
814 enum url_scheme scheme;
816 const char *uname_b, *uname_e;
817 const char *host_b, *host_e;
818 const char *path_b, *path_e;
819 const char *params_b, *params_e;
820 const char *query_b, *query_e;
821 const char *fragment_b, *fragment_e;
824 char *user = NULL, *passwd = NULL;
826 char *url_encoded = NULL;
830 scheme = url_scheme (url);
831 if (scheme == SCHEME_INVALID)
833 error_code = PE_UNSUPPORTED_SCHEME;
837 url_encoded = reencode_escapes (url);
840 p += strlen (supported_schemes[scheme].leading_string);
842 p += url_skip_credentials (p);
845 /* scheme://user:pass@host[:port]... */
848 /* We attempt to break down the URL into the components path,
849 params, query, and fragment. They are ordered like this:
851 scheme://host[:port][/path][;params][?query][#fragment] */
853 params_b = params_e = NULL;
854 query_b = query_e = NULL;
855 fragment_b = fragment_e = NULL;
861 /* Handle IPv6 address inside square brackets. Ideally we'd
862 just look for the terminating ']', but rfc2732 mandates
863 rejecting invalid IPv6 addresses. */
865 /* The address begins after '['. */
867 host_e = strchr (host_b, ']');
871 error_code = PE_UNTERMINATED_IPV6_ADDRESS;
876 /* Check if the IPv6 address is valid. */
877 if (!is_valid_ipv6_address(host_b, host_e))
879 error_code = PE_INVALID_IPV6_ADDRESS;
883 /* Continue parsing after the closing ']'. */
886 error_code = PE_IPV6_NOT_SUPPORTED;
892 p = strpbrk_or_eos (p, ":/;?#");
896 if (host_b == host_e)
898 error_code = PE_EMPTY_HOST;
902 port = scheme_default_port (scheme);
905 const char *port_b, *port_e, *pp;
907 /* scheme://host:port/tralala */
911 p = strpbrk_or_eos (p, "/;?#");
914 /* Allow empty port, as per rfc2396. */
915 if (port_b != port_e)
917 for (port = 0, pp = port_b; pp < port_e; pp++)
921 /* http://host:12randomgarbage/blah */
923 error_code = PE_BAD_PORT_NUMBER;
926 port = 10 * port + (*pp - '0');
935 p = strpbrk_or_eos (p, ";?#");
940 /* Path is not allowed not to exist. */
948 p = strpbrk_or_eos (p, "?#");
955 p = strpbrk_or_eos (p, "#");
958 /* Hack that allows users to use '?' (a wildcard character) in
959 FTP URLs without it being interpreted as a query string
961 if (scheme == SCHEME_FTP)
963 query_b = query_e = NULL;
976 if (uname_b != uname_e)
978 /* http://user:pass@host */
980 /* uname_b uname_e */
981 if (!parse_credentials (uname_b, uname_e - 1, &user, &passwd))
983 error_code = PE_INVALID_USER_NAME;
988 u = xnew0 (struct url);
990 u->host = strdupdelim (host_b, host_e);
995 u->path = strdupdelim (path_b, path_e);
996 path_modified = path_simplify (u->path);
997 split_path (u->path, &u->dir, &u->file);
999 host_modified = lowercase_str (u->host);
1002 u->params = strdupdelim (params_b, params_e);
1004 u->query = strdupdelim (query_b, query_e);
1006 u->fragment = strdupdelim (fragment_b, fragment_e);
1008 if (path_modified || u->fragment || host_modified || path_b == path_e)
1010 /* If we suspect that a transformation has rendered what
1011 url_string might return different from URL_ENCODED, rebuild
1012 u->url using url_string. */
1013 u->url = url_string (u, 0);
1015 if (url_encoded != url)
1016 xfree ((char *) url_encoded);
1020 if (url_encoded == url)
1021 u->url = xstrdup (url);
1023 u->url = url_encoded;
1030 /* Cleanup in case of error: */
1031 if (url_encoded && url_encoded != url)
1032 xfree (url_encoded);
1034 /* Transmit the error code to the caller, if the caller wants to
1037 *error = error_code;
1041 /* Return the error message string from ERROR_CODE, which should have
1042 been retrieved from url_parse. The error message is translated. */
1045 url_error (int error_code)
1047 assert (error_code >= 0 && error_code < countof (parse_errors));
1048 return _(parse_errors[error_code]);
1051 /* Split PATH into DIR and FILE. PATH comes from the URL and is
1052 expected to be URL-escaped.
1054 The path is split into directory (the part up to the last slash)
1055 and file (the part after the last slash), which are subsequently
1056 unescaped. Examples:
1059 "foo/bar/baz" "foo/bar" "baz"
1060 "foo/bar/" "foo/bar" ""
1062 "foo/bar/baz%2fqux" "foo/bar" "baz/qux" (!)
1064 DIR and FILE are freshly allocated. */
1067 split_path (const char *path, char **dir, char **file)
1069 char *last_slash = strrchr (path, '/');
1072 *dir = xstrdup ("");
1073 *file = xstrdup (path);
1077 *dir = strdupdelim (path, last_slash);
1078 *file = xstrdup (last_slash + 1);
1080 url_unescape (*dir);
1081 url_unescape (*file);
1084 /* Note: URL's "full path" is the path with the query string and
1085 params appended. The "fragment" (#foo) is intentionally ignored,
1086 but that might be changed. For example, if the original URL was
1087 "http://host:port/foo/bar/baz;bullshit?querystring#uselessfragment",
1088 the full path will be "/foo/bar/baz;bullshit?querystring". */
1090 /* Return the length of the full path, without the terminating
1094 full_path_length (const struct url *url)
1098 #define FROB(el) if (url->el) len += 1 + strlen (url->el)
1109 /* Write out the full path. */
1112 full_path_write (const struct url *url, char *where)
1114 #define FROB(el, chr) do { \
1115 char *f_el = url->el; \
1117 int l = strlen (f_el); \
1119 memcpy (where, f_el, l); \
1131 /* Public function for getting the "full path". E.g. if u->path is
1132 "foo/bar" and u->query is "param=value", full_path will be
1133 "/foo/bar?param=value". */
1136 url_full_path (const struct url *url)
1138 int length = full_path_length (url);
1139 char *full_path = (char *)xmalloc(length + 1);
1141 full_path_write (url, full_path);
1142 full_path[length] = '\0';
1147 /* Escape unsafe and reserved characters, except for the slash
1151 url_escape_dir (const char *dir)
1153 char *newdir = url_escape_1 (dir, urlchr_unsafe | urlchr_reserved, 1);
1158 /* Unescape slashes in NEWDIR. */
1160 h = newdir; /* hare */
1161 t = newdir; /* tortoise */
1163 for (; *h; h++, t++)
1165 /* url_escape_1 having converted '/' to "%2F" exactly. */
1166 if (*h == '%' && h[1] == '2' && h[2] == 'F')
1179 /* Sync u->path and u->url with u->dir and u->file. Called after
1180 u->file or u->dir have been changed, typically by the FTP code. */
1183 sync_path (struct url *u)
1185 char *newpath, *efile, *edir;
1189 /* u->dir and u->file are not escaped. URL-escape them before
1190 reassembling them into u->path. That way, if they contain
1191 separators like '?' or even if u->file contains slashes, the
1192 path will be correctly assembled. (u->file can contain slashes
1193 if the URL specifies it with %2f, or if an FTP server returns
1195 edir = url_escape_dir (u->dir);
1196 efile = url_escape_1 (u->file, urlchr_unsafe | urlchr_reserved, 1);
1199 newpath = xstrdup (efile);
1202 int dirlen = strlen (edir);
1203 int filelen = strlen (efile);
1205 /* Copy "DIR/FILE" to newpath. */
1206 char *p = newpath = xmalloc (dirlen + 1 + filelen + 1);
1207 memcpy (p, edir, dirlen);
1210 memcpy (p, efile, filelen);
1219 if (efile != u->file)
1222 /* Regenerate u->url as well. */
1224 u->url = url_string (u, 0);
1227 /* Mutators. Code in ftp.c insists on changing u->dir and u->file.
1228 This way we can sync u->path and u->url when they get changed. */
1231 url_set_dir (struct url *url, const char *newdir)
1234 url->dir = xstrdup (newdir);
1239 url_set_file (struct url *url, const char *newfile)
1242 url->file = xstrdup (newfile);
1247 url_free (struct url *url)
1253 xfree_null (url->params);
1254 xfree_null (url->query);
1255 xfree_null (url->fragment);
1256 xfree_null (url->user);
1257 xfree_null (url->passwd);
1265 /* Create all the necessary directories for PATH (a file). Calls
1266 mkdirhier() internally. */
1268 mkalldirs (const char *path)
1275 p = path + strlen (path);
1276 for (; *p != '/' && p != path; p--)
1279 /* Don't create if it's just a file. */
1280 if ((p == path) && (*p != '/'))
1282 t = strdupdelim (path, p);
1284 /* Check whether the directory exists. */
1285 if ((stat (t, &st) == 0))
1287 if (S_ISDIR (st.st_mode))
1294 /* If the dir exists as a file name, remove it first. This
1295 is *only* for Wget to work with buggy old CERN http
1296 servers. Here is the scenario: When Wget tries to
1297 retrieve a directory without a slash, e.g.
1298 http://foo/bar (bar being a directory), CERN server will
1299 not redirect it too http://foo/bar/ -- it will generate a
1300 directory listing containing links to bar/file1,
1301 bar/file2, etc. Wget will lose because it saves this
1302 HTML listing to a file `bar', so it cannot create the
1303 directory. To work around this, if the file of the same
1304 name exists, we just remove it and create the directory
1306 DEBUGP (("Removing %s because of directory danger!\n", t));
1310 res = make_directory (t);
1312 logprintf (LOG_NOTQUIET, "%s: %s", t, strerror (errno));
1317 /* Functions for constructing the file name out of URL components. */
1319 /* A growable string structure, used by url_file_name and friends.
1320 This should perhaps be moved to utils.c.
1322 The idea is to have a convenient and efficient way to construct a
1323 string by having various functions append data to it. Instead of
1324 passing the obligatory BASEVAR, SIZEVAR and TAILPOS to all the
1325 functions in questions, we pass the pointer to this struct. */
1333 /* Ensure that the string can accept APPEND_COUNT more characters past
1334 the current TAIL position. If necessary, this will grow the string
1335 and update its allocated size. If the string is already large
1336 enough to take TAIL+APPEND_COUNT characters, this does nothing. */
1337 #define GROW(g, append_size) do { \
1338 struct growable *G_ = g; \
1339 DO_REALLOC (G_->base, G_->size, G_->tail + append_size, char); \
1342 /* Return the tail position of the string. */
1343 #define TAIL(r) ((r)->base + (r)->tail)
1345 /* Move the tail position by APPEND_COUNT characters. */
1346 #define TAIL_INCR(r, append_count) ((r)->tail += append_count)
1348 /* Append the string STR to DEST. NOTICE: the string in DEST is not
1352 append_string (const char *str, struct growable *dest)
1354 int l = strlen (str);
1356 memcpy (TAIL (dest), str, l);
1357 TAIL_INCR (dest, l);
1360 /* Append CH to DEST. For example, append_char (0, DEST)
1361 zero-terminates DEST. */
1364 append_char (char ch, struct growable *dest)
1368 TAIL_INCR (dest, 1);
1372 filechr_not_unix = 1, /* unusable on Unix, / and \0 */
1373 filechr_not_windows = 2, /* unusable on Windows, one of \|/<>?:*" */
1374 filechr_control = 4 /* a control character, e.g. 0-31 */
1377 #define FILE_CHAR_TEST(c, mask) (filechr_table[(unsigned char)(c)] & (mask))
1379 /* Shorthands for the table: */
1380 #define U filechr_not_unix
1381 #define W filechr_not_windows
1382 #define C filechr_control
1387 /* Table of characters unsafe under various conditions (see above).
1389 Arguably we could also claim `%' to be unsafe, since we use it as
1390 the escape character. If we ever want to be able to reliably
1391 translate file name back to URL, this would become important
1392 crucial. Right now, it's better to be minimal in escaping. */
1394 const static unsigned char filechr_table[256] =
1396 UWC, C, C, C, C, C, C, C, /* NUL SOH STX ETX EOT ENQ ACK BEL */
1397 C, C, C, C, C, C, C, C, /* BS HT LF VT FF CR SO SI */
1398 C, C, C, C, C, C, C, C, /* DLE DC1 DC2 DC3 DC4 NAK SYN ETB */
1399 C, C, C, C, C, C, C, C, /* CAN EM SUB ESC FS GS RS US */
1400 0, 0, W, 0, 0, 0, 0, 0, /* SP ! " # $ % & ' */
1401 0, 0, W, 0, 0, 0, 0, UW, /* ( ) * + , - . / */
1402 0, 0, 0, 0, 0, 0, 0, 0, /* 0 1 2 3 4 5 6 7 */
1403 0, 0, W, 0, W, 0, W, W, /* 8 9 : ; < = > ? */
1404 0, 0, 0, 0, 0, 0, 0, 0, /* @ A B C D E F G */
1405 0, 0, 0, 0, 0, 0, 0, 0, /* H I J K L M N O */
1406 0, 0, 0, 0, 0, 0, 0, 0, /* P Q R S T U V W */
1407 0, 0, 0, 0, W, 0, 0, 0, /* X Y Z [ \ ] ^ _ */
1408 0, 0, 0, 0, 0, 0, 0, 0, /* ` a b c d e f g */
1409 0, 0, 0, 0, 0, 0, 0, 0, /* h i j k l m n o */
1410 0, 0, 0, 0, 0, 0, 0, 0, /* p q r s t u v w */
1411 0, 0, 0, 0, 0, 0, 0, 0, /* x y z { | } ~ DEL */
1413 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, /* 128-143 */
1414 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, /* 144-159 */
1415 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1416 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1418 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1419 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1420 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1421 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1429 /* FN_PORT_SEP is the separator between host and port in file names
1430 for non-standard port numbers. On Unix this is normally ':', as in
1431 "www.xemacs.org:4001/index.html". Under Windows, we set it to +
1432 because Windows can't handle ':' in file names. */
1433 #define FN_PORT_SEP (opt.restrict_files_os != restrict_windows ? ':' : '+')
1435 /* FN_QUERY_SEP is the separator between the file name and the URL
1436 query, normally '?'. Since Windows cannot handle '?' as part of
1437 file name, we use '@' instead there. */
1438 #define FN_QUERY_SEP (opt.restrict_files_os != restrict_windows ? '?' : '@')
1440 /* Quote path element, characters in [b, e), as file name, and append
1441 the quoted string to DEST. Each character is quoted as per
1442 file_unsafe_char and the corresponding table.
1444 If ESCAPED_P is non-zero, the path element is considered to be
1445 URL-escaped and will be unescaped prior to inspection. */
1448 append_uri_pathel (const char *b, const char *e, int escaped_p,
1449 struct growable *dest)
1455 if (opt.restrict_files_os == restrict_unix)
1456 mask = filechr_not_unix;
1458 mask = filechr_not_windows;
1459 if (opt.restrict_files_ctrl)
1460 mask |= filechr_control;
1462 /* Copy [b, e) to PATHEL and URL-unescape it. */
1466 BOUNDED_TO_ALLOCA (b, e, unescaped);
1467 url_unescape (unescaped);
1469 e = unescaped + strlen (unescaped);
1472 /* Defang ".." when found as component of path. Remember that path
1473 comes from the URL and might contain malicious input. */
1474 if (e - b == 2 && b[0] == '.' && b[1] == '.')
1480 /* Walk the PATHEL string and check how many characters we'll need
1483 for (p = b; p < e; p++)
1484 if (FILE_CHAR_TEST (*p, mask))
1487 /* Calculate the length of the output string. e-b is the input
1488 string length. Each quoted char introduces two additional
1489 characters in the string, hence 2*quoted. */
1490 outlen = (e - b) + (2 * quoted);
1491 GROW (dest, outlen);
1495 /* If there's nothing to quote, we can simply append the string
1496 without processing it again. */
1497 memcpy (TAIL (dest), b, outlen);
1501 char *q = TAIL (dest);
1502 for (p = b; p < e; p++)
1504 if (!FILE_CHAR_TEST (*p, mask))
1508 unsigned char ch = *p;
1510 *q++ = XNUM_TO_DIGIT (ch >> 4);
1511 *q++ = XNUM_TO_DIGIT (ch & 0xf);
1514 assert (q - TAIL (dest) == outlen);
1516 TAIL_INCR (dest, outlen);
1519 /* Append to DEST the directory structure that corresponds the
1520 directory part of URL's path. For example, if the URL is
1521 http://server/dir1/dir2/file, this appends "/dir1/dir2".
1523 Each path element ("dir1" and "dir2" in the above example) is
1524 examined, url-unescaped, and re-escaped as file name element.
1526 Additionally, it cuts as many directories from the path as
1527 specified by opt.cut_dirs. For example, if opt.cut_dirs is 1, it
1528 will produce "bar" for the above example. For 2 or more, it will
1531 Each component of the path is quoted for use as file name. */
1534 append_dir_structure (const struct url *u, struct growable *dest)
1536 char *pathel, *next;
1537 int cut = opt.cut_dirs;
1539 /* Go through the path components, de-URL-quote them, and quote them
1540 (if necessary) as file names. */
1543 for (; (next = strchr (pathel, '/')) != NULL; pathel = next + 1)
1548 /* Ignore empty pathels. */
1552 append_char ('/', dest);
1553 append_uri_pathel (pathel, next, 1, dest);
1557 /* Return a unique file name that matches the given URL as good as
1558 possible. Does not create directories on the file system. */
1561 url_file_name (const struct url *u)
1563 struct growable fnres;
1565 char *u_file, *u_query;
1566 char *fname, *unique;
1572 /* Start with the directory prefix, if specified. */
1574 append_string (opt.dir_prefix, &fnres);
1576 /* If "dirstruct" is turned on (typically the case with -r), add
1577 the host and port (unless those have been turned off) and
1578 directory structure. */
1581 if (opt.add_hostdir)
1584 append_char ('/', &fnres);
1585 append_string (u->host, &fnres);
1586 if (u->port != scheme_default_port (u->scheme))
1589 number_to_string (portstr, u->port);
1590 append_char (FN_PORT_SEP, &fnres);
1591 append_string (portstr, &fnres);
1595 append_dir_structure (u, &fnres);
1598 /* Add the file name. */
1600 append_char ('/', &fnres);
1601 u_file = *u->file ? u->file : "index.html";
1602 append_uri_pathel (u_file, u_file + strlen (u_file), 0, &fnres);
1604 /* Append "?query" to the file name. */
1605 u_query = u->query && *u->query ? u->query : NULL;
1608 append_char (FN_QUERY_SEP, &fnres);
1609 append_uri_pathel (u_query, u_query + strlen (u_query), 1, &fnres);
1612 /* Zero-terminate the file name. */
1613 append_char ('\0', &fnres);
1617 /* Check the cases in which the unique extensions are not used:
1618 1) Clobbering is turned off (-nc).
1619 2) Retrieval with regetting.
1620 3) Timestamping is used.
1621 4) Hierarchy is built.
1623 The exception is the case when file does exist and is a
1624 directory (see `mkalldirs' for explanation). */
1626 if ((opt.noclobber || opt.always_rest || opt.timestamping || opt.dirstruct)
1627 && !(file_exists_p (fname) && !file_non_directory_p (fname)))
1630 unique = unique_name (fname, 1);
1631 if (unique != fname)
1636 /* Resolve "." and ".." elements of PATH by destructively modifying
1637 PATH and return non-zero if PATH has been modified, zero otherwise.
1639 The algorithm is in spirit similar to the one described in rfc1808,
1640 although implemented differently, in one pass. To recap, path
1641 elements containing only "." are removed, and ".." is taken to mean
1642 "back up one element". Single leading and trailing slashes are
1645 This function does not handle URL escapes explicitly. If you're
1646 passing paths from URLs, make sure to unquote "%2e" and "%2E" to
1647 ".", so that this function can find the dots. (Wget's URL parser
1648 calls reencode_escapes, which see.)
1650 For example, "a/b/c/./../d/.." will yield "a/b/". More exhaustive
1651 test examples are provided below. If you change anything in this
1652 function, run test_path_simplify to make sure you haven't broken a
1656 path_simplify (char *path)
1658 char *h = path; /* hare */
1659 char *t = path; /* tortoise */
1660 char *beg = path; /* boundary for backing the tortoise */
1661 char *end = path + strlen (path);
1665 /* Hare should be at the beginning of a path element. */
1667 if (h[0] == '.' && (h[1] == '/' || h[1] == '\0'))
1672 else if (h[0] == '.' && h[1] == '.' && (h[2] == '/' || h[2] == '\0'))
1674 /* Handle "../" by retreating the tortoise by one path
1675 element -- but not past beggining. */
1678 /* Move backwards until T hits the beginning of the
1679 previous path element or the beginning of path. */
1680 for (--t; t > beg && t[-1] != '/'; t--)
1685 /* If we're at the beginning, copy the "../" literally
1686 move the beginning so a later ".." doesn't remove
1696 /* A regular path element. If H hasn't advanced past T,
1697 simply skip to the next path element. Otherwise, copy
1698 the path element until the next slash. */
1701 /* Skip the path element, including the slash. */
1702 while (h < end && *h != '/')
1709 /* Copy the path element, including the final slash. */
1710 while (h < end && *h != '/')
1724 /* Return the length of URL's path. Path is considered to be
1725 terminated by one of '?', ';', '#', or by the end of the
1729 path_length (const char *url)
1731 const char *q = strpbrk_or_eos (url, "?;#");
1735 /* Find the last occurrence of character C in the range [b, e), or
1736 NULL, if none are present. We might want to use memrchr (a GNU
1737 extension) under GNU libc. */
1740 find_last_char (const char *b, const char *e, char c)
1748 /* Merge BASE with LINK and return the resulting URI.
1750 Either of the URIs may be absolute or relative, complete with the
1751 host name, or path only. This tries to reasonably handle all
1752 foreseeable cases. It only employs minimal URL parsing, without
1753 knowledge of the specifics of schemes.
1755 I briefly considered making this function call path_simplify after
1756 the merging process, as rfc1738 seems to suggest. This is a bad
1757 idea for several reasons: 1) it complexifies the code, and 2)
1758 url_parse has to simplify path anyway, so it's wasteful to boot. */
1761 uri_merge (const char *base, const char *link)
1767 if (url_has_scheme (link))
1768 return xstrdup (link);
1770 /* We may not examine BASE past END. */
1771 end = base + path_length (base);
1772 linklength = strlen (link);
1776 /* Empty LINK points back to BASE, query string and all. */
1777 return xstrdup (base);
1779 else if (*link == '?')
1781 /* LINK points to the same location, but changes the query
1782 string. Examples: */
1783 /* uri_merge("path", "?new") -> "path?new" */
1784 /* uri_merge("path?foo", "?new") -> "path?new" */
1785 /* uri_merge("path?foo#bar", "?new") -> "path?new" */
1786 /* uri_merge("path#foo", "?new") -> "path?new" */
1787 int baselength = end - base;
1788 merge = xmalloc (baselength + linklength + 1);
1789 memcpy (merge, base, baselength);
1790 memcpy (merge + baselength, link, linklength);
1791 merge[baselength + linklength] = '\0';
1793 else if (*link == '#')
1795 /* uri_merge("path", "#new") -> "path#new" */
1796 /* uri_merge("path#foo", "#new") -> "path#new" */
1797 /* uri_merge("path?foo", "#new") -> "path?foo#new" */
1798 /* uri_merge("path?foo#bar", "#new") -> "path?foo#new" */
1800 const char *end1 = strchr (base, '#');
1802 end1 = base + strlen (base);
1803 baselength = end1 - base;
1804 merge = xmalloc (baselength + linklength + 1);
1805 memcpy (merge, base, baselength);
1806 memcpy (merge + baselength, link, linklength);
1807 merge[baselength + linklength] = '\0';
1809 else if (*link == '/' && *(link + 1) == '/')
1811 /* LINK begins with "//" and so is a net path: we need to
1812 replace everything after (and including) the double slash
1815 /* uri_merge("foo", "//new/bar") -> "//new/bar" */
1816 /* uri_merge("//old/foo", "//new/bar") -> "//new/bar" */
1817 /* uri_merge("http://old/foo", "//new/bar") -> "http://new/bar" */
1821 const char *start_insert;
1823 /* Look for first slash. */
1824 slash = memchr (base, '/', end - base);
1825 /* If found slash and it is a double slash, then replace
1826 from this point, else default to replacing from the
1828 if (slash && *(slash + 1) == '/')
1829 start_insert = slash;
1831 start_insert = base;
1833 span = start_insert - base;
1834 merge = (char *)xmalloc (span + linklength + 1);
1836 memcpy (merge, base, span);
1837 memcpy (merge + span, link, linklength);
1838 merge[span + linklength] = '\0';
1840 else if (*link == '/')
1842 /* LINK is an absolute path: we need to replace everything
1843 after (and including) the FIRST slash with LINK.
1845 So, if BASE is "http://host/whatever/foo/bar", and LINK is
1846 "/qux/xyzzy", our result should be
1847 "http://host/qux/xyzzy". */
1850 const char *start_insert = NULL; /* for gcc to shut up. */
1851 const char *pos = base;
1852 int seen_slash_slash = 0;
1853 /* We're looking for the first slash, but want to ignore
1856 slash = memchr (pos, '/', end - pos);
1857 if (slash && !seen_slash_slash)
1858 if (*(slash + 1) == '/')
1861 seen_slash_slash = 1;
1865 /* At this point, SLASH is the location of the first / after
1866 "//", or the first slash altogether. START_INSERT is the
1867 pointer to the location where LINK will be inserted. When
1868 examining the last two examples, keep in mind that LINK
1871 if (!slash && !seen_slash_slash)
1872 /* example: "foo" */
1874 start_insert = base;
1875 else if (!slash && seen_slash_slash)
1876 /* example: "http://foo" */
1879 else if (slash && !seen_slash_slash)
1880 /* example: "foo/bar" */
1882 start_insert = base;
1883 else if (slash && seen_slash_slash)
1884 /* example: "http://something/" */
1886 start_insert = slash;
1888 span = start_insert - base;
1889 merge = (char *)xmalloc (span + linklength + 1);
1891 memcpy (merge, base, span);
1892 memcpy (merge + span, link, linklength);
1893 merge[span + linklength] = '\0';
1897 /* LINK is a relative URL: we need to replace everything
1898 after last slash (possibly empty) with LINK.
1900 So, if BASE is "whatever/foo/bar", and LINK is "qux/xyzzy",
1901 our result should be "whatever/foo/qux/xyzzy". */
1902 int need_explicit_slash = 0;
1904 const char *start_insert;
1905 const char *last_slash = find_last_char (base, end, '/');
1908 /* No slash found at all. Replace what we have with LINK. */
1909 start_insert = base;
1911 else if (last_slash && last_slash >= base + 2
1912 && last_slash[-2] == ':' && last_slash[-1] == '/')
1914 /* example: http://host" */
1916 start_insert = end + 1;
1917 need_explicit_slash = 1;
1921 /* example: "whatever/foo/bar" */
1923 start_insert = last_slash + 1;
1926 span = start_insert - base;
1927 merge = (char *)xmalloc (span + linklength + 1);
1929 memcpy (merge, base, span);
1930 if (need_explicit_slash)
1931 merge[span - 1] = '/';
1932 memcpy (merge + span, link, linklength);
1933 merge[span + linklength] = '\0';
1939 #define APPEND(p, s) do { \
1940 int len = strlen (s); \
1941 memcpy (p, s, len); \
1945 /* Use this instead of password when the actual password is supposed
1946 to be hidden. We intentionally use a generic string without giving
1947 away the number of characters in the password, like previous
1949 #define HIDDEN_PASSWORD "*password*"
1951 /* Recreate the URL string from the data in URL.
1953 If HIDE is non-zero (as it is when we're calling this on a URL we
1954 plan to print, but not when calling it to canonicalize a URL for
1955 use within the program), password will be hidden. Unsafe
1956 characters in the URL will be quoted. */
1959 url_string (const struct url *url, int hide_password)
1963 char *quoted_user = NULL, *quoted_passwd = NULL;
1965 int scheme_port = supported_schemes[url->scheme].default_port;
1966 char *scheme_str = supported_schemes[url->scheme].leading_string;
1967 int fplen = full_path_length (url);
1969 int brackets_around_host = 0;
1971 assert (scheme_str != NULL);
1973 /* Make sure the user name and password are quoted. */
1976 quoted_user = url_escape_allow_passthrough (url->user);
1980 quoted_passwd = HIDDEN_PASSWORD;
1982 quoted_passwd = url_escape_allow_passthrough (url->passwd);
1986 if (strchr (url->host, ':'))
1987 brackets_around_host = 1;
1989 size = (strlen (scheme_str)
1990 + strlen (url->host)
1991 + (brackets_around_host ? 2 : 0)
1994 if (url->port != scheme_port)
1995 size += 1 + numdigit (url->port);
1998 size += 1 + strlen (quoted_user);
2000 size += 1 + strlen (quoted_passwd);
2003 p = result = xmalloc (size);
2005 APPEND (p, scheme_str);
2008 APPEND (p, quoted_user);
2012 APPEND (p, quoted_passwd);
2017 if (brackets_around_host)
2019 APPEND (p, url->host);
2020 if (brackets_around_host)
2022 if (url->port != scheme_port)
2025 p = number_to_string (p, url->port);
2028 full_path_write (url, p);
2032 assert (p - result == size);
2034 if (quoted_user && quoted_user != url->user)
2035 xfree (quoted_user);
2036 if (quoted_passwd && !hide_password
2037 && quoted_passwd != url->passwd)
2038 xfree (quoted_passwd);
2043 /* Return non-zero if scheme a is similar to scheme b.
2045 Schemes are similar if they are equal. If SSL is supported, schemes
2046 are also similar if one is http (SCHEME_HTTP) and the other is https
2049 schemes_are_similar_p (enum url_scheme a, enum url_scheme b)
2054 if ((a == SCHEME_HTTP && b == SCHEME_HTTPS)
2055 || (a == SCHEME_HTTPS && b == SCHEME_HTTP))
2062 /* Debugging and testing support for path_simplify. */
2064 /* Debug: run path_simplify on PATH and return the result in a new
2065 string. Useful for calling from the debugger. */
2069 char *copy = xstrdup (path);
2070 path_simplify (copy);
2075 run_test (char *test, char *expected_result, int expected_change)
2077 char *test_copy = xstrdup (test);
2078 int modified = path_simplify (test_copy);
2080 if (0 != strcmp (test_copy, expected_result))
2082 printf ("Failed path_simplify(\"%s\"): expected \"%s\", got \"%s\".\n",
2083 test, expected_result, test_copy);
2085 if (modified != expected_change)
2087 if (expected_change == 1)
2088 printf ("Expected modification with path_simplify(\"%s\").\n",
2091 printf ("Expected no modification with path_simplify(\"%s\").\n",
2098 test_path_simplify (void)
2101 char *test, *result;
2108 { "../", "../", 0 },
2109 { "foo", "foo", 0 },
2110 { "foo/bar", "foo/bar", 0 },
2111 { "foo///bar", "foo///bar", 0 },
2112 { "foo/.", "foo/", 1 },
2113 { "foo/./", "foo/", 1 },
2114 { "foo./", "foo./", 0 },
2115 { "foo/../bar", "bar", 1 },
2116 { "foo/../bar/", "bar/", 1 },
2117 { "foo/bar/..", "foo/", 1 },
2118 { "foo/bar/../x", "foo/x", 1 },
2119 { "foo/bar/../x/", "foo/x/", 1 },
2120 { "foo/..", "", 1 },
2121 { "foo/../..", "..", 1 },
2122 { "foo/../../..", "../..", 1 },
2123 { "foo/../../bar/../../baz", "../../baz", 1 },
2124 { "a/b/../../c", "c", 1 },
2125 { "./a/../b", "b", 1 }
2129 for (i = 0; i < countof (tests); i++)
2131 char *test = tests[i].test;
2132 char *expected_result = tests[i].result;
2133 int expected_change = tests[i].should_modify;
2134 run_test (test, expected_result, expected_change);