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