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