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