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