1 /* $NetBSD: fetch.c,v 1.132 2001/12/26 09:40:15 lukem Exp $ */ 2 3 /*- 4 * Copyright (c) 1997-2001 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 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 3. All advertising materials mentioning features or use of this software 22 * must display the following acknowledgement: 23 * This product includes software developed by the NetBSD 24 * Foundation, Inc. and its contributors. 25 * 4. Neither the name of The NetBSD Foundation nor the names of its 26 * contributors may be used to endorse or promote products derived 27 * from this software without specific prior written permission. 28 * 29 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 30 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 31 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 32 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 33 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 34 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 35 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 36 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 37 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 38 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 39 * POSSIBILITY OF SUCH DAMAGE. 40 */ 41 42 #include <sys/cdefs.h> 43 #ifndef lint 44 __RCSID("$NetBSD: fetch.c,v 1.132 2001/12/26 09:40:15 lukem Exp $"); 45 #endif /* not lint */ 46 47 /* 48 * FTP User Program -- Command line file retrieval 49 */ 50 51 #include <sys/types.h> 52 #include <sys/param.h> 53 #include <sys/socket.h> 54 #include <sys/stat.h> 55 #include <sys/time.h> 56 57 #include <netinet/in.h> 58 59 #include <arpa/ftp.h> 60 #include <arpa/inet.h> 61 62 #include <ctype.h> 63 #include <err.h> 64 #include <errno.h> 65 #include <netdb.h> 66 #include <fcntl.h> 67 #include <stdio.h> 68 #include <stdlib.h> 69 #include <string.h> 70 #include <unistd.h> 71 #include <time.h> 72 #include <util.h> 73 74 #include "ftp_var.h" 75 #include "version.h" 76 77 typedef enum { 78 UNKNOWN_URL_T=-1, 79 HTTP_URL_T, 80 FTP_URL_T, 81 FILE_URL_T, 82 CLASSIC_URL_T 83 } url_t; 84 85 void aborthttp(int); 86 static int auth_url(const char *, char **, const char *, const char *); 87 static void base64_encode(const u_char *, size_t, u_char *); 88 static int go_fetch(const char *); 89 static int fetch_ftp(const char *); 90 static int fetch_url(const char *, const char *, char *, char *); 91 static int parse_url(const char *, const char *, url_t *, char **, 92 char **, char **, char **, in_port_t *, char **); 93 static void url_decode(char *); 94 95 static int redirect_loop; 96 97 98 #define ABOUT_URL "about:" /* propaganda */ 99 #define FILE_URL "file://" /* file URL prefix */ 100 #define FTP_URL "ftp://" /* ftp URL prefix */ 101 #define HTTP_URL "http://" /* http URL prefix */ 102 103 104 /* 105 * Generate authorization response based on given authentication challenge. 106 * Returns -1 if an error occurred, otherwise 0. 107 * Sets response to a malloc(3)ed string; caller should free. 108 */ 109 static int 110 auth_url(const char *challenge, char **response, const char *guser, 111 const char *gpass) 112 { 113 char *cp, *ep, *clear, *line, *realm, *scheme; 114 char user[BUFSIZ], *pass; 115 int rval; 116 size_t len, clen, rlen; 117 118 *response = NULL; 119 clear = realm = scheme = NULL; 120 rval = -1; 121 line = xstrdup(challenge); 122 cp = line; 123 124 if (debug) 125 fprintf(ttyout, "auth_url: challenge `%s'\n", challenge); 126 127 scheme = strsep(&cp, " "); 128 #define SCHEME_BASIC "Basic" 129 if (strncasecmp(scheme, SCHEME_BASIC, sizeof(SCHEME_BASIC) - 1) != 0) { 130 warnx("Unsupported WWW Authentication challenge - `%s'", 131 challenge); 132 goto cleanup_auth_url; 133 } 134 cp += strspn(cp, " "); 135 136 #define REALM "realm=\"" 137 if (strncasecmp(cp, REALM, sizeof(REALM) - 1) == 0) 138 cp += sizeof(REALM) - 1; 139 else { 140 warnx("Unsupported WWW Authentication challenge - `%s'", 141 challenge); 142 goto cleanup_auth_url; 143 } 144 if ((ep = strchr(cp, '\"')) != NULL) { 145 size_t len = ep - cp; 146 147 realm = (char *)xmalloc(len + 1); 148 (void)strlcpy(realm, cp, len + 1); 149 } else { 150 warnx("Unsupported WWW Authentication challenge - `%s'", 151 challenge); 152 goto cleanup_auth_url; 153 } 154 155 if (guser != NULL) 156 (void)strlcpy(user, guser, sizeof(user)); 157 else { 158 fprintf(ttyout, "Username for `%s': ", realm); 159 (void)fflush(ttyout); 160 if (fgets(user, sizeof(user) - 1, stdin) == NULL) { 161 clearerr(stdin); 162 goto cleanup_auth_url; 163 } 164 user[strlen(user) - 1] = '\0'; 165 } 166 if (gpass != NULL) 167 pass = (char *)gpass; 168 else 169 pass = getpass("Password: "); 170 171 clen = strlen(user) + strlen(pass) + 2; /* user + ":" + pass + "\0" */ 172 clear = (char *)xmalloc(clen); 173 (void)strlcpy(clear, user, clen); 174 (void)strlcat(clear, ":", clen); 175 (void)strlcat(clear, pass, clen); 176 if (gpass == NULL) 177 memset(pass, 0, strlen(pass)); 178 179 /* scheme + " " + enc + "\0" */ 180 rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1; 181 *response = (char *)xmalloc(rlen); 182 (void)strlcpy(*response, scheme, rlen); 183 len = strlcat(*response, " ", rlen); 184 base64_encode(clear, clen, *response + len); 185 memset(clear, 0, clen); 186 rval = 0; 187 188 cleanup_auth_url: 189 FREEPTR(clear); 190 FREEPTR(line); 191 FREEPTR(realm); 192 return (rval); 193 } 194 195 /* 196 * Encode len bytes starting at clear using base64 encoding into encoded, 197 * which should be at least ((len + 2) * 4 / 3 + 1) in size. 198 */ 199 static void 200 base64_encode(const u_char *clear, size_t len, u_char *encoded) 201 { 202 static const u_char enc[] = 203 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 204 u_char *cp; 205 int i; 206 207 cp = encoded; 208 for (i = 0; i < len; i += 3) { 209 *(cp++) = enc[((clear[i + 0] >> 2))]; 210 *(cp++) = enc[((clear[i + 0] << 4) & 0x30) 211 | ((clear[i + 1] >> 4) & 0x0f)]; 212 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c) 213 | ((clear[i + 2] >> 6) & 0x03)]; 214 *(cp++) = enc[((clear[i + 2] ) & 0x3f)]; 215 } 216 *cp = '\0'; 217 while (i-- > len) 218 *(--cp) = '='; 219 } 220 221 /* 222 * Decode %xx escapes in given string, `in-place'. 223 */ 224 static void 225 url_decode(char *url) 226 { 227 unsigned char *p, *q; 228 229 if (EMPTYSTRING(url)) 230 return; 231 p = q = (unsigned char *)url; 232 233 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10)) 234 while (*p) { 235 if (p[0] == '%' 236 && p[1] && isxdigit((unsigned char)p[1]) 237 && p[2] && isxdigit((unsigned char)p[2])) { 238 *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]); 239 p+=3; 240 } else 241 *q++ = *p++; 242 } 243 *q = '\0'; 244 } 245 246 247 /* 248 * Parse URL of form: 249 * <type>://[<user>[:<password>@]]<host>[:<port>][/<path>] 250 * Returns -1 if a parse error occurred, otherwise 0. 251 * It's the caller's responsibility to url_decode() the returned 252 * user, pass and path. 253 * 254 * Sets type to url_t, each of the given char ** pointers to a 255 * malloc(3)ed strings of the relevant section, and port to 256 * the number given, or ftpport if ftp://, or httpport if http://. 257 * 258 * If <host> is surrounded by `[' and ']', it's parsed as an 259 * IPv6 address (as per RFC 2732). 260 * 261 * XXX: this is not totally RFC 1738 compliant; <path> will have the 262 * leading `/' unless it's an ftp:// URL, as this makes things easier 263 * for file:// and http:// URLs. ftp:// URLs have the `/' between the 264 * host and the url-path removed, but any additional leading slashes 265 * in the url-path are retained (because they imply that we should 266 * later do "CWD" with a null argument). 267 * 268 * Examples: 269 * input url output path 270 * --------- ----------- 271 * "ftp://host" NULL 272 * "http://host/" NULL 273 * "file://host/dir/file" "dir/file" 274 * "ftp://host/" "" 275 * "ftp://host//" NULL 276 * "ftp://host//dir/file" "/dir/file" 277 */ 278 static int 279 parse_url(const char *url, const char *desc, url_t *type, 280 char **user, char **pass, char **host, char **port, 281 in_port_t *portnum, char **path) 282 { 283 const char *origurl; 284 char *cp, *ep, *thost, *tport; 285 size_t len; 286 287 if (url == NULL || desc == NULL || type == NULL || user == NULL 288 || pass == NULL || host == NULL || port == NULL || portnum == NULL 289 || path == NULL) 290 errx(1, "parse_url: invoked with NULL argument!"); 291 292 origurl = url; 293 *type = UNKNOWN_URL_T; 294 *user = *pass = *host = *port = *path = NULL; 295 *portnum = 0; 296 tport = NULL; 297 298 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) { 299 url += sizeof(HTTP_URL) - 1; 300 *type = HTTP_URL_T; 301 *portnum = HTTP_PORT; 302 tport = httpport; 303 } else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) { 304 url += sizeof(FTP_URL) - 1; 305 *type = FTP_URL_T; 306 *portnum = FTP_PORT; 307 tport = ftpport; 308 } else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) { 309 url += sizeof(FILE_URL) - 1; 310 *type = FILE_URL_T; 311 } else { 312 warnx("Invalid %s `%s'", desc, url); 313 cleanup_parse_url: 314 FREEPTR(*user); 315 FREEPTR(*pass); 316 FREEPTR(*host); 317 FREEPTR(*port); 318 FREEPTR(*path); 319 return (-1); 320 } 321 322 if (*url == '\0') 323 return (0); 324 325 /* find [user[:pass]@]host[:port] */ 326 ep = strchr(url, '/'); 327 if (ep == NULL) 328 thost = xstrdup(url); 329 else { 330 len = ep - url; 331 thost = (char *)xmalloc(len + 1); 332 (void)strlcpy(thost, url, len + 1); 333 if (*type == FTP_URL_T) /* skip first / for ftp URLs */ 334 ep++; 335 *path = xstrdup(ep); 336 } 337 338 cp = strchr(thost, '@'); /* look for user[:pass]@ in URLs */ 339 if (cp != NULL) { 340 if (*type == FTP_URL_T) 341 anonftp = 0; /* disable anonftp */ 342 *user = thost; 343 *cp = '\0'; 344 thost = xstrdup(cp + 1); 345 cp = strchr(*user, ':'); 346 if (cp != NULL) { 347 *cp = '\0'; 348 *pass = xstrdup(cp + 1); 349 } 350 } 351 352 #ifdef INET6 353 /* 354 * Check if thost is an encoded IPv6 address, as per 355 * RFC 2732: 356 * `[' ipv6-address ']' 357 */ 358 if (*thost == '[') { 359 cp = thost + 1; 360 if ((ep = strchr(cp, ']')) == NULL || 361 (ep[1] != '\0' && ep[1] != ':')) { 362 warnx("Invalid address `%s' in %s `%s'", 363 thost, desc, origurl); 364 goto cleanup_parse_url; 365 } 366 len = ep - cp; /* change `[xyz]' -> `xyz' */ 367 memmove(thost, thost + 1, len); 368 thost[len] = '\0'; 369 if (! isipv6addr(thost)) { 370 warnx("Invalid IPv6 address `%s' in %s `%s'", 371 thost, desc, origurl); 372 goto cleanup_parse_url; 373 } 374 cp = ep + 1; 375 if (*cp == ':') 376 cp++; 377 else 378 cp = NULL; 379 } else 380 #endif /* INET6 */ 381 if ((cp = strchr(thost, ':')) != NULL) 382 *cp++ = '\0'; 383 *host = thost; 384 385 /* look for [:port] */ 386 if (cp != NULL) { 387 long nport; 388 389 nport = parseport(cp, -1); 390 if (nport == -1) { 391 warnx("Unknown port `%s' in %s `%s'", 392 cp, desc, origurl); 393 goto cleanup_parse_url; 394 } 395 *portnum = nport; 396 tport = cp; 397 } 398 399 if (tport != NULL) 400 *port = xstrdup(tport); 401 if (*path == NULL) 402 *path = xstrdup(""); 403 404 if (debug) 405 fprintf(ttyout, 406 "parse_url: user `%s' pass `%s' host %s port %s(%d) " 407 "path `%s'\n", 408 *user ? *user : "<null>", *pass ? *pass : "<null>", 409 *host ? *host : "<null>", *port ? *port : "<null>", 410 *portnum ? *portnum : -1, *path ? *path : "<null>"); 411 412 return (0); 413 } 414 415 sigjmp_buf httpabort; 416 417 /* 418 * Retrieve URL, via a proxy if necessary, using HTTP. 419 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or 420 * http_proxy as appropriate. 421 * Supports HTTP redirects. 422 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection 423 * is still open (e.g, ftp xfer with trailing /) 424 */ 425 static int 426 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth) 427 { 428 struct addrinfo hints, *res, *res0 = NULL; 429 int error; 430 char hbuf[NI_MAXHOST]; 431 volatile sigfunc oldintr, oldintp; 432 volatile int s; 433 struct stat sb; 434 int ischunked, isproxy, rval, hcode; 435 size_t len; 436 static size_t bufsize; 437 static char *xferbuf; 438 char *cp, *ep, *buf, *savefile; 439 char *auth, *location, *message; 440 char *user, *pass, *host, *port, *path, *decodedpath; 441 char *puser, *ppass; 442 off_t hashbytes, rangestart, rangeend, entitylen; 443 int (*closefunc)(FILE *); 444 FILE *fin, *fout; 445 time_t mtime; 446 url_t urltype; 447 in_port_t portnum; 448 449 oldintr = oldintp = NULL; 450 closefunc = NULL; 451 fin = fout = NULL; 452 s = -1; 453 buf = savefile = NULL; 454 auth = location = message = NULL; 455 ischunked = isproxy = hcode = 0; 456 rval = 1; 457 user = pass = host = path = decodedpath = puser = ppass = NULL; 458 459 #ifdef __GNUC__ /* shut up gcc warnings */ 460 (void)&closefunc; 461 (void)&fin; 462 (void)&fout; 463 (void)&buf; 464 (void)&savefile; 465 (void)&rval; 466 (void)&isproxy; 467 (void)&hcode; 468 (void)&ischunked; 469 (void)&message; 470 (void)&location; 471 (void)&auth; 472 (void)&decodedpath; 473 #endif 474 475 if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, 476 &portnum, &path) == -1) 477 goto cleanup_fetch_url; 478 479 if (urltype == FILE_URL_T && ! EMPTYSTRING(host) 480 && strcasecmp(host, "localhost") != 0) { 481 warnx("No support for non local file URL `%s'", url); 482 goto cleanup_fetch_url; 483 } 484 485 if (EMPTYSTRING(path)) { 486 if (urltype == FTP_URL_T) { 487 rval = fetch_ftp(url); 488 goto cleanup_fetch_url; 489 } 490 if (urltype != HTTP_URL_T || outfile == NULL) { 491 warnx("Invalid URL (no file after host) `%s'", url); 492 goto cleanup_fetch_url; 493 } 494 } 495 496 decodedpath = xstrdup(path); 497 url_decode(decodedpath); 498 499 if (outfile) 500 savefile = xstrdup(outfile); 501 else { 502 cp = strrchr(decodedpath, '/'); /* find savefile */ 503 if (cp != NULL) 504 savefile = xstrdup(cp + 1); 505 else 506 savefile = xstrdup(decodedpath); 507 } 508 if (EMPTYSTRING(savefile)) { 509 if (urltype == FTP_URL_T) { 510 rval = fetch_ftp(url); 511 goto cleanup_fetch_url; 512 } 513 warnx("Invalid URL (no file after directory) `%s'", url); 514 goto cleanup_fetch_url; 515 } else { 516 if (debug) 517 fprintf(ttyout, "got savefile as `%s'\n", savefile); 518 } 519 520 restart_point = 0; 521 filesize = -1; 522 rangestart = rangeend = entitylen = -1; 523 mtime = -1; 524 if (restartautofetch) { 525 if (strcmp(savefile, "-") != 0 && *savefile != '|' && 526 stat(savefile, &sb) == 0) 527 restart_point = sb.st_size; 528 } 529 if (urltype == FILE_URL_T) { /* file:// URLs */ 530 direction = "copied"; 531 fin = fopen(decodedpath, "r"); 532 if (fin == NULL) { 533 warn("Cannot open file `%s'", decodedpath); 534 goto cleanup_fetch_url; 535 } 536 if (fstat(fileno(fin), &sb) == 0) { 537 mtime = sb.st_mtime; 538 filesize = sb.st_size; 539 } 540 if (restart_point) { 541 if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) { 542 warn("Can't lseek to restart `%s'", 543 decodedpath); 544 goto cleanup_fetch_url; 545 } 546 } 547 if (verbose) { 548 fprintf(ttyout, "Copying %s", decodedpath); 549 if (restart_point) 550 fprintf(ttyout, " (restarting at " LLF ")", 551 (LLT)restart_point); 552 fputs("\n", ttyout); 553 } 554 } else { /* ftp:// or http:// URLs */ 555 char *leading; 556 int hasleading; 557 558 if (proxyenv == NULL) { 559 if (urltype == HTTP_URL_T) 560 proxyenv = getoptionvalue("http_proxy"); 561 else if (urltype == FTP_URL_T) 562 proxyenv = getoptionvalue("ftp_proxy"); 563 } 564 direction = "retrieved"; 565 if (! EMPTYSTRING(proxyenv)) { /* use proxy */ 566 url_t purltype; 567 char *phost, *ppath; 568 char *pport, *no_proxy; 569 570 isproxy = 1; 571 572 /* check URL against list of no_proxied sites */ 573 no_proxy = getoptionvalue("no_proxy"); 574 if (! EMPTYSTRING(no_proxy)) { 575 char *np, *np_copy; 576 long np_port; 577 size_t hlen, plen; 578 579 np_copy = xstrdup(no_proxy); 580 hlen = strlen(host); 581 while ((cp = strsep(&np_copy, " ,")) != NULL) { 582 if (*cp == '\0') 583 continue; 584 if ((np = strrchr(cp, ':')) != NULL) { 585 *np = '\0'; 586 np_port = 587 strtol(np + 1, &ep, 10); 588 if (*ep != '\0') 589 continue; 590 if (np_port != portnum) 591 continue; 592 } 593 plen = strlen(cp); 594 if (hlen < plen) 595 continue; 596 if (strncasecmp(host + hlen - plen, 597 cp, plen) == 0) { 598 isproxy = 0; 599 break; 600 } 601 } 602 FREEPTR(np_copy); 603 if (isproxy == 0 && urltype == FTP_URL_T) { 604 rval = fetch_ftp(url); 605 goto cleanup_fetch_url; 606 } 607 } 608 609 if (isproxy) { 610 if (parse_url(proxyenv, "proxy URL", &purltype, 611 &puser, &ppass, &phost, &pport, &portnum, 612 &ppath) == -1) 613 goto cleanup_fetch_url; 614 615 if ((purltype != HTTP_URL_T 616 && purltype != FTP_URL_T) || 617 EMPTYSTRING(phost) || 618 (! EMPTYSTRING(ppath) 619 && strcmp(ppath, "/") != 0)) { 620 warnx("Malformed proxy URL `%s'", 621 proxyenv); 622 FREEPTR(phost); 623 FREEPTR(pport); 624 FREEPTR(ppath); 625 goto cleanup_fetch_url; 626 } 627 if (isipv6addr(host) && 628 strchr(host, '%') != NULL) { 629 warnx( 630 "Scoped address notation `%s' disallowed via web proxy", 631 host); 632 FREEPTR(phost); 633 FREEPTR(pport); 634 FREEPTR(ppath); 635 goto cleanup_fetch_url; 636 } 637 638 FREEPTR(host); 639 host = phost; 640 FREEPTR(port); 641 port = pport; 642 FREEPTR(path); 643 path = xstrdup(url); 644 FREEPTR(ppath); 645 } 646 } /* ! EMPTYSTRING(proxyenv) */ 647 648 memset(&hints, 0, sizeof(hints)); 649 hints.ai_flags = 0; 650 hints.ai_family = family; 651 hints.ai_socktype = SOCK_STREAM; 652 hints.ai_protocol = 0; 653 error = getaddrinfo(host, NULL, &hints, &res0); 654 if (error) { 655 warnx("%s", gai_strerror(error)); 656 goto cleanup_fetch_url; 657 } 658 if (res0->ai_canonname) 659 host = res0->ai_canonname; 660 661 s = -1; 662 for (res = res0; res; res = res->ai_next) { 663 /* 664 * see comment in hookup() 665 */ 666 ai_unmapped(res); 667 if (getnameinfo(res->ai_addr, res->ai_addrlen, 668 hbuf, sizeof(hbuf), NULL, 0, 669 NI_NUMERICHOST) != 0) 670 strncpy(hbuf, "invalid", sizeof(hbuf)); 671 672 if (verbose && res != res0) 673 fprintf(ttyout, "Trying %s...\n", hbuf); 674 675 ((struct sockaddr_in *)res->ai_addr)->sin_port = 676 htons(portnum); 677 s = socket(res->ai_family, SOCK_STREAM, 678 res->ai_protocol); 679 if (s < 0) { 680 warn("Can't create socket"); 681 continue; 682 } 683 684 if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) { 685 warn("Connect to address `%s'", hbuf); 686 close(s); 687 s = -1; 688 continue; 689 } 690 691 /* success */ 692 break; 693 } 694 freeaddrinfo(res0); 695 696 if (s < 0) { 697 warn("Can't connect to %s", host); 698 goto cleanup_fetch_url; 699 } 700 701 fin = fdopen(s, "r+"); 702 /* 703 * Construct and send the request. 704 */ 705 if (verbose) 706 fprintf(ttyout, "Requesting %s\n", url); 707 leading = " ("; 708 hasleading = 0; 709 if (isproxy) { 710 if (verbose) { 711 fprintf(ttyout, "%svia %s:%s", leading, 712 host, port); 713 leading = ", "; 714 hasleading++; 715 } 716 fprintf(fin, "GET %s HTTP/1.0\r\n", path); 717 if (flushcache) 718 fprintf(fin, "Pragma: no-cache\r\n"); 719 } else { 720 fprintf(fin, "GET %s HTTP/1.1\r\n", path); 721 if (strchr(host, ':')) { 722 char *h, *p; 723 724 /* 725 * strip off IPv6 scope identifier, since it is 726 * local to the node 727 */ 728 h = xstrdup(host); 729 if (isipv6addr(h) && 730 (p = strchr(h, '%')) != NULL) { 731 *p = '\0'; 732 } 733 fprintf(fin, "Host: [%s]:%d\r\n", h, portnum); 734 free(h); 735 } else 736 fprintf(fin, "Host: %s:%d\r\n", host, portnum); 737 fprintf(fin, "Accept: */*\r\n"); 738 fprintf(fin, "Connection: close\r\n"); 739 if (restart_point) { 740 fputs(leading, ttyout); 741 fprintf(fin, "Range: bytes=" LLF "-\r\n", 742 (LLT)restart_point); 743 fprintf(ttyout, "restarting at " LLF, 744 (LLT)restart_point); 745 leading = ", "; 746 hasleading++; 747 } 748 if (flushcache) 749 fprintf(fin, "Cache-Control: no-cache\r\n"); 750 } 751 fprintf(fin, "User-Agent: %s/%s\r\n", FTP_PRODUCT, FTP_VERSION); 752 if (wwwauth) { 753 if (verbose) { 754 fprintf(ttyout, "%swith authorization", 755 leading); 756 leading = ", "; 757 hasleading++; 758 } 759 fprintf(fin, "Authorization: %s\r\n", wwwauth); 760 } 761 if (proxyauth) { 762 if (verbose) { 763 fprintf(ttyout, 764 "%swith proxy authorization", leading); 765 leading = ", "; 766 hasleading++; 767 } 768 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth); 769 } 770 if (verbose && hasleading) 771 fputs(")\n", ttyout); 772 fprintf(fin, "\r\n"); 773 if (fflush(fin) == EOF) { 774 warn("Writing HTTP request"); 775 goto cleanup_fetch_url; 776 } 777 778 /* Read the response */ 779 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) { 780 warn("Receiving HTTP reply"); 781 goto cleanup_fetch_url; 782 } 783 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) 784 buf[--len] = '\0'; 785 if (debug) 786 fprintf(ttyout, "received `%s'\n", buf); 787 788 /* Determine HTTP response code */ 789 cp = strchr(buf, ' '); 790 if (cp == NULL) 791 goto improper; 792 else 793 cp++; 794 hcode = strtol(cp, &ep, 10); 795 if (*ep != '\0' && !isspace((unsigned char)*ep)) 796 goto improper; 797 message = xstrdup(cp); 798 799 /* Read the rest of the header. */ 800 FREEPTR(buf); 801 while (1) { 802 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) 803 == NULL) { 804 warn("Receiving HTTP reply"); 805 goto cleanup_fetch_url; 806 } 807 while (len > 0 && 808 (buf[len-1] == '\r' || buf[len-1] == '\n')) 809 buf[--len] = '\0'; 810 if (len == 0) 811 break; 812 if (debug) 813 fprintf(ttyout, "received `%s'\n", buf); 814 815 /* Look for some headers */ 816 cp = buf; 817 818 #define CONTENTLEN "Content-Length: " 819 if (strncasecmp(cp, CONTENTLEN, 820 sizeof(CONTENTLEN) - 1) == 0) { 821 cp += sizeof(CONTENTLEN) - 1; 822 filesize = STRTOLL(cp, &ep, 10); 823 if (filesize < 0 || *ep != '\0') 824 goto improper; 825 if (debug) 826 fprintf(ttyout, 827 "parsed len as: " LLF "\n", 828 (LLT)filesize); 829 830 #define CONTENTRANGE "Content-Range: bytes " 831 } else if (strncasecmp(cp, CONTENTRANGE, 832 sizeof(CONTENTRANGE) - 1) == 0) { 833 cp += sizeof(CONTENTRANGE) - 1; 834 if (*cp == '*') { 835 ep = cp + 1; 836 } 837 else { 838 rangestart = STRTOLL(cp, &ep, 10); 839 if (rangestart < 0 || *ep != '-') 840 goto improper; 841 cp = ep + 1; 842 rangeend = STRTOLL(cp, &ep, 10); 843 if (rangeend < 0 || rangeend < rangestart) 844 goto improper; 845 } 846 if (*ep != '/') 847 goto improper; 848 cp = ep + 1; 849 if (*cp == '*') { 850 ep = cp + 1; 851 } 852 else { 853 entitylen = STRTOLL(cp, &ep, 10); 854 if (entitylen < 0) 855 goto improper; 856 } 857 if (*ep != '\0') 858 goto improper; 859 860 if (debug) { 861 fprintf(ttyout, "parsed range as: "); 862 if (rangestart == -1) 863 fprintf(ttyout, "*"); 864 else 865 fprintf(ttyout, LLF "-" LLF, 866 (LLT)rangestart, 867 (LLT)rangeend); 868 fprintf(ttyout, "/" LLF "\n", (LLT)entitylen); 869 } 870 if (! restart_point) { 871 warnx( 872 "Received unexpected Content-Range header"); 873 goto cleanup_fetch_url; 874 } 875 876 #define LASTMOD "Last-Modified: " 877 } else if (strncasecmp(cp, LASTMOD, 878 sizeof(LASTMOD) - 1) == 0) { 879 struct tm parsed; 880 char *t; 881 882 cp += sizeof(LASTMOD) - 1; 883 /* RFC 1123 */ 884 if ((t = strptime(cp, 885 "%a, %d %b %Y %H:%M:%S GMT", 886 &parsed)) 887 /* RFC 850 */ 888 || (t = strptime(cp, 889 "%a, %d-%b-%y %H:%M:%S GMT", 890 &parsed)) 891 /* asctime */ 892 || (t = strptime(cp, 893 "%a, %b %d %H:%M:%S %Y", 894 &parsed))) { 895 parsed.tm_isdst = -1; 896 if (*t == '\0') 897 mtime = timegm(&parsed); 898 if (debug && mtime != -1) { 899 fprintf(ttyout, 900 "parsed date as: %s", 901 ctime(&mtime)); 902 } 903 } 904 905 #define LOCATION "Location: " 906 } else if (strncasecmp(cp, LOCATION, 907 sizeof(LOCATION) - 1) == 0) { 908 cp += sizeof(LOCATION) - 1; 909 location = xstrdup(cp); 910 if (debug) 911 fprintf(ttyout, 912 "parsed location as: %s\n", cp); 913 914 #define TRANSENC "Transfer-Encoding: " 915 } else if (strncasecmp(cp, TRANSENC, 916 sizeof(TRANSENC) - 1) == 0) { 917 cp += sizeof(TRANSENC) - 1; 918 if (strcasecmp(cp, "binary") == 0) { 919 warnx( 920 "Bogus transfer encoding - `%s' (fetching anyway)", 921 cp); 922 continue; 923 } 924 if (strcasecmp(cp, "chunked") != 0) { 925 warnx( 926 "Unsupported transfer encoding - `%s'", 927 cp); 928 goto cleanup_fetch_url; 929 } 930 ischunked++; 931 if (debug) 932 fprintf(ttyout, 933 "using chunked encoding\n"); 934 935 #define PROXYAUTH "Proxy-Authenticate: " 936 } else if (strncasecmp(cp, PROXYAUTH, 937 sizeof(PROXYAUTH) - 1) == 0) { 938 cp += sizeof(PROXYAUTH) - 1; 939 FREEPTR(auth); 940 auth = xstrdup(cp); 941 if (debug) 942 fprintf(ttyout, 943 "parsed proxy-auth as: %s\n", cp); 944 945 #define WWWAUTH "WWW-Authenticate: " 946 } else if (strncasecmp(cp, WWWAUTH, 947 sizeof(WWWAUTH) - 1) == 0) { 948 cp += sizeof(WWWAUTH) - 1; 949 FREEPTR(auth); 950 auth = xstrdup(cp); 951 if (debug) 952 fprintf(ttyout, 953 "parsed www-auth as: %s\n", cp); 954 955 } 956 957 } 958 /* finished parsing header */ 959 FREEPTR(buf); 960 961 switch (hcode) { 962 case 200: 963 break; 964 case 206: 965 if (! restart_point) { 966 warnx("Not expecting partial content header"); 967 goto cleanup_fetch_url; 968 } 969 break; 970 case 300: 971 case 301: 972 case 302: 973 case 303: 974 case 305: 975 if (EMPTYSTRING(location)) { 976 warnx( 977 "No redirection Location provided by server"); 978 goto cleanup_fetch_url; 979 } 980 if (redirect_loop++ > 5) { 981 warnx("Too many redirections requested"); 982 goto cleanup_fetch_url; 983 } 984 if (hcode == 305) { 985 if (verbose) 986 fprintf(ttyout, "Redirected via %s\n", 987 location); 988 rval = fetch_url(url, location, 989 proxyauth, wwwauth); 990 } else { 991 if (verbose) 992 fprintf(ttyout, "Redirected to %s\n", 993 location); 994 rval = go_fetch(location); 995 } 996 goto cleanup_fetch_url; 997 case 401: 998 case 407: 999 { 1000 char **authp; 1001 char *auser, *apass; 1002 1003 fprintf(ttyout, "%s\n", message); 1004 if (EMPTYSTRING(auth)) { 1005 warnx( 1006 "No authentication challenge provided by server"); 1007 goto cleanup_fetch_url; 1008 } 1009 if (hcode == 401) { 1010 authp = &wwwauth; 1011 auser = user; 1012 apass = pass; 1013 } else { 1014 authp = &proxyauth; 1015 auser = puser; 1016 apass = ppass; 1017 } 1018 if (*authp != NULL) { 1019 char reply[10]; 1020 1021 fprintf(ttyout, 1022 "Authorization failed. Retry (y/n)? "); 1023 if (fgets(reply, sizeof(reply), stdin) 1024 == NULL) { 1025 clearerr(stdin); 1026 goto cleanup_fetch_url; 1027 } else { 1028 if (tolower(reply[0]) != 'y') 1029 goto cleanup_fetch_url; 1030 } 1031 auser = NULL; 1032 apass = NULL; 1033 } 1034 if (auth_url(auth, authp, auser, apass) == 0) { 1035 rval = fetch_url(url, proxyenv, 1036 proxyauth, wwwauth); 1037 memset(*authp, 0, strlen(*authp)); 1038 FREEPTR(*authp); 1039 } 1040 goto cleanup_fetch_url; 1041 } 1042 default: 1043 if (message) 1044 warnx("Error retrieving file - `%s'", message); 1045 else 1046 warnx("Unknown error retrieving file"); 1047 goto cleanup_fetch_url; 1048 } 1049 } /* end of ftp:// or http:// specific setup */ 1050 1051 /* Open the output file. */ 1052 if (strcmp(savefile, "-") == 0) { 1053 fout = stdout; 1054 } else if (*savefile == '|') { 1055 oldintp = xsignal(SIGPIPE, SIG_IGN); 1056 fout = popen(savefile + 1, "w"); 1057 if (fout == NULL) { 1058 warn("Can't run `%s'", savefile + 1); 1059 goto cleanup_fetch_url; 1060 } 1061 closefunc = pclose; 1062 } else { 1063 if ((rangeend != -1 && rangeend <= restart_point) || 1064 (rangestart == -1 && filesize != -1 && filesize <= restart_point)) { 1065 /* already done */ 1066 if (verbose) 1067 fprintf(ttyout, "already done\n"); 1068 rval = 0; 1069 goto cleanup_fetch_url; 1070 } 1071 if (restart_point && rangestart != -1) { 1072 if (entitylen != -1) 1073 filesize = entitylen; 1074 if (rangestart != restart_point) { 1075 warnx( 1076 "Size of `%s' differs from save file `%s'", 1077 url, savefile); 1078 goto cleanup_fetch_url; 1079 } 1080 fout = fopen(savefile, "a"); 1081 } else 1082 fout = fopen(savefile, "w"); 1083 if (fout == NULL) { 1084 warn("Can't open `%s'", savefile); 1085 goto cleanup_fetch_url; 1086 } 1087 closefunc = fclose; 1088 } 1089 1090 /* Trap signals */ 1091 if (sigsetjmp(httpabort, 1)) 1092 goto cleanup_fetch_url; 1093 (void)xsignal(SIGQUIT, psummary); 1094 oldintr = xsignal(SIGINT, aborthttp); 1095 1096 if (rcvbuf_size > bufsize) { 1097 if (xferbuf) 1098 (void)free(xferbuf); 1099 bufsize = rcvbuf_size; 1100 xferbuf = xmalloc(bufsize); 1101 } 1102 1103 bytes = 0; 1104 hashbytes = mark; 1105 progressmeter(-1); 1106 1107 /* Finally, suck down the file. */ 1108 do { 1109 long chunksize; 1110 1111 chunksize = 0; 1112 /* read chunksize */ 1113 if (ischunked) { 1114 if (fgets(xferbuf, bufsize, fin) == NULL) { 1115 warnx("Unexpected EOF reading chunksize"); 1116 goto cleanup_fetch_url; 1117 } 1118 chunksize = strtol(xferbuf, &ep, 16); 1119 1120 /* 1121 * XXX: Work around bug in Apache 1.3.9 and 1122 * 1.3.11, which incorrectly put trailing 1123 * space after the chunksize. 1124 */ 1125 while (*ep == ' ') 1126 ep++; 1127 1128 if (strcmp(ep, "\r\n") != 0) { 1129 warnx("Unexpected data following chunksize"); 1130 goto cleanup_fetch_url; 1131 } 1132 if (debug) 1133 fprintf(ttyout, "got chunksize of " LLF "\n", 1134 (LLT)chunksize); 1135 if (chunksize == 0) 1136 break; 1137 } 1138 /* transfer file or chunk */ 1139 while (1) { 1140 struct timeval then, now, td; 1141 off_t bufrem; 1142 1143 if (rate_get) 1144 (void)gettimeofday(&then, NULL); 1145 bufrem = rate_get ? rate_get : bufsize; 1146 if (ischunked) 1147 bufrem = MIN(chunksize, bufrem); 1148 while (bufrem > 0) { 1149 len = fread(xferbuf, sizeof(char), 1150 MIN(bufsize, bufrem), fin); 1151 if (len <= 0) 1152 goto chunkdone; 1153 bytes += len; 1154 bufrem -= len; 1155 if (fwrite(xferbuf, sizeof(char), len, fout) 1156 != len) { 1157 warn("Writing `%s'", savefile); 1158 goto cleanup_fetch_url; 1159 } 1160 if (hash && !progress) { 1161 while (bytes >= hashbytes) { 1162 (void)putc('#', ttyout); 1163 hashbytes += mark; 1164 } 1165 (void)fflush(ttyout); 1166 } 1167 if (ischunked) { 1168 chunksize -= len; 1169 if (chunksize <= 0) 1170 break; 1171 } 1172 } 1173 if (rate_get) { 1174 while (1) { 1175 (void)gettimeofday(&now, NULL); 1176 timersub(&now, &then, &td); 1177 if (td.tv_sec > 0) 1178 break; 1179 usleep(1000000 - td.tv_usec); 1180 } 1181 } 1182 if (ischunked && chunksize <= 0) 1183 break; 1184 } 1185 /* read CRLF after chunk*/ 1186 chunkdone: 1187 if (ischunked) { 1188 if (fgets(xferbuf, bufsize, fin) == NULL) 1189 break; 1190 if (strcmp(xferbuf, "\r\n") != 0) { 1191 warnx("Unexpected data following chunk"); 1192 goto cleanup_fetch_url; 1193 } 1194 } 1195 } while (ischunked); 1196 if (hash && !progress && bytes > 0) { 1197 if (bytes < mark) 1198 (void)putc('#', ttyout); 1199 (void)putc('\n', ttyout); 1200 } 1201 if (ferror(fin)) { 1202 warn("Reading file"); 1203 goto cleanup_fetch_url; 1204 } 1205 progressmeter(1); 1206 bytes = 0; 1207 (void)fflush(fout); 1208 if (closefunc == fclose && mtime != -1) { 1209 struct timeval tval[2]; 1210 1211 (void)gettimeofday(&tval[0], NULL); 1212 tval[1].tv_sec = mtime; 1213 tval[1].tv_usec = 0; 1214 (*closefunc)(fout); 1215 fout = NULL; 1216 1217 if (utimes(savefile, tval) == -1) { 1218 fprintf(ttyout, 1219 "Can't change modification time to %s", 1220 asctime(localtime(&mtime))); 1221 } 1222 } 1223 if (bytes > 0) 1224 ptransfer(0); 1225 1226 rval = 0; 1227 goto cleanup_fetch_url; 1228 1229 improper: 1230 warnx("Improper response from `%s'", host); 1231 1232 cleanup_fetch_url: 1233 if (oldintr) 1234 (void)xsignal(SIGINT, oldintr); 1235 if (oldintp) 1236 (void)xsignal(SIGPIPE, oldintp); 1237 if (fin != NULL) 1238 fclose(fin); 1239 else if (s != -1) 1240 close(s); 1241 if (closefunc != NULL && fout != NULL) 1242 (*closefunc)(fout); 1243 FREEPTR(savefile); 1244 FREEPTR(user); 1245 FREEPTR(pass); 1246 FREEPTR(host); 1247 FREEPTR(port); 1248 FREEPTR(path); 1249 FREEPTR(decodedpath); 1250 FREEPTR(puser); 1251 FREEPTR(ppass); 1252 FREEPTR(buf); 1253 FREEPTR(auth); 1254 FREEPTR(location); 1255 FREEPTR(message); 1256 return (rval); 1257 } 1258 1259 /* 1260 * Abort a HTTP retrieval 1261 */ 1262 void 1263 aborthttp(int notused) 1264 { 1265 char msgbuf[100]; 1266 int len; 1267 1268 alarmtimer(0); 1269 len = strlcpy(msgbuf, "\nHTTP fetch aborted.\n", sizeof(msgbuf)); 1270 write(fileno(ttyout), msgbuf, len); 1271 siglongjmp(httpabort, 1); 1272 } 1273 1274 /* 1275 * Retrieve ftp URL or classic ftp argument using FTP. 1276 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection 1277 * is still open (e.g, ftp xfer with trailing /) 1278 */ 1279 static int 1280 fetch_ftp(const char *url) 1281 { 1282 char *cp, *xargv[5], rempath[MAXPATHLEN]; 1283 char *host, *path, *dir, *file, *user, *pass; 1284 char *port; 1285 int dirhasglob, filehasglob, oautologin, rval, type, xargc; 1286 in_port_t portnum; 1287 url_t urltype; 1288 1289 host = path = dir = file = user = pass = NULL; 1290 port = NULL; 1291 rval = 1; 1292 type = TYPE_I; 1293 1294 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) { 1295 if ((parse_url(url, "URL", &urltype, &user, &pass, 1296 &host, &port, &portnum, &path) == -1) || 1297 (user != NULL && *user == '\0') || 1298 (pass != NULL && *pass == '\0') || 1299 EMPTYSTRING(host)) { 1300 warnx("Invalid URL `%s'", url); 1301 goto cleanup_fetch_ftp; 1302 } 1303 url_decode(user); 1304 url_decode(pass); 1305 /* 1306 * Note: Don't url_decode(path) here. We need to keep the 1307 * distinction between "/" and "%2F" until later. 1308 */ 1309 1310 /* check for trailing ';type=[aid]' */ 1311 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) { 1312 if (strcasecmp(cp, ";type=a") == 0) 1313 type = TYPE_A; 1314 else if (strcasecmp(cp, ";type=i") == 0) 1315 type = TYPE_I; 1316 else if (strcasecmp(cp, ";type=d") == 0) { 1317 warnx( 1318 "Directory listing via a URL is not supported"); 1319 goto cleanup_fetch_ftp; 1320 } else { 1321 warnx("Invalid suffix `%s' in URL `%s'", cp, 1322 url); 1323 goto cleanup_fetch_ftp; 1324 } 1325 *cp = 0; 1326 } 1327 } else { /* classic style `[user@]host:[file]' */ 1328 urltype = CLASSIC_URL_T; 1329 host = xstrdup(url); 1330 cp = strchr(host, '@'); 1331 if (cp != NULL) { 1332 *cp = '\0'; 1333 user = host; 1334 anonftp = 0; /* disable anonftp */ 1335 host = xstrdup(cp + 1); 1336 } 1337 cp = strchr(host, ':'); 1338 if (cp != NULL) { 1339 *cp = '\0'; 1340 path = xstrdup(cp + 1); 1341 } 1342 } 1343 if (EMPTYSTRING(host)) 1344 goto cleanup_fetch_ftp; 1345 1346 /* Extract the file and (if present) directory name. */ 1347 dir = path; 1348 if (! EMPTYSTRING(dir)) { 1349 /* 1350 * If we are dealing with classic `[user@]host:[path]' syntax, 1351 * then a path of the form `/file' (resulting from input of the 1352 * form `host:/file') means that we should do "CWD /" before 1353 * retrieving the file. So we set dir="/" and file="file". 1354 * 1355 * But if we are dealing with URLs like `ftp://host/path' then 1356 * a path of the form `/file' (resulting from a URL of the form 1357 * `ftp://host//file') means that we should do `CWD ' (with an 1358 * empty argument) before retrieving the file. So we set 1359 * dir="" and file="file". 1360 * 1361 * If the path does not contain / at all, we set dir=NULL. 1362 * (We get a path without any slashes if we are dealing with 1363 * classic `[user@]host:[file]' or URL `ftp://host/file'.) 1364 * 1365 * In all other cases, we set dir to a string that does not 1366 * include the final '/' that separates the dir part from the 1367 * file part of the path. (This will be the empty string if 1368 * and only if we are dealing with a path of the form `/file' 1369 * resulting from an URL of the form `ftp://host//file'.) 1370 */ 1371 cp = strrchr(dir, '/'); 1372 if (cp == dir && urltype == CLASSIC_URL_T) { 1373 file = cp + 1; 1374 dir = "/"; 1375 } else if (cp != NULL) { 1376 *cp++ = '\0'; 1377 file = cp; 1378 } else { 1379 file = dir; 1380 dir = NULL; 1381 } 1382 } else 1383 dir = NULL; 1384 if (urltype == FTP_URL_T && file != NULL) { 1385 url_decode(file); 1386 /* but still don't url_decode(dir) */ 1387 } 1388 if (debug) 1389 fprintf(ttyout, 1390 "fetch_ftp: user `%s' pass `%s' host %s port %s " 1391 "path `%s' dir `%s' file `%s'\n", 1392 user ? user : "<null>", pass ? pass : "<null>", 1393 host ? host : "<null>", port ? port : "<null>", 1394 path ? path : "<null>", 1395 dir ? dir : "<null>", file ? file : "<null>"); 1396 1397 dirhasglob = filehasglob = 0; 1398 if (doglob && urltype == CLASSIC_URL_T) { 1399 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL) 1400 dirhasglob = 1; 1401 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL) 1402 filehasglob = 1; 1403 } 1404 1405 /* Set up the connection */ 1406 if (connected) 1407 disconnect(0, NULL); 1408 xargv[0] = (char *)getprogname(); /* XXX discards const */ 1409 xargv[1] = host; 1410 xargv[2] = NULL; 1411 xargc = 2; 1412 if (port) { 1413 xargv[2] = port; 1414 xargv[3] = NULL; 1415 xargc = 3; 1416 } 1417 oautologin = autologin; 1418 /* don't autologin in setpeer(), use ftp_login() below */ 1419 autologin = 0; 1420 setpeer(xargc, xargv); 1421 autologin = oautologin; 1422 if ((connected == 0) || 1423 (connected == 1 && !ftp_login(host, user, pass))) { 1424 warnx("Can't connect or login to host `%s'", host); 1425 goto cleanup_fetch_ftp; 1426 } 1427 1428 switch (type) { 1429 case TYPE_A: 1430 setascii(1, xargv); 1431 break; 1432 case TYPE_I: 1433 setbinary(1, xargv); 1434 break; 1435 default: 1436 errx(1, "fetch_ftp: unknown transfer type %d", type); 1437 } 1438 1439 /* 1440 * Change directories, if necessary. 1441 * 1442 * Note: don't use EMPTYSTRING(dir) below, because 1443 * dir=="" means something different from dir==NULL. 1444 */ 1445 if (dir != NULL && !dirhasglob) { 1446 char *nextpart; 1447 1448 /* 1449 * If we are dealing with a classic `[user@]host:[path]' 1450 * (urltype is CLASSIC_URL_T) then we have a raw directory 1451 * name (not encoded in any way) and we can change 1452 * directories in one step. 1453 * 1454 * If we are dealing with an `ftp://host/path' URL 1455 * (urltype is FTP_URL_T), then RFC 1738 says we need to 1456 * send a separate CWD command for each unescaped "/" 1457 * in the path, and we have to interpret %hex escaping 1458 * *after* we find the slashes. It's possible to get 1459 * empty components here, (from multiple adjacent 1460 * slashes in the path) and RFC 1738 says that we should 1461 * still do `CWD ' (with a null argument) in such cases. 1462 * 1463 * Many ftp servers don't support `CWD ', so if there's an 1464 * error performing that command, bail out with a descriptive 1465 * message. 1466 * 1467 * Examples: 1468 * 1469 * host: dir="", urltype=CLASSIC_URL_T 1470 * logged in (to default directory) 1471 * host:file dir=NULL, urltype=CLASSIC_URL_T 1472 * "RETR file" 1473 * host:dir/ dir="dir", urltype=CLASSIC_URL_T 1474 * "CWD dir", logged in 1475 * ftp://host/ dir="", urltype=FTP_URL_T 1476 * logged in (to default directory) 1477 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T 1478 * "CWD dir", logged in 1479 * ftp://host/file dir=NULL, urltype=FTP_URL_T 1480 * "RETR file" 1481 * ftp://host//file dir="", urltype=FTP_URL_T 1482 * "CWD ", "RETR file" 1483 * host:/file dir="/", urltype=CLASSIC_URL_T 1484 * "CWD /", "RETR file" 1485 * ftp://host///file dir="/", urltype=FTP_URL_T 1486 * "CWD ", "CWD ", "RETR file" 1487 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T 1488 * "CWD /", "RETR file" 1489 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T 1490 * "CWD foo", "RETR file" 1491 * ftp://host/foo/bar/file dir="foo/bar" 1492 * "CWD foo", "CWD bar", "RETR file" 1493 * ftp://host//foo/bar/file dir="/foo/bar" 1494 * "CWD ", "CWD foo", "CWD bar", "RETR file" 1495 * ftp://host/foo//bar/file dir="foo//bar" 1496 * "CWD foo", "CWD ", "CWD bar", "RETR file" 1497 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar" 1498 * "CWD /", "CWD foo", "CWD bar", "RETR file" 1499 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar" 1500 * "CWD /foo", "CWD bar", "RETR file" 1501 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar" 1502 * "CWD /foo/bar", "RETR file" 1503 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL 1504 * "RETR /foo/bar/file" 1505 * 1506 * Note that we don't need `dir' after this point. 1507 */ 1508 do { 1509 if (urltype == FTP_URL_T) { 1510 nextpart = strchr(dir, '/'); 1511 if (nextpart) { 1512 *nextpart = '\0'; 1513 nextpart++; 1514 } 1515 url_decode(dir); 1516 } else 1517 nextpart = NULL; 1518 if (debug) 1519 fprintf(ttyout, "dir `%s', nextpart `%s'\n", 1520 dir ? dir : "<null>", 1521 nextpart ? nextpart : "<null>"); 1522 if (urltype == FTP_URL_T || *dir != '\0') { 1523 xargv[0] = "cd"; 1524 xargv[1] = dir; 1525 xargv[2] = NULL; 1526 dirchange = 0; 1527 cd(2, xargv); 1528 if (! dirchange) { 1529 if (*dir == '\0' && code == 500) 1530 fprintf(stderr, 1531 "\n" 1532 "ftp: The `CWD ' command (without a directory), which is required by\n" 1533 " RFC 1738 to support the empty directory in the URL pathname (`//'),\n" 1534 " conflicts with the server's conformance to RFC 959.\n" 1535 " Try the same URL without the `//' in the URL pathname.\n" 1536 "\n"); 1537 goto cleanup_fetch_ftp; 1538 } 1539 } 1540 dir = nextpart; 1541 } while (dir != NULL); 1542 } 1543 1544 if (EMPTYSTRING(file)) { 1545 rval = -1; 1546 goto cleanup_fetch_ftp; 1547 } 1548 1549 if (dirhasglob) { 1550 (void)strlcpy(rempath, dir, sizeof(rempath)); 1551 (void)strlcat(rempath, "/", sizeof(rempath)); 1552 (void)strlcat(rempath, file, sizeof(rempath)); 1553 file = rempath; 1554 } 1555 1556 /* Fetch the file(s). */ 1557 xargc = 2; 1558 xargv[0] = "get"; 1559 xargv[1] = file; 1560 xargv[2] = NULL; 1561 if (dirhasglob || filehasglob) { 1562 int ointeractive; 1563 1564 ointeractive = interactive; 1565 interactive = 0; 1566 xargv[0] = "mget"; 1567 mget(xargc, xargv); 1568 interactive = ointeractive; 1569 } else { 1570 if (outfile == NULL) { 1571 cp = strrchr(file, '/'); /* find savefile */ 1572 if (cp != NULL) 1573 outfile = cp + 1; 1574 else 1575 outfile = file; 1576 } 1577 xargv[2] = (char *)outfile; 1578 xargv[3] = NULL; 1579 xargc++; 1580 if (restartautofetch) 1581 reget(xargc, xargv); 1582 else 1583 get(xargc, xargv); 1584 } 1585 1586 if ((code / 100) == COMPLETE) 1587 rval = 0; 1588 1589 cleanup_fetch_ftp: 1590 FREEPTR(host); 1591 FREEPTR(path); 1592 FREEPTR(user); 1593 FREEPTR(pass); 1594 return (rval); 1595 } 1596 1597 /* 1598 * Retrieve the given file to outfile. 1599 * Supports arguments of the form: 1600 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else 1601 * call fetch_ftp() 1602 * "http://host/path" call fetch_url() to use HTTP 1603 * "file:///path" call fetch_url() to copy 1604 * "about:..." print a message 1605 * 1606 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection 1607 * is still open (e.g, ftp xfer with trailing /) 1608 */ 1609 static int 1610 go_fetch(const char *url) 1611 { 1612 char *proxy; 1613 1614 /* 1615 * Check for about:* 1616 */ 1617 if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) { 1618 url += sizeof(ABOUT_URL) -1; 1619 if (strcasecmp(url, "ftp") == 0) { 1620 fputs( 1621 "This version of ftp has been enhanced by Luke Mewburn <lukem@netbsd.org>\n" 1622 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout); 1623 } else if (strcasecmp(url, "lukem") == 0) { 1624 fputs( 1625 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n" 1626 "Please email feedback to <lukem@netbsd.org>.\n", ttyout); 1627 } else if (strcasecmp(url, "netbsd") == 0) { 1628 fputs( 1629 "NetBSD is a freely available and redistributable UNIX-like operating system.\n" 1630 "For more information, see http://www.netbsd.org/index.html\n", ttyout); 1631 } else if (strcasecmp(url, "version") == 0) { 1632 fprintf(ttyout, "Version: %s %s%s\n", 1633 FTP_PRODUCT, FTP_VERSION, 1634 #ifdef INET6 1635 "" 1636 #else 1637 " (-IPv6)" 1638 #endif 1639 ); 1640 } else { 1641 fprintf(ttyout, "`%s' is an interesting topic.\n", url); 1642 } 1643 fputs("\n", ttyout); 1644 return (0); 1645 } 1646 1647 /* 1648 * Check for file:// and http:// URLs. 1649 */ 1650 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 || 1651 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) 1652 return (fetch_url(url, NULL, NULL, NULL)); 1653 1654 /* 1655 * Try FTP URL-style and host:file arguments next. 1656 * If ftpproxy is set with an FTP URL, use fetch_url() 1657 * Othewise, use fetch_ftp(). 1658 */ 1659 proxy = getoptionvalue("ftp_proxy"); 1660 if (!EMPTYSTRING(proxy) && 1661 strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) 1662 return (fetch_url(url, NULL, NULL, NULL)); 1663 1664 return (fetch_ftp(url)); 1665 } 1666 1667 /* 1668 * Retrieve multiple files from the command line, 1669 * calling go_fetch() for each file. 1670 * 1671 * If an ftp path has a trailing "/", the path will be cd-ed into and 1672 * the connection remains open, and the function will return -1 1673 * (to indicate the connection is alive). 1674 * If an error occurs the return value will be the offset+1 in 1675 * argv[] of the file that caused a problem (i.e, argv[x] 1676 * returns x+1) 1677 * Otherwise, 0 is returned if all files retrieved successfully. 1678 */ 1679 int 1680 auto_fetch(int argc, char *argv[]) 1681 { 1682 volatile int argpos; 1683 int rval; 1684 1685 argpos = 0; 1686 1687 if (sigsetjmp(toplevel, 1)) { 1688 if (connected) 1689 disconnect(0, NULL); 1690 return (argpos + 1); 1691 } 1692 (void)xsignal(SIGINT, intr); 1693 (void)xsignal(SIGPIPE, lostpeer); 1694 1695 /* 1696 * Loop through as long as there's files to fetch. 1697 */ 1698 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) { 1699 if (strchr(argv[argpos], ':') == NULL) 1700 break; 1701 redirect_loop = 0; 1702 if (!anonftp) 1703 anonftp = 2; /* Handle "automatic" transfers. */ 1704 rval = go_fetch(argv[argpos]); 1705 if (outfile != NULL && strcmp(outfile, "-") != 0 1706 && outfile[0] != '|') 1707 outfile = NULL; 1708 if (rval > 0) 1709 rval = argpos + 1; 1710 } 1711 1712 if (connected && rval != -1) 1713 disconnect(0, NULL); 1714 return (rval); 1715 } 1716 1717 1718 int 1719 auto_put(int argc, char **argv, const char *uploadserver) 1720 { 1721 char *uargv[4], *path, *pathsep; 1722 int uargc, rval, len; 1723 1724 uargc = 0; 1725 uargv[uargc++] = "mput"; 1726 uargv[uargc++] = argv[0]; 1727 uargv[2] = uargv[3] = NULL; 1728 pathsep = NULL; 1729 rval = 1; 1730 1731 if (debug) 1732 fprintf(ttyout, "auto_put: target `%s'\n", uploadserver); 1733 1734 path = xstrdup(uploadserver); 1735 len = strlen(path); 1736 if (path[len - 1] != '/' && path[len - 1] != ':') { 1737 /* 1738 * make sure we always pass a directory to auto_fetch 1739 */ 1740 if (argc > 1) { /* more than one file to upload */ 1741 int len; 1742 1743 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */ 1744 free(path); 1745 path = (char *)xmalloc(len); 1746 (void)strlcpy(path, uploadserver, len); 1747 (void)strlcat(path, "/", len); 1748 } else { /* single file to upload */ 1749 uargv[0] = "put"; 1750 pathsep = strrchr(path, '/'); 1751 if (pathsep == NULL) { 1752 pathsep = strrchr(path, ':'); 1753 if (pathsep == NULL) { 1754 warnx("Invalid URL `%s'", path); 1755 goto cleanup_auto_put; 1756 } 1757 pathsep++; 1758 uargv[2] = xstrdup(pathsep); 1759 pathsep[0] = '/'; 1760 } else 1761 uargv[2] = xstrdup(pathsep + 1); 1762 pathsep[1] = '\0'; 1763 uargc++; 1764 } 1765 } 1766 if (debug) 1767 fprintf(ttyout, "auto_put: url `%s' argv[2] `%s'\n", 1768 path, uargv[2] ? uargv[2] : "<null>"); 1769 1770 /* connect and cwd */ 1771 rval = auto_fetch(1, &path); 1772 free(path); 1773 if(rval >= 0) 1774 goto cleanup_auto_put; 1775 1776 /* XXX : is this the best way? */ 1777 if (uargc == 3) { 1778 uargv[1] = argv[0]; 1779 put(uargc, uargv); 1780 goto cleanup_auto_put; 1781 } 1782 1783 for(; argv[0] != NULL; argv++) { 1784 uargv[1] = argv[0]; 1785 mput(uargc, uargv); 1786 } 1787 rval = 0; 1788 1789 cleanup_auto_put: 1790 FREEPTR(uargv[2]); 1791 return (rval); 1792 } 1793