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