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