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 *sep, *host, *service;
254 /* split address if necessary */
256 if ((sep = strchr(addr, ':')) != NULL) {
257 len = snprintf(hbuf, sizeof(hbuf),
258 "%.*s", (int)(sep - addr), addr);
261 if (len >= (int)sizeof(hbuf)) {
262 errno = ENAMETOOLONG;
268 } else if (port != 0) {
269 if (port < 1 || port > 65535) {
274 if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0) {
286 memset(&hints, 0, sizeof(hints));
287 hints.ai_family = af;
288 hints.ai_socktype = SOCK_STREAM;
289 hints.ai_flags = AI_ADDRCONFIG;
290 if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
300 * Bind a socket to a specific local address
303 fetch_bind(int sd, int af, const char *addr)
305 struct addrinfo *cliai, *ai;
308 if ((cliai = fetch_resolve(addr, 0, af)) == NULL)
310 for (ai = cliai; ai != NULL; ai = ai->ai_next)
311 if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0)
316 return (err == 0 ? 0 : -1);
321 * Establish a TCP connection to the specified port on the specified host.
324 fetch_connect(const char *host, int port, int af, int verbose)
326 struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai;
327 const char *bindaddr;
329 int err = 0, sd = -1;
331 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
333 /* resolve server address */
335 fetch_info("resolving server address: %s:%d", host, port);
336 if ((sais = fetch_resolve(host, port, af)) == NULL)
339 /* resolve client address */
340 bindaddr = getenv("FETCH_BIND_ADDRESS");
341 if (bindaddr != NULL && *bindaddr != '\0') {
343 fetch_info("resolving client address: %s", bindaddr);
344 if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL)
348 /* try each server address in turn */
349 for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) {
351 if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0)
353 /* attempt to bind to client address */
354 for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) {
355 if (cai->ai_family != sai->ai_family)
357 if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0)
362 fetch_info("failed to bind to %s", bindaddr);
365 /* attempt to connect to server address */
366 if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0)
368 /* clean up before next attempt */
374 fetch_info("failed to connect to %s:%s", host, port);
378 if ((conn = fetch_reopen(sd)) == NULL)
400 * Convert characters A-Z to lowercase (intentionally avoid any locale
401 * specific conversions).
404 fetch_ssl_tolower(char in)
406 if (in >= 'A' && in <= 'Z')
413 * isalpha implementation that intentionally avoids any locale specific
417 fetch_ssl_isalpha(char in)
419 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
423 * Check if passed hostnames a and b are equal.
426 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
433 for (i = 0; i < alen; ++i) {
434 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
441 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
442 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
443 * numeric characters. Double hyphens (like they're found in IDN a-labels
444 * 'xn--') are not allowed. Empty labels are invalid.
447 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
451 if (!len || l[0] == '-' || l[len-1] == '-')
453 for (i = 0; i < len; ++i) {
454 if (!isdigit(l[i]) &&
455 !fetch_ssl_isalpha(l[i]) &&
456 !(l[i] == '*' && wcok) &&
457 !(l[i] == '-' && l[i - 1] != '-'))
464 * Check if host name consists only of numbers. This might indicate an IP
465 * address, which is not a good idea for CN wildcard comparison.
468 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
472 for (i = 0; i < len; ++i) {
473 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
481 * Check if the host name h passed matches the pattern passed in m which
482 * is usually part of subjectAltName or CN of a certificate presented to
483 * the client. This includes wildcard matching. The algorithm is based on
484 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
487 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
490 int delta, hdotidx, mdot1idx, wcidx;
491 const char *hdot, *mdot1, *mdot2;
492 const char *wc; /* wildcard */
494 if (!(h && *h && m && *m))
496 if ((wc = strnstr(m, "*", mlen)) == NULL)
497 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
499 /* hostname should not be just dots and numbers */
500 if (fetch_ssl_hname_is_only_numbers(h, hlen))
502 /* only one wildcard allowed in pattern */
503 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
506 * there must be at least two more domain labels and
507 * wildcard has to be in the leftmost label (RFC6125)
509 mdot1 = strnstr(m, ".", mlen);
510 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
512 mdot1idx = mdot1 - m;
513 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
514 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
516 /* hostname must contain a dot and not be the 1st char */
517 hdot = strnstr(h, ".", hlen);
518 if (hdot == NULL || hdot == h)
522 * host part of hostname must be at least as long as
523 * pattern it's supposed to match
525 if (hdotidx < mdot1idx)
528 * don't allow wildcards in non-traditional domain names
529 * (IDN, A-label, U-label...)
531 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
532 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
534 /* match domain part (part after first dot) */
535 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
538 /* match part left of wildcard */
539 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
541 /* match part right of wildcard */
542 delta = mdot1idx - wcidx - 1;
543 if (!fetch_ssl_hname_equal(hdot - delta, delta,
544 mdot1 - delta, delta))
546 /* all tests succeeded, it's a match */
551 * Get numeric host address info - returns NULL if host was not an IP
552 * address. The caller is responsible for deallocation using
555 static struct addrinfo *
556 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
558 struct addrinfo hints, *res;
561 host = (char *)malloc(len + 1);
562 memcpy(host, hostname, len);
564 memset(&hints, 0, sizeof(hints));
565 hints.ai_family = PF_UNSPEC;
566 hints.ai_socktype = SOCK_STREAM;
567 hints.ai_protocol = 0;
568 hints.ai_flags = AI_NUMERICHOST;
569 /* port is not relevant for this purpose */
570 if (getaddrinfo(host, "443", &hints, &res) != 0)
577 * Compare ip address in addrinfo with address passes.
580 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
585 if (lhost->ai_family == AF_INET && rhostlen == 4) {
586 left = (void *)&((struct sockaddr_in*)(void *)
587 lhost->ai_addr)->sin_addr.s_addr;
589 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
590 left = (void *)&((struct sockaddr_in6 *)(void *)
591 lhost->ai_addr)->sin6_addr;
595 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
599 * Compare ip address in addrinfo with host passed. If host is not an IP
600 * address, comparison will fail.
603 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
606 struct addrinfo *raddr;
611 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
612 return 0; /* not a numeric host */
614 if (laddr->ai_family == raddr->ai_family) {
615 if (laddr->ai_family == AF_INET) {
616 rip = (char *)&((struct sockaddr_in *)(void *)
617 raddr->ai_addr)->sin_addr.s_addr;
618 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
620 } else if (laddr->ai_family == AF_INET6) {
621 rip = (char *)&((struct sockaddr_in6 *)(void *)
622 raddr->ai_addr)->sin6_addr;
623 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
633 * Verify server certificate by subjectAltName.
636 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
637 const char *host, struct addrinfo *ip)
639 const GENERAL_NAME *name;
644 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
645 #if OPENSSL_VERSION_NUMBER < 0x10000000L
647 * This is a workaround, since the following line causes
648 * alignment issues in clang:
649 * name = sk_GENERAL_NAME_value(altnames, i);
650 * OpenSSL explicitly warns not to use those macros
651 * directly, but there isn't much choice (and there
652 * shouldn't be any ill side effects)
654 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
656 name = sk_GENERAL_NAME_value(altnames, i);
658 ns = (const char *)ASN1_STRING_data(name->d.ia5);
659 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
661 if (name->type == GEN_DNS && ip == NULL &&
662 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
664 else if (name->type == GEN_IPADD && ip != NULL &&
665 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
672 * Verify server certificate by CN.
675 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
678 ASN1_STRING *namedata;
679 X509_NAME_ENTRY *nameentry;
680 int cnlen, lastpos, loc, ret;
687 /* get most specific CN (last entry in list) and compare */
688 while ((lastpos = X509_NAME_get_index_by_NID(subject,
689 NID_commonName, lastpos)) != -1)
693 nameentry = X509_NAME_get_entry(subject, loc);
694 namedata = X509_NAME_ENTRY_get_data(nameentry);
695 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
697 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
699 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
707 * Verify that server certificate subjectAltName/CN matches
708 * hostname. First check, if there are alternative subject names. If yes,
709 * those have to match. Only if those don't exist it falls back to
710 * checking the subject's CN.
713 fetch_ssl_verify_hname(X509 *cert, const char *host)
716 STACK_OF(GENERAL_NAME) *altnames;
721 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
722 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
725 if (altnames != NULL) {
726 ret = fetch_ssl_verify_altname(altnames, host, ip);
728 subject = X509_get_subject_name(cert);
730 ret = fetch_ssl_verify_cn(subject, host, ip);
735 if (altnames != NULL)
736 GENERAL_NAMES_free(altnames);
741 * Configure transport security layer based on environment.
744 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
746 long ssl_ctx_options;
748 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET;
749 if (getenv("SSL_ALLOW_SSL3") == NULL)
750 ssl_ctx_options |= SSL_OP_NO_SSLv3;
751 if (getenv("SSL_NO_TLS1") != NULL)
752 ssl_ctx_options |= SSL_OP_NO_TLSv1;
753 if (getenv("SSL_NO_TLS1_1") != NULL)
754 ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
755 if (getenv("SSL_NO_TLS1_2") != NULL)
756 ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
758 fetch_info("SSL options: %lx", ssl_ctx_options);
759 SSL_CTX_set_options(ctx, ssl_ctx_options);
764 * Configure peer verification based on environment.
766 #define LOCAL_CERT_FILE "/usr/local/etc/ssl/cert.pem"
767 #define BASE_CERT_FILE "/etc/ssl/cert.pem"
769 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
771 X509_LOOKUP *crl_lookup;
772 X509_STORE *crl_store;
773 const char *ca_cert_file, *ca_cert_path, *crl_file;
775 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
776 ca_cert_file = getenv("SSL_CA_CERT_FILE");
777 if (ca_cert_file == NULL &&
778 access(LOCAL_CERT_FILE, R_OK) == 0)
779 ca_cert_file = LOCAL_CERT_FILE;
780 if (ca_cert_file == NULL &&
781 access(BASE_CERT_FILE, R_OK) == 0)
782 ca_cert_file = BASE_CERT_FILE;
783 ca_cert_path = getenv("SSL_CA_CERT_PATH");
785 fetch_info("Peer verification enabled");
786 if (ca_cert_file != NULL)
787 fetch_info("Using CA cert file: %s",
789 if (ca_cert_path != NULL)
790 fetch_info("Using CA cert path: %s",
792 if (ca_cert_file == NULL && ca_cert_path == NULL)
793 fetch_info("Using OpenSSL default "
794 "CA cert file and path");
796 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
797 fetch_ssl_cb_verify_crt);
798 if (ca_cert_file != NULL || ca_cert_path != NULL)
799 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
802 SSL_CTX_set_default_verify_paths(ctx);
803 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
805 fetch_info("Using CRL file: %s", crl_file);
806 crl_store = SSL_CTX_get_cert_store(ctx);
807 crl_lookup = X509_STORE_add_lookup(crl_store,
809 if (crl_lookup == NULL ||
810 !X509_load_crl_file(crl_lookup, crl_file,
811 X509_FILETYPE_PEM)) {
813 "Could not load CRL file %s\n",
817 X509_STORE_set_flags(crl_store,
818 X509_V_FLAG_CRL_CHECK |
819 X509_V_FLAG_CRL_CHECK_ALL);
826 * Configure client certificate based on environment.
829 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
831 const char *client_cert_file, *client_key_file;
833 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
834 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
835 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
837 fetch_info("Using client cert file: %s",
839 fetch_info("Using client key file: %s",
842 if (SSL_CTX_use_certificate_chain_file(ctx,
843 client_cert_file) != 1) {
845 "Could not load client certificate %s\n",
849 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
850 SSL_FILETYPE_PEM) != 1) {
852 "Could not load client key %s\n",
861 * Callback for SSL certificate verification, this is called on server
862 * cert verification. It takes no decision, but informs the user in case
863 * verification failed.
866 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
874 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
875 (name = X509_get_subject_name(crt)) != NULL)
876 str = X509_NAME_oneline(name, 0, 0);
877 fprintf(stderr, "Certificate verification failed for %s\n",
878 str != NULL ? str : "no relevant certificate");
887 * Enable SSL on a connection.
890 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
897 /* Init the SSL library and context */
898 if (!SSL_library_init()){
899 fprintf(stderr, "SSL library init failed\n");
903 SSL_load_error_strings();
905 conn->ssl_meth = SSLv23_client_method();
906 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
907 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
909 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
910 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
912 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
915 conn->ssl = SSL_new(conn->ssl_ctx);
916 if (conn->ssl == NULL) {
917 fprintf(stderr, "SSL context creation failed\n");
920 SSL_set_fd(conn->ssl, conn->sd);
922 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
923 if (!SSL_set_tlsext_host_name(conn->ssl,
924 __DECONST(struct url *, URL)->host)) {
926 "TLS server name indication extension failed for host %s\n",
931 while ((ret = SSL_connect(conn->ssl)) == -1) {
932 ssl_err = SSL_get_error(conn->ssl, ret);
933 if (ssl_err != SSL_ERROR_WANT_READ &&
934 ssl_err != SSL_ERROR_WANT_WRITE) {
935 ERR_print_errors_fp(stderr);
939 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
941 if (conn->ssl_cert == NULL) {
942 fprintf(stderr, "No server SSL certificate\n");
946 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
948 fetch_info("Verify hostname");
949 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
951 "SSL certificate subject doesn't match host %s\n",
958 fetch_info("%s connection established using %s",
959 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
960 name = X509_get_subject_name(conn->ssl_cert);
961 str = X509_NAME_oneline(name, 0, 0);
962 fetch_info("Certificate subject: %s", str);
964 name = X509_get_issuer_name(conn->ssl_cert);
965 str = X509_NAME_oneline(name, 0, 0);
966 fetch_info("Certificate issuer: %s", str);
974 fprintf(stderr, "SSL support disabled\n");
979 #define FETCH_READ_WAIT -2
980 #define FETCH_READ_ERROR -1
981 #define FETCH_READ_DONE 0
985 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
990 rlen = SSL_read(ssl, buf, len);
992 ssl_err = SSL_get_error(ssl, rlen);
993 if (ssl_err == SSL_ERROR_WANT_READ ||
994 ssl_err == SSL_ERROR_WANT_WRITE) {
995 return (FETCH_READ_WAIT);
997 ERR_print_errors_fp(stderr);
998 return (FETCH_READ_ERROR);
1006 fetch_socket_read(int sd, char *buf, size_t len)
1010 rlen = read(sd, buf, len);
1012 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1013 return (FETCH_READ_WAIT);
1015 return (FETCH_READ_ERROR);
1021 * Read a character from a connection w/ timeout
1024 fetch_read(conn_t *conn, char *buf, size_t len)
1026 struct timeval now, timeout, delta;
1031 if (fetchTimeout > 0) {
1032 gettimeofday(&timeout, NULL);
1033 timeout.tv_sec += fetchTimeout;
1037 memset(&pfd, 0, sizeof pfd);
1039 pfd.events = POLLIN | POLLERR;
1043 * The socket is non-blocking. Instead of the canonical
1044 * poll() -> read(), we do the following:
1046 * 1) call read() or SSL_read().
1047 * 2) if we received some data, return it.
1048 * 3) if an error occurred, return -1.
1049 * 4) if read() or SSL_read() signaled EOF, return.
1050 * 5) if we did not receive any data but we're not at EOF,
1053 * In the SSL case, this is necessary because if we
1054 * receive a close notification, we have to call
1055 * SSL_read() one additional time after we've read
1056 * everything we received.
1058 * In the non-SSL case, it may improve performance (very
1059 * slightly) when reading small amounts of data.
1062 if (conn->ssl != NULL)
1063 rlen = fetch_ssl_read(conn->ssl, buf, len);
1066 rlen = fetch_socket_read(conn->sd, buf, len);
1069 } else if (rlen == FETCH_READ_ERROR) {
1073 // assert(rlen == FETCH_READ_WAIT);
1074 if (fetchTimeout > 0) {
1075 gettimeofday(&now, NULL);
1076 if (!timercmp(&timeout, &now, >)) {
1081 timersub(&timeout, &now, &delta);
1082 deltams = delta.tv_sec * 1000 +
1083 delta.tv_usec / 1000;;
1087 if (poll(&pfd, 1, deltams) < 0) {
1088 if (errno == EINTR && fetchRestartCalls)
1099 * Read a line of text from a connection w/ timeout
1101 #define MIN_BUF_SIZE 1024
1104 fetch_getln(conn_t *conn)
1111 if (conn->buf == NULL) {
1112 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1116 conn->bufsize = MIN_BUF_SIZE;
1119 conn->buf[0] = '\0';
1123 len = fetch_read(conn, &c, 1);
1128 conn->buf[conn->buflen++] = c;
1129 if (conn->buflen == conn->bufsize) {
1131 tmpsize = conn->bufsize * 2 + 1;
1132 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1137 conn->bufsize = tmpsize;
1139 } while (c != '\n');
1141 conn->buf[conn->buflen] = '\0';
1142 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
1148 * Write to a connection w/ timeout
1151 fetch_write(conn_t *conn, const char *buf, size_t len)
1155 iov.iov_base = __DECONST(char *, buf);
1157 return fetch_writev(conn, &iov, 1);
1161 * Write a vector to a connection w/ timeout
1162 * Note: can modify the iovec.
1165 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1167 struct timeval now, timeout, delta;
1169 ssize_t wlen, total;
1172 memset(&pfd, 0, sizeof pfd);
1175 pfd.events = POLLOUT | POLLERR;
1176 gettimeofday(&timeout, NULL);
1177 timeout.tv_sec += fetchTimeout;
1181 while (iovcnt > 0) {
1182 while (fetchTimeout && pfd.revents == 0) {
1183 gettimeofday(&now, NULL);
1184 if (!timercmp(&timeout, &now, >)) {
1189 timersub(&timeout, &now, &delta);
1190 deltams = delta.tv_sec * 1000 +
1191 delta.tv_usec / 1000;
1194 if (poll(&pfd, 1, deltams) < 0) {
1195 /* POSIX compliance */
1196 if (errno == EAGAIN)
1198 if (errno == EINTR && fetchRestartCalls)
1205 if (conn->ssl != NULL)
1206 wlen = SSL_write(conn->ssl,
1207 iov->iov_base, iov->iov_len);
1210 wlen = writev(conn->sd, iov, iovcnt);
1212 /* we consider a short write a failure */
1213 /* XXX perhaps we shouldn't in the SSL case */
1219 if (errno == EINTR && fetchRestartCalls)
1224 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1225 wlen -= iov->iov_len;
1230 iov->iov_len -= wlen;
1231 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1239 * Write a line of text to a connection w/ timeout
1242 fetch_putln(conn_t *conn, const char *str, size_t len)
1244 struct iovec iov[2];
1247 DEBUG(fprintf(stderr, ">>> %s\n", str));
1248 iov[0].iov_base = __DECONST(char *, str);
1249 iov[0].iov_len = len;
1250 iov[1].iov_base = __DECONST(char *, ENDL);
1251 iov[1].iov_len = sizeof(ENDL);
1253 ret = fetch_writev(conn, &iov[1], 1);
1255 ret = fetch_writev(conn, iov, 2);
1266 fetch_close(conn_t *conn)
1270 if (--conn->ref > 0)
1274 SSL_shutdown(conn->ssl);
1275 SSL_set_connect_state(conn->ssl);
1276 SSL_free(conn->ssl);
1279 if (conn->ssl_ctx) {
1280 SSL_CTX_free(conn->ssl_ctx);
1281 conn->ssl_ctx = NULL;
1283 if (conn->ssl_cert) {
1284 X509_free(conn->ssl_cert);
1285 conn->ssl_cert = NULL;
1288 ret = close(conn->sd);
1295 /*** Directory-related utility functions *************************************/
1298 fetch_add_entry(struct url_ent **p, int *size, int *len,
1299 const char *name, struct url_stat *us)
1301 struct url_ent *tmp;
1308 if (*len >= *size - 1) {
1309 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
1315 *size = (*size * 2 + 1);
1320 snprintf(tmp->name, PATH_MAX, "%s", name);
1321 memcpy(&tmp->stat, us, sizeof(*us));
1324 (++tmp)->name[0] = 0;
1330 /*** Authentication-related utility functions ********************************/
1333 fetch_read_word(FILE *f)
1335 static char word[1024];
1337 if (fscanf(f, " %1023s ", word) != 1)
1343 fetch_netrc_open(void)
1348 if ((p = getenv("NETRC")) != NULL) {
1349 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1350 fetch_info("$NETRC specifies a file name "
1351 "longer than PATH_MAX");
1355 if ((p = getenv("HOME")) != NULL) {
1358 if ((pwd = getpwuid(getuid())) == NULL ||
1359 (p = pwd->pw_dir) == NULL)
1362 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1366 return (open(fn, O_RDONLY));
1370 * Get authentication data for a URL from .netrc
1373 fetch_netrc_auth(struct url *url)
1378 if (url->netrcfd == -2)
1379 url->netrcfd = fetch_netrc_open();
1380 if (url->netrcfd < 0)
1382 if ((f = fdopen(url->netrcfd, "r")) == NULL)
1385 while ((word = fetch_read_word(f)) != NULL) {
1386 if (strcmp(word, "default") == 0) {
1387 DEBUG(fetch_info("Using default .netrc settings"));
1390 if (strcmp(word, "machine") == 0 &&
1391 (word = fetch_read_word(f)) != NULL &&
1392 strcasecmp(word, url->host) == 0) {
1393 DEBUG(fetch_info("Using .netrc settings for %s", word));
1399 while ((word = fetch_read_word(f)) != NULL) {
1400 if (strcmp(word, "login") == 0) {
1401 if ((word = fetch_read_word(f)) == NULL)
1403 if (snprintf(url->user, sizeof(url->user),
1404 "%s", word) > (int)sizeof(url->user)) {
1405 fetch_info("login name in .netrc is too long");
1406 url->user[0] = '\0';
1408 } else if (strcmp(word, "password") == 0) {
1409 if ((word = fetch_read_word(f)) == NULL)
1411 if (snprintf(url->pwd, sizeof(url->pwd),
1412 "%s", word) > (int)sizeof(url->pwd)) {
1413 fetch_info("password in .netrc is too long");
1416 } else if (strcmp(word, "account") == 0) {
1417 if ((word = fetch_read_word(f)) == NULL)
1419 /* XXX not supported! */
1432 * The no_proxy environment variable specifies a set of domains for
1433 * which the proxy should not be consulted; the contents is a comma-,
1434 * or space-separated list of domain names. A single asterisk will
1435 * override all proxy variables and no transactions will be proxied
1436 * (for compatibility with lynx and curl, see the discussion at
1437 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1440 fetch_no_proxy_match(const char *host)
1442 const char *no_proxy, *p, *q;
1443 size_t h_len, d_len;
1445 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1446 (no_proxy = getenv("no_proxy")) == NULL)
1449 /* asterisk matches any hostname */
1450 if (strcmp(no_proxy, "*") == 0)
1453 h_len = strlen(host);
1456 /* position p at the beginning of a domain suffix */
1457 while (*p == ',' || isspace((unsigned char)*p))
1460 /* position q at the first separator character */
1461 for (q = p; *q; ++q)
1462 if (*q == ',' || isspace((unsigned char)*q))
1466 if (d_len > 0 && h_len >= d_len &&
1467 strncasecmp(host + h_len - d_len,
1469 /* domain name matches */