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