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