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