2 * Copyright (c) 1998-2004 Dag-Erling Coïdan 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.
28 * $FreeBSD: src/lib/libfetch/common.c,v 1.56 2008/04/15 23:29:51 cperciva Exp $
31 #include <sys/param.h>
32 #include <sys/socket.h>
36 #include <netinet/in.h>
52 /*** Local data **************************************************************/
55 * Error messages for resolver errors
57 static struct fetcherr netdb_errlist[] = {
59 { EAI_NODATA, FETCH_RESOLV, "Host not found" },
61 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
62 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
63 { EAI_NONAME, FETCH_RESOLV, "No address record" },
64 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
68 static const char ENDL[2] = "\r\n";
71 /*** Error-reporting functions ***********************************************/
74 * Map error code to string
76 static struct fetcherr *
77 fetch_finderr(struct fetcherr *p, int e)
79 while (p->num != -1 && p->num != e)
88 fetch_seterr(struct fetcherr *p, int e)
90 p = fetch_finderr(p, e);
91 fetchLastErrCode = p->cat;
92 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
96 * Set error code according to errno
103 fetchLastErrCode = FETCH_OK;
110 fetchLastErrCode = FETCH_AUTH;
113 case EISDIR: /* XXX */
114 fetchLastErrCode = FETCH_UNAVAIL;
117 fetchLastErrCode = FETCH_MEMORY;
121 fetchLastErrCode = FETCH_TEMP;
124 fetchLastErrCode = FETCH_EXISTS;
127 fetchLastErrCode = FETCH_FULL;
135 fetchLastErrCode = FETCH_NETWORK;
139 fetchLastErrCode = FETCH_ABORT;
142 fetchLastErrCode = FETCH_TIMEOUT;
146 fetchLastErrCode = FETCH_DOWN;
149 fetchLastErrCode = FETCH_UNKNOWN;
151 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
156 * Emit status message
159 fetch_info(const char *fmt, ...)
164 vfprintf(stderr, fmt, ap);
170 /*** Network-related utility functions ***************************************/
173 * Return the default port for a scheme
176 fetch_default_port(const char *scheme)
180 if ((se = getservbyname(scheme, "tcp")) != NULL)
181 return (ntohs(se->s_port));
182 if (strcasecmp(scheme, SCHEME_FTP) == 0)
183 return (FTP_DEFAULT_PORT);
184 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
185 return (HTTP_DEFAULT_PORT);
190 * Return the default proxy port for a scheme
193 fetch_default_proxy_port(const char *scheme)
195 if (strcasecmp(scheme, SCHEME_FTP) == 0)
196 return (FTP_DEFAULT_PROXY_PORT);
197 if (strcasecmp(scheme, SCHEME_HTTP) == 0)
198 return (HTTP_DEFAULT_PROXY_PORT);
204 * Create a connection for an existing descriptor.
211 /* allocate and fill connection structure */
212 if ((conn = calloc(1, sizeof(*conn))) == NULL)
221 * Bump a connection's reference count.
224 fetch_ref(conn_t *conn)
233 * Bind a socket to a specific local address
236 fetch_bind(int sd, int af, const char *addr)
238 struct addrinfo hints, *res, *res0;
241 memset(&hints, 0, sizeof(hints));
242 hints.ai_family = af;
243 hints.ai_socktype = SOCK_STREAM;
244 hints.ai_protocol = 0;
245 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
247 for (res = res0; res; res = res->ai_next)
248 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
255 * Establish a TCP connection to the specified port on the specified host.
258 fetch_connect(const char *host, int port, int af, int verbose)
262 const char *bindaddr;
263 struct addrinfo hints, *res, *res0;
266 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
269 fetch_info("looking up %s", host);
271 /* look up host name and set up socket address structure */
272 snprintf(pbuf, sizeof(pbuf), "%d", port);
273 memset(&hints, 0, sizeof(hints));
274 hints.ai_family = af;
275 hints.ai_socktype = SOCK_STREAM;
276 hints.ai_protocol = 0;
277 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
281 bindaddr = getenv("FETCH_BIND_ADDRESS");
284 fetch_info("connecting to %s:%d", host, port);
287 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
288 if ((sd = socket(res->ai_family, res->ai_socktype,
289 res->ai_protocol)) == -1)
291 if (bindaddr != NULL && *bindaddr != '\0' &&
292 fetch_bind(sd, res->ai_family, bindaddr) != 0) {
293 fetch_info("failed to bind to '%s'", bindaddr);
297 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0)
307 if ((conn = fetch_reopen(sd)) == NULL) {
316 * Enable SSL on a connection.
319 fetch_ssl(conn_t *conn, int verbose)
323 /* Init the SSL library and context */
324 if (!SSL_library_init()){
325 fprintf(stderr, "SSL library init failed\n");
329 SSL_load_error_strings();
331 conn->ssl_meth = SSLv23_client_method();
332 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
333 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
335 conn->ssl = SSL_new(conn->ssl_ctx);
336 if (conn->ssl == NULL){
337 fprintf(stderr, "SSL context creation failed\n");
340 SSL_set_fd(conn->ssl, conn->sd);
341 if (SSL_connect(conn->ssl) == -1){
342 ERR_print_errors_fp(stderr);
350 fprintf(stderr, "SSL connection established using %s\n",
351 SSL_get_cipher(conn->ssl));
352 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
353 name = X509_get_subject_name(conn->ssl_cert);
354 str = X509_NAME_oneline(name, 0, 0);
355 printf("Certificate subject: %s\n", str);
357 name = X509_get_issuer_name(conn->ssl_cert);
358 str = X509_NAME_oneline(name, 0, 0);
359 printf("Certificate issuer: %s\n", str);
367 fprintf(stderr, "SSL support disabled\n");
374 * Read a character from a connection w/ timeout
377 fetch_read(conn_t *conn, char *buf, size_t len)
379 struct timeval now, timeout, delta;
386 gettimeofday(&timeout, NULL);
387 timeout.tv_sec += fetchTimeout;
392 while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) {
393 FD_SET(conn->sd, &readfds);
394 gettimeofday(&now, NULL);
395 delta.tv_sec = timeout.tv_sec - now.tv_sec;
396 delta.tv_usec = timeout.tv_usec - now.tv_usec;
397 if (delta.tv_usec < 0) {
398 delta.tv_usec += 1000000;
401 if (delta.tv_sec < 0) {
407 r = select(conn->sd + 1, &readfds, NULL, NULL, &delta);
409 if (errno == EINTR && fetchRestartCalls)
416 if (conn->ssl != NULL)
417 rlen = SSL_read(conn->ssl, buf, len);
420 rlen = read(conn->sd, buf, len);
424 if (errno == EINTR && fetchRestartCalls)
437 * Read a line of text from a connection w/ timeout
439 #define MIN_BUF_SIZE 1024
442 fetch_getln(conn_t *conn)
449 if (conn->buf == NULL) {
450 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
454 conn->bufsize = MIN_BUF_SIZE;
461 len = fetch_read(conn, &c, 1);
466 conn->buf[conn->buflen++] = c;
467 if (conn->buflen == conn->bufsize) {
469 tmpsize = conn->bufsize * 2 + 1;
470 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
475 conn->bufsize = tmpsize;
479 conn->buf[conn->buflen] = '\0';
480 DEBUG(fprintf(stderr, "<<< %s", conn->buf));
486 * Write to a connection w/ timeout
489 fetch_write(conn_t *conn, const char *buf, size_t len)
493 iov.iov_base = __DECONST(char *, buf);
495 return fetch_writev(conn, &iov, 1);
499 * Write a vector to a connection w/ timeout
500 * Note: can modify the iovec.
503 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
505 struct timeval now, timeout, delta;
512 gettimeofday(&timeout, NULL);
513 timeout.tv_sec += fetchTimeout;
518 while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
519 FD_SET(conn->sd, &writefds);
520 gettimeofday(&now, NULL);
521 delta.tv_sec = timeout.tv_sec - now.tv_sec;
522 delta.tv_usec = timeout.tv_usec - now.tv_usec;
523 if (delta.tv_usec < 0) {
524 delta.tv_usec += 1000000;
527 if (delta.tv_sec < 0) {
533 r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
535 if (errno == EINTR && fetchRestartCalls)
542 if (conn->ssl != NULL)
543 wlen = SSL_write(conn->ssl,
544 iov->iov_base, iov->iov_len);
547 wlen = writev(conn->sd, iov, iovcnt);
549 /* we consider a short write a failure */
555 if (errno == EINTR && fetchRestartCalls)
560 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
561 wlen -= iov->iov_len;
566 iov->iov_len -= wlen;
567 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
575 * Write a line of text to a connection w/ timeout
578 fetch_putln(conn_t *conn, const char *str, size_t len)
583 DEBUG(fprintf(stderr, ">>> %s\n", str));
584 iov[0].iov_base = __DECONST(char *, str);
585 iov[0].iov_len = len;
586 iov[1].iov_base = __DECONST(char *, ENDL);
587 iov[1].iov_len = sizeof(ENDL);
589 ret = fetch_writev(conn, &iov[1], 1);
591 ret = fetch_writev(conn, iov, 2);
602 fetch_close(conn_t *conn)
608 ret = close(conn->sd);
615 /*** Directory-related utility functions *************************************/
618 fetch_add_entry(struct url_ent **p, int *size, int *len,
619 const char *name, struct url_stat *us)
628 if (*len >= *size - 1) {
629 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
635 *size = (*size * 2 + 1);
640 snprintf(tmp->name, PATH_MAX, "%s", name);
641 memcpy(&tmp->stat, us, sizeof(*us));
644 (++tmp)->name[0] = 0;
650 /*** Authentication-related utility functions ********************************/
653 fetch_read_word(FILE *f)
655 static char word[1024];
657 if (fscanf(f, " %1023s ", word) != 1)
663 * Get authentication data for a URL from .netrc
666 fetch_netrc_auth(struct url *url)
673 if ((p = getenv("NETRC")) != NULL) {
674 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
675 fetch_info("$NETRC specifies a file name "
676 "longer than PATH_MAX");
680 if ((p = getenv("HOME")) != NULL) {
683 if ((pwd = getpwuid(getuid())) == NULL ||
684 (p = pwd->pw_dir) == NULL)
687 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
691 if ((f = fopen(fn, "r")) == NULL)
693 while ((word = fetch_read_word(f)) != NULL) {
694 if (strcmp(word, "default") == 0) {
695 DEBUG(fetch_info("Using default .netrc settings"));
698 if (strcmp(word, "machine") == 0 &&
699 (word = fetch_read_word(f)) != NULL &&
700 strcasecmp(word, url->host) == 0) {
701 DEBUG(fetch_info("Using .netrc settings for %s", word));
707 while ((word = fetch_read_word(f)) != NULL) {
708 if (strcmp(word, "login") == 0) {
709 if ((word = fetch_read_word(f)) == NULL)
711 if (snprintf(url->user, sizeof(url->user),
712 "%s", word) > (int)sizeof(url->user)) {
713 fetch_info("login name in .netrc is too long");
716 } else if (strcmp(word, "password") == 0) {
717 if ((word = fetch_read_word(f)) == NULL)
719 if (snprintf(url->pwd, sizeof(url->pwd),
720 "%s", word) > (int)sizeof(url->pwd)) {
721 fetch_info("password in .netrc is too long");
724 } else if (strcmp(word, "account") == 0) {
725 if ((word = fetch_read_word(f)) == NULL)
727 /* XXX not supported! */
740 * The no_proxy environment variable specifies a set of domains for
741 * which the proxy should not be consulted; the contents is a comma-,
742 * or space-separated list of domain names. A single asterisk will
743 * override all proxy variables and no transactions will be proxied
744 * (for compatability with lynx and curl, see the discussion at
745 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
748 fetch_no_proxy_match(const char *host)
750 const char *no_proxy, *p, *q;
753 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
754 (no_proxy = getenv("no_proxy")) == NULL)
757 /* asterisk matches any hostname */
758 if (strcmp(no_proxy, "*") == 0)
761 h_len = strlen(host);
764 /* position p at the beginning of a domain suffix */
765 while (*p == ',' || isspace((unsigned char)*p))
768 /* position q at the first separator character */
770 if (*q == ',' || isspace((unsigned char)*q))
774 if (d_len > 0 && h_len >= d_len &&
775 strncasecmp(host + h_len - d_len,
777 /* domain name matches */