fetch.c revision 200420
1/*-
2 * Copyright (c) 2000-2004 Dag-Erling Co��dan Sm��rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/usr.bin/fetch/fetch.c 200420 2009-12-11 23:35:38Z delphij $");
31
32#include <sys/param.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36
37#include <err.h>
38#include <errno.h>
39#include <signal.h>
40#include <stdint.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <termios.h>
45#include <unistd.h>
46
47#include <fetch.h>
48
49#define MINBUFSIZE	4096
50#define TIMEOUT		120
51
52/* Option flags */
53int	 A_flag;	/*    -A: do not follow 302 redirects */
54int	 a_flag;	/*    -a: auto retry */
55off_t	 B_size;	/*    -B: buffer size */
56int	 b_flag;	/*!   -b: workaround TCP bug */
57char    *c_dirname;	/*    -c: remote directory */
58int	 d_flag;	/*    -d: direct connection */
59int	 F_flag;	/*    -F: restart without checking mtime  */
60char	*f_filename;	/*    -f: file to fetch */
61char	*h_hostname;	/*    -h: host to fetch from */
62int	 i_flag;	/*    -i: specify input file for mtime comparison */
63char	*i_filename;	/*        name of input file */
64int	 l_flag;	/*    -l: link rather than copy file: URLs */
65int	 m_flag;	/* -[Mm]: mirror mode */
66char	*N_filename;	/*    -N: netrc file name */
67int	 n_flag;	/*    -n: do not preserve modification time */
68int	 o_flag;	/*    -o: specify output file */
69int	 o_directory;	/*        output file is a directory */
70char	*o_filename;	/*        name of output file */
71int	 o_stdout;	/*        output file is stdout */
72int	 once_flag;	/*    -1: stop at first successful file */
73int	 p_flag;	/* -[Pp]: use passive FTP */
74int	 R_flag;	/*    -R: don't delete partially transferred files */
75int	 r_flag;	/*    -r: restart previously interrupted transfer */
76off_t	 S_size;        /*    -S: require size to match */
77int	 s_flag;        /*    -s: show size, don't fetch */
78long	 T_secs;	/*    -T: transfer timeout in seconds */
79int	 t_flag;	/*!   -t: workaround TCP bug */
80int	 U_flag;	/*    -U: do not use high ports */
81int	 v_level = 1;	/*    -v: verbosity level */
82int	 v_tty;		/*        stdout is a tty */
83pid_t	 pgrp;		/*        our process group */
84long	 w_secs;	/*    -w: retry delay */
85int	 family = PF_UNSPEC;	/* -[46]: address family to use */
86
87int	 sigalrm;	/* SIGALRM received */
88int	 siginfo;	/* SIGINFO received */
89int	 sigint;	/* SIGINT received */
90
91long	 ftp_timeout = TIMEOUT;		/* default timeout for FTP transfers */
92long	 http_timeout = TIMEOUT;	/* default timeout for HTTP transfers */
93char	*buf;		/* transfer buffer */
94
95
96/*
97 * Signal handler
98 */
99static void
100sig_handler(int sig)
101{
102	switch (sig) {
103	case SIGALRM:
104		sigalrm = 1;
105		break;
106	case SIGINFO:
107		siginfo = 1;
108		break;
109	case SIGINT:
110		sigint = 1;
111		break;
112	}
113}
114
115struct xferstat {
116	char		 name[64];
117	struct timeval	 start;
118	struct timeval	 last;
119	off_t		 size;
120	off_t		 offset;
121	off_t		 rcvd;
122};
123
124/*
125 * Compute and display ETA
126 */
127static const char *
128stat_eta(struct xferstat *xs)
129{
130	static char str[16];
131	long elapsed, eta;
132	off_t received, expected;
133
134	elapsed = xs->last.tv_sec - xs->start.tv_sec;
135	received = xs->rcvd - xs->offset;
136	expected = xs->size - xs->rcvd;
137	eta = (long)((double)elapsed * expected / received);
138	if (eta > 3600)
139		snprintf(str, sizeof str, "%02ldh%02ldm",
140		    eta / 3600, (eta % 3600) / 60);
141	else
142		snprintf(str, sizeof str, "%02ldm%02lds",
143		    eta / 60, eta % 60);
144	return (str);
145}
146
147/*
148 * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
149 */
150static const char *prefixes = " kMGTP";
151static const char *
152stat_bytes(off_t bytes)
153{
154	static char str[16];
155	const char *prefix = prefixes;
156
157	while (bytes > 9999 && prefix[1] != '\0') {
158		bytes /= 1024;
159		prefix++;
160	}
161	snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
162	return (str);
163}
164
165/*
166 * Compute and display transfer rate
167 */
168static const char *
169stat_bps(struct xferstat *xs)
170{
171	static char str[16];
172	double delta, bps;
173
174	delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
175	    - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
176	if (delta == 0.0) {
177		snprintf(str, sizeof str, "?? Bps");
178	} else {
179		bps = (xs->rcvd - xs->offset) / delta;
180		snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
181	}
182	return (str);
183}
184
185/*
186 * Update the stats display
187 */
188static void
189stat_display(struct xferstat *xs, int force)
190{
191	struct timeval now;
192	int ctty_pgrp;
193
194	/* check if we're the foreground process */
195	if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
196	    (pid_t)ctty_pgrp != pgrp)
197		return;
198
199	gettimeofday(&now, NULL);
200	if (!force && now.tv_sec <= xs->last.tv_sec)
201		return;
202	xs->last = now;
203
204	fprintf(stderr, "\r%-46.46s", xs->name);
205	if (xs->size <= 0) {
206		setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
207		fprintf(stderr, "        %s", stat_bytes(xs->rcvd));
208	} else {
209		setproctitle("%s [%d%% of %s]", xs->name,
210		    (int)((100.0 * xs->rcvd) / xs->size),
211		    stat_bytes(xs->size));
212		fprintf(stderr, "%3d%% of %s",
213		    (int)((100.0 * xs->rcvd) / xs->size),
214		    stat_bytes(xs->size));
215	}
216	fprintf(stderr, " %s", stat_bps(xs));
217	if (xs->size > 0 && xs->rcvd > 0 &&
218	    xs->last.tv_sec >= xs->start.tv_sec + 10)
219		fprintf(stderr, " %s", stat_eta(xs));
220}
221
222/*
223 * Initialize the transfer statistics
224 */
225static void
226stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
227{
228	snprintf(xs->name, sizeof xs->name, "%s", name);
229	gettimeofday(&xs->start, NULL);
230	xs->last.tv_sec = xs->last.tv_usec = 0;
231	xs->size = size;
232	xs->offset = offset;
233	xs->rcvd = offset;
234	if (v_tty && v_level > 0)
235		stat_display(xs, 1);
236	else if (v_level > 0)
237		fprintf(stderr, "%-46s", xs->name);
238}
239
240/*
241 * Update the transfer statistics
242 */
243static void
244stat_update(struct xferstat *xs, off_t rcvd)
245{
246	xs->rcvd = rcvd;
247	if (v_tty && v_level > 0)
248		stat_display(xs, 0);
249}
250
251/*
252 * Finalize the transfer statistics
253 */
254static void
255stat_end(struct xferstat *xs)
256{
257	gettimeofday(&xs->last, NULL);
258	if (v_tty && v_level > 0) {
259		stat_display(xs, 1);
260		putc('\n', stderr);
261	} else if (v_level > 0) {
262		fprintf(stderr, "        %s %s\n",
263		    stat_bytes(xs->size), stat_bps(xs));
264	}
265}
266
267/*
268 * Ask the user for authentication details
269 */
270static int
271query_auth(struct url *URL)
272{
273	struct termios tios;
274	tcflag_t saved_flags;
275	int i, nopwd;
276
277	fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
278	    URL->scheme, URL->host, URL->port);
279
280	fprintf(stderr, "Login: ");
281	if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
282		return (-1);
283	for (i = strlen(URL->user); i >= 0; --i)
284		if (URL->user[i] == '\r' || URL->user[i] == '\n')
285			URL->user[i] = '\0';
286
287	fprintf(stderr, "Password: ");
288	if (tcgetattr(STDIN_FILENO, &tios) == 0) {
289		saved_flags = tios.c_lflag;
290		tios.c_lflag &= ~ECHO;
291		tios.c_lflag |= ECHONL|ICANON;
292		tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
293		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
294		tios.c_lflag = saved_flags;
295		tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
296	} else {
297		nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
298	}
299	if (nopwd)
300		return (-1);
301	for (i = strlen(URL->pwd); i >= 0; --i)
302		if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
303			URL->pwd[i] = '\0';
304
305	return (0);
306}
307
308/*
309 * Fetch a file
310 */
311static int
312fetch(char *URL, const char *path)
313{
314	struct url *url;
315	struct url_stat us;
316	struct stat sb, nsb;
317	struct xferstat xs;
318	FILE *f, *of;
319	size_t size, wr;
320	off_t count;
321	char flags[8];
322	const char *slash;
323	char *tmppath;
324	int r;
325	unsigned timeout;
326	char *ptr;
327
328	f = of = NULL;
329	tmppath = NULL;
330
331	timeout = 0;
332	*flags = 0;
333	count = 0;
334
335	/* set verbosity level */
336	if (v_level > 1)
337		strcat(flags, "v");
338	if (v_level > 2)
339		fetchDebug = 1;
340
341	/* parse URL */
342	if ((url = fetchParseURL(URL)) == NULL) {
343		warnx("%s: parse error", URL);
344		goto failure;
345	}
346
347	/* if no scheme was specified, take a guess */
348	if (!*url->scheme) {
349		if (!*url->host)
350			strcpy(url->scheme, SCHEME_FILE);
351		else if (strncasecmp(url->host, "ftp.", 4) == 0)
352			strcpy(url->scheme, SCHEME_FTP);
353		else if (strncasecmp(url->host, "www.", 4) == 0)
354			strcpy(url->scheme, SCHEME_HTTP);
355	}
356
357	/* common flags */
358	switch (family) {
359	case PF_INET:
360		strcat(flags, "4");
361		break;
362	case PF_INET6:
363		strcat(flags, "6");
364		break;
365	}
366
367	/* FTP specific flags */
368	if (strcmp(url->scheme, SCHEME_FTP) == 0) {
369		if (p_flag)
370			strcat(flags, "p");
371		if (d_flag)
372			strcat(flags, "d");
373		if (U_flag)
374			strcat(flags, "l");
375		timeout = T_secs ? T_secs : ftp_timeout;
376	}
377
378	/* HTTP specific flags */
379	if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
380	    strcmp(url->scheme, SCHEME_HTTPS) == 0) {
381		if (d_flag)
382			strcat(flags, "d");
383		if (A_flag)
384			strcat(flags, "A");
385		timeout = T_secs ? T_secs : http_timeout;
386		if (i_flag) {
387			if (stat(i_filename, &sb)) {
388				warn("%s: stat()", i_filename);
389				goto failure;
390			}
391			url->ims_time = sb.st_mtime;
392			strcat(flags, "i");
393		}
394	}
395
396	/* set the protocol timeout. */
397	fetchTimeout = timeout;
398
399	/* just print size */
400	if (s_flag) {
401		if (timeout)
402			alarm(timeout);
403		r = fetchStat(url, &us, flags);
404		if (timeout)
405			alarm(0);
406		if (sigalrm || sigint)
407			goto signal;
408		if (r == -1) {
409			warnx("%s", fetchLastErrString);
410			goto failure;
411		}
412		if (us.size == -1)
413			printf("Unknown\n");
414		else
415			printf("%jd\n", (intmax_t)us.size);
416		goto success;
417	}
418
419	/*
420	 * If the -r flag was specified, we have to compare the local
421	 * and remote files, so we should really do a fetchStat()
422	 * first, but I know of at least one HTTP server that only
423	 * sends the content size in response to GET requests, and
424	 * leaves it out of replies to HEAD requests.  Also, in the
425	 * (frequent) case that the local and remote files match but
426	 * the local file is truncated, we have sufficient information
427	 * before the compare to issue a correct request.  Therefore,
428	 * we always issue a GET request as if we were sure the local
429	 * file was a truncated copy of the remote file; we can drop
430	 * the connection later if we change our minds.
431	 */
432	sb.st_size = -1;
433	if (!o_stdout) {
434		r = stat(path, &sb);
435		if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
436			url->offset = sb.st_size;
437		} else if (r == -1 || !S_ISREG(sb.st_mode)) {
438			/*
439			 * Whatever value sb.st_size has now is either
440			 * wrong (if stat(2) failed) or irrelevant (if the
441			 * path does not refer to a regular file)
442			 */
443			sb.st_size = -1;
444		}
445		if (r == -1 && errno != ENOENT) {
446			warnx("%s: stat()", path);
447			goto failure;
448		}
449	}
450
451	/* start the transfer */
452	if (timeout)
453		alarm(timeout);
454	f = fetchXGet(url, &us, flags);
455	if (timeout)
456		alarm(0);
457	if (sigalrm || sigint)
458		goto signal;
459	if (f == NULL) {
460		warnx("%s: %s", URL, fetchLastErrString);
461		if (i_flag && strcmp(url->scheme, SCHEME_HTTP) == 0
462		    && fetchLastErrCode == FETCH_OK
463		    && strcmp(fetchLastErrString, "Not Modified") == 0) {
464			/* HTTP Not Modified Response, return OK. */
465			r = 0;
466			goto done;
467		} else
468			goto failure;
469	}
470	if (sigint)
471		goto signal;
472
473	/* check that size is as expected */
474	if (S_size) {
475		if (us.size == -1) {
476			warnx("%s: size unknown", URL);
477		} else if (us.size != S_size) {
478			warnx("%s: size mismatch: expected %jd, actual %jd",
479			    URL, (intmax_t)S_size, (intmax_t)us.size);
480			goto failure;
481		}
482	}
483
484	/* symlink instead of copy */
485	if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
486		if (symlink(url->doc, path) == -1) {
487			warn("%s: symlink()", path);
488			goto failure;
489		}
490		goto success;
491	}
492
493	if (us.size == -1 && !o_stdout && v_level > 0)
494		warnx("%s: size of remote file is not known", URL);
495	if (v_level > 1) {
496		if (sb.st_size != -1)
497			fprintf(stderr, "local size / mtime: %jd / %ld\n",
498			    (intmax_t)sb.st_size, (long)sb.st_mtime);
499		if (us.size != -1)
500			fprintf(stderr, "remote size / mtime: %jd / %ld\n",
501			    (intmax_t)us.size, (long)us.mtime);
502	}
503
504	/* open output file */
505	if (o_stdout) {
506		/* output to stdout */
507		of = stdout;
508	} else if (r_flag && sb.st_size != -1) {
509		/* resume mode, local file exists */
510		if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
511			/* no match! have to refetch */
512			fclose(f);
513			/* if precious, warn the user and give up */
514			if (R_flag) {
515				warnx("%s: local modification time "
516				    "does not match remote", path);
517				goto failure_keep;
518			}
519		} else if (us.size != -1) {
520			if (us.size == sb.st_size)
521				/* nothing to do */
522				goto success;
523			if (sb.st_size > us.size) {
524				/* local file too long! */
525				warnx("%s: local file (%jd bytes) is longer "
526				    "than remote file (%jd bytes)", path,
527				    (intmax_t)sb.st_size, (intmax_t)us.size);
528				goto failure;
529			}
530			/* we got it, open local file */
531			if ((of = fopen(path, "a")) == NULL) {
532				warn("%s: fopen()", path);
533				goto failure;
534			}
535			/* check that it didn't move under our feet */
536			if (fstat(fileno(of), &nsb) == -1) {
537				/* can't happen! */
538				warn("%s: fstat()", path);
539				goto failure;
540			}
541			if (nsb.st_dev != sb.st_dev ||
542			    nsb.st_ino != nsb.st_ino ||
543			    nsb.st_size != sb.st_size) {
544				warnx("%s: file has changed", URL);
545				fclose(of);
546				of = NULL;
547				sb = nsb;
548			}
549		}
550	} else if (m_flag && sb.st_size != -1) {
551		/* mirror mode, local file exists */
552		if (sb.st_size == us.size && sb.st_mtime == us.mtime)
553			goto success;
554	}
555
556	if (of == NULL) {
557		/*
558		 * We don't yet have an output file; either this is a
559		 * vanilla run with no special flags, or the local and
560		 * remote files didn't match.
561		 */
562
563		if (url->offset > 0) {
564			/*
565			 * We tried to restart a transfer, but for
566			 * some reason gave up - so we have to restart
567			 * from scratch if we want the whole file
568			 */
569			url->offset = 0;
570			if ((f = fetchXGet(url, &us, flags)) == NULL) {
571				warnx("%s: %s", URL, fetchLastErrString);
572				goto failure;
573			}
574			if (sigint)
575				goto signal;
576		}
577
578		/* construct a temp file name */
579		if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
580			if ((slash = strrchr(path, '/')) == NULL)
581				slash = path;
582			else
583				++slash;
584			asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
585			    (int)(slash - path), path, slash);
586			if (tmppath != NULL) {
587				mkstemps(tmppath, strlen(slash) + 1);
588				of = fopen(tmppath, "w");
589				chown(tmppath, sb.st_uid, sb.st_gid);
590				chmod(tmppath, sb.st_mode & ALLPERMS);
591			}
592		}
593		if (of == NULL)
594			of = fopen(path, "w");
595		if (of == NULL) {
596			warn("%s: open()", path);
597			goto failure;
598		}
599	}
600	count = url->offset;
601
602	/* start the counter */
603	stat_start(&xs, path, us.size, count);
604
605	sigalrm = siginfo = sigint = 0;
606
607	/* suck in the data */
608	signal(SIGINFO, sig_handler);
609	while (!sigint) {
610		if (us.size != -1 && us.size - count < B_size &&
611		    us.size - count >= 0)
612			size = us.size - count;
613		else
614			size = B_size;
615		if (siginfo) {
616			stat_end(&xs);
617			siginfo = 0;
618		}
619		if ((size = fread(buf, 1, size, f)) == 0) {
620			if (ferror(f) && errno == EINTR && !sigint)
621				clearerr(f);
622			else
623				break;
624		}
625		stat_update(&xs, count += size);
626		for (ptr = buf; size > 0; ptr += wr, size -= wr)
627			if ((wr = fwrite(ptr, 1, size, of)) < size) {
628				if (ferror(of) && errno == EINTR && !sigint)
629					clearerr(of);
630				else
631					break;
632			}
633		if (size != 0)
634			break;
635	}
636	if (!sigalrm)
637		sigalrm = ferror(f) && errno == ETIMEDOUT;
638	signal(SIGINFO, SIG_DFL);
639
640	stat_end(&xs);
641
642	/*
643	 * If the transfer timed out or was interrupted, we still want to
644	 * set the mtime in case the file is not removed (-r or -R) and
645	 * the user later restarts the transfer.
646	 */
647 signal:
648	/* set mtime of local file */
649	if (!n_flag && us.mtime && !o_stdout && of != NULL &&
650	    (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
651		struct timeval tv[2];
652
653		fflush(of);
654		tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
655		tv[1].tv_sec = (long)us.mtime;
656		tv[0].tv_usec = tv[1].tv_usec = 0;
657		if (utimes(tmppath ? tmppath : path, tv))
658			warn("%s: utimes()", tmppath ? tmppath : path);
659	}
660
661	/* timed out or interrupted? */
662	if (sigalrm)
663		warnx("transfer timed out");
664	if (sigint) {
665		warnx("transfer interrupted");
666		goto failure;
667	}
668
669	/* timeout / interrupt before connection completley established? */
670	if (f == NULL)
671		goto failure;
672
673	if (!sigalrm) {
674		/* check the status of our files */
675		if (ferror(f))
676			warn("%s", URL);
677		if (ferror(of))
678			warn("%s", path);
679		if (ferror(f) || ferror(of))
680			goto failure;
681	}
682
683	/* did the transfer complete normally? */
684	if (us.size != -1 && count < us.size) {
685		warnx("%s appears to be truncated: %jd/%jd bytes",
686		    path, (intmax_t)count, (intmax_t)us.size);
687		goto failure_keep;
688	}
689
690	/*
691	 * If the transfer timed out and we didn't know how much to
692	 * expect, assume the worst (i.e. we didn't get all of it)
693	 */
694	if (sigalrm && us.size == -1) {
695		warnx("%s may be truncated", path);
696		goto failure_keep;
697	}
698
699 success:
700	r = 0;
701	if (tmppath != NULL && rename(tmppath, path) == -1) {
702		warn("%s: rename()", path);
703		goto failure_keep;
704	}
705	goto done;
706 failure:
707	if (of && of != stdout && !R_flag && !r_flag)
708		if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
709			unlink(tmppath ? tmppath : path);
710	if (R_flag && tmppath != NULL && sb.st_size == -1)
711		rename(tmppath, path); /* ignore errors here */
712 failure_keep:
713	r = -1;
714	goto done;
715 done:
716	if (f)
717		fclose(f);
718	if (of && of != stdout)
719		fclose(of);
720	if (url)
721		fetchFreeURL(url);
722	if (tmppath != NULL)
723		free(tmppath);
724	return (r);
725}
726
727static void
728usage(void)
729{
730	fprintf(stderr, "%s\n%s\n%s\n%s\n",
731"usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
732"       [-T seconds] [-w seconds] [-i file] URL ...",
733"       fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
734"       [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
735}
736
737
738/*
739 * Entry point
740 */
741int
742main(int argc, char *argv[])
743{
744	struct stat sb;
745	struct sigaction sa;
746	const char *p, *s;
747	char *end, *q;
748	int c, e, r;
749
750	while ((c = getopt(argc, argv,
751	    "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
752		switch (c) {
753		case '1':
754			once_flag = 1;
755			break;
756		case '4':
757			family = PF_INET;
758			break;
759		case '6':
760			family = PF_INET6;
761			break;
762		case 'A':
763			A_flag = 1;
764			break;
765		case 'a':
766			a_flag = 1;
767			break;
768		case 'B':
769			B_size = (off_t)strtol(optarg, &end, 10);
770			if (*optarg == '\0' || *end != '\0')
771				errx(1, "invalid buffer size (%s)", optarg);
772			break;
773		case 'b':
774			warnx("warning: the -b option is deprecated");
775			b_flag = 1;
776			break;
777		case 'c':
778			c_dirname = optarg;
779			break;
780		case 'd':
781			d_flag = 1;
782			break;
783		case 'F':
784			F_flag = 1;
785			break;
786		case 'f':
787			f_filename = optarg;
788			break;
789		case 'H':
790			warnx("the -H option is now implicit, "
791			    "use -U to disable");
792			break;
793		case 'h':
794			h_hostname = optarg;
795			break;
796		case 'i':
797			i_flag = 1;
798			i_filename = optarg;
799			break;
800		case 'l':
801			l_flag = 1;
802			break;
803		case 'o':
804			o_flag = 1;
805			o_filename = optarg;
806			break;
807		case 'M':
808		case 'm':
809			if (r_flag)
810				errx(1, "the -m and -r flags "
811				    "are mutually exclusive");
812			m_flag = 1;
813			break;
814		case 'N':
815			N_filename = optarg;
816			break;
817		case 'n':
818			n_flag = 1;
819			break;
820		case 'P':
821		case 'p':
822			p_flag = 1;
823			break;
824		case 'q':
825			v_level = 0;
826			break;
827		case 'R':
828			R_flag = 1;
829			break;
830		case 'r':
831			if (m_flag)
832				errx(1, "the -m and -r flags "
833				    "are mutually exclusive");
834			r_flag = 1;
835			break;
836		case 'S':
837			S_size = (off_t)strtol(optarg, &end, 10);
838			if (*optarg == '\0' || *end != '\0')
839				errx(1, "invalid size (%s)", optarg);
840			break;
841		case 's':
842			s_flag = 1;
843			break;
844		case 'T':
845			T_secs = strtol(optarg, &end, 10);
846			if (*optarg == '\0' || *end != '\0')
847				errx(1, "invalid timeout (%s)", optarg);
848			break;
849		case 't':
850			t_flag = 1;
851			warnx("warning: the -t option is deprecated");
852			break;
853		case 'U':
854			U_flag = 1;
855			break;
856		case 'v':
857			v_level++;
858			break;
859		case 'w':
860			a_flag = 1;
861			w_secs = strtol(optarg, &end, 10);
862			if (*optarg == '\0' || *end != '\0')
863				errx(1, "invalid delay (%s)", optarg);
864			break;
865		default:
866			usage();
867			exit(1);
868		}
869
870	argc -= optind;
871	argv += optind;
872
873	if (h_hostname || f_filename || c_dirname) {
874		if (!h_hostname || !f_filename || argc) {
875			usage();
876			exit(1);
877		}
878		/* XXX this is a hack. */
879		if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
880			errx(1, "invalid hostname");
881		if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
882		    c_dirname ? c_dirname : "", f_filename) == -1)
883			errx(1, "%s", strerror(ENOMEM));
884		argc++;
885	}
886
887	if (!argc) {
888		usage();
889		exit(1);
890	}
891
892	/* allocate buffer */
893	if (B_size < MINBUFSIZE)
894		B_size = MINBUFSIZE;
895	if ((buf = malloc(B_size)) == NULL)
896		errx(1, "%s", strerror(ENOMEM));
897
898	/* timeouts */
899	if ((s = getenv("FTP_TIMEOUT")) != NULL) {
900		ftp_timeout = strtol(s, &end, 10);
901		if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
902			warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
903			ftp_timeout = 0;
904		}
905	}
906	if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
907		http_timeout = strtol(s, &end, 10);
908		if (*s == '\0' || *end != '\0' || http_timeout < 0) {
909			warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
910			http_timeout = 0;
911		}
912	}
913
914	/* signal handling */
915	sa.sa_flags = 0;
916	sa.sa_handler = sig_handler;
917	sigemptyset(&sa.sa_mask);
918	sigaction(SIGALRM, &sa, NULL);
919	sa.sa_flags = SA_RESETHAND;
920	sigaction(SIGINT, &sa, NULL);
921	fetchRestartCalls = 0;
922
923	/* output file */
924	if (o_flag) {
925		if (strcmp(o_filename, "-") == 0) {
926			o_stdout = 1;
927		} else if (stat(o_filename, &sb) == -1) {
928			if (errno == ENOENT) {
929				if (argc > 1)
930					errx(1, "%s is not a directory",
931					    o_filename);
932			} else {
933				err(1, "%s", o_filename);
934			}
935		} else {
936			if (sb.st_mode & S_IFDIR)
937				o_directory = 1;
938		}
939	}
940
941	/* check if output is to a tty (for progress report) */
942	v_tty = isatty(STDERR_FILENO);
943	if (v_tty)
944		pgrp = getpgrp();
945
946	r = 0;
947
948	/* authentication */
949	if (v_tty)
950		fetchAuthMethod = query_auth;
951	if (N_filename != NULL)
952		setenv("NETRC", N_filename, 1);
953
954	while (argc) {
955		if ((p = strrchr(*argv, '/')) == NULL)
956			p = *argv;
957		else
958			p++;
959
960		if (!*p)
961			p = "fetch.out";
962
963		fetchLastErrCode = 0;
964
965		if (o_flag) {
966			if (o_stdout) {
967				e = fetch(*argv, "-");
968			} else if (o_directory) {
969				asprintf(&q, "%s/%s", o_filename, p);
970				e = fetch(*argv, q);
971				free(q);
972			} else {
973				e = fetch(*argv, o_filename);
974			}
975		} else {
976			e = fetch(*argv, p);
977		}
978
979		if (sigint)
980			kill(getpid(), SIGINT);
981
982		if (e == 0 && once_flag)
983			exit(0);
984
985		if (e) {
986			r = 1;
987			if ((fetchLastErrCode
988			    && fetchLastErrCode != FETCH_UNAVAIL
989			    && fetchLastErrCode != FETCH_MOVED
990			    && fetchLastErrCode != FETCH_URL
991			    && fetchLastErrCode != FETCH_RESOLV
992			    && fetchLastErrCode != FETCH_UNKNOWN)) {
993				if (w_secs && v_level)
994					fprintf(stderr, "Waiting %ld seconds "
995					    "before retrying\n", w_secs);
996				if (w_secs)
997					sleep(w_secs);
998				if (a_flag)
999					continue;
1000			}
1001		}
1002
1003		argc--, argv++;
1004	}
1005
1006	exit(r);
1007}
1008