Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.39
      1 /*	$NetBSD: fetch.c,v 1.39 1998/11/18 07:24:26 itohy Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason Thorpe and Luke Mewburn.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 __RCSID("$NetBSD: fetch.c,v 1.39 1998/11/18 07:24:26 itohy Exp $");
     42 #endif /* not lint */
     43 
     44 /*
     45  * FTP User Program -- Command line file retrieval
     46  */
     47 
     48 #include <sys/types.h>
     49 #include <sys/param.h>
     50 #include <sys/socket.h>
     51 #include <sys/stat.h>
     52 #include <sys/time.h>
     53 
     54 #include <netinet/in.h>
     55 
     56 #include <arpa/ftp.h>
     57 #include <arpa/inet.h>
     58 
     59 #include <ctype.h>
     60 #include <err.h>
     61 #include <errno.h>
     62 #include <netdb.h>
     63 #include <fcntl.h>
     64 #include <signal.h>
     65 #include <stdio.h>
     66 #include <stdlib.h>
     67 #include <string.h>
     68 #include <unistd.h>
     69 #include <util.h>
     70 
     71 #include "ftp_var.h"
     72 
     73 typedef enum {
     74 	UNKNOWN_URL_T=-1,
     75 	HTTP_URL_T,
     76 	FTP_URL_T,
     77 	FILE_URL_T
     78 } url_t;
     79 
     80 static int	parse_url __P((const char *, const char *, url_t *, char **,
     81 				char **, char **, in_port_t *, char **));
     82 static int	url_get __P((const char *, const char *, const char *));
     83 void    	aborthttp __P((int));
     84 
     85 
     86 #define	ABOUT_URL	"about:"	/* propaganda */
     87 #define	FILE_URL	"file://"	/* file URL prefix */
     88 #define	FTP_URL		"ftp://"	/* ftp URL prefix */
     89 #define	HTTP_URL	"http://"	/* http URL prefix */
     90 #define FTP_PROXY	"ftp_proxy"	/* env var with ftp proxy location */
     91 #define HTTP_PROXY	"http_proxy"	/* env var with http proxy location */
     92 #define NO_PROXY	"no_proxy"	/* env var with list of non-proxied
     93 					 * hosts, comma or space separated */
     94 
     95 
     96 #define EMPTYSTRING(x)	((x) == NULL || (*(x) == '\0'))
     97 #define FREEPTR(x)	if ((x) != NULL) { free(x); (x) = NULL; }
     98 
     99 /*
    100  * Parse URL of form:
    101  *	<type>://[<user>[:<password>@]]<host>[:<port>]/<url-path>
    102  * Returns -1 if a parse error occurred, otherwise 0.
    103  * Sets type to url_t, each of the given char ** pointers to a
    104  * malloc(3)ed strings of the relevant section, and port to
    105  * 0 if not given, or the number given.
    106  */
    107 static int
    108 parse_url(url, desc, type, user, pass, host, port, path)
    109 	const char	 *url;
    110 	const char	 *desc;
    111 	url_t		 *type;
    112 	char		**user;
    113 	char		**pass;
    114 	char		**host;
    115 	in_port_t	 *port;
    116 	char		**path;
    117 {
    118 	char *cp, *ep, *thost;
    119 
    120 	if (url == NULL || desc == NULL || type == NULL || user == NULL
    121 	    || pass == NULL || host == NULL || port == NULL || path == NULL)
    122 		errx(1, "parse_url: invoked with NULL argument!");
    123 
    124 	*type = UNKNOWN_URL_T;
    125 	*user = *pass = *host = *path = NULL;
    126 	*port = 0;
    127 
    128 	if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
    129 		url += sizeof(HTTP_URL) - 1;
    130 		*type = HTTP_URL_T;
    131 	} else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
    132 		url += sizeof(FTP_URL) - 1;
    133 		*type = FTP_URL_T;
    134 	} else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
    135 		url += sizeof(FILE_URL) - 1;
    136 		*type = FILE_URL_T;
    137 	} else {
    138 		warnx("Invalid %s `%s'", desc, url);
    139 cleanup_parse_url:
    140 		FREEPTR(*user);
    141 		FREEPTR(*pass);
    142 		FREEPTR(*host);
    143 		FREEPTR(*path);
    144 		return (-1);
    145 	}
    146 
    147 	if (*url == '\0')
    148 		return (0);
    149 
    150 			/* find [user[:pass]@]host[:port] */
    151 	ep = strchr(url, '/');
    152 	if (ep == NULL)
    153 		thost = xstrdup(url);
    154 	else {
    155 		size_t len = ep - url;
    156 		thost = (char *)xmalloc(len + 1);
    157 		strncpy(thost, url, len);
    158 		thost[len] = '\0';
    159 		*path = xstrdup(ep);
    160 	}
    161 
    162 	cp = strchr(thost, '@');
    163 	if (cp != NULL) {
    164 		*user = thost;
    165 		*cp = '\0';
    166 		*host = xstrdup(cp + 1);
    167 		cp = strchr(*user, ':');
    168 		if (cp != NULL) {
    169 			*cp = '\0';
    170 			*pass = xstrdup(cp + 1);
    171 		}
    172 	} else
    173 		*host = thost;
    174 
    175 			/* look for [:port] */
    176 	cp = strrchr(*host, ':');
    177 	if (cp != NULL) {
    178 		long nport;
    179 
    180 		*cp = '\0';
    181 		nport = strtol(cp + 1, &ep, 10);
    182 		if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
    183 			warnx("Invalid port `%s' in %s `%s'", cp, desc, line);
    184 			goto cleanup_parse_url;
    185 		}
    186 		*port = htons((in_port_t)nport);
    187 	}
    188 
    189 	if (debug)
    190 		fprintf(ttyout,
    191 		    "parse_url: user `%s', pass `%s', host %s:%d, path `%s'\n",
    192 		    *user ? *user : "", *pass ? *pass : "", *host ? *host : "",
    193 		    ntohs(*port), *path ? *path : "");
    194 
    195 	return (0);
    196 }
    197 
    198 
    199 jmp_buf	httpabort;
    200 
    201 /*
    202  * Retrieve URL, via the proxy in $proxyvar if necessary.
    203  * Modifies the string argument given.
    204  * Returns -1 on failure, 0 on success
    205  */
    206 static int
    207 url_get(url, proxyenv, outfile)
    208 	const char *url;
    209 	const char *proxyenv;
    210 	const char *outfile;
    211 {
    212 	struct sockaddr_in sin;
    213 	int isredirected, isproxy;
    214 	volatile int s;
    215 	size_t len;
    216 	char *cp, *ep;
    217 	char *buf, *savefile;
    218 	volatile sig_t oldintr, oldintp;
    219 	off_t hashbytes;
    220 	struct hostent *hp = NULL;
    221 	int (*closefunc) __P((FILE *));
    222 	FILE *fin, *fout;
    223 	int retval;
    224 	time_t mtime;
    225 	url_t urltype;
    226 	char *user, *pass, *host;
    227 	in_port_t port;
    228 	char *path;
    229 
    230 	closefunc = NULL;
    231 	fin = fout = NULL;
    232 	s = -1;
    233 	buf = savefile = NULL;
    234 	isredirected = isproxy = 0;
    235 	retval = -1;
    236 
    237 #ifdef __GNUC__			/* shut up gcc warnings */
    238 	(void)&closefunc;
    239 	(void)&fin;
    240 	(void)&fout;
    241 	(void)&buf;
    242 	(void)&savefile;
    243 	(void)&retval;
    244 	(void)&isproxy;
    245 #endif
    246 
    247 	if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
    248 	    == -1)
    249 		goto cleanup_url_get;
    250 	if (port == 0)
    251 		port = httpport;
    252 
    253 	if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
    254 	    && strcasecmp(host, "localhost") != 0) {
    255 		warnx("No support for non local file URL `%s'", url);
    256 		goto cleanup_url_get;
    257 	}
    258 
    259 	if (EMPTYSTRING(path)) {
    260 		if (urltype == FTP_URL_T)
    261 			goto noftpautologin;
    262 		if (urltype != HTTP_URL_T || outfile == NULL)  {
    263 			warnx("Invalid URL (no file after host) `%s'", url);
    264 			goto cleanup_url_get;
    265 		}
    266 	}
    267 
    268 	if (outfile)
    269 		savefile = xstrdup(outfile);
    270 	else {
    271 		cp = strrchr(path, '/');		/* find savefile */
    272 		if (cp != NULL)
    273 			savefile = xstrdup(cp + 1);
    274 		else
    275 			savefile = xstrdup(path);
    276 	}
    277 	if (EMPTYSTRING(savefile)) {
    278 		if (urltype == FTP_URL_T)
    279 			goto noftpautologin;
    280 		warnx("Invalid URL (no file after directory) `%s'", url);
    281 		goto cleanup_url_get;
    282 	}
    283 
    284 	filesize = -1;
    285 	mtime = -1;
    286 	if (urltype == FILE_URL_T) {		/* file:// URLs */
    287 		struct stat sb;
    288 
    289 		direction = "copied";
    290 		fin = fopen(path, "r");
    291 		if (fin == NULL) {
    292 			warn("Cannot open file `%s'", path);
    293 			goto cleanup_url_get;
    294 		}
    295 		if (fstat(fileno(fin), &sb) == 0) {
    296 			mtime = sb.st_mtime;
    297 			filesize = sb.st_size;
    298 		}
    299 		fprintf(ttyout, "Copying %s\n", path);
    300 	} else {				/* ftp:// or http:// URLs */
    301 		direction = "retrieved";
    302 		if (proxyenv != NULL) {				/* use proxy */
    303 			url_t purltype;
    304 			char *puser, *ppass, *phost;
    305 			in_port_t pport;
    306 			char *ppath;
    307 			char *no_proxy;
    308 
    309 			isproxy = 1;
    310 
    311 				/* check URL against list of no_proxied sites */
    312 			no_proxy = getenv(NO_PROXY);
    313 			if (no_proxy != NULL) {
    314 				char *np, *np_copy;
    315 				long np_port;
    316 				size_t hlen, plen;
    317 
    318 				np_copy = xstrdup(no_proxy);
    319 				hlen = strlen(host);
    320 				while ((cp = strsep(&np_copy, " ,")) != NULL) {
    321 					if (*cp == '\0')
    322 						continue;
    323 					if ((np = strchr(cp, ':')) != NULL) {
    324 						*np = '\0';
    325 						np_port =
    326 						    strtol(np + 1, &ep, 10);
    327 						if (*ep != '\0')
    328 							continue;
    329 						if (port !=
    330 						    htons((in_port_t)np_port))
    331 							continue;
    332 					}
    333 					plen = strlen(cp);
    334 					if (strncasecmp(host + hlen - plen,
    335 					    cp, plen) == 0) {
    336 						isproxy = 0;
    337 						break;
    338 					}
    339 				}
    340 				FREEPTR(np_copy);
    341 			}
    342 
    343 			if (isproxy) {
    344 				if (parse_url(proxyenv, "proxy URL", &purltype,
    345 				    &puser, &ppass, &phost, &pport, &ppath)
    346 				    == -1)
    347 					goto cleanup_url_get;
    348 
    349 				if ((purltype != HTTP_URL_T
    350 				     && purltype != FTP_URL_T) ||
    351 				    EMPTYSTRING(phost) ||
    352 				    (! EMPTYSTRING(ppath)
    353 				     && strcmp(ppath, "/") != 0)) {
    354 					warnx("Malformed proxy URL `%s'",
    355 					    proxyenv);
    356 					FREEPTR(puser);
    357 					FREEPTR(ppass);
    358 					FREEPTR(phost);
    359 					FREEPTR(ppath);
    360 					goto cleanup_url_get;
    361 				}
    362 
    363 				FREEPTR(user);
    364 				user = puser;
    365 				FREEPTR(pass);
    366 				pass = ppass;
    367 				FREEPTR(host);
    368 				host = phost;
    369 				if (pport == 0)
    370 					port = httpport;
    371 				else
    372 					port = pport;
    373 				FREEPTR(path);
    374 				FREEPTR(ppath);
    375 				path = xstrdup(url);
    376 			}
    377 		} /* proxyenv != NULL */
    378 
    379 		memset(&sin, 0, sizeof(sin));
    380 		sin.sin_family = AF_INET;
    381 
    382 		if (isdigit((unsigned char)host[0])) {
    383 			if (inet_aton(host, &sin.sin_addr) == 0) {
    384 				warnx("Invalid IP address `%s'", host);
    385 				goto cleanup_url_get;
    386 			}
    387 		} else {
    388 			hp = gethostbyname(host);
    389 			if (hp == NULL) {
    390 				warnx("%s: %s", host, hstrerror(h_errno));
    391 				goto cleanup_url_get;
    392 			}
    393 			if (hp->h_addrtype != AF_INET) {
    394 				warnx("`%s': not an Internet address?", host);
    395 				goto cleanup_url_get;
    396 			}
    397 			memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
    398 		}
    399 
    400 		if (port == 0)
    401 			port = httpport;
    402 		sin.sin_port = port;
    403 
    404 		s = socket(AF_INET, SOCK_STREAM, 0);
    405 		if (s == -1) {
    406 			warn("Can't create socket");
    407 			goto cleanup_url_get;
    408 		}
    409 
    410 		while (xconnect(s, (struct sockaddr *)&sin,
    411 		    sizeof(sin)) == -1) {
    412 			if (errno == EINTR)
    413 				continue;
    414 			if (hp && hp->h_addr_list[1]) {
    415 				int oerrno = errno;
    416 				char *ia;
    417 
    418 				ia = inet_ntoa(sin.sin_addr);
    419 				errno = oerrno;
    420 				warn("Connect to address `%s'", ia);
    421 				hp->h_addr_list++;
    422 				memcpy(&sin.sin_addr, hp->h_addr_list[0],
    423 				    (size_t)hp->h_length);
    424 				fprintf(ttyout, "Trying %s...\n",
    425 				    inet_ntoa(sin.sin_addr));
    426 				(void)close(s);
    427 				s = socket(AF_INET, SOCK_STREAM, 0);
    428 				if (s < 0) {
    429 					warn("Can't create socket");
    430 					goto cleanup_url_get;
    431 				}
    432 				continue;
    433 			}
    434 			warn("Can't connect to `%s'", host);
    435 			goto cleanup_url_get;
    436 		}
    437 
    438 		fin = fdopen(s, "r+");
    439 		/*
    440 		 * Construct and send the request.
    441 		 * Proxy requests don't want leading /.
    442 		 */
    443 		if (isproxy) {
    444 			fprintf(ttyout, "Requesting %s\n  (via %s)\n",
    445 			    url, proxyenv);
    446 			fprintf(fin, "GET %s HTTP/1.0\r\n\r\n", path);
    447 		} else {
    448 			fprintf(ttyout, "Requesting %s\n", url);
    449 			fprintf(fin, "GET %s HTTP/1.1\r\n", path);
    450 			fprintf(fin, "Host: %s\r\n", host);
    451 			fprintf(fin, "Connection: close\r\n\r\n");
    452 		}
    453 		if (fflush(fin) == EOF) {
    454 			warn("Writing HTTP request");
    455 			goto cleanup_url_get;
    456 		}
    457 
    458 				/* Read the response */
    459 		if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
    460 			warn("Receiving HTTP reply");
    461 			goto cleanup_url_get;
    462 		}
    463 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
    464 			buf[--len] = '\0';
    465 		if (debug)
    466 			fprintf(ttyout, "received `%s'\n", buf);
    467 
    468 		cp = strchr(buf, ' ');
    469 		if (cp == NULL)
    470 			goto improper;
    471 		else
    472 			cp++;
    473 		if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
    474 			isredirected++;
    475 		} else if (strncmp(cp, "200", 3)) {
    476 			warnx("Error retrieving file `%s'", cp);
    477 			goto cleanup_url_get;
    478 		}
    479 
    480 				/* Read the rest of the header. */
    481 		FREEPTR(buf);
    482 		while (1) {
    483 			if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
    484 			    == NULL) {
    485 				warn("Receiving HTTP reply");
    486 				goto cleanup_url_get;
    487 			}
    488 			while (len > 0 &&
    489 			    (buf[len-1] == '\r' || buf[len-1] == '\n'))
    490 				buf[--len] = '\0';
    491 			if (len == 0)
    492 				break;
    493 			if (debug)
    494 				fprintf(ttyout, "received `%s'\n", buf);
    495 
    496 				/* Look for some headers */
    497 			cp = buf;
    498 #define CONTENTLEN "Content-Length: "
    499 			if (strncasecmp(cp, CONTENTLEN,
    500 			    sizeof(CONTENTLEN) - 1) == 0) {
    501 				cp += sizeof(CONTENTLEN) - 1;
    502 				filesize = strtol(cp, &ep, 10);
    503 				if (filesize < 1 || *ep != '\0')
    504 					goto improper;
    505 				if (debug)
    506 					fprintf(ttyout,
    507 #ifndef NO_QUAD
    508 					    "parsed length as: %qd\n",
    509 					    (long long)filesize);
    510 #else
    511 					    "parsed length as: %ld\n",
    512 					    (long)filesize);
    513 #endif
    514 #define LASTMOD "Last-Modified: "
    515 			} else if (strncasecmp(cp, LASTMOD,
    516 			    sizeof(LASTMOD) - 1) == 0) {
    517 				struct tm parsed;
    518 				char *t;
    519 
    520 				cp += sizeof(LASTMOD) - 1;
    521 							/* RFC 1123 */
    522 				if ((t = strptime(cp,
    523 						"%a, %d %b %Y %H:%M:%S GMT",
    524 						&parsed))
    525 							/* RFC 850 */
    526 				    || (t = strptime(cp,
    527 						"%a, %d-%b-%y %H:%M:%S GMT",
    528 						&parsed))
    529 							/* asctime */
    530 				    || (t = strptime(cp,
    531 						"%a, %b %d %H:%M:%S %Y",
    532 						&parsed))) {
    533 					parsed.tm_isdst = -1;
    534 					if (*t == '\0')
    535 						mtime = mkgmtime(&parsed);
    536 					if (debug && mtime != -1) {
    537 						fprintf(ttyout,
    538 						    "parsed date as: %s",
    539 						    ctime(&mtime));
    540 					}
    541 				}
    542 #define LOCATION "Location: "
    543 			} else if (isredirected &&
    544 			    strncasecmp(cp, LOCATION,
    545 				sizeof(LOCATION) - 1) == 0) {
    546 				cp += sizeof(LOCATION) - 1;
    547 				if (debug)
    548 					fprintf(ttyout,
    549 					    "parsed location as: %s\n", cp);
    550 				if (verbose)
    551 					fprintf(ttyout,
    552 					    "Redirected to %s\n", cp);
    553 				retval = url_get(cp, proxyenv, outfile);
    554 				goto cleanup_url_get;
    555 			}
    556 		}
    557 		FREEPTR(buf);
    558 	}
    559 
    560 	oldintr = oldintp = NULL;
    561 
    562 			/* Open the output file. */
    563 	if (strcmp(savefile, "-") == 0) {
    564 		fout = stdout;
    565 	} else if (*savefile == '|') {
    566 		oldintp = signal(SIGPIPE, SIG_IGN);
    567 		fout = popen(savefile + 1, "w");
    568 		if (fout == NULL) {
    569 			warn("Can't run `%s'", savefile + 1);
    570 			goto cleanup_url_get;
    571 		}
    572 		closefunc = pclose;
    573 	} else {
    574 		fout = fopen(savefile, "w");
    575 		if (fout == NULL) {
    576 			warn("Can't open `%s'", savefile);
    577 			goto cleanup_url_get;
    578 		}
    579 		closefunc = fclose;
    580 	}
    581 
    582 			/* Trap signals */
    583 	if (setjmp(httpabort)) {
    584 		if (oldintr)
    585 			(void)signal(SIGINT, oldintr);
    586 		if (oldintp)
    587 			(void)signal(SIGPIPE, oldintp);
    588 		goto cleanup_url_get;
    589 	}
    590 	oldintr = signal(SIGINT, aborthttp);
    591 
    592 	bytes = 0;
    593 	hashbytes = mark;
    594 	progressmeter(-1);
    595 
    596 			/* Finally, suck down the file. */
    597 	buf = xmalloc(BUFSIZ);
    598 	while ((len = fread(buf, sizeof(char), BUFSIZ, fin)) > 0) {
    599 		bytes += len;
    600 		if (fwrite(buf, sizeof(char), len, fout) != len) {
    601 			warn("Writing `%s'", savefile);
    602 			goto cleanup_url_get;
    603 		}
    604 		if (hash && !progress) {
    605 			while (bytes >= hashbytes) {
    606 				(void)putc('#', ttyout);
    607 				hashbytes += mark;
    608 			}
    609 			(void)fflush(ttyout);
    610 		}
    611 	}
    612 	if (hash && !progress && bytes > 0) {
    613 		if (bytes < mark)
    614 			(void)putc('#', ttyout);
    615 		(void)putc('\n', ttyout);
    616 		(void)fflush(ttyout);
    617 	}
    618 	if (ferror(fin)) {
    619 		warn("Reading file");
    620 		goto cleanup_url_get;
    621 	}
    622 	progressmeter(1);
    623 	(void)fflush(fout);
    624 	(void)signal(SIGINT, oldintr);
    625 	if (oldintp)
    626 		(void)signal(SIGPIPE, oldintp);
    627 	if (closefunc == fclose && mtime != -1) {
    628 		struct timeval tval[2];
    629 
    630 		(void)gettimeofday(&tval[0], NULL);
    631 		tval[1].tv_sec = mtime;
    632 		tval[1].tv_usec = 0;
    633 		(*closefunc)(fout);
    634 		fout = NULL;
    635 
    636 		if (utimes(savefile, tval) == -1) {
    637 			fprintf(ttyout,
    638 			    "Can't change modification time to %s",
    639 			    asctime(localtime(&mtime)));
    640 		}
    641 	}
    642 	if (bytes > 0)
    643 		ptransfer(0);
    644 
    645 	retval = 0;
    646 	goto cleanup_url_get;
    647 
    648 noftpautologin:
    649 	warnx(
    650 	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
    651 	goto cleanup_url_get;
    652 
    653 improper:
    654 	warnx("Improper response from `%s'", host);
    655 
    656 cleanup_url_get:
    657 	resetsockbufsize();
    658 	if (fin != NULL)
    659 		fclose(fin);
    660 	else if (s != -1)
    661 		close(s);
    662 	if (closefunc != NULL && fout != NULL)
    663 		(*closefunc)(fout);
    664 	FREEPTR(savefile);
    665 	FREEPTR(user);
    666 	FREEPTR(pass);
    667 	FREEPTR(host);
    668 	FREEPTR(path);
    669 	FREEPTR(buf);
    670 	return (retval);
    671 }
    672 
    673 /*
    674  * Abort a http retrieval
    675  */
    676 void
    677 aborthttp(notused)
    678 	int notused;
    679 {
    680 
    681 	alarmtimer(0);
    682 	fputs("\nHTTP fetch aborted.\n", ttyout);
    683 	(void)fflush(ttyout);
    684 	longjmp(httpabort, 1);
    685 }
    686 
    687 /*
    688  * Retrieve multiple files from the command line, transferring
    689  * URLs of the form "host:path", "ftp://host/path" using the
    690  * ftp protocol, URLs of the form "http://host/path" using the
    691  * http protocol, and URLs of the form "file:///" by simple
    692  * copying.
    693  * If path has a trailing "/", then return (-1);
    694  * the path will be cd-ed into and the connection remains open,
    695  * and the function will return -1 (to indicate the connection
    696  * is alive).
    697  * If an error occurs the return value will be the offset+1 in
    698  * argv[] of the file that caused a problem (i.e, argv[x]
    699  * returns x+1)
    700  * Otherwise, 0 is returned if all files retrieved successfully.
    701  */
    702 int
    703 auto_fetch(argc, argv, outfile)
    704 	int argc;
    705 	char *argv[];
    706 	char *outfile;
    707 {
    708 	static char lasthost[MAXHOSTNAMELEN];
    709 	char portnum[6];		/* large enough for "65535\0" */
    710 	char *xargv[5];
    711 	const char *line;
    712 	char *cp, *host, *path, *dir, *file;
    713 	char *user, *pass;
    714 	in_port_t port;
    715 	char *ftpproxy, *httpproxy;
    716 	int rval, xargc;
    717 	volatile int argpos;
    718 	int dirhasglob, filehasglob;
    719 	char rempath[MAXPATHLEN];
    720 
    721 #ifdef __GNUC__			/* to shut up gcc warnings */
    722 	(void)&outfile;
    723 #endif
    724 
    725 	argpos = 0;
    726 
    727 	if (setjmp(toplevel)) {
    728 		if (connected)
    729 			disconnect(0, NULL);
    730 		return (argpos + 1);
    731 	}
    732 	(void)signal(SIGINT, (sig_t)intr);
    733 	(void)signal(SIGPIPE, (sig_t)lostpeer);
    734 
    735 	ftpproxy = getenv(FTP_PROXY);
    736 	httpproxy = getenv(HTTP_PROXY);
    737 
    738 	/*
    739 	 * Loop through as long as there's files to fetch.
    740 	 */
    741 	for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
    742 		if (strchr(argv[argpos], ':') == NULL)
    743 			break;
    744 		host = path = dir = file = user = pass = NULL;
    745 		port = 0;
    746 		line = argv[argpos];
    747 
    748 #ifndef SMALL
    749 		/*
    750 		 * Check for about:*
    751 		 */
    752 		if (strncasecmp(line, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
    753 			line += sizeof(ABOUT_URL) -1;
    754 			if (strcasecmp(line, "ftp") == 0) {
    755 				fprintf(ttyout, "%s\n%s\n",
    756 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
    757 "Execute 'man ftp' for more details");
    758 			} else if (strcasecmp(line, "netbsd") == 0) {
    759 				fprintf(ttyout, "%s\n%s\n",
    760 "NetBSD is a freely available and redistributable UNIX-like operating system.",
    761 "For more information, see http://www.netbsd.org/index.html");
    762 			} else {
    763 				fprintf(ttyout,
    764 				    "`%s' is an interesting topic.\n", line);
    765 			}
    766 			continue;
    767 		}
    768 #endif /* SMALL */
    769 
    770 		/*
    771 		 * Check for file:// and http:// URLs.
    772 		 */
    773 		if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
    774 		    strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
    775 			if (url_get(line, httpproxy, outfile) == -1)
    776 				rval = argpos + 1;
    777 			continue;
    778 		}
    779 
    780 		/*
    781 		 * Try FTP URL-style arguments next. If ftpproxy is
    782 		 * set, use url_get() instead of standard ftp.
    783 		 * Finally, try host:file.
    784 		 */
    785 		if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
    786 			url_t urltype;
    787 
    788 			if (ftpproxy) {
    789 				if (url_get(line, ftpproxy, outfile) == -1)
    790 					rval = argpos + 1;
    791 				continue;
    792 			}
    793 			if ((parse_url(line, "URL", &urltype, &user, &pass,
    794 			    &host, &port, &path) == -1) ||
    795 			    (user != NULL && *user == '\0') ||
    796 			    (pass != NULL && *pass == '\0') ||
    797 			    EMPTYSTRING(host)) {
    798 				warnx("Invalid URL `%s'", argv[argpos]);
    799 				rval = argpos + 1;
    800 				break;
    801 			}
    802 		} else {			/* classic style `host:file' */
    803 			host = xstrdup(line);
    804 			cp = strchr(host, ':');
    805 			if (cp != NULL) {
    806 				*cp = '\0';
    807 				path = xstrdup(cp + 1);
    808 			}
    809 		}
    810 		if (EMPTYSTRING(host)) {
    811 			rval = argpos + 1;
    812 			break;
    813 		}
    814 
    815 		/*
    816 		 * Extract the file and (if present) directory name.
    817 		 */
    818 		dir = path;
    819 		if (! EMPTYSTRING(dir)) {
    820 			if (*dir == '/')
    821 				dir++;		/* skip leading / */
    822 			cp = strrchr(dir, '/');
    823 			if (cp != NULL) {
    824 				*cp++ = '\0';
    825 				file = cp;
    826 			} else {
    827 				file = dir;
    828 				dir = NULL;
    829 			}
    830 		}
    831 		if (debug)
    832 			fprintf(ttyout,
    833 "auto_fetch: user `%s', pass `%s', host %s:%d, path, `%s', dir `%s', file `%s'\n",
    834 			    user ? user : "", pass ? pass : "",
    835 			    host ? host : "", ntohs(port), path ? path : "",
    836 			    dir ? dir : "", file ? file : "");
    837 
    838 		dirhasglob = filehasglob = 0;
    839 		if (doglob) {
    840 			if (! EMPTYSTRING(dir) &&
    841 			    strpbrk(dir, "*?[]{}") != NULL)
    842 				dirhasglob = 1;
    843 			if (! EMPTYSTRING(file) &&
    844 			    strpbrk(file, "*?[]{}") != NULL)
    845 				filehasglob = 1;
    846 		}
    847 
    848 		/*
    849 		 * Set up the connection if we don't have one.
    850 		 */
    851 		if (strcasecmp(host, lasthost) != 0) {
    852 			int oautologin;
    853 
    854 			(void)strcpy(lasthost, host);
    855 			if (connected)
    856 				disconnect(0, NULL);
    857 			xargv[0] = __progname;
    858 			xargv[1] = host;
    859 			xargv[2] = NULL;
    860 			xargc = 2;
    861 			if (port) {
    862 				snprintf(portnum, sizeof(portnum),
    863 				    "%d", ntohs(port));
    864 				xargv[2] = portnum;
    865 				xargv[3] = NULL;
    866 				xargc = 3;
    867 			}
    868 			oautologin = autologin;
    869 			if (user != NULL)
    870 				autologin = 0;
    871 			setpeer(xargc, xargv);
    872 			autologin = oautologin;
    873 			if ((connected == 0)
    874 			 || ((connected == 1) &&
    875 			     !ftp_login(host, user, pass)) ) {
    876 				warnx("Can't connect or login to host `%s'",
    877 				    host);
    878 				rval = argpos + 1;
    879 				break;
    880 			}
    881 
    882 				/* Always use binary transfers. */
    883 			setbinary(0, NULL);
    884 		} else {
    885 				/* connection exists, cd back to `/' */
    886 			xargv[0] = "cd";
    887 			xargv[1] = "/";
    888 			xargv[2] = NULL;
    889 			dirchange = 0;
    890 			cd(2, xargv);
    891 			if (! dirchange) {
    892 				rval = argpos + 1;
    893 				break;
    894 			}
    895 		}
    896 
    897 				/* Change directories, if necessary. */
    898 		if (! EMPTYSTRING(dir) && !dirhasglob) {
    899 			xargv[0] = "cd";
    900 			xargv[1] = dir;
    901 			xargv[2] = NULL;
    902 			dirchange = 0;
    903 			cd(2, xargv);
    904 			if (! dirchange) {
    905 				rval = argpos + 1;
    906 				break;
    907 			}
    908 		}
    909 
    910 		if (EMPTYSTRING(file)) {
    911 			rval = -1;
    912 			break;
    913 		}
    914 
    915 		if (!verbose)
    916 			fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "",
    917 			    file);
    918 
    919 		if (dirhasglob) {
    920 			snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
    921 			file = rempath;
    922 		}
    923 
    924 				/* Fetch the file(s). */
    925 		xargc = 2;
    926 		xargv[0] = "get";
    927 		xargv[1] = file;
    928 		xargv[2] = NULL;
    929 		if (dirhasglob || filehasglob) {
    930 			int ointeractive;
    931 
    932 			ointeractive = interactive;
    933 			interactive = 0;
    934 			xargv[0] = "mget";
    935 			mget(xargc, xargv);
    936 			interactive = ointeractive;
    937 		} else {
    938 			if (outfile != NULL) {
    939 				xargv[2] = outfile;
    940 				xargv[3] = NULL;
    941 				xargc++;
    942 			}
    943 			get(xargc, xargv);
    944 			if (outfile != NULL && strcmp(outfile, "-") != 0
    945 			    && outfile[0] != '|')
    946 				outfile = NULL;
    947 		}
    948 
    949 		if ((code / 100) != COMPLETE)
    950 			rval = argpos + 1;
    951 	}
    952 	if (connected && rval != -1)
    953 		disconnect(0, NULL);
    954 	FREEPTR(host);
    955 	FREEPTR(path);
    956 	FREEPTR(user);
    957 	FREEPTR(pass);
    958 	return (rval);
    959 }
    960