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