Home | History | Annotate | Line # | Download | only in ftp
fetch.c revision 1.40
      1 /*	$NetBSD: fetch.c,v 1.40 1998/11/22 06:52:32 explorer 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.40 1998/11/22 06:52:32 explorer 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, "Accept: */*\r\n");
    452 			fprintf(fin, "Connection: close\r\n\r\n");
    453 		}
    454 		if (fflush(fin) == EOF) {
    455 			warn("Writing HTTP request");
    456 			goto cleanup_url_get;
    457 		}
    458 
    459 				/* Read the response */
    460 		if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
    461 			warn("Receiving HTTP reply");
    462 			goto cleanup_url_get;
    463 		}
    464 		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
    465 			buf[--len] = '\0';
    466 		if (debug)
    467 			fprintf(ttyout, "received `%s'\n", buf);
    468 
    469 		cp = strchr(buf, ' ');
    470 		if (cp == NULL)
    471 			goto improper;
    472 		else
    473 			cp++;
    474 		if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
    475 			isredirected++;
    476 		} else if (strncmp(cp, "200", 3)) {
    477 			warnx("Error retrieving file `%s'", cp);
    478 			goto cleanup_url_get;
    479 		}
    480 
    481 				/* Read the rest of the header. */
    482 		FREEPTR(buf);
    483 		while (1) {
    484 			if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
    485 			    == NULL) {
    486 				warn("Receiving HTTP reply");
    487 				goto cleanup_url_get;
    488 			}
    489 			while (len > 0 &&
    490 			    (buf[len-1] == '\r' || buf[len-1] == '\n'))
    491 				buf[--len] = '\0';
    492 			if (len == 0)
    493 				break;
    494 			if (debug)
    495 				fprintf(ttyout, "received `%s'\n", buf);
    496 
    497 				/* Look for some headers */
    498 			cp = buf;
    499 #define CONTENTLEN "Content-Length: "
    500 			if (strncasecmp(cp, CONTENTLEN,
    501 			    sizeof(CONTENTLEN) - 1) == 0) {
    502 				cp += sizeof(CONTENTLEN) - 1;
    503 				filesize = strtol(cp, &ep, 10);
    504 				if (filesize < 1 || *ep != '\0')
    505 					goto improper;
    506 				if (debug)
    507 					fprintf(ttyout,
    508 #ifndef NO_QUAD
    509 					    "parsed length as: %qd\n",
    510 					    (long long)filesize);
    511 #else
    512 					    "parsed length as: %ld\n",
    513 					    (long)filesize);
    514 #endif
    515 #define LASTMOD "Last-Modified: "
    516 			} else if (strncasecmp(cp, LASTMOD,
    517 			    sizeof(LASTMOD) - 1) == 0) {
    518 				struct tm parsed;
    519 				char *t;
    520 
    521 				cp += sizeof(LASTMOD) - 1;
    522 							/* RFC 1123 */
    523 				if ((t = strptime(cp,
    524 						"%a, %d %b %Y %H:%M:%S GMT",
    525 						&parsed))
    526 							/* RFC 850 */
    527 				    || (t = strptime(cp,
    528 						"%a, %d-%b-%y %H:%M:%S GMT",
    529 						&parsed))
    530 							/* asctime */
    531 				    || (t = strptime(cp,
    532 						"%a, %b %d %H:%M:%S %Y",
    533 						&parsed))) {
    534 					parsed.tm_isdst = -1;
    535 					if (*t == '\0')
    536 						mtime = mkgmtime(&parsed);
    537 					if (debug && mtime != -1) {
    538 						fprintf(ttyout,
    539 						    "parsed date as: %s",
    540 						    ctime(&mtime));
    541 					}
    542 				}
    543 #define LOCATION "Location: "
    544 			} else if (isredirected &&
    545 			    strncasecmp(cp, LOCATION,
    546 				sizeof(LOCATION) - 1) == 0) {
    547 				cp += sizeof(LOCATION) - 1;
    548 				if (debug)
    549 					fprintf(ttyout,
    550 					    "parsed location as: %s\n", cp);
    551 				if (verbose)
    552 					fprintf(ttyout,
    553 					    "Redirected to %s\n", cp);
    554 				retval = url_get(cp, proxyenv, outfile);
    555 				goto cleanup_url_get;
    556 			}
    557 		}
    558 		FREEPTR(buf);
    559 	}
    560 
    561 	oldintr = oldintp = NULL;
    562 
    563 			/* Open the output file. */
    564 	if (strcmp(savefile, "-") == 0) {
    565 		fout = stdout;
    566 	} else if (*savefile == '|') {
    567 		oldintp = signal(SIGPIPE, SIG_IGN);
    568 		fout = popen(savefile + 1, "w");
    569 		if (fout == NULL) {
    570 			warn("Can't run `%s'", savefile + 1);
    571 			goto cleanup_url_get;
    572 		}
    573 		closefunc = pclose;
    574 	} else {
    575 		fout = fopen(savefile, "w");
    576 		if (fout == NULL) {
    577 			warn("Can't open `%s'", savefile);
    578 			goto cleanup_url_get;
    579 		}
    580 		closefunc = fclose;
    581 	}
    582 
    583 			/* Trap signals */
    584 	if (setjmp(httpabort)) {
    585 		if (oldintr)
    586 			(void)signal(SIGINT, oldintr);
    587 		if (oldintp)
    588 			(void)signal(SIGPIPE, oldintp);
    589 		goto cleanup_url_get;
    590 	}
    591 	oldintr = signal(SIGINT, aborthttp);
    592 
    593 	bytes = 0;
    594 	hashbytes = mark;
    595 	progressmeter(-1);
    596 
    597 			/* Finally, suck down the file. */
    598 	buf = xmalloc(BUFSIZ);
    599 	while ((len = fread(buf, sizeof(char), BUFSIZ, fin)) > 0) {
    600 		bytes += len;
    601 		if (fwrite(buf, sizeof(char), len, fout) != len) {
    602 			warn("Writing `%s'", savefile);
    603 			goto cleanup_url_get;
    604 		}
    605 		if (hash && !progress) {
    606 			while (bytes >= hashbytes) {
    607 				(void)putc('#', ttyout);
    608 				hashbytes += mark;
    609 			}
    610 			(void)fflush(ttyout);
    611 		}
    612 	}
    613 	if (hash && !progress && bytes > 0) {
    614 		if (bytes < mark)
    615 			(void)putc('#', ttyout);
    616 		(void)putc('\n', ttyout);
    617 		(void)fflush(ttyout);
    618 	}
    619 	if (ferror(fin)) {
    620 		warn("Reading file");
    621 		goto cleanup_url_get;
    622 	}
    623 	progressmeter(1);
    624 	(void)fflush(fout);
    625 	(void)signal(SIGINT, oldintr);
    626 	if (oldintp)
    627 		(void)signal(SIGPIPE, oldintp);
    628 	if (closefunc == fclose && mtime != -1) {
    629 		struct timeval tval[2];
    630 
    631 		(void)gettimeofday(&tval[0], NULL);
    632 		tval[1].tv_sec = mtime;
    633 		tval[1].tv_usec = 0;
    634 		(*closefunc)(fout);
    635 		fout = NULL;
    636 
    637 		if (utimes(savefile, tval) == -1) {
    638 			fprintf(ttyout,
    639 			    "Can't change modification time to %s",
    640 			    asctime(localtime(&mtime)));
    641 		}
    642 	}
    643 	if (bytes > 0)
    644 		ptransfer(0);
    645 
    646 	retval = 0;
    647 	goto cleanup_url_get;
    648 
    649 noftpautologin:
    650 	warnx(
    651 	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
    652 	goto cleanup_url_get;
    653 
    654 improper:
    655 	warnx("Improper response from `%s'", host);
    656 
    657 cleanup_url_get:
    658 	resetsockbufsize();
    659 	if (fin != NULL)
    660 		fclose(fin);
    661 	else if (s != -1)
    662 		close(s);
    663 	if (closefunc != NULL && fout != NULL)
    664 		(*closefunc)(fout);
    665 	FREEPTR(savefile);
    666 	FREEPTR(user);
    667 	FREEPTR(pass);
    668 	FREEPTR(host);
    669 	FREEPTR(path);
    670 	FREEPTR(buf);
    671 	return (retval);
    672 }
    673 
    674 /*
    675  * Abort a http retrieval
    676  */
    677 void
    678 aborthttp(notused)
    679 	int notused;
    680 {
    681 
    682 	alarmtimer(0);
    683 	fputs("\nHTTP fetch aborted.\n", ttyout);
    684 	(void)fflush(ttyout);
    685 	longjmp(httpabort, 1);
    686 }
    687 
    688 /*
    689  * Retrieve multiple files from the command line, transferring
    690  * URLs of the form "host:path", "ftp://host/path" using the
    691  * ftp protocol, URLs of the form "http://host/path" using the
    692  * http protocol, and URLs of the form "file:///" by simple
    693  * copying.
    694  * If path has a trailing "/", then return (-1);
    695  * the path will be cd-ed into and the connection remains open,
    696  * and the function will return -1 (to indicate the connection
    697  * is alive).
    698  * If an error occurs the return value will be the offset+1 in
    699  * argv[] of the file that caused a problem (i.e, argv[x]
    700  * returns x+1)
    701  * Otherwise, 0 is returned if all files retrieved successfully.
    702  */
    703 int
    704 auto_fetch(argc, argv, outfile)
    705 	int argc;
    706 	char *argv[];
    707 	char *outfile;
    708 {
    709 	static char lasthost[MAXHOSTNAMELEN];
    710 	char portnum[6];		/* large enough for "65535\0" */
    711 	char *xargv[5];
    712 	const char *line;
    713 	char *cp, *host, *path, *dir, *file;
    714 	char *user, *pass;
    715 	in_port_t port;
    716 	char *ftpproxy, *httpproxy;
    717 	int rval, xargc;
    718 	volatile int argpos;
    719 	int dirhasglob, filehasglob;
    720 	char rempath[MAXPATHLEN];
    721 
    722 #ifdef __GNUC__			/* to shut up gcc warnings */
    723 	(void)&outfile;
    724 #endif
    725 
    726 	argpos = 0;
    727 
    728 	if (setjmp(toplevel)) {
    729 		if (connected)
    730 			disconnect(0, NULL);
    731 		return (argpos + 1);
    732 	}
    733 	(void)signal(SIGINT, (sig_t)intr);
    734 	(void)signal(SIGPIPE, (sig_t)lostpeer);
    735 
    736 	ftpproxy = getenv(FTP_PROXY);
    737 	httpproxy = getenv(HTTP_PROXY);
    738 
    739 	/*
    740 	 * Loop through as long as there's files to fetch.
    741 	 */
    742 	for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
    743 		if (strchr(argv[argpos], ':') == NULL)
    744 			break;
    745 		host = path = dir = file = user = pass = NULL;
    746 		port = 0;
    747 		line = argv[argpos];
    748 
    749 #ifndef SMALL
    750 		/*
    751 		 * Check for about:*
    752 		 */
    753 		if (strncasecmp(line, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
    754 			line += sizeof(ABOUT_URL) -1;
    755 			if (strcasecmp(line, "ftp") == 0) {
    756 				fprintf(ttyout, "%s\n%s\n",
    757 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
    758 "Execute 'man ftp' for more details");
    759 			} else if (strcasecmp(line, "netbsd") == 0) {
    760 				fprintf(ttyout, "%s\n%s\n",
    761 "NetBSD is a freely available and redistributable UNIX-like operating system.",
    762 "For more information, see http://www.netbsd.org/index.html");
    763 			} else {
    764 				fprintf(ttyout,
    765 				    "`%s' is an interesting topic.\n", line);
    766 			}
    767 			continue;
    768 		}
    769 #endif /* SMALL */
    770 
    771 		/*
    772 		 * Check for file:// and http:// URLs.
    773 		 */
    774 		if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
    775 		    strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
    776 			if (url_get(line, httpproxy, outfile) == -1)
    777 				rval = argpos + 1;
    778 			continue;
    779 		}
    780 
    781 		/*
    782 		 * Try FTP URL-style arguments next. If ftpproxy is
    783 		 * set, use url_get() instead of standard ftp.
    784 		 * Finally, try host:file.
    785 		 */
    786 		if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
    787 			url_t urltype;
    788 
    789 			if (ftpproxy) {
    790 				if (url_get(line, ftpproxy, outfile) == -1)
    791 					rval = argpos + 1;
    792 				continue;
    793 			}
    794 			if ((parse_url(line, "URL", &urltype, &user, &pass,
    795 			    &host, &port, &path) == -1) ||
    796 			    (user != NULL && *user == '\0') ||
    797 			    (pass != NULL && *pass == '\0') ||
    798 			    EMPTYSTRING(host)) {
    799 				warnx("Invalid URL `%s'", argv[argpos]);
    800 				rval = argpos + 1;
    801 				break;
    802 			}
    803 		} else {			/* classic style `host:file' */
    804 			host = xstrdup(line);
    805 			cp = strchr(host, ':');
    806 			if (cp != NULL) {
    807 				*cp = '\0';
    808 				path = xstrdup(cp + 1);
    809 			}
    810 		}
    811 		if (EMPTYSTRING(host)) {
    812 			rval = argpos + 1;
    813 			break;
    814 		}
    815 
    816 		/*
    817 		 * Extract the file and (if present) directory name.
    818 		 */
    819 		dir = path;
    820 		if (! EMPTYSTRING(dir)) {
    821 			if (*dir == '/')
    822 				dir++;		/* skip leading / */
    823 			cp = strrchr(dir, '/');
    824 			if (cp != NULL) {
    825 				*cp++ = '\0';
    826 				file = cp;
    827 			} else {
    828 				file = dir;
    829 				dir = NULL;
    830 			}
    831 		}
    832 		if (debug)
    833 			fprintf(ttyout,
    834 "auto_fetch: user `%s', pass `%s', host %s:%d, path, `%s', dir `%s', file `%s'\n",
    835 			    user ? user : "", pass ? pass : "",
    836 			    host ? host : "", ntohs(port), path ? path : "",
    837 			    dir ? dir : "", file ? file : "");
    838 
    839 		dirhasglob = filehasglob = 0;
    840 		if (doglob) {
    841 			if (! EMPTYSTRING(dir) &&
    842 			    strpbrk(dir, "*?[]{}") != NULL)
    843 				dirhasglob = 1;
    844 			if (! EMPTYSTRING(file) &&
    845 			    strpbrk(file, "*?[]{}") != NULL)
    846 				filehasglob = 1;
    847 		}
    848 
    849 		/*
    850 		 * Set up the connection if we don't have one.
    851 		 */
    852 		if (strcasecmp(host, lasthost) != 0) {
    853 			int oautologin;
    854 
    855 			(void)strcpy(lasthost, host);
    856 			if (connected)
    857 				disconnect(0, NULL);
    858 			xargv[0] = __progname;
    859 			xargv[1] = host;
    860 			xargv[2] = NULL;
    861 			xargc = 2;
    862 			if (port) {
    863 				snprintf(portnum, sizeof(portnum),
    864 				    "%d", ntohs(port));
    865 				xargv[2] = portnum;
    866 				xargv[3] = NULL;
    867 				xargc = 3;
    868 			}
    869 			oautologin = autologin;
    870 			if (user != NULL)
    871 				autologin = 0;
    872 			setpeer(xargc, xargv);
    873 			autologin = oautologin;
    874 			if ((connected == 0)
    875 			 || ((connected == 1) &&
    876 			     !ftp_login(host, user, pass)) ) {
    877 				warnx("Can't connect or login to host `%s'",
    878 				    host);
    879 				rval = argpos + 1;
    880 				break;
    881 			}
    882 
    883 				/* Always use binary transfers. */
    884 			setbinary(0, NULL);
    885 		} else {
    886 				/* connection exists, cd back to `/' */
    887 			xargv[0] = "cd";
    888 			xargv[1] = "/";
    889 			xargv[2] = NULL;
    890 			dirchange = 0;
    891 			cd(2, xargv);
    892 			if (! dirchange) {
    893 				rval = argpos + 1;
    894 				break;
    895 			}
    896 		}
    897 
    898 				/* Change directories, if necessary. */
    899 		if (! EMPTYSTRING(dir) && !dirhasglob) {
    900 			xargv[0] = "cd";
    901 			xargv[1] = dir;
    902 			xargv[2] = NULL;
    903 			dirchange = 0;
    904 			cd(2, xargv);
    905 			if (! dirchange) {
    906 				rval = argpos + 1;
    907 				break;
    908 			}
    909 		}
    910 
    911 		if (EMPTYSTRING(file)) {
    912 			rval = -1;
    913 			break;
    914 		}
    915 
    916 		if (!verbose)
    917 			fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "",
    918 			    file);
    919 
    920 		if (dirhasglob) {
    921 			snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
    922 			file = rempath;
    923 		}
    924 
    925 				/* Fetch the file(s). */
    926 		xargc = 2;
    927 		xargv[0] = "get";
    928 		xargv[1] = file;
    929 		xargv[2] = NULL;
    930 		if (dirhasglob || filehasglob) {
    931 			int ointeractive;
    932 
    933 			ointeractive = interactive;
    934 			interactive = 0;
    935 			xargv[0] = "mget";
    936 			mget(xargc, xargv);
    937 			interactive = ointeractive;
    938 		} else {
    939 			if (outfile != NULL) {
    940 				xargv[2] = outfile;
    941 				xargv[3] = NULL;
    942 				xargc++;
    943 			}
    944 			get(xargc, xargv);
    945 			if (outfile != NULL && strcmp(outfile, "-") != 0
    946 			    && outfile[0] != '|')
    947 				outfile = NULL;
    948 		}
    949 
    950 		if ((code / 100) != COMPLETE)
    951 			rval = argpos + 1;
    952 	}
    953 	if (connected && rval != -1)
    954 		disconnect(0, NULL);
    955 	FREEPTR(host);
    956 	FREEPTR(path);
    957 	FREEPTR(user);
    958 	FREEPTR(pass);
    959 	return (rval);
    960 }
    961