]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/fetch/fetch.c
MFV r336851:
[FreeBSD/FreeBSD.git] / usr.bin / fetch / fetch.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2000-2014 Dag-Erling Smørgrav
5  * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer
13  *    in this position and unchanged.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39
40 #include <ctype.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <getopt.h>
44 #include <signal.h>
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <termios.h>
50 #include <unistd.h>
51
52 #include <fetch.h>
53
54 #define MINBUFSIZE      16384
55 #define TIMEOUT         120
56
57 /* Option flags */
58 static int       A_flag;        /*    -A: do not follow 302 redirects */
59 static int       a_flag;        /*    -a: auto retry */
60 static off_t     B_size;        /*    -B: buffer size */
61 static int       b_flag;        /*!   -b: workaround TCP bug */
62 static char    *c_dirname;      /*    -c: remote directory */
63 static int       d_flag;        /*    -d: direct connection */
64 static int       F_flag;        /*    -F: restart without checking mtime  */
65 static char     *f_filename;    /*    -f: file to fetch */
66 static char     *h_hostname;    /*    -h: host to fetch from */
67 static int       i_flag;        /*    -i: specify file for mtime comparison */
68 static char     *i_filename;    /*        name of input file */
69 static int       l_flag;        /*    -l: link rather than copy file: URLs */
70 static int       m_flag;        /* -[Mm]: mirror mode */
71 static char     *N_filename;    /*    -N: netrc file name */
72 static int       n_flag;        /*    -n: do not preserve modification time */
73 static int       o_flag;        /*    -o: specify output file */
74 static int       o_directory;   /*        output file is a directory */
75 static char     *o_filename;    /*        name of output file */
76 static int       o_stdout;      /*        output file is stdout */
77 static int       once_flag;     /*    -1: stop at first successful file */
78 static int       p_flag;        /* -[Pp]: use passive FTP */
79 static int       R_flag;        /*    -R: don't delete partial files */
80 static int       r_flag;        /*    -r: restart previous transfer */
81 static off_t     S_size;        /*    -S: require size to match */
82 static int       s_flag;        /*    -s: show size, don't fetch */
83 static long      T_secs;        /*    -T: transfer timeout in seconds */
84 static int       t_flag;        /*!   -t: workaround TCP bug */
85 static int       U_flag;        /*    -U: do not use high ports */
86 static int       v_level = 1;   /*    -v: verbosity level */
87 static int       v_tty;         /*        stdout is a tty */
88 static pid_t     pgrp;          /*        our process group */
89 static long      w_secs;        /*    -w: retry delay */
90 static int       family = PF_UNSPEC;    /* -[46]: address family to use */
91
92 static int       sigalrm;       /* SIGALRM received */
93 static int       siginfo;       /* SIGINFO received */
94 static int       sigint;        /* SIGINT received */
95
96 static long      ftp_timeout = TIMEOUT; /* default timeout for FTP transfers */
97 static long      http_timeout = TIMEOUT;/* default timeout for HTTP transfers */
98 static char     *buf;           /* transfer buffer */
99
100 enum options
101 {
102         OPTION_BIND_ADDRESS,
103         OPTION_NO_FTP_PASSIVE_MODE,
104         OPTION_HTTP_REFERER,
105         OPTION_HTTP_USER_AGENT,
106         OPTION_NO_PROXY,
107         OPTION_SSL_CA_CERT_FILE,
108         OPTION_SSL_CA_CERT_PATH,
109         OPTION_SSL_CLIENT_CERT_FILE,
110         OPTION_SSL_CLIENT_KEY_FILE,
111         OPTION_SSL_CRL_FILE,
112         OPTION_SSL_NO_SSL3,
113         OPTION_SSL_NO_TLS1,
114         OPTION_SSL_NO_VERIFY_HOSTNAME,
115         OPTION_SSL_NO_VERIFY_PEER
116 };
117
118
119 static struct option longopts[] =
120 {
121         /* mapping to single character argument */
122         { "one-file", no_argument, NULL, '1' },
123         { "ipv4-only", no_argument, NULL, '4' },
124         { "ipv6-only", no_argument, NULL, '6' },
125         { "no-redirect", no_argument, NULL, 'A' },
126         { "retry", no_argument, NULL, 'a' },
127         { "buffer-size", required_argument, NULL, 'B' },
128         /* -c not mapped, since it's deprecated */
129         { "direct", no_argument, NULL, 'd' },
130         { "force-restart", no_argument, NULL, 'F' },
131         /* -f not mapped, since it's deprecated */
132         /* -h not mapped, since it's deprecated */
133         { "if-modified-since", required_argument, NULL, 'i' },
134         { "symlink", no_argument, NULL, 'l' },
135         /* -M not mapped since it's the same as -m */
136         { "mirror", no_argument, NULL, 'm' },
137         { "netrc", required_argument, NULL, 'N' },
138         { "no-mtime", no_argument, NULL, 'n' },
139         { "output", required_argument, NULL, 'o' },
140         /* -P not mapped since it's the same as -p */
141         { "passive", no_argument, NULL, 'p' },
142         { "quiet", no_argument, NULL, 'q' },
143         { "keep-output", no_argument, NULL, 'R' },
144         { "restart", no_argument, NULL, 'r' },
145         { "require-size", required_argument, NULL, 'S' },
146         { "print-size", no_argument, NULL, 's' },
147         { "timeout", required_argument, NULL, 'T' },
148         { "passive-portrange-default", no_argument, NULL, 'T' },
149         { "verbose", no_argument, NULL, 'v' },
150         { "retry-delay", required_argument, NULL, 'w' },
151
152         /* options without a single character equivalent */
153         { "bind-address", required_argument, NULL, OPTION_BIND_ADDRESS },
154         { "no-passive", no_argument, NULL, OPTION_NO_FTP_PASSIVE_MODE },
155         { "referer", required_argument, NULL, OPTION_HTTP_REFERER },
156         { "user-agent", required_argument, NULL, OPTION_HTTP_USER_AGENT },
157         { "no-proxy", required_argument, NULL, OPTION_NO_PROXY },
158         { "ca-cert", required_argument, NULL, OPTION_SSL_CA_CERT_FILE },
159         { "ca-path", required_argument, NULL, OPTION_SSL_CA_CERT_PATH },
160         { "cert", required_argument, NULL, OPTION_SSL_CLIENT_CERT_FILE },
161         { "key", required_argument, NULL, OPTION_SSL_CLIENT_KEY_FILE },
162         { "crl", required_argument, NULL, OPTION_SSL_CRL_FILE },
163         { "no-sslv3", no_argument, NULL, OPTION_SSL_NO_SSL3 },
164         { "no-tlsv1", no_argument, NULL, OPTION_SSL_NO_TLS1 },
165         { "no-verify-hostname", no_argument, NULL, OPTION_SSL_NO_VERIFY_HOSTNAME },
166         { "no-verify-peer", no_argument, NULL, OPTION_SSL_NO_VERIFY_PEER },
167
168         { NULL, 0, NULL, 0 }
169 };
170
171 /*
172  * Signal handler
173  */
174 static void
175 sig_handler(int sig)
176 {
177         switch (sig) {
178         case SIGALRM:
179                 sigalrm = 1;
180                 break;
181         case SIGINFO:
182                 siginfo = 1;
183                 break;
184         case SIGINT:
185                 sigint = 1;
186                 break;
187         }
188 }
189
190 struct xferstat {
191         char             name[64];
192         struct timeval   start;         /* start of transfer */
193         struct timeval   last;          /* time of last update */
194         struct timeval   last2;         /* time of previous last update */
195         off_t            size;          /* size of file per HTTP hdr */
196         off_t            offset;        /* starting offset in file */
197         off_t            rcvd;          /* bytes already received */
198         off_t            lastrcvd;      /* bytes received since last update */
199 };
200
201 /*
202  * Compute and display ETA
203  */
204 static const char *
205 stat_eta(struct xferstat *xs)
206 {
207         static char str[16];
208         long elapsed, eta;
209         off_t received, expected;
210
211         elapsed = xs->last.tv_sec - xs->start.tv_sec;
212         received = xs->rcvd - xs->offset;
213         expected = xs->size - xs->rcvd;
214         eta = (long)((double)elapsed * expected / received);
215         if (eta > 3600)
216                 snprintf(str, sizeof str, "%02ldh%02ldm",
217                     eta / 3600, (eta % 3600) / 60);
218         else if (eta > 0)
219                 snprintf(str, sizeof str, "%02ldm%02lds",
220                     eta / 60, eta % 60);
221         else
222                 snprintf(str, sizeof str, "%02ldm%02lds",
223                     elapsed / 60, elapsed % 60);
224         return (str);
225 }
226
227 /*
228  * Format a number as "xxxx YB" where Y is ' ', 'k', 'M'...
229  */
230 static const char *prefixes = " kMGTP";
231 static const char *
232 stat_bytes(off_t bytes)
233 {
234         static char str[16];
235         const char *prefix = prefixes;
236
237         while (bytes > 9999 && prefix[1] != '\0') {
238                 bytes /= 1024;
239                 prefix++;
240         }
241         snprintf(str, sizeof str, "%4jd %cB", (intmax_t)bytes, *prefix);
242         return (str);
243 }
244
245 /*
246  * Compute and display transfer rate
247  */
248 static const char *
249 stat_bps(struct xferstat *xs)
250 {
251         static char str[16];
252         double delta, bps;
253
254         delta = (xs->last.tv_sec + (xs->last.tv_usec / 1.e6))
255             - (xs->last2.tv_sec + (xs->last2.tv_usec / 1.e6));
256
257         if (delta == 0.0) {
258                 snprintf(str, sizeof str, "?? Bps");
259         } else {
260                 bps = (xs->rcvd - xs->lastrcvd) / delta;
261                 snprintf(str, sizeof str, "%sps", stat_bytes((off_t)bps));
262         }
263         return (str);
264 }
265
266 /*
267  * Update the stats display
268  */
269 static void
270 stat_display(struct xferstat *xs, int force)
271 {
272         struct timeval now;
273         int ctty_pgrp;
274
275         /* check if we're the foreground process */
276         if (ioctl(STDERR_FILENO, TIOCGPGRP, &ctty_pgrp) == -1 ||
277             (pid_t)ctty_pgrp != pgrp)
278                 return;
279
280         gettimeofday(&now, NULL);
281         if (!force && now.tv_sec <= xs->last.tv_sec)
282                 return;
283         xs->last2 = xs->last;
284         xs->last = now;
285
286         fprintf(stderr, "\r%-46.46s", xs->name);
287         if (xs->size <= 0) {
288                 setproctitle("%s [%s]", xs->name, stat_bytes(xs->rcvd));
289                 fprintf(stderr, "        %s", stat_bytes(xs->rcvd));
290         } else {
291                 setproctitle("%s [%d%% of %s]", xs->name,
292                     (int)((100.0 * xs->rcvd) / xs->size),
293                     stat_bytes(xs->size));
294                 fprintf(stderr, "%3d%% of %s",
295                     (int)((100.0 * xs->rcvd) / xs->size),
296                     stat_bytes(xs->size));
297         }
298         if (force == 2) {
299                 xs->lastrcvd = xs->offset;
300                 xs->last2 = xs->start;
301         }
302         fprintf(stderr, " %s", stat_bps(xs));
303         if ((xs->size > 0 && xs->rcvd > 0 &&
304              xs->last.tv_sec >= xs->start.tv_sec + 3) ||
305             force == 2)
306                 fprintf(stderr, " %s", stat_eta(xs));
307         xs->lastrcvd = xs->rcvd;
308 }
309
310 /*
311  * Initialize the transfer statistics
312  */
313 static void
314 stat_start(struct xferstat *xs, const char *name, off_t size, off_t offset)
315 {
316         snprintf(xs->name, sizeof xs->name, "%s", name);
317         gettimeofday(&xs->start, NULL);
318         xs->last.tv_sec = xs->last.tv_usec = 0;
319         xs->size = size;
320         xs->offset = offset;
321         xs->rcvd = offset;
322         xs->lastrcvd = offset;
323         if (v_tty && v_level > 0)
324                 stat_display(xs, 1);
325         else if (v_level > 0)
326                 fprintf(stderr, "%-46s", xs->name);
327 }
328
329 /*
330  * Update the transfer statistics
331  */
332 static void
333 stat_update(struct xferstat *xs, off_t rcvd)
334 {
335         xs->rcvd = rcvd;
336         if (v_tty && v_level > 0)
337                 stat_display(xs, 0);
338 }
339
340 /*
341  * Finalize the transfer statistics
342  */
343 static void
344 stat_end(struct xferstat *xs)
345 {
346         gettimeofday(&xs->last, NULL);
347         if (v_tty && v_level > 0) {
348                 stat_display(xs, 2);
349                 putc('\n', stderr);
350         } else if (v_level > 0) {
351                 fprintf(stderr, "        %s %s\n",
352                     stat_bytes(xs->size), stat_bps(xs));
353         }
354 }
355
356 /*
357  * Ask the user for authentication details
358  */
359 static int
360 query_auth(struct url *URL)
361 {
362         struct termios tios;
363         tcflag_t saved_flags;
364         int i, nopwd;
365
366         fprintf(stderr, "Authentication required for <%s://%s:%d/>!\n",
367             URL->scheme, URL->host, URL->port);
368
369         fprintf(stderr, "Login: ");
370         if (fgets(URL->user, sizeof URL->user, stdin) == NULL)
371                 return (-1);
372         for (i = strlen(URL->user); i >= 0; --i)
373                 if (URL->user[i] == '\r' || URL->user[i] == '\n')
374                         URL->user[i] = '\0';
375
376         fprintf(stderr, "Password: ");
377         if (tcgetattr(STDIN_FILENO, &tios) == 0) {
378                 saved_flags = tios.c_lflag;
379                 tios.c_lflag &= ~ECHO;
380                 tios.c_lflag |= ECHONL|ICANON;
381                 tcsetattr(STDIN_FILENO, TCSAFLUSH|TCSASOFT, &tios);
382                 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
383                 tios.c_lflag = saved_flags;
384                 tcsetattr(STDIN_FILENO, TCSANOW|TCSASOFT, &tios);
385         } else {
386                 nopwd = (fgets(URL->pwd, sizeof URL->pwd, stdin) == NULL);
387         }
388         if (nopwd)
389                 return (-1);
390         for (i = strlen(URL->pwd); i >= 0; --i)
391                 if (URL->pwd[i] == '\r' || URL->pwd[i] == '\n')
392                         URL->pwd[i] = '\0';
393
394         return (0);
395 }
396
397 /*
398  * Fetch a file
399  */
400 static int
401 fetch(char *URL, const char *path)
402 {
403         struct url *url;
404         struct url_stat us;
405         struct stat sb, nsb;
406         struct xferstat xs;
407         FILE *f, *of;
408         size_t size, readcnt, wr;
409         off_t count;
410         char flags[8];
411         const char *slash;
412         char *tmppath;
413         int r;
414         unsigned timeout;
415         char *ptr;
416
417         f = of = NULL;
418         tmppath = NULL;
419
420         timeout = 0;
421         *flags = 0;
422         count = 0;
423
424         /* set verbosity level */
425         if (v_level > 1)
426                 strcat(flags, "v");
427         if (v_level > 2)
428                 fetchDebug = 1;
429
430         /* parse URL */
431         url = NULL;
432         if (*URL == '\0') {
433                 warnx("empty URL");
434                 goto failure;
435         }
436         if ((url = fetchParseURL(URL)) == NULL) {
437                 warnx("%s: parse error", URL);
438                 goto failure;
439         }
440
441         /* if no scheme was specified, take a guess */
442         if (!*url->scheme) {
443                 if (!*url->host)
444                         strcpy(url->scheme, SCHEME_FILE);
445                 else if (strncasecmp(url->host, "ftp.", 4) == 0)
446                         strcpy(url->scheme, SCHEME_FTP);
447                 else if (strncasecmp(url->host, "www.", 4) == 0)
448                         strcpy(url->scheme, SCHEME_HTTP);
449         }
450
451         /* common flags */
452         switch (family) {
453         case PF_INET:
454                 strcat(flags, "4");
455                 break;
456         case PF_INET6:
457                 strcat(flags, "6");
458                 break;
459         }
460
461         /* FTP specific flags */
462         if (strcmp(url->scheme, SCHEME_FTP) == 0) {
463                 if (p_flag)
464                         strcat(flags, "p");
465                 if (d_flag)
466                         strcat(flags, "d");
467                 if (U_flag)
468                         strcat(flags, "l");
469                 timeout = T_secs ? T_secs : ftp_timeout;
470         }
471
472         /* HTTP specific flags */
473         if (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
474             strcmp(url->scheme, SCHEME_HTTPS) == 0) {
475                 if (d_flag)
476                         strcat(flags, "d");
477                 if (A_flag)
478                         strcat(flags, "A");
479                 timeout = T_secs ? T_secs : http_timeout;
480                 if (i_flag) {
481                         if (stat(i_filename, &sb)) {
482                                 warn("%s: stat()", i_filename);
483                                 goto failure;
484                         }
485                         url->ims_time = sb.st_mtime;
486                         strcat(flags, "i");
487                 }
488         }
489
490         /* set the protocol timeout. */
491         fetchTimeout = timeout;
492
493         /* just print size */
494         if (s_flag) {
495                 if (timeout)
496                         alarm(timeout);
497                 r = fetchStat(url, &us, flags);
498                 if (timeout)
499                         alarm(0);
500                 if (sigalrm || sigint)
501                         goto signal;
502                 if (r == -1) {
503                         warnx("%s", fetchLastErrString);
504                         goto failure;
505                 }
506                 if (us.size == -1)
507                         printf("Unknown\n");
508                 else
509                         printf("%jd\n", (intmax_t)us.size);
510                 goto success;
511         }
512
513         /*
514          * If the -r flag was specified, we have to compare the local
515          * and remote files, so we should really do a fetchStat()
516          * first, but I know of at least one HTTP server that only
517          * sends the content size in response to GET requests, and
518          * leaves it out of replies to HEAD requests.  Also, in the
519          * (frequent) case that the local and remote files match but
520          * the local file is truncated, we have sufficient information
521          * before the compare to issue a correct request.  Therefore,
522          * we always issue a GET request as if we were sure the local
523          * file was a truncated copy of the remote file; we can drop
524          * the connection later if we change our minds.
525          */
526         sb.st_size = -1;
527         if (!o_stdout) {
528                 r = stat(path, &sb);
529                 if (r == 0 && r_flag && S_ISREG(sb.st_mode)) {
530                         url->offset = sb.st_size;
531                 } else if (r == -1 || !S_ISREG(sb.st_mode)) {
532                         /*
533                          * Whatever value sb.st_size has now is either
534                          * wrong (if stat(2) failed) or irrelevant (if the
535                          * path does not refer to a regular file)
536                          */
537                         sb.st_size = -1;
538                 }
539                 if (r == -1 && errno != ENOENT) {
540                         warnx("%s: stat()", path);
541                         goto failure;
542                 }
543         }
544
545         /* start the transfer */
546         if (timeout)
547                 alarm(timeout);
548         f = fetchXGet(url, &us, flags);
549         if (timeout)
550                 alarm(0);
551         if (sigalrm || sigint)
552                 goto signal;
553         if (f == NULL) {
554                 warnx("%s: %s", URL, fetchLastErrString);
555                 if (i_flag && (strcmp(url->scheme, SCHEME_HTTP) == 0 ||
556                     strcmp(url->scheme, SCHEME_HTTPS) == 0) &&
557                     fetchLastErrCode == FETCH_OK &&
558                     strcmp(fetchLastErrString, "Not Modified") == 0) {
559                         /* HTTP Not Modified Response, return OK. */
560                         r = 0;
561                         goto done;
562                 } else
563                         goto failure;
564         }
565         if (sigint)
566                 goto signal;
567
568         /* check that size is as expected */
569         if (S_size) {
570                 if (us.size == -1) {
571                         warnx("%s: size unknown", URL);
572                 } else if (us.size != S_size) {
573                         warnx("%s: size mismatch: expected %jd, actual %jd",
574                             URL, (intmax_t)S_size, (intmax_t)us.size);
575                         goto failure;
576                 }
577         }
578
579         /* symlink instead of copy */
580         if (l_flag && strcmp(url->scheme, "file") == 0 && !o_stdout) {
581                 if (symlink(url->doc, path) == -1) {
582                         warn("%s: symlink()", path);
583                         goto failure;
584                 }
585                 goto success;
586         }
587
588         if (us.size == -1 && !o_stdout && v_level > 0)
589                 warnx("%s: size of remote file is not known", URL);
590         if (v_level > 1) {
591                 if (sb.st_size != -1)
592                         fprintf(stderr, "local size / mtime: %jd / %ld\n",
593                             (intmax_t)sb.st_size, (long)sb.st_mtime);
594                 if (us.size != -1)
595                         fprintf(stderr, "remote size / mtime: %jd / %ld\n",
596                             (intmax_t)us.size, (long)us.mtime);
597         }
598
599         /* open output file */
600         if (o_stdout) {
601                 /* output to stdout */
602                 of = stdout;
603         } else if (r_flag && sb.st_size != -1) {
604                 /* resume mode, local file exists */
605                 if (!F_flag && us.mtime && sb.st_mtime != us.mtime) {
606                         /* no match! have to refetch */
607                         fclose(f);
608                         /* if precious, warn the user and give up */
609                         if (R_flag) {
610                                 warnx("%s: local modification time "
611                                     "does not match remote", path);
612                                 goto failure_keep;
613                         }
614                 } else if (url->offset > sb.st_size) {
615                         /* gap between what we asked for and what we got */
616                         warnx("%s: gap in resume mode", URL);
617                         fclose(of);
618                         of = NULL;
619                         /* picked up again later */
620                 } else if (us.size != -1) {
621                         if (us.size == sb.st_size)
622                                 /* nothing to do */
623                                 goto success;
624                         if (sb.st_size > us.size) {
625                                 /* local file too long! */
626                                 warnx("%s: local file (%jd bytes) is longer "
627                                     "than remote file (%jd bytes)", path,
628                                     (intmax_t)sb.st_size, (intmax_t)us.size);
629                                 goto failure;
630                         }
631                         /* we got it, open local file */
632                         if ((of = fopen(path, "r+")) == NULL) {
633                                 warn("%s: fopen()", path);
634                                 goto failure;
635                         }
636                         /* check that it didn't move under our feet */
637                         if (fstat(fileno(of), &nsb) == -1) {
638                                 /* can't happen! */
639                                 warn("%s: fstat()", path);
640                                 goto failure;
641                         }
642                         if (nsb.st_dev != sb.st_dev ||
643                             nsb.st_ino != sb.st_ino ||
644                             nsb.st_size != sb.st_size) {
645                                 warnx("%s: file has changed", URL);
646                                 fclose(of);
647                                 of = NULL;
648                                 sb = nsb;
649                                 /* picked up again later */
650                         }
651                 }
652                 /* seek to where we left off */
653                 if (of != NULL && fseeko(of, url->offset, SEEK_SET) != 0) {
654                         warn("%s: fseeko()", path);
655                         fclose(of);
656                         of = NULL;
657                         /* picked up again later */
658                 }
659         } else if (m_flag && sb.st_size != -1) {
660                 /* mirror mode, local file exists */
661                 if (sb.st_size == us.size && sb.st_mtime == us.mtime)
662                         goto success;
663         }
664
665         if (of == NULL) {
666                 /*
667                  * We don't yet have an output file; either this is a
668                  * vanilla run with no special flags, or the local and
669                  * remote files didn't match.
670                  */
671
672                 if (url->offset > 0) {
673                         /*
674                          * We tried to restart a transfer, but for
675                          * some reason gave up - so we have to restart
676                          * from scratch if we want the whole file
677                          */
678                         url->offset = 0;
679                         if ((f = fetchXGet(url, &us, flags)) == NULL) {
680                                 warnx("%s: %s", URL, fetchLastErrString);
681                                 goto failure;
682                         }
683                         if (sigint)
684                                 goto signal;
685                 }
686
687                 /* construct a temp file name */
688                 if (sb.st_size != -1 && S_ISREG(sb.st_mode)) {
689                         if ((slash = strrchr(path, '/')) == NULL)
690                                 slash = path;
691                         else
692                                 ++slash;
693                         asprintf(&tmppath, "%.*s.fetch.XXXXXX.%s",
694                             (int)(slash - path), path, slash);
695                         if (tmppath != NULL) {
696                                 if (mkstemps(tmppath, strlen(slash) + 1) == -1) {
697                                         warn("%s: mkstemps()", path);
698                                         goto failure;
699                                 }
700                                 of = fopen(tmppath, "w");
701                                 chown(tmppath, sb.st_uid, sb.st_gid);
702                                 chmod(tmppath, sb.st_mode & ALLPERMS);
703                         }
704                 }
705                 if (of == NULL)
706                         of = fopen(path, "w");
707                 if (of == NULL) {
708                         warn("%s: open()", path);
709                         goto failure;
710                 }
711         }
712         count = url->offset;
713
714         /* start the counter */
715         stat_start(&xs, path, us.size, count);
716
717         sigalrm = siginfo = sigint = 0;
718
719         /* suck in the data */
720         setvbuf(f, NULL, _IOFBF, B_size);
721         signal(SIGINFO, sig_handler);
722         while (!sigint) {
723                 if (us.size != -1 && us.size - count < B_size &&
724                     us.size - count >= 0)
725                         size = us.size - count;
726                 else
727                         size = B_size;
728                 if (siginfo) {
729                         stat_end(&xs);
730                         siginfo = 0;
731                 }
732
733                 if (size == 0)
734                         break;
735
736                 if ((readcnt = fread(buf, 1, size, f)) < size) {
737                         if (ferror(f) && errno == EINTR && !sigint)
738                                 clearerr(f);
739                         else if (readcnt == 0)
740                                 break;
741                 }
742
743                 stat_update(&xs, count += readcnt);
744                 for (ptr = buf; readcnt > 0; ptr += wr, readcnt -= wr)
745                         if ((wr = fwrite(ptr, 1, readcnt, of)) < readcnt) {
746                                 if (ferror(of) && errno == EINTR && !sigint)
747                                         clearerr(of);
748                                 else
749                                         break;
750                         }
751                 if (readcnt != 0)
752                         break;
753         }
754         if (!sigalrm)
755                 sigalrm = ferror(f) && errno == ETIMEDOUT;
756         signal(SIGINFO, SIG_DFL);
757
758         stat_end(&xs);
759
760         /*
761          * If the transfer timed out or was interrupted, we still want to
762          * set the mtime in case the file is not removed (-r or -R) and
763          * the user later restarts the transfer.
764          */
765  signal:
766         /* set mtime of local file */
767         if (!n_flag && us.mtime && !o_stdout && of != NULL &&
768             (stat(path, &sb) != -1) && sb.st_mode & S_IFREG) {
769                 struct timeval tv[2];
770
771                 fflush(of);
772                 tv[0].tv_sec = (long)(us.atime ? us.atime : us.mtime);
773                 tv[1].tv_sec = (long)us.mtime;
774                 tv[0].tv_usec = tv[1].tv_usec = 0;
775                 if (utimes(tmppath ? tmppath : path, tv))
776                         warn("%s: utimes()", tmppath ? tmppath : path);
777         }
778
779         /* timed out or interrupted? */
780         if (sigalrm)
781                 warnx("transfer timed out");
782         if (sigint) {
783                 warnx("transfer interrupted");
784                 goto failure;
785         }
786
787         /* timeout / interrupt before connection completley established? */
788         if (f == NULL)
789                 goto failure;
790
791         if (!sigalrm) {
792                 /* check the status of our files */
793                 if (ferror(f))
794                         warn("%s", URL);
795                 if (ferror(of))
796                         warn("%s", path);
797                 if (ferror(f) || ferror(of))
798                         goto failure;
799         }
800
801         /* did the transfer complete normally? */
802         if (us.size != -1 && count < us.size) {
803                 warnx("%s appears to be truncated: %jd/%jd bytes",
804                     path, (intmax_t)count, (intmax_t)us.size);
805                 goto failure_keep;
806         }
807
808         /*
809          * If the transfer timed out and we didn't know how much to
810          * expect, assume the worst (i.e. we didn't get all of it)
811          */
812         if (sigalrm && us.size == -1) {
813                 warnx("%s may be truncated", path);
814                 goto failure_keep;
815         }
816
817  success:
818         r = 0;
819         if (tmppath != NULL && rename(tmppath, path) == -1) {
820                 warn("%s: rename()", path);
821                 goto failure_keep;
822         }
823         goto done;
824  failure:
825         if (of && of != stdout && !R_flag && !r_flag)
826                 if (stat(path, &sb) != -1 && (sb.st_mode & S_IFREG))
827                         unlink(tmppath ? tmppath : path);
828         if (R_flag && tmppath != NULL && sb.st_size == -1)
829                 rename(tmppath, path); /* ignore errors here */
830  failure_keep:
831         r = -1;
832         goto done;
833  done:
834         if (f)
835                 fclose(f);
836         if (of && of != stdout)
837                 fclose(of);
838         if (url)
839                 fetchFreeURL(url);
840         if (tmppath != NULL)
841                 free(tmppath);
842         return (r);
843 }
844
845 static void
846 usage(void)
847 {
848         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
849 "usage: fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
850 "       [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
851 "       [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
852 "       [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
853 "       [-o file] [--referer=URL] [-S bytes] [-T seconds]",
854 "       [--user-agent=agent-string] [-w seconds] URL ...",
855 "       fetch [-146AadFlMmnPpqRrsUv] [-B bytes] [--bind-address=host]",
856 "       [--ca-cert=file] [--ca-path=dir] [--cert=file] [--crl=file]",
857 "       [-i file] [--key=file] [-N file] [--no-passive] [--no-proxy=list]",
858 "       [--no-sslv3] [--no-tlsv1] [--no-verify-hostname] [--no-verify-peer]",
859 "       [-o file] [--referer=URL] [-S bytes] [-T seconds]",
860 "       [--user-agent=agent-string] [-w seconds] -h host -f file [-c dir]");
861 }
862
863
864 /*
865  * Entry point
866  */
867 int
868 main(int argc, char *argv[])
869 {
870         struct stat sb;
871         struct sigaction sa;
872         const char *p, *s;
873         char *end, *q;
874         int c, e, r;
875
876
877         while ((c = getopt_long(argc, argv,
878             "146AaB:bc:dFf:Hh:i:lMmN:nPpo:qRrS:sT:tUvw:",
879             longopts, NULL)) != -1)
880                 switch (c) {
881                 case '1':
882                         once_flag = 1;
883                         break;
884                 case '4':
885                         family = PF_INET;
886                         break;
887                 case '6':
888                         family = PF_INET6;
889                         break;
890                 case 'A':
891                         A_flag = 1;
892                         break;
893                 case 'a':
894                         a_flag = 1;
895                         break;
896                 case 'B':
897                         B_size = (off_t)strtol(optarg, &end, 10);
898                         if (*optarg == '\0' || *end != '\0')
899                                 errx(1, "invalid buffer size (%s)", optarg);
900                         break;
901                 case 'b':
902                         warnx("warning: the -b option is deprecated");
903                         b_flag = 1;
904                         break;
905                 case 'c':
906                         c_dirname = optarg;
907                         break;
908                 case 'd':
909                         d_flag = 1;
910                         break;
911                 case 'F':
912                         F_flag = 1;
913                         break;
914                 case 'f':
915                         f_filename = optarg;
916                         break;
917                 case 'H':
918                         warnx("the -H option is now implicit, "
919                             "use -U to disable");
920                         break;
921                 case 'h':
922                         h_hostname = optarg;
923                         break;
924                 case 'i':
925                         i_flag = 1;
926                         i_filename = optarg;
927                         break;
928                 case 'l':
929                         l_flag = 1;
930                         break;
931                 case 'o':
932                         o_flag = 1;
933                         o_filename = optarg;
934                         break;
935                 case 'M':
936                 case 'm':
937                         if (r_flag)
938                                 errx(1, "the -m and -r flags "
939                                     "are mutually exclusive");
940                         m_flag = 1;
941                         break;
942                 case 'N':
943                         N_filename = optarg;
944                         break;
945                 case 'n':
946                         n_flag = 1;
947                         break;
948                 case 'P':
949                 case 'p':
950                         p_flag = 1;
951                         break;
952                 case 'q':
953                         v_level = 0;
954                         break;
955                 case 'R':
956                         R_flag = 1;
957                         break;
958                 case 'r':
959                         if (m_flag)
960                                 errx(1, "the -m and -r flags "
961                                     "are mutually exclusive");
962                         r_flag = 1;
963                         break;
964                 case 'S':
965                         S_size = (off_t)strtol(optarg, &end, 10);
966                         if (*optarg == '\0' || *end != '\0')
967                                 errx(1, "invalid size (%s)", optarg);
968                         break;
969                 case 's':
970                         s_flag = 1;
971                         break;
972                 case 'T':
973                         T_secs = strtol(optarg, &end, 10);
974                         if (*optarg == '\0' || *end != '\0')
975                                 errx(1, "invalid timeout (%s)", optarg);
976                         break;
977                 case 't':
978                         t_flag = 1;
979                         warnx("warning: the -t option is deprecated");
980                         break;
981                 case 'U':
982                         U_flag = 1;
983                         break;
984                 case 'v':
985                         v_level++;
986                         break;
987                 case 'w':
988                         a_flag = 1;
989                         w_secs = strtol(optarg, &end, 10);
990                         if (*optarg == '\0' || *end != '\0')
991                                 errx(1, "invalid delay (%s)", optarg);
992                         break;
993                 case OPTION_BIND_ADDRESS:
994                         setenv("FETCH_BIND_ADDRESS", optarg, 1);
995                         break;
996                 case OPTION_NO_FTP_PASSIVE_MODE:
997                         setenv("FTP_PASSIVE_MODE", "no", 1);
998                         break;
999                 case OPTION_HTTP_REFERER:
1000                         setenv("HTTP_REFERER", optarg, 1);
1001                         break;
1002                 case OPTION_HTTP_USER_AGENT:
1003                         setenv("HTTP_USER_AGENT", optarg, 1);
1004                         break;
1005                 case OPTION_NO_PROXY:
1006                         setenv("NO_PROXY", optarg, 1);
1007                         break;
1008                 case OPTION_SSL_CA_CERT_FILE:
1009                         setenv("SSL_CA_CERT_FILE", optarg, 1);
1010                         break;
1011                 case OPTION_SSL_CA_CERT_PATH:
1012                         setenv("SSL_CA_CERT_PATH", optarg, 1);
1013                         break;
1014                 case OPTION_SSL_CLIENT_CERT_FILE:
1015                         setenv("SSL_CLIENT_CERT_FILE", optarg, 1);
1016                         break;
1017                 case OPTION_SSL_CLIENT_KEY_FILE:
1018                         setenv("SSL_CLIENT_KEY_FILE", optarg, 1);
1019                         break;
1020                 case OPTION_SSL_CRL_FILE:
1021                         setenv("SSL_CLIENT_CRL_FILE", optarg, 1);
1022                         break;
1023                 case OPTION_SSL_NO_SSL3:
1024                         setenv("SSL_NO_SSL3", "", 1);
1025                         break;
1026                 case OPTION_SSL_NO_TLS1:
1027                         setenv("SSL_NO_TLS1", "", 1);
1028                         break;
1029                 case OPTION_SSL_NO_VERIFY_HOSTNAME:
1030                         setenv("SSL_NO_VERIFY_HOSTNAME", "", 1);
1031                         break;
1032                 case OPTION_SSL_NO_VERIFY_PEER:
1033                         setenv("SSL_NO_VERIFY_PEER", "", 1);
1034                         break;
1035                 default:
1036                         usage();
1037                         exit(1);
1038                 }
1039
1040         argc -= optind;
1041         argv += optind;
1042
1043         if (h_hostname || f_filename || c_dirname) {
1044                 if (!h_hostname || !f_filename || argc) {
1045                         usage();
1046                         exit(1);
1047                 }
1048                 /* XXX this is a hack. */
1049                 if (strcspn(h_hostname, "@:/") != strlen(h_hostname))
1050                         errx(1, "invalid hostname");
1051                 if (asprintf(argv, "ftp://%s/%s/%s", h_hostname,
1052                     c_dirname ? c_dirname : "", f_filename) == -1)
1053                         errx(1, "%s", strerror(ENOMEM));
1054                 argc++;
1055         }
1056
1057         if (!argc) {
1058                 usage();
1059                 exit(1);
1060         }
1061
1062         /* allocate buffer */
1063         if (B_size < MINBUFSIZE)
1064                 B_size = MINBUFSIZE;
1065         if ((buf = malloc(B_size)) == NULL)
1066                 errx(1, "%s", strerror(ENOMEM));
1067
1068         /* timeouts */
1069         if ((s = getenv("FTP_TIMEOUT")) != NULL) {
1070                 ftp_timeout = strtol(s, &end, 10);
1071                 if (*s == '\0' || *end != '\0' || ftp_timeout < 0) {
1072                         warnx("FTP_TIMEOUT (%s) is not a positive integer", s);
1073                         ftp_timeout = 0;
1074                 }
1075         }
1076         if ((s = getenv("HTTP_TIMEOUT")) != NULL) {
1077                 http_timeout = strtol(s, &end, 10);
1078                 if (*s == '\0' || *end != '\0' || http_timeout < 0) {
1079                         warnx("HTTP_TIMEOUT (%s) is not a positive integer", s);
1080                         http_timeout = 0;
1081                 }
1082         }
1083
1084         /* signal handling */
1085         sa.sa_flags = 0;
1086         sa.sa_handler = sig_handler;
1087         sigemptyset(&sa.sa_mask);
1088         sigaction(SIGALRM, &sa, NULL);
1089         sa.sa_flags = SA_RESETHAND;
1090         sigaction(SIGINT, &sa, NULL);
1091         fetchRestartCalls = 0;
1092
1093         /* output file */
1094         if (o_flag) {
1095                 if (strcmp(o_filename, "-") == 0) {
1096                         o_stdout = 1;
1097                 } else if (stat(o_filename, &sb) == -1) {
1098                         if (errno == ENOENT) {
1099                                 if (argc > 1)
1100                                         errx(1, "%s is not a directory",
1101                                             o_filename);
1102                         } else {
1103                                 err(1, "%s", o_filename);
1104                         }
1105                 } else {
1106                         if (sb.st_mode & S_IFDIR)
1107                                 o_directory = 1;
1108                 }
1109         }
1110
1111         /* check if output is to a tty (for progress report) */
1112         v_tty = isatty(STDERR_FILENO);
1113         if (v_tty)
1114                 pgrp = getpgrp();
1115
1116         r = 0;
1117
1118         /* authentication */
1119         if (v_tty)
1120                 fetchAuthMethod = query_auth;
1121         if (N_filename != NULL)
1122                 if (setenv("NETRC", N_filename, 1) == -1)
1123                         err(1, "setenv: cannot set NETRC=%s", N_filename);
1124
1125         while (argc) {
1126                 if ((p = strrchr(*argv, '/')) == NULL)
1127                         p = *argv;
1128                 else
1129                         p++;
1130
1131                 if (!*p)
1132                         p = "fetch.out";
1133
1134                 fetchLastErrCode = 0;
1135
1136                 if (o_flag) {
1137                         if (o_stdout) {
1138                                 e = fetch(*argv, "-");
1139                         } else if (o_directory) {
1140                                 asprintf(&q, "%s/%s", o_filename, p);
1141                                 e = fetch(*argv, q);
1142                                 free(q);
1143                         } else {
1144                                 e = fetch(*argv, o_filename);
1145                         }
1146                 } else {
1147                         e = fetch(*argv, p);
1148                 }
1149
1150                 if (sigint)
1151                         kill(getpid(), SIGINT);
1152
1153                 if (e == 0 && once_flag)
1154                         exit(0);
1155
1156                 if (e) {
1157                         r = 1;
1158                         if ((fetchLastErrCode
1159                             && fetchLastErrCode != FETCH_UNAVAIL
1160                             && fetchLastErrCode != FETCH_MOVED
1161                             && fetchLastErrCode != FETCH_URL
1162                             && fetchLastErrCode != FETCH_RESOLV
1163                             && fetchLastErrCode != FETCH_UNKNOWN)) {
1164                                 if (w_secs && v_level)
1165                                         fprintf(stderr, "Waiting %ld seconds "
1166                                             "before retrying\n", w_secs);
1167                                 if (w_secs)
1168                                         sleep(w_secs);
1169                                 if (a_flag)
1170                                         continue;
1171                         }
1172                 }
1173
1174                 argc--, argv++;
1175         }
1176
1177         exit(r);
1178 }