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