fetch.c revision 200462
1129470Spjd/*-
2129470Spjd * Copyright (c) 2000-2004 Dag-Erling Co��dan Sm��rgrav
3129470Spjd * All rights reserved.
4129470Spjd *
5129470Spjd * Redistribution and use in source and binary forms, with or without
6129470Spjd * modification, are permitted provided that the following conditions
7129470Spjd * are met:
8129470Spjd * 1. Redistributions of source code must retain the above copyright
9129470Spjd *    notice, this list of conditions and the following disclaimer
10129470Spjd *    in this position and unchanged.
11129470Spjd * 2. Redistributions in binary form must reproduce the above copyright
12129470Spjd *    notice, this list of conditions and the following disclaimer in the
13129470Spjd *    documentation and/or other materials provided with the distribution.
14129470Spjd * 3. The name of the author may not be used to endorse or promote products
15129470Spjd *    derived from this software without specific prior written permission
16129470Spjd *
17129470Spjd * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18129470Spjd * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19129470Spjd * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20129470Spjd * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21129470Spjd * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22129470Spjd * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23129470Spjd * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24129470Spjd * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25129470Spjd * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26129470Spjd * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27129470Spjd */
28129470Spjd
29129470Spjd#include <sys/cdefs.h>
30129470Spjd__FBSDID("$FreeBSD: head/usr.bin/fetch/fetch.c 200462 2009-12-13 03:14:06Z delphij $");
31129470Spjd
32129470Spjd#include <sys/param.h>
33129470Spjd#include <sys/socket.h>
34129470Spjd#include <sys/stat.h>
35129470Spjd#include <sys/time.h>
36129470Spjd
37129470Spjd#include <ctype.h>
38129470Spjd#include <err.h>
39129470Spjd#include <errno.h>
40129470Spjd#include <signal.h>
41129470Spjd#include <stdint.h>
42129470Spjd#include <stdio.h>
43129470Spjd#include <stdlib.h>
44129470Spjd#include <string.h>
45129470Spjd#include <termios.h>
46129470Spjd#include <unistd.h>
47129470Spjd
48129470Spjd#include <fetch.h>
49129470Spjd
50129470Spjd#define MINBUFSIZE	4096
51129470Spjd#define TIMEOUT		120
52129470Spjd
53129470Spjd/* Option flags */
54129470Spjdint	 A_flag;	/*    -A: do not follow 302 redirects */
55129470Spjdint	 a_flag;	/*    -a: auto retry */
56129470Spjdoff_t	 B_size;	/*    -B: buffer size */
57129470Spjdint	 b_flag;	/*!   -b: workaround TCP bug */
58129470Spjdchar    *c_dirname;	/*    -c: remote directory */
59129470Spjdint	 d_flag;	/*    -d: direct connection */
60129470Spjdint	 F_flag;	/*    -F: restart without checking mtime  */
61129470Spjdchar	*f_filename;	/*    -f: file to fetch */
62129470Spjdchar	*h_hostname;	/*    -h: host to fetch from */
63129470Spjdint	 i_flag;	/*    -i: specify input file for mtime comparison */
64129470Spjdchar	*i_filename;	/*        name of input file */
65129470Spjdint	 l_flag;	/*    -l: link rather than copy file: URLs */
66129470Spjdint	 m_flag;	/* -[Mm]: mirror mode */
67129470Spjdchar	*N_filename;	/*    -N: netrc file name */
68129470Spjdint	 n_flag;	/*    -n: do not preserve modification time */
69129470Spjdint	 o_flag;	/*    -o: specify output file */
70129470Spjdint	 o_directory;	/*        output file is a directory */
71129470Spjdchar	*o_filename;	/*        name of output file */
72130591Spjdint	 o_stdout;	/*        output file is stdout */
73130591Spjdint	 once_flag;	/*    -1: stop at first successful file */
74130591Spjdint	 p_flag;	/* -[Pp]: use passive FTP */
75130591Spjdint	 R_flag;	/*    -R: don't delete partially transferred files */
76130591Spjdint	 r_flag;	/*    -r: restart previously interrupted transfer */
77130591Spjdoff_t	 S_size;        /*    -S: require size to match */
78130591Spjdint	 s_flag;        /*    -s: show size, don't fetch */
79130591Spjdlong	 T_secs;	/*    -T: transfer timeout in seconds */
80130591Spjdint	 t_flag;	/*!   -t: workaround TCP bug */
81130591Spjdint	 U_flag;	/*    -U: do not use high ports */
82130591Spjdint	 v_level = 1;	/*    -v: verbosity level */
83130591Spjdint	 v_tty;		/*        stdout is a tty */
84130591Spjdpid_t	 pgrp;		/*        our process group */
85130591Spjdlong	 w_secs;	/*    -w: retry delay */
86130591Spjdint	 family = PF_UNSPEC;	/* -[46]: address family to use */
87130591Spjd
88130591Spjdint	 sigalrm;	/* SIGALRM received */
89130591Spjdint	 siginfo;	/* SIGINFO received */
90130591Spjdint	 sigint;	/* SIGINT received */
91130591Spjd
92130591Spjdlong	 ftp_timeout = TIMEOUT;		/* default timeout for FTP transfers */
93130591Spjdlong	 http_timeout = TIMEOUT;	/* default timeout for HTTP transfers */
94130591Spjdchar	*buf;		/* transfer buffer */
95130591Spjd
96130591Spjd
97130591Spjd/*
98130591Spjd * Signal handler
99130591Spjd */
100130591Spjdstatic void
101130591Spjdsig_handler(int sig)
102130591Spjd{
103130591Spjd	switch (sig) {
104130591Spjd	case SIGALRM:
105130591Spjd		sigalrm = 1;
106130591Spjd		break;
107130591Spjd	case SIGINFO:
108130591Spjd		siginfo = 1;
109130591Spjd		break;
110130591Spjd	case SIGINT:
111130591Spjd		sigint = 1;
112130591Spjd		break;
113130591Spjd	}
114130591Spjd}
115130591Spjd
116130591Spjdstruct xferstat {
117130591Spjd	char		 name[64];
118130591Spjd	struct timeval	 start;
119130591Spjd	struct timeval	 last;
120130591Spjd	off_t		 size;
121130591Spjd	off_t		 offset;
122130591Spjd	off_t		 rcvd;
123130591Spjd};
124130591Spjd
125130591Spjd/*
126130591Spjd * Compute and display ETA
127130591Spjd */
128130591Spjdstatic const char *
129130591Spjdstat_eta(struct xferstat *xs)
130130591Spjd{
131130591Spjd	static char str[16];
132130591Spjd	long elapsed, eta;
133130591Spjd	off_t received, expected;
134130591Spjd
135130591Spjd	elapsed = xs->last.tv_sec - xs->start.tv_sec;
136129470Spjd	received = xs->rcvd - xs->offset;
137129470Spjd	expected = xs->size - xs->rcvd;
138129470Spjd	eta = (long)((double)elapsed * expected / received);
139129470Spjd	if (eta > 3600)
140129470Spjd		snprintf(str, sizeof str, "%02ldh%02ldm",
141129470Spjd		    eta / 3600, (eta % 3600) / 60);
142129470Spjd	else
143129470Spjd		snprintf(str, sizeof str, "%02ldm%02lds",
144129470Spjd		    eta / 60, eta % 60);
145129470Spjd	return (str);
146129470Spjd}
147129470Spjd
148129470Spjd/*
149129470Spjd * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
150129470Spjd */
151129470Spjdstatic const char *prefixes = " kMGTP";
152130591Spjdstatic const char *
153130591Spjdstat_bytes(off_t bytes)
154129470Spjd{
155129470Spjd	static char str[16];
156129470Spjd	const char *prefix = prefixes;
157130591Spjd
158130591Spjd	while (bytes > 9999 && prefix[1] != '\0') {
159129470Spjd		bytes /= 1024;
160129470Spjd		prefix++;
161129470Spjd	}
162129470Spjd	snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
163129470Spjd	return (str);
164129470Spjd}
165129470Spjd
166129470Spjd/*
167129470Spjd * Compute and display transfer rate
168129470Spjd */
169129470Spjdstatic const char *
170129470Spjdstat_bps(struct xferstat *xs)
171129470Spjd{
172129470Spjd	static char str[16];
173129470Spjd	double delta, bps;
174129470Spjd
175129470Spjd	delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
176129470Spjd	    - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
177129470Spjd	if (delta == 0.0) {
178129470Spjd		snprintf(str, sizeof str, "?? Bps");
179129470Spjd	} else {
180129470Spjd		bps = (xs->rcvd - xs->offset) / delta;
181129470Spjd		snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
182129470Spjd	}
183129470Spjd	return (str);
184129470Spjd}
185129470Spjd
186129470Spjd/*
187129470Spjd * Update the stats display
188129470Spjd */
189129470Spjdstatic void
190129470Spjdstat_display(struct xferstat *xs, int force)
191129470Spjd{
192129470Spjd	struct timeval now;
193129470Spjd	int ctty_pgrp;
194129470Spjd
195129470Spjd	/* check if we're the foreground process */
196129470Spjd	if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
197129470Spjd	    (pid_t)ctty_pgrp != pgrp)
198130591Spjd		return;
199130591Spjd
200129470Spjd	gettimeofday(&now, NULL);
201129470Spjd	if (!force && now.tv_sec <= xs->last.tv_sec)
202129470Spjd		return;
203130591Spjd	xs->last = now;
204130591Spjd
205129470Spjd	fprintf(stderr, "\r%-46.46s", xs->name);
206129470Spjd	if (xs->size <= 0) {
207129470Spjd		setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
208129470Spjd		fprintf(stderr, "        %s", stat_bytes(xs->rcvd));
209129470Spjd	} else {
210129470Spjd		setproctitle("%s [%d%% of %s]", xs->name,
211129470Spjd		    (int)((100.0 * xs->rcvd) / xs->size),
212129470Spjd		    stat_bytes(xs->size));
213129470Spjd		fprintf(stderr, "%3d%% of %s",
214129470Spjd		    (int)((100.0 * xs->rcvd) / xs->size),
215129470Spjd		    stat_bytes(xs->size));
216129470Spjd	}
217129470Spjd	fprintf(stderr, " %s", stat_bps(xs));
218129470Spjd	if (xs->size > 0 && xs->rcvd > 0 &&
219129470Spjd	    xs->last.tv_sec >= xs->start.tv_sec + 10)
220129470Spjd		fprintf(stderr, " %s", stat_eta(xs));
221129470Spjd}
222129470Spjd
223129470Spjd/*
224129470Spjd * Initialize the transfer statistics
225129470Spjd */
226129470Spjdstatic void
227129470Spjdstat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
228129470Spjd{
229129470Spjd	snprintf(xs->name, sizeof xs->name, "%s", name);
230129470Spjd	gettimeofday(&xs->start, NULL);
231129470Spjd	xs->last.tv_sec = xs->last.tv_usec = 0;
232129470Spjd	xs->size = size;
233129470Spjd	xs->offset = offset;
234129470Spjd	xs->rcvd = offset;
235129470Spjd	if (v_tty && v_level > 0)
236129470Spjd		stat_display(xs, 1);
237129470Spjd	else if (v_level > 0)
238129470Spjd		fprintf(stderr, "%-46s", xs->name);
239129470Spjd}
240129470Spjd
241129470Spjd/*
242129470Spjd * Update the transfer statistics
243129470Spjd */
244129470Spjdstatic void
245129470Spjdstat_update(struct xferstat *xs, off_t rcvd)
246129470Spjd{
247129470Spjd	xs->rcvd = rcvd;
248129470Spjd	if (v_tty && v_level > 0)
249129470Spjd		stat_display(xs, 0);
250129470Spjd}
251129470Spjd
252129470Spjd/*
253129470Spjd * Finalize the transfer statistics
254129470Spjd */
255129470Spjdstatic void
256129470Spjdstat_end(struct xferstat *xs)
257129470Spjd{
258129470Spjd	gettimeofday(&xs->last, NULL);
259129470Spjd	if (v_tty && v_level > 0) {
260129470Spjd		stat_display(xs, 1);
261129470Spjd		putc('\n', stderr);
262129470Spjd	} else if (v_level > 0) {
263129470Spjd		fprintf(stderr, "        %s %s\n",
264129470Spjd		    stat_bytes(xs->size), stat_bps(xs));
265129470Spjd	}
266129470Spjd}
267129470Spjd
268129470Spjd/*
269129470Spjd * Ask the user for authentication details
270129470Spjd */
271129470Spjdstatic int
272129470Spjdquery_auth(struct url *URL)
273129470Spjd{
274129470Spjd	struct termios tios;
275129470Spjd	tcflag_t saved_flags;
276129470Spjd	int i, nopwd;
277129470Spjd
278129470Spjd	fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
279129470Spjd	    URL->scheme, URL->host, URL->port);
280129470Spjd
281129470Spjd	fprintf(stderr, "Login: ");
282129470Spjd	if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
283129470Spjd		return (-1);
284129470Spjd	for (i = strlen(URL->user); i >= 0; --i)
285129470Spjd		if (URL->user[i] == '\r' || URL->user[i] == '\n')
286129470Spjd			URL->user[i] = '\0';
287129470Spjd
288129470Spjd	fprintf(stderr, "Password: ");
289129470Spjd	if (tcgetattr(STDIN_FILENO, &tios) == 0) {
290129470Spjd		saved_flags = tios.c_lflag;
291129470Spjd		tios.c_lflag &= ~ECHO;
292129470Spjd		tios.c_lflag |= ECHONL|ICANON;
293129470Spjd		tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
294129470Spjd		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
295129470Spjd		tios.c_lflag = saved_flags;
296129470Spjd		tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
297129470Spjd	} else {
298129470Spjd		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
299129470Spjd	}
300129470Spjd	if (nopwd)
301129470Spjd		return (-1);
302129470Spjd	for (i = strlen(URL->pwd); i >= 0; --i)
303129470Spjd		if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
304129470Spjd			URL->pwd[i] = '\0';
305129470Spjd
306129470Spjd	return (0);
307129470Spjd}
308129470Spjd
309129470Spjd/*
310129470Spjd * Fetch a file
311129470Spjd */
312129470Spjdstatic int
313129470Spjdfetch(char *URL, const char *path)
314129470Spjd{
315129470Spjd	struct url *url;
316	struct url_stat us;
317	struct stat sb, nsb;
318	struct xferstat xs;
319	FILE *f, *of;
320	size_t size, wr;
321	off_t count;
322	char flags[8];
323	const char *slash;
324	char *tmppath;
325	int r;
326	unsigned timeout;
327	char *ptr;
328
329	f = of = NULL;
330	tmppath = NULL;
331
332	timeout = 0;
333	*flags = 0;
334	count = 0;
335
336	/* set verbosity level */
337	if (v_level > 1)
338		strcat(flags, "v");
339	if (v_level > 2)
340		fetchDebug = 1;
341
342	/* parse URL */
343	if ((url = fetchParseURL(URL)) == NULL) {
344		warnx("%s: parse error", URL);
345		goto failure;
346	}
347
348	/* if no scheme was specified, take a guess */
349	if (!*url->scheme) {
350		if (!*url->host)
351			strcpy(url->scheme, SCHEME_FILE);
352		else if (strncasecmp(url->host, "ftp.", 4) == 0)
353			strcpy(url->scheme, SCHEME_FTP);
354		else if (strncasecmp(url->host, "www.", 4) == 0)
355			strcpy(url->scheme, SCHEME_HTTP);
356	}
357
358	/* common flags */
359	switch (family) {
360	case PF_INET:
361		strcat(flags, "4");
362		break;
363	case PF_INET6:
364		strcat(flags, "6");
365		break;
366	}
367
368	/* FTP specific flags */
369	if (strcmp(url->scheme, SCHEME_FTP) == 0) {
370		if (p_flag)
371			strcat(flags, "p");
372		if (d_flag)
373			strcat(flags, "d");
374		if (U_flag)
375			strcat(flags, "l");
376		timeout = T_secs ? T_secs : ftp_timeout;
377	}
378
379	/* HTTP specific flags */
380	if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
381	    strcmp(url->scheme, SCHEME_HTTPS) == 0) {
382		if (d_flag)
383			strcat(flags, "d");
384		if (A_flag)
385			strcat(flags, "A");
386		timeout = T_secs ? T_secs : http_timeout;
387		if (i_flag) {
388			if (stat(i_filename, &sb)) {
389				warn("%s: stat()", i_filename);
390				goto failure;
391			}
392			url->ims_time = sb.st_mtime;
393			strcat(flags, "i");
394		}
395	}
396
397	/* set the protocol timeout. */
398	fetchTimeout = timeout;
399
400	/* just print size */
401	if (s_flag) {
402		if (timeout)
403			alarm(timeout);
404		r = fetchStat(url, &us, flags);
405		if (timeout)
406			alarm(0);
407		if (sigalrm || sigint)
408			goto signal;
409		if (r == -1) {
410			warnx("%s", fetchLastErrString);
411			goto failure;
412		}
413		if (us.size == -1)
414			printf("Unknown\n");
415		else
416			printf("%jd\n", (intmax_t)us.size);
417		goto success;
418	}
419
420	/*
421	 * If the -r flag was specified, we have to compare the local
422	 * and remote files, so we should really do a fetchStat()
423	 * first, but I know of at least one HTTP server that only
424	 * sends the content size in response to GET requests, and
425	 * leaves it out of replies to HEAD requests.  Also, in the
426	 * (frequent) case that the local and remote files match but
427	 * the local file is truncated, we have sufficient information
428	 * before the compare to issue a correct request.  Therefore,
429	 * we always issue a GET request as if we were sure the local
430	 * file was a truncated copy of the remote file; we can drop
431	 * the connection later if we change our minds.
432	 */
433	sb.st_size = -1;
434	if (!o_stdout) {
435		r = stat(path, &sb);
436		if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
437			url->offset = sb.st_size;
438		} else if (r == -1 || !S_ISREG(sb.st_mode)) {
439			/*
440			 * Whatever value sb.st_size has now is either
441			 * wrong (if stat(2) failed) or irrelevant (if the
442			 * path does not refer to a regular file)
443			 */
444			sb.st_size = -1;
445		}
446		if (r == -1 && errno != ENOENT) {
447			warnx("%s: stat()", path);
448			goto failure;
449		}
450	}
451
452	/* start the transfer */
453	if (timeout)
454		alarm(timeout);
455	f = fetchXGet(url, &us, flags);
456	if (timeout)
457		alarm(0);
458	if (sigalrm || sigint)
459		goto signal;
460	if (f == NULL) {
461		warnx("%s: %s", URL, fetchLastErrString);
462		if (i_flag && strcmp(url->scheme, SCHEME_HTTP) == 0
463		    && fetchLastErrCode == FETCH_OK
464		    && strcmp(fetchLastErrString, "Not Modified") == 0) {
465			/* HTTP Not Modified Response, return OK. */
466			r = 0;
467			goto done;
468		} else
469			goto failure;
470	}
471	if (sigint)
472		goto signal;
473
474	/* check that size is as expected */
475	if (S_size) {
476		if (us.size == -1) {
477			warnx("%s: size unknown", URL);
478		} else if (us.size != S_size) {
479			warnx("%s: size mismatch: expected %jd, actual %jd",
480			    URL, (intmax_t)S_size, (intmax_t)us.size);
481			goto failure;
482		}
483	}
484
485	/* symlink instead of copy */
486	if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
487		if (symlink(url->doc, path) == -1) {
488			warn("%s: symlink()", path);
489			goto failure;
490		}
491		goto success;
492	}
493
494	if (us.size == -1 && !o_stdout && v_level > 0)
495		warnx("%s: size of remote file is not known", URL);
496	if (v_level > 1) {
497		if (sb.st_size != -1)
498			fprintf(stderr, "local size / mtime: %jd / %ld\n",
499			    (intmax_t)sb.st_size, (long)sb.st_mtime);
500		if (us.size != -1)
501			fprintf(stderr, "remote size / mtime: %jd / %ld\n",
502			    (intmax_t)us.size, (long)us.mtime);
503	}
504
505	/* open output file */
506	if (o_stdout) {
507		/* output to stdout */
508		of = stdout;
509	} else if (r_flag && sb.st_size != -1) {
510		/* resume mode, local file exists */
511		if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
512			/* no match! have to refetch */
513			fclose(f);
514			/* if precious, warn the user and give up */
515			if (R_flag) {
516				warnx("%s: local modification time "
517				    "does not match remote", path);
518				goto failure_keep;
519			}
520		} else if (us.size != -1) {
521			if (us.size == sb.st_size)
522				/* nothing to do */
523				goto success;
524			if (sb.st_size > us.size) {
525				/* local file too long! */
526				warnx("%s: local file (%jd bytes) is longer "
527				    "than remote file (%jd bytes)", path,
528				    (intmax_t)sb.st_size, (intmax_t)us.size);
529				goto failure;
530			}
531			/* we got it, open local file */
532			if ((of = fopen(path, "a")) == NULL) {
533				warn("%s: fopen()", path);
534				goto failure;
535			}
536			/* check that it didn't move under our feet */
537			if (fstat(fileno(of), &nsb) == -1) {
538				/* can't happen! */
539				warn("%s: fstat()", path);
540				goto failure;
541			}
542			if (nsb.st_dev != sb.st_dev ||
543			    nsb.st_ino != nsb.st_ino ||
544			    nsb.st_size != sb.st_size) {
545				warnx("%s: file has changed", URL);
546				fclose(of);
547				of = NULL;
548				sb = nsb;
549			}
550		}
551	} else if (m_flag && sb.st_size != -1) {
552		/* mirror mode, local file exists */
553		if (sb.st_size == us.size && sb.st_mtime == us.mtime)
554			goto success;
555	}
556
557	if (of == NULL) {
558		/*
559		 * We don't yet have an output file; either this is a
560		 * vanilla run with no special flags, or the local and
561		 * remote files didn't match.
562		 */
563
564		if (url->offset > 0) {
565			/*
566			 * We tried to restart a transfer, but for
567			 * some reason gave up - so we have to restart
568			 * from scratch if we want the whole file
569			 */
570			url->offset = 0;
571			if ((f = fetchXGet(url, &us, flags)) == NULL) {
572				warnx("%s: %s", URL, fetchLastErrString);
573				goto failure;
574			}
575			if (sigint)
576				goto signal;
577		}
578
579		/* construct a temp file name */
580		if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
581			if ((slash = strrchr(path, '/')) == NULL)
582				slash = path;
583			else
584				++slash;
585			asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
586			    (int)(slash - path), path, slash);
587			if (tmppath != NULL) {
588				mkstemps(tmppath, strlen(slash) + 1);
589				of = fopen(tmppath, "w");
590				chown(tmppath, sb.st_uid, sb.st_gid);
591				chmod(tmppath, sb.st_mode & ALLPERMS);
592			}
593		}
594		if (of == NULL)
595			of = fopen(path, "w");
596		if (of == NULL) {
597			warn("%s: open()", path);
598			goto failure;
599		}
600	}
601	count = url->offset;
602
603	/* start the counter */
604	stat_start(&xs, path, us.size, count);
605
606	sigalrm = siginfo = sigint = 0;
607
608	/* suck in the data */
609	signal(SIGINFO, sig_handler);
610	while (!sigint) {
611		if (us.size != -1 && us.size - count < B_size &&
612		    us.size - count >= 0)
613			size = us.size - count;
614		else
615			size = B_size;
616		if (siginfo) {
617			stat_end(&xs);
618			siginfo = 0;
619		}
620		if ((size = fread(buf, 1, size, f)) == 0) {
621			if (ferror(f) && errno == EINTR && !sigint)
622				clearerr(f);
623			else
624				break;
625		}
626		stat_update(&xs, count += size);
627		for (ptr = buf; size > 0; ptr += wr, size -= wr)
628			if ((wr = fwrite(ptr, 1, size, of)) < size) {
629				if (ferror(of) && errno == EINTR && !sigint)
630					clearerr(of);
631				else
632					break;
633			}
634		if (size != 0)
635			break;
636	}
637	if (!sigalrm)
638		sigalrm = ferror(f) && errno == ETIMEDOUT;
639	signal(SIGINFO, SIG_DFL);
640
641	stat_end(&xs);
642
643	/*
644	 * If the transfer timed out or was interrupted, we still want to
645	 * set the mtime in case the file is not removed (-r or -R) and
646	 * the user later restarts the transfer.
647	 */
648 signal:
649	/* set mtime of local file */
650	if (!n_flag && us.mtime && !o_stdout && of != NULL &&
651	    (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
652		struct timeval tv[2];
653
654		fflush(of);
655		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
656		tv[1].tv_sec = (long)us.mtime;
657		tv[0].tv_usec = tv[1].tv_usec = 0;
658		if (utimes(tmppath ? tmppath : path, tv))
659			warn("%s: utimes()", tmppath ? tmppath : path);
660	}
661
662	/* timed out or interrupted? */
663	if (sigalrm)
664		warnx("transfer timed out");
665	if (sigint) {
666		warnx("transfer interrupted");
667		goto failure;
668	}
669
670	/* timeout / interrupt before connection completley established? */
671	if (f == NULL)
672		goto failure;
673
674	if (!sigalrm) {
675		/* check the status of our files */
676		if (ferror(f))
677			warn("%s", URL);
678		if (ferror(of))
679			warn("%s", path);
680		if (ferror(f) || ferror(of))
681			goto failure;
682	}
683
684	/* did the transfer complete normally? */
685	if (us.size != -1 && count < us.size) {
686		warnx("%s appears to be truncated: %jd/%jd bytes",
687		    path, (intmax_t)count, (intmax_t)us.size);
688		goto failure_keep;
689	}
690
691	/*
692	 * If the transfer timed out and we didn't know how much to
693	 * expect, assume the worst (i.e. we didn't get all of it)
694	 */
695	if (sigalrm && us.size == -1) {
696		warnx("%s may be truncated", path);
697		goto failure_keep;
698	}
699
700 success:
701	r = 0;
702	if (tmppath != NULL && rename(tmppath, path) == -1) {
703		warn("%s: rename()", path);
704		goto failure_keep;
705	}
706	goto done;
707 failure:
708	if (of && of != stdout && !R_flag && !r_flag)
709		if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
710			unlink(tmppath ? tmppath : path);
711	if (R_flag && tmppath != NULL && sb.st_size == -1)
712		rename(tmppath, path); /* ignore errors here */
713 failure_keep:
714	r = -1;
715	goto done;
716 done:
717	if (f)
718		fclose(f);
719	if (of && of != stdout)
720		fclose(of);
721	if (url)
722		fetchFreeURL(url);
723	if (tmppath != NULL)
724		free(tmppath);
725	return (r);
726}
727
728static void
729usage(void)
730{
731	fprintf(stderr, "%s\n%s\n%s\n%s\n",
732"usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
733"       [-T seconds] [-w seconds] [-i file] URL ...",
734"       fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
735"       [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
736}
737
738
739/*
740 * Entry point
741 */
742int
743main(int argc, char *argv[])
744{
745	struct stat sb;
746	struct sigaction sa;
747	const char *p, *s;
748	char *end, *q;
749	int c, e, r;
750
751	while ((c = getopt(argc, argv,
752	    "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
753		switch (c) {
754		case '1':
755			once_flag = 1;
756			break;
757		case '4':
758			family = PF_INET;
759			break;
760		case '6':
761			family = PF_INET6;
762			break;
763		case 'A':
764			A_flag = 1;
765			break;
766		case 'a':
767			a_flag = 1;
768			break;
769		case 'B':
770			B_size = (off_t)strtol(optarg, &end, 10);
771			if (*optarg == '\0' || *end != '\0')
772				errx(1, "invalid buffer size (%s)", optarg);
773			break;
774		case 'b':
775			warnx("warning: the -b option is deprecated");
776			b_flag = 1;
777			break;
778		case 'c':
779			c_dirname = optarg;
780			break;
781		case 'd':
782			d_flag = 1;
783			break;
784		case 'F':
785			F_flag = 1;
786			break;
787		case 'f':
788			f_filename = optarg;
789			break;
790		case 'H':
791			warnx("the -H option is now implicit, "
792			    "use -U to disable");
793			break;
794		case 'h':
795			h_hostname = optarg;
796			break;
797		case 'i':
798			i_flag = 1;
799			i_filename = optarg;
800			break;
801		case 'l':
802			l_flag = 1;
803			break;
804		case 'o':
805			o_flag = 1;
806			o_filename = optarg;
807			break;
808		case 'M':
809		case 'm':
810			if (r_flag)
811				errx(1, "the -m and -r flags "
812				    "are mutually exclusive");
813			m_flag = 1;
814			break;
815		case 'N':
816			N_filename = optarg;
817			break;
818		case 'n':
819			n_flag = 1;
820			break;
821		case 'P':
822		case 'p':
823			p_flag = 1;
824			break;
825		case 'q':
826			v_level = 0;
827			break;
828		case 'R':
829			R_flag = 1;
830			break;
831		case 'r':
832			if (m_flag)
833				errx(1, "the -m and -r flags "
834				    "are mutually exclusive");
835			r_flag = 1;
836			break;
837		case 'S':
838			S_size = (off_t)strtol(optarg, &end, 10);
839			if (*optarg == '\0' || *end != '\0')
840				errx(1, "invalid size (%s)", optarg);
841			break;
842		case 's':
843			s_flag = 1;
844			break;
845		case 'T':
846			T_secs = strtol(optarg, &end, 10);
847			if (*optarg == '\0' || *end != '\0')
848				errx(1, "invalid timeout (%s)", optarg);
849			break;
850		case 't':
851			t_flag = 1;
852			warnx("warning: the -t option is deprecated");
853			break;
854		case 'U':
855			U_flag = 1;
856			break;
857		case 'v':
858			v_level++;
859			break;
860		case 'w':
861			a_flag = 1;
862			w_secs = strtol(optarg, &end, 10);
863			if (*optarg == '\0' || *end != '\0')
864				errx(1, "invalid delay (%s)", optarg);
865			break;
866		default:
867			usage();
868			exit(1);
869		}
870
871	argc -= optind;
872	argv += optind;
873
874	if (h_hostname || f_filename || c_dirname) {
875		if (!h_hostname || !f_filename || argc) {
876			usage();
877			exit(1);
878		}
879		/* XXX this is a hack. */
880		if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
881			errx(1, "invalid hostname");
882		if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
883		    c_dirname ? c_dirname : "", f_filename) == -1)
884			errx(1, "%s", strerror(ENOMEM));
885		argc++;
886	}
887
888	if (!argc) {
889		usage();
890		exit(1);
891	}
892
893	/* allocate buffer */
894	if (B_size < MINBUFSIZE)
895		B_size = MINBUFSIZE;
896	if ((buf = malloc(B_size)) == NULL)
897		errx(1, "%s", strerror(ENOMEM));
898
899	/* timeouts */
900	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
901		ftp_timeout = strtol(s, &end, 10);
902		if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
903			warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
904			ftp_timeout = 0;
905		}
906	}
907	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
908		http_timeout = strtol(s, &end, 10);
909		if (*s == '\0' || *end != '\0' || http_timeout < 0) {
910			warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
911			http_timeout = 0;
912		}
913	}
914
915	/* signal handling */
916	sa.sa_flags = 0;
917	sa.sa_handler = sig_handler;
918	sigemptyset(&sa.sa_mask);
919	sigaction(SIGALRM, &sa, NULL);
920	sa.sa_flags = SA_RESETHAND;
921	sigaction(SIGINT, &sa, NULL);
922	fetchRestartCalls = 0;
923
924	/* output file */
925	if (o_flag) {
926		if (strcmp(o_filename, "-") == 0) {
927			o_stdout = 1;
928		} else if (stat(o_filename, &sb) == -1) {
929			if (errno == ENOENT) {
930				if (argc > 1)
931					errx(1, "%s is not a directory",
932					    o_filename);
933			} else {
934				err(1, "%s", o_filename);
935			}
936		} else {
937			if (sb.st_mode & S_IFDIR)
938				o_directory = 1;
939		}
940	}
941
942	/* check if output is to a tty (for progress report) */
943	v_tty = isatty(STDERR_FILENO);
944	if (v_tty)
945		pgrp = getpgrp();
946
947	r = 0;
948
949	/* authentication */
950	if (v_tty)
951		fetchAuthMethod = query_auth;
952	if (N_filename != NULL)
953		setenv("NETRC", N_filename, 1);
954
955	while (argc) {
956		if ((p = strrchr(*argv, '/')) == NULL)
957			p = *argv;
958		else
959			p++;
960
961		if (!*p)
962			p = "fetch.out";
963
964		fetchLastErrCode = 0;
965
966		if (o_flag) {
967			if (o_stdout) {
968				e = fetch(*argv, "-");
969			} else if (o_directory) {
970				asprintf(&q, "%s/%s", o_filename, p);
971				e = fetch(*argv, q);
972				free(q);
973			} else {
974				e = fetch(*argv, o_filename);
975			}
976		} else {
977			e = fetch(*argv, p);
978		}
979
980		if (sigint)
981			kill(getpid(), SIGINT);
982
983		if (e == 0 && once_flag)
984			exit(0);
985
986		if (e) {
987			r = 1;
988			if ((fetchLastErrCode
989			    && fetchLastErrCode != FETCH_UNAVAIL
990			    && fetchLastErrCode != FETCH_MOVED
991			    && fetchLastErrCode != FETCH_URL
992			    && fetchLastErrCode != FETCH_RESOLV
993			    && fetchLastErrCode != FETCH_UNKNOWN)) {
994				if (w_secs && v_level)
995					fprintf(stderr, "Waiting %ld seconds "
996					    "before retrying\n", w_secs);
997				if (w_secs)
998					sleep(w_secs);
999				if (a_flag)
1000					continue;
1001			}
1002		}
1003
1004		argc--, argv++;
1005	}
1006
1007	exit(r);
1008}
1009