2 * Copyright (c) 1998-2011 Dag-Erling Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/socket.h>
37 #include <netinet/in.h>
54 /*** Local data **************************************************************/
57 * Error messages for resolver errors
59 static struct fetcherr netdb_errlist[] = {
61 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
63 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
64 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
65 { EAI_NONAME, FETCH_RESOLV, "No address record" },
66 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
70 static const char ENDL[2] = "\r\n";
73 /*** Error-reporting functions ***********************************************/
76 * Map error code to string
78 static struct fetcherr *
79 fetch_finderr(struct fetcherr *p, int e)
81 while (p->num != -1 && p->num != e)
90 fetch_seterr(struct fetcherr *p, int e)
92 p = fetch_finderr(p, e);
93 fetchLastErrCode = p->cat;
94 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
98 * Set error code according to errno
105 fetchLastErrCode = FETCH_OK;
112 fetchLastErrCode = FETCH_AUTH;
115 case EISDIR: /* XXX */
116 fetchLastErrCode = FETCH_UNAVAIL;
119 fetchLastErrCode = FETCH_MEMORY;
123 fetchLastErrCode = FETCH_TEMP;
126 fetchLastErrCode = FETCH_EXISTS;
129 fetchLastErrCode = FETCH_FULL;
137 fetchLastErrCode = FETCH_NETWORK;
141 fetchLastErrCode = FETCH_ABORT;
144 fetchLastErrCode = FETCH_TIMEOUT;
148 fetchLastErrCode = FETCH_DOWN;
151 fetchLastErrCode = FETCH_UNKNOWN;
153 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
158 * Emit status message
161 fetch_info(const char *fmt, ...)
166 vfprintf(stderr, fmt, ap);
172 /*** Network-related utility functions ***************************************/
175 * Return the default port for a scheme
178 fetch_default_port(const char *scheme)
182 if ((se = getservbyname(scheme, "tcp")) != NULL)
183 return (ntohs(se->s_port));
184 if (strcasecmp(scheme, SCHEME_FTP) == 0)
185 return (FTP_DEFAULT_PORT);
186 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
187 return (HTTP_DEFAULT_PORT);
192 * Return the default proxy port for a scheme
195 fetch_default_proxy_port(const char *scheme)
197 if (strcasecmp(scheme, SCHEME_FTP) == 0)
198 return (FTP_DEFAULT_PROXY_PORT);
199 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
200 return (HTTP_DEFAULT_PROXY_PORT);
206 * Create a connection for an existing descriptor.
214 /* allocate and fill connection structure */
215 if ((conn = calloc(1, sizeof(*conn))) == NULL)
217 fcntl(sd, F_SETFD, FD_CLOEXEC);
218 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
226 * Bump a connection's reference count.
229 fetch_ref(conn_t *conn)
238 * Bind a socket to a specific local address
241 fetch_bind(int sd, int af, const char *addr)
243 struct addrinfo hints, *res, *res0;
246 memset(&hints, 0, sizeof(hints));
247 hints.ai_family = af;
248 hints.ai_socktype = SOCK_STREAM;
249 hints.ai_protocol = 0;
250 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
252 for (res = res0; res; res = res->ai_next)
253 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
260 * Establish a TCP connection to the specified port on the specified host.
263 fetch_connect(const char *host, int port, int af, int verbose)
267 const char *bindaddr;
268 struct addrinfo hints, *res, *res0;
271 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
274 fetch_info("looking up %s", host);
276 /* look up host name and set up socket address structure */
277 snprintf(pbuf, sizeof(pbuf), "%d", port);
278 memset(&hints, 0, sizeof(hints));
279 hints.ai_family = af;
280 hints.ai_socktype = SOCK_STREAM;
281 hints.ai_protocol = 0;
282 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
286 bindaddr = getenv("FETCH_BIND_ADDRESS");
289 fetch_info("connecting to %s:%d", host, port);
292 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
293 if ((sd = socket(res->ai_family, res->ai_socktype,
294 res->ai_protocol)) == -1)
296 if (bindaddr != NULL && *bindaddr != '\0' &&
297 fetch_bind(sd, res->ai_family, bindaddr) != 0) {
298 fetch_info("failed to bind to '%s'", bindaddr);
302 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
303 fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
313 if ((conn = fetch_reopen(sd)) == NULL) {
322 * Enable SSL on a connection.
325 fetch_ssl(conn_t *conn, int verbose)
330 /* Init the SSL library and context */
331 if (!SSL_library_init()){
332 fprintf(stderr, "SSL library init failed\n");
336 SSL_load_error_strings();
338 conn->ssl_meth = SSLv23_client_method();
339 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
340 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
342 conn->ssl = SSL_new(conn->ssl_ctx);
343 if (conn->ssl == NULL){
344 fprintf(stderr, "SSL context creation failed\n");
347 SSL_set_fd(conn->ssl, conn->sd);
348 while ((ret = SSL_connect(conn->ssl)) == -1) {
349 ssl_err = SSL_get_error(conn->ssl, ret);
350 if (ssl_err != SSL_ERROR_WANT_READ &&
351 ssl_err != SSL_ERROR_WANT_WRITE) {
352 ERR_print_errors_fp(stderr);
361 fprintf(stderr, "SSL connection established using %s\n",
362 SSL_get_cipher(conn->ssl));
363 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
364 name = X509_get_subject_name(conn->ssl_cert);
365 str = X509_NAME_oneline(name, 0, 0);
366 printf("Certificate subject: %s\n", str);
368 name = X509_get_issuer_name(conn->ssl_cert);
369 str = X509_NAME_oneline(name, 0, 0);
370 printf("Certificate issuer: %s\n", str);
378 fprintf(stderr, "SSL support disabled\n");
383 #define FETCH_READ_WAIT -2
384 #define FETCH_READ_ERROR -1
385 #define FETCH_READ_DONE 0
389 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
394 rlen = SSL_read(ssl, buf, len);
396 ssl_err = SSL_get_error(ssl, rlen);
397 if (ssl_err == SSL_ERROR_WANT_READ ||
398 ssl_err == SSL_ERROR_WANT_WRITE) {
399 return (FETCH_READ_WAIT);
401 ERR_print_errors_fp(stderr);
402 return (FETCH_READ_ERROR);
410 * Cache some data that was read from a socket but cannot be immediately
411 * returned because of an interrupted system call.
414 fetch_cache_data(conn_t *conn, char *src, size_t nbytes)
418 if (conn->cache.size < nbytes) {
419 tmp = realloc(conn->cache.buf, nbytes);
424 conn->cache.buf = tmp;
425 conn->cache.size = nbytes;
428 memcpy(conn->cache.buf, src, nbytes);
429 conn->cache.len = nbytes;
437 fetch_socket_read(int sd, char *buf, size_t len)
441 rlen = read(sd, buf, len);
443 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
444 return (FETCH_READ_WAIT);
446 return (FETCH_READ_ERROR);
452 * Read a character from a connection w/ timeout
455 fetch_read(conn_t *conn, char *buf, size_t len)
457 struct timeval now, timeout, delta;
462 if (fetchTimeout > 0) {
463 gettimeofday(&timeout, NULL);
464 timeout.tv_sec += fetchTimeout;
470 if (conn->cache.len > 0) {
472 * The last invocation of fetch_read was interrupted by a
473 * signal after some data had been read from the socket. Copy
474 * the cached data into the supplied buffer before trying to
475 * read from the socket again.
477 total = (conn->cache.len < len) ? conn->cache.len : len;
478 memcpy(buf, conn->cache.buf, total);
480 conn->cache.len -= total;
481 conn->cache.pos += total;
488 * The socket is non-blocking. Instead of the canonical
489 * select() -> read(), we do the following:
491 * 1) call read() or SSL_read().
492 * 2) if an error occurred, return -1.
493 * 3) if we received data but we still expect more,
494 * update our counters and loop.
495 * 4) if read() or SSL_read() signaled EOF, return.
496 * 5) if we did not receive any data but we're not at EOF,
499 * In the SSL case, this is necessary because if we
500 * receive a close notification, we have to call
501 * SSL_read() one additional time after we've read
502 * everything we received.
504 * In the non-SSL case, it may improve performance (very
505 * slightly) when reading small amounts of data.
508 if (conn->ssl != NULL)
509 rlen = fetch_ssl_read(conn->ssl, buf, len);
512 rlen = fetch_socket_read(conn->sd, buf, len);
515 } else if (rlen > 0) {
520 } else if (rlen == FETCH_READ_ERROR) {
522 fetch_cache_data(conn, start, total);
525 // assert(rlen == FETCH_READ_WAIT);
527 while (!FD_ISSET(conn->sd, &readfds)) {
528 FD_SET(conn->sd, &readfds);
529 if (fetchTimeout > 0) {
530 gettimeofday(&now, NULL);
531 if (!timercmp(&timeout, &now, >)) {
536 timersub(&timeout, &now, &delta);
539 if (select(conn->sd + 1, &readfds, NULL, NULL,
540 fetchTimeout > 0 ? &delta : NULL) < 0) {
541 if (errno == EINTR) {
542 if (fetchRestartCalls)
544 /* Save anything that was read. */
545 fetch_cache_data(conn, start, total);
557 * Read a line of text from a connection w/ timeout
559 #define MIN_BUF_SIZE 1024
562 fetch_getln(conn_t *conn)
569 if (conn->buf == NULL) {
570 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
574 conn->bufsize = MIN_BUF_SIZE;
581 len = fetch_read(conn, &c, 1);
586 conn->buf[conn->buflen++] = c;
587 if (conn->buflen == conn->bufsize) {
589 tmpsize = conn->bufsize * 2 + 1;
590 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
595 conn->bufsize = tmpsize;
599 conn->buf[conn->buflen] = '\0';
600 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
606 * Write to a connection w/ timeout
609 fetch_write(conn_t *conn, const char *buf, size_t len)
613 iov.iov_base = __DECONST(char *, buf);
615 return fetch_writev(conn, &iov, 1);
619 * Write a vector to a connection w/ timeout
620 * Note: can modify the iovec.
623 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
625 struct timeval now, timeout, delta;
632 gettimeofday(&timeout, NULL);
633 timeout.tv_sec += fetchTimeout;
638 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
639 FD_SET(conn->sd, &writefds);
640 gettimeofday(&now, NULL);
641 delta.tv_sec = timeout.tv_sec - now.tv_sec;
642 delta.tv_usec = timeout.tv_usec - now.tv_usec;
643 if (delta.tv_usec < 0) {
644 delta.tv_usec += 1000000;
647 if (delta.tv_sec < 0) {
653 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
655 if (errno == EINTR && fetchRestartCalls)
662 if (conn->ssl != NULL)
663 wlen = SSL_write(conn->ssl,
664 iov->iov_base, iov->iov_len);
667 wlen = writev(conn->sd, iov, iovcnt);
669 /* we consider a short write a failure */
670 /* XXX perhaps we shouldn't in the SSL case */
676 if (errno == EINTR && fetchRestartCalls)
681 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
682 wlen -= iov->iov_len;
687 iov->iov_len -= wlen;
688 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
696 * Write a line of text to a connection w/ timeout
699 fetch_putln(conn_t *conn, const char *str, size_t len)
704 DEBUG(fprintf(stderr, ">>> %s\n", str));
705 iov[0].iov_base = __DECONST(char *, str);
706 iov[0].iov_len = len;
707 iov[1].iov_base = __DECONST(char *, ENDL);
708 iov[1].iov_len = sizeof(ENDL);
710 ret = fetch_writev(conn, &iov[1], 1);
712 ret = fetch_writev(conn, iov, 2);
723 fetch_close(conn_t *conn)
729 ret = close(conn->sd);
730 free(conn->cache.buf);
737 /*** Directory-related utility functions *************************************/
740 fetch_add_entry(struct url_ent **p, int *size, int *len,
741 const char *name, struct url_stat *us)
750 if (*len >= *size - 1) {
751 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
757 *size = (*size * 2 + 1);
762 snprintf(tmp->name, PATH_MAX, "%s", name);
763 memcpy(&tmp->stat, us, sizeof(*us));
766 (++tmp)->name[0] = 0;
772 /*** Authentication-related utility functions ********************************/
775 fetch_read_word(FILE *f)
777 static char word[1024];
779 if (fscanf(f, " %1023s ", word) != 1)
785 * Get authentication data for a URL from .netrc
788 fetch_netrc_auth(struct url *url)
795 if ((p = getenv("NETRC")) != NULL) {
796 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
797 fetch_info("$NETRC specifies a file name "
798 "longer than PATH_MAX");
802 if ((p = getenv("HOME")) != NULL) {
805 if ((pwd = getpwuid(getuid())) == NULL ||
806 (p = pwd->pw_dir) == NULL)
809 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
813 if ((f = fopen(fn, "r")) == NULL)
815 while ((word = fetch_read_word(f)) != NULL) {
816 if (strcmp(word, "default") == 0) {
817 DEBUG(fetch_info("Using default .netrc settings"));
820 if (strcmp(word, "machine") == 0 &&
821 (word = fetch_read_word(f)) != NULL &&
822 strcasecmp(word, url->host) == 0) {
823 DEBUG(fetch_info("Using .netrc settings for %s", word));
829 while ((word = fetch_read_word(f)) != NULL) {
830 if (strcmp(word, "login") == 0) {
831 if ((word = fetch_read_word(f)) == NULL)
833 if (snprintf(url->user, sizeof(url->user),
834 "%s", word) > (int)sizeof(url->user)) {
835 fetch_info("login name in .netrc is too long");
838 } else if (strcmp(word, "password") == 0) {
839 if ((word = fetch_read_word(f)) == NULL)
841 if (snprintf(url->pwd, sizeof(url->pwd),
842 "%s", word) > (int)sizeof(url->pwd)) {
843 fetch_info("password in .netrc is too long");
846 } else if (strcmp(word, "account") == 0) {
847 if ((word = fetch_read_word(f)) == NULL)
849 /* XXX not supported! */
862 * The no_proxy environment variable specifies a set of domains for
863 * which the proxy should not be consulted; the contents is a comma-,
864 * or space-separated list of domain names. A single asterisk will
865 * override all proxy variables and no transactions will be proxied
866 * (for compatability with lynx and curl, see the discussion at
867 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
870 fetch_no_proxy_match(const char *host)
872 const char *no_proxy, *p, *q;
875 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
876 (no_proxy = getenv("no_proxy")) == NULL)
879 /* asterisk matches any hostname */
880 if (strcmp(no_proxy, "*") == 0)
883 h_len = strlen(host);
886 /* position p at the beginning of a domain suffix */
887 while (*p == ',' || isspace((unsigned char)*p))
890 /* position q at the first separator character */
892 if (*q == ',' || isspace((unsigned char)*q))
896 if (d_len > 0 && h_len >= d_len &&
897 strncasecmp(host + h_len - d_len,
899 /* domain name matches */