xref: /netbsd-src/share/examples/refuse/ian/libfetch/common.c (revision a577a06f30c97892195d4559bf0afe04305518c4)
10920b4f2Sagc /*-
20920b4f2Sagc  * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav
30920b4f2Sagc  * All rights reserved.
40920b4f2Sagc  *
50920b4f2Sagc  * Redistribution and use in source and binary forms, with or without
60920b4f2Sagc  * modification, are permitted provided that the following conditions
70920b4f2Sagc  * are met:
80920b4f2Sagc  * 1. Redistributions of source code must retain the above copyright
90920b4f2Sagc  *    notice, this list of conditions and the following disclaimer
100920b4f2Sagc  *    in this position and unchanged.
110920b4f2Sagc  * 2. Redistributions in binary form must reproduce the above copyright
120920b4f2Sagc  *    notice, this list of conditions and the following disclaimer in the
130920b4f2Sagc  *    documentation and/or other materials provided with the distribution.
140920b4f2Sagc  * 3. The name of the author may not be used to endorse or promote products
150920b4f2Sagc  *    derived from this software without specific prior written permission
160920b4f2Sagc  *
170920b4f2Sagc  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
180920b4f2Sagc  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
190920b4f2Sagc  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
200920b4f2Sagc  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
210920b4f2Sagc  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
220920b4f2Sagc  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
230920b4f2Sagc  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
240920b4f2Sagc  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
250920b4f2Sagc  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
260920b4f2Sagc  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
270920b4f2Sagc  */
280920b4f2Sagc 
290920b4f2Sagc #include "free2net.h"
300920b4f2Sagc 
310920b4f2Sagc #include <sys/cdefs.h>
320920b4f2Sagc __FBSDID("$FreeBSD: src/lib/libfetch/common.c,v 1.48.4.2 2006/11/11 00:16:07 des Exp $");
330920b4f2Sagc 
340920b4f2Sagc #include <sys/param.h>
350920b4f2Sagc #include <sys/socket.h>
360920b4f2Sagc #include <sys/time.h>
370920b4f2Sagc #include <sys/uio.h>
380920b4f2Sagc #include <netinet/in.h>
390920b4f2Sagc 
400920b4f2Sagc #include <errno.h>
410920b4f2Sagc #include <netdb.h>
420920b4f2Sagc #include <pwd.h>
430920b4f2Sagc #include <stdarg.h>
440920b4f2Sagc #include <stdlib.h>
450920b4f2Sagc #include <stdio.h>
460920b4f2Sagc #include <string.h>
470920b4f2Sagc #include <unistd.h>
480920b4f2Sagc 
490920b4f2Sagc #include "fetch.h"
500920b4f2Sagc #include "common.h"
510920b4f2Sagc 
520920b4f2Sagc 
530920b4f2Sagc /*** Local data **************************************************************/
540920b4f2Sagc 
550920b4f2Sagc /*
560920b4f2Sagc  * Error messages for resolver errors
570920b4f2Sagc  */
580920b4f2Sagc static struct fetcherr _netdb_errlist[] = {
590920b4f2Sagc #ifdef EAI_NODATA
600920b4f2Sagc 	{ EAI_NODATA,	FETCH_RESOLV,	"Host not found" },
610920b4f2Sagc #endif
620920b4f2Sagc 	{ EAI_AGAIN,	FETCH_TEMP,	"Transient resolver failure" },
630920b4f2Sagc 	{ EAI_FAIL,	FETCH_RESOLV,	"Non-recoverable resolver failure" },
640920b4f2Sagc 	{ EAI_NONAME,	FETCH_RESOLV,	"No address record" },
650920b4f2Sagc 	{ -1,		FETCH_UNKNOWN,	"Unknown resolver error" }
660920b4f2Sagc };
670920b4f2Sagc 
680920b4f2Sagc /* End-of-Line */
690920b4f2Sagc static const char ENDL[2] = "\r\n";
700920b4f2Sagc 
710920b4f2Sagc 
720920b4f2Sagc /*** Error-reporting functions ***********************************************/
730920b4f2Sagc 
740920b4f2Sagc /*
750920b4f2Sagc  * Map error code to string
760920b4f2Sagc  */
770920b4f2Sagc static struct fetcherr *
_fetch_finderr(struct fetcherr * p,int e)780920b4f2Sagc _fetch_finderr(struct fetcherr *p, int e)
790920b4f2Sagc {
800920b4f2Sagc 	while (p->num != -1 && p->num != e)
810920b4f2Sagc 		p++;
820920b4f2Sagc 	return (p);
830920b4f2Sagc }
840920b4f2Sagc 
850920b4f2Sagc /*
860920b4f2Sagc  * Set error code
870920b4f2Sagc  */
880920b4f2Sagc void
_fetch_seterr(struct fetcherr * p,int e)890920b4f2Sagc _fetch_seterr(struct fetcherr *p, int e)
900920b4f2Sagc {
910920b4f2Sagc 	p = _fetch_finderr(p, e);
920920b4f2Sagc 	fetchLastErrCode = p->cat;
930920b4f2Sagc 	snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
940920b4f2Sagc }
950920b4f2Sagc 
960920b4f2Sagc /*
970920b4f2Sagc  * Set error code according to errno
980920b4f2Sagc  */
990920b4f2Sagc void
_fetch_syserr(void)1000920b4f2Sagc _fetch_syserr(void)
1010920b4f2Sagc {
1020920b4f2Sagc 	switch (errno) {
1030920b4f2Sagc 	case 0:
1040920b4f2Sagc 		fetchLastErrCode = FETCH_OK;
1050920b4f2Sagc 		break;
1060920b4f2Sagc 	case EPERM:
1070920b4f2Sagc 	case EACCES:
1080920b4f2Sagc 	case EROFS:
1090920b4f2Sagc 	case EAUTH:
1100920b4f2Sagc 	case ENEEDAUTH:
1110920b4f2Sagc 		fetchLastErrCode = FETCH_AUTH;
1120920b4f2Sagc 		break;
1130920b4f2Sagc 	case ENOENT:
1140920b4f2Sagc 	case EISDIR: /* XXX */
1150920b4f2Sagc 		fetchLastErrCode = FETCH_UNAVAIL;
1160920b4f2Sagc 		break;
1170920b4f2Sagc 	case ENOMEM:
1180920b4f2Sagc 		fetchLastErrCode = FETCH_MEMORY;
1190920b4f2Sagc 		break;
1200920b4f2Sagc 	case EBUSY:
1210920b4f2Sagc 	case EAGAIN:
1220920b4f2Sagc 		fetchLastErrCode = FETCH_TEMP;
1230920b4f2Sagc 		break;
1240920b4f2Sagc 	case EEXIST:
1250920b4f2Sagc 		fetchLastErrCode = FETCH_EXISTS;
1260920b4f2Sagc 		break;
1270920b4f2Sagc 	case ENOSPC:
1280920b4f2Sagc 		fetchLastErrCode = FETCH_FULL;
1290920b4f2Sagc 		break;
1300920b4f2Sagc 	case EADDRINUSE:
1310920b4f2Sagc 	case EADDRNOTAVAIL:
1320920b4f2Sagc 	case ENETDOWN:
1330920b4f2Sagc 	case ENETUNREACH:
1340920b4f2Sagc 	case ENETRESET:
1350920b4f2Sagc 	case EHOSTUNREACH:
1360920b4f2Sagc 		fetchLastErrCode = FETCH_NETWORK;
1370920b4f2Sagc 		break;
1380920b4f2Sagc 	case ECONNABORTED:
1390920b4f2Sagc 	case ECONNRESET:
1400920b4f2Sagc 		fetchLastErrCode = FETCH_ABORT;
1410920b4f2Sagc 		break;
1420920b4f2Sagc 	case ETIMEDOUT:
1430920b4f2Sagc 		fetchLastErrCode = FETCH_TIMEOUT;
1440920b4f2Sagc 		break;
1450920b4f2Sagc 	case ECONNREFUSED:
1460920b4f2Sagc 	case EHOSTDOWN:
1470920b4f2Sagc 		fetchLastErrCode = FETCH_DOWN;
1480920b4f2Sagc 		break;
1490920b4f2Sagc default:
1500920b4f2Sagc 		fetchLastErrCode = FETCH_UNKNOWN;
1510920b4f2Sagc 	}
1520920b4f2Sagc 	snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
1530920b4f2Sagc }
1540920b4f2Sagc 
1550920b4f2Sagc 
1560920b4f2Sagc /*
1570920b4f2Sagc  * Emit status message
1580920b4f2Sagc  */
1590920b4f2Sagc void
_fetch_info(const char * fmt,...)1600920b4f2Sagc _fetch_info(const char *fmt, ...)
1610920b4f2Sagc {
1620920b4f2Sagc 	va_list ap;
1630920b4f2Sagc 
1640920b4f2Sagc 	va_start(ap, fmt);
1650920b4f2Sagc 	vfprintf(stderr, fmt, ap);
1660920b4f2Sagc 	va_end(ap);
1670920b4f2Sagc 	fputc('\n', stderr);
1680920b4f2Sagc }
1690920b4f2Sagc 
1700920b4f2Sagc 
1710920b4f2Sagc /*** Network-related utility functions ***************************************/
1720920b4f2Sagc 
1730920b4f2Sagc /*
1740920b4f2Sagc  * Return the default port for a scheme
1750920b4f2Sagc  */
1760920b4f2Sagc int
_fetch_default_port(const char * scheme)1770920b4f2Sagc _fetch_default_port(const char *scheme)
1780920b4f2Sagc {
1790920b4f2Sagc 	struct servent *se;
1800920b4f2Sagc 
1810920b4f2Sagc 	if ((se = getservbyname(scheme, "tcp")) != NULL)
1820920b4f2Sagc 		return (ntohs(se->s_port));
1830920b4f2Sagc 	if (strcasecmp(scheme, SCHEME_FTP) == 0)
1840920b4f2Sagc 		return (FTP_DEFAULT_PORT);
1850920b4f2Sagc 	if (strcasecmp(scheme, SCHEME_HTTP) == 0)
1860920b4f2Sagc 		return (HTTP_DEFAULT_PORT);
1870920b4f2Sagc 	return (0);
1880920b4f2Sagc }
1890920b4f2Sagc 
1900920b4f2Sagc /*
1910920b4f2Sagc  * Return the default proxy port for a scheme
1920920b4f2Sagc  */
1930920b4f2Sagc int
_fetch_default_proxy_port(const char * scheme)1940920b4f2Sagc _fetch_default_proxy_port(const char *scheme)
1950920b4f2Sagc {
1960920b4f2Sagc 	if (strcasecmp(scheme, SCHEME_FTP) == 0)
1970920b4f2Sagc 		return (FTP_DEFAULT_PROXY_PORT);
1980920b4f2Sagc 	if (strcasecmp(scheme, SCHEME_HTTP) == 0)
1990920b4f2Sagc 		return (HTTP_DEFAULT_PROXY_PORT);
2000920b4f2Sagc 	return (0);
2010920b4f2Sagc }
2020920b4f2Sagc 
2030920b4f2Sagc 
2040920b4f2Sagc /*
2050920b4f2Sagc  * Create a connection for an existing descriptor.
2060920b4f2Sagc  */
2070920b4f2Sagc conn_t *
_fetch_reopen(int sd)2080920b4f2Sagc _fetch_reopen(int sd)
2090920b4f2Sagc {
2100920b4f2Sagc 	conn_t *conn;
2110920b4f2Sagc 
2120920b4f2Sagc 	/* allocate and fill connection structure */
2130920b4f2Sagc 	if ((conn = calloc(1, sizeof(*conn))) == NULL)
2140920b4f2Sagc 		return (NULL);
2150920b4f2Sagc 	conn->sd = sd;
2160920b4f2Sagc 	++conn->ref;
2170920b4f2Sagc 	return (conn);
2180920b4f2Sagc }
2190920b4f2Sagc 
2200920b4f2Sagc 
2210920b4f2Sagc /*
2220920b4f2Sagc  * Bump a connection's reference count.
2230920b4f2Sagc  */
2240920b4f2Sagc conn_t *
_fetch_ref(conn_t * conn)2250920b4f2Sagc _fetch_ref(conn_t *conn)
2260920b4f2Sagc {
2270920b4f2Sagc 
2280920b4f2Sagc 	++conn->ref;
2290920b4f2Sagc 	return (conn);
2300920b4f2Sagc }
2310920b4f2Sagc 
2320920b4f2Sagc 
2330920b4f2Sagc /*
2340920b4f2Sagc  * Bind a socket to a specific local address
2350920b4f2Sagc  */
2360920b4f2Sagc int
_fetch_bind(int sd,int af,const char * addr)2370920b4f2Sagc _fetch_bind(int sd, int af, const char *addr)
2380920b4f2Sagc {
2390920b4f2Sagc 	struct addrinfo hints, *res, *res0;
2400920b4f2Sagc 
2410920b4f2Sagc 	memset(&hints, 0, sizeof(hints));
2420920b4f2Sagc 	hints.ai_family = af;
2430920b4f2Sagc 	hints.ai_socktype = SOCK_STREAM;
2440920b4f2Sagc 	hints.ai_protocol = 0;
2450920b4f2Sagc 	if (getaddrinfo(addr, NULL, &hints, &res0) != 0)
2460920b4f2Sagc 		return (-1);
2470920b4f2Sagc 	for (res = res0; res; res = res->ai_next)
2480920b4f2Sagc 		if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
2490920b4f2Sagc 			return (0);
2500920b4f2Sagc 	return (-1);
2510920b4f2Sagc }
2520920b4f2Sagc 
2530920b4f2Sagc 
2540920b4f2Sagc /*
2550920b4f2Sagc  * Establish a TCP connection to the specified port on the specified host.
2560920b4f2Sagc  */
2570920b4f2Sagc conn_t *
_fetch_connect(const char * host,int port,int af,int verbose)2580920b4f2Sagc _fetch_connect(const char *host, int port, int af, int verbose)
2590920b4f2Sagc {
2600920b4f2Sagc 	conn_t *conn;
2610920b4f2Sagc 	char pbuf[10];
2620920b4f2Sagc 	const char *bindaddr;
2630920b4f2Sagc 	struct addrinfo hints, *res, *res0;
2640920b4f2Sagc 	int sd, err;
2650920b4f2Sagc 
2660920b4f2Sagc 	DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
2670920b4f2Sagc 
2680920b4f2Sagc 	if (verbose)
2690920b4f2Sagc 		_fetch_info("looking up %s", host);
2700920b4f2Sagc 
2710920b4f2Sagc 	/* look up host name and set up socket address structure */
2720920b4f2Sagc 	snprintf(pbuf, sizeof(pbuf), "%d", port);
2730920b4f2Sagc 	memset(&hints, 0, sizeof(hints));
2740920b4f2Sagc 	hints.ai_family = af;
2750920b4f2Sagc 	hints.ai_socktype = SOCK_STREAM;
2760920b4f2Sagc 	hints.ai_protocol = 0;
2770920b4f2Sagc 	if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
2780920b4f2Sagc 		_netdb_seterr(err);
2790920b4f2Sagc 		return (NULL);
2800920b4f2Sagc 	}
2810920b4f2Sagc 	bindaddr = getenv("FETCH_BIND_ADDRESS");
2820920b4f2Sagc 
2830920b4f2Sagc 	if (verbose)
2840920b4f2Sagc 		_fetch_info("connecting to %s:%d", host, port);
2850920b4f2Sagc 
2860920b4f2Sagc 	/* try to connect */
2870920b4f2Sagc 	for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
2880920b4f2Sagc 		if ((sd = socket(res->ai_family, res->ai_socktype,
2890920b4f2Sagc 			 res->ai_protocol)) == -1)
2900920b4f2Sagc 			continue;
2910920b4f2Sagc 		if (bindaddr != NULL && *bindaddr != '\0' &&
2920920b4f2Sagc 		    _fetch_bind(sd, res->ai_family, bindaddr) != 0) {
2930920b4f2Sagc 			_fetch_info("failed to bind to '%s'", bindaddr);
2940920b4f2Sagc 			close(sd);
2950920b4f2Sagc 			continue;
2960920b4f2Sagc 		}
2970920b4f2Sagc 		if (connect(sd, res->ai_addr, res->ai_addrlen) == 0)
2980920b4f2Sagc 			break;
2990920b4f2Sagc 		close(sd);
3000920b4f2Sagc 	}
3010920b4f2Sagc 	freeaddrinfo(res0);
3020920b4f2Sagc 	if (sd == -1) {
3030920b4f2Sagc 		_fetch_syserr();
3040920b4f2Sagc 		return (NULL);
3050920b4f2Sagc 	}
3060920b4f2Sagc 
3070920b4f2Sagc 	if ((conn = _fetch_reopen(sd)) == NULL) {
3080920b4f2Sagc 		_fetch_syserr();
3090920b4f2Sagc 		close(sd);
3100920b4f2Sagc 	}
3110920b4f2Sagc 	return (conn);
3120920b4f2Sagc }
3130920b4f2Sagc 
3140920b4f2Sagc 
3150920b4f2Sagc /*
3160920b4f2Sagc  * Enable SSL on a connection.
3170920b4f2Sagc  */
3180920b4f2Sagc int
_fetch_ssl(conn_t * conn,int verbose)3190920b4f2Sagc _fetch_ssl(conn_t *conn, int verbose)
3200920b4f2Sagc {
3210920b4f2Sagc 
3220920b4f2Sagc #ifdef WITH_SSL
3230920b4f2Sagc 	/* Init the SSL library and context */
3240920b4f2Sagc 	if (!SSL_library_init()){
3250920b4f2Sagc 		fprintf(stderr, "SSL library init failed\n");
3260920b4f2Sagc 		return (-1);
3270920b4f2Sagc 	}
3280920b4f2Sagc 
3290920b4f2Sagc 	SSL_load_error_strings();
3300920b4f2Sagc 
3310920b4f2Sagc 	conn->ssl_meth = SSLv23_client_method();
3320920b4f2Sagc 	conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
3330920b4f2Sagc 	SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
3340920b4f2Sagc 
3350920b4f2Sagc 	conn->ssl = SSL_new(conn->ssl_ctx);
3360920b4f2Sagc 	if (conn->ssl == NULL){
3370920b4f2Sagc 		fprintf(stderr, "SSL context creation failed\n");
3380920b4f2Sagc 		return (-1);
3390920b4f2Sagc 	}
3400920b4f2Sagc 	SSL_set_fd(conn->ssl, conn->sd);
3410920b4f2Sagc 	if (SSL_connect(conn->ssl) == -1){
3420920b4f2Sagc 		ERR_print_errors_fp(stderr);
3430920b4f2Sagc 		return (-1);
3440920b4f2Sagc 	}
3450920b4f2Sagc 
3460920b4f2Sagc 	if (verbose) {
3470920b4f2Sagc 		X509_NAME *name;
3480920b4f2Sagc 		char *str;
3490920b4f2Sagc 
3500920b4f2Sagc 		fprintf(stderr, "SSL connection established using %s\n",
3510920b4f2Sagc 		    SSL_get_cipher(conn->ssl));
3520920b4f2Sagc 		conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
3530920b4f2Sagc 		name = X509_get_subject_name(conn->ssl_cert);
3540920b4f2Sagc 		str = X509_NAME_oneline(name, 0, 0);
3550920b4f2Sagc 		printf("Certificate subject: %s\n", str);
3560920b4f2Sagc 		free(str);
3570920b4f2Sagc 		name = X509_get_issuer_name(conn->ssl_cert);
3580920b4f2Sagc 		str = X509_NAME_oneline(name, 0, 0);
3590920b4f2Sagc 		printf("Certificate issuer: %s\n", str);
3600920b4f2Sagc 		free(str);
3610920b4f2Sagc 	}
3620920b4f2Sagc 
3630920b4f2Sagc 	return (0);
3640920b4f2Sagc #else
3650920b4f2Sagc 	/* LINTED */
3660920b4f2Sagc 	(void)conn;
3670920b4f2Sagc 	/* LINTED */
3680920b4f2Sagc 	(void)verbose;
3690920b4f2Sagc 	fprintf(stderr, "SSL support disabled\n");
3700920b4f2Sagc 	return (-1);
3710920b4f2Sagc #endif
3720920b4f2Sagc }
3730920b4f2Sagc 
3740920b4f2Sagc 
3750920b4f2Sagc /*
3760920b4f2Sagc  * Read a character from a connection w/ timeout
3770920b4f2Sagc  */
3780920b4f2Sagc ssize_t
_fetch_read(conn_t * conn,char * buf,size_t len)3790920b4f2Sagc _fetch_read(conn_t *conn, char *buf, size_t len)
3800920b4f2Sagc {
3810920b4f2Sagc 	struct timeval now, timeout, wait;
3820920b4f2Sagc 	fd_set readfds;
3830920b4f2Sagc 	ssize_t rlen, total;
3840920b4f2Sagc 	int r;
3850920b4f2Sagc 
3860920b4f2Sagc 	if (fetchTimeout) {
3870920b4f2Sagc 		FD_ZERO(&readfds);
3880920b4f2Sagc 		gettimeofday(&timeout, NULL);
3890920b4f2Sagc 		timeout.tv_sec += fetchTimeout;
3900920b4f2Sagc 	}
3910920b4f2Sagc 
3920920b4f2Sagc 	total = 0;
3930920b4f2Sagc 	while (len > 0) {
3940920b4f2Sagc 		while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) {
3950920b4f2Sagc 			FD_SET(conn->sd, &readfds);
3960920b4f2Sagc 			gettimeofday(&now, NULL);
3970920b4f2Sagc 			wait.tv_sec = timeout.tv_sec - now.tv_sec;
3980920b4f2Sagc 			wait.tv_usec = timeout.tv_usec - now.tv_usec;
3990920b4f2Sagc 			if (wait.tv_usec < 0) {
4000920b4f2Sagc 				wait.tv_usec += 1000000;
4010920b4f2Sagc 				wait.tv_sec--;
4020920b4f2Sagc 			}
4030920b4f2Sagc 			if (wait.tv_sec < 0) {
4040920b4f2Sagc 				errno = ETIMEDOUT;
4050920b4f2Sagc 				_fetch_syserr();
4060920b4f2Sagc 				return (-1);
4070920b4f2Sagc 			}
4080920b4f2Sagc 			errno = 0;
4090920b4f2Sagc 			r = select(conn->sd + 1, &readfds, NULL, NULL, &wait);
4100920b4f2Sagc 			if (r == -1) {
4110920b4f2Sagc 				if (errno == EINTR && fetchRestartCalls)
4120920b4f2Sagc 					continue;
4130920b4f2Sagc 				_fetch_syserr();
4140920b4f2Sagc 				return (-1);
4150920b4f2Sagc 			}
4160920b4f2Sagc 		}
4170920b4f2Sagc #ifdef WITH_SSL
4180920b4f2Sagc 		if (conn->ssl != NULL)
4190920b4f2Sagc 			rlen = SSL_read(conn->ssl, buf, len);
4200920b4f2Sagc 		else
4210920b4f2Sagc #endif
4220920b4f2Sagc 			rlen = read(conn->sd, buf, len);
4230920b4f2Sagc 		if (rlen == 0)
4240920b4f2Sagc 			break;
4250920b4f2Sagc 		if (rlen < 0) {
4260920b4f2Sagc 			if (errno == EINTR && fetchRestartCalls)
4270920b4f2Sagc 				continue;
4280920b4f2Sagc 			return (-1);
4290920b4f2Sagc 		}
4300920b4f2Sagc 		len -= rlen;
4310920b4f2Sagc 		buf += rlen;
4320920b4f2Sagc 		total += rlen;
4330920b4f2Sagc 	}
4340920b4f2Sagc 	return (total);
4350920b4f2Sagc }
4360920b4f2Sagc 
4370920b4f2Sagc 
4380920b4f2Sagc /*
4390920b4f2Sagc  * Read a line of text from a connection w/ timeout
4400920b4f2Sagc  */
4410920b4f2Sagc #define MIN_BUF_SIZE 1024
4420920b4f2Sagc 
4430920b4f2Sagc int
_fetch_getln(conn_t * conn)4440920b4f2Sagc _fetch_getln(conn_t *conn)
4450920b4f2Sagc {
4460920b4f2Sagc 	char *tmp;
4470920b4f2Sagc 	size_t tmpsize;
4480920b4f2Sagc 	ssize_t len;
4490920b4f2Sagc 	char c;
4500920b4f2Sagc 
4510920b4f2Sagc 	if (conn->buf == NULL) {
4520920b4f2Sagc 		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
4530920b4f2Sagc 			errno = ENOMEM;
4540920b4f2Sagc 			return (-1);
4550920b4f2Sagc 		}
4560920b4f2Sagc 		conn->bufsize = MIN_BUF_SIZE;
4570920b4f2Sagc 	}
4580920b4f2Sagc 
4590920b4f2Sagc 	conn->buf[0] = '\0';
4600920b4f2Sagc 	conn->buflen = 0;
4610920b4f2Sagc 
4620920b4f2Sagc 	do {
4630920b4f2Sagc 		len = _fetch_read(conn, &c, 1);
4640920b4f2Sagc 		if (len == -1)
4650920b4f2Sagc 			return (-1);
4660920b4f2Sagc 		if (len == 0)
4670920b4f2Sagc 			break;
4680920b4f2Sagc 		conn->buf[conn->buflen++] = c;
4690920b4f2Sagc 		if (conn->buflen == conn->bufsize) {
4700920b4f2Sagc 			tmp = conn->buf;
4710920b4f2Sagc 			tmpsize = conn->bufsize * 2 + 1;
4720920b4f2Sagc 			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
4730920b4f2Sagc 				errno = ENOMEM;
4740920b4f2Sagc 				return (-1);
4750920b4f2Sagc 			}
4760920b4f2Sagc 			conn->buf = tmp;
4770920b4f2Sagc 			conn->bufsize = tmpsize;
4780920b4f2Sagc 		}
4790920b4f2Sagc 	} while (c != '\n');
4800920b4f2Sagc 
4810920b4f2Sagc 	conn->buf[conn->buflen] = '\0';
4820920b4f2Sagc 	DEBUG(fprintf(stderr, "<<< %s", conn->buf));
4830920b4f2Sagc 	return (0);
4840920b4f2Sagc }
4850920b4f2Sagc 
4860920b4f2Sagc 
4870920b4f2Sagc /*
4880920b4f2Sagc  * Write to a connection w/ timeout
4890920b4f2Sagc  */
4900920b4f2Sagc ssize_t
_fetch_write(conn_t * conn,const char * buf,size_t len)4910920b4f2Sagc _fetch_write(conn_t *conn, const char *buf, size_t len)
4920920b4f2Sagc {
4930920b4f2Sagc 	struct iovec iov;
4940920b4f2Sagc 
4950920b4f2Sagc 	iov.iov_base = __DECONST(char *, buf);
4960920b4f2Sagc 	iov.iov_len = len;
4970920b4f2Sagc 	return _fetch_writev(conn, &iov, 1);
4980920b4f2Sagc }
4990920b4f2Sagc 
5000920b4f2Sagc /*
5010920b4f2Sagc  * Write a vector to a connection w/ timeout
5020920b4f2Sagc  * Note: can modify the iovec.
5030920b4f2Sagc  */
5040920b4f2Sagc ssize_t
_fetch_writev(conn_t * conn,struct iovec * iov,int iovcnt)5050920b4f2Sagc _fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
5060920b4f2Sagc {
5070920b4f2Sagc 	struct timeval now, timeout, wait;
5080920b4f2Sagc 	fd_set writefds;
5090920b4f2Sagc 	ssize_t wlen, total;
5100920b4f2Sagc 	int r;
5110920b4f2Sagc 
5120920b4f2Sagc 	if (fetchTimeout) {
5130920b4f2Sagc 		FD_ZERO(&writefds);
5140920b4f2Sagc 		gettimeofday(&timeout, NULL);
5150920b4f2Sagc 		timeout.tv_sec += fetchTimeout;
5160920b4f2Sagc 	}
5170920b4f2Sagc 
5180920b4f2Sagc 	total = 0;
5190920b4f2Sagc 	while (iovcnt > 0) {
5200920b4f2Sagc 		while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
5210920b4f2Sagc 			FD_SET(conn->sd, &writefds);
5220920b4f2Sagc 			gettimeofday(&now, NULL);
5230920b4f2Sagc 			wait.tv_sec = timeout.tv_sec - now.tv_sec;
5240920b4f2Sagc 			wait.tv_usec = timeout.tv_usec - now.tv_usec;
5250920b4f2Sagc 			if (wait.tv_usec < 0) {
5260920b4f2Sagc 				wait.tv_usec += 1000000;
5270920b4f2Sagc 				wait.tv_sec--;
5280920b4f2Sagc 			}
5290920b4f2Sagc 			if (wait.tv_sec < 0) {
5300920b4f2Sagc 				errno = ETIMEDOUT;
5310920b4f2Sagc 				_fetch_syserr();
5320920b4f2Sagc 				return (-1);
5330920b4f2Sagc 			}
5340920b4f2Sagc 			errno = 0;
5350920b4f2Sagc 			r = select(conn->sd + 1, NULL, &writefds, NULL, &wait);
5360920b4f2Sagc 			if (r == -1) {
5370920b4f2Sagc 				if (errno == EINTR && fetchRestartCalls)
5380920b4f2Sagc 					continue;
5390920b4f2Sagc 				return (-1);
5400920b4f2Sagc 			}
5410920b4f2Sagc 		}
5420920b4f2Sagc 		errno = 0;
5430920b4f2Sagc #ifdef WITH_SSL
5440920b4f2Sagc 		if (conn->ssl != NULL)
5450920b4f2Sagc 			wlen = SSL_write(conn->ssl,
5460920b4f2Sagc 			    iov->iov_base, iov->iov_len);
5470920b4f2Sagc 		else
5480920b4f2Sagc #endif
5490920b4f2Sagc 			wlen = writev(conn->sd, iov, iovcnt);
5500920b4f2Sagc 		if (wlen == 0) {
5510920b4f2Sagc 			/* we consider a short write a failure */
5520920b4f2Sagc 			errno = EPIPE;
5530920b4f2Sagc 			_fetch_syserr();
5540920b4f2Sagc 			return (-1);
5550920b4f2Sagc 		}
5560920b4f2Sagc 		if (wlen < 0) {
5570920b4f2Sagc 			if (errno == EINTR && fetchRestartCalls)
5580920b4f2Sagc 				continue;
5590920b4f2Sagc 			return (-1);
5600920b4f2Sagc 		}
5610920b4f2Sagc 		total += wlen;
5620920b4f2Sagc 		while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
5630920b4f2Sagc 			wlen -= iov->iov_len;
5640920b4f2Sagc 			iov++;
5650920b4f2Sagc 			iovcnt--;
5660920b4f2Sagc 		}
5670920b4f2Sagc 		if (iovcnt > 0) {
5680920b4f2Sagc 			iov->iov_len -= wlen;
569*a577a06fSagc 			iov->iov_base = (__DECONST(char *, iov->iov_base)) + wlen;
5700920b4f2Sagc 		}
5710920b4f2Sagc 	}
5720920b4f2Sagc 	return (total);
5730920b4f2Sagc }
5740920b4f2Sagc 
5750920b4f2Sagc 
5760920b4f2Sagc /*
5770920b4f2Sagc  * Write a line of text to a connection w/ timeout
5780920b4f2Sagc  */
5790920b4f2Sagc int
_fetch_putln(conn_t * conn,const char * str,size_t len)5800920b4f2Sagc _fetch_putln(conn_t *conn, const char *str, size_t len)
5810920b4f2Sagc {
5820920b4f2Sagc 	struct iovec iov[2];
5830920b4f2Sagc 	int ret;
5840920b4f2Sagc 
5850920b4f2Sagc 	DEBUG(fprintf(stderr, ">>> %s\n", str));
5860920b4f2Sagc 	iov[0].iov_base = __DECONST(char *, str);
5870920b4f2Sagc 	iov[0].iov_len = len;
5880920b4f2Sagc 	iov[1].iov_base = __DECONST(char *, ENDL);
5890920b4f2Sagc 	iov[1].iov_len = sizeof(ENDL);
5900920b4f2Sagc 	if (len == 0)
5910920b4f2Sagc 		ret = _fetch_writev(conn, &iov[1], 1);
5920920b4f2Sagc 	else
5930920b4f2Sagc 		ret = _fetch_writev(conn, iov, 2);
5940920b4f2Sagc 	if (ret == -1)
5950920b4f2Sagc 		return (-1);
5960920b4f2Sagc 	return (0);
5970920b4f2Sagc }
5980920b4f2Sagc 
5990920b4f2Sagc 
6000920b4f2Sagc /*
6010920b4f2Sagc  * Close connection
6020920b4f2Sagc  */
6030920b4f2Sagc int
_fetch_close(conn_t * conn)6040920b4f2Sagc _fetch_close(conn_t *conn)
6050920b4f2Sagc {
6060920b4f2Sagc 	int ret;
6070920b4f2Sagc 
6080920b4f2Sagc 	if (--conn->ref > 0)
6090920b4f2Sagc 		return (0);
6100920b4f2Sagc 	ret = close(conn->sd);
6110920b4f2Sagc 	free(conn->buf);
6120920b4f2Sagc 	free(conn);
6130920b4f2Sagc 	return (ret);
6140920b4f2Sagc }
6150920b4f2Sagc 
6160920b4f2Sagc 
6170920b4f2Sagc /*** Directory-related utility functions *************************************/
6180920b4f2Sagc 
6190920b4f2Sagc int
_fetch_add_entry(struct url_ent ** p,int * size,int * len,const char * name,struct url_stat * us)6200920b4f2Sagc _fetch_add_entry(struct url_ent **p, int *size, int *len,
6210920b4f2Sagc     const char *name, struct url_stat *us)
6220920b4f2Sagc {
6230920b4f2Sagc 	struct url_ent *tmp;
6240920b4f2Sagc 
6250920b4f2Sagc 	if (*p == NULL) {
6260920b4f2Sagc 		*size = 0;
6270920b4f2Sagc 		*len = 0;
6280920b4f2Sagc 	}
6290920b4f2Sagc 
6300920b4f2Sagc 	if (*len >= *size - 1) {
6310920b4f2Sagc 		tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
6320920b4f2Sagc 		if (tmp == NULL) {
6330920b4f2Sagc 			errno = ENOMEM;
6340920b4f2Sagc 			_fetch_syserr();
6350920b4f2Sagc 			return (-1);
6360920b4f2Sagc 		}
6370920b4f2Sagc 		*size = (*size * 2 + 1);
6380920b4f2Sagc 		*p = tmp;
6390920b4f2Sagc 	}
6400920b4f2Sagc 
6410920b4f2Sagc 	tmp = *p + *len;
6420920b4f2Sagc 	snprintf(tmp->name, PATH_MAX, "%s", name);
6430920b4f2Sagc 	bcopy(us, &tmp->stat, sizeof(*us));
6440920b4f2Sagc 
6450920b4f2Sagc 	(*len)++;
6460920b4f2Sagc 	(++tmp)->name[0] = 0;
6470920b4f2Sagc 
6480920b4f2Sagc 	return (0);
6490920b4f2Sagc }
6500920b4f2Sagc 
6510920b4f2Sagc 
6520920b4f2Sagc /*** Authentication-related utility functions ********************************/
6530920b4f2Sagc 
6540920b4f2Sagc static const char *
_fetch_read_word(FILE * f)6550920b4f2Sagc _fetch_read_word(FILE *f)
6560920b4f2Sagc {
6570920b4f2Sagc 	static char word[1024];
6580920b4f2Sagc 
6590920b4f2Sagc 	if (fscanf(f, " %1024s ", word) != 1)
6600920b4f2Sagc 		return (NULL);
6610920b4f2Sagc 	return (word);
6620920b4f2Sagc }
6630920b4f2Sagc 
6640920b4f2Sagc /*
6650920b4f2Sagc  * Get authentication data for a URL from .netrc
6660920b4f2Sagc  */
6670920b4f2Sagc int
_fetch_netrc_auth(struct url * url)6680920b4f2Sagc _fetch_netrc_auth(struct url *url)
6690920b4f2Sagc {
6700920b4f2Sagc 	char fn[PATH_MAX];
6710920b4f2Sagc 	const char *word;
6720920b4f2Sagc 	char *p;
6730920b4f2Sagc 	FILE *f;
6740920b4f2Sagc 
6750920b4f2Sagc 	if ((p = getenv("NETRC")) != NULL) {
6760920b4f2Sagc 		if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
6770920b4f2Sagc 			_fetch_info("$NETRC specifies a file name "
6780920b4f2Sagc 			    "longer than PATH_MAX");
6790920b4f2Sagc 			return (-1);
6800920b4f2Sagc 		}
6810920b4f2Sagc 	} else {
6820920b4f2Sagc 		if ((p = getenv("HOME")) != NULL) {
6830920b4f2Sagc 			struct passwd *pwd;
6840920b4f2Sagc 
6850920b4f2Sagc 			if ((pwd = getpwuid(getuid())) == NULL ||
6860920b4f2Sagc 			    (p = pwd->pw_dir) == NULL)
6870920b4f2Sagc 				return (-1);
6880920b4f2Sagc 		}
6890920b4f2Sagc 		if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
6900920b4f2Sagc 			return (-1);
6910920b4f2Sagc 	}
6920920b4f2Sagc 
6930920b4f2Sagc 	if ((f = fopen(fn, "r")) == NULL)
6940920b4f2Sagc 		return (-1);
6950920b4f2Sagc 	while ((word = _fetch_read_word(f)) != NULL) {
6960920b4f2Sagc 		if (strcmp(word, "default") == 0) {
6970920b4f2Sagc 			DEBUG(_fetch_info("Using default .netrc settings"));
6980920b4f2Sagc 			break;
6990920b4f2Sagc 		}
7000920b4f2Sagc 		if (strcmp(word, "machine") == 0 &&
7010920b4f2Sagc 		    (word = _fetch_read_word(f)) != NULL &&
7020920b4f2Sagc 		    strcasecmp(word, url->host) == 0) {
7030920b4f2Sagc 			DEBUG(_fetch_info("Using .netrc settings for %s", word));
7040920b4f2Sagc 			break;
7050920b4f2Sagc 		}
7060920b4f2Sagc 	}
7070920b4f2Sagc 	if (word == NULL)
7080920b4f2Sagc 		goto ferr;
7090920b4f2Sagc 	while ((word = _fetch_read_word(f)) != NULL) {
7100920b4f2Sagc 		if (strcmp(word, "login") == 0) {
7110920b4f2Sagc 			if ((word = _fetch_read_word(f)) == NULL)
7120920b4f2Sagc 				goto ferr;
7130920b4f2Sagc 			if (snprintf(url->user, sizeof(url->user),
7140920b4f2Sagc 				"%s", word) > (int)sizeof(url->user)) {
7150920b4f2Sagc 				_fetch_info("login name in .netrc is too long");
7160920b4f2Sagc 				url->user[0] = '\0';
7170920b4f2Sagc 			}
7180920b4f2Sagc 		} else if (strcmp(word, "password") == 0) {
7190920b4f2Sagc 			if ((word = _fetch_read_word(f)) == NULL)
7200920b4f2Sagc 				goto ferr;
7210920b4f2Sagc 			if (snprintf(url->pwd, sizeof(url->pwd),
7220920b4f2Sagc 				"%s", word) > (int)sizeof(url->pwd)) {
7230920b4f2Sagc 				_fetch_info("password in .netrc is too long");
7240920b4f2Sagc 				url->pwd[0] = '\0';
7250920b4f2Sagc 			}
7260920b4f2Sagc 		} else if (strcmp(word, "account") == 0) {
7270920b4f2Sagc 			if ((word = _fetch_read_word(f)) == NULL)
7280920b4f2Sagc 				goto ferr;
7290920b4f2Sagc 			/* XXX not supported! */
7300920b4f2Sagc 		} else {
7310920b4f2Sagc 			break;
7320920b4f2Sagc 		}
7330920b4f2Sagc 	}
7340920b4f2Sagc 	fclose(f);
7350920b4f2Sagc 	return (0);
7360920b4f2Sagc  ferr:
7370920b4f2Sagc 	fclose(f);
7380920b4f2Sagc 	return (-1);
7390920b4f2Sagc }
740