xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /* $OpenBSD: b_sock.c,v 1.56 2014/07/16 10:43:06 deraadt 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 #include <openssl/buffer.h>
76 #include <openssl/err.h>
77 
78 int
79 BIO_get_host_ip(const char *str, unsigned char *ip)
80 {
81 	int i;
82 	int err = 1;
83 	struct hostent *he;
84 
85 	if (inet_pton(AF_INET, str, ip) == 1)
86 		return (1);
87 
88 	/* do a gethostbyname */
89 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
90 	he = BIO_gethostbyname(str);
91 	if (he == NULL) {
92 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
93 		goto err;
94 	}
95 
96 	/* cast to short because of win16 winsock definition */
97 	if ((short)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, (char *)&i,
321 		    sizeof(i));
322 		bind_mode = BIO_BIND_NORMAL;
323 	}
324 	if (bind(s, &server.sa, addrlen) == -1) {
325 		err_num = errno;
326 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
327 		    (err_num == EADDRINUSE)) {
328 			client = server;
329 			if (h == NULL || strcmp(h, "*") == 0) {
330 				if (client.sa.sa_family == AF_INET6) {
331 					memset(&client.sa_in6.sin6_addr, 0,
332 					    sizeof(client.sa_in6.sin6_addr));
333 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
334 				} else if (client.sa.sa_family == AF_INET) {
335 					client.sa_in.sin_addr.s_addr =
336 					    htonl(0x7F000001);
337 				} else
338 					goto err;
339 			}
340 			cs = socket(client.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
341 			if (cs != -1) {
342 				int ii;
343 				ii = connect(cs, &client.sa, addrlen);
344 				close(cs);
345 				if (ii == -1) {
346 					bind_mode = BIO_BIND_REUSEADDR;
347 					close(s);
348 					goto again;
349 				}
350 				/* else error */
351 			}
352 			/* else error */
353 		}
354 		SYSerr(SYS_F_BIND, err_num);
355 		ERR_asprintf_error_data("port='%s'", host);
356 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
357 		    BIO_R_UNABLE_TO_BIND_SOCKET);
358 		goto err;
359 	}
360 	if (listen(s, SOMAXCONN) == -1) {
361 		SYSerr(SYS_F_BIND, errno);
362 		ERR_asprintf_error_data("port='%s'", host);
363 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,
364 		    BIO_R_UNABLE_TO_LISTEN_SOCKET);
365 		goto err;
366 	}
367 	ret = 1;
368 err:
369 	free(str);
370 	if ((ret == 0) && (s != -1)) {
371 		close(s);
372 		s = -1;
373 	}
374 	return (s);
375 }
376 
377 int
378 BIO_accept(int sock, char **addr)
379 {
380 	int ret = -1;
381 	unsigned long l;
382 	unsigned short port;
383 	char *p, *tmp;
384 
385 	struct {
386 		socklen_t len;
387 		union {
388 			struct sockaddr sa;
389 			struct sockaddr_in sa_in;
390 			struct sockaddr_in6 sa_in6;
391 		} from;
392 	} sa;
393 
394 	sa.len = sizeof(sa.from);
395 	memset(&sa.from, 0, sizeof(sa.from));
396 	ret = accept(sock, &sa.from.sa, &sa.len);
397 	if (ret == -1) {
398 		if (BIO_sock_should_retry(ret))
399 			return -2;
400 		SYSerr(SYS_F_ACCEPT, errno);
401 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
402 		goto end;
403 	}
404 
405 	if (addr == NULL)
406 		goto end;
407 
408 	do {
409 		char   h[NI_MAXHOST], s[NI_MAXSERV];
410 		size_t nl;
411 
412 		if (getnameinfo(&sa.from.sa, sa.len, h, sizeof(h),
413 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
414 			break;
415 		nl = strlen(h) + strlen(s) + 2;
416 		p = *addr;
417 		if (p)
418 			*p = '\0';
419 		if (!(tmp = realloc(p, nl))) {
420 			close(ret);
421 			ret = -1;
422 			free(p);
423 			*addr = NULL;
424 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
425 			goto end;
426 		}
427 		p = tmp;
428 		*addr = p;
429 		snprintf(*addr, nl, "%s:%s", h, s);
430 		goto end;
431 	} while (0);
432 	if (sa.from.sa.sa_family != AF_INET)
433 		goto end;
434 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
435 	port = ntohs(sa.from.sa_in.sin_port);
436 	if (*addr == NULL) {
437 		if ((p = malloc(24)) == NULL) {
438 			close(ret);
439 			ret = -1;
440 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
441 			goto end;
442 		}
443 		*addr = p;
444 	}
445 	snprintf(*addr, 24, "%d.%d.%d.%d:%d",
446 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
447 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
448 
449 end:
450 	return (ret);
451 }
452 
453 int
454 BIO_set_tcp_ndelay(int s, int on)
455 {
456 	return (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == 0);
457 }
458 
459 int
460 BIO_socket_nbio(int s, int mode)
461 {
462 	return (BIO_socket_ioctl(s, FIONBIO, &mode) == 0);
463 }
464