xref: /dflybsd-src/lib/libfetch/common.c (revision 3eca42272f995aeaee9d72266e8812fa6860c9da)
1 /*-
2  * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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
16  *
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.
27  *
28  * $FreeBSD: src/lib/libfetch/common.c,v 1.56 2008/04/15 23:29:51 cperciva Exp $
29  */
30 
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <sys/time.h>
34 #include <sys/uio.h>
35 
36 #include <netinet/in.h>
37 
38 #include <ctype.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <netdb.h>
42 #include <pwd.h>
43 #include <stdarg.h>
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #include "fetch.h"
50 #include "common.h"
51 
52 
53 /*** Local data **************************************************************/
54 
55 /*
56  * Error messages for resolver errors
57  */
58 static struct fetcherr netdb_errlist[] = {
59 #ifdef EAI_NODATA
60 	{ EAI_NODATA,	FETCH_RESOLV,	"Host not found" },
61 #endif
62 	{ EAI_AGAIN,	FETCH_TEMP,	"Transient resolver failure" },
63 	{ EAI_FAIL,	FETCH_RESOLV,	"Non-recoverable resolver failure" },
64 	{ EAI_NONAME,	FETCH_RESOLV,	"No address record" },
65 	{ -1,		FETCH_UNKNOWN,	"Unknown resolver error" }
66 };
67 
68 /* End-of-Line */
69 static const char ENDL[2] = "\r\n";
70 
71 
72 /*** Error-reporting functions ***********************************************/
73 
74 /*
75  * Map error code to string
76  */
77 static struct fetcherr *
78 fetch_finderr(struct fetcherr *p, int e)
79 {
80 	while (p->num != -1 && p->num != e)
81 		p++;
82 	return (p);
83 }
84 
85 /*
86  * Set error code
87  */
88 void
89 fetch_seterr(struct fetcherr *p, int e)
90 {
91 	p = fetch_finderr(p, e);
92 	fetchLastErrCode = p->cat;
93 	snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
94 }
95 
96 /*
97  * Set error code according to errno
98  */
99 void
100 fetch_syserr(void)
101 {
102 	switch (errno) {
103 	case 0:
104 		fetchLastErrCode = FETCH_OK;
105 		break;
106 	case EPERM:
107 	case EACCES:
108 	case EROFS:
109 	case EAUTH:
110 	case ENEEDAUTH:
111 		fetchLastErrCode = FETCH_AUTH;
112 		break;
113 	case ENOENT:
114 	case EISDIR: /* XXX */
115 		fetchLastErrCode = FETCH_UNAVAIL;
116 		break;
117 	case ENOMEM:
118 		fetchLastErrCode = FETCH_MEMORY;
119 		break;
120 	case EBUSY:
121 	case EAGAIN:
122 		fetchLastErrCode = FETCH_TEMP;
123 		break;
124 	case EEXIST:
125 		fetchLastErrCode = FETCH_EXISTS;
126 		break;
127 	case ENOSPC:
128 		fetchLastErrCode = FETCH_FULL;
129 		break;
130 	case EADDRINUSE:
131 	case EADDRNOTAVAIL:
132 	case ENETDOWN:
133 	case ENETUNREACH:
134 	case ENETRESET:
135 	case EHOSTUNREACH:
136 		fetchLastErrCode = FETCH_NETWORK;
137 		break;
138 	case ECONNABORTED:
139 	case ECONNRESET:
140 		fetchLastErrCode = FETCH_ABORT;
141 		break;
142 	case ETIMEDOUT:
143 		fetchLastErrCode = FETCH_TIMEOUT;
144 		break;
145 	case ECONNREFUSED:
146 	case EHOSTDOWN:
147 		fetchLastErrCode = FETCH_DOWN;
148 		break;
149 default:
150 		fetchLastErrCode = FETCH_UNKNOWN;
151 	}
152 	snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
153 }
154 
155 
156 /*
157  * Emit status message
158  */
159 void
160 fetch_info(const char *fmt, ...)
161 {
162 	va_list ap;
163 
164 	va_start(ap, fmt);
165 	vfprintf(stderr, fmt, ap);
166 	va_end(ap);
167 	fputc('\n', stderr);
168 }
169 
170 
171 /*** Network-related utility functions ***************************************/
172 
173 /*
174  * Return the default port for a scheme
175  */
176 int
177 fetch_default_port(const char *scheme)
178 {
179 	struct servent *se;
180 
181 	if ((se = getservbyname(scheme, "tcp")) != NULL)
182 		return (ntohs(se->s_port));
183 	if (strcasecmp(scheme, SCHEME_FTP) == 0)
184 		return (FTP_DEFAULT_PORT);
185 	if (strcasecmp(scheme, SCHEME_HTTP) == 0)
186 		return (HTTP_DEFAULT_PORT);
187 	return (0);
188 }
189 
190 /*
191  * Return the default proxy port for a scheme
192  */
193 int
194 fetch_default_proxy_port(const char *scheme)
195 {
196 	if (strcasecmp(scheme, SCHEME_FTP) == 0)
197 		return (FTP_DEFAULT_PROXY_PORT);
198 	if (strcasecmp(scheme, SCHEME_HTTP) == 0)
199 		return (HTTP_DEFAULT_PROXY_PORT);
200 	return (0);
201 }
202 
203 
204 /*
205  * Create a connection for an existing descriptor.
206  */
207 conn_t *
208 fetch_reopen(int sd)
209 {
210 	conn_t *conn;
211 
212 	/* allocate and fill connection structure */
213 	if ((conn = calloc(1, sizeof(*conn))) == NULL)
214 		return (NULL);
215         fcntl(sd, F_SETFD, FD_CLOEXEC);
216 	conn->sd = sd;
217 	++conn->ref;
218 	return (conn);
219 }
220 
221 
222 /*
223  * Bump a connection's reference count.
224  */
225 conn_t *
226 fetch_ref(conn_t *conn)
227 {
228 
229 	++conn->ref;
230 	return (conn);
231 }
232 
233 
234 /*
235  * Bind a socket to a specific local address
236  */
237 int
238 fetch_bind(int sd, int af, const char *addr)
239 {
240 	struct addrinfo hints, *res, *res0;
241 	int err;
242 
243 	memset(&hints, 0, sizeof(hints));
244 	hints.ai_family = af;
245 	hints.ai_socktype = SOCK_STREAM;
246 	hints.ai_protocol = 0;
247 	if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0)
248 		return (-1);
249 	for (res = res0; res; res = res->ai_next)
250 		if (bind(sd, res->ai_addr, res->ai_addrlen) == 0)
251 			return (0);
252 	return (-1);
253 }
254 
255 
256 /*
257  * Establish a TCP connection to the specified port on the specified host.
258  */
259 conn_t *
260 fetch_connect(const char *host, int port, int af, int verbose)
261 {
262 	conn_t *conn;
263 	char pbuf[10];
264 	const char *bindaddr;
265 	struct addrinfo hints, *res, *res0;
266 	int sd, err;
267 
268 	DEBUG(fprintf(stderr, "---> %s:%d\n", host, port));
269 
270 	if (verbose)
271 		fetch_info("looking up %s", host);
272 
273 	/* look up host name and set up socket address structure */
274 	snprintf(pbuf, sizeof(pbuf), "%d", port);
275 	memset(&hints, 0, sizeof(hints));
276 	hints.ai_family = af;
277 	hints.ai_socktype = SOCK_STREAM;
278 	hints.ai_protocol = 0;
279 	if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) {
280 		netdb_seterr(err);
281 		return (NULL);
282 	}
283 	bindaddr = getenv("FETCH_BIND_ADDRESS");
284 
285 	if (verbose)
286 		fetch_info("connecting to %s:%d", host, port);
287 
288 	/* try to connect */
289 	for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) {
290 		if ((sd = socket(res->ai_family, res->ai_socktype,
291 			 res->ai_protocol)) == -1)
292 			continue;
293 		if (bindaddr != NULL && *bindaddr != '\0' &&
294 		    fetch_bind(sd, res->ai_family, bindaddr) != 0) {
295 			fetch_info("failed to bind to '%s'", bindaddr);
296 			close(sd);
297 			continue;
298 		}
299 		if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 &&
300                     fcntl(sd, F_SETFL, O_NONBLOCK) == 0)
301 			break;
302 		close(sd);
303 	}
304 	freeaddrinfo(res0);
305 	if (sd == -1) {
306 		fetch_syserr();
307 		return (NULL);
308 	}
309 
310 	if ((conn = fetch_reopen(sd)) == NULL) {
311 		fetch_syserr();
312 		close(sd);
313 	}
314 	return (conn);
315 }
316 
317 
318 /*
319  * Enable SSL on a connection.
320  */
321 int
322 fetch_ssl(conn_t *conn, int verbose)
323 {
324         int ret, ssl_err;
325 
326 #ifdef WITH_SSL
327 	/* Init the SSL library and context */
328 	if (!SSL_library_init()){
329 		fprintf(stderr, "SSL library init failed\n");
330 		return (-1);
331 	}
332 
333 	SSL_load_error_strings();
334 
335 	conn->ssl_meth = SSLv23_client_method();
336 	conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
337 	SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
338 
339 	conn->ssl = SSL_new(conn->ssl_ctx);
340 	if (conn->ssl == NULL){
341 		fprintf(stderr, "SSL context creation failed\n");
342 		return (-1);
343 	}
344 	SSL_set_fd(conn->ssl, conn->sd);
345 	while ((ret = SSL_connect(conn->ssl)) == -1) {
346 		ssl_err = SSL_get_error(conn->ssl, ret);
347 		if (ssl_err != SSL_ERROR_WANT_READ &&
348 		    ssl_err != SSL_ERROR_WANT_WRITE) {
349 			ERR_print_errors_fp(stderr);
350 			return (-1);
351 		}
352 	}
353 
354 	if (verbose) {
355 		X509_NAME *name;
356 		char *str;
357 
358 		fprintf(stderr, "SSL connection established using %s\n",
359 		    SSL_get_cipher(conn->ssl));
360 		conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
361 		name = X509_get_subject_name(conn->ssl_cert);
362 		str = X509_NAME_oneline(name, 0, 0);
363 		printf("Certificate subject: %s\n", str);
364 		free(str);
365 		name = X509_get_issuer_name(conn->ssl_cert);
366 		str = X509_NAME_oneline(name, 0, 0);
367 		printf("Certificate issuer: %s\n", str);
368 		free(str);
369 	}
370 
371 	return (0);
372 #else
373 	(void)conn;
374 	(void)verbose;
375 	fprintf(stderr, "SSL support disabled\n");
376 	return (-1);
377 #endif
378 }
379 
380 #define FETCH_READ_WAIT		-2
381 #define FETCH_READ_ERROR	-1
382 #define FETCH_READ_DONE		 0
383 
384 #ifdef WITH_SSL
385 static ssize_t
386 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
387 {
388 	ssize_t rlen;
389 	int ssl_err;
390 
391 	rlen = SSL_read(ssl, buf, len);
392 	if (rlen < 0) {
393 		ssl_err = SSL_get_error(ssl, rlen);
394 		if (ssl_err == SSL_ERROR_WANT_READ ||
395 		    ssl_err == SSL_ERROR_WANT_WRITE) {
396 			return (FETCH_READ_WAIT);
397 		} else {
398 			ERR_print_errors_fp(stderr);
399 			return (FETCH_READ_ERROR);
400 		}
401 	}
402 	return (rlen);
403 }
404 #endif
405 
406 /*
407  * Cache some data that was read from a socket but cannot be immediately
408  * returned because of an interrupted system call.
409  */
410 static int
411 fetch_cache_data(conn_t *conn, char *src, size_t nbytes)
412 {
413 	char *tmp;
414 
415 	if (conn->cache.size < nbytes) {
416 		tmp = realloc(conn->cache.buf, nbytes);
417 		if (tmp == NULL) {
418 			fetch_syserr();
419 			return (-1);
420 		}
421 		conn->cache.buf = tmp;
422 		conn->cache.size = nbytes;
423 	}
424 
425 	memcpy(conn->cache.buf, src, nbytes);
426 	conn->cache.len = nbytes;
427 	conn->cache.pos = 0;
428 
429 	return (0);
430 }
431 
432 
433 static ssize_t
434 fetch_socket_read(int sd, char *buf, size_t len)
435 {
436 	ssize_t rlen;
437 
438 	rlen = read(sd, buf, len);
439 	if (rlen < 0) {
440 		if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
441 			return (FETCH_READ_WAIT);
442 		else
443 			return (FETCH_READ_ERROR);
444 	}
445 	return (rlen);
446 }
447 
448 /*
449  * Read a character from a connection w/ timeout
450  */
451 ssize_t
452 fetch_read(conn_t *conn, char *buf, size_t len)
453 {
454 	struct timeval now, timeout, delta;
455 	fd_set readfds;
456 	ssize_t rlen, total;
457 	int r;
458 	char *start;
459 
460 	if (fetchTimeout) {
461 		FD_ZERO(&readfds);
462 		gettimeofday(&timeout, NULL);
463 		timeout.tv_sec += fetchTimeout;
464 	}
465 
466 	total = 0;
467 	start = buf;
468 
469 	if (conn->cache.len > 0) {
470 		/*
471 		 * The last invocation of fetch_read was interrupted by a
472 		 * signal after some data had been read from the socket. Copy
473 		 * the cached data into the supplied buffer before trying to
474 		 * read from the socket again.
475 		 */
476 		total = (conn->cache.len < len) ? conn->cache.len : len;
477 		memcpy(buf, conn->cache.buf, total);
478 
479 		conn->cache.len -= total;
480 		conn->cache.pos += total;
481 		len -= total;
482 		buf += total;
483 	}
484 
485 	while (len > 0) {
486 		/*
487 		 * The socket is non-blocking.  Instead of the canonical
488 		 * select() -> read(), we do the following:
489 		 *
490 		 * 1) call read() or SSL_read().
491 		 * 2) if an error occurred, return -1.
492 		 * 3) if we received data but we still expect more,
493 		 *    update our counters and loop.
494 		 * 4) if read() or SSL_read() signaled EOF, return.
495 		 * 5) if we did not receive any data but we're not at EOF,
496 		 *    call select().
497 		 *
498 		 * In the SSL case, this is necessary because if we
499 		 * receive a close notification, we have to call
500 		 * SSL_read() one additional time after we've read
501 		 * everything we received.
502 		 *
503 		 * In the non-SSL case, it may improve performance (very
504 		 * slightly) when reading small amounts of data.
505 		 */
506 #ifdef WITH_SSL
507 		if (conn->ssl != NULL)
508 			rlen = fetch_ssl_read(conn->ssl, buf, len);
509 		else
510 #endif
511 			rlen = fetch_socket_read(conn->sd, buf, len);
512 		if (rlen == 0) {
513 			break;
514 		} else if (rlen > 0) {
515 			len -= rlen;
516 			buf += rlen;
517 			total += rlen;
518 			continue;
519 		} else if (rlen == FETCH_READ_ERROR) {
520 			if (errno == EINTR)
521 				fetch_cache_data(conn, start, total);
522 			return (-1);
523 		}
524 		// assert(rlen == FETCH_READ_WAIT);
525 		while (fetchTimeout && !FD_ISSET(conn->sd, &readfds)) {
526 			FD_SET(conn->sd, &readfds);
527 			gettimeofday(&now, NULL);
528 			delta.tv_sec = timeout.tv_sec - now.tv_sec;
529 			delta.tv_usec = timeout.tv_usec - now.tv_usec;
530 			if (delta.tv_usec < 0) {
531 				delta.tv_usec += 1000000;
532 				delta.tv_sec--;
533 			}
534 			if (delta.tv_sec < 0) {
535 				errno = ETIMEDOUT;
536 				fetch_syserr();
537 				return (-1);
538 			}
539 			errno = 0;
540 			r = select(conn->sd + 1, &readfds, NULL, NULL, &delta);
541 			if (r == -1) {
542 				if (errno == EINTR) {
543 					if (fetchRestartCalls)
544 						continue;
545 					/* Save anything that was read. */
546 					fetch_cache_data(conn, start, total);
547 				}
548 				fetch_syserr();
549 				return (-1);
550 			}
551 		}
552 	}
553 	return (total);
554 }
555 
556 
557 /*
558  * Read a line of text from a connection w/ timeout
559  */
560 #define MIN_BUF_SIZE 1024
561 
562 int
563 fetch_getln(conn_t *conn)
564 {
565 	char *tmp;
566 	size_t tmpsize;
567 	ssize_t len;
568 	char c;
569 
570 	if (conn->buf == NULL) {
571 		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
572 			errno = ENOMEM;
573 			return (-1);
574 		}
575 		conn->bufsize = MIN_BUF_SIZE;
576 	}
577 
578 	conn->buf[0] = '\0';
579 	conn->buflen = 0;
580 
581 	do {
582 		len = fetch_read(conn, &c, 1);
583 		if (len == -1)
584 			return (-1);
585 		if (len == 0)
586 			break;
587 		conn->buf[conn->buflen++] = c;
588 		if (conn->buflen == conn->bufsize) {
589 			tmp = conn->buf;
590 			tmpsize = conn->bufsize * 2 + 1;
591 			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
592 				errno = ENOMEM;
593 				return (-1);
594 			}
595 			conn->buf = tmp;
596 			conn->bufsize = tmpsize;
597 		}
598 	} while (c != '\n');
599 
600 	conn->buf[conn->buflen] = '\0';
601 	DEBUG(fprintf(stderr, "<<< %s", conn->buf));
602 	return (0);
603 }
604 
605 
606 /*
607  * Write to a connection w/ timeout
608  */
609 ssize_t
610 fetch_write(conn_t *conn, const char *buf, size_t len)
611 {
612 	struct iovec iov;
613 
614 	iov.iov_base = __DECONST(char *, buf);
615 	iov.iov_len = len;
616 	return fetch_writev(conn, &iov, 1);
617 }
618 
619 /*
620  * Write a vector to a connection w/ timeout
621  * Note: can modify the iovec.
622  */
623 ssize_t
624 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
625 {
626 	struct timeval now, timeout, delta;
627 	fd_set writefds;
628 	ssize_t wlen, total;
629 	int r;
630 
631 	if (fetchTimeout) {
632 		FD_ZERO(&writefds);
633 		gettimeofday(&timeout, NULL);
634 		timeout.tv_sec += fetchTimeout;
635 	}
636 
637 	total = 0;
638 	while (iovcnt > 0) {
639 		while (fetchTimeout && !FD_ISSET(conn->sd, &writefds)) {
640 			FD_SET(conn->sd, &writefds);
641 			gettimeofday(&now, NULL);
642 			delta.tv_sec = timeout.tv_sec - now.tv_sec;
643 			delta.tv_usec = timeout.tv_usec - now.tv_usec;
644 			if (delta.tv_usec < 0) {
645 				delta.tv_usec += 1000000;
646 				delta.tv_sec--;
647 			}
648 			if (delta.tv_sec < 0) {
649 				errno = ETIMEDOUT;
650 				fetch_syserr();
651 				return (-1);
652 			}
653 			errno = 0;
654 			r = select(conn->sd + 1, NULL, &writefds, NULL, &delta);
655 			if (r == -1) {
656 				if (errno == EINTR && fetchRestartCalls)
657 					continue;
658 				return (-1);
659 			}
660 		}
661 		errno = 0;
662 #ifdef WITH_SSL
663 		if (conn->ssl != NULL)
664 			wlen = SSL_write(conn->ssl,
665 			    iov->iov_base, iov->iov_len);
666 		else
667 #endif
668 			wlen = writev(conn->sd, iov, iovcnt);
669 		if (wlen == 0) {
670 			/* we consider a short write a failure */
671 			/* XXX perhaps we shouldn't in the SSL case */
672 			errno = EPIPE;
673 			fetch_syserr();
674 			return (-1);
675 		}
676 		if (wlen < 0) {
677 			if (errno == EINTR && fetchRestartCalls)
678 				continue;
679 			return (-1);
680 		}
681 		total += wlen;
682 		while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
683 			wlen -= iov->iov_len;
684 			iov++;
685 			iovcnt--;
686 		}
687 		if (iovcnt > 0) {
688 			iov->iov_len -= wlen;
689 			iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
690 		}
691 	}
692 	return (total);
693 }
694 
695 
696 /*
697  * Write a line of text to a connection w/ timeout
698  */
699 int
700 fetch_putln(conn_t *conn, const char *str, size_t len)
701 {
702 	struct iovec iov[2];
703 	int ret;
704 
705 	DEBUG(fprintf(stderr, ">>> %s\n", str));
706 	iov[0].iov_base = __DECONST(char *, str);
707 	iov[0].iov_len = len;
708 	iov[1].iov_base = __DECONST(char *, ENDL);
709 	iov[1].iov_len = sizeof(ENDL);
710 	if (len == 0)
711 		ret = fetch_writev(conn, &iov[1], 1);
712 	else
713 		ret = fetch_writev(conn, iov, 2);
714 	if (ret == -1)
715 		return (-1);
716 	return (0);
717 }
718 
719 
720 /*
721  * Close connection
722  */
723 int
724 fetch_close(conn_t *conn)
725 {
726 	int ret;
727 
728 	if (--conn->ref > 0)
729 		return (0);
730 	ret = close(conn->sd);
731 	free(conn->cache.buf);
732 	free(conn->buf);
733 	free(conn);
734 	return (ret);
735 }
736 
737 
738 /*** Directory-related utility functions *************************************/
739 
740 int
741 fetch_add_entry(struct url_ent **p, int *size, int *len,
742     const char *name, struct url_stat *us)
743 {
744 	struct url_ent *tmp;
745 
746 	if (*p == NULL) {
747 		*size = 0;
748 		*len = 0;
749 	}
750 
751 	if (*len >= *size - 1) {
752 		tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p));
753 		if (tmp == NULL) {
754 			errno = ENOMEM;
755 			fetch_syserr();
756 			return (-1);
757 		}
758 		*size = (*size * 2 + 1);
759 		*p = tmp;
760 	}
761 
762 	tmp = *p + *len;
763 	snprintf(tmp->name, PATH_MAX, "%s", name);
764 	memcpy(&tmp->stat, us, sizeof(*us));
765 
766 	(*len)++;
767 	(++tmp)->name[0] = 0;
768 
769 	return (0);
770 }
771 
772 
773 /*** Authentication-related utility functions ********************************/
774 
775 static const char *
776 fetch_read_word(FILE *f)
777 {
778 	static char word[1024];
779 
780 	if (fscanf(f, " %1023s ", word) != 1)
781 		return (NULL);
782 	return (word);
783 }
784 
785 /*
786  * Get authentication data for a URL from .netrc
787  */
788 int
789 fetch_netrc_auth(struct url *url)
790 {
791 	char fn[PATH_MAX];
792 	const char *word;
793 	char *p;
794 	FILE *f;
795 
796 	if ((p = getenv("NETRC")) != NULL) {
797 		if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
798 			fetch_info("$NETRC specifies a file name "
799 			    "longer than PATH_MAX");
800 			return (-1);
801 		}
802 	} else {
803 		if ((p = getenv("HOME")) != NULL) {
804 			struct passwd *pwd;
805 
806 			if ((pwd = getpwuid(getuid())) == NULL ||
807 			    (p = pwd->pw_dir) == NULL)
808 				return (-1);
809 		}
810 		if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
811 			return (-1);
812 	}
813 
814 	if ((f = fopen(fn, "r")) == NULL)
815 		return (-1);
816 	while ((word = fetch_read_word(f)) != NULL) {
817 		if (strcmp(word, "default") == 0) {
818 			DEBUG(fetch_info("Using default .netrc settings"));
819 			break;
820 		}
821 		if (strcmp(word, "machine") == 0 &&
822 		    (word = fetch_read_word(f)) != NULL &&
823 		    strcasecmp(word, url->host) == 0) {
824 			DEBUG(fetch_info("Using .netrc settings for %s", word));
825 			break;
826 		}
827 	}
828 	if (word == NULL)
829 		goto ferr;
830 	while ((word = fetch_read_word(f)) != NULL) {
831 		if (strcmp(word, "login") == 0) {
832 			if ((word = fetch_read_word(f)) == NULL)
833 				goto ferr;
834 			if (snprintf(url->user, sizeof(url->user),
835 				"%s", word) > (int)sizeof(url->user)) {
836 				fetch_info("login name in .netrc is too long");
837 				url->user[0] = '\0';
838 			}
839 		} else if (strcmp(word, "password") == 0) {
840 			if ((word = fetch_read_word(f)) == NULL)
841 				goto ferr;
842 			if (snprintf(url->pwd, sizeof(url->pwd),
843 				"%s", word) > (int)sizeof(url->pwd)) {
844 				fetch_info("password in .netrc is too long");
845 				url->pwd[0] = '\0';
846 			}
847 		} else if (strcmp(word, "account") == 0) {
848 			if ((word = fetch_read_word(f)) == NULL)
849 				goto ferr;
850 			/* XXX not supported! */
851 		} else {
852 			break;
853 		}
854 	}
855 	fclose(f);
856 	return (0);
857  ferr:
858 	fclose(f);
859 	return (-1);
860 }
861 
862 /*
863  * The no_proxy environment variable specifies a set of domains for
864  * which the proxy should not be consulted; the contents is a comma-,
865  * or space-separated list of domain names.  A single asterisk will
866  * override all proxy variables and no transactions will be proxied
867  * (for compatability with lynx and curl, see the discussion at
868  * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
869  */
870 int
871 fetch_no_proxy_match(const char *host)
872 {
873 	const char *no_proxy, *p, *q;
874 	size_t h_len, d_len;
875 
876 	if ((no_proxy = getenv("NO_PROXY")) == NULL &&
877 	    (no_proxy = getenv("no_proxy")) == NULL)
878 		return (0);
879 
880 	/* asterisk matches any hostname */
881 	if (strcmp(no_proxy, "*") == 0)
882 		return (1);
883 
884 	h_len = strlen(host);
885 	p = no_proxy;
886 	do {
887 		/* position p at the beginning of a domain suffix */
888 		while (*p == ',' || isspace((unsigned char)*p))
889 			p++;
890 
891 		/* position q at the first separator character */
892 		for (q = p; *q; ++q)
893 			if (*q == ',' || isspace((unsigned char)*q))
894 				break;
895 
896 		d_len = q - p;
897 		if (d_len > 0 && h_len >= d_len &&
898 		    strncasecmp(host + h_len - d_len,
899 			p, d_len) == 0) {
900 			/* domain name matches */
901 			return (1);
902 		}
903 
904 		p = q + 1;
905 	} while (*q);
906 
907 	return (0);
908 }
909