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