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