silense a warning
[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 /* include memdebug.h last */
87 #include "memdebug.h"
88
89 #define DEFAULT_PORT 8999
90
91 #ifndef DEFAULT_LOGFILE
92 #define DEFAULT_LOGFILE "log/sockfilt.log"
93 #endif
94
95 #ifdef SIGPIPE
96 static volatile int sigpipe;  /* Why? It's not used */
97 #endif
98
99 const char *serverlogfile = (char *)DEFAULT_LOGFILE;
100
101 static void lograw(unsigned char *buffer, int len)
102 {
103   char data[120];
104   int i;
105   unsigned char *ptr = buffer;
106   char *optr = data;
107   int width=0;
108
109   for(i=0; i<len; i++) {
110     switch(ptr[i]) {
111     case '\n':
112       sprintf(optr, "\\n");
113       width += 2;
114       optr += 2;
115       break;
116     case '\r':
117       sprintf(optr, "\\r");
118       width += 2;
119       optr += 2;
120       break;
121     default:
122       sprintf(optr, "%c", (isgraph(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
123       width++;
124       optr++;
125       break;
126     }
127
128     if(width>60) {
129       logmsg("'%s'", data);
130       width = 0;
131       optr = data;
132     }
133   }
134   if(width)
135     logmsg("'%s'", data);
136 }
137
138 #ifdef SIGPIPE
139 static void sigpipe_handler(int sig)
140 {
141   (void)sig; /* prevent warning */
142   sigpipe = 1;
143 }
144 #endif
145
146 char use_ipv6=FALSE;
147 unsigned short port = DEFAULT_PORT;
148 unsigned short connectport = 0; /* if non-zero, we activate this mode */
149
150 enum sockmode {
151   PASSIVE_LISTEN,    /* as a server waiting for connections */
152   PASSIVE_CONNECT,   /* as a server, connected to a client */
153   ACTIVE,            /* as a client, connected to a server */
154   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
155 };
156
157 /*
158   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
159
160   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
161   accept()
162 */
163 static int juggle(curl_socket_t *sockfdp,
164                   curl_socket_t listenfd,
165                   enum sockmode *mode)
166 {
167   struct timeval timeout;
168   fd_set fds_read;
169   fd_set fds_write;
170   fd_set fds_err;
171   curl_socket_t maxfd;
172   int r;
173   unsigned char buffer[256]; /* FIX: bigger buffer */
174   char data[256];
175   curl_socket_t sockfd;
176
177   timeout.tv_sec = 120;
178   timeout.tv_usec = 0;
179
180   FD_ZERO(&fds_read);
181   FD_ZERO(&fds_write);
182   FD_ZERO(&fds_err);
183
184   FD_SET(fileno(stdin), &fds_read);
185
186   switch(*mode) {
187   case PASSIVE_LISTEN:
188     /* server mode */
189     sockfd = listenfd;
190     /* there's always a socket to wait for */
191     FD_SET(sockfd, &fds_read);
192     maxfd = sockfd;
193     break;
194
195   case PASSIVE_CONNECT:
196     sockfd = *sockfdp;
197     if(-1 == sockfd) {
198       /* eeek, we are supposedly connected and then this cannot be -1 ! */
199       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
200       maxfd = 0; /* stdin */
201     }
202     else {
203       /* there's always a socket to wait for */
204       FD_SET(sockfd, &fds_read);
205       maxfd = sockfd;
206     }
207     break;
208
209   case ACTIVE:
210     sockfd = *sockfdp;
211
212     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
213     if(sockfd != CURL_SOCKET_BAD) {
214       FD_SET(sockfd, &fds_read);
215       maxfd = sockfd;
216     }
217     else {
218       logmsg("No socket to read on");
219       maxfd = 0;
220     }
221     break;
222
223   case ACTIVE_DISCONNECT:
224     logmsg("disconnected, no socket to read on");
225     maxfd = 0;
226     sockfd = CURL_SOCKET_BAD;
227     break;
228   }
229
230   do {
231     r = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
232   } while((r == -1) && (ourerrno() == EINTR));
233
234   switch(r) {
235   case -1:
236     return FALSE;
237
238   case 0: /* timeout! */
239     return TRUE;
240   }
241
242
243   if(FD_ISSET(fileno(stdin), &fds_read)) {
244     ssize_t nread;
245     /* read from stdin, commands/data to be dealt with and possibly passed on
246        to the socket
247
248        protocol:
249
250        4 letter command + LF [mandatory]
251
252        4-digit hexadecimal data length + LF [if the command takes data]
253        data                       [the data being as long as set above]
254
255        Commands:
256
257        DATA - plain pass-thru data
258     */
259     nread = read(fileno(stdin), buffer, 5);
260     if(5 == nread) {
261
262       logmsg("Received %c%c%c%c (on stdin)",
263              buffer[0], buffer[1], buffer[2], buffer[3] );
264
265       if(!memcmp("PING", buffer, 4)) {
266         /* send reply on stdout, just proving we are alive */
267         write(fileno(stdout), "PONG\n", 5);
268       }
269
270       else if(!memcmp("PORT", buffer, 4)) {
271         /* question asking us what PORT number we are listening to.
272            Replies with PORT with "IPv[num]/[port]" */
273         sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, port);
274         r = (int)strlen((char *)buffer);
275         sprintf(data, "PORT\n%04x\n", r);
276         write(fileno(stdout), data, 10);
277         write(fileno(stdout), buffer, r);
278       }
279       else if(!memcmp("QUIT", buffer, 4)) {
280         /* just die */
281         logmsg("quits");
282         return FALSE;
283       }
284       else if(!memcmp("DATA", buffer, 4)) {
285         /* data IN => data OUT */
286         long len;
287
288         if(5 != read(fileno(stdin), buffer, 5))
289           return FALSE;
290
291         len = strtol((char *)buffer, NULL, 16);
292         if(len != read(fileno(stdin), buffer, len))
293           return FALSE;
294
295         logmsg("> %d bytes data, server => client", len);
296         lograw(buffer, (int)len);
297
298         if(*mode == PASSIVE_LISTEN) {
299           logmsg("*** We are disconnected!");
300           write(fileno(stdout), "DISC\n", 5);
301         }
302         else
303           /* send away on the socket */
304           swrite(sockfd, buffer, len);
305       }
306       else if(!memcmp("DISC", buffer, 4)) {
307         /* disconnect! */
308         write(fileno(stdout), "DISC\n", 5);
309         if(sockfd != CURL_SOCKET_BAD) {
310           logmsg("====> Client forcibly disconnected");
311           sclose(sockfd);
312           *sockfdp = CURL_SOCKET_BAD;
313           if(*mode == PASSIVE_CONNECT)
314             *mode = PASSIVE_LISTEN;
315           else
316             *mode = ACTIVE_DISCONNECT;
317         }
318         else
319           logmsg("attempt to close already dead connection");
320         return TRUE;
321       }
322     }
323     else if(nread == -1){
324       logmsg("read %d from stdin, exiting", (int)nread);
325       return FALSE;
326     }
327   }
328
329   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
330
331     if(*mode == PASSIVE_LISTEN) {
332       /* there's no stream set up yet, this is an indication that there's a
333          client connecting. */
334       sockfd = accept(sockfd, NULL, NULL);
335       if(-1 == sockfd)
336         logmsg("accept() failed\n");
337       else {
338         logmsg("====> Client connect");
339         write(fileno(stdout), "CNCT\n", 5);
340         *sockfdp = sockfd; /* store the new socket */
341         *mode = PASSIVE_CONNECT; /* we have connected */
342       }
343       return TRUE;
344     }
345
346     /* read from socket, pass on data to stdout */
347     r = sread(sockfd, buffer, sizeof(buffer));
348
349     if(r <= 0) {
350       logmsg("====> Client disconnect");
351       write(fileno(stdout), "DISC\n", 5);
352       sclose(sockfd);
353       *sockfdp = CURL_SOCKET_BAD;
354       if(*mode == PASSIVE_CONNECT)
355         *mode = PASSIVE_LISTEN;
356       else
357         *mode = ACTIVE_DISCONNECT;
358       return TRUE;
359     }
360
361     sprintf(data, "DATA\n%04x\n", r);
362     write(fileno(stdout), data, 10);
363     write(fileno(stdout), buffer, r);
364
365     logmsg("< %d bytes data, client => server", r);
366     lograw(buffer, r);
367   }
368
369   return TRUE;
370 }
371
372 static curl_socket_t sockdaemon(curl_socket_t sock,
373                                 unsigned short *port)
374 {
375   /* passive daemon style */
376   struct sockaddr_in me;
377 #ifdef ENABLE_IPV6
378   struct sockaddr_in6 me6;
379 #endif /* ENABLE_IPV6 */
380   int flag = 1;
381   int rc;
382
383   if (setsockopt
384       (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
385        sizeof(int)) < 0) {
386     perror("setsockopt(SO_REUSEADDR)");
387   }
388
389 #ifdef ENABLE_IPV6
390   if(!use_ipv6) {
391 #endif
392     me.sin_family = AF_INET;
393     me.sin_addr.s_addr = INADDR_ANY;
394     me.sin_port = htons(*port);
395     rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
396 #ifdef ENABLE_IPV6
397   }
398   else {
399     memset(&me6, 0, sizeof(struct sockaddr_in6));
400     me6.sin6_family = AF_INET6;
401     me6.sin6_addr = in6addr_any;
402     me6.sin6_port = htons(*port);
403     rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
404   }
405 #endif /* ENABLE_IPV6 */
406   if(rc < 0) {
407     perror("binding stream socket");
408     logmsg("Error binding socket");
409     return CURL_SOCKET_BAD;
410   }
411
412   if(!*port) {
413     /* The system picked a port number, now figure out which port we actually
414        got */
415     /* we succeeded to bind */
416     struct sockaddr_in add;
417     socklen_t socksize = sizeof(add);
418
419     if(getsockname(sock, (struct sockaddr *) &add,
420                    &socksize)<0) {
421       fprintf(stderr, "getsockname() failed");
422       return CURL_SOCKET_BAD;
423     }
424     *port = ntohs(add.sin_port);
425   }
426
427   /* start accepting connections */
428   listen(sock, 4);
429
430   return sock;
431 }
432
433 static curl_socket_t mksock(bool use_ipv6)
434 {
435   curl_socket_t sock;
436 #ifdef ENABLE_IPV6
437   if(!use_ipv6)
438 #else
439     (void)use_ipv6;
440 #endif
441   sock = socket(AF_INET, SOCK_STREAM, 0);
442 #ifdef ENABLE_IPV6
443   else
444     sock = socket(AF_INET6, SOCK_STREAM, 0);
445 #endif
446
447   if (sock < 0) {
448     perror("opening stream socket");
449     logmsg("Error opening socket");
450     return CURL_SOCKET_BAD;
451   }
452
453   return sock;
454 }
455
456
457 int main(int argc, char *argv[])
458 {
459   struct sockaddr_in me;
460 #ifdef ENABLE_IPV6
461   struct sockaddr_in6 me6;
462 #endif /* ENABLE_IPV6 */
463   curl_socket_t sock;
464   curl_socket_t msgsock;
465   FILE *pidfile;
466   char *pidname= (char *)".sockfilt.pid";
467   int rc;
468   int arg=1;
469   enum sockmode mode = PASSIVE_LISTEN; /* default */
470
471   while(argc>arg) {
472     if(!strcmp("--version", argv[arg])) {
473       printf("sockfilt IPv4%s\n",
474 #ifdef ENABLE_IPV6
475              "/IPv6"
476 #else
477              ""
478 #endif
479              );
480       return 0;
481     }
482     else if(!strcmp("--pidfile", argv[arg])) {
483       arg++;
484       if(argc>arg)
485         pidname = argv[arg++];
486     }
487     else if(!strcmp("--logfile", argv[arg])) {
488       arg++;
489       if(argc>arg)
490         serverlogfile = argv[arg++];
491     }
492     else if(!strcmp("--ipv6", argv[arg])) {
493 #ifdef ENABLE_IPV6
494       use_ipv6=TRUE;
495 #endif
496       arg++;
497     }
498     else if(!strcmp("--ipv4", argv[arg])) {
499       /* for completeness, we support this option as well */
500       use_ipv6=FALSE;
501       arg++;
502     }
503     else if(!strcmp("--port", argv[arg])) {
504       arg++;
505       if(argc>arg) {
506         port = (unsigned short)atoi(argv[arg]);
507         arg++;
508       }
509     }
510     else if(!strcmp("--connect", argv[arg])) {
511       /* Asked to actively connect to the specified local port instead of
512          doing a passive server-style listening. */
513       arg++;
514       if(argc>arg) {
515         connectport = (unsigned short)atoi(argv[arg]);
516         arg++;
517       }
518     }
519     else {
520       puts("Usage: sockfilt [option]\n"
521            " --version\n"
522            " --logfile [file]\n"
523            " --pidfile [file]\n"
524            " --ipv4\n"
525            " --ipv6\n"
526            " --port [port]");
527       return 0;
528     }
529   }
530
531 #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
532   win32_init();
533   atexit(win32_cleanup);
534 #else
535
536 #ifdef SIGPIPE
537 #ifdef HAVE_SIGNAL
538   signal(SIGPIPE, sigpipe_handler);
539 #endif
540 #ifdef HAVE_SIGINTERRUPT
541   siginterrupt(SIGPIPE, 1);
542 #endif
543 #endif
544 #endif
545
546
547   sock = mksock(use_ipv6);
548
549   if(connectport) {
550     /* Active mode, we should connect to the given port number */
551     mode = ACTIVE;
552 #ifdef ENABLE_IPV6
553     if(!use_ipv6) {
554 #endif
555       memset(&me, 0, sizeof(me));
556       me.sin_family = AF_INET;
557       me.sin_port = htons(connectport);
558       me.sin_addr.s_addr = INADDR_ANY;
559       Curl_inet_pton(AF_INET, "127.0.0.1", &me.sin_addr);
560
561       rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
562 #ifdef ENABLE_IPV6
563     }
564     else {
565       memset(&me6, 0, sizeof(me6));
566       me6.sin6_family = AF_INET6;
567       me6.sin6_port = htons(connectport);
568       Curl_inet_pton(AF_INET6, "::1", &me6.sin6_addr);
569
570       rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
571     }
572 #endif /* ENABLE_IPV6 */
573     if(rc) {
574       perror("connecting stream socket");
575       logmsg("Error connecting to port %d", port);
576       return 1;
577     }
578     logmsg("====> Client connect");
579     msgsock = sock; /* use this as stream */
580   }
581   else {
582     /* passive daemon style */
583     sock = sockdaemon(sock, &port);
584     if(CURL_SOCKET_BAD == sock)
585       return 1;
586     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
587   }
588
589   logmsg("Running IPv%d version",
590          (use_ipv6?6:4));
591
592   if(connectport)
593     logmsg("Connected to port %d", connectport);
594   else
595     logmsg("Listening on port %d", port);
596
597   pidfile = fopen(pidname, "w");
598   if(pidfile) {
599     int pid = (int)getpid();
600     fprintf(pidfile, "%d\n", pid);
601     fclose(pidfile);
602     logmsg("Wrote pid %d to %s", pid, pidname);
603   }
604   else
605     fprintf(stderr, "Couldn't write pid file\n");
606
607   while(juggle(&msgsock, sock, &mode));
608
609   sclose(sock);
610
611   return 0;
612 }
613