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