Fixes so it will compile again under Win32.
[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 <openssl/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;
199         int size;
200                  
201         size=sizeof(int);
202         /* Note: under Windows the third parameter is of type (char *)
203          * whereas under other systems it is (void *) if you don't have
204          * a cast it will choke the compiler: if you do have a cast then
205          * you can either go for (char *) or (void *).
206          */
207         i=getsockopt(sock,SOL_SOCKET,SO_ERROR,(void *)&j,&size);
208         if (i < 0)
209                 return(1);
210         else
211                 return(j);
212         }
213
214 long BIO_ghbn_ctrl(int cmd, int iarg, char *parg)
215         {
216         int i;
217         char **p;
218
219         switch (cmd)
220                 {
221         case BIO_GHBN_CTRL_HITS:
222                 return(BIO_ghbn_hits);
223                 /* break; */
224         case BIO_GHBN_CTRL_MISSES:
225                 return(BIO_ghbn_miss);
226                 /* break; */
227         case BIO_GHBN_CTRL_CACHE_SIZE:
228                 return(GHBN_NUM);
229                 /* break; */
230         case BIO_GHBN_CTRL_GET_ENTRY:
231                 if ((iarg >= 0) && (iarg <GHBN_NUM) &&
232                         (ghbn_cache[iarg].order > 0))
233                         {
234                         p=(char **)parg;
235                         if (p == NULL) return(0);
236                         *p=ghbn_cache[iarg].name;
237                         ghbn_cache[iarg].name[128]='\0';
238                         return(1);
239                         }
240                 return(0);
241                 /* break; */
242         case BIO_GHBN_CTRL_FLUSH:
243                 for (i=0; i<GHBN_NUM; i++)
244                         ghbn_cache[i].order=0;
245                 break;
246         default:
247                 return(0);
248                 }
249         return(1);
250         }
251
252 static struct hostent *ghbn_dup(struct hostent *a)
253         {
254         struct hostent *ret;
255         int i,j;
256
257         MemCheck_off();
258         ret=(struct hostent *)Malloc(sizeof(struct hostent));
259         if (ret == NULL) return(NULL);
260         memset(ret,0,sizeof(struct hostent));
261
262         for (i=0; a->h_aliases[i] != NULL; i++)
263                 ;
264         i++;
265         ret->h_aliases=(char **)Malloc(sizeof(char *)*i);
266         memset(ret->h_aliases,0,sizeof(char *)*i);
267         if (ret == NULL) goto err;
268
269         for (i=0; a->h_addr_list[i] != NULL; i++)
270                 ;
271         i++;
272         ret->h_addr_list=(char **)Malloc(sizeof(char *)*i);
273         memset(ret->h_addr_list,0,sizeof(char *)*i);
274         if (ret->h_addr_list == NULL) goto err;
275
276         j=strlen(a->h_name)+1;
277         if ((ret->h_name=Malloc(j)) == NULL) goto err;
278         memcpy((char *)ret->h_name,a->h_name,j+1);
279         for (i=0; a->h_aliases[i] != NULL; i++)
280                 {
281                 j=strlen(a->h_aliases[i])+1;
282                 if ((ret->h_aliases[i]=Malloc(j)) == NULL) goto err;
283                 memcpy(ret->h_aliases[i],a->h_aliases[i],j+1);
284                 }
285         ret->h_length=a->h_length;
286         ret->h_addrtype=a->h_addrtype;
287         for (i=0; a->h_addr_list[i] != NULL; i++)
288                 {
289                 if ((ret->h_addr_list[i]=Malloc(a->h_length)) == NULL)
290                         goto err;
291                 memcpy(ret->h_addr_list[i],a->h_addr_list[i],a->h_length);
292                 }
293         if (0)
294                 {
295 err:    
296                 if (ret != NULL)
297                         ghbn_free(ret);
298                 ret=NULL;
299                 }
300         MemCheck_on();
301         return(ret);
302         }
303
304 static void ghbn_free(struct hostent *a)
305         {
306         int i;
307
308         if(a == NULL)
309             return;
310
311         if (a->h_aliases != NULL)
312                 {
313                 for (i=0; a->h_aliases[i] != NULL; i++)
314                         Free(a->h_aliases[i]);
315                 Free(a->h_aliases);
316                 }
317         if (a->h_addr_list != NULL)
318                 {
319                 for (i=0; a->h_addr_list[i] != NULL; i++)
320                         Free(a->h_addr_list[i]);
321                 Free(a->h_addr_list);
322                 }
323         if (a->h_name != NULL) Free((char *)a->h_name);
324         Free(a);
325         }
326
327 struct hostent *BIO_gethostbyname(const char *name)
328         {
329         struct hostent *ret;
330         int i,lowi=0,j;
331         unsigned long low= (unsigned long)-1;
332
333 /*      return(gethostbyname(name)); */
334
335         CRYPTO_w_lock(CRYPTO_LOCK_BIO_GETHOSTBYNAME);
336         j=strlen(name);
337         if (j < 128)
338                 {
339                 for (i=0; i<GHBN_NUM; i++)
340                         {
341                         if (low > ghbn_cache[i].order)
342                                 {
343                                 low=ghbn_cache[i].order;
344                                 lowi=i;
345                                 }
346                         if (ghbn_cache[i].order > 0)
347                                 {
348                                 if (strncmp(name,ghbn_cache[i].name,128) == 0)
349                                         break;
350                                 }
351                         }
352                 }
353         else
354                 i=GHBN_NUM;
355
356         if (i == GHBN_NUM) /* no hit*/
357                 {
358                 BIO_ghbn_miss++;
359                 ret=gethostbyname(name);
360
361                 if (ret == NULL) return(NULL);
362                 if (j > 128) return(ret); /* too big to cache */
363
364                 /* else add to cache */
365                 if (ghbn_cache[lowi].ent != NULL)
366                         ghbn_free(ghbn_cache[lowi].ent);
367
368                 strncpy(ghbn_cache[lowi].name,name,128);
369                 ghbn_cache[lowi].ent=ghbn_dup(ret);
370                 ghbn_cache[lowi].order=BIO_ghbn_miss+BIO_ghbn_hits;
371                 }
372         else
373                 {
374                 BIO_ghbn_hits++;
375                 ret= ghbn_cache[i].ent;
376                 ghbn_cache[i].order=BIO_ghbn_miss+BIO_ghbn_hits;
377                 }
378         CRYPTO_w_unlock(CRYPTO_LOCK_BIO_GETHOSTBYNAME);
379         return(ret);
380         }
381
382 int BIO_sock_init(void)
383         {
384 #ifdef WINDOWS
385         static struct WSAData wsa_state;
386
387         if (!wsa_init_done)
388                 {
389                 int err;
390           
391 #ifdef SIGINT
392                 signal(SIGINT,(void (*)(int))BIO_sock_cleanup);
393 #endif
394                 wsa_init_done=1;
395                 memset(&wsa_state,0,sizeof(wsa_state));
396                 if (WSAStartup(0x0101,&wsa_state)!=0)
397                         {
398                         err=WSAGetLastError();
399                         SYSerr(SYS_F_WSASTARTUP,err);
400                         BIOerr(BIO_F_BIO_SOCK_INIT,BIO_R_WSASTARTUP);
401                         return(-1);
402                         }
403                 }
404 #endif /* WINDOWS */
405         return(1);
406         }
407
408 void BIO_sock_cleanup(void)
409         {
410 #ifdef WINDOWS
411         if (wsa_init_done)
412                 {
413                 wsa_init_done=0;
414                 WSACancelBlockingCall();
415                 WSACleanup();
416                 }
417 #endif
418         }
419
420 int BIO_socket_ioctl(int fd, long type, unsigned long *arg)
421         {
422         int i;
423
424         i=ioctlsocket(fd,type,arg);
425         if (i < 0)
426                 SYSerr(SYS_F_IOCTLSOCKET,get_last_socket_error());
427         return(i);
428         }
429
430 /* The reason I have implemented this instead of using sscanf is because
431  * Visual C 1.52c gives an unresolved external when linking a DLL :-( */
432 static int get_ip(const char *str, unsigned char ip[4])
433         {
434         unsigned int tmp[4];
435         int num=0,c,ok=0;
436
437         tmp[0]=tmp[1]=tmp[2]=tmp[3]=0;
438
439         for (;;)
440                 {
441                 c= *(str++);
442                 if ((c >= '0') && (c <= '9'))
443                         {
444                         ok=1;
445                         tmp[num]=tmp[num]*10+c-'0';
446                         if (tmp[num] > 255) return(-1);
447                         }
448                 else if (c == '.')
449                         {
450                         if (!ok) return(-1);
451                         if (num == 3) break;
452                         num++;
453                         ok=0;
454                         }
455                 else if ((num == 3) && ok)
456                         break;
457                 else
458                         return(0);
459                 }
460         ip[0]=tmp[0];
461         ip[1]=tmp[1];
462         ip[2]=tmp[2];
463         ip[3]=tmp[3];
464         return(1);
465         }
466
467 int BIO_get_accept_socket(char *host, int bind_mode)
468         {
469         int ret=0;
470         struct sockaddr_in server,client;
471         int s= -1,cs;
472         unsigned char ip[4];
473         unsigned short port;
474         char *str,*e;
475         const char *h,*p;
476         unsigned long l;
477         int err_num;
478
479         if (!BIO_sock_init()) return(INVALID_SOCKET);
480
481         if ((str=BUF_strdup(host)) == NULL) return(INVALID_SOCKET);
482
483         h=p=NULL;
484         h=str;
485         for (e=str; *e; e++)
486                 {
487                 if (*e == ':')
488                         {
489                         p= &(e[1]);
490                         *e='\0';
491                         }
492                 else if (*e == '/')
493                         {
494                         *e='\0';
495                         break;
496                         }
497                 }
498
499         if (p == NULL)
500                 {
501                 p=h;
502                 h="*";
503                 }
504
505         if (!BIO_get_port(p,&port)) return(INVALID_SOCKET);
506
507         memset((char *)&server,0,sizeof(server));
508         server.sin_family=AF_INET;
509         server.sin_port=htons(port);
510
511         if (strcmp(h,"*") == 0)
512                 server.sin_addr.s_addr=INADDR_ANY;
513         else
514                 {
515                 if (!BIO_get_host_ip(h,&(ip[0]))) return(INVALID_SOCKET);
516                 l=(unsigned long)
517                         ((unsigned long)ip[0]<<24L)|
518                         ((unsigned long)ip[1]<<16L)|
519                         ((unsigned long)ip[2]<< 8L)|
520                         ((unsigned long)ip[3]);
521                 server.sin_addr.s_addr=htonl(l);
522                 }
523
524 again:
525         s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
526         if (s == INVALID_SOCKET)
527                 {
528                 SYSerr(SYS_F_SOCKET,get_last_socket_error());
529                 ERR_add_error_data(3,"port='",host,"'");
530                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_CREATE_SOCKET);
531                 goto err;
532                 }
533
534 #ifdef SO_REUSEADDR
535         if (bind_mode == BIO_BIND_REUSEADDR)
536                 {
537                 int i=1;
538
539                 ret=setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&i,sizeof(i));
540                 bind_mode=BIO_BIND_NORMAL;
541                 }
542 #endif
543         if (bind(s,(struct sockaddr *)&server,sizeof(server)) == -1)
544                 {
545 #ifdef SO_REUSEADDR
546                 err_num=get_last_socket_error();
547                 if ((bind_mode == BIO_BIND_REUSEADDR_IF_UNUSED) &&
548                         (err_num == EADDRINUSE))
549                         {
550                         memcpy((char *)&client,(char *)&server,sizeof(server));
551                         if (strcmp(h,"*") == 0)
552                                 client.sin_addr.s_addr=htonl(0x7F000001);
553                         cs=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
554                         if (cs != INVALID_SOCKET)
555                                 {
556                                 int ii;
557                                 ii=connect(cs,(struct sockaddr *)&client,
558                                         sizeof(client));
559                                 closesocket(cs);
560                                 if (ii == INVALID_SOCKET)
561                                         {
562                                         bind_mode=BIO_BIND_REUSEADDR;
563                                         closesocket(s);
564                                         goto again;
565                                         }
566                                 /* else error */
567                                 }
568                         /* else error */
569                         }
570 #endif
571                 SYSerr(SYS_F_BIND,err_num);
572                 ERR_add_error_data(3,"port='",host,"'");
573                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_BIND_SOCKET);
574                 goto err;
575                 }
576         if (listen(s,MAX_LISTEN) == -1)
577                 {
578                 SYSerr(SYS_F_BIND,get_last_socket_error());
579                 ERR_add_error_data(3,"port='",host,"'");
580                 BIOerr(BIO_F_BIO_GET_ACCEPT_SOCKET,BIO_R_UNABLE_TO_LISTEN_SOCKET);
581                 goto err;
582                 }
583         ret=1;
584 err:
585         if (str != NULL) Free(str);
586         if ((ret == 0) && (s != INVALID_SOCKET))
587                 {
588                 closesocket(s);
589                 s= INVALID_SOCKET;
590                 }
591         return(s);
592         }
593
594 int BIO_accept(int sock, char **addr)
595         {
596         int ret=INVALID_SOCKET;
597         static struct sockaddr_in from;
598         unsigned long l;
599         unsigned short port;
600         int len;
601         char *p;
602
603         memset((char *)&from,0,sizeof(from));
604         len=sizeof(from);
605         ret=accept(sock,(struct sockaddr *)&from,&len);
606         if (ret == INVALID_SOCKET)
607                 {
608                 SYSerr(SYS_F_ACCEPT,get_last_socket_error());
609                 BIOerr(BIO_F_BIO_ACCEPT,BIO_R_ACCEPT_ERROR);
610                 goto end;
611                 }
612
613         if (addr == NULL) goto end;
614
615         l=ntohl(from.sin_addr.s_addr);
616         port=ntohs(from.sin_port);
617         if (*addr == NULL)
618                 {
619                 if ((p=Malloc(24)) == NULL)
620                         {
621                         BIOerr(BIO_F_BIO_ACCEPT,ERR_R_MALLOC_FAILURE);
622                         goto end;
623                         }
624                 *addr=p;
625                 }
626         sprintf(*addr,"%d.%d.%d.%d:%d",
627                 (unsigned char)(l>>24L)&0xff,
628                 (unsigned char)(l>>16L)&0xff,
629                 (unsigned char)(l>> 8L)&0xff,
630                 (unsigned char)(l     )&0xff,
631                 port);
632 end:
633         return(ret);
634         }
635
636 int BIO_set_tcp_ndelay(int s, int on)
637         {
638         int ret=0;
639 #if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP))
640         int opt;
641
642 #ifdef SOL_TCP
643         opt=SOL_TCP;
644 #else
645 #ifdef IPPROTO_TCP
646         opt=IPPROTO_TCP;
647 #endif
648 #endif
649         
650         ret=setsockopt(s,opt,TCP_NODELAY,(char *)&on,sizeof(on));
651 #endif
652         return(ret == 0);
653         }
654 #endif
655
656 int BIO_socket_nbio(int s, int mode)
657         {
658         int ret= -1;
659         unsigned long l;
660
661         l=mode;
662 #ifdef FIONBIO
663         ret=BIO_socket_ioctl(s,FIONBIO,&l);
664 #endif
665         return(ret == 0);
666         }