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