ba10d76b2893cf163152815cc684eacd9a52245d
[openssl.git] / apps / s_socket.c
1 /* apps/s_socket.c -  socket-related functions used by s_client and s_server */
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
65 /* With IPv6, it looks like Digital has mixed up the proper order of
66    recursive header file inclusion, resulting in the compiler complaining
67    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
68    is needed to have fileno() declared correctly...  So let's define u_int */
69 #if defined(VMS) && defined(__DECC) && !defined(__U_INT)
70 #define __U_INT
71 typedef unsigned int u_int;
72 #endif
73
74 #define USE_SOCKETS
75 #define NON_MAIN
76 #include "apps.h"
77 #undef USE_SOCKETS
78 #undef NON_MAIN
79 #include "s_apps.h"
80 #include <openssl/ssl.h>
81
82 static struct hostent *GetHostByName(char *name);
83 static void sock_cleanup(void);
84 static int sock_init(void);
85 static int init_client_ip(int *sock,unsigned char ip[4], int port);
86 static int init_server(int *sock, int port);
87 static int init_server_long(int *sock, int port,char *ip);
88 static int do_accept(int acc_sock, int *sock, char **host);
89 static int host_ip(char *str, unsigned char ip[4]);
90
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 static 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 static 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 static 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 do_server(int port, int *ret, int (*cb)(), char *context)
221         {
222         int sock;
223         char *name;
224         int accept_socket;
225         int i;
226
227         if (!init_server(&accept_socket,port)) return(0);
228
229         if (ret != NULL)
230                 {
231                 *ret=accept_socket;
232                 /* return(1);*/
233                 }
234         for (;;)
235                 {
236                 if (do_accept(accept_socket,&sock,&name) == 0)
237                         {
238                         SHUTDOWN(accept_socket);
239                         return(0);
240                         }
241                 i=(*cb)(name,sock, context);
242                 if (name != NULL) Free(name);
243                 SHUTDOWN2(sock);
244                 if (i < 0)
245                         {
246                         SHUTDOWN2(accept_socket);
247                         return(i);
248                         }
249                 }
250         }
251
252 static int init_server_long(int *sock, int port, char *ip)
253         {
254         int ret=0;
255         struct sockaddr_in server;
256         int s= -1,i;
257
258         if (!sock_init()) return(0);
259
260         memset((char *)&server,0,sizeof(server));
261         server.sin_family=AF_INET;
262         server.sin_port=htons((unsigned short)port);
263         if (ip == NULL)
264                 server.sin_addr.s_addr=INADDR_ANY;
265         else
266 /* Added for T3E, address-of fails on bit field (beckman@acl.lanl.gov) */
267 #ifndef BIT_FIELD_LIMITS
268                 memcpy(&server.sin_addr.s_addr,ip,4);
269 #else
270                 memcpy(&server.sin_addr,ip,4);
271 #endif
272         s=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
273
274         if (s == INVALID_SOCKET) goto err;
275 #if defined SOL_SOCKET && defined SO_REUSEADDR
276                 {
277                 int j = 1;
278                 setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
279                            (void *) &j, sizeof j);
280                 }
281 #endif
282         if (bind(s,(struct sockaddr *)&server,sizeof(server)) == -1)
283                 {
284 #ifndef WINDOWS
285                 perror("bind");
286 #endif
287                 goto err;
288                 }
289         /* Make it 128 for linux */
290         if (listen(s,128) == -1) goto err;
291         i=0;
292         *sock=s;
293         ret=1;
294 err:
295         if ((ret == 0) && (s != -1))
296                 {
297                 SHUTDOWN(s);
298                 }
299         return(ret);
300         }
301
302 static int init_server(int *sock, int port)
303         {
304         return(init_server_long(sock, port, NULL));
305         }
306
307 static int do_accept(int acc_sock, int *sock, char **host)
308         {
309         int ret,i;
310         struct hostent *h1,*h2;
311         static struct sockaddr_in from;
312         int len;
313 /*      struct linger ling; */
314
315         if (!sock_init()) return(0);
316
317 #ifndef WINDOWS
318 redoit:
319 #endif
320
321         memset((char *)&from,0,sizeof(from));
322         len=sizeof(from);
323         /* Note: under VMS with SOCKETSHR the fourth parameter is currently
324          * of type (int *) whereas under other systems it is (void *) if
325          * you don't have a cast it will choke the compiler: if you do
326          * have a cast then you can either go for (int *) or (void *).
327          */
328         ret=accept(acc_sock,(struct sockaddr *)&from,(void *)&len);
329         if (ret == INVALID_SOCKET)
330                 {
331 #ifdef WINDOWS
332                 i=WSAGetLastError();
333                 BIO_printf(bio_err,"accept error %d\n",i);
334 #else
335                 if (errno == EINTR)
336                         {
337                         /*check_timeout(); */
338                         goto redoit;
339                         }
340                 fprintf(stderr,"errno=%d ",errno);
341                 perror("accept");
342 #endif
343                 return(0);
344                 }
345
346 /*
347         ling.l_onoff=1;
348         ling.l_linger=0;
349         i=setsockopt(ret,SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling));
350         if (i < 0) { perror("linger"); return(0); }
351         i=0;
352         i=setsockopt(ret,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
353         if (i < 0) { perror("keepalive"); return(0); }
354 */
355
356         if (host == NULL) goto end;
357 #ifndef BIT_FIELD_LIMITS
358         /* I should use WSAAsyncGetHostByName() under windows */
359         h1=gethostbyaddr((char *)&from.sin_addr.s_addr,
360                 sizeof(from.sin_addr.s_addr),AF_INET);
361 #else
362         h1=gethostbyaddr((char *)&from.sin_addr,
363                 sizeof(struct in_addr),AF_INET);
364 #endif
365         if (h1 == NULL)
366                 {
367                 BIO_printf(bio_err,"bad gethostbyaddr\n");
368                 *host=NULL;
369                 /* return(0); */
370                 }
371         else
372                 {
373                 if ((*host=(char *)Malloc(strlen(h1->h_name)+1)) == NULL)
374                         {
375                         perror("Malloc");
376                         return(0);
377                         }
378                 strcpy(*host,h1->h_name);
379
380                 h2=GetHostByName(*host);
381                 if (h2 == NULL)
382                         {
383                         BIO_printf(bio_err,"gethostbyname failure\n");
384                         return(0);
385                         }
386                 i=0;
387                 if (h2->h_addrtype != AF_INET)
388                         {
389                         BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
390                         return(0);
391                         }
392                 }
393 end:
394         *sock=ret;
395         return(1);
396         }
397
398 int extract_host_port(char *str, char **host_ptr, unsigned char *ip,
399              short *port_ptr)
400         {
401         char *h,*p;
402
403         h=str;
404         p=strchr(str,':');
405         if (p == NULL)
406                 {
407                 BIO_printf(bio_err,"no port defined\n");
408                 return(0);
409                 }
410         *(p++)='\0';
411
412         if ((ip != NULL) && !host_ip(str,ip))
413                 goto err;
414         if (host_ptr != NULL) *host_ptr=h;
415
416         if (!extract_port(p,port_ptr))
417                 goto err;
418         return(1);
419 err:
420         return(0);
421         }
422
423 static int host_ip(char *str, unsigned char ip[4])
424         {
425         unsigned int in[4]; 
426         int i;
427
428         if (sscanf(str,"%u.%u.%u.%u",&(in[0]),&(in[1]),&(in[2]),&(in[3])) == 4)
429                 {
430                 for (i=0; i<4; i++)
431                         if (in[i] > 255)
432                                 {
433                                 BIO_printf(bio_err,"invalid IP address\n");
434                                 goto err;
435                                 }
436                 ip[0]=in[0];
437                 ip[1]=in[1];
438                 ip[2]=in[2];
439                 ip[3]=in[3];
440                 }
441         else
442                 { /* do a gethostbyname */
443                 struct hostent *he;
444
445                 if (!sock_init()) return(0);
446
447                 he=GetHostByName(str);
448                 if (he == NULL)
449                         {
450                         BIO_printf(bio_err,"gethostbyname failure\n");
451                         goto err;
452                         }
453                 /* cast to short because of win16 winsock definition */
454                 if ((short)he->h_addrtype != AF_INET)
455                         {
456                         BIO_printf(bio_err,"gethostbyname addr is not AF_INET\n");
457                         return(0);
458                         }
459                 ip[0]=he->h_addr_list[0][0];
460                 ip[1]=he->h_addr_list[0][1];
461                 ip[2]=he->h_addr_list[0][2];
462                 ip[3]=he->h_addr_list[0][3];
463                 }
464         return(1);
465 err:
466         return(0);
467         }
468
469 int extract_port(char *str, short *port_ptr)
470         {
471         int i;
472         struct servent *s;
473
474         i=atoi(str);
475         if (i != 0)
476                 *port_ptr=(unsigned short)i;
477         else
478                 {
479                 s=getservbyname(str,"tcp");
480                 if (s == NULL)
481                         {
482                         BIO_printf(bio_err,"getservbyname failure for %s\n",str);
483                         return(0);
484                         }
485                 *port_ptr=ntohs((unsigned short)s->s_port);
486                 }
487         return(1);
488         }
489
490 #define GHBN_NUM        4
491 static struct ghbn_cache_st
492         {
493         char name[128];
494         struct hostent ent;
495         unsigned long order;
496         } ghbn_cache[GHBN_NUM];
497
498 static unsigned long ghbn_hits=0L;
499 static unsigned long ghbn_miss=0L;
500
501 static struct hostent *GetHostByName(char *name)
502         {
503         struct hostent *ret;
504         int i,lowi=0;
505         unsigned long low= (unsigned long)-1;
506
507         for (i=0; i<GHBN_NUM; i++)
508                 {
509                 if (low > ghbn_cache[i].order)
510                         {
511                         low=ghbn_cache[i].order;
512                         lowi=i;
513                         }
514                 if (ghbn_cache[i].order > 0)
515                         {
516                         if (strncmp(name,ghbn_cache[i].name,128) == 0)
517                                 break;
518                         }
519                 }
520         if (i == GHBN_NUM) /* no hit*/
521                 {
522                 ghbn_miss++;
523                 ret=gethostbyname(name);
524                 if (ret == NULL) return(NULL);
525                 /* else add to cache */
526                 strncpy(ghbn_cache[lowi].name,name,128);
527                 memcpy((char *)&(ghbn_cache[lowi].ent),ret,sizeof(struct hostent));
528                 ghbn_cache[lowi].order=ghbn_miss+ghbn_hits;
529                 return(ret);
530                 }
531         else
532                 {
533                 ghbn_hits++;
534                 ret= &(ghbn_cache[i].ent);
535                 ghbn_cache[i].order=ghbn_miss+ghbn_hits;
536                 return(ret);
537                 }
538         }