1 /* $OpenBSD: fetch.c,v 1.185 2019/12/19 00:07:20 jca Exp $ */ 2 /* $NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $ */ 3 4 /*- 5 * Copyright (c) 1997 The NetBSD Foundation, Inc. 6 * All rights reserved. 7 * 8 * This code is derived from software contributed to The NetBSD Foundation 9 * by Jason Thorpe and Luke Mewburn. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 * POSSIBILITY OF SUCH DAMAGE. 31 */ 32 33 /* 34 * FTP User Program -- Command line file retrieval 35 */ 36 37 #include <sys/types.h> 38 #include <sys/socket.h> 39 #include <sys/stat.h> 40 41 #include <netinet/in.h> 42 43 #include <arpa/ftp.h> 44 #include <arpa/inet.h> 45 46 #include <ctype.h> 47 #include <err.h> 48 #include <libgen.h> 49 #include <netdb.h> 50 #include <fcntl.h> 51 #include <signal.h> 52 #include <vis.h> 53 #include <stdio.h> 54 #include <stdarg.h> 55 #include <errno.h> 56 #include <stdlib.h> 57 #include <string.h> 58 #include <unistd.h> 59 #include <util.h> 60 #include <resolv.h> 61 62 #ifndef NOSSL 63 #include <tls.h> 64 #else /* !NOSSL */ 65 struct tls; 66 #endif /* !NOSSL */ 67 68 #include "ftp_var.h" 69 #include "cmds.h" 70 71 static int url_get(const char *, const char *, const char *, int); 72 static int save_chunked(FILE *, struct tls *, int , char *, size_t); 73 static void aborthttp(int); 74 static void abortfile(int); 75 static char hextochar(const char *); 76 static char *urldecode(const char *); 77 static char *recode_credentials(const char *_userinfo); 78 static char *ftp_readline(FILE *, size_t *); 79 static void ftp_close(FILE **, struct tls **, volatile int *); 80 static const char *sockerror(struct tls *); 81 #ifdef SMALL 82 #define ftp_printf(fp, ...) fprintf(fp, __VA_ARGS__) 83 #else 84 static int ftp_printf(FILE *, const char *, ...); 85 #endif /* SMALL */ 86 #ifndef NOSSL 87 static int proxy_connect(int, char *, char *); 88 static int stdio_tls_write_wrapper(void *, const char *, int); 89 static int stdio_tls_read_wrapper(void *, char *, int); 90 #endif /* !NOSSL */ 91 92 #define FTP_URL "ftp://" /* ftp URL prefix */ 93 #define HTTP_URL "http://" /* http URL prefix */ 94 #define HTTPS_URL "https://" /* https URL prefix */ 95 #define FILE_URL "file:" /* file URL prefix */ 96 #define FTP_PROXY "ftp_proxy" /* env var with ftp proxy location */ 97 #define HTTP_PROXY "http_proxy" /* env var with http proxy location */ 98 99 #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0')) 100 101 static const char at_encoding_warning[] = 102 "Extra `@' characters in usernames and passwords should be encoded as %%40"; 103 104 static jmp_buf httpabort; 105 106 static int redirect_loop; 107 static int retried; 108 109 /* 110 * Determine whether the character needs encoding, per RFC1738: 111 * - No corresponding graphic US-ASCII. 112 * - Unsafe characters. 113 */ 114 static int 115 unsafe_char(const char *c0) 116 { 117 const char *unsafe_chars = " <>\"#{}|\\^~[]`"; 118 const unsigned char *c = (const unsigned char *)c0; 119 120 /* 121 * No corresponding graphic US-ASCII. 122 * Control characters and octets not used in US-ASCII. 123 */ 124 return (iscntrl(*c) || !isascii(*c) || 125 126 /* 127 * Unsafe characters. 128 * '%' is also unsafe, if is not followed by two 129 * hexadecimal digits. 130 */ 131 strchr(unsafe_chars, *c) != NULL || 132 (*c == '%' && (!isxdigit(*++c) || !isxdigit(*++c)))); 133 } 134 135 /* 136 * Encode given URL, per RFC1738. 137 * Allocate and return string to the caller. 138 */ 139 static char * 140 url_encode(const char *path) 141 { 142 size_t i, length, new_length; 143 char *epath, *epathp; 144 145 length = new_length = strlen(path); 146 147 /* 148 * First pass: 149 * Count unsafe characters, and determine length of the 150 * final URL. 151 */ 152 for (i = 0; i < length; i++) 153 if (unsafe_char(path + i)) 154 new_length += 2; 155 156 epath = epathp = malloc(new_length + 1); /* One more for '\0'. */ 157 if (epath == NULL) 158 err(1, "Can't allocate memory for URL encoding"); 159 160 /* 161 * Second pass: 162 * Encode, and copy final URL. 163 */ 164 for (i = 0; i < length; i++) 165 if (unsafe_char(path + i)) { 166 snprintf(epathp, 4, "%%" "%02x", 167 (unsigned char)path[i]); 168 epathp += 3; 169 } else 170 *(epathp++) = path[i]; 171 172 *epathp = '\0'; 173 return (epath); 174 } 175 176 /* ARGSUSED */ 177 static void 178 tooslow(int signo) 179 { 180 dprintf(STDERR_FILENO, "%s: connect taking too long\n", __progname); 181 _exit(2); 182 } 183 184 /* 185 * Retrieve URL, via the proxy in $proxyvar if necessary. 186 * Returns -1 on failure, 0 on success 187 */ 188 static int 189 url_get(const char *origline, const char *proxyenv, const char *outfile, int lastfile) 190 { 191 char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4]; 192 char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL; 193 char *epath, *redirurl, *loctail, *h, *p, gerror[200]; 194 int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1; 195 int isunavail = 0, retryafter = -1; 196 struct addrinfo hints, *res0, *res; 197 const char * volatile savefile; 198 char * volatile proxyurl = NULL; 199 char *credentials = NULL; 200 volatile int fd = -1, out = -1; 201 volatile sig_t oldintr, oldinti; 202 FILE *fin = NULL; 203 off_t hashbytes; 204 const char *errstr; 205 ssize_t len, wlen; 206 char *proxyhost = NULL; 207 #ifndef NOSSL 208 char *sslpath = NULL, *sslhost = NULL; 209 int ishttpurl = 0, ishttpsurl = 0; 210 #endif /* !NOSSL */ 211 #ifndef SMALL 212 char *full_host = NULL; 213 const char *scheme; 214 char *locbase; 215 struct addrinfo *ares = NULL; 216 #endif /* !SMALL */ 217 struct tls *tls = NULL; 218 int status; 219 int save_errno; 220 const size_t buflen = 128 * 1024; 221 int chunked = 0; 222 223 direction = "received"; 224 225 newline = strdup(origline); 226 if (newline == NULL) 227 errx(1, "Can't allocate memory to parse URL"); 228 if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) { 229 host = newline + sizeof(HTTP_URL) - 1; 230 #ifndef NOSSL 231 ishttpurl = 1; 232 #endif /* !NOSSL */ 233 #ifndef SMALL 234 scheme = HTTP_URL; 235 #endif /* !SMALL */ 236 } else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) { 237 host = newline + sizeof(FTP_URL) - 1; 238 isftpurl = 1; 239 #ifndef SMALL 240 scheme = FTP_URL; 241 #endif /* !SMALL */ 242 } else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) { 243 host = newline + sizeof(FILE_URL) - 1; 244 isfileurl = 1; 245 #ifndef SMALL 246 scheme = FILE_URL; 247 #endif /* !SMALL */ 248 } else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) { 249 #ifndef NOSSL 250 host = newline + sizeof(HTTPS_URL) - 1; 251 ishttpsurl = 1; 252 #else 253 errx(1, "%s: No HTTPS support", newline); 254 #endif /* !NOSSL */ 255 #ifndef SMALL 256 scheme = HTTPS_URL; 257 #endif /* !SMALL */ 258 } else 259 errx(1, "url_get: Invalid URL '%s'", newline); 260 261 if (isfileurl && redirect_loop > 0) 262 errx(1, "Redirection to local file not permitted"); 263 264 if (isfileurl) { 265 path = host; 266 } else { 267 path = strchr(host, '/'); /* Find path */ 268 if (EMPTYSTRING(path)) { 269 if (outfile) { /* No slash, but */ 270 path=strchr(host,'\0'); /* we have outfile. */ 271 goto noslash; 272 } 273 if (isftpurl) 274 goto noftpautologin; 275 warnx("No `/' after host (use -o): %s", origline); 276 goto cleanup_url_get; 277 } 278 *path++ = '\0'; 279 if (EMPTYSTRING(path) && !outfile) { 280 if (isftpurl) 281 goto noftpautologin; 282 warnx("No filename after host (use -o): %s", origline); 283 goto cleanup_url_get; 284 } 285 } 286 287 noslash: 288 289 #ifndef NOSSL 290 /* 291 * Look for auth header in host, since now host does not 292 * contain the path. Basic auth from RFC 2617, valid 293 * characters for path are in RFC 3986 section 3.3. 294 */ 295 if (proxyenv == NULL && (ishttpurl || ishttpsurl)) { 296 if ((p = strchr(host, '@')) != NULL) { 297 *p = '\0'; 298 credentials = recode_credentials(host); 299 host = p + 1; 300 } 301 } 302 #endif /* NOSSL */ 303 304 if (outfile) 305 savefile = outfile; 306 else { 307 if (path[strlen(path) - 1] == '/') /* Consider no file */ 308 savefile = NULL; /* after dir invalid. */ 309 else 310 savefile = basename(path); 311 } 312 313 if (EMPTYSTRING(savefile)) { 314 if (isftpurl) 315 goto noftpautologin; 316 warnx("No filename after directory (use -o): %s", origline); 317 goto cleanup_url_get; 318 } 319 320 #ifndef SMALL 321 if (resume && pipeout) { 322 warnx("can't append to stdout"); 323 goto cleanup_url_get; 324 } 325 #endif /* !SMALL */ 326 327 if (!isfileurl && proxyenv != NULL) { /* use proxy */ 328 #ifndef NOSSL 329 if (ishttpsurl) { 330 sslpath = strdup(path); 331 sslhost = strdup(host); 332 if (! sslpath || ! sslhost) 333 errx(1, "Can't allocate memory for https path/host."); 334 } 335 #endif /* !NOSSL */ 336 proxyhost = strdup(host); 337 if (proxyhost == NULL) 338 errx(1, "Can't allocate memory for proxy host."); 339 proxyurl = strdup(proxyenv); 340 if (proxyurl == NULL) 341 errx(1, "Can't allocate memory for proxy URL."); 342 if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) 343 host = proxyurl + sizeof(HTTP_URL) - 1; 344 else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0) 345 host = proxyurl + sizeof(FTP_URL) - 1; 346 else { 347 warnx("Malformed proxy URL: %s", proxyenv); 348 goto cleanup_url_get; 349 } 350 if (EMPTYSTRING(host)) { 351 warnx("Malformed proxy URL: %s", proxyenv); 352 goto cleanup_url_get; 353 } 354 if (*--path == '\0') 355 *path = '/'; /* add / back to real path */ 356 path = strchr(host, '/'); /* remove trailing / on host */ 357 if (!EMPTYSTRING(path)) 358 *path++ = '\0'; /* i guess this ++ is useless */ 359 360 path = strchr(host, '@'); /* look for credentials in proxy */ 361 if (!EMPTYSTRING(path)) { 362 *path = '\0'; 363 if (strchr(host, ':') == NULL) { 364 warnx("Malformed proxy URL: %s", proxyenv); 365 goto cleanup_url_get; 366 } 367 credentials = recode_credentials(host); 368 *path = '@'; /* restore @ in proxyurl */ 369 370 /* 371 * This removes the password from proxyurl, 372 * filling with stars 373 */ 374 for (host = 1 + strchr(proxyurl + 5, ':'); *host != '@'; 375 host++) 376 *host = '*'; 377 378 host = path + 1; 379 } 380 381 path = newline; 382 } 383 384 if (isfileurl) { 385 struct stat st; 386 387 fd = open(path, O_RDONLY); 388 if (fd == -1) { 389 warn("Can't open file %s", path); 390 goto cleanup_url_get; 391 } 392 393 if (fstat(fd, &st) == -1) 394 filesize = -1; 395 else 396 filesize = st.st_size; 397 398 /* Open the output file. */ 399 if (!pipeout) { 400 #ifndef SMALL 401 if (resume) 402 out = open(savefile, O_CREAT | O_WRONLY | 403 O_APPEND, 0666); 404 405 else 406 #endif /* !SMALL */ 407 out = open(savefile, O_CREAT | O_WRONLY | 408 O_TRUNC, 0666); 409 if (out < 0) { 410 warn("Can't open %s", savefile); 411 goto cleanup_url_get; 412 } 413 } else 414 out = fileno(stdout); 415 416 #ifndef SMALL 417 if (resume) { 418 if (fstat(out, &st) == -1) { 419 warn("Can't fstat %s", savefile); 420 goto cleanup_url_get; 421 } 422 if (lseek(fd, st.st_size, SEEK_SET) == -1) { 423 warn("Can't lseek %s", path); 424 goto cleanup_url_get; 425 } 426 restart_point = st.st_size; 427 } 428 #endif /* !SMALL */ 429 430 /* Trap signals */ 431 oldintr = NULL; 432 oldinti = NULL; 433 if (setjmp(httpabort)) { 434 if (oldintr) 435 (void)signal(SIGINT, oldintr); 436 if (oldinti) 437 (void)signal(SIGINFO, oldinti); 438 goto cleanup_url_get; 439 } 440 oldintr = signal(SIGINT, abortfile); 441 442 bytes = 0; 443 hashbytes = mark; 444 progressmeter(-1, path); 445 446 if ((buf = malloc(buflen)) == NULL) 447 errx(1, "Can't allocate memory for transfer buffer"); 448 449 /* Finally, suck down the file. */ 450 i = 0; 451 oldinti = signal(SIGINFO, psummary); 452 while ((len = read(fd, buf, buflen)) > 0) { 453 bytes += len; 454 for (cp = buf; len > 0; len -= i, cp += i) { 455 if ((i = write(out, cp, len)) == -1) { 456 warn("Writing %s", savefile); 457 signal(SIGINFO, oldinti); 458 goto cleanup_url_get; 459 } else if (i == 0) 460 break; 461 } 462 if (hash && !progress) { 463 while (bytes >= hashbytes) { 464 (void)putc('#', ttyout); 465 hashbytes += mark; 466 } 467 (void)fflush(ttyout); 468 } 469 } 470 signal(SIGINFO, oldinti); 471 if (hash && !progress && bytes > 0) { 472 if (bytes < mark) 473 (void)putc('#', ttyout); 474 (void)putc('\n', ttyout); 475 (void)fflush(ttyout); 476 } 477 if (len != 0) { 478 warn("Reading from file"); 479 goto cleanup_url_get; 480 } 481 progressmeter(1, NULL); 482 if (verbose) 483 ptransfer(0); 484 (void)signal(SIGINT, oldintr); 485 486 rval = 0; 487 goto cleanup_url_get; 488 } 489 490 if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL && 491 (hosttail[1] == '\0' || hosttail[1] == ':')) { 492 host++; 493 *hosttail++ = '\0'; 494 #ifndef SMALL 495 if (asprintf(&full_host, "[%s]", host) == -1) 496 errx(1, "Cannot allocate memory for hostname"); 497 #endif /* !SMALL */ 498 } else 499 hosttail = host; 500 501 portnum = strrchr(hosttail, ':'); /* find portnum */ 502 if (portnum != NULL) 503 *portnum++ = '\0'; 504 #ifndef NOSSL 505 port = portnum ? portnum : (ishttpsurl ? httpsport : httpport); 506 #else /* !NOSSL */ 507 port = portnum ? portnum : httpport; 508 #endif /* !NOSSL */ 509 510 #ifndef SMALL 511 if (full_host == NULL) 512 if ((full_host = strdup(host)) == NULL) 513 errx(1, "Cannot allocate memory for hostname"); 514 if (debug) 515 fprintf(ttyout, "host %s, port %s, path %s, " 516 "save as %s, auth %s.\n", host, port, path, 517 savefile, credentials ? credentials : "none"); 518 #endif /* !SMALL */ 519 520 memset(&hints, 0, sizeof(hints)); 521 hints.ai_family = family; 522 hints.ai_socktype = SOCK_STREAM; 523 error = getaddrinfo(host, port, &hints, &res0); 524 /* 525 * If the services file is corrupt/missing, fall back 526 * on our hard-coded defines. 527 */ 528 if (error == EAI_SERVICE && port == httpport) { 529 snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT); 530 error = getaddrinfo(host, pbuf, &hints, &res0); 531 #ifndef NOSSL 532 } else if (error == EAI_SERVICE && port == httpsport) { 533 snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT); 534 error = getaddrinfo(host, pbuf, &hints, &res0); 535 #endif /* !NOSSL */ 536 } 537 if (error) { 538 warnx("%s: %s", host, gai_strerror(error)); 539 goto cleanup_url_get; 540 } 541 542 #ifndef SMALL 543 if (srcaddr) { 544 hints.ai_flags |= AI_NUMERICHOST; 545 error = getaddrinfo(srcaddr, NULL, &hints, &ares); 546 if (error) { 547 warnx("%s: %s", srcaddr, gai_strerror(error)); 548 goto cleanup_url_get; 549 } 550 } 551 #endif /* !SMALL */ 552 553 /* ensure consistent order of the output */ 554 if (verbose) 555 setvbuf(ttyout, NULL, _IOLBF, 0); 556 557 fd = -1; 558 for (res = res0; res; res = res->ai_next) { 559 if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, 560 sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0) 561 strlcpy(hbuf, "(unknown)", sizeof(hbuf)); 562 if (verbose) 563 fprintf(ttyout, "Trying %s...\n", hbuf); 564 565 fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); 566 if (fd == -1) { 567 cause = "socket"; 568 continue; 569 } 570 571 #ifndef SMALL 572 if (srcaddr) { 573 if (ares->ai_family != res->ai_family) { 574 close(fd); 575 fd = -1; 576 errno = EINVAL; 577 cause = "bind"; 578 continue; 579 } 580 if (bind(fd, ares->ai_addr, ares->ai_addrlen) == -1) { 581 save_errno = errno; 582 close(fd); 583 errno = save_errno; 584 fd = -1; 585 cause = "bind"; 586 continue; 587 } 588 } 589 #endif /* !SMALL */ 590 591 if (connect_timeout) { 592 (void)signal(SIGALRM, tooslow); 593 alarmtimer(connect_timeout); 594 } 595 596 for (error = connect(fd, res->ai_addr, res->ai_addrlen); 597 error != 0 && errno == EINTR; error = connect_wait(fd)) 598 continue; 599 if (error != 0) { 600 save_errno = errno; 601 close(fd); 602 errno = save_errno; 603 fd = -1; 604 cause = "connect"; 605 continue; 606 } 607 608 /* get port in numeric */ 609 if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0, 610 pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0) 611 port = pbuf; 612 else 613 port = NULL; 614 615 #ifndef NOSSL 616 if (proxyenv && sslhost) 617 proxy_connect(fd, sslhost, credentials); 618 #endif /* !NOSSL */ 619 break; 620 } 621 freeaddrinfo(res0); 622 #ifndef SMALL 623 if (srcaddr) 624 freeaddrinfo(ares); 625 #endif /* !SMALL */ 626 if (fd < 0) { 627 warn("%s", cause); 628 goto cleanup_url_get; 629 } 630 631 #ifndef NOSSL 632 if (ishttpsurl) { 633 if (proxyenv && sslpath) { 634 ishttpsurl = 0; 635 proxyurl = NULL; 636 path = sslpath; 637 } 638 if (sslhost == NULL) { 639 sslhost = strdup(host); 640 if (sslhost == NULL) 641 errx(1, "Can't allocate memory for https host."); 642 } 643 if ((tls = tls_client()) == NULL) { 644 fprintf(ttyout, "failed to create SSL client\n"); 645 goto cleanup_url_get; 646 } 647 if (tls_configure(tls, tls_config) != 0) { 648 fprintf(ttyout, "SSL configuration failure: %s\n", 649 tls_error(tls)); 650 goto cleanup_url_get; 651 } 652 if (tls_connect_socket(tls, fd, sslhost) != 0) { 653 fprintf(ttyout, "SSL failure: %s\n", tls_error(tls)); 654 goto cleanup_url_get; 655 } 656 if (tls_handshake(tls) != 0) { 657 fprintf(ttyout, "SSL failure: %s\n", tls_error(tls)); 658 goto cleanup_url_get; 659 } 660 fin = funopen(tls, stdio_tls_read_wrapper, 661 stdio_tls_write_wrapper, NULL, NULL); 662 } else { 663 fin = fdopen(fd, "r+"); 664 fd = -1; 665 } 666 #else /* !NOSSL */ 667 fin = fdopen(fd, "r+"); 668 fd = -1; 669 #endif /* !NOSSL */ 670 671 #ifdef SMALL 672 if (lastfile) { 673 if (pipeout) { 674 if (pledge("stdio rpath inet dns tty", NULL) == -1) 675 err(1, "pledge"); 676 } else { 677 if (pledge("stdio rpath wpath cpath inet dns tty", NULL) == -1) 678 err(1, "pledge"); 679 } 680 } 681 #endif 682 683 if (connect_timeout) { 684 signal(SIGALRM, SIG_DFL); 685 alarmtimer(0); 686 } 687 688 /* 689 * Construct and send the request. Proxy requests don't want leading /. 690 */ 691 #ifndef NOSSL 692 cookie_get(host, path, ishttpsurl, &buf); 693 #endif /* !NOSSL */ 694 695 epath = url_encode(path); 696 if (proxyurl) { 697 if (verbose) { 698 fprintf(ttyout, "Requesting %s (via %s)\n", 699 origline, proxyurl); 700 } 701 /* 702 * Host: directive must use the destination host address for 703 * the original URI (path). 704 */ 705 if (credentials) 706 ftp_printf(fin, "GET %s HTTP/1.1\r\n" 707 "Connection: close\r\n" 708 "Proxy-Authorization: Basic %s\r\n" 709 "Host: %s\r\n%s%s\r\n\r\n", 710 epath, credentials, 711 proxyhost, buf ? buf : "", httpuseragent); 712 else 713 ftp_printf(fin, "GET %s HTTP/1.1\r\n" 714 "Connection: close\r\n" 715 "Host: %s\r\n%s%s\r\n\r\n", 716 epath, proxyhost, buf ? buf : "", httpuseragent); 717 } else { 718 if (verbose) 719 fprintf(ttyout, "Requesting %s\n", origline); 720 #ifndef SMALL 721 if (resume) { 722 struct stat stbuf; 723 724 if (stat(savefile, &stbuf) == 0) 725 restart_point = stbuf.st_size; 726 else 727 restart_point = 0; 728 } 729 #endif /* SMALL */ 730 #ifndef NOSSL 731 if (credentials) { 732 ftp_printf(fin, 733 "GET /%s HTTP/1.1\r\n" 734 "Connection: close\r\n" 735 "Authorization: Basic %s\r\n" 736 "Host: ", epath, credentials); 737 free(credentials); 738 credentials = NULL; 739 } else 740 #endif /* NOSSL */ 741 ftp_printf(fin, 742 "GET /%s HTTP/1.1\r\n" 743 "Connection: close\r\n" 744 "Host: ", epath); 745 if (proxyhost) { 746 ftp_printf(fin, "%s", proxyhost); 747 port = NULL; 748 } else if (strchr(host, ':')) { 749 /* 750 * strip off scoped address portion, since it's 751 * local to node 752 */ 753 h = strdup(host); 754 if (h == NULL) 755 errx(1, "Can't allocate memory."); 756 if ((p = strchr(h, '%')) != NULL) 757 *p = '\0'; 758 ftp_printf(fin, "[%s]", h); 759 free(h); 760 } else 761 ftp_printf(fin, "%s", host); 762 763 /* 764 * Send port number only if it's specified and does not equal 765 * 80. Some broken HTTP servers get confused if you explicitly 766 * send them the port number. 767 */ 768 #ifndef NOSSL 769 if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0) 770 ftp_printf(fin, ":%s", port); 771 if (restart_point) 772 ftp_printf(fin, "\r\nRange: bytes=%lld-", 773 (long long)restart_point); 774 #else /* !NOSSL */ 775 if (port && strcmp(port, "80") != 0) 776 ftp_printf(fin, ":%s", port); 777 #endif /* !NOSSL */ 778 ftp_printf(fin, "\r\n%s%s\r\n\r\n", 779 buf ? buf : "", httpuseragent); 780 } 781 free(epath); 782 783 #ifndef NOSSL 784 free(buf); 785 #endif /* !NOSSL */ 786 buf = NULL; 787 788 if (fflush(fin) == EOF) { 789 warnx("Writing HTTP request: %s", sockerror(tls)); 790 goto cleanup_url_get; 791 } 792 if ((buf = ftp_readline(fin, &len)) == NULL) { 793 warnx("Receiving HTTP reply: %s", sockerror(tls)); 794 goto cleanup_url_get; 795 } 796 797 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) 798 buf[--len] = '\0'; 799 #ifndef SMALL 800 if (debug) 801 fprintf(ttyout, "received '%s'\n", buf); 802 #endif /* !SMALL */ 803 804 cp = strchr(buf, ' '); 805 if (cp == NULL) 806 goto improper; 807 else 808 cp++; 809 810 strlcpy(ststr, cp, sizeof(ststr)); 811 status = strtonum(ststr, 200, 503, &errstr); 812 if (errstr) { 813 strnvis(gerror, cp, sizeof gerror, VIS_SAFE); 814 warnx("Error retrieving %s: %s", origline, gerror); 815 goto cleanup_url_get; 816 } 817 818 switch (status) { 819 case 200: /* OK */ 820 #ifndef SMALL 821 /* 822 * When we request a partial file, and we receive an HTTP 200 823 * it is a good indication that the server doesn't support 824 * range requests, and is about to send us the entire file. 825 * If the restart_point == 0, then we are not actually 826 * requesting a partial file, and an HTTP 200 is appropriate. 827 */ 828 if (resume && restart_point != 0) { 829 warnx("Server does not support resume."); 830 restart_point = resume = 0; 831 } 832 /* FALLTHROUGH */ 833 case 206: /* Partial Content */ 834 #endif /* !SMALL */ 835 break; 836 case 301: /* Moved Permanently */ 837 case 302: /* Found */ 838 case 303: /* See Other */ 839 case 307: /* Temporary Redirect */ 840 isredirect++; 841 if (redirect_loop++ > 10) { 842 warnx("Too many redirections requested"); 843 goto cleanup_url_get; 844 } 845 break; 846 #ifndef SMALL 847 case 416: /* Requested Range Not Satisfiable */ 848 warnx("File is already fully retrieved."); 849 goto cleanup_url_get; 850 #endif /* !SMALL */ 851 case 503: 852 isunavail = 1; 853 break; 854 default: 855 strnvis(gerror, cp, sizeof gerror, VIS_SAFE); 856 warnx("Error retrieving %s: %s", origline, gerror); 857 goto cleanup_url_get; 858 } 859 860 /* 861 * Read the rest of the header. 862 */ 863 free(buf); 864 filesize = -1; 865 866 for (;;) { 867 if ((buf = ftp_readline(fin, &len)) == NULL) { 868 warnx("Receiving HTTP reply: %s", sockerror(tls)); 869 goto cleanup_url_get; 870 } 871 872 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) 873 buf[--len] = '\0'; 874 if (len == 0) 875 break; 876 #ifndef SMALL 877 if (debug) 878 fprintf(ttyout, "received '%s'\n", buf); 879 #endif /* !SMALL */ 880 881 /* Look for some headers */ 882 cp = buf; 883 #define CONTENTLEN "Content-Length: " 884 if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) { 885 size_t s; 886 cp += sizeof(CONTENTLEN) - 1; 887 if ((s = strcspn(cp, " \t"))) 888 *(cp+s) = 0; 889 filesize = strtonum(cp, 0, LLONG_MAX, &errstr); 890 if (errstr != NULL) 891 goto improper; 892 #ifndef SMALL 893 if (restart_point) 894 filesize += restart_point; 895 #endif /* !SMALL */ 896 #define LOCATION "Location: " 897 } else if (isredirect && 898 strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) { 899 cp += sizeof(LOCATION) - 1; 900 /* 901 * If there is a colon before the first slash, this URI 902 * is not relative. RFC 3986 4.2 903 */ 904 if (cp[strcspn(cp, ":/")] != ':') { 905 #ifdef SMALL 906 errx(1, "Relative redirect not supported"); 907 #else /* SMALL */ 908 /* XXX doesn't handle protocol-relative URIs */ 909 if (*cp == '/') { 910 locbase = NULL; 911 cp++; 912 } else { 913 locbase = strdup(path); 914 if (locbase == NULL) 915 errx(1, "Can't allocate memory" 916 " for location base"); 917 loctail = strchr(locbase, '#'); 918 if (loctail != NULL) 919 *loctail = '\0'; 920 loctail = strchr(locbase, '?'); 921 if (loctail != NULL) 922 *loctail = '\0'; 923 loctail = strrchr(locbase, '/'); 924 if (loctail == NULL) { 925 free(locbase); 926 locbase = NULL; 927 } else 928 loctail[1] = '\0'; 929 } 930 /* Contruct URL from relative redirect */ 931 if (asprintf(&redirurl, "%s%s%s%s/%s%s", 932 scheme, full_host, 933 portnum ? ":" : "", 934 portnum ? portnum : "", 935 locbase ? locbase : "", 936 cp) == -1) 937 errx(1, "Cannot build " 938 "redirect URL"); 939 free(locbase); 940 #endif /* SMALL */ 941 } else if ((redirurl = strdup(cp)) == NULL) 942 errx(1, "Cannot allocate memory for URL"); 943 loctail = strchr(redirurl, '#'); 944 if (loctail != NULL) 945 *loctail = '\0'; 946 if (verbose) 947 fprintf(ttyout, "Redirected to %s\n", redirurl); 948 ftp_close(&fin, &tls, &fd); 949 rval = url_get(redirurl, proxyenv, savefile, lastfile); 950 free(redirurl); 951 goto cleanup_url_get; 952 #define RETRYAFTER "Retry-After: " 953 } else if (isunavail && 954 strncasecmp(cp, RETRYAFTER, sizeof(RETRYAFTER) - 1) == 0) { 955 size_t s; 956 cp += sizeof(RETRYAFTER) - 1; 957 if ((s = strcspn(cp, " \t"))) 958 cp[s] = '\0'; 959 retryafter = strtonum(cp, 0, 0, &errstr); 960 if (errstr != NULL) 961 retryafter = -1; 962 #define TRANSFER_ENCODING "Transfer-Encoding: " 963 } else if (strncasecmp(cp, TRANSFER_ENCODING, 964 sizeof(TRANSFER_ENCODING) - 1) == 0) { 965 cp += sizeof(TRANSFER_ENCODING) - 1; 966 cp[strcspn(cp, " \t")] = '\0'; 967 if (strcasecmp(cp, "chunked") == 0) 968 chunked = 1; 969 } 970 free(buf); 971 } 972 973 /* Content-Length should be ignored for Transfer-Encoding: chunked */ 974 if (chunked) 975 filesize = -1; 976 977 if (isunavail) { 978 if (retried || retryafter != 0) 979 warnx("Error retrieving %s: 503 Service Unavailable", 980 origline); 981 else { 982 if (verbose) 983 fprintf(ttyout, "Retrying %s\n", origline); 984 retried = 1; 985 ftp_close(&fin, &tls, &fd); 986 rval = url_get(origline, proxyenv, savefile, lastfile); 987 } 988 goto cleanup_url_get; 989 } 990 991 /* Open the output file. */ 992 if (!pipeout) { 993 #ifndef SMALL 994 if (resume) 995 out = open(savefile, O_CREAT | O_WRONLY | O_APPEND, 996 0666); 997 else 998 #endif /* !SMALL */ 999 out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 1000 0666); 1001 if (out == -1) { 1002 warn("Can't open %s", savefile); 1003 goto cleanup_url_get; 1004 } 1005 } else { 1006 out = fileno(stdout); 1007 #ifdef SMALL 1008 if (lastfile) { 1009 if (pledge("stdio tty", NULL) == -1) 1010 err(1, "pledge"); 1011 } 1012 #endif 1013 } 1014 1015 /* Trap signals */ 1016 oldintr = NULL; 1017 oldinti = NULL; 1018 if (setjmp(httpabort)) { 1019 if (oldintr) 1020 (void)signal(SIGINT, oldintr); 1021 if (oldinti) 1022 (void)signal(SIGINFO, oldinti); 1023 goto cleanup_url_get; 1024 } 1025 oldintr = signal(SIGINT, aborthttp); 1026 1027 bytes = 0; 1028 hashbytes = mark; 1029 progressmeter(-1, path); 1030 1031 free(buf); 1032 1033 /* Finally, suck down the file. */ 1034 if ((buf = malloc(buflen)) == NULL) 1035 errx(1, "Can't allocate memory for transfer buffer"); 1036 oldinti = signal(SIGINFO, psummary); 1037 if (chunked) { 1038 error = save_chunked(fin, tls, out, buf, buflen); 1039 signal(SIGINFO, oldinti); 1040 if (error == -1) 1041 goto cleanup_url_get; 1042 } else { 1043 i = 0; 1044 len = 1; 1045 while (len > 0) { 1046 len = fread(buf, 1, buflen, fin); 1047 bytes += len; 1048 for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) { 1049 if ((i = write(out, cp, wlen)) == -1) { 1050 warn("Writing %s", savefile); 1051 signal(SIGINFO, oldinti); 1052 goto cleanup_url_get; 1053 } else if (i == 0) 1054 break; 1055 } 1056 if (hash && !progress) { 1057 while (bytes >= hashbytes) { 1058 (void)putc('#', ttyout); 1059 hashbytes += mark; 1060 } 1061 (void)fflush(ttyout); 1062 } 1063 } 1064 signal(SIGINFO, oldinti); 1065 if (hash && !progress && bytes > 0) { 1066 if (bytes < mark) 1067 (void)putc('#', ttyout); 1068 (void)putc('\n', ttyout); 1069 (void)fflush(ttyout); 1070 } 1071 if (len != 0) { 1072 warnx("Reading from socket: %s", sockerror(tls)); 1073 goto cleanup_url_get; 1074 } 1075 } 1076 progressmeter(1, NULL); 1077 if ( 1078 #ifndef SMALL 1079 !resume && 1080 #endif /* !SMALL */ 1081 filesize != -1 && len == 0 && bytes != filesize) { 1082 if (verbose) 1083 fputs("Read short file.\n", ttyout); 1084 goto cleanup_url_get; 1085 } 1086 1087 if (verbose) 1088 ptransfer(0); 1089 (void)signal(SIGINT, oldintr); 1090 1091 rval = 0; 1092 goto cleanup_url_get; 1093 1094 noftpautologin: 1095 warnx( 1096 "Auto-login using ftp URLs isn't supported when using $ftp_proxy"); 1097 goto cleanup_url_get; 1098 1099 improper: 1100 warnx("Improper response from %s", host); 1101 1102 cleanup_url_get: 1103 #ifndef SMALL 1104 free(full_host); 1105 #endif /* !SMALL */ 1106 #ifndef NOSSL 1107 free(sslhost); 1108 #endif /* !NOSSL */ 1109 ftp_close(&fin, &tls, &fd); 1110 if (out >= 0 && out != fileno(stdout)) 1111 close(out); 1112 free(buf); 1113 free(proxyhost); 1114 free(proxyurl); 1115 free(newline); 1116 free(credentials); 1117 return (rval); 1118 } 1119 1120 static int 1121 save_chunked(FILE *fin, struct tls *tls, int out, char *buf, size_t buflen) 1122 { 1123 1124 char *header, *end, *cp; 1125 unsigned long chunksize; 1126 size_t hlen, rlen, wlen; 1127 ssize_t written; 1128 char cr, lf; 1129 1130 for (;;) { 1131 header = ftp_readline(fin, &hlen); 1132 if (header == NULL) 1133 break; 1134 /* strip CRLF and any optional chunk extension */ 1135 header[strcspn(header, ";\r\n")] = '\0'; 1136 errno = 0; 1137 chunksize = strtoul(header, &end, 16); 1138 if (errno || header[0] == '\0' || *end != '\0' || 1139 chunksize > INT_MAX) { 1140 warnx("Invalid chunk size '%s'", header); 1141 free(header); 1142 return -1; 1143 } 1144 free(header); 1145 1146 if (chunksize == 0) { 1147 /* We're done. Ignore optional trailer. */ 1148 return 0; 1149 } 1150 1151 for (written = 0; chunksize != 0; chunksize -= rlen) { 1152 rlen = (chunksize < buflen) ? chunksize : buflen; 1153 rlen = fread(buf, 1, rlen, fin); 1154 if (rlen == 0) 1155 break; 1156 bytes += rlen; 1157 for (cp = buf, wlen = rlen; wlen > 0; 1158 wlen -= written, cp += written) { 1159 if ((written = write(out, cp, wlen)) == -1) { 1160 warn("Writing output file"); 1161 return -1; 1162 } 1163 } 1164 } 1165 1166 if (rlen == 0 || 1167 fread(&cr, 1, 1, fin) != 1 || 1168 fread(&lf, 1, 1, fin) != 1) 1169 break; 1170 1171 if (cr != '\r' || lf != '\n') { 1172 warnx("Invalid chunked encoding"); 1173 return -1; 1174 } 1175 } 1176 1177 if (ferror(fin)) 1178 warnx("Error while reading from socket: %s", sockerror(tls)); 1179 else 1180 warnx("Invalid chunked encoding: short read"); 1181 1182 return -1; 1183 } 1184 1185 /* 1186 * Abort a http retrieval 1187 */ 1188 /* ARGSUSED */ 1189 static void 1190 aborthttp(int signo) 1191 { 1192 1193 alarmtimer(0); 1194 fputs("\nhttp fetch aborted.\n", ttyout); 1195 (void)fflush(ttyout); 1196 longjmp(httpabort, 1); 1197 } 1198 1199 /* 1200 * Abort a http retrieval 1201 */ 1202 /* ARGSUSED */ 1203 static void 1204 abortfile(int signo) 1205 { 1206 1207 alarmtimer(0); 1208 fputs("\nfile fetch aborted.\n", ttyout); 1209 (void)fflush(ttyout); 1210 longjmp(httpabort, 1); 1211 } 1212 1213 /* 1214 * Retrieve multiple files from the command line, transferring 1215 * files of the form "host:path", "ftp://host/path" using the 1216 * ftp protocol, and files of the form "http://host/path" using 1217 * the http protocol. 1218 * If path has a trailing "/", then return (-1); 1219 * the path will be cd-ed into and the connection remains open, 1220 * and the function will return -1 (to indicate the connection 1221 * is alive). 1222 * If an error occurs the return value will be the offset+1 in 1223 * argv[] of the file that caused a problem (i.e, argv[x] 1224 * returns x+1) 1225 * Otherwise, 0 is returned if all files retrieved successfully. 1226 */ 1227 int 1228 auto_fetch(int argc, char *argv[], char *outfile) 1229 { 1230 char *xargv[5]; 1231 char *cp, *url, *host, *dir, *file, *portnum; 1232 char *username, *pass, *pathstart; 1233 char *ftpproxy, *httpproxy; 1234 int rval, xargc, lastfile; 1235 volatile int argpos; 1236 int dirhasglob, filehasglob, oautologin; 1237 char rempath[PATH_MAX]; 1238 1239 argpos = 0; 1240 1241 if (setjmp(toplevel)) { 1242 if (connected) 1243 disconnect(0, NULL); 1244 return (argpos + 1); 1245 } 1246 (void)signal(SIGINT, (sig_t)intr); 1247 (void)signal(SIGPIPE, (sig_t)lostpeer); 1248 1249 if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0') 1250 ftpproxy = NULL; 1251 if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0') 1252 httpproxy = NULL; 1253 1254 /* 1255 * Loop through as long as there's files to fetch. 1256 */ 1257 username = pass = NULL; 1258 for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) { 1259 if (strchr(argv[argpos], ':') == NULL) 1260 break; 1261 1262 free(username); 1263 free(pass); 1264 host = dir = file = portnum = username = pass = NULL; 1265 1266 lastfile = (argv[argpos+1] == NULL); 1267 1268 /* 1269 * We muck with the string, so we make a copy. 1270 */ 1271 url = strdup(argv[argpos]); 1272 if (url == NULL) 1273 errx(1, "Can't allocate memory for auto-fetch."); 1274 1275 /* 1276 * Try HTTP URL-style arguments first. 1277 */ 1278 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 || 1279 strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0 || 1280 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) { 1281 redirect_loop = 0; 1282 retried = 0; 1283 if (url_get(url, httpproxy, outfile, lastfile) == -1) 1284 rval = argpos + 1; 1285 continue; 1286 } 1287 1288 /* 1289 * Try FTP URL-style arguments next. If ftpproxy is 1290 * set, use url_get() instead of standard ftp. 1291 * Finally, try host:file. 1292 */ 1293 host = url; 1294 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) { 1295 char *passend, *passagain, *userend; 1296 1297 if (ftpproxy) { 1298 if (url_get(url, ftpproxy, outfile, lastfile) == -1) 1299 rval = argpos + 1; 1300 continue; 1301 } 1302 host += sizeof(FTP_URL) - 1; 1303 dir = strchr(host, '/'); 1304 1305 /* Look for [user:pass@]host[:port] */ 1306 1307 /* check if we have "user:pass@" */ 1308 userend = strchr(host, ':'); 1309 passend = strchr(host, '@'); 1310 if (passend && userend && userend < passend && 1311 (!dir || passend < dir)) { 1312 username = host; 1313 pass = userend + 1; 1314 host = passend + 1; 1315 *userend = *passend = '\0'; 1316 passagain = strchr(host, '@'); 1317 if (strchr(pass, '@') != NULL || 1318 (passagain != NULL && passagain < dir)) { 1319 warnx(at_encoding_warning); 1320 username = pass = NULL; 1321 goto bad_ftp_url; 1322 } 1323 1324 if (EMPTYSTRING(username)) { 1325 bad_ftp_url: 1326 warnx("Invalid URL: %s", argv[argpos]); 1327 rval = argpos + 1; 1328 username = pass = NULL; 1329 continue; 1330 } 1331 username = urldecode(username); 1332 pass = urldecode(pass); 1333 } 1334 1335 /* check [host]:port, or [host] */ 1336 if (host[0] == '[') { 1337 cp = strchr(host, ']'); 1338 if (cp && (!dir || cp < dir)) { 1339 if (cp + 1 == dir || cp[1] == ':') { 1340 host++; 1341 *cp++ = '\0'; 1342 } else 1343 cp = NULL; 1344 } else 1345 cp = host; 1346 } else 1347 cp = host; 1348 1349 /* split off host[:port] if there is */ 1350 if (cp) { 1351 portnum = strchr(cp, ':'); 1352 pathstart = strchr(cp, '/'); 1353 /* : in path is not a port # indicator */ 1354 if (portnum && pathstart && 1355 pathstart < portnum) 1356 portnum = NULL; 1357 1358 if (!portnum) 1359 ; 1360 else { 1361 if (!dir) 1362 ; 1363 else if (portnum + 1 < dir) { 1364 *portnum++ = '\0'; 1365 /* 1366 * XXX should check if portnum 1367 * is decimal number 1368 */ 1369 } else { 1370 /* empty portnum */ 1371 goto bad_ftp_url; 1372 } 1373 } 1374 } else 1375 portnum = NULL; 1376 } else { /* classic style `host:file' */ 1377 dir = strchr(host, ':'); 1378 } 1379 if (EMPTYSTRING(host)) { 1380 rval = argpos + 1; 1381 continue; 1382 } 1383 1384 /* 1385 * If dir is NULL, the file wasn't specified 1386 * (URL looked something like ftp://host) 1387 */ 1388 if (dir != NULL) 1389 *dir++ = '\0'; 1390 1391 /* 1392 * Extract the file and (if present) directory name. 1393 */ 1394 if (!EMPTYSTRING(dir)) { 1395 cp = strrchr(dir, '/'); 1396 if (cp != NULL) { 1397 *cp++ = '\0'; 1398 file = cp; 1399 } else { 1400 file = dir; 1401 dir = NULL; 1402 } 1403 } 1404 #ifndef SMALL 1405 if (debug) 1406 fprintf(ttyout, 1407 "user %s:%s host %s port %s dir %s file %s\n", 1408 username, pass ? "XXXX" : NULL, host, portnum, 1409 dir, file); 1410 #endif /* !SMALL */ 1411 1412 /* 1413 * Set up the connection. 1414 */ 1415 if (connected) 1416 disconnect(0, NULL); 1417 xargv[0] = __progname; 1418 xargv[1] = host; 1419 xargv[2] = NULL; 1420 xargc = 2; 1421 if (!EMPTYSTRING(portnum)) { 1422 xargv[2] = portnum; 1423 xargv[3] = NULL; 1424 xargc = 3; 1425 } 1426 oautologin = autologin; 1427 if (username == NULL) 1428 anonftp = 1; 1429 else { 1430 anonftp = 0; 1431 autologin = 0; 1432 } 1433 setpeer(xargc, xargv); 1434 autologin = oautologin; 1435 if (connected == 0 || 1436 (connected == 1 && autologin && (username == NULL || 1437 !ftp_login(host, username, pass)))) { 1438 warnx("Can't connect or login to host `%s'", host); 1439 rval = argpos + 1; 1440 continue; 1441 } 1442 1443 /* Always use binary transfers. */ 1444 setbinary(0, NULL); 1445 1446 dirhasglob = filehasglob = 0; 1447 if (doglob) { 1448 if (!EMPTYSTRING(dir) && 1449 strpbrk(dir, "*?[]{}") != NULL) 1450 dirhasglob = 1; 1451 if (!EMPTYSTRING(file) && 1452 strpbrk(file, "*?[]{}") != NULL) 1453 filehasglob = 1; 1454 } 1455 1456 /* Change directories, if necessary. */ 1457 if (!EMPTYSTRING(dir) && !dirhasglob) { 1458 xargv[0] = "cd"; 1459 xargv[1] = dir; 1460 xargv[2] = NULL; 1461 cd(2, xargv); 1462 if (!dirchange) { 1463 rval = argpos + 1; 1464 continue; 1465 } 1466 } 1467 1468 if (EMPTYSTRING(file)) { 1469 #ifndef SMALL 1470 rval = -1; 1471 #else /* !SMALL */ 1472 recvrequest("NLST", "-", NULL, "w", 0, 0); 1473 rval = 0; 1474 #endif /* !SMALL */ 1475 continue; 1476 } 1477 1478 if (verbose) 1479 fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file); 1480 1481 if (dirhasglob) { 1482 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file); 1483 file = rempath; 1484 } 1485 1486 /* Fetch the file(s). */ 1487 xargc = 2; 1488 xargv[0] = "get"; 1489 xargv[1] = file; 1490 xargv[2] = NULL; 1491 if (dirhasglob || filehasglob) { 1492 int ointeractive; 1493 1494 ointeractive = interactive; 1495 interactive = 0; 1496 xargv[0] = "mget"; 1497 #ifndef SMALL 1498 if (resume) { 1499 xargc = 3; 1500 xargv[1] = "-c"; 1501 xargv[2] = file; 1502 xargv[3] = NULL; 1503 } 1504 #endif /* !SMALL */ 1505 mget(xargc, xargv); 1506 interactive = ointeractive; 1507 } else { 1508 if (outfile != NULL) { 1509 xargv[2] = outfile; 1510 xargv[3] = NULL; 1511 xargc++; 1512 } 1513 #ifndef SMALL 1514 if (resume) 1515 reget(xargc, xargv); 1516 else 1517 #endif /* !SMALL */ 1518 get(xargc, xargv); 1519 } 1520 1521 if ((code / 100) != COMPLETE) 1522 rval = argpos + 1; 1523 } 1524 if (connected && rval != -1) 1525 disconnect(0, NULL); 1526 return (rval); 1527 } 1528 1529 char * 1530 urldecode(const char *str) 1531 { 1532 char *ret, c; 1533 int i, reallen; 1534 1535 if (str == NULL) 1536 return NULL; 1537 if ((ret = malloc(strlen(str)+1)) == NULL) 1538 err(1, "Can't allocate memory for URL decoding"); 1539 for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) { 1540 c = str[i]; 1541 if (c == '+') { 1542 *ret = ' '; 1543 continue; 1544 } 1545 1546 /* Cannot use strtol here because next char 1547 * after %xx may be a digit. 1548 */ 1549 if (c == '%' && isxdigit((unsigned char)str[i+1]) && 1550 isxdigit((unsigned char)str[i+2])) { 1551 *ret = hextochar(&str[i+1]); 1552 i+=2; 1553 continue; 1554 } 1555 *ret = c; 1556 } 1557 *ret = '\0'; 1558 1559 return ret-reallen; 1560 } 1561 1562 static char * 1563 recode_credentials(const char *userinfo) 1564 { 1565 char *ui, *creds; 1566 size_t ulen, credsize; 1567 1568 /* url-decode the user and pass */ 1569 ui = urldecode(userinfo); 1570 1571 ulen = strlen(ui); 1572 credsize = (ulen + 2) / 3 * 4 + 1; 1573 creds = malloc(credsize); 1574 if (creds == NULL) 1575 errx(1, "out of memory"); 1576 if (b64_ntop(ui, ulen, creds, credsize) == -1) 1577 errx(1, "error in base64 encoding"); 1578 free(ui); 1579 return (creds); 1580 } 1581 1582 static char 1583 hextochar(const char *str) 1584 { 1585 unsigned char c, ret; 1586 1587 c = str[0]; 1588 ret = c; 1589 if (isalpha(c)) 1590 ret -= isupper(c) ? 'A' - 10 : 'a' - 10; 1591 else 1592 ret -= '0'; 1593 ret *= 16; 1594 1595 c = str[1]; 1596 ret += c; 1597 if (isalpha(c)) 1598 ret -= isupper(c) ? 'A' - 10 : 'a' - 10; 1599 else 1600 ret -= '0'; 1601 return ret; 1602 } 1603 1604 int 1605 isurl(const char *p) 1606 { 1607 1608 if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 || 1609 strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 || 1610 #ifndef NOSSL 1611 strncasecmp(p, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0 || 1612 #endif /* !NOSSL */ 1613 strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 || 1614 strstr(p, ":/")) 1615 return (1); 1616 return (0); 1617 } 1618 1619 static char * 1620 ftp_readline(FILE *fp, size_t *lenp) 1621 { 1622 return fparseln(fp, lenp, NULL, "\0\0\0", 0); 1623 } 1624 1625 #ifndef SMALL 1626 static int 1627 ftp_printf(FILE *fp, const char *fmt, ...) 1628 { 1629 va_list ap; 1630 int ret; 1631 1632 va_start(ap, fmt); 1633 ret = vfprintf(fp, fmt, ap); 1634 va_end(ap); 1635 1636 if (debug) { 1637 va_start(ap, fmt); 1638 vfprintf(ttyout, fmt, ap); 1639 va_end(ap); 1640 } 1641 1642 return ret; 1643 } 1644 #endif /* !SMALL */ 1645 1646 static void 1647 ftp_close(FILE **fin, struct tls **tls, volatile int *fd) 1648 { 1649 #ifndef NOSSL 1650 int ret; 1651 1652 if (*tls != NULL) { 1653 if (tls_session_fd != -1) 1654 dprintf(STDERR_FILENO, "tls session resumed: %s\n", 1655 tls_conn_session_resumed(*tls) ? "yes" : "no"); 1656 do { 1657 ret = tls_close(*tls); 1658 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT); 1659 tls_free(*tls); 1660 *tls = NULL; 1661 } 1662 if (*fd != -1) { 1663 close(*fd); 1664 *fd = -1; 1665 } 1666 #endif 1667 if (*fin != NULL) { 1668 fclose(*fin); 1669 *fin = NULL; 1670 } 1671 } 1672 1673 static const char * 1674 sockerror(struct tls *tls) 1675 { 1676 int save_errno = errno; 1677 #ifndef NOSSL 1678 if (tls != NULL) { 1679 const char *tlserr = tls_error(tls); 1680 if (tlserr != NULL) 1681 return tlserr; 1682 } 1683 #endif 1684 return strerror(save_errno); 1685 } 1686 1687 #ifndef NOSSL 1688 static int 1689 proxy_connect(int socket, char *host, char *cookie) 1690 { 1691 int l; 1692 char buf[1024]; 1693 char *connstr, *hosttail, *port; 1694 1695 if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL && 1696 (hosttail[1] == '\0' || hosttail[1] == ':')) { 1697 host++; 1698 *hosttail++ = '\0'; 1699 } else 1700 hosttail = host; 1701 1702 port = strrchr(hosttail, ':'); /* find portnum */ 1703 if (port != NULL) 1704 *port++ = '\0'; 1705 if (!port) 1706 port = "443"; 1707 1708 if (cookie) { 1709 l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n" 1710 "Proxy-Authorization: Basic %s\r\n%s\r\n\r\n", 1711 host, port, cookie, HTTP_USER_AGENT); 1712 } else { 1713 l = asprintf(&connstr, "CONNECT %s:%s HTTP/1.1\r\n%s\r\n\r\n", 1714 host, port, HTTP_USER_AGENT); 1715 } 1716 1717 if (l == -1) 1718 errx(1, "Could not allocate memory to assemble connect string!"); 1719 #ifndef SMALL 1720 if (debug) 1721 printf("%s", connstr); 1722 #endif /* !SMALL */ 1723 if (write(socket, connstr, l) != l) 1724 err(1, "Could not send connect string"); 1725 read(socket, &buf, sizeof(buf)); /* only proxy header XXX: error handling? */ 1726 free(connstr); 1727 return(200); 1728 } 1729 1730 static int 1731 stdio_tls_write_wrapper(void *arg, const char *buf, int len) 1732 { 1733 struct tls *tls = arg; 1734 ssize_t ret; 1735 1736 do { 1737 ret = tls_write(tls, buf, len); 1738 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT); 1739 1740 return ret; 1741 } 1742 1743 static int 1744 stdio_tls_read_wrapper(void *arg, char *buf, int len) 1745 { 1746 struct tls *tls = arg; 1747 ssize_t ret; 1748 1749 do { 1750 ret = tls_read(tls, buf, len); 1751 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT); 1752 1753 return ret; 1754 } 1755 #endif /* !NOSSL */ 1756