juggle() actually returns bool.
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2008, 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, ssize_t len)
102 {
103   char data[120];
104   ssize_t i;
105   unsigned char *ptr = buffer;
106   char *optr = data;
107   ssize_t 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 bool 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 bool 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 sockfd;
172   curl_socket_t maxfd;
173   ssize_t rc;
174   ssize_t nread_stdin;
175   ssize_t nread_socket;
176   ssize_t bytes_written;
177   ssize_t buffer_len;
178
179  /* 'buffer' is this excessively large only to be able to support things like
180     test 1003 which tests exceedingly large server response lines */
181   unsigned char buffer[17010];
182   char data[16];
183
184 #ifdef HAVE_GETPPID
185   /* As a last resort, quit if sockfilt process becomes orphan. Just in case
186      parent ftpserver process has died without killing its sockfilt children */
187   if(getppid() <= 1)
188     return FALSE;
189 #endif
190
191   timeout.tv_sec = 120;
192   timeout.tv_usec = 0;
193
194   FD_ZERO(&fds_read);
195   FD_ZERO(&fds_write);
196   FD_ZERO(&fds_err);
197
198   FD_SET(fileno(stdin), &fds_read);
199
200   switch(*mode) {
201
202   case PASSIVE_LISTEN:
203
204     /* server mode */
205     sockfd = listenfd;
206     /* there's always a socket to wait for */
207     FD_SET(sockfd, &fds_read);
208     maxfd = sockfd;
209     break;
210
211   case PASSIVE_CONNECT:
212
213     sockfd = *sockfdp;
214     if(CURL_SOCKET_BAD == sockfd) {
215       /* eeek, we are supposedly connected and then this cannot be -1 ! */
216       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
217       maxfd = 0; /* stdin */
218     }
219     else {
220       /* there's always a socket to wait for */
221       FD_SET(sockfd, &fds_read);
222       maxfd = sockfd;
223     }
224     break;
225
226   case ACTIVE:
227
228     sockfd = *sockfdp;
229     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
230     if(CURL_SOCKET_BAD != sockfd) {
231       FD_SET(sockfd, &fds_read);
232       maxfd = sockfd;
233     }
234     else {
235       logmsg("No socket to read on");
236       maxfd = 0;
237     }
238     break;
239
240   case ACTIVE_DISCONNECT:
241
242     logmsg("disconnected, no socket to read on");
243     maxfd = 0;
244     sockfd = CURL_SOCKET_BAD;
245     break;
246
247   } /* switch(*mode) */
248
249   do {
250     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
251   } while((rc == -1) && (SOCKERRNO == EINTR));
252
253   switch(rc) {
254   case -1:
255     return FALSE;
256
257   case 0: /* timeout! */
258     return TRUE;
259   }
260
261
262   if(FD_ISSET(fileno(stdin), &fds_read)) {
263     /* read from stdin, commands/data to be dealt with and possibly passed on
264        to the socket
265
266        protocol:
267
268        4 letter command + LF [mandatory]
269
270        4-digit hexadecimal data length + LF [if the command takes data]
271        data                       [the data being as long as set above]
272
273        Commands:
274
275        DATA - plain pass-thru data
276     */
277     nread_stdin = read(fileno(stdin), buffer, 5);
278     if(5 == nread_stdin) {
279
280       logmsg("Received %c%c%c%c (on stdin)",
281              buffer[0], buffer[1], buffer[2], buffer[3] );
282
283       if(!memcmp("PING", buffer, 4)) {
284         /* send reply on stdout, just proving we are alive */
285         write(fileno(stdout), "PONG\n", 5);
286       }
287
288       else if(!memcmp("PORT", buffer, 4)) {
289         /* Question asking us what PORT number we are listening to.
290            Replies to PORT with "IPv[num]/[port]" */
291         sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
292         buffer_len = (ssize_t)strlen((char *)buffer);
293         snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
294         write(fileno(stdout), data, 10);
295         write(fileno(stdout), buffer, buffer_len);
296       }
297       else if(!memcmp("QUIT", buffer, 4)) {
298         /* just die */
299         logmsg("quits");
300         return FALSE;
301       }
302       else if(!memcmp("DATA", buffer, 4)) {
303         /* data IN => data OUT */
304
305         if(5 != read(fileno(stdin), buffer, 5))
306           return FALSE;
307         buffer[5] = '\0';
308
309         buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
310         if (buffer_len > (ssize_t)sizeof(buffer)) {
311           logmsg("ERROR: Buffer size (%ld bytes) too small for data size "
312                  "(%ld bytes)", (long)sizeof(buffer), (long)buffer_len);
313           return FALSE;
314         }
315         logmsg("> %d bytes data, server => client", buffer_len);
316
317         /*
318          * To properly support huge data chunks, we need to repeat the call
319          * to read() until we're done or it fails.
320          */
321         nread_stdin = 0;
322         do {
323           /* get data in the buffer at the correct position */
324           rc = read(fileno(stdin), &buffer[nread_stdin],
325                     buffer_len - nread_stdin);
326           logmsg("read %d bytes", rc);
327           if(rc <= 0)
328             return FALSE;
329           nread_stdin += rc;
330         } while (nread_stdin < buffer_len);
331
332         lograw(buffer, buffer_len);
333
334         if(*mode == PASSIVE_LISTEN) {
335           logmsg("*** We are disconnected!");
336           write(fileno(stdout), "DISC\n", 5);
337         }
338         else {
339           /* send away on the socket */
340           bytes_written = swrite(sockfd, buffer, buffer_len);
341           if(bytes_written != buffer_len) {
342             logmsg("Not all data was sent. Bytes to send: %d sent: %d", 
343                    buffer_len, bytes_written);
344           }
345         }
346       }
347       else if(!memcmp("DISC", buffer, 4)) {
348         /* disconnect! */
349         write(fileno(stdout), "DISC\n", 5);
350         if(sockfd != CURL_SOCKET_BAD) {
351           logmsg("====> Client forcibly disconnected");
352           sclose(sockfd);
353           *sockfdp = CURL_SOCKET_BAD;
354           if(*mode == PASSIVE_CONNECT)
355             *mode = PASSIVE_LISTEN;
356           else
357             *mode = ACTIVE_DISCONNECT;
358         }
359         else
360           logmsg("attempt to close already dead connection");
361         return TRUE;
362       }
363     }
364     else if(-1 == nread_stdin) {
365       logmsg("read %d from stdin, exiting", nread_stdin);
366       return FALSE;
367     }
368   }
369
370
371   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
372
373     if(*mode == PASSIVE_LISTEN) {
374       /* there's no stream set up yet, this is an indication that there's a
375          client connecting. */
376       sockfd = accept(sockfd, NULL, NULL);
377       if(CURL_SOCKET_BAD == sockfd)
378         logmsg("accept() failed");
379       else {
380         logmsg("====> Client connect");
381         write(fileno(stdout), "CNCT\n", 5);
382         *sockfdp = sockfd; /* store the new socket */
383         *mode = PASSIVE_CONNECT; /* we have connected */
384       }
385       return TRUE;
386     }
387
388     /* read from socket, pass on data to stdout */
389     nread_socket = sread(sockfd, buffer, sizeof(buffer));
390
391     if(nread_socket <= 0) {
392       logmsg("====> Client disconnect");
393       write(fileno(stdout), "DISC\n", 5);
394       sclose(sockfd);
395       *sockfdp = CURL_SOCKET_BAD;
396       if(*mode == PASSIVE_CONNECT)
397         *mode = PASSIVE_LISTEN;
398       else
399         *mode = ACTIVE_DISCONNECT;
400       return TRUE;
401     }
402
403     snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
404     write(fileno(stdout), data, 10);
405     write(fileno(stdout), buffer, nread_socket);
406
407     logmsg("< %d bytes data, client => server", nread_socket);
408     lograw(buffer, nread_socket);
409   }
410
411   return TRUE;
412 }
413
414 static curl_socket_t sockdaemon(curl_socket_t sock,
415                                 unsigned short *listenport)
416 {
417   /* passive daemon style */
418   struct sockaddr_in me;
419 #ifdef ENABLE_IPV6
420   struct sockaddr_in6 me6;
421 #endif /* ENABLE_IPV6 */
422   int flag = 1;
423   int rc;
424   int totdelay = 0;
425   int maxretr = 10;
426   int delay= 20;
427   int attempt = 0;
428   int error = 0;
429
430   do {
431     attempt++;
432     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
433          (void *)&flag, sizeof(flag));
434     if(rc) {
435       error = SOCKERRNO;
436       if(maxretr) {
437         rc = wait_ms(delay);
438         if(rc) {
439           /* should not happen */
440           error = SOCKERRNO;
441           logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
442           sclose(sock);
443           return CURL_SOCKET_BAD;
444         }
445         totdelay += delay;
446         delay *= 2; /* double the sleep for next attempt */
447       }
448     }
449   } while(rc && maxretr--);
450
451   if(rc) {
452     logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
453            attempt, totdelay, error, strerror(error));
454     logmsg("Continuing anyway...");
455   }
456
457 #ifdef ENABLE_IPV6
458   if(!use_ipv6) {
459 #endif
460     memset(&me, 0, sizeof(me));
461     me.sin_family = AF_INET;
462     me.sin_addr.s_addr = INADDR_ANY;
463     me.sin_port = htons(*listenport);
464     rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
465 #ifdef ENABLE_IPV6
466   }
467   else {
468     memset(&me6, 0, sizeof(me6));
469     me6.sin6_family = AF_INET6;
470     me6.sin6_addr = in6addr_any;
471     me6.sin6_port = htons(*listenport);
472     rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
473   }
474 #endif /* ENABLE_IPV6 */
475   if(rc) {
476     error = SOCKERRNO;
477     logmsg("Error binding socket: (%d) %s", error, strerror(error));
478     sclose(sock);
479     return CURL_SOCKET_BAD;
480   }
481
482   if(!*listenport) {
483     /* The system picked a port number, now figure out which port we actually
484        got */
485     /* we succeeded to bind */
486     struct sockaddr_in add;
487     socklen_t socksize = sizeof(add);
488
489     if(getsockname(sock, (struct sockaddr *) &add,
490                    &socksize)<0) {
491       error = SOCKERRNO;
492       logmsg("getsockname() failed with error: (%d) %s",
493              error, strerror(error));
494       sclose(sock);
495       return CURL_SOCKET_BAD;
496     }
497     *listenport = ntohs(add.sin_port);
498   }
499
500   /* start accepting connections */
501   rc = listen(sock, 5);
502   if(0 != rc) {
503     error = SOCKERRNO;
504     logmsg("listen() failed with error: (%d) %s",
505            error, strerror(error));
506     sclose(sock);
507     return CURL_SOCKET_BAD;
508   }
509
510   return sock;
511 }
512
513
514 int main(int argc, char *argv[])
515 {
516   struct sockaddr_in me;
517 #ifdef ENABLE_IPV6
518   struct sockaddr_in6 me6;
519 #endif /* ENABLE_IPV6 */
520   curl_socket_t sock;
521   curl_socket_t msgsock;
522   FILE *pidfile;
523   char *pidname= (char *)".sockfilt.pid";
524   int rc;
525   int error;
526   int arg=1;
527   enum sockmode mode = PASSIVE_LISTEN; /* default */
528   const char *addr = NULL;
529
530   while(argc>arg) {
531     if(!strcmp("--version", argv[arg])) {
532       printf("sockfilt IPv4%s\n",
533 #ifdef ENABLE_IPV6
534              "/IPv6"
535 #else
536              ""
537 #endif
538              );
539       return 0;
540     }
541     else if(!strcmp("--pidfile", argv[arg])) {
542       arg++;
543       if(argc>arg)
544         pidname = argv[arg++];
545     }
546     else if(!strcmp("--logfile", argv[arg])) {
547       arg++;
548       if(argc>arg)
549         serverlogfile = argv[arg++];
550     }
551     else if(!strcmp("--ipv6", argv[arg])) {
552 #ifdef ENABLE_IPV6
553       use_ipv6=TRUE;
554 #endif
555       arg++;
556     }
557     else if(!strcmp("--ipv4", argv[arg])) {
558       /* for completeness, we support this option as well */
559       use_ipv6=FALSE;
560       arg++;
561     }
562     else if(!strcmp("--port", argv[arg])) {
563       arg++;
564       if(argc>arg) {
565         port = (unsigned short)atoi(argv[arg]);
566         arg++;
567       }
568     }
569     else if(!strcmp("--connect", argv[arg])) {
570       /* Asked to actively connect to the specified local port instead of
571          doing a passive server-style listening. */
572       arg++;
573       if(argc>arg) {
574         connectport = (unsigned short)atoi(argv[arg]);
575         arg++;
576       }
577     }
578     else if(!strcmp("--addr", argv[arg])) {
579       /* Set an IP address to use with --connect; otherwise use localhost */
580       arg++;
581       if(argc>arg) {
582         addr = argv[arg];
583         arg++;
584       }
585     }
586     else {
587       puts("Usage: sockfilt [option]\n"
588            " --version\n"
589            " --logfile [file]\n"
590            " --pidfile [file]\n"
591            " --ipv4\n"
592            " --ipv6\n"
593            " --port [port]\n"
594            " --connect [port]\n"
595            " --addr [address]");
596       return 0;
597     }
598   }
599
600 #ifdef WIN32
601   win32_init();
602   atexit(win32_cleanup);
603 #else
604
605 #ifdef SIGPIPE
606 #ifdef HAVE_SIGNAL
607   signal(SIGPIPE, sigpipe_handler);
608 #endif
609 #ifdef HAVE_SIGINTERRUPT
610   siginterrupt(SIGPIPE, 1);
611 #endif
612 #endif
613 #endif
614
615 #ifdef ENABLE_IPV6
616   if(!use_ipv6)
617 #endif
618     sock = socket(AF_INET, SOCK_STREAM, 0);
619 #ifdef ENABLE_IPV6
620   else
621     sock = socket(AF_INET6, SOCK_STREAM, 0);
622 #endif
623
624   if(CURL_SOCKET_BAD == sock) {
625     error = SOCKERRNO;
626     logmsg("Error creating socket: (%d) %s",
627            error, strerror(error));
628     return 1;
629   }
630
631   if(connectport) {
632     /* Active mode, we should connect to the given port number */
633     mode = ACTIVE;
634 #ifdef ENABLE_IPV6
635     if(!use_ipv6) {
636 #endif
637       memset(&me, 0, sizeof(me));
638       me.sin_family = AF_INET;
639       me.sin_port = htons(connectport);
640       me.sin_addr.s_addr = INADDR_ANY;
641       if (!addr)
642         addr = "127.0.0.1";
643       Curl_inet_pton(AF_INET, addr, &me.sin_addr);
644
645       rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
646 #ifdef ENABLE_IPV6
647     }
648     else {
649       memset(&me6, 0, sizeof(me6));
650       me6.sin6_family = AF_INET6;
651       me6.sin6_port = htons(connectport);
652       if (!addr)
653         addr = "::1";
654       Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
655
656       rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
657     }
658 #endif /* ENABLE_IPV6 */
659     if(rc) {
660       error = SOCKERRNO;
661       logmsg("Error connecting to port %d: (%d) %s",
662              port, error, strerror(error));
663       sclose(sock);
664       return 1;
665     }
666     logmsg("====> Client connect");
667     msgsock = sock; /* use this as stream */
668   }
669   else {
670     /* passive daemon style */
671     sock = sockdaemon(sock, &port);
672     if(CURL_SOCKET_BAD == sock)
673       return 1;
674     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
675   }
676
677   logmsg("Running IPv%d version",
678          (use_ipv6?6:4));
679
680   if(connectport)
681     logmsg("Connected to port %d", connectport);
682   else
683     logmsg("Listening on port %d", port);
684
685   pidfile = fopen(pidname, "w");
686   if(pidfile) {
687     long pid = (long)getpid();
688     fprintf(pidfile, "%ld\n", pid);
689     fclose(pidfile);
690     logmsg("Wrote pid %ld to %s", pid, pidname);
691   }
692   else {
693     error = ERRNO;
694     logmsg("fopen() failed with error: %d %s", error, strerror(error));
695     logmsg("Error opening file: %s", pidname);
696     logmsg("Couldn't write pid file");
697     sclose(sock);
698     return 1;
699   }
700
701   while(juggle(&msgsock, sock, &mode));
702
703   sclose(sock);
704
705   return 0;
706 }
707