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