1 /* $NetBSD: fetch.c,v 1.237 2023/07/02 10:02:09 mlelstv Exp $ */ 2 3 /*- 4 * Copyright (c) 1997-2015 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Luke Mewburn. 9 * 10 * This code is derived from software contributed to The NetBSD Foundation 11 * by Scott Aaron Bamford. 12 * 13 * This code is derived from software contributed to The NetBSD Foundation 14 * by Thomas Klausner. 15 * 16 * Redistribution and use in source and binary forms, with or without 17 * modification, are permitted provided that the following conditions 18 * are met: 19 * 1. Redistributions of source code must retain the above copyright 20 * notice, this list of conditions and the following disclaimer. 21 * 2. Redistributions in binary form must reproduce the above copyright 22 * notice, this list of conditions and the following disclaimer in the 23 * documentation and/or other materials provided with the distribution. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 26 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 27 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 29 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 30 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 31 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 33 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 35 * POSSIBILITY OF SUCH DAMAGE. 36 */ 37 38 #include <sys/cdefs.h> 39 #ifndef lint 40 __RCSID("$NetBSD: fetch.c,v 1.237 2023/07/02 10:02:09 mlelstv Exp $"); 41 #endif /* not lint */ 42 43 /* 44 * FTP User Program -- Command line file retrieval 45 */ 46 47 #include <sys/types.h> 48 #include <sys/param.h> 49 #include <sys/socket.h> 50 #include <sys/stat.h> 51 #include <sys/time.h> 52 53 #include <netinet/in.h> 54 55 #include <arpa/ftp.h> 56 #include <arpa/inet.h> 57 58 #include <assert.h> 59 #include <ctype.h> 60 #include <err.h> 61 #include <errno.h> 62 #include <netdb.h> 63 #include <fcntl.h> 64 #include <stdio.h> 65 #include <stdlib.h> 66 #include <string.h> 67 #include <unistd.h> 68 #include <time.h> 69 70 #include "ssl.h" 71 #include "ftp_var.h" 72 #include "version.h" 73 74 typedef enum { 75 UNKNOWN_URL_T=-1, 76 HTTP_URL_T, 77 HTTPS_URL_T, 78 FTP_URL_T, 79 FILE_URL_T, 80 CLASSIC_URL_T 81 } url_t; 82 83 struct authinfo { 84 char *auth; 85 char *user; 86 char *pass; 87 }; 88 89 struct urlinfo { 90 char *host; 91 char *port; 92 char *path; 93 url_t utype; 94 in_port_t portnum; 95 }; 96 97 struct posinfo { 98 off_t rangestart; 99 off_t rangeend; 100 off_t entitylen; 101 }; 102 103 __dead static void aborthttp(int); 104 __dead static void timeouthttp(int); 105 #ifndef NO_AUTH 106 static int auth_url(const char *, char **, const struct authinfo *); 107 static void base64_encode(const unsigned char *, size_t, unsigned char *); 108 #endif 109 static int go_fetch(const char *, struct urlinfo *); 110 static int fetch_ftp(const char *); 111 static int fetch_url(const char *, const char *, char *, char *, 112 struct urlinfo *); 113 static const char *match_token(const char **, const char *); 114 static int parse_url(const char *, const char *, struct urlinfo *, 115 struct authinfo *, struct urlinfo *); 116 static void url_decode(char *); 117 static void freeauthinfo(struct authinfo *); 118 static void freeurlinfo(struct urlinfo *); 119 120 static int redirect_loop; 121 122 123 #define STRNEQUAL(a,b) (strncasecmp((a), (b), sizeof((b))-1) == 0) 124 #define ISLWS(x) ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t') 125 #define SKIPLWS(x) do { while (ISLWS((*x))) x++; } while (0) 126 127 128 #define ABOUT_URL "about:" /* propaganda */ 129 #define FILE_URL "file://" /* file URL prefix */ 130 #define FTP_URL "ftp://" /* ftp URL prefix */ 131 #define HTTP_URL "http://" /* http URL prefix */ 132 #ifdef WITH_SSL 133 #define HTTPS_URL "https://" /* https URL prefix */ 134 135 #define IS_HTTP_TYPE(urltype) \ 136 (((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T)) 137 #else 138 #define IS_HTTP_TYPE(urltype) \ 139 ((urltype) == HTTP_URL_T) 140 #endif 141 142 /** 143 * fwrite(3) replacement that just uses write(2). Many stdio implementations 144 * don't handle interrupts properly and corrupt the output. We are taking 145 * alarm interrupts because of the progress bar. 146 * 147 * Assumes `fp' is pristine with no prior I/O calls on it. 148 */ 149 static size_t 150 maxwrite(const void *buf, size_t size, size_t nmemb, FILE *fp) 151 { 152 const char *p = buf; 153 ssize_t nwr = 0; 154 ssize_t n; 155 int fd = fileno(fp); 156 157 size *= nmemb; /* assume no overflow */ 158 159 while (size > 0) { 160 if ((n = write(fd, p, size)) == -1) { 161 switch (errno) { 162 case EINTR: 163 case EAGAIN: 164 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN 165 case EWOULDBLOCK: 166 #endif 167 continue; 168 default: 169 return nwr; 170 } 171 } 172 p += n; 173 nwr += n; 174 size -= n; 175 } 176 return nwr; 177 } 178 179 /* 180 * Determine if token is the next word in buf (case insensitive). 181 * If so, advance buf past the token and any trailing LWS, and 182 * return a pointer to the token (in buf). Otherwise, return NULL. 183 * token may be preceded by LWS. 184 * token must be followed by LWS or NUL. (I.e, don't partial match). 185 */ 186 static const char * 187 match_token(const char **buf, const char *token) 188 { 189 const char *p, *orig; 190 size_t tlen; 191 192 tlen = strlen(token); 193 p = *buf; 194 SKIPLWS(p); 195 orig = p; 196 if (strncasecmp(p, token, tlen) != 0) 197 return NULL; 198 p += tlen; 199 if (*p != '\0' && !ISLWS(*p)) 200 return NULL; 201 SKIPLWS(p); 202 orig = *buf; 203 *buf = p; 204 return orig; 205 } 206 207 static void 208 initposinfo(struct posinfo *pi) 209 { 210 pi->rangestart = pi->rangeend = pi->entitylen = -1; 211 } 212 213 static void 214 initauthinfo(struct authinfo *ai, char *auth) 215 { 216 ai->auth = auth; 217 ai->user = ai->pass = 0; 218 } 219 220 static void 221 freeauthinfo(struct authinfo *a) 222 { 223 FREEPTR(a->user); 224 if (a->pass != NULL) 225 memset(a->pass, 0, strlen(a->pass)); 226 FREEPTR(a->pass); 227 } 228 229 static void 230 initurlinfo(struct urlinfo *ui) 231 { 232 ui->host = ui->port = ui->path = 0; 233 ui->utype = UNKNOWN_URL_T; 234 ui->portnum = 0; 235 } 236 237 static void 238 copyurlinfo(struct urlinfo *dui, struct urlinfo *sui) 239 { 240 dui->host = ftp_strdup(sui->host); 241 dui->port = ftp_strdup(sui->port); 242 dui->path = ftp_strdup(sui->path); 243 dui->utype = sui->utype; 244 dui->portnum = sui->portnum; 245 } 246 247 static void 248 freeurlinfo(struct urlinfo *ui) 249 { 250 FREEPTR(ui->host); 251 FREEPTR(ui->port); 252 FREEPTR(ui->path); 253 } 254 255 #ifndef NO_AUTH 256 /* 257 * Generate authorization response based on given authentication challenge. 258 * Returns -1 if an error occurred, otherwise 0. 259 * Sets response to a malloc(3)ed string; caller should free. 260 */ 261 static int 262 auth_url(const char *challenge, char **response, const struct authinfo *auth) 263 { 264 const char *cp, *scheme, *errormsg; 265 char *ep, *clear, *realm; 266 char uuser[BUFSIZ], *gotpass; 267 const char *upass; 268 int rval; 269 size_t len, clen, rlen; 270 271 *response = NULL; 272 clear = realm = NULL; 273 rval = -1; 274 cp = challenge; 275 scheme = "Basic"; /* only support Basic authentication */ 276 gotpass = NULL; 277 278 DPRINTF("%s: challenge `%s'\n", __func__, challenge); 279 280 if (! match_token(&cp, scheme)) { 281 warnx("Unsupported authentication challenge `%s'", 282 challenge); 283 goto cleanup_auth_url; 284 } 285 286 #define REALM "realm=\"" 287 if (STRNEQUAL(cp, REALM)) 288 cp += sizeof(REALM) - 1; 289 else { 290 warnx("Unsupported authentication challenge `%s'", 291 challenge); 292 goto cleanup_auth_url; 293 } 294 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */ 295 if ((ep = strchr(cp, '\"')) != NULL) { 296 len = ep - cp; 297 realm = (char *)ftp_malloc(len + 1); 298 (void)strlcpy(realm, cp, len + 1); 299 } else { 300 warnx("Unsupported authentication challenge `%s'", 301 challenge); 302 goto cleanup_auth_url; 303 } 304 305 fprintf(ttyout, "Username for `%s': ", realm); 306 if (auth->user != NULL) { 307 (void)strlcpy(uuser, auth->user, sizeof(uuser)); 308 fprintf(ttyout, "%s\n", uuser); 309 } else { 310 (void)fflush(ttyout); 311 if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) { 312 warnx("%s; can't authenticate", errormsg); 313 goto cleanup_auth_url; 314 } 315 } 316 if (auth->pass != NULL) 317 upass = auth->pass; 318 else { 319 gotpass = getpass("Password: "); 320 if (gotpass == NULL) { 321 warnx("Can't read password"); 322 goto cleanup_auth_url; 323 } 324 upass = gotpass; 325 } 326 327 clen = strlen(uuser) + strlen(upass) + 2; /* user + ":" + pass + "\0" */ 328 clear = (char *)ftp_malloc(clen); 329 (void)strlcpy(clear, uuser, clen); 330 (void)strlcat(clear, ":", clen); 331 (void)strlcat(clear, upass, clen); 332 if (gotpass) 333 memset(gotpass, 0, strlen(gotpass)); 334 335 /* scheme + " " + enc + "\0" */ 336 rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1; 337 *response = ftp_malloc(rlen); 338 (void)strlcpy(*response, scheme, rlen); 339 len = strlcat(*response, " ", rlen); 340 /* use `clen - 1' to not encode the trailing NUL */ 341 base64_encode((unsigned char *)clear, clen - 1, 342 (unsigned char *)*response + len); 343 memset(clear, 0, clen); 344 rval = 0; 345 346 cleanup_auth_url: 347 FREEPTR(clear); 348 FREEPTR(realm); 349 return (rval); 350 } 351 352 /* 353 * Encode len bytes starting at clear using base64 encoding into encoded, 354 * which should be at least ((len + 2) * 4 / 3 + 1) in size. 355 */ 356 static void 357 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded) 358 { 359 static const unsigned char enc[] = 360 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 361 unsigned char *cp; 362 size_t i; 363 364 cp = encoded; 365 for (i = 0; i < len; i += 3) { 366 *(cp++) = enc[((clear[i + 0] >> 2))]; 367 *(cp++) = enc[((clear[i + 0] << 4) & 0x30) 368 | ((clear[i + 1] >> 4) & 0x0f)]; 369 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c) 370 | ((clear[i + 2] >> 6) & 0x03)]; 371 *(cp++) = enc[((clear[i + 2] ) & 0x3f)]; 372 } 373 *cp = '\0'; 374 while (i-- > len) 375 *(--cp) = '='; 376 } 377 #endif 378 379 /* 380 * Decode %xx escapes in given string, `in-place'. 381 */ 382 static void 383 url_decode(char *url) 384 { 385 unsigned char *p, *q; 386 387 if (EMPTYSTRING(url)) 388 return; 389 p = q = (unsigned char *)url; 390 391 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10)) 392 while (*p) { 393 if (p[0] == '%' 394 && p[1] && isxdigit((unsigned char)p[1]) 395 && p[2] && isxdigit((unsigned char)p[2])) { 396 *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]); 397 p+=3; 398 } else 399 *q++ = *p++; 400 } 401 *q = '\0'; 402 } 403 404 static const char * 405 get_port(const struct urlinfo *ui) 406 { 407 408 switch(ui->utype) { 409 case HTTP_URL_T: 410 return httpport; 411 case FTP_URL_T: 412 return ftpport; 413 case FILE_URL_T: 414 return ""; 415 #ifdef WITH_SSL 416 case HTTPS_URL_T: 417 return httpsport; 418 #endif 419 default: 420 return NULL; 421 } 422 } 423 424 static int 425 use_relative(const struct urlinfo *ui) 426 { 427 if (ui == NULL) 428 return 0; 429 switch (ui->utype) { 430 case HTTP_URL_T: 431 case FILE_URL_T: 432 #ifdef WITH_SSL 433 case HTTPS_URL_T: 434 #endif 435 return 1; 436 default: 437 return 0; 438 } 439 } 440 441 /* 442 * Parse URL of form (per RFC 3986): 443 * <type>://[<user>[:<password>]@]<host>[:<port>][/<path>] 444 * Returns -1 if a parse error occurred, otherwise 0. 445 * It's the caller's responsibility to url_decode() the returned 446 * user, pass and path. 447 * 448 * Sets type to url_t, each of the given char ** pointers to a 449 * malloc(3)ed strings of the relevant section, and port to 450 * the number given, or ftpport if ftp://, or httpport if http://. 451 * 452 * XXX: this is not totally RFC 3986 compliant; <path> will have the 453 * leading `/' unless it's an ftp:// URL, as this makes things easier 454 * for file:// and http:// URLs. ftp:// URLs have the `/' between the 455 * host and the URL-path removed, but any additional leading slashes 456 * in the URL-path are retained (because they imply that we should 457 * later do "CWD" with a null argument). 458 * 459 * Examples: 460 * input URL output path 461 * --------- ----------- 462 * "http://host" "/" 463 * "http://host/" "/" 464 * "http://host/path" "/path" 465 * "file://host/dir/file" "dir/file" 466 * "ftp://host" "" 467 * "ftp://host/" "" 468 * "ftp://host//" "/" 469 * "ftp://host/dir/file" "dir/file" 470 * "ftp://host//dir/file" "/dir/file" 471 */ 472 473 static int 474 parse_url(const char *url, const char *desc, struct urlinfo *ui, 475 struct authinfo *auth, struct urlinfo *rui) 476 { 477 const char *origurl, *tport; 478 char *cp, *ep, *thost; 479 size_t len; 480 481 if (url == NULL || desc == NULL || ui == NULL || auth == NULL) 482 errx(1, "parse_url: invoked with NULL argument!"); 483 DPRINTF("parse_url: %s `%s'\n", desc, url); 484 485 origurl = url; 486 487 if (STRNEQUAL(url, HTTP_URL)) { 488 url += sizeof(HTTP_URL) - 1; 489 ui->utype = HTTP_URL_T; 490 ui->portnum = HTTP_PORT; 491 } else if (STRNEQUAL(url, FTP_URL)) { 492 url += sizeof(FTP_URL) - 1; 493 ui->utype = FTP_URL_T; 494 ui->portnum = FTP_PORT; 495 } else if (STRNEQUAL(url, FILE_URL)) { 496 url += sizeof(FILE_URL) - 1; 497 ui->utype = FILE_URL_T; 498 #ifdef WITH_SSL 499 } else if (STRNEQUAL(url, HTTPS_URL)) { 500 url += sizeof(HTTPS_URL) - 1; 501 ui->utype = HTTPS_URL_T; 502 ui->portnum = HTTPS_PORT; 503 #endif 504 } else if (rui != NULL) { 505 copyurlinfo(ui, rui); 506 } else { 507 warnx("Invalid %s `%s'", desc, url); 508 cleanup_parse_url: 509 freeauthinfo(auth); 510 freeurlinfo(ui); 511 return (-1); 512 } 513 514 515 if (*url == '\0') 516 return (0); 517 518 /* find [user[:pass]@]host[:port] */ 519 ep = strchr(url, '/'); 520 if (ep == NULL) 521 thost = ftp_strdup(url); 522 else { 523 len = ep - url; 524 thost = (char *)ftp_malloc(len + 1); 525 (void)strlcpy(thost, url, len + 1); 526 if (ui->utype == FTP_URL_T) /* skip first / for ftp URLs */ 527 ep++; 528 ui->path = ftp_strdup(ep); 529 } 530 531 cp = strchr(thost, '@'); /* look for user[:pass]@ in URLs */ 532 if (cp != NULL) { 533 if (ui->utype == FTP_URL_T) 534 anonftp = 0; /* disable anonftp */ 535 auth->user = thost; 536 *cp = '\0'; 537 thost = ftp_strdup(cp + 1); 538 cp = strchr(auth->user, ':'); 539 if (cp != NULL) { 540 *cp = '\0'; 541 auth->pass = ftp_strdup(cp + 1); 542 } 543 url_decode(auth->user); 544 if (auth->pass) 545 url_decode(auth->pass); 546 } 547 548 #ifdef INET6 549 /* 550 * Check if thost is an encoded IPv6 address, as per 551 * RFC 3986: 552 * `[' ipv6-address ']' 553 */ 554 if (*thost == '[') { 555 cp = thost + 1; 556 if ((ep = strchr(cp, ']')) == NULL || 557 (ep[1] != '\0' && ep[1] != ':')) { 558 warnx("Invalid address `%s' in %s `%s'", 559 thost, desc, origurl); 560 goto cleanup_parse_url; 561 } 562 len = ep - cp; /* change `[xyz]' -> `xyz' */ 563 memmove(thost, thost + 1, len); 564 thost[len] = '\0'; 565 if (! isipv6addr(thost)) { 566 warnx("Invalid IPv6 address `%s' in %s `%s'", 567 thost, desc, origurl); 568 goto cleanup_parse_url; 569 } 570 cp = ep + 1; 571 if (*cp == ':') 572 cp++; 573 else 574 cp = NULL; 575 } else 576 #endif /* INET6 */ 577 if ((cp = strchr(thost, ':')) != NULL) 578 *cp++ = '\0'; 579 if (*thost != '\0') 580 ui->host = thost; 581 582 /* look for [:port] */ 583 if (cp != NULL) { 584 unsigned long nport; 585 586 nport = strtoul(cp, &ep, 10); 587 if (*cp == '\0' || *ep != '\0' || 588 nport < 1 || nport > MAX_IN_PORT_T) { 589 warnx("Unknown port `%s' in %s `%s'", 590 cp, desc, origurl); 591 goto cleanup_parse_url; 592 } 593 ui->portnum = nport; 594 tport = cp; 595 } else 596 tport = get_port(ui); 597 598 599 if (tport != NULL) 600 ui->port = ftp_strdup(tport); 601 if (ui->path == NULL) { 602 const char *emptypath = "/"; 603 if (ui->utype == FTP_URL_T) /* skip first / for ftp URLs */ 604 emptypath++; 605 ui->path = ftp_strdup(emptypath); 606 } 607 608 DPRINTF("%s: user `%s' pass `%s' host %s port %s(%d) " 609 "path `%s'\n", __func__, 610 STRorNULL(auth->user), STRorNULL(auth->pass), 611 STRorNULL(ui->host), STRorNULL(ui->port), 612 ui->portnum ? ui->portnum : -1, STRorNULL(ui->path)); 613 614 return (0); 615 } 616 617 sigjmp_buf httpabort; 618 619 static int 620 ftp_socket(const struct urlinfo *ui, void **ssl, struct authinfo *auth) 621 { 622 struct addrinfo hints, *res, *res0 = NULL; 623 int error; 624 int s; 625 const char *host = ui->host; 626 const char *port = ui->port; 627 char *fuser = NULL, *pass = NULL, *facct = NULL; 628 int n; 629 630 if (ui->utype != HTTPS_URL_T) 631 ssl = NULL; 632 633 memset(&hints, 0, sizeof(hints)); 634 hints.ai_flags = 0; 635 hints.ai_family = family; 636 hints.ai_socktype = SOCK_STREAM; 637 hints.ai_protocol = 0; 638 639 error = getaddrinfo(host, port, &hints, &res0); 640 if (error) { 641 warnx("Can't LOOKUP `%s:%s': %s", host, port, 642 (error == EAI_SYSTEM) ? strerror(errno) 643 : gai_strerror(error)); 644 return -1; 645 } 646 647 if (res0->ai_canonname) 648 host = res0->ai_canonname; 649 650 s = -1; 651 if (ssl) 652 *ssl = NULL; 653 for (res = res0; res; res = res->ai_next) { 654 char hname[NI_MAXHOST], sname[NI_MAXSERV]; 655 656 ai_unmapped(res); 657 if (getnameinfo(res->ai_addr, res->ai_addrlen, 658 hname, sizeof(hname), sname, sizeof(sname), 659 NI_NUMERICHOST | NI_NUMERICSERV) != 0) { 660 strlcpy(hname, "?", sizeof(hname)); 661 strlcpy(sname, "?", sizeof(sname)); 662 } 663 664 if (verbose && res0->ai_next) { 665 #ifdef INET6 666 if(res->ai_family == AF_INET6) { 667 fprintf(ttyout, "Trying [%s]:%s ...\n", 668 hname, sname); 669 } else { 670 #endif 671 fprintf(ttyout, "Trying %s:%s ...\n", 672 hname, sname); 673 #ifdef INET6 674 } 675 #endif 676 } 677 678 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol); 679 if (s < 0) { 680 warn( 681 "Can't create socket for connection to " 682 "`%s:%s'", hname, sname); 683 continue; 684 } 685 686 if (ftp_connect(s, res->ai_addr, res->ai_addrlen, 687 verbose || !res->ai_next) < 0) { 688 close(s); 689 s = -1; 690 continue; 691 } 692 693 if (ruserpass("", &fuser, &pass, &facct) < 0) { 694 close(s); 695 s = -1; 696 continue; 697 } 698 699 if (autologin) { 700 if (fuser != NULL && auth->user == NULL) 701 auth->user = ftp_strdup(fuser); 702 if (pass != NULL && auth->pass == NULL) 703 auth->pass = ftp_strdup(pass); 704 } 705 706 for (n = 0; n < macnum; ++n) { 707 if (!strcmp("init", macros[n].mac_name)) { 708 (void)strlcpy(line, "$init", sizeof(line)); 709 makeargv(); 710 domacro(margc, margv); 711 break; 712 } 713 } 714 715 #ifdef WITH_SSL 716 if (ssl) { 717 if ((*ssl = fetch_start_ssl(s, host)) == NULL) { 718 close(s); 719 s = -1; 720 continue; 721 } 722 } 723 #endif 724 break; 725 } 726 727 FREEPTR(fuser); 728 if (pass != NULL) 729 memset(pass, 0, strlen(pass)); 730 FREEPTR(pass); 731 if (facct != NULL) 732 memset(facct, 0, strlen(facct)); 733 FREEPTR(facct); 734 735 if (res0) 736 freeaddrinfo(res0); 737 return s; 738 } 739 740 static int 741 handle_noproxy(const char *host, in_port_t portnum) 742 { 743 744 char *cp, *ep, *np, *np_copy, *np_iter, *no_proxy; 745 unsigned long np_port; 746 size_t hlen, plen; 747 int isproxy = 1; 748 749 /* check URL against list of no_proxied sites */ 750 no_proxy = getoptionvalue("no_proxy"); 751 if (EMPTYSTRING(no_proxy)) 752 return isproxy; 753 754 np_iter = np_copy = ftp_strdup(no_proxy); 755 hlen = strlen(host); 756 while ((cp = strsep(&np_iter, " ,")) != NULL) { 757 if (*cp == '\0') 758 continue; 759 if ((np = strrchr(cp, ':')) != NULL) { 760 *np++ = '\0'; 761 np_port = strtoul(np, &ep, 10); 762 if (*np == '\0' || *ep != '\0') 763 continue; 764 if (np_port != portnum) 765 continue; 766 } 767 plen = strlen(cp); 768 if (hlen < plen) 769 continue; 770 if (strncasecmp(host + hlen - plen, cp, plen) == 0) { 771 isproxy = 0; 772 break; 773 } 774 } 775 FREEPTR(np_copy); 776 return isproxy; 777 } 778 779 static int 780 handle_proxy(const char *url, const char *penv, struct urlinfo *ui, 781 struct authinfo *pauth) 782 { 783 struct urlinfo pui; 784 785 if (isipv6addr(ui->host) && strchr(ui->host, '%') != NULL) { 786 warnx("Scoped address notation `%s' disallowed via web proxy", 787 ui->host); 788 return -1; 789 } 790 791 initurlinfo(&pui); 792 if (parse_url(penv, "proxy URL", &pui, pauth, NULL) == -1) 793 return -1; 794 795 if ((!IS_HTTP_TYPE(pui.utype) && pui.utype != FTP_URL_T) || 796 EMPTYSTRING(pui.host) || 797 (! EMPTYSTRING(pui.path) && strcmp(pui.path, "/") != 0)) { 798 warnx("Malformed proxy URL `%s'", penv); 799 freeurlinfo(&pui); 800 return -1; 801 } 802 803 FREEPTR(pui.path); 804 #ifdef WITH_SSL 805 if (ui->utype == HTTPS_URL_T) 806 pui.path = ftp_strdup(ui->path); 807 else 808 #endif 809 pui.path = ftp_strdup(url); 810 811 freeurlinfo(ui); 812 *ui = pui; 813 814 return 0; 815 } 816 817 static void 818 print_host(FETCH *fin, const struct urlinfo *ui) 819 { 820 char *h, *p; 821 822 if (strchr(ui->host, ':') == NULL) { 823 fetch_printf(fin, "Host: %s", ui->host); 824 } else { 825 /* 826 * strip off IPv6 scope identifier, since it is 827 * local to the node 828 */ 829 h = ftp_strdup(ui->host); 830 if (isipv6addr(h) && (p = strchr(h, '%')) != NULL) 831 *p = '\0'; 832 833 fetch_printf(fin, "Host: [%s]", h); 834 free(h); 835 } 836 837 if ((ui->utype == HTTP_URL_T && ui->portnum != HTTP_PORT) || 838 (ui->utype == HTTPS_URL_T && ui->portnum != HTTPS_PORT)) 839 fetch_printf(fin, ":%u", ui->portnum); 840 fetch_printf(fin, "\r\n"); 841 } 842 843 static void 844 print_agent(FETCH *fin) 845 { 846 const char *useragent; 847 if ((useragent = getenv("FTPUSERAGENT")) != NULL) { 848 fetch_printf(fin, "User-Agent: %s\r\n", useragent); 849 } else { 850 fetch_printf(fin, "User-Agent: %s/%s\r\n", 851 FTP_PRODUCT, FTP_VERSION); 852 } 853 } 854 855 static void 856 print_cache(FETCH *fin, int isproxy) 857 { 858 fetch_printf(fin, isproxy ? 859 "Pragma: no-cache\r\n" : 860 "Cache-Control: no-cache\r\n"); 861 } 862 863 static int 864 print_get(FETCH *fin, int hasleading, int isproxy, const struct urlinfo *oui, 865 const struct urlinfo *ui) 866 { 867 const char *leading = hasleading ? ", " : " ("; 868 869 if (isproxy) { 870 if (verbose) { 871 fprintf(ttyout, "%svia %s:%u", leading, 872 ui->host, ui->portnum); 873 leading = ", "; 874 hasleading++; 875 } 876 fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path); 877 print_host(fin, oui); 878 return hasleading; 879 } 880 881 fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path); 882 print_host(fin, ui); 883 fetch_printf(fin, "Accept: */*\r\n"); 884 fetch_printf(fin, "Connection: close\r\n"); 885 if (restart_point) { 886 fputs(leading, ttyout); 887 fetch_printf(fin, "Range: bytes=" LLF "-\r\n", 888 (LLT)restart_point); 889 fprintf(ttyout, "restarting at " LLF, (LLT)restart_point); 890 hasleading++; 891 } 892 return hasleading; 893 } 894 895 static void 896 getmtime(const char *cp, time_t *mtime) 897 { 898 struct tm parsed; 899 const char *t; 900 901 memset(&parsed, 0, sizeof(parsed)); 902 t = parse_rfc2616time(&parsed, cp); 903 904 if (t == NULL) 905 return; 906 907 parsed.tm_isdst = -1; 908 if (*t == '\0') 909 *mtime = timegm(&parsed); 910 911 #ifndef NO_DEBUG 912 if (ftp_debug && *mtime != -1) { 913 fprintf(ttyout, "parsed time as: %s", 914 rfc2822time(localtime(mtime))); 915 } 916 #endif 917 } 918 919 static int 920 print_proxy(FETCH *fin, int hasleading, const char *wwwauth, 921 const char *proxyauth) 922 { 923 const char *leading = hasleading ? ", " : " ("; 924 925 if (wwwauth) { 926 if (verbose) { 927 fprintf(ttyout, "%swith authorization", leading); 928 hasleading++; 929 } 930 fetch_printf(fin, "Authorization: %s\r\n", wwwauth); 931 } 932 if (proxyauth) { 933 if (verbose) { 934 fprintf(ttyout, "%swith proxy authorization", leading); 935 hasleading++; 936 } 937 fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth); 938 } 939 return hasleading; 940 } 941 942 #ifdef WITH_SSL 943 static void 944 print_connect(FETCH *fin, const struct urlinfo *ui) 945 { 946 char hname[NI_MAXHOST], *p; 947 const char *h; 948 949 if (isipv6addr(ui->host)) { 950 /* 951 * strip off IPv6 scope identifier, 952 * since it is local to the node 953 */ 954 if ((p = strchr(ui->host, '%')) == NULL) 955 snprintf(hname, sizeof(hname), "[%s]", ui->host); 956 else 957 snprintf(hname, sizeof(hname), "[%.*s]", 958 (int)(p - ui->host), ui->host); 959 h = hname; 960 } else 961 h = ui->host; 962 963 fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum); 964 fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum); 965 } 966 #endif 967 968 #define C_OK 0 969 #define C_CLEANUP 1 970 #define C_IMPROPER 2 971 972 static int 973 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len) 974 { 975 const char *errormsg; 976 977 alarmtimer(quit_time ? quit_time : 60); 978 *len = fetch_getline(fin, buf, buflen, &errormsg); 979 alarmtimer(0); 980 if (*len < 0) { 981 if (*errormsg == '\n') 982 errormsg++; 983 warnx("Receiving HTTP reply: %s", errormsg); 984 return C_CLEANUP; 985 } 986 while (*len > 0 && (ISLWS(buf[*len-1]))) 987 buf[--*len] = '\0'; 988 989 if (*len) 990 DPRINTF("%s: received `%s'\n", __func__, buf); 991 return C_OK; 992 } 993 994 static int 995 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode) 996 { 997 int len, rv; 998 char *ep, *buf = *cp; 999 1000 *hcode = 0; 1001 if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK) 1002 return rv; 1003 1004 /* Determine HTTP response code */ 1005 *cp = strchr(buf, ' '); 1006 if (*cp == NULL) 1007 return C_IMPROPER; 1008 1009 (*cp)++; 1010 1011 *hcode = strtol(*cp, &ep, 10); 1012 if (*ep != '\0' && !isspace((unsigned char)*ep)) 1013 return C_IMPROPER; 1014 1015 return C_OK; 1016 } 1017 1018 static int 1019 parse_posinfo(const char **cp, struct posinfo *pi) 1020 { 1021 char *ep; 1022 if (!match_token(cp, "bytes")) 1023 return -1; 1024 1025 if (**cp == '*') 1026 (*cp)++; 1027 else { 1028 pi->rangestart = STRTOLL(*cp, &ep, 10); 1029 if (pi->rangestart < 0 || *ep != '-') 1030 return -1; 1031 *cp = ep + 1; 1032 pi->rangeend = STRTOLL(*cp, &ep, 10); 1033 if (pi->rangeend < 0 || pi->rangeend < pi->rangestart) 1034 return -1; 1035 *cp = ep; 1036 } 1037 if (**cp != '/') 1038 return -1; 1039 (*cp)++; 1040 if (**cp == '*') 1041 (*cp)++; 1042 else { 1043 pi->entitylen = STRTOLL(*cp, &ep, 10); 1044 if (pi->entitylen < 0) 1045 return -1; 1046 *cp = ep; 1047 } 1048 if (**cp != '\0') 1049 return -1; 1050 1051 #ifndef NO_DEBUG 1052 if (ftp_debug) { 1053 fprintf(ttyout, "parsed range as: "); 1054 if (pi->rangestart == -1) 1055 fprintf(ttyout, "*"); 1056 else 1057 fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart, 1058 (LLT)pi->rangeend); 1059 fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen); 1060 } 1061 #endif 1062 return 0; 1063 } 1064 1065 #ifndef NO_AUTH 1066 static void 1067 do_auth(int hcode, const char *url, const char *penv, struct authinfo *wauth, 1068 struct authinfo *pauth, char **auth, const char *message, 1069 volatile int *rval, struct urlinfo *ui) 1070 { 1071 struct authinfo aauth; 1072 char *response; 1073 1074 if (hcode == 401) 1075 aauth = *wauth; 1076 else 1077 aauth = *pauth; 1078 1079 if (verbose || aauth.auth == NULL || 1080 aauth.user == NULL || aauth.pass == NULL) 1081 fprintf(ttyout, "%s\n", message); 1082 if (EMPTYSTRING(*auth)) { 1083 warnx("No authentication challenge provided by server"); 1084 return; 1085 } 1086 1087 if (aauth.auth != NULL) { 1088 char reply[10]; 1089 1090 fprintf(ttyout, "Authorization failed. Retry (y/n)? "); 1091 if (get_line(stdin, reply, sizeof(reply), NULL) < 0) { 1092 return; 1093 } 1094 if (tolower((unsigned char)reply[0]) != 'y') 1095 return; 1096 1097 aauth.user = NULL; 1098 aauth.pass = NULL; 1099 } 1100 1101 if (auth_url(*auth, &response, &aauth) == 0) { 1102 *rval = fetch_url(url, penv, 1103 hcode == 401 ? pauth->auth : response, 1104 hcode == 401 ? response : wauth->auth, 1105 ui); 1106 memset(response, 0, strlen(response)); 1107 FREEPTR(response); 1108 } 1109 } 1110 #endif 1111 1112 static int 1113 negotiate_connection(FETCH *fin, const char *url, const char *penv, 1114 struct posinfo *pi, time_t *mtime, struct authinfo *wauth, 1115 struct authinfo *pauth, volatile int *rval, volatile int *ischunked, 1116 char **auth, struct urlinfo *ui) 1117 { 1118 int len, hcode, rv; 1119 char buf[FTPBUFLEN], *ep; 1120 const char *cp, *token; 1121 char *location, *message; 1122 1123 *auth = message = location = NULL; 1124 1125 /* Read the response */ 1126 ep = buf; 1127 switch (getresponse(fin, &ep, sizeof(buf), &hcode)) { 1128 case C_CLEANUP: 1129 goto cleanup_fetch_url; 1130 case C_IMPROPER: 1131 goto improper; 1132 case C_OK: 1133 message = ftp_strdup(ep); 1134 break; 1135 } 1136 1137 /* Read the rest of the header. */ 1138 1139 for (;;) { 1140 if ((rv = getresponseline(fin, buf, sizeof(buf), &len)) != C_OK) 1141 goto cleanup_fetch_url; 1142 if (len == 0) 1143 break; 1144 1145 /* 1146 * Look for some headers 1147 */ 1148 1149 cp = buf; 1150 1151 if (match_token(&cp, "Content-Length:")) { 1152 filesize = STRTOLL(cp, &ep, 10); 1153 if (filesize < 0 || *ep != '\0') 1154 goto improper; 1155 DPRINTF("%s: parsed len as: " LLF "\n", 1156 __func__, (LLT)filesize); 1157 1158 } else if (match_token(&cp, "Content-Range:")) { 1159 if (parse_posinfo(&cp, pi) == -1) 1160 goto improper; 1161 if (! restart_point) { 1162 warnx( 1163 "Received unexpected Content-Range header"); 1164 goto cleanup_fetch_url; 1165 } 1166 1167 } else if (match_token(&cp, "Last-Modified:")) { 1168 getmtime(cp, mtime); 1169 1170 } else if (match_token(&cp, "Location:")) { 1171 location = ftp_strdup(cp); 1172 DPRINTF("%s: parsed location as `%s'\n", 1173 __func__, cp); 1174 1175 } else if (match_token(&cp, "Transfer-Encoding:")) { 1176 if (match_token(&cp, "binary")) { 1177 warnx( 1178 "Bogus transfer encoding `binary' (fetching anyway)"); 1179 continue; 1180 } 1181 if (! (token = match_token(&cp, "chunked"))) { 1182 warnx( 1183 "Unsupported transfer encoding `%s'", 1184 token); 1185 goto cleanup_fetch_url; 1186 } 1187 (*ischunked)++; 1188 DPRINTF("%s: using chunked encoding\n", 1189 __func__); 1190 1191 } else if (match_token(&cp, "Proxy-Authenticate:") 1192 || match_token(&cp, "WWW-Authenticate:")) { 1193 if (! (token = match_token(&cp, "Basic"))) { 1194 DPRINTF("%s: skipping unknown auth " 1195 "scheme `%s'\n", __func__, token); 1196 continue; 1197 } 1198 FREEPTR(*auth); 1199 *auth = ftp_strdup(token); 1200 DPRINTF("%s: parsed auth as `%s'\n", 1201 __func__, cp); 1202 } 1203 1204 } 1205 /* finished parsing header */ 1206 1207 switch (hcode) { 1208 case 200: 1209 break; 1210 case 206: 1211 if (! restart_point) { 1212 warnx("Not expecting partial content header"); 1213 goto cleanup_fetch_url; 1214 } 1215 break; 1216 case 300: 1217 case 301: 1218 case 302: 1219 case 303: 1220 case 305: 1221 case 307: 1222 if (EMPTYSTRING(location)) { 1223 warnx( 1224 "No redirection Location provided by server"); 1225 goto cleanup_fetch_url; 1226 } 1227 if (redirect_loop++ > 5) { 1228 warnx("Too many redirections requested"); 1229 goto cleanup_fetch_url; 1230 } 1231 if (hcode == 305) { 1232 if (verbose) 1233 fprintf(ttyout, "Redirected via %s\n", 1234 location); 1235 *rval = fetch_url(url, location, 1236 pauth->auth, wauth->auth, ui); 1237 } else { 1238 if (verbose) 1239 fprintf(ttyout, "Redirected to %s\n", 1240 location); 1241 *rval = go_fetch(location, ui); 1242 } 1243 goto cleanup_fetch_url; 1244 #ifndef NO_AUTH 1245 case 401: 1246 case 407: 1247 do_auth(hcode, url, penv, wauth, pauth, auth, message, rval, 1248 ui); 1249 goto cleanup_fetch_url; 1250 #endif 1251 default: 1252 if (message) 1253 warnx("Error retrieving file `%s'", message); 1254 else 1255 warnx("Unknown error retrieving file"); 1256 goto cleanup_fetch_url; 1257 } 1258 rv = C_OK; 1259 goto out; 1260 1261 cleanup_fetch_url: 1262 rv = C_CLEANUP; 1263 goto out; 1264 improper: 1265 rv = C_IMPROPER; 1266 goto out; 1267 out: 1268 FREEPTR(message); 1269 FREEPTR(location); 1270 return rv; 1271 } /* end of ftp:// or http:// specific setup */ 1272 1273 #ifdef WITH_SSL 1274 static int 1275 connectmethod(FETCH *fin, const char *url, const char *penv, 1276 struct urlinfo *oui, struct urlinfo *ui, struct authinfo *wauth, 1277 struct authinfo *pauth, char **auth, int *hasleading, volatile int *rval) 1278 { 1279 void *ssl; 1280 int hcode, rv; 1281 const char *cp; 1282 char buf[FTPBUFLEN], *ep; 1283 char *message = NULL; 1284 1285 print_connect(fin, oui); 1286 1287 print_agent(fin); 1288 *hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth); 1289 1290 if (verbose && *hasleading) 1291 fputs(")\n", ttyout); 1292 *hasleading = 0; 1293 1294 fetch_printf(fin, "\r\n"); 1295 if (fetch_flush(fin) == EOF) { 1296 warn("Writing HTTP request"); 1297 alarmtimer(0); 1298 goto cleanup_fetch_url; 1299 } 1300 alarmtimer(0); 1301 1302 /* Read the response */ 1303 ep = buf; 1304 switch (getresponse(fin, &ep, sizeof(buf), &hcode)) { 1305 case C_CLEANUP: 1306 goto cleanup_fetch_url; 1307 case C_IMPROPER: 1308 goto improper; 1309 case C_OK: 1310 message = ftp_strdup(ep); 1311 break; 1312 } 1313 1314 for (;;) { 1315 int len; 1316 if (getresponseline(fin, buf, sizeof(buf), &len) != C_OK) 1317 goto cleanup_fetch_url; 1318 if (len == 0) 1319 break; 1320 1321 cp = buf; 1322 if (match_token(&cp, "Proxy-Authenticate:")) { 1323 const char *token; 1324 if (!(token = match_token(&cp, "Basic"))) { 1325 DPRINTF( 1326 "%s: skipping unknown auth scheme `%s'\n", 1327 __func__, token); 1328 continue; 1329 } 1330 FREEPTR(*auth); 1331 *auth = ftp_strdup(token); 1332 DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp); 1333 } 1334 } 1335 1336 /* finished parsing header */ 1337 switch (hcode) { 1338 case 200: 1339 break; 1340 #ifndef NO_AUTH 1341 case 407: 1342 do_auth(hcode, url, penv, wauth, pauth, auth, message, rval, 1343 ui); 1344 goto cleanup_fetch_url; 1345 #endif 1346 default: 1347 if (message) 1348 warnx("Error proxy connect " "`%s'", message); 1349 else 1350 warnx("Unknown error proxy " "connect"); 1351 goto cleanup_fetch_url; 1352 } 1353 1354 if ((ssl = fetch_start_ssl(fetch_fileno(fin), oui->host)) == NULL) 1355 goto cleanup_fetch_url; 1356 fetch_set_ssl(fin, ssl); 1357 1358 rv = C_OK; 1359 goto out; 1360 improper: 1361 rv = C_IMPROPER; 1362 goto out; 1363 cleanup_fetch_url: 1364 rv = C_CLEANUP; 1365 goto out; 1366 out: 1367 FREEPTR(message); 1368 return rv; 1369 } 1370 #endif 1371 1372 /* 1373 * Retrieve URL, via a proxy if necessary, using HTTP. 1374 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or 1375 * http_proxy/https_proxy as appropriate. 1376 * Supports HTTP redirects. 1377 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection 1378 * is still open (e.g, ftp xfer with trailing /) 1379 */ 1380 static int 1381 fetch_url(const char *url, const char *proxyenv, char *proxyauth, 1382 char *wwwauth, struct urlinfo *rui) 1383 { 1384 sigfunc volatile oldint; 1385 sigfunc volatile oldpipe; 1386 sigfunc volatile oldalrm; 1387 sigfunc volatile oldquit; 1388 int volatile s; 1389 struct stat sb; 1390 int volatile isproxy; 1391 int volatile rval, ischunked; 1392 size_t flen; 1393 static size_t bufsize; 1394 static char *xferbuf; 1395 const char *cp; 1396 char *ep; 1397 char *volatile auth; 1398 char *volatile savefile; 1399 char *volatile location; 1400 char *volatile message; 1401 char *volatile decodedpath; 1402 struct authinfo wauth, pauth; 1403 struct posinfo pi; 1404 off_t hashbytes; 1405 int (*volatile closefunc)(FILE *); 1406 FETCH *volatile fin; 1407 FILE *volatile fout; 1408 const char *volatile penv = proxyenv; 1409 struct urlinfo ui, oui; 1410 time_t mtime; 1411 void *ssl = NULL; 1412 1413 DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv)); 1414 1415 oldquit = oldalrm = oldint = oldpipe = SIG_ERR; 1416 closefunc = NULL; 1417 fin = NULL; 1418 fout = NULL; 1419 s = -1; 1420 savefile = NULL; 1421 auth = location = message = NULL; 1422 ischunked = isproxy = 0; 1423 rval = 1; 1424 1425 initurlinfo(&ui); 1426 initurlinfo(&oui); 1427 initauthinfo(&wauth, wwwauth); 1428 initauthinfo(&pauth, proxyauth); 1429 1430 decodedpath = NULL; 1431 1432 if (sigsetjmp(httpabort, 1)) 1433 goto cleanup_fetch_url; 1434 1435 if (parse_url(url, "URL", &ui, &wauth, rui) == -1) 1436 goto cleanup_fetch_url; 1437 1438 copyurlinfo(&oui, &ui); 1439 1440 if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host) 1441 && strcasecmp(ui.host, "localhost") != 0) { 1442 warnx("No support for non local file URL `%s'", url); 1443 goto cleanup_fetch_url; 1444 } 1445 1446 if (EMPTYSTRING(ui.path)) { 1447 if (ui.utype == FTP_URL_T) { 1448 rval = fetch_ftp(url); 1449 goto cleanup_fetch_url; 1450 } 1451 if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL) { 1452 warnx("Invalid URL (no file after host) `%s'", url); 1453 goto cleanup_fetch_url; 1454 } 1455 } 1456 1457 decodedpath = ftp_strdup(ui.path); 1458 url_decode(decodedpath); 1459 1460 if (outfile) 1461 savefile = outfile; 1462 else { 1463 cp = strrchr(decodedpath, '/'); /* find savefile */ 1464 if (cp != NULL) 1465 savefile = ftp_strdup(cp + 1); 1466 else 1467 savefile = ftp_strdup(decodedpath); 1468 /* 1469 * Use the first URL we requested not the name after a 1470 * possible redirect, but careful to save it because our 1471 * "safety" check is the match to outfile. 1472 */ 1473 outfile = ftp_strdup(savefile); 1474 } 1475 DPRINTF("%s: savefile `%s'\n", __func__, savefile); 1476 if (EMPTYSTRING(savefile)) { 1477 if (ui.utype == FTP_URL_T) { 1478 rval = fetch_ftp(url); 1479 goto cleanup_fetch_url; 1480 } 1481 warnx("No file after directory (you must specify an " 1482 "output file) `%s'", url); 1483 goto cleanup_fetch_url; 1484 } 1485 1486 restart_point = 0; 1487 filesize = -1; 1488 initposinfo(&pi); 1489 mtime = -1; 1490 if (restartautofetch) { 1491 if (stat(savefile, &sb) == 0) 1492 restart_point = sb.st_size; 1493 } 1494 if (ui.utype == FILE_URL_T) { /* file:// URLs */ 1495 direction = "copied"; 1496 fin = fetch_open(decodedpath, "r"); 1497 if (fin == NULL) { 1498 warn("Can't open `%s'", decodedpath); 1499 goto cleanup_fetch_url; 1500 } 1501 if (fstat(fetch_fileno(fin), &sb) == 0) { 1502 mtime = sb.st_mtime; 1503 filesize = sb.st_size; 1504 } 1505 if (restart_point) { 1506 if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) 1507 < 0) { 1508 warn("Can't seek to restart `%s'", 1509 decodedpath); 1510 goto cleanup_fetch_url; 1511 } 1512 } 1513 if (verbose) { 1514 fprintf(ttyout, "Copying %s", decodedpath); 1515 if (restart_point) 1516 fprintf(ttyout, " (restarting at " LLF ")", 1517 (LLT)restart_point); 1518 fputs("\n", ttyout); 1519 } 1520 if (0 == rcvbuf_size) { 1521 rcvbuf_size = 8 * 1024; /* XXX */ 1522 } 1523 } else { /* ftp:// or http:// URLs */ 1524 int hasleading; 1525 static char hostnamebuf[MAXHOSTNAMELEN]; 1526 1527 (void)strlcpy(hostnamebuf, ui.host, sizeof(hostnamebuf)); 1528 hostname = hostnamebuf; 1529 1530 if (penv == NULL) { 1531 #ifdef WITH_SSL 1532 if (ui.utype == HTTPS_URL_T) 1533 penv = getoptionvalue("https_proxy"); 1534 #endif 1535 if (penv == NULL && IS_HTTP_TYPE(ui.utype)) 1536 penv = getoptionvalue("http_proxy"); 1537 else if (ui.utype == FTP_URL_T) 1538 penv = getoptionvalue("ftp_proxy"); 1539 } 1540 direction = "retrieved"; 1541 if (! EMPTYSTRING(penv)) { /* use proxy */ 1542 1543 isproxy = handle_noproxy(ui.host, ui.portnum); 1544 1545 if (isproxy == 0 && ui.utype == FTP_URL_T) { 1546 rval = fetch_ftp(url); 1547 goto cleanup_fetch_url; 1548 } 1549 1550 if (isproxy) { 1551 if (restart_point) { 1552 warnx( 1553 "Can't restart via proxy URL `%s'", 1554 penv); 1555 goto cleanup_fetch_url; 1556 } 1557 if (handle_proxy(url, penv, &ui, &pauth) < 0) 1558 goto cleanup_fetch_url; 1559 } 1560 } /* ! EMPTYSTRING(penv) */ 1561 1562 s = ftp_socket(&ui, &ssl, &wauth); 1563 if (s < 0) { 1564 warnx("Can't connect to `%s:%s'", ui.host, ui.port); 1565 goto cleanup_fetch_url; 1566 } 1567 1568 oldalrm = xsignal(SIGALRM, timeouthttp); 1569 alarmtimer(quit_time ? quit_time : 60); 1570 fin = fetch_fdopen(s, "r+"); 1571 fetch_set_ssl(fin, ssl); 1572 alarmtimer(0); 1573 1574 alarmtimer(quit_time ? quit_time : 60); 1575 /* 1576 * Construct and send the request. 1577 */ 1578 if (verbose) 1579 fprintf(ttyout, "Requesting %s\n", url); 1580 1581 hasleading = 0; 1582 #ifdef WITH_SSL 1583 if (isproxy && oui.utype == HTTPS_URL_T) { 1584 switch (connectmethod(fin, url, penv, &oui, &ui, 1585 &wauth, &pauth, __UNVOLATILE(&auth), &hasleading, 1586 &rval)) { 1587 case C_CLEANUP: 1588 goto cleanup_fetch_url; 1589 case C_IMPROPER: 1590 goto improper; 1591 case C_OK: 1592 break; 1593 default: 1594 abort(); 1595 } 1596 } 1597 #endif 1598 1599 hasleading = print_get(fin, hasleading, isproxy, &oui, &ui); 1600 1601 if (flushcache) 1602 print_cache(fin, isproxy); 1603 1604 print_agent(fin); 1605 hasleading = print_proxy(fin, hasleading, wauth.auth, 1606 auth ? NULL : pauth.auth); 1607 if (hasleading) { 1608 hasleading = 0; 1609 if (verbose) 1610 fputs(")\n", ttyout); 1611 } 1612 1613 fetch_printf(fin, "\r\n"); 1614 if (fetch_flush(fin) == EOF) { 1615 warn("Writing HTTP request"); 1616 alarmtimer(0); 1617 goto cleanup_fetch_url; 1618 } 1619 alarmtimer(0); 1620 1621 switch (negotiate_connection(fin, url, penv, &pi, 1622 &mtime, &wauth, &pauth, &rval, &ischunked, 1623 __UNVOLATILE(&auth), &ui)) { 1624 case C_OK: 1625 break; 1626 case C_CLEANUP: 1627 goto cleanup_fetch_url; 1628 case C_IMPROPER: 1629 goto improper; 1630 default: 1631 abort(); 1632 } 1633 } 1634 1635 /* Open the output file. */ 1636 1637 /* 1638 * Only trust filenames with special meaning if they came from 1639 * the command line 1640 */ 1641 if (outfile == savefile) { 1642 if (strcmp(savefile, "-") == 0) { 1643 fout = stdout; 1644 } else if (*savefile == '|') { 1645 oldpipe = xsignal(SIGPIPE, SIG_IGN); 1646 fout = popen(savefile + 1, "w"); 1647 if (fout == NULL) { 1648 warn("Can't execute `%s'", savefile + 1); 1649 goto cleanup_fetch_url; 1650 } 1651 closefunc = pclose; 1652 } 1653 } 1654 if (fout == NULL) { 1655 if ((pi.rangeend != -1 && pi.rangeend <= restart_point) || 1656 (pi.rangestart == -1 && 1657 filesize != -1 && filesize <= restart_point)) { 1658 /* already done */ 1659 if (verbose) 1660 fprintf(ttyout, "already done\n"); 1661 rval = 0; 1662 goto cleanup_fetch_url; 1663 } 1664 if (restart_point && pi.rangestart != -1) { 1665 if (pi.entitylen != -1) 1666 filesize = pi.entitylen; 1667 if (pi.rangestart != restart_point) { 1668 warnx( 1669 "Size of `%s' differs from save file `%s'", 1670 url, savefile); 1671 goto cleanup_fetch_url; 1672 } 1673 fout = fopen(savefile, "a"); 1674 } else 1675 fout = fopen(savefile, "w"); 1676 if (fout == NULL) { 1677 warn("Can't open `%s'", savefile); 1678 goto cleanup_fetch_url; 1679 } 1680 closefunc = fclose; 1681 } 1682 1683 /* Trap signals */ 1684 oldquit = xsignal(SIGQUIT, psummary); 1685 oldint = xsignal(SIGINT, aborthttp); 1686 1687 assert(rcvbuf_size > 0); 1688 if ((size_t)rcvbuf_size > bufsize) { 1689 if (xferbuf) 1690 (void)free(xferbuf); 1691 bufsize = rcvbuf_size; 1692 xferbuf = ftp_malloc(bufsize); 1693 } 1694 1695 bytes = 0; 1696 hashbytes = mark; 1697 if (oldalrm != SIG_ERR) { 1698 (void)xsignal(SIGALRM, oldalrm); 1699 oldalrm = SIG_ERR; 1700 } 1701 progressmeter(-1); 1702 1703 /* Finally, suck down the file. */ 1704 do { 1705 long chunksize; 1706 short lastchunk; 1707 1708 chunksize = 0; 1709 lastchunk = 0; 1710 /* read chunk-size */ 1711 if (ischunked) { 1712 if (fetch_getln(xferbuf, bufsize, fin) == NULL) { 1713 warnx("Unexpected EOF reading chunk-size"); 1714 goto cleanup_fetch_url; 1715 } 1716 errno = 0; 1717 chunksize = strtol(xferbuf, &ep, 16); 1718 if (ep == xferbuf) { 1719 warnx("Invalid chunk-size"); 1720 goto cleanup_fetch_url; 1721 } 1722 if (errno == ERANGE || chunksize < 0) { 1723 errno = ERANGE; 1724 warn("Chunk-size `%.*s'", 1725 (int)(ep-xferbuf), xferbuf); 1726 goto cleanup_fetch_url; 1727 } 1728 1729 /* 1730 * XXX: Work around bug in Apache 1.3.9 and 1731 * 1.3.11, which incorrectly put trailing 1732 * space after the chunk-size. 1733 */ 1734 while (*ep == ' ') 1735 ep++; 1736 1737 /* skip [ chunk-ext ] */ 1738 if (*ep == ';') { 1739 while (*ep && *ep != '\r') 1740 ep++; 1741 } 1742 1743 if (strcmp(ep, "\r\n") != 0) { 1744 warnx("Unexpected data following chunk-size"); 1745 goto cleanup_fetch_url; 1746 } 1747 DPRINTF("%s: got chunk-size of " LLF "\n", __func__, 1748 (LLT)chunksize); 1749 if (chunksize == 0) { 1750 lastchunk = 1; 1751 goto chunkdone; 1752 } 1753 } 1754 /* transfer file or chunk */ 1755 while (1) { 1756 struct timeval then, now, td; 1757 volatile off_t bufrem; 1758 1759 if (rate_get) 1760 (void)gettimeofday(&then, NULL); 1761 bufrem = rate_get ? rate_get : (off_t)bufsize; 1762 if (ischunked) 1763 bufrem = MIN(chunksize, bufrem); 1764 while (bufrem > 0) { 1765 size_t nr = MIN((off_t)bufsize, bufrem); 1766 flen = fetch_read(xferbuf, sizeof(char), 1767 nr, fin); 1768 if (flen == 0) { 1769 if (fetch_error(fin)) 1770 goto chunkerror; 1771 goto chunkdone; 1772 } 1773 bytes += flen; 1774 bufrem -= flen; 1775 if (maxwrite(xferbuf, sizeof(char), flen, fout) 1776 != flen) { 1777 warn("Writing `%s'", savefile); 1778 goto cleanup_fetch_url; 1779 } 1780 if (hash && !progress) { 1781 while (bytes >= hashbytes) { 1782 (void)putc('#', ttyout); 1783 hashbytes += mark; 1784 } 1785 (void)fflush(ttyout); 1786 } 1787 if (ischunked) { 1788 chunksize -= flen; 1789 if (chunksize <= 0) 1790 break; 1791 } 1792 } 1793 if (rate_get) { 1794 while (1) { 1795 (void)gettimeofday(&now, NULL); 1796 timersub(&now, &then, &td); 1797 if (td.tv_sec > 0) 1798 break; 1799 usleep(1000000 - td.tv_usec); 1800 } 1801 } 1802 if (ischunked && chunksize <= 0) 1803 break; 1804 } 1805 /* read CRLF after chunk*/ 1806 chunkdone: 1807 if (ischunked) { 1808 if (fetch_getln(xferbuf, bufsize, fin) == NULL) { 1809 alarmtimer(0); 1810 warnx("Unexpected EOF reading chunk CRLF"); 1811 goto cleanup_fetch_url; 1812 } 1813 if (strcmp(xferbuf, "\r\n") != 0) { 1814 warnx("Unexpected data following chunk"); 1815 goto cleanup_fetch_url; 1816 } 1817 if (lastchunk) 1818 break; 1819 } 1820 } while (ischunked); 1821 1822 /* XXX: deal with optional trailer & CRLF here? */ 1823 chunkerror: 1824 if (hash && !progress && bytes > 0) { 1825 if (bytes < mark) 1826 (void)putc('#', ttyout); 1827 (void)putc('\n', ttyout); 1828 } 1829 if (fetch_error(fin)) { 1830 warn("Reading file"); 1831 goto cleanup_fetch_url; 1832 } 1833 progressmeter(1); 1834 (void)fflush(fout); 1835 if (closefunc == fclose && mtime != -1) { 1836 struct timeval tval[2]; 1837 1838 (void)gettimeofday(&tval[0], NULL); 1839 tval[1].tv_sec = mtime; 1840 tval[1].tv_usec = 0; 1841 (*closefunc)(fout); 1842 fout = NULL; 1843 1844 if (utimes(savefile, tval) == -1) { 1845 fprintf(ttyout, 1846 "Can't change modification time to %s", 1847 rfc2822time(localtime(&mtime))); 1848 } 1849 } 1850 if (bytes > 0) 1851 ptransfer(0); 1852 bytes = 0; 1853 1854 rval = 0; 1855 goto cleanup_fetch_url; 1856 1857 improper: 1858 warnx("Improper response from `%s:%s'", ui.host, ui.port); 1859 1860 cleanup_fetch_url: 1861 if (oldint != SIG_ERR) 1862 (void)xsignal(SIGINT, oldint); 1863 if (oldpipe != SIG_ERR) 1864 (void)xsignal(SIGPIPE, oldpipe); 1865 if (oldalrm != SIG_ERR) 1866 (void)xsignal(SIGALRM, oldalrm); 1867 if (oldquit != SIG_ERR) 1868 (void)xsignal(SIGQUIT, oldquit); 1869 if (fin != NULL) 1870 fetch_close(fin); 1871 else if (s != -1) 1872 close(s); 1873 if (closefunc != NULL && fout != NULL) 1874 (*closefunc)(fout); 1875 if (savefile != outfile) 1876 FREEPTR(savefile); 1877 freeurlinfo(&ui); 1878 freeurlinfo(&oui); 1879 freeauthinfo(&wauth); 1880 freeauthinfo(&pauth); 1881 FREEPTR(decodedpath); 1882 FREEPTR(auth); 1883 FREEPTR(location); 1884 FREEPTR(message); 1885 return (rval); 1886 } 1887 1888 /* 1889 * Abort a HTTP retrieval 1890 */ 1891 static void 1892 aborthttp(int notused) 1893 { 1894 char msgbuf[100]; 1895 int len; 1896 1897 sigint_raised = 1; 1898 alarmtimer(0); 1899 if (fromatty) { 1900 len = snprintf(msgbuf, sizeof(msgbuf), 1901 "\n%s: HTTP fetch aborted.\n", getprogname()); 1902 if (len > 0) 1903 write(fileno(ttyout), msgbuf, len); 1904 } 1905 siglongjmp(httpabort, 1); 1906 } 1907 1908 static void 1909 timeouthttp(int notused) 1910 { 1911 char msgbuf[100]; 1912 int len; 1913 1914 alarmtimer(0); 1915 if (fromatty) { 1916 len = snprintf(msgbuf, sizeof(msgbuf), 1917 "\n%s: HTTP fetch timeout.\n", getprogname()); 1918 if (len > 0) 1919 write(fileno(ttyout), msgbuf, len); 1920 } 1921 siglongjmp(httpabort, 1); 1922 } 1923 1924 /* 1925 * Retrieve ftp URL or classic ftp argument using FTP. 1926 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection 1927 * is still open (e.g, ftp xfer with trailing /) 1928 */ 1929 static int 1930 fetch_ftp(const char *url) 1931 { 1932 char *cp, *xargv[5], rempath[MAXPATHLEN]; 1933 char *dir, *file; 1934 char cmdbuf[MAXPATHLEN]; 1935 char dirbuf[4]; 1936 int dirhasglob, filehasglob, rval, transtype, xargc; 1937 int oanonftp, oautologin; 1938 struct authinfo auth; 1939 struct urlinfo ui; 1940 1941 DPRINTF("%s: `%s'\n", __func__, url); 1942 dir = file = NULL; 1943 rval = 1; 1944 transtype = TYPE_I; 1945 1946 initurlinfo(&ui); 1947 initauthinfo(&auth, NULL); 1948 1949 if (STRNEQUAL(url, FTP_URL)) { 1950 if ((parse_url(url, "URL", &ui, &auth, NULL) == -1) || 1951 (auth.user != NULL && *auth.user == '\0') || 1952 EMPTYSTRING(ui.host)) { 1953 warnx("Invalid URL `%s'", url); 1954 goto cleanup_fetch_ftp; 1955 } 1956 /* 1957 * Note: Don't url_decode(path) here. We need to keep the 1958 * distinction between "/" and "%2F" until later. 1959 */ 1960 1961 /* check for trailing ';type=[aid]' */ 1962 if (! EMPTYSTRING(ui.path) 1963 && (cp = strrchr(ui.path, ';')) != NULL) { 1964 if (strcasecmp(cp, ";type=a") == 0) 1965 transtype = TYPE_A; 1966 else if (strcasecmp(cp, ";type=i") == 0) 1967 transtype = TYPE_I; 1968 else if (strcasecmp(cp, ";type=d") == 0) { 1969 warnx( 1970 "Directory listing via a URL is not supported"); 1971 goto cleanup_fetch_ftp; 1972 } else { 1973 warnx("Invalid suffix `%s' in URL `%s'", cp, 1974 url); 1975 goto cleanup_fetch_ftp; 1976 } 1977 *cp = 0; 1978 } 1979 } else { /* classic style `[user@]host:[file]' */ 1980 ui.utype = CLASSIC_URL_T; 1981 ui.host = ftp_strdup(url); 1982 cp = strchr(ui.host, '@'); 1983 if (cp != NULL) { 1984 *cp = '\0'; 1985 auth.user = ui.host; 1986 anonftp = 0; /* disable anonftp */ 1987 ui.host = ftp_strdup(cp + 1); 1988 } 1989 cp = strchr(ui.host, ':'); 1990 if (cp != NULL) { 1991 *cp = '\0'; 1992 ui.path = ftp_strdup(cp + 1); 1993 } 1994 } 1995 if (EMPTYSTRING(ui.host)) 1996 goto cleanup_fetch_ftp; 1997 1998 /* Extract the file and (if present) directory name. */ 1999 dir = ui.path; 2000 if (! EMPTYSTRING(dir)) { 2001 /* 2002 * If we are dealing with classic `[user@]host:[path]' syntax, 2003 * then a path of the form `/file' (resulting from input of the 2004 * form `host:/file') means that we should do "CWD /" before 2005 * retrieving the file. So we set dir="/" and file="file". 2006 * 2007 * But if we are dealing with URLs like `ftp://host/path' then 2008 * a path of the form `/file' (resulting from a URL of the form 2009 * `ftp://host//file') means that we should do `CWD ' (with an 2010 * empty argument) before retrieving the file. So we set 2011 * dir="" and file="file". 2012 * 2013 * If the path does not contain / at all, we set dir=NULL. 2014 * (We get a path without any slashes if we are dealing with 2015 * classic `[user@]host:[file]' or URL `ftp://host/file'.) 2016 * 2017 * In all other cases, we set dir to a string that does not 2018 * include the final '/' that separates the dir part from the 2019 * file part of the path. (This will be the empty string if 2020 * and only if we are dealing with a path of the form `/file' 2021 * resulting from an URL of the form `ftp://host//file'.) 2022 */ 2023 cp = strrchr(dir, '/'); 2024 if (cp == dir && ui.utype == CLASSIC_URL_T) { 2025 file = cp + 1; 2026 (void)strlcpy(dirbuf, "/", sizeof(dirbuf)); 2027 dir = dirbuf; 2028 } else if (cp != NULL) { 2029 *cp++ = '\0'; 2030 file = cp; 2031 } else { 2032 file = dir; 2033 dir = NULL; 2034 } 2035 } else 2036 dir = NULL; 2037 if (ui.utype == FTP_URL_T && file != NULL) { 2038 url_decode(file); 2039 /* but still don't url_decode(dir) */ 2040 } 2041 DPRINTF("%s: user `%s' pass `%s' host %s port %s " 2042 "path `%s' dir `%s' file `%s'\n", __func__, 2043 STRorNULL(auth.user), STRorNULL(auth.pass), 2044 STRorNULL(ui.host), STRorNULL(ui.port), 2045 STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file)); 2046 2047 dirhasglob = filehasglob = 0; 2048 if (doglob && 2049 (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) { 2050 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL) 2051 dirhasglob = 1; 2052 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL) 2053 filehasglob = 1; 2054 } 2055 2056 /* Set up the connection */ 2057 oanonftp = anonftp; 2058 if (connected) 2059 disconnect(0, NULL); 2060 anonftp = oanonftp; 2061 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf)); 2062 xargv[0] = cmdbuf; 2063 xargv[1] = ui.host; 2064 xargv[2] = NULL; 2065 xargc = 2; 2066 if (ui.port) { 2067 xargv[2] = ui.port; 2068 xargv[3] = NULL; 2069 xargc = 3; 2070 } 2071 oautologin = autologin; 2072 /* don't autologin in setpeer(), use ftp_login() below */ 2073 autologin = 0; 2074 setpeer(xargc, xargv); 2075 autologin = oautologin; 2076 if ((connected == 0) || 2077 (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) { 2078 warnx("Can't connect or login to host `%s:%s'", 2079 ui.host, ui.port ? ui.port : "?"); 2080 goto cleanup_fetch_ftp; 2081 } 2082 2083 switch (transtype) { 2084 case TYPE_A: 2085 setascii(1, xargv); 2086 break; 2087 case TYPE_I: 2088 setbinary(1, xargv); 2089 break; 2090 default: 2091 errx(1, "%s: unknown transfer type %d", __func__, transtype); 2092 } 2093 2094 /* 2095 * Change directories, if necessary. 2096 * 2097 * Note: don't use EMPTYSTRING(dir) below, because 2098 * dir=="" means something different from dir==NULL. 2099 */ 2100 if (dir != NULL && !dirhasglob) { 2101 char *nextpart; 2102 2103 /* 2104 * If we are dealing with a classic `[user@]host:[path]' 2105 * (urltype is CLASSIC_URL_T) then we have a raw directory 2106 * name (not encoded in any way) and we can change 2107 * directories in one step. 2108 * 2109 * If we are dealing with an `ftp://host/path' URL 2110 * (urltype is FTP_URL_T), then RFC 3986 says we need to 2111 * send a separate CWD command for each unescaped "/" 2112 * in the path, and we have to interpret %hex escaping 2113 * *after* we find the slashes. It's possible to get 2114 * empty components here, (from multiple adjacent 2115 * slashes in the path) and RFC 3986 says that we should 2116 * still do `CWD ' (with a null argument) in such cases. 2117 * 2118 * Many ftp servers don't support `CWD ', so if there's an 2119 * error performing that command, bail out with a descriptive 2120 * message. 2121 * 2122 * Examples: 2123 * 2124 * host: dir="", urltype=CLASSIC_URL_T 2125 * logged in (to default directory) 2126 * host:file dir=NULL, urltype=CLASSIC_URL_T 2127 * "RETR file" 2128 * host:dir/ dir="dir", urltype=CLASSIC_URL_T 2129 * "CWD dir", logged in 2130 * ftp://host/ dir="", urltype=FTP_URL_T 2131 * logged in (to default directory) 2132 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T 2133 * "CWD dir", logged in 2134 * ftp://host/file dir=NULL, urltype=FTP_URL_T 2135 * "RETR file" 2136 * ftp://host//file dir="", urltype=FTP_URL_T 2137 * "CWD ", "RETR file" 2138 * host:/file dir="/", urltype=CLASSIC_URL_T 2139 * "CWD /", "RETR file" 2140 * ftp://host///file dir="/", urltype=FTP_URL_T 2141 * "CWD ", "CWD ", "RETR file" 2142 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T 2143 * "CWD /", "RETR file" 2144 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T 2145 * "CWD foo", "RETR file" 2146 * ftp://host/foo/bar/file dir="foo/bar" 2147 * "CWD foo", "CWD bar", "RETR file" 2148 * ftp://host//foo/bar/file dir="/foo/bar" 2149 * "CWD ", "CWD foo", "CWD bar", "RETR file" 2150 * ftp://host/foo//bar/file dir="foo//bar" 2151 * "CWD foo", "CWD ", "CWD bar", "RETR file" 2152 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar" 2153 * "CWD /", "CWD foo", "CWD bar", "RETR file" 2154 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar" 2155 * "CWD /foo", "CWD bar", "RETR file" 2156 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar" 2157 * "CWD /foo/bar", "RETR file" 2158 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL 2159 * "RETR /foo/bar/file" 2160 * 2161 * Note that we don't need `dir' after this point. 2162 */ 2163 do { 2164 if (ui.utype == FTP_URL_T) { 2165 nextpart = strchr(dir, '/'); 2166 if (nextpart) { 2167 *nextpart = '\0'; 2168 nextpart++; 2169 } 2170 url_decode(dir); 2171 } else 2172 nextpart = NULL; 2173 DPRINTF("%s: dir `%s', nextpart `%s'\n", __func__, 2174 STRorNULL(dir), STRorNULL(nextpart)); 2175 if (ui.utype == FTP_URL_T || *dir != '\0') { 2176 (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf)); 2177 xargv[0] = cmdbuf; 2178 xargv[1] = dir; 2179 xargv[2] = NULL; 2180 dirchange = 0; 2181 cd(2, xargv); 2182 if (! dirchange) { 2183 if (*dir == '\0' && code == 500) 2184 fprintf(stderr, 2185 "\n" 2186 "ftp: The `CWD ' command (without a directory), which is required by\n" 2187 " RFC 3986 to support the empty directory in the URL pathname (`//'),\n" 2188 " conflicts with the server's conformance to RFC 959.\n" 2189 " Try the same URL without the `//' in the URL pathname.\n" 2190 "\n"); 2191 goto cleanup_fetch_ftp; 2192 } 2193 } 2194 dir = nextpart; 2195 } while (dir != NULL); 2196 } 2197 2198 if (EMPTYSTRING(file)) { 2199 rval = -1; 2200 goto cleanup_fetch_ftp; 2201 } 2202 2203 if (dirhasglob) { 2204 (void)strlcpy(rempath, dir, sizeof(rempath)); 2205 (void)strlcat(rempath, "/", sizeof(rempath)); 2206 (void)strlcat(rempath, file, sizeof(rempath)); 2207 file = rempath; 2208 } 2209 2210 /* Fetch the file(s). */ 2211 xargc = 2; 2212 (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf)); 2213 xargv[0] = cmdbuf; 2214 xargv[1] = file; 2215 xargv[2] = NULL; 2216 if (dirhasglob || filehasglob) { 2217 int ointeractive; 2218 2219 ointeractive = interactive; 2220 interactive = 0; 2221 if (restartautofetch) 2222 (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf)); 2223 else 2224 (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf)); 2225 xargv[0] = cmdbuf; 2226 mget(xargc, xargv); 2227 interactive = ointeractive; 2228 } else { 2229 char *destfile = outfile; 2230 if (destfile == NULL) { 2231 cp = strrchr(file, '/'); /* find savefile */ 2232 if (cp != NULL) 2233 destfile = cp + 1; 2234 else 2235 destfile = file; 2236 } 2237 xargv[2] = (char *)destfile; 2238 xargv[3] = NULL; 2239 xargc++; 2240 if (restartautofetch) 2241 reget(xargc, xargv); 2242 else 2243 get(xargc, xargv); 2244 } 2245 2246 if ((code / 100) == COMPLETE) 2247 rval = 0; 2248 2249 cleanup_fetch_ftp: 2250 freeurlinfo(&ui); 2251 freeauthinfo(&auth); 2252 return (rval); 2253 } 2254 2255 /* 2256 * Retrieve the given file to outfile. 2257 * Supports arguments of the form: 2258 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else 2259 * call fetch_ftp() 2260 * "http://host/path" call fetch_url() to use HTTP 2261 * "file:///path" call fetch_url() to copy 2262 * "about:..." print a message 2263 * 2264 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection 2265 * is still open (e.g, ftp xfer with trailing /) 2266 */ 2267 static int 2268 go_fetch(const char *url, struct urlinfo *rui) 2269 { 2270 char *proxyenv; 2271 char *p; 2272 2273 #ifndef NO_ABOUT 2274 /* 2275 * Check for about:* 2276 */ 2277 if (STRNEQUAL(url, ABOUT_URL)) { 2278 url += sizeof(ABOUT_URL) -1; 2279 if (strcasecmp(url, "ftp") == 0 || 2280 strcasecmp(url, "tnftp") == 0) { 2281 fputs( 2282 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n" 2283 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout); 2284 } else if (strcasecmp(url, "lukem") == 0) { 2285 fputs( 2286 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n" 2287 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout); 2288 } else if (strcasecmp(url, "netbsd") == 0) { 2289 fputs( 2290 "NetBSD is a freely available and redistributable UNIX-like operating system.\n" 2291 "For more information, see http://www.NetBSD.org/\n", ttyout); 2292 } else if (strcasecmp(url, "version") == 0) { 2293 fprintf(ttyout, "Version: %s %s%s\n", 2294 FTP_PRODUCT, FTP_VERSION, 2295 #ifdef INET6 2296 "" 2297 #else 2298 " (-IPv6)" 2299 #endif 2300 ); 2301 } else { 2302 fprintf(ttyout, "`%s' is an interesting topic.\n", url); 2303 } 2304 fputs("\n", ttyout); 2305 return (0); 2306 } 2307 #endif 2308 2309 /* 2310 * Check for file:// and http:// URLs. 2311 */ 2312 if (STRNEQUAL(url, HTTP_URL) 2313 #ifdef WITH_SSL 2314 || STRNEQUAL(url, HTTPS_URL) 2315 #endif 2316 || STRNEQUAL(url, FILE_URL)) 2317 return (fetch_url(url, NULL, NULL, NULL, rui)); 2318 2319 /* 2320 * If it contains "://" but does not begin with ftp:// 2321 * or something that was already handled, then it's 2322 * unsupported. 2323 * 2324 * If it contains ":" but not "://" then we assume the 2325 * part before the colon is a host name, not an URL scheme, 2326 * so we don't try to match that here. 2327 */ 2328 if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL)) 2329 errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url); 2330 2331 /* 2332 * Refer to previous urlinfo if provided. This makes relative 2333 * redirects work. 2334 */ 2335 if (use_relative(rui)) 2336 return fetch_url(url, NULL, NULL, NULL, rui); 2337 2338 /* 2339 * Try FTP URL-style and host:file arguments next. 2340 * If ftpproxy is set with an FTP URL, use fetch_url() 2341 * Otherwise, use fetch_ftp(). 2342 */ 2343 proxyenv = getoptionvalue("ftp_proxy"); 2344 if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL)) 2345 return (fetch_url(url, NULL, NULL, NULL, rui)); 2346 2347 return (fetch_ftp(url)); 2348 } 2349 2350 /* 2351 * Retrieve multiple files from the command line, 2352 * calling go_fetch() for each file. 2353 * 2354 * If an ftp path has a trailing "/", the path will be cd-ed into and 2355 * the connection remains open, and the function will return -1 2356 * (to indicate the connection is alive). 2357 * If an error occurs the return value will be the offset+1 in 2358 * argv[] of the file that caused a problem (i.e, argv[x] 2359 * returns x+1) 2360 * Otherwise, 0 is returned if all files retrieved successfully. 2361 */ 2362 int 2363 auto_fetch(int argc, char *argv[]) 2364 { 2365 volatile int argpos, rval; 2366 2367 argpos = rval = 0; 2368 2369 if (sigsetjmp(toplevel, 1)) { 2370 if (connected) 2371 disconnect(0, NULL); 2372 if (rval > 0) 2373 rval = argpos + 1; 2374 return (rval); 2375 } 2376 (void)xsignal(SIGINT, intr); 2377 (void)xsignal(SIGPIPE, lostpeer); 2378 2379 /* 2380 * Loop through as long as there's files to fetch. 2381 */ 2382 for (; (rval == 0) && (argpos < argc); argpos++) { 2383 if (strchr(argv[argpos], ':') == NULL) 2384 break; 2385 redirect_loop = 0; 2386 if (!anonftp) 2387 anonftp = 2; /* Handle "automatic" transfers. */ 2388 rval = go_fetch(argv[argpos], NULL); 2389 if (outfile != NULL && strcmp(outfile, "-") != 0 2390 && outfile[0] != '|') { 2391 FREEPTR(outfile); 2392 } 2393 if (rval > 0) 2394 rval = argpos + 1; 2395 } 2396 2397 if (connected && rval != -1) 2398 disconnect(0, NULL); 2399 return (rval); 2400 } 2401 2402 2403 /* 2404 * Upload multiple files from the command line. 2405 * 2406 * If an error occurs the return value will be the offset+1 in 2407 * argv[] of the file that caused a problem (i.e, argv[x] 2408 * returns x+1) 2409 * Otherwise, 0 is returned if all files uploaded successfully. 2410 */ 2411 int 2412 auto_put(int argc, char **argv, const char *uploadserver) 2413 { 2414 char *uargv[4], *path, *pathsep; 2415 int uargc, rval, argpos; 2416 size_t len; 2417 char cmdbuf[MAX_C_NAME]; 2418 2419 (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf)); 2420 uargv[0] = cmdbuf; 2421 uargv[1] = argv[0]; 2422 uargc = 2; 2423 uargv[2] = uargv[3] = NULL; 2424 pathsep = NULL; 2425 rval = 1; 2426 2427 DPRINTF("%s: target `%s'\n", __func__, uploadserver); 2428 2429 path = ftp_strdup(uploadserver); 2430 len = strlen(path); 2431 if (path[len - 1] != '/' && path[len - 1] != ':') { 2432 /* 2433 * make sure we always pass a directory to auto_fetch 2434 */ 2435 if (argc > 1) { /* more than one file to upload */ 2436 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */ 2437 free(path); 2438 path = (char *)ftp_malloc(len); 2439 (void)strlcpy(path, uploadserver, len); 2440 (void)strlcat(path, "/", len); 2441 } else { /* single file to upload */ 2442 (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf)); 2443 uargv[0] = cmdbuf; 2444 pathsep = strrchr(path, '/'); 2445 if (pathsep == NULL) { 2446 pathsep = strrchr(path, ':'); 2447 if (pathsep == NULL) { 2448 warnx("Invalid URL `%s'", path); 2449 goto cleanup_auto_put; 2450 } 2451 pathsep++; 2452 uargv[2] = ftp_strdup(pathsep); 2453 pathsep[0] = '/'; 2454 } else 2455 uargv[2] = ftp_strdup(pathsep + 1); 2456 pathsep[1] = '\0'; 2457 uargc++; 2458 } 2459 } 2460 DPRINTF("%s: URL `%s' argv[2] `%s'\n", __func__, 2461 path, STRorNULL(uargv[2])); 2462 2463 /* connect and cwd */ 2464 rval = auto_fetch(1, &path); 2465 if(rval >= 0) 2466 goto cleanup_auto_put; 2467 2468 rval = 0; 2469 2470 /* target filename provided; upload 1 file */ 2471 /* XXX : is this the best way? */ 2472 if (uargc == 3) { 2473 uargv[1] = argv[0]; 2474 put(uargc, uargv); 2475 if ((code / 100) != COMPLETE) 2476 rval = 1; 2477 } else { /* otherwise a target dir: upload all files to it */ 2478 for(argpos = 0; argv[argpos] != NULL; argpos++) { 2479 uargv[1] = argv[argpos]; 2480 mput(uargc, uargv); 2481 if ((code / 100) != COMPLETE) { 2482 rval = argpos + 1; 2483 break; 2484 } 2485 } 2486 } 2487 2488 cleanup_auto_put: 2489 free(path); 2490 FREEPTR(uargv[2]); 2491 return (rval); 2492 } 2493