xref: /freebsd/lib/libfetch/common.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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 	fprintf(stderr, "SSL support disabled\n");
998 	return (-1);
999 #endif
1000 }
1001 
1002 #define FETCH_READ_WAIT		-2
1003 #define FETCH_READ_ERROR	-1
1004 #define FETCH_READ_DONE		 0
1005 
1006 #ifdef WITH_SSL
1007 static ssize_t
1008 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1009 {
1010 	ssize_t rlen;
1011 	int ssl_err;
1012 
1013 	rlen = SSL_read(ssl, buf, len);
1014 	if (rlen < 0) {
1015 		ssl_err = SSL_get_error(ssl, rlen);
1016 		if (ssl_err == SSL_ERROR_WANT_READ ||
1017 		    ssl_err == SSL_ERROR_WANT_WRITE) {
1018 			return (FETCH_READ_WAIT);
1019 		} else {
1020 			ERR_print_errors_fp(stderr);
1021 			return (FETCH_READ_ERROR);
1022 		}
1023 	}
1024 	return (rlen);
1025 }
1026 #endif
1027 
1028 static ssize_t
1029 fetch_socket_read(int sd, char *buf, size_t len)
1030 {
1031 	ssize_t rlen;
1032 
1033 	rlen = read(sd, buf, len);
1034 	if (rlen < 0) {
1035 		if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1036 			return (FETCH_READ_WAIT);
1037 		else
1038 			return (FETCH_READ_ERROR);
1039 	}
1040 	return (rlen);
1041 }
1042 
1043 /*
1044  * Read a character from a connection w/ timeout
1045  */
1046 ssize_t
1047 fetch_read(conn_t *conn, char *buf, size_t len)
1048 {
1049 	struct timeval now, timeout, delta;
1050 	struct pollfd pfd;
1051 	ssize_t rlen;
1052 	int deltams;
1053 
1054 	if (fetchTimeout > 0) {
1055 		gettimeofday(&timeout, NULL);
1056 		timeout.tv_sec += fetchTimeout;
1057 	}
1058 
1059 	deltams = INFTIM;
1060 	memset(&pfd, 0, sizeof pfd);
1061 	pfd.fd = conn->sd;
1062 	pfd.events = POLLIN | POLLERR;
1063 
1064 	for (;;) {
1065 		/*
1066 		 * The socket is non-blocking.  Instead of the canonical
1067 		 * poll() -> read(), we do the following:
1068 		 *
1069 		 * 1) call read() or SSL_read().
1070 		 * 2) if we received some data, return it.
1071 		 * 3) if an error occurred, return -1.
1072 		 * 4) if read() or SSL_read() signaled EOF, return.
1073 		 * 5) if we did not receive any data but we're not at EOF,
1074 		 *    call poll().
1075 		 *
1076 		 * In the SSL case, this is necessary because if we
1077 		 * receive a close notification, we have to call
1078 		 * SSL_read() one additional time after we've read
1079 		 * everything we received.
1080 		 *
1081 		 * In the non-SSL case, it may improve performance (very
1082 		 * slightly) when reading small amounts of data.
1083 		 */
1084 #ifdef WITH_SSL
1085 		if (conn->ssl != NULL)
1086 			rlen = fetch_ssl_read(conn->ssl, buf, len);
1087 		else
1088 #endif
1089 			rlen = fetch_socket_read(conn->sd, buf, len);
1090 		if (rlen >= 0) {
1091 			break;
1092 		} else if (rlen == FETCH_READ_ERROR) {
1093 			fetch_syserr();
1094 			return (-1);
1095 		}
1096 		// assert(rlen == FETCH_READ_WAIT);
1097 		if (fetchTimeout > 0) {
1098 			gettimeofday(&now, NULL);
1099 			if (!timercmp(&timeout, &now, >)) {
1100 				errno = ETIMEDOUT;
1101 				fetch_syserr();
1102 				return (-1);
1103 			}
1104 			timersub(&timeout, &now, &delta);
1105 			deltams = delta.tv_sec * 1000 +
1106 			    delta.tv_usec / 1000;;
1107 		}
1108 		errno = 0;
1109 		pfd.revents = 0;
1110 		if (poll(&pfd, 1, deltams) < 0) {
1111 			if (errno == EINTR && fetchRestartCalls)
1112 				continue;
1113 			fetch_syserr();
1114 			return (-1);
1115 		}
1116 	}
1117 	return (rlen);
1118 }
1119 
1120 
1121 /*
1122  * Read a line of text from a connection w/ timeout
1123  */
1124 #define MIN_BUF_SIZE 1024
1125 
1126 int
1127 fetch_getln(conn_t *conn)
1128 {
1129 	char *tmp;
1130 	size_t tmpsize;
1131 	ssize_t len;
1132 	char c;
1133 
1134 	if (conn->buf == NULL) {
1135 		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1136 			errno = ENOMEM;
1137 			return (-1);
1138 		}
1139 		conn->bufsize = MIN_BUF_SIZE;
1140 	}
1141 
1142 	conn->buf[0] = '\0';
1143 	conn->buflen = 0;
1144 
1145 	do {
1146 		len = fetch_read(conn, &c, 1);
1147 		if (len == -1)
1148 			return (-1);
1149 		if (len == 0)
1150 			break;
1151 		conn->buf[conn->buflen++] = c;
1152 		if (conn->buflen == conn->bufsize) {
1153 			tmp = conn->buf;
1154 			tmpsize = conn->bufsize * 2 + 1;
1155 			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1156 				errno = ENOMEM;
1157 				return (-1);
1158 			}
1159 			conn->buf = tmp;
1160 			conn->bufsize = tmpsize;
1161 		}
1162 	} while (c != '\n');
1163 
1164 	conn->buf[conn->buflen] = '\0';
1165 	DEBUGF("<<< %s", conn->buf);
1166 	return (0);
1167 }
1168 
1169 
1170 /*
1171  * Write to a connection w/ timeout
1172  */
1173 ssize_t
1174 fetch_write(conn_t *conn, const char *buf, size_t len)
1175 {
1176 	struct iovec iov;
1177 
1178 	iov.iov_base = __DECONST(char *, buf);
1179 	iov.iov_len = len;
1180 	return fetch_writev(conn, &iov, 1);
1181 }
1182 
1183 /*
1184  * Write a vector to a connection w/ timeout
1185  * Note: can modify the iovec.
1186  */
1187 ssize_t
1188 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1189 {
1190 	struct timeval now, timeout, delta;
1191 	struct pollfd pfd;
1192 	ssize_t wlen, total;
1193 	int deltams;
1194 
1195 	memset(&pfd, 0, sizeof pfd);
1196 	if (fetchTimeout) {
1197 		pfd.fd = conn->sd;
1198 		pfd.events = POLLOUT | POLLERR;
1199 		gettimeofday(&timeout, NULL);
1200 		timeout.tv_sec += fetchTimeout;
1201 	}
1202 
1203 	total = 0;
1204 	while (iovcnt > 0) {
1205 		while (fetchTimeout && pfd.revents == 0) {
1206 			gettimeofday(&now, NULL);
1207 			if (!timercmp(&timeout, &now, >)) {
1208 				errno = ETIMEDOUT;
1209 				fetch_syserr();
1210 				return (-1);
1211 			}
1212 			timersub(&timeout, &now, &delta);
1213 			deltams = delta.tv_sec * 1000 +
1214 			    delta.tv_usec / 1000;
1215 			errno = 0;
1216 			pfd.revents = 0;
1217 			if (poll(&pfd, 1, deltams) < 0) {
1218 				/* POSIX compliance */
1219 				if (errno == EAGAIN)
1220 					continue;
1221 				if (errno == EINTR && fetchRestartCalls)
1222 					continue;
1223 				return (-1);
1224 			}
1225 		}
1226 		errno = 0;
1227 #ifdef WITH_SSL
1228 		if (conn->ssl != NULL)
1229 			wlen = SSL_write(conn->ssl,
1230 			    iov->iov_base, iov->iov_len);
1231 		else
1232 #endif
1233 			wlen = writev(conn->sd, iov, iovcnt);
1234 		if (wlen == 0) {
1235 			/* we consider a short write a failure */
1236 			/* XXX perhaps we shouldn't in the SSL case */
1237 			errno = EPIPE;
1238 			fetch_syserr();
1239 			return (-1);
1240 		}
1241 		if (wlen < 0) {
1242 			if (errno == EINTR && fetchRestartCalls)
1243 				continue;
1244 			return (-1);
1245 		}
1246 		total += wlen;
1247 		while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1248 			wlen -= iov->iov_len;
1249 			iov++;
1250 			iovcnt--;
1251 		}
1252 		if (iovcnt > 0) {
1253 			iov->iov_len -= wlen;
1254 			iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1255 		}
1256 	}
1257 	return (total);
1258 }
1259 
1260 
1261 /*
1262  * Write a line of text to a connection w/ timeout
1263  */
1264 int
1265 fetch_putln(conn_t *conn, const char *str, size_t len)
1266 {
1267 	struct iovec iov[2];
1268 	int ret;
1269 
1270 	DEBUGF(">>> %s\n", str);
1271 	iov[0].iov_base = __DECONST(char *, str);
1272 	iov[0].iov_len = len;
1273 	iov[1].iov_base = __DECONST(char *, ENDL);
1274 	iov[1].iov_len = sizeof(ENDL);
1275 	if (len == 0)
1276 		ret = fetch_writev(conn, &iov[1], 1);
1277 	else
1278 		ret = fetch_writev(conn, iov, 2);
1279 	if (ret == -1)
1280 		return (-1);
1281 	return (0);
1282 }
1283 
1284 
1285 /*
1286  * Close connection
1287  */
1288 int
1289 fetch_close(conn_t *conn)
1290 {
1291 	int ret;
1292 
1293 	if (--conn->ref > 0)
1294 		return (0);
1295 #ifdef WITH_SSL
1296 	if (conn->ssl) {
1297 		SSL_shutdown(conn->ssl);
1298 		SSL_set_connect_state(conn->ssl);
1299 		SSL_free(conn->ssl);
1300 		conn->ssl = NULL;
1301 	}
1302 	if (conn->ssl_ctx) {
1303 		SSL_CTX_free(conn->ssl_ctx);
1304 		conn->ssl_ctx = NULL;
1305 	}
1306 	if (conn->ssl_cert) {
1307 		X509_free(conn->ssl_cert);
1308 		conn->ssl_cert = NULL;
1309 	}
1310 #endif
1311 	ret = close(conn->sd);
1312 	free(conn->buf);
1313 	free(conn);
1314 	return (ret);
1315 }
1316 
1317 
1318 /*** Directory-related utility functions *************************************/
1319 
1320 int
1321 fetch_add_entry(struct url_ent **p, int *size, int *len,
1322     const char *name, struct url_stat *us)
1323 {
1324 	struct url_ent *tmp;
1325 
1326 	if (*p == NULL) {
1327 		*size = 0;
1328 		*len = 0;
1329 	}
1330 
1331 	if (*len >= *size - 1) {
1332 		tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1333 		if (tmp == NULL) {
1334 			errno = ENOMEM;
1335 			fetch_syserr();
1336 			return (-1);
1337 		}
1338 		*size = (*size * 2 + 1);
1339 		*p = tmp;
1340 	}
1341 
1342 	tmp = *p + *len;
1343 	snprintf(tmp->name, PATH_MAX, "%s", name);
1344 	memcpy(&tmp->stat, us, sizeof(*us));
1345 
1346 	(*len)++;
1347 	(++tmp)->name[0] = 0;
1348 
1349 	return (0);
1350 }
1351 
1352 
1353 /*** Authentication-related utility functions ********************************/
1354 
1355 static const char *
1356 fetch_read_word(FILE *f)
1357 {
1358 	static char word[1024];
1359 
1360 	if (fscanf(f, " %1023s ", word) != 1)
1361 		return (NULL);
1362 	return (word);
1363 }
1364 
1365 static int
1366 fetch_netrc_open(void)
1367 {
1368 	struct passwd *pwd;
1369 	char fn[PATH_MAX];
1370 	const char *p;
1371 	int fd, serrno;
1372 
1373 	if ((p = getenv("NETRC")) != NULL) {
1374 		DEBUGF("NETRC=%s\n", p);
1375 		if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1376 			fetch_info("$NETRC specifies a file name "
1377 			    "longer than PATH_MAX");
1378 			return (-1);
1379 		}
1380 	} else {
1381 		if ((p = getenv("HOME")) == NULL) {
1382 			if ((pwd = getpwuid(getuid())) == NULL ||
1383 			    (p = pwd->pw_dir) == NULL)
1384 				return (-1);
1385 		}
1386 		if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1387 			return (-1);
1388 	}
1389 
1390 	if ((fd = open(fn, O_RDONLY)) < 0) {
1391 		serrno = errno;
1392 		DEBUGF("%s: %s\n", fn, strerror(serrno));
1393 		errno = serrno;
1394 	}
1395 	return (fd);
1396 }
1397 
1398 /*
1399  * Get authentication data for a URL from .netrc
1400  */
1401 int
1402 fetch_netrc_auth(struct url *url)
1403 {
1404 	const char *word;
1405 	int serrno;
1406 	FILE *f;
1407 
1408 	if (url->netrcfd < 0)
1409 		url->netrcfd = fetch_netrc_open();
1410 	if (url->netrcfd < 0)
1411 		return (-1);
1412 	if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1413 		serrno = errno;
1414 		DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1415 		close(url->netrcfd);
1416 		url->netrcfd = -1;
1417 		errno = serrno;
1418 		return (-1);
1419 	}
1420 	rewind(f);
1421 	DEBUGF("searching netrc for %s\n", url->host);
1422 	while ((word = fetch_read_word(f)) != NULL) {
1423 		if (strcmp(word, "default") == 0) {
1424 			DEBUGF("using default netrc settings\n");
1425 			break;
1426 		}
1427 		if (strcmp(word, "machine") == 0 &&
1428 		    (word = fetch_read_word(f)) != NULL &&
1429 		    strcasecmp(word, url->host) == 0) {
1430 			DEBUGF("using netrc settings for %s\n", word);
1431 			break;
1432 		}
1433 	}
1434 	if (word == NULL)
1435 		goto ferr;
1436 	while ((word = fetch_read_word(f)) != NULL) {
1437 		if (strcmp(word, "login") == 0) {
1438 			if ((word = fetch_read_word(f)) == NULL)
1439 				goto ferr;
1440 			if (snprintf(url->user, sizeof(url->user),
1441 				"%s", word) > (int)sizeof(url->user)) {
1442 				fetch_info("login name in .netrc is too long");
1443 				url->user[0] = '\0';
1444 			}
1445 		} else if (strcmp(word, "password") == 0) {
1446 			if ((word = fetch_read_word(f)) == NULL)
1447 				goto ferr;
1448 			if (snprintf(url->pwd, sizeof(url->pwd),
1449 				"%s", word) > (int)sizeof(url->pwd)) {
1450 				fetch_info("password in .netrc is too long");
1451 				url->pwd[0] = '\0';
1452 			}
1453 		} else if (strcmp(word, "account") == 0) {
1454 			if ((word = fetch_read_word(f)) == NULL)
1455 				goto ferr;
1456 			/* XXX not supported! */
1457 		} else {
1458 			break;
1459 		}
1460 	}
1461 	fclose(f);
1462 	url->netrcfd = -1;
1463 	return (0);
1464 ferr:
1465 	serrno = errno;
1466 	fclose(f);
1467 	url->netrcfd = -1;
1468 	errno = serrno;
1469 	return (-1);
1470 }
1471 
1472 /*
1473  * The no_proxy environment variable specifies a set of domains for
1474  * which the proxy should not be consulted; the contents is a comma-,
1475  * or space-separated list of domain names.  A single asterisk will
1476  * override all proxy variables and no transactions will be proxied
1477  * (for compatibility with lynx and curl, see the discussion at
1478  * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1479  */
1480 int
1481 fetch_no_proxy_match(const char *host)
1482 {
1483 	const char *no_proxy, *p, *q;
1484 	size_t h_len, d_len;
1485 
1486 	if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1487 	    (no_proxy = getenv("no_proxy")) == NULL)
1488 		return (0);
1489 
1490 	/* asterisk matches any hostname */
1491 	if (strcmp(no_proxy, "*") == 0)
1492 		return (1);
1493 
1494 	h_len = strlen(host);
1495 	p = no_proxy;
1496 	do {
1497 		/* position p at the beginning of a domain suffix */
1498 		while (*p == ',' || isspace((unsigned char)*p))
1499 			p++;
1500 
1501 		/* position q at the first separator character */
1502 		for (q = p; *q; ++q)
1503 			if (*q == ',' || isspace((unsigned char)*q))
1504 				break;
1505 
1506 		d_len = q - p;
1507 		if (d_len > 0 && h_len >= d_len &&
1508 		    strncasecmp(host + h_len - d_len,
1509 			p, d_len) == 0) {
1510 			/* domain name matches */
1511 			return (1);
1512 		}
1513 
1514 		p = q + 1;
1515 	} while (*q);
1516 
1517 	return (0);
1518 }
1519