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