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