2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1998-2016 Dag-Erling Smørgrav
5 * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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
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.
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/socket.h>
40 #include <netinet/in.h>
55 #include <openssl/x509v3.h>
62 /*** Local data **************************************************************/
65 * Error messages for resolver errors
67 static struct fetcherr netdb_errlist[] = {
69 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
71 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
72 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
73 { EAI_NONAME, FETCH_RESOLV, "No address record" },
74 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
78 static const char ENDL[2] = "\r\n";
81 /*** Error-reporting functions ***********************************************/
84 * Map error code to string
86 static struct fetcherr *
87 fetch_finderr(struct fetcherr *p, int e)
89 while (p->num != -1 && p->num != e)
98 fetch_seterr(struct fetcherr *p, int e)
100 p = fetch_finderr(p, e);
101 fetchLastErrCode = p->cat;
102 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
106 * Set error code according to errno
113 fetchLastErrCode = FETCH_OK;
120 fetchLastErrCode = FETCH_AUTH;
123 case EISDIR: /* XXX */
124 fetchLastErrCode = FETCH_UNAVAIL;
127 fetchLastErrCode = FETCH_MEMORY;
131 fetchLastErrCode = FETCH_TEMP;
134 fetchLastErrCode = FETCH_EXISTS;
137 fetchLastErrCode = FETCH_FULL;
145 fetchLastErrCode = FETCH_NETWORK;
149 fetchLastErrCode = FETCH_ABORT;
152 fetchLastErrCode = FETCH_TIMEOUT;
156 fetchLastErrCode = FETCH_DOWN;
159 fetchLastErrCode = FETCH_UNKNOWN;
161 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
166 * Emit status message
169 fetch_info(const char *fmt, ...)
174 vfprintf(stderr, fmt, ap);
180 /*** Network-related utility functions ***************************************/
183 * Return the default port for a scheme
186 fetch_default_port(const char *scheme)
190 if ((se = getservbyname(scheme, "tcp")) != NULL)
191 return (ntohs(se->s_port));
192 if (strcmp(scheme, SCHEME_FTP) == 0)
193 return (FTP_DEFAULT_PORT);
194 if (strcmp(scheme, SCHEME_HTTP) == 0)
195 return (HTTP_DEFAULT_PORT);
200 * Return the default proxy port for a scheme
203 fetch_default_proxy_port(const char *scheme)
205 if (strcmp(scheme, SCHEME_FTP) == 0)
206 return (FTP_DEFAULT_PROXY_PORT);
207 if (strcmp(scheme, SCHEME_HTTP) == 0)
208 return (HTTP_DEFAULT_PROXY_PORT);
214 * Create a connection for an existing descriptor.
222 /* allocate and fill connection structure */
223 if ((conn = calloc(1, sizeof(*conn))) == NULL)
225 fcntl(sd, F_SETFD, FD_CLOEXEC);
226 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
234 * Bump a connection's reference count.
237 fetch_ref(conn_t *conn)
249 fetch_resolve(const char *addr, int port, int af)
251 char hbuf[256], sbuf[8];
252 struct addrinfo hints, *res;
253 const char *hb, *he, *sep;
254 const char *host, *service;
257 /* first, check for a bracketed IPv6 address */
260 if ((sep = strchr(hb, ']')) == NULL) {
267 sep = strchrnul(hb, ':');
271 /* see if we need to copy the host name */
273 len = snprintf(hbuf, sizeof(hbuf),
274 "%.*s", (int)(he - hb), hb);
277 if (len >= (int)sizeof(hbuf)) {
278 errno = ENAMETOOLONG;
286 /* was it followed by a service name? */
287 if (*sep == '\0' && port != 0) {
288 if (port < 1 || port > 65535) {
292 if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0)
295 } else if (*sep != '\0') {
302 memset(&hints, 0, sizeof(hints));
303 hints.ai_family = af;
304 hints.ai_socktype = SOCK_STREAM;
305 hints.ai_flags = AI_ADDRCONFIG;
306 if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
319 * Bind a socket to a specific local address
322 fetch_bind(int sd, int af, const char *addr)
324 struct addrinfo *cliai, *ai;
327 if ((cliai = fetch_resolve(addr, 0, af)) == NULL)
329 for (ai = cliai; ai != NULL; ai = ai->ai_next)
330 if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0)
335 return (err == 0 ? 0 : -1);
340 * Establish a TCP connection to the specified port on the specified host.
343 fetch_connect(const char *host, int port, int af, int verbose)
345 struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai;
346 const char *bindaddr;
348 int err = 0, sd = -1;
350 DEBUGF("---> %s:%d\n", host, port);
352 /* resolve server address */
354 fetch_info("resolving server address: %s:%d", host, port);
355 if ((sais = fetch_resolve(host, port, af)) == NULL)
358 /* resolve client address */
359 bindaddr = getenv("FETCH_BIND_ADDRESS");
360 if (bindaddr != NULL && *bindaddr != '\0') {
362 fetch_info("resolving client address: %s", bindaddr);
363 if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL)
367 /* try each server address in turn */
368 for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) {
370 if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0)
372 /* attempt to bind to client address */
373 for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) {
374 if (cai->ai_family != sai->ai_family)
376 if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0)
381 fetch_info("failed to bind to %s", bindaddr);
384 /* attempt to connect to server address */
385 if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0)
387 /* clean up before next attempt */
393 fetch_info("failed to connect to %s:%d", host, port);
397 if ((conn = fetch_reopen(sd)) == NULL)
419 * Convert characters A-Z to lowercase (intentionally avoid any locale
420 * specific conversions).
423 fetch_ssl_tolower(char in)
425 if (in >= 'A' && in <= 'Z')
432 * isalpha implementation that intentionally avoids any locale specific
436 fetch_ssl_isalpha(char in)
438 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
442 * Check if passed hostnames a and b are equal.
445 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
452 for (i = 0; i < alen; ++i) {
453 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
460 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
461 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
462 * numeric characters. Double hyphens (like they're found in IDN a-labels
463 * 'xn--') are not allowed. Empty labels are invalid.
466 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
470 if (!len || l[0] == '-' || l[len-1] == '-')
472 for (i = 0; i < len; ++i) {
473 if (!isdigit(l[i]) &&
474 !fetch_ssl_isalpha(l[i]) &&
475 !(l[i] == '*' && wcok) &&
476 !(l[i] == '-' && l[i - 1] != '-'))
483 * Check if host name consists only of numbers. This might indicate an IP
484 * address, which is not a good idea for CN wildcard comparison.
487 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
491 for (i = 0; i < len; ++i) {
492 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
500 * Check if the host name h passed matches the pattern passed in m which
501 * is usually part of subjectAltName or CN of a certificate presented to
502 * the client. This includes wildcard matching. The algorithm is based on
503 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
506 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
509 int delta, hdotidx, mdot1idx, wcidx;
510 const char *hdot, *mdot1, *mdot2;
511 const char *wc; /* wildcard */
513 if (!(h && *h && m && *m))
515 if ((wc = strnstr(m, "*", mlen)) == NULL)
516 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
518 /* hostname should not be just dots and numbers */
519 if (fetch_ssl_hname_is_only_numbers(h, hlen))
521 /* only one wildcard allowed in pattern */
522 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
525 * there must be at least two more domain labels and
526 * wildcard has to be in the leftmost label (RFC6125)
528 mdot1 = strnstr(m, ".", mlen);
529 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
531 mdot1idx = mdot1 - m;
532 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
533 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
535 /* hostname must contain a dot and not be the 1st char */
536 hdot = strnstr(h, ".", hlen);
537 if (hdot == NULL || hdot == h)
541 * host part of hostname must be at least as long as
542 * pattern it's supposed to match
544 if (hdotidx < mdot1idx)
547 * don't allow wildcards in non-traditional domain names
548 * (IDN, A-label, U-label...)
550 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
551 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
553 /* match domain part (part after first dot) */
554 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
557 /* match part left of wildcard */
558 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
560 /* match part right of wildcard */
561 delta = mdot1idx - wcidx - 1;
562 if (!fetch_ssl_hname_equal(hdot - delta, delta,
563 mdot1 - delta, delta))
565 /* all tests succeeded, it's a match */
570 * Get numeric host address info - returns NULL if host was not an IP
571 * address. The caller is responsible for deallocation using
574 static struct addrinfo *
575 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
577 struct addrinfo hints, *res;
580 host = (char *)malloc(len + 1);
581 memcpy(host, hostname, len);
583 memset(&hints, 0, sizeof(hints));
584 hints.ai_family = PF_UNSPEC;
585 hints.ai_socktype = SOCK_STREAM;
586 hints.ai_protocol = 0;
587 hints.ai_flags = AI_NUMERICHOST;
588 /* port is not relevant for this purpose */
589 if (getaddrinfo(host, "443", &hints, &res) != 0)
596 * Compare ip address in addrinfo with address passes.
599 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
604 if (lhost->ai_family == AF_INET && rhostlen == 4) {
605 left = (void *)&((struct sockaddr_in*)(void *)
606 lhost->ai_addr)->sin_addr.s_addr;
608 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
609 left = (void *)&((struct sockaddr_in6 *)(void *)
610 lhost->ai_addr)->sin6_addr;
614 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
618 * Compare ip address in addrinfo with host passed. If host is not an IP
619 * address, comparison will fail.
622 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
625 struct addrinfo *raddr;
630 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
631 return 0; /* not a numeric host */
633 if (laddr->ai_family == raddr->ai_family) {
634 if (laddr->ai_family == AF_INET) {
635 rip = (char *)&((struct sockaddr_in *)(void *)
636 raddr->ai_addr)->sin_addr.s_addr;
637 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
639 } else if (laddr->ai_family == AF_INET6) {
640 rip = (char *)&((struct sockaddr_in6 *)(void *)
641 raddr->ai_addr)->sin6_addr;
642 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
652 * Verify server certificate by subjectAltName.
655 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
656 const char *host, struct addrinfo *ip)
658 const GENERAL_NAME *name;
663 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
664 #if OPENSSL_VERSION_NUMBER < 0x10000000L
666 * This is a workaround, since the following line causes
667 * alignment issues in clang:
668 * name = sk_GENERAL_NAME_value(altnames, i);
669 * OpenSSL explicitly warns not to use those macros
670 * directly, but there isn't much choice (and there
671 * shouldn't be any ill side effects)
673 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
675 name = sk_GENERAL_NAME_value(altnames, i);
677 #if OPENSSL_VERSION_NUMBER < 0x10100000L
678 ns = (const char *)ASN1_STRING_data(name->d.ia5);
680 ns = (const char *)ASN1_STRING_get0_data(name->d.ia5);
682 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
684 if (name->type == GEN_DNS && ip == NULL &&
685 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
687 else if (name->type == GEN_IPADD && ip != NULL &&
688 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
695 * Verify server certificate by CN.
698 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
701 ASN1_STRING *namedata;
702 X509_NAME_ENTRY *nameentry;
703 int cnlen, lastpos, loc, ret;
710 /* get most specific CN (last entry in list) and compare */
711 while ((lastpos = X509_NAME_get_index_by_NID(subject,
712 NID_commonName, lastpos)) != -1)
716 nameentry = X509_NAME_get_entry(subject, loc);
717 namedata = X509_NAME_ENTRY_get_data(nameentry);
718 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
720 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
722 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
730 * Verify that server certificate subjectAltName/CN matches
731 * hostname. First check, if there are alternative subject names. If yes,
732 * those have to match. Only if those don't exist it falls back to
733 * checking the subject's CN.
736 fetch_ssl_verify_hname(X509 *cert, const char *host)
739 STACK_OF(GENERAL_NAME) *altnames;
744 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
745 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
748 if (altnames != NULL) {
749 ret = fetch_ssl_verify_altname(altnames, host, ip);
751 subject = X509_get_subject_name(cert);
753 ret = fetch_ssl_verify_cn(subject, host, ip);
758 if (altnames != NULL)
759 GENERAL_NAMES_free(altnames);
764 * Configure transport security layer based on environment.
767 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
769 long ssl_ctx_options;
771 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET;
772 if (getenv("SSL_ALLOW_SSL3") == NULL)
773 ssl_ctx_options |= SSL_OP_NO_SSLv3;
774 if (getenv("SSL_NO_TLS1") != NULL)
775 ssl_ctx_options |= SSL_OP_NO_TLSv1;
776 if (getenv("SSL_NO_TLS1_1") != NULL)
777 ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
778 if (getenv("SSL_NO_TLS1_2") != NULL)
779 ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
781 fetch_info("SSL options: %lx", ssl_ctx_options);
782 SSL_CTX_set_options(ctx, ssl_ctx_options);
787 * Configure peer verification based on environment.
789 #define LOCAL_CERT_FILE "/usr/local/etc/ssl/cert.pem"
790 #define BASE_CERT_FILE "/etc/ssl/cert.pem"
792 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
794 X509_LOOKUP *crl_lookup;
795 X509_STORE *crl_store;
796 const char *ca_cert_file, *ca_cert_path, *crl_file;
798 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
799 ca_cert_file = getenv("SSL_CA_CERT_FILE");
800 if (ca_cert_file == NULL &&
801 access(LOCAL_CERT_FILE, R_OK) == 0)
802 ca_cert_file = LOCAL_CERT_FILE;
803 if (ca_cert_file == NULL &&
804 access(BASE_CERT_FILE, R_OK) == 0)
805 ca_cert_file = BASE_CERT_FILE;
806 ca_cert_path = getenv("SSL_CA_CERT_PATH");
808 fetch_info("Peer verification enabled");
809 if (ca_cert_file != NULL)
810 fetch_info("Using CA cert file: %s",
812 if (ca_cert_path != NULL)
813 fetch_info("Using CA cert path: %s",
815 if (ca_cert_file == NULL && ca_cert_path == NULL)
816 fetch_info("Using OpenSSL default "
817 "CA cert file and path");
819 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
820 fetch_ssl_cb_verify_crt);
821 if (ca_cert_file != NULL || ca_cert_path != NULL)
822 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
825 SSL_CTX_set_default_verify_paths(ctx);
826 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
828 fetch_info("Using CRL file: %s", crl_file);
829 crl_store = SSL_CTX_get_cert_store(ctx);
830 crl_lookup = X509_STORE_add_lookup(crl_store,
832 if (crl_lookup == NULL ||
833 !X509_load_crl_file(crl_lookup, crl_file,
834 X509_FILETYPE_PEM)) {
836 "Could not load CRL file %s\n",
840 X509_STORE_set_flags(crl_store,
841 X509_V_FLAG_CRL_CHECK |
842 X509_V_FLAG_CRL_CHECK_ALL);
849 * Configure client certificate based on environment.
852 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
854 const char *client_cert_file, *client_key_file;
856 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
857 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
858 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
860 fetch_info("Using client cert file: %s",
862 fetch_info("Using client key file: %s",
865 if (SSL_CTX_use_certificate_chain_file(ctx,
866 client_cert_file) != 1) {
868 "Could not load client certificate %s\n",
872 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
873 SSL_FILETYPE_PEM) != 1) {
875 "Could not load client key %s\n",
884 * Callback for SSL certificate verification, this is called on server
885 * cert verification. It takes no decision, but informs the user in case
886 * verification failed.
889 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
897 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
898 (name = X509_get_subject_name(crt)) != NULL)
899 str = X509_NAME_oneline(name, 0, 0);
900 fprintf(stderr, "Certificate verification failed for %s\n",
901 str != NULL ? str : "no relevant certificate");
910 * Enable SSL on a connection.
913 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
920 /* Init the SSL library and context */
921 if (!SSL_library_init()){
922 fprintf(stderr, "SSL library init failed\n");
926 SSL_load_error_strings();
928 conn->ssl_meth = SSLv23_client_method();
929 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
930 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
932 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
933 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
935 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
938 conn->ssl = SSL_new(conn->ssl_ctx);
939 if (conn->ssl == NULL) {
940 fprintf(stderr, "SSL context creation failed\n");
943 SSL_set_fd(conn->ssl, conn->sd);
945 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
946 if (!SSL_set_tlsext_host_name(conn->ssl,
947 __DECONST(struct url *, URL)->host)) {
949 "TLS server name indication extension failed for host %s\n",
954 while ((ret = SSL_connect(conn->ssl)) == -1) {
955 ssl_err = SSL_get_error(conn->ssl, ret);
956 if (ssl_err != SSL_ERROR_WANT_READ &&
957 ssl_err != SSL_ERROR_WANT_WRITE) {
958 ERR_print_errors_fp(stderr);
962 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
964 if (conn->ssl_cert == NULL) {
965 fprintf(stderr, "No server SSL certificate\n");
969 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
971 fetch_info("Verify hostname");
972 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
974 "SSL certificate subject doesn't match host %s\n",
981 fetch_info("%s connection established using %s",
982 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
983 name = X509_get_subject_name(conn->ssl_cert);
984 str = X509_NAME_oneline(name, 0, 0);
985 fetch_info("Certificate subject: %s", str);
987 name = X509_get_issuer_name(conn->ssl_cert);
988 str = X509_NAME_oneline(name, 0, 0);
989 fetch_info("Certificate issuer: %s", str);
997 fprintf(stderr, "SSL support disabled\n");
1002 #define FETCH_READ_WAIT -2
1003 #define FETCH_READ_ERROR -1
1004 #define FETCH_READ_DONE 0
1008 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1013 rlen = SSL_read(ssl, buf, len);
1015 ssl_err = SSL_get_error(ssl, rlen);
1016 if (ssl_err == SSL_ERROR_WANT_READ ||
1017 ssl_err == SSL_ERROR_WANT_WRITE) {
1018 return (FETCH_READ_WAIT);
1020 ERR_print_errors_fp(stderr);
1021 return (FETCH_READ_ERROR);
1029 fetch_socket_read(int sd, char *buf, size_t len)
1033 rlen = read(sd, buf, len);
1035 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1036 return (FETCH_READ_WAIT);
1038 return (FETCH_READ_ERROR);
1044 * Read a character from a connection w/ timeout
1047 fetch_read(conn_t *conn, char *buf, size_t len)
1049 struct timeval now, timeout, delta;
1054 if (fetchTimeout > 0) {
1055 gettimeofday(&timeout, NULL);
1056 timeout.tv_sec += fetchTimeout;
1060 memset(&pfd, 0, sizeof pfd);
1062 pfd.events = POLLIN | POLLERR;
1066 * The socket is non-blocking. Instead of the canonical
1067 * poll() -> read(), we do the following:
1069 * 1) call read() or SSL_read().
1070 * 2) if we received some data, return it.
1071 * 3) if an error occurred, return -1.
1072 * 4) if read() or SSL_read() signaled EOF, return.
1073 * 5) if we did not receive any data but we're not at EOF,
1076 * In the SSL case, this is necessary because if we
1077 * receive a close notification, we have to call
1078 * SSL_read() one additional time after we've read
1079 * everything we received.
1081 * In the non-SSL case, it may improve performance (very
1082 * slightly) when reading small amounts of data.
1085 if (conn->ssl != NULL)
1086 rlen = fetch_ssl_read(conn->ssl, buf, len);
1089 rlen = fetch_socket_read(conn->sd, buf, len);
1092 } else if (rlen == FETCH_READ_ERROR) {
1096 // assert(rlen == FETCH_READ_WAIT);
1097 if (fetchTimeout > 0) {
1098 gettimeofday(&now, NULL);
1099 if (!timercmp(&timeout, &now, >)) {
1104 timersub(&timeout, &now, &delta);
1105 deltams = delta.tv_sec * 1000 +
1106 delta.tv_usec / 1000;;
1110 if (poll(&pfd, 1, deltams) < 0) {
1111 if (errno == EINTR && fetchRestartCalls)
1122 * Read a line of text from a connection w/ timeout
1124 #define MIN_BUF_SIZE 1024
1127 fetch_getln(conn_t *conn)
1134 if (conn->buf == NULL) {
1135 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1139 conn->bufsize = MIN_BUF_SIZE;
1142 conn->buf[0] = '\0';
1146 len = fetch_read(conn, &c, 1);
1151 conn->buf[conn->buflen++] = c;
1152 if (conn->buflen == conn->bufsize) {
1154 tmpsize = conn->bufsize * 2 + 1;
1155 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1160 conn->bufsize = tmpsize;
1162 } while (c != '\n');
1164 conn->buf[conn->buflen] = '\0';
1165 DEBUGF("<<< %s", conn->buf);
1171 * Write to a connection w/ timeout
1174 fetch_write(conn_t *conn, const char *buf, size_t len)
1178 iov.iov_base = __DECONST(char *, buf);
1180 return fetch_writev(conn, &iov, 1);
1184 * Write a vector to a connection w/ timeout
1185 * Note: can modify the iovec.
1188 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1190 struct timeval now, timeout, delta;
1192 ssize_t wlen, total;
1195 memset(&pfd, 0, sizeof pfd);
1198 pfd.events = POLLOUT | POLLERR;
1199 gettimeofday(&timeout, NULL);
1200 timeout.tv_sec += fetchTimeout;
1204 while (iovcnt > 0) {
1205 while (fetchTimeout && pfd.revents == 0) {
1206 gettimeofday(&now, NULL);
1207 if (!timercmp(&timeout, &now, >)) {
1212 timersub(&timeout, &now, &delta);
1213 deltams = delta.tv_sec * 1000 +
1214 delta.tv_usec / 1000;
1217 if (poll(&pfd, 1, deltams) < 0) {
1218 /* POSIX compliance */
1219 if (errno == EAGAIN)
1221 if (errno == EINTR && fetchRestartCalls)
1228 if (conn->ssl != NULL)
1229 wlen = SSL_write(conn->ssl,
1230 iov->iov_base, iov->iov_len);
1233 wlen = writev(conn->sd, iov, iovcnt);
1235 /* we consider a short write a failure */
1236 /* XXX perhaps we shouldn't in the SSL case */
1242 if (errno == EINTR && fetchRestartCalls)
1247 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1248 wlen -= iov->iov_len;
1253 iov->iov_len -= wlen;
1254 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1262 * Write a line of text to a connection w/ timeout
1265 fetch_putln(conn_t *conn, const char *str, size_t len)
1267 struct iovec iov[2];
1270 DEBUGF(">>> %s\n", str);
1271 iov[0].iov_base = __DECONST(char *, str);
1272 iov[0].iov_len = len;
1273 iov[1].iov_base = __DECONST(char *, ENDL);
1274 iov[1].iov_len = sizeof(ENDL);
1276 ret = fetch_writev(conn, &iov[1], 1);
1278 ret = fetch_writev(conn, iov, 2);
1289 fetch_close(conn_t *conn)
1293 if (--conn->ref > 0)
1297 SSL_shutdown(conn->ssl);
1298 SSL_set_connect_state(conn->ssl);
1299 SSL_free(conn->ssl);
1302 if (conn->ssl_ctx) {
1303 SSL_CTX_free(conn->ssl_ctx);
1304 conn->ssl_ctx = NULL;
1306 if (conn->ssl_cert) {
1307 X509_free(conn->ssl_cert);
1308 conn->ssl_cert = NULL;
1311 ret = close(conn->sd);
1318 /*** Directory-related utility functions *************************************/
1321 fetch_add_entry(struct url_ent **p, int *size, int *len,
1322 const char *name, struct url_stat *us)
1324 struct url_ent *tmp;
1331 if (*len >= *size - 1) {
1332 tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1338 *size = (*size * 2 + 1);
1343 snprintf(tmp->name, PATH_MAX, "%s", name);
1344 memcpy(&tmp->stat, us, sizeof(*us));
1347 (++tmp)->name[0] = 0;
1353 /*** Authentication-related utility functions ********************************/
1356 fetch_read_word(FILE *f)
1358 static char word[1024];
1360 if (fscanf(f, " %1023s ", word) != 1)
1366 fetch_netrc_open(void)
1373 if ((p = getenv("NETRC")) != NULL) {
1374 DEBUGF("NETRC=%s\n", p);
1375 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1376 fetch_info("$NETRC specifies a file name "
1377 "longer than PATH_MAX");
1381 if ((p = getenv("HOME")) == NULL) {
1382 if ((pwd = getpwuid(getuid())) == NULL ||
1383 (p = pwd->pw_dir) == NULL)
1386 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1390 if ((fd = open(fn, O_RDONLY)) < 0) {
1392 DEBUGF("%s: %s\n", fn, strerror(serrno));
1399 * Get authentication data for a URL from .netrc
1402 fetch_netrc_auth(struct url *url)
1408 if (url->netrcfd < 0)
1409 url->netrcfd = fetch_netrc_open();
1410 if (url->netrcfd < 0)
1412 if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1414 DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1415 close(url->netrcfd);
1421 DEBUGF("searching netrc for %s\n", url->host);
1422 while ((word = fetch_read_word(f)) != NULL) {
1423 if (strcmp(word, "default") == 0) {
1424 DEBUGF("using default netrc settings\n");
1427 if (strcmp(word, "machine") == 0 &&
1428 (word = fetch_read_word(f)) != NULL &&
1429 strcasecmp(word, url->host) == 0) {
1430 DEBUGF("using netrc settings for %s\n", word);
1436 while ((word = fetch_read_word(f)) != NULL) {
1437 if (strcmp(word, "login") == 0) {
1438 if ((word = fetch_read_word(f)) == NULL)
1440 if (snprintf(url->user, sizeof(url->user),
1441 "%s", word) > (int)sizeof(url->user)) {
1442 fetch_info("login name in .netrc is too long");
1443 url->user[0] = '\0';
1445 } else if (strcmp(word, "password") == 0) {
1446 if ((word = fetch_read_word(f)) == NULL)
1448 if (snprintf(url->pwd, sizeof(url->pwd),
1449 "%s", word) > (int)sizeof(url->pwd)) {
1450 fetch_info("password in .netrc is too long");
1453 } else if (strcmp(word, "account") == 0) {
1454 if ((word = fetch_read_word(f)) == NULL)
1456 /* XXX not supported! */
1473 * The no_proxy environment variable specifies a set of domains for
1474 * which the proxy should not be consulted; the contents is a comma-,
1475 * or space-separated list of domain names. A single asterisk will
1476 * override all proxy variables and no transactions will be proxied
1477 * (for compatibility with lynx and curl, see the discussion at
1478 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1481 fetch_no_proxy_match(const char *host)
1483 const char *no_proxy, *p, *q;
1484 size_t h_len, d_len;
1486 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1487 (no_proxy = getenv("no_proxy")) == NULL)
1490 /* asterisk matches any hostname */
1491 if (strcmp(no_proxy, "*") == 0)
1494 h_len = strlen(host);
1497 /* position p at the beginning of a domain suffix */
1498 while (*p == ',' || isspace((unsigned char)*p))
1501 /* position q at the first separator character */
1502 for (q = p; *q; ++q)
1503 if (*q == ',' || isspace((unsigned char)*q))
1507 if (d_len > 0 && h_len >= d_len &&
1508 strncasecmp(host + h_len - d_len,
1510 /* domain name matches */