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