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