Make b_sock.c IPv6 savvy.
[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 && strchr(h,':')) hint.ai_family = AF_INET6;
644         if ((*getaddrinfo.f)(h,p,&hint,&res)) break;
645         server = *res->ai_addr;
646         (*freeaddrinfo.f)(res);
647         goto again;
648         } while (0);
649 #endif
650
651         if (!BIO_get_port(p,&port)) goto err;
652
653         memset((char *)&server,0,sizeof(server));
654         sin = (struct sockaddr_in *)&server;
655         sin->sin_family=AF_INET;
656         sin->sin_port=htons(port);
657
658         if (h == NULL || strcmp(h,"*") == 0)
659                 sin->sin_addr.s_addr=INADDR_ANY;
660         else
661                 {
662                 if (!BIO_get_host_ip(h,&(ip[0]))) goto err;
663                 l=(unsigned long)
664                         ((unsigned long)ip[0]<<24L)|
665                         ((unsigned long)ip[1]<<16L)|
666                         ((unsigned long)ip[2]<< 8L)|
667                         ((unsigned long)ip[3]);
668                 sin->sin_addr.s_addr=htonl(l);
669                 }
670
671 again:
672         s=socket(server.sa_family,SOCK_STREAM,SOCKET_PROTOCOL);
673         if (s == INVALID_SOCKET)
674                 {
675                 SYSerr(SYS_F_SOCKET,get_last_socket_error());
676                 ERR_add_error_data(3,"port='",host,"'");
677                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_CREATE_SOCKET);
678                 goto err;
679                 }
680
681 #ifdef SO_REUSEADDR
682         if (bind_mode == BIO_BIND_REUSEADDR)
683                 {
684                 int i=1;
685
686                 ret=setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&i,sizeof(i));
687                 bind_mode=BIO_BIND_NORMAL;
688                 }
689 #endif
690         if (bind(s,&server,sizeof(server)) == -1)
691                 {
692 #ifdef SO_REUSEADDR
693                 err_num=get_last_socket_error();
694                 if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
695                         (err_num == EADDRINUSE))
696                         {
697                         client = server;
698                         if (h == NULL || strcmp(h,"*") == 0)
699                                 {
700 #ifdef AF_INET6
701                                 if (client.sa_family == AF_INET6)
702                                         {
703                                         struct sockaddr_in6 *sin =
704                                                 (struct sockaddr_in6 *)&client;
705                                         memset(&sin->sin6_addr,0,sizeof(sin->sin6_addr));
706                                         sin->sin6_addr.s6_addr[15]=1;
707                                         }
708                                 else
709 #endif
710                                 if (client.sa_family == AF_INET)
711                                         {
712                                         struct sockaddr_in *sin =
713                                                 (struct sockaddr_in *)&client;
714                                         sin->sin_addr.s_addr=htonl(0x7F000001);
715                                         }
716                                 else    goto err;
717                                 }
718                         cs=socket(client.sa_family,SOCK_STREAM,SOCKET_PROTOCOL);
719                         if (cs != INVALID_SOCKET)
720                                 {
721                                 int ii;
722                                 ii=connect(cs,(struct sockaddr *)&client,
723                                         sizeof(client));
724                                 closesocket(cs);
725                                 if (ii == INVALID_SOCKET)
726                                         {
727                                         bind_mode=BIO_BIND_REUSEADDR;
728                                         closesocket(s);
729                                         goto again;
730                                         }
731                                 /* else error */
732                                 }
733                         /* else error */
734                         }
735 #endif
736                 SYSerr(SYS_F_BIND,err_num);
737                 ERR_add_error_data(3,"port='",host,"'");
738                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_BIND_SOCKET);
739                 goto err;
740                 }
741         if (listen(s,MAX_LISTEN) == -1)
742                 {
743                 SYSerr(SYS_F_BIND,get_last_socket_error());
744                 ERR_add_error_data(3,"port='",host,"'");
745                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_LISTEN_SOCKET);
746                 goto err;
747                 }
748         ret=1;
749 err:
750         if (str != NULL) OPENSSL_free(str);
751         if ((ret == 0) && (s != INVALID_SOCKET))
752                 {
753                 closesocket(s);
754                 s= INVALID_SOCKET;
755                 }
756         return(s);
757         }
758
759 int BIO_accept(int sock, char **addr)
760         {
761         int ret=INVALID_SOCKET;
762         struct sockaddr from;
763         struct sockaddr_in *sin;
764         unsigned long l;
765         unsigned short port;
766         int len;
767         char *p;
768
769         memset(&from,0,sizeof(from));
770         len=sizeof(from);
771         /* Note: under VMS with SOCKETSHR the fourth parameter is currently
772          * of type (int *) whereas under other systems it is (void *) if
773          * you don't have a cast it will choke the compiler: if you do
774          * have a cast then you can either go for (int *) or (void *).
775          */
776         ret=accept(sock,&from,(void *)&len);
777         if (ret == INVALID_SOCKET)
778                 {
779                 if(BIO_sock_should_retry(ret)) return -2;
780                 SYSerr(SYS_F_ACCEPT,get_last_socket_error());
781                 BIOerr(BIO_F_BIO_ACCEPT,BIO_R_ACCEPT_ERROR);
782                 goto end;
783                 }
784
785         if (addr == NULL) goto end;
786
787 #ifdef EAI_FAMILY
788         do {
789         char   h[NI_MAXHOST],s[NI_MAXSERV];
790         size_t l;
791         static union {  void *p;
792                         int (*f)(const struct sockaddr *,socklen_t,
793                                  char *,size_t,char *,size_t,int);
794                         } getnameinfo = {NULL};
795
796         if (getnameinfo.p==NULL)
797                 {
798                 if ((getnameinfo.p=DSO_global_lookup("getnameinfo"))==NULL)
799                         getnameinfo.p=(void*)-1;
800                 }
801         if (getnameinfo.p==(void *)-1) break;
802
803         if ((*getnameinfo.f)(&from,sizeof(from),h,sizeof(h),s,sizeof(s),
804             NI_NUMERICHOST|NI_NUMERICSERV)) break;
805         l = strlen(h)+strlen(p)+2; if (len<24) len=24;
806         p = *addr;
807         if (p)  p = OPENSSL_realloc(p,l);
808         else    p = OPENSSL_malloc(l);
809         if (p==NULL)
810                 {
811                 BIOerr(BIO_F_BIO_ACCEPT,ERR_R_MALLOC_FAILURE);
812                 goto end;
813                 }
814         *addr = p;
815         BIO_snprintf(*addr,l,"%s:%s",h,s);
816         goto end;
817         } while(0);
818 #endif
819         if (from.sa_family != AF_INET) goto end;
820         sin = (struct sockaddr_in *)&from;
821         l=ntohl(sin->sin_addr.s_addr);
822         port=ntohs(sin->sin_port);
823         if (*addr == NULL)
824                 {
825                 if ((p=OPENSSL_malloc(24)) == NULL)
826                         {
827                         BIOerr(BIO_F_BIO_ACCEPT,ERR_R_MALLOC_FAILURE);
828                         goto end;
829                         }
830                 *addr=p;
831                 }
832         BIO_snprintf(*addr,24,"%d.%d.%d.%d:%d",
833                      (unsigned char)(l>>24L)&0xff,
834                      (unsigned char)(l>>16L)&0xff,
835                      (unsigned char)(l>> 8L)&0xff,
836                      (unsigned char)(l     )&0xff,
837                      port);
838 end:
839         return(ret);
840         }
841
842 int BIO_set_tcp_ndelay(int s, int on)
843         {
844         int ret=0;
845 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
846         int opt;
847
848 #ifdef SOL_TCP
849         opt=SOL_TCP;
850 #else
851 #ifdef IPPROTO_TCP
852         opt=IPPROTO_TCP;
853 #endif
854 #endif
855         
856         ret=setsockopt(s,opt,TCP_NODELAY,(char *)&on,sizeof(on));
857 #endif
858         return(ret == 0);
859         }
860 #endif
861
862 int BIO_socket_nbio(int s, int mode)
863         {
864         int ret= -1;
865         int l;
866
867         l=mode;
868 #ifdef FIONBIO
869         ret=BIO_socket_ioctl(s,FIONBIO,&l);
870 #endif
871         return(ret == 0);
872         }