Revert "Update to 7.40.1"
[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() as
510  * well as disk files, anonymous and names pipes, and character input.
511  *
512  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
513  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
514  */
515 struct select_ws_wait_data {
516   HANDLE handle; /* actual handle to wait for during select */
517   HANDLE event;  /* internal event to abort waiting thread */
518 };
519 static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter)
520 {
521   struct select_ws_wait_data *data;
522   HANDLE handle, handles[2];
523   INPUT_RECORD inputrecord;
524   LARGE_INTEGER size, pos;
525   DWORD type, length;
526
527   /* retrieve handles from internal structure */
528   data = (struct select_ws_wait_data *) lpParameter;
529   if(data) {
530     handle = data->handle;
531     handles[0] = data->event;
532     handles[1] = handle;
533     free(data);
534   }
535   else
536     return -1;
537
538   /* retrieve the type of file to wait on */
539   type = GetFileType(handle);
540   switch(type) {
541     case FILE_TYPE_DISK:
542        /* The handle represents a file on disk, this means:
543         * - WaitForMultipleObjectsEx will always be signalled for it.
544         * - comparison of current position in file and total size of
545         *   the file can be used to check if we reached the end yet.
546         *
547         * Approach: Loop till either the internal event is signalled
548         *           or if the end of the file has already been reached.
549         */
550       while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
551             == WAIT_OBJECT_0 + 1) {
552         /* get total size of file */
553         size.QuadPart = 0;
554         if(GetFileSizeEx(handle, &size)) {
555           /* get the current position within the file */
556           pos.QuadPart = 0;
557           if(SetFilePointerEx(handle, pos, &pos, FILE_CURRENT)) {
558             /* compare position with size, abort if not equal */
559             if(size.QuadPart == pos.QuadPart) {
560               /* sleep and continue waiting */
561               SleepEx(100, FALSE);
562               continue;
563             }
564           }
565         }
566         /* there is some data available, stop waiting */
567         break;
568       }
569       break;
570
571     case FILE_TYPE_CHAR:
572        /* The handle represents a character input, this means:
573         * - WaitForMultipleObjectsEx will be signalled on any kind of input,
574         *   including mouse and window size events we do not care about.
575         *
576         * Approach: Loop till either the internal event is signalled
577         *           or we get signalled for an actual key-event.
578         */
579       while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
580             == WAIT_OBJECT_0 + 1) {
581         /* check if this is an actual console handle */
582         if(GetConsoleMode(handle, &length)) {
583           /* retrieve an event from the console buffer */
584           length = 0;
585           if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
586             /* check if the event is not an actual key-event */
587             if(length == 1 && inputrecord.EventType != KEY_EVENT) {
588               /* purge the non-key-event and continue waiting */
589               ReadConsoleInput(handle, &inputrecord, 1, &length);
590               continue;
591             }
592           }
593         }
594         /* there is some data available, stop waiting */
595         break;
596       }
597       break;
598
599     case FILE_TYPE_PIPE:
600        /* The handle represents an anonymous or named pipe, this means:
601         * - WaitForMultipleObjectsEx will always be signalled for it.
602         * - peek into the pipe and retrieve the amount of data available.
603         *
604         * Approach: Loop till either the internal event is signalled
605         *           or there is data in the pipe available for reading.
606         */
607       while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
608             == WAIT_OBJECT_0 + 1) {
609         /* peek into the pipe and retrieve the amount of data available */
610         if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
611           /* if there is no data available, sleep and continue waiting */
612           if(length == 0) {
613             SleepEx(100, FALSE);
614             continue;
615           }
616         }
617         else {
618           /* if the pipe has been closed, sleep and continue waiting */
619           if(GetLastError() == ERROR_BROKEN_PIPE) {
620             SleepEx(100, FALSE);
621             continue;
622           }
623         }
624         /* there is some data available, stop waiting */
625         break;
626       }
627       break;
628
629     default:
630       /* The handle has an unknown type, try to wait on it */
631       WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE);
632       break;
633   }
634
635   return 0;
636 }
637 static HANDLE select_ws_wait(HANDLE handle, HANDLE event)
638 {
639   struct select_ws_wait_data *data;
640   HANDLE thread = NULL;
641
642   /* allocate internal waiting data structure */
643   data = malloc(sizeof(struct select_ws_wait_data));
644   if(data) {
645     data->handle = handle;
646     data->event = event;
647
648     /* launch waiting thread */
649     thread = CreateThread(NULL, 0,
650                           &select_ws_wait_thread,
651                           data, 0, NULL);
652
653     /* free data if thread failed to launch */
654     if(!thread) {
655       free(data);
656     }
657   }
658
659   return thread;
660 }
661 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
662                      fd_set *exceptfds, struct timeval *timeout)
663 {
664   DWORD milliseconds, wait, idx;
665   WSAEVENT wsaevent, *wsaevents;
666   WSANETWORKEVENTS wsanetevents;
667   HANDLE handle, *handles, *threads;
668   curl_socket_t sock, *fdarr, *wsasocks;
669   long networkevents;
670   int error, fds;
671   HANDLE waitevent = NULL;
672   DWORD nfd = 0, thd = 0, wsa = 0;
673   int ret = 0;
674
675   /* check if the input value is valid */
676   if(nfds < 0) {
677     errno = EINVAL;
678     return -1;
679   }
680
681   /* check if we got descriptors, sleep in case we got none */
682   if(!nfds) {
683     Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
684     return 0;
685   }
686
687   /* create internal event to signal waiting threads */
688   waitevent = CreateEvent(NULL, TRUE, FALSE, NULL);
689   if(!waitevent) {
690     errno = ENOMEM;
691     return -1;
692   }
693
694   /* allocate internal array for the original input handles */
695   fdarr = malloc(nfds * sizeof(curl_socket_t));
696   if(fdarr == NULL) {
697     errno = ENOMEM;
698     return -1;
699   }
700
701   /* allocate internal array for the internal event handles */
702   handles = malloc(nfds * sizeof(HANDLE));
703   if(handles == NULL) {
704     free(fdarr);
705     errno = ENOMEM;
706     return -1;
707   }
708
709   /* allocate internal array for the internal threads handles */
710   threads = malloc(nfds * sizeof(HANDLE));
711   if(threads == NULL) {
712     free(handles);
713     free(fdarr);
714     errno = ENOMEM;
715     return -1;
716   }
717
718   /* allocate internal array for the internal socket handles */
719   wsasocks = malloc(nfds * sizeof(curl_socket_t));
720   if(wsasocks == NULL) {
721     free(threads);
722     free(handles);
723     free(fdarr);
724     errno = ENOMEM;
725     return -1;
726   }
727
728   /* allocate internal array for the internal WINSOCK2 events */
729   wsaevents = malloc(nfds * sizeof(WSAEVENT));
730   if(wsaevents == NULL) {
731     free(threads);
732     free(wsasocks);
733     free(handles);
734     free(fdarr);
735     errno = ENOMEM;
736     return -1;
737   }
738
739   /* loop over the handles in the input descriptor sets */
740   for(fds = 0; fds < nfds; fds++) {
741     networkevents = 0;
742     handles[nfd] = 0;
743
744     if(FD_ISSET(fds, readfds))
745       networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
746
747     if(FD_ISSET(fds, writefds))
748       networkevents |= FD_WRITE|FD_CONNECT;
749
750     if(FD_ISSET(fds, exceptfds))
751       networkevents |= FD_OOB|FD_CLOSE;
752
753     /* only wait for events for which we actually care */
754     if(networkevents) {
755       fdarr[nfd] = curlx_sitosk(fds);
756       if(fds == fileno(stdin)) {
757         handle = GetStdHandle(STD_INPUT_HANDLE);
758         handle = select_ws_wait(handle, waitevent);
759         handles[nfd] = handle;
760         threads[thd] = handle;
761         thd++;
762       }
763       else if(fds == fileno(stdout)) {
764         handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
765       }
766       else if(fds == fileno(stderr)) {
767         handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
768       }
769       else {
770         wsaevent = WSACreateEvent();
771         if(wsaevent != WSA_INVALID_EVENT) {
772           error = WSAEventSelect(fds, wsaevent, networkevents);
773           if(error != SOCKET_ERROR) {
774             handle = (HANDLE) wsaevent;
775             handles[nfd] = handle;
776             wsasocks[wsa] = curlx_sitosk(fds);
777             wsaevents[wsa] = wsaevent;
778             wsa++;
779           }
780           else {
781             WSACloseEvent(wsaevent);
782             handle = (HANDLE) curlx_sitosk(fds);
783             handle = select_ws_wait(handle, waitevent);
784             handles[nfd] = handle;
785             threads[thd] = handle;
786             thd++;
787           }
788         }
789       }
790       nfd++;
791     }
792   }
793
794   /* convert struct timeval to milliseconds */
795   if(timeout) {
796     milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
797   }
798   else {
799     milliseconds = INFINITE;
800   }
801
802   /* wait for one of the internal handles to trigger */
803   wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
804
805   /* signal the event handle for the waiting threads */
806   SetEvent(waitevent);
807
808   /* loop over the internal handles returned in the descriptors */
809   for(idx = 0; idx < nfd; idx++) {
810     handle = handles[idx];
811     sock = fdarr[idx];
812     fds = curlx_sktosi(sock);
813
814     /* check if the current internal handle was triggered */
815     if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
816        WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
817       /* first handle stdin, stdout and stderr */
818       if(fds == fileno(stdin)) {
819         /* stdin is never ready for write or exceptional */
820         FD_CLR(sock, writefds);
821         FD_CLR(sock, exceptfds);
822       }
823       else if(fds == fileno(stdout) || fds == fileno(stderr)) {
824         /* stdout and stderr are never ready for read or exceptional */
825         FD_CLR(sock, readfds);
826         FD_CLR(sock, exceptfds);
827       }
828       else {
829         /* try to handle the event with the WINSOCK2 functions */
830         wsanetevents.lNetworkEvents = 0;
831         error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
832         if(error != SOCKET_ERROR) {
833           /* remove from descriptor set if not ready for read/accept/close */
834           if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
835             FD_CLR(sock, readfds);
836
837           /* remove from descriptor set if not ready for write/connect */
838           if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
839             FD_CLR(sock, writefds);
840
841           /* HACK:
842            * use exceptfds together with readfds to signal
843            * that the connection was closed by the client.
844            *
845            * Reason: FD_CLOSE is only signaled once, sometimes
846            * at the same time as FD_READ with data being available.
847            * This means that recv/sread is not reliable to detect
848            * that the connection is closed.
849            */
850           /* remove from descriptor set if not exceptional */
851           if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
852             FD_CLR(sock, exceptfds);
853         }
854       }
855
856       /* check if the event has not been filtered using specific tests */
857       if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
858          FD_ISSET(sock, exceptfds)) {
859         ret++;
860       }
861     }
862     else {
863       /* remove from all descriptor sets since this handle did not trigger */
864       FD_CLR(sock, readfds);
865       FD_CLR(sock, writefds);
866       FD_CLR(sock, exceptfds);
867     }
868   }
869
870   for(idx = 0; idx < wsa; idx++) {
871     WSAEventSelect(wsasocks[idx], NULL, 0);
872     WSACloseEvent(wsaevents[idx]);
873   }
874
875   for(idx = 0; idx < thd; idx++) {
876     WaitForSingleObject(threads[thd], INFINITE);
877     CloseHandle(threads[thd]);
878   }
879
880   CloseHandle(waitevent);
881
882   free(wsaevents);
883   free(wsasocks);
884   free(threads);
885   free(handles);
886   free(fdarr);
887
888   return ret;
889 }
890 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
891 #endif  /* USE_WINSOCK */
892
893 /*
894   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
895
896   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
897   accept()
898 */
899 static bool juggle(curl_socket_t *sockfdp,
900                    curl_socket_t listenfd,
901                    enum sockmode *mode)
902 {
903   struct timeval timeout;
904   fd_set fds_read;
905   fd_set fds_write;
906   fd_set fds_err;
907   curl_socket_t sockfd = CURL_SOCKET_BAD;
908   int maxfd = -99;
909   ssize_t rc;
910   ssize_t nread_socket;
911   ssize_t bytes_written;
912   ssize_t buffer_len;
913   int error = 0;
914
915  /* 'buffer' is this excessively large only to be able to support things like
916     test 1003 which tests exceedingly large server response lines */
917   unsigned char buffer[17010];
918   char data[16];
919
920   if(got_exit_signal) {
921     logmsg("signalled to die, exiting...");
922     return FALSE;
923   }
924
925 #ifdef HAVE_GETPPID
926   /* As a last resort, quit if sockfilt process becomes orphan. Just in case
927      parent ftpserver process has died without killing its sockfilt children */
928   if(getppid() <= 1) {
929     logmsg("process becomes orphan, exiting");
930     return FALSE;
931   }
932 #endif
933
934   timeout.tv_sec = 120;
935   timeout.tv_usec = 0;
936
937   FD_ZERO(&fds_read);
938   FD_ZERO(&fds_write);
939   FD_ZERO(&fds_err);
940
941   FD_SET((curl_socket_t)fileno(stdin), &fds_read);
942
943   switch(*mode) {
944
945   case PASSIVE_LISTEN:
946
947     /* server mode */
948     sockfd = listenfd;
949     /* there's always a socket to wait for */
950     FD_SET(sockfd, &fds_read);
951     maxfd = (int)sockfd;
952     break;
953
954   case PASSIVE_CONNECT:
955
956     sockfd = *sockfdp;
957     if(CURL_SOCKET_BAD == sockfd) {
958       /* eeek, we are supposedly connected and then this cannot be -1 ! */
959       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
960       maxfd = 0; /* stdin */
961     }
962     else {
963       /* there's always a socket to wait for */
964       FD_SET(sockfd, &fds_read);
965 #ifdef USE_WINSOCK
966       FD_SET(sockfd, &fds_err);
967 #endif
968       maxfd = (int)sockfd;
969     }
970     break;
971
972   case ACTIVE:
973
974     sockfd = *sockfdp;
975     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
976     if(CURL_SOCKET_BAD != sockfd) {
977       FD_SET(sockfd, &fds_read);
978 #ifdef USE_WINSOCK
979       FD_SET(sockfd, &fds_err);
980 #endif
981       maxfd = (int)sockfd;
982     }
983     else {
984       logmsg("No socket to read on");
985       maxfd = 0;
986     }
987     break;
988
989   case ACTIVE_DISCONNECT:
990
991     logmsg("disconnected, no socket to read on");
992     maxfd = 0;
993     sockfd = CURL_SOCKET_BAD;
994     break;
995
996   } /* switch(*mode) */
997
998
999   do {
1000
1001     /* select() blocking behavior call on blocking descriptors please */
1002
1003     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
1004
1005     if(got_exit_signal) {
1006       logmsg("signalled to die, exiting...");
1007       return FALSE;
1008     }
1009
1010   } while((rc == -1) && ((error = errno) == EINTR));
1011
1012   if(rc < 0) {
1013     logmsg("select() failed with error: (%d) %s",
1014            error, strerror(error));
1015     return FALSE;
1016   }
1017
1018   if(rc == 0)
1019     /* timeout */
1020     return TRUE;
1021
1022
1023   if(FD_ISSET(fileno(stdin), &fds_read)) {
1024     /* read from stdin, commands/data to be dealt with and possibly passed on
1025        to the socket
1026
1027        protocol:
1028
1029        4 letter command + LF [mandatory]
1030
1031        4-digit hexadecimal data length + LF [if the command takes data]
1032        data                       [the data being as long as set above]
1033
1034        Commands:
1035
1036        DATA - plain pass-thru data
1037     */
1038
1039     if(!read_stdin(buffer, 5))
1040       return FALSE;
1041
1042     logmsg("Received %c%c%c%c (on stdin)",
1043            buffer[0], buffer[1], buffer[2], buffer[3] );
1044
1045     if(!memcmp("PING", buffer, 4)) {
1046       /* send reply on stdout, just proving we are alive */
1047       if(!write_stdout("PONG\n", 5))
1048         return FALSE;
1049     }
1050
1051     else if(!memcmp("PORT", buffer, 4)) {
1052       /* Question asking us what PORT number we are listening to.
1053          Replies to PORT with "IPv[num]/[port]" */
1054       sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
1055       buffer_len = (ssize_t)strlen((char *)buffer);
1056       snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
1057       if(!write_stdout(data, 10))
1058         return FALSE;
1059       if(!write_stdout(buffer, buffer_len))
1060         return FALSE;
1061     }
1062     else if(!memcmp("QUIT", buffer, 4)) {
1063       /* just die */
1064       logmsg("quits");
1065       return FALSE;
1066     }
1067     else if(!memcmp("DATA", buffer, 4)) {
1068       /* data IN => data OUT */
1069
1070       if(!read_stdin(buffer, 5))
1071         return FALSE;
1072
1073       buffer[5] = '\0';
1074
1075       buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
1076       if (buffer_len > (ssize_t)sizeof(buffer)) {
1077         logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
1078                "(%zd bytes)", sizeof(buffer), buffer_len);
1079         return FALSE;
1080       }
1081       logmsg("> %zd bytes data, server => client", buffer_len);
1082
1083       if(!read_stdin(buffer, buffer_len))
1084         return FALSE;
1085
1086       lograw(buffer, buffer_len);
1087
1088       if(*mode == PASSIVE_LISTEN) {
1089         logmsg("*** We are disconnected!");
1090         if(!write_stdout("DISC\n", 5))
1091           return FALSE;
1092       }
1093       else {
1094         /* send away on the socket */
1095         bytes_written = swrite(sockfd, buffer, buffer_len);
1096         if(bytes_written != buffer_len) {
1097           logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
1098                  buffer_len, bytes_written);
1099         }
1100       }
1101     }
1102     else if(!memcmp("DISC", buffer, 4)) {
1103       /* disconnect! */
1104       if(!write_stdout("DISC\n", 5))
1105         return FALSE;
1106       if(sockfd != CURL_SOCKET_BAD) {
1107         logmsg("====> Client forcibly disconnected");
1108         sclose(sockfd);
1109         *sockfdp = CURL_SOCKET_BAD;
1110         if(*mode == PASSIVE_CONNECT)
1111           *mode = PASSIVE_LISTEN;
1112         else
1113           *mode = ACTIVE_DISCONNECT;
1114       }
1115       else
1116         logmsg("attempt to close already dead connection");
1117       return TRUE;
1118     }
1119   }
1120
1121
1122   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
1123
1124     curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
1125
1126     if(*mode == PASSIVE_LISTEN) {
1127       /* there's no stream set up yet, this is an indication that there's a
1128          client connecting. */
1129       newfd = accept(sockfd, NULL, NULL);
1130       if(CURL_SOCKET_BAD == newfd) {
1131         error = SOCKERRNO;
1132         logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
1133                sockfd, error, strerror(error));
1134       }
1135       else {
1136         logmsg("====> Client connect");
1137         if(!write_stdout("CNCT\n", 5))
1138           return FALSE;
1139         *sockfdp = newfd; /* store the new socket */
1140         *mode = PASSIVE_CONNECT; /* we have connected */
1141       }
1142       return TRUE;
1143     }
1144
1145     /* read from socket, pass on data to stdout */
1146     nread_socket = sread(sockfd, buffer, sizeof(buffer));
1147
1148     if(nread_socket > 0) {
1149       snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
1150       if(!write_stdout(data, 10))
1151         return FALSE;
1152       if(!write_stdout(buffer, nread_socket))
1153         return FALSE;
1154
1155       logmsg("< %zd bytes data, client => server", nread_socket);
1156       lograw(buffer, nread_socket);
1157     }
1158
1159     if(nread_socket <= 0
1160 #ifdef USE_WINSOCK
1161        || FD_ISSET(sockfd, &fds_err)
1162 #endif
1163        ) {
1164       logmsg("====> Client disconnect");
1165       if(!write_stdout("DISC\n", 5))
1166         return FALSE;
1167       sclose(sockfd);
1168       *sockfdp = CURL_SOCKET_BAD;
1169       if(*mode == PASSIVE_CONNECT)
1170         *mode = PASSIVE_LISTEN;
1171       else
1172         *mode = ACTIVE_DISCONNECT;
1173       return TRUE;
1174     }
1175   }
1176
1177   return TRUE;
1178 }
1179
1180 static curl_socket_t sockdaemon(curl_socket_t sock,
1181                                 unsigned short *listenport)
1182 {
1183   /* passive daemon style */
1184   srvr_sockaddr_union_t listener;
1185   int flag;
1186   int rc;
1187   int totdelay = 0;
1188   int maxretr = 10;
1189   int delay= 20;
1190   int attempt = 0;
1191   int error = 0;
1192
1193   do {
1194     attempt++;
1195     flag = 1;
1196     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1197          (void *)&flag, sizeof(flag));
1198     if(rc) {
1199       error = SOCKERRNO;
1200       logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1201              error, strerror(error));
1202       if(maxretr) {
1203         rc = wait_ms(delay);
1204         if(rc) {
1205           /* should not happen */
1206           error = errno;
1207           logmsg("wait_ms() failed with error: (%d) %s",
1208                  error, strerror(error));
1209           sclose(sock);
1210           return CURL_SOCKET_BAD;
1211         }
1212         if(got_exit_signal) {
1213           logmsg("signalled to die, exiting...");
1214           sclose(sock);
1215           return CURL_SOCKET_BAD;
1216         }
1217         totdelay += delay;
1218         delay *= 2; /* double the sleep for next attempt */
1219       }
1220     }
1221   } while(rc && maxretr--);
1222
1223   if(rc) {
1224     logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
1225            attempt, totdelay, error, strerror(error));
1226     logmsg("Continuing anyway...");
1227   }
1228
1229   /* When the specified listener port is zero, it is actually a
1230      request to let the system choose a non-zero available port. */
1231
1232 #ifdef ENABLE_IPV6
1233   if(!use_ipv6) {
1234 #endif
1235     memset(&listener.sa4, 0, sizeof(listener.sa4));
1236     listener.sa4.sin_family = AF_INET;
1237     listener.sa4.sin_addr.s_addr = INADDR_ANY;
1238     listener.sa4.sin_port = htons(*listenport);
1239     rc = bind(sock, &listener.sa, sizeof(listener.sa4));
1240 #ifdef ENABLE_IPV6
1241   }
1242   else {
1243     memset(&listener.sa6, 0, sizeof(listener.sa6));
1244     listener.sa6.sin6_family = AF_INET6;
1245     listener.sa6.sin6_addr = in6addr_any;
1246     listener.sa6.sin6_port = htons(*listenport);
1247     rc = bind(sock, &listener.sa, sizeof(listener.sa6));
1248   }
1249 #endif /* ENABLE_IPV6 */
1250   if(rc) {
1251     error = SOCKERRNO;
1252     logmsg("Error binding socket on port %hu: (%d) %s",
1253            *listenport, error, strerror(error));
1254     sclose(sock);
1255     return CURL_SOCKET_BAD;
1256   }
1257
1258   if(!*listenport) {
1259     /* The system was supposed to choose a port number, figure out which
1260        port we actually got and update the listener port value with it. */
1261     curl_socklen_t la_size;
1262     srvr_sockaddr_union_t localaddr;
1263 #ifdef ENABLE_IPV6
1264     if(!use_ipv6)
1265 #endif
1266       la_size = sizeof(localaddr.sa4);
1267 #ifdef ENABLE_IPV6
1268     else
1269       la_size = sizeof(localaddr.sa6);
1270 #endif
1271     memset(&localaddr.sa, 0, (size_t)la_size);
1272     if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1273       error = SOCKERRNO;
1274       logmsg("getsockname() failed with error: (%d) %s",
1275              error, strerror(error));
1276       sclose(sock);
1277       return CURL_SOCKET_BAD;
1278     }
1279     switch (localaddr.sa.sa_family) {
1280     case AF_INET:
1281       *listenport = ntohs(localaddr.sa4.sin_port);
1282       break;
1283 #ifdef ENABLE_IPV6
1284     case AF_INET6:
1285       *listenport = ntohs(localaddr.sa6.sin6_port);
1286       break;
1287 #endif
1288     default:
1289       break;
1290     }
1291     if(!*listenport) {
1292       /* Real failure, listener port shall not be zero beyond this point. */
1293       logmsg("Apparently getsockname() succeeded, with listener port zero.");
1294       logmsg("A valid reason for this failure is a binary built without");
1295       logmsg("proper network library linkage. This might not be the only");
1296       logmsg("reason, but double check it before anything else.");
1297       sclose(sock);
1298       return CURL_SOCKET_BAD;
1299     }
1300   }
1301
1302   /* bindonly option forces no listening */
1303   if(bind_only) {
1304     logmsg("instructed to bind port without listening");
1305     return sock;
1306   }
1307
1308   /* start accepting connections */
1309   rc = listen(sock, 5);
1310   if(0 != rc) {
1311     error = SOCKERRNO;
1312     logmsg("listen(%d, 5) failed with error: (%d) %s",
1313            sock, error, strerror(error));
1314     sclose(sock);
1315     return CURL_SOCKET_BAD;
1316   }
1317
1318   return sock;
1319 }
1320
1321
1322 int main(int argc, char *argv[])
1323 {
1324   srvr_sockaddr_union_t me;
1325   curl_socket_t sock = CURL_SOCKET_BAD;
1326   curl_socket_t msgsock = CURL_SOCKET_BAD;
1327   int wrotepidfile = 0;
1328   char *pidname= (char *)".sockfilt.pid";
1329   bool juggle_again;
1330   int rc;
1331   int error;
1332   int arg=1;
1333   enum sockmode mode = PASSIVE_LISTEN; /* default */
1334   const char *addr = NULL;
1335
1336   while(argc>arg) {
1337     if(!strcmp("--version", argv[arg])) {
1338       printf("sockfilt IPv4%s\n",
1339 #ifdef ENABLE_IPV6
1340              "/IPv6"
1341 #else
1342              ""
1343 #endif
1344              );
1345       return 0;
1346     }
1347     else if(!strcmp("--verbose", argv[arg])) {
1348       verbose = TRUE;
1349       arg++;
1350     }
1351     else if(!strcmp("--pidfile", argv[arg])) {
1352       arg++;
1353       if(argc>arg)
1354         pidname = argv[arg++];
1355     }
1356     else if(!strcmp("--logfile", argv[arg])) {
1357       arg++;
1358       if(argc>arg)
1359         serverlogfile = argv[arg++];
1360     }
1361     else if(!strcmp("--ipv6", argv[arg])) {
1362 #ifdef ENABLE_IPV6
1363       ipv_inuse = "IPv6";
1364       use_ipv6 = TRUE;
1365 #endif
1366       arg++;
1367     }
1368     else if(!strcmp("--ipv4", argv[arg])) {
1369       /* for completeness, we support this option as well */
1370 #ifdef ENABLE_IPV6
1371       ipv_inuse = "IPv4";
1372       use_ipv6 = FALSE;
1373 #endif
1374       arg++;
1375     }
1376     else if(!strcmp("--bindonly", argv[arg])) {
1377       bind_only = TRUE;
1378       arg++;
1379     }
1380     else if(!strcmp("--port", argv[arg])) {
1381       arg++;
1382       if(argc>arg) {
1383         char *endptr;
1384         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1385         if((endptr != argv[arg] + strlen(argv[arg])) ||
1386            ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1387           fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1388                   argv[arg]);
1389           return 0;
1390         }
1391         port = curlx_ultous(ulnum);
1392         arg++;
1393       }
1394     }
1395     else if(!strcmp("--connect", argv[arg])) {
1396       /* Asked to actively connect to the specified local port instead of
1397          doing a passive server-style listening. */
1398       arg++;
1399       if(argc>arg) {
1400         char *endptr;
1401         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1402         if((endptr != argv[arg] + strlen(argv[arg])) ||
1403            (ulnum < 1025UL) || (ulnum > 65535UL)) {
1404           fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1405                   argv[arg]);
1406           return 0;
1407         }
1408         connectport = curlx_ultous(ulnum);
1409         arg++;
1410       }
1411     }
1412     else if(!strcmp("--addr", argv[arg])) {
1413       /* Set an IP address to use with --connect; otherwise use localhost */
1414       arg++;
1415       if(argc>arg) {
1416         addr = argv[arg];
1417         arg++;
1418       }
1419     }
1420     else {
1421       puts("Usage: sockfilt [option]\n"
1422            " --version\n"
1423            " --verbose\n"
1424            " --logfile [file]\n"
1425            " --pidfile [file]\n"
1426            " --ipv4\n"
1427            " --ipv6\n"
1428            " --bindonly\n"
1429            " --port [port]\n"
1430            " --connect [port]\n"
1431            " --addr [address]");
1432       return 0;
1433     }
1434   }
1435
1436 #ifdef WIN32
1437   win32_init();
1438   atexit(win32_cleanup);
1439
1440   setmode(fileno(stdin), O_BINARY);
1441   setmode(fileno(stdout), O_BINARY);
1442   setmode(fileno(stderr), O_BINARY);
1443 #endif
1444
1445   install_signal_handlers();
1446
1447 #ifdef ENABLE_IPV6
1448   if(!use_ipv6)
1449 #endif
1450     sock = socket(AF_INET, SOCK_STREAM, 0);
1451 #ifdef ENABLE_IPV6
1452   else
1453     sock = socket(AF_INET6, SOCK_STREAM, 0);
1454 #endif
1455
1456   if(CURL_SOCKET_BAD == sock) {
1457     error = SOCKERRNO;
1458     logmsg("Error creating socket: (%d) %s",
1459            error, strerror(error));
1460     write_stdout("FAIL\n", 5);
1461     goto sockfilt_cleanup;
1462   }
1463
1464   if(connectport) {
1465     /* Active mode, we should connect to the given port number */
1466     mode = ACTIVE;
1467 #ifdef ENABLE_IPV6
1468     if(!use_ipv6) {
1469 #endif
1470       memset(&me.sa4, 0, sizeof(me.sa4));
1471       me.sa4.sin_family = AF_INET;
1472       me.sa4.sin_port = htons(connectport);
1473       me.sa4.sin_addr.s_addr = INADDR_ANY;
1474       if (!addr)
1475         addr = "127.0.0.1";
1476       Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1477
1478       rc = connect(sock, &me.sa, sizeof(me.sa4));
1479 #ifdef ENABLE_IPV6
1480     }
1481     else {
1482       memset(&me.sa6, 0, sizeof(me.sa6));
1483       me.sa6.sin6_family = AF_INET6;
1484       me.sa6.sin6_port = htons(connectport);
1485       if (!addr)
1486         addr = "::1";
1487       Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1488
1489       rc = connect(sock, &me.sa, sizeof(me.sa6));
1490     }
1491 #endif /* ENABLE_IPV6 */
1492     if(rc) {
1493       error = SOCKERRNO;
1494       logmsg("Error connecting to port %hu: (%d) %s",
1495              connectport, error, strerror(error));
1496       write_stdout("FAIL\n", 5);
1497       goto sockfilt_cleanup;
1498     }
1499     logmsg("====> Client connect");
1500     msgsock = sock; /* use this as stream */
1501   }
1502   else {
1503     /* passive daemon style */
1504     sock = sockdaemon(sock, &port);
1505     if(CURL_SOCKET_BAD == sock) {
1506       write_stdout("FAIL\n", 5);
1507       goto sockfilt_cleanup;
1508     }
1509     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1510   }
1511
1512   logmsg("Running %s version", ipv_inuse);
1513
1514   if(connectport)
1515     logmsg("Connected to port %hu", connectport);
1516   else if(bind_only)
1517     logmsg("Bound without listening on port %hu", port);
1518   else
1519     logmsg("Listening on port %hu", port);
1520
1521   wrotepidfile = write_pidfile(pidname);
1522   if(!wrotepidfile) {
1523     write_stdout("FAIL\n", 5);
1524     goto sockfilt_cleanup;
1525   }
1526
1527   do {
1528     juggle_again = juggle(&msgsock, sock, &mode);
1529   } while(juggle_again);
1530
1531 sockfilt_cleanup:
1532
1533   if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1534     sclose(msgsock);
1535
1536   if(sock != CURL_SOCKET_BAD)
1537     sclose(sock);
1538
1539   if(wrotepidfile)
1540     unlink(pidname);
1541
1542   restore_signal_handlers();
1543
1544   if(got_exit_signal) {
1545     logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1546     /*
1547      * To properly set the return status of the process we
1548      * must raise the same signal SIGINT or SIGTERM that we
1549      * caught and let the old handler take care of it.
1550      */
1551     raise(exit_signal);
1552   }
1553
1554   logmsg("============> sockfilt quits");
1555   return 0;
1556 }
1557