2 * Copyright (c) 1998-2014 Dag-Erling Smørgrav
3 * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer
11 * in this position and unchanged.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
34 #include <sys/socket.h>
38 #include <netinet/in.h>
53 #include <openssl/x509v3.h>
60 /*** Local data **************************************************************/
63 * Error messages for resolver errors
65 static struct fetcherr netdb_errlist[] = {
67 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
69 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
70 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
71 { EAI_NONAME, FETCH_RESOLV, "No address record" },
72 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
76 static const char ENDL[2] = "\r\n";
79 /*** Error-reporting functions ***********************************************/
82 * Map error code to string
84 static struct fetcherr *
85 fetch_finderr(struct fetcherr *p, int e)
87 while (p->num != -1 && p->num != e)
96 fetch_seterr(struct fetcherr *p, int e)
98 p = fetch_finderr(p, e);
99 fetchLastErrCode = p->cat;
100 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
104 * Set error code according to errno
111 fetchLastErrCode = FETCH_OK;
118 fetchLastErrCode = FETCH_AUTH;
121 case EISDIR: /* XXX */
122 fetchLastErrCode = FETCH_UNAVAIL;
125 fetchLastErrCode = FETCH_MEMORY;
129 fetchLastErrCode = FETCH_TEMP;
132 fetchLastErrCode = FETCH_EXISTS;
135 fetchLastErrCode = FETCH_FULL;
143 fetchLastErrCode = FETCH_NETWORK;
147 fetchLastErrCode = FETCH_ABORT;
150 fetchLastErrCode = FETCH_TIMEOUT;
154 fetchLastErrCode = FETCH_DOWN;
157 fetchLastErrCode = FETCH_UNKNOWN;
159 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
164 * Emit status message
167 fetch_info(const char *fmt, ...)
172 vfprintf(stderr, fmt, ap);
178 /*** Network-related utility functions ***************************************/
181 * Return the default port for a scheme
184 fetch_default_port(const char *scheme)
188 if ((se = getservbyname(scheme, "tcp")) != NULL)
189 return (ntohs(se->s_port));
190 if (strcasecmp(scheme, SCHEME_FTP) == 0)
191 return (FTP_DEFAULT_PORT);
192 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
193 return (HTTP_DEFAULT_PORT);
198 * Return the default proxy port for a scheme
201 fetch_default_proxy_port(const char *scheme)
203 if (strcasecmp(scheme, SCHEME_FTP) == 0)
204 return (FTP_DEFAULT_PROXY_PORT);
205 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
206 return (HTTP_DEFAULT_PROXY_PORT);
212 * Create a connection for an existing descriptor.
220 /* allocate and fill connection structure */
221 if ((conn = calloc(1, sizeof(*conn))) == NULL)
223 fcntl(sd, F_SETFD, FD_CLOEXEC);
224 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
232 * Bump a connection's reference count.
235 fetch_ref(conn_t *conn)
244 * Bind a socket to a specific local address
247 fetch_bind(int sd, int af, const char *addr)
249 struct addrinfo hints, *res, *res0;
252 memset(&hints, 0, sizeof(hints));
253 hints.ai_family = af;
254 hints.ai_socktype = SOCK_STREAM;
255 hints.ai_protocol = 0;
256 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
258 for (res = res0; res; res = res->ai_next)
259 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
266 * Establish a TCP connection to the specified port on the specified host.
269 fetch_connect(const char *host, int port, int af, int verbose)
273 const char *bindaddr;
274 struct addrinfo hints, *res, *res0;
277 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
280 fetch_info("looking up %s", host);
282 /* look up host name and set up socket address structure */
283 snprintf(pbuf, sizeof(pbuf), "%d", port);
284 memset(&hints, 0, sizeof(hints));
285 hints.ai_family = af;
286 hints.ai_socktype = SOCK_STREAM;
287 hints.ai_protocol = 0;
288 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
292 bindaddr = getenv("FETCH_BIND_ADDRESS");
295 fetch_info("connecting to %s:%d", host, port);
298 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
299 if ((sd = socket(res->ai_family, res->ai_socktype,
300 res->ai_protocol)) == -1)
302 if (bindaddr != NULL && *bindaddr != '\0' &&
303 fetch_bind(sd, res->ai_family, bindaddr) != 0) {
304 fetch_info("failed to bind to '%s'", bindaddr);
308 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
309 fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
319 if ((conn = fetch_reopen(sd)) == NULL) {
328 * Convert characters A-Z to lowercase (intentionally avoid any locale
329 * specific conversions).
332 fetch_ssl_tolower(char in)
334 if (in >= 'A' && in <= 'Z')
341 * isalpha implementation that intentionally avoids any locale specific
345 fetch_ssl_isalpha(char in)
347 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
351 * Check if passed hostnames a and b are equal.
354 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
361 for (i = 0; i < alen; ++i) {
362 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
369 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
370 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
371 * numeric characters. Double hyphens (like they're found in IDN a-labels
372 * 'xn--') are not allowed. Empty labels are invalid.
375 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
379 if (!len || l[0] == '-' || l[len-1] == '-')
381 for (i = 0; i < len; ++i) {
382 if (!isdigit(l[i]) &&
383 !fetch_ssl_isalpha(l[i]) &&
384 !(l[i] == '*' && wcok) &&
385 !(l[i] == '-' && l[i - 1] != '-'))
392 * Check if host name consists only of numbers. This might indicate an IP
393 * address, which is not a good idea for CN wildcard comparison.
396 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
400 for (i = 0; i < len; ++i) {
401 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
409 * Check if the host name h passed matches the pattern passed in m which
410 * is usually part of subjectAltName or CN of a certificate presented to
411 * the client. This includes wildcard matching. The algorithm is based on
412 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
415 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
418 int delta, hdotidx, mdot1idx, wcidx;
419 const char *hdot, *mdot1, *mdot2;
420 const char *wc; /* wildcard */
422 if (!(h && *h && m && *m))
424 if ((wc = strnstr(m, "*", mlen)) == NULL)
425 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
427 /* hostname should not be just dots and numbers */
428 if (fetch_ssl_hname_is_only_numbers(h, hlen))
430 /* only one wildcard allowed in pattern */
431 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
434 * there must be at least two more domain labels and
435 * wildcard has to be in the leftmost label (RFC6125)
437 mdot1 = strnstr(m, ".", mlen);
438 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
440 mdot1idx = mdot1 - m;
441 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
442 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
444 /* hostname must contain a dot and not be the 1st char */
445 hdot = strnstr(h, ".", hlen);
446 if (hdot == NULL || hdot == h)
450 * host part of hostname must be at least as long as
451 * pattern it's supposed to match
453 if (hdotidx < mdot1idx)
456 * don't allow wildcards in non-traditional domain names
457 * (IDN, A-label, U-label...)
459 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
460 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
462 /* match domain part (part after first dot) */
463 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
466 /* match part left of wildcard */
467 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
469 /* match part right of wildcard */
470 delta = mdot1idx - wcidx - 1;
471 if (!fetch_ssl_hname_equal(hdot - delta, delta,
472 mdot1 - delta, delta))
474 /* all tests succeded, it's a match */
479 * Get numeric host address info - returns NULL if host was not an IP
480 * address. The caller is responsible for deallocation using
483 static struct addrinfo *
484 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
486 struct addrinfo hints, *res;
489 host = (char *)malloc(len + 1);
490 memcpy(host, hostname, len);
492 memset(&hints, 0, sizeof(hints));
493 hints.ai_family = PF_UNSPEC;
494 hints.ai_socktype = SOCK_STREAM;
495 hints.ai_protocol = 0;
496 hints.ai_flags = AI_NUMERICHOST;
497 /* port is not relevant for this purpose */
498 if (getaddrinfo(host, "443", &hints, &res) != 0)
505 * Compare ip address in addrinfo with address passes.
508 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
513 if (lhost->ai_family == AF_INET && rhostlen == 4) {
514 left = (void *)&((struct sockaddr_in*)(void *)
515 lhost->ai_addr)->sin_addr.s_addr;
517 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
518 left = (void *)&((struct sockaddr_in6 *)(void *)
519 lhost->ai_addr)->sin6_addr;
523 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
527 * Compare ip address in addrinfo with host passed. If host is not an IP
528 * address, comparison will fail.
531 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
534 struct addrinfo *raddr;
539 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
540 return 0; /* not a numeric host */
542 if (laddr->ai_family == raddr->ai_family) {
543 if (laddr->ai_family == AF_INET) {
544 rip = (char *)&((struct sockaddr_in *)(void *)
545 raddr->ai_addr)->sin_addr.s_addr;
546 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
548 } else if (laddr->ai_family == AF_INET6) {
549 rip = (char *)&((struct sockaddr_in6 *)(void *)
550 raddr->ai_addr)->sin6_addr;
551 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
561 * Verify server certificate by subjectAltName.
564 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
565 const char *host, struct addrinfo *ip)
567 const GENERAL_NAME *name;
572 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
573 #if OPENSSL_VERSION_NUMBER < 0x10000000L
575 * This is a workaround, since the following line causes
576 * alignment issues in clang:
577 * name = sk_GENERAL_NAME_value(altnames, i);
578 * OpenSSL explicitly warns not to use those macros
579 * directly, but there isn't much choice (and there
580 * shouldn't be any ill side effects)
582 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
584 name = sk_GENERAL_NAME_value(altnames, i);
586 ns = (const char *)ASN1_STRING_data(name->d.ia5);
587 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
589 if (name->type == GEN_DNS && ip == NULL &&
590 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
592 else if (name->type == GEN_IPADD && ip != NULL &&
593 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
600 * Verify server certificate by CN.
603 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
606 ASN1_STRING *namedata;
607 X509_NAME_ENTRY *nameentry;
608 int cnlen, lastpos, loc, ret;
615 /* get most specific CN (last entry in list) and compare */
616 while ((lastpos = X509_NAME_get_index_by_NID(subject,
617 NID_commonName, lastpos)) != -1)
621 nameentry = X509_NAME_get_entry(subject, loc);
622 namedata = X509_NAME_ENTRY_get_data(nameentry);
623 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
625 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
627 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
635 * Verify that server certificate subjectAltName/CN matches
636 * hostname. First check, if there are alternative subject names. If yes,
637 * those have to match. Only if those don't exist it falls back to
638 * checking the subject's CN.
641 fetch_ssl_verify_hname(X509 *cert, const char *host)
644 STACK_OF(GENERAL_NAME) *altnames;
649 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
650 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
653 if (altnames != NULL) {
654 ret = fetch_ssl_verify_altname(altnames, host, ip);
656 subject = X509_get_subject_name(cert);
658 ret = fetch_ssl_verify_cn(subject, host, ip);
663 if (altnames != NULL)
664 GENERAL_NAMES_free(altnames);
669 * Configure transport security layer based on environment.
672 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
674 long ssl_ctx_options;
676 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET;
677 if (getenv("SSL_ALLOW_SSL3") == NULL)
678 ssl_ctx_options |= SSL_OP_NO_SSLv3;
679 if (getenv("SSL_NO_TLS1") != NULL)
680 ssl_ctx_options |= SSL_OP_NO_TLSv1;
682 fetch_info("SSL options: %lx", ssl_ctx_options);
683 SSL_CTX_set_options(ctx, ssl_ctx_options);
688 * Configure peer verification based on environment.
690 #define LOCAL_CERT_FILE "/usr/local/etc/ssl/cert.pem"
691 #define BASE_CERT_FILE "/etc/ssl/cert.pem"
693 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
695 X509_LOOKUP *crl_lookup;
696 X509_STORE *crl_store;
697 const char *ca_cert_file, *ca_cert_path, *crl_file;
699 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
700 ca_cert_file = getenv("SSL_CA_CERT_FILE");
701 if (ca_cert_file == NULL &&
702 access(LOCAL_CERT_FILE, R_OK) == 0)
703 ca_cert_file = LOCAL_CERT_FILE;
704 if (ca_cert_file == NULL &&
705 access(BASE_CERT_FILE, R_OK) == 0)
706 ca_cert_file = BASE_CERT_FILE;
707 ca_cert_path = getenv("SSL_CA_CERT_PATH");
709 fetch_info("Peer verification enabled");
710 if (ca_cert_file != NULL)
711 fetch_info("Using CA cert file: %s",
713 if (ca_cert_path != NULL)
714 fetch_info("Using CA cert path: %s",
716 if (ca_cert_file == NULL && ca_cert_path == NULL)
717 fetch_info("Using OpenSSL default "
718 "CA cert file and path");
720 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
721 fetch_ssl_cb_verify_crt);
722 if (ca_cert_file != NULL || ca_cert_path != NULL)
723 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
726 SSL_CTX_set_default_verify_paths(ctx);
727 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
729 fetch_info("Using CRL file: %s", crl_file);
730 crl_store = SSL_CTX_get_cert_store(ctx);
731 crl_lookup = X509_STORE_add_lookup(crl_store,
733 if (crl_lookup == NULL ||
734 !X509_load_crl_file(crl_lookup, crl_file,
735 X509_FILETYPE_PEM)) {
737 "Could not load CRL file %s\n",
741 X509_STORE_set_flags(crl_store,
742 X509_V_FLAG_CRL_CHECK |
743 X509_V_FLAG_CRL_CHECK_ALL);
750 * Configure client certificate based on environment.
753 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
755 const char *client_cert_file, *client_key_file;
757 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
758 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
759 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
761 fetch_info("Using client cert file: %s",
763 fetch_info("Using client key file: %s",
766 if (SSL_CTX_use_certificate_chain_file(ctx,
767 client_cert_file) != 1) {
769 "Could not load client certificate %s\n",
773 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
774 SSL_FILETYPE_PEM) != 1) {
776 "Could not load client key %s\n",
785 * Callback for SSL certificate verification, this is called on server
786 * cert verification. It takes no decision, but informs the user in case
787 * verification failed.
790 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
798 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
799 (name = X509_get_subject_name(crt)) != NULL)
800 str = X509_NAME_oneline(name, 0, 0);
801 fprintf(stderr, "Certificate verification failed for %s\n",
802 str != NULL ? str : "no relevant certificate");
811 * Enable SSL on a connection.
814 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
821 /* Init the SSL library and context */
822 if (!SSL_library_init()){
823 fprintf(stderr, "SSL library init failed\n");
827 SSL_load_error_strings();
829 conn->ssl_meth = SSLv23_client_method();
830 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
831 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
833 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
834 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
836 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
839 conn->ssl = SSL_new(conn->ssl_ctx);
840 if (conn->ssl == NULL) {
841 fprintf(stderr, "SSL context creation failed\n");
844 SSL_set_fd(conn->ssl, conn->sd);
846 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
847 if (!SSL_set_tlsext_host_name(conn->ssl,
848 __DECONST(struct url *, URL)->host)) {
850 "TLS server name indication extension failed for host %s\n",
855 while ((ret = SSL_connect(conn->ssl)) == -1) {
856 ssl_err = SSL_get_error(conn->ssl, ret);
857 if (ssl_err != SSL_ERROR_WANT_READ &&
858 ssl_err != SSL_ERROR_WANT_WRITE) {
859 ERR_print_errors_fp(stderr);
863 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
865 if (conn->ssl_cert == NULL) {
866 fprintf(stderr, "No server SSL certificate\n");
870 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
872 fetch_info("Verify hostname");
873 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
875 "SSL certificate subject doesn't match host %s\n",
882 fetch_info("%s connection established using %s",
883 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
884 name = X509_get_subject_name(conn->ssl_cert);
885 str = X509_NAME_oneline(name, 0, 0);
886 fetch_info("Certificate subject: %s", str);
888 name = X509_get_issuer_name(conn->ssl_cert);
889 str = X509_NAME_oneline(name, 0, 0);
890 fetch_info("Certificate issuer: %s", str);
898 fprintf(stderr, "SSL support disabled\n");
903 #define FETCH_READ_WAIT -2
904 #define FETCH_READ_ERROR -1
905 #define FETCH_READ_DONE 0
909 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
914 rlen = SSL_read(ssl, buf, len);
916 ssl_err = SSL_get_error(ssl, rlen);
917 if (ssl_err == SSL_ERROR_WANT_READ ||
918 ssl_err == SSL_ERROR_WANT_WRITE) {
919 return (FETCH_READ_WAIT);
921 ERR_print_errors_fp(stderr);
922 return (FETCH_READ_ERROR);
930 fetch_socket_read(int sd, char *buf, size_t len)
934 rlen = read(sd, buf, len);
936 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
937 return (FETCH_READ_WAIT);
939 return (FETCH_READ_ERROR);
945 * Read a character from a connection w/ timeout
948 fetch_read(conn_t *conn, char *buf, size_t len)
950 struct timeval now, timeout, delta;
955 if (fetchTimeout > 0) {
956 gettimeofday(&timeout, NULL);
957 timeout.tv_sec += fetchTimeout;
961 memset(&pfd, 0, sizeof pfd);
963 pfd.events = POLLIN | POLLERR;
967 * The socket is non-blocking. Instead of the canonical
968 * poll() -> read(), we do the following:
970 * 1) call read() or SSL_read().
971 * 2) if we received some data, return it.
972 * 3) if an error occurred, return -1.
973 * 4) if read() or SSL_read() signaled EOF, return.
974 * 5) if we did not receive any data but we're not at EOF,
977 * In the SSL case, this is necessary because if we
978 * receive a close notification, we have to call
979 * SSL_read() one additional time after we've read
980 * everything we received.
982 * In the non-SSL case, it may improve performance (very
983 * slightly) when reading small amounts of data.
986 if (conn->ssl != NULL)
987 rlen = fetch_ssl_read(conn->ssl, buf, len);
990 rlen = fetch_socket_read(conn->sd, buf, len);
993 } else if (rlen == FETCH_READ_ERROR) {
997 // assert(rlen == FETCH_READ_WAIT);
998 if (fetchTimeout > 0) {
999 gettimeofday(&now, NULL);
1000 if (!timercmp(&timeout, &now, >)) {
1005 timersub(&timeout, &now, &delta);
1006 deltams = delta.tv_sec * 1000 +
1007 delta.tv_usec / 1000;;
1011 if (poll(&pfd, 1, deltams) < 0) {
1012 if (errno == EINTR && fetchRestartCalls)
1023 * Read a line of text from a connection w/ timeout
1025 #define MIN_BUF_SIZE 1024
1028 fetch_getln(conn_t *conn)
1035 if (conn->buf == NULL) {
1036 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1040 conn->bufsize = MIN_BUF_SIZE;
1043 conn->buf[0] = '\0';
1047 len = fetch_read(conn, &c, 1);
1052 conn->buf[conn->buflen++] = c;
1053 if (conn->buflen == conn->bufsize) {
1055 tmpsize = conn->bufsize * 2 + 1;
1056 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1061 conn->bufsize = tmpsize;
1063 } while (c != '\n');
1065 conn->buf[conn->buflen] = '\0';
1066 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
1072 * Write to a connection w/ timeout
1075 fetch_write(conn_t *conn, const char *buf, size_t len)
1079 iov.iov_base = __DECONST(char *, buf);
1081 return fetch_writev(conn, &iov, 1);
1085 * Write a vector to a connection w/ timeout
1086 * Note: can modify the iovec.
1089 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1091 struct timeval now, timeout, delta;
1093 ssize_t wlen, total;
1096 memset(&pfd, 0, sizeof pfd);
1099 pfd.events = POLLOUT | POLLERR;
1100 gettimeofday(&timeout, NULL);
1101 timeout.tv_sec += fetchTimeout;
1105 while (iovcnt > 0) {
1106 while (fetchTimeout && pfd.revents == 0) {
1107 gettimeofday(&now, NULL);
1108 if (!timercmp(&timeout, &now, >)) {
1113 timersub(&timeout, &now, &delta);
1114 deltams = delta.tv_sec * 1000 +
1115 delta.tv_usec / 1000;
1118 if (poll(&pfd, 1, deltams) < 0) {
1119 /* POSIX compliance */
1120 if (errno == EAGAIN)
1122 if (errno == EINTR && fetchRestartCalls)
1129 if (conn->ssl != NULL)
1130 wlen = SSL_write(conn->ssl,
1131 iov->iov_base, iov->iov_len);
1134 wlen = writev(conn->sd, iov, iovcnt);
1136 /* we consider a short write a failure */
1137 /* XXX perhaps we shouldn't in the SSL case */
1143 if (errno == EINTR && fetchRestartCalls)
1148 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1149 wlen -= iov->iov_len;
1154 iov->iov_len -= wlen;
1155 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1163 * Write a line of text to a connection w/ timeout
1166 fetch_putln(conn_t *conn, const char *str, size_t len)
1168 struct iovec iov[2];
1171 DEBUG(fprintf(stderr, ">>> %s\n", str));
1172 iov[0].iov_base = __DECONST(char *, str);
1173 iov[0].iov_len = len;
1174 iov[1].iov_base = __DECONST(char *, ENDL);
1175 iov[1].iov_len = sizeof(ENDL);
1177 ret = fetch_writev(conn, &iov[1], 1);
1179 ret = fetch_writev(conn, iov, 2);
1190 fetch_close(conn_t *conn)
1194 if (--conn->ref > 0)
1198 SSL_shutdown(conn->ssl);
1199 SSL_set_connect_state(conn->ssl);
1200 SSL_free(conn->ssl);
1203 if (conn->ssl_ctx) {
1204 SSL_CTX_free(conn->ssl_ctx);
1205 conn->ssl_ctx = NULL;
1207 if (conn->ssl_cert) {
1208 X509_free(conn->ssl_cert);
1209 conn->ssl_cert = NULL;
1212 ret = close(conn->sd);
1219 /*** Directory-related utility functions *************************************/
1222 fetch_add_entry(struct url_ent **p, int *size, int *len,
1223 const char *name, struct url_stat *us)
1225 struct url_ent *tmp;
1232 if (*len >= *size - 1) {
1233 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
1239 *size = (*size * 2 + 1);
1244 snprintf(tmp->name, PATH_MAX, "%s", name);
1245 memcpy(&tmp->stat, us, sizeof(*us));
1248 (++tmp)->name[0] = 0;
1254 /*** Authentication-related utility functions ********************************/
1257 fetch_read_word(FILE *f)
1259 static char word[1024];
1261 if (fscanf(f, " %1023s ", word) != 1)
1267 * Get authentication data for a URL from .netrc
1270 fetch_netrc_auth(struct url *url)
1277 if ((p = getenv("NETRC")) != NULL) {
1278 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1279 fetch_info("$NETRC specifies a file name "
1280 "longer than PATH_MAX");
1284 if ((p = getenv("HOME")) != NULL) {
1287 if ((pwd = getpwuid(getuid())) == NULL ||
1288 (p = pwd->pw_dir) == NULL)
1291 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1295 if ((f = fopen(fn, "r")) == NULL)
1297 while ((word = fetch_read_word(f)) != NULL) {
1298 if (strcmp(word, "default") == 0) {
1299 DEBUG(fetch_info("Using default .netrc settings"));
1302 if (strcmp(word, "machine") == 0 &&
1303 (word = fetch_read_word(f)) != NULL &&
1304 strcasecmp(word, url->host) == 0) {
1305 DEBUG(fetch_info("Using .netrc settings for %s", word));
1311 while ((word = fetch_read_word(f)) != NULL) {
1312 if (strcmp(word, "login") == 0) {
1313 if ((word = fetch_read_word(f)) == NULL)
1315 if (snprintf(url->user, sizeof(url->user),
1316 "%s", word) > (int)sizeof(url->user)) {
1317 fetch_info("login name in .netrc is too long");
1318 url->user[0] = '\0';
1320 } else if (strcmp(word, "password") == 0) {
1321 if ((word = fetch_read_word(f)) == NULL)
1323 if (snprintf(url->pwd, sizeof(url->pwd),
1324 "%s", word) > (int)sizeof(url->pwd)) {
1325 fetch_info("password in .netrc is too long");
1328 } else if (strcmp(word, "account") == 0) {
1329 if ((word = fetch_read_word(f)) == NULL)
1331 /* XXX not supported! */
1344 * The no_proxy environment variable specifies a set of domains for
1345 * which the proxy should not be consulted; the contents is a comma-,
1346 * or space-separated list of domain names. A single asterisk will
1347 * override all proxy variables and no transactions will be proxied
1348 * (for compatability with lynx and curl, see the discussion at
1349 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1352 fetch_no_proxy_match(const char *host)
1354 const char *no_proxy, *p, *q;
1355 size_t h_len, d_len;
1357 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1358 (no_proxy = getenv("no_proxy")) == NULL)
1361 /* asterisk matches any hostname */
1362 if (strcmp(no_proxy, "*") == 0)
1365 h_len = strlen(host);
1368 /* position p at the beginning of a domain suffix */
1369 while (*p == ',' || isspace((unsigned char)*p))
1372 /* position q at the first separator character */
1373 for (q = p; *q; ++q)
1374 if (*q == ',' || isspace((unsigned char)*q))
1378 if (d_len > 0 && h_len >= d_len &&
1379 strncasecmp(host + h_len - d_len,
1381 /* domain name matches */