1 /*- 2 * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer 10 * in this position and unchanged. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 3. The name of the author may not be used to endorse or promote products 15 * derived from this software without specific prior written permission 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 * 28 * $FreeBSD: src/lib/libfetch/common.c,v 1.56 2008/04/15 23:29:51 cperciva Exp $ 29 */ 30 31 #include <sys/param.h> 32 #include <sys/socket.h> 33 #include <sys/time.h> 34 #include <sys/uio.h> 35 36 #include <netinet/in.h> 37 38 #include <ctype.h> 39 #include <errno.h> 40 #include <netdb.h> 41 #include <pwd.h> 42 #include <stdarg.h> 43 #include <stdlib.h> 44 #include <stdio.h> 45 #include <string.h> 46 #include <unistd.h> 47 48 #include "fetch.h" 49 #include "common.h" 50 51 52 /*** Local data **************************************************************/ 53 54 /* 55 * Error messages for resolver errors 56 */ 57 static struct fetcherr netdb_errlist[] = { 58 #ifdef EAI_NODATA 59 { EAI_NODATA, FETCH_RESOLV, "Host not found" }, 60 #endif 61 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" }, 62 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" }, 63 { EAI_NONAME, FETCH_RESOLV, "No address record" }, 64 { -1, FETCH_UNKNOWN, "Unknown resolver error" } 65 }; 66 67 /* End-of-Line */ 68 static const char ENDL[2] = "\r\n"; 69 70 71 /*** Error-reporting functions ***********************************************/ 72 73 /* 74 * Map error code to string 75 */ 76 static struct fetcherr * 77 fetch_finderr(struct fetcherr *p, int e) 78 { 79 while (p->num != -1 && p->num != e) 80 p++; 81 return (p); 82 } 83 84 /* 85 * Set error code 86 */ 87 void 88 fetch_seterr(struct fetcherr *p, int e) 89 { 90 p = fetch_finderr(p, e); 91 fetchLastErrCode = p->cat; 92 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string); 93 } 94 95 /* 96 * Set error code according to errno 97 */ 98 void 99 fetch_syserr(void) 100 { 101 switch (errno) { 102 case 0: 103 fetchLastErrCode = FETCH_OK; 104 break; 105 case EPERM: 106 case EACCES: 107 case EROFS: 108 case EAUTH: 109 case ENEEDAUTH: 110 fetchLastErrCode = FETCH_AUTH; 111 break; 112 case ENOENT: 113 case EISDIR: /* XXX */ 114 fetchLastErrCode = FETCH_UNAVAIL; 115 break; 116 case ENOMEM: 117 fetchLastErrCode = FETCH_MEMORY; 118 break; 119 case EBUSY: 120 case EAGAIN: 121 fetchLastErrCode = FETCH_TEMP; 122 break; 123 case EEXIST: 124 fetchLastErrCode = FETCH_EXISTS; 125 break; 126 case ENOSPC: 127 fetchLastErrCode = FETCH_FULL; 128 break; 129 case EADDRINUSE: 130 case EADDRNOTAVAIL: 131 case ENETDOWN: 132 case ENETUNREACH: 133 case ENETRESET: 134 case EHOSTUNREACH: 135 fetchLastErrCode = FETCH_NETWORK; 136 break; 137 case ECONNABORTED: 138 case ECONNRESET: 139 fetchLastErrCode = FETCH_ABORT; 140 break; 141 case ETIMEDOUT: 142 fetchLastErrCode = FETCH_TIMEOUT; 143 break; 144 case ECONNREFUSED: 145 case EHOSTDOWN: 146 fetchLastErrCode = FETCH_DOWN; 147 break; 148 default: 149 fetchLastErrCode = FETCH_UNKNOWN; 150 } 151 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno)); 152 } 153 154 155 /* 156 * Emit status message 157 */ 158 void 159 fetch_info(const char *fmt, ...) 160 { 161 va_list ap; 162 163 va_start(ap, fmt); 164 vfprintf(stderr, fmt, ap); 165 va_end(ap); 166 fputc('\n', stderr); 167 } 168 169 170 /*** Network-related utility functions ***************************************/ 171 172 /* 173 * Return the default port for a scheme 174 */ 175 int 176 fetch_default_port(const char *scheme) 177 { 178 struct servent *se; 179 180 if ((se = getservbyname(scheme, "tcp")) != NULL) 181 return (ntohs(se->s_port)); 182 if (strcasecmp(scheme, SCHEME_FTP) == 0) 183 return (FTP_DEFAULT_PORT); 184 if (strcasecmp(scheme, SCHEME_HTTP) == 0) 185 return (HTTP_DEFAULT_PORT); 186 return (0); 187 } 188 189 /* 190 * Return the default proxy port for a scheme 191 */ 192 int 193 fetch_default_proxy_port(const char *scheme) 194 { 195 if (strcasecmp(scheme, SCHEME_FTP) == 0) 196 return (FTP_DEFAULT_PROXY_PORT); 197 if (strcasecmp(scheme, SCHEME_HTTP) == 0) 198 return (HTTP_DEFAULT_PROXY_PORT); 199 return (0); 200 } 201 202 203 /* 204 * Create a connection for an existing descriptor. 205 */ 206 conn_t * 207 fetch_reopen(int sd) 208 { 209 conn_t *conn; 210 211 /* allocate and fill connection structure */ 212 if ((conn = calloc(1, sizeof(*conn))) == NULL) 213 return (NULL); 214 conn->sd = sd; 215 ++conn->ref; 216 return (conn); 217 } 218 219 220 /* 221 * Bump a connection's reference count. 222 */ 223 conn_t * 224 fetch_ref(conn_t *conn) 225 { 226 227 ++conn->ref; 228 return (conn); 229 } 230 231 232 /* 233 * Bind a socket to a specific local address 234 */ 235 int 236 fetch_bind(int sd, int af, const char *addr) 237 { 238 struct addrinfo hints, *res, *res0; 239 int err; 240 241 memset(&hints, 0, sizeof(hints)); 242 hints.ai_family = af; 243 hints.ai_socktype = SOCK_STREAM; 244 hints.ai_protocol = 0; 245 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0) 246 return (-1); 247 for (res = res0; res; res = res->ai_next) 248 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0) 249 return (0); 250 return (-1); 251 } 252 253 254 /* 255 * Establish a TCP connection to the specified port on the specified host. 256 */ 257 conn_t * 258 fetch_connect(const char *host, int port, int af, int verbose) 259 { 260 conn_t *conn; 261 char pbuf[10]; 262 const char *bindaddr; 263 struct addrinfo hints, *res, *res0; 264 int sd, err; 265 266 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port)); 267 268 if (verbose) 269 fetch_info("looking up %s", host); 270 271 /* look up host name and set up socket address structure */ 272 snprintf(pbuf, sizeof(pbuf), "%d", port); 273 memset(&hints, 0, sizeof(hints)); 274 hints.ai_family = af; 275 hints.ai_socktype = SOCK_STREAM; 276 hints.ai_protocol = 0; 277 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) { 278 netdb_seterr(err); 279 return (NULL); 280 } 281 bindaddr = getenv("FETCH_BIND_ADDRESS"); 282 283 if (verbose) 284 fetch_info("connecting to %s:%d", host, port); 285 286 /* try to connect */ 287 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) { 288 if ((sd = socket(res->ai_family, res->ai_socktype, 289 res->ai_protocol)) == -1) 290 continue; 291 if (bindaddr != NULL && *bindaddr != '\0' && 292 fetch_bind(sd, res->ai_family, bindaddr) != 0) { 293 fetch_info("failed to bind to '%s'", bindaddr); 294 close(sd); 295 continue; 296 } 297 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0) 298 break; 299 close(sd); 300 } 301 freeaddrinfo(res0); 302 if (sd == -1) { 303 fetch_syserr(); 304 return (NULL); 305 } 306 307 if ((conn = fetch_reopen(sd)) == NULL) { 308 fetch_syserr(); 309 close(sd); 310 } 311 return (conn); 312 } 313 314 315 /* 316 * Enable SSL on a connection. 317 */ 318 int 319 fetch_ssl(conn_t *conn, int verbose) 320 { 321 322 #ifdef WITH_SSL 323 /* Init the SSL library and context */ 324 if (!SSL_library_init()){ 325 fprintf(stderr, "SSL library init failed\n"); 326 return (-1); 327 } 328 329 SSL_load_error_strings(); 330 331 conn->ssl_meth = SSLv23_client_method(); 332 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth); 333 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY); 334 335 conn->ssl = SSL_new(conn->ssl_ctx); 336 if (conn->ssl == NULL){ 337 fprintf(stderr, "SSL context creation failed\n"); 338 return (-1); 339 } 340 SSL_set_fd(conn->ssl, conn->sd); 341 if (SSL_connect(conn->ssl) == -1){ 342 ERR_print_errors_fp(stderr); 343 return (-1); 344 } 345 346 if (verbose) { 347 X509_NAME *name; 348 char *str; 349 350 fprintf(stderr, "SSL connection established using %s\n", 351 SSL_get_cipher(conn->ssl)); 352 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl); 353 name = X509_get_subject_name(conn->ssl_cert); 354 str = X509_NAME_oneline(name, 0, 0); 355 printf("Certificate subject: %s\n", str); 356 free(str); 357 name = X509_get_issuer_name(conn->ssl_cert); 358 str = X509_NAME_oneline(name, 0, 0); 359 printf("Certificate issuer: %s\n", str); 360 free(str); 361 } 362 363 return (0); 364 #else 365 (void)conn; 366 (void)verbose; 367 fprintf(stderr, "SSL support disabled\n"); 368 return (-1); 369 #endif 370 } 371 372 373 /* 374 * Read a character from a connection w/ timeout 375 */ 376 ssize_t 377 fetch_read(conn_t *conn, char *buf, size_t len) 378 { 379 struct timeval now, timeout, delta; 380 fd_set readfds; 381 ssize_t rlen, total; 382 int r; 383 384 if (fetchTimeout) { 385 FD_ZERO(&readfds); 386 gettimeofday(&timeout, NULL); 387 timeout.tv_sec += fetchTimeout; 388 } 389 390 total = 0; 391 while (len > 0) { 392 while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) { 393 FD_SET(conn->sd, &readfds); 394 gettimeofday(&now, NULL); 395 delta.tv_sec = timeout.tv_sec - now.tv_sec; 396 delta.tv_usec = timeout.tv_usec - now.tv_usec; 397 if (delta.tv_usec < 0) { 398 delta.tv_usec += 1000000; 399 delta.tv_sec--; 400 } 401 if (delta.tv_sec < 0) { 402 errno = ETIMEDOUT; 403 fetch_syserr(); 404 return (-1); 405 } 406 errno = 0; 407 r = select(conn->sd + 1, &readfds, NULL, NULL, &delta); 408 if (r == -1) { 409 if (errno == EINTR && fetchRestartCalls) 410 continue; 411 fetch_syserr(); 412 return (-1); 413 } 414 } 415 #ifdef WITH_SSL 416 if (conn->ssl != NULL) 417 rlen = SSL_read(conn->ssl, buf, len); 418 else 419 #endif 420 rlen = read(conn->sd, buf, len); 421 if (rlen == 0) 422 break; 423 if (rlen < 0) { 424 if (errno == EINTR && fetchRestartCalls) 425 continue; 426 return (-1); 427 } 428 len -= rlen; 429 buf += rlen; 430 total += rlen; 431 } 432 return (total); 433 } 434 435 436 /* 437 * Read a line of text from a connection w/ timeout 438 */ 439 #define MIN_BUF_SIZE 1024 440 441 int 442 fetch_getln(conn_t *conn) 443 { 444 char *tmp; 445 size_t tmpsize; 446 ssize_t len; 447 char c; 448 449 if (conn->buf == NULL) { 450 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) { 451 errno = ENOMEM; 452 return (-1); 453 } 454 conn->bufsize = MIN_BUF_SIZE; 455 } 456 457 conn->buf[0] = '\0'; 458 conn->buflen = 0; 459 460 do { 461 len = fetch_read(conn, &c, 1); 462 if (len == -1) 463 return (-1); 464 if (len == 0) 465 break; 466 conn->buf[conn->buflen++] = c; 467 if (conn->buflen == conn->bufsize) { 468 tmp = conn->buf; 469 tmpsize = conn->bufsize * 2 + 1; 470 if ((tmp = realloc(tmp, tmpsize)) == NULL) { 471 errno = ENOMEM; 472 return (-1); 473 } 474 conn->buf = tmp; 475 conn->bufsize = tmpsize; 476 } 477 } while (c != '\n'); 478 479 conn->buf[conn->buflen] = '\0'; 480 DEBUG(fprintf(stderr, "<<< %s", conn->buf)); 481 return (0); 482 } 483 484 485 /* 486 * Write to a connection w/ timeout 487 */ 488 ssize_t 489 fetch_write(conn_t *conn, const char *buf, size_t len) 490 { 491 struct iovec iov; 492 493 iov.iov_base = __DECONST(char *, buf); 494 iov.iov_len = len; 495 return fetch_writev(conn, &iov, 1); 496 } 497 498 /* 499 * Write a vector to a connection w/ timeout 500 * Note: can modify the iovec. 501 */ 502 ssize_t 503 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt) 504 { 505 struct timeval now, timeout, delta; 506 fd_set writefds; 507 ssize_t wlen, total; 508 int r; 509 510 if (fetchTimeout) { 511 FD_ZERO(&writefds); 512 gettimeofday(&timeout, NULL); 513 timeout.tv_sec += fetchTimeout; 514 } 515 516 total = 0; 517 while (iovcnt > 0) { 518 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) { 519 FD_SET(conn->sd, &writefds); 520 gettimeofday(&now, NULL); 521 delta.tv_sec = timeout.tv_sec - now.tv_sec; 522 delta.tv_usec = timeout.tv_usec - now.tv_usec; 523 if (delta.tv_usec < 0) { 524 delta.tv_usec += 1000000; 525 delta.tv_sec--; 526 } 527 if (delta.tv_sec < 0) { 528 errno = ETIMEDOUT; 529 fetch_syserr(); 530 return (-1); 531 } 532 errno = 0; 533 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta); 534 if (r == -1) { 535 if (errno == EINTR && fetchRestartCalls) 536 continue; 537 return (-1); 538 } 539 } 540 errno = 0; 541 #ifdef WITH_SSL 542 if (conn->ssl != NULL) 543 wlen = SSL_write(conn->ssl, 544 iov->iov_base, iov->iov_len); 545 else 546 #endif 547 wlen = writev(conn->sd, iov, iovcnt); 548 if (wlen == 0) { 549 /* we consider a short write a failure */ 550 errno = EPIPE; 551 fetch_syserr(); 552 return (-1); 553 } 554 if (wlen < 0) { 555 if (errno == EINTR && fetchRestartCalls) 556 continue; 557 return (-1); 558 } 559 total += wlen; 560 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) { 561 wlen -= iov->iov_len; 562 iov++; 563 iovcnt--; 564 } 565 if (iovcnt > 0) { 566 iov->iov_len -= wlen; 567 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen; 568 } 569 } 570 return (total); 571 } 572 573 574 /* 575 * Write a line of text to a connection w/ timeout 576 */ 577 int 578 fetch_putln(conn_t *conn, const char *str, size_t len) 579 { 580 struct iovec iov[2]; 581 int ret; 582 583 DEBUG(fprintf(stderr, ">>> %s\n", str)); 584 iov[0].iov_base = __DECONST(char *, str); 585 iov[0].iov_len = len; 586 iov[1].iov_base = __DECONST(char *, ENDL); 587 iov[1].iov_len = sizeof(ENDL); 588 if (len == 0) 589 ret = fetch_writev(conn, &iov[1], 1); 590 else 591 ret = fetch_writev(conn, iov, 2); 592 if (ret == -1) 593 return (-1); 594 return (0); 595 } 596 597 598 /* 599 * Close connection 600 */ 601 int 602 fetch_close(conn_t *conn) 603 { 604 int ret; 605 606 if (--conn->ref > 0) 607 return (0); 608 ret = close(conn->sd); 609 free(conn->buf); 610 free(conn); 611 return (ret); 612 } 613 614 615 /*** Directory-related utility functions *************************************/ 616 617 int 618 fetch_add_entry(struct url_ent **p, int *size, int *len, 619 const char *name, struct url_stat *us) 620 { 621 struct url_ent *tmp; 622 623 if (*p == NULL) { 624 *size = 0; 625 *len = 0; 626 } 627 628 if (*len >= *size - 1) { 629 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p)); 630 if (tmp == NULL) { 631 errno = ENOMEM; 632 fetch_syserr(); 633 return (-1); 634 } 635 *size = (*size * 2 + 1); 636 *p = tmp; 637 } 638 639 tmp = *p + *len; 640 snprintf(tmp->name, PATH_MAX, "%s", name); 641 memcpy(&tmp->stat, us, sizeof(*us)); 642 643 (*len)++; 644 (++tmp)->name[0] = 0; 645 646 return (0); 647 } 648 649 650 /*** Authentication-related utility functions ********************************/ 651 652 static const char * 653 fetch_read_word(FILE *f) 654 { 655 static char word[1024]; 656 657 if (fscanf(f, " %1023s ", word) != 1) 658 return (NULL); 659 return (word); 660 } 661 662 /* 663 * Get authentication data for a URL from .netrc 664 */ 665 int 666 fetch_netrc_auth(struct url *url) 667 { 668 char fn[PATH_MAX]; 669 const char *word; 670 char *p; 671 FILE *f; 672 673 if ((p = getenv("NETRC")) != NULL) { 674 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) { 675 fetch_info("$NETRC specifies a file name " 676 "longer than PATH_MAX"); 677 return (-1); 678 } 679 } else { 680 if ((p = getenv("HOME")) != NULL) { 681 struct passwd *pwd; 682 683 if ((pwd = getpwuid(getuid())) == NULL || 684 (p = pwd->pw_dir) == NULL) 685 return (-1); 686 } 687 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn)) 688 return (-1); 689 } 690 691 if ((f = fopen(fn, "r")) == NULL) 692 return (-1); 693 while ((word = fetch_read_word(f)) != NULL) { 694 if (strcmp(word, "default") == 0) { 695 DEBUG(fetch_info("Using default .netrc settings")); 696 break; 697 } 698 if (strcmp(word, "machine") == 0 && 699 (word = fetch_read_word(f)) != NULL && 700 strcasecmp(word, url->host) == 0) { 701 DEBUG(fetch_info("Using .netrc settings for %s", word)); 702 break; 703 } 704 } 705 if (word == NULL) 706 goto ferr; 707 while ((word = fetch_read_word(f)) != NULL) { 708 if (strcmp(word, "login") == 0) { 709 if ((word = fetch_read_word(f)) == NULL) 710 goto ferr; 711 if (snprintf(url->user, sizeof(url->user), 712 "%s", word) > (int)sizeof(url->user)) { 713 fetch_info("login name in .netrc is too long"); 714 url->user[0] = '\0'; 715 } 716 } else if (strcmp(word, "password") == 0) { 717 if ((word = fetch_read_word(f)) == NULL) 718 goto ferr; 719 if (snprintf(url->pwd, sizeof(url->pwd), 720 "%s", word) > (int)sizeof(url->pwd)) { 721 fetch_info("password in .netrc is too long"); 722 url->pwd[0] = '\0'; 723 } 724 } else if (strcmp(word, "account") == 0) { 725 if ((word = fetch_read_word(f)) == NULL) 726 goto ferr; 727 /* XXX not supported! */ 728 } else { 729 break; 730 } 731 } 732 fclose(f); 733 return (0); 734 ferr: 735 fclose(f); 736 return (-1); 737 } 738 739 /* 740 * The no_proxy environment variable specifies a set of domains for 741 * which the proxy should not be consulted; the contents is a comma-, 742 * or space-separated list of domain names. A single asterisk will 743 * override all proxy variables and no transactions will be proxied 744 * (for compatability with lynx and curl, see the discussion at 745 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>). 746 */ 747 int 748 fetch_no_proxy_match(const char *host) 749 { 750 const char *no_proxy, *p, *q; 751 size_t h_len, d_len; 752 753 if ((no_proxy = getenv("NO_PROXY")) == NULL && 754 (no_proxy = getenv("no_proxy")) == NULL) 755 return (0); 756 757 /* asterisk matches any hostname */ 758 if (strcmp(no_proxy, "*") == 0) 759 return (1); 760 761 h_len = strlen(host); 762 p = no_proxy; 763 do { 764 /* position p at the beginning of a domain suffix */ 765 while (*p == ',' || isspace((unsigned char)*p)) 766 p++; 767 768 /* position q at the first separator character */ 769 for (q = p; *q; ++q) 770 if (*q == ',' || isspace((unsigned char)*q)) 771 break; 772 773 d_len = q - p; 774 if (d_len > 0 && h_len >= d_len && 775 strncasecmp(host + h_len - d_len, 776 p, d_len) == 0) { 777 /* domain name matches */ 778 return (1); 779 } 780 781 p = q + 1; 782 } while (*q); 783 784 return (0); 785 } 786