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