xref: /freebsd/usr.bin/fetch/fetch.c (revision a0409676120c1e558d0ade943019934e0f15118d)
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 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 
40 #include <ctype.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <getopt.h>
44 #include <signal.h>
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <termios.h>
50 #include <unistd.h>
51 
52 #include <fetch.h>
53 
54 #define MINBUFSIZE	16384
55 #define TIMEOUT		120
56 
57 /* Option flags */
58 static int	 A_flag;	/*    -A: do not follow 302 redirects */
59 static int	 a_flag;	/*    -a: auto retry */
60 static off_t	 B_size;	/*    -B: buffer size */
61 static int	 b_flag;	/*!   -b: workaround TCP bug */
62 static char    *c_dirname;	/*    -c: remote directory */
63 static int	 d_flag;	/*    -d: direct connection */
64 static int	 F_flag;	/*    -F: restart without checking mtime  */
65 static char	*f_filename;	/*    -f: file to fetch */
66 static char	*h_hostname;	/*    -h: host to fetch from */
67 static int	 i_flag;	/*    -i: specify file for mtime comparison */
68 static char	*i_filename;	/*        name of input file */
69 static int	 l_flag;	/*    -l: link rather than copy file: URLs */
70 static int	 m_flag;	/* -[Mm]: mirror mode */
71 static char	*N_filename;	/*    -N: netrc file name */
72 static int	 n_flag;	/*    -n: do not preserve modification time */
73 static int	 o_flag;	/*    -o: specify output file */
74 static int	 o_directory;	/*        output file is a directory */
75 static char	*o_filename;	/*        name of output file */
76 static int	 o_stdout;	/*        output file is stdout */
77 static int	 once_flag;	/*    -1: stop at first successful file */
78 static int	 p_flag;	/* -[Pp]: use passive FTP */
79 static int	 R_flag;	/*    -R: don't delete partial files */
80 static int	 r_flag;	/*    -r: restart previous transfer */
81 static off_t	 S_size;        /*    -S: require size to match */
82 static int	 s_flag;        /*    -s: show size, don't fetch */
83 static long	 T_secs;	/*    -T: transfer timeout in seconds */
84 static int	 t_flag;	/*!   -t: workaround TCP bug */
85 static int	 U_flag;	/*    -U: do not use high ports */
86 static int	 v_level = 1;	/*    -v: verbosity level */
87 static int	 v_tty;		/*        stdout is a tty */
88 static int	 v_progress;	/*        whether to display progress */
89 static pid_t	 pgrp;		/*        our process group */
90 static long	 w_secs;	/*    -w: retry delay */
91 static int	 family = PF_UNSPEC;	/* -[46]: address family to use */
92 
93 static int	 sigalrm;	/* SIGALRM received */
94 static int	 siginfo;	/* SIGINFO received */
95 static int	 sigint;	/* SIGINT received */
96 
97 static long	 ftp_timeout = TIMEOUT;	/* default timeout for FTP transfers */
98 static long	 http_timeout = TIMEOUT;/* default timeout for HTTP transfers */
99 static char	*buf;		/* transfer buffer */
100 
101 enum options
102 {
103 	OPTION_BIND_ADDRESS,
104 	OPTION_NO_FTP_PASSIVE_MODE,
105 	OPTION_HTTP_REFERER,
106 	OPTION_HTTP_USER_AGENT,
107 	OPTION_NO_PROXY,
108 	OPTION_SSL_CA_CERT_FILE,
109 	OPTION_SSL_CA_CERT_PATH,
110 	OPTION_SSL_CLIENT_CERT_FILE,
111 	OPTION_SSL_CLIENT_KEY_FILE,
112 	OPTION_SSL_CRL_FILE,
113 	OPTION_SSL_NO_SSL3,
114 	OPTION_SSL_NO_TLS1,
115 	OPTION_SSL_NO_VERIFY_HOSTNAME,
116 	OPTION_SSL_NO_VERIFY_PEER
117 };
118 
119 
120 static struct option longopts[] =
121 {
122 	/* mapping to single character argument */
123 	{ "one-file", no_argument, NULL, '1' },
124 	{ "ipv4-only", no_argument, NULL, '4' },
125 	{ "ipv6-only", no_argument, NULL, '6' },
126 	{ "no-redirect", no_argument, NULL, 'A' },
127 	{ "retry", no_argument, NULL, 'a' },
128 	{ "buffer-size", required_argument, NULL, 'B' },
129 	/* -c not mapped, since it's deprecated */
130 	{ "direct", no_argument, NULL, 'd' },
131 	{ "force-restart", no_argument, NULL, 'F' },
132 	/* -f not mapped, since it's deprecated */
133 	/* -h not mapped, since it's deprecated */
134 	{ "if-modified-since", required_argument, NULL, 'i' },
135 	{ "symlink", no_argument, NULL, 'l' },
136 	/* -M not mapped since it's the same as -m */
137 	{ "mirror", no_argument, NULL, 'm' },
138 	{ "netrc", required_argument, NULL, 'N' },
139 	{ "no-mtime", no_argument, NULL, 'n' },
140 	{ "output", required_argument, NULL, 'o' },
141 	/* -P not mapped since it's the same as -p */
142 	{ "passive", no_argument, NULL, 'p' },
143 	{ "quiet", no_argument, NULL, 'q' },
144 	{ "keep-output", no_argument, NULL, 'R' },
145 	{ "restart", no_argument, NULL, 'r' },
146 	{ "require-size", required_argument, NULL, 'S' },
147 	{ "print-size", no_argument, NULL, 's' },
148 	{ "timeout", required_argument, NULL, 'T' },
149 	{ "passive-portrange-default", no_argument, NULL, 'T' },
150 	{ "verbose", no_argument, NULL, 'v' },
151 	{ "retry-delay", required_argument, NULL, 'w' },
152 
153 	/* options without a single character equivalent */
154 	{ "bind-address", required_argument, NULL, OPTION_BIND_ADDRESS },
155 	{ "no-passive", no_argument, NULL, OPTION_NO_FTP_PASSIVE_MODE },
156 	{ "referer", required_argument, NULL, OPTION_HTTP_REFERER },
157 	{ "user-agent", required_argument, NULL, OPTION_HTTP_USER_AGENT },
158 	{ "no-proxy", required_argument, NULL, OPTION_NO_PROXY },
159 	{ "ca-cert", required_argument, NULL, OPTION_SSL_CA_CERT_FILE },
160 	{ "ca-path", required_argument, NULL, OPTION_SSL_CA_CERT_PATH },
161 	{ "cert", required_argument, NULL, OPTION_SSL_CLIENT_CERT_FILE },
162 	{ "key", required_argument, NULL, OPTION_SSL_CLIENT_KEY_FILE },
163 	{ "crl", required_argument, NULL, OPTION_SSL_CRL_FILE },
164 	{ "no-sslv3", no_argument, NULL, OPTION_SSL_NO_SSL3 },
165 	{ "no-tlsv1", no_argument, NULL, OPTION_SSL_NO_TLS1 },
166 	{ "no-verify-hostname", no_argument, NULL, OPTION_SSL_NO_VERIFY_HOSTNAME },
167 	{ "no-verify-peer", no_argument, NULL, OPTION_SSL_NO_VERIFY_PEER },
168 
169 	{ NULL, 0, NULL, 0 }
170 };
171 
172 /*
173  * Signal handler
174  */
175 static void
176 sig_handler(int sig)
177 {
178 	switch (sig) {
179 	case SIGALRM:
180 		sigalrm = 1;
181 		break;
182 	case SIGINFO:
183 		siginfo = 1;
184 		break;
185 	case SIGINT:
186 		sigint = 1;
187 		break;
188 	}
189 }
190 
191 struct xferstat {
192 	char		 name[64];
193 	struct timeval	 start;		/* start of transfer */
194 	struct timeval	 last;		/* time of last update */
195 	struct timeval	 last2;		/* time of previous last update */
196 	off_t		 size;		/* size of file per HTTP hdr */
197 	off_t		 offset;	/* starting offset in file */
198 	off_t		 rcvd;		/* bytes already received */
199 	off_t		 lastrcvd;	/* bytes received since last update */
200 };
201 
202 /*
203  * Format a number of seconds as either XXdYYh, XXhYYm, XXmYYs, or XXs
204  * depending on its magnitude
205  */
206 static void
207 stat_seconds(char *str, size_t strsz, long seconds)
208 {
209 
210 	if (seconds > 86400)
211 		snprintf(str, strsz, "%02ldd%02ldh",
212 		    seconds / 86400, (seconds % 86400) / 3600);
213 	else if (seconds > 3600)
214 		snprintf(str, strsz, "%02ldh%02ldm",
215 		    seconds / 3600, (seconds % 3600) / 60);
216 	else if (seconds > 60)
217 		snprintf(str, strsz, "%02ldm%02lds",
218 		    seconds / 60, seconds % 60);
219 	else
220 		snprintf(str, strsz, "   %02lds",
221 		    seconds);
222 }
223 
224 /*
225  * Compute and display ETA
226  */
227 static void
228 stat_eta(char *str, size_t strsz, const struct xferstat *xs)
229 {
230 	long elapsed, eta;
231 	off_t received, expected;
232 
233 	elapsed = xs->last.tv_sec - xs->start.tv_sec;
234 	received = xs->rcvd - xs->offset;
235 	expected = xs->size - xs->rcvd;
236 	eta = (long)((double)elapsed * expected / received);
237 	if (eta > 0)
238 		stat_seconds(str, strsz, eta);
239 	else
240 		stat_seconds(str, strsz, elapsed);
241 }
242 
243 /*
244  * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
245  */
246 static const char *prefixes = " kMGTP";
247 static void
248 stat_bytes(char *str, size_t strsz, off_t bytes)
249 {
250 	const char *prefix = prefixes;
251 
252 	while (bytes > 9999 && prefix[1] != '\0') {
253 		bytes /= 1024;
254 		prefix++;
255 	}
256 	snprintf(str, strsz, "%4ju %cB", (uintmax_t)bytes, *prefix);
257 }
258 
259 /*
260  * Compute and display transfer rate
261  */
262 static void
263 stat_bps(char *str, size_t strsz, struct xferstat *xs)
264 {
265 	char bytes[16];
266 	double delta, bps;
267 
268 	delta = ((double)xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
269 	    - ((double)xs->last2.tv_sec + (xs->last2.tv_usec / 1.e6));
270 
271 	if (delta == 0.0) {
272 		snprintf(str, strsz, "?? Bps");
273 	} else {
274 		bps = (xs->rcvd - xs->lastrcvd) / delta;
275 		stat_bytes(bytes, sizeof bytes, (off_t)bps);
276 		snprintf(str, strsz, "%sps", bytes);
277 	}
278 }
279 
280 /*
281  * Update the stats display
282  */
283 static void
284 stat_display(struct xferstat *xs, int force)
285 {
286 	char bytes[16], bps[16], eta[16];
287 	struct timeval now;
288 	int ctty_pgrp;
289 
290 	/* check if we're the foreground process */
291 	if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) != 0 ||
292 	    (pid_t)ctty_pgrp != pgrp)
293 		return;
294 
295 	gettimeofday(&now, NULL);
296 	if (!force && now.tv_sec <= xs->last.tv_sec)
297 		return;
298 	xs->last2 = xs->last;
299 	xs->last = now;
300 
301 	fprintf(stderr, "\r%-46.46s", xs->name);
302 	if (xs->rcvd >= xs->size) {
303 		stat_bytes(bytes, sizeof bytes, xs->rcvd);
304 		setproctitle("%s [%s]", xs->name, bytes);
305 		fprintf(stderr, "        %s", bytes);
306 	} else {
307 		stat_bytes(bytes, sizeof bytes, xs->size);
308 		setproctitle("%s [%d%% of %s]", xs->name,
309 		    (int)((100.0 * xs->rcvd) / xs->size),
310 		    bytes);
311 		fprintf(stderr, "%3d%% of %s",
312 		    (int)((100.0 * xs->rcvd) / xs->size),
313 		    bytes);
314 	}
315 	if (force == 2) {
316 		xs->lastrcvd = xs->offset;
317 		xs->last2 = xs->start;
318 	}
319 	stat_bps(bps, sizeof bps, xs);
320 	fprintf(stderr, " %s", bps);
321 	if ((xs->size > 0 && xs->rcvd > 0 &&
322 	     xs->last.tv_sec >= xs->start.tv_sec + 3) ||
323 	    force == 2) {
324 		stat_eta(eta, sizeof eta, xs);
325 		fprintf(stderr, " %s", eta);
326 	}
327 	xs->lastrcvd = xs->rcvd;
328 }
329 
330 /*
331  * Initialize the transfer statistics
332  */
333 static void
334 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
335 {
336 
337 	memset(xs, 0, sizeof *xs);
338 	snprintf(xs->name, sizeof xs->name, "%s", name);
339 	gettimeofday(&xs->start, NULL);
340 	xs->last2 = xs->last = xs->start;
341 	xs->size = size;
342 	xs->offset = offset;
343 	xs->rcvd = offset;
344 	xs->lastrcvd = offset;
345 	if (v_progress)
346 		stat_display(xs, 1);
347 	else if (v_level > 0)
348 		fprintf(stderr, "%-46s", xs->name);
349 }
350 
351 /*
352  * Update the transfer statistics
353  */
354 static void
355 stat_update(struct xferstat *xs, off_t rcvd)
356 {
357 
358 	xs->rcvd = rcvd;
359 	if (v_progress)
360 		stat_display(xs, 0);
361 }
362 
363 /*
364  * Finalize the transfer statistics
365  */
366 static void
367 stat_end(struct xferstat *xs)
368 {
369 	char bytes[16], bps[16], eta[16];
370 
371 	gettimeofday(&xs->last, NULL);
372 	if (v_progress) {
373 		stat_display(xs, 2);
374 		putc('\n', stderr);
375 	} else if (v_level > 0) {
376 		stat_bytes(bytes, sizeof bytes, xs->rcvd);
377 		stat_bps(bps, sizeof bps, xs);
378 		stat_eta(eta, sizeof eta, xs);
379 		fprintf(stderr, "        %s %s %s\n", bytes, bps, eta);
380 	}
381 }
382 
383 /*
384  * Ask the user for authentication details
385  */
386 static int
387 query_auth(struct url *URL)
388 {
389 	struct termios tios;
390 	tcflag_t saved_flags;
391 	int i, nopwd;
392 
393 	fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
394 	    URL->scheme, URL->host, URL->port);
395 
396 	fprintf(stderr, "Login: ");
397 	if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
398 		return (-1);
399 	for (i = strlen(URL->user); i >= 0; --i)
400 		if (URL->user[i] == '\r' || URL->user[i] == '\n')
401 			URL->user[i] = '\0';
402 
403 	fprintf(stderr, "Password: ");
404 	if (tcgetattr(STDIN_FILENO, &tios) == 0) {
405 		saved_flags = tios.c_lflag;
406 		tios.c_lflag &= ~ECHO;
407 		tios.c_lflag |= ECHONL|ICANON;
408 		tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
409 		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
410 		tios.c_lflag = saved_flags;
411 		tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
412 	} else {
413 		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
414 	}
415 	if (nopwd)
416 		return (-1);
417 	for (i = strlen(URL->pwd); i >= 0; --i)
418 		if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
419 			URL->pwd[i] = '\0';
420 
421 	return (0);
422 }
423 
424 /*
425  * Fetch a file
426  */
427 static int
428 fetch(char *URL, const char *path)
429 {
430 	struct url *url;
431 	struct url_stat us;
432 	struct stat sb, nsb;
433 	struct xferstat xs;
434 	FILE *f, *of;
435 	size_t size, readcnt, wr;
436 	off_t count;
437 	char flags[8];
438 	const char *slash;
439 	char *tmppath;
440 	int r;
441 	unsigned timeout;
442 	char *ptr;
443 
444 	f = of = NULL;
445 	tmppath = NULL;
446 
447 	timeout = 0;
448 	*flags = 0;
449 	count = 0;
450 
451 	/* set verbosity level */
452 	if (v_level > 1)
453 		strcat(flags, "v");
454 	if (v_level > 2)
455 		fetchDebug = 1;
456 
457 	/* parse URL */
458 	url = NULL;
459 	if (*URL == '\0') {
460 		warnx("empty URL");
461 		goto failure;
462 	}
463 	if ((url = fetchParseURL(URL)) == NULL) {
464 		warnx("%s: parse error", URL);
465 		goto failure;
466 	}
467 
468 	/* if no scheme was specified, take a guess */
469 	if (!*url->scheme) {
470 		if (!*url->host)
471 			strcpy(url->scheme, SCHEME_FILE);
472 		else if (strncasecmp(url->host, "ftp.", 4) == 0)
473 			strcpy(url->scheme, SCHEME_FTP);
474 		else if (strncasecmp(url->host, "www.", 4) == 0)
475 			strcpy(url->scheme, SCHEME_HTTP);
476 	}
477 
478 	/* common flags */
479 	switch (family) {
480 	case PF_INET:
481 		strcat(flags, "4");
482 		break;
483 	case PF_INET6:
484 		strcat(flags, "6");
485 		break;
486 	}
487 
488 	/* FTP specific flags */
489 	if (strcmp(url->scheme, SCHEME_FTP) == 0) {
490 		if (p_flag)
491 			strcat(flags, "p");
492 		if (d_flag)
493 			strcat(flags, "d");
494 		if (U_flag)
495 			strcat(flags, "l");
496 		timeout = T_secs ? T_secs : ftp_timeout;
497 	}
498 
499 	/* HTTP specific flags */
500 	if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
501 	    strcmp(url->scheme, SCHEME_HTTPS) == 0) {
502 		if (d_flag)
503 			strcat(flags, "d");
504 		if (A_flag)
505 			strcat(flags, "A");
506 		timeout = T_secs ? T_secs : http_timeout;
507 		if (i_flag) {
508 			if (stat(i_filename, &sb)) {
509 				warn("%s: stat()", i_filename);
510 				goto failure;
511 			}
512 			url->ims_time = sb.st_mtime;
513 			strcat(flags, "i");
514 		}
515 	}
516 
517 	/* set the protocol timeout. */
518 	fetchTimeout = timeout;
519 
520 	/* just print size */
521 	if (s_flag) {
522 		if (timeout)
523 			alarm(timeout);
524 		r = fetchStat(url, &us, flags);
525 		if (timeout)
526 			alarm(0);
527 		if (sigalrm || sigint)
528 			goto signal;
529 		if (r == -1) {
530 			warnx("%s", fetchLastErrString);
531 			goto failure;
532 		}
533 		if (us.size == -1)
534 			printf("Unknown\n");
535 		else
536 			printf("%jd\n", (intmax_t)us.size);
537 		goto success;
538 	}
539 
540 	/*
541 	 * If the -r flag was specified, we have to compare the local
542 	 * and remote files, so we should really do a fetchStat()
543 	 * first, but I know of at least one HTTP server that only
544 	 * sends the content size in response to GET requests, and
545 	 * leaves it out of replies to HEAD requests.  Also, in the
546 	 * (frequent) case that the local and remote files match but
547 	 * the local file is truncated, we have sufficient information
548 	 * before the compare to issue a correct request.  Therefore,
549 	 * we always issue a GET request as if we were sure the local
550 	 * file was a truncated copy of the remote file; we can drop
551 	 * the connection later if we change our minds.
552 	 */
553 	sb.st_size = -1;
554 	if (!o_stdout) {
555 		r = stat(path, &sb);
556 		if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
557 			url->offset = sb.st_size;
558 		} else if (r == -1 || !S_ISREG(sb.st_mode)) {
559 			/*
560 			 * Whatever value sb.st_size has now is either
561 			 * wrong (if stat(2) failed) or irrelevant (if the
562 			 * path does not refer to a regular file)
563 			 */
564 			sb.st_size = -1;
565 		}
566 		if (r == -1 && errno != ENOENT) {
567 			warnx("%s: stat()", path);
568 			goto failure;
569 		}
570 	}
571 
572 	/* start the transfer */
573 	if (timeout)
574 		alarm(timeout);
575 	f = fetchXGet(url, &us, flags);
576 	if (timeout)
577 		alarm(0);
578 	if (sigalrm || sigint)
579 		goto signal;
580 	if (f == NULL) {
581 		warnx("%s: %s", URL, fetchLastErrString);
582 		if (i_flag && (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
583 		    strcmp(url->scheme, SCHEME_HTTPS) == 0) &&
584 		    fetchLastErrCode == FETCH_OK &&
585 		    strcmp(fetchLastErrString, "Not Modified") == 0) {
586 			/* HTTP Not Modified Response, return OK. */
587 			r = 0;
588 			goto done;
589 		} else
590 			goto failure;
591 	}
592 	if (sigint)
593 		goto signal;
594 
595 	/* check that size is as expected */
596 	if (S_size) {
597 		if (us.size == -1) {
598 			warnx("%s: size unknown", URL);
599 		} else if (us.size != S_size) {
600 			warnx("%s: size mismatch: expected %jd, actual %jd",
601 			    URL, (intmax_t)S_size, (intmax_t)us.size);
602 			goto failure;
603 		}
604 	}
605 
606 	/* symlink instead of copy */
607 	if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
608 		if (symlink(url->doc, path) == -1) {
609 			warn("%s: symlink()", path);
610 			goto failure;
611 		}
612 		goto success;
613 	}
614 
615 	if (us.size == -1 && !o_stdout && v_level > 0)
616 		warnx("%s: size of remote file is not known", URL);
617 	if (v_level > 1) {
618 		if (sb.st_size != -1)
619 			fprintf(stderr, "local size / mtime: %jd / %ld\n",
620 			    (intmax_t)sb.st_size, (long)sb.st_mtime);
621 		if (us.size != -1)
622 			fprintf(stderr, "remote size / mtime: %jd / %ld\n",
623 			    (intmax_t)us.size, (long)us.mtime);
624 	}
625 
626 	/* open output file */
627 	if (o_stdout) {
628 		/* output to stdout */
629 		of = stdout;
630 	} else if (r_flag && sb.st_size != -1) {
631 		/* resume mode, local file exists */
632 		if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
633 			/* no match! have to refetch */
634 			fclose(f);
635 			/* if precious, warn the user and give up */
636 			if (R_flag) {
637 				warnx("%s: local modification time "
638 				    "does not match remote", path);
639 				goto failure_keep;
640 			}
641 		} else if (url->offset > sb.st_size) {
642 			/* gap between what we asked for and what we got */
643 			warnx("%s: gap in resume mode", URL);
644 			fclose(of);
645 			of = NULL;
646 			/* picked up again later */
647 		} else if (us.size != -1) {
648 			if (us.size == sb.st_size)
649 				/* nothing to do */
650 				goto success;
651 			if (sb.st_size > us.size) {
652 				/* local file too long! */
653 				warnx("%s: local file (%jd bytes) is longer "
654 				    "than remote file (%jd bytes)", path,
655 				    (intmax_t)sb.st_size, (intmax_t)us.size);
656 				goto failure;
657 			}
658 			/* we got it, open local file */
659 			if ((of = fopen(path, "r+")) == NULL) {
660 				warn("%s: fopen()", path);
661 				goto failure;
662 			}
663 			/* check that it didn't move under our feet */
664 			if (fstat(fileno(of), &nsb) == -1) {
665 				/* can't happen! */
666 				warn("%s: fstat()", path);
667 				goto failure;
668 			}
669 			if (nsb.st_dev != sb.st_dev ||
670 			    nsb.st_ino != sb.st_ino ||
671 			    nsb.st_size != sb.st_size) {
672 				warnx("%s: file has changed", URL);
673 				fclose(of);
674 				of = NULL;
675 				sb = nsb;
676 				/* picked up again later */
677 			}
678 		}
679 		/* seek to where we left off */
680 		if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) {
681 			warn("%s: fseeko()", path);
682 			fclose(of);
683 			of = NULL;
684 			/* picked up again later */
685 		}
686 	} else if (m_flag && sb.st_size != -1) {
687 		/* mirror mode, local file exists */
688 		if (sb.st_size == us.size && sb.st_mtime == us.mtime)
689 			goto success;
690 	}
691 
692 	if (of == NULL) {
693 		/*
694 		 * We don't yet have an output file; either this is a
695 		 * vanilla run with no special flags, or the local and
696 		 * remote files didn't match.
697 		 */
698 
699 		if (url->offset > 0) {
700 			/*
701 			 * We tried to restart a transfer, but for
702 			 * some reason gave up - so we have to restart
703 			 * from scratch if we want the whole file
704 			 */
705 			url->offset = 0;
706 			if ((f = fetchXGet(url, &us, flags)) == NULL) {
707 				warnx("%s: %s", URL, fetchLastErrString);
708 				goto failure;
709 			}
710 			if (sigint)
711 				goto signal;
712 		}
713 
714 		/* construct a temp file name */
715 		if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
716 			if ((slash = strrchr(path, '/')) == NULL)
717 				slash = path;
718 			else
719 				++slash;
720 			asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
721 			    (int)(slash - path), path, slash);
722 			if (tmppath != NULL) {
723 				if (mkstemps(tmppath, strlen(slash) + 1) == -1) {
724 					warn("%s: mkstemps()", path);
725 					goto failure;
726 				}
727 				of = fopen(tmppath, "w");
728 				chown(tmppath, sb.st_uid, sb.st_gid);
729 				chmod(tmppath, sb.st_mode & ALLPERMS);
730 			}
731 		}
732 		if (of == NULL)
733 			of = fopen(path, "w");
734 		if (of == NULL) {
735 			warn("%s: open()", path);
736 			goto failure;
737 		}
738 	}
739 	count = url->offset;
740 
741 	/* start the counter */
742 	stat_start(&xs, path, us.size, count);
743 
744 	sigalrm = siginfo = sigint = 0;
745 
746 	/* suck in the data */
747 	setvbuf(f, NULL, _IOFBF, B_size);
748 	signal(SIGINFO, sig_handler);
749 	while (!sigint) {
750 		if (us.size != -1 && us.size - count < B_size &&
751 		    us.size - count >= 0)
752 			size = us.size - count;
753 		else
754 			size = B_size;
755 		if (siginfo) {
756 			stat_end(&xs);
757 			siginfo = 0;
758 		}
759 
760 		if (size == 0)
761 			break;
762 
763 		if ((readcnt = fread(buf, 1, size, f)) < size) {
764 			if (ferror(f) && errno == EINTR && !sigint)
765 				clearerr(f);
766 			else if (readcnt == 0)
767 				break;
768 		}
769 
770 		stat_update(&xs, count += readcnt);
771 		for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
772 			if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
773 				if (ferror(of) && errno == EINTR && !sigint)
774 					clearerr(of);
775 				else
776 					break;
777 			}
778 		if (readcnt != 0)
779 			break;
780 	}
781 	if (!sigalrm)
782 		sigalrm = ferror(f) && errno == ETIMEDOUT;
783 	signal(SIGINFO, SIG_DFL);
784 
785 	stat_end(&xs);
786 
787 	/*
788 	 * If the transfer timed out or was interrupted, we still want to
789 	 * set the mtime in case the file is not removed (-r or -R) and
790 	 * the user later restarts the transfer.
791 	 */
792  signal:
793 	/* set mtime of local file */
794 	if (!n_flag && us.mtime && !o_stdout && of != NULL &&
795 	    (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
796 		struct timeval tv[2];
797 
798 		fflush(of);
799 		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
800 		tv[1].tv_sec = (long)us.mtime;
801 		tv[0].tv_usec = tv[1].tv_usec = 0;
802 		if (utimes(tmppath ? tmppath : path, tv))
803 			warn("%s: utimes()", tmppath ? tmppath : path);
804 	}
805 
806 	/* timed out or interrupted? */
807 	if (sigalrm)
808 		warnx("transfer timed out");
809 	if (sigint) {
810 		warnx("transfer interrupted");
811 		goto failure;
812 	}
813 
814 	/* timeout / interrupt before connection completley established? */
815 	if (f == NULL)
816 		goto failure;
817 
818 	if (!sigalrm) {
819 		/* check the status of our files */
820 		if (ferror(f))
821 			warn("%s", URL);
822 		if (ferror(of))
823 			warn("%s", path);
824 		if (ferror(f) || ferror(of))
825 			goto failure;
826 	}
827 
828 	/* did the transfer complete normally? */
829 	if (us.size != -1 && count < us.size) {
830 		warnx("%s appears to be truncated: %jd/%jd bytes",
831 		    path, (intmax_t)count, (intmax_t)us.size);
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 (sigalrm && 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, 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 = (off_t)strtol(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_CLIENT_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 	sigaction(SIGALRM, &sa, NULL);
1116 	sa.sa_flags = SA_RESETHAND;
1117 	sigaction(SIGINT, &sa, NULL);
1118 	fetchRestartCalls = 0;
1119 
1120 	/* output file */
1121 	if (o_flag) {
1122 		if (strcmp(o_filename, "-") == 0) {
1123 			o_stdout = 1;
1124 		} else if (stat(o_filename, &sb) == -1) {
1125 			if (errno == ENOENT) {
1126 				if (argc > 1)
1127 					errx(1, "%s is not a directory",
1128 					    o_filename);
1129 			} else {
1130 				err(1, "%s", o_filename);
1131 			}
1132 		} else {
1133 			if (sb.st_mode & S_IFDIR)
1134 				o_directory = 1;
1135 		}
1136 	}
1137 
1138 	/* check if output is to a tty (for progress report) */
1139 	v_tty = isatty(STDERR_FILENO);
1140 	v_progress = v_tty && v_level > 0;
1141 	if (v_progress)
1142 		pgrp = getpgrp();
1143 
1144 	r = 0;
1145 
1146 	/* authentication */
1147 	if (v_tty)
1148 		fetchAuthMethod = query_auth;
1149 	if (N_filename != NULL)
1150 		if (setenv("NETRC", N_filename, 1) == -1)
1151 			err(1, "setenv: cannot set NETRC=%s", N_filename);
1152 
1153 	while (argc) {
1154 		if ((p = strrchr(*argv, '/')) == NULL)
1155 			p = *argv;
1156 		else
1157 			p++;
1158 
1159 		if (!*p)
1160 			p = "fetch.out";
1161 
1162 		fetchLastErrCode = 0;
1163 
1164 		if (o_flag) {
1165 			if (o_stdout) {
1166 				e = fetch(*argv, "-");
1167 			} else if (o_directory) {
1168 				asprintf(&q, "%s/%s", o_filename, p);
1169 				e = fetch(*argv, q);
1170 				free(q);
1171 			} else {
1172 				e = fetch(*argv, o_filename);
1173 			}
1174 		} else {
1175 			e = fetch(*argv, p);
1176 		}
1177 
1178 		if (sigint)
1179 			kill(getpid(), SIGINT);
1180 
1181 		if (e == 0 && once_flag)
1182 			exit(0);
1183 
1184 		if (e) {
1185 			r = 1;
1186 			if ((fetchLastErrCode
1187 			    && fetchLastErrCode != FETCH_UNAVAIL
1188 			    && fetchLastErrCode != FETCH_MOVED
1189 			    && fetchLastErrCode != FETCH_URL
1190 			    && fetchLastErrCode != FETCH_RESOLV
1191 			    && fetchLastErrCode != FETCH_UNKNOWN)) {
1192 				if (w_secs && v_level)
1193 					fprintf(stderr, "Waiting %ld seconds "
1194 					    "before retrying\n", w_secs);
1195 				if (w_secs)
1196 					sleep(w_secs);
1197 				if (a_flag)
1198 					continue;
1199 			}
1200 		}
1201 
1202 		argc--, argv++;
1203 	}
1204 
1205 	exit(r);
1206 }
1207