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