xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision be0a55f1adb524f873af8d9ab444f994ebb68e07)
1 /* $OpenBSD: b_sock.c,v 1.60 2014/12/03 21:55:51 bcook Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <sys/ioctl.h>
60 #include <sys/socket.h>
61 #include <string.h>
62 
63 #include <arpa/inet.h>
64 #include <netinet/in.h>
65 #include <netinet/tcp.h>
66 
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <limits.h>
70 #include <netdb.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <unistd.h>
74 
75 #include <openssl/bio.h>
76 #include <openssl/buffer.h>
77 #include <openssl/err.h>
78 
79 int
80 BIO_get_host_ip(const char *str, unsigned char *ip)
81 {
82 	int i;
83 	int err = 1;
84 	struct hostent *he;
85 
86 	if (inet_pton(AF_INET, str, ip) == 1)
87 		return (1);
88 
89 	/* do a gethostbyname */
90 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
91 	he = BIO_gethostbyname(str);
92 	if (he == NULL) {
93 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
94 		goto err;
95 	}
96 
97 	if (he->h_addrtype != AF_INET) {
98 		BIOerr(BIO_F_BIO_GET_HOST_IP,
99 		    BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
100 		goto err;
101 	}
102 	for (i = 0; i < 4; i++)
103 		ip[i] = he->h_addr_list[0][i];
104 	err = 0;
105 
106 err:
107 	CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
108 	if (err) {
109 		ERR_asprintf_error_data("host=%s", str);
110 		return 0;
111 	} else
112 		return 1;
113 }
114 
115 int
116 BIO_get_port(const char *str, unsigned short *port_ptr)
117 {
118 	struct addrinfo *res = NULL;
119 	struct addrinfo hints = {
120 		.ai_family = AF_UNSPEC,
121 		.ai_socktype = SOCK_STREAM,
122 		.ai_flags = AI_PASSIVE,
123 	};
124 	long port;
125 	char *ep;
126 
127 	if (str == NULL) {
128 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_SPECIFIED);
129 		return (0);
130 	}
131 
132 	errno = 0;
133 	port = strtol(str, &ep, 10);
134 	if (str[0] != '\0' && *ep == '\0') {
135 		if (errno == ERANGE && (port == LONG_MAX || port == LONG_MIN)) {
136 			BIOerr(BIO_F_BIO_GET_PORT, BIO_R_INVALID_PORT_NUMBER);
137 			return (0);
138 		}
139 		if (port < 0 || port > 65535) {
140 			BIOerr(BIO_F_BIO_GET_PORT, BIO_R_INVALID_PORT_NUMBER);
141 			return (0);
142 		}
143 		goto done;
144 	}
145 
146 	if (getaddrinfo(NULL, str, &hints, &res) == 0) {
147 		port = ntohs(((struct sockaddr_in *)(res->ai_addr))->sin_port);
148 		goto done;
149 	}
150 
151 	if (strcmp(str, "http") == 0)
152 		port = 80;
153 	else if (strcmp(str, "telnet") == 0)
154 		port = 23;
155 	else if (strcmp(str, "socks") == 0)
156 		port = 1080;
157 	else if (strcmp(str, "https") == 0)
158 		port = 443;
159 	else if (strcmp(str, "ssl") == 0)
160 		port = 443;
161 	else if (strcmp(str, "ftp") == 0)
162 		port = 21;
163 	else if (strcmp(str, "gopher") == 0)
164 		port = 70;
165 	else {
166 		SYSerr(SYS_F_GETSERVBYNAME, errno);
167 		ERR_asprintf_error_data("service='%s'", str);
168 		return (0);
169 	}
170 
171 done:
172 	if (res)
173 		freeaddrinfo(res);
174 	*port_ptr = (unsigned short)port;
175 	return (1);
176 }
177 
178 int
179 BIO_sock_error(int sock)
180 {
181 	socklen_t len;
182 	int err;
183 
184 	len = sizeof(err);
185 	if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &len) != 0)
186 		return (1);
187 	return (err);
188 }
189 
190 struct hostent *
191 BIO_gethostbyname(const char *name)
192 {
193 	return gethostbyname(name);
194 }
195 
196 int
197 BIO_sock_init(void)
198 {
199 	return (1);
200 }
201 
202 void
203 BIO_sock_cleanup(void)
204 {
205 }
206 
207 int
208 BIO_socket_ioctl(int fd, long type, void *arg)
209 {
210 	int ret;
211 
212 	ret = ioctl(fd, type, arg);
213 	if (ret < 0)
214 		SYSerr(SYS_F_IOCTLSOCKET, errno);
215 	return (ret);
216 }
217 
218 int
219 BIO_get_accept_socket(char *host, int bind_mode)
220 {
221 	int ret = 0;
222 	union {
223 		struct sockaddr sa;
224 		struct sockaddr_in sa_in;
225 		struct sockaddr_in6 sa_in6;
226 	} server, client;
227 	int s = -1, cs, addrlen;
228 	unsigned char ip[4];
229 	unsigned short port;
230 	char *str = NULL, *e;
231 	char *h, *p;
232 	unsigned long l;
233 	int err_num;
234 
235 	if (host == NULL || (str = strdup(host)) == NULL)
236 		return (-1);
237 
238 	h = p = NULL;
239 	h = str;
240 	for (e = str; *e; e++) {
241 		if (*e == ':') {
242 			p = e;
243 		} else if (*e == '/') {
244 			*e = '\0';
245 			break;
246 		}
247 	}
248 	/* points at last ':', '::port' is special [see below] */
249 	if (p)
250 		*p++ = '\0';
251 	else
252 		p = h, h = NULL;
253 
254 	do {
255 		struct addrinfo *res, hint;
256 
257 		/*
258 		 * '::port' enforces IPv6 wildcard listener. Some OSes,
259 		 * e.g. Solaris, default to IPv6 without any hint. Also
260 		 * note that commonly IPv6 wildchard socket can service
261 		 * IPv4 connections just as well...
262 		 */
263 		memset(&hint, 0, sizeof(hint));
264 		hint.ai_flags = AI_PASSIVE;
265 		if (h) {
266 			if (strchr(h, ':')) {
267 				if (h[1] == '\0')
268 					h = NULL;
269 				hint.ai_family = AF_INET6;
270 			} else if (h[0] == '*' && h[1] == '\0') {
271 				hint.ai_family = AF_INET;
272 				h = NULL;
273 			}
274 		}
275 
276 		if (getaddrinfo(h, p, &hint, &res))
277 			break;
278 
279 		addrlen = res->ai_addrlen <= sizeof(server) ?
280 		    res->ai_addrlen : sizeof(server);
281 		memcpy(&server, res->ai_addr, addrlen);
282 
283 		freeaddrinfo(res);
284 		goto again;
285 	} while (0);
286 
287 	if (!BIO_get_port(p, &port))
288 		goto err;
289 
290 	memset((char *)&server, 0, sizeof(server));
291 	server.sa_in.sin_family = AF_INET;
292 	server.sa_in.sin_port = htons(port);
293 	addrlen = sizeof(server.sa_in);
294 
295 	if (h == NULL || strcmp(h, "*") == 0)
296 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
297 	else {
298 		if (!BIO_get_host_ip(h, &(ip[0])))
299 			goto err;
300 		l = (unsigned long)((unsigned long)ip[0]<<24L)|
301 		    ((unsigned long)ip[1]<<16L)|
302 		    ((unsigned long)ip[2]<< 8L)|
303 		    ((unsigned long)ip[3]);
304 		server.sa_in.sin_addr.s_addr = htonl(l);
305 	}
306 
307 again:
308 	s = socket(server.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
309 	if (s == -1) {
310 		SYSerr(SYS_F_SOCKET, errno);
311 		ERR_asprintf_error_data("port='%s'", host);
312 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
313 		    BIO_R_UNABLE_TO_CREATE_SOCKET);
314 		goto err;
315 	}
316 
317 	if (bind_mode == BIO_BIND_REUSEADDR) {
318 		int i = 1;
319 
320 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
321 		bind_mode = BIO_BIND_NORMAL;
322 	}
323 	if (bind(s, &server.sa, addrlen) == -1) {
324 		err_num = errno;
325 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
326 		    (err_num == EADDRINUSE)) {
327 			client = server;
328 			if (h == NULL || strcmp(h, "*") == 0) {
329 				if (client.sa.sa_family == AF_INET6) {
330 					memset(&client.sa_in6.sin6_addr, 0,
331 					    sizeof(client.sa_in6.sin6_addr));
332 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
333 				} else if (client.sa.sa_family == AF_INET) {
334 					client.sa_in.sin_addr.s_addr =
335 					    htonl(0x7F000001);
336 				} else
337 					goto err;
338 			}
339 			cs = socket(client.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
340 			if (cs != -1) {
341 				int ii;
342 				ii = connect(cs, &client.sa, addrlen);
343 				close(cs);
344 				if (ii == -1) {
345 					bind_mode = BIO_BIND_REUSEADDR;
346 					close(s);
347 					goto again;
348 				}
349 				/* else error */
350 			}
351 			/* else error */
352 		}
353 		SYSerr(SYS_F_BIND, err_num);
354 		ERR_asprintf_error_data("port='%s'", host);
355 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
356 		    BIO_R_UNABLE_TO_BIND_SOCKET);
357 		goto err;
358 	}
359 	if (listen(s, SOMAXCONN) == -1) {
360 		SYSerr(SYS_F_BIND, errno);
361 		ERR_asprintf_error_data("port='%s'", host);
362 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
363 		    BIO_R_UNABLE_TO_LISTEN_SOCKET);
364 		goto err;
365 	}
366 	ret = 1;
367 err:
368 	free(str);
369 	if ((ret == 0) && (s != -1)) {
370 		close(s);
371 		s = -1;
372 	}
373 	return (s);
374 }
375 
376 int
377 BIO_accept(int sock, char **addr)
378 {
379 	int ret = -1;
380 	unsigned long l;
381 	unsigned short port;
382 	char *p, *tmp;
383 
384 	struct {
385 		socklen_t len;
386 		union {
387 			struct sockaddr sa;
388 			struct sockaddr_in sa_in;
389 			struct sockaddr_in6 sa_in6;
390 		} from;
391 	} sa;
392 
393 	sa.len = sizeof(sa.from);
394 	memset(&sa.from, 0, sizeof(sa.from));
395 	ret = accept(sock, &sa.from.sa, &sa.len);
396 	if (ret == -1) {
397 		if (BIO_sock_should_retry(ret))
398 			return -2;
399 		SYSerr(SYS_F_ACCEPT, errno);
400 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
401 		goto end;
402 	}
403 
404 	if (addr == NULL)
405 		goto end;
406 
407 	do {
408 		char   h[NI_MAXHOST], s[NI_MAXSERV];
409 		size_t nl;
410 
411 		if (getnameinfo(&sa.from.sa, sa.len, h, sizeof(h),
412 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
413 			break;
414 		nl = strlen(h) + strlen(s) + 2;
415 		p = *addr;
416 		if (p)
417 			*p = '\0';
418 		if (!(tmp = realloc(p, nl))) {
419 			close(ret);
420 			ret = -1;
421 			free(p);
422 			*addr = NULL;
423 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
424 			goto end;
425 		}
426 		p = tmp;
427 		*addr = p;
428 		snprintf(*addr, nl, "%s:%s", h, s);
429 		goto end;
430 	} while (0);
431 	if (sa.from.sa.sa_family != AF_INET)
432 		goto end;
433 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
434 	port = ntohs(sa.from.sa_in.sin_port);
435 	if (*addr == NULL) {
436 		if ((p = malloc(24)) == NULL) {
437 			close(ret);
438 			ret = -1;
439 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
440 			goto end;
441 		}
442 		*addr = p;
443 	}
444 	snprintf(*addr, 24, "%d.%d.%d.%d:%d",
445 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
446 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
447 
448 end:
449 	return (ret);
450 }
451 
452 int
453 BIO_set_tcp_ndelay(int s, int on)
454 {
455 	return (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == 0);
456 }
457 
458 int
459 BIO_socket_nbio(int s, int mode)
460 {
461 	int flags = fcntl(s, F_GETFD);
462 	if (mode && !(flags & O_NONBLOCK))
463 		return (fcntl(s, F_SETFL, flags | O_NONBLOCK) != -1);
464 	else if (!mode && (flags & O_NONBLOCK))
465 		return (fcntl(s, F_SETFL, flags & ~O_NONBLOCK) != -1);
466 	return (1);
467 }
468