2 * Copyright (c) 1998-2011 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>
52 #include <openssl/x509v3.h>
59 /*** Local data **************************************************************/
62 * Error messages for resolver errors
64 static struct fetcherr netdb_errlist[] = {
66 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
68 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
69 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
70 { EAI_NONAME, FETCH_RESOLV, "No address record" },
71 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
75 static const char ENDL[2] = "\r\n";
78 /*** Error-reporting functions ***********************************************/
81 * Map error code to string
83 static struct fetcherr *
84 fetch_finderr(struct fetcherr *p, int e)
86 while (p->num != -1 && p->num != e)
95 fetch_seterr(struct fetcherr *p, int e)
97 p = fetch_finderr(p, e);
98 fetchLastErrCode = p->cat;
99 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
103 * Set error code according to errno
110 fetchLastErrCode = FETCH_OK;
117 fetchLastErrCode = FETCH_AUTH;
120 case EISDIR: /* XXX */
121 fetchLastErrCode = FETCH_UNAVAIL;
124 fetchLastErrCode = FETCH_MEMORY;
128 fetchLastErrCode = FETCH_TEMP;
131 fetchLastErrCode = FETCH_EXISTS;
134 fetchLastErrCode = FETCH_FULL;
142 fetchLastErrCode = FETCH_NETWORK;
146 fetchLastErrCode = FETCH_ABORT;
149 fetchLastErrCode = FETCH_TIMEOUT;
153 fetchLastErrCode = FETCH_DOWN;
156 fetchLastErrCode = FETCH_UNKNOWN;
158 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
163 * Emit status message
166 fetch_info(const char *fmt, ...)
171 vfprintf(stderr, fmt, ap);
177 /*** Network-related utility functions ***************************************/
180 * Return the default port for a scheme
183 fetch_default_port(const char *scheme)
187 if ((se = getservbyname(scheme, "tcp")) != NULL)
188 return (ntohs(se->s_port));
189 if (strcasecmp(scheme, SCHEME_FTP) == 0)
190 return (FTP_DEFAULT_PORT);
191 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
192 return (HTTP_DEFAULT_PORT);
197 * Return the default proxy port for a scheme
200 fetch_default_proxy_port(const char *scheme)
202 if (strcasecmp(scheme, SCHEME_FTP) == 0)
203 return (FTP_DEFAULT_PROXY_PORT);
204 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
205 return (HTTP_DEFAULT_PROXY_PORT);
211 * Create a connection for an existing descriptor.
219 /* allocate and fill connection structure */
220 if ((conn = calloc(1, sizeof(*conn))) == NULL)
222 fcntl(sd, F_SETFD, FD_CLOEXEC);
223 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
231 * Bump a connection's reference count.
234 fetch_ref(conn_t *conn)
243 * Bind a socket to a specific local address
246 fetch_bind(int sd, int af, const char *addr)
248 struct addrinfo hints, *res, *res0;
251 memset(&hints, 0, sizeof(hints));
252 hints.ai_family = af;
253 hints.ai_socktype = SOCK_STREAM;
254 hints.ai_protocol = 0;
255 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
257 for (res = res0; res; res = res->ai_next)
258 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
265 * Establish a TCP connection to the specified port on the specified host.
268 fetch_connect(const char *host, int port, int af, int verbose)
272 const char *bindaddr;
273 struct addrinfo hints, *res, *res0;
276 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
279 fetch_info("looking up %s", host);
281 /* look up host name and set up socket address structure */
282 snprintf(pbuf, sizeof(pbuf), "%d", port);
283 memset(&hints, 0, sizeof(hints));
284 hints.ai_family = af;
285 hints.ai_socktype = SOCK_STREAM;
286 hints.ai_protocol = 0;
287 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
291 bindaddr = getenv("FETCH_BIND_ADDRESS");
294 fetch_info("connecting to %s:%d", host, port);
297 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
298 if ((sd = socket(res->ai_family, res->ai_socktype,
299 res->ai_protocol)) == -1)
301 if (bindaddr != NULL && *bindaddr != '\0' &&
302 fetch_bind(sd, res->ai_family, bindaddr) != 0) {
303 fetch_info("failed to bind to '%s'", bindaddr);
307 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
308 fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
318 if ((conn = fetch_reopen(sd)) == NULL) {
327 * Convert characters A-Z to lowercase (intentionally avoid any locale
328 * specific conversions).
331 fetch_ssl_tolower(char in)
333 if (in >= 'A' && in <= 'Z')
340 * isalpha implementation that intentionally avoids any locale specific
344 fetch_ssl_isalpha(char in)
346 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
350 * Check if passed hostnames a and b are equal.
353 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
360 for (i = 0; i < alen; ++i) {
361 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
368 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
369 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
370 * numeric characters. Double hyphens (like they're found in IDN a-labels
371 * 'xn--') are not allowed. Empty labels are invalid.
374 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
378 if (!len || l[0] == '-' || l[len-1] == '-')
380 for (i = 0; i < len; ++i) {
381 if (!isdigit(l[i]) &&
382 !fetch_ssl_isalpha(l[i]) &&
383 !(l[i] == '*' && wcok) &&
384 !(l[i] == '-' && l[i - 1] != '-'))
391 * Check if host name consists only of numbers. This might indicate an IP
392 * address, which is not a good idea for CN wildcard comparison.
395 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
399 for (i = 0; i < len; ++i) {
400 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
408 * Check if the host name h passed matches the pattern passed in m which
409 * is usually part of subjectAltName or CN of a certificate presented to
410 * the client. This includes wildcard matching. The algorithm is based on
411 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
414 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
417 int delta, hdotidx, mdot1idx, wcidx;
418 const char *hdot, *mdot1, *mdot2;
419 const char *wc; /* wildcard */
421 if (!(h && *h && m && *m))
423 if ((wc = strnstr(m, "*", mlen)) == NULL)
424 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
426 /* hostname should not be just dots and numbers */
427 if (fetch_ssl_hname_is_only_numbers(h, hlen))
429 /* only one wildcard allowed in pattern */
430 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
433 * there must be at least two more domain labels and
434 * wildcard has to be in the leftmost label (RFC6125)
436 mdot1 = strnstr(m, ".", mlen);
437 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
439 mdot1idx = mdot1 - m;
440 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
441 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
443 /* hostname must contain a dot and not be the 1st char */
444 hdot = strnstr(h, ".", hlen);
445 if (hdot == NULL || hdot == h)
449 * host part of hostname must be at least as long as
450 * pattern it's supposed to match
452 if (hdotidx < mdot1idx)
455 * don't allow wildcards in non-traditional domain names
456 * (IDN, A-label, U-label...)
458 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
459 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
461 /* match domain part (part after first dot) */
462 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
465 /* match part left of wildcard */
466 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
468 /* match part right of wildcard */
469 delta = mdot1idx - wcidx - 1;
470 if (!fetch_ssl_hname_equal(hdot - delta, delta,
471 mdot1 - delta, delta))
473 /* all tests succeded, it's a match */
478 * Get numeric host address info - returns NULL if host was not an IP
479 * address. The caller is responsible for deallocation using
482 static struct addrinfo *
483 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
485 struct addrinfo hints, *res;
488 host = (char *)malloc(len + 1);
489 memcpy(host, hostname, len);
491 memset(&hints, 0, sizeof(hints));
492 hints.ai_family = PF_UNSPEC;
493 hints.ai_socktype = SOCK_STREAM;
494 hints.ai_protocol = 0;
495 hints.ai_flags = AI_NUMERICHOST;
496 /* port is not relevant for this purpose */
497 getaddrinfo(host, "443", &hints, &res);
503 * Compare ip address in addrinfo with address passes.
506 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
511 if (lhost->ai_family == AF_INET && rhostlen == 4) {
512 left = (void *)&((struct sockaddr_in*)(void *)
513 lhost->ai_addr)->sin_addr.s_addr;
515 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
516 left = (void *)&((struct sockaddr_in6 *)(void *)
517 lhost->ai_addr)->sin6_addr;
521 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
525 * Compare ip address in addrinfo with host passed. If host is not an IP
526 * address, comparison will fail.
529 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
532 struct addrinfo *raddr;
537 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
538 return 0; /* not a numeric host */
540 if (laddr->ai_family == raddr->ai_family) {
541 if (laddr->ai_family == AF_INET) {
542 rip = (char *)&((struct sockaddr_in *)(void *)
543 raddr->ai_addr)->sin_addr.s_addr;
544 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
546 } else if (laddr->ai_family == AF_INET6) {
547 rip = (char *)&((struct sockaddr_in6 *)(void *)
548 raddr->ai_addr)->sin6_addr;
549 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
559 * Verify server certificate by subjectAltName.
562 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
563 const char *host, struct addrinfo *ip)
565 const GENERAL_NAME *name;
570 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
571 #if OPENSSL_VERSION_NUMBER < 0x10000000L
573 * This is a workaround, since the following line causes
574 * alignment issues in clang:
575 * name = sk_GENERAL_NAME_value(altnames, i);
576 * OpenSSL explicitly warns not to use those macros
577 * directly, but there isn't much choice (and there
578 * shouldn't be any ill side effects)
580 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
582 name = sk_GENERAL_NAME_value(altnames, i);
584 ns = (const char *)ASN1_STRING_data(name->d.ia5);
585 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
587 if (name->type == GEN_DNS && ip == NULL &&
588 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
590 else if (name->type == GEN_IPADD && ip != NULL &&
591 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
598 * Verify server certificate by CN.
601 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
604 ASN1_STRING *namedata;
605 X509_NAME_ENTRY *nameentry;
606 int cnlen, lastpos, loc, ret;
613 /* get most specific CN (last entry in list) and compare */
614 while ((lastpos = X509_NAME_get_index_by_NID(subject,
615 NID_commonName, lastpos)) != -1)
619 nameentry = X509_NAME_get_entry(subject, loc);
620 namedata = X509_NAME_ENTRY_get_data(nameentry);
621 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
623 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
625 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
633 * Verify that server certificate subjectAltName/CN matches
634 * hostname. First check, if there are alternative subject names. If yes,
635 * those have to match. Only if those don't exist it falls back to
636 * checking the subject's CN.
639 fetch_ssl_verify_hname(X509 *cert, const char *host)
642 STACK_OF(GENERAL_NAME) *altnames;
647 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
648 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
651 if (altnames != NULL) {
652 ret = fetch_ssl_verify_altname(altnames, host, ip);
654 subject = X509_get_subject_name(cert);
656 ret = fetch_ssl_verify_cn(subject, host, ip);
661 if (altnames != NULL)
662 GENERAL_NAMES_free(altnames);
667 * Configure transport security layer based on environment.
670 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
672 long ssl_ctx_options;
674 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_TICKET;
675 if (getenv("SSL_ALLOW_SSL2") == NULL)
676 ssl_ctx_options |= SSL_OP_NO_SSLv2;
677 if (getenv("SSL_NO_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: %x", ssl_ctx_options);
683 SSL_CTX_set_options(ctx, ssl_ctx_options);
688 * Configure peer verification based on environment.
691 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
693 X509_LOOKUP *crl_lookup;
694 X509_STORE *crl_store;
695 const char *ca_cert_file, *ca_cert_path, *crl_file;
697 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
698 ca_cert_file = getenv("SSL_CA_CERT_FILE") != NULL ?
699 getenv("SSL_CA_CERT_FILE") : "/etc/ssl/cert.pem";
700 ca_cert_path = getenv("SSL_CA_CERT_PATH");
702 fetch_info("Peer verification enabled");
703 if (ca_cert_file != NULL)
704 fetch_info("Using CA cert file: %s",
706 if (ca_cert_path != NULL)
707 fetch_info("Using CA cert path: %s",
710 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
711 fetch_ssl_cb_verify_crt);
712 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
714 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
716 fetch_info("Using CRL file: %s", crl_file);
717 crl_store = SSL_CTX_get_cert_store(ctx);
718 crl_lookup = X509_STORE_add_lookup(crl_store,
720 if (crl_lookup == NULL ||
721 !X509_load_crl_file(crl_lookup, crl_file,
722 X509_FILETYPE_PEM)) {
724 "Could not load CRL file %s\n",
728 X509_STORE_set_flags(crl_store,
729 X509_V_FLAG_CRL_CHECK |
730 X509_V_FLAG_CRL_CHECK_ALL);
737 * Configure client certificate based on environment.
740 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
742 const char *client_cert_file, *client_key_file;
744 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
745 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
746 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
748 fetch_info("Using client cert file: %s",
750 fetch_info("Using client key file: %s",
753 if (SSL_CTX_use_certificate_chain_file(ctx,
754 client_cert_file) != 1) {
756 "Could not load client certificate %s\n",
760 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
761 SSL_FILETYPE_PEM) != 1) {
763 "Could not load client key %s\n",
772 * Callback for SSL certificate verification, this is called on server
773 * cert verification. It takes no decision, but informs the user in case
774 * verification failed.
777 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
785 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
786 (name = X509_get_subject_name(crt)) != NULL)
787 str = X509_NAME_oneline(name, 0, 0);
788 fprintf(stderr, "Certificate verification failed for %s\n",
789 str != NULL ? str : "no relevant certificate");
798 * Enable SSL on a connection.
801 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
808 /* Init the SSL library and context */
809 if (!SSL_library_init()){
810 fprintf(stderr, "SSL library init failed\n");
814 SSL_load_error_strings();
816 conn->ssl_meth = SSLv23_client_method();
817 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
818 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
820 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
821 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
823 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
826 conn->ssl = SSL_new(conn->ssl_ctx);
827 if (conn->ssl == NULL) {
828 fprintf(stderr, "SSL context creation failed\n");
831 SSL_set_fd(conn->ssl, conn->sd);
832 while ((ret = SSL_connect(conn->ssl)) == -1) {
833 ssl_err = SSL_get_error(conn->ssl, ret);
834 if (ssl_err != SSL_ERROR_WANT_READ &&
835 ssl_err != SSL_ERROR_WANT_WRITE) {
836 ERR_print_errors_fp(stderr);
840 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
842 if (conn->ssl_cert == NULL) {
843 fprintf(stderr, "No server SSL certificate\n");
847 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
849 fetch_info("Verify hostname");
850 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
852 "SSL certificate subject doesn't match host %s\n",
859 fetch_info("SSL connection established using %s",
860 SSL_get_cipher(conn->ssl));
861 name = X509_get_subject_name(conn->ssl_cert);
862 str = X509_NAME_oneline(name, 0, 0);
863 fetch_info("Certificate subject: %s", str);
865 name = X509_get_issuer_name(conn->ssl_cert);
866 str = X509_NAME_oneline(name, 0, 0);
867 fetch_info("Certificate issuer: %s", str);
875 fprintf(stderr, "SSL support disabled\n");
880 #define FETCH_READ_WAIT -2
881 #define FETCH_READ_ERROR -1
882 #define FETCH_READ_DONE 0
886 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
891 rlen = SSL_read(ssl, buf, len);
893 ssl_err = SSL_get_error(ssl, rlen);
894 if (ssl_err == SSL_ERROR_WANT_READ ||
895 ssl_err == SSL_ERROR_WANT_WRITE) {
896 return (FETCH_READ_WAIT);
898 ERR_print_errors_fp(stderr);
899 return (FETCH_READ_ERROR);
907 * Cache some data that was read from a socket but cannot be immediately
908 * returned because of an interrupted system call.
911 fetch_cache_data(conn_t *conn, char *src, size_t nbytes)
915 if (conn->cache.size < nbytes) {
916 tmp = realloc(conn->cache.buf, nbytes);
921 conn->cache.buf = tmp;
922 conn->cache.size = nbytes;
925 memcpy(conn->cache.buf, src, nbytes);
926 conn->cache.len = nbytes;
934 fetch_socket_read(int sd, char *buf, size_t len)
938 rlen = read(sd, buf, len);
940 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
941 return (FETCH_READ_WAIT);
943 return (FETCH_READ_ERROR);
949 * Read a character from a connection w/ timeout
952 fetch_read(conn_t *conn, char *buf, size_t len)
954 struct timeval now, timeout, delta;
959 if (fetchTimeout > 0) {
960 gettimeofday(&timeout, NULL);
961 timeout.tv_sec += fetchTimeout;
967 if (conn->cache.len > 0) {
969 * The last invocation of fetch_read was interrupted by a
970 * signal after some data had been read from the socket. Copy
971 * the cached data into the supplied buffer before trying to
972 * read from the socket again.
974 total = (conn->cache.len < len) ? conn->cache.len : len;
975 memcpy(buf, conn->cache.buf, total);
977 conn->cache.len -= total;
978 conn->cache.pos += total;
985 * The socket is non-blocking. Instead of the canonical
986 * select() -> read(), we do the following:
988 * 1) call read() or SSL_read().
989 * 2) if an error occurred, return -1.
990 * 3) if we received data but we still expect more,
991 * update our counters and loop.
992 * 4) if read() or SSL_read() signaled EOF, return.
993 * 5) if we did not receive any data but we're not at EOF,
996 * In the SSL case, this is necessary because if we
997 * receive a close notification, we have to call
998 * SSL_read() one additional time after we've read
999 * everything we received.
1001 * In the non-SSL case, it may improve performance (very
1002 * slightly) when reading small amounts of data.
1005 if (conn->ssl != NULL)
1006 rlen = fetch_ssl_read(conn->ssl, buf, len);
1009 rlen = fetch_socket_read(conn->sd, buf, len);
1012 } else if (rlen > 0) {
1017 } else if (rlen == FETCH_READ_ERROR) {
1019 fetch_cache_data(conn, start, total);
1022 // assert(rlen == FETCH_READ_WAIT);
1024 while (!FD_ISSET(conn->sd, &readfds)) {
1025 FD_SET(conn->sd, &readfds);
1026 if (fetchTimeout > 0) {
1027 gettimeofday(&now, NULL);
1028 if (!timercmp(&timeout, &now, >)) {
1033 timersub(&timeout, &now, &delta);
1036 if (select(conn->sd + 1, &readfds, NULL, NULL,
1037 fetchTimeout > 0 ? &delta : NULL) < 0) {
1038 if (errno == EINTR) {
1039 if (fetchRestartCalls)
1041 /* Save anything that was read. */
1042 fetch_cache_data(conn, start, total);
1054 * Read a line of text from a connection w/ timeout
1056 #define MIN_BUF_SIZE 1024
1059 fetch_getln(conn_t *conn)
1066 if (conn->buf == NULL) {
1067 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1071 conn->bufsize = MIN_BUF_SIZE;
1074 conn->buf[0] = '\0';
1078 len = fetch_read(conn, &c, 1);
1083 conn->buf[conn->buflen++] = c;
1084 if (conn->buflen == conn->bufsize) {
1086 tmpsize = conn->bufsize * 2 + 1;
1087 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1092 conn->bufsize = tmpsize;
1094 } while (c != '\n');
1096 conn->buf[conn->buflen] = '\0';
1097 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
1103 * Write to a connection w/ timeout
1106 fetch_write(conn_t *conn, const char *buf, size_t len)
1110 iov.iov_base = __DECONST(char *, buf);
1112 return fetch_writev(conn, &iov, 1);
1116 * Write a vector to a connection w/ timeout
1117 * Note: can modify the iovec.
1120 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1122 struct timeval now, timeout, delta;
1124 ssize_t wlen, total;
1129 gettimeofday(&timeout, NULL);
1130 timeout.tv_sec += fetchTimeout;
1134 while (iovcnt > 0) {
1135 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
1136 FD_SET(conn->sd, &writefds);
1137 gettimeofday(&now, NULL);
1138 delta.tv_sec = timeout.tv_sec - now.tv_sec;
1139 delta.tv_usec = timeout.tv_usec - now.tv_usec;
1140 if (delta.tv_usec < 0) {
1141 delta.tv_usec += 1000000;
1144 if (delta.tv_sec < 0) {
1150 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
1152 if (errno == EINTR && fetchRestartCalls)
1159 if (conn->ssl != NULL)
1160 wlen = SSL_write(conn->ssl,
1161 iov->iov_base, iov->iov_len);
1164 wlen = writev(conn->sd, iov, iovcnt);
1166 /* we consider a short write a failure */
1167 /* XXX perhaps we shouldn't in the SSL case */
1173 if (errno == EINTR && fetchRestartCalls)
1178 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1179 wlen -= iov->iov_len;
1184 iov->iov_len -= wlen;
1185 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1193 * Write a line of text to a connection w/ timeout
1196 fetch_putln(conn_t *conn, const char *str, size_t len)
1198 struct iovec iov[2];
1201 DEBUG(fprintf(stderr, ">>> %s\n", str));
1202 iov[0].iov_base = __DECONST(char *, str);
1203 iov[0].iov_len = len;
1204 iov[1].iov_base = __DECONST(char *, ENDL);
1205 iov[1].iov_len = sizeof(ENDL);
1207 ret = fetch_writev(conn, &iov[1], 1);
1209 ret = fetch_writev(conn, iov, 2);
1220 fetch_close(conn_t *conn)
1224 if (--conn->ref > 0)
1228 SSL_shutdown(conn->ssl);
1229 SSL_set_connect_state(conn->ssl);
1230 SSL_free(conn->ssl);
1233 if (conn->ssl_ctx) {
1234 SSL_CTX_free(conn->ssl_ctx);
1235 conn->ssl_ctx = NULL;
1237 if (conn->ssl_cert) {
1238 X509_free(conn->ssl_cert);
1239 conn->ssl_cert = NULL;
1242 ret = close(conn->sd);
1243 free(conn->cache.buf);
1250 /*** Directory-related utility functions *************************************/
1253 fetch_add_entry(struct url_ent **p, int *size, int *len,
1254 const char *name, struct url_stat *us)
1256 struct url_ent *tmp;
1263 if (*len >= *size - 1) {
1264 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
1270 *size = (*size * 2 + 1);
1275 snprintf(tmp->name, PATH_MAX, "%s", name);
1276 memcpy(&tmp->stat, us, sizeof(*us));
1279 (++tmp)->name[0] = 0;
1285 /*** Authentication-related utility functions ********************************/
1288 fetch_read_word(FILE *f)
1290 static char word[1024];
1292 if (fscanf(f, " %1023s ", word) != 1)
1298 * Get authentication data for a URL from .netrc
1301 fetch_netrc_auth(struct url *url)
1308 if ((p = getenv("NETRC")) != NULL) {
1309 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1310 fetch_info("$NETRC specifies a file name "
1311 "longer than PATH_MAX");
1315 if ((p = getenv("HOME")) != NULL) {
1318 if ((pwd = getpwuid(getuid())) == NULL ||
1319 (p = pwd->pw_dir) == NULL)
1322 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1326 if ((f = fopen(fn, "r")) == NULL)
1328 while ((word = fetch_read_word(f)) != NULL) {
1329 if (strcmp(word, "default") == 0) {
1330 DEBUG(fetch_info("Using default .netrc settings"));
1333 if (strcmp(word, "machine") == 0 &&
1334 (word = fetch_read_word(f)) != NULL &&
1335 strcasecmp(word, url->host) == 0) {
1336 DEBUG(fetch_info("Using .netrc settings for %s", word));
1342 while ((word = fetch_read_word(f)) != NULL) {
1343 if (strcmp(word, "login") == 0) {
1344 if ((word = fetch_read_word(f)) == NULL)
1346 if (snprintf(url->user, sizeof(url->user),
1347 "%s", word) > (int)sizeof(url->user)) {
1348 fetch_info("login name in .netrc is too long");
1349 url->user[0] = '\0';
1351 } else if (strcmp(word, "password") == 0) {
1352 if ((word = fetch_read_word(f)) == NULL)
1354 if (snprintf(url->pwd, sizeof(url->pwd),
1355 "%s", word) > (int)sizeof(url->pwd)) {
1356 fetch_info("password in .netrc is too long");
1359 } else if (strcmp(word, "account") == 0) {
1360 if ((word = fetch_read_word(f)) == NULL)
1362 /* XXX not supported! */
1375 * The no_proxy environment variable specifies a set of domains for
1376 * which the proxy should not be consulted; the contents is a comma-,
1377 * or space-separated list of domain names. A single asterisk will
1378 * override all proxy variables and no transactions will be proxied
1379 * (for compatability with lynx and curl, see the discussion at
1380 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1383 fetch_no_proxy_match(const char *host)
1385 const char *no_proxy, *p, *q;
1386 size_t h_len, d_len;
1388 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1389 (no_proxy = getenv("no_proxy")) == NULL)
1392 /* asterisk matches any hostname */
1393 if (strcmp(no_proxy, "*") == 0)
1396 h_len = strlen(host);
1399 /* position p at the beginning of a domain suffix */
1400 while (*p == ',' || isspace((unsigned char)*p))
1403 /* position q at the first separator character */
1404 for (q = p; *q; ++q)
1405 if (*q == ',' || isspace((unsigned char)*q))
1409 if (d_len > 0 && h_len >= d_len &&
1410 strncasecmp(host + h_len - d_len,
1412 /* domain name matches */