VMS support.
[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(__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 #if (__VMS_VER < 70000000) /* FIONBIO used as a switch to enable ioctl,
82                               and that isn't in VMS < 7.0 */
83 #undef FIONBIO
84 #endif
85 #ifdef VMS /* for vfork() */
86 #include <processes.h>
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                 unsigned long l=1;
259
260                 s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
261                 if (s == INVALID_SOCKET) { perror("socket"); return(0); }
262
263                 i=0;
264                 i=setsockopt(s,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
265                 if (i < 0) { perror("keepalive"); return(0); }
266                 *sock=s;
267
268 #ifdef FIONBIO
269                 BIO_socket_ioctl(s,FIONBIO,&l);
270 #endif
271                 }
272         else
273                 s= *sock;
274
275         i=connect(s,(struct sockaddr *)&them,sizeof(them));
276         if (i == INVALID_SOCKET)
277                 {
278                 if (BIO_sock_should_retry(i))
279                         return(-1);
280                 else
281                         return(0);
282                 }
283         else
284                 return(1);
285         }
286
287 int do_server(int port, int *ret, int (*cb)(), char *context)
288         {
289         int sock;
290         char *name;
291         int accept_socket;
292         int i;
293
294         if (!init_server(&accept_socket,port)) return(0);
295
296         if (ret != NULL)
297                 {
298                 *ret=accept_socket;
299                 /* return(1);*/
300                 }
301         for (;;)
302                 {
303                 if (do_accept(accept_socket,&sock,&name) == 0)
304                         {
305                         SHUTDOWN(accept_socket);
306                         return(0);
307                         }
308                 i=(*cb)(name,sock, context);
309                 if (name != NULL) Free(name);
310                 SHUTDOWN2(sock);
311                 if (i < 0)
312                         {
313                         SHUTDOWN2(accept_socket);
314                         return(i);
315                         }
316                 }
317         }
318
319 int init_server_long(int *sock, int port, char *ip)
320         {
321         int ret=0;
322         struct sockaddr_in server;
323         int s= -1,i;
324
325         if (!sock_init()) return(0);
326
327         memset((char *)&server,0,sizeof(server));
328         server.sin_family=AF_INET;
329         server.sin_port=htons((unsigned short)port);
330         if (ip == NULL)
331                 server.sin_addr.s_addr=INADDR_ANY;
332         else
333 /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
334 #ifndef BIT_FIELD_LIMITS
335                 memcpy(&server.sin_addr.s_addr,ip,4);
336 #else
337                 memcpy(&server.sin_addr,ip,4);
338 #endif
339         s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
340
341         if (s == INVALID_SOCKET) goto err;
342 #if defined SOL_SOCKET && defined SO_REUSEADDR
343                 {
344                 int j = 1;
345                 setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
346                            (void *) &j, sizeof j);
347                 }
348 #endif
349         if (bind(s,(struct sockaddr *)&server,sizeof(server)) == -1)
350                 {
351 #ifndef WINDOWS
352                 perror("bind");
353 #endif
354                 goto err;
355                 }
356         /* Make it 128 for linux */
357         if (listen(s,128) == -1) goto err;
358         i=0;
359         *sock=s;
360         ret=1;
361 err:
362         if ((ret == 0) && (s != -1))
363                 {
364                 SHUTDOWN(s);
365                 }
366         return(ret);
367         }
368
369 int init_server(int *sock, int port)
370         {
371         return(init_server_long(sock, port, NULL));
372         }
373
374 int do_accept(int acc_sock, int *sock, char **host)
375         {
376         int ret,i;
377         struct hostent *h1,*h2;
378         static struct sockaddr_in from;
379         int len;
380 /*      struct linger ling; */
381
382         if (!sock_init()) return(0);
383
384 #ifndef WINDOWS
385 redoit:
386 #endif
387
388         memset((char *)&from,0,sizeof(from));
389         len=sizeof(from);
390         /* Note: under VMS with SOCKETSHR the third parameter is currently
391          * of type (int *) whereas under other systems it is (void *) if
392          * you don't have a cast it will choke the compiler: if you do
393          * have a cast then you can either go for (int *) or (void *).
394          */
395         ret=accept(acc_sock,(struct sockaddr *)&from,(void *)&len);
396         if (ret == INVALID_SOCKET)
397                 {
398 #ifdef WINDOWS
399                 i=WSAGetLastError();
400                 BIO_printf(bio_err,"accept error %d\n",i);
401 #else
402                 if (errno == EINTR)
403                         {
404                         /*check_timeout(); */
405                         goto redoit;
406                         }
407                 fprintf(stderr,"errno=%d ",errno);
408                 perror("accept");
409 #endif
410                 return(0);
411                 }
412
413 /*
414         ling.l_onoff=1;
415         ling.l_linger=0;
416         i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
417         if (i < 0) { perror("linger"); return(0); }
418         i=0;
419         i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
420         if (i < 0) { perror("keepalive"); return(0); }
421 */
422
423         if (host == NULL) goto end;
424 #ifndef BIT_FIELD_LIMITS
425         /* I should use WSAAsyncGetHostByName() under windows */
426         h1=gethostbyaddr((char *)&from.sin_addr.s_addr,
427                 sizeof(from.sin_addr.s_addr),AF_INET);
428 #else
429         h1=gethostbyaddr((char *)&from.sin_addr,
430                 sizeof(struct in_addr),AF_INET);
431 #endif
432         if (h1 == NULL)
433                 {
434                 BIO_printf(bio_err,"bad gethostbyaddr\n");
435                 *host=NULL;
436                 /* return(0); */
437                 }
438         else
439                 {
440                 if ((*host=(char *)Malloc(strlen(h1->h_name)+1)) == NULL)
441                         {
442                         perror("Malloc");
443                         return(0);
444                         }
445                 strcpy(*host,h1->h_name);
446
447                 h2=GetHostByName(*host);
448                 if (h2 == NULL)
449                         {
450                         BIO_printf(bio_err,"gethostbyname failure\n");
451                         return(0);
452                         }
453                 i=0;
454                 if (h2->h_addrtype != AF_INET)
455                         {
456                         BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
457                         return(0);
458                         }
459                 }
460 end:
461         *sock=ret;
462         return(1);
463         }
464
465 int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
466              short *port_ptr)
467         {
468         char *h,*p;
469
470         h=str;
471         p=strchr(str,':');
472         if (p == NULL)
473                 {
474                 BIO_printf(bio_err,"no port defined\n");
475                 return(0);
476                 }
477         *(p++)='\0';
478
479         if ((ip != NULL) && !host_ip(str,ip))
480                 goto err;
481         if (host_ptr != NULL) *host_ptr=h;
482
483         if (!extract_port(p,port_ptr))
484                 goto err;
485         return(1);
486 err:
487         return(0);
488         }
489
490 int host_ip(char *str, unsigned char ip[4])
491         {
492         unsigned int in[4]; 
493         int i;
494
495         if (sscanf(str,"%d.%d.%d.%d",&(in[0]),&(in[1]),&(in[2]),&(in[3])) == 4)
496                 {
497                 for (i=0; i<4; i++)
498                         if (in[i] > 255)
499                                 {
500                                 BIO_printf(bio_err,"invalid IP address\n");
501                                 goto err;
502                                 }
503                 ip[0]=in[0];
504                 ip[1]=in[1];
505                 ip[2]=in[2];
506                 ip[3]=in[3];
507                 }
508         else
509                 { /* do a gethostbyname */
510                 struct hostent *he;
511
512                 if (!sock_init()) return(0);
513
514                 he=GetHostByName(str);
515                 if (he == NULL)
516                         {
517                         BIO_printf(bio_err,"gethostbyname failure\n");
518                         goto err;
519                         }
520                 /* cast to short because of win16 winsock definition */
521                 if ((short)he->h_addrtype != AF_INET)
522                         {
523                         BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
524                         return(0);
525                         }
526                 ip[0]=he->h_addr_list[0][0];
527                 ip[1]=he->h_addr_list[0][1];
528                 ip[2]=he->h_addr_list[0][2];
529                 ip[3]=he->h_addr_list[0][3];
530                 }
531         return(1);
532 err:
533         return(0);
534         }
535
536 int extract_port(char *str, short *port_ptr)
537         {
538         int i;
539         struct servent *s;
540
541         i=atoi(str);
542         if (i != 0)
543                 *port_ptr=(unsigned short)i;
544         else
545                 {
546                 s=getservbyname(str,"tcp");
547                 if (s == NULL)
548                         {
549                         BIO_printf(bio_err,"getservbyname failure for %s\n",str);
550                         return(0);
551                         }
552                 *port_ptr=ntohs((unsigned short)s->s_port);
553                 }
554         return(1);
555         }
556
557 #define GHBN_NUM        4
558 static struct ghbn_cache_st
559         {
560         char name[128];
561         struct hostent ent;
562         unsigned long order;
563         } ghbn_cache[GHBN_NUM];
564
565 static unsigned long ghbn_hits=0L;
566 static unsigned long ghbn_miss=0L;
567
568 static struct hostent *GetHostByName(char *name)
569         {
570         struct hostent *ret;
571         int i,lowi=0;
572         unsigned long low= (unsigned long)-1;
573
574         for (i=0; i<GHBN_NUM; i++)
575                 {
576                 if (low > ghbn_cache[i].order)
577                         {
578                         low=ghbn_cache[i].order;
579                         lowi=i;
580                         }
581                 if (ghbn_cache[i].order > 0)
582                         {
583                         if (strncmp(name,ghbn_cache[i].name,128) == 0)
584                                 break;
585                         }
586                 }
587         if (i == GHBN_NUM) /* no hit*/
588                 {
589                 ghbn_miss++;
590                 ret=gethostbyname(name);
591                 if (ret == NULL) return(NULL);
592                 /* else add to cache */
593                 strncpy(ghbn_cache[lowi].name,name,128);
594                 memcpy((char *)&(ghbn_cache[lowi].ent),ret,sizeof(struct hostent));
595                 ghbn_cache[lowi].order=ghbn_miss+ghbn_hits;
596                 return(ret);
597                 }
598         else
599                 {
600                 ghbn_hits++;
601                 ret= &(ghbn_cache[i].ent);
602                 ghbn_cache[i].order=ghbn_miss+ghbn_hits;
603                 return(ret);
604                 }
605         }
606
607 #ifndef MSDOS
608 int spawn(int argc, char **argv, int *in, int *out)
609         {
610         int pid;
611 #define CHILD_READ      p1[0]
612 #define CHILD_WRITE     p2[1]
613 #define PARENT_READ     p2[0]
614 #define PARENT_WRITE    p1[1]
615         int p1[2],p2[2];
616
617         if ((pipe(p1) < 0) || (pipe(p2) < 0)) return(-1);
618
619 #ifdef VMS
620         if ((pid=vfork()) == 0)
621 #else
622         if ((pid=fork()) == 0)
623 #endif
624                 { /* child */
625                 if (dup2(CHILD_WRITE,fileno(stdout)) < 0)
626                         perror("dup2");
627                 if (dup2(CHILD_WRITE,fileno(stderr)) < 0)
628                         perror("dup2");
629                 if (dup2(CHILD_READ,fileno(stdin)) < 0)
630                         perror("dup2");
631                 close(CHILD_READ); 
632                 close(CHILD_WRITE);
633
634                 close(PARENT_READ);
635                 close(PARENT_WRITE);
636                 execvp(argv[0],argv);
637                 perror("child");
638                 exit(1);
639                 }
640
641         /* parent */
642         *in= PARENT_READ;
643         *out=PARENT_WRITE;
644         close(CHILD_READ);
645         close(CHILD_WRITE);
646         return(pid);
647         }
648 #endif /* MSDOS */
649
650
651 #ifdef undef
652         /* Turn on synchronous sockets so that we can do a WaitForMultipleObjects
653          * on sockets */
654         {
655         SOCKET s;
656         int optionValue = SO_SYNCHRONOUS_NONALERT;
657         int err;
658
659         err = setsockopt( 
660             INVALID_SOCKET, 
661             SOL_SOCKET, 
662             SO_OPENTYPE, 
663             (char *)&optionValue, 
664             sizeof(optionValue));
665         if (err != NO_ERROR) {
666         /* failed for some reason... */
667                 BIO_printf(bio_err, "failed to setsockopt(SO_OPENTYPE, SO_SYNCHRONOUS_ALERT) - %d\n",
668                         WSAGetLastError());
669                 }
670         }
671 #endif