45c293905280284c1376580fcd2f9f8fb77f4e9a
[openssl.git] / apps / s_socket.c
1 /* apps/s_socket.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 /* With IPv6, it looks like Digital has mixed up the proper order of
60    recursive header file inclusion, resulting in the compiler complaining
61    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
62    is needed to have fileno() declared correctly...  So let's define u_int */
63 #if defined(VMS) && defined(__DECC) && !defined(__U_INT)
64 #define __U_INT
65 typedef unsigned int u_int;
66 #endif
67
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <errno.h>
72 #include <signal.h>
73 #define USE_SOCKETS
74 #define NON_MAIN
75 #include "apps.h"
76 #undef USE_SOCKETS
77 #undef NON_MAIN
78 #include "s_apps.h"
79 #include <openssl/ssl.h>
80
81 #ifdef VMS
82 #if (__VMS_VER < 70000000) /* FIONBIO used as a switch to enable ioctl,
83                               and that isn't in VMS < 7.0 */
84 #undef FIONBIO
85 #endif
86 #include <processes.h> /* for vfork() */
87 #endif
88
89 static struct hostent *GetHostByName(char *name);
90 int sock_init(void );
91 #ifdef WIN16
92 #define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
93 #else
94 #define SOCKET_PROTOCOL IPPROTO_TCP
95 #endif
96
97 #ifdef WINDOWS
98 static struct WSAData wsa_state;
99 static int wsa_init_done=0;
100
101 #ifdef WIN16
102 static HWND topWnd=0;
103 static FARPROC lpTopWndProc=NULL;
104 static FARPROC lpTopHookProc=NULL;
105 extern HINSTANCE _hInstance;  /* nice global CRT provides */
106
107 static LONG FAR PASCAL topHookProc(HWND hwnd, UINT message, WPARAM wParam,
108              LPARAM lParam)
109         {
110         if (hwnd == topWnd)
111                 {
112                 switch(message)
113                         {
114                 case WM_DESTROY:
115                 case WM_CLOSE:
116                         SetWindowLong(topWnd,GWL_WNDPROC,(LONG)lpTopWndProc);
117                         sock_cleanup();
118                         break;
119                         }
120                 }
121         return CallWindowProc(lpTopWndProc,hwnd,message,wParam,lParam);
122         }
123
124 static BOOL CALLBACK enumproc(HWND hwnd,LPARAM lParam)
125         {
126         topWnd=hwnd;
127         return(FALSE);
128         }
129
130 #endif /* WIN32 */
131 #endif /* WINDOWS */
132
133 void sock_cleanup(void)
134         {
135 #ifdef WINDOWS
136         if (wsa_init_done)
137                 {
138                 wsa_init_done=0;
139                 WSACancelBlockingCall();
140                 WSACleanup();
141                 }
142 #endif
143         }
144
145 int sock_init(void)
146         {
147 #ifdef WINDOWS
148         if (!wsa_init_done)
149                 {
150                 int err;
151           
152 #ifdef SIGINT
153                 signal(SIGINT,(void (*)(int))sock_cleanup);
154 #endif
155                 wsa_init_done=1;
156                 memset(&wsa_state,0,sizeof(wsa_state));
157                 if (WSAStartup(0x0101,&wsa_state)!=0)
158                         {
159                         err=WSAGetLastError();
160                         BIO_printf(bio_err,"unable to start WINSOCK, error code=%d\n",err);
161                         return(0);
162                         }
163
164 #ifdef WIN16
165                 EnumTaskWindows(GetCurrentTask(),enumproc,0L);
166                 lpTopWndProc=(FARPROC)GetWindowLong(topWnd,GWL_WNDPROC);
167                 lpTopHookProc=MakeProcInstance((FARPROC)topHookProc,_hInstance);
168
169                 SetWindowLong(topWnd,GWL_WNDPROC,(LONG)lpTopHookProc);
170 #endif /* WIN16 */
171                 }
172 #endif /* WINDOWS */
173         return(1);
174         }
175
176 int init_client(int *sock, char *host, int port)
177         {
178         unsigned char ip[4];
179         short p=0;
180
181         if (!host_ip(host,&(ip[0])))
182                 {
183                 return(0);
184                 }
185         if (p != 0) port=p;
186         return(init_client_ip(sock,ip,port));
187         }
188
189 int init_client_ip(int *sock, unsigned char ip[4], int port)
190         {
191         unsigned long addr;
192         struct sockaddr_in them;
193         int s,i;
194
195         if (!sock_init()) return(0);
196
197         memset((char *)&them,0,sizeof(them));
198         them.sin_family=AF_INET;
199         them.sin_port=htons((unsigned short)port);
200         addr=(unsigned long)
201                 ((unsigned long)ip[0]<<24L)|
202                 ((unsigned long)ip[1]<<16L)|
203                 ((unsigned long)ip[2]<< 8L)|
204                 ((unsigned long)ip[3]);
205         them.sin_addr.s_addr=htonl(addr);
206
207         s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
208         if (s == INVALID_SOCKET) { perror("socket"); return(0); }
209
210         i=0;
211         i=setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
212         if (i < 0) { perror("keepalive"); return(0); }
213
214         if (connect(s,(struct sockaddr *)&them,sizeof(them)) == -1)
215                 { close(s); perror("connect"); return(0); }
216         *sock=s;
217         return(1);
218         }
219
220 int nbio_sock_error(int sock)
221         {
222         int j,i;
223         int size;
224
225         size=sizeof(int);
226         /* Note: under VMS with SOCKETSHR the third parameter is currently
227          * of type (int *) whereas under other systems it is (void *) if
228          * you don't have a cast it will choke the compiler: if you do
229          * have a cast then you can either go for (int *) or (void *).
230          */
231         i=getsockopt(sock,SOL_SOCKET,SO_ERROR,(char *)&j,(void *)&size);
232         if (i < 0)
233                 return(1);
234         else
235                 return(j);
236         }
237
238 int nbio_init_client_ip(int *sock, unsigned char ip[4], int port)
239         {
240         unsigned long addr;
241         struct sockaddr_in them;
242         int s,i;
243
244         if (!sock_init()) return(0);
245
246         memset((char *)&them,0,sizeof(them));
247         them.sin_family=AF_INET;
248         them.sin_port=htons((unsigned short)port);
249         addr=   (unsigned long)
250                 ((unsigned long)ip[0]<<24L)|
251                 ((unsigned long)ip[1]<<16L)|
252                 ((unsigned long)ip[2]<< 8L)|
253                 ((unsigned long)ip[3]);
254         them.sin_addr.s_addr=htonl(addr);
255
256         if (*sock <= 0)
257                 {
258 #ifdef FIONBIO
259                 unsigned long l=1;
260 #endif
261
262                 s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
263                 if (s == INVALID_SOCKET) { perror("socket"); return(0); }
264
265                 i=0;
266                 i=setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
267                 if (i < 0) { perror("keepalive"); return(0); }
268                 *sock=s;
269
270 #ifdef FIONBIO
271                 BIO_socket_ioctl(s,FIONBIO,&l);
272 #endif
273                 }
274         else
275                 s= *sock;
276
277         i=connect(s,(struct sockaddr *)&them,sizeof(them));
278         if (i == INVALID_SOCKET)
279                 {
280                 if (BIO_sock_should_retry(i))
281                         return(-1);
282                 else
283                         return(0);
284                 }
285         else
286                 return(1);
287         }
288
289 int do_server(int port, int *ret, int (*cb)(), char *context)
290         {
291         int sock;
292         char *name;
293         int accept_socket;
294         int i;
295
296         if (!init_server(&accept_socket,port)) return(0);
297
298         if (ret != NULL)
299                 {
300                 *ret=accept_socket;
301                 /* return(1);*/
302                 }
303         for (;;)
304                 {
305                 if (do_accept(accept_socket,&sock,&name) == 0)
306                         {
307                         SHUTDOWN(accept_socket);
308                         return(0);
309                         }
310                 i=(*cb)(name,sock, context);
311                 if (name != NULL) Free(name);
312                 SHUTDOWN2(sock);
313                 if (i < 0)
314                         {
315                         SHUTDOWN2(accept_socket);
316                         return(i);
317                         }
318                 }
319         }
320
321 int init_server_long(int *sock, int port, char *ip)
322         {
323         int ret=0;
324         struct sockaddr_in server;
325         int s= -1,i;
326
327         if (!sock_init()) return(0);
328
329         memset((char *)&server,0,sizeof(server));
330         server.sin_family=AF_INET;
331         server.sin_port=htons((unsigned short)port);
332         if (ip == NULL)
333                 server.sin_addr.s_addr=INADDR_ANY;
334         else
335 /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
336 #ifndef BIT_FIELD_LIMITS
337                 memcpy(&server.sin_addr.s_addr,ip,4);
338 #else
339                 memcpy(&server.sin_addr,ip,4);
340 #endif
341         s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
342
343         if (s == INVALID_SOCKET) goto err;
344 #if defined SOL_SOCKET && defined SO_REUSEADDR
345                 {
346                 int j = 1;
347                 setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
348                            (void *) &j, sizeof j);
349                 }
350 #endif
351         if (bind(s,(struct sockaddr *)&server,sizeof(server)) == -1)
352                 {
353 #ifndef WINDOWS
354                 perror("bind");
355 #endif
356                 goto err;
357                 }
358         /* Make it 128 for linux */
359         if (listen(s,128) == -1) goto err;
360         i=0;
361         *sock=s;
362         ret=1;
363 err:
364         if ((ret == 0) && (s != -1))
365                 {
366                 SHUTDOWN(s);
367                 }
368         return(ret);
369         }
370
371 int init_server(int *sock, int port)
372         {
373         return(init_server_long(sock, port, NULL));
374         }
375
376 int do_accept(int acc_sock, int *sock, char **host)
377         {
378         int ret,i;
379         struct hostent *h1,*h2;
380         static struct sockaddr_in from;
381         int len;
382 /*      struct linger ling; */
383
384         if (!sock_init()) return(0);
385
386 #ifndef WINDOWS
387 redoit:
388 #endif
389
390         memset((char *)&from,0,sizeof(from));
391         len=sizeof(from);
392         /* Note: under VMS with SOCKETSHR the fourth parameter is currently
393          * of type (int *) whereas under other systems it is (void *) if
394          * you don't have a cast it will choke the compiler: if you do
395          * have a cast then you can either go for (int *) or (void *).
396          */
397         ret=accept(acc_sock,(struct sockaddr *)&from,(void *)&len);
398         if (ret == INVALID_SOCKET)
399                 {
400 #ifdef WINDOWS
401                 i=WSAGetLastError();
402                 BIO_printf(bio_err,"accept error %d\n",i);
403 #else
404                 if (errno == EINTR)
405                         {
406                         /*check_timeout(); */
407                         goto redoit;
408                         }
409                 fprintf(stderr,"errno=%d ",errno);
410                 perror("accept");
411 #endif
412                 return(0);
413                 }
414
415 /*
416         ling.l_onoff=1;
417         ling.l_linger=0;
418         i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
419         if (i < 0) { perror("linger"); return(0); }
420         i=0;
421         i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
422         if (i < 0) { perror("keepalive"); return(0); }
423 */
424
425         if (host == NULL) goto end;
426 #ifndef BIT_FIELD_LIMITS
427         /* I should use WSAAsyncGetHostByName() under windows */
428         h1=gethostbyaddr((char *)&from.sin_addr.s_addr,
429                 sizeof(from.sin_addr.s_addr),AF_INET);
430 #else
431         h1=gethostbyaddr((char *)&from.sin_addr,
432                 sizeof(struct in_addr),AF_INET);
433 #endif
434         if (h1 == NULL)
435                 {
436                 BIO_printf(bio_err,"bad gethostbyaddr\n");
437                 *host=NULL;
438                 /* return(0); */
439                 }
440         else
441                 {
442                 if ((*host=(char *)Malloc(strlen(h1->h_name)+1)) == NULL)
443                         {
444                         perror("Malloc");
445                         return(0);
446                         }
447                 strcpy(*host,h1->h_name);
448
449                 h2=GetHostByName(*host);
450                 if (h2 == NULL)
451                         {
452                         BIO_printf(bio_err,"gethostbyname failure\n");
453                         return(0);
454                         }
455                 i=0;
456                 if (h2->h_addrtype != AF_INET)
457                         {
458                         BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
459                         return(0);
460                         }
461                 }
462 end:
463         *sock=ret;
464         return(1);
465         }
466
467 int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
468              short *port_ptr)
469         {
470         char *h,*p;
471
472         h=str;
473         p=strchr(str,':');
474         if (p == NULL)
475                 {
476                 BIO_printf(bio_err,"no port defined\n");
477                 return(0);
478                 }
479         *(p++)='\0';
480
481         if ((ip != NULL) && !host_ip(str,ip))
482                 goto err;
483         if (host_ptr != NULL) *host_ptr=h;
484
485         if (!extract_port(p,port_ptr))
486                 goto err;
487         return(1);
488 err:
489         return(0);
490         }
491
492 int host_ip(char *str, unsigned char ip[4])
493         {
494         unsigned int in[4]; 
495         int i;
496
497         if (sscanf(str,"%u.%u.%u.%u",&(in[0]),&(in[1]),&(in[2]),&(in[3])) == 4)
498                 {
499                 for (i=0; i<4; i++)
500                         if (in[i] > 255)
501                                 {
502                                 BIO_printf(bio_err,"invalid IP address\n");
503                                 goto err;
504                                 }
505                 ip[0]=in[0];
506                 ip[1]=in[1];
507                 ip[2]=in[2];
508                 ip[3]=in[3];
509                 }
510         else
511                 { /* do a gethostbyname */
512                 struct hostent *he;
513
514                 if (!sock_init()) return(0);
515
516                 he=GetHostByName(str);
517                 if (he == NULL)
518                         {
519                         BIO_printf(bio_err,"gethostbyname failure\n");
520                         goto err;
521                         }
522                 /* cast to short because of win16 winsock definition */
523                 if ((short)he->h_addrtype != AF_INET)
524                         {
525                         BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
526                         return(0);
527                         }
528                 ip[0]=he->h_addr_list[0][0];
529                 ip[1]=he->h_addr_list[0][1];
530                 ip[2]=he->h_addr_list[0][2];
531                 ip[3]=he->h_addr_list[0][3];
532                 }
533         return(1);
534 err:
535         return(0);
536         }
537
538 int extract_port(char *str, short *port_ptr)
539         {
540         int i;
541         struct servent *s;
542
543         i=atoi(str);
544         if (i != 0)
545                 *port_ptr=(unsigned short)i;
546         else
547                 {
548                 s=getservbyname(str,"tcp");
549                 if (s == NULL)
550                         {
551                         BIO_printf(bio_err,"getservbyname failure for %s\n",str);
552                         return(0);
553                         }
554                 *port_ptr=ntohs((unsigned short)s->s_port);
555                 }
556         return(1);
557         }
558
559 #define GHBN_NUM        4
560 static struct ghbn_cache_st
561         {
562         char name[128];
563         struct hostent ent;
564         unsigned long order;
565         } ghbn_cache[GHBN_NUM];
566
567 static unsigned long ghbn_hits=0L;
568 static unsigned long ghbn_miss=0L;
569
570 static struct hostent *GetHostByName(char *name)
571         {
572         struct hostent *ret;
573         int i,lowi=0;
574         unsigned long low= (unsigned long)-1;
575
576         for (i=0; i<GHBN_NUM; i++)
577                 {
578                 if (low > ghbn_cache[i].order)
579                         {
580                         low=ghbn_cache[i].order;
581                         lowi=i;
582                         }
583                 if (ghbn_cache[i].order > 0)
584                         {
585                         if (strncmp(name,ghbn_cache[i].name,128) == 0)
586                                 break;
587                         }
588                 }
589         if (i == GHBN_NUM) /* no hit*/
590                 {
591                 ghbn_miss++;
592                 ret=gethostbyname(name);
593                 if (ret == NULL) return(NULL);
594                 /* else add to cache */
595                 strncpy(ghbn_cache[lowi].name,name,128);
596                 memcpy((char *)&(ghbn_cache[lowi].ent),ret,sizeof(struct hostent));
597                 ghbn_cache[lowi].order=ghbn_miss+ghbn_hits;
598                 return(ret);
599                 }
600         else
601                 {
602                 ghbn_hits++;
603                 ret= &(ghbn_cache[i].ent);
604                 ghbn_cache[i].order=ghbn_miss+ghbn_hits;
605                 return(ret);
606                 }
607         }
608
609 #ifndef MSDOS
610 int spawn(int argc, char **argv, int *in, int *out)
611         {
612         int pid;
613 #define CHILD_READ      p1[0]
614 #define CHILD_WRITE     p2[1]
615 #define PARENT_READ     p2[0]
616 #define PARENT_WRITE    p1[1]
617         int p1[2],p2[2];
618
619         if ((pipe(p1) < 0) || (pipe(p2) < 0)) return(-1);
620
621 #ifdef VMS
622         if ((pid=vfork()) == 0)
623 #else
624         if ((pid=fork()) == 0)
625 #endif
626                 { /* child */
627                 if (dup2(CHILD_WRITE,fileno(stdout)) < 0)
628                         perror("dup2");
629                 if (dup2(CHILD_WRITE,fileno(stderr)) < 0)
630                         perror("dup2");
631                 if (dup2(CHILD_READ,fileno(stdin)) < 0)
632                         perror("dup2");
633                 close(CHILD_READ); 
634                 close(CHILD_WRITE);
635
636                 close(PARENT_READ);
637                 close(PARENT_WRITE);
638                 execvp(argv[0],argv);
639                 perror("child");
640                 exit(1);
641                 }
642
643         /* parent */
644         *in= PARENT_READ;
645         *out=PARENT_WRITE;
646         close(CHILD_READ);
647         close(CHILD_WRITE);
648         return(pid);
649         }
650 #endif /* MSDOS */
651
652
653 #ifdef undef
654         /* Turn on synchronous sockets so that we can do a WaitForMultipleObjects
655          * on sockets */
656         {
657         SOCKET s;
658         int optionValue = SO_SYNCHRONOUS_NONALERT;
659         int err;
660
661         err = setsockopt( 
662             INVALID_SOCKET, 
663             SOL_SOCKET, 
664             SO_OPENTYPE, 
665             (char *)&optionValue, 
666             sizeof(optionValue));
667         if (err != NO_ERROR) {
668         /* failed for some reason... */
669                 BIO_printf(bio_err, "failed to setsockopt(SO_OPENTYPE, SO_SYNCHRONOUS_ALERT) - %d\n",
670                         WSAGetLastError());
671                 }
672         }
673 #endif