]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - usr.bin/fetch/fetch.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / usr.bin / fetch / fetch.c
1 /*-
2  * Copyright (c) 2000-2004 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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36
37 #include <ctype.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <signal.h>
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <termios.h>
46 #include <unistd.h>
47
48 #include <fetch.h>
49
50 #define MINBUFSIZE      4096
51
52 /* Option flags */
53 int      A_flag;        /*    -A: do not follow 302 redirects */
54 int      a_flag;        /*    -a: auto retry */
55 off_t    B_size;        /*    -B: buffer size */
56 int      b_flag;        /*!   -b: workaround TCP bug */
57 char    *c_dirname;     /*    -c: remote directory */
58 int      d_flag;        /*    -d: direct connection */
59 int      F_flag;        /*    -F: restart without checking mtime  */
60 char    *f_filename;    /*    -f: file to fetch */
61 char    *h_hostname;    /*    -h: host to fetch from */
62 int      i_flag;        /*    -i: specify input file for mtime comparison */
63 char    *i_filename;    /*        name of input file */
64 int      l_flag;        /*    -l: link rather than copy file: URLs */
65 int      m_flag;        /* -[Mm]: mirror mode */
66 char    *N_filename;    /*    -N: netrc file name */
67 int      n_flag;        /*    -n: do not preserve modification time */
68 int      o_flag;        /*    -o: specify output file */
69 int      o_directory;   /*        output file is a directory */
70 char    *o_filename;    /*        name of output file */
71 int      o_stdout;      /*        output file is stdout */
72 int      once_flag;     /*    -1: stop at first successful file */
73 int      p_flag;        /* -[Pp]: use passive FTP */
74 int      R_flag;        /*    -R: don't delete partially transferred files */
75 int      r_flag;        /*    -r: restart previously interrupted transfer */
76 off_t    S_size;        /*    -S: require size to match */
77 int      s_flag;        /*    -s: show size, don't fetch */
78 long     T_secs = 120;  /*    -T: transfer timeout in seconds */
79 int      t_flag;        /*!   -t: workaround TCP bug */
80 int      U_flag;        /*    -U: do not use high ports */
81 int      v_level = 1;   /*    -v: verbosity level */
82 int      v_tty;         /*        stdout is a tty */
83 pid_t    pgrp;          /*        our process group */
84 long     w_secs;        /*    -w: retry delay */
85 int      family = PF_UNSPEC;    /* -[46]: address family to use */
86
87 int      sigalrm;       /* SIGALRM received */
88 int      siginfo;       /* SIGINFO received */
89 int      sigint;        /* SIGINT received */
90
91 long     ftp_timeout;   /* default timeout for FTP transfers */
92 long     http_timeout;  /* default timeout for HTTP transfers */
93 char    *buf;           /* transfer buffer */
94
95
96 /*
97  * Signal handler
98  */
99 static void
100 sig_handler(int sig)
101 {
102         switch (sig) {
103         case SIGALRM:
104                 sigalrm = 1;
105                 break;
106         case SIGINFO:
107                 siginfo = 1;
108                 break;
109         case SIGINT:
110                 sigint = 1;
111                 break;
112         }
113 }
114
115 struct xferstat {
116         char             name[64];
117         struct timeval   start;
118         struct timeval   last;
119         off_t            size;
120         off_t            offset;
121         off_t            rcvd;
122 };
123
124 /*
125  * Compute and display ETA
126  */
127 static const char *
128 stat_eta(struct xferstat *xs)
129 {
130         static char str[16];
131         long elapsed, eta;
132         off_t received, expected;
133
134         elapsed = xs->last.tv_sec - xs->start.tv_sec;
135         received = xs->rcvd - xs->offset;
136         expected = xs->size - xs->rcvd;
137         eta = (long)((double)elapsed * expected / received);
138         if (eta > 3600)
139                 snprintf(str, sizeof str, "%02ldh%02ldm",
140                     eta / 3600, (eta % 3600) / 60);
141         else
142                 snprintf(str, sizeof str, "%02ldm%02lds",
143                     eta / 60, eta % 60);
144         return (str);
145 }
146
147 /*
148  * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
149  */
150 static const char *prefixes = " kMGTP";
151 static const char *
152 stat_bytes(off_t bytes)
153 {
154         static char str[16];
155         const char *prefix = prefixes;
156
157         while (bytes > 9999 && prefix[1] != '\0') {
158                 bytes /= 1024;
159                 prefix++;
160         }
161         snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
162         return (str);
163 }
164
165 /*
166  * Compute and display transfer rate
167  */
168 static const char *
169 stat_bps(struct xferstat *xs)
170 {
171         static char str[16];
172         double delta, bps;
173
174         delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
175             - (xs->start.tv_sec + (xs->start.tv_usec / 1.e6));
176         if (delta == 0.0) {
177                 snprintf(str, sizeof str, "?? Bps");
178         } else {
179                 bps = (xs->rcvd - xs->offset) / delta;
180                 snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
181         }
182         return (str);
183 }
184
185 /*
186  * Update the stats display
187  */
188 static void
189 stat_display(struct xferstat *xs, int force)
190 {
191         struct timeval now;
192         int ctty_pgrp;
193
194         /* check if we're the foreground process */
195         if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
196             (pid_t)ctty_pgrp != pgrp)
197                 return;
198
199         gettimeofday(&now, NULL);
200         if (!force && now.tv_sec <= xs->last.tv_sec)
201                 return;
202         xs->last = now;
203
204         fprintf(stderr, "\r%-46.46s", xs->name);
205         if (xs->size <= 0) {
206                 setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
207                 fprintf(stderr, "        %s", stat_bytes(xs->rcvd));
208         } else {
209                 setproctitle("%s [%d%% of %s]", xs->name,
210                     (int)((100.0 * xs->rcvd) / xs->size),
211                     stat_bytes(xs->size));
212                 fprintf(stderr, "%3d%% of %s",
213                     (int)((100.0 * xs->rcvd) / xs->size),
214                     stat_bytes(xs->size));
215         }
216         fprintf(stderr, " %s", stat_bps(xs));
217         if (xs->size > 0 && xs->rcvd > 0 &&
218             xs->last.tv_sec >= xs->start.tv_sec + 10)
219                 fprintf(stderr, " %s", stat_eta(xs));
220 }
221
222 /*
223  * Initialize the transfer statistics
224  */
225 static void
226 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
227 {
228         snprintf(xs->name, sizeof xs->name, "%s", name);
229         gettimeofday(&xs->start, NULL);
230         xs->last.tv_sec = xs->last.tv_usec = 0;
231         xs->size = size;
232         xs->offset = offset;
233         xs->rcvd = offset;
234         if (v_tty && v_level > 0)
235                 stat_display(xs, 1);
236         else if (v_level > 0)
237                 fprintf(stderr, "%-46s", xs->name);
238 }
239
240 /*
241  * Update the transfer statistics
242  */
243 static void
244 stat_update(struct xferstat *xs, off_t rcvd)
245 {
246         xs->rcvd = rcvd;
247         if (v_tty && v_level > 0)
248                 stat_display(xs, 0);
249 }
250
251 /*
252  * Finalize the transfer statistics
253  */
254 static void
255 stat_end(struct xferstat *xs)
256 {
257         gettimeofday(&xs->last, NULL);
258         if (v_tty && v_level > 0) {
259                 stat_display(xs, 1);
260                 putc('\n', stderr);
261         } else if (v_level > 0) {
262                 fprintf(stderr, "        %s %s\n",
263                     stat_bytes(xs->size), stat_bps(xs));
264         }
265 }
266
267 /*
268  * Ask the user for authentication details
269  */
270 static int
271 query_auth(struct url *URL)
272 {
273         struct termios tios;
274         tcflag_t saved_flags;
275         int i, nopwd;
276
277         fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
278             URL->scheme, URL->host, URL->port);
279
280         fprintf(stderr, "Login: ");
281         if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
282                 return (-1);
283         for (i = strlen(URL->user); i >= 0; --i)
284                 if (URL->user[i] == '\r' || URL->user[i] == '\n')
285                         URL->user[i] = '\0';
286
287         fprintf(stderr, "Password: ");
288         if (tcgetattr(STDIN_FILENO, &tios) == 0) {
289                 saved_flags = tios.c_lflag;
290                 tios.c_lflag &= ~ECHO;
291                 tios.c_lflag |= ECHONL|ICANON;
292                 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
293                 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
294                 tios.c_lflag = saved_flags;
295                 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
296         } else {
297                 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
298         }
299         if (nopwd)
300                 return (-1);
301         for (i = strlen(URL->pwd); i >= 0; --i)
302                 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
303                         URL->pwd[i] = '\0';
304
305         return (0);
306 }
307
308 /*
309  * Fetch a file
310  */
311 static int
312 fetch(char *URL, const char *path)
313 {
314         struct url *url;
315         struct url_stat us;
316         struct stat sb, nsb;
317         struct xferstat xs;
318         FILE *f, *of;
319         size_t size, wr;
320         off_t count;
321         char flags[8];
322         const char *slash;
323         char *tmppath;
324         int r;
325         unsigned timeout;
326         char *ptr;
327
328         f = of = NULL;
329         tmppath = NULL;
330
331         timeout = 0;
332         *flags = 0;
333         count = 0;
334
335         /* set verbosity level */
336         if (v_level > 1)
337                 strcat(flags, "v");
338         if (v_level > 2)
339                 fetchDebug = 1;
340
341         /* parse URL */
342         if ((url = fetchParseURL(URL)) == NULL) {
343                 warnx("%s: parse error", URL);
344                 goto failure;
345         }
346
347         /* if no scheme was specified, take a guess */
348         if (!*url->scheme) {
349                 if (!*url->host)
350                         strcpy(url->scheme, SCHEME_FILE);
351                 else if (strncasecmp(url->host, "ftp.", 4) == 0)
352                         strcpy(url->scheme, SCHEME_FTP);
353                 else if (strncasecmp(url->host, "www.", 4) == 0)
354                         strcpy(url->scheme, SCHEME_HTTP);
355         }
356
357         /* common flags */
358         switch (family) {
359         case PF_INET:
360                 strcat(flags, "4");
361                 break;
362         case PF_INET6:
363                 strcat(flags, "6");
364                 break;
365         }
366
367         /* FTP specific flags */
368         if (strcmp(url->scheme, SCHEME_FTP) == 0) {
369                 if (p_flag)
370                         strcat(flags, "p");
371                 if (d_flag)
372                         strcat(flags, "d");
373                 if (U_flag)
374                         strcat(flags, "l");
375                 timeout = T_secs ? T_secs : ftp_timeout;
376         }
377
378         /* HTTP specific flags */
379         if (strcmp(url->scheme, SCHEME_HTTP) == 0) {
380                 if (d_flag)
381                         strcat(flags, "d");
382                 if (A_flag)
383                         strcat(flags, "A");
384                 timeout = T_secs ? T_secs : http_timeout;
385                 if (i_flag) {
386                         if (stat(i_filename, &sb)) {
387                                 warn("%s: stat()", i_filename);
388                                 goto failure;
389                         }
390                         url->ims_time = sb.st_mtime;
391                         strcat(flags, "i");
392                 }
393         }
394
395         /* set the protocol timeout. */
396         fetchTimeout = timeout;
397
398         /* just print size */
399         if (s_flag) {
400                 if (timeout)
401                         alarm(timeout);
402                 r = fetchStat(url, &us, flags);
403                 if (timeout)
404                         alarm(0);
405                 if (sigalrm || sigint)
406                         goto signal;
407                 if (r == -1) {
408                         warnx("%s", fetchLastErrString);
409                         goto failure;
410                 }
411                 if (us.size == -1)
412                         printf("Unknown\n");
413                 else
414                         printf("%jd\n", (intmax_t)us.size);
415                 goto success;
416         }
417
418         /*
419          * If the -r flag was specified, we have to compare the local
420          * and remote files, so we should really do a fetchStat()
421          * first, but I know of at least one HTTP server that only
422          * sends the content size in response to GET requests, and
423          * leaves it out of replies to HEAD requests.  Also, in the
424          * (frequent) case that the local and remote files match but
425          * the local file is truncated, we have sufficient information
426          * before the compare to issue a correct request.  Therefore,
427          * we always issue a GET request as if we were sure the local
428          * file was a truncated copy of the remote file; we can drop
429          * the connection later if we change our minds.
430          */
431         sb.st_size = -1;
432         if (!o_stdout) {
433                 r = stat(path, &sb);
434                 if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
435                         url->offset = sb.st_size;
436                 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
437                         /*
438                          * Whatever value sb.st_size has now is either
439                          * wrong (if stat(2) failed) or irrelevant (if the
440                          * path does not refer to a regular file)
441                          */
442                         sb.st_size = -1;
443                 }
444                 if (r == -1 && errno != ENOENT) {
445                         warnx("%s: stat()", path);
446                         goto failure;
447                 }
448         }
449
450         /* start the transfer */
451         if (timeout)
452                 alarm(timeout);
453         f = fetchXGet(url, &us, flags);
454         if (timeout)
455                 alarm(0);
456         if (sigalrm || sigint)
457                 goto signal;
458         if (f == NULL) {
459                 warnx("%s: %s", URL, fetchLastErrString);
460                 if (i_flag && strcmp(url->scheme, SCHEME_HTTP) == 0
461                     && fetchLastErrCode == FETCH_OK
462                     && strcmp(fetchLastErrString, "Not Modified") == 0) {
463                         /* HTTP Not Modified Response, return OK. */
464                         r = 0;
465                         goto done;
466                 } else
467                         goto failure;
468         }
469         if (sigint)
470                 goto signal;
471
472         /* check that size is as expected */
473         if (S_size) {
474                 if (us.size == -1) {
475                         warnx("%s: size unknown", URL);
476                 } else if (us.size != S_size) {
477                         warnx("%s: size mismatch: expected %jd, actual %jd",
478                             URL, (intmax_t)S_size, (intmax_t)us.size);
479                         goto failure;
480                 }
481         }
482
483         /* symlink instead of copy */
484         if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
485                 if (symlink(url->doc, path) == -1) {
486                         warn("%s: symlink()", path);
487                         goto failure;
488                 }
489                 goto success;
490         }
491
492         if (us.size == -1 && !o_stdout && v_level > 0)
493                 warnx("%s: size of remote file is not known", URL);
494         if (v_level > 1) {
495                 if (sb.st_size != -1)
496                         fprintf(stderr, "local size / mtime: %jd / %ld\n",
497                             (intmax_t)sb.st_size, (long)sb.st_mtime);
498                 if (us.size != -1)
499                         fprintf(stderr, "remote size / mtime: %jd / %ld\n",
500                             (intmax_t)us.size, (long)us.mtime);
501         }
502
503         /* open output file */
504         if (o_stdout) {
505                 /* output to stdout */
506                 of = stdout;
507         } else if (r_flag && sb.st_size != -1) {
508                 /* resume mode, local file exists */
509                 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
510                         /* no match! have to refetch */
511                         fclose(f);
512                         /* if precious, warn the user and give up */
513                         if (R_flag) {
514                                 warnx("%s: local modification time "
515                                     "does not match remote", path);
516                                 goto failure_keep;
517                         }
518                 } else if (us.size != -1) {
519                         if (us.size == sb.st_size)
520                                 /* nothing to do */
521                                 goto success;
522                         if (sb.st_size > us.size) {
523                                 /* local file too long! */
524                                 warnx("%s: local file (%jd bytes) is longer "
525                                     "than remote file (%jd bytes)", path,
526                                     (intmax_t)sb.st_size, (intmax_t)us.size);
527                                 goto failure;
528                         }
529                         /* we got it, open local file */
530                         if ((of = fopen(path, "a")) == NULL) {
531                                 warn("%s: fopen()", path);
532                                 goto failure;
533                         }
534                         /* check that it didn't move under our feet */
535                         if (fstat(fileno(of), &nsb) == -1) {
536                                 /* can't happen! */
537                                 warn("%s: fstat()", path);
538                                 goto failure;
539                         }
540                         if (nsb.st_dev != sb.st_dev ||
541                             nsb.st_ino != nsb.st_ino ||
542                             nsb.st_size != sb.st_size) {
543                                 warnx("%s: file has changed", URL);
544                                 fclose(of);
545                                 of = NULL;
546                                 sb = nsb;
547                         }
548                 }
549         } else if (m_flag && sb.st_size != -1) {
550                 /* mirror mode, local file exists */
551                 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
552                         goto success;
553         }
554
555         if (of == NULL) {
556                 /*
557                  * We don't yet have an output file; either this is a
558                  * vanilla run with no special flags, or the local and
559                  * remote files didn't match.
560                  */
561
562                 if (url->offset > 0) {
563                         /*
564                          * We tried to restart a transfer, but for
565                          * some reason gave up - so we have to restart
566                          * from scratch if we want the whole file
567                          */
568                         url->offset = 0;
569                         if ((f = fetchXGet(url, &us, flags)) == NULL) {
570                                 warnx("%s: %s", URL, fetchLastErrString);
571                                 goto failure;
572                         }
573                         if (sigint)
574                                 goto signal;
575                 }
576
577                 /* construct a temp file name */
578                 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
579                         if ((slash = strrchr(path, '/')) == NULL)
580                                 slash = path;
581                         else
582                                 ++slash;
583                         asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
584                             (int)(slash - path), path, slash);
585                         if (tmppath != NULL) {
586                                 mkstemps(tmppath, strlen(slash) + 1);
587                                 of = fopen(tmppath, "w");
588                                 chown(tmppath, sb.st_uid, sb.st_gid);
589                                 chmod(tmppath, sb.st_mode & ALLPERMS);
590                         }
591                 }
592                 if (of == NULL)
593                         of = fopen(path, "w");
594                 if (of == NULL) {
595                         warn("%s: open()", path);
596                         goto failure;
597                 }
598         }
599         count = url->offset;
600
601         /* start the counter */
602         stat_start(&xs, path, us.size, count);
603
604         sigalrm = siginfo = sigint = 0;
605
606         /* suck in the data */
607         signal(SIGINFO, sig_handler);
608         while (!sigint) {
609                 if (us.size != -1 && us.size - count < B_size &&
610                     us.size - count >= 0)
611                         size = us.size - count;
612                 else
613                         size = B_size;
614                 if (siginfo) {
615                         stat_end(&xs);
616                         siginfo = 0;
617                 }
618                 if ((size = fread(buf, 1, size, f)) == 0) {
619                         if (ferror(f) && errno == EINTR && !sigint)
620                                 clearerr(f);
621                         else
622                                 break;
623                 }
624                 stat_update(&xs, count += size);
625                 for (ptr = buf; size > 0; ptr += wr, size -= wr)
626                         if ((wr = fwrite(ptr, 1, size, of)) < size) {
627                                 if (ferror(of) && errno == EINTR && !sigint)
628                                         clearerr(of);
629                                 else
630                                         break;
631                         }
632                 if (size != 0)
633                         break;
634         }
635         if (!sigalrm)
636                 sigalrm = ferror(f) && errno == ETIMEDOUT;
637         signal(SIGINFO, SIG_DFL);
638
639         stat_end(&xs);
640
641         /*
642          * If the transfer timed out or was interrupted, we still want to
643          * set the mtime in case the file is not removed (-r or -R) and
644          * the user later restarts the transfer.
645          */
646  signal:
647         /* set mtime of local file */
648         if (!n_flag && us.mtime && !o_stdout && of != NULL &&
649             (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
650                 struct timeval tv[2];
651
652                 fflush(of);
653                 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
654                 tv[1].tv_sec = (long)us.mtime;
655                 tv[0].tv_usec = tv[1].tv_usec = 0;
656                 if (utimes(tmppath ? tmppath : path, tv))
657                         warn("%s: utimes()", tmppath ? tmppath : path);
658         }
659
660         /* timed out or interrupted? */
661         if (sigalrm)
662                 warnx("transfer timed out");
663         if (sigint) {
664                 warnx("transfer interrupted");
665                 goto failure;
666         }
667
668         /* timeout / interrupt before connection completley established? */
669         if (f == NULL)
670                 goto failure;
671
672         if (!sigalrm) {
673                 /* check the status of our files */
674                 if (ferror(f))
675                         warn("%s", URL);
676                 if (ferror(of))
677                         warn("%s", path);
678                 if (ferror(f) || ferror(of))
679                         goto failure;
680         }
681
682         /* did the transfer complete normally? */
683         if (us.size != -1 && count < us.size) {
684                 warnx("%s appears to be truncated: %jd/%jd bytes",
685                     path, (intmax_t)count, (intmax_t)us.size);
686                 goto failure_keep;
687         }
688
689         /*
690          * If the transfer timed out and we didn't know how much to
691          * expect, assume the worst (i.e. we didn't get all of it)
692          */
693         if (sigalrm && us.size == -1) {
694                 warnx("%s may be truncated", path);
695                 goto failure_keep;
696         }
697
698  success:
699         r = 0;
700         if (tmppath != NULL && rename(tmppath, path) == -1) {
701                 warn("%s: rename()", path);
702                 goto failure_keep;
703         }
704         goto done;
705  failure:
706         if (of && of != stdout && !R_flag && !r_flag)
707                 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
708                         unlink(tmppath ? tmppath : path);
709         if (R_flag && tmppath != NULL && sb.st_size == -1)
710                 rename(tmppath, path); /* ignore errors here */
711  failure_keep:
712         r = -1;
713         goto done;
714  done:
715         if (f)
716                 fclose(f);
717         if (of && of != stdout)
718                 fclose(of);
719         if (url)
720                 fetchFreeURL(url);
721         if (tmppath != NULL)
722                 free(tmppath);
723         return (r);
724 }
725
726 static void
727 usage(void)
728 {
729         fprintf(stderr, "%s\n%s\n%s\n%s\n",
730 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
731 "       [-T seconds] [-w seconds] [-i file] URL ...",
732 "       fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
733 "       [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
734 }
735
736
737 /*
738  * Entry point
739  */
740 int
741 main(int argc, char *argv[])
742 {
743         struct stat sb;
744         struct sigaction sa;
745         const char *p, *s;
746         char *end, *q;
747         int c, e, r;
748
749         while ((c = getopt(argc, argv,
750             "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
751                 switch (c) {
752                 case '1':
753                         once_flag = 1;
754                         break;
755                 case '4':
756                         family = PF_INET;
757                         break;
758                 case '6':
759                         family = PF_INET6;
760                         break;
761                 case 'A':
762                         A_flag = 1;
763                         break;
764                 case 'a':
765                         a_flag = 1;
766                         break;
767                 case 'B':
768                         B_size = (off_t)strtol(optarg, &end, 10);
769                         if (*optarg == '\0' || *end != '\0')
770                                 errx(1, "invalid buffer size (%s)", optarg);
771                         break;
772                 case 'b':
773                         warnx("warning: the -b option is deprecated");
774                         b_flag = 1;
775                         break;
776                 case 'c':
777                         c_dirname = optarg;
778                         break;
779                 case 'd':
780                         d_flag = 1;
781                         break;
782                 case 'F':
783                         F_flag = 1;
784                         break;
785                 case 'f':
786                         f_filename = optarg;
787                         break;
788                 case 'H':
789                         warnx("the -H option is now implicit, "
790                             "use -U to disable");
791                         break;
792                 case 'h':
793                         h_hostname = optarg;
794                         break;
795                 case 'i':
796                         i_flag = 1;
797                         i_filename = optarg;
798                         break;
799                 case 'l':
800                         l_flag = 1;
801                         break;
802                 case 'o':
803                         o_flag = 1;
804                         o_filename = optarg;
805                         break;
806                 case 'M':
807                 case 'm':
808                         if (r_flag)
809                                 errx(1, "the -m and -r flags "
810                                     "are mutually exclusive");
811                         m_flag = 1;
812                         break;
813                 case 'N':
814                         N_filename = optarg;
815                         break;
816                 case 'n':
817                         n_flag = 1;
818                         break;
819                 case 'P':
820                 case 'p':
821                         p_flag = 1;
822                         break;
823                 case 'q':
824                         v_level = 0;
825                         break;
826                 case 'R':
827                         R_flag = 1;
828                         break;
829                 case 'r':
830                         if (m_flag)
831                                 errx(1, "the -m and -r flags "
832                                     "are mutually exclusive");
833                         r_flag = 1;
834                         break;
835                 case 'S':
836                         S_size = (off_t)strtol(optarg, &end, 10);
837                         if (*optarg == '\0' || *end != '\0')
838                                 errx(1, "invalid size (%s)", optarg);
839                         break;
840                 case 's':
841                         s_flag = 1;
842                         break;
843                 case 'T':
844                         T_secs = strtol(optarg, &end, 10);
845                         if (*optarg == '\0' || *end != '\0')
846                                 errx(1, "invalid timeout (%s)", optarg);
847                         break;
848                 case 't':
849                         t_flag = 1;
850                         warnx("warning: the -t option is deprecated");
851                         break;
852                 case 'U':
853                         U_flag = 1;
854                         break;
855                 case 'v':
856                         v_level++;
857                         break;
858                 case 'w':
859                         a_flag = 1;
860                         w_secs = strtol(optarg, &end, 10);
861                         if (*optarg == '\0' || *end != '\0')
862                                 errx(1, "invalid delay (%s)", optarg);
863                         break;
864                 default:
865                         usage();
866                         exit(1);
867                 }
868
869         argc -= optind;
870         argv += optind;
871
872         if (h_hostname || f_filename || c_dirname) {
873                 if (!h_hostname || !f_filename || argc) {
874                         usage();
875                         exit(1);
876                 }
877                 /* XXX this is a hack. */
878                 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
879                         errx(1, "invalid hostname");
880                 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
881                     c_dirname ? c_dirname : "", f_filename) == -1)
882                         errx(1, "%s", strerror(ENOMEM));
883                 argc++;
884         }
885
886         if (!argc) {
887                 usage();
888                 exit(1);
889         }
890
891         /* allocate buffer */
892         if (B_size < MINBUFSIZE)
893                 B_size = MINBUFSIZE;
894         if ((buf = malloc(B_size)) == NULL)
895                 errx(1, "%s", strerror(ENOMEM));
896
897         /* timeouts */
898         if ((s = getenv("FTP_TIMEOUT")) != NULL) {
899                 ftp_timeout = strtol(s, &end, 10);
900                 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
901                         warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
902                         ftp_timeout = 0;
903                 }
904         }
905         if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
906                 http_timeout = strtol(s, &end, 10);
907                 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
908                         warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
909                         http_timeout = 0;
910                 }
911         }
912
913         /* signal handling */
914         sa.sa_flags = 0;
915         sa.sa_handler = sig_handler;
916         sigemptyset(&sa.sa_mask);
917         sigaction(SIGALRM, &sa, NULL);
918         sa.sa_flags = SA_RESETHAND;
919         sigaction(SIGINT, &sa, NULL);
920         fetchRestartCalls = 0;
921
922         /* output file */
923         if (o_flag) {
924                 if (strcmp(o_filename, "-") == 0) {
925                         o_stdout = 1;
926                 } else if (stat(o_filename, &sb) == -1) {
927                         if (errno == ENOENT) {
928                                 if (argc > 1)
929                                         errx(1, "%s is not a directory",
930                                             o_filename);
931                         } else {
932                                 err(1, "%s", o_filename);
933                         }
934                 } else {
935                         if (sb.st_mode & S_IFDIR)
936                                 o_directory = 1;
937                 }
938         }
939
940         /* check if output is to a tty (for progress report) */
941         v_tty = isatty(STDERR_FILENO);
942         if (v_tty)
943                 pgrp = getpgrp();
944
945         r = 0;
946
947         /* authentication */
948         if (v_tty)
949                 fetchAuthMethod = query_auth;
950         if (N_filename != NULL)
951                 setenv("NETRC", N_filename, 1);
952
953         while (argc) {
954                 if ((p = strrchr(*argv, '/')) == NULL)
955                         p = *argv;
956                 else
957                         p++;
958
959                 if (!*p)
960                         p = "fetch.out";
961
962                 fetchLastErrCode = 0;
963
964                 if (o_flag) {
965                         if (o_stdout) {
966                                 e = fetch(*argv, "-");
967                         } else if (o_directory) {
968                                 asprintf(&q, "%s/%s", o_filename, p);
969                                 e = fetch(*argv, q);
970                                 free(q);
971                         } else {
972                                 e = fetch(*argv, o_filename);
973                         }
974                 } else {
975                         e = fetch(*argv, p);
976                 }
977
978                 if (sigint)
979                         kill(getpid(), SIGINT);
980
981                 if (e == 0 && once_flag)
982                         exit(0);
983
984                 if (e) {
985                         r = 1;
986                         if ((fetchLastErrCode
987                             && fetchLastErrCode != FETCH_UNAVAIL
988                             && fetchLastErrCode != FETCH_MOVED
989                             && fetchLastErrCode != FETCH_URL
990                             && fetchLastErrCode != FETCH_RESOLV
991                             && fetchLastErrCode != FETCH_UNKNOWN)) {
992                                 if (w_secs && v_level)
993                                         fprintf(stderr, "Waiting %ld seconds "
994                                             "before retrying\n", w_secs);
995                                 if (w_secs)
996                                         sleep(w_secs);
997                                 if (a_flag)
998                                         continue;
999                         }
1000                 }
1001
1002                 argc--, argv++;
1003         }
1004
1005         exit(r);
1006 }