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