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