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