xref: /freebsd/usr.bin/fetch/fetch.c (revision 41466b50c1d5bfd1cf6adaae547a579a75d7c04e)
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$
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 */
52 int	 A_flag;	/*    -A: do not follow 302 redirects */
53 int	 a_flag;	/*    -a: auto retry */
54 off_t	 B_size;	/*    -B: buffer size */
55 int	 b_flag;	/*!   -b: workaround TCP bug */
56 char    *c_dirname;	/*    -c: remote directory */
57 int	 d_flag;	/*    -d: direct connection */
58 int	 F_flag;	/*    -F: restart without checking mtime  */
59 char	*f_filename;	/*    -f: file to fetch */
60 char	*h_hostname;	/*    -h: host to fetch from */
61 int	 l_flag;	/*    -l: link rather than copy file: URLs */
62 int	 m_flag;	/* -[Mm]: mirror mode */
63 int	 n_flag;	/*    -n: do not preserve modification time */
64 int	 o_flag;	/*    -o: specify output file */
65 int	 o_directory;	/*        output file is a directory */
66 char	*o_filename;	/*        name of output file */
67 int	 o_stdout;	/*        output file is stdout */
68 int	 once_flag;	/*    -1: stop at first successful file */
69 int	 p_flag;	/* -[Pp]: use passive FTP */
70 int	 R_flag;	/*    -R: don't delete partially transferred files */
71 int	 r_flag;	/*    -r: restart previously interrupted transfer */
72 off_t	 S_size;        /*    -S: require size to match */
73 int	 s_flag;        /*    -s: show size, don't fetch */
74 u_int	 T_secs = 120;	/*    -T: transfer timeout in seconds */
75 int	 t_flag;	/*!   -t: workaround TCP bug */
76 int	 U_flag;	/*    -U: do not use high ports */
77 int	 v_level = 1;	/*    -v: verbosity level */
78 int	 v_tty;		/*        stdout is a tty */
79 pid_t	 pgrp;		/*        our process group */
80 u_int	 w_secs;	/*    -w: retry delay */
81 int	 family = PF_UNSPEC;	/* -[46]: address family to use */
82 
83 int	 sigalrm;	/* SIGALRM received */
84 int	 siginfo;	/* SIGINFO received */
85 int	 sigint;	/* SIGINT received */
86 
87 u_int	 ftp_timeout;	/* default timeout for FTP transfers */
88 u_int	 http_timeout;	/* default timeout for HTTP transfers */
89 u_char	*buf;		/* transfer buffer */
90 
91 
92 /*
93  * Signal handler
94  */
95 static void
96 sig_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 
111 struct 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  */
124 static void
125 stat_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  */
154 static void
155 stat_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  */
170 static void
171 stat_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  */
180 static void
181 stat_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  */
209 static int
210 query_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, URL->doc);
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  */
251 static int
252 fetch(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 			warnx("tmppath: %s", tmppath);
485 			of = fopen(tmppath, "w");
486 		} else {
487 			of = fopen(path, "w");
488 		}
489 
490 		if (of == NULL) {
491 			warn("%s: open()", path);
492 			goto failure;
493 		}
494 	}
495 	count = url->offset;
496 
497 	/* start the counter */
498 	stat_start(&xs, path, us.size, count);
499 
500 	sigalrm = siginfo = sigint = 0;
501 
502 	/* suck in the data */
503 	signal(SIGINFO, sig_handler);
504 	while (!sigint && !sigalrm) {
505 		if (us.size != -1 && us.size - count < B_size)
506 			size = us.size - count;
507 		else
508 			size = B_size;
509 		if (timeout)
510 			alarm(timeout);
511 		if (siginfo) {
512 			stat_end(&xs);
513 			siginfo = 0;
514 		}
515 		if ((size = fread(buf, 1, size, f)) == 0) {
516 			if (ferror(f) && errno == EINTR && !sigalrm && !sigint)
517 				clearerr(f);
518 			else
519 				break;
520 		}
521 		if (timeout)
522 			alarm(0);
523 		stat_update(&xs, count += size);
524 		for (ptr = buf; size > 0; ptr += wr, size -= wr)
525 			if ((wr = fwrite(ptr, 1, size, of)) < size) {
526 				if (ferror(of) && errno == EINTR &&
527 				    !sigalrm && !sigint)
528 					clearerr(of);
529 				else
530 					break;
531 			}
532 		if (size != 0)
533 			break;
534 	}
535 	signal(SIGINFO, SIG_DFL);
536 
537 	if (timeout)
538 		alarm(0);
539 
540 	stat_end(&xs);
541 
542 	/* set mtime of local file */
543 	if (!n_flag && us.mtime && !o_stdout
544 	    && (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
545 		struct timeval tv[2];
546 
547 		fflush(of);
548 		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
549 		tv[1].tv_sec = (long)us.mtime;
550 		tv[0].tv_usec = tv[1].tv_usec = 0;
551 		if (utimes(path, tv))
552 			warn("%s: utimes()", path);
553 	}
554 
555 	/* timed out or interrupted? */
556  signal:
557 	if (sigalrm)
558 		warnx("transfer timed out");
559 	if (sigint) {
560 		warnx("transfer interrupted");
561 		goto failure;
562 	}
563 
564 	if (!sigalrm) {
565 		/* check the status of our files */
566 		if (ferror(f))
567 			warn("%s", URL);
568 		if (ferror(of))
569 			warn("%s", path);
570 		if (ferror(f) || ferror(of))
571 			goto failure;
572 	}
573 
574 	/* did the transfer complete normally? */
575 	if (us.size != -1 && count < us.size) {
576 		warnx("%s appears to be truncated: %lld/%lld bytes",
577 		    path, (long long)count, (long long)us.size);
578 		goto failure_keep;
579 	}
580 
581 	/*
582 	 * If the transfer timed out and we didn't know how much to
583 	 * expect, assume the worst (i.e. we didn't get all of it)
584 	 */
585 	if (sigalrm && us.size == -1) {
586 		warnx("%s may be truncated", path);
587 		goto failure_keep;
588 	}
589 
590  success:
591 	r = 0;
592 	if (tmppath != NULL && rename(tmppath, path) == -1) {
593 		warn("%s: rename()", path);
594 		goto failure_keep;
595 	}
596 	goto done;
597  failure:
598 	if (of && of != stdout && !R_flag && !r_flag)
599 		if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
600 			unlink(tmppath ? tmppath : path);
601 	if (R_flag && tmppath != NULL && sb.st_size == -1)
602 		rename(tmppath, path); /* ignore errors here */
603  failure_keep:
604 	r = -1;
605 	goto done;
606  done:
607 	if (f)
608 		fclose(f);
609 	if (of && of != stdout)
610 		fclose(of);
611 	if (url)
612 		fetchFreeURL(url);
613 	if (tmppath != NULL)
614 		free(tmppath);
615 	return r;
616 }
617 
618 static void
619 usage(void)
620 {
621 	fprintf(stderr, "%s\n%s\n%s\n",
622 	    "Usage: fetch [-146AFMPRUadlmnpqrsv] [-o outputfile] [-S bytes]",
623 	    "             [-B bytes] [-T seconds] [-w seconds]",
624 	    "             [-h host -f file [-c dir] | URL ...]");
625 }
626 
627 
628 #define PARSENUM(NAME, TYPE)				\
629 static int						\
630 NAME(const char *s, TYPE *v)				\
631 {							\
632         *v = 0;						\
633 	for (*v = 0; *s; s++)				\
634 		if (isdigit(*s))			\
635 			*v = *v * 10 + *s - '0';	\
636 		else					\
637 			return -1;			\
638 	return 0;					\
639 }
640 
641 PARSENUM(parseint, u_int);
642 PARSENUM(parseoff, off_t);
643 
644 /*
645  * Entry point
646  */
647 int
648 main(int argc, char *argv[])
649 {
650 	struct stat sb;
651 	struct sigaction sa;
652 	const char *p, *s;
653 	char *q;
654 	int c, e, r;
655 
656 	while ((c = getopt(argc, argv,
657 	    "146AaB:bc:dFf:Hh:lMmnPpo:qRrS:sT:tUvw:")) != EOF)
658 		switch (c) {
659 		case '1':
660 			once_flag = 1;
661 			break;
662 		case '4':
663 			family = PF_INET;
664 			break;
665 		case '6':
666 			family = PF_INET6;
667 			break;
668 		case 'A':
669 			A_flag = 1;
670 			break;
671 		case 'a':
672 			a_flag = 1;
673 			break;
674 		case 'B':
675 			if (parseoff(optarg, &B_size) == -1)
676 				errx(1, "invalid buffer size (%s)", optarg);
677 			break;
678 		case 'b':
679 			warnx("warning: the -b option is deprecated");
680 			b_flag = 1;
681 			break;
682 		case 'c':
683 			c_dirname = optarg;
684 			break;
685 		case 'd':
686 			d_flag = 1;
687 			break;
688 		case 'F':
689 			F_flag = 1;
690 			break;
691 		case 'f':
692 			f_filename = optarg;
693 			break;
694 		case 'H':
695 			warnx("The -H option is now implicit, "
696 			    "use -U to disable");
697 			break;
698 		case 'h':
699 			h_hostname = optarg;
700 			break;
701 		case 'l':
702 			l_flag = 1;
703 			break;
704 		case 'o':
705 			o_flag = 1;
706 			o_filename = optarg;
707 			break;
708 		case 'M':
709 		case 'm':
710 			if (r_flag)
711 				errx(1, "the -m and -r flags "
712 				    "are mutually exclusive");
713 			m_flag = 1;
714 			break;
715 		case 'n':
716 			n_flag = 1;
717 			break;
718 		case 'P':
719 		case 'p':
720 			p_flag = 1;
721 			break;
722 		case 'q':
723 			v_level = 0;
724 			break;
725 		case 'R':
726 			R_flag = 1;
727 			break;
728 		case 'r':
729 			if (m_flag)
730 				errx(1, "the -m and -r flags "
731 				    "are mutually exclusive");
732 			r_flag = 1;
733 			break;
734 		case 'S':
735 			if (parseoff(optarg, &S_size) == -1)
736 				errx(1, "invalid size (%s)", optarg);
737 			break;
738 		case 's':
739 			s_flag = 1;
740 			break;
741 		case 'T':
742 			if (parseint(optarg, &T_secs) == -1)
743 				errx(1, "invalid timeout (%s)", optarg);
744 			break;
745 		case 't':
746 			t_flag = 1;
747 			warnx("warning: the -t option is deprecated");
748 			break;
749 		case 'U':
750 			U_flag = 1;
751 			break;
752 		case 'v':
753 			v_level++;
754 			break;
755 		case 'w':
756 			a_flag = 1;
757 			if (parseint(optarg, &w_secs) == -1)
758 				errx(1, "invalid delay (%s)", optarg);
759 			break;
760 		default:
761 			usage();
762 			exit(EX_USAGE);
763 		}
764 
765 	argc -= optind;
766 	argv += optind;
767 
768 	if (h_hostname || f_filename || c_dirname) {
769 		if (!h_hostname || !f_filename || argc) {
770 			usage();
771 			exit(EX_USAGE);
772 		}
773 		/* XXX this is a hack. */
774 		if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
775 			errx(1, "invalid hostname");
776 		if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
777 		    c_dirname ? c_dirname : "", f_filename) == -1)
778 			errx(1, "%s", strerror(ENOMEM));
779 		argc++;
780 	}
781 
782 	if (!argc) {
783 		usage();
784 		exit(EX_USAGE);
785 	}
786 
787 	/* allocate buffer */
788 	if (B_size < MINBUFSIZE)
789 		B_size = MINBUFSIZE;
790 	if ((buf = malloc(B_size)) == NULL)
791 		errx(1, "%s", strerror(ENOMEM));
792 
793 	/* timeouts */
794 	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
795 		if (parseint(s, &ftp_timeout) == -1) {
796 			warnx("FTP_TIMEOUT (%s) is not a positive integer",
797 			    optarg);
798 			ftp_timeout = 0;
799 		}
800 	}
801 	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
802 		if (parseint(s, &http_timeout) == -1) {
803 			warnx("HTTP_TIMEOUT (%s) is not a positive integer",
804 			    optarg);
805 			http_timeout = 0;
806 		}
807 	}
808 
809 	/* signal handling */
810 	sa.sa_flags = 0;
811 	sa.sa_handler = sig_handler;
812 	sigemptyset(&sa.sa_mask);
813 	sigaction(SIGALRM, &sa, NULL);
814 	sa.sa_flags = SA_RESETHAND;
815 	sigaction(SIGINT, &sa, NULL);
816 	fetchRestartCalls = 0;
817 
818 	/* output file */
819 	if (o_flag) {
820 		if (strcmp(o_filename, "-") == 0) {
821 			o_stdout = 1;
822 		} else if (stat(o_filename, &sb) == -1) {
823 			if (errno == ENOENT) {
824 				if (argc > 1)
825 					errx(EX_USAGE, "%s is not a directory",
826 					    o_filename);
827 			} else {
828 				err(EX_IOERR, "%s", o_filename);
829 			}
830 		} else {
831 			if (sb.st_mode & S_IFDIR)
832 				o_directory = 1;
833 		}
834 	}
835 
836 	/* check if output is to a tty (for progress report) */
837 	v_tty = isatty(STDERR_FILENO);
838 	if (v_tty)
839 		pgrp = getpgrp();
840 
841 	r = 0;
842 
843 	/* authentication */
844 	if (v_tty)
845 		fetchAuthMethod = query_auth;
846 
847 	while (argc) {
848 		if ((p = strrchr(*argv, '/')) == NULL)
849 			p = *argv;
850 		else
851 			p++;
852 
853 		if (!*p)
854 			p = "fetch.out";
855 
856 		fetchLastErrCode = 0;
857 
858 		if (o_flag) {
859 			if (o_stdout) {
860 				e = fetch(*argv, "-");
861 			} else if (o_directory) {
862 				asprintf(&q, "%s/%s", o_filename, p);
863 				e = fetch(*argv, q);
864 				free(q);
865 			} else {
866 				e = fetch(*argv, o_filename);
867 			}
868 		} else {
869 			e = fetch(*argv, p);
870 		}
871 
872 		if (sigint)
873 			kill(getpid(), SIGINT);
874 
875 		if (e == 0 && once_flag)
876 			exit(0);
877 
878 		if (e) {
879 			r = 1;
880 			if ((fetchLastErrCode
881 			    && fetchLastErrCode != FETCH_UNAVAIL
882 			    && fetchLastErrCode != FETCH_MOVED
883 			    && fetchLastErrCode != FETCH_URL
884 			    && fetchLastErrCode != FETCH_RESOLV
885 			    && fetchLastErrCode != FETCH_UNKNOWN)) {
886 				if (w_secs && v_level)
887 					fprintf(stderr, "Waiting %d seconds "
888 					    "before retrying\n", w_secs);
889 				if (w_secs)
890 					sleep(w_secs);
891 				if (a_flag)
892 					continue;
893 			}
894 		}
895 
896 		argc--, argv++;
897 	}
898 
899 	exit(r);
900 }
901