fetch.c revision 109702
1/*-
2 * Copyright (c) 2000 Dag-Erling Co�dan Sm�rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/usr.bin/fetch/fetch.c 109702 2003-01-22 18:33:39Z des $");
31
32#include <sys/param.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36
37#include <ctype.h>
38#include <err.h>
39#include <errno.h>
40#include <signal.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <sysexits.h>
45#include <termios.h>
46#include <unistd.h>
47
48#include <fetch.h>
49
50#define MINBUFSIZE	4096
51
52/* Option flags */
53int	 A_flag;	/*    -A: do not follow 302 redirects */
54int	 a_flag;	/*    -a: auto retry */
55off_t	 B_size;	/*    -B: buffer size */
56int	 b_flag;	/*!   -b: workaround TCP bug */
57char    *c_dirname;	/*    -c: remote directory */
58int	 d_flag;	/*    -d: direct connection */
59int	 F_flag;	/*    -F: restart without checking mtime  */
60char	*f_filename;	/*    -f: file to fetch */
61char	*h_hostname;	/*    -h: host to fetch from */
62int	 l_flag;	/*    -l: link rather than copy file: URLs */
63int	 m_flag;	/* -[Mm]: mirror mode */
64char	*N_filename;	/*    -N: netrc file name */
65int	 n_flag;	/*    -n: do not preserve modification time */
66int	 o_flag;	/*    -o: specify output file */
67int	 o_directory;	/*        output file is a directory */
68char	*o_filename;	/*        name of output file */
69int	 o_stdout;	/*        output file is stdout */
70int	 once_flag;	/*    -1: stop at first successful file */
71int	 p_flag;	/* -[Pp]: use passive FTP */
72int	 R_flag;	/*    -R: don't delete partially transferred files */
73int	 r_flag;	/*    -r: restart previously interrupted transfer */
74off_t	 S_size;        /*    -S: require size to match */
75int	 s_flag;        /*    -s: show size, don't fetch */
76long	 T_secs = 120;	/*    -T: transfer timeout in seconds */
77int	 t_flag;	/*!   -t: workaround TCP bug */
78int	 U_flag;	/*    -U: do not use high ports */
79int	 v_level = 1;	/*    -v: verbosity level */
80int	 v_tty;		/*        stdout is a tty */
81pid_t	 pgrp;		/*        our process group */
82long	 w_secs;	/*    -w: retry delay */
83int	 family = PF_UNSPEC;	/* -[46]: address family to use */
84
85int	 sigalrm;	/* SIGALRM received */
86int	 siginfo;	/* SIGINFO received */
87int	 sigint;	/* SIGINT received */
88
89long	 ftp_timeout;	/* default timeout for FTP transfers */
90long	 http_timeout;	/* default timeout for HTTP transfers */
91u_char	*buf;		/* transfer buffer */
92
93
94/*
95 * Signal handler
96 */
97static void
98sig_handler(int sig)
99{
100	switch (sig) {
101	case SIGALRM:
102		sigalrm = 1;
103		break;
104	case SIGINFO:
105		siginfo = 1;
106		break;
107	case SIGINT:
108		sigint = 1;
109		break;
110	}
111}
112
113struct xferstat {
114	char		 name[40];
115	struct timeval	 start;
116	struct timeval	 end;
117	struct timeval	 last;
118	off_t		 size;
119	off_t		 offset;
120	off_t		 rcvd;
121};
122
123/*
124 * Compute and display ETA
125 */
126static void
127stat_eta(struct xferstat *xs)
128{
129	long elapsed;
130	long remaining;
131
132	elapsed = xs->last.tv_sec - xs->start.tv_sec;
133	remaining = ((xs->size * elapsed) / xs->rcvd) - elapsed;
134	if (remaining > 3600) {
135		fprintf(stderr, "%02ld:", remaining / 3600);
136		remaining %= 3600;
137	}
138	fprintf(stderr, "%02ld:%02ld",
139	    remaining / 60, remaining % 60);
140}
141
142/*
143 * Compute and display transfer rate
144 */
145static void
146stat_bps(struct xferstat *xs)
147{
148	long elapsed;
149	double bps;
150
151	elapsed = xs->last.tv_sec - xs->start.tv_sec;
152	bps = (xs->rcvd - xs->offset) / elapsed;
153	if (bps > 1024*1024)
154		fprintf(stderr, "%.2f MBps", bps / (1024*1024));
155	else if (bps > 1024)
156		fprintf(stderr, "%.2f kBps", bps / 1024);
157	else
158		fprintf(stderr, "%.2f Bps", bps);
159}
160
161/*
162 * Update the stats display
163 */
164static void
165stat_display(struct xferstat *xs, int force)
166{
167	struct timeval now;
168	int ctty_pgrp;
169
170	if (!v_tty || !v_level)
171		return;
172
173	/* check if we're the foreground process */
174	if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
175	    (pid_t)ctty_pgrp != pgrp)
176		return;
177
178	gettimeofday(&now, NULL);
179	if (!force && now.tv_sec <= xs->last.tv_sec)
180		return;
181	xs->last = now;
182
183	fprintf(stderr, "\rReceiving %s", xs->name);
184	if (xs->size <= 0) {
185		fprintf(stderr, ": %lld bytes", (long long)xs->rcvd);
186	} else {
187		long elapsed;
188
189		fprintf(stderr, " (%lld bytes): %d%%", (long long)xs->size,
190		    (int)((100.0 * xs->rcvd) / xs->size));
191		elapsed = xs->last.tv_sec - xs->start.tv_sec;
192		if (elapsed > 30 && xs->rcvd > 0) {
193			fprintf(stderr, " (ETA ");
194			stat_eta(xs);
195			if (v_level > 1) {
196				fprintf(stderr, " at ");
197				stat_bps(xs);
198			}
199			fprintf(stderr, ")  ");
200		}
201	}
202}
203
204/*
205 * Initialize the transfer statistics
206 */
207static void
208stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
209{
210	snprintf(xs->name, sizeof xs->name, "%s", name);
211	gettimeofday(&xs->start, NULL);
212	xs->last.tv_sec = xs->last.tv_usec = 0;
213	xs->end = xs->last;
214	xs->size = size;
215	xs->offset = offset;
216	xs->rcvd = offset;
217	stat_display(xs, 1);
218}
219
220/*
221 * Update the transfer statistics
222 */
223static void
224stat_update(struct xferstat *xs, off_t rcvd)
225{
226	xs->rcvd = rcvd;
227	stat_display(xs, 0);
228}
229
230/*
231 * Finalize the transfer statistics
232 */
233static void
234stat_end(struct xferstat *xs)
235{
236	double delta;
237
238	if (!v_level)
239		return;
240
241	gettimeofday(&xs->end, NULL);
242
243	stat_display(xs, 1);
244	fputc('\n', stderr);
245	delta = (xs->end.tv_sec + (xs->end.tv_usec / 1.e6))
246	    - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
247	fprintf(stderr, "%lld bytes transferred in %.1f seconds (",
248	    (long long)(xs->rcvd - xs->offset), delta);
249	stat_bps(xs);
250	fprintf(stderr, ")\n");
251}
252
253/*
254 * Ask the user for authentication details
255 */
256static int
257query_auth(struct url *URL)
258{
259	struct termios tios;
260	tcflag_t saved_flags;
261	int i, nopwd;
262
263
264	fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
265	    URL->scheme, URL->host, URL->port);
266
267	fprintf(stderr, "Login: ");
268	if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
269		return -1;
270	for (i = 0; URL->user[i]; ++i)
271		if (isspace(URL->user[i]))
272			URL->user[i] = '\0';
273
274	fprintf(stderr, "Password: ");
275	if (tcgetattr(STDIN_FILENO, &tios) == 0) {
276		saved_flags = tios.c_lflag;
277		tios.c_lflag &= ~ECHO;
278		tios.c_lflag |= ECHONL|ICANON;
279		tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
280		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
281		tios.c_lflag = saved_flags;
282		tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
283	} else {
284		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
285	}
286	if (nopwd)
287		return -1;
288
289	for (i = 0; URL->pwd[i]; ++i)
290		if (isspace(URL->pwd[i]))
291			URL->pwd[i] = '\0';
292	return 0;
293}
294
295/*
296 * Fetch a file
297 */
298static int
299fetch(char *URL, const char *path)
300{
301	struct url *url;
302	struct url_stat us;
303	struct stat sb, nsb;
304	struct xferstat xs;
305	FILE *f, *of;
306	size_t size, wr;
307	off_t count;
308	char flags[8];
309	const char *slash;
310	char *tmppath;
311	int r;
312	u_int timeout;
313	u_char *ptr;
314
315	f = of = NULL;
316	tmppath = NULL;
317
318	timeout = 0;
319	*flags = 0;
320	count = 0;
321
322	/* set verbosity level */
323	if (v_level > 1)
324		strcat(flags, "v");
325	if (v_level > 2)
326		fetchDebug = 1;
327
328	/* parse URL */
329	if ((url = fetchParseURL(URL)) == NULL) {
330		warnx("%s: parse error", URL);
331		goto failure;
332	}
333
334	/* if no scheme was specified, take a guess */
335	if (!*url->scheme) {
336		if (!*url->host)
337			strcpy(url->scheme, SCHEME_FILE);
338		else if (strncasecmp(url->host, "ftp.", 4) == 0)
339			strcpy(url->scheme, SCHEME_FTP);
340		else if (strncasecmp(url->host, "www.", 4) == 0)
341			strcpy(url->scheme, SCHEME_HTTP);
342	}
343
344	/* common flags */
345	switch (family) {
346	case PF_INET:
347		strcat(flags, "4");
348		break;
349	case PF_INET6:
350		strcat(flags, "6");
351		break;
352	}
353
354	/* FTP specific flags */
355	if (strcmp(url->scheme, "ftp") == 0) {
356		if (p_flag)
357			strcat(flags, "p");
358		if (d_flag)
359			strcat(flags, "d");
360		if (U_flag)
361			strcat(flags, "l");
362		timeout = T_secs ? T_secs : ftp_timeout;
363	}
364
365	/* HTTP specific flags */
366	if (strcmp(url->scheme, "http") == 0) {
367		if (d_flag)
368			strcat(flags, "d");
369		if (A_flag)
370			strcat(flags, "A");
371		timeout = T_secs ? T_secs : http_timeout;
372	}
373
374	/* set the protocol timeout. */
375	fetchTimeout = timeout;
376
377	/* just print size */
378	if (s_flag) {
379		if (timeout)
380			alarm(timeout);
381		r = fetchStat(url, &us, flags);
382		if (timeout)
383			alarm(0);
384		if (sigalrm || sigint)
385			goto signal;
386		if (r == -1) {
387			warnx("%s", fetchLastErrString);
388			goto failure;
389		}
390		if (us.size == -1)
391			printf("Unknown\n");
392		else
393			printf("%lld\n", (long long)us.size);
394		goto success;
395	}
396
397	/*
398	 * If the -r flag was specified, we have to compare the local
399	 * and remote files, so we should really do a fetchStat()
400	 * first, but I know of at least one HTTP server that only
401	 * sends the content size in response to GET requests, and
402	 * leaves it out of replies to HEAD requests.  Also, in the
403	 * (frequent) case that the local and remote files match but
404	 * the local file is truncated, we have sufficient information
405	 * before the compare to issue a correct request.  Therefore,
406	 * we always issue a GET request as if we were sure the local
407	 * file was a truncated copy of the remote file; we can drop
408	 * the connection later if we change our minds.
409	 */
410	sb.st_size = -1;
411	if (!o_stdout && stat(path, &sb) == -1 && errno != ENOENT) {
412		warnx("%s: stat()", path);
413		goto failure;
414	}
415	if (!o_stdout && r_flag && S_ISREG(sb.st_mode))
416		url->offset = sb.st_size;
417
418	/* start the transfer */
419	if (timeout)
420		alarm(timeout);
421	f = fetchXGet(url, &us, flags);
422	if (timeout)
423		alarm(0);
424	if (sigalrm || sigint)
425		goto signal;
426	if (f == NULL) {
427		warnx("%s: %s", URL, fetchLastErrString);
428		goto failure;
429	}
430	if (sigint)
431		goto signal;
432
433	/* check that size is as expected */
434	if (S_size) {
435		if (us.size == -1) {
436			warnx("%s: size unknown", URL);
437			goto failure;
438		} else if (us.size != S_size) {
439			warnx("%s: size mismatch: expected %lld, actual %lld",
440			    URL, (long long)S_size, (long long)us.size);
441			goto failure;
442		}
443	}
444
445	/* symlink instead of copy */
446	if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
447		if (symlink(url->doc, path) == -1) {
448			warn("%s: symlink()", path);
449			goto failure;
450		}
451		goto success;
452	}
453
454	if (us.size == -1 && !o_stdout && v_level > 0)
455		warnx("%s: size of remote file is not known", URL);
456	if (v_level > 1) {
457		if (sb.st_size != -1)
458			fprintf(stderr, "local size / mtime: %lld / %ld\n",
459			    (long long)sb.st_size, (long)sb.st_mtime);
460		if (us.size != -1)
461			fprintf(stderr, "remote size / mtime: %lld / %ld\n",
462			    (long long)us.size, (long)us.mtime);
463	}
464
465	/* open output file */
466	if (o_stdout) {
467		/* output to stdout */
468		of = stdout;
469	} else if (r_flag && sb.st_size != -1) {
470		/* resume mode, local file exists */
471		if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
472			/* no match! have to refetch */
473			fclose(f);
474			/* if precious, warn the user and give up */
475			if (R_flag) {
476				warnx("%s: local modification time "
477				    "does not match remote", path);
478				goto failure_keep;
479			}
480		} else {
481			if (us.size == sb.st_size)
482				/* nothing to do */
483				goto success;
484			if (sb.st_size > us.size) {
485				/* local file too long! */
486				warnx("%s: local file (%lld bytes) is longer "
487				    "than remote file (%lld bytes)", path,
488				    (long long)sb.st_size, (long long)us.size);
489				goto failure;
490			}
491			/* we got it, open local file */
492			if ((of = fopen(path, "a")) == NULL) {
493				warn("%s: fopen()", path);
494				goto failure;
495			}
496			/* check that it didn't move under our feet */
497			if (fstat(fileno(of), &nsb) == -1) {
498				/* can't happen! */
499				warn("%s: fstat()", path);
500				goto failure;
501			}
502			if (nsb.st_dev != sb.st_dev ||
503			    nsb.st_ino != nsb.st_ino ||
504			    nsb.st_size != sb.st_size) {
505				warnx("%s: file has changed", URL);
506				fclose(of);
507				of = NULL;
508				sb = nsb;
509			}
510		}
511	} else if (m_flag && sb.st_size != -1) {
512		/* mirror mode, local file exists */
513		if (sb.st_size == us.size && sb.st_mtime == us.mtime)
514			goto success;
515	}
516
517	if (of == NULL) {
518		/*
519		 * We don't yet have an output file; either this is a
520		 * vanilla run with no special flags, or the local and
521		 * remote files didn't match.
522		 */
523
524		if (url->offset > 0) {
525			/*
526			 * We tried to restart a transfer, but for
527			 * some reason gave up - so we have to restart
528			 * from scratch if we want the whole file
529			 */
530			url->offset = 0;
531			if ((f = fetchXGet(url, &us, flags)) == NULL) {
532				warnx("%s: %s", URL, fetchLastErrString);
533				goto failure;
534			}
535			if (sigint)
536				goto signal;
537		}
538
539		/* construct a temp file name */
540		if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
541			if ((slash = strrchr(path, '/')) == NULL)
542				slash = path;
543			else
544				++slash;
545			asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
546			    (int)(slash - path), path, slash);
547			if (tmppath != NULL) {
548				mkstemps(tmppath, strlen(slash) + 1);
549				of = fopen(tmppath, "w");
550			}
551		}
552		if (of == NULL)
553			of = fopen(path, "w");
554		if (of == NULL) {
555			warn("%s: open()", path);
556			goto failure;
557		}
558	}
559	count = url->offset;
560
561	/* start the counter */
562	stat_start(&xs, path, us.size, count);
563
564	sigalrm = siginfo = sigint = 0;
565
566	/* suck in the data */
567	signal(SIGINFO, sig_handler);
568	while (!sigint) {
569		if (us.size != -1 && us.size - count < B_size)
570			size = us.size - count;
571		else
572			size = B_size;
573		if (siginfo) {
574			stat_end(&xs);
575			siginfo = 0;
576		}
577		if ((size = fread(buf, 1, size, f)) == 0) {
578			if (ferror(f) && errno == EINTR && !sigint)
579				clearerr(f);
580			else
581				break;
582		}
583		stat_update(&xs, count += size);
584		for (ptr = buf; size > 0; ptr += wr, size -= wr)
585			if ((wr = fwrite(ptr, 1, size, of)) < size) {
586				if (ferror(of) && errno == EINTR && !sigint)
587					clearerr(of);
588				else
589					break;
590			}
591		if (size != 0)
592			break;
593	}
594	if (!sigalrm)
595		sigalrm = ferror(f) && errno == ETIMEDOUT;
596	signal(SIGINFO, SIG_DFL);
597
598	stat_end(&xs);
599
600	/*
601	 * If the transfer timed out or was interrupted, we still want to
602	 * set the mtime in case the file is not removed (-r or -R) and
603	 * the user later restarts the transfer.
604	 */
605 signal:
606	/* set mtime of local file */
607	if (!n_flag && us.mtime && !o_stdout && of != NULL &&
608	    (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
609		struct timeval tv[2];
610
611		fflush(of);
612		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
613		tv[1].tv_sec = (long)us.mtime;
614		tv[0].tv_usec = tv[1].tv_usec = 0;
615		if (utimes(tmppath ? tmppath : path, tv))
616			warn("%s: utimes()", tmppath ? tmppath : path);
617	}
618
619	/* timed out or interrupted? */
620	if (sigalrm)
621		warnx("transfer timed out");
622	if (sigint) {
623		warnx("transfer interrupted");
624		goto failure;
625	}
626
627	/* timeout / interrupt before connection completley established? */
628	if (f == NULL)
629		goto failure;
630
631	if (!sigalrm) {
632		/* check the status of our files */
633		if (ferror(f))
634			warn("%s", URL);
635		if (ferror(of))
636			warn("%s", path);
637		if (ferror(f) || ferror(of))
638			goto failure;
639	}
640
641	/* did the transfer complete normally? */
642	if (us.size != -1 && count < us.size) {
643		warnx("%s appears to be truncated: %lld/%lld bytes",
644		    path, (long long)count, (long long)us.size);
645		goto failure_keep;
646	}
647
648	/*
649	 * If the transfer timed out and we didn't know how much to
650	 * expect, assume the worst (i.e. we didn't get all of it)
651	 */
652	if (sigalrm && us.size == -1) {
653		warnx("%s may be truncated", path);
654		goto failure_keep;
655	}
656
657 success:
658	r = 0;
659	if (tmppath != NULL && rename(tmppath, path) == -1) {
660		warn("%s: rename()", path);
661		goto failure_keep;
662	}
663	goto done;
664 failure:
665	if (of && of != stdout && !R_flag && !r_flag)
666		if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
667			unlink(tmppath ? tmppath : path);
668	if (R_flag && tmppath != NULL && sb.st_size == -1)
669		rename(tmppath, path); /* ignore errors here */
670 failure_keep:
671	r = -1;
672	goto done;
673 done:
674	if (f)
675		fclose(f);
676	if (of && of != stdout)
677		fclose(of);
678	if (url)
679		fetchFreeURL(url);
680	if (tmppath != NULL)
681		free(tmppath);
682	return r;
683}
684
685static void
686usage(void)
687{
688	fprintf(stderr, "%s\n%s\n%s\n",
689	    "usage: fetch [-146AFMPRUadlmnpqrsv] [-N netrc] [-o outputfile]",
690	    "             [-S bytes] [-B bytes] [-T seconds] [-w seconds]",
691	    "             [-h host -f file [-c dir] | URL ...]");
692}
693
694
695/*
696 * Entry point
697 */
698int
699main(int argc, char *argv[])
700{
701	struct stat sb;
702	struct sigaction sa;
703	const char *p, *s;
704	char *end, *q;
705	int c, e, r;
706
707	while ((c = getopt(argc, argv,
708	    "146AaB:bc:dFf:Hh:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
709		switch (c) {
710		case '1':
711			once_flag = 1;
712			break;
713		case '4':
714			family = PF_INET;
715			break;
716		case '6':
717			family = PF_INET6;
718			break;
719		case 'A':
720			A_flag = 1;
721			break;
722		case 'a':
723			a_flag = 1;
724			break;
725		case 'B':
726			B_size = (off_t)strtol(optarg, &end, 10);
727			if (*optarg == '\0' || *end != '\0')
728				errx(1, "invalid buffer size (%s)", optarg);
729			break;
730		case 'b':
731			warnx("warning: the -b option is deprecated");
732			b_flag = 1;
733			break;
734		case 'c':
735			c_dirname = optarg;
736			break;
737		case 'd':
738			d_flag = 1;
739			break;
740		case 'F':
741			F_flag = 1;
742			break;
743		case 'f':
744			f_filename = optarg;
745			break;
746		case 'H':
747			warnx("the -H option is now implicit, "
748			    "use -U to disable");
749			break;
750		case 'h':
751			h_hostname = optarg;
752			break;
753		case 'l':
754			l_flag = 1;
755			break;
756		case 'o':
757			o_flag = 1;
758			o_filename = optarg;
759			break;
760		case 'M':
761		case 'm':
762			if (r_flag)
763				errx(1, "the -m and -r flags "
764				    "are mutually exclusive");
765			m_flag = 1;
766			break;
767		case 'N':
768			N_filename = optarg;
769			break;
770		case 'n':
771			n_flag = 1;
772			break;
773		case 'P':
774		case 'p':
775			p_flag = 1;
776			break;
777		case 'q':
778			v_level = 0;
779			break;
780		case 'R':
781			R_flag = 1;
782			break;
783		case 'r':
784			if (m_flag)
785				errx(1, "the -m and -r flags "
786				    "are mutually exclusive");
787			r_flag = 1;
788			break;
789		case 'S':
790			S_size = (off_t)strtol(optarg, &end, 10);
791			if (*optarg == '\0' || *end != '\0')
792				errx(1, "invalid size (%s)", optarg);
793			break;
794		case 's':
795			s_flag = 1;
796			break;
797		case 'T':
798			T_secs = strtol(optarg, &end, 10);
799			if (*optarg == '\0' || *end != '\0')
800				errx(1, "invalid timeout (%s)", optarg);
801			break;
802		case 't':
803			t_flag = 1;
804			warnx("warning: the -t option is deprecated");
805			break;
806		case 'U':
807			U_flag = 1;
808			break;
809		case 'v':
810			v_level++;
811			break;
812		case 'w':
813			a_flag = 1;
814			w_secs = strtol(optarg, &end, 10);
815			if (*optarg == '\0' || *end != '\0')
816				errx(1, "invalid delay (%s)", optarg);
817			break;
818		default:
819			usage();
820			exit(EX_USAGE);
821		}
822
823	argc -= optind;
824	argv += optind;
825
826	if (h_hostname || f_filename || c_dirname) {
827		if (!h_hostname || !f_filename || argc) {
828			usage();
829			exit(EX_USAGE);
830		}
831		/* XXX this is a hack. */
832		if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
833			errx(1, "invalid hostname");
834		if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
835		    c_dirname ? c_dirname : "", f_filename) == -1)
836			errx(1, "%s", strerror(ENOMEM));
837		argc++;
838	}
839
840	if (!argc) {
841		usage();
842		exit(EX_USAGE);
843	}
844
845	/* allocate buffer */
846	if (B_size < MINBUFSIZE)
847		B_size = MINBUFSIZE;
848	if ((buf = malloc(B_size)) == NULL)
849		errx(1, "%s", strerror(ENOMEM));
850
851	/* timeouts */
852	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
853		ftp_timeout = strtol(s, &end, 10);
854		if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
855			warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
856			ftp_timeout = 0;
857		}
858	}
859	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
860		http_timeout = strtol(s, &end, 10);
861		if (*s == '\0' || *end != '\0' || http_timeout < 0) {
862			warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
863			http_timeout = 0;
864		}
865	}
866
867	/* signal handling */
868	sa.sa_flags = 0;
869	sa.sa_handler = sig_handler;
870	sigemptyset(&sa.sa_mask);
871	sigaction(SIGALRM, &sa, NULL);
872	sa.sa_flags = SA_RESETHAND;
873	sigaction(SIGINT, &sa, NULL);
874	fetchRestartCalls = 0;
875
876	/* output file */
877	if (o_flag) {
878		if (strcmp(o_filename, "-") == 0) {
879			o_stdout = 1;
880		} else if (stat(o_filename, &sb) == -1) {
881			if (errno == ENOENT) {
882				if (argc > 1)
883					errx(EX_USAGE, "%s is not a directory",
884					    o_filename);
885			} else {
886				err(EX_IOERR, "%s", o_filename);
887			}
888		} else {
889			if (sb.st_mode & S_IFDIR)
890				o_directory = 1;
891		}
892	}
893
894	/* check if output is to a tty (for progress report) */
895	v_tty = isatty(STDERR_FILENO);
896	if (v_tty)
897		pgrp = getpgrp();
898
899	r = 0;
900
901	/* authentication */
902	if (v_tty)
903		fetchAuthMethod = query_auth;
904	if (N_filename != NULL)
905		setenv("NETRC", N_filename, 1);
906
907	while (argc) {
908		if ((p = strrchr(*argv, '/')) == NULL)
909			p = *argv;
910		else
911			p++;
912
913		if (!*p)
914			p = "fetch.out";
915
916		fetchLastErrCode = 0;
917
918		if (o_flag) {
919			if (o_stdout) {
920				e = fetch(*argv, "-");
921			} else if (o_directory) {
922				asprintf(&q, "%s/%s", o_filename, p);
923				e = fetch(*argv, q);
924				free(q);
925			} else {
926				e = fetch(*argv, o_filename);
927			}
928		} else {
929			e = fetch(*argv, p);
930		}
931
932		if (sigint)
933			kill(getpid(), SIGINT);
934
935		if (e == 0 && once_flag)
936			exit(0);
937
938		if (e) {
939			r = 1;
940			if ((fetchLastErrCode
941			    && fetchLastErrCode != FETCH_UNAVAIL
942			    && fetchLastErrCode != FETCH_MOVED
943			    && fetchLastErrCode != FETCH_URL
944			    && fetchLastErrCode != FETCH_RESOLV
945			    && fetchLastErrCode != FETCH_UNKNOWN)) {
946				if (w_secs && v_level)
947					fprintf(stderr, "Waiting %ld seconds "
948					    "before retrying\n", w_secs);
949				if (w_secs)
950					sleep(w_secs);
951				if (a_flag)
952					continue;
953			}
954		}
955
956		argc--, argv++;
957	}
958
959	exit(r);
960}
961