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