merge
[dragonfly.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  * $FreeBSD: src/usr.bin/fetch/fetch.c,v 1.84 2009/01/17 13:34:56 des Exp $
29  */
30
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <signal.h>
40 #include <stdint.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <termios.h>
45 #include <unistd.h>
46
47 #include <fetch.h>
48
49 #define MINBUFSIZE      4096
50 #define TIMEOUT         120
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;        /*    -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 = TIMEOUT;         /* default timeout for FTP transfers */
92 long     http_timeout = 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, readcnt, 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 == 0) {
349                 if (*url->host == 0)
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             strcmp(url->scheme, SCHEME_HTTPS) == 0) {
381                 if (d_flag)
382                         strcat(flags, "d");
383                 if (A_flag)
384                         strcat(flags, "A");
385                 timeout = T_secs ? T_secs : http_timeout;
386                 if (i_flag) {
387                         if (stat(i_filename, &sb)) {
388                                 warn("%s: stat()", i_filename);
389                                 goto failure;
390                         }
391                         url->ims_time = sb.st_mtime;
392                         strcat(flags, "i");
393                 }
394         }
395
396         /* set the protocol timeout. */
397         fetchTimeout = timeout;
398
399         /* just print size */
400         if (s_flag) {
401                 if (timeout)
402                         alarm(timeout);
403                 r = fetchStat(url, &us, flags);
404                 if (timeout)
405                         alarm(0);
406                 if (sigalrm || sigint)
407                         goto signal;
408                 if (r == -1) {
409                         warnx("%s", fetchLastErrString);
410                         goto failure;
411                 }
412                 if (us.size == -1)
413                         printf("Unknown\n");
414                 else
415                         printf("%jd\n", (intmax_t)us.size);
416                 goto success;
417         }
418
419         /*
420          * If the -r flag was specified, we have to compare the local
421          * and remote files, so we should really do a fetchStat()
422          * first, but I know of at least one HTTP server that only
423          * sends the content size in response to GET requests, and
424          * leaves it out of replies to HEAD requests.  Also, in the
425          * (frequent) case that the local and remote files match but
426          * the local file is truncated, we have sufficient information
427          * before the compare to issue a correct request.  Therefore,
428          * we always issue a GET request as if we were sure the local
429          * file was a truncated copy of the remote file; we can drop
430          * the connection later if we change our minds.
431          */
432         sb.st_size = -1;
433         if (!o_stdout) {
434                 r = stat(path, &sb);
435                 if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
436                         url->offset = sb.st_size;
437                 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
438                         /*
439                          * Whatever value sb.st_size has now is either
440                          * wrong (if stat(2) failed) or irrelevant (if the
441                          * path does not refer to a regular file)
442                          */
443                         sb.st_size = -1;
444                 }
445                 if (r == -1 && errno != ENOENT) {
446                         warnx("%s: stat()", path);
447                         goto failure;
448                 }
449         }
450
451         /* start the transfer */
452         if (timeout)
453                 alarm(timeout);
454         f = fetchXGet(url, &us, flags);
455         if (timeout)
456                 alarm(0);
457         if (sigalrm || sigint)
458                 goto signal;
459         if (f == NULL) {
460                 warnx("%s: %s", URL, fetchLastErrString);
461                 if (i_flag && strcmp(url->scheme, SCHEME_HTTP) == 0
462                     && fetchLastErrCode == FETCH_OK
463                     && strcmp(fetchLastErrString, "Not Modified") == 0) {
464                         /* HTTP Not Modified Response, return OK. */
465                         r = 0;
466                         goto done;
467                 } else
468                         goto failure;
469         }
470         if (sigint)
471                 goto signal;
472
473         /* check that size is as expected */
474         if (S_size) {
475                 if (us.size == -1) {
476                         warnx("%s: size unknown", URL);
477                 } else if (us.size != S_size) {
478                         warnx("%s: size mismatch: expected %jd, actual %jd",
479                             URL, (intmax_t)S_size, (intmax_t)us.size);
480                         goto failure;
481                 }
482         }
483
484         /* symlink instead of copy */
485         if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
486                 if (symlink(url->doc, path) == -1) {
487                         warn("%s: symlink()", path);
488                         goto failure;
489                 }
490                 goto success;
491         }
492
493         if (us.size == -1 && !o_stdout && v_level > 0)
494                 warnx("%s: size of remote file is not known", URL);
495         if (v_level > 1) {
496                 if (sb.st_size != -1)
497                         fprintf(stderr, "local size / mtime: %jd / %ld\n",
498                             (intmax_t)sb.st_size, (long)sb.st_mtime);
499                 if (us.size != -1)
500                         fprintf(stderr, "remote size / mtime: %jd / %ld\n",
501                             (intmax_t)us.size, (long)us.mtime);
502         }
503
504         /* open output file */
505         if (o_stdout) {
506                 /* output to stdout */
507                 of = stdout;
508         } else if (r_flag && sb.st_size != -1) {
509                 /* resume mode, local file exists */
510                 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
511                         /* no match! have to refetch */
512                         fclose(f);
513                         /* if precious, warn the user and give up */
514                         if (R_flag) {
515                                 warnx("%s: local modification time "
516                                     "does not match remote", path);
517                                 goto failure_keep;
518                         }
519                 } else if (us.size != -1) {
520                         if (us.size == sb.st_size)
521                                 /* nothing to do */
522                                 goto success;
523                         if (sb.st_size > us.size) {
524                                 /* local file too long! */
525                                 warnx("%s: local file (%jd bytes) is longer "
526                                     "than remote file (%jd bytes)", path,
527                                     (intmax_t)sb.st_size, (intmax_t)us.size);
528                                 goto failure;
529                         }
530                         /* we got it, open local file */
531                         if ((of = fopen(path, "a")) == NULL) {
532                                 warn("%s: fopen()", path);
533                                 goto failure;
534                         }
535                         /* check that it didn't move under our feet */
536                         if (fstat(fileno(of), &nsb) == -1) {
537                                 /* can't happen! */
538                                 warn("%s: fstat()", path);
539                                 goto failure;
540                         }
541                         if (nsb.st_dev != sb.st_dev ||
542                             nsb.st_ino != nsb.st_ino ||
543                             nsb.st_size != sb.st_size) {
544                                 warnx("%s: file has changed", URL);
545                                 fclose(of);
546                                 of = NULL;
547                                 sb = nsb;
548                         }
549                 }
550         } else if (m_flag && sb.st_size != -1) {
551                 /* mirror mode, local file exists */
552                 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
553                         goto success;
554         }
555
556         if (of == NULL) {
557                 /*
558                  * We don't yet have an output file; either this is a
559                  * vanilla run with no special flags, or the local and
560                  * remote files didn't match.
561                  */
562
563                 if (url->offset > 0) {
564                         /*
565                          * We tried to restart a transfer, but for
566                          * some reason gave up - so we have to restart
567                          * from scratch if we want the whole file
568                          */
569                         url->offset = 0;
570                         if ((f = fetchXGet(url, &us, flags)) == NULL) {
571                                 warnx("%s: %s", URL, fetchLastErrString);
572                                 goto failure;
573                         }
574                         if (sigint)
575                                 goto signal;
576                 }
577
578                 /* construct a temporary file name */
579                 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
580                         if ((slash = strrchr(path, '/')) == NULL)
581                                 slash = path;
582                         else
583                                 ++slash;
584                         asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
585                             (int)(slash - path), path, slash);
586                         if (tmppath != NULL) {
587                                 if (mkstemps(tmppath, strlen(slash)+1) == -1) {
588                                         warn("%s: mkstemps()", path);
589                                         goto failure;
590                                 }
591
592                                 of = fopen(tmppath, "w");
593                                 chown(tmppath, sb.st_uid, sb.st_gid);
594                                 chmod(tmppath, sb.st_mode & ALLPERMS);
595                         }
596                 }
597
598                 if (of == NULL)
599                         if ((of = fopen(path, "w")) == NULL) {
600                                 warn("%s: fopen()", path);
601                         goto failure;
602                 }
603         }
604         count = url->offset;
605
606         /* start the counter */
607         stat_start(&xs, path, us.size, count);
608
609         sigalrm = siginfo = sigint = 0;
610
611         /* suck in the data */
612         signal(SIGINFO, sig_handler);
613         while (!sigint) {
614                 if (us.size != -1 && us.size - count < B_size &&
615                     us.size - count >= 0)
616                         size = us.size - count;
617                 else
618                         size = B_size;
619                 if (siginfo) {
620                         stat_end(&xs);
621                         siginfo = 0;
622                 }
623
624                 if (size == 0)
625                         break;
626
627                 if ((readcnt = fread(buf, 1, size, f)) < size) {
628                         if (ferror(f) && errno == EINTR && !sigint)
629                                 clearerr(f);
630                         else if (readcnt == 0)
631                                 break;
632                 }
633
634                 stat_update(&xs, count += readcnt);
635                 for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
636                         if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
637                                 if (ferror(of) && errno == EINTR && !sigint)
638                                         clearerr(of);
639                                 else
640                                         break;
641                         }
642                 if (readcnt != 0)
643                         break;
644         }
645         if (!sigalrm)
646                 sigalrm = ferror(f) && errno == ETIMEDOUT;
647         signal(SIGINFO, SIG_DFL);
648
649         stat_end(&xs);
650
651         /*
652          * If the transfer timed out or was interrupted, we still want to
653          * set the mtime in case the file is not removed (-r or -R) and
654          * the user later restarts the transfer.
655          */
656  signal:
657         /* set mtime of local file */
658         if (!n_flag && us.mtime && !o_stdout && of != NULL &&
659             (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
660                 struct timeval tv[2];
661
662                 fflush(of);
663                 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
664                 tv[1].tv_sec = (long)us.mtime;
665                 tv[0].tv_usec = tv[1].tv_usec = 0;
666                 if (utimes(tmppath ? tmppath : path, tv))
667                         warn("%s: utimes()", tmppath ? tmppath : path);
668         }
669
670         /* timed out or interrupted? */
671         if (sigalrm)
672                 warnx("transfer timed out");
673         if (sigint) {
674                 warnx("transfer interrupted");
675                 goto failure;
676         }
677
678         /* timeout / interrupt before connection completley established? */
679         if (f == NULL)
680                 goto failure;
681
682         if (!sigalrm) {
683                 /* check the status of our files */
684                 if (ferror(f))
685                         warn("%s", URL);
686                 if (ferror(of))
687                         warn("%s", path);
688                 if (ferror(f) || ferror(of))
689                         goto failure;
690         }
691
692         /* did the transfer complete normally? */
693         if (us.size != -1 && count < us.size) {
694                 warnx("%s appears to be truncated: %jd/%jd bytes",
695                     path, (intmax_t)count, (intmax_t)us.size);
696                 goto failure_keep;
697         }
698
699         /*
700          * If the transfer timed out and we didn't know how much to
701          * expect, assume the worst (i.e. we didn't get all of it)
702          */
703         if (sigalrm && us.size == -1) {
704                 warnx("%s may be truncated", path);
705                 goto failure_keep;
706         }
707
708  success:
709         r = 0;
710         if (tmppath != NULL && rename(tmppath, path) == -1) {
711                 warn("%s: rename()", path);
712                 goto failure_keep;
713         }
714         goto done;
715  failure:
716         if (of && of != stdout && !R_flag && !r_flag)
717                 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
718                         unlink(tmppath ? tmppath : path);
719         if (R_flag && tmppath != NULL && sb.st_size == -1)
720                 rename(tmppath, path); /* ignore errors here */
721  failure_keep:
722         r = -1;
723         goto done;
724  done:
725         if (f)
726                 fclose(f);
727         if (of && of != stdout)
728                 fclose(of);
729         if (url)
730                 fetchFreeURL(url);
731         if (tmppath != NULL)
732                 free(tmppath);
733         return (r);
734 }
735
736 static void
737 usage(void)
738 {
739         fprintf(stderr, "%s\n%s\n%s\n%s\n",
740 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
741 "       [-T seconds] [-w seconds] [-i file] URL ...",
742 "       fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [-N file] [-o file] [-S bytes]",
743 "       [-T seconds] [-w seconds] [-i file] -h host -f file [-c dir]");
744 }
745
746
747 /*
748  * Entry point
749  */
750 int
751 main(int argc, char *argv[])
752 {
753         struct stat sb;
754         struct sigaction sa;
755         const char *p, *s;
756         char *end, *q;
757         int c, e, r;
758
759         while ((c = getopt(argc, argv,
760             "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:")) != -1)
761                 switch (c) {
762                 case '1':
763                         once_flag = 1;
764                         break;
765                 case '4':
766                         family = PF_INET;
767                         break;
768                 case '6':
769                         family = PF_INET6;
770                         break;
771                 case 'A':
772                         A_flag = 1;
773                         break;
774                 case 'a':
775                         a_flag = 1;
776                         break;
777                 case 'B':
778                         B_size = (off_t)strtol(optarg, &end, 10);
779                         if (*optarg == '\0' || *end != '\0')
780                                 errx(1, "invalid buffer size (%s)", optarg);
781                         break;
782                 case 'b':
783                         warnx("warning: the -b option is deprecated");
784                         b_flag = 1;
785                         break;
786                 case 'c':
787                         c_dirname = optarg;
788                         break;
789                 case 'd':
790                         d_flag = 1;
791                         break;
792                 case 'F':
793                         F_flag = 1;
794                         break;
795                 case 'f':
796                         f_filename = optarg;
797                         break;
798                 case 'H':
799                         warnx("the -H option is now implicit, "
800                             "use -U to disable");
801                         break;
802                 case 'h':
803                         h_hostname = optarg;
804                         break;
805                 case 'i':
806                         i_flag = 1;
807                         i_filename = optarg;
808                         break;
809                 case 'l':
810                         l_flag = 1;
811                         break;
812                 case 'o':
813                         o_flag = 1;
814                         o_filename = optarg;
815                         break;
816                 case 'M':
817                 case 'm':
818                         if (r_flag)
819                                 errx(1, "the -m and -r flags "
820                                     "are mutually exclusive");
821                         m_flag = 1;
822                         break;
823                 case 'N':
824                         N_filename = optarg;
825                         break;
826                 case 'n':
827                         n_flag = 1;
828                         break;
829                 case 'P':
830                 case 'p':
831                         p_flag = 1;
832                         break;
833                 case 'q':
834                         v_level = 0;
835                         break;
836                 case 'R':
837                         R_flag = 1;
838                         break;
839                 case 'r':
840                         if (m_flag)
841                                 errx(1, "the -m and -r flags "
842                                     "are mutually exclusive");
843                         r_flag = 1;
844                         break;
845                 case 'S':
846                         S_size = (off_t)strtol(optarg, &end, 10);
847                         if (*optarg == '\0' || *end != '\0')
848                                 errx(1, "invalid size (%s)", optarg);
849                         break;
850                 case 's':
851                         s_flag = 1;
852                         break;
853                 case 'T':
854                         T_secs = strtol(optarg, &end, 10);
855                         if (*optarg == '\0' || *end != '\0')
856                                 errx(1, "invalid timeout (%s)", optarg);
857                         break;
858                 case 't':
859                         t_flag = 1;
860                         warnx("warning: the -t option is deprecated");
861                         break;
862                 case 'U':
863                         U_flag = 1;
864                         break;
865                 case 'v':
866                         v_level++;
867                         break;
868                 case 'w':
869                         a_flag = 1;
870                         w_secs = strtol(optarg, &end, 10);
871                         if (*optarg == '\0' || *end != '\0')
872                                 errx(1, "invalid delay (%s)", optarg);
873                         break;
874                 default:
875                         usage();
876                         exit(1);
877                 }
878
879         argc -= optind;
880         argv += optind;
881
882         if (h_hostname || f_filename || c_dirname) {
883                 if (!h_hostname || !f_filename || argc) {
884                         usage();
885                         exit(1);
886                 }
887                 /* XXX this is a hack. */
888                 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
889                         errx(1, "invalid hostname");
890                 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
891                     c_dirname ? c_dirname : "", f_filename) == -1)
892                         errx(1, "%s", strerror(ENOMEM));
893                 argc++;
894         }
895
896         if (!argc) {
897                 usage();
898                 exit(1);
899         }
900
901         /* allocate buffer */
902         if (B_size < MINBUFSIZE)
903                 B_size = MINBUFSIZE;
904         if ((buf = malloc(B_size)) == NULL)
905                 errx(1, "%s", strerror(ENOMEM));
906
907         /* timeouts */
908         if ((s = getenv("FTP_TIMEOUT")) != NULL) {
909                 ftp_timeout = strtol(s, &end, 10);
910                 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
911                         warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
912                         ftp_timeout = 0;
913                 }
914         }
915         if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
916                 http_timeout = strtol(s, &end, 10);
917                 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
918                         warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
919                         http_timeout = 0;
920                 }
921         }
922
923         /* signal handling */
924         sa.sa_flags = 0;
925         sa.sa_handler = sig_handler;
926         sigemptyset(&sa.sa_mask);
927         sigaction(SIGALRM, &sa, NULL);
928         sa.sa_flags = SA_RESETHAND;
929         sigaction(SIGINT, &sa, NULL);
930         fetchRestartCalls = 0;
931
932         /* output file */
933         if (o_flag) {
934                 if (strcmp(o_filename, "-") == 0) {
935                         o_stdout = 1;
936                 } else if (stat(o_filename, &sb) == -1) {
937                         if (errno == ENOENT) {
938                                 if (argc > 1)
939                                         errx(1, "%s is not a directory",
940                                             o_filename);
941                         } else {
942                                 err(1, "%s", o_filename);
943                         }
944                 } else {
945                         if (sb.st_mode & S_IFDIR)
946                                 o_directory = 1;
947                 }
948         }
949
950         /* check if output is to a tty (for progress report) */
951         v_tty = isatty(STDERR_FILENO);
952         if (v_tty)
953                 pgrp = getpgrp();
954
955         r = 0;
956
957         /* authentication */
958         if (v_tty)
959                 fetchAuthMethod = query_auth;
960         if (N_filename != NULL) {
961                 if (setenv("NETRC", N_filename, 1) == -1)
962                         err(1, "setenv: cannot set NETRC=%s", N_filename);
963         }
964
965         while (argc) {
966                 if ((p = strrchr(*argv, '/')) == NULL)
967                         p = *argv;
968                 else
969                         p++;
970
971                 if (!*p)
972                         p = "fetch.out";
973
974                 fetchLastErrCode = 0;
975
976                 if (o_flag) {
977                         if (o_stdout) {
978                                 e = fetch(*argv, "-");
979                         } else if (o_directory) {
980                                 asprintf(&q, "%s/%s", o_filename, p);
981                                 e = fetch(*argv, q);
982                                 free(q);
983                         } else {
984                                 e = fetch(*argv, o_filename);
985                         }
986                 } else {
987                         e = fetch(*argv, p);
988                 }
989
990                 if (sigint)
991                         kill(getpid(), SIGINT);
992
993                 if (e == 0 && once_flag)
994                         exit(0);
995
996                 if (e) {
997                         r = 1;
998                         if ((fetchLastErrCode
999                             && fetchLastErrCode != FETCH_UNAVAIL
1000                             && fetchLastErrCode != FETCH_MOVED
1001                             && fetchLastErrCode != FETCH_URL
1002                             && fetchLastErrCode != FETCH_RESOLV
1003                             && fetchLastErrCode != FETCH_UNKNOWN)) {
1004                                 if (w_secs && v_level)
1005                                         fprintf(stderr, "Waiting %ld seconds "
1006                                             "before retrying\n", w_secs);
1007                                 if (w_secs)
1008                                         sleep(w_secs);
1009                                 if (a_flag)
1010                                         continue;
1011                         }
1012                 }
1013
1014                 argc--, argv++;
1015         }
1016
1017         exit(r);
1018 }