xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision 4463abb8fec17413bc617454f913355216b5437a)
1 /* $OpenBSD: b_sock.c,v 1.43 2014/06/24 17:42:54 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 
62 #include <arpa/inet.h>
63 #include <netinet/in.h>
64 #include <netinet/tcp.h>
65 
66 #include <errno.h>
67 #include <netdb.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <unistd.h>
71 
72 #include <openssl/bio.h>
73 
74 #include "cryptlib.h"
75 
76 int
77 BIO_get_host_ip(const char *str, unsigned char *ip)
78 {
79 	int i;
80 	int err = 1;
81 	int locked = 0;
82 	struct hostent *he;
83 
84 	if (inet_pton(AF_INET, str, ip) == 1)
85 		return (1);
86 
87 	/* do a gethostbyname */
88 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
89 	locked = 1;
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, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
99 		goto err;
100 	}
101 	for (i = 0; i < 4; i++)
102 		ip[i] = he->h_addr_list[0][i];
103 	err = 0;
104 
105 err:
106 	if (locked)
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 servent *s;
119 	long port;
120 	char *ep;
121 
122 	if (str == NULL) {
123 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_SPECIFIED);
124 		return (0);
125 	}
126 
127 	errno = 0;
128 	port = strtol(str, &ep, 10);
129 	if (str[0] != '\0' && *ep == '\0') {
130 		if (errno == ERANGE && (port == LONG_MAX || port == LONG_MIN)) {
131 			BIOerr(BIO_F_BIO_GET_PORT, BIO_R_INVALID_PORT_NUMBER);
132 			return (0);
133 		}
134 		if (port < 0 || port > 65535) {
135 			BIOerr(BIO_F_BIO_GET_PORT, BIO_R_INVALID_PORT_NUMBER);
136 			return (0);
137 		}
138 
139 		*port_ptr = (unsigned short)port;
140 		return (1);
141 	}
142 
143 	CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
144 	s = getservbyname(str, "tcp");
145 	if (s != NULL)
146 		*port_ptr = ntohs((unsigned short)s->s_port);
147 	CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
148 
149 	if (s == NULL) {
150 		if (strcmp(str, "http") == 0)
151 			*port_ptr = 80;
152 		else if (strcmp(str, "telnet") == 0)
153 			*port_ptr = 23;
154 		else if (strcmp(str, "socks") == 0)
155 			*port_ptr = 1080;
156 		else if (strcmp(str, "https") == 0)
157 			*port_ptr = 443;
158 		else if (strcmp(str, "ssl") == 0)
159 			*port_ptr = 443;
160 		else if (strcmp(str, "ftp") == 0)
161 			*port_ptr = 21;
162 		else if (strcmp(str, "gopher") == 0)
163 			*port_ptr = 70;
164 		else {
165 			SYSerr(SYS_F_GETSERVBYNAME, errno);
166 			ERR_asprintf_error_data("service='%s'", str);
167 			return (0);
168 		}
169 	}
170 	return (1);
171 }
172 
173 int
174 BIO_sock_error(int sock)
175 {
176 	int j, i;
177 	int size;
178 
179 	size = sizeof(int);
180 	/* Note: under Windows the third parameter is of type (char *)
181 	 * whereas under other systems it is (void *) if you don't have
182 	 * a cast it will choke the compiler: if you do have a cast then
183 	 * you can either go for (char *) or (void *).
184 	 */
185 	i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size);
186 	if (i < 0)
187 		return (1);
188 	else
189 		return (j);
190 }
191 
192 struct hostent *
193 BIO_gethostbyname(const char *name)
194 {
195 	return gethostbyname(name);
196 }
197 
198 int
199 BIO_sock_init(void)
200 {
201 	return (1);
202 }
203 
204 void
205 BIO_sock_cleanup(void)
206 {
207 }
208 
209 int
210 BIO_socket_ioctl(int fd, long type, void *arg)
211 {
212 	int i;
213 
214 #  define ARG arg
215 
216 	i = ioctl(fd, type, ARG);
217 	if (i < 0)
218 		SYSerr(SYS_F_IOCTLSOCKET, errno);
219 	return (i);
220 }
221 
222 int
223 BIO_get_accept_socket(char *host, int bind_mode)
224 {
225 	int ret = 0;
226 	union {
227 		struct sockaddr sa;
228 		struct sockaddr_in sa_in;
229 		struct sockaddr_in6 sa_in6;
230 	} server, client;
231 	int s = -1, cs, addrlen;
232 	unsigned char ip[4];
233 	unsigned short port;
234 	char *str = NULL, *e;
235 	char *h, *p;
236 	unsigned long l;
237 	int err_num;
238 
239 	if ((str = BUF_strdup(host)) == NULL)
240 		return (-1);
241 
242 	h = p = NULL;
243 	h = str;
244 	for (e = str; *e; e++) {
245 		if (*e == ':') {
246 			p = e;
247 		} else if (*e == '/') {
248 			*e = '\0';
249 			break;
250 		}
251 	}
252 	if (p)
253 		*p++='\0';	/* points at last ':', '::port' is special [see below] */
254 	else
255 		p = h, h = NULL;
256 
257 #ifdef EAI_FAMILY
258 	do {
259 		struct addrinfo *res, hint;
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 		memset(&hint, 0, sizeof(hint));
266 		hint.ai_flags = AI_PASSIVE;
267 		if (h) {
268 			if (strchr(h, ':')) {
269 				if (h[1] == '\0')
270 					h = NULL;
271 				hint.ai_family = AF_INET6;
272 			} else if (h[0] == '*' && h[1] == '\0') {
273 				hint.ai_family = AF_INET;
274 				h = NULL;
275 			}
276 		}
277 
278 		if (getaddrinfo(h, p, &hint, &res))
279 			break;
280 
281 		addrlen = res->ai_addrlen <= sizeof(server) ?
282 		    res->ai_addrlen : sizeof(server);
283 		memcpy(&server, res->ai_addr, addrlen);
284 
285 		freeaddrinfo(res);
286 		goto again;
287 	} while (0);
288 #endif
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, BIO_R_UNABLE_TO_CREATE_SOCKET);
316 		goto err;
317 	}
318 
319 #ifdef SO_REUSEADDR
320 	if (bind_mode == BIO_BIND_REUSEADDR) {
321 		int i = 1;
322 
323 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
324 		bind_mode = BIO_BIND_NORMAL;
325 	}
326 #endif
327 	if (bind(s, &server.sa, addrlen) == -1) {
328 #ifdef SO_REUSEADDR
329 		err_num = errno;
330 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
331 		    (err_num == EADDRINUSE)) {
332 			client = server;
333 			if (h == NULL || strcmp(h, "*") == 0) {
334 				if (client.sa.sa_family == AF_INET6) {
335 					memset(&client.sa_in6.sin6_addr, 0, 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 = htonl(0x7F000001);
339 				} else
340 					goto err;
341 			}
342 			cs = socket(client.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
343 			if (cs != -1) {
344 				int ii;
345 				ii = connect(cs, &client.sa, addrlen);
346 				close(cs);
347 				if (ii == -1) {
348 					bind_mode = BIO_BIND_REUSEADDR;
349 					close(s);
350 					goto again;
351 				}
352 				/* else error */
353 			}
354 			/* else error */
355 		}
356 #endif
357 		SYSerr(SYS_F_BIND, err_num);
358 		ERR_asprintf_error_data("port='%s'", host);
359 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
360 		goto err;
361 	}
362 	if (listen(s, SOMAXCONN) == -1) {
363 		SYSerr(SYS_F_BIND, errno);
364 		ERR_asprintf_error_data("port='%s'", host);
365 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
366 		goto err;
367 	}
368 	ret = 1;
369 err:
370 	free(str);
371 	if ((ret == 0) && (s != -1)) {
372 		close(s);
373 		s = -1;
374 	}
375 	return (s);
376 }
377 
378 int
379 BIO_accept(int sock, char **addr)
380 {
381 	int ret = -1;
382 	unsigned long l;
383 	unsigned short port;
384 	char *p, *tmp;
385 
386 	struct {
387 		socklen_t len;
388 		union {
389 			struct sockaddr sa;
390 			struct sockaddr_in sa_in;
391 			struct sockaddr_in6 sa_in6;
392 		} from;
393 	} sa;
394 
395 	sa.len = sizeof(sa.from);
396 	memset(&sa.from, 0, sizeof(sa.from));
397 	ret = accept(sock, &sa.from.sa, &sa.len);
398 	if (ret == -1) {
399 		if (BIO_sock_should_retry(ret))
400 			return -2;
401 		SYSerr(SYS_F_ACCEPT, errno);
402 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
403 		goto end;
404 	}
405 
406 	if (addr == NULL)
407 		goto end;
408 
409 #ifdef EAI_FAMILY
410 	do {
411 		char   h[NI_MAXHOST], s[NI_MAXSERV];
412 		size_t nl;
413 
414 		if (getnameinfo(&sa.from.sa, sa.len, h, sizeof(h),
415 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
416 			break;
417 		nl = strlen(h) + strlen(s) + 2;
418 		p = *addr;
419 		if (p) {
420 			*p = '\0';
421 			if (!(tmp = realloc(p, nl))) {
422 				close(ret);
423 				ret = -1;
424 				free(p);
425 				*addr = NULL;
426 				BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
427 				goto end;
428 			}
429 			p = tmp;
430 		} else {
431 			p = malloc(nl);
432 		}
433 		if (p == NULL) {
434 			close(ret);
435 			ret = -1;
436 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
437 			goto end;
438 		}
439 		*addr = p;
440 		snprintf(*addr, nl, "%s:%s", h, s);
441 		goto end;
442 	} while (0);
443 #endif
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 	int ret = -1;
475 	int l;
476 
477 	l = mode;
478 	ret = BIO_socket_ioctl(s, FIONBIO, &l);
479 
480 	return (ret == 0);
481 }
482