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