fetch.c revision 62245
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 62245 2000-06-29 08:39:29Z 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 */
53int	 d_flag;	/*    -d: direct connection */
54int	 F_flag;	/*    -F: restart without checking mtime  */
55char	*f_filename;	/*    -f: file to fetch */
56int	 H_flag;	/*    -H: use high port */
57char	*h_hostname;	/*    -h: host to fetch from */
58int	 l_flag;	/*    -l: link rather than copy file: URLs */
59int	 m_flag;	/* -[Mm]: set local timestamp to remote timestamp */
60int	 o_flag;	/*    -o: specify output file */
61int	 o_directory;	/*        output file is a directory */
62char	*o_filename;	/*        name of output file */
63int	 o_stdout;	/*        output file is stdout */
64int	 once_flag;	/*    -1: stop at first successful file */
65int	 p_flag = 1;	/* -[Pp]: use passive FTP */
66int	 R_flag;	/*    -R: don't delete partially transferred files */
67int	 r_flag;	/*    -r: restart previously interrupted transfer */
68u_int	 T_secs = 0;	/*    -T: transfer timeout in seconds */
69int	 s_flag;        /*    -s: show size, don't fetch */
70off_t	 S_size;        /*    -S: require size to match */
71int	 t_flag;	/*!   -t: workaround TCP bug */
72int	 v_level = 1;	/*    -v: verbosity level */
73int	 v_tty;		/*        stdout is a tty */
74u_int	 w_secs;	/*    -w: retry delay */
75int	 family = PF_UNSPEC;	/* -[46]: address family to use */
76
77
78u_int	 ftp_timeout;	/* default timeout for FTP transfers */
79u_int	 http_timeout;	/* default timeout for HTTP transfers */
80u_char	*buf;		/* transfer buffer */
81
82
83void
84sig_handler(int sig)
85{
86    errx(1, "Transfer timed out");
87}
88
89struct xferstat {
90    char		 name[40];
91    struct timeval	 start;
92    struct timeval	 end;
93    struct timeval	 last;
94    off_t		 size;
95    off_t		 offset;
96    off_t		 rcvd;
97};
98
99void
100stat_start(struct xferstat *xs, char *name, off_t size, off_t offset)
101{
102    snprintf(xs->name, sizeof xs->name, "%s", name);
103    xs->size = size;
104    xs->offset = offset;
105    if (v_level) {
106	fprintf(stderr, "Receiving %s", xs->name);
107	if (xs->size != -1)
108	    fprintf(stderr, " (%lld bytes)", xs->size - xs->offset);
109    }
110    gettimeofday(&xs->start, NULL);
111    xs->last = xs->start;
112}
113
114void
115stat_update(struct xferstat *xs, off_t rcvd)
116{
117    struct timeval now;
118
119    xs->rcvd = rcvd;
120
121    if (v_level <= 1 || !v_tty)
122	return;
123
124    gettimeofday(&now, NULL);
125    if (now.tv_sec <= xs->last.tv_sec)
126	return;
127    xs->last = now;
128
129    fprintf(stderr, "\rReceiving %s", xs->name);
130    if (xs->size == -1)
131	fprintf(stderr, ": %lld bytes", xs->rcvd - xs->offset);
132    else
133	fprintf(stderr, " (%lld bytes): %d%%", xs->size - xs->offset,
134		(int)((100.0 * xs->rcvd) / (xs->size - xs->offset)));
135}
136
137void
138stat_end(struct xferstat *xs)
139{
140    double delta;
141    double bps;
142
143    gettimeofday(&xs->end, NULL);
144
145    if (!v_level)
146	return;
147
148    fputc('\n', stderr);
149    delta = (xs->end.tv_sec + (xs->end.tv_usec / 1.e6))
150	- (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
151    fprintf(stderr, "%lld bytes transferred in %.1f seconds ",
152	    xs->size - xs->offset, delta);
153    bps = (xs->size - xs->offset) / delta;
154    if (bps > 1024*1024)
155	fprintf(stderr, "(%.2f MBps)\n", bps / (1024*1024));
156    else if (bps > 1024)
157	fprintf(stderr, "(%.2f kBps)\n", bps / 1024);
158    else
159	fprintf(stderr, "(%.2f Bps)\n", bps);
160}
161
162int
163fetch(char *URL, char *path)
164{
165    struct url *url;
166    struct url_stat us;
167    struct stat sb;
168    struct xferstat xs;
169    FILE *f, *of;
170    size_t size;
171    off_t count;
172    char flags[8];
173    int ch, n, r;
174    u_int timeout;
175
176    f = of = NULL;
177
178    /* parse URL */
179    if ((url = fetchParseURL(URL)) == NULL) {
180	warnx("%s: parse error", URL);
181	goto failure;
182    }
183
184    timeout = 0;
185    *flags = 0;
186
187    /* common flags */
188    if (v_level > 2)
189	strcat(flags, "v");
190    switch (family) {
191    case PF_INET:
192	strcat(flags, "4");
193	break;
194    case PF_INET6:
195	strcat(flags, "6");
196	break;
197    }
198
199    /* FTP specific flags */
200    if (strcmp(url->scheme, "ftp") == 0) {
201	if (p_flag)
202	    strcat(flags, "p");
203	if (d_flag)
204	    strcat(flags, "d");
205	if (H_flag)
206	    strcat(flags, "h");
207	timeout = T_secs ? T_secs : ftp_timeout;
208    }
209
210    /* HTTP specific flags */
211    if (strcmp(url->scheme, "http") == 0) {
212	if (d_flag)
213	    strcat(flags, "d");
214	if (A_flag)
215	    strcat(flags, "A");
216	timeout = T_secs ? T_secs : http_timeout;
217    }
218
219    /*
220     * Set the protocol timeout.
221     * This currently only works for FTP, so we still use
222     * alarm(timeout) further down.
223     */
224    fetchTimeout = timeout;
225
226    /* stat remote file */
227    alarm(timeout);
228    if (fetchStat(url, &us, flags) == -1)
229	warnx("%s: size not known", path);
230    alarm(timeout);
231
232    /* just print size */
233    if (s_flag) {
234	if (us.size == -1)
235	    printf("Unknown\n");
236	else
237	    printf("%lld\n", us.size);
238	goto success;
239    }
240
241    /* check that size is as expected */
242    if (S_size && us.size != -1 && us.size != S_size) {
243	warnx("%s: size mismatch: expected %lld, actual %lld",
244	      path, S_size, us.size);
245	goto failure;
246    }
247
248    /* symlink instead of copy */
249    if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
250	if (symlink(url->doc, path) == -1) {
251	    warn("%s: symlink()", path);
252	    goto failure;
253	}
254	goto success;
255    }
256
257    if (o_stdout) {
258	/* output to stdout */
259	of = stdout;
260    } else if (r_flag && us.size != -1 && stat(path, &sb) != -1
261	       && (F_flag || (us.mtime && sb.st_mtime == us.mtime))) {
262	/* output to file, restart aborted transfer */
263	if (us.size == sb.st_size)
264	    goto success;
265	else if (sb.st_size > us.size && truncate(path, us.size) == -1) {
266	    warn("%s: truncate()", path);
267	    goto failure;
268	}
269	if ((of = fopen(path, "a")) == NULL) {
270	    warn("%s: open()", path);
271	    goto failure;
272	}
273	url->offset = sb.st_size;
274    } else if (m_flag && us.size != -1 && stat(path, &sb) != -1) {
275	/* output to file, mirror mode */
276	warnx(" local: %lld bytes, mtime %ld", sb.st_size, sb.st_mtime);
277	warnx("remote: %lld bytes, mtime %ld", us.size, us.mtime);
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 (m_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 success:
386    r = 0;
387    goto done;
388 failure:
389    r = -1;
390    goto done;
391 done:
392    if (f)
393	fclose(f);
394    if (of && of != stdout)
395	fclose(of);
396    fetchFreeURL(url);
397    return r;
398}
399
400void
401usage(void)
402{
403    /* XXX badly out of synch */
404    fprintf(stderr,
405	    "Usage: fetch [-1AFHMPRabdlmnpqrstv] [-o outputfile] [-S bytes]\n"
406	    "             [-B bytes] [-T seconds] [-w seconds]\n"
407	    "             [-f file -h host [-c dir] | URL ...]\n"
408	);
409}
410
411
412#define PARSENUM(NAME, TYPE)		\
413int					\
414NAME(char *s, TYPE *v)			\
415{					\
416    *v = 0;				\
417    for (*v = 0; *s; s++)		\
418	if (isdigit(*s))		\
419	    *v = *v * 10 + *s - '0';	\
420	else				\
421	    return -1;			\
422    return 0;				\
423}
424
425PARSENUM(parseint, u_int)
426PARSENUM(parsesize, size_t)
427PARSENUM(parseoff, off_t)
428
429int
430main(int argc, char *argv[])
431{
432    struct stat sb;
433    char *p, *q, *s;
434    int c, e, r;
435
436    while ((c = getopt(argc, argv,
437		       "146AaB:bdFf:h:lHMmnPpo:qRrS:sT:tvw:")) != EOF)
438	switch (c) {
439	case '1':
440	    once_flag = 1;
441	    break;
442	case '4':
443	    family = PF_INET;
444	    break;
445	case '6':
446	    family = PF_INET6;
447	    break;
448	case 'A':
449	    A_flag = 1;
450	    break;
451	case 'a':
452	    a_flag = 1;
453	    break;
454	case 'B':
455	    if (parsesize(optarg, &B_size) == -1)
456		errx(1, "invalid buffer size");
457	    break;
458	case 'b':
459	    warnx("warning: the -b option is deprecated");
460	    b_flag = 1;
461	    break;
462	case 'd':
463	    d_flag = 1;
464	    break;
465	case 'F':
466	    F_flag = 1;
467	    break;
468	case 'f':
469	    f_filename = optarg;
470	    break;
471	case 'H':
472	    H_flag = 1;
473	    break;
474	case 'h':
475	    h_hostname = optarg;
476	    break;
477	case 'l':
478	    l_flag = 1;
479	    break;
480	case 'o':
481	    o_flag = 1;
482	    o_filename = optarg;
483	    break;
484	case 'M':
485	case 'm':
486	    m_flag = 1;
487	    break;
488	case 'n':
489	    m_flag = 0;
490	    break;
491	case 'P':
492	case 'p':
493	    p_flag = 1;
494	    break;
495	case 'q':
496	    v_level = 0;
497	    break;
498	case 'R':
499	    R_flag = 1;
500	    break;
501	case 'r':
502	    r_flag = 1;
503	    break;
504	case 'S':
505	    if (parseoff(optarg, &S_size) == -1)
506		errx(1, "invalid size");
507	    break;
508	case 's':
509	    s_flag = 1;
510	    break;
511	case 'T':
512	    if (parseint(optarg, &T_secs) == -1)
513		errx(1, "invalid timeout");
514	    break;
515	case 't':
516	    t_flag = 1;
517	    warnx("warning: the -t option is deprecated");
518	    break;
519	case 'v':
520	    v_level++;
521	    break;
522	case 'w':
523	    a_flag = 1;
524	    if (parseint(optarg, &w_secs) == -1)
525		errx(1, "invalid delay");
526	    break;
527	default:
528	    usage();
529	    exit(EX_USAGE);
530	}
531
532    argc -= optind;
533    argv += optind;
534
535    if (h_hostname || f_filename) {
536	if (!h_hostname || !f_filename || argc) {
537	    usage();
538	    exit(EX_USAGE);
539	}
540	/* XXX this is a hack. */
541	if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
542	    errx(1, "invalid hostname");
543	if (asprintf(argv, "ftp://%s/%s", h_hostname, f_filename) == -1)
544	    errx(1, strerror(ENOMEM));
545	argc++;
546    }
547
548    if (!argc) {
549	usage();
550	exit(EX_USAGE);
551    }
552
553    /* allocate buffer */
554    if (B_size < MINBUFSIZE)
555	B_size = MINBUFSIZE;
556    if ((buf = malloc(B_size)) == NULL)
557	errx(1, strerror(ENOMEM));
558
559    /* timeout handling */
560    signal(SIGALRM, sig_handler);
561    if ((s = getenv("FTP_TIMEOUT")) != NULL) {
562	if (parseint(s, &ftp_timeout) == -1) {
563	    warnx("FTP_TIMEOUT is not a positive integer");
564	    ftp_timeout = 0;
565	}
566    }
567    if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
568	if (parseint(s, &http_timeout) == -1) {
569	    warnx("HTTP_TIMEOUT is not a positive integer");
570	    http_timeout = 0;
571	}
572    }
573
574    /* output file */
575    if (o_flag) {
576	if (strcmp(o_filename, "-") == 0) {
577	    o_stdout = 1;
578	} else if (stat(o_filename, &sb) == -1) {
579	    if (errno == ENOENT) {
580		if (argc > 1)
581		    errx(EX_USAGE, "%s is not a directory", o_filename);
582	    } else {
583		err(EX_IOERR, "%s", o_filename);
584	    }
585	} else {
586	    if (sb.st_mode & S_IFDIR)
587		o_directory = 1;
588	}
589    }
590
591    /* check if output is to a tty (for progress report) */
592    v_tty = isatty(STDOUT_FILENO);
593    r = 0;
594
595    while (argc) {
596	if ((p = strrchr(*argv, '/')) == NULL)
597	    p = *argv;
598	else
599	    p++;
600
601	if (!*p)
602	    p = "fetch.out";
603
604	fetchLastErrCode = 0;
605
606	if (o_flag) {
607	    if (o_stdout) {
608		e = fetch(*argv, "-");
609	    } else if (o_directory) {
610		asprintf(&q, "%s/%s", o_filename, p);
611		e = fetch(*argv, q);
612		free(q);
613	    } else {
614		e = fetch(*argv, o_filename);
615	    }
616	} else {
617	    e = fetch(*argv, p);
618	}
619
620	if (e == 0 && once_flag)
621	    exit(0);
622
623	if (e) {
624	    r = 1;
625	    if ((fetchLastErrCode
626		 && fetchLastErrCode != FETCH_UNAVAIL
627		 && fetchLastErrCode != FETCH_MOVED
628		 && fetchLastErrCode != FETCH_URL
629		 && fetchLastErrCode != FETCH_RESOLV
630		 && fetchLastErrCode != FETCH_UNKNOWN)) {
631		if (w_secs) {
632		    if (v_level)
633			fprintf(stderr, "Waiting %d seconds before retrying\n", w_secs);
634		    sleep(w_secs);
635		}
636		if (a_flag)
637		    continue;
638		fprintf(stderr, "Skipping %s\n", *argv);
639	    }
640	}
641
642	argc--, argv++;
643    }
644
645    exit(r);
646}
647