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