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