d14a7797fdd3206513669c4b222462ad2f8b0ac4
[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 #ifndef NO_SOCK
60
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <errno.h>
64 #define USE_SOCKETS
65 #include "cryptlib.h"
66 #include "bio.h"
67
68 /*      BIOerr(BIO_F_WSASTARTUP,BIO_R_WSASTARTUP ); */
69
70 #ifdef WIN16
71 #define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
72 #else
73 #define SOCKET_PROTOCOL IPPROTO_TCP
74 #endif
75
76 #ifdef SO_MAXCONN
77 #define MAX_LISTEN  SOMAXCONN
78 #elif defined(SO_MAXCONN)
79 #define MAX_LISTEN  SO_MAXCONN
80 #else
81 #define MAX_LISTEN  32
82 #endif
83
84 #ifdef WINDOWS
85 static int wsa_init_done=0;
86 #endif
87
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
99 #ifndef NOPROTO
100 static int get_ip(const char *str,unsigned char *ip);
101 static void ghbn_free(struct hostent *a);
102 static struct hostent *ghbn_dup(struct hostent *a);
103 #else
104 static int get_ip();
105 static void ghbn_free();
106 static struct hostent *ghbn_dup();
107 #endif
108
109 int BIO_get_host_ip(const char *str, unsigned char *ip)
110         {
111         int i;
112         struct hostent *he;
113
114         i=get_ip(str,ip);
115         if (i > 0) return(1);
116         if (i < 0)
117                 {
118                 BIOerr(BIO_F_BIO_GET_HOST_IP,BIO_R_INVALID_IP_ADDRESS);
119                 ERR_add_error_data(2,"host=",str);
120                 return(0);
121                 }
122         else
123                 { /* do a gethostbyname */
124                 if (!BIO_sock_init()) return(0);
125
126                 he=BIO_gethostbyname(str);
127                 if (he == NULL)
128                         {
129                         BIOerr(BIO_F_BIO_GET_HOST_IP,BIO_R_BAD_HOSTNAME_LOOKUP);
130                         ERR_add_error_data(2,"host=",str);
131                         return(0);
132                         }
133
134                 /* cast to short because of win16 winsock definition */
135                 if ((short)he->h_addrtype != AF_INET)
136                         {
137                         BIOerr(BIO_F_BIO_GET_HOST_IP,BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET);
138                         ERR_add_error_data(2,"host=",str);
139                         return(0);
140                         }
141                 for (i=0; i<4; i++)
142                         ip[i]=he->h_addr_list[0][i];
143                 }
144         return(1);
145         }
146
147 int BIO_get_port(const char *str, unsigned short *port_ptr)
148         {
149         int i;
150         struct servent *s;
151
152         if (str == NULL)
153                 {
154                 BIOerr(BIO_F_BIO_GET_PORT,BIO_R_NO_PORT_DEFINED);
155                 return(0);
156                 }
157         i=atoi(str);
158         if (i != 0)
159                 *port_ptr=(unsigned short)i;
160         else
161                 {
162                 s=getservbyname(str,"tcp");
163                 if (s == NULL)
164                         {
165                         if (strcmp(str,"http") == 0)
166                                 *port_ptr=80;
167                         else if (strcmp(str,"telnet") == 0)
168                                 *port_ptr=23;
169                         else if (strcmp(str,"socks") == 0)
170                                 *port_ptr=1080;
171                         else if (strcmp(str,"https") == 0)
172                                 *port_ptr=443;
173                         else if (strcmp(str,"ssl") == 0)
174                                 *port_ptr=443;
175                         else if (strcmp(str,"ftp") == 0)
176                                 *port_ptr=21;
177                         else if (strcmp(str,"gopher") == 0)
178                                 *port_ptr=70;
179 #if 0
180                         else if (strcmp(str,"wais") == 0)
181                                 *port_ptr=21;
182 #endif
183                         else
184                                 {
185                                 SYSerr(SYS_F_GETSERVBYNAME,get_last_socket_error());
186                                 ERR_add_error_data(3,"service='",str,"'");
187                                 return(0);
188                                 }
189                         return(1);
190                         }
191                 *port_ptr=htons((unsigned short)s->s_port);
192                 }
193         return(1);
194         }
195
196 int BIO_sock_error(int sock)
197         {
198         int j,i,size;
199                  
200         size=sizeof(int);
201
202         i=getsockopt(sock,SOL_SOCKET,SO_ERROR,(char *)&j,&size);
203         if (i < 0)
204                 return(1);
205         else
206                 return(j);
207         }
208
209 long BIO_ghbn_ctrl(int cmd, int iarg, char *parg)
210         {
211         int i;
212         char **p;
213
214         switch (cmd)
215                 {
216         case BIO_GHBN_CTRL_HITS:
217                 return(BIO_ghbn_hits);
218                 /* break; */
219         case BIO_GHBN_CTRL_MISSES:
220                 return(BIO_ghbn_miss);
221                 /* break; */
222         case BIO_GHBN_CTRL_CACHE_SIZE:
223                 return(GHBN_NUM);
224                 /* break; */
225         case BIO_GHBN_CTRL_GET_ENTRY:
226                 if ((iarg >= 0) && (iarg <GHBN_NUM) &&
227                         (ghbn_cache[iarg].order > 0))
228                         {
229                         p=(char **)parg;
230                         if (p == NULL) return(0);
231                         *p=ghbn_cache[iarg].name;
232                         ghbn_cache[iarg].name[128]='\0';
233                         return(1);
234                         }
235                 return(0);
236                 /* break; */
237         case BIO_GHBN_CTRL_FLUSH:
238                 for (i=0; i<GHBN_NUM; i++)
239                         ghbn_cache[i].order=0;
240                 break;
241         default:
242                 return(0);
243                 }
244         return(1);
245         }
246
247 static struct hostent *ghbn_dup(struct hostent *a)
248         {
249         struct hostent *ret;
250         int i,j;
251
252         MemCheck_off();
253         ret=(struct hostent *)Malloc(sizeof(struct hostent));
254         if (ret == NULL) return(NULL);
255         memset(ret,0,sizeof(struct hostent));
256
257         for (i=0; a->h_aliases[i] != NULL; i++)
258                 ;
259         i++;
260         ret->h_aliases=(char **)Malloc(sizeof(char *)*i);
261         memset(ret->h_aliases,0,sizeof(char *)*i);
262         if (ret == NULL) goto err;
263
264         for (i=0; a->h_addr_list[i] != NULL; i++)
265                 ;
266         i++;
267         ret->h_addr_list=(char **)Malloc(sizeof(char *)*i);
268         memset(ret->h_addr_list,0,sizeof(char *)*i);
269         if (ret->h_addr_list == NULL) goto err;
270
271         j=strlen(a->h_name)+1;
272         if ((ret->h_name=Malloc(j)) == NULL) goto err;
273         memcpy((char *)ret->h_name,a->h_name,j+1);
274         for (i=0; a->h_aliases[i] != NULL; i++)
275                 {
276                 j=strlen(a->h_aliases[i])+1;
277                 if ((ret->h_aliases[i]=Malloc(j)) == NULL) goto err;
278                 memcpy(ret->h_aliases[i],a->h_aliases[i],j+1);
279                 }
280         ret->h_length=a->h_length;
281         ret->h_addrtype=a->h_addrtype;
282         for (i=0; a->h_addr_list[i] != NULL; i++)
283                 {
284                 if ((ret->h_addr_list[i]=Malloc(a->h_length)) == NULL)
285                         goto err;
286                 memcpy(ret->h_addr_list[i],a->h_addr_list[i],a->h_length);
287                 }
288         if (0)
289                 {
290 err:    
291                 if (ret != NULL)
292                         ghbn_free(ret);
293                 ret=NULL;
294                 }
295         MemCheck_on();
296         return(ret);
297         }
298
299 static void ghbn_free(struct hostent *a)
300         {
301         int i;
302
303         if(a == NULL)
304             return;
305
306         if (a->h_aliases != NULL)
307                 {
308                 for (i=0; a->h_aliases[i] != NULL; i++)
309                         Free(a->h_aliases[i]);
310                 Free(a->h_aliases);
311                 }
312         if (a->h_addr_list != NULL)
313                 {
314                 for (i=0; a->h_addr_list[i] != NULL; i++)
315                         Free(a->h_addr_list[i]);
316                 Free(a->h_addr_list);
317                 }
318         if (a->h_name != NULL) Free((char *)a->h_name);
319         Free(a);
320         }
321
322 struct hostent *BIO_gethostbyname(const char *name)
323         {
324         struct hostent *ret;
325         int i,lowi=0,j;
326         unsigned long low= (unsigned long)-1;
327
328 /*      return(gethostbyname(name)); */
329
330         CRYPTO_w_lock(CRYPTO_LOCK_BIO_GETHOSTBYNAME);
331         j=strlen(name);
332         if (j < 128)
333                 {
334                 for (i=0; i<GHBN_NUM; i++)
335                         {
336                         if (low > ghbn_cache[i].order)
337                                 {
338                                 low=ghbn_cache[i].order;
339                                 lowi=i;
340                                 }
341                         if (ghbn_cache[i].order > 0)
342                                 {
343                                 if (strncmp(name,ghbn_cache[i].name,128) == 0)
344                                         break;
345                                 }
346                         }
347                 }
348         else
349                 i=GHBN_NUM;
350
351         if (i == GHBN_NUM) /* no hit*/
352                 {
353                 BIO_ghbn_miss++;
354                 ret=gethostbyname(name);
355
356                 if (ret == NULL) return(NULL);
357                 if (j > 128) return(ret); /* too big to cache */
358
359                 /* else add to cache */
360                 if (ghbn_cache[lowi].ent != NULL)
361                         ghbn_free(ghbn_cache[lowi].ent);
362
363                 strncpy(ghbn_cache[lowi].name,name,128);
364                 ghbn_cache[lowi].ent=ghbn_dup(ret);
365                 ghbn_cache[lowi].order=BIO_ghbn_miss+BIO_ghbn_hits;
366                 }
367         else
368                 {
369                 BIO_ghbn_hits++;
370                 ret= ghbn_cache[i].ent;
371                 ghbn_cache[i].order=BIO_ghbn_miss+BIO_ghbn_hits;
372                 }
373         CRYPTO_w_unlock(CRYPTO_LOCK_BIO_GETHOSTBYNAME);
374         return(ret);
375         }
376
377 int BIO_sock_init(void)
378         {
379 #ifdef WINDOWS
380         static struct WSAData wsa_state;
381
382         if (!wsa_init_done)
383                 {
384                 int err;
385           
386 #ifdef SIGINT
387                 signal(SIGINT,(void (*)(int))BIO_sock_cleanup);
388 #endif
389                 wsa_init_done=1;
390                 memset(&wsa_state,0,sizeof(wsa_state));
391                 if (WSAStartup(0x0101,&wsa_state)!=0)
392                         {
393                         err=WSAGetLastError();
394                         SYSerr(SYS_F_WSASTARTUP,err);
395                         BIOerr(BIO_F_BIO_SOCK_INIT,BIO_R_WSASTARTUP);
396                         return(-1);
397                         }
398                 }
399 #endif /* WINDOWS */
400         return(1);
401         }
402
403 void BIO_sock_cleanup(void)
404         {
405 #ifdef WINDOWS
406         if (wsa_init_done)
407                 {
408                 wsa_init_done=0;
409                 WSACancelBlockingCall();
410                 WSACleanup();
411                 }
412 #endif
413         }
414
415 int BIO_socket_ioctl(int fd, long type, unsigned long *arg)
416         {
417         int i;
418
419         i=ioctlsocket(fd,type,arg);
420         if (i < 0)
421                 SYSerr(SYS_F_IOCTLSOCKET,get_last_socket_error());
422         return(i);
423         }
424
425 /* The reason I have implemented this instead of using sscanf is because
426  * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
427 static int get_ip(const char *str, unsigned char ip[4])
428         {
429         unsigned int tmp[4];
430         int num=0,c,ok=0;
431
432         tmp[0]=tmp[1]=tmp[2]=tmp[3]=0;
433
434         for (;;)
435                 {
436                 c= *(str++);
437                 if ((c >= '0') && (c <= '9'))
438                         {
439                         ok=1;
440                         tmp[num]=tmp[num]*10+c-'0';
441                         if (tmp[num] > 255) return(-1);
442                         }
443                 else if (c == '.')
444                         {
445                         if (!ok) return(-1);
446                         if (num == 3) break;
447                         num++;
448                         ok=0;
449                         }
450                 else if ((num == 3) && ok)
451                         break;
452                 else
453                         return(0);
454                 }
455         ip[0]=tmp[0];
456         ip[1]=tmp[1];
457         ip[2]=tmp[2];
458         ip[3]=tmp[3];
459         return(1);
460         }
461
462 int BIO_get_accept_socket(char *host, int bind_mode)
463         {
464         int ret=0;
465         struct sockaddr_in server,client;
466         int s= -1,cs;
467         unsigned char ip[4];
468         unsigned short port;
469         char *str,*e;
470         const char *h,*p;
471         unsigned long l;
472         int err_num;
473
474         if (!BIO_sock_init()) return(INVALID_SOCKET);
475
476         if ((str=BUF_strdup(host)) == NULL) return(INVALID_SOCKET);
477
478         h=p=NULL;
479         h=str;
480         for (e=str; *e; e++)
481                 {
482                 if (*e == ':')
483                         {
484                         p= &(e[1]);
485                         *e='\0';
486                         }
487                 else if (*e == '/')
488                         {
489                         *e='\0';
490                         break;
491                         }
492                 }
493
494         if (p == NULL)
495                 {
496                 p=h;
497                 h="*";
498                 }
499
500         if (!BIO_get_port(p,&port)) return(INVALID_SOCKET);
501
502         memset((char *)&server,0,sizeof(server));
503         server.sin_family=AF_INET;
504         server.sin_port=htons(port);
505
506         if (strcmp(h,"*") == 0)
507                 server.sin_addr.s_addr=INADDR_ANY;
508         else
509                 {
510                 if (!BIO_get_host_ip(h,&(ip[0]))) return(INVALID_SOCKET);
511                 l=(unsigned long)
512                         ((unsigned long)ip[0]<<24L)|
513                         ((unsigned long)ip[1]<<16L)|
514                         ((unsigned long)ip[2]<< 8L)|
515                         ((unsigned long)ip[3]);
516                 server.sin_addr.s_addr=htonl(l);
517                 }
518
519 again:
520         s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
521         if (s == INVALID_SOCKET)
522                 {
523                 SYSerr(SYS_F_SOCKET,get_last_socket_error());
524                 ERR_add_error_data(3,"port='",host,"'");
525                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_CREATE_SOCKET);
526                 goto err;
527                 }
528
529 #ifdef SO_REUSEADDR
530         if (bind_mode == BIO_BIND_REUSEADDR)
531                 {
532                 int i=1;
533
534                 ret=setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&i,sizeof(i));
535                 bind_mode=BIO_BIND_NORMAL;
536                 }
537 #endif
538         if (bind(s,(struct sockaddr *)&server,sizeof(server)) == -1)
539                 {
540 #ifdef SO_REUSEADDR
541                 err_num=get_last_socket_error();
542                 if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
543                         (err_num == EADDRINUSE))
544                         {
545                         memcpy((char *)&client,(char *)&server,sizeof(server));
546                         if (strcmp(h,"*") == 0)
547                                 client.sin_addr.s_addr=htonl(0x7F000001);
548                         cs=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
549                         if (cs != INVALID_SOCKET)
550                                 {
551                                 int ii;
552                                 ii=connect(cs,(struct sockaddr *)&client,
553                                         sizeof(client));
554                                 closesocket(cs);
555                                 if (ii == INVALID_SOCKET)
556                                         {
557                                         bind_mode=BIO_BIND_REUSEADDR;
558                                         closesocket(s);
559                                         goto again;
560                                         }
561                                 /* else error */
562                                 }
563                         /* else error */
564                         }
565 #endif
566                 SYSerr(SYS_F_BIND,err_num);
567                 ERR_add_error_data(3,"port='",host,"'");
568                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_BIND_SOCKET);
569                 goto err;
570                 }
571         if (listen(s,MAX_LISTEN) == -1)
572                 {
573                 SYSerr(SYS_F_BIND,get_last_socket_error());
574                 ERR_add_error_data(3,"port='",host,"'");
575                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_LISTEN_SOCKET);
576                 goto err;
577                 }
578         ret=1;
579 err:
580         if (str != NULL) Free(str);
581         if ((ret == 0) && (s != INVALID_SOCKET))
582                 {
583                 closesocket(s);
584                 s= INVALID_SOCKET;
585                 }
586         return(s);
587         }
588
589 int BIO_accept(int sock, char **addr)
590         {
591         int ret=INVALID_SOCKET;
592         static struct sockaddr_in from;
593         unsigned long l;
594         unsigned short port;
595         int len;
596         char *p;
597
598         memset((char *)&from,0,sizeof(from));
599         len=sizeof(from);
600         ret=accept(sock,(struct sockaddr *)&from,&len);
601         if (ret == INVALID_SOCKET)
602                 {
603                 SYSerr(SYS_F_ACCEPT,get_last_socket_error());
604                 BIOerr(BIO_F_BIO_ACCEPT,BIO_R_ACCEPT_ERROR);
605                 goto end;
606                 }
607
608         if (addr == NULL) goto end;
609
610         l=ntohl(from.sin_addr.s_addr);
611         port=ntohs(from.sin_port);
612         if (*addr == NULL)
613                 {
614                 if ((p=Malloc(24)) == NULL)
615                         {
616                         BIOerr(BIO_F_BIO_ACCEPT,ERR_R_MALLOC_FAILURE);
617                         goto end;
618                         }
619                 *addr=p;
620                 }
621         sprintf(*addr,"%d.%d.%d.%d:%d",
622                 (unsigned char)(l>>24L)&0xff,
623                 (unsigned char)(l>>16L)&0xff,
624                 (unsigned char)(l>> 8L)&0xff,
625                 (unsigned char)(l     )&0xff,
626                 port);
627 end:
628         return(ret);
629         }
630
631 int BIO_set_tcp_ndelay(int s, int on)
632         {
633         int ret=0;
634 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
635         int opt;
636
637 #ifdef SOL_TCP
638         opt=SOL_TCP;
639 #else
640 #ifdef IPPROTO_TCP
641         opt=IPPROTO_TCP;
642 #endif
643 #endif
644         
645         ret=setsockopt(s,opt,TCP_NODELAY,(char *)&on,sizeof(on));
646 #endif
647         return(ret == 0);
648         }
649 #endif
650
651 int BIO_socket_nbio(int s, int mode)
652         {
653         int ret= -1;
654         unsigned long l;
655
656         l=mode;
657 #ifdef FIONBIO
658         ret=BIO_socket_ioctl(s,FIONBIO,&l);
659 #endif
660         return(ret == 0);
661         }