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