xref: /freebsd/usr.bin/fetch/fetch.c (revision e0c4386e7e71d93b0edc0c8fa156263fc4a8b0b6)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2000-2014 Dag-Erling Smørgrav
5  * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer
13  *    in this position and unchanged.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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 <getopt.h>
41 #include <signal.h>
42 #include <stdint.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <termios.h>
47 #include <unistd.h>
48 
49 #include <fetch.h>
50 
51 #define MINBUFSIZE	16384
52 #define TIMEOUT		120
53 
54 /* Option flags */
55 static int	 A_flag;	/*    -A: do not follow 302 redirects */
56 static int	 a_flag;	/*    -a: auto retry */
57 static off_t	 B_size;	/*    -B: buffer size */
58 static int	 b_flag;	/*!   -b: workaround TCP bug */
59 static char    *c_dirname;	/*    -c: remote directory */
60 static int	 d_flag;	/*    -d: direct connection */
61 static int	 F_flag;	/*    -F: restart without checking mtime  */
62 static char	*f_filename;	/*    -f: file to fetch */
63 static char	*h_hostname;	/*    -h: host to fetch from */
64 static int	 i_flag;	/*    -i: specify file for mtime comparison */
65 static char	*i_filename;	/*        name of input file */
66 static int	 l_flag;	/*    -l: link rather than copy file: URLs */
67 static int	 m_flag;	/* -[Mm]: mirror mode */
68 static char	*N_filename;	/*    -N: netrc file name */
69 static int	 n_flag;	/*    -n: do not preserve modification time */
70 static int	 o_flag;	/*    -o: specify output file */
71 static int	 o_directory;	/*        output file is a directory */
72 static char	*o_filename;	/*        name of output file */
73 static int	 o_stdout;	/*        output file is stdout */
74 static int	 once_flag;	/*    -1: stop at first successful file */
75 static int	 p_flag;	/* -[Pp]: use passive FTP */
76 static int	 R_flag;	/*    -R: don't delete partial files */
77 static int	 r_flag;	/*    -r: restart previous transfer */
78 static off_t	 S_size;        /*    -S: require size to match */
79 static int	 s_flag;        /*    -s: show size, don't fetch */
80 static long	 T_secs;	/*    -T: transfer timeout in seconds */
81 static int	 t_flag;	/*!   -t: workaround TCP bug */
82 static int	 U_flag;	/*    -U: do not use high ports */
83 static int	 v_level = 1;	/*    -v: verbosity level */
84 static int	 v_tty;		/*        stdout is a tty */
85 static int	 v_progress;	/*        whether to display progress */
86 static pid_t	 pgrp;		/*        our process group */
87 static long	 w_secs;	/*    -w: retry delay */
88 static int	 family = PF_UNSPEC;	/* -[46]: address family to use */
89 
90 static int	 sigalrm;	/* SIGALRM received */
91 static int	 siginfo;	/* SIGINFO received */
92 static int	 sigint;	/* SIGINT received */
93 
94 static long	 ftp_timeout = TIMEOUT;	/* default timeout for FTP transfers */
95 static long	 http_timeout = TIMEOUT;/* default timeout for HTTP transfers */
96 static char	*buf;		/* transfer buffer */
97 
98 enum options
99 {
100 	OPTION_BIND_ADDRESS,
101 	OPTION_NO_FTP_PASSIVE_MODE,
102 	OPTION_HTTP_REFERER,
103 	OPTION_HTTP_USER_AGENT,
104 	OPTION_NO_PROXY,
105 	OPTION_SSL_CA_CERT_FILE,
106 	OPTION_SSL_CA_CERT_PATH,
107 	OPTION_SSL_CLIENT_CERT_FILE,
108 	OPTION_SSL_CLIENT_KEY_FILE,
109 	OPTION_SSL_CRL_FILE,
110 	OPTION_SSL_NO_SSL3,
111 	OPTION_SSL_NO_TLS1,
112 	OPTION_SSL_NO_VERIFY_HOSTNAME,
113 	OPTION_SSL_NO_VERIFY_PEER
114 };
115 
116 
117 static struct option longopts[] =
118 {
119 	/* mapping to single character argument */
120 	{ "one-file", no_argument, NULL, '1' },
121 	{ "ipv4-only", no_argument, NULL, '4' },
122 	{ "ipv6-only", no_argument, NULL, '6' },
123 	{ "no-redirect", no_argument, NULL, 'A' },
124 	{ "retry", no_argument, NULL, 'a' },
125 	{ "buffer-size", required_argument, NULL, 'B' },
126 	/* -c not mapped, since it's deprecated */
127 	{ "direct", no_argument, NULL, 'd' },
128 	{ "force-restart", no_argument, NULL, 'F' },
129 	/* -f not mapped, since it's deprecated */
130 	/* -h not mapped, since it's deprecated */
131 	{ "if-modified-since", required_argument, NULL, 'i' },
132 	{ "symlink", no_argument, NULL, 'l' },
133 	/* -M not mapped since it's the same as -m */
134 	{ "mirror", no_argument, NULL, 'm' },
135 	{ "netrc", required_argument, NULL, 'N' },
136 	{ "no-mtime", no_argument, NULL, 'n' },
137 	{ "output", required_argument, NULL, 'o' },
138 	/* -P not mapped since it's the same as -p */
139 	{ "passive", no_argument, NULL, 'p' },
140 	{ "quiet", no_argument, NULL, 'q' },
141 	{ "keep-output", no_argument, NULL, 'R' },
142 	{ "restart", no_argument, NULL, 'r' },
143 	{ "require-size", required_argument, NULL, 'S' },
144 	{ "print-size", no_argument, NULL, 's' },
145 	{ "timeout", required_argument, NULL, 'T' },
146 	{ "passive-portrange-default", no_argument, NULL, 'T' },
147 	{ "verbose", no_argument, NULL, 'v' },
148 	{ "retry-delay", required_argument, NULL, 'w' },
149 
150 	/* options without a single character equivalent */
151 	{ "bind-address", required_argument, NULL, OPTION_BIND_ADDRESS },
152 	{ "no-passive", no_argument, NULL, OPTION_NO_FTP_PASSIVE_MODE },
153 	{ "referer", required_argument, NULL, OPTION_HTTP_REFERER },
154 	{ "user-agent", required_argument, NULL, OPTION_HTTP_USER_AGENT },
155 	{ "no-proxy", required_argument, NULL, OPTION_NO_PROXY },
156 	{ "ca-cert", required_argument, NULL, OPTION_SSL_CA_CERT_FILE },
157 	{ "ca-path", required_argument, NULL, OPTION_SSL_CA_CERT_PATH },
158 	{ "cert", required_argument, NULL, OPTION_SSL_CLIENT_CERT_FILE },
159 	{ "key", required_argument, NULL, OPTION_SSL_CLIENT_KEY_FILE },
160 	{ "crl", required_argument, NULL, OPTION_SSL_CRL_FILE },
161 	{ "no-sslv3", no_argument, NULL, OPTION_SSL_NO_SSL3 },
162 	{ "no-tlsv1", no_argument, NULL, OPTION_SSL_NO_TLS1 },
163 	{ "no-verify-hostname", no_argument, NULL, OPTION_SSL_NO_VERIFY_HOSTNAME },
164 	{ "no-verify-peer", no_argument, NULL, OPTION_SSL_NO_VERIFY_PEER },
165 
166 	{ NULL, 0, NULL, 0 }
167 };
168 
169 /*
170  * Signal handler
171  */
172 static void
173 sig_handler(int sig)
174 {
175 	switch (sig) {
176 	case SIGALRM:
177 		sigalrm = 1;
178 		break;
179 	case SIGINFO:
180 		siginfo = 1;
181 		break;
182 	case SIGINT:
183 		sigint = 1;
184 		break;
185 	}
186 }
187 
188 struct xferstat {
189 	char		 name[64];
190 	struct timeval	 start;		/* start of transfer */
191 	struct timeval	 last;		/* time of last update */
192 	struct timeval	 last2;		/* time of previous last update */
193 	off_t		 size;		/* size of file per HTTP hdr */
194 	off_t		 offset;	/* starting offset in file */
195 	off_t		 rcvd;		/* bytes already received */
196 	off_t		 lastrcvd;	/* bytes received since last update */
197 };
198 
199 /*
200  * Format a number of seconds as either XXdYYh, XXhYYm, XXmYYs, or XXs
201  * depending on its magnitude
202  */
203 static void
204 stat_seconds(char *str, size_t strsz, long seconds)
205 {
206 
207 	if (seconds > 86400)
208 		snprintf(str, strsz, "%02ldd%02ldh",
209 		    seconds / 86400, (seconds % 86400) / 3600);
210 	else if (seconds > 3600)
211 		snprintf(str, strsz, "%02ldh%02ldm",
212 		    seconds / 3600, (seconds % 3600) / 60);
213 	else if (seconds > 60)
214 		snprintf(str, strsz, "%02ldm%02lds",
215 		    seconds / 60, seconds % 60);
216 	else
217 		snprintf(str, strsz, "   %02lds",
218 		    seconds);
219 }
220 
221 /*
222  * Compute and display ETA
223  */
224 static void
225 stat_eta(char *str, size_t strsz, const struct xferstat *xs)
226 {
227 	long elapsed, eta;
228 	off_t received, expected;
229 
230 	elapsed = xs->last.tv_sec - xs->start.tv_sec;
231 	received = xs->rcvd - xs->offset;
232 	expected = xs->size - xs->rcvd;
233 	eta = (long)((double)elapsed * expected / received);
234 	if (eta > 0)
235 		stat_seconds(str, strsz, eta);
236 	else
237 		stat_seconds(str, strsz, elapsed);
238 }
239 
240 /*
241  * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
242  */
243 static const char *prefixes = " kMGTP";
244 static void
245 stat_bytes(char *str, size_t strsz, off_t bytes)
246 {
247 	const char *prefix = prefixes;
248 
249 	while (bytes > 9999 && prefix[1] != '\0') {
250 		bytes /= 1024;
251 		prefix++;
252 	}
253 	snprintf(str, strsz, "%4ju %cB", (uintmax_t)bytes, *prefix);
254 }
255 
256 /*
257  * Compute and display transfer rate
258  */
259 static void
260 stat_bps(char *str, size_t strsz, struct xferstat *xs)
261 {
262 	char bytes[16];
263 	double delta, bps;
264 
265 	delta = ((double)xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
266 	    - ((double)xs->last2.tv_sec + (xs->last2.tv_usec / 1.e6));
267 
268 	if (delta == 0.0) {
269 		snprintf(str, strsz, "?? Bps");
270 	} else {
271 		bps = (xs->rcvd - xs->lastrcvd) / delta;
272 		stat_bytes(bytes, sizeof bytes, (off_t)bps);
273 		snprintf(str, strsz, "%sps", bytes);
274 	}
275 }
276 
277 /*
278  * Update the stats display
279  */
280 static void
281 stat_display(struct xferstat *xs, int force)
282 {
283 	char bytes[16], bps[16], eta[16];
284 	struct timeval now;
285 	int ctty_pgrp;
286 
287 	/* check if we're the foreground process */
288 	if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) != 0 ||
289 	    (pid_t)ctty_pgrp != pgrp)
290 		return;
291 
292 	gettimeofday(&now, NULL);
293 	if (!force && now.tv_sec <= xs->last.tv_sec)
294 		return;
295 	xs->last2 = xs->last;
296 	xs->last = now;
297 
298 	fprintf(stderr, "\r%-46.46s", xs->name);
299 	if (xs->rcvd >= xs->size) {
300 		stat_bytes(bytes, sizeof bytes, xs->rcvd);
301 		setproctitle("%s [%s]", xs->name, bytes);
302 		fprintf(stderr, "        %s", bytes);
303 	} else {
304 		stat_bytes(bytes, sizeof bytes, xs->size);
305 		setproctitle("%s [%d%% of %s]", xs->name,
306 		    (int)((100.0 * xs->rcvd) / xs->size),
307 		    bytes);
308 		fprintf(stderr, "%3d%% of %s",
309 		    (int)((100.0 * xs->rcvd) / xs->size),
310 		    bytes);
311 	}
312 	if (force == 2) {
313 		xs->lastrcvd = xs->offset;
314 		xs->last2 = xs->start;
315 	}
316 	stat_bps(bps, sizeof bps, xs);
317 	fprintf(stderr, " %s", bps);
318 	if ((xs->size > 0 && xs->rcvd > 0 &&
319 	     xs->last.tv_sec >= xs->start.tv_sec + 3) ||
320 	    force == 2) {
321 		stat_eta(eta, sizeof eta, xs);
322 		fprintf(stderr, " %s", eta);
323 	}
324 	xs->lastrcvd = xs->rcvd;
325 }
326 
327 /*
328  * Initialize the transfer statistics
329  */
330 static void
331 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
332 {
333 
334 	memset(xs, 0, sizeof *xs);
335 	snprintf(xs->name, sizeof xs->name, "%s", name);
336 	gettimeofday(&xs->start, NULL);
337 	xs->last2 = xs->last = xs->start;
338 	xs->size = size;
339 	xs->offset = offset;
340 	xs->rcvd = offset;
341 	xs->lastrcvd = offset;
342 	if (v_progress)
343 		stat_display(xs, 1);
344 	else if (v_level > 0)
345 		fprintf(stderr, "%-46s", xs->name);
346 }
347 
348 /*
349  * Update the transfer statistics
350  */
351 static void
352 stat_update(struct xferstat *xs, off_t rcvd)
353 {
354 
355 	xs->rcvd = rcvd;
356 	if (v_progress)
357 		stat_display(xs, 0);
358 }
359 
360 /*
361  * Finalize the transfer statistics
362  */
363 static void
364 stat_end(struct xferstat *xs)
365 {
366 	char bytes[16], bps[16], eta[16];
367 
368 	gettimeofday(&xs->last, NULL);
369 	if (v_progress) {
370 		stat_display(xs, 2);
371 		putc('\n', stderr);
372 	} else if (v_level > 0) {
373 		stat_bytes(bytes, sizeof bytes, xs->rcvd);
374 		stat_bps(bps, sizeof bps, xs);
375 		stat_eta(eta, sizeof eta, xs);
376 		fprintf(stderr, "        %s %s %s\n", bytes, bps, eta);
377 	}
378 }
379 
380 /*
381  * Ask the user for authentication details
382  */
383 static int
384 query_auth(struct url *URL)
385 {
386 	struct termios tios;
387 	tcflag_t saved_flags;
388 	int i, nopwd;
389 
390 	fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
391 	    URL->scheme, URL->host, URL->port);
392 
393 	fprintf(stderr, "Login: ");
394 	if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
395 		return (-1);
396 	for (i = strlen(URL->user); i >= 0; --i)
397 		if (URL->user[i] == '\r' || URL->user[i] == '\n')
398 			URL->user[i] = '\0';
399 
400 	fprintf(stderr, "Password: ");
401 	if (tcgetattr(STDIN_FILENO, &tios) == 0) {
402 		saved_flags = tios.c_lflag;
403 		tios.c_lflag &= ~ECHO;
404 		tios.c_lflag |= ECHONL|ICANON;
405 		tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
406 		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
407 		tios.c_lflag = saved_flags;
408 		tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
409 	} else {
410 		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
411 	}
412 	if (nopwd)
413 		return (-1);
414 	for (i = strlen(URL->pwd); i >= 0; --i)
415 		if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
416 			URL->pwd[i] = '\0';
417 
418 	return (0);
419 }
420 
421 /*
422  * Fetch a file
423  */
424 static int
425 fetch(char *URL, const char *path, int *is_http)
426 {
427 	struct url *url;
428 	struct url_stat us;
429 	struct stat sb, nsb;
430 	struct xferstat xs;
431 	FILE *f, *of;
432 	size_t size, readcnt, wr;
433 	off_t count, size_prev;
434 	char flags[8];
435 	const char *slash;
436 	char *tmppath;
437 	int r, tries;
438 	unsigned timeout;
439 	char *ptr;
440 
441 	f = of = NULL;
442 	tmppath = NULL;
443 
444 	timeout = 0;
445 	*flags = 0;
446 	count = 0;
447 
448 	/* set verbosity level */
449 	if (v_level > 1)
450 		strcat(flags, "v");
451 	if (v_level > 2)
452 		fetchDebug = 1;
453 
454 	/* parse URL */
455 	url = NULL;
456 	if (*URL == '\0') {
457 		warnx("empty URL");
458 		goto failure;
459 	}
460 	if ((url = fetchParseURL(URL)) == NULL) {
461 		warnx("%s: parse error", URL);
462 		goto failure;
463 	}
464 
465 	/* if no scheme was specified, take a guess */
466 	if (!*url->scheme) {
467 		if (!*url->host)
468 			strcpy(url->scheme, SCHEME_FILE);
469 		else if (strncasecmp(url->host, "ftp.", 4) == 0)
470 			strcpy(url->scheme, SCHEME_FTP);
471 		else if (strncasecmp(url->host, "www.", 4) == 0)
472 			strcpy(url->scheme, SCHEME_HTTP);
473 	}
474 
475 	/* for both of http and https */
476 	*is_http = strncmp(url->scheme, "http", 4) == 0;
477 
478 	/* common flags */
479 	switch (family) {
480 	case PF_INET:
481 		strcat(flags, "4");
482 		break;
483 	case PF_INET6:
484 		strcat(flags, "6");
485 		break;
486 	}
487 
488 	/* FTP specific flags */
489 	if (strcmp(url->scheme, SCHEME_FTP) == 0) {
490 		if (p_flag)
491 			strcat(flags, "p");
492 		if (d_flag)
493 			strcat(flags, "d");
494 		if (U_flag)
495 			strcat(flags, "l");
496 		timeout = T_secs ? T_secs : ftp_timeout;
497 	}
498 
499 	/* HTTP specific flags */
500 	if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
501 	    strcmp(url->scheme, SCHEME_HTTPS) == 0) {
502 		if (d_flag)
503 			strcat(flags, "d");
504 		if (A_flag)
505 			strcat(flags, "A");
506 		timeout = T_secs ? T_secs : http_timeout;
507 		if (i_flag) {
508 			if (stat(i_filename, &sb)) {
509 				warn("%s: stat()", i_filename);
510 				goto failure;
511 			}
512 			url->ims_time = sb.st_mtime;
513 			strcat(flags, "i");
514 		}
515 	}
516 
517 	/* set the protocol timeout. */
518 	fetchTimeout = timeout;
519 
520 	/* just print size */
521 	if (s_flag) {
522 		if (timeout)
523 			alarm(timeout);
524 		r = fetchStat(url, &us, flags);
525 		if (timeout)
526 			alarm(0);
527 		if (sigalrm || sigint)
528 			goto signal;
529 		if (r == -1) {
530 			warnx("%s", fetchLastErrString);
531 			goto failure;
532 		}
533 		if (us.size == -1)
534 			printf("Unknown\n");
535 		else
536 			printf("%jd\n", (intmax_t)us.size);
537 		goto success;
538 	}
539 
540 	tries = 1;
541 again:
542 	r = 0;
543 	/*
544 	 * If the -r flag was specified, we have to compare the local
545 	 * and remote files, so we should really do a fetchStat()
546 	 * first, but I know of at least one HTTP server that only
547 	 * sends the content size in response to GET requests, and
548 	 * leaves it out of replies to HEAD requests.  Also, in the
549 	 * (frequent) case that the local and remote files match but
550 	 * the local file is truncated, we have sufficient information
551 	 * before the compare to issue a correct request.  Therefore,
552 	 * we always issue a GET request as if we were sure the local
553 	 * file was a truncated copy of the remote file; we can drop
554 	 * the connection later if we change our minds.
555 	 */
556 	sb.st_size = -1;
557 	if (!o_stdout) {
558 		r = stat(path, &sb);
559 		if (r == 0 && (r_flag || tries > 1) && S_ISREG(sb.st_mode)) {
560 			url->offset = sb.st_size;
561 		} else if (r == -1 || !S_ISREG(sb.st_mode)) {
562 			/*
563 			 * Whatever value sb.st_size has now is either
564 			 * wrong (if stat(2) failed) or irrelevant (if the
565 			 * path does not refer to a regular file)
566 			 */
567 			sb.st_size = -1;
568 		}
569 		if (r == -1 && errno != ENOENT) {
570 			warnx("%s: stat()", path);
571 			goto failure;
572 		}
573 	}
574 	size_prev = sb.st_size;
575 
576 	/* start the transfer */
577 	if (timeout)
578 		alarm(timeout);
579 	f = fetchXGet(url, &us, flags);
580 	if (timeout)
581 		alarm(0);
582 	if (sigalrm || sigint)
583 		goto signal;
584 	if (f == NULL) {
585 		warnx("%s: %s", URL, fetchLastErrString);
586 		if (i_flag && (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
587 		    strcmp(url->scheme, SCHEME_HTTPS) == 0) &&
588 		    fetchLastErrCode == FETCH_OK &&
589 		    strcmp(fetchLastErrString, "Not Modified") == 0) {
590 			/* HTTP Not Modified Response, return OK. */
591 			r = 0;
592 			goto done;
593 		} else
594 			goto failure;
595 	}
596 	if (sigint)
597 		goto signal;
598 
599 	/* check that size is as expected */
600 	if (S_size) {
601 		if (us.size == -1) {
602 			warnx("%s: size unknown", URL);
603 		} else if (us.size != S_size) {
604 			warnx("%s: size mismatch: expected %jd, actual %jd",
605 			    URL, (intmax_t)S_size, (intmax_t)us.size);
606 			goto failure;
607 		}
608 	}
609 
610 	/* symlink instead of copy */
611 	if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
612 		if (symlink(url->doc, path) == -1) {
613 			warn("%s: symlink()", path);
614 			goto failure;
615 		}
616 		goto success;
617 	}
618 
619 	if (us.size == -1 && !o_stdout && v_level > 0)
620 		warnx("%s: size of remote file is not known", URL);
621 	if (v_level > 1) {
622 		if (sb.st_size != -1)
623 			fprintf(stderr, "local size / mtime: %jd / %ld\n",
624 			    (intmax_t)sb.st_size, (long)sb.st_mtime);
625 		if (us.size != -1)
626 			fprintf(stderr, "remote size / mtime: %jd / %ld\n",
627 			    (intmax_t)us.size, (long)us.mtime);
628 	}
629 
630 	/* open output file */
631 	if (o_stdout) {
632 		/* output to stdout */
633 		of = stdout;
634 	} else if (r_flag && sb.st_size != -1) {
635 		/* resume mode, local file exists */
636 		if (!F_flag && us.mtime && sb.st_mtime != us.mtime && tries == 1) {
637 			/* no match! have to refetch */
638 			fclose(f);
639 			/* if precious, warn the user and give up */
640 			if (R_flag) {
641 				warnx("%s: local modification time "
642 				    "does not match remote", path);
643 				goto failure_keep;
644 			}
645 		} else if (url->offset > sb.st_size) {
646 			/* gap between what we asked for and what we got */
647 			warnx("%s: gap in resume mode", URL);
648 			fclose(of);
649 			of = NULL;
650 			/* picked up again later */
651 		} else if (us.size != -1) {
652 			if (us.size == sb.st_size)
653 				/* nothing to do */
654 				goto success;
655 			if (sb.st_size > us.size) {
656 				/* local file too long! */
657 				warnx("%s: local file (%jd bytes) is longer "
658 				    "than remote file (%jd bytes)", path,
659 				    (intmax_t)sb.st_size, (intmax_t)us.size);
660 				goto failure;
661 			}
662 			/* we got it, open local file */
663 			if ((of = fopen(path, "r+")) == NULL) {
664 				warn("%s: fopen()", path);
665 				goto failure;
666 			}
667 			/* check that it didn't move under our feet */
668 			if (fstat(fileno(of), &nsb) == -1) {
669 				/* can't happen! */
670 				warn("%s: fstat()", path);
671 				goto failure;
672 			}
673 			if (nsb.st_dev != sb.st_dev ||
674 			    nsb.st_ino != sb.st_ino ||
675 			    nsb.st_size != sb.st_size) {
676 				warnx("%s: file has changed", URL);
677 				fclose(of);
678 				of = NULL;
679 				sb = nsb;
680 				/* picked up again later */
681 			}
682 		}
683 		/* seek to where we left off */
684 		if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) {
685 			warn("%s: fseeko()", path);
686 			fclose(of);
687 			of = NULL;
688 			/* picked up again later */
689 		}
690 	} else if (m_flag && sb.st_size != -1) {
691 		/* mirror mode, local file exists */
692 		if (sb.st_size == us.size && sb.st_mtime == us.mtime)
693 			goto success;
694 	}
695 
696 	if (of == NULL) {
697 		/*
698 		 * We don't yet have an output file; either this is a
699 		 * vanilla run with no special flags, or the local and
700 		 * remote files didn't match.
701 		 */
702 
703 		if (url->offset > 0) {
704 			/*
705 			 * We tried to restart a transfer, but for
706 			 * some reason gave up - so we have to restart
707 			 * from scratch if we want the whole file
708 			 */
709 			url->offset = 0;
710 			if ((f = fetchXGet(url, &us, flags)) == NULL) {
711 				warnx("%s: %s", URL, fetchLastErrString);
712 				goto failure;
713 			}
714 			if (sigint)
715 				goto signal;
716 		}
717 
718 		/* construct a temp file name */
719 		if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
720 			if ((slash = strrchr(path, '/')) == NULL)
721 				slash = path;
722 			else
723 				++slash;
724 			if(tmppath != NULL)
725 				free(tmppath);
726 			asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
727 			    (int)(slash - path), path, slash);
728 			if (tmppath != NULL) {
729 				if (mkstemps(tmppath, strlen(slash) + 1) == -1) {
730 					warn("%s: mkstemps()", path);
731 					goto failure;
732 				}
733 				of = fopen(tmppath, "w");
734 				chown(tmppath, sb.st_uid, sb.st_gid);
735 				chmod(tmppath, sb.st_mode & ALLPERMS);
736 			}
737 		}
738 		if (of == NULL)
739 			of = fopen(path, "w");
740 		if (of == NULL) {
741 			warn("%s: open()", path);
742 			goto failure;
743 		}
744 	}
745 	count = url->offset;
746 
747 	/* start the counter */
748 	stat_start(&xs, path, us.size, count);
749 
750 	sigalrm = siginfo = sigint = 0;
751 
752 	/* suck in the data */
753 	setvbuf(f, NULL, _IOFBF, B_size);
754 	signal(SIGINFO, sig_handler);
755 	while (!sigint) {
756 		if (us.size != -1 && us.size - count < B_size &&
757 		    us.size - count >= 0)
758 			size = us.size - count;
759 		else
760 			size = B_size;
761 		if (siginfo) {
762 			stat_end(&xs);
763 			siginfo = 0;
764 		}
765 
766 		if (size == 0)
767 			break;
768 
769 		if ((readcnt = fread(buf, 1, size, f)) < size) {
770 			if (ferror(f) && errno == EINTR && !sigint)
771 				clearerr(f);
772 			else if (readcnt == 0)
773 				break;
774 		}
775 
776 		stat_update(&xs, count += readcnt);
777 		for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
778 			if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
779 				if (ferror(of) && errno == EINTR && !sigint)
780 					clearerr(of);
781 				else
782 					break;
783 			}
784 		if (readcnt != 0)
785 			break;
786 	}
787 	if (!sigalrm)
788 		sigalrm = ferror(f) && errno == ETIMEDOUT;
789 	signal(SIGINFO, SIG_DFL);
790 
791 	stat_end(&xs);
792 
793 	/*
794 	 * If the transfer timed out or was interrupted, we still want to
795 	 * set the mtime in case the file is not removed (-r or -R) and
796 	 * the user later restarts the transfer.
797 	 */
798  signal:
799 	/* set mtime of local file */
800 	if (!n_flag && us.mtime && !o_stdout && of != NULL &&
801 	    (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
802 		struct timeval tv[2];
803 
804 		fflush(of);
805 		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
806 		tv[1].tv_sec = (long)us.mtime;
807 		tv[0].tv_usec = tv[1].tv_usec = 0;
808 		if (utimes(tmppath ? tmppath : path, tv))
809 			warn("%s: utimes()", tmppath ? tmppath : path);
810 	}
811 
812 	/* timed out or interrupted? */
813 	if (sigalrm)
814 		warnx("transfer timed out");
815 	if (sigint) {
816 		warnx("transfer interrupted");
817 		goto failure;
818 	}
819 
820 	/* timeout / interrupt before connection completley established? */
821 	if (f == NULL)
822 		goto failure;
823 
824 	if (!sigalrm) {
825 		/* check the status of our files */
826 		if (ferror(f))
827 			warn("%s", URL);
828 		if (ferror(of))
829 			warn("%s", path);
830 		if (ferror(f) || ferror(of))
831 			goto failure;
832 	}
833 
834 	/* did the transfer complete normally? */
835 	if (us.size != -1 && count < us.size) {
836 		warnx("%s appears to be truncated: %jd/%jd bytes",
837 		    path, (intmax_t)count, (intmax_t)us.size);
838 		if(!o_stdout && a_flag && count > size_prev) {
839 			fclose(f);
840 			if (w_secs)
841 				sleep(w_secs);
842 			tries++;
843 			goto again;
844 		}
845 		goto failure_keep;
846 	}
847 
848 	/*
849 	 * If the transfer timed out and we didn't know how much to
850 	 * expect, assume the worst (i.e. we didn't get all of it)
851 	 */
852 	if (sigalrm && us.size == -1) {
853 		warnx("%s may be truncated", path);
854 		goto failure_keep;
855 	}
856 
857  success:
858 	r = 0;
859 	if (tmppath != NULL && rename(tmppath, path) == -1) {
860 		warn("%s: rename()", path);
861 		goto failure_keep;
862 	}
863 	goto done;
864  failure:
865 	if (of && of != stdout && !R_flag && !r_flag)
866 		if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
867 			unlink(tmppath ? tmppath : path);
868 	if (R_flag && tmppath != NULL && sb.st_size == -1)
869 		rename(tmppath, path); /* ignore errors here */
870  failure_keep:
871 	r = -1;
872 	goto done;
873  done:
874 	if (f)
875 		fclose(f);
876 	if (of && of != stdout)
877 		fclose(of);
878 	if (url)
879 		fetchFreeURL(url);
880 	if (tmppath != NULL)
881 		free(tmppath);
882 	return (r);
883 }
884 
885 static void
886 usage(void)
887 {
888 	fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
889 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
890 "       [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
891 "       [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
892 "       [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
893 "       [-o file] [--referer=URL] [-S bytes] [-T seconds]",
894 "       [--user-agent=agent-string] [-w seconds] URL ...",
895 "       fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
896 "       [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
897 "       [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
898 "       [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
899 "       [-o file] [--referer=URL] [-S bytes] [-T seconds]",
900 "       [--user-agent=agent-string] [-w seconds] -h host -f file [-c dir]");
901 }
902 
903 
904 /*
905  * Entry point
906  */
907 int
908 main(int argc, char *argv[])
909 {
910 	struct stat sb;
911 	struct sigaction sa;
912 	const char *p, *s;
913 	char *end, *q;
914 	int c, e, is_http, r;
915 
916 
917 	while ((c = getopt_long(argc, argv,
918 	    "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:",
919 	    longopts, NULL)) != -1)
920 		switch (c) {
921 		case '1':
922 			once_flag = 1;
923 			break;
924 		case '4':
925 			family = PF_INET;
926 			break;
927 		case '6':
928 			family = PF_INET6;
929 			break;
930 		case 'A':
931 			A_flag = 1;
932 			break;
933 		case 'a':
934 			a_flag = 1;
935 			break;
936 		case 'B':
937 			B_size = (off_t)strtol(optarg, &end, 10);
938 			if (*optarg == '\0' || *end != '\0')
939 				errx(1, "invalid buffer size (%s)", optarg);
940 			break;
941 		case 'b':
942 			warnx("warning: the -b option is deprecated");
943 			b_flag = 1;
944 			break;
945 		case 'c':
946 			c_dirname = optarg;
947 			break;
948 		case 'd':
949 			d_flag = 1;
950 			break;
951 		case 'F':
952 			F_flag = 1;
953 			break;
954 		case 'f':
955 			f_filename = optarg;
956 			break;
957 		case 'H':
958 			warnx("the -H option is now implicit, "
959 			    "use -U to disable");
960 			break;
961 		case 'h':
962 			h_hostname = optarg;
963 			break;
964 		case 'i':
965 			i_flag = 1;
966 			i_filename = optarg;
967 			break;
968 		case 'l':
969 			l_flag = 1;
970 			break;
971 		case 'o':
972 			o_flag = 1;
973 			o_filename = optarg;
974 			break;
975 		case 'M':
976 		case 'm':
977 			if (r_flag)
978 				errx(1, "the -m and -r flags "
979 				    "are mutually exclusive");
980 			m_flag = 1;
981 			break;
982 		case 'N':
983 			N_filename = optarg;
984 			break;
985 		case 'n':
986 			n_flag = 1;
987 			break;
988 		case 'P':
989 		case 'p':
990 			p_flag = 1;
991 			break;
992 		case 'q':
993 			v_level = 0;
994 			break;
995 		case 'R':
996 			R_flag = 1;
997 			break;
998 		case 'r':
999 			if (m_flag)
1000 				errx(1, "the -m and -r flags "
1001 				    "are mutually exclusive");
1002 			r_flag = 1;
1003 			break;
1004 		case 'S':
1005 			S_size = strtoll(optarg, &end, 10);
1006 			if (*optarg == '\0' || *end != '\0')
1007 				errx(1, "invalid size (%s)", optarg);
1008 			break;
1009 		case 's':
1010 			s_flag = 1;
1011 			break;
1012 		case 'T':
1013 			T_secs = strtol(optarg, &end, 10);
1014 			if (*optarg == '\0' || *end != '\0')
1015 				errx(1, "invalid timeout (%s)", optarg);
1016 			break;
1017 		case 't':
1018 			t_flag = 1;
1019 			warnx("warning: the -t option is deprecated");
1020 			break;
1021 		case 'U':
1022 			U_flag = 1;
1023 			break;
1024 		case 'v':
1025 			v_level++;
1026 			break;
1027 		case 'w':
1028 			a_flag = 1;
1029 			w_secs = strtol(optarg, &end, 10);
1030 			if (*optarg == '\0' || *end != '\0')
1031 				errx(1, "invalid delay (%s)", optarg);
1032 			break;
1033 		case OPTION_BIND_ADDRESS:
1034 			setenv("FETCH_BIND_ADDRESS", optarg, 1);
1035 			break;
1036 		case OPTION_NO_FTP_PASSIVE_MODE:
1037 			setenv("FTP_PASSIVE_MODE", "no", 1);
1038 			break;
1039 		case OPTION_HTTP_REFERER:
1040 			setenv("HTTP_REFERER", optarg, 1);
1041 			break;
1042 		case OPTION_HTTP_USER_AGENT:
1043 			setenv("HTTP_USER_AGENT", optarg, 1);
1044 			break;
1045 		case OPTION_NO_PROXY:
1046 			setenv("NO_PROXY", optarg, 1);
1047 			break;
1048 		case OPTION_SSL_CA_CERT_FILE:
1049 			setenv("SSL_CA_CERT_FILE", optarg, 1);
1050 			break;
1051 		case OPTION_SSL_CA_CERT_PATH:
1052 			setenv("SSL_CA_CERT_PATH", optarg, 1);
1053 			break;
1054 		case OPTION_SSL_CLIENT_CERT_FILE:
1055 			setenv("SSL_CLIENT_CERT_FILE", optarg, 1);
1056 			break;
1057 		case OPTION_SSL_CLIENT_KEY_FILE:
1058 			setenv("SSL_CLIENT_KEY_FILE", optarg, 1);
1059 			break;
1060 		case OPTION_SSL_CRL_FILE:
1061 			setenv("SSL_CLIENT_CRL_FILE", optarg, 1);
1062 			break;
1063 		case OPTION_SSL_NO_SSL3:
1064 			setenv("SSL_NO_SSL3", "", 1);
1065 			break;
1066 		case OPTION_SSL_NO_TLS1:
1067 			setenv("SSL_NO_TLS1", "", 1);
1068 			break;
1069 		case OPTION_SSL_NO_VERIFY_HOSTNAME:
1070 			setenv("SSL_NO_VERIFY_HOSTNAME", "", 1);
1071 			break;
1072 		case OPTION_SSL_NO_VERIFY_PEER:
1073 			setenv("SSL_NO_VERIFY_PEER", "", 1);
1074 			break;
1075 		default:
1076 			usage();
1077 			exit(1);
1078 		}
1079 
1080 	argc -= optind;
1081 	argv += optind;
1082 
1083 	if (h_hostname || f_filename || c_dirname) {
1084 		if (!h_hostname || !f_filename || argc) {
1085 			usage();
1086 			exit(1);
1087 		}
1088 		/* XXX this is a hack. */
1089 		if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
1090 			errx(1, "invalid hostname");
1091 		if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
1092 		    c_dirname ? c_dirname : "", f_filename) == -1)
1093 			errx(1, "%s", strerror(ENOMEM));
1094 		argc++;
1095 	}
1096 
1097 	if (!argc) {
1098 		usage();
1099 		exit(1);
1100 	}
1101 
1102 	/* allocate buffer */
1103 	if (B_size < MINBUFSIZE)
1104 		B_size = MINBUFSIZE;
1105 	if ((buf = malloc(B_size)) == NULL)
1106 		errx(1, "%s", strerror(ENOMEM));
1107 
1108 	/* timeouts */
1109 	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
1110 		ftp_timeout = strtol(s, &end, 10);
1111 		if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
1112 			warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
1113 			ftp_timeout = 0;
1114 		}
1115 	}
1116 	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
1117 		http_timeout = strtol(s, &end, 10);
1118 		if (*s == '\0' || *end != '\0' || http_timeout < 0) {
1119 			warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
1120 			http_timeout = 0;
1121 		}
1122 	}
1123 
1124 	/* signal handling */
1125 	sa.sa_flags = 0;
1126 	sa.sa_handler = sig_handler;
1127 	sigemptyset(&sa.sa_mask);
1128 	sigaction(SIGALRM, &sa, NULL);
1129 	sa.sa_flags = SA_RESETHAND;
1130 	sigaction(SIGINT, &sa, NULL);
1131 	fetchRestartCalls = 0;
1132 
1133 	/* output file */
1134 	if (o_flag) {
1135 		if (strcmp(o_filename, "-") == 0) {
1136 			o_stdout = 1;
1137 		} else if (stat(o_filename, &sb) == -1) {
1138 			if (errno == ENOENT) {
1139 				if (argc > 1)
1140 					errx(1, "%s is not a directory",
1141 					    o_filename);
1142 			} else {
1143 				err(1, "%s", o_filename);
1144 			}
1145 		} else {
1146 			if (sb.st_mode & S_IFDIR)
1147 				o_directory = 1;
1148 		}
1149 	}
1150 
1151 	/* check if output is to a tty (for progress report) */
1152 	v_tty = isatty(STDERR_FILENO);
1153 	v_progress = v_tty && v_level > 0;
1154 	if (v_progress)
1155 		pgrp = getpgrp();
1156 
1157 	r = 0;
1158 
1159 	/* authentication */
1160 	if (v_tty)
1161 		fetchAuthMethod = query_auth;
1162 	if (N_filename != NULL)
1163 		if (setenv("NETRC", N_filename, 1) == -1)
1164 			err(1, "setenv: cannot set NETRC=%s", N_filename);
1165 
1166 	while (argc) {
1167 		if ((p = strrchr(*argv, '/')) == NULL)
1168 			p = *argv;
1169 		else
1170 			p++;
1171 
1172 		if (!*p)
1173 			p = "fetch.out";
1174 
1175 		fetchLastErrCode = 0;
1176 
1177 		if (o_flag) {
1178 			if (o_stdout) {
1179 				e = fetch(*argv, "-", &is_http);
1180 			} else if (o_directory) {
1181 				asprintf(&q, "%s/%s", o_filename, p);
1182 				e = fetch(*argv, q, &is_http);
1183 				free(q);
1184 			} else {
1185 				e = fetch(*argv, o_filename, &is_http);
1186 			}
1187 		} else {
1188 			e = fetch(*argv, p, &is_http);
1189 		}
1190 
1191 		if (sigint)
1192 			kill(getpid(), SIGINT);
1193 
1194 		if (e == 0 && once_flag)
1195 			exit(0);
1196 
1197 		if (e) {
1198 			r = 1;
1199 			if ((fetchLastErrCode
1200 			    && fetchLastErrCode != FETCH_AUTH
1201 			    && fetchLastErrCode != FETCH_UNAVAIL
1202 			    && fetchLastErrCode != FETCH_MOVED
1203 			    && fetchLastErrCode != FETCH_URL
1204 			    && fetchLastErrCode != FETCH_RESOLV
1205 			    && fetchLastErrCode != FETCH_UNKNOWN
1206 			    && (!is_http || (
1207 			    	   fetchLastErrCode != FETCH_PROTO
1208 			    	&& fetchLastErrCode != FETCH_SERVER
1209 			    	&& fetchLastErrCode != FETCH_TEMP
1210 			    	&& fetchLastErrCode != FETCH_TIMEOUT
1211 			    )))) {
1212 				if (w_secs && v_level)
1213 					fprintf(stderr, "Waiting %ld seconds "
1214 					    "before retrying\n", w_secs);
1215 				if (w_secs)
1216 					sleep(w_secs);
1217 				if (a_flag)
1218 					continue;
1219 			}
1220 		}
1221 
1222 		argc--, argv++;
1223 	}
1224 
1225 	exit(r);
1226 }
1227