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