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: stable/12/lib/libfetch/common.c 373238 2023-10-05 16:01:02Z des $");
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 *
fetch_finderr(struct fetcherr * p,int e)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
fetch_seterr(struct fetcherr * p,int e)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
fetch_syserr(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
fetch_info(const char * fmt,...)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
fetch_default_port(const char * scheme)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
fetch_default_proxy_port(const char * scheme)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 *
fetch_reopen(int sd)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 *
fetch_ref(conn_t * conn)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 *
fetch_resolve(const char * addr,int port,int af)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
fetch_bind(int sd,int af,const char * addr)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 *
fetch_connect(const char * host,int port,int af,int verbose)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
fetch_ssl_tolower(char in)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
fetch_ssl_isalpha(char in)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
fetch_ssl_hname_equal(const char * a,size_t alen,const char * b,size_t blen)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
fetch_ssl_is_trad_domain_label(const char * l,size_t len,int wcok)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
fetch_ssl_hname_is_only_numbers(const char * hostname,size_t len)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
fetch_ssl_hname_match(const char * h,size_t hlen,const char * m,size_t mlen)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 *
fetch_ssl_get_numeric_addrinfo(const char * hostname,size_t len)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
fetch_ssl_ipaddr_match_bin(const struct addrinfo * lhost,const char * rhost,size_t rhostlen)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
fetch_ssl_ipaddr_match(const struct addrinfo * laddr,const char * r,size_t rlen)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
fetch_ssl_verify_altname(STACK_OF (GENERAL_NAME)* altnames,const char * host,struct addrinfo * ip)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
fetch_ssl_verify_cn(X509_NAME * subject,const char * host,struct addrinfo * ip)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
fetch_ssl_verify_hname(X509 * cert,const char * host)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
fetch_ssl_setup_transport_layer(SSL_CTX * ctx,int verbose)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 static int
fetch_ssl_setup_peer_verification(SSL_CTX * ctx,int verbose)790 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
791 {
792 	X509_LOOKUP *crl_lookup;
793 	X509_STORE *crl_store;
794 	const char *ca_cert_file, *ca_cert_path, *crl_file;
795 
796 	if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
797 		ca_cert_file = getenv("SSL_CA_CERT_FILE");
798 		ca_cert_path = getenv("SSL_CA_CERT_PATH");
799 		if (verbose) {
800 			fetch_info("Peer verification enabled");
801 			if (ca_cert_file != NULL)
802 				fetch_info("Using CA cert file: %s",
803 				    ca_cert_file);
804 			if (ca_cert_path != NULL)
805 				fetch_info("Using CA cert path: %s",
806 				    ca_cert_path);
807 			if (ca_cert_file == NULL && ca_cert_path == NULL)
808 				fetch_info("Using OpenSSL default "
809 				    "CA cert file and path");
810 		}
811 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
812 		    fetch_ssl_cb_verify_crt);
813 		if (ca_cert_file != NULL || ca_cert_path != NULL)
814 			SSL_CTX_load_verify_locations(ctx, ca_cert_file,
815 			    ca_cert_path);
816 		else
817 			SSL_CTX_set_default_verify_paths(ctx);
818 		if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
819 			if (verbose)
820 				fetch_info("Using CRL file: %s", crl_file);
821 			crl_store = SSL_CTX_get_cert_store(ctx);
822 			crl_lookup = X509_STORE_add_lookup(crl_store,
823 			    X509_LOOKUP_file());
824 			if (crl_lookup == NULL ||
825 			    !X509_load_crl_file(crl_lookup, crl_file,
826 				X509_FILETYPE_PEM)) {
827 				fprintf(stderr,
828 				    "Could not load CRL file %s\n",
829 				    crl_file);
830 				return (0);
831 			}
832 			X509_STORE_set_flags(crl_store,
833 			    X509_V_FLAG_CRL_CHECK |
834 			    X509_V_FLAG_CRL_CHECK_ALL);
835 		}
836 	}
837 	return (1);
838 }
839 
840 /*
841  * Configure client certificate based on environment.
842  */
843 static int
fetch_ssl_setup_client_certificate(SSL_CTX * ctx,int verbose)844 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
845 {
846 	const char *client_cert_file, *client_key_file;
847 
848 	if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
849 		client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
850 		    getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
851 		if (verbose) {
852 			fetch_info("Using client cert file: %s",
853 			    client_cert_file);
854 			fetch_info("Using client key file: %s",
855 			    client_key_file);
856 		}
857 		if (SSL_CTX_use_certificate_chain_file(ctx,
858 			client_cert_file) != 1) {
859 			fprintf(stderr,
860 			    "Could not load client certificate %s\n",
861 			    client_cert_file);
862 			return (0);
863 		}
864 		if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
865 			SSL_FILETYPE_PEM) != 1) {
866 			fprintf(stderr,
867 			    "Could not load client key %s\n",
868 			    client_key_file);
869 			return (0);
870 		}
871 	}
872 	return (1);
873 }
874 
875 /*
876  * Callback for SSL certificate verification, this is called on server
877  * cert verification. It takes no decision, but informs the user in case
878  * verification failed.
879  */
880 int
fetch_ssl_cb_verify_crt(int verified,X509_STORE_CTX * ctx)881 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
882 {
883 	X509 *crt;
884 	X509_NAME *name;
885 	char *str;
886 
887 	str = NULL;
888 	if (!verified) {
889 		if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
890 		    (name = X509_get_subject_name(crt)) != NULL)
891 			str = X509_NAME_oneline(name, 0, 0);
892 		fprintf(stderr, "Certificate verification failed for %s\n",
893 		    str != NULL ? str : "no relevant certificate");
894 		OPENSSL_free(str);
895 	}
896 	return (verified);
897 }
898 
899 #endif
900 
901 /*
902  * Enable SSL on a connection.
903  */
904 int
fetch_ssl(conn_t * conn,const struct url * URL,int verbose)905 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
906 {
907 #ifdef WITH_SSL
908 	int ret, ssl_err;
909 	X509_NAME *name;
910 	char *str;
911 
912 	/* Init the SSL library and context */
913 	if (!SSL_library_init()){
914 		fprintf(stderr, "SSL library init failed\n");
915 		return (-1);
916 	}
917 
918 	SSL_load_error_strings();
919 
920 	conn->ssl_meth = SSLv23_client_method();
921 	conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
922 	SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
923 
924 	fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
925 	if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
926 		return (-1);
927 	if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
928 		return (-1);
929 
930 	conn->ssl = SSL_new(conn->ssl_ctx);
931 	if (conn->ssl == NULL) {
932 		fprintf(stderr, "SSL context creation failed\n");
933 		return (-1);
934 	}
935 	SSL_set_fd(conn->ssl, conn->sd);
936 
937 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
938 	if (!SSL_set_tlsext_host_name(conn->ssl,
939 	    __DECONST(struct url *, URL)->host)) {
940 		fprintf(stderr,
941 		    "TLS server name indication extension failed for host %s\n",
942 		    URL->host);
943 		return (-1);
944 	}
945 #endif
946 	while ((ret = SSL_connect(conn->ssl)) == -1) {
947 		ssl_err = SSL_get_error(conn->ssl, ret);
948 		if (ssl_err != SSL_ERROR_WANT_READ &&
949 		    ssl_err != SSL_ERROR_WANT_WRITE) {
950 			ERR_print_errors_fp(stderr);
951 			return (-1);
952 		}
953 	}
954 	conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
955 
956 	if (conn->ssl_cert == NULL) {
957 		fprintf(stderr, "No server SSL certificate\n");
958 		return (-1);
959 	}
960 
961 	if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
962 		if (verbose)
963 			fetch_info("Verify hostname");
964 		if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
965 			fprintf(stderr,
966 			    "SSL certificate subject doesn't match host %s\n",
967 			    URL->host);
968 			return (-1);
969 		}
970 	}
971 
972 	if (verbose) {
973 		fetch_info("%s connection established using %s",
974 		    SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
975 		name = X509_get_subject_name(conn->ssl_cert);
976 		str = X509_NAME_oneline(name, 0, 0);
977 		fetch_info("Certificate subject: %s", str);
978 		OPENSSL_free(str);
979 		name = X509_get_issuer_name(conn->ssl_cert);
980 		str = X509_NAME_oneline(name, 0, 0);
981 		fetch_info("Certificate issuer: %s", str);
982 		OPENSSL_free(str);
983 	}
984 
985 	return (0);
986 #else
987 	(void)conn;
988 	(void)verbose;
989 	fprintf(stderr, "SSL support disabled\n");
990 	return (-1);
991 #endif
992 }
993 
994 #define FETCH_READ_WAIT		-2
995 #define FETCH_READ_ERROR	-1
996 #define FETCH_READ_DONE		 0
997 
998 #ifdef WITH_SSL
999 static ssize_t
fetch_ssl_read(SSL * ssl,char * buf,size_t len)1000 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1001 {
1002 	ssize_t rlen;
1003 	int ssl_err;
1004 
1005 	rlen = SSL_read(ssl, buf, len);
1006 	if (rlen < 0) {
1007 		ssl_err = SSL_get_error(ssl, rlen);
1008 		if (ssl_err == SSL_ERROR_WANT_READ ||
1009 		    ssl_err == SSL_ERROR_WANT_WRITE) {
1010 			return (FETCH_READ_WAIT);
1011 		} else {
1012 			ERR_print_errors_fp(stderr);
1013 			return (FETCH_READ_ERROR);
1014 		}
1015 	}
1016 	return (rlen);
1017 }
1018 #endif
1019 
1020 static ssize_t
fetch_socket_read(int sd,char * buf,size_t len)1021 fetch_socket_read(int sd, char *buf, size_t len)
1022 {
1023 	ssize_t rlen;
1024 
1025 	rlen = read(sd, buf, len);
1026 	if (rlen < 0) {
1027 		if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1028 			return (FETCH_READ_WAIT);
1029 		else
1030 			return (FETCH_READ_ERROR);
1031 	}
1032 	return (rlen);
1033 }
1034 
1035 /*
1036  * Read a character from a connection w/ timeout
1037  */
1038 ssize_t
fetch_read(conn_t * conn,char * buf,size_t len)1039 fetch_read(conn_t *conn, char *buf, size_t len)
1040 {
1041 	struct timeval now, timeout, delta;
1042 	struct pollfd pfd;
1043 	ssize_t rlen;
1044 	int deltams;
1045 
1046 	if (fetchTimeout > 0) {
1047 		gettimeofday(&timeout, NULL);
1048 		timeout.tv_sec += fetchTimeout;
1049 	}
1050 
1051 	deltams = INFTIM;
1052 	memset(&pfd, 0, sizeof pfd);
1053 	pfd.fd = conn->sd;
1054 	pfd.events = POLLIN | POLLERR;
1055 
1056 	for (;;) {
1057 		/*
1058 		 * The socket is non-blocking.  Instead of the canonical
1059 		 * poll() -> read(), we do the following:
1060 		 *
1061 		 * 1) call read() or SSL_read().
1062 		 * 2) if we received some data, return it.
1063 		 * 3) if an error occurred, return -1.
1064 		 * 4) if read() or SSL_read() signaled EOF, return.
1065 		 * 5) if we did not receive any data but we're not at EOF,
1066 		 *    call poll().
1067 		 *
1068 		 * In the SSL case, this is necessary because if we
1069 		 * receive a close notification, we have to call
1070 		 * SSL_read() one additional time after we've read
1071 		 * everything we received.
1072 		 *
1073 		 * In the non-SSL case, it may improve performance (very
1074 		 * slightly) when reading small amounts of data.
1075 		 */
1076 #ifdef WITH_SSL
1077 		if (conn->ssl != NULL)
1078 			rlen = fetch_ssl_read(conn->ssl, buf, len);
1079 		else
1080 #endif
1081 			rlen = fetch_socket_read(conn->sd, buf, len);
1082 		if (rlen >= 0) {
1083 			break;
1084 		} else if (rlen == FETCH_READ_ERROR) {
1085 			fetch_syserr();
1086 			return (-1);
1087 		}
1088 		// assert(rlen == FETCH_READ_WAIT);
1089 		if (fetchTimeout > 0) {
1090 			gettimeofday(&now, NULL);
1091 			if (!timercmp(&timeout, &now, >)) {
1092 				errno = ETIMEDOUT;
1093 				fetch_syserr();
1094 				return (-1);
1095 			}
1096 			timersub(&timeout, &now, &delta);
1097 			deltams = delta.tv_sec * 1000 +
1098 			    delta.tv_usec / 1000;;
1099 		}
1100 		errno = 0;
1101 		pfd.revents = 0;
1102 		if (poll(&pfd, 1, deltams) < 0) {
1103 			if (errno == EINTR && fetchRestartCalls)
1104 				continue;
1105 			fetch_syserr();
1106 			return (-1);
1107 		}
1108 	}
1109 	return (rlen);
1110 }
1111 
1112 
1113 /*
1114  * Read a line of text from a connection w/ timeout
1115  */
1116 #define MIN_BUF_SIZE 1024
1117 
1118 int
fetch_getln(conn_t * conn)1119 fetch_getln(conn_t *conn)
1120 {
1121 	char *tmp;
1122 	size_t tmpsize;
1123 	ssize_t len;
1124 	char c;
1125 
1126 	if (conn->buf == NULL) {
1127 		if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1128 			errno = ENOMEM;
1129 			return (-1);
1130 		}
1131 		conn->bufsize = MIN_BUF_SIZE;
1132 	}
1133 
1134 	conn->buf[0] = '\0';
1135 	conn->buflen = 0;
1136 
1137 	do {
1138 		len = fetch_read(conn, &c, 1);
1139 		if (len == -1)
1140 			return (-1);
1141 		if (len == 0)
1142 			break;
1143 		conn->buf[conn->buflen++] = c;
1144 		if (conn->buflen == conn->bufsize) {
1145 			tmp = conn->buf;
1146 			tmpsize = conn->bufsize * 2 + 1;
1147 			if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1148 				errno = ENOMEM;
1149 				return (-1);
1150 			}
1151 			conn->buf = tmp;
1152 			conn->bufsize = tmpsize;
1153 		}
1154 	} while (c != '\n');
1155 
1156 	conn->buf[conn->buflen] = '\0';
1157 	DEBUGF("<<< %s", conn->buf);
1158 	return (0);
1159 }
1160 
1161 
1162 /*
1163  * Write to a connection w/ timeout
1164  */
1165 ssize_t
fetch_write(conn_t * conn,const char * buf,size_t len)1166 fetch_write(conn_t *conn, const char *buf, size_t len)
1167 {
1168 	struct iovec iov;
1169 
1170 	iov.iov_base = __DECONST(char *, buf);
1171 	iov.iov_len = len;
1172 	return fetch_writev(conn, &iov, 1);
1173 }
1174 
1175 /*
1176  * Write a vector to a connection w/ timeout
1177  * Note: can modify the iovec.
1178  */
1179 ssize_t
fetch_writev(conn_t * conn,struct iovec * iov,int iovcnt)1180 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1181 {
1182 	struct timeval now, timeout, delta;
1183 	struct pollfd pfd;
1184 	ssize_t wlen, total;
1185 	int deltams;
1186 
1187 	memset(&pfd, 0, sizeof pfd);
1188 	if (fetchTimeout) {
1189 		pfd.fd = conn->sd;
1190 		pfd.events = POLLOUT | POLLERR;
1191 		gettimeofday(&timeout, NULL);
1192 		timeout.tv_sec += fetchTimeout;
1193 	}
1194 
1195 	total = 0;
1196 	while (iovcnt > 0) {
1197 		while (fetchTimeout && pfd.revents == 0) {
1198 			gettimeofday(&now, NULL);
1199 			if (!timercmp(&timeout, &now, >)) {
1200 				errno = ETIMEDOUT;
1201 				fetch_syserr();
1202 				return (-1);
1203 			}
1204 			timersub(&timeout, &now, &delta);
1205 			deltams = delta.tv_sec * 1000 +
1206 			    delta.tv_usec / 1000;
1207 			errno = 0;
1208 			pfd.revents = 0;
1209 			if (poll(&pfd, 1, deltams) < 0) {
1210 				/* POSIX compliance */
1211 				if (errno == EAGAIN)
1212 					continue;
1213 				if (errno == EINTR && fetchRestartCalls)
1214 					continue;
1215 				return (-1);
1216 			}
1217 		}
1218 		errno = 0;
1219 #ifdef WITH_SSL
1220 		if (conn->ssl != NULL)
1221 			wlen = SSL_write(conn->ssl,
1222 			    iov->iov_base, iov->iov_len);
1223 		else
1224 #endif
1225 			wlen = writev(conn->sd, iov, iovcnt);
1226 		if (wlen == 0) {
1227 			/* we consider a short write a failure */
1228 			/* XXX perhaps we shouldn't in the SSL case */
1229 			errno = EPIPE;
1230 			fetch_syserr();
1231 			return (-1);
1232 		}
1233 		if (wlen < 0) {
1234 			if (errno == EINTR && fetchRestartCalls)
1235 				continue;
1236 			return (-1);
1237 		}
1238 		total += wlen;
1239 		while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1240 			wlen -= iov->iov_len;
1241 			iov++;
1242 			iovcnt--;
1243 		}
1244 		if (iovcnt > 0) {
1245 			iov->iov_len -= wlen;
1246 			iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1247 		}
1248 	}
1249 	return (total);
1250 }
1251 
1252 
1253 /*
1254  * Write a line of text to a connection w/ timeout
1255  */
1256 int
fetch_putln(conn_t * conn,const char * str,size_t len)1257 fetch_putln(conn_t *conn, const char *str, size_t len)
1258 {
1259 	struct iovec iov[2];
1260 	int ret;
1261 
1262 	DEBUGF(">>> %s\n", str);
1263 	iov[0].iov_base = __DECONST(char *, str);
1264 	iov[0].iov_len = len;
1265 	iov[1].iov_base = __DECONST(char *, ENDL);
1266 	iov[1].iov_len = sizeof(ENDL);
1267 	if (len == 0)
1268 		ret = fetch_writev(conn, &iov[1], 1);
1269 	else
1270 		ret = fetch_writev(conn, iov, 2);
1271 	if (ret == -1)
1272 		return (-1);
1273 	return (0);
1274 }
1275 
1276 
1277 /*
1278  * Close connection
1279  */
1280 int
fetch_close(conn_t * conn)1281 fetch_close(conn_t *conn)
1282 {
1283 	int ret;
1284 
1285 	if (--conn->ref > 0)
1286 		return (0);
1287 #ifdef WITH_SSL
1288 	if (conn->ssl) {
1289 		SSL_shutdown(conn->ssl);
1290 		SSL_set_connect_state(conn->ssl);
1291 		SSL_free(conn->ssl);
1292 		conn->ssl = NULL;
1293 	}
1294 	if (conn->ssl_ctx) {
1295 		SSL_CTX_free(conn->ssl_ctx);
1296 		conn->ssl_ctx = NULL;
1297 	}
1298 	if (conn->ssl_cert) {
1299 		X509_free(conn->ssl_cert);
1300 		conn->ssl_cert = NULL;
1301 	}
1302 #endif
1303 	ret = close(conn->sd);
1304 	free(conn->buf);
1305 	free(conn);
1306 	return (ret);
1307 }
1308 
1309 
1310 /*** Directory-related utility functions *************************************/
1311 
1312 int
fetch_add_entry(struct url_ent ** p,int * size,int * len,const char * name,struct url_stat * us)1313 fetch_add_entry(struct url_ent **p, int *size, int *len,
1314     const char *name, struct url_stat *us)
1315 {
1316 	struct url_ent *tmp;
1317 
1318 	if (*p == NULL) {
1319 		*size = 0;
1320 		*len = 0;
1321 	}
1322 
1323 	if (*len >= *size - 1) {
1324 		tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1325 		if (tmp == NULL) {
1326 			errno = ENOMEM;
1327 			fetch_syserr();
1328 			return (-1);
1329 		}
1330 		*size = (*size * 2 + 1);
1331 		*p = tmp;
1332 	}
1333 
1334 	tmp = *p + *len;
1335 	snprintf(tmp->name, PATH_MAX, "%s", name);
1336 	memcpy(&tmp->stat, us, sizeof(*us));
1337 
1338 	(*len)++;
1339 	(++tmp)->name[0] = 0;
1340 
1341 	return (0);
1342 }
1343 
1344 
1345 /*** Authentication-related utility functions ********************************/
1346 
1347 static const char *
fetch_read_word(FILE * f)1348 fetch_read_word(FILE *f)
1349 {
1350 	static char word[1024];
1351 
1352 	if (fscanf(f, " %1023s ", word) != 1)
1353 		return (NULL);
1354 	return (word);
1355 }
1356 
1357 static int
fetch_netrc_open(void)1358 fetch_netrc_open(void)
1359 {
1360 	struct passwd *pwd;
1361 	char fn[PATH_MAX];
1362 	const char *p;
1363 	int fd, serrno;
1364 
1365 	if ((p = getenv("NETRC")) != NULL) {
1366 		DEBUGF("NETRC=%s\n", p);
1367 		if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1368 			fetch_info("$NETRC specifies a file name "
1369 			    "longer than PATH_MAX");
1370 			return (-1);
1371 		}
1372 	} else {
1373 		if ((p = getenv("HOME")) == NULL) {
1374 			if ((pwd = getpwuid(getuid())) == NULL ||
1375 			    (p = pwd->pw_dir) == NULL)
1376 				return (-1);
1377 		}
1378 		if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1379 			return (-1);
1380 	}
1381 
1382 	if ((fd = open(fn, O_RDONLY)) < 0) {
1383 		serrno = errno;
1384 		DEBUGF("%s: %s\n", fn, strerror(serrno));
1385 		errno = serrno;
1386 	}
1387 	return (fd);
1388 }
1389 
1390 /*
1391  * Get authentication data for a URL from .netrc
1392  */
1393 int
fetch_netrc_auth(struct url * url)1394 fetch_netrc_auth(struct url *url)
1395 {
1396 	const char *word;
1397 	int serrno;
1398 	FILE *f;
1399 
1400 	if (url->netrcfd < 0)
1401 		url->netrcfd = fetch_netrc_open();
1402 	if (url->netrcfd < 0)
1403 		return (-1);
1404 	if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1405 		serrno = errno;
1406 		DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1407 		close(url->netrcfd);
1408 		url->netrcfd = -1;
1409 		errno = serrno;
1410 		return (-1);
1411 	}
1412 	rewind(f);
1413 	DEBUGF("searching netrc for %s\n", url->host);
1414 	while ((word = fetch_read_word(f)) != NULL) {
1415 		if (strcmp(word, "default") == 0) {
1416 			DEBUGF("using default netrc settings\n");
1417 			break;
1418 		}
1419 		if (strcmp(word, "machine") == 0 &&
1420 		    (word = fetch_read_word(f)) != NULL &&
1421 		    strcasecmp(word, url->host) == 0) {
1422 			DEBUGF("using netrc settings for %s\n", word);
1423 			break;
1424 		}
1425 	}
1426 	if (word == NULL)
1427 		goto ferr;
1428 	while ((word = fetch_read_word(f)) != NULL) {
1429 		if (strcmp(word, "login") == 0) {
1430 			if ((word = fetch_read_word(f)) == NULL)
1431 				goto ferr;
1432 			if (snprintf(url->user, sizeof(url->user),
1433 				"%s", word) > (int)sizeof(url->user)) {
1434 				fetch_info("login name in .netrc is too long");
1435 				url->user[0] = '\0';
1436 			}
1437 		} else if (strcmp(word, "password") == 0) {
1438 			if ((word = fetch_read_word(f)) == NULL)
1439 				goto ferr;
1440 			if (snprintf(url->pwd, sizeof(url->pwd),
1441 				"%s", word) > (int)sizeof(url->pwd)) {
1442 				fetch_info("password in .netrc is too long");
1443 				url->pwd[0] = '\0';
1444 			}
1445 		} else if (strcmp(word, "account") == 0) {
1446 			if ((word = fetch_read_word(f)) == NULL)
1447 				goto ferr;
1448 			/* XXX not supported! */
1449 		} else {
1450 			break;
1451 		}
1452 	}
1453 	fclose(f);
1454 	url->netrcfd = -1;
1455 	return (0);
1456 ferr:
1457 	serrno = errno;
1458 	fclose(f);
1459 	url->netrcfd = -1;
1460 	errno = serrno;
1461 	return (-1);
1462 }
1463 
1464 /*
1465  * The no_proxy environment variable specifies a set of domains for
1466  * which the proxy should not be consulted; the contents is a comma-,
1467  * or space-separated list of domain names.  A single asterisk will
1468  * override all proxy variables and no transactions will be proxied
1469  * (for compatibility with lynx and curl, see the discussion at
1470  * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1471  */
1472 int
fetch_no_proxy_match(const char * host)1473 fetch_no_proxy_match(const char *host)
1474 {
1475 	const char *no_proxy, *p, *q;
1476 	size_t h_len, d_len;
1477 
1478 	if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1479 	    (no_proxy = getenv("no_proxy")) == NULL)
1480 		return (0);
1481 
1482 	/* asterisk matches any hostname */
1483 	if (strcmp(no_proxy, "*") == 0)
1484 		return (1);
1485 
1486 	h_len = strlen(host);
1487 	p = no_proxy;
1488 	do {
1489 		/* position p at the beginning of a domain suffix */
1490 		while (*p == ',' || isspace((unsigned char)*p))
1491 			p++;
1492 
1493 		/* position q at the first separator character */
1494 		for (q = p; *q; ++q)
1495 			if (*q == ',' || isspace((unsigned char)*q))
1496 				break;
1497 
1498 		d_len = q - p;
1499 		if (d_len > 0 && h_len >= d_len &&
1500 		    strncasecmp(host + h_len - d_len,
1501 			p, d_len) == 0) {
1502 			/* domain name matches */
1503 			return (1);
1504 		}
1505 
1506 		p = q + 1;
1507 	} while (*q);
1508 
1509 	return (0);
1510 }
1511