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