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