xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision 69f1b12577c83a06eb3c8e46f40a2c2d79144e6b)
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 <stdio.h>
60 #include <stdlib.h>
61 #include <errno.h>
62 #include "cryptlib.h"
63 #include <openssl/bio.h>
64 #include <sys/ioctl.h>
65 
66 #include <netdb.h>
67 #include <sys/socket.h>
68 #include <netinet/in.h>
69 
70 #ifndef OPENSSL_NO_SOCK
71 
72 #include <openssl/dso.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 #if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
85 static int wsa_init_done = 0;
86 #endif
87 
88 /*
89  * WSAAPI specifier is required to make indirect calls to run-time
90  * linked WinSock 2 functions used in this module, to be specific
91  * [get|free]addrinfo and getnameinfo. This is because WinSock uses
92  * uses non-C calling convention, __stdcall vs. __cdecl, on x86
93  * Windows. On non-WinSock platforms WSAAPI needs to be void.
94  */
95 #ifndef WSAAPI
96 #define WSAAPI
97 #endif
98 
99 static int get_ip(const char *str, unsigned char *ip);
100 
101 int
102 BIO_get_host_ip(const char *str, unsigned char *ip)
103 {
104 	int i;
105 	int err = 1;
106 	int locked = 0;
107 	struct hostent *he;
108 
109 	i = get_ip(str, ip);
110 	if (i < 0) {
111 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS);
112 		goto err;
113 	}
114 
115 	/* At this point, we have something that is most probably correct
116 	   in some way, so let's init the socket. */
117 	if (BIO_sock_init() != 1)
118 		return 0; /* don't generate another error code here */
119 
120 	/* If the string actually contained an IP address, we need not do
121 	   anything more */
122 	if (i > 0)
123 		return (1);
124 
125 	/* do a gethostbyname */
126 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
127 	locked = 1;
128 	he = BIO_gethostbyname(str);
129 	if (he == NULL) {
130 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
131 		goto err;
132 	}
133 
134 	/* cast to short because of win16 winsock definition */
135 	if ((short)he->h_addrtype != AF_INET) {
136 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
137 		goto err;
138 	}
139 	for (i = 0; i < 4; i++)
140 		ip[i] = he->h_addr_list[0][i];
141 	err = 0;
142 
143 err:
144 	if (locked)
145 		CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
146 	if (err) {
147 		ERR_add_error_data(2, "host=", str);
148 		return 0;
149 	} else
150 		return 1;
151 }
152 
153 int
154 BIO_get_port(const char *str, unsigned short *port_ptr)
155 {
156 	int i;
157 	struct servent *s;
158 
159 	if (str == NULL) {
160 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
161 		return (0);
162 	}
163 	i = atoi(str);
164 	if (i != 0)
165 		*port_ptr = (unsigned short)i;
166 	else {
167 		CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
168 		s = getservbyname(str, "tcp");
169 		if (s != NULL)
170 			*port_ptr = ntohs((unsigned short)s->s_port);
171 		CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
172 		if (s == NULL) {
173 			if (strcmp(str, "http") == 0)
174 				*port_ptr = 80;
175 			else if (strcmp(str, "telnet") == 0)
176 				*port_ptr = 23;
177 			else if (strcmp(str, "socks") == 0)
178 				*port_ptr = 1080;
179 			else if (strcmp(str, "https") == 0)
180 				*port_ptr = 443;
181 			else if (strcmp(str, "ssl") == 0)
182 				*port_ptr = 443;
183 			else if (strcmp(str, "ftp") == 0)
184 				*port_ptr = 21;
185 			else if (strcmp(str, "gopher") == 0)
186 				*port_ptr = 70;
187 			else {
188 				SYSerr(SYS_F_GETSERVBYNAME, errno);
189 				ERR_add_error_data(3, "service='", str, "'");
190 				return (0);
191 			}
192 		}
193 	}
194 	return (1);
195 }
196 
197 int
198 BIO_sock_error(int sock)
199 {
200 	int j, i;
201 	int size;
202 
203 	size = sizeof(int);
204 	/* Note: under Windows the third parameter is of type (char *)
205 	 * whereas under other systems it is (void *) if you don't have
206 	 * a cast it will choke the compiler: if you do have a cast then
207 	 * you can either go for (char *) or (void *).
208 	 */
209 	i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, (void *)&size);
210 	if (i < 0)
211 		return (1);
212 	else
213 		return (j);
214 }
215 
216 struct hostent *
217 BIO_gethostbyname(const char *name)
218 {
219 	return gethostbyname(name);
220 }
221 
222 
223 int
224 BIO_sock_init(void)
225 {
226 	return (1);
227 }
228 
229 void
230 BIO_sock_cleanup(void)
231 {
232 }
233 
234 int
235 BIO_socket_ioctl(int fd, long type, void *arg)
236 {
237 	int i;
238 
239 #  define ARG arg
240 
241 	i = ioctl(fd, type, ARG);
242 	if (i < 0)
243 		SYSerr(SYS_F_IOCTLSOCKET, errno);
244 	return (i);
245 }
246 
247 /* The reason I have implemented this instead of using sscanf is because
248  * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
249 static int
250 get_ip(const char *str, unsigned char ip[4])
251 {
252 	unsigned int tmp[4];
253 	int num = 0, c, ok = 0;
254 
255 	tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
256 
257 	for (;;) {
258 		c= *(str++);
259 		if ((c >= '0') && (c <= '9')) {
260 			ok = 1;
261 			tmp[num] = tmp[num]*10 + c-'0';
262 			if (tmp[num] > 255)
263 				return (0);
264 		} else if (c == '.') {
265 			if (!ok)
266 				return (-1);
267 			if (num == 3)
268 				return (0);
269 			num++;
270 			ok = 0;
271 		} else if (c == '\0' && (num == 3) && ok)
272 			break;
273 		else
274 			return (0);
275 	}
276 	ip[0] = tmp[0];
277 	ip[1] = tmp[1];
278 	ip[2] = tmp[2];
279 	ip[3] = tmp[3];
280 	return (1);
281 }
282 
283 int
284 BIO_get_accept_socket(char *host, int bind_mode)
285 {
286 	int ret = 0;
287 	union {
288 		struct sockaddr sa;
289 		struct sockaddr_in sa_in;
290 #if OPENSSL_USE_IPV6
291 		struct sockaddr_in6 sa_in6;
292 #endif
293 	} server, client;
294 	int s = -1, cs, addrlen;
295 	unsigned char ip[4];
296 	unsigned short port;
297 	char *str = NULL, *e;
298 	char *h, *p;
299 	unsigned long l;
300 	int err_num;
301 
302 	if (BIO_sock_init() != 1)
303 		return (-1);
304 
305 	if ((str = BUF_strdup(host)) == NULL)
306 		return (-1);
307 
308 	h = p = NULL;
309 	h = str;
310 	for (e = str; *e; e++) {
311 		if (*e == ':') {
312 			p = e;
313 		} else if (*e == '/') {
314 			*e = '\0';
315 			break;
316 		}
317 	}
318 	if (p)
319 		*p++='\0';	/* points at last ':', '::port' is special [see below] */
320 	else
321 		p = h, h = NULL;
322 
323 #ifdef EAI_FAMILY
324 	do {
325 		static union {
326 			void *p;
327 			int (WSAAPI *f)(const char *, const char *,
328 			    const struct addrinfo *,
329 			    struct addrinfo **);
330 		} p_getaddrinfo = {NULL};
331 		static union {
332 			void *p;
333 			void (WSAAPI *f)(struct addrinfo *);
334 		} p_freeaddrinfo = {NULL};
335 		struct addrinfo *res, hint;
336 
337 		if (p_getaddrinfo.p == NULL) {
338 			if ((p_getaddrinfo.p = DSO_global_lookup("getaddrinfo"))==NULL ||
339 			    (p_freeaddrinfo.p = DSO_global_lookup("freeaddrinfo"))==NULL)
340 				p_getaddrinfo.p = (void*) - 1;
341 		}
342 		if (p_getaddrinfo.p == (void *) - 1)
343 			break;
344 
345 		/* '::port' enforces IPv6 wildcard listener. Some OSes,
346 		 * e.g. Solaris, default to IPv6 without any hint. Also
347 		 * note that commonly IPv6 wildchard socket can service
348 		 * IPv4 connections just as well...  */
349 		memset(&hint, 0, sizeof(hint));
350 		hint.ai_flags = AI_PASSIVE;
351 		if (h) {
352 			if (strchr(h, ':')) {
353 				if (h[1] == '\0')
354 					h = NULL;
355 #if OPENSSL_USE_IPV6
356 				hint.ai_family = AF_INET6;
357 #else
358 				h = NULL;
359 #endif
360 			} else if (h[0] == '*' && h[1] == '\0') {
361 				hint.ai_family = AF_INET;
362 				h = NULL;
363 			}
364 		}
365 
366 		if ((*p_getaddrinfo.f)(h, p, &hint, &res))
367 			break;
368 
369 		addrlen = res->ai_addrlen <= sizeof(server) ?
370 		    res->ai_addrlen : sizeof(server);
371 		memcpy(&server, res->ai_addr, addrlen);
372 
373 		(*p_freeaddrinfo.f)(res);
374 		goto again;
375 	} while (0);
376 #endif
377 
378 	if (!BIO_get_port(p, &port))
379 		goto err;
380 
381 	memset((char *)&server, 0, sizeof(server));
382 	server.sa_in.sin_family = AF_INET;
383 	server.sa_in.sin_port = htons(port);
384 	addrlen = sizeof(server.sa_in);
385 
386 	if (h == NULL || strcmp(h, "*") == 0)
387 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
388 	else {
389 		if (!BIO_get_host_ip(h, &(ip[0])))
390 			goto err;
391 		l = (unsigned long)((unsigned long)ip[0]<<24L)|
392 		    ((unsigned long)ip[1]<<16L)|
393 		    ((unsigned long)ip[2]<< 8L)|
394 		    ((unsigned long)ip[3]);
395 		server.sa_in.sin_addr.s_addr = htonl(l);
396 	}
397 
398 again:
399 	s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
400 	if (s == -1) {
401 		SYSerr(SYS_F_SOCKET, errno);
402 		ERR_add_error_data(3, "port='", host, "'");
403 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
404 		goto err;
405 	}
406 
407 #ifdef SO_REUSEADDR
408 	if (bind_mode == BIO_BIND_REUSEADDR) {
409 		int i = 1;
410 
411 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
412 		bind_mode = BIO_BIND_NORMAL;
413 	}
414 #endif
415 	if (bind(s, &server.sa, addrlen) == -1) {
416 #ifdef SO_REUSEADDR
417 		err_num = errno;
418 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
419 		    (err_num == EADDRINUSE)) {
420 			client = server;
421 			if (h == NULL || strcmp(h, "*") == 0) {
422 #if OPENSSL_USE_IPV6
423 				if (client.sa.sa_family == AF_INET6) {
424 					memset(&client.sa_in6.sin6_addr, 0, sizeof(client.sa_in6.sin6_addr));
425 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
426 				} else
427 #endif
428 				if (client.sa.sa_family == AF_INET) {
429 					client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
430 				} else
431 					goto err;
432 			}
433 			cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
434 			if (cs != -1) {
435 				int ii;
436 				ii = connect(cs, &client.sa, addrlen);
437 				close(cs);
438 				if (ii == -1) {
439 					bind_mode = BIO_BIND_REUSEADDR;
440 					close(s);
441 					goto again;
442 				}
443 				/* else error */
444 			}
445 			/* else error */
446 		}
447 #endif
448 		SYSerr(SYS_F_BIND, err_num);
449 		ERR_add_error_data(3, "port='", host, "'");
450 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
451 		goto err;
452 	}
453 	if (listen(s, MAX_LISTEN) == -1) {
454 		SYSerr(SYS_F_BIND, errno);
455 		ERR_add_error_data(3, "port='", host, "'");
456 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
457 		goto err;
458 	}
459 	ret = 1;
460 err:
461 	if (str != NULL)
462 		free(str);
463 	if ((ret == 0) && (s != -1)) {
464 		close(s);
465 		s = -1;
466 	}
467 	return (s);
468 }
469 
470 int
471 BIO_accept(int sock, char **addr)
472 {
473 	int ret = -1;
474 	unsigned long l;
475 	unsigned short port;
476 	char *p;
477 
478 	struct {
479 		/*
480 		 * As for following union. Trouble is that there are platforms
481 		 * that have socklen_t and there are platforms that don't, on
482 		 * some platforms socklen_t is int and on some size_t. So what
483 		 * one can do? One can cook #ifdef spaghetti, which is nothing
484 		 * but masochistic. Or one can do union between int and size_t.
485 		 * One naturally does it primarily for 64-bit platforms where
486 		 * sizeof(int) != sizeof(size_t). But would it work? Note that
487 		 * if size_t member is initialized to 0, then later int member
488 		 * assignment naturally does the job on little-endian platforms
489 		 * regardless accept's expectations! What about big-endians?
490 		 * If accept expects int*, then it works, and if size_t*, then
491 		 * length value would appear as unreasonably large. But this
492 		 * won't prevent it from filling in the address structure. The
493 		 * trouble of course would be if accept returns more data than
494 		 * actual buffer can accomodate and overwrite stack... That's
495 		 * where early OPENSSL_assert comes into picture. Besides, the
496 		 * only 64-bit big-endian platform found so far that expects
497 		 * size_t* is HP-UX, where stack grows towards higher address.
498 		 * <appro>
499 		 */
500 		union {
501 			size_t s;
502 			int i;
503 		} len;
504 		union {
505 			struct sockaddr sa;
506 			struct sockaddr_in sa_in;
507 #if OPENSSL_USE_IPV6
508 			struct sockaddr_in6 sa_in6;
509 #endif
510 		} from;
511 	} sa;
512 
513 	sa.len.s = 0;
514 	sa.len.i = sizeof(sa.from);
515 	memset(&sa.from, 0, sizeof(sa.from));
516 	ret = accept(sock, &sa.from.sa, (void *)&sa.len);
517 	if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) {
518 		OPENSSL_assert(sa.len.s <= sizeof(sa.from));
519 		sa.len.i = (int)sa.len.s;
520 		/* use sa.len.i from this point */
521 	}
522 	if (ret == -1) {
523 		if (BIO_sock_should_retry(ret))
524 			return -2;
525 		SYSerr(SYS_F_ACCEPT, errno);
526 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
527 		goto end;
528 	}
529 
530 	if (addr == NULL)
531 		goto end;
532 
533 #ifdef EAI_FAMILY
534 	do {
535 		char   h[NI_MAXHOST], s[NI_MAXSERV];
536 		size_t nl;
537 		static union {
538 			void *p;
539 			int (WSAAPI *f)(const struct sockaddr *,
540 			size_t/*socklen_t*/, char *, size_t,
541 			    char *, size_t, int);
542 		} p_getnameinfo = {NULL};
543 		/* 2nd argument to getnameinfo is specified to
544 		 * be socklen_t. Unfortunately there is a number
545 		 * of environments where socklen_t is not defined.
546 		 * As it's passed by value, it's safe to pass it
547 		 * as size_t... <appro> */
548 
549 		if (p_getnameinfo.p == NULL) {
550 			if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL)
551 				p_getnameinfo.p = (void*) - 1;
552 		}
553 		if (p_getnameinfo.p == (void *) - 1)
554 			break;
555 
556 		if ((*p_getnameinfo.f)(&sa.from.sa, sa.len.i, h, sizeof(h),
557 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
558 			break;
559 		nl = strlen(h) + strlen(s) + 2;
560 		p = *addr;
561 		if (p) {
562 			*p = '\0';
563 			p = realloc(p, nl);
564 		} else {
565 			p = malloc(nl);
566 		}
567 		if (p == NULL) {
568 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
569 			goto end;
570 		}
571 		*addr = p;
572 		(void) snprintf(*addr, nl, "%s:%s", h, s);
573 		goto end;
574 	} while (0);
575 #endif
576 	if (sa.from.sa.sa_family != AF_INET)
577 		goto end;
578 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
579 	port = ntohs(sa.from.sa_in.sin_port);
580 	if (*addr == NULL) {
581 		if ((p = malloc(24)) == NULL) {
582 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
583 			goto end;
584 		}
585 		*addr = p;
586 	}
587 	(void) snprintf(*addr, 24, "%d.%d.%d.%d:%d",
588 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
589 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
590 
591 end:
592 	return (ret);
593 }
594 
595 int
596 BIO_set_tcp_ndelay(int s, int on)
597 {
598 	int ret = 0;
599 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
600 	int opt;
601 
602 #ifdef SOL_TCP
603 	opt = SOL_TCP;
604 #else
605 #ifdef IPPROTO_TCP
606 	opt = IPPROTO_TCP;
607 #endif
608 #endif
609 
610 	ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on));
611 #endif
612 	return (ret == 0);
613 }
614 
615 int
616 BIO_socket_nbio(int s, int mode)
617 {
618 	int ret = -1;
619 	int l;
620 
621 	l = mode;
622 #ifdef FIONBIO
623 	ret = BIO_socket_ioctl(s, FIONBIO, &l);
624 #endif
625 	return (ret == 0);
626 }
627 #endif
628