fetch.c revision 65362
1/*-
2 * Copyright (c) 2000 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 *	$FreeBSD: head/usr.bin/fetch/fetch.c 65362 2000-09-02 09:48:34Z des $
29 */
30
31#include <sys/param.h>
32#include <sys/stat.h>
33#include <sys/socket.h>
34
35#include <ctype.h>
36#include <err.h>
37#include <errno.h>
38#include <signal.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <sysexits.h>
43#include <unistd.h>
44
45#include <fetch.h>
46
47#define MINBUFSIZE	4096
48
49/* Option flags */
50int	 A_flag;	/*    -A: do not follow 302 redirects */
51int	 a_flag;	/*    -a: auto retry */
52size_t	 B_size;	/*    -B: buffer size */
53int	 b_flag;	/*!   -b: workaround TCP bug */
54char    *c_dirname;	/*    -c: remote directory */
55int	 d_flag;	/*    -d: direct connection */
56int	 F_flag;	/*    -F: restart without checking mtime  */
57char	*f_filename;	/*    -f: file to fetch */
58int	 H_flag;	/*    -H: use high port */
59char	*h_hostname;	/*    -h: host to fetch from */
60int	 l_flag;	/*    -l: link rather than copy file: URLs */
61int	 m_flag;	/* -[Mm]: mirror mode */
62int	 n_flag;	/*    -n: do not preserve modification time */
63int	 o_flag;	/*    -o: specify output file */
64int	 o_directory;	/*        output file is a directory */
65char	*o_filename;	/*        name of output file */
66int	 o_stdout;	/*        output file is stdout */
67int	 once_flag;	/*    -1: stop at first successful file */
68int	 p_flag;	/* -[Pp]: use passive FTP */
69int	 R_flag;	/*    -R: don't delete partially transferred files */
70int	 r_flag;	/*    -r: restart previously interrupted transfer */
71u_int	 T_secs = 0;	/*    -T: transfer timeout in seconds */
72int	 s_flag;        /*    -s: show size, don't fetch */
73off_t	 S_size;        /*    -S: require size to match */
74int	 t_flag;	/*!   -t: workaround TCP bug */
75int	 v_level = 1;	/*    -v: verbosity level */
76int	 v_tty;		/*        stdout is a tty */
77u_int	 w_secs;	/*    -w: retry delay */
78int	 family = PF_UNSPEC;	/* -[46]: address family to use */
79
80int	 sigalrm;	/* SIGALRM received */
81int	 sigint;	/* SIGINT received */
82
83u_int	 ftp_timeout;	/* default timeout for FTP transfers */
84u_int	 http_timeout;	/* default timeout for HTTP transfers */
85u_char	*buf;		/* transfer buffer */
86
87
88void
89sig_handler(int sig)
90{
91    switch (sig) {
92    case SIGALRM:
93	sigalrm = 1;
94	break;
95    case SIGINT:
96	sigint = 1;
97	break;
98    }
99}
100
101struct xferstat {
102    char		 name[40];
103    struct timeval	 start;
104    struct timeval	 end;
105    struct timeval	 last;
106    off_t		 size;
107    off_t		 offset;
108    off_t		 rcvd;
109};
110
111void
112stat_display(struct xferstat *xs, int force)
113{
114    struct timeval now;
115
116    if (!v_tty || !v_level)
117	return;
118
119    gettimeofday(&now, NULL);
120    if (!force && now.tv_sec <= xs->last.tv_sec)
121	return;
122    xs->last = now;
123
124    fprintf(stderr, "\rReceiving %s", xs->name);
125    if (xs->size == -1)
126	fprintf(stderr, ": %lld bytes", xs->rcvd);
127    else
128	fprintf(stderr, " (%lld bytes): %d%%", xs->size,
129		(int)((100.0 * xs->rcvd) / xs->size));
130}
131
132void
133stat_start(struct xferstat *xs, char *name, off_t size, off_t offset)
134{
135    snprintf(xs->name, sizeof xs->name, "%s", name);
136    gettimeofday(&xs->start, NULL);
137    xs->last.tv_sec = xs->last.tv_usec = 0;
138    xs->end = xs->last;
139    xs->size = size;
140    xs->offset = offset;
141    xs->rcvd = offset;
142    stat_display(xs, 1);
143}
144
145void
146stat_update(struct xferstat *xs, off_t rcvd, int force)
147{
148    xs->rcvd = rcvd;
149    stat_display(xs, 0);
150}
151
152void
153stat_end(struct xferstat *xs)
154{
155    double delta;
156    double bps;
157
158    if (!v_level)
159	return;
160
161    gettimeofday(&xs->end, NULL);
162
163    stat_display(xs, 1);
164    fputc('\n', stderr);
165    delta = (xs->end.tv_sec + (xs->end.tv_usec / 1.e6))
166	- (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
167    fprintf(stderr, "%lld bytes transferred in %.1f seconds ",
168	    xs->rcvd - xs->offset, delta);
169    bps = (xs->rcvd - xs->offset) / delta;
170    if (bps > 1024*1024)
171	fprintf(stderr, "(%.2f MBps)\n", bps / (1024*1024));
172    else if (bps > 1024)
173	fprintf(stderr, "(%.2f kBps)\n", bps / 1024);
174    else
175	fprintf(stderr, "(%.2f Bps)\n", bps);
176}
177
178int
179fetch(char *URL, char *path)
180{
181    struct url *url;
182    struct url_stat us;
183    struct stat sb;
184    struct xferstat xs;
185    FILE *f, *of;
186    size_t size;
187    off_t count;
188    char flags[8];
189    int n, r;
190    u_int timeout;
191
192    f = of = NULL;
193
194    /* parse URL */
195    if ((url = fetchParseURL(URL)) == NULL) {
196	warnx("%s: parse error", URL);
197	goto failure;
198    }
199
200    timeout = 0;
201    *flags = 0;
202    count = 0;
203
204    /* common flags */
205    if (v_level > 1)
206	strcat(flags, "v");
207    switch (family) {
208    case PF_INET:
209	strcat(flags, "4");
210	break;
211    case PF_INET6:
212	strcat(flags, "6");
213	break;
214    }
215
216    /* FTP specific flags */
217    if (strcmp(url->scheme, "ftp") == 0) {
218	if (p_flag)
219	    strcat(flags, "p");
220	if (d_flag)
221	    strcat(flags, "d");
222	if (H_flag)
223	    strcat(flags, "h");
224	timeout = T_secs ? T_secs : ftp_timeout;
225    }
226
227    /* HTTP specific flags */
228    if (strcmp(url->scheme, "http") == 0) {
229	if (d_flag)
230	    strcat(flags, "d");
231	if (A_flag)
232	    strcat(flags, "A");
233	timeout = T_secs ? T_secs : http_timeout;
234    }
235
236    /* set the protocol timeout. */
237    fetchTimeout = timeout;
238
239    /* just print size */
240    if (s_flag) {
241	if (fetchStat(url, &us, flags) == -1)
242	    goto failure;
243	if (us.size == -1)
244	    printf("Unknown\n");
245	else
246	    printf("%lld\n", us.size);
247	goto success;
248    }
249
250    /*
251     * If the -r flag was specified, we have to compare the local and
252     * remote files, so we should really do a fetchStat() first, but I
253     * know of at least one HTTP server that only sends the content
254     * size in response to GET requests, and leaves it out of replies
255     * to HEAD requests. Also, in the (frequent) case that the local
256     * and remote files match but the local file is truncated, we have
257     * sufficient information *before* the compare to issue a correct
258     * request. Therefore, we always issue a GET request as if we were
259     * sure the local file was a truncated copy of the remote file; we
260     * can drop the connection later if we change our minds.
261     */
262    if (r_flag && !o_stdout && stat(path, &sb) != -1)
263	url->offset = sb.st_size;
264    else
265	sb.st_size = 0;
266
267    /* start the transfer */
268    if ((f = fetchXGet(url, &us, flags)) == NULL) {
269	warnx("%s: %s", path, fetchLastErrString);
270	goto failure;
271    }
272    if (sigint)
273	goto signal;
274
275    /* check that size is as expected */
276    if (S_size) {
277	if (us.size == -1) {
278	    warnx("%s: size unknown", path);
279	    goto failure;
280	} else if (us.size != S_size) {
281	    warnx("%s: size mismatch: expected %lld, actual %lld",
282		  path, S_size, us.size);
283	    goto failure;
284	}
285    }
286
287    /* symlink instead of copy */
288    if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
289	if (symlink(url->doc, path) == -1) {
290	    warn("%s: symlink()", path);
291	    goto failure;
292	}
293	goto success;
294    }
295
296    if (v_level > 1) {
297	if (sb.st_size)
298	    warnx("local: %lld / %ld", sb.st_size, sb.st_mtime);
299	warnx("remote: %lld / %ld", us.size, us.mtime);
300    }
301
302    /* open output file */
303    if (o_stdout) {
304	/* output to stdout */
305	of = stdout;
306    } else if (sb.st_size) {
307	/* resume mode, local file exists */
308	if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
309	    /* no match! have to refetch */
310	    fclose(f);
311	    url->offset = 0;
312	    if ((f = fetchXGet(url, &us, flags)) == NULL) {
313		warnx("%s: %s", path, fetchLastErrString);
314		goto failure;
315	    }
316	    if (sigint)
317		goto signal;
318	} else {
319	    if (us.size == sb.st_size)
320		/* nothing to do */
321		goto success;
322	    if (sb.st_size > us.size) {
323		/* local file too long! */
324		warnx("%s: local file (%lld bytes) is longer "
325		      "than remote file (%lld bytes)",
326		      path, sb.st_size, us.size);
327		goto failure;
328	    }
329	    /* we got through, open local file and seek to offset */
330	    /*
331	     * XXX there's a race condition here - the file we open is not
332	     * necessarily the same as the one we stat()'ed earlier...
333	     */
334	    if ((of = fopen(path, "a")) == NULL) {
335		warn("%s: fopen()", path);
336		goto failure;
337	    }
338	    if (fseek(of, url->offset, SEEK_SET) == -1) {
339		warn("%s: fseek()", path);
340		goto failure;
341	    }
342	}
343    }
344    if (m_flag && stat(path, &sb) != -1) {
345	/* mirror mode, local file exists */
346	if (sb.st_size == us.size && sb.st_mtime == us.mtime)
347	    goto success;
348    }
349    if (!of) {
350	/*
351	 * We don't yet have an output file; either this is a vanilla
352	 * run with no special flags, or the local and remote files
353	 * didn't match.
354	 */
355	if ((of = fopen(path, "w")) == NULL) {
356	    warn("%s: open()", path);
357	    goto failure;
358	}
359    }
360    count = url->offset;
361
362    /* start the counter */
363    stat_start(&xs, path, us.size, count);
364
365    sigint = sigalrm = 0;
366
367    /* suck in the data */
368    for (n = 0; !sigint && !sigalrm; ++n) {
369	if (us.size != -1 && us.size - count < B_size)
370	    size = us.size - count;
371	else
372	    size = B_size;
373	if (timeout)
374	    alarm(timeout);
375	if ((size = fread(buf, 1, size, f)) <= 0)
376	    break;
377	stat_update(&xs, count += size, 0);
378	if (fwrite(buf, size, 1, of) != 1)
379	    break;
380    }
381
382    if (timeout)
383	alarm(0);
384
385    stat_end(&xs);
386
387    /* Set mtime of local file */
388    if (!n_flag && us.mtime && !o_stdout
389	&& (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
390	struct timeval tv[2];
391
392	fflush(of);
393	tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
394	tv[1].tv_sec = (long)us.mtime;
395	tv[0].tv_usec = tv[1].tv_usec = 0;
396	if (utimes(path, tv))
397	    warn("%s: utimes()", path);
398    }
399
400    /* timed out or interrupted? */
401 signal:
402    if (sigalrm)
403	warnx("transfer timed out");
404    if (sigint) {
405	warnx("transfer interrupted");
406	goto failure;
407    }
408
409    if (!sigalrm) {
410	/* check the status of our files */
411	if (ferror(f))
412	    warn("%s", URL);
413	if (ferror(of))
414	    warn("%s", path);
415	if (ferror(f) || ferror(of))
416	    goto failure;
417    }
418
419    /* did the transfer complete normally? */
420    if (us.size != -1 && count < us.size) {
421	warnx("%s appears to be truncated: %lld/%lld bytes",
422	      path, count, us.size);
423	goto failure_keep;
424    }
425
426 success:
427    r = 0;
428    goto done;
429 failure:
430    if (of && of != stdout && !R_flag && !r_flag)
431	if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
432	    unlink(path);
433 failure_keep:
434    r = -1;
435    goto done;
436 done:
437    if (f)
438	fclose(f);
439    if (of && of != stdout)
440	fclose(of);
441    if (url)
442	fetchFreeURL(url);
443    return r;
444}
445
446void
447usage(void)
448{
449    /* XXX badly out of synch */
450    fprintf(stderr,
451	    "Usage: fetch [-1AFHMPRabdlmnpqrstv] [-o outputfile] [-S bytes]\n"
452	    "             [-B bytes] [-T seconds] [-w seconds]\n"
453	    "             [-f file -h host [-c dir] | URL ...]\n"
454	);
455}
456
457
458#define PARSENUM(NAME, TYPE)		\
459int					\
460NAME(char *s, TYPE *v)			\
461{					\
462    *v = 0;				\
463    for (*v = 0; *s; s++)		\
464	if (isdigit(*s))		\
465	    *v = *v * 10 + *s - '0';	\
466	else				\
467	    return -1;			\
468    return 0;				\
469}
470
471PARSENUM(parseint, u_int)
472PARSENUM(parsesize, size_t)
473PARSENUM(parseoff, off_t)
474
475int
476main(int argc, char *argv[])
477{
478    struct stat sb;
479    struct sigaction sa;
480    char *p, *q, *s;
481    int c, e, r;
482
483    while ((c = getopt(argc, argv,
484		       "146AaB:bc:dFf:h:lHMmnPpo:qRrS:sT:tvw:")) != EOF)
485	switch (c) {
486	case '1':
487	    once_flag = 1;
488	    break;
489	case '4':
490	    family = PF_INET;
491	    break;
492	case '6':
493	    family = PF_INET6;
494	    break;
495	case 'A':
496	    A_flag = 1;
497	    break;
498	case 'a':
499	    a_flag = 1;
500	    break;
501	case 'B':
502	    if (parsesize(optarg, &B_size) == -1)
503		errx(1, "invalid buffer size");
504	    break;
505	case 'b':
506	    warnx("warning: the -b option is deprecated");
507	    b_flag = 1;
508	    break;
509	case 'c':
510	    c_dirname = optarg;
511	    break;
512	case 'd':
513	    d_flag = 1;
514	    break;
515	case 'F':
516	    F_flag = 1;
517	    break;
518	case 'f':
519	    f_filename = optarg;
520	    break;
521	case 'H':
522	    H_flag = 1;
523	    break;
524	case 'h':
525	    h_hostname = optarg;
526	    break;
527	case 'l':
528	    l_flag = 1;
529	    break;
530	case 'o':
531	    o_flag = 1;
532	    o_filename = optarg;
533	    break;
534	case 'M':
535	case 'm':
536	    if (r_flag)
537		errx(1, "the -m and -r flags are mutually exclusive");
538	    m_flag = 1;
539	    break;
540	case 'n':
541	    n_flag = 1;
542	    break;
543	case 'P':
544	case 'p':
545	    p_flag = 1;
546	    break;
547	case 'q':
548	    v_level = 0;
549	    break;
550	case 'R':
551	    R_flag = 1;
552	    break;
553	case 'r':
554	    if (m_flag)
555		errx(1, "the -m and -r flags are mutually exclusive");
556	    r_flag = 1;
557	    break;
558	case 'S':
559	    if (parseoff(optarg, &S_size) == -1)
560		errx(1, "invalid size");
561	    break;
562	case 's':
563	    s_flag = 1;
564	    break;
565	case 'T':
566	    if (parseint(optarg, &T_secs) == -1)
567		errx(1, "invalid timeout");
568	    break;
569	case 't':
570	    t_flag = 1;
571	    warnx("warning: the -t option is deprecated");
572	    break;
573	case 'v':
574	    v_level++;
575	    break;
576	case 'w':
577	    a_flag = 1;
578	    if (parseint(optarg, &w_secs) == -1)
579		errx(1, "invalid delay");
580	    break;
581	default:
582	    usage();
583	    exit(EX_USAGE);
584	}
585
586    argc -= optind;
587    argv += optind;
588
589    if (h_hostname || f_filename || c_dirname) {
590	if (!h_hostname || !f_filename || argc) {
591	    usage();
592	    exit(EX_USAGE);
593	}
594	/* XXX this is a hack. */
595	if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
596	    errx(1, "invalid hostname");
597	if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
598		     c_dirname ? c_dirname : "", f_filename) == -1)
599	    errx(1, strerror(ENOMEM));
600	argc++;
601    }
602
603    if (!argc) {
604	usage();
605	exit(EX_USAGE);
606    }
607
608    /* allocate buffer */
609    if (B_size < MINBUFSIZE)
610	B_size = MINBUFSIZE;
611    if ((buf = malloc(B_size)) == NULL)
612	errx(1, strerror(ENOMEM));
613
614    /* timeouts */
615    if ((s = getenv("FTP_TIMEOUT")) != NULL) {
616	if (parseint(s, &ftp_timeout) == -1) {
617	    warnx("FTP_TIMEOUT is not a positive integer");
618	    ftp_timeout = 0;
619	}
620    }
621    if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
622	if (parseint(s, &http_timeout) == -1) {
623	    warnx("HTTP_TIMEOUT is not a positive integer");
624	    http_timeout = 0;
625	}
626    }
627
628    /* signal handling */
629    sa.sa_flags = 0;
630    sa.sa_handler = sig_handler;
631    sigemptyset(&sa.sa_mask);
632    sigaction(SIGALRM, &sa, NULL);
633    sa.sa_flags = SA_RESETHAND;
634    sigaction(SIGINT, &sa, NULL);
635    fetchRestartCalls = 0;
636
637    /* output file */
638    if (o_flag) {
639	if (strcmp(o_filename, "-") == 0) {
640	    o_stdout = 1;
641	} else if (stat(o_filename, &sb) == -1) {
642	    if (errno == ENOENT) {
643		if (argc > 1)
644		    errx(EX_USAGE, "%s is not a directory", o_filename);
645	    } else {
646		err(EX_IOERR, "%s", o_filename);
647	    }
648	} else {
649	    if (sb.st_mode & S_IFDIR)
650		o_directory = 1;
651	}
652    }
653
654    /* check if output is to a tty (for progress report) */
655    v_tty = isatty(STDERR_FILENO);
656    r = 0;
657
658    while (argc) {
659	if ((p = strrchr(*argv, '/')) == NULL)
660	    p = *argv;
661	else
662	    p++;
663
664	if (!*p)
665	    p = "fetch.out";
666
667	fetchLastErrCode = 0;
668
669	if (o_flag) {
670	    if (o_stdout) {
671		e = fetch(*argv, "-");
672	    } else if (o_directory) {
673		asprintf(&q, "%s/%s", o_filename, p);
674		e = fetch(*argv, q);
675		free(q);
676	    } else {
677		e = fetch(*argv, o_filename);
678	    }
679	} else {
680	    e = fetch(*argv, p);
681	}
682
683	if (sigint)
684	    kill(getpid(), SIGINT);
685
686	if (e == 0 && once_flag)
687	    exit(0);
688
689	if (e) {
690	    r = 1;
691	    if ((fetchLastErrCode
692		 && fetchLastErrCode != FETCH_UNAVAIL
693		 && fetchLastErrCode != FETCH_MOVED
694		 && fetchLastErrCode != FETCH_URL
695		 && fetchLastErrCode != FETCH_RESOLV
696		 && fetchLastErrCode != FETCH_UNKNOWN)) {
697		if (w_secs) {
698		    if (v_level)
699			fprintf(stderr, "Waiting %d seconds before retrying\n",
700				w_secs);
701		    sleep(w_secs);
702		}
703		if (a_flag)
704		    continue;
705	    }
706	}
707
708	argc--, argv++;
709    }
710
711    exit(r);
712}
713