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