xref: /freebsd/lib/libfetch/common.c (revision f6a3b357e9be4c6423c85eff9a847163a0d307c8)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1998-2016 Dag-Erling Smørgrav
5  * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer
13  *    in this position and unchanged.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <sys/uio.h>
39 
40 #include <netinet/in.h>
41 
42 #include <ctype.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <netdb.h>
46 #include <poll.h>
47 #include <pwd.h>
48 #include <stdarg.h>
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <unistd.h>
53 
54 #ifdef WITH_SSL
55 #include <openssl/x509v3.h>
56 #endif
57 
58 #include "fetch.h"
59 #include "common.h"
60 
61 
62 /*** Local data **************************************************************/
63 
64 /*
65  * Error messages for resolver errors
66  */
67 static struct fetcherr netdb_errlist[] = {
68 #ifdef EAI_NODATA
69 	{ EAI_NODATA,	FETCH_RESOLV,	"Host not found" },
70 #endif
71 	{ EAI_AGAIN,	FETCH_TEMP,	"Transient resolver failure" },
72 	{ EAI_FAIL,	FETCH_RESOLV,	"Non-recoverable resolver failure" },
73 	{ EAI_NONAME,	FETCH_RESOLV,	"No address record" },
74 	{ -1,		FETCH_UNKNOWN,	"Unknown resolver error" }
75 };
76 
77 /* End-of-Line */
78 static const char ENDL[2] = "\r\n";
79 
80 
81 /*** Error-reporting functions ***********************************************/
82 
83 /*
84  * Map error code to string
85  */
86 static struct fetcherr *
87 fetch_finderr(struct fetcherr *p, int e)
88 {
89 	while (p->num != -1 && p->num != e)
90 		p++;
91 	return (p);
92 }
93 
94 /*
95  * Set error code
96  */
97 void
98 fetch_seterr(struct fetcherr *p, int e)
99 {
100 	p = fetch_finderr(p, e);
101 	fetchLastErrCode = p->cat;
102 	snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
103 }
104 
105 /*
106  * Set error code according to errno
107  */
108 void
109 fetch_syserr(void)
110 {
111 	switch (errno) {
112 	case 0:
113 		fetchLastErrCode = FETCH_OK;
114 		break;
115 	case EPERM:
116 	case EACCES:
117 	case EROFS:
118 	case EAUTH:
119 	case ENEEDAUTH:
120 		fetchLastErrCode = FETCH_AUTH;
121 		break;
122 	case ENOENT:
123 	case EISDIR: /* XXX */
124 		fetchLastErrCode = FETCH_UNAVAIL;
125 		break;
126 	case ENOMEM:
127 		fetchLastErrCode = FETCH_MEMORY;
128 		break;
129 	case EBUSY:
130 	case EAGAIN:
131 		fetchLastErrCode = FETCH_TEMP;
132 		break;
133 	case EEXIST:
134 		fetchLastErrCode = FETCH_EXISTS;
135 		break;
136 	case ENOSPC:
137 		fetchLastErrCode = FETCH_FULL;
138 		break;
139 	case EADDRINUSE:
140 	case EADDRNOTAVAIL:
141 	case ENETDOWN:
142 	case ENETUNREACH:
143 	case ENETRESET:
144 	case EHOSTUNREACH:
145 		fetchLastErrCode = FETCH_NETWORK;
146 		break;
147 	case ECONNABORTED:
148 	case ECONNRESET:
149 		fetchLastErrCode = FETCH_ABORT;
150 		break;
151 	case ETIMEDOUT:
152 		fetchLastErrCode = FETCH_TIMEOUT;
153 		break;
154 	case ECONNREFUSED:
155 	case EHOSTDOWN:
156 		fetchLastErrCode = FETCH_DOWN;
157 		break;
158 	default:
159 		fetchLastErrCode = FETCH_UNKNOWN;
160 	}
161 	snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
162 }
163 
164 
165 /*
166  * Emit status message
167  */
168 void
169 fetch_info(const char *fmt, ...)
170 {
171 	va_list ap;
172 
173 	va_start(ap, fmt);
174 	vfprintf(stderr, fmt, ap);
175 	va_end(ap);
176 	fputc('\n', stderr);
177 }
178 
179 
180 /*** Network-related utility functions ***************************************/
181 
182 /*
183  * Return the default port for a scheme
184  */
185 int
186 fetch_default_port(const char *scheme)
187 {
188 	struct servent *se;
189 
190 	if ((se = getservbyname(scheme, "tcp")) != NULL)
191 		return (ntohs(se->s_port));
192 	if (strcmp(scheme, SCHEME_FTP) == 0)
193 		return (FTP_DEFAULT_PORT);
194 	if (strcmp(scheme, SCHEME_HTTP) == 0)
195 		return (HTTP_DEFAULT_PORT);
196 	return (0);
197 }
198 
199 /*
200  * Return the default proxy port for a scheme
201  */
202 int
203 fetch_default_proxy_port(const char *scheme)
204 {
205 	if (strcmp(scheme, SCHEME_FTP) == 0)
206 		return (FTP_DEFAULT_PROXY_PORT);
207 	if (strcmp(scheme, SCHEME_HTTP) == 0)
208 		return (HTTP_DEFAULT_PROXY_PORT);
209 	return (0);
210 }
211 
212 
213 /*
214  * Create a connection for an existing descriptor.
215  */
216 conn_t *
217 fetch_reopen(int sd)
218 {
219 	conn_t *conn;
220 	int opt = 1;
221 
222 	/* allocate and fill connection structure */
223 	if ((conn = calloc(1, sizeof(*conn))) == NULL)
224 		return (NULL);
225 	fcntl(sd, F_SETFD, FD_CLOEXEC);
226 	setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
227 	conn->sd = sd;
228 	++conn->ref;
229 	return (conn);
230 }
231 
232 
233 /*
234  * Bump a connection's reference count.
235  */
236 conn_t *
237 fetch_ref(conn_t *conn)
238 {
239 
240 	++conn->ref;
241 	return (conn);
242 }
243 
244 
245 /*
246  * Resolve an address
247  */
248 struct addrinfo *
249 fetch_resolve(const char *addr, int port, int af)
250 {
251 	char hbuf[256], sbuf[8];
252 	struct addrinfo hints, *res;
253 	const char *hb, *he, *sep;
254 	const char *host, *service;
255 	int err, len;
256 
257 	/* first, check for a bracketed IPv6 address */
258 	if (*addr == '[') {
259 		hb = addr + 1;
260 		if ((sep = strchr(hb, ']')) == NULL) {
261 			errno = EINVAL;
262 			goto syserr;
263 		}
264 		he = sep++;
265 	} else {
266 		hb = addr;
267 		sep = strchrnul(hb, ':');
268 		he = sep;
269 	}
270 
271 	/* see if we need to copy the host name */
272 	if (*he != '\0') {
273 		len = snprintf(hbuf, sizeof(hbuf),
274 		    "%.*s", (int)(he - hb), hb);
275 		if (len < 0)
276 			goto syserr;
277 		if (len >= (int)sizeof(hbuf)) {
278 			errno = ENAMETOOLONG;
279 			goto syserr;
280 		}
281 		host = hbuf;
282 	} else {
283 		host = hb;
284 	}
285 
286 	/* was it followed by a service name? */
287 	if (*sep == '\0' && port != 0) {
288 		if (port < 1 || port > 65535) {
289 			errno = EINVAL;
290 			goto syserr;
291 		}
292 		if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0)
293 			goto syserr;
294 		service = sbuf;
295 	} else if (*sep != '\0') {
296 		service = sep + 1;
297 	} else {
298 		service = NULL;
299 	}
300 
301 	/* resolve */
302 	memset(&hints, 0, sizeof(hints));
303 	hints.ai_family = af;
304 	hints.ai_socktype = SOCK_STREAM;
305 	hints.ai_flags = AI_ADDRCONFIG;
306 	if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
307 		netdb_seterr(err);
308 		return (NULL);
309 	}
310 	return (res);
311 syserr:
312 	fetch_syserr();
313 	return (NULL);
314 }
315 
316 
317 
318 /*
319  * Bind a socket to a specific local address
320  */
321 int
322 fetch_bind(int sd, int af, const char *addr)
323 {
324 	struct addrinfo *cliai, *ai;
325 	int err;
326 
327 	if ((cliai = fetch_resolve(addr, 0, af)) == NULL)
328 		return (-1);
329 	for (ai = cliai; ai != NULL; ai = ai->ai_next)
330 		if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0)
331 			break;
332 	if (err != 0)
333 		fetch_syserr();
334 	freeaddrinfo(cliai);
335 	return (err == 0 ? 0 : -1);
336 }
337 
338 
339 /*
340  * Establish a TCP connection to the specified port on the specified host.
341  */
342 conn_t *
343 fetch_connect(const char *host, int port, int af, int verbose)
344 {
345 	struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai;
346 	const char *bindaddr;
347 	conn_t *conn = NULL;
348 	int err = 0, sd = -1;
349 
350 	DEBUGF("---> %s:%d\n", host, port);
351 
352 	/* resolve server address */
353 	if (verbose)
354 		fetch_info("resolving server address: %s:%d", host, port);
355 	if ((sais = fetch_resolve(host, port, af)) == NULL)
356 		goto fail;
357 
358 	/* resolve client address */
359 	bindaddr = getenv("FETCH_BIND_ADDRESS");
360 	if (bindaddr != NULL && *bindaddr != '\0') {
361 		if (verbose)
362 			fetch_info("resolving client address: %s", bindaddr);
363 		if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL)
364 			goto fail;
365 	}
366 
367 	/* try each server address in turn */
368 	for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) {
369 		/* open socket */
370 		if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0)
371 			goto syserr;
372 		/* attempt to bind to client address */
373 		for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) {
374 			if (cai->ai_family != sai->ai_family)
375 				continue;
376 			if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0)
377 				break;
378 		}
379 		if (err != 0) {
380 			if (verbose)
381 				fetch_info("failed to bind to %s", bindaddr);
382 			goto syserr;
383 		}
384 		/* attempt to connect to server address */
385 		if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0)
386 			break;
387 		/* clean up before next attempt */
388 		close(sd);
389 		sd = -1;
390 	}
391 	if (err != 0) {
392 		if (verbose)
393 			fetch_info("failed to connect to %s:%d", host, port);
394 		goto syserr;
395 	}
396 
397 	if ((conn = fetch_reopen(sd)) == NULL)
398 		goto syserr;
399 	if (cais != NULL)
400 		freeaddrinfo(cais);
401 	if (sais != NULL)
402 		freeaddrinfo(sais);
403 	return (conn);
404 syserr:
405 	fetch_syserr();
406 	goto fail;
407 fail:
408 	if (sd >= 0)
409 		close(sd);
410 	if (cais != NULL)
411 		freeaddrinfo(cais);
412 	if (sais != NULL)
413 		freeaddrinfo(sais);
414 	return (NULL);
415 }
416 
417 #ifdef WITH_SSL
418 /*
419  * Convert characters A-Z to lowercase (intentionally avoid any locale
420  * specific conversions).
421  */
422 static char
423 fetch_ssl_tolower(char in)
424 {
425 	if (in >= 'A' && in <= 'Z')
426 		return (in + 32);
427 	else
428 		return (in);
429 }
430 
431 /*
432  * isalpha implementation that intentionally avoids any locale specific
433  * conversions.
434  */
435 static int
436 fetch_ssl_isalpha(char in)
437 {
438 	return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
439 }
440 
441 /*
442  * Check if passed hostnames a and b are equal.
443  */
444 static int
445 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
446     size_t blen)
447 {
448 	size_t i;
449 
450 	if (alen != blen)
451 		return (0);
452 	for (i = 0; i < alen; ++i) {
453 		if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
454 			return (0);
455 	}
456 	return (1);
457 }
458 
459 /*
460  * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
461  * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
462  * numeric characters. Double hyphens (like they're found in IDN a-labels
463  * 'xn--') are not allowed. Empty labels are invalid.
464  */
465 static int
466 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
467 {
468 	size_t i;
469 
470 	if (!len || l[0] == '-' || l[len-1] == '-')
471 		return (0);
472 	for (i = 0; i < len; ++i) {
473 		if (!isdigit(l[i]) &&
474 		    !fetch_ssl_isalpha(l[i]) &&
475 		    !(l[i] == '*' && wcok) &&
476 		    !(l[i] == '-' && l[i - 1] != '-'))
477 			return (0);
478 	}
479 	return (1);
480 }
481 
482 /*
483  * Check if host name consists only of numbers. This might indicate an IP
484  * address, which is not a good idea for CN wildcard comparison.
485  */
486 static int
487 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
488 {
489 	size_t i;
490 
491 	for (i = 0; i < len; ++i) {
492 		if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
493 		    hostname[i] == '.'))
494 			return (0);
495 	}
496 	return (1);
497 }
498 
499 /*
500  * Check if the host name h passed matches the pattern passed in m which
501  * is usually part of subjectAltName or CN of a certificate presented to
502  * the client. This includes wildcard matching. The algorithm is based on
503  * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
504  */
505 static int
506 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
507     size_t mlen)
508 {
509 	int delta, hdotidx, mdot1idx, wcidx;
510 	const char *hdot, *mdot1, *mdot2;
511 	const char *wc; /* wildcard */
512 
513 	if (!(h && *h && m && *m))
514 		return (0);
515 	if ((wc = strnstr(m, "*", mlen)) == NULL)
516 		return (fetch_ssl_hname_equal(h, hlen, m, mlen));
517 	wcidx = wc - m;
518 	/* hostname should not be just dots and numbers */
519 	if (fetch_ssl_hname_is_only_numbers(h, hlen))
520 		return (0);
521 	/* only one wildcard allowed in pattern */
522 	if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
523 		return (0);
524 	/*
525 	 * there must be at least two more domain labels and
526 	 * wildcard has to be in the leftmost label (RFC6125)
527 	 */
528 	mdot1 = strnstr(m, ".", mlen);
529 	if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
530 		return (0);
531 	mdot1idx = mdot1 - m;
532 	mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
533 	if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
534 		return (0);
535 	/* hostname must contain a dot and not be the 1st char */
536 	hdot = strnstr(h, ".", hlen);
537 	if (hdot == NULL || hdot == h)
538 		return (0);
539 	hdotidx = hdot - h;
540 	/*
541 	 * host part of hostname must be at least as long as
542 	 * pattern it's supposed to match
543 	 */
544 	if (hdotidx < mdot1idx)
545 		return (0);
546 	/*
547 	 * don't allow wildcards in non-traditional domain names
548 	 * (IDN, A-label, U-label...)
549 	 */
550 	if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
551 	    !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
552 		return (0);
553 	/* match domain part (part after first dot) */
554 	if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
555 	    mlen - mdot1idx))
556 		return (0);
557 	/* match part left of wildcard */
558 	if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
559 		return (0);
560 	/* match part right of wildcard */
561 	delta = mdot1idx - wcidx - 1;
562 	if (!fetch_ssl_hname_equal(hdot - delta, delta,
563 	    mdot1 - delta, delta))
564 		return (0);
565 	/* all tests succeeded, it's a match */
566 	return (1);
567 }
568 
569 /*
570  * Get numeric host address info - returns NULL if host was not an IP
571  * address. The caller is responsible for deallocation using
572  * freeaddrinfo(3).
573  */
574 static struct addrinfo *
575 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
576 {
577 	struct addrinfo hints, *res;
578 	char *host;
579 
580 	host = (char *)malloc(len + 1);
581 	memcpy(host, hostname, len);
582 	host[len] = '\0';
583 	memset(&hints, 0, sizeof(hints));
584 	hints.ai_family = PF_UNSPEC;
585 	hints.ai_socktype = SOCK_STREAM;
586 	hints.ai_protocol = 0;
587 	hints.ai_flags = AI_NUMERICHOST;
588 	/* port is not relevant for this purpose */
589 	if (getaddrinfo(host, "443", &hints, &res) != 0)
590 		res = NULL;
591 	free(host);
592 	return res;
593 }
594 
595 /*
596  * Compare ip address in addrinfo with address passes.
597  */
598 static int
599 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
600     size_t rhostlen)
601 {
602 	const void *left;
603 
604 	if (lhost->ai_family == AF_INET && rhostlen == 4) {
605 		left = (void *)&((struct sockaddr_in*)(void *)
606 		    lhost->ai_addr)->sin_addr.s_addr;
607 #ifdef INET6
608 	} else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
609 		left = (void *)&((struct sockaddr_in6 *)(void *)
610 		    lhost->ai_addr)->sin6_addr;
611 #endif
612 	} else
613 		return (0);
614 	return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
615 }
616 
617 /*
618  * Compare ip address in addrinfo with host passed. If host is not an IP
619  * address, comparison will fail.
620  */
621 static int
622 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
623     size_t rlen)
624 {
625 	struct addrinfo *raddr;
626 	int ret;
627 	char *rip;
628 
629 	ret = 0;
630 	if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
631 		return 0; /* not a numeric host */
632 
633 	if (laddr->ai_family == raddr->ai_family) {
634 		if (laddr->ai_family == AF_INET) {
635 			rip = (char *)&((struct sockaddr_in *)(void *)
636 			    raddr->ai_addr)->sin_addr.s_addr;
637 			ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
638 #ifdef INET6
639 		} else if (laddr->ai_family == AF_INET6) {
640 			rip = (char *)&((struct sockaddr_in6 *)(void *)
641 			    raddr->ai_addr)->sin6_addr;
642 			ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
643 #endif
644 		}
645 
646 	}
647 	freeaddrinfo(raddr);
648 	return (ret);
649 }
650 
651 /*
652  * Verify server certificate by subjectAltName.
653  */
654 static int
655 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
656     const char *host, struct addrinfo *ip)
657 {
658 	const GENERAL_NAME *name;
659 	size_t nslen;
660 	int i;
661 	const char *ns;
662 
663 	for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
664 #if OPENSSL_VERSION_NUMBER < 0x10000000L
665 		/*
666 		 * This is a workaround, since the following line causes
667 		 * alignment issues in clang:
668 		 * name = sk_GENERAL_NAME_value(altnames, i);
669 		 * OpenSSL explicitly warns not to use those macros
670 		 * directly, but there isn't much choice (and there
671 		 * shouldn't be any ill side effects)
672 		 */
673 		name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
674 #else
675 		name = sk_GENERAL_NAME_value(altnames, i);
676 #endif
677 #if OPENSSL_VERSION_NUMBER < 0x10100000L
678 		ns = (const char *)ASN1_STRING_data(name->d.ia5);
679 #else
680 		ns = (const char *)ASN1_STRING_get0_data(name->d.ia5);
681 #endif
682 		nslen = (size_t)ASN1_STRING_length(name->d.ia5);
683 
684 		if (name->type == GEN_DNS && ip == NULL &&
685 		    fetch_ssl_hname_match(host, strlen(host), ns, nslen))
686 			return (1);
687 		else if (name->type == GEN_IPADD && ip != NULL &&
688 		    fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
689 			return (1);
690 	}
691 	return (0);
692 }
693 
694 /*
695  * Verify server certificate by CN.
696  */
697 static int
698 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
699     struct addrinfo *ip)
700 {
701 	ASN1_STRING *namedata;
702 	X509_NAME_ENTRY *nameentry;
703 	int cnlen, lastpos, loc, ret;
704 	unsigned char *cn;
705 
706 	ret = 0;
707 	lastpos = -1;
708 	loc = -1;
709 	cn = NULL;
710 	/* get most specific CN (last entry in list) and compare */
711 	while ((lastpos = X509_NAME_get_index_by_NID(subject,
712 	    NID_commonName, lastpos)) != -1)
713 		loc = lastpos;
714 
715 	if (loc > -1) {
716 		nameentry = X509_NAME_get_entry(subject, loc);
717 		namedata = X509_NAME_ENTRY_get_data(nameentry);
718 		cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
719 		if (ip == NULL &&
720 		    fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
721 			ret = 1;
722 		else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
723 			ret = 1;
724 		OPENSSL_free(cn);
725 	}
726 	return (ret);
727 }
728 
729 /*
730  * Verify that server certificate subjectAltName/CN matches
731  * hostname. First check, if there are alternative subject names. If yes,
732  * those have to match. Only if those don't exist it falls back to
733  * checking the subject's CN.
734  */
735 static int
736 fetch_ssl_verify_hname(X509 *cert, const char *host)
737 {
738 	struct addrinfo *ip;
739 	STACK_OF(GENERAL_NAME) *altnames;
740 	X509_NAME *subject;
741 	int ret;
742 
743 	ret = 0;
744 	ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
745 	altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
746 	    NULL, NULL);
747 
748 	if (altnames != NULL) {
749 		ret = fetch_ssl_verify_altname(altnames, host, ip);
750 	} else {
751 		subject = X509_get_subject_name(cert);
752 		if (subject != NULL)
753 			ret = fetch_ssl_verify_cn(subject, host, ip);
754 	}
755 
756 	if (ip != NULL)
757 		freeaddrinfo(ip);
758 	if (altnames != NULL)
759 		GENERAL_NAMES_free(altnames);
760 	return (ret);
761 }
762 
763 /*
764  * Configure transport security layer based on environment.
765  */
766 static void
767 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
768 {
769 	long ssl_ctx_options;
770 
771 	ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET;
772 	if (getenv("SSL_ALLOW_SSL3") == NULL)
773 		ssl_ctx_options |= SSL_OP_NO_SSLv3;
774 	if (getenv("SSL_NO_TLS1") != NULL)
775 		ssl_ctx_options |= SSL_OP_NO_TLSv1;
776 	if (getenv("SSL_NO_TLS1_1") != NULL)
777 		ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
778 	if (getenv("SSL_NO_TLS1_2") != NULL)
779 		ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
780 	if (verbose)
781 		fetch_info("SSL options: %lx", ssl_ctx_options);
782 	SSL_CTX_set_options(ctx, ssl_ctx_options);
783 }
784 
785 
786 /*
787  * Configure peer verification based on environment.
788  */
789 #define LOCAL_CERT_FILE	"/usr/local/etc/ssl/cert.pem"
790 #define BASE_CERT_FILE	"/etc/ssl/cert.pem"
791 static int
792 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
793 {
794 	X509_LOOKUP *crl_lookup;
795 	X509_STORE *crl_store;
796 	const char *ca_cert_file, *ca_cert_path, *crl_file;
797 
798 	if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
799 		ca_cert_file = getenv("SSL_CA_CERT_FILE");
800 		if (ca_cert_file == NULL &&
801 		    access(LOCAL_CERT_FILE, R_OK) == 0)
802 			ca_cert_file = LOCAL_CERT_FILE;
803 		if (ca_cert_file == NULL &&
804 		    access(BASE_CERT_FILE, R_OK) == 0)
805 			ca_cert_file = BASE_CERT_FILE;
806 		ca_cert_path = getenv("SSL_CA_CERT_PATH");
807 		if (verbose) {
808 			fetch_info("Peer verification enabled");
809 			if (ca_cert_file != NULL)
810 				fetch_info("Using CA cert file: %s",
811 				    ca_cert_file);
812 			if (ca_cert_path != NULL)
813 				fetch_info("Using CA cert path: %s",
814 				    ca_cert_path);
815 			if (ca_cert_file == NULL && ca_cert_path == NULL)
816 				fetch_info("Using OpenSSL default "
817 				    "CA cert file and path");
818 		}
819 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
820 		    fetch_ssl_cb_verify_crt);
821 		if (ca_cert_file != NULL || ca_cert_path != NULL)
822 			SSL_CTX_load_verify_locations(ctx, ca_cert_file,
823 			    ca_cert_path);
824 		else
825 			SSL_CTX_set_default_verify_paths(ctx);
826 		if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
827 			if (verbose)
828 				fetch_info("Using CRL file: %s", crl_file);
829 			crl_store = SSL_CTX_get_cert_store(ctx);
830 			crl_lookup = X509_STORE_add_lookup(crl_store,
831 			    X509_LOOKUP_file());
832 			if (crl_lookup == NULL ||
833 			    !X509_load_crl_file(crl_lookup, crl_file,
834 				X509_FILETYPE_PEM)) {
835 				fprintf(stderr,
836 				    "Could not load CRL file %s\n",
837 				    crl_file);
838 				return (0);
839 			}
840 			X509_STORE_set_flags(crl_store,
841 			    X509_V_FLAG_CRL_CHECK |
842 			    X509_V_FLAG_CRL_CHECK_ALL);
843 		}
844 	}
845 	return (1);
846 }
847 
848 /*
849  * Configure client certificate based on environment.
850  */
851 static int
852 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
853 {
854 	const char *client_cert_file, *client_key_file;
855 
856 	if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
857 		client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
858 		    getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
859 		if (verbose) {
860 			fetch_info("Using client cert file: %s",
861 			    client_cert_file);
862 			fetch_info("Using client key file: %s",
863 			    client_key_file);
864 		}
865 		if (SSL_CTX_use_certificate_chain_file(ctx,
866 			client_cert_file) != 1) {
867 			fprintf(stderr,
868 			    "Could not load client certificate %s\n",
869 			    client_cert_file);
870 			return (0);
871 		}
872 		if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
873 			SSL_FILETYPE_PEM) != 1) {
874 			fprintf(stderr,
875 			    "Could not load client key %s\n",
876 			    client_key_file);
877 			return (0);
878 		}
879 	}
880 	return (1);
881 }
882 
883 /*
884  * Callback for SSL certificate verification, this is called on server
885  * cert verification. It takes no decision, but informs the user in case
886  * verification failed.
887  */
888 int
889 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
890 {
891 	X509 *crt;
892 	X509_NAME *name;
893 	char *str;
894 
895 	str = NULL;
896 	if (!verified) {
897 		if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
898 		    (name = X509_get_subject_name(crt)) != NULL)
899 			str = X509_NAME_oneline(name, 0, 0);
900 		fprintf(stderr, "Certificate verification failed for %s\n",
901 		    str != NULL ? str : "no relevant certificate");
902 		OPENSSL_free(str);
903 	}
904 	return (verified);
905 }
906 
907 #endif
908 
909 /*
910  * Enable SSL on a connection.
911  */
912 int
913 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
914 {
915 #ifdef WITH_SSL
916 	int ret, ssl_err;
917 	X509_NAME *name;
918 	char *str;
919 
920 	/* Init the SSL library and context */
921 	if (!SSL_library_init()){
922 		fprintf(stderr, "SSL library init failed\n");
923 		return (-1);
924 	}
925 
926 	SSL_load_error_strings();
927 
928 	conn->ssl_meth = SSLv23_client_method();
929 	conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
930 	SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
931 
932 	fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
933 	if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
934 		return (-1);
935 	if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
936 		return (-1);
937 
938 	conn->ssl = SSL_new(conn->ssl_ctx);
939 	if (conn->ssl == NULL) {
940 		fprintf(stderr, "SSL context creation failed\n");
941 		return (-1);
942 	}
943 	SSL_set_fd(conn->ssl, conn->sd);
944 
945 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
946 	if (!SSL_set_tlsext_host_name(conn->ssl,
947 	    __DECONST(struct url *, URL)->host)) {
948 		fprintf(stderr,
949 		    "TLS server name indication extension failed for host %s\n",
950 		    URL->host);
951 		return (-1);
952 	}
953 #endif
954 	while ((ret = SSL_connect(conn->ssl)) == -1) {
955 		ssl_err = SSL_get_error(conn->ssl, ret);
956 		if (ssl_err != SSL_ERROR_WANT_READ &&
957 		    ssl_err != SSL_ERROR_WANT_WRITE) {
958 			ERR_print_errors_fp(stderr);
959 			return (-1);
960 		}
961 	}
962 	conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
963 
964 	if (conn->ssl_cert == NULL) {
965 		fprintf(stderr, "No server SSL certificate\n");
966 		return (-1);
967 	}
968 
969 	if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
970 		if (verbose)
971 			fetch_info("Verify hostname");
972 		if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
973 			fprintf(stderr,
974 			    "SSL certificate subject doesn't match host %s\n",
975 			    URL->host);
976 			return (-1);
977 		}
978 	}
979 
980 	if (verbose) {
981 		fetch_info("%s connection established using %s",
982 		    SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
983 		name = X509_get_subject_name(conn->ssl_cert);
984 		str = X509_NAME_oneline(name, 0, 0);
985 		fetch_info("Certificate subject: %s", str);
986 		OPENSSL_free(str);
987 		name = X509_get_issuer_name(conn->ssl_cert);
988 		str = X509_NAME_oneline(name, 0, 0);
989 		fetch_info("Certificate issuer: %s", str);
990 		OPENSSL_free(str);
991 	}
992 
993 	return (0);
994 #else
995 	(void)conn;
996 	(void)verbose;
997 	(void)URL;
998 	fprintf(stderr, "SSL support disabled\n");
999 	return (-1);
1000 #endif
1001 }
1002 
1003 #define FETCH_READ_WAIT		-2
1004 #define FETCH_READ_ERROR	-1
1005 #define FETCH_READ_DONE		 0
1006 
1007 #ifdef WITH_SSL
1008 static ssize_t
1009 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1010 {
1011 	ssize_t rlen;
1012 	int ssl_err;
1013 
1014 	rlen = SSL_read(ssl, buf, len);
1015 	if (rlen < 0) {
1016 		ssl_err = SSL_get_error(ssl, rlen);
1017 		if (ssl_err == SSL_ERROR_WANT_READ ||
1018 		    ssl_err == SSL_ERROR_WANT_WRITE) {
1019 			return (FETCH_READ_WAIT);
1020 		} else {
1021 			ERR_print_errors_fp(stderr);
1022 			return (FETCH_READ_ERROR);
1023 		}
1024 	}
1025 	return (rlen);
1026 }
1027 #endif
1028 
1029 static ssize_t
1030 fetch_socket_read(int sd, char *buf, size_t len)
1031 {
1032 	ssize_t rlen;
1033 
1034 	rlen = read(sd, buf, len);
1035 	if (rlen < 0) {
1036 		if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1037 			return (FETCH_READ_WAIT);
1038 		else
1039 			return (FETCH_READ_ERROR);
1040 	}
1041 	return (rlen);
1042 }
1043 
1044 /*
1045  * Read a character from a connection w/ timeout
1046  */
1047 ssize_t
1048 fetch_read(conn_t *conn, char *buf, size_t len)
1049 {
1050 	struct timeval now, timeout, delta;
1051 	struct pollfd pfd;
1052 	ssize_t rlen;
1053 	int deltams;
1054 
1055 	if (fetchTimeout > 0) {
1056 		gettimeofday(&timeout, NULL);
1057 		timeout.tv_sec += fetchTimeout;
1058 	}
1059 
1060 	deltams = INFTIM;
1061 	memset(&pfd, 0, sizeof pfd);
1062 	pfd.fd = conn->sd;
1063 	pfd.events = POLLIN | POLLERR;
1064 
1065 	for (;;) {
1066 		/*
1067 		 * The socket is non-blocking.  Instead of the canonical
1068 		 * poll() -> read(), we do the following:
1069 		 *
1070 		 * 1) call read() or SSL_read().
1071 		 * 2) if we received some data, return it.
1072 		 * 3) if an error occurred, return -1.
1073 		 * 4) if read() or SSL_read() signaled EOF, return.
1074 		 * 5) if we did not receive any data but we're not at EOF,
1075 		 *    call poll().
1076 		 *
1077 		 * In the SSL case, this is necessary because if we
1078 		 * receive a close notification, we have to call
1079 		 * SSL_read() one additional time after we've read
1080 		 * everything we received.
1081 		 *
1082 		 * In the non-SSL case, it may improve performance (very
1083 		 * slightly) when reading small amounts of data.
1084 		 */
1085 #ifdef WITH_SSL
1086 		if (conn->ssl != NULL)
1087 			rlen = fetch_ssl_read(conn->ssl, buf, len);
1088 		else
1089 #endif
1090 			rlen = fetch_socket_read(conn->sd, buf, len);
1091 		if (rlen >= 0) {
1092 			break;
1093 		} else if (rlen == FETCH_READ_ERROR) {
1094 			fetch_syserr();
1095 			return (-1);
1096 		}
1097 		// assert(rlen == FETCH_READ_WAIT);
1098 		if (fetchTimeout > 0) {
1099 			gettimeofday(&now, NULL);
1100 			if (!timercmp(&timeout, &now, >)) {
1101 				errno = ETIMEDOUT;
1102 				fetch_syserr();
1103 				return (-1);
1104 			}
1105 			timersub(&timeout, &now, &delta);
1106 			deltams = delta.tv_sec * 1000 +
1107 			    delta.tv_usec / 1000;;
1108 		}
1109 		errno = 0;
1110 		pfd.revents = 0;
1111 		if (poll(&pfd, 1, deltams) < 0) {
1112 			if (errno == EINTR && fetchRestartCalls)
1113 				continue;
1114 			fetch_syserr();
1115 			return (-1);
1116 		}
1117 	}
1118 	return (rlen);
1119 }
1120 
1121 
1122 /*
1123  * Read a line of text from a connection w/ timeout
1124  */
1125 #define MIN_BUF_SIZE 1024
1126 
1127 int
1128 fetch_getln(conn_t *conn)
1129 {
1130 	char *tmp;
1131 	size_t tmpsize;
1132 	ssize_t len;
1133 	char c;
1134 
1135 	if (conn->buf == NULL) {
1136 		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1137 			errno = ENOMEM;
1138 			return (-1);
1139 		}
1140 		conn->bufsize = MIN_BUF_SIZE;
1141 	}
1142 
1143 	conn->buf[0] = '\0';
1144 	conn->buflen = 0;
1145 
1146 	do {
1147 		len = fetch_read(conn, &c, 1);
1148 		if (len == -1)
1149 			return (-1);
1150 		if (len == 0)
1151 			break;
1152 		conn->buf[conn->buflen++] = c;
1153 		if (conn->buflen == conn->bufsize) {
1154 			tmp = conn->buf;
1155 			tmpsize = conn->bufsize * 2 + 1;
1156 			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1157 				errno = ENOMEM;
1158 				return (-1);
1159 			}
1160 			conn->buf = tmp;
1161 			conn->bufsize = tmpsize;
1162 		}
1163 	} while (c != '\n');
1164 
1165 	conn->buf[conn->buflen] = '\0';
1166 	DEBUGF("<<< %s", conn->buf);
1167 	return (0);
1168 }
1169 
1170 
1171 /*
1172  * Write to a connection w/ timeout
1173  */
1174 ssize_t
1175 fetch_write(conn_t *conn, const char *buf, size_t len)
1176 {
1177 	struct iovec iov;
1178 
1179 	iov.iov_base = __DECONST(char *, buf);
1180 	iov.iov_len = len;
1181 	return fetch_writev(conn, &iov, 1);
1182 }
1183 
1184 /*
1185  * Write a vector to a connection w/ timeout
1186  * Note: can modify the iovec.
1187  */
1188 ssize_t
1189 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1190 {
1191 	struct timeval now, timeout, delta;
1192 	struct pollfd pfd;
1193 	ssize_t wlen, total;
1194 	int deltams;
1195 
1196 	memset(&pfd, 0, sizeof pfd);
1197 	if (fetchTimeout) {
1198 		pfd.fd = conn->sd;
1199 		pfd.events = POLLOUT | POLLERR;
1200 		gettimeofday(&timeout, NULL);
1201 		timeout.tv_sec += fetchTimeout;
1202 	}
1203 
1204 	total = 0;
1205 	while (iovcnt > 0) {
1206 		while (fetchTimeout && pfd.revents == 0) {
1207 			gettimeofday(&now, NULL);
1208 			if (!timercmp(&timeout, &now, >)) {
1209 				errno = ETIMEDOUT;
1210 				fetch_syserr();
1211 				return (-1);
1212 			}
1213 			timersub(&timeout, &now, &delta);
1214 			deltams = delta.tv_sec * 1000 +
1215 			    delta.tv_usec / 1000;
1216 			errno = 0;
1217 			pfd.revents = 0;
1218 			if (poll(&pfd, 1, deltams) < 0) {
1219 				/* POSIX compliance */
1220 				if (errno == EAGAIN)
1221 					continue;
1222 				if (errno == EINTR && fetchRestartCalls)
1223 					continue;
1224 				return (-1);
1225 			}
1226 		}
1227 		errno = 0;
1228 #ifdef WITH_SSL
1229 		if (conn->ssl != NULL)
1230 			wlen = SSL_write(conn->ssl,
1231 			    iov->iov_base, iov->iov_len);
1232 		else
1233 #endif
1234 			wlen = writev(conn->sd, iov, iovcnt);
1235 		if (wlen == 0) {
1236 			/* we consider a short write a failure */
1237 			/* XXX perhaps we shouldn't in the SSL case */
1238 			errno = EPIPE;
1239 			fetch_syserr();
1240 			return (-1);
1241 		}
1242 		if (wlen < 0) {
1243 			if (errno == EINTR && fetchRestartCalls)
1244 				continue;
1245 			return (-1);
1246 		}
1247 		total += wlen;
1248 		while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1249 			wlen -= iov->iov_len;
1250 			iov++;
1251 			iovcnt--;
1252 		}
1253 		if (iovcnt > 0) {
1254 			iov->iov_len -= wlen;
1255 			iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1256 		}
1257 	}
1258 	return (total);
1259 }
1260 
1261 
1262 /*
1263  * Write a line of text to a connection w/ timeout
1264  */
1265 int
1266 fetch_putln(conn_t *conn, const char *str, size_t len)
1267 {
1268 	struct iovec iov[2];
1269 	int ret;
1270 
1271 	DEBUGF(">>> %s\n", str);
1272 	iov[0].iov_base = __DECONST(char *, str);
1273 	iov[0].iov_len = len;
1274 	iov[1].iov_base = __DECONST(char *, ENDL);
1275 	iov[1].iov_len = sizeof(ENDL);
1276 	if (len == 0)
1277 		ret = fetch_writev(conn, &iov[1], 1);
1278 	else
1279 		ret = fetch_writev(conn, iov, 2);
1280 	if (ret == -1)
1281 		return (-1);
1282 	return (0);
1283 }
1284 
1285 
1286 /*
1287  * Close connection
1288  */
1289 int
1290 fetch_close(conn_t *conn)
1291 {
1292 	int ret;
1293 
1294 	if (--conn->ref > 0)
1295 		return (0);
1296 #ifdef WITH_SSL
1297 	if (conn->ssl) {
1298 		SSL_shutdown(conn->ssl);
1299 		SSL_set_connect_state(conn->ssl);
1300 		SSL_free(conn->ssl);
1301 		conn->ssl = NULL;
1302 	}
1303 	if (conn->ssl_ctx) {
1304 		SSL_CTX_free(conn->ssl_ctx);
1305 		conn->ssl_ctx = NULL;
1306 	}
1307 	if (conn->ssl_cert) {
1308 		X509_free(conn->ssl_cert);
1309 		conn->ssl_cert = NULL;
1310 	}
1311 #endif
1312 	ret = close(conn->sd);
1313 	free(conn->buf);
1314 	free(conn);
1315 	return (ret);
1316 }
1317 
1318 
1319 /*** Directory-related utility functions *************************************/
1320 
1321 int
1322 fetch_add_entry(struct url_ent **p, int *size, int *len,
1323     const char *name, struct url_stat *us)
1324 {
1325 	struct url_ent *tmp;
1326 
1327 	if (*p == NULL) {
1328 		*size = 0;
1329 		*len = 0;
1330 	}
1331 
1332 	if (*len >= *size - 1) {
1333 		tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1334 		if (tmp == NULL) {
1335 			errno = ENOMEM;
1336 			fetch_syserr();
1337 			return (-1);
1338 		}
1339 		*size = (*size * 2 + 1);
1340 		*p = tmp;
1341 	}
1342 
1343 	tmp = *p + *len;
1344 	snprintf(tmp->name, PATH_MAX, "%s", name);
1345 	memcpy(&tmp->stat, us, sizeof(*us));
1346 
1347 	(*len)++;
1348 	(++tmp)->name[0] = 0;
1349 
1350 	return (0);
1351 }
1352 
1353 
1354 /*** Authentication-related utility functions ********************************/
1355 
1356 static const char *
1357 fetch_read_word(FILE *f)
1358 {
1359 	static char word[1024];
1360 
1361 	if (fscanf(f, " %1023s ", word) != 1)
1362 		return (NULL);
1363 	return (word);
1364 }
1365 
1366 static int
1367 fetch_netrc_open(void)
1368 {
1369 	struct passwd *pwd;
1370 	char fn[PATH_MAX];
1371 	const char *p;
1372 	int fd, serrno;
1373 
1374 	if ((p = getenv("NETRC")) != NULL) {
1375 		DEBUGF("NETRC=%s\n", p);
1376 		if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1377 			fetch_info("$NETRC specifies a file name "
1378 			    "longer than PATH_MAX");
1379 			return (-1);
1380 		}
1381 	} else {
1382 		if ((p = getenv("HOME")) == NULL) {
1383 			if ((pwd = getpwuid(getuid())) == NULL ||
1384 			    (p = pwd->pw_dir) == NULL)
1385 				return (-1);
1386 		}
1387 		if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1388 			return (-1);
1389 	}
1390 
1391 	if ((fd = open(fn, O_RDONLY)) < 0) {
1392 		serrno = errno;
1393 		DEBUGF("%s: %s\n", fn, strerror(serrno));
1394 		errno = serrno;
1395 	}
1396 	return (fd);
1397 }
1398 
1399 /*
1400  * Get authentication data for a URL from .netrc
1401  */
1402 int
1403 fetch_netrc_auth(struct url *url)
1404 {
1405 	const char *word;
1406 	int serrno;
1407 	FILE *f;
1408 
1409 	if (url->netrcfd < 0)
1410 		url->netrcfd = fetch_netrc_open();
1411 	if (url->netrcfd < 0)
1412 		return (-1);
1413 	if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1414 		serrno = errno;
1415 		DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1416 		close(url->netrcfd);
1417 		url->netrcfd = -1;
1418 		errno = serrno;
1419 		return (-1);
1420 	}
1421 	rewind(f);
1422 	DEBUGF("searching netrc for %s\n", url->host);
1423 	while ((word = fetch_read_word(f)) != NULL) {
1424 		if (strcmp(word, "default") == 0) {
1425 			DEBUGF("using default netrc settings\n");
1426 			break;
1427 		}
1428 		if (strcmp(word, "machine") == 0 &&
1429 		    (word = fetch_read_word(f)) != NULL &&
1430 		    strcasecmp(word, url->host) == 0) {
1431 			DEBUGF("using netrc settings for %s\n", word);
1432 			break;
1433 		}
1434 	}
1435 	if (word == NULL)
1436 		goto ferr;
1437 	while ((word = fetch_read_word(f)) != NULL) {
1438 		if (strcmp(word, "login") == 0) {
1439 			if ((word = fetch_read_word(f)) == NULL)
1440 				goto ferr;
1441 			if (snprintf(url->user, sizeof(url->user),
1442 				"%s", word) > (int)sizeof(url->user)) {
1443 				fetch_info("login name in .netrc is too long");
1444 				url->user[0] = '\0';
1445 			}
1446 		} else if (strcmp(word, "password") == 0) {
1447 			if ((word = fetch_read_word(f)) == NULL)
1448 				goto ferr;
1449 			if (snprintf(url->pwd, sizeof(url->pwd),
1450 				"%s", word) > (int)sizeof(url->pwd)) {
1451 				fetch_info("password in .netrc is too long");
1452 				url->pwd[0] = '\0';
1453 			}
1454 		} else if (strcmp(word, "account") == 0) {
1455 			if ((word = fetch_read_word(f)) == NULL)
1456 				goto ferr;
1457 			/* XXX not supported! */
1458 		} else {
1459 			break;
1460 		}
1461 	}
1462 	fclose(f);
1463 	url->netrcfd = -1;
1464 	return (0);
1465 ferr:
1466 	serrno = errno;
1467 	fclose(f);
1468 	url->netrcfd = -1;
1469 	errno = serrno;
1470 	return (-1);
1471 }
1472 
1473 /*
1474  * The no_proxy environment variable specifies a set of domains for
1475  * which the proxy should not be consulted; the contents is a comma-,
1476  * or space-separated list of domain names.  A single asterisk will
1477  * override all proxy variables and no transactions will be proxied
1478  * (for compatibility with lynx and curl, see the discussion at
1479  * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1480  */
1481 int
1482 fetch_no_proxy_match(const char *host)
1483 {
1484 	const char *no_proxy, *p, *q;
1485 	size_t h_len, d_len;
1486 
1487 	if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1488 	    (no_proxy = getenv("no_proxy")) == NULL)
1489 		return (0);
1490 
1491 	/* asterisk matches any hostname */
1492 	if (strcmp(no_proxy, "*") == 0)
1493 		return (1);
1494 
1495 	h_len = strlen(host);
1496 	p = no_proxy;
1497 	do {
1498 		/* position p at the beginning of a domain suffix */
1499 		while (*p == ',' || isspace((unsigned char)*p))
1500 			p++;
1501 
1502 		/* position q at the first separator character */
1503 		for (q = p; *q; ++q)
1504 			if (*q == ',' || isspace((unsigned char)*q))
1505 				break;
1506 
1507 		d_len = q - p;
1508 		if (d_len > 0 && h_len >= d_len &&
1509 		    strncasecmp(host + h_len - d_len,
1510 			p, d_len) == 0) {
1511 			/* domain name matches */
1512 			return (1);
1513 		}
1514 
1515 		p = q + 1;
1516 	} while (*q);
1517 
1518 	return (0);
1519 }
1520