xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision a8913c44aee6c78b4770e56ab6afb429afabee6d)
1 /* $OpenBSD: b_sock.c,v 1.52 2014/07/10 13:58:22 jsing 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 <limits.h>
69 #include <netdb.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <unistd.h>
73 
74 #include <openssl/bio.h>
75 
76 #include "cryptlib.h"
77 
78 int
79 BIO_get_host_ip(const char *str, unsigned char *ip)
80 {
81 	int i;
82 	int err = 1;
83 	int locked = 0;
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 	locked = 1;
92 	he = BIO_gethostbyname(str);
93 	if (he == NULL) {
94 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
95 		goto err;
96 	}
97 
98 	/* cast to short because of win16 winsock definition */
99 	if ((short)he->h_addrtype != AF_INET) {
100 		BIOerr(BIO_F_BIO_GET_HOST_IP,
101 		    BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
102 		goto err;
103 	}
104 	for (i = 0; i < 4; i++)
105 		ip[i] = he->h_addr_list[0][i];
106 	err = 0;
107 
108 err:
109 	if (locked)
110 		CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
111 	if (err) {
112 		ERR_asprintf_error_data("host=%s", str);
113 		return 0;
114 	} else
115 		return 1;
116 }
117 
118 int
119 BIO_get_port(const char *str, unsigned short *port_ptr)
120 {
121 	struct addrinfo *res = NULL;
122 	struct addrinfo hints = {
123 		.ai_family = AF_UNSPEC,
124 		.ai_socktype = SOCK_STREAM,
125 		.ai_flags = AI_PASSIVE,
126 	};
127 	long port;
128 	char *ep;
129 
130 	if (str == NULL) {
131 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_SPECIFIED);
132 		return (0);
133 	}
134 
135 	errno = 0;
136 	port = strtol(str, &ep, 10);
137 	if (str[0] != '\0' && *ep == '\0') {
138 		if (errno == ERANGE && (port == LONG_MAX || port == LONG_MIN)) {
139 			BIOerr(BIO_F_BIO_GET_PORT, BIO_R_INVALID_PORT_NUMBER);
140 			return (0);
141 		}
142 		if (port < 0 || port > 65535) {
143 			BIOerr(BIO_F_BIO_GET_PORT, BIO_R_INVALID_PORT_NUMBER);
144 			return (0);
145 		}
146 		goto done;
147 	}
148 
149 	if (getaddrinfo(NULL, str, &hints, &res) == 0) {
150 		port = ntohs(((struct sockaddr_in *)(res->ai_addr))->sin_port);
151 		goto done;
152 	}
153 
154 	if (strcmp(str, "http") == 0)
155 		port = 80;
156 	else if (strcmp(str, "telnet") == 0)
157 		port = 23;
158 	else if (strcmp(str, "socks") == 0)
159 		port = 1080;
160 	else if (strcmp(str, "https") == 0)
161 		port = 443;
162 	else if (strcmp(str, "ssl") == 0)
163 		port = 443;
164 	else if (strcmp(str, "ftp") == 0)
165 		port = 21;
166 	else if (strcmp(str, "gopher") == 0)
167 		port = 70;
168 	else {
169 		SYSerr(SYS_F_GETSERVBYNAME, errno);
170 		ERR_asprintf_error_data("service='%s'", str);
171 		return (0);
172 	}
173 
174 done:
175 	if (res)
176 		freeaddrinfo(res);
177 	*port_ptr = (unsigned short)port;
178 	return (1);
179 }
180 
181 int
182 BIO_sock_error(int sock)
183 {
184 	socklen_t len;
185 	int err;
186 
187 	len = sizeof(err);
188 	if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &len) != 0)
189 		return (1);
190 	return (err);
191 }
192 
193 struct hostent *
194 BIO_gethostbyname(const char *name)
195 {
196 	return gethostbyname(name);
197 }
198 
199 int
200 BIO_sock_init(void)
201 {
202 	return (1);
203 }
204 
205 void
206 BIO_sock_cleanup(void)
207 {
208 }
209 
210 int
211 BIO_socket_ioctl(int fd, long type, void *arg)
212 {
213 	int ret;
214 
215 	ret = ioctl(fd, type, arg);
216 	if (ret < 0)
217 		SYSerr(SYS_F_IOCTLSOCKET, errno);
218 	return (ret);
219 }
220 
221 int
222 BIO_get_accept_socket(char *host, int bind_mode)
223 {
224 	int ret = 0;
225 	union {
226 		struct sockaddr sa;
227 		struct sockaddr_in sa_in;
228 		struct sockaddr_in6 sa_in6;
229 	} server, client;
230 	int s = -1, cs, addrlen;
231 	unsigned char ip[4];
232 	unsigned short port;
233 	char *str = NULL, *e;
234 	char *h, *p;
235 	unsigned long l;
236 	int err_num;
237 
238 	if ((str = BUF_strdup(host)) == NULL)
239 		return (-1);
240 
241 	h = p = NULL;
242 	h = str;
243 	for (e = str; *e; e++) {
244 		if (*e == ':') {
245 			p = e;
246 		} else if (*e == '/') {
247 			*e = '\0';
248 			break;
249 		}
250 	}
251 	/* points at last ':', '::port' is special [see below] */
252 	if (p)
253 		*p++ = '\0';
254 	else
255 		p = h, h = NULL;
256 
257 	do {
258 		struct addrinfo *res, hint;
259 
260 		/*
261 		 * '::port' enforces IPv6 wildcard listener. Some OSes,
262 		 * e.g. Solaris, default to IPv6 without any hint. Also
263 		 * note that commonly IPv6 wildchard socket can service
264 		 * IPv4 connections just as well...
265 		 */
266 		memset(&hint, 0, sizeof(hint));
267 		hint.ai_flags = AI_PASSIVE;
268 		if (h) {
269 			if (strchr(h, ':')) {
270 				if (h[1] == '\0')
271 					h = NULL;
272 				hint.ai_family = AF_INET6;
273 			} else if (h[0] == '*' && h[1] == '\0') {
274 				hint.ai_family = AF_INET;
275 				h = NULL;
276 			}
277 		}
278 
279 		if (getaddrinfo(h, p, &hint, &res))
280 			break;
281 
282 		addrlen = res->ai_addrlen <= sizeof(server) ?
283 		    res->ai_addrlen : sizeof(server);
284 		memcpy(&server, res->ai_addr, addrlen);
285 
286 		freeaddrinfo(res);
287 		goto again;
288 	} while (0);
289 
290 	if (!BIO_get_port(p, &port))
291 		goto err;
292 
293 	memset((char *)&server, 0, sizeof(server));
294 	server.sa_in.sin_family = AF_INET;
295 	server.sa_in.sin_port = htons(port);
296 	addrlen = sizeof(server.sa_in);
297 
298 	if (h == NULL || strcmp(h, "*") == 0)
299 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
300 	else {
301 		if (!BIO_get_host_ip(h, &(ip[0])))
302 			goto err;
303 		l = (unsigned long)((unsigned long)ip[0]<<24L)|
304 		    ((unsigned long)ip[1]<<16L)|
305 		    ((unsigned long)ip[2]<< 8L)|
306 		    ((unsigned long)ip[3]);
307 		server.sa_in.sin_addr.s_addr = htonl(l);
308 	}
309 
310 again:
311 	s = socket(server.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
312 	if (s == -1) {
313 		SYSerr(SYS_F_SOCKET, errno);
314 		ERR_asprintf_error_data("port='%s'", host);
315 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
316 		    BIO_R_UNABLE_TO_CREATE_SOCKET);
317 		goto err;
318 	}
319 
320 	if (bind_mode == BIO_BIND_REUSEADDR) {
321 		int i = 1;
322 
323 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i,
324 		    sizeof(i));
325 		bind_mode = BIO_BIND_NORMAL;
326 	}
327 	if (bind(s, &server.sa, addrlen) == -1) {
328 		err_num = errno;
329 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
330 		    (err_num == EADDRINUSE)) {
331 			client = server;
332 			if (h == NULL || strcmp(h, "*") == 0) {
333 				if (client.sa.sa_family == AF_INET6) {
334 					memset(&client.sa_in6.sin6_addr, 0,
335 					    sizeof(client.sa_in6.sin6_addr));
336 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
337 				} else if (client.sa.sa_family == AF_INET) {
338 					client.sa_in.sin_addr.s_addr =
339 					    htonl(0x7F000001);
340 				} else
341 					goto err;
342 			}
343 			cs = socket(client.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
344 			if (cs != -1) {
345 				int ii;
346 				ii = connect(cs, &client.sa, addrlen);
347 				close(cs);
348 				if (ii == -1) {
349 					bind_mode = BIO_BIND_REUSEADDR;
350 					close(s);
351 					goto again;
352 				}
353 				/* else error */
354 			}
355 			/* else error */
356 		}
357 		SYSerr(SYS_F_BIND, err_num);
358 		ERR_asprintf_error_data("port='%s'", host);
359 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
360 		    BIO_R_UNABLE_TO_BIND_SOCKET);
361 		goto err;
362 	}
363 	if (listen(s, SOMAXCONN) == -1) {
364 		SYSerr(SYS_F_BIND, errno);
365 		ERR_asprintf_error_data("port='%s'", host);
366 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
367 		    BIO_R_UNABLE_TO_LISTEN_SOCKET);
368 		goto err;
369 	}
370 	ret = 1;
371 err:
372 	free(str);
373 	if ((ret == 0) && (s != -1)) {
374 		close(s);
375 		s = -1;
376 	}
377 	return (s);
378 }
379 
380 int
381 BIO_accept(int sock, char **addr)
382 {
383 	int ret = -1;
384 	unsigned long l;
385 	unsigned short port;
386 	char *p, *tmp;
387 
388 	struct {
389 		socklen_t len;
390 		union {
391 			struct sockaddr sa;
392 			struct sockaddr_in sa_in;
393 			struct sockaddr_in6 sa_in6;
394 		} from;
395 	} sa;
396 
397 	sa.len = sizeof(sa.from);
398 	memset(&sa.from, 0, sizeof(sa.from));
399 	ret = accept(sock, &sa.from.sa, &sa.len);
400 	if (ret == -1) {
401 		if (BIO_sock_should_retry(ret))
402 			return -2;
403 		SYSerr(SYS_F_ACCEPT, errno);
404 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
405 		goto end;
406 	}
407 
408 	if (addr == NULL)
409 		goto end;
410 
411 	do {
412 		char   h[NI_MAXHOST], s[NI_MAXSERV];
413 		size_t nl;
414 
415 		if (getnameinfo(&sa.from.sa, sa.len, h, sizeof(h),
416 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
417 			break;
418 		nl = strlen(h) + strlen(s) + 2;
419 		p = *addr;
420 		if (p) {
421 			*p = '\0';
422 			if (!(tmp = realloc(p, nl))) {
423 				close(ret);
424 				ret = -1;
425 				free(p);
426 				*addr = NULL;
427 				BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
428 				goto end;
429 			}
430 			p = tmp;
431 		} else {
432 			p = malloc(nl);
433 		}
434 		if (p == NULL) {
435 			close(ret);
436 			ret = -1;
437 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
438 			goto end;
439 		}
440 		*addr = p;
441 		snprintf(*addr, nl, "%s:%s", h, s);
442 		goto end;
443 	} while (0);
444 	if (sa.from.sa.sa_family != AF_INET)
445 		goto end;
446 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
447 	port = ntohs(sa.from.sa_in.sin_port);
448 	if (*addr == NULL) {
449 		if ((p = malloc(24)) == NULL) {
450 			close(ret);
451 			ret = -1;
452 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
453 			goto end;
454 		}
455 		*addr = p;
456 	}
457 	snprintf(*addr, 24, "%d.%d.%d.%d:%d",
458 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
459 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
460 
461 end:
462 	return (ret);
463 }
464 
465 int
466 BIO_set_tcp_ndelay(int s, int on)
467 {
468 	return (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == 0);
469 }
470 
471 int
472 BIO_socket_nbio(int s, int mode)
473 {
474 	return (BIO_socket_ioctl(s, FIONBIO, &mode) == 0);
475 }
476