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