xref: /openbsd-src/lib/libcrypto/bio/b_sock.c (revision c3d505be928f54a35067888fc76997fb1d51a8b2)
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 #define USE_SOCKETS
63 #include "cryptlib.h"
64 #include <openssl/bio.h>
65 #if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_BSDSOCK)
66 #include <netdb.h>
67 #if defined(NETWARE_CLIB)
68 #include <sys/ioctl.h>
69 NETDB_DEFINE_CONTEXT
70 #endif
71 #endif
72 
73 #ifndef OPENSSL_NO_SOCK
74 
75 #include <openssl/dso.h>
76 
77 #define SOCKET_PROTOCOL IPPROTO_TCP
78 
79 #ifdef SO_MAXCONN
80 #define MAX_LISTEN  SO_MAXCONN
81 #elif defined(SOMAXCONN)
82 #define MAX_LISTEN  SOMAXCONN
83 #else
84 #define MAX_LISTEN  32
85 #endif
86 
87 #if defined(OPENSSL_SYS_WINDOWS) || (defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK))
88 static int wsa_init_done = 0;
89 #endif
90 
91 /*
92  * WSAAPI specifier is required to make indirect calls to run-time
93  * linked WinSock 2 functions used in this module, to be specific
94  * [get|free]addrinfo and getnameinfo. This is because WinSock uses
95  * uses non-C calling convention, __stdcall vs. __cdecl, on x86
96  * Windows. On non-WinSock platforms WSAAPI needs to be void.
97  */
98 #ifndef WSAAPI
99 #define WSAAPI
100 #endif
101 
102 #if 0
103 static unsigned long BIO_ghbn_hits = 0L;
104 static unsigned long BIO_ghbn_miss = 0L;
105 
106 #define GHBN_NUM	4
107 static struct ghbn_cache_st {
108 	char name[129];
109 	struct hostent *ent;
110 	unsigned long order;
111 } ghbn_cache[GHBN_NUM];
112 #endif
113 
114 static int get_ip(const char *str, unsigned char *ip);
115 #if 0
116 static void ghbn_free(struct hostent *a);
117 static struct hostent *ghbn_dup(struct hostent *a);
118 #endif
119 
120 int
121 BIO_get_host_ip(const char *str, unsigned char *ip)
122 {
123 	int i;
124 	int err = 1;
125 	int locked = 0;
126 	struct hostent *he;
127 
128 	i = get_ip(str, ip);
129 	if (i < 0) {
130 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_INVALID_IP_ADDRESS);
131 		goto err;
132 	}
133 
134 	/* At this point, we have something that is most probably correct
135 	   in some way, so let's init the socket. */
136 	if (BIO_sock_init() != 1)
137 		return 0; /* don't generate another error code here */
138 
139 	/* If the string actually contained an IP address, we need not do
140 	   anything more */
141 	if (i > 0)
142 		return (1);
143 
144 	/* do a gethostbyname */
145 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
146 	locked = 1;
147 	he = BIO_gethostbyname(str);
148 	if (he == NULL) {
149 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_BAD_HOSTNAME_LOOKUP);
150 		goto err;
151 	}
152 
153 	/* cast to short because of win16 winsock definition */
154 	if ((short)he->h_addrtype != AF_INET) {
155 		BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
156 		goto err;
157 	}
158 	for (i = 0; i < 4; i++)
159 		ip[i] = he->h_addr_list[0][i];
160 	err = 0;
161 
162 err:
163 	if (locked)
164 		CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
165 	if (err) {
166 		ERR_add_error_data(2, "host=", str);
167 		return 0;
168 	} else
169 		return 1;
170 }
171 
172 int
173 BIO_get_port(const char *str, unsigned short *port_ptr)
174 {
175 	int i;
176 	struct servent *s;
177 
178 	if (str == NULL) {
179 		BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED);
180 		return (0);
181 	}
182 	i = atoi(str);
183 	if (i != 0)
184 		*port_ptr = (unsigned short)i;
185 	else {
186 		CRYPTO_w_lock(CRYPTO_LOCK_GETSERVBYNAME);
187 		/* Note: under VMS with SOCKETSHR, it seems like the first
188 		 * parameter is 'char *', instead of 'const char *'
189 		 */
190 #ifndef CONST_STRICT
191 		s = getservbyname((char *)str, "tcp");
192 #else
193 		s = getservbyname(str, "tcp");
194 #endif
195 		if (s != NULL)
196 			*port_ptr = ntohs((unsigned short)s->s_port);
197 		CRYPTO_w_unlock(CRYPTO_LOCK_GETSERVBYNAME);
198 		if (s == NULL) {
199 			if (strcmp(str, "http") == 0)
200 				*port_ptr = 80;
201 			else if (strcmp(str, "telnet") == 0)
202 				*port_ptr = 23;
203 			else if (strcmp(str, "socks") == 0)
204 				*port_ptr = 1080;
205 			else if (strcmp(str, "https") == 0)
206 				*port_ptr = 443;
207 			else if (strcmp(str, "ssl") == 0)
208 				*port_ptr = 443;
209 			else if (strcmp(str, "ftp") == 0)
210 				*port_ptr = 21;
211 			else if (strcmp(str, "gopher") == 0)
212 				*port_ptr = 70;
213 #if 0
214 			else if (strcmp(str, "wais") == 0)
215 				*port_ptr = 21;
216 #endif
217 			else {
218 				SYSerr(SYS_F_GETSERVBYNAME, errno);
219 				ERR_add_error_data(3, "service = '", str, "'");
220 				return (0);
221 			}
222 		}
223 	}
224 	return (1);
225 }
226 
227 int
228 BIO_sock_error(int sock)
229 {
230 	int j, i;
231 	int size;
232 
233 #if defined(OPENSSL_SYS_BEOS_R5)
234 	return 0;
235 #endif
236 
237 	size = sizeof(int);
238 	/* Note: under Windows the third parameter is of type (char *)
239 	 * whereas under other systems it is (void *) if you don't have
240 	 * a cast it will choke the compiler: if you do have a cast then
241 	 * you can either go for (char *) or (void *).
242 	 */
243 	i = getsockopt(sock, SOL_SOCKET, SO_ERROR,(void *)&j,(void *)&size);
244 	if (i < 0)
245 		return (1);
246 	else
247 		return (j);
248 }
249 
250 #if 0
251 long
252 BIO_ghbn_ctrl(int cmd, int iarg, char *parg)
253 {
254 	int i;
255 	char **p;
256 
257 	switch (cmd) {
258 	case BIO_GHBN_CTRL_HITS:
259 		return (BIO_ghbn_hits);
260 		/* break; */
261 	case BIO_GHBN_CTRL_MISSES:
262 		return (BIO_ghbn_miss);
263 		/* break; */
264 	case BIO_GHBN_CTRL_CACHE_SIZE:
265 		return (GHBN_NUM);
266 		/* break; */
267 	case BIO_GHBN_CTRL_GET_ENTRY:
268 		if ((iarg >= 0) && (iarg < GHBN_NUM) &&
269 		    (ghbn_cache[iarg].order > 0)) {
270 			p = (char **)parg;
271 			if (p == NULL)
272 				return (0);
273 			*p = ghbn_cache[iarg].name;
274 			ghbn_cache[iarg].name[128] = '\0';
275 			return (1);
276 		}
277 		return (0);
278 		/* break; */
279 	case BIO_GHBN_CTRL_FLUSH:
280 		for (i = 0; i < GHBN_NUM; i++)
281 			ghbn_cache[i].order = 0;
282 		break;
283 	default:
284 		return (0);
285 	}
286 	return (1);
287 }
288 #endif
289 
290 #if 0
291 static struct hostent
292 *ghbn_dup(struct hostent *a)
293 {
294 	struct hostent *ret;
295 	int i, j;
296 
297 	MemCheck_off();
298 	ret = (struct hostent *)OPENSSL_malloc(sizeof(struct hostent));
299 	if (ret == NULL)
300 		return (NULL);
301 	memset(ret, 0, sizeof(struct hostent));
302 
303 	for (i = 0; a->h_aliases[i] != NULL; i++)
304 		;
305 	i++;
306 	ret->h_aliases = (char **)OPENSSL_malloc(i*sizeof(char *));
307 	if (ret->h_aliases == NULL)
308 		goto err;
309 	memset(ret->h_aliases, 0, i*sizeof(char *));
310 
311 	for (i = 0; a->h_addr_list[i] != NULL; i++)
312 		;
313 	i++;
314 	ret->h_addr_list = (char **)OPENSSL_malloc(i*sizeof(char *));
315 	if (ret->h_addr_list == NULL)
316 		goto err;
317 	memset(ret->h_addr_list, 0, i*sizeof(char *));
318 
319 	j = strlen(a->h_name) + 1;
320 	if ((ret->h_name = OPENSSL_malloc(j)) == NULL) goto err;
321 		memcpy((char *)ret->h_name, a->h_name, j);
322 	for (i = 0; a->h_aliases[i] != NULL; i++) {
323 		j = strlen(a->h_aliases[i]) + 1;
324 		if ((ret->h_aliases[i] = OPENSSL_malloc(j)) == NULL) goto err;
325 			memcpy(ret->h_aliases[i], a->h_aliases[i], j);
326 	}
327 	ret->h_length = a->h_length;
328 	ret->h_addrtype = a->h_addrtype;
329 	for (i = 0; a->h_addr_list[i] != NULL; i++) {
330 		if ((ret->h_addr_list[i] = OPENSSL_malloc(a->h_length)) == NULL)
331 			goto err;
332 		memcpy(ret->h_addr_list[i], a->h_addr_list[i], a->h_length);
333 	}
334 	if (0) {
335 err:
336 		if (ret != NULL)
337 			ghbn_free(ret);
338 		ret = NULL;
339 	}
340 	MemCheck_on();
341 	return (ret);
342 }
343 
344 static void
345 ghbn_free(struct hostent *a)
346 {
347 	int i;
348 
349 	if (a == NULL)
350 		return;
351 
352 	if (a->h_aliases != NULL) {
353 		for (i = 0; a->h_aliases[i] != NULL; i++)
354 			OPENSSL_free(a->h_aliases[i]);
355 		OPENSSL_free(a->h_aliases);
356 	}
357 	if (a->h_addr_list != NULL) {
358 		for (i = 0; a->h_addr_list[i] != NULL; i++)
359 			OPENSSL_free(a->h_addr_list[i]);
360 		OPENSSL_free(a->h_addr_list);
361 	}
362 	if (a->h_name != NULL)
363 		OPENSSL_free(a->h_name);
364 	OPENSSL_free(a);
365 }
366 
367 #endif
368 
369 struct hostent
370 *BIO_gethostbyname(const char *name) {
371 #if 1
372 	/* Caching gethostbyname() results forever is wrong,
373 	 * so we have to let the true gethostbyname() worry about this */
374 #if (defined(NETWARE_BSDSOCK) && !defined(__NOVELL_LIBC__))
375 	return gethostbyname((char*)name);
376 #else
377 	return gethostbyname(name);
378 #endif
379 #else
380 	struct hostent *ret;
381 	int i, lowi = 0, j;
382 	unsigned long low = (unsigned long) - 1;
383 
384 
385 #  if 0
386 	/* It doesn't make sense to use locking here: The function interface
387 	 * is not thread-safe, because threads can never be sure when
388 	 * some other thread destroys the data they were given a pointer to.
389 	 */
390 	CRYPTO_w_lock(CRYPTO_LOCK_GETHOSTBYNAME);
391 #  endif
392 	j = strlen(name);
393 	if (j < 128) {
394 		for (i = 0; i < GHBN_NUM; i++) {
395 			if (low > ghbn_cache[i].order) {
396 				low = ghbn_cache[i].order;
397 				lowi = i;
398 			}
399 			if (ghbn_cache[i].order > 0) {
400 				if (strncmp(name, ghbn_cache[i].name, 128) == 0)
401 					break;
402 			}
403 		}
404 	} else
405 		i = GHBN_NUM;
406 
407 	if (i == GHBN_NUM) /* no hit*/
408 	{
409 		BIO_ghbn_miss++;
410 		/* Note: under VMS with SOCKETSHR, it seems like the first
411 		 * parameter is 'char *', instead of 'const char *'
412 		 */
413 #  ifndef CONST_STRICT
414 		ret = gethostbyname((char *)name);
415 #  else
416 		ret = gethostbyname(name);
417 #  endif
418 
419 		if (ret == NULL)
420 			goto end;
421 		if (j > 128) /* too big to cache */
422 		{
423 #  if 0
424 			/* If we were trying to make this function thread-safe (which
425 			 * is bound to fail), we'd have to give up in this case
426 			 * (or allocate more memory). */
427 			ret = NULL;
428 #  endif
429 			goto end;
430 		}
431 
432 		/* else add to cache */
433 		if (ghbn_cache[lowi].ent != NULL)
434 			ghbn_free(ghbn_cache[lowi].ent); /* XXX not thread-safe */
435 		ghbn_cache[lowi].name[0] = '\0';
436 
437 		if ((ret = ghbn_cache[lowi].ent = ghbn_dup(ret)) == NULL) {
438 			BIOerr(BIO_F_BIO_GETHOSTBYNAME, ERR_R_MALLOC_FAILURE);
439 			goto end;
440 		}
441 		strncpy(ghbn_cache[lowi].name, name, 128);
442 		ghbn_cache[lowi].order = BIO_ghbn_miss + BIO_ghbn_hits;
443 	} else {
444 		BIO_ghbn_hits++;
445 		ret = ghbn_cache[i].ent;
446 		ghbn_cache[i].order = BIO_ghbn_miss + BIO_ghbn_hits;
447 	}
448 end:
449 #  if 0
450 	CRYPTO_w_unlock(CRYPTO_LOCK_GETHOSTBYNAME);
451 #  endif
452 	return (ret);
453 #endif
454 }
455 
456 
457 int
458 BIO_sock_init(void)
459 {
460 #ifdef OPENSSL_SYS_WINDOWS
461 	static struct WSAData wsa_state;
462 
463 	if (!wsa_init_done) {
464 		int err;
465 
466 		wsa_init_done = 1;
467 		memset(&wsa_state, 0, sizeof(wsa_state));
468 		/* Not making wsa_state available to the rest of the
469 		 * code is formally wrong. But the structures we use
470 		 * are [beleived to be] invariable among Winsock DLLs,
471 		 * while API availability is [expected to be] probed
472 		 * at run-time with DSO_global_lookup. */
473 		if (WSAStartup(0x0202, &wsa_state) != 0) {
474 			err = WSAGetLastError();
475 			SYSerr(SYS_F_WSASTARTUP, err);
476 			BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
477 			return (-1);
478 		}
479 	}
480 #endif /* OPENSSL_SYS_WINDOWS */
481 #ifdef WATT32
482 	extern int _watt_do_exit;
483 	_watt_do_exit = 0;
484 	/* don't make sock_init() call exit() */
485 	if (sock_init())
486 		return (-1);
487 #endif
488 
489 #if defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
490 	WORD wVerReq;
491 	WSADATA wsaData;
492 	int err;
493 
494 	if (!wsa_init_done) {
495 		wsa_init_done = 1;
496 		wVerReq = MAKEWORD( 2, 0 );
497 		err = WSAStartup(wVerReq, &wsaData);
498 		if (err != 0) {
499 			SYSerr(SYS_F_WSASTARTUP, err);
500 			BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP);
501 			return (-1);
502 		}
503 	}
504 #endif
505 
506 	return (1);
507 }
508 
509 void
510 BIO_sock_cleanup(void)
511 {
512 #ifdef OPENSSL_SYS_WINDOWS
513 	if (wsa_init_done) {
514 		wsa_init_done = 0;
515 #if 0		/* this call is claimed to be non-present in Winsock2 */
516 		WSACancelBlockingCall();
517 #endif
518 		WSACleanup();
519 	}
520 #elif defined(OPENSSL_SYS_NETWARE) && !defined(NETWARE_BSDSOCK)
521 	if (wsa_init_done) {
522 		wsa_init_done = 0;
523 		WSACleanup();
524 	}
525 #endif
526 }
527 
528 #if !defined(OPENSSL_SYS_VMS) || __VMS_VER >= 70000000
529 
530 int
531 BIO_socket_ioctl(int fd, long type, void *arg)
532 {
533 	int i;
534 
535 #ifdef __DJGPP__
536 	i = ioctl(fd, type,(char *)arg);
537 #else
538 # if defined(OPENSSL_SYS_VMS)
539 	/* 2011-02-18 SMS.
540 	 * VMS ioctl() can't tolerate a 64-bit "void *arg", but we
541 	 * observe that all the consumers pass in an "unsigned long *",
542 	 * so we arrange a local copy with a short pointer, and use
543 	 * that, instead.
544 	 */
545 #  if __INITIAL_POINTER_SIZE == 64
546 #   define ARG arg_32p
547 #   pragma pointer_size save
548 #   pragma pointer_size 32
549 	unsigned long arg_32;
550 	unsigned long *arg_32p;
551 #   pragma pointer_size restore
552 	arg_32p = &arg_32;
553 	arg_32 = *((unsigned long *) arg);
554 #  else /* __INITIAL_POINTER_SIZE == 64 */
555 #   define ARG arg
556 #  endif /* __INITIAL_POINTER_SIZE == 64 [else] */
557 # else /* defined(OPENSSL_SYS_VMS) */
558 #  define ARG arg
559 # endif /* defined(OPENSSL_SYS_VMS) [else] */
560 
561 	i = ioctl(fd, type, ARG);
562 #endif /* __DJGPP__ */
563 	if (i < 0)
564 		SYSerr(SYS_F_IOCTLSOCKET, errno);
565 	return (i);
566 }
567 #endif /* __VMS_VER */
568 
569 /* The reason I have implemented this instead of using sscanf is because
570  * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
571 static int
572 get_ip(const char *str, unsigned char ip[4])
573 {
574 	unsigned int tmp[4];
575 	int num = 0, c, ok = 0;
576 
577 	tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
578 
579 	for (;;) {
580 		c= *(str++);
581 		if ((c >= '0') && (c <= '9')) {
582 			ok = 1;
583 			tmp[num] = tmp[num]*10 + c-'0';
584 			if (tmp[num] > 255)
585 				return (0);
586 		} else if (c == '.') {
587 			if (!ok)
588 				return (-1);
589 			if (num == 3)
590 				return (0);
591 			num++;
592 			ok = 0;
593 		} else if (c == '\0' && (num == 3) && ok)
594 		break;
595 		else
596 			return (0);
597 	}
598 	ip[0] = tmp[0];
599 	ip[1] = tmp[1];
600 	ip[2] = tmp[2];
601 	ip[3] = tmp[3];
602 	return (1);
603 }
604 
605 int
606 BIO_get_accept_socket(char *host, int bind_mode)
607 {
608 	int ret = 0;
609 	union {
610 		struct sockaddr sa;
611 		struct sockaddr_in sa_in;
612 #if OPENSSL_USE_IPV6
613 		struct sockaddr_in6 sa_in6;
614 #endif
615 	} server, client;
616 	int s = -1, cs, addrlen;
617 	unsigned char ip[4];
618 	unsigned short port;
619 	char *str = NULL, *e;
620 	char *h, *p;
621 	unsigned long l;
622 	int err_num;
623 
624 	if (BIO_sock_init() != 1)
625 		return (-1);
626 
627 	if ((str = BUF_strdup(host)) == NULL)
628 		return (-1);
629 
630 	h = p = NULL;
631 	h = str;
632 	for (e = str; *e; e++) {
633 		if (*e == ':') {
634 			p = e;
635 		} else if (*e == '/') {
636 			*e = '\0';
637 			break;
638 		}
639 	}
640 	if (p)
641 		*p++='\0';	/* points at last ':', '::port' is special [see below] */
642 	else
643 		p = h, h = NULL;
644 
645 #ifdef EAI_FAMILY
646 	do {
647 		static union {
648 			void *p;
649 			int (WSAAPI *f)(const char *, const char *,
650 			const struct addrinfo *,
651 			struct addrinfo **);
652 		} p_getaddrinfo = {NULL};
653 		static union {
654 			void *p;
655 			void (WSAAPI *f)(struct addrinfo *);
656 		} p_freeaddrinfo = {NULL};
657 		struct addrinfo *res, hint;
658 
659 		if (p_getaddrinfo.p == NULL) {
660 			if ((p_getaddrinfo.p = DSO_global_lookup("getaddrinfo"))==NULL ||
661 			    (p_freeaddrinfo.p = DSO_global_lookup("freeaddrinfo"))==NULL)
662 			p_getaddrinfo.p = (void*) - 1;
663 		}
664 		if (p_getaddrinfo.p == (void *) - 1) break;
665 
666 		/* '::port' enforces IPv6 wildcard listener. Some OSes,
667 		 * e.g. Solaris, default to IPv6 without any hint. Also
668 		 * note that commonly IPv6 wildchard socket can service
669 		 * IPv4 connections just as well...  */
670 		memset(&hint, 0, sizeof(hint));
671 		hint.ai_flags = AI_PASSIVE;
672 		if (h) {
673 			if (strchr(h, ':')) {
674 				if (h[1] == '\0')
675 					h = NULL;
676 #if OPENSSL_USE_IPV6
677 				hint.ai_family = AF_INET6;
678 #else
679 				h = NULL;
680 #endif
681 			} else if (h[0] == '*' && h[1] == '\0') {
682 				hint.ai_family = AF_INET;
683 				h = NULL;
684 			}
685 		}
686 
687 		if ((*p_getaddrinfo.f)(h, p, &hint, &res))
688 			break;
689 
690 		addrlen = res->ai_addrlen <= sizeof(server) ?
691 		    res->ai_addrlen : sizeof(server);
692 		memcpy(&server, res->ai_addr, addrlen);
693 
694 		(*p_freeaddrinfo.f)(res);
695 		goto again;
696 	} while (0);
697 #endif
698 
699 	if (!BIO_get_port(p, &port))
700 		goto err;
701 
702 	memset((char *)&server, 0, sizeof(server));
703 	server.sa_in.sin_family = AF_INET;
704 	server.sa_in.sin_port = htons(port);
705 	addrlen = sizeof(server.sa_in);
706 
707 	if (h == NULL || strcmp(h, "*") == 0)
708 		server.sa_in.sin_addr.s_addr = INADDR_ANY;
709 	else {
710 		if (!BIO_get_host_ip(h, &(ip[0])))
711 			goto err;
712 		l = (unsigned long)
713 		    ((unsigned long)ip[0]<<24L)|
714 		    ((unsigned long)ip[1]<<16L)|
715 		    ((unsigned long)ip[2]<< 8L)|
716 		    ((unsigned long)ip[3]);
717 		server.sa_in.sin_addr.s_addr = htonl(l);
718 	}
719 
720 again:
721 	s = socket(server.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
722 	if (s == -1) {
723 		SYSerr(SYS_F_SOCKET, errno);
724 		ERR_add_error_data(3, "port = '", host, "'");
725 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_CREATE_SOCKET);
726 		goto err;
727 	}
728 
729 #ifdef SO_REUSEADDR
730 	if (bind_mode == BIO_BIND_REUSEADDR) {
731 		int i = 1;
732 
733 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR,(char *)&i, sizeof(i));
734 		bind_mode = BIO_BIND_NORMAL;
735 	}
736 #endif
737 	if (bind(s, &server.sa, addrlen) == -1) {
738 #ifdef SO_REUSEADDR
739 		err_num = errno;
740 		if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
741 #ifdef OPENSSL_SYS_WINDOWS
742 			/* Some versions of Windows define EADDRINUSE to
743 			 * a dummy value.
744 			 */
745 		(err_num == WSAEADDRINUSE))
746 #else
747 		(err_num == EADDRINUSE))
748 #endif
749 		{
750 			client = server;
751 			if (h == NULL || strcmp(h, "*") == 0) {
752 #if OPENSSL_USE_IPV6
753 				if (client.sa.sa_family == AF_INET6) {
754 					memset(&client.sa_in6.sin6_addr, 0, sizeof(client.sa_in6.sin6_addr));
755 					client.sa_in6.sin6_addr.s6_addr[15] = 1;
756 				} else
757 #endif
758 				if (client.sa.sa_family == AF_INET) {
759 					client.sa_in.sin_addr.s_addr = htonl(0x7F000001);
760 				} else
761 					goto err;
762 			}
763 			cs = socket(client.sa.sa_family, SOCK_STREAM, SOCKET_PROTOCOL);
764 			if (cs != -1) {
765 				int ii;
766 				ii = connect(cs, &client.sa, addrlen);
767 				close(cs);
768 				if (ii == -1) {
769 					bind_mode = BIO_BIND_REUSEADDR;
770 					close(s);
771 					goto again;
772 				}
773 				/* else error */
774 			}
775 			/* else error */
776 		}
777 #endif
778 		SYSerr(SYS_F_BIND, err_num);
779 		ERR_add_error_data(3, "port = '", host, "'");
780 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_BIND_SOCKET);
781 		goto err;
782 	}
783 	if (listen(s, MAX_LISTEN) == -1) {
784 		SYSerr(SYS_F_BIND, errno);
785 		ERR_add_error_data(3, "port = '", host, "'");
786 		BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET, BIO_R_UNABLE_TO_LISTEN_SOCKET);
787 		goto err;
788 	}
789 	ret = 1;
790 err:
791 	if (str != NULL)
792 		OPENSSL_free(str);
793 	if ((ret == 0) && (s != -1)) {
794 		close(s);
795 		s = -1;
796 	}
797 	return (s);
798 }
799 
800 int
801 BIO_accept(int sock, char **addr)
802 {
803 	int ret = -1;
804 	unsigned long l;
805 	unsigned short port;
806 	char *p;
807 
808 	struct {
809 		/*
810 		 * As for following union. Trouble is that there are platforms
811 		 * that have socklen_t and there are platforms that don't, on
812 		 * some platforms socklen_t is int and on some size_t. So what
813 		 * one can do? One can cook #ifdef spaghetti, which is nothing
814 		 * but masochistic. Or one can do union between int and size_t.
815 		 * One naturally does it primarily for 64-bit platforms where
816 		 * sizeof(int) != sizeof(size_t). But would it work? Note that
817 		 * if size_t member is initialized to 0, then later int member
818 		 * assignment naturally does the job on little-endian platforms
819 		 * regardless accept's expectations! What about big-endians?
820 		 * If accept expects int*, then it works, and if size_t*, then
821 		 * length value would appear as unreasonably large. But this
822 		 * won't prevent it from filling in the address structure. The
823 		 * trouble of course would be if accept returns more data than
824 		 * actual buffer can accomodate and overwrite stack... That's
825 		 * where early OPENSSL_assert comes into picture. Besides, the
826 		 * only 64-bit big-endian platform found so far that expects
827 		 * size_t* is HP-UX, where stack grows towards higher address.
828 		 * <appro>
829 		 */
830 		union {
831 			size_t s;
832 			int i;
833 		} len;
834 		union {
835 			struct sockaddr sa;
836 			struct sockaddr_in sa_in;
837 #if OPENSSL_USE_IPV6
838 			struct sockaddr_in6 sa_in6;
839 #endif
840 		} from;
841 	} sa;
842 
843 	sa.len.s = 0;
844 	sa.len.i = sizeof(sa.from);
845 	memset(&sa.from, 0, sizeof(sa.from));
846 	ret = accept(sock, &sa.from.sa,(void *)&sa.len);
847 	if (sizeof(sa.len.i) != sizeof(sa.len.s) && sa.len.i == 0) {
848 		OPENSSL_assert(sa.len.s <= sizeof(sa.from));
849 		sa.len.i = (int)sa.len.s;
850 		/* use sa.len.i from this point */
851 	}
852 	if (ret == -1) {
853 		if (BIO_sock_should_retry(ret)) return -2;
854 			SYSerr(SYS_F_ACCEPT, errno);
855 		BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR);
856 		goto end;
857 	}
858 
859 	if (addr == NULL)
860 		goto end;
861 
862 #ifdef EAI_FAMILY
863 	do {
864 		char   h[NI_MAXHOST], s[NI_MAXSERV];
865 		size_t nl;
866 		static union {
867 			void *p;
868 			int (WSAAPI *f)(const struct sockaddr *,
869 			    size_t/*socklen_t*/, char *, size_t,
870 			    char *, size_t, int);
871 		} p_getnameinfo = {NULL};
872 		/* 2nd argument to getnameinfo is specified to
873 		 * be socklen_t. Unfortunately there is a number
874 		 * of environments where socklen_t is not defined.
875 		 * As it's passed by value, it's safe to pass it
876 		 * as size_t... <appro> */
877 
878 		if (p_getnameinfo.p == NULL) {
879 			if ((p_getnameinfo.p = DSO_global_lookup("getnameinfo")) == NULL)
880 				p_getnameinfo.p = (void*) - 1;
881 		}
882 		if (p_getnameinfo.p == (void *) - 1)
883 			break;
884 
885 		if ((*p_getnameinfo.f)(&sa.from.sa, sa.len.i, h, sizeof(h),
886 		    s, sizeof(s), NI_NUMERICHOST|NI_NUMERICSERV))
887 			break;
888 		nl = strlen(h) + strlen(s) + 2;
889 		p = *addr;
890 		if (p) {
891 			*p = '\0';
892 			p = OPENSSL_realloc(p, nl);
893 		} else {
894 			p = OPENSSL_malloc(nl);
895 		}
896 		if (p == NULL) {
897 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
898 			goto end;
899 		}
900 		*addr = p;
901 		(void) snprintf(*addr, nl, "%s:%s", h, s);
902 		goto end;
903 	} while (0);
904 #endif
905 	if (sa.from.sa.sa_family != AF_INET)
906 		goto end;
907 	l = ntohl(sa.from.sa_in.sin_addr.s_addr);
908 	port = ntohs(sa.from.sa_in.sin_port);
909 	if (*addr == NULL) {
910 		if ((p = OPENSSL_malloc(24)) == NULL) {
911 			BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE);
912 			goto end;
913 		}
914 		*addr = p;
915 	}
916 	(void) snprintf(*addr, 24, "%d.%d.%d.%d:%d",
917 	    (unsigned char)(l >> 24L) & 0xff, (unsigned char)(l >> 16L) & 0xff,
918 	    (unsigned char)(l >> 8L) & 0xff, (unsigned char)(l) & 0xff, port);
919 
920 end:
921 	return (ret);
922 }
923 
924 int
925 BIO_set_tcp_ndelay(int s, int on)
926 {
927 	int ret = 0;
928 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
929 	int opt;
930 
931 #ifdef SOL_TCP
932 	opt = SOL_TCP;
933 #else
934 #ifdef IPPROTO_TCP
935 	opt = IPPROTO_TCP;
936 #endif
937 #endif
938 
939 	ret = setsockopt(s, opt, TCP_NODELAY,(char *)&on, sizeof(on));
940 #endif
941 	return (ret == 0);
942 }
943 
944 int
945 BIO_socket_nbio(int s, int mode)
946 {
947 	int ret = -1;
948 	int l;
949 
950 	l = mode;
951 #ifdef FIONBIO
952 	ret = BIO_socket_ioctl(s, FIONBIO, &l);
953 #endif
954 	return (ret == 0);
955 }
956 #endif
957