xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision f6a4cb390e7b3520ac2d68add2a87c5fa3901774)
1 /* $OpenBSD: b_sock.c,v 1.44 2014/07/08 09:06:49 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 	socklen_t len;
177 	int err;
178 
179 	len = sizeof(err);
180 	if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &len) != 0)
181 		return (1);
182 	return (err);
183 }
184 
185 struct hostent *
186 BIO_gethostbyname(const char *name)
187 {
188 	return gethostbyname(name);
189 }
190 
191 int
192 BIO_sock_init(void)
193 {
194 	return (1);
195 }
196 
197 void
198 BIO_sock_cleanup(void)
199 {
200 }
201 
202 int
203 BIO_socket_ioctl(int fd, long type, void *arg)
204 {
205 	int ret;
206 
207 	ret = ioctl(fd, type, arg);
208 	if (ret < 0)
209 		SYSerr(SYS_F_IOCTLSOCKET, errno);
210 	return (ret);
211 }
212 
213 int
214 BIO_get_accept_socket(char *host, int bind_mode)
215 {
216 	int ret = 0;
217 	union {
218 		struct sockaddr sa;
219 		struct sockaddr_in sa_in;
220 		struct sockaddr_in6 sa_in6;
221 	} server, client;
222 	int s = -1, cs, addrlen;
223 	unsigned char ip[4];
224 	unsigned short port;
225 	char *str = NULL, *e;
226 	char *h, *p;
227 	unsigned long l;
228 	int err_num;
229 
230 	if ((str = BUF_strdup(host)) == NULL)
231 		return (-1);
232 
233 	h = p = NULL;
234 	h = str;
235 	for (e = str; *e; e++) {
236 		if (*e == ':') {
237 			p = e;
238 		} else if (*e == '/') {
239 			*e = '\0';
240 			break;
241 		}
242 	}
243 	if (p)
244 		*p++='\0';	/* points at last ':', '::port' is special [see below] */
245 	else
246 		p = h, h = NULL;
247 
248 #ifdef EAI_FAMILY
249 	do {
250 		struct addrinfo *res, hint;
251 
252 		/* '::port' enforces IPv6 wildcard listener. Some OSes,
253 		 * e.g. Solaris, default to IPv6 without any hint. Also
254 		 * note that commonly IPv6 wildchard socket can service
255 		 * IPv4 connections just as well...  */
256 		memset(&hint, 0, sizeof(hint));
257 		hint.ai_flags = AI_PASSIVE;
258 		if (h) {
259 			if (strchr(h, ':')) {
260 				if (h[1] == '\0')
261 					h = NULL;
262 				hint.ai_family = AF_INET6;
263 			} else if (h[0] == '*' && h[1] == '\0') {
264 				hint.ai_family = AF_INET;
265 				h = NULL;
266 			}
267 		}
268 
269 		if (getaddrinfo(h, p, &hint, &res))
270 			break;
271 
272 		addrlen = res->ai_addrlen <= sizeof(server) ?
273 		    res->ai_addrlen : sizeof(server);
274 		memcpy(&server, res->ai_addr, addrlen);
275 
276 		freeaddrinfo(res);
277 		goto again;
278 	} while (0);
279 #endif
280 
281 	if (!BIO_get_port(p, &port))
282 		goto err;
283 
284 	memset((char *)&server, 0, sizeof(server));
285 	server.sa_in.sin_family = AF_INET;
286 	server.sa_in.sin_port = htons(port);
287 	addrlen = sizeof(server.sa_in);
288 
289 	if (h == NULL || strcmp(h, "*") == 0)
290 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
291 	else {
292 		if (!BIO_get_host_ip(h, &(ip[0])))
293 			goto err;
294 		l = (unsigned long)((unsigned long)ip[0]<<24L)|
295 		    ((unsigned long)ip[1]<<16L)|
296 		    ((unsigned long)ip[2]<< 8L)|
297 		    ((unsigned long)ip[3]);
298 		server.sa_in.sin_addr.s_addr = htonl(l);
299 	}
300 
301 again:
302 	s = socket(server.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
303 	if (s == -1) {
304 		SYSerr(SYS_F_SOCKET, errno);
305 		ERR_asprintf_error_data("port='%s'", host);
306 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
307 		goto err;
308 	}
309 
310 #ifdef SO_REUSEADDR
311 	if (bind_mode == BIO_BIND_REUSEADDR) {
312 		int i = 1;
313 
314 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
315 		bind_mode = BIO_BIND_NORMAL;
316 	}
317 #endif
318 	if (bind(s, &server.sa, addrlen) == -1) {
319 #ifdef SO_REUSEADDR
320 		err_num = errno;
321 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
322 		    (err_num == EADDRINUSE)) {
323 			client = server;
324 			if (h == NULL || strcmp(h, "*") == 0) {
325 				if (client.sa.sa_family == AF_INET6) {
326 					memset(&client.sa_in6.sin6_addr, 0, sizeof(client.sa_in6.sin6_addr));
327 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
328 				} else if (client.sa.sa_family == AF_INET) {
329 					client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
330 				} else
331 					goto err;
332 			}
333 			cs = socket(client.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
334 			if (cs != -1) {
335 				int ii;
336 				ii = connect(cs, &client.sa, addrlen);
337 				close(cs);
338 				if (ii == -1) {
339 					bind_mode = BIO_BIND_REUSEADDR;
340 					close(s);
341 					goto again;
342 				}
343 				/* else error */
344 			}
345 			/* else error */
346 		}
347 #endif
348 		SYSerr(SYS_F_BIND, err_num);
349 		ERR_asprintf_error_data("port='%s'", host);
350 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
351 		goto err;
352 	}
353 	if (listen(s, SOMAXCONN) == -1) {
354 		SYSerr(SYS_F_BIND, errno);
355 		ERR_asprintf_error_data("port='%s'", host);
356 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
357 		goto err;
358 	}
359 	ret = 1;
360 err:
361 	free(str);
362 	if ((ret == 0) && (s != -1)) {
363 		close(s);
364 		s = -1;
365 	}
366 	return (s);
367 }
368 
369 int
370 BIO_accept(int sock, char **addr)
371 {
372 	int ret = -1;
373 	unsigned long l;
374 	unsigned short port;
375 	char *p, *tmp;
376 
377 	struct {
378 		socklen_t len;
379 		union {
380 			struct sockaddr sa;
381 			struct sockaddr_in sa_in;
382 			struct sockaddr_in6 sa_in6;
383 		} from;
384 	} sa;
385 
386 	sa.len = sizeof(sa.from);
387 	memset(&sa.from, 0, sizeof(sa.from));
388 	ret = accept(sock, &sa.from.sa, &sa.len);
389 	if (ret == -1) {
390 		if (BIO_sock_should_retry(ret))
391 			return -2;
392 		SYSerr(SYS_F_ACCEPT, errno);
393 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
394 		goto end;
395 	}
396 
397 	if (addr == NULL)
398 		goto end;
399 
400 #ifdef EAI_FAMILY
401 	do {
402 		char   h[NI_MAXHOST], s[NI_MAXSERV];
403 		size_t nl;
404 
405 		if (getnameinfo(&sa.from.sa, sa.len, h, sizeof(h),
406 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
407 			break;
408 		nl = strlen(h) + strlen(s) + 2;
409 		p = *addr;
410 		if (p) {
411 			*p = '\0';
412 			if (!(tmp = realloc(p, nl))) {
413 				close(ret);
414 				ret = -1;
415 				free(p);
416 				*addr = NULL;
417 				BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
418 				goto end;
419 			}
420 			p = tmp;
421 		} else {
422 			p = malloc(nl);
423 		}
424 		if (p == NULL) {
425 			close(ret);
426 			ret = -1;
427 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
428 			goto end;
429 		}
430 		*addr = p;
431 		snprintf(*addr, nl, "%s:%s", h, s);
432 		goto end;
433 	} while (0);
434 #endif
435 	if (sa.from.sa.sa_family != AF_INET)
436 		goto end;
437 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
438 	port = ntohs(sa.from.sa_in.sin_port);
439 	if (*addr == NULL) {
440 		if ((p = malloc(24)) == NULL) {
441 			close(ret);
442 			ret = -1;
443 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
444 			goto end;
445 		}
446 		*addr = p;
447 	}
448 	snprintf(*addr, 24, "%d.%d.%d.%d:%d",
449 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
450 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
451 
452 end:
453 	return (ret);
454 }
455 
456 int
457 BIO_set_tcp_ndelay(int s, int on)
458 {
459 	return (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == 0);
460 }
461 
462 int
463 BIO_socket_nbio(int s, int mode)
464 {
465 	return (BIO_socket_ioctl(s, FIONBIO, &mode) == 0);
466 }
467