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