2 * Copyright (c) 1998-2016 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)
247 fetch_resolve(const char *addr, int port, int af)
249 char hbuf[256], sbuf[8];
250 struct addrinfo hints, *res;
251 const char *hb, *he, *sep;
252 const char *host, *service;
255 /* first, check for a bracketed IPv6 address */
258 if ((sep = strchr(hb, ']')) == NULL) {
265 sep = strchrnul(hb, ':');
269 /* see if we need to copy the host name */
271 len = snprintf(hbuf, sizeof(hbuf),
272 "%.*s", (int)(he - hb), hb);
275 if (len >= (int)sizeof(hbuf)) {
276 errno = ENAMETOOLONG;
284 /* was it followed by a service name? */
285 if (*sep == '\0' && port != 0) {
286 if (port < 1 || port > 65535) {
290 if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0)
293 } else if (*sep != '\0') {
300 memset(&hints, 0, sizeof(hints));
301 hints.ai_family = af;
302 hints.ai_socktype = SOCK_STREAM;
303 hints.ai_flags = AI_ADDRCONFIG;
304 if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
317 * Bind a socket to a specific local address
320 fetch_bind(int sd, int af, const char *addr)
322 struct addrinfo *cliai, *ai;
325 if ((cliai = fetch_resolve(addr, 0, af)) == NULL)
327 for (ai = cliai; ai != NULL; ai = ai->ai_next)
328 if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0)
333 return (err == 0 ? 0 : -1);
338 * Establish a TCP connection to the specified port on the specified host.
341 fetch_connect(const char *host, int port, int af, int verbose)
343 struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai;
344 const char *bindaddr;
346 int err = 0, sd = -1;
348 DEBUGF("---> %s:%d\n", host, port);
350 /* resolve server address */
352 fetch_info("resolving server address: %s:%d", host, port);
353 if ((sais = fetch_resolve(host, port, af)) == NULL)
356 /* resolve client address */
357 bindaddr = getenv("FETCH_BIND_ADDRESS");
358 if (bindaddr != NULL && *bindaddr != '\0') {
360 fetch_info("resolving client address: %s", bindaddr);
361 if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL)
365 /* try each server address in turn */
366 for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) {
368 if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0)
370 /* attempt to bind to client address */
371 for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) {
372 if (cai->ai_family != sai->ai_family)
374 if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0)
379 fetch_info("failed to bind to %s", bindaddr);
382 /* attempt to connect to server address */
383 if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0)
385 /* clean up before next attempt */
391 fetch_info("failed to connect to %s:%d", host, port);
395 if ((conn = fetch_reopen(sd)) == NULL)
417 * Convert characters A-Z to lowercase (intentionally avoid any locale
418 * specific conversions).
421 fetch_ssl_tolower(char in)
423 if (in >= 'A' && in <= 'Z')
430 * isalpha implementation that intentionally avoids any locale specific
434 fetch_ssl_isalpha(char in)
436 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
440 * Check if passed hostnames a and b are equal.
443 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
450 for (i = 0; i < alen; ++i) {
451 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
458 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
459 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
460 * numeric characters. Double hyphens (like they're found in IDN a-labels
461 * 'xn--') are not allowed. Empty labels are invalid.
464 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
468 if (!len || l[0] == '-' || l[len-1] == '-')
470 for (i = 0; i < len; ++i) {
471 if (!isdigit(l[i]) &&
472 !fetch_ssl_isalpha(l[i]) &&
473 !(l[i] == '*' && wcok) &&
474 !(l[i] == '-' && l[i - 1] != '-'))
481 * Check if host name consists only of numbers. This might indicate an IP
482 * address, which is not a good idea for CN wildcard comparison.
485 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
489 for (i = 0; i < len; ++i) {
490 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
498 * Check if the host name h passed matches the pattern passed in m which
499 * is usually part of subjectAltName or CN of a certificate presented to
500 * the client. This includes wildcard matching. The algorithm is based on
501 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
504 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
507 int delta, hdotidx, mdot1idx, wcidx;
508 const char *hdot, *mdot1, *mdot2;
509 const char *wc; /* wildcard */
511 if (!(h && *h && m && *m))
513 if ((wc = strnstr(m, "*", mlen)) == NULL)
514 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
516 /* hostname should not be just dots and numbers */
517 if (fetch_ssl_hname_is_only_numbers(h, hlen))
519 /* only one wildcard allowed in pattern */
520 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
523 * there must be at least two more domain labels and
524 * wildcard has to be in the leftmost label (RFC6125)
526 mdot1 = strnstr(m, ".", mlen);
527 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
529 mdot1idx = mdot1 - m;
530 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
531 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
533 /* hostname must contain a dot and not be the 1st char */
534 hdot = strnstr(h, ".", hlen);
535 if (hdot == NULL || hdot == h)
539 * host part of hostname must be at least as long as
540 * pattern it's supposed to match
542 if (hdotidx < mdot1idx)
545 * don't allow wildcards in non-traditional domain names
546 * (IDN, A-label, U-label...)
548 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
549 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
551 /* match domain part (part after first dot) */
552 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
555 /* match part left of wildcard */
556 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
558 /* match part right of wildcard */
559 delta = mdot1idx - wcidx - 1;
560 if (!fetch_ssl_hname_equal(hdot - delta, delta,
561 mdot1 - delta, delta))
563 /* all tests succeeded, it's a match */
568 * Get numeric host address info - returns NULL if host was not an IP
569 * address. The caller is responsible for deallocation using
572 static struct addrinfo *
573 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
575 struct addrinfo hints, *res;
578 host = (char *)malloc(len + 1);
579 memcpy(host, hostname, len);
581 memset(&hints, 0, sizeof(hints));
582 hints.ai_family = PF_UNSPEC;
583 hints.ai_socktype = SOCK_STREAM;
584 hints.ai_protocol = 0;
585 hints.ai_flags = AI_NUMERICHOST;
586 /* port is not relevant for this purpose */
587 if (getaddrinfo(host, "443", &hints, &res) != 0)
594 * Compare ip address in addrinfo with address passes.
597 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
602 if (lhost->ai_family == AF_INET && rhostlen == 4) {
603 left = (void *)&((struct sockaddr_in*)(void *)
604 lhost->ai_addr)->sin_addr.s_addr;
606 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
607 left = (void *)&((struct sockaddr_in6 *)(void *)
608 lhost->ai_addr)->sin6_addr;
612 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
616 * Compare ip address in addrinfo with host passed. If host is not an IP
617 * address, comparison will fail.
620 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
623 struct addrinfo *raddr;
628 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
629 return 0; /* not a numeric host */
631 if (laddr->ai_family == raddr->ai_family) {
632 if (laddr->ai_family == AF_INET) {
633 rip = (char *)&((struct sockaddr_in *)(void *)
634 raddr->ai_addr)->sin_addr.s_addr;
635 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
637 } else if (laddr->ai_family == AF_INET6) {
638 rip = (char *)&((struct sockaddr_in6 *)(void *)
639 raddr->ai_addr)->sin6_addr;
640 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
650 * Verify server certificate by subjectAltName.
653 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
654 const char *host, struct addrinfo *ip)
656 const GENERAL_NAME *name;
661 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
662 #if OPENSSL_VERSION_NUMBER < 0x10000000L
664 * This is a workaround, since the following line causes
665 * alignment issues in clang:
666 * name = sk_GENERAL_NAME_value(altnames, i);
667 * OpenSSL explicitly warns not to use those macros
668 * directly, but there isn't much choice (and there
669 * shouldn't be any ill side effects)
671 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
673 name = sk_GENERAL_NAME_value(altnames, i);
675 ns = (const char *)ASN1_STRING_data(name->d.ia5);
676 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
678 if (name->type == GEN_DNS && ip == NULL &&
679 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
681 else if (name->type == GEN_IPADD && ip != NULL &&
682 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
689 * Verify server certificate by CN.
692 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
695 ASN1_STRING *namedata;
696 X509_NAME_ENTRY *nameentry;
697 int cnlen, lastpos, loc, ret;
704 /* get most specific CN (last entry in list) and compare */
705 while ((lastpos = X509_NAME_get_index_by_NID(subject,
706 NID_commonName, lastpos)) != -1)
710 nameentry = X509_NAME_get_entry(subject, loc);
711 namedata = X509_NAME_ENTRY_get_data(nameentry);
712 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
714 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
716 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
724 * Verify that server certificate subjectAltName/CN matches
725 * hostname. First check, if there are alternative subject names. If yes,
726 * those have to match. Only if those don't exist it falls back to
727 * checking the subject's CN.
730 fetch_ssl_verify_hname(X509 *cert, const char *host)
733 STACK_OF(GENERAL_NAME) *altnames;
738 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
739 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
742 if (altnames != NULL) {
743 ret = fetch_ssl_verify_altname(altnames, host, ip);
745 subject = X509_get_subject_name(cert);
747 ret = fetch_ssl_verify_cn(subject, host, ip);
752 if (altnames != NULL)
753 GENERAL_NAMES_free(altnames);
758 * Configure transport security layer based on environment.
761 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
763 long ssl_ctx_options;
765 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET;
766 if (getenv("SSL_ALLOW_SSL3") == NULL)
767 ssl_ctx_options |= SSL_OP_NO_SSLv3;
768 if (getenv("SSL_NO_TLS1") != NULL)
769 ssl_ctx_options |= SSL_OP_NO_TLSv1;
770 if (getenv("SSL_NO_TLS1_1") != NULL)
771 ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
772 if (getenv("SSL_NO_TLS1_2") != NULL)
773 ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
775 fetch_info("SSL options: %lx", ssl_ctx_options);
776 SSL_CTX_set_options(ctx, ssl_ctx_options);
781 * Configure peer verification based on environment.
783 #define LOCAL_CERT_FILE "/usr/local/etc/ssl/cert.pem"
784 #define BASE_CERT_FILE "/etc/ssl/cert.pem"
786 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
788 X509_LOOKUP *crl_lookup;
789 X509_STORE *crl_store;
790 const char *ca_cert_file, *ca_cert_path, *crl_file;
792 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
793 ca_cert_file = getenv("SSL_CA_CERT_FILE");
794 if (ca_cert_file == NULL &&
795 access(LOCAL_CERT_FILE, R_OK) == 0)
796 ca_cert_file = LOCAL_CERT_FILE;
797 if (ca_cert_file == NULL &&
798 access(BASE_CERT_FILE, R_OK) == 0)
799 ca_cert_file = BASE_CERT_FILE;
800 ca_cert_path = getenv("SSL_CA_CERT_PATH");
802 fetch_info("Peer verification enabled");
803 if (ca_cert_file != NULL)
804 fetch_info("Using CA cert file: %s",
806 if (ca_cert_path != NULL)
807 fetch_info("Using CA cert path: %s",
809 if (ca_cert_file == NULL && ca_cert_path == NULL)
810 fetch_info("Using OpenSSL default "
811 "CA cert file and path");
813 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
814 fetch_ssl_cb_verify_crt);
815 if (ca_cert_file != NULL || ca_cert_path != NULL)
816 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
819 SSL_CTX_set_default_verify_paths(ctx);
820 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
822 fetch_info("Using CRL file: %s", crl_file);
823 crl_store = SSL_CTX_get_cert_store(ctx);
824 crl_lookup = X509_STORE_add_lookup(crl_store,
826 if (crl_lookup == NULL ||
827 !X509_load_crl_file(crl_lookup, crl_file,
828 X509_FILETYPE_PEM)) {
830 "Could not load CRL file %s\n",
834 X509_STORE_set_flags(crl_store,
835 X509_V_FLAG_CRL_CHECK |
836 X509_V_FLAG_CRL_CHECK_ALL);
843 * Configure client certificate based on environment.
846 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
848 const char *client_cert_file, *client_key_file;
850 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
851 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
852 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
854 fetch_info("Using client cert file: %s",
856 fetch_info("Using client key file: %s",
859 if (SSL_CTX_use_certificate_chain_file(ctx,
860 client_cert_file) != 1) {
862 "Could not load client certificate %s\n",
866 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
867 SSL_FILETYPE_PEM) != 1) {
869 "Could not load client key %s\n",
878 * Callback for SSL certificate verification, this is called on server
879 * cert verification. It takes no decision, but informs the user in case
880 * verification failed.
883 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
891 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
892 (name = X509_get_subject_name(crt)) != NULL)
893 str = X509_NAME_oneline(name, 0, 0);
894 fprintf(stderr, "Certificate verification failed for %s\n",
895 str != NULL ? str : "no relevant certificate");
904 * Enable SSL on a connection.
907 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
914 /* Init the SSL library and context */
915 if (!SSL_library_init()){
916 fprintf(stderr, "SSL library init failed\n");
920 SSL_load_error_strings();
922 conn->ssl_meth = SSLv23_client_method();
923 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
924 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
926 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
927 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
929 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
932 conn->ssl = SSL_new(conn->ssl_ctx);
933 if (conn->ssl == NULL) {
934 fprintf(stderr, "SSL context creation failed\n");
937 SSL_set_fd(conn->ssl, conn->sd);
939 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
940 if (!SSL_set_tlsext_host_name(conn->ssl,
941 __DECONST(struct url *, URL)->host)) {
943 "TLS server name indication extension failed for host %s\n",
948 while ((ret = SSL_connect(conn->ssl)) == -1) {
949 ssl_err = SSL_get_error(conn->ssl, ret);
950 if (ssl_err != SSL_ERROR_WANT_READ &&
951 ssl_err != SSL_ERROR_WANT_WRITE) {
952 ERR_print_errors_fp(stderr);
956 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
958 if (conn->ssl_cert == NULL) {
959 fprintf(stderr, "No server SSL certificate\n");
963 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
965 fetch_info("Verify hostname");
966 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
968 "SSL certificate subject doesn't match host %s\n",
975 fetch_info("%s connection established using %s",
976 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
977 name = X509_get_subject_name(conn->ssl_cert);
978 str = X509_NAME_oneline(name, 0, 0);
979 fetch_info("Certificate subject: %s", str);
981 name = X509_get_issuer_name(conn->ssl_cert);
982 str = X509_NAME_oneline(name, 0, 0);
983 fetch_info("Certificate issuer: %s", str);
991 fprintf(stderr, "SSL support disabled\n");
996 #define FETCH_READ_WAIT -2
997 #define FETCH_READ_ERROR -1
998 #define FETCH_READ_DONE 0
1002 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1007 rlen = SSL_read(ssl, buf, len);
1009 ssl_err = SSL_get_error(ssl, rlen);
1010 if (ssl_err == SSL_ERROR_WANT_READ ||
1011 ssl_err == SSL_ERROR_WANT_WRITE) {
1012 return (FETCH_READ_WAIT);
1014 ERR_print_errors_fp(stderr);
1015 return (FETCH_READ_ERROR);
1023 fetch_socket_read(int sd, char *buf, size_t len)
1027 rlen = read(sd, buf, len);
1029 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1030 return (FETCH_READ_WAIT);
1032 return (FETCH_READ_ERROR);
1038 * Read a character from a connection w/ timeout
1041 fetch_read(conn_t *conn, char *buf, size_t len)
1043 struct timeval now, timeout, delta;
1048 if (fetchTimeout > 0) {
1049 gettimeofday(&timeout, NULL);
1050 timeout.tv_sec += fetchTimeout;
1054 memset(&pfd, 0, sizeof pfd);
1056 pfd.events = POLLIN | POLLERR;
1060 * The socket is non-blocking. Instead of the canonical
1061 * poll() -> read(), we do the following:
1063 * 1) call read() or SSL_read().
1064 * 2) if we received some data, return it.
1065 * 3) if an error occurred, return -1.
1066 * 4) if read() or SSL_read() signaled EOF, return.
1067 * 5) if we did not receive any data but we're not at EOF,
1070 * In the SSL case, this is necessary because if we
1071 * receive a close notification, we have to call
1072 * SSL_read() one additional time after we've read
1073 * everything we received.
1075 * In the non-SSL case, it may improve performance (very
1076 * slightly) when reading small amounts of data.
1079 if (conn->ssl != NULL)
1080 rlen = fetch_ssl_read(conn->ssl, buf, len);
1083 rlen = fetch_socket_read(conn->sd, buf, len);
1086 } else if (rlen == FETCH_READ_ERROR) {
1090 // assert(rlen == FETCH_READ_WAIT);
1091 if (fetchTimeout > 0) {
1092 gettimeofday(&now, NULL);
1093 if (!timercmp(&timeout, &now, >)) {
1098 timersub(&timeout, &now, &delta);
1099 deltams = delta.tv_sec * 1000 +
1100 delta.tv_usec / 1000;;
1104 if (poll(&pfd, 1, deltams) < 0) {
1105 if (errno == EINTR && fetchRestartCalls)
1116 * Read a line of text from a connection w/ timeout
1118 #define MIN_BUF_SIZE 1024
1121 fetch_getln(conn_t *conn)
1128 if (conn->buf == NULL) {
1129 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1133 conn->bufsize = MIN_BUF_SIZE;
1136 conn->buf[0] = '\0';
1140 len = fetch_read(conn, &c, 1);
1145 conn->buf[conn->buflen++] = c;
1146 if (conn->buflen == conn->bufsize) {
1148 tmpsize = conn->bufsize * 2 + 1;
1149 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1154 conn->bufsize = tmpsize;
1156 } while (c != '\n');
1158 conn->buf[conn->buflen] = '\0';
1159 DEBUGF("<<< %s", conn->buf);
1165 * Write to a connection w/ timeout
1168 fetch_write(conn_t *conn, const char *buf, size_t len)
1172 iov.iov_base = __DECONST(char *, buf);
1174 return fetch_writev(conn, &iov, 1);
1178 * Write a vector to a connection w/ timeout
1179 * Note: can modify the iovec.
1182 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1184 struct timeval now, timeout, delta;
1186 ssize_t wlen, total;
1189 memset(&pfd, 0, sizeof pfd);
1192 pfd.events = POLLOUT | POLLERR;
1193 gettimeofday(&timeout, NULL);
1194 timeout.tv_sec += fetchTimeout;
1198 while (iovcnt > 0) {
1199 while (fetchTimeout && pfd.revents == 0) {
1200 gettimeofday(&now, NULL);
1201 if (!timercmp(&timeout, &now, >)) {
1206 timersub(&timeout, &now, &delta);
1207 deltams = delta.tv_sec * 1000 +
1208 delta.tv_usec / 1000;
1211 if (poll(&pfd, 1, deltams) < 0) {
1212 /* POSIX compliance */
1213 if (errno == EAGAIN)
1215 if (errno == EINTR && fetchRestartCalls)
1222 if (conn->ssl != NULL)
1223 wlen = SSL_write(conn->ssl,
1224 iov->iov_base, iov->iov_len);
1227 wlen = writev(conn->sd, iov, iovcnt);
1229 /* we consider a short write a failure */
1230 /* XXX perhaps we shouldn't in the SSL case */
1236 if (errno == EINTR && fetchRestartCalls)
1241 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1242 wlen -= iov->iov_len;
1247 iov->iov_len -= wlen;
1248 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1256 * Write a line of text to a connection w/ timeout
1259 fetch_putln(conn_t *conn, const char *str, size_t len)
1261 struct iovec iov[2];
1264 DEBUGF(">>> %s\n", str);
1265 iov[0].iov_base = __DECONST(char *, str);
1266 iov[0].iov_len = len;
1267 iov[1].iov_base = __DECONST(char *, ENDL);
1268 iov[1].iov_len = sizeof(ENDL);
1270 ret = fetch_writev(conn, &iov[1], 1);
1272 ret = fetch_writev(conn, iov, 2);
1283 fetch_close(conn_t *conn)
1287 if (--conn->ref > 0)
1291 SSL_shutdown(conn->ssl);
1292 SSL_set_connect_state(conn->ssl);
1293 SSL_free(conn->ssl);
1296 if (conn->ssl_ctx) {
1297 SSL_CTX_free(conn->ssl_ctx);
1298 conn->ssl_ctx = NULL;
1300 if (conn->ssl_cert) {
1301 X509_free(conn->ssl_cert);
1302 conn->ssl_cert = NULL;
1305 ret = close(conn->sd);
1312 /*** Directory-related utility functions *************************************/
1315 fetch_add_entry(struct url_ent **p, int *size, int *len,
1316 const char *name, struct url_stat *us)
1318 struct url_ent *tmp;
1325 if (*len >= *size - 1) {
1326 tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1332 *size = (*size * 2 + 1);
1337 snprintf(tmp->name, PATH_MAX, "%s", name);
1338 memcpy(&tmp->stat, us, sizeof(*us));
1341 (++tmp)->name[0] = 0;
1347 /*** Authentication-related utility functions ********************************/
1350 fetch_read_word(FILE *f)
1352 static char word[1024];
1354 if (fscanf(f, " %1023s ", word) != 1)
1360 fetch_netrc_open(void)
1367 if ((p = getenv("NETRC")) != NULL) {
1368 DEBUGF("NETRC=%s\n", p);
1369 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1370 fetch_info("$NETRC specifies a file name "
1371 "longer than PATH_MAX");
1375 if ((p = getenv("HOME")) == NULL) {
1376 if ((pwd = getpwuid(getuid())) == NULL ||
1377 (p = pwd->pw_dir) == NULL)
1380 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1384 if ((fd = open(fn, O_RDONLY)) < 0) {
1386 DEBUGF("%s: %s\n", fn, strerror(serrno));
1393 * Get authentication data for a URL from .netrc
1396 fetch_netrc_auth(struct url *url)
1402 if (url->netrcfd < 0)
1403 url->netrcfd = fetch_netrc_open();
1404 if (url->netrcfd < 0)
1406 if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1408 DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1409 close(url->netrcfd);
1415 DEBUGF("searching netrc for %s\n", url->host);
1416 while ((word = fetch_read_word(f)) != NULL) {
1417 if (strcmp(word, "default") == 0) {
1418 DEBUGF("using default netrc settings\n");
1421 if (strcmp(word, "machine") == 0 &&
1422 (word = fetch_read_word(f)) != NULL &&
1423 strcasecmp(word, url->host) == 0) {
1424 DEBUGF("using netrc settings for %s\n", word);
1430 while ((word = fetch_read_word(f)) != NULL) {
1431 if (strcmp(word, "login") == 0) {
1432 if ((word = fetch_read_word(f)) == NULL)
1434 if (snprintf(url->user, sizeof(url->user),
1435 "%s", word) > (int)sizeof(url->user)) {
1436 fetch_info("login name in .netrc is too long");
1437 url->user[0] = '\0';
1439 } else if (strcmp(word, "password") == 0) {
1440 if ((word = fetch_read_word(f)) == NULL)
1442 if (snprintf(url->pwd, sizeof(url->pwd),
1443 "%s", word) > (int)sizeof(url->pwd)) {
1444 fetch_info("password in .netrc is too long");
1447 } else if (strcmp(word, "account") == 0) {
1448 if ((word = fetch_read_word(f)) == NULL)
1450 /* XXX not supported! */
1467 * The no_proxy environment variable specifies a set of domains for
1468 * which the proxy should not be consulted; the contents is a comma-,
1469 * or space-separated list of domain names. A single asterisk will
1470 * override all proxy variables and no transactions will be proxied
1471 * (for compatibility with lynx and curl, see the discussion at
1472 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1475 fetch_no_proxy_match(const char *host)
1477 const char *no_proxy, *p, *q;
1478 size_t h_len, d_len;
1480 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1481 (no_proxy = getenv("no_proxy")) == NULL)
1484 /* asterisk matches any hostname */
1485 if (strcmp(no_proxy, "*") == 0)
1488 h_len = strlen(host);
1491 /* position p at the beginning of a domain suffix */
1492 while (*p == ',' || isspace((unsigned char)*p))
1495 /* position q at the first separator character */
1496 for (q = p; *q; ++q)
1497 if (*q == ',' || isspace((unsigned char)*q))
1501 if (d_len > 0 && h_len >= d_len &&
1502 strncasecmp(host + h_len - d_len,
1504 /* domain name matches */