fetch.c revision 153919
1187423Sgonzo/*-
2187423Sgonzo * Copyright (c) 2000-2004 Dag-Erling Co�dan Sm�rgrav
3187423Sgonzo * All rights reserved.
4187423Sgonzo *
5187423Sgonzo * Redistribution and use in source and binary forms, with or without
6187423Sgonzo * modification, are permitted provided that the following conditions
7187423Sgonzo * are met:
8187423Sgonzo * 1. Redistributions of source code must retain the above copyright
9187423Sgonzo *    notice, this list of conditions and the following disclaimer
10187423Sgonzo *    in this position and unchanged.
11187423Sgonzo * 2. Redistributions in binary form must reproduce the above copyright
12187423Sgonzo *    notice, this list of conditions and the following disclaimer in the
13187423Sgonzo *    documentation and/or other materials provided with the distribution.
14187423Sgonzo * 3. The name of the author may not be used to endorse or promote products
15187423Sgonzo *    derived from this software without specific prior written permission
16187423Sgonzo *
17187423Sgonzo * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18187423Sgonzo * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19187423Sgonzo * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20187423Sgonzo * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21187423Sgonzo * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22187423Sgonzo * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23187423Sgonzo * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24187423Sgonzo * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25187423Sgonzo * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26187423Sgonzo * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27187423Sgonzo */
28187423Sgonzo
29187423Sgonzo#include <sys/cdefs.h>
30187423Sgonzo__FBSDID("$FreeBSD: head/usr.bin/fetch/fetch.c 153919 2005-12-30 23:36:26Z des $");
31187423Sgonzo
32187423Sgonzo#include <sys/param.h>
33187423Sgonzo#include <sys/socket.h>
34187423Sgonzo#include <sys/stat.h>
35187423Sgonzo#include <sys/time.h>
36187423Sgonzo
37187423Sgonzo#include <ctype.h>
38187423Sgonzo#include <err.h>
39198562Sthompsa#include <errno.h>
40187423Sgonzo#include <signal.h>
41187423Sgonzo#include <stdint.h>
42187423Sgonzo#include <stdio.h>
43187423Sgonzo#include <stdlib.h>
44192178Sgonzo#include <string.h>
45192178Sgonzo#include <sysexits.h>
46187423Sgonzo#include <termios.h>
47187423Sgonzo#include <unistd.h>
48223562Skevlo
49187423Sgonzo#include <fetch.h>
50187423Sgonzo
51187423Sgonzo#define MINBUFSIZE	4096
52187423Sgonzo
53187423Sgonzo/* Option flags */
54187456Sgonzoint	 A_flag;	/*    -A: do not follow 302 redirects */
55187423Sgonzoint	 a_flag;	/*    -a: auto retry */
56211476Sadrianoff_t	 B_size;	/*    -B: buffer size */
57211476Sadrianint	 b_flag;	/*!   -b: workaround TCP bug */
58211476Sadrianchar    *c_dirname;	/*    -c: remote directory */
59223562Skevloint	 d_flag;	/*    -d: direct connection */
60223562Skevloint	 F_flag;	/*    -F: restart without checking mtime  */
61202954Sgonzochar	*f_filename;	/*    -f: file to fetch */
62202954Sgonzochar	*h_hostname;	/*    -h: host to fetch from */
63192178Sgonzoint	 l_flag;	/*    -l: link rather than copy file: URLs */
64198562Sthompsaint	 m_flag;	/* -[Mm]: mirror mode */
65198562Sthompsachar	*N_filename;	/*    -N: netrc file name */
66198562Sthompsaint	 n_flag;	/*    -n: do not preserve modification time */
67187423Sgonzoint	 o_flag;	/*    -o: specify output file */
68198562Sthompsaint	 o_directory;	/*        output file is a directory */
69198562Sthompsachar	*o_filename;	/*        name of output file */
70198562Sthompsaint	 o_stdout;	/*        output file is stdout */
71198562Sthompsaint	 once_flag;	/*    -1: stop at first successful file */
72198562Sthompsaint	 p_flag;	/* -[Pp]: use passive FTP */
73198562Sthompsaint	 R_flag;	/*    -R: don't delete partially transferred files */
74198562Sthompsaint	 r_flag;	/*    -r: restart previously interrupted transfer */
75198562Sthompsaoff_t	 S_size;        /*    -S: require size to match */
76198562Sthompsaint	 s_flag;        /*    -s: show size, don't fetch */
77198562Sthompsalong	 T_secs = 120;	/*    -T: transfer timeout in seconds */
78198562Sthompsaint	 t_flag;	/*!   -t: workaround TCP bug */
79198562Sthompsaint	 U_flag;	/*    -U: do not use high ports */
80198562Sthompsaint	 v_level = 1;	/*    -v: verbosity level */
81198562Sthompsaint	 v_tty;		/*        stdout is a tty */
82198562Sthompsapid_t	 pgrp;		/*        our process group */
83198562Sthompsalong	 w_secs;	/*    -w: retry delay */
84198562Sthompsaint	 family = PF_UNSPEC;	/* -[46]: address family to use */
85198562Sthompsa
86198562Sthompsaint	 sigalrm;	/* SIGALRM received */
87198562Sthompsaint	 siginfo;	/* SIGINFO received */
88198562Sthompsaint	 sigint;	/* SIGINT received */
89198562Sthompsa
90198562Sthompsalong	 ftp_timeout;	/* default timeout for FTP transfers */
91198562Sthompsalong	 http_timeout;	/* default timeout for HTTP transfers */
92198562Sthompsachar	*buf;		/* transfer buffer */
93198562Sthompsa
94198562Sthompsa
95198562Sthompsa/*
96198562Sthompsa * Signal handler
97198562Sthompsa */
98198562Sthompsastatic void
99198562Sthompsasig_handler(int sig)
100198562Sthompsa{
101187423Sgonzo	switch (sig) {
102198669Srrs	case SIGALRM:
103198669Srrs		sigalrm = 1;
104198669Srrs		break;
105198669Srrs	case SIGINFO:
106198669Srrs		siginfo = 1;
107198669Srrs		break;
108187423Sgonzo	case SIGINT:
109187423Sgonzo		sigint = 1;
110187423Sgonzo		break;
111187423Sgonzo	}
112187423Sgonzo}
113187423Sgonzo
114187423Sgonzostruct xferstat {
115187423Sgonzo	char		 name[64];
116187423Sgonzo	struct timeval	 start;
117187423Sgonzo	struct timeval	 last;
118187423Sgonzo	off_t		 size;
119187423Sgonzo	off_t		 offset;
120187423Sgonzo	off_t		 rcvd;
121187423Sgonzo};
122211480Sadrian
123187463Sgonzo/*
124187463Sgonzo * Compute and display ETA
125187463Sgonzo */
126187423Sgonzostatic const char *
127187423Sgonzostat_eta(struct xferstat *xs)
128187423Sgonzo{
129187423Sgonzo	static char str[16];
130187423Sgonzo	long elapsed, eta;
131187423Sgonzo	off_t received, expected;
132187423Sgonzo
133187423Sgonzo	elapsed = xs->last.tv_sec - xs->start.tv_sec;
134187423Sgonzo	received = xs->rcvd - xs->offset;
135187423Sgonzo	expected = xs->size - xs->rcvd;
136187423Sgonzo	eta = (long)((double)elapsed * expected / received);
137187423Sgonzo	if (eta > 3600)
138187423Sgonzo		snprintf(str, sizeof str, "%02ldh%02ldm",
139187423Sgonzo		    eta / 3600, (eta % 3600) / 60);
140220056Sadrian	else
141220056Sadrian		snprintf(str, sizeof str, "%02ldm%02lds",
142220056Sadrian		    eta / 60, eta % 60);
143220056Sadrian	return (str);
144220056Sadrian}
145220056Sadrian
146220056Sadrian/*
147220056Sadrian * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
148220056Sadrian */
149220056Sadrianstatic const char *prefixes = " kMGTP";
150220056Sadrianstatic const char *
151220056Sadrianstat_bytes(off_t bytes)
152220056Sadrian{
153220056Sadrian	static char str[16];
154220056Sadrian	const char *prefix = prefixes;
155220056Sadrian
156220056Sadrian	while (bytes > 9999 && prefix[1] != '\0') {
157220056Sadrian		bytes /= 1024;
158220056Sadrian		prefix++;
159220056Sadrian	}
160220056Sadrian	snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
161220056Sadrian	return (str);
162220056Sadrian}
163220056Sadrian
164220056Sadrian/*
165220056Sadrian * Compute and display transfer rate
166187423Sgonzo */
167187423Sgonzostatic const char *
168187423Sgonzostat_bps(struct xferstat *xs)
169187423Sgonzo{
170195513Sgonzo	static char str[16];
171220056Sadrian	double delta, bps;
172220056Sadrian
173202954Sgonzo	delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
174187423Sgonzo	    - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
175202954Sgonzo	if (delta == 0.0) {
176202954Sgonzo		snprintf(str, sizeof str, "?? Bps");
177202954Sgonzo	} else {
178202954Sgonzo		bps = (xs->rcvd - xs->offset) / delta;
179202954Sgonzo		snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
180187423Sgonzo	}
181187423Sgonzo	return (str);
182202954Sgonzo}
183202954Sgonzo
184201845Simp/*
185201881Simp * Update the stats display
186201845Simp */
187192178Sgonzostatic void
188192178Sgonzostat_display(struct xferstat *xs, int force)
189192178Sgonzo{
190192178Sgonzo	struct timeval now;
191192178Sgonzo	int ctty_pgrp;
192192178Sgonzo
193192178Sgonzo	/* check if we're the foreground process */
194212774Sthompsa	if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
195192178Sgonzo	    (pid_t)ctty_pgrp != pgrp)
196192178Sgonzo		return;
197192178Sgonzo
198192178Sgonzo	gettimeofday(&now, NULL);
199192178Sgonzo	if (!force && now.tv_sec <= xs->last.tv_sec)
200192178Sgonzo		return;
201192178Sgonzo	xs->last = now;
202192178Sgonzo
203192178Sgonzo	fprintf(stderr, "\r%-46.46s", xs->name);
204192178Sgonzo	if (xs->size <= 0) {
205192178Sgonzo		setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
206192178Sgonzo		fprintf(stderr, "        %s", stat_bytes(xs->rcvd));
207220052Sadrian	} else {
208220052Sadrian		setproctitle("%s [%d%% of %s]", xs->name,
209220052Sadrian		    (int)((100.0 * xs->rcvd) / xs->size),
210220052Sadrian		    stat_bytes(xs->size));
211220052Sadrian		fprintf(stderr, "%3d%% of %s",
212220052Sadrian		    (int)((100.0 * xs->rcvd) / xs->size),
213220052Sadrian		    stat_bytes(xs->size));
214220052Sadrian	}
215220052Sadrian	fprintf(stderr, " %s", stat_bps(xs));
216220052Sadrian	if (xs->size > 0 && xs->rcvd > 0 &&
217220052Sadrian	    xs->last.tv_sec >= xs->start.tv_sec + 10)
218220096Sadrian		fprintf(stderr, " %s", stat_eta(xs));
219220052Sadrian}
220220052Sadrian
221187424Sgonzo/*
222202954Sgonzo * Initialize the transfer statistics
223187424Sgonzo */
224187423Sgonzostatic void
225216318Sgonzostat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
226216318Sgonzo{
227216318Sgonzo	snprintf(xs->name, sizeof xs->name, "%s", name);
228187424Sgonzo	gettimeofday(&xs->start, NULL);
229187423Sgonzo	xs->last.tv_sec = xs->last.tv_usec = 0;
230187423Sgonzo	xs->size = size;
231187424Sgonzo	xs->offset = offset;
232187424Sgonzo	xs->rcvd = offset;
233187424Sgonzo	if (v_tty && v_level > 0)
234187424Sgonzo		stat_display(xs, 1);
235187424Sgonzo	else if (v_level > 0)
236211476Sadrian		fprintf(stderr, "%-46s", xs->name);
237211476Sadrian}
238211476Sadrian
239211476Sadrian/*
240211476Sadrian * Update the transfer statistics
241195513Sgonzo */
242192365Sgonzostatic void
243187424Sgonzostat_update(struct xferstat *xs, off_t rcvd)
244198562Sthompsa{
245187423Sgonzo	xs->rcvd = rcvd;
246211476Sadrian	if (v_tty && v_level > 0)
247211476Sadrian		stat_display(xs, 0);
248211476Sadrian}
249211476Sadrian
250211476Sadrian/*
251192132Sgonzo * Finalize the transfer statistics
252187424Sgonzo */
253187423Sgonzostatic void
254187423Sgonzostat_end(struct xferstat *xs)
255187423Sgonzo{
256187423Sgonzo	gettimeofday(&xs->last, NULL);
257187423Sgonzo	if (v_tty && v_level > 0) {
258192178Sgonzo		stat_display(xs, 1);
259192178Sgonzo		putc('\n', stderr);
260198562Sthompsa	} else if (v_level > 0) {
261192178Sgonzo		fprintf(stderr, "        %s %s\n",
262198562Sthompsa		    stat_bytes(xs->size), stat_bps(xs));
263198562Sthompsa	}
264192178Sgonzo}
265192178Sgonzo
266192178Sgonzo/*
267192178Sgonzo * Ask the user for authentication details
268192178Sgonzo */
269192178Sgonzostatic int
270192178Sgonzoquery_auth(struct url *URL)
271198562Sthompsa{
272192178Sgonzo	struct termios tios;
273198562Sthompsa	tcflag_t saved_flags;
274198562Sthompsa	int i, nopwd;
275192178Sgonzo
276192178Sgonzo	fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
277192178Sgonzo	    URL->scheme, URL->host, URL->port);
278192178Sgonzo
279220056Sadrian	fprintf(stderr, "Login: ");
280220056Sadrian	if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
281212774Sthompsa		return (-1);
282187424Sgonzo	for (i = strlen(URL->user); i >= 0; --i)
283187424Sgonzo		if (URL->user[i] == '\r' || URL->user[i] == '\n')
284187424Sgonzo			URL->user[i] = '\0';
285187424Sgonzo
286187424Sgonzo	fprintf(stderr, "Password: ");
287187423Sgonzo	if (tcgetattr(STDIN_FILENO, &tios) == 0) {
288188882Sgonzo		saved_flags = tios.c_lflag;
289188882Sgonzo		tios.c_lflag &= ~ECHO;
290188882Sgonzo		tios.c_lflag |= ECHONL|ICANON;
291211481Sadrian		tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
292188882Sgonzo		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
293187424Sgonzo		tios.c_lflag = saved_flags;
294202849Simp		tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
295202849Simp	} else {
296202849Simp		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
297187423Sgonzo	}
298187423Sgonzo	if (nopwd)
299		return (-1);
300	for (i = strlen(URL->pwd); i >= 0; --i)
301		if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
302			URL->pwd[i] = '\0';
303
304	return (0);
305}
306
307/*
308 * Fetch a file
309 */
310static int
311fetch(char *URL, const char *path)
312{
313	struct url *url;
314	struct url_stat us;
315	struct stat sb, nsb;
316	struct xferstat xs;
317	FILE *f, *of;
318	size_t size, wr;
319	off_t count;
320	char flags[8];
321	const char *slash;
322	char *tmppath;
323	int r;
324	unsigned timeout;
325	char *ptr;
326
327	f = of = NULL;
328	tmppath = NULL;
329
330	timeout = 0;
331	*flags = 0;
332	count = 0;
333
334	/* set verbosity level */
335	if (v_level > 1)
336		strcat(flags, "v");
337	if (v_level > 2)
338		fetchDebug = 1;
339
340	/* parse URL */
341	if ((url = fetchParseURL(URL)) == NULL) {
342		warnx("%s: parse error", URL);
343		goto failure;
344	}
345
346	/* if no scheme was specified, take a guess */
347	if (!*url->scheme) {
348		if (!*url->host)
349			strcpy(url->scheme, SCHEME_FILE);
350		else if (strncasecmp(url->host, "ftp.", 4) == 0)
351			strcpy(url->scheme, SCHEME_FTP);
352		else if (strncasecmp(url->host, "www.", 4) == 0)
353			strcpy(url->scheme, SCHEME_HTTP);
354	}
355
356	/* common flags */
357	switch (family) {
358	case PF_INET:
359		strcat(flags, "4");
360		break;
361	case PF_INET6:
362		strcat(flags, "6");
363		break;
364	}
365
366	/* FTP specific flags */
367	if (strcmp(url->scheme, "ftp") == 0) {
368		if (p_flag)
369			strcat(flags, "p");
370		if (d_flag)
371			strcat(flags, "d");
372		if (U_flag)
373			strcat(flags, "l");
374		timeout = T_secs ? T_secs : ftp_timeout;
375	}
376
377	/* HTTP specific flags */
378	if (strcmp(url->scheme, "http") == 0) {
379		if (d_flag)
380			strcat(flags, "d");
381		if (A_flag)
382			strcat(flags, "A");
383		timeout = T_secs ? T_secs : http_timeout;
384	}
385
386	/* set the protocol timeout. */
387	fetchTimeout = timeout;
388
389	/* just print size */
390	if (s_flag) {
391		if (timeout)
392			alarm(timeout);
393		r = fetchStat(url, &us, flags);
394		if (timeout)
395			alarm(0);
396		if (sigalrm || sigint)
397			goto signal;
398		if (r == -1) {
399			warnx("%s", fetchLastErrString);
400			goto failure;
401		}
402		if (us.size == -1)
403			printf("Unknown\n");
404		else
405			printf("%jd\n", (intmax_t)us.size);
406		goto success;
407	}
408
409	/*
410	 * If the -r flag was specified, we have to compare the local
411	 * and remote files, so we should really do a fetchStat()
412	 * first, but I know of at least one HTTP server that only
413	 * sends the content size in response to GET requests, and
414	 * leaves it out of replies to HEAD requests.  Also, in the
415	 * (frequent) case that the local and remote files match but
416	 * the local file is truncated, we have sufficient information
417	 * before the compare to issue a correct request.  Therefore,
418	 * we always issue a GET request as if we were sure the local
419	 * file was a truncated copy of the remote file; we can drop
420	 * the connection later if we change our minds.
421	 */
422	sb.st_size = -1;
423	if (!o_stdout) {
424		r = stat(path, &sb);
425		if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
426			url->offset = sb.st_size;
427		} else if (r == -1 || !S_ISREG(sb.st_mode)) {
428			/*
429			 * Whatever value sb.st_size has now is either
430			 * wrong (if stat(2) failed) or irrelevant (if the
431			 * path does not refer to a regular file)
432			 */
433			sb.st_size = -1;
434		}
435		if (r == -1 && errno != ENOENT) {
436			warnx("%s: stat()", path);
437			goto failure;
438		}
439	}
440
441	/* start the transfer */
442	if (timeout)
443		alarm(timeout);
444	f = fetchXGet(url, &us, flags);
445	if (timeout)
446		alarm(0);
447	if (sigalrm || sigint)
448		goto signal;
449	if (f == NULL) {
450		warnx("%s: %s", URL, fetchLastErrString);
451		goto failure;
452	}
453	if (sigint)
454		goto signal;
455
456	/* check that size is as expected */
457	if (S_size) {
458		if (us.size == -1) {
459			warnx("%s: size unknown", URL);
460		} else if (us.size != S_size) {
461			warnx("%s: size mismatch: expected %jd, actual %jd",
462			    URL, (intmax_t)S_size, (intmax_t)us.size);
463			goto failure;
464		}
465	}
466
467	/* symlink instead of copy */
468	if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
469		if (symlink(url->doc, path) == -1) {
470			warn("%s: symlink()", path);
471			goto failure;
472		}
473		goto success;
474	}
475
476	if (us.size == -1 && !o_stdout && v_level > 0)
477		warnx("%s: size of remote file is not known", URL);
478	if (v_level > 1) {
479		if (sb.st_size != -1)
480			fprintf(stderr, "local size / mtime: %jd / %ld\n",
481			    (intmax_t)sb.st_size, (long)sb.st_mtime);
482		if (us.size != -1)
483			fprintf(stderr, "remote size / mtime: %jd / %ld\n",
484			    (intmax_t)us.size, (long)us.mtime);
485	}
486
487	/* open output file */
488	if (o_stdout) {
489		/* output to stdout */
490		of = stdout;
491	} else if (r_flag && sb.st_size != -1) {
492		/* resume mode, local file exists */
493		if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
494			/* no match! have to refetch */
495			fclose(f);
496			/* if precious, warn the user and give up */
497			if (R_flag) {
498				warnx("%s: local modification time "
499				    "does not match remote", path);
500				goto failure_keep;
501			}
502		} else if (us.size != -1) {
503			if (us.size == sb.st_size)
504				/* nothing to do */
505				goto success;
506			if (sb.st_size > us.size) {
507				/* local file too long! */
508				warnx("%s: local file (%jd bytes) is longer "
509				    "than remote file (%jd bytes)", path,
510				    (intmax_t)sb.st_size, (intmax_t)us.size);
511				goto failure;
512			}
513			/* we got it, open local file */
514			if ((of = fopen(path, "a")) == NULL) {
515				warn("%s: fopen()", path);
516				goto failure;
517			}
518			/* check that it didn't move under our feet */
519			if (fstat(fileno(of), &nsb) == -1) {
520				/* can't happen! */
521				warn("%s: fstat()", path);
522				goto failure;
523			}
524			if (nsb.st_dev != sb.st_dev ||
525			    nsb.st_ino != nsb.st_ino ||
526			    nsb.st_size != sb.st_size) {
527				warnx("%s: file has changed", URL);
528				fclose(of);
529				of = NULL;
530				sb = nsb;
531			}
532		}
533	} else if (m_flag && sb.st_size != -1) {
534		/* mirror mode, local file exists */
535		if (sb.st_size == us.size && sb.st_mtime == us.mtime)
536			goto success;
537	}
538
539	if (of == NULL) {
540		/*
541		 * We don't yet have an output file; either this is a
542		 * vanilla run with no special flags, or the local and
543		 * remote files didn't match.
544		 */
545
546		if (url->offset > 0) {
547			/*
548			 * We tried to restart a transfer, but for
549			 * some reason gave up - so we have to restart
550			 * from scratch if we want the whole file
551			 */
552			url->offset = 0;
553			if ((f = fetchXGet(url, &us, flags)) == NULL) {
554				warnx("%s: %s", URL, fetchLastErrString);
555				goto failure;
556			}
557			if (sigint)
558				goto signal;
559		}
560
561		/* construct a temp file name */
562		if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
563			if ((slash = strrchr(path, '/')) == NULL)
564				slash = path;
565			else
566				++slash;
567			asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
568			    (int)(slash - path), path, slash);
569			if (tmppath != NULL) {
570				mkstemps(tmppath, strlen(slash) + 1);
571				of = fopen(tmppath, "w");
572			}
573		}
574		if (of == NULL)
575			of = fopen(path, "w");
576		if (of == NULL) {
577			warn("%s: open()", path);
578			goto failure;
579		}
580	}
581	count = url->offset;
582
583	/* start the counter */
584	stat_start(&xs, path, us.size, count);
585
586	sigalrm = siginfo = sigint = 0;
587
588	/* suck in the data */
589	signal(SIGINFO, sig_handler);
590	while (!sigint) {
591		if (us.size != -1 && us.size - count < B_size &&
592		    us.size - count >= 0)
593			size = us.size - count;
594		else
595			size = B_size;
596		if (siginfo) {
597			stat_end(&xs);
598			siginfo = 0;
599		}
600		if ((size = fread(buf, 1, size, f)) == 0) {
601			if (ferror(f) && errno == EINTR && !sigint)
602				clearerr(f);
603			else
604				break;
605		}
606		stat_update(&xs, count += size);
607		for (ptr = buf; size > 0; ptr += wr, size -= wr)
608			if ((wr = fwrite(ptr, 1, size, of)) < size) {
609				if (ferror(of) && errno == EINTR && !sigint)
610					clearerr(of);
611				else
612					break;
613			}
614		if (size != 0)
615			break;
616	}
617	if (!sigalrm)
618		sigalrm = ferror(f) && errno == ETIMEDOUT;
619	signal(SIGINFO, SIG_DFL);
620
621	stat_end(&xs);
622
623	/*
624	 * If the transfer timed out or was interrupted, we still want to
625	 * set the mtime in case the file is not removed (-r or -R) and
626	 * the user later restarts the transfer.
627	 */
628 signal:
629	/* set mtime of local file */
630	if (!n_flag && us.mtime && !o_stdout && of != NULL &&
631	    (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
632		struct timeval tv[2];
633
634		fflush(of);
635		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
636		tv[1].tv_sec = (long)us.mtime;
637		tv[0].tv_usec = tv[1].tv_usec = 0;
638		if (utimes(tmppath ? tmppath : path, tv))
639			warn("%s: utimes()", tmppath ? tmppath : path);
640	}
641
642	/* timed out or interrupted? */
643	if (sigalrm)
644		warnx("transfer timed out");
645	if (sigint) {
646		warnx("transfer interrupted");
647		goto failure;
648	}
649
650	/* timeout / interrupt before connection completley established? */
651	if (f == NULL)
652		goto failure;
653
654	if (!sigalrm) {
655		/* check the status of our files */
656		if (ferror(f))
657			warn("%s", URL);
658		if (ferror(of))
659			warn("%s", path);
660		if (ferror(f) || ferror(of))
661			goto failure;
662	}
663
664	/* did the transfer complete normally? */
665	if (us.size != -1 && count < us.size) {
666		warnx("%s appears to be truncated: %jd/%jd bytes",
667		    path, (intmax_t)count, (intmax_t)us.size);
668		goto failure_keep;
669	}
670
671	/*
672	 * If the transfer timed out and we didn't know how much to
673	 * expect, assume the worst (i.e. we didn't get all of it)
674	 */
675	if (sigalrm && us.size == -1) {
676		warnx("%s may be truncated", path);
677		goto failure_keep;
678	}
679
680 success:
681	r = 0;
682	if (tmppath != NULL && rename(tmppath, path) == -1) {
683		warn("%s: rename()", path);
684		goto failure_keep;
685	}
686	goto done;
687 failure:
688	if (of && of != stdout && !R_flag && !r_flag)
689		if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
690			unlink(tmppath ? tmppath : path);
691	if (R_flag && tmppath != NULL && sb.st_size == -1)
692		rename(tmppath, path); /* ignore errors here */
693 failure_keep:
694	r = -1;
695	goto done;
696 done:
697	if (f)
698		fclose(f);
699	if (of && of != stdout)
700		fclose(of);
701	if (url)
702		fetchFreeURL(url);
703	if (tmppath != NULL)
704		free(tmppath);
705	return (r);
706}
707
708static void
709usage(void)
710{
711	fprintf(stderr, "%s\n%s\n%s\n",
712	    "usage: fetch [-146AFMPRUadlmnpqrsv] [-N netrc] [-o outputfile]",
713	    "             [-S bytes] [-B bytes] [-T seconds] [-w seconds]",
714	    "             [-h host -f file [-c dir] | URL ...]");
715}
716
717
718/*
719 * Entry point
720 */
721int
722main(int argc, char *argv[])
723{
724	struct stat sb;
725	struct sigaction sa;
726	const char *p, *s;
727	char *end, *q;
728	int c, e, r;
729
730	while ((c = getopt(argc, argv,
731	    "146AaB:bc:dFf:Hh:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
732		switch (c) {
733		case '1':
734			once_flag = 1;
735			break;
736		case '4':
737			family = PF_INET;
738			break;
739		case '6':
740			family = PF_INET6;
741			break;
742		case 'A':
743			A_flag = 1;
744			break;
745		case 'a':
746			a_flag = 1;
747			break;
748		case 'B':
749			B_size = (off_t)strtol(optarg, &end, 10);
750			if (*optarg == '\0' || *end != '\0')
751				errx(1, "invalid buffer size (%s)", optarg);
752			break;
753		case 'b':
754			warnx("warning: the -b option is deprecated");
755			b_flag = 1;
756			break;
757		case 'c':
758			c_dirname = optarg;
759			break;
760		case 'd':
761			d_flag = 1;
762			break;
763		case 'F':
764			F_flag = 1;
765			break;
766		case 'f':
767			f_filename = optarg;
768			break;
769		case 'H':
770			warnx("the -H option is now implicit, "
771			    "use -U to disable");
772			break;
773		case 'h':
774			h_hostname = optarg;
775			break;
776		case 'l':
777			l_flag = 1;
778			break;
779		case 'o':
780			o_flag = 1;
781			o_filename = optarg;
782			break;
783		case 'M':
784		case 'm':
785			if (r_flag)
786				errx(1, "the -m and -r flags "
787				    "are mutually exclusive");
788			m_flag = 1;
789			break;
790		case 'N':
791			N_filename = optarg;
792			break;
793		case 'n':
794			n_flag = 1;
795			break;
796		case 'P':
797		case 'p':
798			p_flag = 1;
799			break;
800		case 'q':
801			v_level = 0;
802			break;
803		case 'R':
804			R_flag = 1;
805			break;
806		case 'r':
807			if (m_flag)
808				errx(1, "the -m and -r flags "
809				    "are mutually exclusive");
810			r_flag = 1;
811			break;
812		case 'S':
813			S_size = (off_t)strtol(optarg, &end, 10);
814			if (*optarg == '\0' || *end != '\0')
815				errx(1, "invalid size (%s)", optarg);
816			break;
817		case 's':
818			s_flag = 1;
819			break;
820		case 'T':
821			T_secs = strtol(optarg, &end, 10);
822			if (*optarg == '\0' || *end != '\0')
823				errx(1, "invalid timeout (%s)", optarg);
824			break;
825		case 't':
826			t_flag = 1;
827			warnx("warning: the -t option is deprecated");
828			break;
829		case 'U':
830			U_flag = 1;
831			break;
832		case 'v':
833			v_level++;
834			break;
835		case 'w':
836			a_flag = 1;
837			w_secs = strtol(optarg, &end, 10);
838			if (*optarg == '\0' || *end != '\0')
839				errx(1, "invalid delay (%s)", optarg);
840			break;
841		default:
842			usage();
843			exit(EX_USAGE);
844		}
845
846	argc -= optind;
847	argv += optind;
848
849	if (h_hostname || f_filename || c_dirname) {
850		if (!h_hostname || !f_filename || argc) {
851			usage();
852			exit(EX_USAGE);
853		}
854		/* XXX this is a hack. */
855		if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
856			errx(1, "invalid hostname");
857		if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
858		    c_dirname ? c_dirname : "", f_filename) == -1)
859			errx(1, "%s", strerror(ENOMEM));
860		argc++;
861	}
862
863	if (!argc) {
864		usage();
865		exit(EX_USAGE);
866	}
867
868	/* allocate buffer */
869	if (B_size < MINBUFSIZE)
870		B_size = MINBUFSIZE;
871	if ((buf = malloc(B_size)) == NULL)
872		errx(1, "%s", strerror(ENOMEM));
873
874	/* timeouts */
875	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
876		ftp_timeout = strtol(s, &end, 10);
877		if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
878			warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
879			ftp_timeout = 0;
880		}
881	}
882	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
883		http_timeout = strtol(s, &end, 10);
884		if (*s == '\0' || *end != '\0' || http_timeout < 0) {
885			warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
886			http_timeout = 0;
887		}
888	}
889
890	/* signal handling */
891	sa.sa_flags = 0;
892	sa.sa_handler = sig_handler;
893	sigemptyset(&sa.sa_mask);
894	sigaction(SIGALRM, &sa, NULL);
895	sa.sa_flags = SA_RESETHAND;
896	sigaction(SIGINT, &sa, NULL);
897	fetchRestartCalls = 0;
898
899	/* output file */
900	if (o_flag) {
901		if (strcmp(o_filename, "-") == 0) {
902			o_stdout = 1;
903		} else if (stat(o_filename, &sb) == -1) {
904			if (errno == ENOENT) {
905				if (argc > 1)
906					errx(EX_USAGE, "%s is not a directory",
907					    o_filename);
908			} else {
909				err(EX_IOERR, "%s", o_filename);
910			}
911		} else {
912			if (sb.st_mode & S_IFDIR)
913				o_directory = 1;
914		}
915	}
916
917	/* check if output is to a tty (for progress report) */
918	v_tty = isatty(STDERR_FILENO);
919	if (v_tty)
920		pgrp = getpgrp();
921
922	r = 0;
923
924	/* authentication */
925	if (v_tty)
926		fetchAuthMethod = query_auth;
927	if (N_filename != NULL)
928		setenv("NETRC", N_filename, 1);
929
930	while (argc) {
931		if ((p = strrchr(*argv, '/')) == NULL)
932			p = *argv;
933		else
934			p++;
935
936		if (!*p)
937			p = "fetch.out";
938
939		fetchLastErrCode = 0;
940
941		if (o_flag) {
942			if (o_stdout) {
943				e = fetch(*argv, "-");
944			} else if (o_directory) {
945				asprintf(&q, "%s/%s", o_filename, p);
946				e = fetch(*argv, q);
947				free(q);
948			} else {
949				e = fetch(*argv, o_filename);
950			}
951		} else {
952			e = fetch(*argv, p);
953		}
954
955		if (sigint)
956			kill(getpid(), SIGINT);
957
958		if (e == 0 && once_flag)
959			exit(0);
960
961		if (e) {
962			r = 1;
963			if ((fetchLastErrCode
964			    && fetchLastErrCode != FETCH_UNAVAIL
965			    && fetchLastErrCode != FETCH_MOVED
966			    && fetchLastErrCode != FETCH_URL
967			    && fetchLastErrCode != FETCH_RESOLV
968			    && fetchLastErrCode != FETCH_UNKNOWN)) {
969				if (w_secs && v_level)
970					fprintf(stderr, "Waiting %ld seconds "
971					    "before retrying\n", w_secs);
972				if (w_secs)
973					sleep(w_secs);
974				if (a_flag)
975					continue;
976			}
977		}
978
979		argc--, argv++;
980	}
981
982	exit(r);
983}
984