d9243319fa60629628efe207b56f9557757a14fc
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2013, 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  ***************************************************************************/
22 #include "server_setup.h"
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
50 /*
51  * Signal handling notes for sockfilt
52  * ----------------------------------
53  *
54  * This program is a single-threaded process.
55  *
56  * This program is intended to be highly portable and as such it must be kept as
57  * simple as possible, due to this the only signal handling mechanisms used will
58  * be those of ANSI C, and used only in the most basic form which is good enough
59  * for the purpose of this program.
60  *
61  * For the above reason and the specific needs of this program signals SIGHUP,
62  * SIGPIPE and SIGALRM will be simply ignored on systems where this can be done.
63  * If possible, signals SIGINT and SIGTERM will be handled by this program as an
64  * indication to cleanup and finish execution as soon as possible.  This will be
65  * achieved with a single signal handler 'exit_signal_handler' for both signals.
66  *
67  * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal
68  * will just set to one the global var 'got_exit_signal' storing in global var
69  * 'exit_signal' the signal that triggered this change.
70  *
71  * Nothing fancy that could introduce problems is used, the program at certain
72  * points in its normal flow checks if var 'got_exit_signal' is set and in case
73  * this is true it just makes its way out of loops and functions in structured
74  * and well behaved manner to achieve proper program cleanup and termination.
75  *
76  * Even with the above mechanism implemented it is worthwile to note that other
77  * signals might still be received, or that there might be systems on which it
78  * is not possible to trap and ignore some of the above signals.  This implies
79  * that for increased portability and reliability the program must be coded as
80  * if no signal was being ignored or handled at all.  Enjoy it!
81  */
82
83 #ifdef HAVE_SIGNAL_H
84 #include <signal.h>
85 #endif
86 #ifdef HAVE_NETINET_IN_H
87 #include <netinet/in.h>
88 #endif
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
91 #endif
92 #ifdef HAVE_NETDB_H
93 #include <netdb.h>
94 #endif
95 #ifdef USE_WINSOCK
96 #include <conio.h>  /* for _kbhit() used in select_ws() */
97 #endif
98
99 #define ENABLE_CURLX_PRINTF
100 /* make the curlx header define all printf() functions to use the curlx_*
101    versions instead */
102 #include "curlx.h" /* from the private lib dir */
103 #include "getpart.h"
104 #include "inet_pton.h"
105 #include "util.h"
106 #include "server_sockaddr.h"
107 #include "warnless.h"
108
109 /* include memdebug.h last */
110 #include "memdebug.h"
111
112 #ifdef USE_WINSOCK
113 #undef  EINTR
114 #define EINTR    4 /* errno.h value */
115 #undef  EAGAIN
116 #define EAGAIN  11 /* errno.h value */
117 #undef  ENOMEM
118 #define ENOMEM  12 /* errno.h value */
119 #undef  EINVAL
120 #define EINVAL  22 /* errno.h value */
121 #endif
122
123 #define DEFAULT_PORT 8999
124
125 #ifndef DEFAULT_LOGFILE
126 #define DEFAULT_LOGFILE "log/sockfilt.log"
127 #endif
128
129 const char *serverlogfile = DEFAULT_LOGFILE;
130
131 static bool verbose = FALSE;
132 static bool bind_only = FALSE;
133 #ifdef ENABLE_IPV6
134 static bool use_ipv6 = FALSE;
135 #endif
136 static const char *ipv_inuse = "IPv4";
137 static unsigned short port = DEFAULT_PORT;
138 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
139
140 enum sockmode {
141   PASSIVE_LISTEN,    /* as a server waiting for connections */
142   PASSIVE_CONNECT,   /* as a server, connected to a client */
143   ACTIVE,            /* as a client, connected to a server */
144   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
145 };
146
147 /* do-nothing macro replacement for systems which lack siginterrupt() */
148
149 #ifndef HAVE_SIGINTERRUPT
150 #define siginterrupt(x,y) do {} while(0)
151 #endif
152
153 /* vars used to keep around previous signal handlers */
154
155 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
156
157 #ifdef SIGHUP
158 static SIGHANDLER_T old_sighup_handler  = SIG_ERR;
159 #endif
160
161 #ifdef SIGPIPE
162 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
163 #endif
164
165 #ifdef SIGALRM
166 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
167 #endif
168
169 #ifdef SIGINT
170 static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
171 #endif
172
173 #ifdef SIGTERM
174 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
175 #endif
176
177 #if defined(SIGBREAK) && defined(WIN32)
178 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
179 #endif
180
181 /* var which if set indicates that the program should finish execution */
182
183 SIG_ATOMIC_T got_exit_signal = 0;
184
185 /* if next is set indicates the first signal handled in exit_signal_handler */
186
187 static volatile int exit_signal = 0;
188
189 /* signal handler that will be triggered to indicate that the program
190   should finish its execution in a controlled manner as soon as possible.
191   The first time this is called it will set got_exit_signal to one and
192   store in exit_signal the signal that triggered its execution. */
193
194 static RETSIGTYPE exit_signal_handler(int signum)
195 {
196   int old_errno = errno;
197   if(got_exit_signal == 0) {
198     got_exit_signal = 1;
199     exit_signal = signum;
200   }
201   (void)signal(signum, exit_signal_handler);
202   errno = old_errno;
203 }
204
205 static void install_signal_handlers(void)
206 {
207 #ifdef SIGHUP
208   /* ignore SIGHUP signal */
209   if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
210     logmsg("cannot install SIGHUP handler: %s", strerror(errno));
211 #endif
212 #ifdef SIGPIPE
213   /* ignore SIGPIPE signal */
214   if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
215     logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
216 #endif
217 #ifdef SIGALRM
218   /* ignore SIGALRM signal */
219   if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
220     logmsg("cannot install SIGALRM handler: %s", strerror(errno));
221 #endif
222 #ifdef SIGINT
223   /* handle SIGINT signal with our exit_signal_handler */
224   if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
225     logmsg("cannot install SIGINT handler: %s", strerror(errno));
226   else
227     siginterrupt(SIGINT, 1);
228 #endif
229 #ifdef SIGTERM
230   /* handle SIGTERM signal with our exit_signal_handler */
231   if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
232     logmsg("cannot install SIGTERM handler: %s", strerror(errno));
233   else
234     siginterrupt(SIGTERM, 1);
235 #endif
236 #if defined(SIGBREAK) && defined(WIN32)
237   /* handle SIGBREAK signal with our exit_signal_handler */
238   if((old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler)) == SIG_ERR)
239     logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
240   else
241     siginterrupt(SIGBREAK, 1);
242 #endif
243 }
244
245 static void restore_signal_handlers(void)
246 {
247 #ifdef SIGHUP
248   if(SIG_ERR != old_sighup_handler)
249     (void)signal(SIGHUP, old_sighup_handler);
250 #endif
251 #ifdef SIGPIPE
252   if(SIG_ERR != old_sigpipe_handler)
253     (void)signal(SIGPIPE, old_sigpipe_handler);
254 #endif
255 #ifdef SIGALRM
256   if(SIG_ERR != old_sigalrm_handler)
257     (void)signal(SIGALRM, old_sigalrm_handler);
258 #endif
259 #ifdef SIGINT
260   if(SIG_ERR != old_sigint_handler)
261     (void)signal(SIGINT, old_sigint_handler);
262 #endif
263 #ifdef SIGTERM
264   if(SIG_ERR != old_sigterm_handler)
265     (void)signal(SIGTERM, old_sigterm_handler);
266 #endif
267 #if defined(SIGBREAK) && defined(WIN32)
268   if(SIG_ERR != old_sigbreak_handler)
269     (void)signal(SIGBREAK, old_sigbreak_handler);
270 #endif
271 }
272
273 #ifdef WIN32
274 /*
275  * read-wrapper to support reading from stdin on Windows.
276  */
277 static ssize_t read_wincon(int fd, void *buf, size_t count)
278 {
279   HANDLE handle = NULL;
280   DWORD mode, rcount = 0;
281   BOOL success;
282
283   if(fd == fileno(stdin)) {
284     handle = GetStdHandle(STD_INPUT_HANDLE);
285   }
286   else {
287     return read(fd, buf, count);
288   }
289
290   if(GetConsoleMode(handle, &mode)) {
291     success = ReadConsole(handle, buf, count, &rcount, NULL);
292   }
293   else {
294     success = ReadFile(handle, buf, count, &rcount, NULL);
295   }
296   if(success) {
297     return rcount;
298   }
299
300   errno = GetLastError();
301   return -1;
302 }
303 #define read(a,b,c) read_wincon(a,b,c)
304
305 /*
306  * write-wrapper to support writing to stdout and stderr on Windows.
307  */
308 static ssize_t write_wincon(int fd, const void *buf, size_t count)
309 {
310   HANDLE handle = NULL;
311   DWORD mode, wcount = 0;
312   BOOL success;
313
314   if(fd == fileno(stdout)) {
315     handle = GetStdHandle(STD_OUTPUT_HANDLE);
316   }
317   else if(fd == fileno(stderr)) {
318     handle = GetStdHandle(STD_ERROR_HANDLE);
319   }
320   else {
321     return write(fd, buf, count);
322   }
323
324   if(GetConsoleMode(handle, &mode)) {
325     success = WriteConsole(handle, buf, count, &wcount, NULL);
326   }
327   else {
328     success = WriteFile(handle, buf, count, &wcount, NULL);
329   }
330   if(success) {
331     return wcount;
332   }
333
334   errno = GetLastError();
335   return -1;
336 }
337 #define write(a,b,c) write_wincon(a,b,c)
338 #endif
339
340 /*
341  * fullread is a wrapper around the read() function. This will repeat the call
342  * to read() until it actually has read the complete number of bytes indicated
343  * in nbytes or it fails with a condition that cannot be handled with a simple
344  * retry of the read call.
345  */
346
347 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
348 {
349   int error;
350   ssize_t rc;
351   ssize_t nread = 0;
352
353   do {
354     rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
355
356     if(got_exit_signal) {
357       logmsg("signalled to die");
358       return -1;
359     }
360
361     if(rc < 0) {
362       error = errno;
363       if((error == EINTR) || (error == EAGAIN))
364         continue;
365       logmsg("reading from file descriptor: %d,", filedes);
366       logmsg("unrecoverable read() failure: (%d) %s",
367              error, strerror(error));
368       return -1;
369     }
370
371     if(rc == 0) {
372       logmsg("got 0 reading from stdin");
373       return 0;
374     }
375
376     nread += rc;
377
378   } while((size_t)nread < nbytes);
379
380   if(verbose)
381     logmsg("read %zd bytes", nread);
382
383   return nread;
384 }
385
386 /*
387  * fullwrite is a wrapper around the write() function. This will repeat the
388  * call to write() until it actually has written the complete number of bytes
389  * indicated in nbytes or it fails with a condition that cannot be handled
390  * with a simple retry of the write call.
391  */
392
393 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
394 {
395   int error;
396   ssize_t wc;
397   ssize_t nwrite = 0;
398
399   do {
400     wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
401
402     if(got_exit_signal) {
403       logmsg("signalled to die");
404       return -1;
405     }
406
407     if(wc < 0) {
408       error = errno;
409       if((error == EINTR) || (error == EAGAIN))
410         continue;
411       logmsg("writing to file descriptor: %d,", filedes);
412       logmsg("unrecoverable write() failure: (%d) %s",
413              error, strerror(error));
414       return -1;
415     }
416
417     if(wc == 0) {
418       logmsg("put 0 writing to stdout");
419       return 0;
420     }
421
422     nwrite += wc;
423
424   } while((size_t)nwrite < nbytes);
425
426   if(verbose)
427     logmsg("wrote %zd bytes", nwrite);
428
429   return nwrite;
430 }
431
432 /*
433  * read_stdin tries to read from stdin nbytes into the given buffer. This is a
434  * blocking function that will only return TRUE when nbytes have actually been
435  * read or FALSE when an unrecoverable error has been detected. Failure of this
436  * function is an indication that the sockfilt process should terminate.
437  */
438
439 static bool read_stdin(void *buffer, size_t nbytes)
440 {
441   ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
442   if(nread != (ssize_t)nbytes) {
443     logmsg("exiting...");
444     return FALSE;
445   }
446   return TRUE;
447 }
448
449 /*
450  * write_stdout tries to write to stdio nbytes from the given buffer. This is a
451  * blocking function that will only return TRUE when nbytes have actually been
452  * written or FALSE when an unrecoverable error has been detected. Failure of
453  * this function is an indication that the sockfilt process should terminate.
454  */
455
456 static bool write_stdout(const void *buffer, size_t nbytes)
457 {
458   ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
459   if(nwrite != (ssize_t)nbytes) {
460     logmsg("exiting...");
461     return FALSE;
462   }
463   return TRUE;
464 }
465
466 static void lograw(unsigned char *buffer, ssize_t len)
467 {
468   char data[120];
469   ssize_t i;
470   unsigned char *ptr = buffer;
471   char *optr = data;
472   ssize_t width=0;
473
474   for(i=0; i<len; i++) {
475     switch(ptr[i]) {
476     case '\n':
477       sprintf(optr, "\\n");
478       width += 2;
479       optr += 2;
480       break;
481     case '\r':
482       sprintf(optr, "\\r");
483       width += 2;
484       optr += 2;
485       break;
486     default:
487       sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
488       width++;
489       optr++;
490       break;
491     }
492
493     if(width>60) {
494       logmsg("'%s'", data);
495       width = 0;
496       optr = data;
497     }
498   }
499   if(width)
500     logmsg("'%s'", data);
501 }
502
503 #ifdef USE_WINSOCK
504 /*
505  * WinSock select() does not support standard file descriptors,
506  * it can only check SOCKETs. The following function is an attempt
507  * to re-create a select() function with support for other handle types.
508  *
509  * select() function with support for WINSOCK2 sockets and all
510  * other handle types supported by WaitForMultipleObjectsEx().
511  *
512  * TODO: Differentiate between read/write/except for non-SOCKET handles.
513  *
514  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
515  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
516  */
517 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
518                      fd_set *exceptfds, struct timeval *timeout)
519 {
520   long networkevents;
521   DWORD milliseconds, wait, idx, mode, avail, events, inputs;
522   WSAEVENT wsaevent, *wsaevents;
523   WSANETWORKEVENTS wsanetevents;
524   INPUT_RECORD *inputrecords;
525   HANDLE handle, *handles;
526   curl_socket_t sock, *fdarr, *wsasocks;
527   int error, fds;
528   DWORD nfd = 0, wsa = 0;
529   int ret = 0;
530
531   /* check if the input value is valid */
532   if(nfds < 0) {
533     errno = EINVAL;
534     return -1;
535   }
536
537   /* check if we got descriptors, sleep in case we got none */
538   if(!nfds) {
539     Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
540     return 0;
541   }
542
543   /* allocate internal array for the original input handles */
544   fdarr = malloc(nfds * sizeof(curl_socket_t));
545   if(fdarr == NULL) {
546     errno = ENOMEM;
547     return -1;
548   }
549
550   /* allocate internal array for the internal event handles */
551   handles = malloc(nfds * sizeof(HANDLE));
552   if(handles == NULL) {
553     errno = ENOMEM;
554     return -1;
555   }
556
557   /* allocate internal array for the internal socket handles */
558   wsasocks = malloc(nfds * sizeof(curl_socket_t));
559   if(wsasocks == NULL) {
560     errno = ENOMEM;
561     return -1;
562   }
563
564   /* allocate internal array for the internal WINSOCK2 events */
565   wsaevents = malloc(nfds * sizeof(WSAEVENT));
566   if(wsaevents == NULL) {
567     errno = ENOMEM;
568     return -1;
569   }
570
571   /* loop over the handles in the input descriptor sets */
572   for(fds = 0; fds < nfds; fds++) {
573     networkevents = 0;
574     handles[nfd] = 0;
575
576     if(FD_ISSET(fds, readfds))
577       networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
578
579     if(FD_ISSET(fds, writefds))
580       networkevents |= FD_WRITE|FD_CONNECT;
581
582     if(FD_ISSET(fds, exceptfds))
583       networkevents |= FD_OOB|FD_CLOSE;
584
585     /* only wait for events for which we actually care */
586     if(networkevents) {
587       fdarr[nfd] = curlx_sitosk(fds);
588       if(fds == fileno(stdin)) {
589         handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
590       }
591       else if(fds == fileno(stdout)) {
592         handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
593       }
594       else if(fds == fileno(stderr)) {
595         handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
596       }
597       else {
598         wsaevent = WSACreateEvent();
599         if(wsaevent != WSA_INVALID_EVENT) {
600           error = WSAEventSelect(fds, wsaevent, networkevents);
601           if(error != SOCKET_ERROR) {
602             handles[nfd] = wsaevent;
603             wsasocks[wsa] = curlx_sitosk(fds);
604             wsaevents[wsa] = wsaevent;
605             wsa++;
606           }
607           else {
608             handles[nfd] = (HANDLE) curlx_sitosk(fds);
609             WSACloseEvent(wsaevent);
610           }
611         }
612       }
613       nfd++;
614     }
615   }
616
617   /* convert struct timeval to milliseconds */
618   if(timeout) {
619     milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
620   }
621   else {
622     milliseconds = INFINITE;
623   }
624
625   /* wait for one of the internal handles to trigger */
626   wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
627
628   /* loop over the internal handles returned in the descriptors */
629   for(idx = 0; idx < nfd; idx++) {
630     handle = handles[idx];
631     sock = fdarr[idx];
632     fds = curlx_sktosi(sock);
633
634     /* check if the current internal handle was triggered */
635     if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
636        WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
637       /* try to handle the event with STD* handle functions */
638       if(fds == fileno(stdin)) {
639         /* check if there is no data in the input buffer */
640         if(!stdin->_cnt) {
641           /* check if we are getting data from a PIPE */
642           if(!GetConsoleMode(handle, &mode)) {
643             /* check if there is no data from PIPE input */
644             if(!PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
645               avail = 0;
646             if(!avail) {
647               FD_CLR(sock, readfds);
648               /* reduce CPU load */
649               Sleep(10);
650             }
651           } /* check if there is no data from keyboard input */
652           else if (!_kbhit()) {
653             /* check if there are INPUT_RECORDs in the input buffer */
654             if(GetNumberOfConsoleInputEvents(handle, &events)) {
655               if(events > 0) {
656                 /* remove INPUT_RECORDs from the input buffer */
657                 inputrecords = (INPUT_RECORD*)malloc(events *
658                                                      sizeof(INPUT_RECORD));
659                 if(inputrecords) {
660                   if(!ReadConsoleInput(handle, inputrecords,
661                                        events, &inputs))
662                     inputs = 0;
663                   free(inputrecords);
664                 }
665
666                 /* check if we got all inputs, otherwise clear buffer */
667                 if(events != inputs)
668                   FlushConsoleInputBuffer(handle);
669               }
670             }
671
672             /* remove from descriptor set since there is no real data */
673             FD_CLR(sock, readfds);
674           }
675         }
676
677         /* stdin is never ready for write or exceptional */
678         FD_CLR(sock, writefds);
679         FD_CLR(sock, exceptfds);
680       }
681       else if(fds == fileno(stdout) || fds == fileno(stderr)) {
682         /* stdout and stderr are never ready for read or exceptional */
683         FD_CLR(sock, readfds);
684         FD_CLR(sock, exceptfds);
685       }
686       else {
687         /* try to handle the event with the WINSOCK2 functions */
688         error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
689         if(error != SOCKET_ERROR) {
690           /* remove from descriptor set if not ready for read/accept/close */
691           if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
692             FD_CLR(sock, readfds);
693
694           /* remove from descriptor set if not ready for write/connect */
695           if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
696             FD_CLR(sock, writefds);
697
698           /* HACK:
699            * use exceptfds together with readfds to signal
700            * that the connection was closed by the client.
701            *
702            * Reason: FD_CLOSE is only signaled once, sometimes
703            * at the same time as FD_READ with data being available.
704            * This means that recv/sread is not reliable to detect
705            * that the connection is closed.
706            */
707           /* remove from descriptor set if not exceptional */
708           if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
709             FD_CLR(sock, exceptfds);
710         }
711       }
712
713       /* check if the event has not been filtered using specific tests */
714       if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
715          FD_ISSET(sock, exceptfds)) {
716         ret++;
717       }
718     }
719     else {
720       /* remove from all descriptor sets since this handle did not trigger */
721       FD_CLR(sock, readfds);
722       FD_CLR(sock, writefds);
723       FD_CLR(sock, exceptfds);
724     }
725   }
726
727   for(idx = 0; idx < wsa; idx++) {
728     WSAEventSelect(wsasocks[idx], NULL, 0);
729     WSACloseEvent(wsaevents[idx]);
730   }
731
732   free(wsaevents);
733   free(wsasocks);
734   free(handles);
735   free(fdarr);
736
737   return ret;
738 }
739 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
740 #endif  /* USE_WINSOCK */
741
742 /*
743   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
744
745   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
746   accept()
747 */
748 static bool juggle(curl_socket_t *sockfdp,
749                    curl_socket_t listenfd,
750                    enum sockmode *mode)
751 {
752   struct timeval timeout;
753   fd_set fds_read;
754   fd_set fds_write;
755   fd_set fds_err;
756   curl_socket_t sockfd = CURL_SOCKET_BAD;
757   int maxfd = -99;
758   ssize_t rc;
759   ssize_t nread_socket;
760   ssize_t bytes_written;
761   ssize_t buffer_len;
762   int error = 0;
763
764  /* 'buffer' is this excessively large only to be able to support things like
765     test 1003 which tests exceedingly large server response lines */
766   unsigned char buffer[17010];
767   char data[16];
768
769   if(got_exit_signal) {
770     logmsg("signalled to die, exiting...");
771     return FALSE;
772   }
773
774 #ifdef HAVE_GETPPID
775   /* As a last resort, quit if sockfilt process becomes orphan. Just in case
776      parent ftpserver process has died without killing its sockfilt children */
777   if(getppid() <= 1) {
778     logmsg("process becomes orphan, exiting");
779     return FALSE;
780   }
781 #endif
782
783   timeout.tv_sec = 120;
784   timeout.tv_usec = 0;
785
786   FD_ZERO(&fds_read);
787   FD_ZERO(&fds_write);
788   FD_ZERO(&fds_err);
789
790   FD_SET((curl_socket_t)fileno(stdin), &fds_read);
791
792   switch(*mode) {
793
794   case PASSIVE_LISTEN:
795
796     /* server mode */
797     sockfd = listenfd;
798     /* there's always a socket to wait for */
799     FD_SET(sockfd, &fds_read);
800     maxfd = (int)sockfd;
801     break;
802
803   case PASSIVE_CONNECT:
804
805     sockfd = *sockfdp;
806     if(CURL_SOCKET_BAD == sockfd) {
807       /* eeek, we are supposedly connected and then this cannot be -1 ! */
808       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
809       maxfd = 0; /* stdin */
810     }
811     else {
812       /* there's always a socket to wait for */
813       FD_SET(sockfd, &fds_read);
814 #ifdef USE_WINSOCK
815       FD_SET(sockfd, &fds_err);
816 #endif
817       maxfd = (int)sockfd;
818     }
819     break;
820
821   case ACTIVE:
822
823     sockfd = *sockfdp;
824     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
825     if(CURL_SOCKET_BAD != sockfd) {
826       FD_SET(sockfd, &fds_read);
827 #ifdef USE_WINSOCK
828       FD_SET(sockfd, &fds_err);
829 #endif
830       maxfd = (int)sockfd;
831     }
832     else {
833       logmsg("No socket to read on");
834       maxfd = 0;
835     }
836     break;
837
838   case ACTIVE_DISCONNECT:
839
840     logmsg("disconnected, no socket to read on");
841     maxfd = 0;
842     sockfd = CURL_SOCKET_BAD;
843     break;
844
845   } /* switch(*mode) */
846
847
848   do {
849
850     /* select() blocking behavior call on blocking descriptors please */
851
852     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
853
854     if(got_exit_signal) {
855       logmsg("signalled to die, exiting...");
856       return FALSE;
857     }
858
859   } while((rc == -1) && ((error = errno) == EINTR));
860
861   if(rc < 0) {
862     logmsg("select() failed with error: (%d) %s",
863            error, strerror(error));
864     return FALSE;
865   }
866
867   if(rc == 0)
868     /* timeout */
869     return TRUE;
870
871
872   if(FD_ISSET(fileno(stdin), &fds_read)) {
873     /* read from stdin, commands/data to be dealt with and possibly passed on
874        to the socket
875
876        protocol:
877
878        4 letter command + LF [mandatory]
879
880        4-digit hexadecimal data length + LF [if the command takes data]
881        data                       [the data being as long as set above]
882
883        Commands:
884
885        DATA - plain pass-thru data
886     */
887
888     if(!read_stdin(buffer, 5))
889       return FALSE;
890
891     logmsg("Received %c%c%c%c (on stdin)",
892            buffer[0], buffer[1], buffer[2], buffer[3] );
893
894     if(!memcmp("PING", buffer, 4)) {
895       /* send reply on stdout, just proving we are alive */
896       if(!write_stdout("PONG\n", 5))
897         return FALSE;
898     }
899
900     else if(!memcmp("PORT", buffer, 4)) {
901       /* Question asking us what PORT number we are listening to.
902          Replies to PORT with "IPv[num]/[port]" */
903       sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
904       buffer_len = (ssize_t)strlen((char *)buffer);
905       snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
906       if(!write_stdout(data, 10))
907         return FALSE;
908       if(!write_stdout(buffer, buffer_len))
909         return FALSE;
910     }
911     else if(!memcmp("QUIT", buffer, 4)) {
912       /* just die */
913       logmsg("quits");
914       return FALSE;
915     }
916     else if(!memcmp("DATA", buffer, 4)) {
917       /* data IN => data OUT */
918
919       if(!read_stdin(buffer, 5))
920         return FALSE;
921
922       buffer[5] = '\0';
923
924       buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
925       if (buffer_len > (ssize_t)sizeof(buffer)) {
926         logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
927                "(%zd bytes)", sizeof(buffer), buffer_len);
928         return FALSE;
929       }
930       logmsg("> %zd bytes data, server => client", buffer_len);
931
932       if(!read_stdin(buffer, buffer_len))
933         return FALSE;
934
935       lograw(buffer, buffer_len);
936
937       if(*mode == PASSIVE_LISTEN) {
938         logmsg("*** We are disconnected!");
939         if(!write_stdout("DISC\n", 5))
940           return FALSE;
941       }
942       else {
943         /* send away on the socket */
944         bytes_written = swrite(sockfd, buffer, buffer_len);
945         if(bytes_written != buffer_len) {
946           logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
947                  buffer_len, bytes_written);
948         }
949       }
950     }
951     else if(!memcmp("DISC", buffer, 4)) {
952       /* disconnect! */
953       if(!write_stdout("DISC\n", 5))
954         return FALSE;
955       if(sockfd != CURL_SOCKET_BAD) {
956         logmsg("====> Client forcibly disconnected");
957         sclose(sockfd);
958         *sockfdp = CURL_SOCKET_BAD;
959         if(*mode == PASSIVE_CONNECT)
960           *mode = PASSIVE_LISTEN;
961         else
962           *mode = ACTIVE_DISCONNECT;
963       }
964       else
965         logmsg("attempt to close already dead connection");
966       return TRUE;
967     }
968   }
969
970
971   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
972
973     curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
974
975     if(*mode == PASSIVE_LISTEN) {
976       /* there's no stream set up yet, this is an indication that there's a
977          client connecting. */
978       newfd = accept(sockfd, NULL, NULL);
979       if(CURL_SOCKET_BAD == newfd) {
980         error = SOCKERRNO;
981         logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
982                sockfd, error, strerror(error));
983       }
984       else {
985         logmsg("====> Client connect");
986         if(!write_stdout("CNCT\n", 5))
987           return FALSE;
988         *sockfdp = newfd; /* store the new socket */
989         *mode = PASSIVE_CONNECT; /* we have connected */
990       }
991       return TRUE;
992     }
993
994     /* read from socket, pass on data to stdout */
995     nread_socket = sread(sockfd, buffer, sizeof(buffer));
996
997     if(nread_socket > 0) {
998       snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
999       if(!write_stdout(data, 10))
1000         return FALSE;
1001       if(!write_stdout(buffer, nread_socket))
1002         return FALSE;
1003
1004       logmsg("< %zd bytes data, client => server", nread_socket);
1005       lograw(buffer, nread_socket);
1006     }
1007
1008     if(nread_socket <= 0
1009 #ifdef USE_WINSOCK
1010        || FD_ISSET(sockfd, &fds_err)
1011 #endif
1012        ) {
1013       logmsg("====> Client disconnect");
1014       if(!write_stdout("DISC\n", 5))
1015         return FALSE;
1016       sclose(sockfd);
1017       *sockfdp = CURL_SOCKET_BAD;
1018       if(*mode == PASSIVE_CONNECT)
1019         *mode = PASSIVE_LISTEN;
1020       else
1021         *mode = ACTIVE_DISCONNECT;
1022       return TRUE;
1023     }
1024   }
1025
1026   return TRUE;
1027 }
1028
1029 static curl_socket_t sockdaemon(curl_socket_t sock,
1030                                 unsigned short *listenport)
1031 {
1032   /* passive daemon style */
1033   srvr_sockaddr_union_t listener;
1034   int flag;
1035   int rc;
1036   int totdelay = 0;
1037   int maxretr = 10;
1038   int delay= 20;
1039   int attempt = 0;
1040   int error = 0;
1041
1042   do {
1043     attempt++;
1044     flag = 1;
1045     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1046          (void *)&flag, sizeof(flag));
1047     if(rc) {
1048       error = SOCKERRNO;
1049       logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1050              error, strerror(error));
1051       if(maxretr) {
1052         rc = wait_ms(delay);
1053         if(rc) {
1054           /* should not happen */
1055           error = errno;
1056           logmsg("wait_ms() failed with error: (%d) %s",
1057                  error, strerror(error));
1058           sclose(sock);
1059           return CURL_SOCKET_BAD;
1060         }
1061         if(got_exit_signal) {
1062           logmsg("signalled to die, exiting...");
1063           sclose(sock);
1064           return CURL_SOCKET_BAD;
1065         }
1066         totdelay += delay;
1067         delay *= 2; /* double the sleep for next attempt */
1068       }
1069     }
1070   } while(rc && maxretr--);
1071
1072   if(rc) {
1073     logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
1074            attempt, totdelay, error, strerror(error));
1075     logmsg("Continuing anyway...");
1076   }
1077
1078   /* When the specified listener port is zero, it is actually a
1079      request to let the system choose a non-zero available port. */
1080
1081 #ifdef ENABLE_IPV6
1082   if(!use_ipv6) {
1083 #endif
1084     memset(&listener.sa4, 0, sizeof(listener.sa4));
1085     listener.sa4.sin_family = AF_INET;
1086     listener.sa4.sin_addr.s_addr = INADDR_ANY;
1087     listener.sa4.sin_port = htons(*listenport);
1088     rc = bind(sock, &listener.sa, sizeof(listener.sa4));
1089 #ifdef ENABLE_IPV6
1090   }
1091   else {
1092     memset(&listener.sa6, 0, sizeof(listener.sa6));
1093     listener.sa6.sin6_family = AF_INET6;
1094     listener.sa6.sin6_addr = in6addr_any;
1095     listener.sa6.sin6_port = htons(*listenport);
1096     rc = bind(sock, &listener.sa, sizeof(listener.sa6));
1097   }
1098 #endif /* ENABLE_IPV6 */
1099   if(rc) {
1100     error = SOCKERRNO;
1101     logmsg("Error binding socket on port %hu: (%d) %s",
1102            *listenport, error, strerror(error));
1103     sclose(sock);
1104     return CURL_SOCKET_BAD;
1105   }
1106
1107   if(!*listenport) {
1108     /* The system was supposed to choose a port number, figure out which
1109        port we actually got and update the listener port value with it. */
1110     curl_socklen_t la_size;
1111     srvr_sockaddr_union_t localaddr;
1112 #ifdef ENABLE_IPV6
1113     if(!use_ipv6)
1114 #endif
1115       la_size = sizeof(localaddr.sa4);
1116 #ifdef ENABLE_IPV6
1117     else
1118       la_size = sizeof(localaddr.sa6);
1119 #endif
1120     memset(&localaddr.sa, 0, (size_t)la_size);
1121     if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1122       error = SOCKERRNO;
1123       logmsg("getsockname() failed with error: (%d) %s",
1124              error, strerror(error));
1125       sclose(sock);
1126       return CURL_SOCKET_BAD;
1127     }
1128     switch (localaddr.sa.sa_family) {
1129     case AF_INET:
1130       *listenport = ntohs(localaddr.sa4.sin_port);
1131       break;
1132 #ifdef ENABLE_IPV6
1133     case AF_INET6:
1134       *listenport = ntohs(localaddr.sa6.sin6_port);
1135       break;
1136 #endif
1137     default:
1138       break;
1139     }
1140     if(!*listenport) {
1141       /* Real failure, listener port shall not be zero beyond this point. */
1142       logmsg("Apparently getsockname() succeeded, with listener port zero.");
1143       logmsg("A valid reason for this failure is a binary built without");
1144       logmsg("proper network library linkage. This might not be the only");
1145       logmsg("reason, but double check it before anything else.");
1146       sclose(sock);
1147       return CURL_SOCKET_BAD;
1148     }
1149   }
1150
1151   /* bindonly option forces no listening */
1152   if(bind_only) {
1153     logmsg("instructed to bind port without listening");
1154     return sock;
1155   }
1156
1157   /* start accepting connections */
1158   rc = listen(sock, 5);
1159   if(0 != rc) {
1160     error = SOCKERRNO;
1161     logmsg("listen(%d, 5) failed with error: (%d) %s",
1162            sock, error, strerror(error));
1163     sclose(sock);
1164     return CURL_SOCKET_BAD;
1165   }
1166
1167   return sock;
1168 }
1169
1170
1171 int main(int argc, char *argv[])
1172 {
1173   srvr_sockaddr_union_t me;
1174   curl_socket_t sock = CURL_SOCKET_BAD;
1175   curl_socket_t msgsock = CURL_SOCKET_BAD;
1176   int wrotepidfile = 0;
1177   char *pidname= (char *)".sockfilt.pid";
1178   bool juggle_again;
1179   int rc;
1180   int error;
1181   int arg=1;
1182   enum sockmode mode = PASSIVE_LISTEN; /* default */
1183   const char *addr = NULL;
1184
1185   while(argc>arg) {
1186     if(!strcmp("--version", argv[arg])) {
1187       printf("sockfilt IPv4%s\n",
1188 #ifdef ENABLE_IPV6
1189              "/IPv6"
1190 #else
1191              ""
1192 #endif
1193              );
1194       return 0;
1195     }
1196     else if(!strcmp("--verbose", argv[arg])) {
1197       verbose = TRUE;
1198       arg++;
1199     }
1200     else if(!strcmp("--pidfile", argv[arg])) {
1201       arg++;
1202       if(argc>arg)
1203         pidname = argv[arg++];
1204     }
1205     else if(!strcmp("--logfile", argv[arg])) {
1206       arg++;
1207       if(argc>arg)
1208         serverlogfile = argv[arg++];
1209     }
1210     else if(!strcmp("--ipv6", argv[arg])) {
1211 #ifdef ENABLE_IPV6
1212       ipv_inuse = "IPv6";
1213       use_ipv6 = TRUE;
1214 #endif
1215       arg++;
1216     }
1217     else if(!strcmp("--ipv4", argv[arg])) {
1218       /* for completeness, we support this option as well */
1219 #ifdef ENABLE_IPV6
1220       ipv_inuse = "IPv4";
1221       use_ipv6 = FALSE;
1222 #endif
1223       arg++;
1224     }
1225     else if(!strcmp("--bindonly", argv[arg])) {
1226       bind_only = TRUE;
1227       arg++;
1228     }
1229     else if(!strcmp("--port", argv[arg])) {
1230       arg++;
1231       if(argc>arg) {
1232         char *endptr;
1233         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1234         if((endptr != argv[arg] + strlen(argv[arg])) ||
1235            ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1236           fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1237                   argv[arg]);
1238           return 0;
1239         }
1240         port = curlx_ultous(ulnum);
1241         arg++;
1242       }
1243     }
1244     else if(!strcmp("--connect", argv[arg])) {
1245       /* Asked to actively connect to the specified local port instead of
1246          doing a passive server-style listening. */
1247       arg++;
1248       if(argc>arg) {
1249         char *endptr;
1250         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1251         if((endptr != argv[arg] + strlen(argv[arg])) ||
1252            (ulnum < 1025UL) || (ulnum > 65535UL)) {
1253           fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1254                   argv[arg]);
1255           return 0;
1256         }
1257         connectport = curlx_ultous(ulnum);
1258         arg++;
1259       }
1260     }
1261     else if(!strcmp("--addr", argv[arg])) {
1262       /* Set an IP address to use with --connect; otherwise use localhost */
1263       arg++;
1264       if(argc>arg) {
1265         addr = argv[arg];
1266         arg++;
1267       }
1268     }
1269     else {
1270       puts("Usage: sockfilt [option]\n"
1271            " --version\n"
1272            " --verbose\n"
1273            " --logfile [file]\n"
1274            " --pidfile [file]\n"
1275            " --ipv4\n"
1276            " --ipv6\n"
1277            " --bindonly\n"
1278            " --port [port]\n"
1279            " --connect [port]\n"
1280            " --addr [address]");
1281       return 0;
1282     }
1283   }
1284
1285 #ifdef WIN32
1286   win32_init();
1287   atexit(win32_cleanup);
1288
1289   setmode(fileno(stdin), O_BINARY);
1290   setmode(fileno(stdout), O_BINARY);
1291   setmode(fileno(stderr), O_BINARY);
1292 #endif
1293
1294   install_signal_handlers();
1295
1296 #ifdef ENABLE_IPV6
1297   if(!use_ipv6)
1298 #endif
1299     sock = socket(AF_INET, SOCK_STREAM, 0);
1300 #ifdef ENABLE_IPV6
1301   else
1302     sock = socket(AF_INET6, SOCK_STREAM, 0);
1303 #endif
1304
1305   if(CURL_SOCKET_BAD == sock) {
1306     error = SOCKERRNO;
1307     logmsg("Error creating socket: (%d) %s",
1308            error, strerror(error));
1309     write_stdout("FAIL\n", 5);
1310     goto sockfilt_cleanup;
1311   }
1312
1313   if(connectport) {
1314     /* Active mode, we should connect to the given port number */
1315     mode = ACTIVE;
1316 #ifdef ENABLE_IPV6
1317     if(!use_ipv6) {
1318 #endif
1319       memset(&me.sa4, 0, sizeof(me.sa4));
1320       me.sa4.sin_family = AF_INET;
1321       me.sa4.sin_port = htons(connectport);
1322       me.sa4.sin_addr.s_addr = INADDR_ANY;
1323       if (!addr)
1324         addr = "127.0.0.1";
1325       Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1326
1327       rc = connect(sock, &me.sa, sizeof(me.sa4));
1328 #ifdef ENABLE_IPV6
1329     }
1330     else {
1331       memset(&me.sa6, 0, sizeof(me.sa6));
1332       me.sa6.sin6_family = AF_INET6;
1333       me.sa6.sin6_port = htons(connectport);
1334       if (!addr)
1335         addr = "::1";
1336       Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1337
1338       rc = connect(sock, &me.sa, sizeof(me.sa6));
1339     }
1340 #endif /* ENABLE_IPV6 */
1341     if(rc) {
1342       error = SOCKERRNO;
1343       logmsg("Error connecting to port %hu: (%d) %s",
1344              connectport, error, strerror(error));
1345       write_stdout("FAIL\n", 5);
1346       goto sockfilt_cleanup;
1347     }
1348     logmsg("====> Client connect");
1349     msgsock = sock; /* use this as stream */
1350   }
1351   else {
1352     /* passive daemon style */
1353     sock = sockdaemon(sock, &port);
1354     if(CURL_SOCKET_BAD == sock) {
1355       write_stdout("FAIL\n", 5);
1356       goto sockfilt_cleanup;
1357     }
1358     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1359   }
1360
1361   logmsg("Running %s version", ipv_inuse);
1362
1363   if(connectport)
1364     logmsg("Connected to port %hu", connectport);
1365   else if(bind_only)
1366     logmsg("Bound without listening on port %hu", port);
1367   else
1368     logmsg("Listening on port %hu", port);
1369
1370   wrotepidfile = write_pidfile(pidname);
1371   if(!wrotepidfile) {
1372     write_stdout("FAIL\n", 5);
1373     goto sockfilt_cleanup;
1374   }
1375
1376   do {
1377     juggle_again = juggle(&msgsock, sock, &mode);
1378   } while(juggle_again);
1379
1380 sockfilt_cleanup:
1381
1382   if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1383     sclose(msgsock);
1384
1385   if(sock != CURL_SOCKET_BAD)
1386     sclose(sock);
1387
1388   if(wrotepidfile)
1389     unlink(pidname);
1390
1391   restore_signal_handlers();
1392
1393   if(got_exit_signal) {
1394     logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1395     /*
1396      * To properly set the return status of the process we
1397      * must raise the same signal SIGINT or SIGTERM that we
1398      * caught and let the old handler take care of it.
1399      */
1400     raise(exit_signal);
1401   }
1402
1403   logmsg("============> sockfilt quits");
1404   return 0;
1405 }
1406