prevent 64bit warnings
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2005, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 /* Purpose
25  *
26  * 1. Accept a TCP connection on a custom port (ipv4 or ipv6), or connect
27  *    to a given (localhost) port.
28  *
29  * 2. Get commands on STDIN. Pass data on to the TCP stream.
30  *    Get data from TCP stream and pass on to STDOUT.
31  *
32  * This program is made to perform all the socket/stream/connection stuff for
33  * the test suite's (perl) FTP server. Previously the perl code did all of
34  * this by its own, but I decided to let this program do the socket layer
35  * because of several things:
36  *
37  * o We want the perl code to work with rather old perl installations, thus
38  *   we cannot use recent perl modules or features.
39  *
40  * o We want IPv6 support for systems that provide it, and doing optional IPv6
41  *   support in perl seems if not impossible so at least awkward.
42  *
43  * o We want FTP-SSL support, which means that a connection that starts with
44  *   plain sockets needs to be able to "go SSL" in the midst. This would also
45  *   require some nasty perl stuff I'd rather avoid.
46  *
47  * (Source originally based on sws.c)
48  */
49 #include "setup.h" /* portability help from the lib directory */
50
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <stdarg.h>
55 #include <signal.h>
56 #include <time.h>
57 #include <ctype.h>
58 #include <sys/time.h>
59 #include <sys/types.h>
60
61 #ifdef HAVE_UNISTD_H
62 #include <unistd.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 #include <netinet/in.h>
69 #endif
70 #ifdef _XOPEN_SOURCE_EXTENDED
71 /* This define is "almost" required to build on HPUX 11 */
72 #include <arpa/inet.h>
73 #endif
74 #ifdef HAVE_NETDB_H
75 #include <netdb.h>
76 #endif
77
78 #define ENABLE_CURLX_PRINTF
79 /* make the curlx header define all printf() functions to use the curlx_*
80    versions instead */
81 #include "curlx.h" /* from the private lib dir */
82 #include "getpart.h"
83 #include "inet_pton.h"
84 #include "util.h"
85
86 #ifndef FALSE
87 #define FALSE 0
88 #endif
89 #ifndef TRUE
90 #define TRUE 1
91 #endif
92
93 #if defined(WIN32) && !defined(__CYGWIN__)
94 #include <windows.h>
95 #include <winsock2.h>
96 #include <process.h>
97
98 #define sleep(sec)   Sleep ((sec)*1000)
99
100 #define EINPROGRESS  WSAEINPROGRESS
101 #define EWOULDBLOCK  WSAEWOULDBLOCK
102 #define EISCONN      WSAEISCONN
103 #define ENOTSOCK     WSAENOTSOCK
104 #define ECONNREFUSED WSAECONNREFUSED
105
106 static void win32_cleanup(void);
107
108 #if defined(ENABLE_IPV6) && defined(__MINGW32__)
109 const struct in6_addr in6addr_any = {{ IN6ADDR_ANY_INIT }};
110 #endif
111 #endif
112
113 /* include memdebug.h last */
114 #include "memdebug.h"
115
116 #define DEFAULT_PORT 8999
117
118 #ifndef DEFAULT_LOGFILE
119 #define DEFAULT_LOGFILE "log/sockfilt.log"
120 #endif
121
122 #ifdef SIGPIPE
123 static volatile int sigpipe;  /* Why? It's not used */
124 #endif
125
126 const char *serverlogfile = (char *)DEFAULT_LOGFILE;
127
128 static void lograw(unsigned char *buffer, int len)
129 {
130   char data[120];
131   int i;
132   unsigned char *ptr = buffer;
133   char *optr = data;
134   int width=0;
135
136   for(i=0; i<len; i++) {
137     sprintf(optr, "%c",
138             (isgraph(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
139     optr += 1;
140     width += 1;
141
142     if(width>60) {
143       logmsg("RAW: '%s'", data);
144       width = 0;
145       optr = data;
146     }
147   }
148   if(width)
149     logmsg("RAW: '%s'", data);
150 }
151
152 #ifdef SIGPIPE
153 static void sigpipe_handler(int sig)
154 {
155   (void)sig; /* prevent warning */
156   sigpipe = 1;
157 }
158 #endif
159
160 #if defined(WIN32) && !defined(__CYGWIN__)
161 #undef perror
162 #define perror(m) win32_perror(m)
163
164 static void win32_perror(const char *msg)
165 {
166   char buf[256];
167   DWORD err = WSAGetLastError();
168
169   if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
170                      LANG_NEUTRAL, buf, sizeof(buf), NULL))
171      snprintf(buf, sizeof(buf), "Unknown error %lu (%#lx)", err, err);
172   if (msg)
173      fprintf(stderr, "%s: ", msg);
174   fprintf(stderr, "%s\n", buf);
175 }
176 #endif
177
178 #if defined(WIN32) && !defined(__CYGWIN__)
179 static void win32_init(void)
180 {
181   WORD wVersionRequested;
182   WSADATA wsaData;
183   int err;
184   wVersionRequested = MAKEWORD(2, 0);
185
186   err = WSAStartup(wVersionRequested, &wsaData);
187
188   if (err != 0) {
189     perror("Winsock init failed");
190     logmsg("Error initialising winsock -- aborting\n");
191     exit(1);
192   }
193
194   if ( LOBYTE( wsaData.wVersion ) != 2 ||
195        HIBYTE( wsaData.wVersion ) != 0 ) {
196
197     WSACleanup();
198     perror("Winsock init failed");
199     logmsg("No suitable winsock.dll found -- aborting\n");
200     exit(1);
201   }
202 }
203 static void win32_cleanup(void)
204 {
205   WSACleanup();
206 }
207 #endif
208
209 char use_ipv6=FALSE;
210 unsigned short port = DEFAULT_PORT;
211 unsigned short connectport = 0; /* if non-zero, we activate this mode */
212
213 enum sockmode {
214   PASSIVE_LISTEN,    /* as a server waiting for connections */
215   PASSIVE_CONNECT,   /* as a server, connected to a client */
216   ACTIVE,            /* as a client, connected to a server */
217   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
218 };
219
220 /*
221   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
222
223   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
224   accept()
225 */
226 static int juggle(curl_socket_t *sockfdp,
227                   curl_socket_t listenfd,
228                   enum sockmode *mode)
229 {
230   struct timeval timeout;
231   fd_set fds_read;
232   fd_set fds_write;
233   fd_set fds_err;
234   curl_socket_t maxfd;
235   int r;
236   unsigned char buffer[256]; /* FIX: bigger buffer */
237   char data[256];
238   int sockfd;
239
240   timeout.tv_sec = 120;
241   timeout.tv_usec = 0;
242
243   FD_ZERO(&fds_read);
244   FD_ZERO(&fds_write);
245   FD_ZERO(&fds_err);
246
247   FD_SET(fileno(stdin), &fds_read);
248
249   switch(*mode) {
250   case PASSIVE_LISTEN:
251     /* server mode */
252     sockfd = listenfd;
253     /* there's always a socket to wait for */
254     FD_SET(sockfd, &fds_read);
255     maxfd = sockfd;
256     break;
257
258   case PASSIVE_CONNECT:
259     sockfd = *sockfdp;
260     if(-1 == sockfd) {
261       /* eeek, we are supposedly connected and then this cannot be -1 ! */
262       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
263       maxfd = 0; /* stdin */
264     }
265     else {
266       /* there's always a socket to wait for */
267       FD_SET(sockfd, &fds_read);
268       maxfd = sockfd;
269     }
270     break;
271
272   case ACTIVE:
273     sockfd = *sockfdp;
274
275     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
276     if(sockfd != CURL_SOCKET_BAD) {
277       FD_SET(sockfd, &fds_read);
278       maxfd = sockfd;
279     }
280     else {
281       logmsg("No socket to read on");
282       maxfd = 0;
283     }
284     break;
285
286   case ACTIVE_DISCONNECT:
287     logmsg("disconnected, no socket to read on");
288     maxfd = 0;
289     sockfd = CURL_SOCKET_BAD;
290     break;
291   }
292
293   do {
294     r = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
295   } while((r == -1) && (ourerrno() == EINTR));
296
297   switch(r) {
298   case -1:
299     return FALSE;
300
301   case 0: /* timeout! */
302     return TRUE;
303   }
304
305
306   if(FD_ISSET(fileno(stdin), &fds_read)) {
307     size_t nread;
308     /* read from stdin, commands/data to be dealt with and possibly passed on
309        to the socket
310
311        protocol:
312
313        4 letter command + LF [mandatory]
314
315        4-digit hexadecimal data length + LF [if the command takes data]
316        data                       [the data being as long as set above]
317
318        Commands:
319
320        DATA - plain pass-thru data
321     */
322     nread = read(fileno(stdin), buffer, 5);
323     if(5 == nread) {
324
325       logmsg("Received %c%c%c%c (on stdin)",
326              buffer[0], buffer[1], buffer[2], buffer[3] );
327
328       if(!memcmp("PING", buffer, 4)) {
329         /* send reply on stdout, just proving we are alive */
330         write(fileno(stdout), "PONG\n", 5);
331       }
332
333       else if(!memcmp("PORT", buffer, 4)) {
334         /* question asking us what PORT number we are listening to.
335            Replies with PORT with "IPv[num]/[port]" */
336         sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, port);
337         r = (int)strlen((char *)buffer);
338         sprintf(data, "PORT\n%04x\n", r);
339         write(fileno(stdout), data, 10);
340         write(fileno(stdout), buffer, r);
341       }
342       else if(!memcmp("QUIT", buffer, 4)) {
343         /* just die */
344         logmsg("quits");
345         return FALSE;
346       }
347       else if(!memcmp("DATA", buffer, 4)) {
348         /* data IN => data OUT */
349         long len;
350
351         if(5 != read(fileno(stdin), buffer, 5))
352           return FALSE;
353
354         len = strtol((char *)buffer, NULL, 16);
355         if(len != read(fileno(stdin), buffer, len))
356           return FALSE;
357
358         logmsg("> %d bytes data, server => client", len);
359         lograw(buffer, (int)len);
360
361         if(*mode == PASSIVE_LISTEN) {
362           logmsg("*** We are disconnected!");
363           write(fileno(stdout), "DISC\n", 5);
364         }
365         else
366           /* send away on the socket */
367           swrite(sockfd, buffer, len);
368       }
369       else if(!memcmp("DISC", buffer, 4)) {
370         /* disconnect! */
371         write(fileno(stdout), "DISC\n", 5);
372         if(sockfd != CURL_SOCKET_BAD) {
373           logmsg("====> Client forcibly disconnected");
374           sclose(sockfd);
375           *sockfdp = CURL_SOCKET_BAD;
376           if(*mode == PASSIVE_CONNECT)
377             *mode = PASSIVE_LISTEN;
378           else
379             *mode = ACTIVE_DISCONNECT;
380         }
381         else
382           logmsg("attempt to close already dead connection");
383         return TRUE;
384       }
385     }
386     else {
387       logmsg("read %d from stdin, exiting", (int)nread);
388       return FALSE;
389     }
390   }
391
392   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
393
394     if(*mode == PASSIVE_LISTEN) {
395       /* there's no stream set up yet, this is an indication that there's a
396          client connecting. */
397       sockfd = accept(sockfd, NULL, NULL);
398       if(-1 == sockfd)
399         logmsg("accept() failed\n");
400       else {
401         logmsg("====> Client connect");
402         write(fileno(stdout), "CNCT\n", 5);
403         *sockfdp = sockfd; /* store the new socket */
404         *mode = PASSIVE_CONNECT; /* we have connected */
405       }
406       return TRUE;
407     }
408
409     /* read from socket, pass on data to stdout */
410     r = sread(sockfd, buffer, sizeof(buffer));
411
412     if(r <= 0) {
413       logmsg("====> Client disconnect");
414       write(fileno(stdout), "DISC\n", 5);
415       sclose(sockfd);
416       *sockfdp = CURL_SOCKET_BAD;
417       if(*mode == PASSIVE_CONNECT)
418         *mode = PASSIVE_LISTEN;
419       else
420         *mode = ACTIVE_DISCONNECT;
421       return TRUE;
422     }
423
424     sprintf(data, "DATA\n%04x\n", r);
425     write(fileno(stdout), data, 10);
426     write(fileno(stdout), buffer, r);
427
428     logmsg("< %d bytes data, client => server", r);
429     lograw(buffer, r);
430   }
431
432   return TRUE;
433 }
434
435 int main(int argc, char *argv[])
436 {
437   struct sockaddr_in me;
438 #ifdef ENABLE_IPV6
439   struct sockaddr_in6 me6;
440 #endif /* ENABLE_IPV6 */
441   int sock;
442   int msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
443   int flag;
444   FILE *pidfile;
445   char *pidname= (char *)".sockfilt.pid";
446   int rc;
447   int arg=1;
448   bool ok = FALSE;
449   enum sockmode mode = PASSIVE_LISTEN; /* default */
450
451   while(argc>arg) {
452     if(!strcmp("--version", argv[arg])) {
453       printf("sockfilt IPv4%s\n",
454 #ifdef ENABLE_IPV6
455              "/IPv6"
456 #else
457              ""
458 #endif
459              );
460       return 0;
461     }
462     else if(!strcmp("--pidfile", argv[arg])) {
463       arg++;
464       if(argc>arg)
465         pidname = argv[arg++];
466     }
467     else if(!strcmp("--logfile", argv[arg])) {
468       arg++;
469       if(argc>arg)
470         serverlogfile = argv[arg++];
471     }
472     else if(!strcmp("--ipv6", argv[arg])) {
473 #ifdef ENABLE_IPV6
474       use_ipv6=TRUE;
475 #endif
476       arg++;
477     }
478     else if(!strcmp("--ipv4", argv[arg])) {
479       /* for completeness, we support this option as well */
480       use_ipv6=FALSE;
481       arg++;
482     }
483     else if(!strcmp("--port", argv[arg])) {
484       arg++;
485       if(argc>arg) {
486         port = (unsigned short)atoi(argv[arg]);
487         arg++;
488       }
489     }
490     else if(!strcmp("--connect", argv[arg])) {
491       /* Asked to actively connect to the specified local port instead of
492          doing a passive server-style listening. */
493       arg++;
494       if(argc>arg) {
495         connectport = (unsigned short)atoi(argv[arg]);
496         arg++;
497       }
498     }
499     else {
500       puts("Usage: sockfilt [option]\n"
501            " --version\n"
502            " --logfile [file]\n"
503            " --pidfile [file]\n"
504            " --ipv4\n"
505            " --ipv6\n"
506            " --port [port]");
507       return 0;
508     }
509   }
510
511 #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
512   win32_init();
513   atexit(win32_cleanup);
514 #else
515
516 #ifdef SIGPIPE
517 #ifdef HAVE_SIGNAL
518   signal(SIGPIPE, sigpipe_handler);
519 #endif
520 #ifdef HAVE_SIGINTERRUPT
521   siginterrupt(SIGPIPE, 1);
522 #endif
523 #endif
524 #endif
525
526 #ifdef ENABLE_IPV6
527   if(!use_ipv6)
528 #endif
529     sock = socket(AF_INET, SOCK_STREAM, 0);
530 #ifdef ENABLE_IPV6
531   else
532     sock = socket(AF_INET6, SOCK_STREAM, 0);
533 #endif
534
535   if (sock < 0) {
536     perror("opening stream socket");
537     logmsg("Error opening socket");
538     return 1;
539   }
540
541   if(connectport) {
542     /* Active mode, we should connect to the given port number */
543     mode = ACTIVE;
544 #ifdef ENABLE_IPV6
545     if(!use_ipv6) {
546 #endif
547       memset(&me, 0, sizeof(me));
548       me.sin_family = AF_INET;
549       me.sin_port = htons(connectport);
550       me.sin_addr.s_addr = INADDR_ANY;
551       Curl_inet_pton(AF_INET, "127.0.0.1", &me.sin_addr);
552
553       rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
554 #ifdef ENABLE_IPV6
555     }
556     else {
557       memset(&me6, 0, sizeof(me6));
558       me6.sin6_family = AF_INET6;
559       me6.sin6_port = htons(connectport);
560       Curl_inet_pton(AF_INET6, "::1", &me6.sin6_addr);
561
562       rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
563     }
564 #endif /* ENABLE_IPV6 */
565     if(rc) {
566       perror("connecting stream socket");
567       logmsg("Error connecting to port %d", port);
568       return 1;
569     }
570     logmsg("====> Client connect");
571     msgsock = sock; /* use this as stream */
572   }
573   else {
574     /* passive daemon style */
575
576     flag = 1;
577     if (setsockopt
578         (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
579          sizeof(int)) < 0) {
580       perror("setsockopt(SO_REUSEADDR)");
581     }
582
583 #ifdef ENABLE_IPV6
584     if(!use_ipv6) {
585 #endif
586       me.sin_family = AF_INET;
587       me.sin_addr.s_addr = INADDR_ANY;
588       me.sin_port = htons(port);
589       rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
590 #ifdef ENABLE_IPV6
591     }
592     else {
593       memset(&me6, 0, sizeof(struct sockaddr_in6));
594       me6.sin6_family = AF_INET6;
595       me6.sin6_addr = in6addr_any;
596       me6.sin6_port = htons(port);
597       rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
598     }
599 #endif /* ENABLE_IPV6 */
600     if(rc < 0) {
601       perror("binding stream socket");
602       logmsg("Error binding socket");
603       return 1;
604     }
605
606     if(!port) {
607       /* The system picked a port number, now figure out which port we actually
608          got */
609       /* we succeeded to bind */
610       struct sockaddr_in add;
611       socklen_t socksize = sizeof(add);
612
613       if(getsockname(sock, (struct sockaddr *) &add,
614                      &socksize)<0) {
615         fprintf(stderr, "getsockname() failed");
616         return 1;
617       }
618       port = ntohs(add.sin_port);
619     }
620
621     /* start accepting connections */
622     listen(sock, 1);
623
624   }
625
626   logmsg("Running IPv%d version",
627          (use_ipv6?6:4));
628
629   if(connectport)
630     logmsg("Connected to port %d", connectport);
631   else
632     logmsg("Listening on port %d", port);
633
634   pidfile = fopen(pidname, "w");
635   if(pidfile) {
636     int pid = (int)getpid();
637     fprintf(pidfile, "%d\n", pid);
638     fclose(pidfile);
639     logmsg("Wrote pid %d to %s", pid, pidname);
640   }
641   else
642     fprintf(stderr, "Couldn't write pid file\n");
643
644   do {
645     ok = juggle(&msgsock, sock, &mode);
646   } while(ok);
647
648   sclose(sock);
649
650   return 0;
651 }
652