1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1998-2016 Dag-Erling Smørgrav 5 * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de> 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer 13 * in this position and unchanged. 14 * 2. Redistributions in binary form must reproduce the above copyright 15 * notice, this list of conditions and the following disclaimer in the 16 * documentation and/or other materials provided with the distribution. 17 * 3. The name of the author may not be used to endorse or promote products 18 * derived from this software without specific prior written permission 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 __FBSDID("$FreeBSD$"); 34 35 #include <sys/param.h> 36 #include <sys/socket.h> 37 #include <sys/time.h> 38 #include <sys/uio.h> 39 40 #include <netinet/in.h> 41 42 #include <ctype.h> 43 #include <errno.h> 44 #include <fcntl.h> 45 #include <inttypes.h> 46 #include <netdb.h> 47 #include <paths.h> 48 #include <poll.h> 49 #include <pwd.h> 50 #include <stdarg.h> 51 #include <stdlib.h> 52 #include <stdio.h> 53 #include <string.h> 54 #include <unistd.h> 55 56 #ifdef WITH_SSL 57 #include <openssl/x509v3.h> 58 #endif 59 60 #include "fetch.h" 61 #include "common.h" 62 63 64 /*** Local data **************************************************************/ 65 66 /* 67 * Error messages for resolver errors 68 */ 69 static struct fetcherr netdb_errlist[] = { 70 #ifdef EAI_ADDRFAMILY 71 { EAI_ADDRFAMILY, FETCH_RESOLV, "Address family for host not supported" }, 72 #endif 73 #ifdef EAI_NODATA 74 { EAI_NODATA, FETCH_RESOLV, "No address for host" }, 75 #endif 76 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" }, 77 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" }, 78 { EAI_NONAME, FETCH_RESOLV, "Host does not resolve" }, 79 { -1, FETCH_UNKNOWN, "Unknown resolver error" } 80 }; 81 82 /* 83 * SOCKS5 error enumerations 84 */ 85 enum SOCKS5_ERR { 86 /* Protocol errors */ 87 SOCKS5_ERR_SELECTION, 88 SOCKS5_ERR_READ_METHOD, 89 SOCKS5_ERR_VER5_ONLY, 90 SOCKS5_ERR_NOMETHODS, 91 SOCKS5_ERR_NOTIMPLEMENTED, 92 SOCKS5_ERR_HOSTNAME_SIZE, 93 SOCKS5_ERR_REQUEST, 94 SOCKS5_ERR_REPLY, 95 SOCKS5_ERR_NON_VER5_RESP, 96 SOCKS5_ERR_GENERAL, 97 SOCKS5_ERR_NOT_ALLOWED, 98 SOCKS5_ERR_NET_UNREACHABLE, 99 SOCKS5_ERR_HOST_UNREACHABLE, 100 SOCKS5_ERR_CONN_REFUSED, 101 SOCKS5_ERR_TTL_EXPIRED, 102 SOCKS5_ERR_COM_UNSUPPORTED, 103 SOCKS5_ERR_ADDR_UNSUPPORTED, 104 SOCKS5_ERR_UNSPECIFIED, 105 /* Configuration errors */ 106 SOCKS5_ERR_BAD_HOST, 107 SOCKS5_ERR_BAD_PROXY_FORMAT, 108 SOCKS5_ERR_BAD_PORT 109 }; 110 111 /* 112 * Error messages for SOCKS5 errors 113 */ 114 static struct fetcherr socks5_errlist[] = { 115 /* SOCKS5 protocol errors */ 116 { SOCKS5_ERR_SELECTION, FETCH_ABORT, "SOCKS5: Failed to send selection method" }, 117 { SOCKS5_ERR_READ_METHOD, FETCH_ABORT, "SOCKS5: Failed to read method" }, 118 { SOCKS5_ERR_VER5_ONLY, FETCH_PROTO, "SOCKS5: Only version 5 is implemented" }, 119 { SOCKS5_ERR_NOMETHODS, FETCH_PROTO, "SOCKS5: No acceptable methods" }, 120 { SOCKS5_ERR_NOTIMPLEMENTED, FETCH_PROTO, "SOCKS5: Method currently not implemented" }, 121 { SOCKS5_ERR_HOSTNAME_SIZE, FETCH_PROTO, "SOCKS5: Hostname size is above 256 bytes" }, 122 { SOCKS5_ERR_REQUEST, FETCH_PROTO, "SOCKS5: Failed to request" }, 123 { SOCKS5_ERR_REPLY, FETCH_PROTO, "SOCKS5: Failed to receive reply" }, 124 { SOCKS5_ERR_NON_VER5_RESP, FETCH_PROTO, "SOCKS5: Server responded with a non-version 5 response" }, 125 { SOCKS5_ERR_GENERAL, FETCH_ABORT, "SOCKS5: General server failure" }, 126 { SOCKS5_ERR_NOT_ALLOWED, FETCH_AUTH, "SOCKS5: Connection not allowed by ruleset" }, 127 { SOCKS5_ERR_NET_UNREACHABLE, FETCH_NETWORK, "SOCKS5: Network unreachable" }, 128 { SOCKS5_ERR_HOST_UNREACHABLE, FETCH_ABORT, "SOCKS5: Host unreachable" }, 129 { SOCKS5_ERR_CONN_REFUSED, FETCH_ABORT, "SOCKS5: Connection refused" }, 130 { SOCKS5_ERR_TTL_EXPIRED, FETCH_TIMEOUT, "SOCKS5: TTL expired" }, 131 { SOCKS5_ERR_COM_UNSUPPORTED, FETCH_PROTO, "SOCKS5: Command not supported" }, 132 { SOCKS5_ERR_ADDR_UNSUPPORTED, FETCH_ABORT, "SOCKS5: Address type not supported" }, 133 { SOCKS5_ERR_UNSPECIFIED, FETCH_UNKNOWN, "SOCKS5: Unspecified error" }, 134 /* Configuration error */ 135 { SOCKS5_ERR_BAD_HOST, FETCH_ABORT, "SOCKS5: Bad proxy host" }, 136 { SOCKS5_ERR_BAD_PROXY_FORMAT, FETCH_ABORT, "SOCKS5: Bad proxy format" }, 137 { SOCKS5_ERR_BAD_PORT, FETCH_ABORT, "SOCKS5: Bad port" } 138 }; 139 140 /* End-of-Line */ 141 static const char ENDL[2] = "\r\n"; 142 143 144 /*** Error-reporting functions ***********************************************/ 145 146 /* 147 * Map error code to string 148 */ 149 static struct fetcherr * 150 fetch_finderr(struct fetcherr *p, int e) 151 { 152 while (p->num != -1 && p->num != e) 153 p++; 154 return (p); 155 } 156 157 /* 158 * Set error code 159 */ 160 void 161 fetch_seterr(struct fetcherr *p, int e) 162 { 163 p = fetch_finderr(p, e); 164 fetchLastErrCode = p->cat; 165 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string); 166 } 167 168 /* 169 * Set error code according to errno 170 */ 171 void 172 fetch_syserr(void) 173 { 174 switch (errno) { 175 case 0: 176 fetchLastErrCode = FETCH_OK; 177 break; 178 case EPERM: 179 case EACCES: 180 case EROFS: 181 case EAUTH: 182 case ENEEDAUTH: 183 fetchLastErrCode = FETCH_AUTH; 184 break; 185 case ENOENT: 186 case EISDIR: /* XXX */ 187 fetchLastErrCode = FETCH_UNAVAIL; 188 break; 189 case ENOMEM: 190 fetchLastErrCode = FETCH_MEMORY; 191 break; 192 case EBUSY: 193 case EAGAIN: 194 fetchLastErrCode = FETCH_TEMP; 195 break; 196 case EEXIST: 197 fetchLastErrCode = FETCH_EXISTS; 198 break; 199 case ENOSPC: 200 fetchLastErrCode = FETCH_FULL; 201 break; 202 case EADDRINUSE: 203 case EADDRNOTAVAIL: 204 case ENETDOWN: 205 case ENETUNREACH: 206 case ENETRESET: 207 case EHOSTUNREACH: 208 fetchLastErrCode = FETCH_NETWORK; 209 break; 210 case ECONNABORTED: 211 case ECONNRESET: 212 fetchLastErrCode = FETCH_ABORT; 213 break; 214 case ETIMEDOUT: 215 fetchLastErrCode = FETCH_TIMEOUT; 216 break; 217 case ECONNREFUSED: 218 case EHOSTDOWN: 219 fetchLastErrCode = FETCH_DOWN; 220 break; 221 default: 222 fetchLastErrCode = FETCH_UNKNOWN; 223 } 224 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno)); 225 } 226 227 228 /* 229 * Emit status message 230 */ 231 void 232 fetch_info(const char *fmt, ...) 233 { 234 va_list ap; 235 236 va_start(ap, fmt); 237 vfprintf(stderr, fmt, ap); 238 va_end(ap); 239 fputc('\n', stderr); 240 } 241 242 243 /*** Network-related utility functions ***************************************/ 244 245 /* 246 * Return the default port for a scheme 247 */ 248 int 249 fetch_default_port(const char *scheme) 250 { 251 struct servent *se; 252 253 if ((se = getservbyname(scheme, "tcp")) != NULL) 254 return (ntohs(se->s_port)); 255 if (strcmp(scheme, SCHEME_FTP) == 0) 256 return (FTP_DEFAULT_PORT); 257 if (strcmp(scheme, SCHEME_HTTP) == 0) 258 return (HTTP_DEFAULT_PORT); 259 return (0); 260 } 261 262 /* 263 * Return the default proxy port for a scheme 264 */ 265 int 266 fetch_default_proxy_port(const char *scheme) 267 { 268 if (strcmp(scheme, SCHEME_FTP) == 0) 269 return (FTP_DEFAULT_PROXY_PORT); 270 if (strcmp(scheme, SCHEME_HTTP) == 0) 271 return (HTTP_DEFAULT_PROXY_PORT); 272 return (0); 273 } 274 275 276 /* 277 * Create a connection for an existing descriptor. 278 */ 279 conn_t * 280 fetch_reopen(int sd) 281 { 282 conn_t *conn; 283 int opt = 1; 284 285 /* allocate and fill connection structure */ 286 if ((conn = calloc(1, sizeof(*conn))) == NULL) 287 return (NULL); 288 fcntl(sd, F_SETFD, FD_CLOEXEC); 289 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt); 290 conn->sd = sd; 291 ++conn->ref; 292 return (conn); 293 } 294 295 296 /* 297 * Bump a connection's reference count. 298 */ 299 conn_t * 300 fetch_ref(conn_t *conn) 301 { 302 303 ++conn->ref; 304 return (conn); 305 } 306 307 308 /* 309 * Resolve an address 310 */ 311 struct addrinfo * 312 fetch_resolve(const char *addr, int port, int af) 313 { 314 char hbuf[256], sbuf[8]; 315 struct addrinfo hints, *res; 316 const char *hb, *he, *sep; 317 const char *host, *service; 318 int err, len; 319 320 /* first, check for a bracketed IPv6 address */ 321 if (*addr == '[') { 322 hb = addr + 1; 323 if ((sep = strchr(hb, ']')) == NULL) { 324 errno = EINVAL; 325 goto syserr; 326 } 327 he = sep++; 328 } else { 329 hb = addr; 330 sep = strchrnul(hb, ':'); 331 he = sep; 332 } 333 334 /* see if we need to copy the host name */ 335 if (*he != '\0') { 336 len = snprintf(hbuf, sizeof(hbuf), 337 "%.*s", (int)(he - hb), hb); 338 if (len < 0) 339 goto syserr; 340 if (len >= (int)sizeof(hbuf)) { 341 errno = ENAMETOOLONG; 342 goto syserr; 343 } 344 host = hbuf; 345 } else { 346 host = hb; 347 } 348 349 /* was it followed by a service name? */ 350 if (*sep == '\0' && port != 0) { 351 if (port < 1 || port > 65535) { 352 errno = EINVAL; 353 goto syserr; 354 } 355 if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0) 356 goto syserr; 357 service = sbuf; 358 } else if (*sep != '\0') { 359 service = sep + 1; 360 } else { 361 service = NULL; 362 } 363 364 /* resolve */ 365 memset(&hints, 0, sizeof(hints)); 366 hints.ai_family = af; 367 hints.ai_socktype = SOCK_STREAM; 368 hints.ai_flags = AI_ADDRCONFIG; 369 if ((err = getaddrinfo(host, service, &hints, &res)) != 0) { 370 netdb_seterr(err); 371 return (NULL); 372 } 373 return (res); 374 syserr: 375 fetch_syserr(); 376 return (NULL); 377 } 378 379 380 /* 381 * Bind a socket to a specific local address 382 */ 383 int 384 fetch_bind(int sd, int af, const char *addr) 385 { 386 struct addrinfo *cliai, *ai; 387 int err; 388 389 if ((cliai = fetch_resolve(addr, 0, af)) == NULL) 390 return (-1); 391 for (ai = cliai; ai != NULL; ai = ai->ai_next) 392 if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0) 393 break; 394 if (err != 0) 395 fetch_syserr(); 396 freeaddrinfo(cliai); 397 return (err == 0 ? 0 : -1); 398 } 399 400 401 /* 402 * SOCKS5 connection initiation, based on RFC 1928 403 * Default DNS resolution over SOCKS5 404 */ 405 int 406 fetch_socks5_init(conn_t *conn, const char *host, int port, int verbose) 407 { 408 /* 409 * Size is based on largest packet prefix (4 bytes) + 410 * Largest FQDN (256) + one byte size (1) + 411 * Port (2) 412 */ 413 unsigned char buf[BUFF_SIZE]; 414 unsigned char *ptr; 415 int ret = 1; 416 417 if (verbose) 418 fetch_info("Initializing SOCKS5 connection: %s:%d", host, port); 419 420 /* Connection initialization */ 421 ptr = buf; 422 *ptr++ = SOCKS_VERSION_5; 423 *ptr++ = SOCKS_CONNECTION; 424 *ptr++ = SOCKS_RSV; 425 426 if (fetch_write(conn, buf, 3) != 3) { 427 ret = SOCKS5_ERR_SELECTION; 428 goto fail; 429 } 430 431 /* Verify response from SOCKS5 server */ 432 if (fetch_read(conn, buf, 2) != 2) { 433 ret = SOCKS5_ERR_READ_METHOD; 434 goto fail; 435 } 436 437 ptr = buf; 438 if (ptr[0] != SOCKS_VERSION_5) { 439 ret = SOCKS5_ERR_VER5_ONLY; 440 goto fail; 441 } 442 if (ptr[1] == SOCKS_NOMETHODS) { 443 ret = SOCKS5_ERR_NOMETHODS; 444 goto fail; 445 } 446 else if (ptr[1] != SOCKS5_NOTIMPLEMENTED) { 447 ret = SOCKS5_ERR_NOTIMPLEMENTED; 448 goto fail; 449 } 450 451 /* Send Request */ 452 *ptr++ = SOCKS_VERSION_5; 453 *ptr++ = SOCKS_CONNECTION; 454 *ptr++ = SOCKS_RSV; 455 /* Encode all targets as a hostname to avoid DNS leaks */ 456 *ptr++ = SOCKS_ATYP_DOMAINNAME; 457 if (strlen(host) > FQDN_SIZE) { 458 ret = SOCKS5_ERR_HOSTNAME_SIZE; 459 goto fail; 460 } 461 *ptr++ = strlen(host); 462 memcpy(ptr, host, strlen(host)); 463 ptr = ptr + strlen(host); 464 465 port = htons(port); 466 *ptr++ = port & 0x00ff; 467 *ptr++ = (port & 0xff00) >> 8; 468 469 if (fetch_write(conn, buf, ptr - buf) != ptr - buf) { 470 ret = SOCKS5_ERR_REQUEST; 471 goto fail; 472 } 473 474 /* BND.ADDR is variable length, read the largest on non-blocking socket */ 475 if (!fetch_read(conn, buf, BUFF_SIZE)) { 476 ret = SOCKS5_ERR_REPLY; 477 goto fail; 478 } 479 480 ptr = buf; 481 if (*ptr++ != SOCKS_VERSION_5) { 482 ret = SOCKS5_ERR_NON_VER5_RESP; 483 goto fail; 484 } 485 486 switch(*ptr++) { 487 case SOCKS_SUCCESS: 488 break; 489 case SOCKS_GENERAL_FAILURE: 490 ret = SOCKS5_ERR_GENERAL; 491 goto fail; 492 case SOCKS_CONNECTION_NOT_ALLOWED: 493 ret = SOCKS5_ERR_NOT_ALLOWED; 494 goto fail; 495 case SOCKS_NETWORK_UNREACHABLE: 496 ret = SOCKS5_ERR_NET_UNREACHABLE; 497 goto fail; 498 case SOCKS_HOST_UNREACHABLE: 499 ret = SOCKS5_ERR_HOST_UNREACHABLE; 500 goto fail; 501 case SOCKS_CONNECTION_REFUSED: 502 ret = SOCKS5_ERR_CONN_REFUSED; 503 goto fail; 504 case SOCKS_TTL_EXPIRED: 505 ret = SOCKS5_ERR_TTL_EXPIRED; 506 goto fail; 507 case SOCKS_COMMAND_NOT_SUPPORTED: 508 ret = SOCKS5_ERR_COM_UNSUPPORTED; 509 goto fail; 510 case SOCKS_ADDRESS_NOT_SUPPORTED: 511 ret = SOCKS5_ERR_ADDR_UNSUPPORTED; 512 goto fail; 513 default: 514 ret = SOCKS5_ERR_UNSPECIFIED; 515 goto fail; 516 } 517 518 return (ret); 519 520 fail: 521 socks5_seterr(ret); 522 return (0); 523 } 524 525 /* 526 * Perform SOCKS5 initialization 527 */ 528 int 529 fetch_socks5_getenv(char **host, int *port) 530 { 531 char *socks5env, *endptr, *ext; 532 const char *portDelim; 533 size_t slen; 534 535 portDelim = ":"; 536 if ((socks5env = getenv("SOCKS5_PROXY")) == NULL || *socks5env == '\0') { 537 *host = NULL; 538 *port = -1; 539 return (-1); 540 } 541 542 /* 543 * IPv6 addresses begin and end in brackets. Set the port delimiter 544 * accordingly and search for it so we can do appropriate validation. 545 */ 546 if (socks5env[0] == '[') 547 portDelim = "]:"; 548 549 slen = strlen(socks5env); 550 ext = strstr(socks5env, portDelim); 551 if (socks5env[0] == '[') { 552 if (socks5env[slen - 1] == ']') { 553 *host = strndup(socks5env, slen); 554 } else if (ext != NULL) { 555 *host = strndup(socks5env, ext - socks5env + 1); 556 } else { 557 socks5_seterr(SOCKS5_ERR_BAD_PROXY_FORMAT); 558 return (0); 559 } 560 } else { 561 *host = strndup(socks5env, ext - socks5env); 562 } 563 564 if (*host == NULL) { 565 fprintf(stderr, "Failure to allocate memory, exiting.\n"); 566 return (-1); 567 } 568 if (ext == NULL) { 569 *port = 1080; /* Default port as defined in RFC1928 */ 570 } else { 571 ext += strlen(portDelim); 572 errno = 0; 573 *port = strtoimax(ext, (char **)&endptr, 10); 574 if (*endptr != '\0' || errno != 0 || *port < 0 || 575 *port > 65535) { 576 free(*host); 577 *host = NULL; 578 socks5_seterr(SOCKS5_ERR_BAD_PORT); 579 return (0); 580 } 581 } 582 583 return (2); 584 } 585 586 587 /* 588 * Establish a TCP connection to the specified port on the specified host. 589 */ 590 conn_t * 591 fetch_connect(const char *host, int port, int af, int verbose) 592 { 593 struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai; 594 const char *bindaddr; 595 conn_t *conn = NULL; 596 int err = 0, sd = -1; 597 char *sockshost; 598 int socksport; 599 600 DEBUGF("---> %s:%d\n", host, port); 601 602 /* 603 * Check if SOCKS5_PROXY env variable is set. fetch_socks5_getenv 604 * will either set sockshost = NULL or allocate memory in all cases. 605 */ 606 sockshost = NULL; 607 if (!fetch_socks5_getenv(&sockshost, &socksport)) 608 goto fail; 609 610 /* Not using SOCKS5 proxy */ 611 if (sockshost == NULL) { 612 /* resolve server address */ 613 if (verbose) 614 fetch_info("resolving server address: %s:%d", host, 615 port); 616 if ((sais = fetch_resolve(host, port, af)) == NULL) 617 goto fail; 618 619 /* resolve client address */ 620 bindaddr = getenv("FETCH_BIND_ADDRESS"); 621 if (bindaddr != NULL && *bindaddr != '\0') { 622 if (verbose) 623 fetch_info("resolving client address: %s", 624 bindaddr); 625 if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL) 626 goto fail; 627 } 628 } else { 629 /* resolve socks5 proxy address */ 630 if (verbose) 631 fetch_info("resolving SOCKS5 server address: %s:%d", 632 sockshost, socksport); 633 if ((sais = fetch_resolve(sockshost, socksport, af)) == NULL) { 634 socks5_seterr(SOCKS5_ERR_BAD_HOST); 635 goto fail; 636 } 637 } 638 639 /* try each server address in turn */ 640 for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) { 641 /* open socket */ 642 if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0) 643 goto syserr; 644 /* attempt to bind to client address */ 645 for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) { 646 if (cai->ai_family != sai->ai_family) 647 continue; 648 if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0) 649 break; 650 } 651 if (err != 0) { 652 if (verbose) 653 fetch_info("failed to bind to %s", bindaddr); 654 goto syserr; 655 } 656 /* attempt to connect to server address */ 657 if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0) 658 break; 659 /* clean up before next attempt */ 660 close(sd); 661 sd = -1; 662 } 663 if (err != 0) { 664 if (verbose && sockshost == NULL) { 665 fetch_info("failed to connect to %s:%d", host, port); 666 goto syserr; 667 } else if (sockshost != NULL) { 668 if (verbose) 669 fetch_info( 670 "failed to connect to SOCKS5 server %s:%d", 671 sockshost, socksport); 672 socks5_seterr(SOCKS5_ERR_CONN_REFUSED); 673 goto fail; 674 } 675 goto syserr; 676 } 677 678 if ((conn = fetch_reopen(sd)) == NULL) 679 goto syserr; 680 681 if (sockshost) 682 if (!fetch_socks5_init(conn, host, port, verbose)) 683 goto fail; 684 free(sockshost); 685 if (cais != NULL) 686 freeaddrinfo(cais); 687 if (sais != NULL) 688 freeaddrinfo(sais); 689 return (conn); 690 syserr: 691 fetch_syserr(); 692 fail: 693 free(sockshost); 694 /* Fully close if it was opened; otherwise just don't leak the fd. */ 695 if (conn != NULL) 696 fetch_close(conn); 697 else if (sd >= 0) 698 close(sd); 699 if (cais != NULL) 700 freeaddrinfo(cais); 701 if (sais != NULL) 702 freeaddrinfo(sais); 703 return (NULL); 704 } 705 706 #ifdef WITH_SSL 707 /* 708 * Convert characters A-Z to lowercase (intentionally avoid any locale 709 * specific conversions). 710 */ 711 static char 712 fetch_ssl_tolower(char in) 713 { 714 if (in >= 'A' && in <= 'Z') 715 return (in + 32); 716 else 717 return (in); 718 } 719 720 /* 721 * isalpha implementation that intentionally avoids any locale specific 722 * conversions. 723 */ 724 static int 725 fetch_ssl_isalpha(char in) 726 { 727 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z')); 728 } 729 730 /* 731 * Check if passed hostnames a and b are equal. 732 */ 733 static int 734 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b, 735 size_t blen) 736 { 737 size_t i; 738 739 if (alen != blen) 740 return (0); 741 for (i = 0; i < alen; ++i) { 742 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i])) 743 return (0); 744 } 745 return (1); 746 } 747 748 /* 749 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9 750 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha- 751 * numeric characters. Double hyphens (like they're found in IDN a-labels 752 * 'xn--') are not allowed. Empty labels are invalid. 753 */ 754 static int 755 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok) 756 { 757 size_t i; 758 759 if (!len || l[0] == '-' || l[len-1] == '-') 760 return (0); 761 for (i = 0; i < len; ++i) { 762 if (!isdigit(l[i]) && 763 !fetch_ssl_isalpha(l[i]) && 764 !(l[i] == '*' && wcok) && 765 !(l[i] == '-' && l[i - 1] != '-')) 766 return (0); 767 } 768 return (1); 769 } 770 771 /* 772 * Check if host name consists only of numbers. This might indicate an IP 773 * address, which is not a good idea for CN wildcard comparison. 774 */ 775 static int 776 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len) 777 { 778 size_t i; 779 780 for (i = 0; i < len; ++i) { 781 if (!((hostname[i] >= '0' && hostname[i] <= '9') || 782 hostname[i] == '.')) 783 return (0); 784 } 785 return (1); 786 } 787 788 /* 789 * Check if the host name h passed matches the pattern passed in m which 790 * is usually part of subjectAltName or CN of a certificate presented to 791 * the client. This includes wildcard matching. The algorithm is based on 792 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280. 793 */ 794 static int 795 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m, 796 size_t mlen) 797 { 798 int delta, hdotidx, mdot1idx, wcidx; 799 const char *hdot, *mdot1, *mdot2; 800 const char *wc; /* wildcard */ 801 802 if (!(h && *h && m && *m)) 803 return (0); 804 if ((wc = strnstr(m, "*", mlen)) == NULL) 805 return (fetch_ssl_hname_equal(h, hlen, m, mlen)); 806 wcidx = wc - m; 807 /* hostname should not be just dots and numbers */ 808 if (fetch_ssl_hname_is_only_numbers(h, hlen)) 809 return (0); 810 /* only one wildcard allowed in pattern */ 811 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL) 812 return (0); 813 /* 814 * there must be at least two more domain labels and 815 * wildcard has to be in the leftmost label (RFC6125) 816 */ 817 mdot1 = strnstr(m, ".", mlen); 818 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4) 819 return (0); 820 mdot1idx = mdot1 - m; 821 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1); 822 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2) 823 return (0); 824 /* hostname must contain a dot and not be the 1st char */ 825 hdot = strnstr(h, ".", hlen); 826 if (hdot == NULL || hdot == h) 827 return (0); 828 hdotidx = hdot - h; 829 /* 830 * host part of hostname must be at least as long as 831 * pattern it's supposed to match 832 */ 833 if (hdotidx < mdot1idx) 834 return (0); 835 /* 836 * don't allow wildcards in non-traditional domain names 837 * (IDN, A-label, U-label...) 838 */ 839 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) || 840 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1)) 841 return (0); 842 /* match domain part (part after first dot) */ 843 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1, 844 mlen - mdot1idx)) 845 return (0); 846 /* match part left of wildcard */ 847 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx)) 848 return (0); 849 /* match part right of wildcard */ 850 delta = mdot1idx - wcidx - 1; 851 if (!fetch_ssl_hname_equal(hdot - delta, delta, 852 mdot1 - delta, delta)) 853 return (0); 854 /* all tests succeeded, it's a match */ 855 return (1); 856 } 857 858 /* 859 * Get numeric host address info - returns NULL if host was not an IP 860 * address. The caller is responsible for deallocation using 861 * freeaddrinfo(3). 862 */ 863 static struct addrinfo * 864 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len) 865 { 866 struct addrinfo hints, *res; 867 char *host; 868 869 host = (char *)malloc(len + 1); 870 memcpy(host, hostname, len); 871 host[len] = '\0'; 872 memset(&hints, 0, sizeof(hints)); 873 hints.ai_family = PF_UNSPEC; 874 hints.ai_socktype = SOCK_STREAM; 875 hints.ai_protocol = 0; 876 hints.ai_flags = AI_NUMERICHOST; 877 /* port is not relevant for this purpose */ 878 if (getaddrinfo(host, "443", &hints, &res) != 0) 879 res = NULL; 880 free(host); 881 return res; 882 } 883 884 /* 885 * Compare ip address in addrinfo with address passes. 886 */ 887 static int 888 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost, 889 size_t rhostlen) 890 { 891 const void *left; 892 893 if (lhost->ai_family == AF_INET && rhostlen == 4) { 894 left = (void *)&((struct sockaddr_in*)(void *) 895 lhost->ai_addr)->sin_addr.s_addr; 896 #ifdef INET6 897 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) { 898 left = (void *)&((struct sockaddr_in6 *)(void *) 899 lhost->ai_addr)->sin6_addr; 900 #endif 901 } else 902 return (0); 903 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0); 904 } 905 906 /* 907 * Compare ip address in addrinfo with host passed. If host is not an IP 908 * address, comparison will fail. 909 */ 910 static int 911 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r, 912 size_t rlen) 913 { 914 struct addrinfo *raddr; 915 int ret; 916 char *rip; 917 918 ret = 0; 919 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL) 920 return 0; /* not a numeric host */ 921 922 if (laddr->ai_family == raddr->ai_family) { 923 if (laddr->ai_family == AF_INET) { 924 rip = (char *)&((struct sockaddr_in *)(void *) 925 raddr->ai_addr)->sin_addr.s_addr; 926 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4); 927 #ifdef INET6 928 } else if (laddr->ai_family == AF_INET6) { 929 rip = (char *)&((struct sockaddr_in6 *)(void *) 930 raddr->ai_addr)->sin6_addr; 931 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16); 932 #endif 933 } 934 935 } 936 freeaddrinfo(raddr); 937 return (ret); 938 } 939 940 /* 941 * Verify server certificate by subjectAltName. 942 */ 943 static int 944 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames, 945 const char *host, struct addrinfo *ip) 946 { 947 const GENERAL_NAME *name; 948 size_t nslen; 949 int i; 950 const char *ns; 951 952 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) { 953 name = sk_GENERAL_NAME_value(altnames, i); 954 ns = (const char *)ASN1_STRING_get0_data(name->d.ia5); 955 nslen = (size_t)ASN1_STRING_length(name->d.ia5); 956 957 if (name->type == GEN_DNS && ip == NULL && 958 fetch_ssl_hname_match(host, strlen(host), ns, nslen)) 959 return (1); 960 else if (name->type == GEN_IPADD && ip != NULL && 961 fetch_ssl_ipaddr_match_bin(ip, ns, nslen)) 962 return (1); 963 } 964 return (0); 965 } 966 967 /* 968 * Verify server certificate by CN. 969 */ 970 static int 971 fetch_ssl_verify_cn(X509_NAME *subject, const char *host, 972 struct addrinfo *ip) 973 { 974 ASN1_STRING *namedata; 975 X509_NAME_ENTRY *nameentry; 976 int cnlen, lastpos, loc, ret; 977 unsigned char *cn; 978 979 ret = 0; 980 lastpos = -1; 981 loc = -1; 982 cn = NULL; 983 /* get most specific CN (last entry in list) and compare */ 984 while ((lastpos = X509_NAME_get_index_by_NID(subject, 985 NID_commonName, lastpos)) != -1) 986 loc = lastpos; 987 988 if (loc > -1) { 989 nameentry = X509_NAME_get_entry(subject, loc); 990 namedata = X509_NAME_ENTRY_get_data(nameentry); 991 cnlen = ASN1_STRING_to_UTF8(&cn, namedata); 992 if (ip == NULL && 993 fetch_ssl_hname_match(host, strlen(host), cn, cnlen)) 994 ret = 1; 995 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen)) 996 ret = 1; 997 OPENSSL_free(cn); 998 } 999 return (ret); 1000 } 1001 1002 /* 1003 * Verify that server certificate subjectAltName/CN matches 1004 * hostname. First check, if there are alternative subject names. If yes, 1005 * those have to match. Only if those don't exist it falls back to 1006 * checking the subject's CN. 1007 */ 1008 static int 1009 fetch_ssl_verify_hname(X509 *cert, const char *host) 1010 { 1011 struct addrinfo *ip; 1012 STACK_OF(GENERAL_NAME) *altnames; 1013 X509_NAME *subject; 1014 int ret; 1015 1016 ret = 0; 1017 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host)); 1018 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name, 1019 NULL, NULL); 1020 1021 if (altnames != NULL) { 1022 ret = fetch_ssl_verify_altname(altnames, host, ip); 1023 } else { 1024 subject = X509_get_subject_name(cert); 1025 if (subject != NULL) 1026 ret = fetch_ssl_verify_cn(subject, host, ip); 1027 } 1028 1029 if (ip != NULL) 1030 freeaddrinfo(ip); 1031 if (altnames != NULL) 1032 GENERAL_NAMES_free(altnames); 1033 return (ret); 1034 } 1035 1036 /* 1037 * Configure transport security layer based on environment. 1038 */ 1039 static void 1040 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose) 1041 { 1042 long ssl_ctx_options; 1043 1044 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv3 | SSL_OP_NO_TICKET; 1045 if (getenv("SSL_NO_TLS1") != NULL) 1046 ssl_ctx_options |= SSL_OP_NO_TLSv1; 1047 if (getenv("SSL_NO_TLS1_1") != NULL) 1048 ssl_ctx_options |= SSL_OP_NO_TLSv1_1; 1049 if (getenv("SSL_NO_TLS1_2") != NULL) 1050 ssl_ctx_options |= SSL_OP_NO_TLSv1_2; 1051 if (verbose) 1052 fetch_info("SSL options: %lx", ssl_ctx_options); 1053 SSL_CTX_set_options(ctx, ssl_ctx_options); 1054 } 1055 1056 1057 /* 1058 * Configure peer verification based on environment. 1059 */ 1060 #define LOCAL_CERT_FILE _PATH_LOCALBASE "/etc/ssl/cert.pem" 1061 #define BASE_CERT_FILE "/etc/ssl/cert.pem" 1062 static int 1063 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose) 1064 { 1065 X509_LOOKUP *crl_lookup; 1066 X509_STORE *crl_store; 1067 const char *ca_cert_file, *ca_cert_path, *crl_file; 1068 1069 if (getenv("SSL_NO_VERIFY_PEER") == NULL) { 1070 ca_cert_file = getenv("SSL_CA_CERT_FILE"); 1071 if (ca_cert_file == NULL && 1072 access(LOCAL_CERT_FILE, R_OK) == 0) 1073 ca_cert_file = LOCAL_CERT_FILE; 1074 if (ca_cert_file == NULL && 1075 access(BASE_CERT_FILE, R_OK) == 0) 1076 ca_cert_file = BASE_CERT_FILE; 1077 ca_cert_path = getenv("SSL_CA_CERT_PATH"); 1078 if (verbose) { 1079 fetch_info("Peer verification enabled"); 1080 if (ca_cert_file != NULL) 1081 fetch_info("Using CA cert file: %s", 1082 ca_cert_file); 1083 if (ca_cert_path != NULL) 1084 fetch_info("Using CA cert path: %s", 1085 ca_cert_path); 1086 if (ca_cert_file == NULL && ca_cert_path == NULL) 1087 fetch_info("Using OpenSSL default " 1088 "CA cert file and path"); 1089 } 1090 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, 1091 fetch_ssl_cb_verify_crt); 1092 if (ca_cert_file != NULL || ca_cert_path != NULL) 1093 SSL_CTX_load_verify_locations(ctx, ca_cert_file, 1094 ca_cert_path); 1095 else 1096 SSL_CTX_set_default_verify_paths(ctx); 1097 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) { 1098 if (verbose) 1099 fetch_info("Using CRL file: %s", crl_file); 1100 crl_store = SSL_CTX_get_cert_store(ctx); 1101 crl_lookup = X509_STORE_add_lookup(crl_store, 1102 X509_LOOKUP_file()); 1103 if (crl_lookup == NULL || 1104 !X509_load_crl_file(crl_lookup, crl_file, 1105 X509_FILETYPE_PEM)) { 1106 fprintf(stderr, 1107 "Could not load CRL file %s\n", 1108 crl_file); 1109 return (0); 1110 } 1111 X509_STORE_set_flags(crl_store, 1112 X509_V_FLAG_CRL_CHECK | 1113 X509_V_FLAG_CRL_CHECK_ALL); 1114 } 1115 } 1116 return (1); 1117 } 1118 1119 /* 1120 * Configure client certificate based on environment. 1121 */ 1122 static int 1123 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose) 1124 { 1125 const char *client_cert_file, *client_key_file; 1126 1127 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) { 1128 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ? 1129 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file; 1130 if (verbose) { 1131 fetch_info("Using client cert file: %s", 1132 client_cert_file); 1133 fetch_info("Using client key file: %s", 1134 client_key_file); 1135 } 1136 if (SSL_CTX_use_certificate_chain_file(ctx, 1137 client_cert_file) != 1) { 1138 fprintf(stderr, 1139 "Could not load client certificate %s\n", 1140 client_cert_file); 1141 return (0); 1142 } 1143 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file, 1144 SSL_FILETYPE_PEM) != 1) { 1145 fprintf(stderr, 1146 "Could not load client key %s\n", 1147 client_key_file); 1148 return (0); 1149 } 1150 } 1151 return (1); 1152 } 1153 1154 /* 1155 * Callback for SSL certificate verification, this is called on server 1156 * cert verification. It takes no decision, but informs the user in case 1157 * verification failed. 1158 */ 1159 int 1160 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx) 1161 { 1162 X509 *crt; 1163 X509_NAME *name; 1164 char *str; 1165 1166 str = NULL; 1167 if (!verified) { 1168 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL && 1169 (name = X509_get_subject_name(crt)) != NULL) 1170 str = X509_NAME_oneline(name, 0, 0); 1171 fprintf(stderr, "Certificate verification failed for %s\n", 1172 str != NULL ? str : "no relevant certificate"); 1173 OPENSSL_free(str); 1174 } 1175 return (verified); 1176 } 1177 1178 #endif 1179 1180 /* 1181 * Enable SSL on a connection. 1182 */ 1183 int 1184 fetch_ssl(conn_t *conn, const struct url *URL, int verbose) 1185 { 1186 #ifdef WITH_SSL 1187 int ret, ssl_err; 1188 X509_NAME *name; 1189 char *str; 1190 1191 conn->ssl_meth = SSLv23_client_method(); 1192 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth); 1193 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY); 1194 1195 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose); 1196 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose)) 1197 return (-1); 1198 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose)) 1199 return (-1); 1200 1201 conn->ssl = SSL_new(conn->ssl_ctx); 1202 if (conn->ssl == NULL) { 1203 fprintf(stderr, "SSL context creation failed\n"); 1204 return (-1); 1205 } 1206 SSL_set_fd(conn->ssl, conn->sd); 1207 1208 #if !defined(OPENSSL_NO_TLSEXT) 1209 if (!SSL_set_tlsext_host_name(conn->ssl, 1210 __DECONST(struct url *, URL)->host)) { 1211 fprintf(stderr, 1212 "TLS server name indication extension failed for host %s\n", 1213 URL->host); 1214 return (-1); 1215 } 1216 #endif 1217 while ((ret = SSL_connect(conn->ssl)) == -1) { 1218 ssl_err = SSL_get_error(conn->ssl, ret); 1219 if (ssl_err != SSL_ERROR_WANT_READ && 1220 ssl_err != SSL_ERROR_WANT_WRITE) { 1221 ERR_print_errors_fp(stderr); 1222 return (-1); 1223 } 1224 } 1225 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl); 1226 1227 if (conn->ssl_cert == NULL) { 1228 fprintf(stderr, "No server SSL certificate\n"); 1229 return (-1); 1230 } 1231 1232 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) { 1233 if (verbose) 1234 fetch_info("Verify hostname"); 1235 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) { 1236 fprintf(stderr, 1237 "SSL certificate subject doesn't match host %s\n", 1238 URL->host); 1239 return (-1); 1240 } 1241 } 1242 1243 if (verbose) { 1244 fetch_info("%s connection established using %s", 1245 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl)); 1246 name = X509_get_subject_name(conn->ssl_cert); 1247 str = X509_NAME_oneline(name, 0, 0); 1248 fetch_info("Certificate subject: %s", str); 1249 OPENSSL_free(str); 1250 name = X509_get_issuer_name(conn->ssl_cert); 1251 str = X509_NAME_oneline(name, 0, 0); 1252 fetch_info("Certificate issuer: %s", str); 1253 OPENSSL_free(str); 1254 } 1255 1256 return (0); 1257 #else 1258 (void)conn; 1259 (void)verbose; 1260 (void)URL; 1261 fprintf(stderr, "SSL support disabled\n"); 1262 return (-1); 1263 #endif 1264 } 1265 1266 #define FETCH_READ_WAIT -2 1267 #define FETCH_READ_ERROR -1 1268 #define FETCH_READ_DONE 0 1269 1270 #ifdef WITH_SSL 1271 static ssize_t 1272 fetch_ssl_read(SSL *ssl, char *buf, size_t len) 1273 { 1274 ssize_t rlen; 1275 int ssl_err; 1276 1277 rlen = SSL_read(ssl, buf, len); 1278 if (rlen < 0) { 1279 ssl_err = SSL_get_error(ssl, rlen); 1280 if (ssl_err == SSL_ERROR_WANT_READ || 1281 ssl_err == SSL_ERROR_WANT_WRITE) { 1282 return (FETCH_READ_WAIT); 1283 } else { 1284 ERR_print_errors_fp(stderr); 1285 return (FETCH_READ_ERROR); 1286 } 1287 } 1288 return (rlen); 1289 } 1290 #endif 1291 1292 static ssize_t 1293 fetch_socket_read(int sd, char *buf, size_t len) 1294 { 1295 ssize_t rlen; 1296 1297 rlen = read(sd, buf, len); 1298 if (rlen < 0) { 1299 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls)) 1300 return (FETCH_READ_WAIT); 1301 else 1302 return (FETCH_READ_ERROR); 1303 } 1304 return (rlen); 1305 } 1306 1307 /* 1308 * Read a character from a connection w/ timeout 1309 */ 1310 ssize_t 1311 fetch_read(conn_t *conn, char *buf, size_t len) 1312 { 1313 struct timeval now, timeout, delta; 1314 struct pollfd pfd; 1315 ssize_t rlen; 1316 int deltams; 1317 1318 if (fetchTimeout > 0) { 1319 gettimeofday(&timeout, NULL); 1320 timeout.tv_sec += fetchTimeout; 1321 } 1322 1323 deltams = INFTIM; 1324 memset(&pfd, 0, sizeof pfd); 1325 pfd.fd = conn->sd; 1326 pfd.events = POLLIN | POLLERR; 1327 1328 for (;;) { 1329 /* 1330 * The socket is non-blocking. Instead of the canonical 1331 * poll() -> read(), we do the following: 1332 * 1333 * 1) call read() or SSL_read(). 1334 * 2) if we received some data, return it. 1335 * 3) if an error occurred, return -1. 1336 * 4) if read() or SSL_read() signaled EOF, return. 1337 * 5) if we did not receive any data but we're not at EOF, 1338 * call poll(). 1339 * 1340 * In the SSL case, this is necessary because if we 1341 * receive a close notification, we have to call 1342 * SSL_read() one additional time after we've read 1343 * everything we received. 1344 * 1345 * In the non-SSL case, it may improve performance (very 1346 * slightly) when reading small amounts of data. 1347 */ 1348 #ifdef WITH_SSL 1349 if (conn->ssl != NULL) 1350 rlen = fetch_ssl_read(conn->ssl, buf, len); 1351 else 1352 #endif 1353 rlen = fetch_socket_read(conn->sd, buf, len); 1354 if (rlen >= 0) { 1355 break; 1356 } else if (rlen == FETCH_READ_ERROR) { 1357 fetch_syserr(); 1358 return (-1); 1359 } 1360 // assert(rlen == FETCH_READ_WAIT); 1361 if (fetchTimeout > 0) { 1362 gettimeofday(&now, NULL); 1363 if (!timercmp(&timeout, &now, >)) { 1364 errno = ETIMEDOUT; 1365 fetch_syserr(); 1366 return (-1); 1367 } 1368 timersub(&timeout, &now, &delta); 1369 deltams = delta.tv_sec * 1000 + 1370 delta.tv_usec / 1000;; 1371 } 1372 errno = 0; 1373 pfd.revents = 0; 1374 if (poll(&pfd, 1, deltams) < 0) { 1375 if (errno == EINTR && fetchRestartCalls) 1376 continue; 1377 fetch_syserr(); 1378 return (-1); 1379 } 1380 } 1381 return (rlen); 1382 } 1383 1384 1385 /* 1386 * Read a line of text from a connection w/ timeout 1387 */ 1388 #define MIN_BUF_SIZE 1024 1389 1390 int 1391 fetch_getln(conn_t *conn) 1392 { 1393 char *tmp; 1394 size_t tmpsize; 1395 ssize_t len; 1396 char c; 1397 1398 if (conn->buf == NULL) { 1399 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) { 1400 errno = ENOMEM; 1401 return (-1); 1402 } 1403 conn->bufsize = MIN_BUF_SIZE; 1404 } 1405 1406 conn->buf[0] = '\0'; 1407 conn->buflen = 0; 1408 1409 do { 1410 len = fetch_read(conn, &c, 1); 1411 if (len == -1) 1412 return (-1); 1413 if (len == 0) 1414 break; 1415 conn->buf[conn->buflen++] = c; 1416 if (conn->buflen == conn->bufsize) { 1417 tmp = conn->buf; 1418 tmpsize = conn->bufsize * 2 + 1; 1419 if ((tmp = realloc(tmp, tmpsize)) == NULL) { 1420 errno = ENOMEM; 1421 return (-1); 1422 } 1423 conn->buf = tmp; 1424 conn->bufsize = tmpsize; 1425 } 1426 } while (c != '\n'); 1427 1428 conn->buf[conn->buflen] = '\0'; 1429 DEBUGF("<<< %s", conn->buf); 1430 return (0); 1431 } 1432 1433 1434 /* 1435 * Write to a connection w/ timeout 1436 */ 1437 ssize_t 1438 fetch_write(conn_t *conn, const char *buf, size_t len) 1439 { 1440 struct iovec iov; 1441 1442 iov.iov_base = __DECONST(char *, buf); 1443 iov.iov_len = len; 1444 return fetch_writev(conn, &iov, 1); 1445 } 1446 1447 /* 1448 * Write a vector to a connection w/ timeout 1449 * Note: can modify the iovec. 1450 */ 1451 ssize_t 1452 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt) 1453 { 1454 struct timeval now, timeout, delta; 1455 struct pollfd pfd; 1456 ssize_t wlen, total; 1457 int deltams; 1458 1459 memset(&pfd, 0, sizeof pfd); 1460 if (fetchTimeout) { 1461 pfd.fd = conn->sd; 1462 pfd.events = POLLOUT | POLLERR; 1463 gettimeofday(&timeout, NULL); 1464 timeout.tv_sec += fetchTimeout; 1465 } 1466 1467 total = 0; 1468 while (iovcnt > 0) { 1469 while (fetchTimeout && pfd.revents == 0) { 1470 gettimeofday(&now, NULL); 1471 if (!timercmp(&timeout, &now, >)) { 1472 errno = ETIMEDOUT; 1473 fetch_syserr(); 1474 return (-1); 1475 } 1476 timersub(&timeout, &now, &delta); 1477 deltams = delta.tv_sec * 1000 + 1478 delta.tv_usec / 1000; 1479 errno = 0; 1480 pfd.revents = 0; 1481 if (poll(&pfd, 1, deltams) < 0) { 1482 /* POSIX compliance */ 1483 if (errno == EAGAIN) 1484 continue; 1485 if (errno == EINTR && fetchRestartCalls) 1486 continue; 1487 return (-1); 1488 } 1489 } 1490 errno = 0; 1491 #ifdef WITH_SSL 1492 if (conn->ssl != NULL) 1493 wlen = SSL_write(conn->ssl, 1494 iov->iov_base, iov->iov_len); 1495 else 1496 #endif 1497 wlen = writev(conn->sd, iov, iovcnt); 1498 if (wlen == 0) { 1499 /* we consider a short write a failure */ 1500 /* XXX perhaps we shouldn't in the SSL case */ 1501 errno = EPIPE; 1502 fetch_syserr(); 1503 return (-1); 1504 } 1505 if (wlen < 0) { 1506 if (errno == EINTR && fetchRestartCalls) 1507 continue; 1508 return (-1); 1509 } 1510 total += wlen; 1511 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) { 1512 wlen -= iov->iov_len; 1513 iov++; 1514 iovcnt--; 1515 } 1516 if (iovcnt > 0) { 1517 iov->iov_len -= wlen; 1518 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen; 1519 } 1520 } 1521 return (total); 1522 } 1523 1524 1525 /* 1526 * Write a line of text to a connection w/ timeout 1527 */ 1528 int 1529 fetch_putln(conn_t *conn, const char *str, size_t len) 1530 { 1531 struct iovec iov[2]; 1532 int ret; 1533 1534 DEBUGF(">>> %s\n", str); 1535 iov[0].iov_base = __DECONST(char *, str); 1536 iov[0].iov_len = len; 1537 iov[1].iov_base = __DECONST(char *, ENDL); 1538 iov[1].iov_len = sizeof(ENDL); 1539 if (len == 0) 1540 ret = fetch_writev(conn, &iov[1], 1); 1541 else 1542 ret = fetch_writev(conn, iov, 2); 1543 if (ret == -1) 1544 return (-1); 1545 return (0); 1546 } 1547 1548 1549 /* 1550 * Close connection 1551 */ 1552 int 1553 fetch_close(conn_t *conn) 1554 { 1555 int ret; 1556 1557 if (--conn->ref > 0) 1558 return (0); 1559 #ifdef WITH_SSL 1560 if (conn->ssl) { 1561 SSL_shutdown(conn->ssl); 1562 SSL_set_connect_state(conn->ssl); 1563 SSL_free(conn->ssl); 1564 conn->ssl = NULL; 1565 } 1566 if (conn->ssl_ctx) { 1567 SSL_CTX_free(conn->ssl_ctx); 1568 conn->ssl_ctx = NULL; 1569 } 1570 if (conn->ssl_cert) { 1571 X509_free(conn->ssl_cert); 1572 conn->ssl_cert = NULL; 1573 } 1574 #endif 1575 ret = close(conn->sd); 1576 free(conn->buf); 1577 free(conn); 1578 return (ret); 1579 } 1580 1581 1582 /*** Directory-related utility functions *************************************/ 1583 1584 int 1585 fetch_add_entry(struct url_ent **p, int *size, int *len, 1586 const char *name, struct url_stat *us) 1587 { 1588 struct url_ent *tmp; 1589 1590 if (*p == NULL) { 1591 *size = 0; 1592 *len = 0; 1593 } 1594 1595 if (*len >= *size - 1) { 1596 tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p)); 1597 if (tmp == NULL) { 1598 errno = ENOMEM; 1599 fetch_syserr(); 1600 return (-1); 1601 } 1602 *size = (*size * 2 + 1); 1603 *p = tmp; 1604 } 1605 1606 tmp = *p + *len; 1607 snprintf(tmp->name, PATH_MAX, "%s", name); 1608 memcpy(&tmp->stat, us, sizeof(*us)); 1609 1610 (*len)++; 1611 (++tmp)->name[0] = 0; 1612 1613 return (0); 1614 } 1615 1616 1617 /*** Authentication-related utility functions ********************************/ 1618 1619 static const char * 1620 fetch_read_word(FILE *f) 1621 { 1622 static char word[1024]; 1623 1624 if (fscanf(f, " %1023s ", word) != 1) 1625 return (NULL); 1626 return (word); 1627 } 1628 1629 static int 1630 fetch_netrc_open(void) 1631 { 1632 struct passwd *pwd; 1633 char fn[PATH_MAX]; 1634 const char *p; 1635 int fd, serrno; 1636 1637 if ((p = getenv("NETRC")) != NULL) { 1638 DEBUGF("NETRC=%s\n", p); 1639 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) { 1640 fetch_info("$NETRC specifies a file name " 1641 "longer than PATH_MAX"); 1642 return (-1); 1643 } 1644 } else { 1645 if ((p = getenv("HOME")) == NULL) { 1646 if ((pwd = getpwuid(getuid())) == NULL || 1647 (p = pwd->pw_dir) == NULL) 1648 return (-1); 1649 } 1650 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn)) 1651 return (-1); 1652 } 1653 1654 if ((fd = open(fn, O_RDONLY)) < 0) { 1655 serrno = errno; 1656 DEBUGF("%s: %s\n", fn, strerror(serrno)); 1657 errno = serrno; 1658 } 1659 return (fd); 1660 } 1661 1662 /* 1663 * Get authentication data for a URL from .netrc 1664 */ 1665 int 1666 fetch_netrc_auth(struct url *url) 1667 { 1668 const char *word; 1669 int serrno; 1670 FILE *f; 1671 1672 if (url->netrcfd < 0) 1673 url->netrcfd = fetch_netrc_open(); 1674 if (url->netrcfd < 0) 1675 return (-1); 1676 if ((f = fdopen(url->netrcfd, "r")) == NULL) { 1677 serrno = errno; 1678 DEBUGF("fdopen(netrcfd): %s", strerror(errno)); 1679 close(url->netrcfd); 1680 url->netrcfd = -1; 1681 errno = serrno; 1682 return (-1); 1683 } 1684 rewind(f); 1685 DEBUGF("searching netrc for %s\n", url->host); 1686 while ((word = fetch_read_word(f)) != NULL) { 1687 if (strcmp(word, "default") == 0) { 1688 DEBUGF("using default netrc settings\n"); 1689 break; 1690 } 1691 if (strcmp(word, "machine") == 0 && 1692 (word = fetch_read_word(f)) != NULL && 1693 strcasecmp(word, url->host) == 0) { 1694 DEBUGF("using netrc settings for %s\n", word); 1695 break; 1696 } 1697 } 1698 if (word == NULL) 1699 goto ferr; 1700 while ((word = fetch_read_word(f)) != NULL) { 1701 if (strcmp(word, "login") == 0) { 1702 if ((word = fetch_read_word(f)) == NULL) 1703 goto ferr; 1704 if (snprintf(url->user, sizeof(url->user), 1705 "%s", word) > (int)sizeof(url->user)) { 1706 fetch_info("login name in .netrc is too long"); 1707 url->user[0] = '\0'; 1708 } 1709 } else if (strcmp(word, "password") == 0) { 1710 if ((word = fetch_read_word(f)) == NULL) 1711 goto ferr; 1712 if (snprintf(url->pwd, sizeof(url->pwd), 1713 "%s", word) > (int)sizeof(url->pwd)) { 1714 fetch_info("password in .netrc is too long"); 1715 url->pwd[0] = '\0'; 1716 } 1717 } else if (strcmp(word, "account") == 0) { 1718 if ((word = fetch_read_word(f)) == NULL) 1719 goto ferr; 1720 /* XXX not supported! */ 1721 } else { 1722 break; 1723 } 1724 } 1725 fclose(f); 1726 url->netrcfd = -1; 1727 return (0); 1728 ferr: 1729 serrno = errno; 1730 fclose(f); 1731 url->netrcfd = -1; 1732 errno = serrno; 1733 return (-1); 1734 } 1735 1736 /* 1737 * The no_proxy environment variable specifies a set of domains for 1738 * which the proxy should not be consulted; the contents is a comma-, 1739 * or space-separated list of domain names. A single asterisk will 1740 * override all proxy variables and no transactions will be proxied 1741 * (for compatibility with lynx and curl, see the discussion at 1742 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>). 1743 */ 1744 int 1745 fetch_no_proxy_match(const char *host) 1746 { 1747 const char *no_proxy, *p, *q; 1748 size_t h_len, d_len; 1749 1750 if ((no_proxy = getenv("NO_PROXY")) == NULL && 1751 (no_proxy = getenv("no_proxy")) == NULL) 1752 return (0); 1753 1754 /* asterisk matches any hostname */ 1755 if (strcmp(no_proxy, "*") == 0) 1756 return (1); 1757 1758 h_len = strlen(host); 1759 p = no_proxy; 1760 do { 1761 /* position p at the beginning of a domain suffix */ 1762 while (*p == ',' || isspace((unsigned char)*p)) 1763 p++; 1764 1765 /* position q at the first separator character */ 1766 for (q = p; *q; ++q) 1767 if (*q == ',' || isspace((unsigned char)*q)) 1768 break; 1769 1770 d_len = q - p; 1771 if (d_len > 0 && h_len >= d_len && 1772 strncasecmp(host + h_len - d_len, 1773 p, d_len) == 0) { 1774 /* domain name matches */ 1775 return (1); 1776 } 1777 1778 p = q + 1; 1779 } while (*q); 1780 1781 return (0); 1782 } 1783