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