Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.61
      1  1.61    itojun /*	$NetBSD: fetch.c,v 1.61 1999/07/04 22:46:20 itojun Exp $	*/
      2   1.1     lukem 
      3   1.1     lukem /*-
      4  1.50     lukem  * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
      5   1.1     lukem  * All rights reserved.
      6   1.1     lukem  *
      7   1.1     lukem  * This code is derived from software contributed to The NetBSD Foundation
      8  1.54     lukem  * by Luke Mewburn.
      9   1.1     lukem  *
     10   1.1     lukem  * Redistribution and use in source and binary forms, with or without
     11   1.1     lukem  * modification, are permitted provided that the following conditions
     12   1.1     lukem  * are met:
     13   1.1     lukem  * 1. Redistributions of source code must retain the above copyright
     14   1.1     lukem  *    notice, this list of conditions and the following disclaimer.
     15   1.1     lukem  * 2. Redistributions in binary form must reproduce the above copyright
     16   1.1     lukem  *    notice, this list of conditions and the following disclaimer in the
     17   1.1     lukem  *    documentation and/or other materials provided with the distribution.
     18   1.1     lukem  * 3. All advertising materials mentioning features or use of this software
     19   1.1     lukem  *    must display the following acknowledgement:
     20   1.1     lukem  *        This product includes software developed by the NetBSD
     21   1.1     lukem  *        Foundation, Inc. and its contributors.
     22   1.1     lukem  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23   1.1     lukem  *    contributors may be used to endorse or promote products derived
     24   1.1     lukem  *    from this software without specific prior written permission.
     25   1.1     lukem  *
     26   1.1     lukem  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27   1.1     lukem  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28   1.1     lukem  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  1.14     lukem  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  1.14     lukem  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31   1.1     lukem  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32   1.1     lukem  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33   1.1     lukem  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34   1.1     lukem  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35   1.1     lukem  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36   1.1     lukem  * POSSIBILITY OF SUCH DAMAGE.
     37   1.1     lukem  */
     38   1.1     lukem 
     39  1.12     lukem #include <sys/cdefs.h>
     40   1.1     lukem #ifndef lint
     41  1.61    itojun __RCSID("$NetBSD: fetch.c,v 1.61 1999/07/04 22:46:20 itojun Exp $");
     42   1.1     lukem #endif /* not lint */
     43   1.1     lukem 
     44   1.1     lukem /*
     45   1.1     lukem  * FTP User Program -- Command line file retrieval
     46   1.1     lukem  */
     47   1.1     lukem 
     48   1.1     lukem #include <sys/types.h>
     49   1.1     lukem #include <sys/param.h>
     50   1.1     lukem #include <sys/socket.h>
     51  1.30     lukem #include <sys/stat.h>
     52  1.32     lukem #include <sys/time.h>
     53  1.43     lukem #include <sys/utsname.h>
     54   1.1     lukem 
     55   1.1     lukem #include <netinet/in.h>
     56   1.1     lukem 
     57   1.2     lukem #include <arpa/ftp.h>
     58   1.1     lukem #include <arpa/inet.h>
     59   1.1     lukem 
     60   1.1     lukem #include <ctype.h>
     61   1.1     lukem #include <err.h>
     62  1.22     lukem #include <errno.h>
     63   1.1     lukem #include <netdb.h>
     64   1.1     lukem #include <fcntl.h>
     65   1.3     lukem #include <signal.h>
     66   1.1     lukem #include <stdio.h>
     67   1.1     lukem #include <stdlib.h>
     68   1.1     lukem #include <string.h>
     69   1.1     lukem #include <unistd.h>
     70  1.57  christos #include <time.h>
     71  1.24     lukem #include <util.h>
     72   1.1     lukem 
     73   1.1     lukem #include "ftp_var.h"
     74   1.1     lukem 
     75  1.27     lukem typedef enum {
     76  1.27     lukem 	UNKNOWN_URL_T=-1,
     77  1.27     lukem 	HTTP_URL_T,
     78  1.27     lukem 	FTP_URL_T,
     79  1.53     lukem 	FILE_URL_T,
     80  1.53     lukem 	CLASSIC_URL_T
     81  1.27     lukem } url_t;
     82  1.27     lukem 
     83  1.50     lukem void    	aborthttp __P((int));
     84  1.54     lukem static int	auth_url __P((const char *, char **, const char *,
     85  1.54     lukem 				const char *));
     86  1.50     lukem static void	base64_encode __P((const char *, size_t, char *));
     87  1.52     lukem static int	go_fetch __P((const char *));
     88  1.52     lukem static int	fetch_ftp __P((const char *));
     89  1.52     lukem static int	fetch_url __P((const char *, const char *, char *, char *));
     90  1.27     lukem static int	parse_url __P((const char *, const char *, url_t *, char **,
     91  1.60    itojun 				char **, char **, char **, char **));
     92  1.50     lukem static void	url_decode __P((char *));
     93  1.12     lukem 
     94  1.42     lukem static int	redirect_loop;
     95  1.42     lukem 
     96  1.12     lukem 
     97  1.25     lukem #define	ABOUT_URL	"about:"	/* propaganda */
     98  1.25     lukem #define	FILE_URL	"file://"	/* file URL prefix */
     99   1.1     lukem #define	FTP_URL		"ftp://"	/* ftp URL prefix */
    100   1.1     lukem #define	HTTP_URL	"http://"	/* http URL prefix */
    101   1.1     lukem 
    102   1.1     lukem 
    103   1.1     lukem #define EMPTYSTRING(x)	((x) == NULL || (*(x) == '\0'))
    104  1.27     lukem #define FREEPTR(x)	if ((x) != NULL) { free(x); (x) = NULL; }
    105  1.27     lukem 
    106  1.27     lukem /*
    107  1.44     lukem  * Generate authorization response based on given authentication challenge.
    108  1.44     lukem  * Returns -1 if an error occurred, otherwise 0.
    109  1.44     lukem  * Sets response to a malloc(3)ed string; caller should free.
    110  1.44     lukem  */
    111  1.44     lukem static int
    112  1.54     lukem auth_url(challenge, response, guser, gpass)
    113  1.44     lukem 	const char	 *challenge;
    114  1.44     lukem 	char		**response;
    115  1.54     lukem 	const char	 *guser;
    116  1.54     lukem 	const char	 *gpass;
    117  1.44     lukem {
    118  1.44     lukem 	char		*cp, *ep, *clear, *line, *realm, *scheme;
    119  1.44     lukem 	char		user[BUFSIZ], *pass;
    120  1.44     lukem 	int		rval;
    121  1.44     lukem 	size_t		len;
    122  1.44     lukem 
    123  1.44     lukem 	*response = NULL;
    124  1.44     lukem 	clear = realm = scheme = NULL;
    125  1.44     lukem 	rval = -1;
    126  1.44     lukem 	line = xstrdup(challenge);
    127  1.44     lukem 	cp = line;
    128  1.44     lukem 
    129  1.44     lukem 	if (debug)
    130  1.44     lukem 		fprintf(ttyout, "auth_url: challenge `%s'\n", challenge);
    131  1.44     lukem 
    132  1.44     lukem 	scheme = strsep(&cp, " ");
    133  1.44     lukem #define SCHEME_BASIC "Basic"
    134  1.44     lukem 	if (strncasecmp(scheme, SCHEME_BASIC, sizeof(SCHEME_BASIC) - 1) != 0) {
    135  1.44     lukem 		warnx("Unsupported WWW Authentication challenge - `%s'",
    136  1.44     lukem 		    challenge);
    137  1.44     lukem 		goto cleanup_auth_url;
    138  1.44     lukem 	}
    139  1.44     lukem 	cp += strspn(cp, " ");
    140  1.44     lukem 
    141  1.44     lukem #define REALM "realm=\""
    142  1.44     lukem 	if (strncasecmp(cp, REALM, sizeof(REALM) - 1) == 0)
    143  1.44     lukem 		cp += sizeof(REALM) - 1;
    144  1.44     lukem 	else {
    145  1.44     lukem 		warnx("Unsupported WWW Authentication challenge - `%s'",
    146  1.44     lukem 		    challenge);
    147  1.44     lukem 		goto cleanup_auth_url;
    148  1.44     lukem 	}
    149  1.44     lukem 	if ((ep = strchr(cp, '\"')) != NULL) {
    150  1.44     lukem 		size_t len = ep - cp;
    151  1.44     lukem 
    152  1.44     lukem 		realm = (char *)xmalloc(len + 1);
    153  1.44     lukem 		strncpy(realm, cp, len);
    154  1.44     lukem 		realm[len] = '\0';
    155  1.44     lukem 	} else {
    156  1.44     lukem 		warnx("Unsupported WWW Authentication challenge - `%s'",
    157  1.44     lukem 		    challenge);
    158  1.44     lukem 		goto cleanup_auth_url;
    159  1.44     lukem 	}
    160  1.44     lukem 
    161  1.54     lukem 	if (guser != NULL) {
    162  1.54     lukem 		strncpy(user, guser, sizeof(user) - 1);
    163  1.54     lukem 		user[sizeof(user) - 1] = '\0';
    164  1.54     lukem 	} else {
    165  1.54     lukem 		fprintf(ttyout, "Username for `%s': ", realm);
    166  1.54     lukem 		(void)fflush(ttyout);
    167  1.54     lukem 		if (fgets(user, sizeof(user) - 1, stdin) == NULL)
    168  1.54     lukem 			goto cleanup_auth_url;
    169  1.54     lukem 		user[strlen(user) - 1] = '\0';
    170  1.54     lukem 	}
    171  1.54     lukem 	if (gpass != NULL)
    172  1.54     lukem 		pass = (char *)gpass;
    173  1.54     lukem 	else
    174  1.54     lukem 		pass = getpass("Password: ");
    175  1.44     lukem 
    176  1.44     lukem 	len = strlen(user) + strlen(pass) + 1;		/* user + ":" + pass */
    177  1.44     lukem 	clear = (char *)xmalloc(len + 1);
    178  1.55     lukem 	snprintf(clear, len, "%s:%s", user, pass);
    179  1.54     lukem 	if (gpass == NULL)
    180  1.54     lukem 		memset(pass, '\0', strlen(pass));
    181  1.44     lukem 
    182  1.44     lukem 						/* scheme + " " + enc */
    183  1.44     lukem 	len = strlen(scheme) + 1 + (len + 2) * 4 / 3;
    184  1.44     lukem 	*response = (char *)xmalloc(len + 1);
    185  1.55     lukem 	len = snprintf(*response, len, "%s ", scheme);
    186  1.50     lukem 	base64_encode(clear, strlen(clear), *response + len);
    187  1.54     lukem 	memset(clear, '\0', strlen(clear));
    188  1.44     lukem 	rval = 0;
    189  1.44     lukem 
    190  1.44     lukem cleanup_auth_url:
    191  1.44     lukem 	FREEPTR(clear);
    192  1.44     lukem 	FREEPTR(line);
    193  1.44     lukem 	FREEPTR(realm);
    194  1.44     lukem 	return (rval);
    195  1.44     lukem }
    196  1.44     lukem 
    197  1.44     lukem /*
    198  1.44     lukem  * Encode len bytes starting at clear using base64 encoding into encoded,
    199  1.44     lukem  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
    200  1.44     lukem  */
    201  1.44     lukem void
    202  1.50     lukem base64_encode(clear, len, encoded)
    203  1.44     lukem 	const char	*clear;
    204  1.44     lukem 	size_t		 len;
    205  1.44     lukem 	char		*encoded;
    206  1.44     lukem {
    207  1.44     lukem 	static const char enc[] =
    208  1.44     lukem 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    209  1.44     lukem 	char *cp;
    210  1.44     lukem 	int i;
    211  1.44     lukem 
    212  1.44     lukem 	cp = encoded;
    213  1.44     lukem 	for (i = 0; i < len; i += 3) {
    214  1.44     lukem 		*(cp++) = enc[((clear[i + 0] >> 2))];
    215  1.44     lukem 		*(cp++) = enc[((clear[i + 0] << 4) & 0x30)
    216  1.44     lukem 			    | ((clear[i + 1] >> 4) & 0x0f)];
    217  1.44     lukem 		*(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
    218  1.44     lukem 			    | ((clear[i + 2] >> 6) & 0x03)];
    219  1.44     lukem 		*(cp++) = enc[((clear[i + 2]     ) & 0x3f)];
    220  1.44     lukem 	}
    221  1.44     lukem 	*cp = '\0';
    222  1.44     lukem 	while (i-- > len)
    223  1.44     lukem 		*(--cp) = '=';
    224  1.44     lukem }
    225  1.44     lukem 
    226  1.50     lukem /*
    227  1.50     lukem  * Decode %xx escapes in given string, `in-place'.
    228  1.50     lukem  */
    229  1.50     lukem static void
    230  1.50     lukem url_decode(url)
    231  1.50     lukem 	char *url;
    232  1.50     lukem {
    233  1.50     lukem 	unsigned char *p, *q;
    234  1.50     lukem 
    235  1.50     lukem 	if (EMPTYSTRING(url))
    236  1.50     lukem 		return;
    237  1.50     lukem 	p = q = url;
    238  1.50     lukem 
    239  1.50     lukem #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
    240  1.50     lukem 	while (*p) {
    241  1.50     lukem 		if (p[0] == '%'
    242  1.50     lukem 		    && p[1] && isxdigit((unsigned char)p[1])
    243  1.50     lukem 		    && p[2] && isxdigit((unsigned char)p[2])) {
    244  1.50     lukem 			*q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
    245  1.50     lukem 			p+=3;
    246  1.50     lukem 		} else
    247  1.50     lukem 			*q++ = *p++;
    248  1.50     lukem 	}
    249  1.50     lukem 	*q = '\0';
    250  1.50     lukem }
    251  1.50     lukem 
    252  1.44     lukem 
    253  1.44     lukem /*
    254  1.27     lukem  * Parse URL of form:
    255  1.27     lukem  *	<type>://[<user>[:<password>@]]<host>[:<port>]/<url-path>
    256  1.27     lukem  * Returns -1 if a parse error occurred, otherwise 0.
    257  1.50     lukem  * Only permit [<user>[:<password>@]] for ftp:// URLs
    258  1.50     lukem  * It's the caller's responsibility to url_decode() the returned
    259  1.50     lukem  * user, pass and path.
    260  1.27     lukem  * Sets type to url_t, each of the given char ** pointers to a
    261  1.27     lukem  * malloc(3)ed strings of the relevant section, and port to
    262  1.41     lukem  * the number given, or ftpport if ftp://, or httpport if http://.
    263  1.52     lukem  *
    264  1.53     lukem  * XXX: this is not totally RFC 1738 compliant; path will have the
    265  1.53     lukem  * leading `/' unless it's an ftp:// URL, as this makes things easier
    266  1.53     lukem  * for file:// and http:// URLs. ftp:// URLs have the `/' between the
    267  1.53     lukem  * host and the url-path removed, but any additional leading slashes
    268  1.53     lukem  * in the url-path are retained (because they imply that we should
    269  1.53     lukem  * later do "CWD" with a null argument).
    270  1.53     lukem  *
    271  1.53     lukem  * Examples:
    272  1.53     lukem  *	 input url			 output path
    273  1.53     lukem  *	 ---------			 -----------
    274  1.53     lukem  *	"http://host"			NULL
    275  1.53     lukem  *	"http://host/"			"/"
    276  1.53     lukem  *	"http://host/dir/file"		"/dir/file"
    277  1.53     lukem  *	"ftp://host/dir/file"		"dir/file"
    278  1.53     lukem  *	"ftp://host//dir/file"		"/dir/file"
    279  1.27     lukem  */
    280  1.27     lukem static int
    281  1.27     lukem parse_url(url, desc, type, user, pass, host, port, path)
    282  1.27     lukem 	const char	 *url;
    283  1.27     lukem 	const char	 *desc;
    284  1.27     lukem 	url_t		 *type;
    285  1.27     lukem 	char		**user;
    286  1.27     lukem 	char		**pass;
    287  1.27     lukem 	char		**host;
    288  1.60    itojun 	char		**port;
    289  1.27     lukem 	char		**path;
    290  1.27     lukem {
    291  1.27     lukem 	char *cp, *ep, *thost;
    292  1.50     lukem 	size_t len;
    293  1.27     lukem 
    294  1.27     lukem 	if (url == NULL || desc == NULL || type == NULL || user == NULL
    295  1.27     lukem 	    || pass == NULL || host == NULL || port == NULL || path == NULL)
    296  1.27     lukem 		errx(1, "parse_url: invoked with NULL argument!");
    297  1.27     lukem 
    298  1.27     lukem 	*type = UNKNOWN_URL_T;
    299  1.27     lukem 	*user = *pass = *host = *path = NULL;
    300  1.60    itojun 	*port = NULL;
    301  1.27     lukem 
    302  1.27     lukem 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
    303  1.27     lukem 		url += sizeof(HTTP_URL) - 1;
    304  1.27     lukem 		*type = HTTP_URL_T;
    305  1.61    itojun 		*port = strdup(httpport);
    306  1.27     lukem 	} else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
    307  1.27     lukem 		url += sizeof(FTP_URL) - 1;
    308  1.27     lukem 		*type = FTP_URL_T;
    309  1.61    itojun 		*port = strdup(ftpport);
    310  1.27     lukem 	} else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
    311  1.27     lukem 		url += sizeof(FILE_URL) - 1;
    312  1.27     lukem 		*type = FILE_URL_T;
    313  1.27     lukem 	} else {
    314  1.27     lukem 		warnx("Invalid %s `%s'", desc, url);
    315  1.27     lukem cleanup_parse_url:
    316  1.27     lukem 		FREEPTR(*user);
    317  1.27     lukem 		FREEPTR(*pass);
    318  1.27     lukem 		FREEPTR(*host);
    319  1.60    itojun 		FREEPTR(*port);
    320  1.27     lukem 		FREEPTR(*path);
    321  1.27     lukem 		return (-1);
    322  1.27     lukem 	}
    323  1.27     lukem 
    324  1.27     lukem 	if (*url == '\0')
    325  1.27     lukem 		return (0);
    326  1.27     lukem 
    327  1.27     lukem 			/* find [user[:pass]@]host[:port] */
    328  1.27     lukem 	ep = strchr(url, '/');
    329  1.27     lukem 	if (ep == NULL)
    330  1.27     lukem 		thost = xstrdup(url);
    331  1.27     lukem 	else {
    332  1.50     lukem 		len = ep - url;
    333  1.27     lukem 		thost = (char *)xmalloc(len + 1);
    334  1.27     lukem 		strncpy(thost, url, len);
    335  1.27     lukem 		thost[len] = '\0';
    336  1.53     lukem 		if (*type == FTP_URL_T)	/* skip first / for ftp URLs */
    337  1.53     lukem 			ep++;
    338  1.27     lukem 		*path = xstrdup(ep);
    339  1.27     lukem 	}
    340  1.27     lukem 
    341  1.27     lukem 	cp = strchr(thost, '@');
    342  1.54     lukem 					/* look for user[:pass]@ in URLs */
    343  1.54     lukem 	if (cp != NULL) {
    344  1.54     lukem 		if (*type == FTP_URL_T)
    345  1.54     lukem 			anonftp = 0;	/* disable anonftp */
    346  1.27     lukem 		*user = thost;
    347  1.27     lukem 		*cp = '\0';
    348  1.27     lukem 		*host = xstrdup(cp + 1);
    349  1.27     lukem 		cp = strchr(*user, ':');
    350  1.27     lukem 		if (cp != NULL) {
    351  1.27     lukem 			*cp = '\0';
    352  1.27     lukem 			*pass = xstrdup(cp + 1);
    353  1.27     lukem 		}
    354  1.27     lukem 	} else
    355  1.27     lukem 		*host = thost;
    356  1.27     lukem 
    357  1.60    itojun 	/* look for IPv6 address URL */
    358  1.60    itojun 	if (*thost == '[' && (cp = strrchr(thost, ']'))) {
    359  1.60    itojun 		size_t len = cp - thost - 1 ;
    360  1.60    itojun 		*host = (char *)xmalloc(len + 1);
    361  1.60    itojun 		strncpy(*host, thost + 1, len);
    362  1.60    itojun 		(*host)[len] = '\0';
    363  1.60    itojun 		cp = strrchr(++cp, ':');
    364  1.60    itojun 	} else if ((cp = strrchr(thost, ':')) != NULL) {
    365  1.60    itojun 		size_t len = cp - thost;
    366  1.60    itojun 		*host = (char *)xmalloc(len + 1);
    367  1.60    itojun 		strncpy(*host, thost, len);
    368  1.60    itojun 		(*host)[len] = '\0';
    369  1.60    itojun 	} else {
    370  1.60    itojun 		*host = xstrdup(thost);
    371  1.60    itojun 		cp = NULL;
    372  1.60    itojun 	}
    373  1.60    itojun 
    374  1.27     lukem 			/* look for [:port] */
    375  1.27     lukem 	if (cp != NULL) {
    376  1.27     lukem 		long nport;
    377  1.27     lukem 
    378  1.27     lukem 		*cp = '\0';
    379  1.27     lukem 		nport = strtol(cp + 1, &ep, 10);
    380  1.27     lukem 		if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
    381  1.42     lukem 			warnx("Invalid port `%s' in %s `%s'", cp, desc, url);
    382  1.27     lukem 			goto cleanup_parse_url;
    383  1.27     lukem 		}
    384  1.60    itojun 		*port = (char *)xmalloc(6);	/* large enough for "65535\0" */
    385  1.60    itojun 		snprintf(*port, 6, "%ld", nport);
    386  1.27     lukem 	}
    387  1.27     lukem 
    388  1.27     lukem 	if (debug)
    389  1.27     lukem 		fprintf(ttyout,
    390  1.60    itojun 		    "parse_url: user `%s' pass `%s' host %s:%s path `%s'\n",
    391  1.53     lukem 		    *user ? *user : "<null>", *pass ? *pass : "<null>",
    392  1.60    itojun 		    *host ? *host : "<null>", *port ? *port : "<null>",
    393  1.53     lukem 		    *path ? *path : "<null>");
    394  1.27     lukem 
    395  1.27     lukem 	return (0);
    396  1.27     lukem }
    397  1.27     lukem 
    398   1.1     lukem 
    399   1.2     lukem jmp_buf	httpabort;
    400   1.2     lukem 
    401   1.1     lukem /*
    402  1.50     lukem  * Retrieve URL, via a proxy if necessary, using HTTP.
    403  1.50     lukem  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
    404  1.50     lukem  * http_proxy as appropriate.
    405  1.50     lukem  * Supports HTTP redirects.
    406  1.41     lukem  * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
    407  1.41     lukem  * is still open (e.g, ftp xfer with trailing /)
    408   1.1     lukem  */
    409  1.12     lukem static int
    410  1.52     lukem fetch_url(url, proxyenv, proxyauth, wwwauth)
    411  1.44     lukem 	const char	*url;
    412  1.44     lukem 	const char	*proxyenv;
    413  1.44     lukem 	char		*proxyauth;
    414  1.44     lukem 	char		*wwwauth;
    415   1.1     lukem {
    416  1.60    itojun 	struct addrinfo		hints, *res;
    417  1.42     lukem 	volatile sig_t		oldintr, oldintp;
    418  1.42     lukem 	volatile int		s;
    419  1.45     lukem 	int 			ischunked, isproxy, rval, hcode;
    420  1.42     lukem 	size_t			len;
    421  1.44     lukem 	char			*cp, *ep, *buf, *savefile;
    422  1.44     lukem 	char			*auth, *location, *message;
    423  1.50     lukem 	char			*user, *pass, *host, *path, *decodedpath;
    424  1.54     lukem 	char			*puser, *ppass;
    425  1.42     lukem 	off_t			hashbytes;
    426  1.42     lukem 	int			 (*closefunc) __P((FILE *));
    427  1.42     lukem 	FILE			*fin, *fout;
    428  1.42     lukem 	time_t			mtime;
    429  1.42     lukem 	url_t			urltype;
    430  1.60    itojun 	in_port_t		portnum;
    431  1.60    itojun 	char			*port;
    432  1.60    itojun 	int			error;
    433   1.1     lukem 
    434  1.22     lukem 	closefunc = NULL;
    435  1.24     lukem 	fin = fout = NULL;
    436   1.1     lukem 	s = -1;
    437  1.44     lukem 	buf = savefile = NULL;
    438  1.44     lukem 	auth = location = message = NULL;
    439  1.52     lukem 	ischunked = isproxy = hcode = 0;
    440  1.42     lukem 	rval = 1;
    441  1.54     lukem 	user = pass = host = path = decodedpath = puser = ppass = NULL;
    442   1.1     lukem 
    443  1.27     lukem #ifdef __GNUC__			/* shut up gcc warnings */
    444  1.22     lukem 	(void)&closefunc;
    445  1.24     lukem 	(void)&fin;
    446  1.22     lukem 	(void)&fout;
    447  1.24     lukem 	(void)&buf;
    448  1.12     lukem 	(void)&savefile;
    449  1.42     lukem 	(void)&rval;
    450  1.28      fvdl 	(void)&isproxy;
    451  1.51  christos 	(void)&hcode;
    452  1.51  christos 	(void)&ischunked;
    453  1.51  christos 	(void)&message;
    454  1.51  christos 	(void)&location;
    455  1.51  christos 	(void)&auth;
    456  1.51  christos 	(void)&decodedpath;
    457  1.12     lukem #endif
    458  1.12     lukem 
    459  1.27     lukem 	if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
    460  1.27     lukem 	    == -1)
    461  1.42     lukem 		goto cleanup_fetch_url;
    462  1.60    itojun 	portnum = strtol(port, NULL, 10);
    463   1.5     lukem 
    464  1.27     lukem 	if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
    465  1.27     lukem 	    && strcasecmp(host, "localhost") != 0) {
    466  1.27     lukem 		warnx("No support for non local file URL `%s'", url);
    467  1.42     lukem 		goto cleanup_fetch_url;
    468   1.9     lukem 	}
    469  1.27     lukem 
    470   1.9     lukem 	if (EMPTYSTRING(path)) {
    471  1.42     lukem 		if (urltype == FTP_URL_T) {
    472  1.52     lukem 			rval = fetch_ftp(url);
    473  1.42     lukem 			goto cleanup_fetch_url;
    474  1.42     lukem 		}
    475  1.27     lukem 		if (urltype != HTTP_URL_T || outfile == NULL)  {
    476  1.27     lukem 			warnx("Invalid URL (no file after host) `%s'", url);
    477  1.42     lukem 			goto cleanup_fetch_url;
    478  1.27     lukem 		}
    479   1.9     lukem 	}
    480   1.1     lukem 
    481  1.50     lukem 	decodedpath = xstrdup(path);
    482  1.50     lukem 	url_decode(decodedpath);
    483  1.50     lukem 
    484  1.22     lukem 	if (outfile)
    485  1.29     lukem 		savefile = xstrdup(outfile);
    486  1.22     lukem 	else {
    487  1.50     lukem 		cp = strrchr(decodedpath, '/');		/* find savefile */
    488  1.29     lukem 		if (cp != NULL)
    489  1.29     lukem 			savefile = xstrdup(cp + 1);
    490  1.22     lukem 		else
    491  1.50     lukem 			savefile = xstrdup(decodedpath);
    492  1.22     lukem 	}
    493   1.9     lukem 	if (EMPTYSTRING(savefile)) {
    494  1.42     lukem 		if (urltype == FTP_URL_T) {
    495  1.52     lukem 			rval = fetch_ftp(url);
    496  1.42     lukem 			goto cleanup_fetch_url;
    497  1.42     lukem 		}
    498  1.27     lukem 		warnx("Invalid URL (no file after directory) `%s'", url);
    499  1.42     lukem 		goto cleanup_fetch_url;
    500  1.52     lukem 	} else {
    501  1.52     lukem 		if (debug)
    502  1.52     lukem 			fprintf(ttyout, "got savefile as `%s'\n", savefile);
    503   1.9     lukem 	}
    504   1.1     lukem 
    505  1.25     lukem 	filesize = -1;
    506  1.25     lukem 	mtime = -1;
    507  1.25     lukem 	if (urltype == FILE_URL_T) {		/* file:// URLs */
    508  1.25     lukem 		struct stat sb;
    509  1.25     lukem 
    510  1.25     lukem 		direction = "copied";
    511  1.50     lukem 		fin = fopen(decodedpath, "r");
    512  1.25     lukem 		if (fin == NULL) {
    513  1.50     lukem 			warn("Cannot open file `%s'", decodedpath);
    514  1.42     lukem 			goto cleanup_fetch_url;
    515   1.5     lukem 		}
    516  1.25     lukem 		if (fstat(fileno(fin), &sb) == 0) {
    517  1.25     lukem 			mtime = sb.st_mtime;
    518  1.25     lukem 			filesize = sb.st_size;
    519  1.25     lukem 		}
    520  1.49     lukem 		if (verbose)
    521  1.50     lukem 			fprintf(ttyout, "Copying %s\n", decodedpath);
    522  1.25     lukem 	} else {				/* ftp:// or http:// URLs */
    523  1.42     lukem 		if (proxyenv == NULL) {
    524  1.42     lukem 			if (urltype == HTTP_URL_T)
    525  1.42     lukem 				proxyenv = httpproxy;
    526  1.42     lukem 			else if (urltype == FTP_URL_T)
    527  1.42     lukem 				proxyenv = ftpproxy;
    528  1.42     lukem 		}
    529  1.25     lukem 		direction = "retrieved";
    530  1.25     lukem 		if (proxyenv != NULL) {				/* use proxy */
    531  1.27     lukem 			url_t purltype;
    532  1.54     lukem 			char *phost, *ppath;
    533  1.60    itojun 			char *pport;
    534  1.27     lukem 
    535  1.27     lukem 			isproxy = 1;
    536  1.27     lukem 
    537  1.27     lukem 				/* check URL against list of no_proxied sites */
    538  1.27     lukem 			if (no_proxy != NULL) {
    539  1.27     lukem 				char *np, *np_copy;
    540  1.27     lukem 				long np_port;
    541  1.27     lukem 				size_t hlen, plen;
    542  1.27     lukem 
    543  1.27     lukem 				np_copy = xstrdup(no_proxy);
    544  1.27     lukem 				hlen = strlen(host);
    545  1.27     lukem 				while ((cp = strsep(&np_copy, " ,")) != NULL) {
    546  1.27     lukem 					if (*cp == '\0')
    547  1.27     lukem 						continue;
    548  1.60    itojun 					if ((np = strrchr(cp, ':')) != NULL) {
    549  1.27     lukem 						*np = '\0';
    550  1.27     lukem 						np_port =
    551  1.27     lukem 						    strtol(np + 1, &ep, 10);
    552  1.27     lukem 						if (*ep != '\0')
    553  1.27     lukem 							continue;
    554  1.60    itojun 						if (portnum !=
    555  1.27     lukem 						    htons((in_port_t)np_port))
    556  1.27     lukem 							continue;
    557  1.27     lukem 					}
    558  1.27     lukem 					plen = strlen(cp);
    559  1.27     lukem 					if (strncasecmp(host + hlen - plen,
    560  1.27     lukem 					    cp, plen) == 0) {
    561  1.27     lukem 						isproxy = 0;
    562  1.27     lukem 						break;
    563  1.27     lukem 					}
    564  1.27     lukem 				}
    565  1.27     lukem 				FREEPTR(np_copy);
    566  1.25     lukem 			}
    567   1.1     lukem 
    568  1.27     lukem 			if (isproxy) {
    569  1.27     lukem 				if (parse_url(proxyenv, "proxy URL", &purltype,
    570  1.60    itojun 				    &puser, &ppass, &phost, &pport, &ppath)
    571  1.27     lukem 				    == -1)
    572  1.42     lukem 					goto cleanup_fetch_url;
    573  1.27     lukem 
    574  1.27     lukem 				if ((purltype != HTTP_URL_T
    575  1.27     lukem 				     && purltype != FTP_URL_T) ||
    576  1.27     lukem 				    EMPTYSTRING(phost) ||
    577  1.27     lukem 				    (! EMPTYSTRING(ppath)
    578  1.27     lukem 				     && strcmp(ppath, "/") != 0)) {
    579  1.27     lukem 					warnx("Malformed proxy URL `%s'",
    580  1.27     lukem 					    proxyenv);
    581  1.27     lukem 					FREEPTR(phost);
    582  1.60    itojun 					FREEPTR(pport);
    583  1.27     lukem 					FREEPTR(ppath);
    584  1.42     lukem 					goto cleanup_fetch_url;
    585  1.27     lukem 				}
    586  1.12     lukem 
    587  1.27     lukem 				FREEPTR(host);
    588  1.27     lukem 				host = phost;
    589  1.27     lukem 				FREEPTR(path);
    590  1.54     lukem 				path = xstrdup(url);
    591  1.27     lukem 				FREEPTR(ppath);
    592  1.27     lukem 			}
    593  1.27     lukem 		} /* proxyenv != NULL */
    594  1.25     lukem 
    595  1.60    itojun #if 0
    596  1.25     lukem 		memset(&sin, 0, sizeof(sin));
    597  1.25     lukem 		sin.sin_family = AF_INET;
    598  1.25     lukem 
    599  1.25     lukem 		if (isdigit((unsigned char)host[0])) {
    600  1.25     lukem 			if (inet_aton(host, &sin.sin_addr) == 0) {
    601  1.27     lukem 				warnx("Invalid IP address `%s'", host);
    602  1.42     lukem 				goto cleanup_fetch_url;
    603  1.25     lukem 			}
    604  1.25     lukem 		} else {
    605  1.25     lukem 			hp = gethostbyname(host);
    606  1.25     lukem 			if (hp == NULL) {
    607  1.25     lukem 				warnx("%s: %s", host, hstrerror(h_errno));
    608  1.42     lukem 				goto cleanup_fetch_url;
    609  1.25     lukem 			}
    610  1.25     lukem 			if (hp->h_addrtype != AF_INET) {
    611  1.27     lukem 				warnx("`%s': not an Internet address?", host);
    612  1.42     lukem 				goto cleanup_fetch_url;
    613  1.25     lukem 			}
    614  1.25     lukem 			memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
    615   1.1     lukem 		}
    616   1.1     lukem 
    617  1.60    itojun 		if (port == NULL) {
    618  1.41     lukem 			warnx("Unknown port for URL `%s'", url);
    619  1.42     lukem 			goto cleanup_fetch_url;
    620  1.41     lukem 		}
    621  1.25     lukem 		sin.sin_port = port;
    622  1.25     lukem 
    623  1.25     lukem 		s = socket(AF_INET, SOCK_STREAM, 0);
    624  1.25     lukem 		if (s == -1) {
    625  1.25     lukem 			warn("Can't create socket");
    626  1.42     lukem 			goto cleanup_fetch_url;
    627  1.22     lukem 		}
    628   1.1     lukem 
    629  1.25     lukem 		while (xconnect(s, (struct sockaddr *)&sin,
    630  1.25     lukem 		    sizeof(sin)) == -1) {
    631  1.25     lukem 			if (errno == EINTR)
    632  1.25     lukem 				continue;
    633  1.25     lukem 			if (hp && hp->h_addr_list[1]) {
    634  1.25     lukem 				int oerrno = errno;
    635  1.25     lukem 				char *ia;
    636  1.25     lukem 
    637  1.25     lukem 				ia = inet_ntoa(sin.sin_addr);
    638  1.25     lukem 				errno = oerrno;
    639  1.27     lukem 				warn("Connect to address `%s'", ia);
    640  1.25     lukem 				hp->h_addr_list++;
    641  1.25     lukem 				memcpy(&sin.sin_addr, hp->h_addr_list[0],
    642  1.25     lukem 				    (size_t)hp->h_length);
    643  1.49     lukem 				if (verbose)
    644  1.49     lukem 					fprintf(ttyout, "Trying %s...\n",
    645  1.49     lukem 					    inet_ntoa(sin.sin_addr));
    646  1.25     lukem 				(void)close(s);
    647  1.25     lukem 				s = socket(AF_INET, SOCK_STREAM, 0);
    648  1.25     lukem 				if (s < 0) {
    649  1.25     lukem 					warn("Can't create socket");
    650  1.42     lukem 					goto cleanup_fetch_url;
    651  1.25     lukem 				}
    652  1.25     lukem 				continue;
    653  1.25     lukem 			}
    654  1.27     lukem 			warn("Can't connect to `%s'", host);
    655  1.42     lukem 			goto cleanup_fetch_url;
    656  1.25     lukem 		}
    657  1.60    itojun #else
    658  1.60    itojun 		memset(&hints, 0, sizeof(hints));
    659  1.60    itojun 		hints.ai_flags = AI_CANONNAME;
    660  1.60    itojun 		hints.ai_family = AF_UNSPEC;
    661  1.60    itojun 		hints.ai_socktype = SOCK_STREAM;
    662  1.60    itojun 		hints.ai_protocol = 0;
    663  1.60    itojun 		error = getaddrinfo(host, port, &hints, &res);
    664  1.60    itojun 		if (error) {
    665  1.60    itojun 			warn(gai_strerror(error));
    666  1.60    itojun 			goto cleanup_fetch_url;
    667  1.60    itojun 		}
    668  1.60    itojun 		if (res->ai_canonname)
    669  1.60    itojun 			host = res->ai_canonname;
    670  1.60    itojun 
    671  1.60    itojun 		while (1) {
    672  1.60    itojun 			s = socket(res->ai_family,
    673  1.60    itojun 				   res->ai_socktype, res->ai_protocol);
    674  1.60    itojun 			if (s < 0) {
    675  1.60    itojun 				warn("Can't create socket");
    676  1.60    itojun 				goto cleanup_fetch_url;
    677  1.60    itojun 			}
    678  1.60    itojun 
    679  1.60    itojun 			if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) {
    680  1.60    itojun 				char hbuf[MAXHOSTNAMELEN];
    681  1.60    itojun 				getnameinfo(res->ai_addr, res->ai_addrlen,
    682  1.60    itojun 					hbuf, sizeof(hbuf), NULL, 0,
    683  1.60    itojun 					NI_NUMERICHOST);
    684  1.60    itojun 				warn("Connect to address `%s'", hbuf);
    685  1.60    itojun 				close(s);
    686  1.60    itojun 				res = res->ai_next;
    687  1.60    itojun 				if (res) {
    688  1.60    itojun 					getnameinfo(res->ai_addr, res->ai_addrlen,
    689  1.60    itojun 						hbuf, sizeof(hbuf), NULL, 0,
    690  1.60    itojun 						NI_NUMERICHOST);
    691  1.60    itojun 					if (verbose)
    692  1.60    itojun 						fprintf(ttyout, "Trying %s...\n", hbuf);
    693  1.60    itojun 					continue;
    694  1.60    itojun 				}
    695  1.60    itojun 				warn("Can't connect to %s", host);
    696  1.60    itojun 				goto cleanup_fetch_url;
    697  1.60    itojun 			}
    698  1.60    itojun 
    699  1.60    itojun 			break;
    700  1.60    itojun 		}
    701  1.60    itojun #endif
    702  1.60    itojun 
    703  1.24     lukem 
    704  1.25     lukem 		fin = fdopen(s, "r+");
    705  1.25     lukem 		/*
    706  1.27     lukem 		 * Construct and send the request.
    707  1.27     lukem 		 * Proxy requests don't want leading /.
    708  1.25     lukem 		 */
    709  1.27     lukem 		if (isproxy) {
    710  1.49     lukem 			if (verbose)
    711  1.49     lukem 				fprintf(ttyout, "Requesting %s\n  (via %s)\n",
    712  1.49     lukem 				    url, proxyenv);
    713  1.44     lukem 			fprintf(fin, "GET %s HTTP/1.0\r\n", path);
    714  1.47     lukem 			if (flushcache)
    715  1.47     lukem 				fprintf(fin, "Pragma: no-cache\r\n");
    716  1.27     lukem 		} else {
    717  1.43     lukem 			struct utsname unam;
    718  1.43     lukem 
    719  1.49     lukem 			if (verbose)
    720  1.49     lukem 				fprintf(ttyout, "Requesting %s\n", url);
    721  1.27     lukem 			fprintf(fin, "GET %s HTTP/1.1\r\n", path);
    722  1.60    itojun 			fprintf(fin, "Host: %s:%s\r\n", host, port);
    723  1.40  explorer 			fprintf(fin, "Accept: */*\r\n");
    724  1.43     lukem 			if (uname(&unam) != -1) {
    725  1.43     lukem 				fprintf(fin, "User-Agent: %s-%s/ftp\r\n",
    726  1.43     lukem 				    unam.sysname, unam.release);
    727  1.43     lukem 			}
    728  1.42     lukem 			fprintf(fin, "Connection: close\r\n");
    729  1.47     lukem 			if (flushcache)
    730  1.47     lukem 				fprintf(fin, "Cache-Control: no-cache\r\n");
    731  1.25     lukem 		}
    732  1.44     lukem 		if (wwwauth) {
    733  1.49     lukem 			if (verbose)
    734  1.49     lukem 				fprintf(ttyout, "  (with authorization)\n");
    735  1.44     lukem 			fprintf(fin, "Authorization: %s\r\n", wwwauth);
    736  1.44     lukem 		}
    737  1.46     lukem 		if (proxyauth) {
    738  1.49     lukem 			if (verbose)
    739  1.49     lukem 				fprintf(ttyout,
    740  1.49     lukem 				    "  (with proxy authorization)\n");
    741  1.44     lukem 			fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
    742  1.46     lukem 		}
    743  1.44     lukem 		fprintf(fin, "\r\n");
    744  1.25     lukem 		if (fflush(fin) == EOF) {
    745  1.25     lukem 			warn("Writing HTTP request");
    746  1.42     lukem 			goto cleanup_fetch_url;
    747  1.25     lukem 		}
    748   1.1     lukem 
    749  1.25     lukem 				/* Read the response */
    750  1.24     lukem 		if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
    751  1.24     lukem 			warn("Receiving HTTP reply");
    752  1.42     lukem 			goto cleanup_fetch_url;
    753  1.24     lukem 		}
    754  1.24     lukem 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
    755  1.24     lukem 			buf[--len] = '\0';
    756  1.24     lukem 		if (debug)
    757  1.27     lukem 			fprintf(ttyout, "received `%s'\n", buf);
    758   1.1     lukem 
    759  1.42     lukem 				/* Determine HTTP response code */
    760  1.25     lukem 		cp = strchr(buf, ' ');
    761  1.25     lukem 		if (cp == NULL)
    762  1.25     lukem 			goto improper;
    763  1.25     lukem 		else
    764  1.25     lukem 			cp++;
    765  1.42     lukem 		hcode = strtol(cp, &ep, 10);
    766  1.42     lukem 		if (*ep != '\0' && !isspace((unsigned char)*ep))
    767  1.42     lukem 			goto improper;
    768  1.42     lukem 		message = xstrdup(cp);
    769  1.25     lukem 
    770  1.25     lukem 				/* Read the rest of the header. */
    771  1.27     lukem 		FREEPTR(buf);
    772  1.25     lukem 		while (1) {
    773  1.25     lukem 			if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
    774  1.25     lukem 			    == NULL) {
    775  1.25     lukem 				warn("Receiving HTTP reply");
    776  1.42     lukem 				goto cleanup_fetch_url;
    777  1.25     lukem 			}
    778  1.25     lukem 			while (len > 0 &&
    779  1.25     lukem 			    (buf[len-1] == '\r' || buf[len-1] == '\n'))
    780  1.25     lukem 				buf[--len] = '\0';
    781  1.25     lukem 			if (len == 0)
    782  1.25     lukem 				break;
    783  1.25     lukem 			if (debug)
    784  1.27     lukem 				fprintf(ttyout, "received `%s'\n", buf);
    785  1.25     lukem 
    786  1.25     lukem 				/* Look for some headers */
    787  1.25     lukem 			cp = buf;
    788  1.42     lukem 
    789   1.1     lukem #define CONTENTLEN "Content-Length: "
    790  1.25     lukem 			if (strncasecmp(cp, CONTENTLEN,
    791  1.44     lukem 					sizeof(CONTENTLEN) - 1) == 0) {
    792  1.25     lukem 				cp += sizeof(CONTENTLEN) - 1;
    793  1.25     lukem 				filesize = strtol(cp, &ep, 10);
    794  1.25     lukem 				if (filesize < 1 || *ep != '\0')
    795  1.25     lukem 					goto improper;
    796  1.25     lukem 				if (debug)
    797  1.25     lukem 					fprintf(ttyout,
    798  1.25     lukem #ifndef NO_QUAD
    799  1.25     lukem 					    "parsed length as: %qd\n",
    800  1.25     lukem 					    (long long)filesize);
    801  1.25     lukem #else
    802  1.25     lukem 					    "parsed length as: %ld\n",
    803  1.25     lukem 					    (long)filesize);
    804  1.25     lukem #endif
    805  1.42     lukem 
    806  1.25     lukem #define LASTMOD "Last-Modified: "
    807  1.25     lukem 			} else if (strncasecmp(cp, LASTMOD,
    808  1.44     lukem 						sizeof(LASTMOD) - 1) == 0) {
    809  1.25     lukem 				struct tm parsed;
    810  1.25     lukem 				char *t;
    811  1.25     lukem 
    812  1.25     lukem 				cp += sizeof(LASTMOD) - 1;
    813  1.25     lukem 							/* RFC 1123 */
    814  1.25     lukem 				if ((t = strptime(cp,
    815  1.25     lukem 						"%a, %d %b %Y %H:%M:%S GMT",
    816  1.25     lukem 						&parsed))
    817  1.25     lukem 							/* RFC 850 */
    818  1.25     lukem 				    || (t = strptime(cp,
    819  1.25     lukem 						"%a, %d-%b-%y %H:%M:%S GMT",
    820  1.25     lukem 						&parsed))
    821  1.25     lukem 							/* asctime */
    822  1.25     lukem 				    || (t = strptime(cp,
    823  1.25     lukem 						"%a, %b %d %H:%M:%S %Y",
    824  1.25     lukem 						&parsed))) {
    825  1.38     lukem 					parsed.tm_isdst = -1;
    826  1.25     lukem 					if (*t == '\0')
    827  1.39     itohy 						mtime = mkgmtime(&parsed);
    828  1.38     lukem 					if (debug && mtime != -1) {
    829  1.25     lukem 						fprintf(ttyout,
    830  1.25     lukem 						    "parsed date as: %s",
    831  1.25     lukem 						    ctime(&mtime));
    832  1.38     lukem 					}
    833  1.25     lukem 				}
    834  1.42     lukem 
    835  1.24     lukem #define LOCATION "Location: "
    836  1.42     lukem 			} else if (strncasecmp(cp, LOCATION,
    837  1.44     lukem 						sizeof(LOCATION) - 1) == 0) {
    838  1.25     lukem 				cp += sizeof(LOCATION) - 1;
    839  1.42     lukem 				location = xstrdup(cp);
    840  1.25     lukem 				if (debug)
    841  1.25     lukem 					fprintf(ttyout,
    842  1.25     lukem 					    "parsed location as: %s\n", cp);
    843  1.44     lukem 
    844  1.45     lukem #define TRANSENC "Transfer-Encoding: "
    845  1.45     lukem 			} else if (strncasecmp(cp, TRANSENC,
    846  1.45     lukem 						sizeof(TRANSENC) - 1) == 0) {
    847  1.45     lukem 				cp += sizeof(TRANSENC) - 1;
    848  1.45     lukem 				if (strcasecmp(cp, "chunked") != 0) {
    849  1.45     lukem 					warnx(
    850  1.45     lukem 				    "Unsupported transfer encoding - `%s'",
    851  1.45     lukem 					    cp);
    852  1.45     lukem 					goto cleanup_fetch_url;
    853  1.45     lukem 				}
    854  1.45     lukem 				ischunked++;
    855  1.45     lukem 				if (debug)
    856  1.45     lukem 					fprintf(ttyout,
    857  1.45     lukem 					    "using chunked encoding\n");
    858  1.45     lukem 
    859  1.44     lukem #define PROXYAUTH "Proxy-Authenticate: "
    860  1.44     lukem 			} else if (strncasecmp(cp, PROXYAUTH,
    861  1.44     lukem 						sizeof(PROXYAUTH) - 1) == 0) {
    862  1.44     lukem 				cp += sizeof(PROXYAUTH) - 1;
    863  1.44     lukem 				FREEPTR(auth);
    864  1.44     lukem 				auth = xstrdup(cp);
    865  1.44     lukem 				if (debug)
    866  1.44     lukem 					fprintf(ttyout,
    867  1.44     lukem 					    "parsed proxy-auth as: %s\n", cp);
    868  1.44     lukem 
    869  1.44     lukem #define WWWAUTH	"WWW-Authenticate: "
    870  1.44     lukem 			} else if (strncasecmp(cp, WWWAUTH,
    871  1.44     lukem 			    sizeof(WWWAUTH) - 1) == 0) {
    872  1.44     lukem 				cp += sizeof(WWWAUTH) - 1;
    873  1.44     lukem 				FREEPTR(auth);
    874  1.44     lukem 				auth = xstrdup(cp);
    875  1.44     lukem 				if (debug)
    876  1.44     lukem 					fprintf(ttyout,
    877  1.44     lukem 					    "parsed www-auth as: %s\n", cp);
    878  1.44     lukem 
    879  1.25     lukem 			}
    880  1.44     lukem 
    881  1.24     lukem 		}
    882  1.54     lukem 				/* finished parsing header */
    883  1.27     lukem 		FREEPTR(buf);
    884   1.1     lukem 
    885  1.52     lukem 		switch (hcode) {
    886  1.52     lukem 		case 200:
    887  1.52     lukem 			break;
    888  1.52     lukem 		case 300:
    889  1.52     lukem 		case 301:
    890  1.52     lukem 		case 302:
    891  1.52     lukem 		case 303:
    892  1.52     lukem 		case 305:
    893  1.52     lukem 			if (EMPTYSTRING(location)) {
    894  1.52     lukem 				warnx(
    895  1.52     lukem 				"No redirection Location provided by server");
    896  1.52     lukem 				goto cleanup_fetch_url;
    897  1.52     lukem 			}
    898  1.52     lukem 			if (redirect_loop++ > 5) {
    899  1.52     lukem 				warnx("Too many redirections requested");
    900  1.52     lukem 				goto cleanup_fetch_url;
    901  1.52     lukem 			}
    902  1.52     lukem 			if (hcode == 305) {
    903  1.52     lukem 				if (verbose)
    904  1.52     lukem 					fprintf(ttyout, "Redirected via %s\n",
    905  1.52     lukem 					    location);
    906  1.52     lukem 				rval = fetch_url(url, location,
    907  1.52     lukem 				    proxyauth, wwwauth);
    908  1.52     lukem 			} else {
    909  1.52     lukem 				if (verbose)
    910  1.52     lukem 					fprintf(ttyout, "Redirected to %s\n",
    911  1.52     lukem 					    location);
    912  1.52     lukem 				rval = go_fetch(location);
    913  1.52     lukem 			}
    914  1.42     lukem 			goto cleanup_fetch_url;
    915  1.52     lukem 		case 401:
    916  1.52     lukem 		case 407:
    917  1.52     lukem 		    {
    918  1.52     lukem 			char **authp;
    919  1.54     lukem 			char *auser, *apass;
    920  1.52     lukem 
    921  1.52     lukem 			fprintf(ttyout, "%s\n", message);
    922  1.52     lukem 			if (EMPTYSTRING(auth)) {
    923  1.52     lukem 				warnx(
    924  1.52     lukem 			    "No authentication challenge provided by server");
    925  1.52     lukem 				goto cleanup_fetch_url;
    926  1.52     lukem 			}
    927  1.54     lukem 			if (hcode == 401) {
    928  1.54     lukem 				authp = &wwwauth;
    929  1.54     lukem 				auser = user;
    930  1.54     lukem 				apass = pass;
    931  1.54     lukem 			} else {
    932  1.54     lukem 				authp = &proxyauth;
    933  1.54     lukem 				auser = puser;
    934  1.54     lukem 				apass = ppass;
    935  1.54     lukem 			}
    936  1.52     lukem 			if (*authp != NULL) {
    937  1.52     lukem 				char reply[10];
    938  1.52     lukem 
    939  1.52     lukem 				fprintf(ttyout,
    940  1.52     lukem 				    "Authorization failed. Retry (y/n)? ");
    941  1.52     lukem 				if (fgets(reply, sizeof(reply), stdin) != NULL
    942  1.52     lukem 				    && tolower(reply[0]) != 'y')
    943  1.52     lukem 					goto cleanup_fetch_url;
    944  1.54     lukem 				auser = NULL;
    945  1.54     lukem 				apass = NULL;
    946  1.52     lukem 			}
    947  1.54     lukem 			if (auth_url(auth, authp, auser, apass) == 0) {
    948  1.52     lukem 				rval = fetch_url(url, proxyenv,
    949  1.52     lukem 				    proxyauth, wwwauth);
    950  1.52     lukem 				memset(*authp, '\0', strlen(*authp));
    951  1.52     lukem 				FREEPTR(*authp);
    952  1.52     lukem 			}
    953  1.42     lukem 			goto cleanup_fetch_url;
    954  1.52     lukem 		    }
    955  1.52     lukem 		default:
    956  1.52     lukem 			if (message)
    957  1.52     lukem 				warnx("Error retrieving file - `%s'", message);
    958  1.52     lukem 			else
    959  1.52     lukem 				warnx("Unknown error retrieving file");
    960  1.44     lukem 			goto cleanup_fetch_url;
    961  1.44     lukem 		}
    962  1.52     lukem 	}		/* end of ftp:// or http:// specific setup */
    963  1.42     lukem 
    964  1.22     lukem 	oldintr = oldintp = NULL;
    965  1.22     lukem 
    966  1.22     lukem 			/* Open the output file. */
    967  1.22     lukem 	if (strcmp(savefile, "-") == 0) {
    968  1.22     lukem 		fout = stdout;
    969  1.22     lukem 	} else if (*savefile == '|') {
    970  1.22     lukem 		oldintp = signal(SIGPIPE, SIG_IGN);
    971  1.22     lukem 		fout = popen(savefile + 1, "w");
    972  1.22     lukem 		if (fout == NULL) {
    973  1.27     lukem 			warn("Can't run `%s'", savefile + 1);
    974  1.42     lukem 			goto cleanup_fetch_url;
    975  1.22     lukem 		}
    976  1.22     lukem 		closefunc = pclose;
    977  1.22     lukem 	} else {
    978  1.22     lukem 		fout = fopen(savefile, "w");
    979  1.22     lukem 		if (fout == NULL) {
    980  1.27     lukem 			warn("Can't open `%s'", savefile);
    981  1.42     lukem 			goto cleanup_fetch_url;
    982  1.22     lukem 		}
    983  1.22     lukem 		closefunc = fclose;
    984   1.1     lukem 	}
    985   1.1     lukem 
    986  1.22     lukem 			/* Trap signals */
    987   1.2     lukem 	if (setjmp(httpabort)) {
    988   1.2     lukem 		if (oldintr)
    989   1.3     lukem 			(void)signal(SIGINT, oldintr);
    990  1.22     lukem 		if (oldintp)
    991  1.22     lukem 			(void)signal(SIGPIPE, oldintp);
    992  1.42     lukem 		goto cleanup_fetch_url;
    993   1.2     lukem 	}
    994   1.2     lukem 	oldintr = signal(SIGINT, aborthttp);
    995   1.2     lukem 
    996   1.1     lukem 	bytes = 0;
    997   1.1     lukem 	hashbytes = mark;
    998   1.1     lukem 	progressmeter(-1);
    999   1.2     lukem 
   1000  1.24     lukem 			/* Finally, suck down the file. */
   1001  1.45     lukem 	buf = xmalloc(BUFSIZ + 1);
   1002  1.45     lukem 	do {
   1003  1.45     lukem 		ssize_t chunksize;
   1004  1.45     lukem 
   1005  1.45     lukem 		chunksize = 0;
   1006  1.45     lukem 					/* read chunksize */
   1007  1.45     lukem 		if (ischunked) {
   1008  1.45     lukem 			if (fgets(buf, BUFSIZ, fin) == NULL) {
   1009  1.45     lukem 				warnx("Unexpected EOF reading chunksize");
   1010  1.45     lukem 				goto cleanup_fetch_url;
   1011  1.45     lukem 			}
   1012  1.45     lukem 			chunksize = strtol(buf, &ep, 16);
   1013  1.45     lukem 			if (strcmp(ep, "\r\n") != 0) {
   1014  1.45     lukem 				warnx("Unexpected data following chunksize");
   1015  1.45     lukem 				goto cleanup_fetch_url;
   1016  1.45     lukem 			}
   1017  1.45     lukem 			if (debug)
   1018  1.59     lukem 				fprintf(ttyout,
   1019  1.59     lukem #ifndef NO_QUAD
   1020  1.59     lukem 				    "got chunksize of %qd\n",
   1021  1.45     lukem 				    (long long)chunksize);
   1022  1.59     lukem #else
   1023  1.59     lukem 				    "got chunksize of %ld\n",
   1024  1.59     lukem 				    (long)chunksize);
   1025  1.59     lukem #endif
   1026  1.45     lukem 			if (chunksize == 0)
   1027  1.45     lukem 				break;
   1028  1.45     lukem 		}
   1029  1.59     lukem 					/* transfer file or chunk */
   1030  1.59     lukem 		while (1) {
   1031  1.59     lukem 			struct timeval then, now, td;
   1032  1.59     lukem 			off_t bufrem;
   1033  1.59     lukem 
   1034  1.59     lukem 			(void)gettimeofday(&then, NULL);
   1035  1.59     lukem 			bufrem = rate_get ? rate_get : BUFSIZ;
   1036  1.59     lukem 			while (bufrem > 0) {
   1037  1.59     lukem 				len = fread(buf, sizeof(char),
   1038  1.59     lukem 				    ischunked ? MIN(chunksize, bufrem) : BUFSIZ,
   1039  1.59     lukem 				    fin);
   1040  1.59     lukem 				if (len <= 0)
   1041  1.59     lukem 					goto chunkdone;
   1042  1.59     lukem 				bytes += len;
   1043  1.59     lukem 				bufrem -= len;
   1044  1.59     lukem 				if (fwrite(buf, sizeof(char), len, fout)
   1045  1.59     lukem 				    != len) {
   1046  1.59     lukem 					warn("Writing `%s'", savefile);
   1047  1.59     lukem 					goto cleanup_fetch_url;
   1048  1.59     lukem 				}
   1049  1.45     lukem 			}
   1050  1.45     lukem 			if (hash && !progress) {
   1051  1.45     lukem 				while (bytes >= hashbytes) {
   1052  1.45     lukem 					(void)putc('#', ttyout);
   1053  1.45     lukem 					hashbytes += mark;
   1054  1.45     lukem 				}
   1055  1.45     lukem 				(void)fflush(ttyout);
   1056  1.45     lukem 			}
   1057  1.59     lukem 			if (ischunked) {
   1058  1.45     lukem 				chunksize -= len;
   1059  1.59     lukem 				if (chunksize <= 0)
   1060  1.59     lukem 					goto chunkdone;
   1061  1.59     lukem 			}
   1062  1.59     lukem 			if (rate_get) {
   1063  1.59     lukem 				while (1) {
   1064  1.59     lukem 					(void)gettimeofday(&now, NULL);
   1065  1.59     lukem 					timersub(&now, &then, &td);
   1066  1.59     lukem 					if (td.tv_sec > 0)
   1067  1.59     lukem 						break;
   1068  1.59     lukem 					usleep(1000000 - td.tv_usec);
   1069  1.59     lukem 				}
   1070  1.59     lukem 			}
   1071   1.1     lukem 		}
   1072  1.45     lukem 					/* read CRLF after chunk*/
   1073  1.59     lukem  chunkdone:
   1074  1.45     lukem 		if (ischunked) {
   1075  1.45     lukem 			if (fgets(buf, BUFSIZ, fin) == NULL)
   1076  1.45     lukem 				break;
   1077  1.45     lukem 			if (strcmp(buf, "\r\n") != 0) {
   1078  1.45     lukem 				warnx("Unexpected data following chunk");
   1079  1.45     lukem 				goto cleanup_fetch_url;
   1080   1.1     lukem 			}
   1081   1.1     lukem 		}
   1082  1.45     lukem 	} while (ischunked);
   1083   1.1     lukem 	if (hash && !progress && bytes > 0) {
   1084   1.1     lukem 		if (bytes < mark)
   1085  1.22     lukem 			(void)putc('#', ttyout);
   1086  1.22     lukem 		(void)putc('\n', ttyout);
   1087   1.1     lukem 	}
   1088  1.25     lukem 	if (ferror(fin)) {
   1089  1.25     lukem 		warn("Reading file");
   1090  1.42     lukem 		goto cleanup_fetch_url;
   1091   1.1     lukem 	}
   1092   1.2     lukem 	progressmeter(1);
   1093  1.25     lukem 	(void)fflush(fout);
   1094   1.3     lukem 	(void)signal(SIGINT, oldintr);
   1095  1.22     lukem 	if (oldintp)
   1096  1.22     lukem 		(void)signal(SIGPIPE, oldintp);
   1097  1.25     lukem 	if (closefunc == fclose && mtime != -1) {
   1098  1.25     lukem 		struct timeval tval[2];
   1099  1.25     lukem 
   1100  1.25     lukem 		(void)gettimeofday(&tval[0], NULL);
   1101  1.25     lukem 		tval[1].tv_sec = mtime;
   1102  1.25     lukem 		tval[1].tv_usec = 0;
   1103  1.31     lukem 		(*closefunc)(fout);
   1104  1.31     lukem 		fout = NULL;
   1105  1.31     lukem 
   1106  1.31     lukem 		if (utimes(savefile, tval) == -1) {
   1107  1.25     lukem 			fprintf(ttyout,
   1108  1.25     lukem 			    "Can't change modification time to %s",
   1109  1.25     lukem 			    asctime(localtime(&mtime)));
   1110  1.25     lukem 		}
   1111  1.25     lukem 	}
   1112  1.25     lukem 	if (bytes > 0)
   1113  1.25     lukem 		ptransfer(0);
   1114   1.1     lukem 
   1115  1.42     lukem 	rval = 0;
   1116  1.42     lukem 	goto cleanup_fetch_url;
   1117  1.11     lukem 
   1118   1.1     lukem improper:
   1119  1.27     lukem 	warnx("Improper response from `%s'", host);
   1120  1.11     lukem 
   1121  1.42     lukem cleanup_fetch_url:
   1122  1.23   thorpej 	resetsockbufsize();
   1123  1.24     lukem 	if (fin != NULL)
   1124  1.24     lukem 		fclose(fin);
   1125  1.24     lukem 	else if (s != -1)
   1126   1.1     lukem 		close(s);
   1127  1.22     lukem 	if (closefunc != NULL && fout != NULL)
   1128  1.22     lukem 		(*closefunc)(fout);
   1129  1.29     lukem 	FREEPTR(savefile);
   1130  1.27     lukem 	FREEPTR(user);
   1131  1.27     lukem 	FREEPTR(pass);
   1132  1.27     lukem 	FREEPTR(host);
   1133  1.60    itojun 	FREEPTR(port);
   1134  1.27     lukem 	FREEPTR(path);
   1135  1.50     lukem 	FREEPTR(decodedpath);
   1136  1.54     lukem 	FREEPTR(puser);
   1137  1.54     lukem 	FREEPTR(ppass);
   1138  1.27     lukem 	FREEPTR(buf);
   1139  1.44     lukem 	FREEPTR(auth);
   1140  1.42     lukem 	FREEPTR(location);
   1141  1.42     lukem 	FREEPTR(message);
   1142  1.42     lukem 	return (rval);
   1143   1.1     lukem }
   1144   1.1     lukem 
   1145   1.1     lukem /*
   1146  1.50     lukem  * Abort a HTTP retrieval
   1147   1.2     lukem  */
   1148   1.2     lukem void
   1149   1.3     lukem aborthttp(notused)
   1150   1.3     lukem 	int notused;
   1151   1.2     lukem {
   1152   1.2     lukem 
   1153   1.2     lukem 	alarmtimer(0);
   1154  1.24     lukem 	fputs("\nHTTP fetch aborted.\n", ttyout);
   1155   1.2     lukem 	longjmp(httpabort, 1);
   1156   1.2     lukem }
   1157   1.2     lukem 
   1158   1.2     lukem /*
   1159  1.50     lukem  * Retrieve ftp URL or classic ftp argument using FTP.
   1160  1.42     lukem  * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
   1161  1.42     lukem  * is still open (e.g, ftp xfer with trailing /)
   1162  1.42     lukem  */
   1163  1.42     lukem static int
   1164  1.52     lukem fetch_ftp(url)
   1165  1.42     lukem 	const char *url;
   1166  1.42     lukem {
   1167  1.42     lukem 	char		*cp, *xargv[5], rempath[MAXPATHLEN];
   1168  1.42     lukem 	char		*host, *path, *dir, *file, *user, *pass;
   1169  1.60    itojun 	char		*port;
   1170  1.53     lukem 	int		dirhasglob, filehasglob, oautologin, rval, type, xargc;
   1171  1.53     lukem 	url_t		urltype;
   1172  1.42     lukem 
   1173  1.42     lukem 	host = path = dir = file = user = pass = NULL;
   1174  1.60    itojun 	port = NULL;
   1175  1.42     lukem 	rval = 1;
   1176  1.53     lukem 	type = TYPE_I;
   1177  1.42     lukem 
   1178  1.42     lukem 	if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
   1179  1.42     lukem 		if ((parse_url(url, "URL", &urltype, &user, &pass,
   1180  1.42     lukem 		    &host, &port, &path) == -1) ||
   1181  1.42     lukem 		    (user != NULL && *user == '\0') ||
   1182  1.42     lukem 		    (pass != NULL && *pass == '\0') ||
   1183  1.42     lukem 		    EMPTYSTRING(host)) {
   1184  1.42     lukem 			warnx("Invalid URL `%s'", url);
   1185  1.42     lukem 			goto cleanup_fetch_ftp;
   1186  1.42     lukem 		}
   1187  1.50     lukem 		url_decode(user);
   1188  1.50     lukem 		url_decode(pass);
   1189  1.53     lukem 		/*
   1190  1.53     lukem 		 * Note: Don't url_decode(path) here.  We need to keep the
   1191  1.53     lukem 		 * distinction between "/" and "%2F" until later.
   1192  1.53     lukem 		 */
   1193  1.53     lukem 
   1194  1.53     lukem 					/* check for trailing ';type=[aid]' */
   1195  1.58     lukem 		if (path != NULL && (cp = strrchr(path, ';')) != NULL) {
   1196  1.53     lukem 			if (strcasecmp(cp, ";type=a") == 0)
   1197  1.53     lukem 				type = TYPE_A;
   1198  1.53     lukem 			else if (strcasecmp(cp, ";type=i") == 0)
   1199  1.53     lukem 				type = TYPE_I;
   1200  1.53     lukem 			else if (strcasecmp(cp, ";type=d") == 0) {
   1201  1.53     lukem 				warnx(
   1202  1.53     lukem 			    "Directory listing via a URL is not supported");
   1203  1.53     lukem 				goto cleanup_fetch_ftp;
   1204  1.53     lukem 			} else {
   1205  1.53     lukem 				warnx("Invalid suffix `%s' in URL `%s'", cp,
   1206  1.53     lukem 				    url);
   1207  1.53     lukem 				goto cleanup_fetch_ftp;
   1208  1.53     lukem 			}
   1209  1.53     lukem 			*cp = 0;
   1210  1.53     lukem 		}
   1211  1.42     lukem 	} else {			/* classic style `host:file' */
   1212  1.53     lukem 		urltype = CLASSIC_URL_T;
   1213  1.42     lukem 		host = xstrdup(url);
   1214  1.42     lukem 		cp = strchr(host, ':');
   1215  1.42     lukem 		if (cp != NULL) {
   1216  1.42     lukem 			*cp = '\0';
   1217  1.42     lukem 			path = xstrdup(cp + 1);
   1218  1.42     lukem 		}
   1219  1.42     lukem 	}
   1220  1.42     lukem 	if (EMPTYSTRING(host))
   1221  1.42     lukem 		goto cleanup_fetch_ftp;
   1222  1.42     lukem 
   1223  1.50     lukem 			/* Extract the file and (if present) directory name. */
   1224  1.42     lukem 	dir = path;
   1225  1.42     lukem 	if (! EMPTYSTRING(dir)) {
   1226  1.53     lukem 		/*
   1227  1.53     lukem 		 * If we are dealing with classic `host:path' syntax,
   1228  1.53     lukem 		 * then a path of the form `/file' (resulting from
   1229  1.53     lukem 		 * input of the form `host:/file') means that we should
   1230  1.53     lukem 		 * do "CWD /" before retreiving the file.  So we set
   1231  1.53     lukem 		 * dir="/" and file="file".
   1232  1.53     lukem 		 *
   1233  1.53     lukem 		 * But if we are dealing with URLs like
   1234  1.53     lukem 		 * `ftp://host/path' then a path of the form `/file'
   1235  1.53     lukem 		 * (resulting from a URL of the form `ftp://host//file')
   1236  1.53     lukem 		 * means that we should do `CWD ' (with an empty
   1237  1.53     lukem 		 * argument) before retrieving the file.  So we set
   1238  1.53     lukem 		 * dir="" and file="file".
   1239  1.53     lukem 		 *
   1240  1.53     lukem 		 * If the path does not contain / at all, we set
   1241  1.53     lukem 		 * dir=NULL.  (We get a path without any slashes if
   1242  1.53     lukem 		 * we are dealing with classic `host:file' or URL
   1243  1.53     lukem 		 * `ftp://host/file'.)
   1244  1.53     lukem 		 *
   1245  1.53     lukem 		 * In all other cases, we set dir to a string that does
   1246  1.53     lukem 		 * not include the final '/' that separates the dir part
   1247  1.53     lukem 		 * from the file part of the path.  (This will be the
   1248  1.53     lukem 		 * empty string if and only if we are dealing with a
   1249  1.53     lukem 		 * path of the form `/file' resulting from an URL of the
   1250  1.53     lukem 		 * form `ftp://host//file'.)
   1251  1.53     lukem 		 */
   1252  1.42     lukem 		cp = strrchr(dir, '/');
   1253  1.53     lukem 		if (cp == dir && urltype == CLASSIC_URL_T) {
   1254  1.50     lukem 			file = cp + 1;
   1255  1.50     lukem 			dir = "/";
   1256  1.50     lukem 		} else if (cp != NULL) {
   1257  1.42     lukem 			*cp++ = '\0';
   1258  1.42     lukem 			file = cp;
   1259  1.42     lukem 		} else {
   1260  1.42     lukem 			file = dir;
   1261  1.42     lukem 			dir = NULL;
   1262  1.42     lukem 		}
   1263  1.42     lukem 	}
   1264  1.53     lukem 	if (urltype == FTP_URL_T && file != NULL) {
   1265  1.53     lukem 		url_decode(file);
   1266  1.53     lukem 		/* but still don't url_decode(dir) */
   1267  1.53     lukem 	}
   1268  1.42     lukem 	if (debug)
   1269  1.42     lukem 		fprintf(ttyout,
   1270  1.60    itojun     "fetch_ftp: user `%s' pass `%s' host %s:%s path `%s' dir `%s' file `%s'\n",
   1271  1.53     lukem 		    user ? user : "<null>", pass ? pass : "<null>",
   1272  1.60    itojun 		    host ? host : "<null>", port ? port : "<null>",
   1273  1.60    itojun 		    path ? path : "<null>",
   1274  1.53     lukem 		    dir ? dir : "<null>", file ? file : "<null>");
   1275  1.42     lukem 
   1276  1.42     lukem 	dirhasglob = filehasglob = 0;
   1277  1.53     lukem 	if (doglob && urltype == CLASSIC_URL_T) {
   1278  1.42     lukem 		if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
   1279  1.42     lukem 			dirhasglob = 1;
   1280  1.42     lukem 		if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
   1281  1.42     lukem 			filehasglob = 1;
   1282  1.42     lukem 	}
   1283  1.42     lukem 
   1284  1.50     lukem 			/* Set up the connection */
   1285  1.50     lukem 	if (connected)
   1286  1.50     lukem 		disconnect(0, NULL);
   1287  1.50     lukem 	xargv[0] = __progname;
   1288  1.50     lukem 	xargv[1] = host;
   1289  1.50     lukem 	xargv[2] = NULL;
   1290  1.50     lukem 	xargc = 2;
   1291  1.50     lukem 	if (port) {
   1292  1.60    itojun 		xargv[2] = port;
   1293  1.50     lukem 		xargv[3] = NULL;
   1294  1.50     lukem 		xargc = 3;
   1295  1.50     lukem 	}
   1296  1.50     lukem 	oautologin = autologin;
   1297  1.50     lukem 	if (user != NULL)
   1298  1.50     lukem 		autologin = 0;
   1299  1.50     lukem 	setpeer(xargc, xargv);
   1300  1.50     lukem 	autologin = oautologin;
   1301  1.50     lukem 	if ((connected == 0) || ((connected == 1)
   1302  1.50     lukem 	    && !ftp_login(host, user, pass))) {
   1303  1.50     lukem 		warnx("Can't connect or login to host `%s'", host);
   1304  1.50     lukem 		goto cleanup_fetch_ftp;
   1305  1.50     lukem 	}
   1306  1.42     lukem 
   1307  1.53     lukem 	switch (type) {
   1308  1.53     lukem 	case TYPE_A:
   1309  1.53     lukem 		setascii(0, NULL);
   1310  1.53     lukem 		break;
   1311  1.53     lukem 	case TYPE_I:
   1312  1.53     lukem 		setbinary(0, NULL);
   1313  1.53     lukem 		break;
   1314  1.53     lukem 	default:
   1315  1.53     lukem 		errx(1, "fetch_ftp: unknown transfer type %d\n", type);
   1316  1.53     lukem 	}
   1317  1.53     lukem 
   1318  1.53     lukem 			/*
   1319  1.53     lukem 			 * Change directories, if necessary.
   1320  1.53     lukem 			 *
   1321  1.53     lukem 			 * Note: don't use EMPTYSTRING(dir) below, because
   1322  1.53     lukem 			 * dir="" means something different from dir=NULL.
   1323  1.53     lukem 			 */
   1324  1.53     lukem 	if (dir != NULL && !dirhasglob) {
   1325  1.53     lukem 		char *nextpart;
   1326  1.42     lukem 
   1327  1.53     lukem 		/*
   1328  1.53     lukem 		 * If we are dealing with a classic `host:path' (urltype
   1329  1.53     lukem 		 * is CLASSIC_URL_T) then we have a raw directory
   1330  1.53     lukem 		 * name (not encoded in any way) and we can change
   1331  1.53     lukem 		 * directories in one step.
   1332  1.53     lukem 		 *
   1333  1.53     lukem 		 * If we are dealing with an `ftp://host/path' URL
   1334  1.53     lukem 		 * (urltype is FTP_URL_T), then RFC 1738 says we need to
   1335  1.53     lukem 		 * send a separate CWD command for each unescaped "/"
   1336  1.53     lukem 		 * in the path, and we have to interpret %hex escaping
   1337  1.53     lukem 		 * *after* we find the slashes.  It's possible to get
   1338  1.53     lukem 		 * empty components here, (from multiple adjacent
   1339  1.53     lukem 		 * slashes in the path) and RFC 1738 says that we should
   1340  1.53     lukem 		 * still do `CWD ' (with a null argument) in such cases.
   1341  1.53     lukem 		 *
   1342  1.53     lukem 		 * XXX: many ftp servers don't support `CWD ', so we
   1343  1.53     lukem 		 * just skip the empty components.
   1344  1.53     lukem 		 *
   1345  1.53     lukem 		 * Examples:
   1346  1.53     lukem 		 *
   1347  1.53     lukem 		 * host:file			dir=NULL, urltype=CLASSIC_URL_T
   1348  1.53     lukem 		 *		"RETR file"
   1349  1.53     lukem 		 * ftp://host/file		dir=NULL, urltype=FTP_URL_T
   1350  1.53     lukem 		 *		"RETR file"
   1351  1.53     lukem 		 * ftp://host//file		dir="", urltype=FTP_URL_T
   1352  1.53     lukem 		 *		(no-op), "RETR file"
   1353  1.53     lukem 		 * host:/file			dir="/", urltype=CLASSIC_URL_T
   1354  1.53     lukem 		 *		"CWD /", "RETR file"
   1355  1.53     lukem 		 * ftp://host///file		dir="/", urltype=FTP_URL_T
   1356  1.53     lukem 		 *		(no-op), (no-op), "RETR file"
   1357  1.53     lukem 		 * ftp://host/%2F/file		dir="%2F", urltype=FTP_URL_T
   1358  1.53     lukem 		 *		"CWD /", "RETR file"
   1359  1.53     lukem 		 * ftp://host/foo/file		dir="foo", urltype=FTP_URL_T
   1360  1.53     lukem 		 *		"CWD foo", "RETR file"
   1361  1.53     lukem 		 * ftp://host/foo/bar/file	dir="foo/bar"
   1362  1.53     lukem 		 *		"CWD foo", "CWD bar", "RETR file"
   1363  1.53     lukem 		 * ftp://host//foo/bar/file	dir="/foo/bar"
   1364  1.53     lukem 		 *		(no-op), "CWD foo", "CWD bar", "RETR file"
   1365  1.53     lukem 		 * ftp://host/foo//bar/file	dir="foo//bar"
   1366  1.53     lukem 		 *		"CWD foo", (no-op), "CWD bar", "RETR file"
   1367  1.53     lukem 		 * ftp://host/%2F/foo/bar/file	dir="%2F/foo/bar"
   1368  1.53     lukem 		 *		"CWD /", "CWD foo", "CWD bar", "RETR file"
   1369  1.53     lukem 		 * ftp://host/%2Ffoo/bar/file	dir="%2Ffoo/bar"
   1370  1.53     lukem 		 *		"CWD /foo", "CWD bar", "RETR file"
   1371  1.53     lukem 		 * ftp://host/%2Ffoo%2Fbar/file	dir="%2Ffoo%2Fbar"
   1372  1.53     lukem 		 *		"CWD /foo/bar", "RETR file"
   1373  1.53     lukem 		 * ftp://host/%2Ffoo%2Fbar%2Ffile	dir=NULL
   1374  1.53     lukem 		 *		"RETR /foo/bar/file"
   1375  1.53     lukem 		 *
   1376  1.53     lukem 		 * Note that we don't need `dir' after this point.
   1377  1.53     lukem 		 */
   1378  1.53     lukem 		do {
   1379  1.53     lukem 			if (urltype == FTP_URL_T) {
   1380  1.53     lukem 				nextpart = strchr(dir, '/');
   1381  1.53     lukem 				if (nextpart) {
   1382  1.53     lukem 					*nextpart = '\0';
   1383  1.53     lukem 					nextpart++;
   1384  1.53     lukem 				}
   1385  1.53     lukem 				url_decode(dir);
   1386  1.53     lukem 			} else
   1387  1.53     lukem 				nextpart = NULL;
   1388  1.53     lukem 			if (debug)
   1389  1.53     lukem 				fprintf(ttyout, "dir `%s', nextpart `%s'\n",
   1390  1.53     lukem 				    dir ? dir : "<null>",
   1391  1.53     lukem 				    nextpart ? nextpart : "<null>");
   1392  1.53     lukem 			if (*dir != '\0') {
   1393  1.53     lukem 				xargv[0] = "cd";
   1394  1.53     lukem 				xargv[1] = dir;
   1395  1.53     lukem 				xargv[2] = NULL;
   1396  1.53     lukem 				dirchange = 0;
   1397  1.53     lukem 				cd(2, xargv);
   1398  1.53     lukem 				if (! dirchange)
   1399  1.53     lukem 					goto cleanup_fetch_ftp;
   1400  1.53     lukem 			}
   1401  1.53     lukem 			dir = nextpart;
   1402  1.53     lukem 		} while (dir != NULL);
   1403  1.42     lukem 	}
   1404  1.42     lukem 
   1405  1.42     lukem 	if (EMPTYSTRING(file)) {
   1406  1.42     lukem 		rval = -1;
   1407  1.42     lukem 		goto cleanup_fetch_ftp;
   1408  1.42     lukem 	}
   1409  1.42     lukem 
   1410  1.42     lukem 	if (dirhasglob) {
   1411  1.42     lukem 		snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
   1412  1.42     lukem 		file = rempath;
   1413  1.42     lukem 	}
   1414  1.42     lukem 
   1415  1.42     lukem 			/* Fetch the file(s). */
   1416  1.42     lukem 	xargc = 2;
   1417  1.42     lukem 	xargv[0] = "get";
   1418  1.42     lukem 	xargv[1] = file;
   1419  1.42     lukem 	xargv[2] = NULL;
   1420  1.42     lukem 	if (dirhasglob || filehasglob) {
   1421  1.42     lukem 		int ointeractive;
   1422  1.42     lukem 
   1423  1.42     lukem 		ointeractive = interactive;
   1424  1.42     lukem 		interactive = 0;
   1425  1.42     lukem 		xargv[0] = "mget";
   1426  1.42     lukem 		mget(xargc, xargv);
   1427  1.42     lukem 		interactive = ointeractive;
   1428  1.42     lukem 	} else {
   1429  1.53     lukem 		if (outfile == NULL) {
   1430  1.53     lukem 			cp = strrchr(file, '/');	/* find savefile */
   1431  1.53     lukem 			if (cp != NULL)
   1432  1.53     lukem 				outfile = cp + 1;
   1433  1.53     lukem 			else
   1434  1.53     lukem 				outfile = file;
   1435  1.42     lukem 		}
   1436  1.53     lukem 		xargv[2] = (char *)outfile;
   1437  1.53     lukem 		xargv[3] = NULL;
   1438  1.53     lukem 		xargc++;
   1439  1.52     lukem 		if (restartautofetch)
   1440  1.52     lukem 			reget(xargc, xargv);
   1441  1.52     lukem 		else
   1442  1.52     lukem 			get(xargc, xargv);
   1443  1.42     lukem 	}
   1444  1.42     lukem 
   1445  1.42     lukem 	if ((code / 100) == COMPLETE)
   1446  1.42     lukem 		rval = 0;
   1447  1.42     lukem 
   1448  1.42     lukem cleanup_fetch_ftp:
   1449  1.42     lukem 	FREEPTR(host);
   1450  1.42     lukem 	FREEPTR(path);
   1451  1.42     lukem 	FREEPTR(user);
   1452  1.42     lukem 	FREEPTR(pass);
   1453  1.42     lukem 	return (rval);
   1454  1.60    itojun }
   1455  1.60    itojun 
   1456  1.60    itojun int
   1457  1.60    itojun isurl(p)
   1458  1.60    itojun 	const char *p;
   1459  1.60    itojun {
   1460  1.60    itojun 	if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0
   1461  1.60    itojun 	 || strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
   1462  1.60    itojun 		return 1;
   1463  1.60    itojun 	}
   1464  1.60    itojun 	return 0;
   1465  1.42     lukem }
   1466  1.42     lukem 
   1467  1.42     lukem /*
   1468  1.42     lukem  * Retrieve the given file to outfile.
   1469  1.42     lukem  * Supports arguments of the form:
   1470  1.42     lukem  *	"host:path", "ftp://host/path"	if $ftpproxy, call fetch_url() else
   1471  1.42     lukem  *					call fetch_ftp()
   1472  1.50     lukem  *	"http://host/path"		call fetch_url() to use HTTP
   1473  1.42     lukem  *	"file:///path"			call fetch_url() to copy
   1474  1.42     lukem  *	"about:..."			print a message
   1475  1.42     lukem  *
   1476  1.42     lukem  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
   1477  1.42     lukem  * is still open (e.g, ftp xfer with trailing /)
   1478  1.42     lukem  */
   1479  1.42     lukem static int
   1480  1.52     lukem go_fetch(url)
   1481  1.42     lukem 	const char *url;
   1482  1.42     lukem {
   1483  1.42     lukem 
   1484  1.56       cgd #ifndef NO_ABOUT
   1485  1.42     lukem 	/*
   1486  1.42     lukem 	 * Check for about:*
   1487  1.42     lukem 	 */
   1488  1.42     lukem 	if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
   1489  1.42     lukem 		url += sizeof(ABOUT_URL) -1;
   1490  1.42     lukem 		if (strcasecmp(url, "ftp") == 0) {
   1491  1.42     lukem 			fprintf(ttyout, "%s\n%s\n",
   1492  1.42     lukem "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
   1493  1.50     lukem "Execute `man ftp' for more details");
   1494  1.42     lukem 		} else if (strcasecmp(url, "netbsd") == 0) {
   1495  1.42     lukem 			fprintf(ttyout, "%s\n%s\n",
   1496  1.42     lukem "NetBSD is a freely available and redistributable UNIX-like operating system.",
   1497  1.42     lukem "For more information, see http://www.netbsd.org/index.html");
   1498  1.42     lukem 		} else {
   1499  1.42     lukem 			fprintf(ttyout, "`%s' is an interesting topic.\n", url);
   1500  1.42     lukem 		}
   1501  1.42     lukem 		return (0);
   1502  1.42     lukem 	}
   1503  1.56       cgd #endif /* NO_ABOUT */
   1504  1.42     lukem 
   1505  1.42     lukem 	/*
   1506  1.42     lukem 	 * Check for file:// and http:// URLs.
   1507  1.42     lukem 	 */
   1508  1.42     lukem 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
   1509  1.42     lukem 	    strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
   1510  1.52     lukem 		return (fetch_url(url, NULL, NULL, NULL));
   1511  1.42     lukem 
   1512  1.42     lukem 	/*
   1513  1.42     lukem 	 * Try FTP URL-style and host:file arguments next.
   1514  1.42     lukem 	 * If ftpproxy is set with an FTP URL, use fetch_url()
   1515  1.42     lukem 	 * Othewise, use fetch_ftp().
   1516  1.42     lukem 	 */
   1517  1.42     lukem 	if (ftpproxy && strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
   1518  1.52     lukem 		return (fetch_url(url, NULL, NULL, NULL));
   1519  1.42     lukem 
   1520  1.52     lukem 	return (fetch_ftp(url));
   1521  1.42     lukem }
   1522  1.42     lukem 
   1523  1.42     lukem /*
   1524  1.42     lukem  * Retrieve multiple files from the command line,
   1525  1.42     lukem  * calling go_fetch() for each file.
   1526  1.42     lukem  *
   1527  1.42     lukem  * If an ftp path has a trailing "/", the path will be cd-ed into and
   1528  1.41     lukem  * the connection remains open, and the function will return -1
   1529  1.41     lukem  * (to indicate the connection is alive).
   1530   1.1     lukem  * If an error occurs the return value will be the offset+1 in
   1531   1.1     lukem  * argv[] of the file that caused a problem (i.e, argv[x]
   1532   1.1     lukem  * returns x+1)
   1533   1.1     lukem  * Otherwise, 0 is returned if all files retrieved successfully.
   1534   1.1     lukem  */
   1535   1.1     lukem int
   1536  1.52     lukem auto_fetch(argc, argv)
   1537   1.1     lukem 	int argc;
   1538   1.1     lukem 	char *argv[];
   1539   1.1     lukem {
   1540  1.42     lukem 	volatile int	argpos;
   1541  1.42     lukem 	int		rval;
   1542  1.22     lukem 
   1543   1.2     lukem 	argpos = 0;
   1544   1.1     lukem 
   1545   1.2     lukem 	if (setjmp(toplevel)) {
   1546   1.2     lukem 		if (connected)
   1547   1.2     lukem 			disconnect(0, NULL);
   1548   1.3     lukem 		return (argpos + 1);
   1549   1.2     lukem 	}
   1550   1.3     lukem 	(void)signal(SIGINT, (sig_t)intr);
   1551   1.3     lukem 	(void)signal(SIGPIPE, (sig_t)lostpeer);
   1552   1.1     lukem 
   1553   1.1     lukem 	/*
   1554   1.1     lukem 	 * Loop through as long as there's files to fetch.
   1555   1.1     lukem 	 */
   1556  1.27     lukem 	for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
   1557   1.1     lukem 		if (strchr(argv[argpos], ':') == NULL)
   1558   1.1     lukem 			break;
   1559  1.42     lukem 		redirect_loop = 0;
   1560  1.50     lukem 		anonftp = 1;		/* Handle "automatic" transfers. */
   1561  1.52     lukem 		rval = go_fetch(argv[argpos]);
   1562  1.52     lukem 		if (outfile != NULL && strcmp(outfile, "-") != 0
   1563  1.52     lukem 		    && outfile[0] != '|')
   1564  1.52     lukem 			outfile = NULL;
   1565  1.42     lukem 		if (rval > 0)
   1566   1.1     lukem 			rval = argpos + 1;
   1567  1.42     lukem 	}
   1568   1.3     lukem 
   1569   1.1     lukem 	if (connected && rval != -1)
   1570   1.1     lukem 		disconnect(0, NULL);
   1571   1.1     lukem 	return (rval);
   1572   1.1     lukem }
   1573