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