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