xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision 218a6791728e28e81fa012b17fa74308f8d3fc5e)
1 /* crypto/bio/b_sock.c */
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 <netinet/in.h>
63 
64 #include <errno.h>
65 #include <netdb.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <unistd.h>
69 
70 #include <openssl/bio.h>
71 
72 #include "cryptlib.h"
73 
74 #define SOCKET_PROTOCOL IPPROTO_TCP
75 
76 #ifdef SO_MAXCONN
77 #define MAX_LISTEN  SO_MAXCONN
78 #elif defined(SOMAXCONN)
79 #define MAX_LISTEN  SOMAXCONN
80 #else
81 #define MAX_LISTEN  32
82 #endif
83 
84 static int get_ip(const char *str, unsigned char *ip);
85 
86 int
87 BIO_get_host_ip(const char *str, unsigned char *ip)
88 {
89 	int i;
90 	int err = 1;
91 	int locked = 0;
92 	struct hostent *he;
93 
94 	i = get_ip(str, ip);
95 	if (i < 0) {
96 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS);
97 		goto err;
98 	}
99 
100 	/* At this point, we have something that is most probably correct
101 	   in some way, so let's init the socket. */
102 	if (BIO_sock_init() != 1)
103 		return 0; /* don't generate another error code here */
104 
105 	/* If the string actually contained an IP address, we need not do
106 	   anything more */
107 	if (i > 0)
108 		return (1);
109 
110 	/* do a gethostbyname */
111 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
112 	locked = 1;
113 	he = BIO_gethostbyname(str);
114 	if (he == NULL) {
115 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
116 		goto err;
117 	}
118 
119 	/* cast to short because of win16 winsock definition */
120 	if ((short)he->h_addrtype != AF_INET) {
121 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
122 		goto err;
123 	}
124 	for (i = 0; i < 4; i++)
125 		ip[i] = he->h_addr_list[0][i];
126 	err = 0;
127 
128 err:
129 	if (locked)
130 		CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
131 	if (err) {
132 		ERR_asprintf_error_data("host=%s", str);
133 		return 0;
134 	} else
135 		return 1;
136 }
137 
138 int
139 BIO_get_port(const char *str, unsigned short *port_ptr)
140 {
141 	int i;
142 	struct servent *s;
143 
144 	if (str == NULL) {
145 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
146 		return (0);
147 	}
148 	i = atoi(str);
149 	if (i != 0)
150 		*port_ptr = (unsigned short)i;
151 	else {
152 		CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
153 		s = getservbyname(str, "tcp");
154 		if (s != NULL)
155 			*port_ptr = ntohs((unsigned short)s->s_port);
156 		CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
157 		if (s == NULL) {
158 			if (strcmp(str, "http") == 0)
159 				*port_ptr = 80;
160 			else if (strcmp(str, "telnet") == 0)
161 				*port_ptr = 23;
162 			else if (strcmp(str, "socks") == 0)
163 				*port_ptr = 1080;
164 			else if (strcmp(str, "https") == 0)
165 				*port_ptr = 443;
166 			else if (strcmp(str, "ssl") == 0)
167 				*port_ptr = 443;
168 			else if (strcmp(str, "ftp") == 0)
169 				*port_ptr = 21;
170 			else if (strcmp(str, "gopher") == 0)
171 				*port_ptr = 70;
172 			else {
173 				SYSerr(SYS_F_GETSERVBYNAME, errno);
174 				ERR_asprintf_error_data("service='%s'", str);
175 				return (0);
176 			}
177 		}
178 	}
179 	return (1);
180 }
181 
182 int
183 BIO_sock_error(int sock)
184 {
185 	int j, i;
186 	int size;
187 
188 	size = sizeof(int);
189 	/* Note: under Windows the third parameter is of type (char *)
190 	 * whereas under other systems it is (void *) if you don't have
191 	 * a cast it will choke the compiler: if you do have a cast then
192 	 * you can either go for (char *) or (void *).
193 	 */
194 	i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size);
195 	if (i < 0)
196 		return (1);
197 	else
198 		return (j);
199 }
200 
201 struct hostent *
202 BIO_gethostbyname(const char *name)
203 {
204 	return gethostbyname(name);
205 }
206 
207 
208 int
209 BIO_sock_init(void)
210 {
211 	return (1);
212 }
213 
214 void
215 BIO_sock_cleanup(void)
216 {
217 }
218 
219 int
220 BIO_socket_ioctl(int fd, long type, void *arg)
221 {
222 	int i;
223 
224 #  define ARG arg
225 
226 	i = ioctl(fd, type, ARG);
227 	if (i < 0)
228 		SYSerr(SYS_F_IOCTLSOCKET, errno);
229 	return (i);
230 }
231 
232 /* The reason I have implemented this instead of using sscanf is because
233  * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
234 static int
235 get_ip(const char *str, unsigned char ip[4])
236 {
237 	unsigned int tmp[4];
238 	int num = 0, c, ok = 0;
239 
240 	tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
241 
242 	for (;;) {
243 		c= *(str++);
244 		if ((c >= '0') && (c <= '9')) {
245 			ok = 1;
246 			tmp[num] = tmp[num]*10 + c-'0';
247 			if (tmp[num] > 255)
248 				return (0);
249 		} else if (c == '.') {
250 			if (!ok)
251 				return (-1);
252 			if (num == 3)
253 				return (0);
254 			num++;
255 			ok = 0;
256 		} else if (c == '\0' && (num == 3) && ok)
257 			break;
258 		else
259 			return (0);
260 	}
261 	ip[0] = tmp[0];
262 	ip[1] = tmp[1];
263 	ip[2] = tmp[2];
264 	ip[3] = tmp[3];
265 	return (1);
266 }
267 
268 int
269 BIO_get_accept_socket(char *host, int bind_mode)
270 {
271 	int ret = 0;
272 	union {
273 		struct sockaddr sa;
274 		struct sockaddr_in sa_in;
275 		struct sockaddr_in6 sa_in6;
276 	} server, client;
277 	int s = -1, cs, addrlen;
278 	unsigned char ip[4];
279 	unsigned short port;
280 	char *str = NULL, *e;
281 	char *h, *p;
282 	unsigned long l;
283 	int err_num;
284 
285 	if (BIO_sock_init() != 1)
286 		return (-1);
287 
288 	if ((str = BUF_strdup(host)) == NULL)
289 		return (-1);
290 
291 	h = p = NULL;
292 	h = str;
293 	for (e = str; *e; e++) {
294 		if (*e == ':') {
295 			p = e;
296 		} else if (*e == '/') {
297 			*e = '\0';
298 			break;
299 		}
300 	}
301 	if (p)
302 		*p++='\0';	/* points at last ':', '::port' is special [see below] */
303 	else
304 		p = h, h = NULL;
305 
306 #ifdef EAI_FAMILY
307 	do {
308 		struct addrinfo *res, hint;
309 
310 		/* '::port' enforces IPv6 wildcard listener. Some OSes,
311 		 * e.g. Solaris, default to IPv6 without any hint. Also
312 		 * note that commonly IPv6 wildchard socket can service
313 		 * IPv4 connections just as well...  */
314 		memset(&hint, 0, sizeof(hint));
315 		hint.ai_flags = AI_PASSIVE;
316 		if (h) {
317 			if (strchr(h, ':')) {
318 				if (h[1] == '\0')
319 					h = NULL;
320 				hint.ai_family = AF_INET6;
321 			} else if (h[0] == '*' && h[1] == '\0') {
322 				hint.ai_family = AF_INET;
323 				h = NULL;
324 			}
325 		}
326 
327 		if (getaddrinfo(h, p, &hint, &res))
328 			break;
329 
330 		addrlen = res->ai_addrlen <= sizeof(server) ?
331 		    res->ai_addrlen : sizeof(server);
332 		memcpy(&server, res->ai_addr, addrlen);
333 
334 		freeaddrinfo(res);
335 		goto again;
336 	} while (0);
337 #endif
338 
339 	if (!BIO_get_port(p, &port))
340 		goto err;
341 
342 	memset((char *)&server, 0, sizeof(server));
343 	server.sa_in.sin_family = AF_INET;
344 	server.sa_in.sin_port = htons(port);
345 	addrlen = sizeof(server.sa_in);
346 
347 	if (h == NULL || strcmp(h, "*") == 0)
348 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
349 	else {
350 		if (!BIO_get_host_ip(h, &(ip[0])))
351 			goto err;
352 		l = (unsigned long)((unsigned long)ip[0]<<24L)|
353 		    ((unsigned long)ip[1]<<16L)|
354 		    ((unsigned long)ip[2]<< 8L)|
355 		    ((unsigned long)ip[3]);
356 		server.sa_in.sin_addr.s_addr = htonl(l);
357 	}
358 
359 again:
360 	s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
361 	if (s == -1) {
362 		SYSerr(SYS_F_SOCKET, errno);
363 		ERR_asprintf_error_data("port='%s'", host);
364 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
365 		goto err;
366 	}
367 
368 #ifdef SO_REUSEADDR
369 	if (bind_mode == BIO_BIND_REUSEADDR) {
370 		int i = 1;
371 
372 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
373 		bind_mode = BIO_BIND_NORMAL;
374 	}
375 #endif
376 	if (bind(s, &server.sa, addrlen) == -1) {
377 #ifdef SO_REUSEADDR
378 		err_num = errno;
379 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
380 		    (err_num == EADDRINUSE)) {
381 			client = server;
382 			if (h == NULL || strcmp(h, "*") == 0) {
383 				if (client.sa.sa_family == AF_INET6) {
384 					memset(&client.sa_in6.sin6_addr, 0, sizeof(client.sa_in6.sin6_addr));
385 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
386 				} else if (client.sa.sa_family == AF_INET) {
387 					client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
388 				} else
389 					goto err;
390 			}
391 			cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
392 			if (cs != -1) {
393 				int ii;
394 				ii = connect(cs, &client.sa, addrlen);
395 				close(cs);
396 				if (ii == -1) {
397 					bind_mode = BIO_BIND_REUSEADDR;
398 					close(s);
399 					goto again;
400 				}
401 				/* else error */
402 			}
403 			/* else error */
404 		}
405 #endif
406 		SYSerr(SYS_F_BIND, err_num);
407 		ERR_asprintf_error_data("port='%s'", host);
408 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
409 		goto err;
410 	}
411 	if (listen(s, MAX_LISTEN) == -1) {
412 		SYSerr(SYS_F_BIND, errno);
413 		ERR_asprintf_error_data("port='%s'", host);
414 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
415 		goto err;
416 	}
417 	ret = 1;
418 err:
419 	free(str);
420 	if ((ret == 0) && (s != -1)) {
421 		close(s);
422 		s = -1;
423 	}
424 	return (s);
425 }
426 
427 int
428 BIO_accept(int sock, char **addr)
429 {
430 	int ret = -1;
431 	unsigned long l;
432 	unsigned short port;
433 	char *p, *tmp;
434 
435 	struct {
436 		socklen_t len;
437 		union {
438 			struct sockaddr sa;
439 			struct sockaddr_in sa_in;
440 			struct sockaddr_in6 sa_in6;
441 		} from;
442 	} sa;
443 
444 	sa.len = sizeof(sa.from);
445 	memset(&sa.from, 0, sizeof(sa.from));
446 	ret = accept(sock, &sa.from.sa, &sa.len);
447 	if (ret == -1) {
448 		if (BIO_sock_should_retry(ret))
449 			return -2;
450 		SYSerr(SYS_F_ACCEPT, errno);
451 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
452 		goto end;
453 	}
454 
455 	if (addr == NULL)
456 		goto end;
457 
458 #ifdef EAI_FAMILY
459 	do {
460 		char   h[NI_MAXHOST], s[NI_MAXSERV];
461 		size_t nl;
462 
463 		if (getnameinfo(&sa.from.sa, sa.len, h, sizeof(h),
464 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
465 			break;
466 		nl = strlen(h) + strlen(s) + 2;
467 		p = *addr;
468 		if (p) {
469 			*p = '\0';
470 			if (!(tmp = realloc(p, nl))) {
471 				close(ret);
472 				ret = -1;
473 				free(p);
474 				*addr = NULL;
475 				BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
476 				goto end;
477 			}
478 			p = tmp;
479 		} else {
480 			p = malloc(nl);
481 		}
482 		if (p == NULL) {
483 			close(ret);
484 			ret = -1;
485 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
486 			goto end;
487 		}
488 		*addr = p;
489 		snprintf(*addr, nl, "%s:%s", h, s);
490 		goto end;
491 	} while (0);
492 #endif
493 	if (sa.from.sa.sa_family != AF_INET)
494 		goto end;
495 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
496 	port = ntohs(sa.from.sa_in.sin_port);
497 	if (*addr == NULL) {
498 		if ((p = malloc(24)) == NULL) {
499 			close(ret);
500 			ret = -1;
501 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
502 			goto end;
503 		}
504 		*addr = p;
505 	}
506 	snprintf(*addr, 24, "%d.%d.%d.%d:%d",
507 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
508 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
509 
510 end:
511 	return (ret);
512 }
513 
514 int
515 BIO_set_tcp_ndelay(int s, int on)
516 {
517 	int ret = 0;
518 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
519 	int opt;
520 
521 #ifdef SOL_TCP
522 	opt = SOL_TCP;
523 #else
524 #ifdef IPPROTO_TCP
525 	opt = IPPROTO_TCP;
526 #endif
527 #endif
528 
529 	ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
530 #endif
531 	return (ret == 0);
532 }
533 
534 int
535 BIO_socket_nbio(int s, int mode)
536 {
537 	int ret = -1;
538 	int l;
539 
540 	l = mode;
541 	ret = BIO_socket_ioctl(s, FIONBIO, &l);
542 
543 	return (ret == 0);
544 }
545