common.c revision 236193
1103285Sikob/*-
2103285Sikob * Copyright (c) 1998-2011 Dag-Erling Sm��rgrav
3103285Sikob * All rights reserved.
4103285Sikob *
5103285Sikob * Redistribution and use in source and binary forms, with or without
6103285Sikob * modification, are permitted provided that the following conditions
7103285Sikob * are met:
8103285Sikob * 1. Redistributions of source code must retain the above copyright
9103285Sikob *    notice, this list of conditions and the following disclaimer
10103285Sikob *    in this position and unchanged.
11103285Sikob * 2. Redistributions in binary form must reproduce the above copyright
12103285Sikob *    notice, this list of conditions and the following disclaimer in the
13103285Sikob *    documentation and/or other materials provided with the distribution.
14103285Sikob * 3. The name of the author may not be used to endorse or promote products
15103285Sikob *    derived from this software without specific prior written permission
16103285Sikob *
17103285Sikob * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18103285Sikob * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19103285Sikob * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20103285Sikob * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21103285Sikob * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22103285Sikob * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23103285Sikob * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24103285Sikob * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25103285Sikob * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26103285Sikob * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27103285Sikob */
28103285Sikob
29103285Sikob#include <sys/cdefs.h>
30103285Sikob__FBSDID("$FreeBSD: head/lib/libfetch/common.c 236193 2012-05-28 19:22:23Z jilles $");
31103285Sikob
32103285Sikob#include <sys/param.h>
33103285Sikob#include <sys/socket.h>
34103285Sikob#include <sys/time.h>
35103285Sikob#include <sys/uio.h>
36103285Sikob
37103285Sikob#include <netinet/in.h>
38103285Sikob
39103285Sikob#include <ctype.h>
40103285Sikob#include <errno.h>
41103285Sikob#include <fcntl.h>
42103285Sikob#include <netdb.h>
43103285Sikob#include <pwd.h>
44103285Sikob#include <stdarg.h>
45103285Sikob#include <stdlib.h>
46103285Sikob#include <stdio.h>
47103285Sikob#include <string.h>
48103285Sikob#include <unistd.h>
49103285Sikob
50103285Sikob#include "fetch.h"
51103285Sikob#include "common.h"
52103285Sikob
53103285Sikob
54103285Sikob/*** Local data **************************************************************/
55103285Sikob
56103285Sikob/*
57106810Ssimokawa * Error messages for resolver errors
58106810Ssimokawa */
59103285Sikobstatic struct fetcherr netdb_errlist[] = {
60103285Sikob#ifdef EAI_NODATA
61108281Ssimokawa	{ EAI_NODATA,	FETCH_RESOLV,	"Host not found" },
62106810Ssimokawa#endif
63106810Ssimokawa	{ EAI_AGAIN,	FETCH_TEMP,	"Transient resolver failure" },
64106810Ssimokawa	{ EAI_FAIL,	FETCH_RESOLV,	"Non-recoverable resolver failure" },
65106810Ssimokawa	{ EAI_NONAME,	FETCH_RESOLV,	"No address record" },
66103285Sikob	{ -1,		FETCH_UNKNOWN,	"Unknown resolver error" }
67103285Sikob};
68103285Sikob
69103285Sikob/* End-of-Line */
70103285Sikobstatic const char ENDL[2] = "\r\n";
71106816Ssimokawa
72106816Ssimokawa
73106816Ssimokawa/*** Error-reporting functions ***********************************************/
74106816Ssimokawa
75106816Ssimokawa/*
76106810Ssimokawa * Map error code to string
77106816Ssimokawa */
78106816Ssimokawastatic struct fetcherr *
79106816Ssimokawafetch_finderr(struct fetcherr *p, int e)
80106816Ssimokawa{
81103285Sikob	while (p->num != -1 && p->num != e)
82103285Sikob		p++;
83103285Sikob	return (p);
84103285Sikob}
85106804Ssimokawa
86103285Sikob/*
87106804Ssimokawa * Set error code
88106810Ssimokawa */
89106810Ssimokawavoid
90106816Ssimokawafetch_seterr(struct fetcherr *p, int e)
91106816Ssimokawa{
92106816Ssimokawa	p = fetch_finderr(p, e);
93106816Ssimokawa	fetchLastErrCode = p->cat;
94106816Ssimokawa	snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
95106816Ssimokawa}
96106804Ssimokawa
97106816Ssimokawa/*
98106816Ssimokawa * Set error code according to errno
99106816Ssimokawa */
100106816Ssimokawavoid
101106804Ssimokawafetch_syserr(void)
102103285Sikob{
103106804Ssimokawa	switch (errno) {
104103285Sikob	case 0:
105106816Ssimokawa		fetchLastErrCode = FETCH_OK;
106103285Sikob		break;
107106816Ssimokawa	case EPERM:
108106816Ssimokawa	case EACCES:
109106816Ssimokawa	case EROFS:
110106816Ssimokawa	case EAUTH:
111106816Ssimokawa	case ENEEDAUTH:
112106816Ssimokawa		fetchLastErrCode = FETCH_AUTH;
113106816Ssimokawa		break;
114106816Ssimokawa	case ENOENT:
115106816Ssimokawa	case EISDIR: /* XXX */
116106816Ssimokawa		fetchLastErrCode = FETCH_UNAVAIL;
117106816Ssimokawa		break;
118106816Ssimokawa	case ENOMEM:
119106816Ssimokawa		fetchLastErrCode = FETCH_MEMORY;
120106816Ssimokawa		break;
121106816Ssimokawa	case EBUSY:
122106816Ssimokawa	case EAGAIN:
123106816Ssimokawa		fetchLastErrCode = FETCH_TEMP;
124106816Ssimokawa		break;
125106816Ssimokawa	case EEXIST:
126103285Sikob		fetchLastErrCode = FETCH_EXISTS;
127103285Sikob		break;
128103285Sikob	case ENOSPC:
129103285Sikob		fetchLastErrCode = FETCH_FULL;
130103285Sikob		break;
131103285Sikob	case EADDRINUSE:
132103285Sikob	case EADDRNOTAVAIL:
133106816Ssimokawa	case ENETDOWN:
134106816Ssimokawa	case ENETUNREACH:
135106804Ssimokawa	case ENETRESET:
136106810Ssimokawa	case EHOSTUNREACH:
137103285Sikob		fetchLastErrCode = FETCH_NETWORK;
138106804Ssimokawa		break;
139103285Sikob	case ECONNABORTED:
140103285Sikob	case ECONNRESET:
141103285Sikob		fetchLastErrCode = FETCH_ABORT;
142103285Sikob		break;
143103285Sikob	case ETIMEDOUT:
144106810Ssimokawa		fetchLastErrCode = FETCH_TIMEOUT;
145106810Ssimokawa		break;
146106810Ssimokawa	case ECONNREFUSED:
147106810Ssimokawa	case EHOSTDOWN:
148106810Ssimokawa		fetchLastErrCode = FETCH_DOWN;
149106810Ssimokawa		break;
150106810Ssimokawadefault:
151106810Ssimokawa		fetchLastErrCode = FETCH_UNKNOWN;
152106810Ssimokawa	}
153106810Ssimokawa	snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
154106810Ssimokawa}
155106810Ssimokawa
156106816Ssimokawa
157106810Ssimokawa/*
158106810Ssimokawa * Emit status message
159106810Ssimokawa */
160106810Ssimokawavoid
161110072Ssimokawafetch_info(const char *fmt, ...)
162106810Ssimokawa{
163106810Ssimokawa	va_list ap;
164106810Ssimokawa
165106810Ssimokawa	va_start(ap, fmt);
166106810Ssimokawa	vfprintf(stderr, fmt, ap);
167106810Ssimokawa	va_end(ap);
168106810Ssimokawa	fputc('\n', stderr);
169106816Ssimokawa}
170106816Ssimokawa
171106810Ssimokawa
172106810Ssimokawa/*** Network-related utility functions ***************************************/
173106810Ssimokawa
174106810Ssimokawa/*
175106810Ssimokawa * Return the default port for a scheme
176106810Ssimokawa */
177106810Ssimokawaint
178106810Ssimokawafetch_default_port(const char *scheme)
179106810Ssimokawa{
180103285Sikob	struct servent *se;
181106810Ssimokawa
182106810Ssimokawa	if ((se = getservbyname(scheme, "tcp")) != NULL)
183106804Ssimokawa		return (ntohs(se->s_port));
184103285Sikob	if (strcasecmp(scheme, SCHEME_FTP) == 0)
185103285Sikob		return (FTP_DEFAULT_PORT);
186106804Ssimokawa	if (strcasecmp(scheme, SCHEME_HTTP) == 0)
187106804Ssimokawa		return (HTTP_DEFAULT_PORT);
188103285Sikob	return (0);
189103285Sikob}
190103285Sikob
191103285Sikob/*
192106816Ssimokawa * Return the default proxy port for a scheme
193106804Ssimokawa */
194103285Sikobint
195106804Ssimokawafetch_default_proxy_port(const char *scheme)
196103285Sikob{
197103285Sikob	if (strcasecmp(scheme, SCHEME_FTP) == 0)
198103285Sikob		return (FTP_DEFAULT_PROXY_PORT);
199103285Sikob	if (strcasecmp(scheme, SCHEME_HTTP) == 0)
200103285Sikob		return (HTTP_DEFAULT_PROXY_PORT);
201103285Sikob	return (0);
202103285Sikob}
203103285Sikob
204106816Ssimokawa
205106810Ssimokawa/*
206106810Ssimokawa * Create a connection for an existing descriptor.
207103285Sikob */
208106804Ssimokawaconn_t *
209103285Sikobfetch_reopen(int sd)
210103285Sikob{
211103285Sikob	conn_t *conn;
212103285Sikob	int opt = 1;
213103285Sikob
214103285Sikob	/* allocate and fill connection structure */
215103285Sikob	if ((conn = calloc(1, sizeof(*conn))) == NULL)
216103285Sikob		return (NULL);
217103285Sikob	fcntl(sd, F_SETFD, FD_CLOEXEC);
218103285Sikob	setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
219103285Sikob	conn->sd = sd;
220103285Sikob	++conn->ref;
221103285Sikob	return (conn);
222103285Sikob}
223103285Sikob
224103285Sikob
225103285Sikob/*
226103285Sikob * Bump a connection's reference count.
227103285Sikob */
228103285Sikobconn_t *
229103285Sikobfetch_ref(conn_t *conn)
230103285Sikob{
231103285Sikob
232103285Sikob	++conn->ref;
233106810Ssimokawa	return (conn);
234103285Sikob}
235103285Sikob
236103285Sikob
237103285Sikob/*
238103285Sikob * Bind a socket to a specific local address
239103285Sikob */
240103285Sikobint
241103285Sikobfetch_bind(int sd, int af, const char *addr)
242103285Sikob{
243110072Ssimokawa	struct addrinfo hints, *res, *res0;
244106810Ssimokawa	int err;
245106810Ssimokawa
246106810Ssimokawa	memset(&hints, 0, sizeof(hints));
247106810Ssimokawa	hints.ai_family = af;
248106810Ssimokawa	hints.ai_socktype = SOCK_STREAM;
249103285Sikob	hints.ai_protocol = 0;
250103285Sikob	if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
251103285Sikob		return (-1);
252103285Sikob	for (res = res0; res; res = res->ai_next)
253103285Sikob		if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
254103285Sikob			return (0);
255103285Sikob	return (-1);
256103285Sikob}
257103285Sikob
258103285Sikob
259106810Ssimokawa/*
260106804Ssimokawa * Establish a TCP connection to the specified port on the specified host.
261106804Ssimokawa */
262106804Ssimokawaconn_t *
263106804Ssimokawafetch_connect(const char *host, int port, int af, int verbose)
264106804Ssimokawa{
265103285Sikob	conn_t *conn;
266103285Sikob	char pbuf[10];
267103285Sikob	const char *bindaddr;
268103285Sikob	struct addrinfo hints, *res, *res0;
269103285Sikob	int sd, err;
270103285Sikob
271103285Sikob	DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
272106810Ssimokawa
273106804Ssimokawa	if (verbose)
274106804Ssimokawa		fetch_info("looking up %s", host);
275106804Ssimokawa
276106804Ssimokawa	/* look up host name and set up socket address structure */
277106804Ssimokawa	snprintf(pbuf, sizeof(pbuf), "%d", port);
278103285Sikob	memset(&hints, 0, sizeof(hints));
279103285Sikob	hints.ai_family = af;
280103285Sikob	hints.ai_socktype = SOCK_STREAM;
281103285Sikob	hints.ai_protocol = 0;
282103285Sikob	if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
283103285Sikob		netdb_seterr(err);
284103285Sikob		return (NULL);
285103285Sikob	}
286103285Sikob	bindaddr = getenv("FETCH_BIND_ADDRESS");
287103285Sikob
288103285Sikob	if (verbose)
289103285Sikob		fetch_info("connecting to %s:%d", host, port);
290103285Sikob
291103285Sikob	/* try to connect */
292103285Sikob	for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
293103285Sikob		if ((sd = socket(res->ai_family, res->ai_socktype,
294103285Sikob			 res->ai_protocol)) == -1)
295103285Sikob			continue;
296103285Sikob		if (bindaddr != NULL && *bindaddr != '\0' &&
297103285Sikob		    fetch_bind(sd, res->ai_family, bindaddr) != 0) {
298103285Sikob			fetch_info("failed to bind to '%s'", bindaddr);
299103285Sikob			close(sd);
300103285Sikob			continue;
301103285Sikob		}
302103285Sikob		if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
303103285Sikob		    fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
304103285Sikob			break;
305103285Sikob		close(sd);
306103285Sikob	}
307103285Sikob	freeaddrinfo(res0);
308103285Sikob	if (sd == -1) {
309		fetch_syserr();
310		return (NULL);
311	}
312
313	if ((conn = fetch_reopen(sd)) == NULL) {
314		fetch_syserr();
315		close(sd);
316	}
317	return (conn);
318}
319
320
321/*
322 * Enable SSL on a connection.
323 */
324int
325fetch_ssl(conn_t *conn, int verbose)
326{
327#ifdef WITH_SSL
328	int ret, ssl_err;
329
330	/* Init the SSL library and context */
331	if (!SSL_library_init()){
332		fprintf(stderr, "SSL library init failed\n");
333		return (-1);
334	}
335
336	SSL_load_error_strings();
337
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);
341
342	conn->ssl = SSL_new(conn->ssl_ctx);
343	if (conn->ssl == NULL){
344		fprintf(stderr, "SSL context creation failed\n");
345		return (-1);
346	}
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);
353			return (-1);
354		}
355	}
356
357	if (verbose) {
358		X509_NAME *name;
359		char *str;
360
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);
367		free(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);
371		free(str);
372	}
373
374	return (0);
375#else
376	(void)conn;
377	(void)verbose;
378	fprintf(stderr, "SSL support disabled\n");
379	return (-1);
380#endif
381}
382
383#define FETCH_READ_WAIT		-2
384#define FETCH_READ_ERROR	-1
385#define FETCH_READ_DONE		 0
386
387#ifdef WITH_SSL
388static ssize_t
389fetch_ssl_read(SSL *ssl, char *buf, size_t len)
390{
391	ssize_t rlen;
392	int ssl_err;
393
394	rlen = SSL_read(ssl, buf, len);
395	if (rlen < 0) {
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);
400		} else {
401			ERR_print_errors_fp(stderr);
402			return (FETCH_READ_ERROR);
403		}
404	}
405	return (rlen);
406}
407#endif
408
409/*
410 * Cache some data that was read from a socket but cannot be immediately
411 * returned because of an interrupted system call.
412 */
413static int
414fetch_cache_data(conn_t *conn, char *src, size_t nbytes)
415{
416	char *tmp;
417
418	if (conn->cache.size < nbytes) {
419		tmp = realloc(conn->cache.buf, nbytes);
420		if (tmp == NULL) {
421			fetch_syserr();
422			return (-1);
423		}
424		conn->cache.buf = tmp;
425		conn->cache.size = nbytes;
426	}
427
428	memcpy(conn->cache.buf, src, nbytes);
429	conn->cache.len = nbytes;
430	conn->cache.pos = 0;
431
432	return (0);
433}
434
435
436static ssize_t
437fetch_socket_read(int sd, char *buf, size_t len)
438{
439	ssize_t rlen;
440
441	rlen = read(sd, buf, len);
442	if (rlen < 0) {
443		if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
444			return (FETCH_READ_WAIT);
445		else
446			return (FETCH_READ_ERROR);
447	}
448	return (rlen);
449}
450
451/*
452 * Read a character from a connection w/ timeout
453 */
454ssize_t
455fetch_read(conn_t *conn, char *buf, size_t len)
456{
457	struct timeval now, timeout, delta;
458	fd_set readfds;
459	ssize_t rlen, total;
460	char *start;
461
462	if (fetchTimeout > 0) {
463		gettimeofday(&timeout, NULL);
464		timeout.tv_sec += fetchTimeout;
465	}
466
467	total = 0;
468	start = buf;
469
470	if (conn->cache.len > 0) {
471		/*
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.
476		 */
477		total = (conn->cache.len < len) ? conn->cache.len : len;
478		memcpy(buf, conn->cache.buf, total);
479
480		conn->cache.len -= total;
481		conn->cache.pos += total;
482		len -= total;
483		buf += total;
484	}
485
486	while (len > 0) {
487		/*
488		 * The socket is non-blocking.  Instead of the canonical
489		 * select() -> read(), we do the following:
490		 *
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,
497		 *    call select().
498		 *
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.
503		 *
504		 * In the non-SSL case, it may improve performance (very
505		 * slightly) when reading small amounts of data.
506		 */
507#ifdef WITH_SSL
508		if (conn->ssl != NULL)
509			rlen = fetch_ssl_read(conn->ssl, buf, len);
510		else
511#endif
512			rlen = fetch_socket_read(conn->sd, buf, len);
513		if (rlen == 0) {
514			break;
515		} else if (rlen > 0) {
516			len -= rlen;
517			buf += rlen;
518			total += rlen;
519			continue;
520		} else if (rlen == FETCH_READ_ERROR) {
521			if (errno == EINTR)
522				fetch_cache_data(conn, start, total);
523			return (-1);
524		}
525		// assert(rlen == FETCH_READ_WAIT);
526		FD_ZERO(&readfds);
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, >)) {
532					errno = ETIMEDOUT;
533					fetch_syserr();
534					return (-1);
535				}
536				timersub(&timeout, &now, &delta);
537			}
538			errno = 0;
539			if (select(conn->sd + 1, &readfds, NULL, NULL,
540				fetchTimeout > 0 ? &delta : NULL) < 0) {
541				if (errno == EINTR) {
542					if (fetchRestartCalls)
543						continue;
544					/* Save anything that was read. */
545					fetch_cache_data(conn, start, total);
546				}
547				fetch_syserr();
548				return (-1);
549			}
550		}
551	}
552	return (total);
553}
554
555
556/*
557 * Read a line of text from a connection w/ timeout
558 */
559#define MIN_BUF_SIZE 1024
560
561int
562fetch_getln(conn_t *conn)
563{
564	char *tmp;
565	size_t tmpsize;
566	ssize_t len;
567	char c;
568
569	if (conn->buf == NULL) {
570		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
571			errno = ENOMEM;
572			return (-1);
573		}
574		conn->bufsize = MIN_BUF_SIZE;
575	}
576
577	conn->buf[0] = '\0';
578	conn->buflen = 0;
579
580	do {
581		len = fetch_read(conn, &c, 1);
582		if (len == -1)
583			return (-1);
584		if (len == 0)
585			break;
586		conn->buf[conn->buflen++] = c;
587		if (conn->buflen == conn->bufsize) {
588			tmp = conn->buf;
589			tmpsize = conn->bufsize * 2 + 1;
590			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
591				errno = ENOMEM;
592				return (-1);
593			}
594			conn->buf = tmp;
595			conn->bufsize = tmpsize;
596		}
597	} while (c != '\n');
598
599	conn->buf[conn->buflen] = '\0';
600	DEBUG(fprintf(stderr, "<<< %s", conn->buf));
601	return (0);
602}
603
604
605/*
606 * Write to a connection w/ timeout
607 */
608ssize_t
609fetch_write(conn_t *conn, const char *buf, size_t len)
610{
611	struct iovec iov;
612
613	iov.iov_base = __DECONST(char *, buf);
614	iov.iov_len = len;
615	return fetch_writev(conn, &iov, 1);
616}
617
618/*
619 * Write a vector to a connection w/ timeout
620 * Note: can modify the iovec.
621 */
622ssize_t
623fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
624{
625	struct timeval now, timeout, delta;
626	fd_set writefds;
627	ssize_t wlen, total;
628	int r;
629
630	if (fetchTimeout) {
631		FD_ZERO(&writefds);
632		gettimeofday(&timeout, NULL);
633		timeout.tv_sec += fetchTimeout;
634	}
635
636	total = 0;
637	while (iovcnt > 0) {
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;
645				delta.tv_sec--;
646			}
647			if (delta.tv_sec < 0) {
648				errno = ETIMEDOUT;
649				fetch_syserr();
650				return (-1);
651			}
652			errno = 0;
653			r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
654			if (r == -1) {
655				if (errno == EINTR && fetchRestartCalls)
656					continue;
657				return (-1);
658			}
659		}
660		errno = 0;
661#ifdef WITH_SSL
662		if (conn->ssl != NULL)
663			wlen = SSL_write(conn->ssl,
664			    iov->iov_base, iov->iov_len);
665		else
666#endif
667			wlen = writev(conn->sd, iov, iovcnt);
668		if (wlen == 0) {
669			/* we consider a short write a failure */
670			/* XXX perhaps we shouldn't in the SSL case */
671			errno = EPIPE;
672			fetch_syserr();
673			return (-1);
674		}
675		if (wlen < 0) {
676			if (errno == EINTR && fetchRestartCalls)
677				continue;
678			return (-1);
679		}
680		total += wlen;
681		while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
682			wlen -= iov->iov_len;
683			iov++;
684			iovcnt--;
685		}
686		if (iovcnt > 0) {
687			iov->iov_len -= wlen;
688			iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
689		}
690	}
691	return (total);
692}
693
694
695/*
696 * Write a line of text to a connection w/ timeout
697 */
698int
699fetch_putln(conn_t *conn, const char *str, size_t len)
700{
701	struct iovec iov[2];
702	int ret;
703
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);
709	if (len == 0)
710		ret = fetch_writev(conn, &iov[1], 1);
711	else
712		ret = fetch_writev(conn, iov, 2);
713	if (ret == -1)
714		return (-1);
715	return (0);
716}
717
718
719/*
720 * Close connection
721 */
722int
723fetch_close(conn_t *conn)
724{
725	int ret;
726
727	if (--conn->ref > 0)
728		return (0);
729	ret = close(conn->sd);
730	free(conn->cache.buf);
731	free(conn->buf);
732	free(conn);
733	return (ret);
734}
735
736
737/*** Directory-related utility functions *************************************/
738
739int
740fetch_add_entry(struct url_ent **p, int *size, int *len,
741    const char *name, struct url_stat *us)
742{
743	struct url_ent *tmp;
744
745	if (*p == NULL) {
746		*size = 0;
747		*len = 0;
748	}
749
750	if (*len >= *size - 1) {
751		tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
752		if (tmp == NULL) {
753			errno = ENOMEM;
754			fetch_syserr();
755			return (-1);
756		}
757		*size = (*size * 2 + 1);
758		*p = tmp;
759	}
760
761	tmp = *p + *len;
762	snprintf(tmp->name, PATH_MAX, "%s", name);
763	memcpy(&tmp->stat, us, sizeof(*us));
764
765	(*len)++;
766	(++tmp)->name[0] = 0;
767
768	return (0);
769}
770
771
772/*** Authentication-related utility functions ********************************/
773
774static const char *
775fetch_read_word(FILE *f)
776{
777	static char word[1024];
778
779	if (fscanf(f, " %1023s ", word) != 1)
780		return (NULL);
781	return (word);
782}
783
784/*
785 * Get authentication data for a URL from .netrc
786 */
787int
788fetch_netrc_auth(struct url *url)
789{
790	char fn[PATH_MAX];
791	const char *word;
792	char *p;
793	FILE *f;
794
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");
799			return (-1);
800		}
801	} else {
802		if ((p = getenv("HOME")) != NULL) {
803			struct passwd *pwd;
804
805			if ((pwd = getpwuid(getuid())) == NULL ||
806			    (p = pwd->pw_dir) == NULL)
807				return (-1);
808		}
809		if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
810			return (-1);
811	}
812
813	if ((f = fopen(fn, "r")) == NULL)
814		return (-1);
815	while ((word = fetch_read_word(f)) != NULL) {
816		if (strcmp(word, "default") == 0) {
817			DEBUG(fetch_info("Using default .netrc settings"));
818			break;
819		}
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));
824			break;
825		}
826	}
827	if (word == NULL)
828		goto ferr;
829	while ((word = fetch_read_word(f)) != NULL) {
830		if (strcmp(word, "login") == 0) {
831			if ((word = fetch_read_word(f)) == NULL)
832				goto ferr;
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");
836				url->user[0] = '\0';
837			}
838		} else if (strcmp(word, "password") == 0) {
839			if ((word = fetch_read_word(f)) == NULL)
840				goto ferr;
841			if (snprintf(url->pwd, sizeof(url->pwd),
842				"%s", word) > (int)sizeof(url->pwd)) {
843				fetch_info("password in .netrc is too long");
844				url->pwd[0] = '\0';
845			}
846		} else if (strcmp(word, "account") == 0) {
847			if ((word = fetch_read_word(f)) == NULL)
848				goto ferr;
849			/* XXX not supported! */
850		} else {
851			break;
852		}
853	}
854	fclose(f);
855	return (0);
856 ferr:
857	fclose(f);
858	return (-1);
859}
860
861/*
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>).
868 */
869int
870fetch_no_proxy_match(const char *host)
871{
872	const char *no_proxy, *p, *q;
873	size_t h_len, d_len;
874
875	if ((no_proxy = getenv("NO_PROXY")) == NULL &&
876	    (no_proxy = getenv("no_proxy")) == NULL)
877		return (0);
878
879	/* asterisk matches any hostname */
880	if (strcmp(no_proxy, "*") == 0)
881		return (1);
882
883	h_len = strlen(host);
884	p = no_proxy;
885	do {
886		/* position p at the beginning of a domain suffix */
887		while (*p == ',' || isspace((unsigned char)*p))
888			p++;
889
890		/* position q at the first separator character */
891		for (q = p; *q; ++q)
892			if (*q == ',' || isspace((unsigned char)*q))
893				break;
894
895		d_len = q - p;
896		if (d_len > 0 && h_len >= d_len &&
897		    strncasecmp(host + h_len - d_len,
898			p, d_len) == 0) {
899			/* domain name matches */
900			return (1);
901		}
902
903		p = q + 1;
904	} while (*q);
905
906	return (0);
907}
908