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