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