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