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