1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
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.haxx.se/docs/copyright.html.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
22 #include "server_setup.h"
26 * 1. Accept a TCP connection on a custom port (IPv4 or IPv6), or connect
27 * to a given (localhost) port.
29 * 2. Get commands on STDIN. Pass data on to the TCP stream.
30 * Get data from TCP stream and pass on to STDOUT.
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:
37 * o We want the perl code to work with rather old perl installations, thus
38 * we cannot use recent perl modules or features.
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.
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.
47 * (Source originally based on sws.c)
51 * Signal handling notes for sockfilt
52 * ----------------------------------
54 * This program is a single-threaded process.
56 * This program is intended to be highly portable and as such it must be kept
57 * as simple as possible, due to this the only signal handling mechanisms used
58 * will be those of ANSI C, and used only in the most basic form which is good
59 * enough for the purpose of this program.
61 * For the above reason and the specific needs of this program signals SIGHUP,
62 * SIGPIPE and SIGALRM will be simply ignored on systems where this can be
63 * done. If possible, signals SIGINT and SIGTERM will be handled by this
64 * program as an indication to cleanup and finish execution as soon as
65 * possible. This will be achieved with a single signal handler
66 * 'exit_signal_handler' for both signals.
68 * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal
69 * will just set to one the global var 'got_exit_signal' storing in global var
70 * 'exit_signal' the signal that triggered this change.
72 * Nothing fancy that could introduce problems is used, the program at certain
73 * points in its normal flow checks if var 'got_exit_signal' is set and in
74 * case this is true it just makes its way out of loops and functions in
75 * structured and well behaved manner to achieve proper program cleanup and
78 * Even with the above mechanism implemented it is worthwile to note that
79 * other signals might still be received, or that there might be systems on
80 * which it is not possible to trap and ignore some of the above signals.
81 * This implies that for increased portability and reliability the program
82 * must be coded as if no signal was being ignored or handled at all. Enjoy
89 #ifdef HAVE_NETINET_IN_H
90 #include <netinet/in.h>
92 #ifdef HAVE_NETINET_IN6_H
93 #include <netinet/in6.h>
95 #ifdef HAVE_ARPA_INET_H
96 #include <arpa/inet.h>
102 #define ENABLE_CURLX_PRINTF
103 /* make the curlx header define all printf() functions to use the curlx_*
105 #include "curlx.h" /* from the private lib dir */
107 #include "inet_pton.h"
109 #include "server_sockaddr.h"
110 #include "warnless.h"
112 /* include memdebug.h last */
113 #include "memdebug.h"
117 #define EINTR 4 /* errno.h value */
119 #define EAGAIN 11 /* errno.h value */
121 #define ENOMEM 12 /* errno.h value */
123 #define EINVAL 22 /* errno.h value */
126 #define DEFAULT_PORT 8999
128 #ifndef DEFAULT_LOGFILE
129 #define DEFAULT_LOGFILE "log/sockfilt.log"
132 const char *serverlogfile = DEFAULT_LOGFILE;
134 static bool verbose = FALSE;
135 static bool bind_only = FALSE;
137 static bool use_ipv6 = FALSE;
139 static const char *ipv_inuse = "IPv4";
140 static unsigned short port = DEFAULT_PORT;
141 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
144 PASSIVE_LISTEN, /* as a server waiting for connections */
145 PASSIVE_CONNECT, /* as a server, connected to a client */
146 ACTIVE, /* as a client, connected to a server */
147 ACTIVE_DISCONNECT /* as a client, disconnected from server */
150 /* do-nothing macro replacement for systems which lack siginterrupt() */
152 #ifndef HAVE_SIGINTERRUPT
153 #define siginterrupt(x,y) do {} while(0)
156 /* vars used to keep around previous signal handlers */
158 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
161 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
165 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
169 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
173 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
177 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
180 #if defined(SIGBREAK) && defined(WIN32)
181 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
184 /* var which if set indicates that the program should finish execution */
186 SIG_ATOMIC_T got_exit_signal = 0;
188 /* if next is set indicates the first signal handled in exit_signal_handler */
190 static volatile int exit_signal = 0;
192 /* signal handler that will be triggered to indicate that the program
193 should finish its execution in a controlled manner as soon as possible.
194 The first time this is called it will set got_exit_signal to one and
195 store in exit_signal the signal that triggered its execution. */
197 static RETSIGTYPE exit_signal_handler(int signum)
199 int old_errno = errno;
200 if(got_exit_signal == 0) {
202 exit_signal = signum;
204 (void)signal(signum, exit_signal_handler);
208 static void install_signal_handlers(void)
211 /* ignore SIGHUP signal */
212 old_sighup_handler = signal(SIGHUP, SIG_IGN);
213 if(old_sighup_handler == SIG_ERR)
214 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
217 /* ignore SIGPIPE signal */
218 old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
219 if(old_sigpipe_handler == SIG_ERR)
220 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
223 /* ignore SIGALRM signal */
224 old_sigalrm_handler = signal(SIGALRM, SIG_IGN);
225 if(old_sigalrm_handler == SIG_ERR)
226 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
229 /* handle SIGINT signal with our exit_signal_handler */
230 old_sigint_handler = signal(SIGINT, exit_signal_handler);
231 if(old_sigint_handler == SIG_ERR)
232 logmsg("cannot install SIGINT handler: %s", strerror(errno));
234 siginterrupt(SIGINT, 1);
237 /* handle SIGTERM signal with our exit_signal_handler */
238 old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
239 if(old_sigterm_handler == SIG_ERR)
240 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
242 siginterrupt(SIGTERM, 1);
244 #if defined(SIGBREAK) && defined(WIN32)
245 /* handle SIGBREAK signal with our exit_signal_handler */
246 old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
247 if(old_sigbreak_handler == SIG_ERR)
248 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
250 siginterrupt(SIGBREAK, 1);
254 static void restore_signal_handlers(void)
257 if(SIG_ERR != old_sighup_handler)
258 (void)signal(SIGHUP, old_sighup_handler);
261 if(SIG_ERR != old_sigpipe_handler)
262 (void)signal(SIGPIPE, old_sigpipe_handler);
265 if(SIG_ERR != old_sigalrm_handler)
266 (void)signal(SIGALRM, old_sigalrm_handler);
269 if(SIG_ERR != old_sigint_handler)
270 (void)signal(SIGINT, old_sigint_handler);
273 if(SIG_ERR != old_sigterm_handler)
274 (void)signal(SIGTERM, old_sigterm_handler);
276 #if defined(SIGBREAK) && defined(WIN32)
277 if(SIG_ERR != old_sigbreak_handler)
278 (void)signal(SIGBREAK, old_sigbreak_handler);
284 * read-wrapper to support reading from stdin on Windows.
286 static ssize_t read_wincon(int fd, void *buf, size_t count)
288 HANDLE handle = NULL;
289 DWORD mode, rcount = 0;
292 if(fd == fileno(stdin)) {
293 handle = GetStdHandle(STD_INPUT_HANDLE);
296 return read(fd, buf, count);
299 if(GetConsoleMode(handle, &mode)) {
300 success = ReadConsole(handle, buf, curlx_uztoul(count), &rcount, NULL);
303 success = ReadFile(handle, buf, curlx_uztoul(count), &rcount, NULL);
309 errno = GetLastError();
313 #define read(a,b,c) read_wincon(a,b,c)
316 * write-wrapper to support writing to stdout and stderr on Windows.
318 static ssize_t write_wincon(int fd, const void *buf, size_t count)
320 HANDLE handle = NULL;
321 DWORD mode, wcount = 0;
324 if(fd == fileno(stdout)) {
325 handle = GetStdHandle(STD_OUTPUT_HANDLE);
327 else if(fd == fileno(stderr)) {
328 handle = GetStdHandle(STD_ERROR_HANDLE);
331 return write(fd, buf, count);
334 if(GetConsoleMode(handle, &mode)) {
335 success = WriteConsole(handle, buf, curlx_uztoul(count), &wcount, NULL);
338 success = WriteFile(handle, buf, curlx_uztoul(count), &wcount, NULL);
344 errno = GetLastError();
348 #define write(a,b,c) write_wincon(a,b,c)
352 * fullread is a wrapper around the read() function. This will repeat the call
353 * to read() until it actually has read the complete number of bytes indicated
354 * in nbytes or it fails with a condition that cannot be handled with a simple
355 * retry of the read call.
358 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
365 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
367 if(got_exit_signal) {
368 logmsg("signalled to die");
374 if((error == EINTR) || (error == EAGAIN))
376 logmsg("reading from file descriptor: %d,", filedes);
377 logmsg("unrecoverable read() failure: (%d) %s",
378 error, strerror(error));
383 logmsg("got 0 reading from stdin");
389 } while((size_t)nread < nbytes);
392 logmsg("read %zd bytes", nread);
398 * fullwrite is a wrapper around the write() function. This will repeat the
399 * call to write() until it actually has written the complete number of bytes
400 * indicated in nbytes or it fails with a condition that cannot be handled
401 * with a simple retry of the write call.
404 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
411 wc = write(filedes, (const unsigned char *)buffer + nwrite,
414 if(got_exit_signal) {
415 logmsg("signalled to die");
421 if((error == EINTR) || (error == EAGAIN))
423 logmsg("writing to file descriptor: %d,", filedes);
424 logmsg("unrecoverable write() failure: (%d) %s",
425 error, strerror(error));
430 logmsg("put 0 writing to stdout");
436 } while((size_t)nwrite < nbytes);
439 logmsg("wrote %zd bytes", nwrite);
445 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
446 * blocking function that will only return TRUE when nbytes have actually been
447 * read or FALSE when an unrecoverable error has been detected. Failure of this
448 * function is an indication that the sockfilt process should terminate.
451 static bool read_stdin(void *buffer, size_t nbytes)
453 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
454 if(nread != (ssize_t)nbytes) {
455 logmsg("exiting...");
462 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
463 * blocking function that will only return TRUE when nbytes have actually been
464 * written or FALSE when an unrecoverable error has been detected. Failure of
465 * this function is an indication that the sockfilt process should terminate.
468 static bool write_stdout(const void *buffer, size_t nbytes)
470 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
471 if(nwrite != (ssize_t)nbytes) {
472 logmsg("exiting...");
478 static void lograw(unsigned char *buffer, ssize_t len)
482 unsigned char *ptr = buffer;
485 int left = sizeof(data);
487 for(i = 0; i<len; i++) {
490 snprintf(optr, left, "\\n");
496 snprintf(optr, left, "\\r");
502 snprintf(optr, left, "%c", (ISGRAPH(ptr[i]) ||
503 ptr[i] == 0x20) ?ptr[i]:'.');
511 logmsg("'%s'", data);
518 logmsg("'%s'", data);
523 * WinSock select() does not support standard file descriptors,
524 * it can only check SOCKETs. The following function is an attempt
525 * to re-create a select() function with support for other handle types.
527 * select() function with support for WINSOCK2 sockets and all
528 * other handle types supported by WaitForMultipleObjectsEx() as
529 * well as disk files, anonymous and names pipes, and character input.
531 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
532 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
534 struct select_ws_wait_data {
535 HANDLE handle; /* actual handle to wait for during select */
536 HANDLE event; /* internal event to abort waiting thread */
538 static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter)
540 struct select_ws_wait_data *data;
541 HANDLE handle, handles[2];
542 INPUT_RECORD inputrecord;
543 LARGE_INTEGER size, pos;
546 /* retrieve handles from internal structure */
547 data = (struct select_ws_wait_data *) lpParameter;
549 handle = data->handle;
550 handles[0] = data->event;
557 /* retrieve the type of file to wait on */
558 type = GetFileType(handle);
561 /* The handle represents a file on disk, this means:
562 * - WaitForMultipleObjectsEx will always be signalled for it.
563 * - comparison of current position in file and total size of
564 * the file can be used to check if we reached the end yet.
566 * Approach: Loop till either the internal event is signalled
567 * or if the end of the file has already been reached.
569 while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE)
571 /* get total size of file */
574 size.LowPart = GetFileSize(handle, &length);
575 if((size.LowPart != INVALID_FILE_SIZE) ||
576 (GetLastError() == NO_ERROR)) {
577 size.HighPart = length;
578 /* get the current position within the file */
580 pos.LowPart = SetFilePointer(handle, 0, &pos.HighPart,
582 if((pos.LowPart != INVALID_SET_FILE_POINTER) ||
583 (GetLastError() == NO_ERROR)) {
584 /* compare position with size, abort if not equal */
585 if(size.QuadPart == pos.QuadPart) {
586 /* sleep and continue waiting */
592 /* there is some data available, stop waiting */
598 /* The handle represents a character input, this means:
599 * - WaitForMultipleObjectsEx will be signalled on any kind of input,
600 * including mouse and window size events we do not care about.
602 * Approach: Loop till either the internal event is signalled
603 * or we get signalled for an actual key-event.
605 while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
606 == WAIT_OBJECT_0 + 1) {
607 /* check if this is an actual console handle */
609 if(GetConsoleMode(handle, &length)) {
610 /* retrieve an event from the console buffer */
612 if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
613 /* check if the event is not an actual key-event */
614 if(length == 1 && inputrecord.EventType != KEY_EVENT) {
615 /* purge the non-key-event and continue waiting */
616 ReadConsoleInput(handle, &inputrecord, 1, &length);
621 /* there is some data available, stop waiting */
627 /* The handle represents an anonymous or named pipe, this means:
628 * - WaitForMultipleObjectsEx will always be signalled for it.
629 * - peek into the pipe and retrieve the amount of data available.
631 * Approach: Loop till either the internal event is signalled
632 * or there is data in the pipe available for reading.
634 while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE)
636 /* peek into the pipe and retrieve the amount of data available */
638 if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
639 /* if there is no data available, sleep and continue waiting */
646 /* if the pipe has been closed, sleep and continue waiting */
647 if(GetLastError() == ERROR_BROKEN_PIPE) {
652 /* there is some data available, stop waiting */
658 /* The handle has an unknown type, try to wait on it */
659 WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE);
665 static HANDLE select_ws_wait(HANDLE handle, HANDLE event)
667 struct select_ws_wait_data *data;
668 HANDLE thread = NULL;
670 /* allocate internal waiting data structure */
671 data = malloc(sizeof(struct select_ws_wait_data));
673 data->handle = handle;
676 /* launch waiting thread */
677 thread = CreateThread(NULL, 0,
678 &select_ws_wait_thread,
681 /* free data if thread failed to launch */
689 struct select_ws_data {
690 curl_socket_t fd; /* the original input handle (indexed by fds) */
691 curl_socket_t wsasock; /* the internal socket handle (indexed by wsa) */
692 WSAEVENT wsaevent; /* the internal WINSOCK2 event (indexed by wsa) */
693 HANDLE thread; /* the internal threads handle (indexed by thd) */
695 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
696 fd_set *exceptfds, struct timeval *timeout)
698 DWORD milliseconds, wait, idx;
699 WSANETWORKEVENTS wsanetevents;
700 struct select_ws_data *data;
701 HANDLE handle, *handles;
706 HANDLE waitevent = NULL;
707 DWORD nfd = 0, thd = 0, wsa = 0;
710 /* check if the input value is valid */
716 /* check if we got descriptors, sleep in case we got none */
718 Sleep((timeout->tv_sec*1000)+(DWORD)(((double)timeout->tv_usec)/1000.0));
722 /* create internal event to signal waiting threads */
723 waitevent = CreateEvent(NULL, TRUE, FALSE, NULL);
729 /* allocate internal array for the internal data */
730 data = malloc(nfds * sizeof(struct select_ws_data));
736 /* allocate internal array for the internal event handles */
737 handles = malloc(nfds * sizeof(HANDLE));
738 if(handles == NULL) {
744 /* clear internal arrays */
745 memset(data, 0, nfds * sizeof(struct select_ws_data));
746 memset(handles, 0, nfds * sizeof(HANDLE));
748 /* loop over the handles in the input descriptor sets */
749 for(fds = 0; fds < nfds; fds++) {
753 if(FD_ISSET(fds, readfds))
754 networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
756 if(FD_ISSET(fds, writefds))
757 networkevents |= FD_WRITE|FD_CONNECT;
759 if(FD_ISSET(fds, exceptfds))
760 networkevents |= FD_OOB|FD_CLOSE;
762 /* only wait for events for which we actually care */
764 data[nfd].fd = curlx_sitosk(fds);
765 if(fds == fileno(stdin)) {
766 handle = GetStdHandle(STD_INPUT_HANDLE);
767 handle = select_ws_wait(handle, waitevent);
768 handles[nfd] = handle;
769 data[thd].thread = handle;
772 else if(fds == fileno(stdout)) {
773 handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
775 else if(fds == fileno(stderr)) {
776 handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
779 wsaevent = WSACreateEvent();
780 if(wsaevent != WSA_INVALID_EVENT) {
781 error = WSAEventSelect(fds, wsaevent, networkevents);
782 if(error != SOCKET_ERROR) {
783 handle = (HANDLE) wsaevent;
784 handles[nfd] = handle;
785 data[wsa].wsasock = curlx_sitosk(fds);
786 data[wsa].wsaevent = wsaevent;
790 WSACloseEvent(wsaevent);
791 handle = (HANDLE) curlx_sitosk(fds);
792 handle = select_ws_wait(handle, waitevent);
793 handles[nfd] = handle;
794 data[thd].thread = handle;
803 /* convert struct timeval to milliseconds */
805 milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
808 milliseconds = INFINITE;
811 /* wait for one of the internal handles to trigger */
812 wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
814 /* signal the event handle for the waiting threads */
817 /* loop over the internal handles returned in the descriptors */
818 for(idx = 0; idx < nfd; idx++) {
819 handle = handles[idx];
821 fds = curlx_sktosi(sock);
823 /* check if the current internal handle was triggered */
824 if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
825 WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
826 /* first handle stdin, stdout and stderr */
827 if(fds == fileno(stdin)) {
828 /* stdin is never ready for write or exceptional */
829 FD_CLR(sock, writefds);
830 FD_CLR(sock, exceptfds);
832 else if(fds == fileno(stdout) || fds == fileno(stderr)) {
833 /* stdout and stderr are never ready for read or exceptional */
834 FD_CLR(sock, readfds);
835 FD_CLR(sock, exceptfds);
838 /* try to handle the event with the WINSOCK2 functions */
839 wsanetevents.lNetworkEvents = 0;
840 error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
841 if(error != SOCKET_ERROR) {
842 /* remove from descriptor set if not ready for read/accept/close */
843 if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
844 FD_CLR(sock, readfds);
846 /* remove from descriptor set if not ready for write/connect */
847 if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
848 FD_CLR(sock, writefds);
851 * use exceptfds together with readfds to signal
852 * that the connection was closed by the client.
854 * Reason: FD_CLOSE is only signaled once, sometimes
855 * at the same time as FD_READ with data being available.
856 * This means that recv/sread is not reliable to detect
857 * that the connection is closed.
859 /* remove from descriptor set if not exceptional */
860 if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
861 FD_CLR(sock, exceptfds);
865 /* check if the event has not been filtered using specific tests */
866 if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
867 FD_ISSET(sock, exceptfds)) {
872 /* remove from all descriptor sets since this handle did not trigger */
873 FD_CLR(sock, readfds);
874 FD_CLR(sock, writefds);
875 FD_CLR(sock, exceptfds);
879 for(fds = 0; fds < nfds; fds++) {
880 if(FD_ISSET(fds, readfds))
881 logmsg("select_ws: %d is readable", fds);
883 if(FD_ISSET(fds, writefds))
884 logmsg("select_ws: %d is writable", fds);
886 if(FD_ISSET(fds, exceptfds))
887 logmsg("select_ws: %d is excepted", fds);
890 for(idx = 0; idx < wsa; idx++) {
891 WSAEventSelect(data[idx].wsasock, NULL, 0);
892 WSACloseEvent(data[idx].wsaevent);
895 for(idx = 0; idx < thd; idx++) {
896 WaitForSingleObject(data[idx].thread, INFINITE);
897 CloseHandle(data[idx].thread);
900 CloseHandle(waitevent);
907 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
908 #endif /* USE_WINSOCK */
911 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
913 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
916 static bool juggle(curl_socket_t *sockfdp,
917 curl_socket_t listenfd,
920 struct timeval timeout;
924 curl_socket_t sockfd = CURL_SOCKET_BAD;
927 ssize_t nread_socket;
928 ssize_t bytes_written;
932 /* 'buffer' is this excessively large only to be able to support things like
933 test 1003 which tests exceedingly large server response lines */
934 unsigned char buffer[17010];
937 if(got_exit_signal) {
938 logmsg("signalled to die, exiting...");
943 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
944 parent ftpserver process has died without killing its sockfilt children */
946 logmsg("process becomes orphan, exiting");
951 timeout.tv_sec = 120;
958 FD_SET((curl_socket_t)fileno(stdin), &fds_read);
966 /* there's always a socket to wait for */
967 FD_SET(sockfd, &fds_read);
971 case PASSIVE_CONNECT:
974 if(CURL_SOCKET_BAD == sockfd) {
975 /* eeek, we are supposedly connected and then this cannot be -1 ! */
976 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
977 maxfd = 0; /* stdin */
980 /* there's always a socket to wait for */
981 FD_SET(sockfd, &fds_read);
983 FD_SET(sockfd, &fds_err);
992 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
993 if(CURL_SOCKET_BAD != sockfd) {
994 FD_SET(sockfd, &fds_read);
996 FD_SET(sockfd, &fds_err);
1001 logmsg("No socket to read on");
1006 case ACTIVE_DISCONNECT:
1008 logmsg("disconnected, no socket to read on");
1010 sockfd = CURL_SOCKET_BAD;
1013 } /* switch(*mode) */
1018 /* select() blocking behavior call on blocking descriptors please */
1020 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
1022 if(got_exit_signal) {
1023 logmsg("signalled to die, exiting...");
1027 } while((rc == -1) && ((error = errno) == EINTR));
1030 logmsg("select() failed with error: (%d) %s",
1031 error, strerror(error));
1040 if(FD_ISSET(fileno(stdin), &fds_read)) {
1041 /* read from stdin, commands/data to be dealt with and possibly passed on
1046 4 letter command + LF [mandatory]
1048 4-digit hexadecimal data length + LF [if the command takes data]
1049 data [the data being as long as set above]
1053 DATA - plain pass-through data
1056 if(!read_stdin(buffer, 5))
1059 logmsg("Received %c%c%c%c (on stdin)",
1060 buffer[0], buffer[1], buffer[2], buffer[3]);
1062 if(!memcmp("PING", buffer, 4)) {
1063 /* send reply on stdout, just proving we are alive */
1064 if(!write_stdout("PONG\n", 5))
1068 else if(!memcmp("PORT", buffer, 4)) {
1069 /* Question asking us what PORT number we are listening to.
1070 Replies to PORT with "IPv[num]/[port]" */
1071 snprintf((char *)buffer, sizeof(buffer), "%s/%hu\n", ipv_inuse, port);
1072 buffer_len = (ssize_t)strlen((char *)buffer);
1073 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
1074 if(!write_stdout(data, 10))
1076 if(!write_stdout(buffer, buffer_len))
1079 else if(!memcmp("QUIT", buffer, 4)) {
1084 else if(!memcmp("DATA", buffer, 4)) {
1085 /* data IN => data OUT */
1087 if(!read_stdin(buffer, 5))
1092 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
1093 if(buffer_len > (ssize_t)sizeof(buffer)) {
1094 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
1095 "(%zd bytes)", sizeof(buffer), buffer_len);
1098 logmsg("> %zd bytes data, server => client", buffer_len);
1100 if(!read_stdin(buffer, buffer_len))
1103 lograw(buffer, buffer_len);
1105 if(*mode == PASSIVE_LISTEN) {
1106 logmsg("*** We are disconnected!");
1107 if(!write_stdout("DISC\n", 5))
1111 /* send away on the socket */
1112 bytes_written = swrite(sockfd, buffer, buffer_len);
1113 if(bytes_written != buffer_len) {
1114 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
1115 buffer_len, bytes_written);
1119 else if(!memcmp("DISC", buffer, 4)) {
1121 if(!write_stdout("DISC\n", 5))
1123 if(sockfd != CURL_SOCKET_BAD) {
1124 logmsg("====> Client forcibly disconnected");
1126 *sockfdp = CURL_SOCKET_BAD;
1127 if(*mode == PASSIVE_CONNECT)
1128 *mode = PASSIVE_LISTEN;
1130 *mode = ACTIVE_DISCONNECT;
1133 logmsg("attempt to close already dead connection");
1139 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
1141 curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
1143 if(*mode == PASSIVE_LISTEN) {
1144 /* there's no stream set up yet, this is an indication that there's a
1145 client connecting. */
1146 newfd = accept(sockfd, NULL, NULL);
1147 if(CURL_SOCKET_BAD == newfd) {
1149 logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
1150 sockfd, error, strerror(error));
1153 logmsg("====> Client connect");
1154 if(!write_stdout("CNCT\n", 5))
1156 *sockfdp = newfd; /* store the new socket */
1157 *mode = PASSIVE_CONNECT; /* we have connected */
1162 /* read from socket, pass on data to stdout */
1163 nread_socket = sread(sockfd, buffer, sizeof(buffer));
1165 if(nread_socket > 0) {
1166 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
1167 if(!write_stdout(data, 10))
1169 if(!write_stdout(buffer, nread_socket))
1172 logmsg("< %zd bytes data, client => server", nread_socket);
1173 lograw(buffer, nread_socket);
1176 if(nread_socket <= 0
1178 || FD_ISSET(sockfd, &fds_err)
1181 logmsg("====> Client disconnect");
1182 if(!write_stdout("DISC\n", 5))
1185 *sockfdp = CURL_SOCKET_BAD;
1186 if(*mode == PASSIVE_CONNECT)
1187 *mode = PASSIVE_LISTEN;
1189 *mode = ACTIVE_DISCONNECT;
1197 static curl_socket_t sockdaemon(curl_socket_t sock,
1198 unsigned short *listenport)
1200 /* passive daemon style */
1201 srvr_sockaddr_union_t listener;
1213 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1214 (void *)&flag, sizeof(flag));
1217 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1218 error, strerror(error));
1220 rc = wait_ms(delay);
1222 /* should not happen */
1224 logmsg("wait_ms() failed with error: (%d) %s",
1225 error, strerror(error));
1227 return CURL_SOCKET_BAD;
1229 if(got_exit_signal) {
1230 logmsg("signalled to die, exiting...");
1232 return CURL_SOCKET_BAD;
1235 delay *= 2; /* double the sleep for next attempt */
1238 } while(rc && maxretr--);
1241 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
1242 attempt, totdelay, error, strerror(error));
1243 logmsg("Continuing anyway...");
1246 /* When the specified listener port is zero, it is actually a
1247 request to let the system choose a non-zero available port. */
1252 memset(&listener.sa4, 0, sizeof(listener.sa4));
1253 listener.sa4.sin_family = AF_INET;
1254 listener.sa4.sin_addr.s_addr = INADDR_ANY;
1255 listener.sa4.sin_port = htons(*listenport);
1256 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
1260 memset(&listener.sa6, 0, sizeof(listener.sa6));
1261 listener.sa6.sin6_family = AF_INET6;
1262 listener.sa6.sin6_addr = in6addr_any;
1263 listener.sa6.sin6_port = htons(*listenport);
1264 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
1266 #endif /* ENABLE_IPV6 */
1269 logmsg("Error binding socket on port %hu: (%d) %s",
1270 *listenport, error, strerror(error));
1272 return CURL_SOCKET_BAD;
1276 /* The system was supposed to choose a port number, figure out which
1277 port we actually got and update the listener port value with it. */
1278 curl_socklen_t la_size;
1279 srvr_sockaddr_union_t localaddr;
1283 la_size = sizeof(localaddr.sa4);
1286 la_size = sizeof(localaddr.sa6);
1288 memset(&localaddr.sa, 0, (size_t)la_size);
1289 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1291 logmsg("getsockname() failed with error: (%d) %s",
1292 error, strerror(error));
1294 return CURL_SOCKET_BAD;
1296 switch(localaddr.sa.sa_family) {
1298 *listenport = ntohs(localaddr.sa4.sin_port);
1302 *listenport = ntohs(localaddr.sa6.sin6_port);
1309 /* Real failure, listener port shall not be zero beyond this point. */
1310 logmsg("Apparently getsockname() succeeded, with listener port zero.");
1311 logmsg("A valid reason for this failure is a binary built without");
1312 logmsg("proper network library linkage. This might not be the only");
1313 logmsg("reason, but double check it before anything else.");
1315 return CURL_SOCKET_BAD;
1319 /* bindonly option forces no listening */
1321 logmsg("instructed to bind port without listening");
1325 /* start accepting connections */
1326 rc = listen(sock, 5);
1329 logmsg("listen(%d, 5) failed with error: (%d) %s",
1330 sock, error, strerror(error));
1332 return CURL_SOCKET_BAD;
1339 int main(int argc, char *argv[])
1341 srvr_sockaddr_union_t me;
1342 curl_socket_t sock = CURL_SOCKET_BAD;
1343 curl_socket_t msgsock = CURL_SOCKET_BAD;
1344 int wrotepidfile = 0;
1345 const char *pidname = ".sockfilt.pid";
1350 enum sockmode mode = PASSIVE_LISTEN; /* default */
1351 const char *addr = NULL;
1354 if(!strcmp("--version", argv[arg])) {
1355 printf("sockfilt IPv4%s\n",
1364 else if(!strcmp("--verbose", argv[arg])) {
1368 else if(!strcmp("--pidfile", argv[arg])) {
1371 pidname = argv[arg++];
1373 else if(!strcmp("--logfile", argv[arg])) {
1376 serverlogfile = argv[arg++];
1378 else if(!strcmp("--ipv6", argv[arg])) {
1385 else if(!strcmp("--ipv4", argv[arg])) {
1386 /* for completeness, we support this option as well */
1393 else if(!strcmp("--bindonly", argv[arg])) {
1397 else if(!strcmp("--port", argv[arg])) {
1401 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1402 if((endptr != argv[arg] + strlen(argv[arg])) ||
1403 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1404 fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1408 port = curlx_ultous(ulnum);
1412 else if(!strcmp("--connect", argv[arg])) {
1413 /* Asked to actively connect to the specified local port instead of
1414 doing a passive server-style listening. */
1418 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1419 if((endptr != argv[arg] + strlen(argv[arg])) ||
1420 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1421 fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1425 connectport = curlx_ultous(ulnum);
1429 else if(!strcmp("--addr", argv[arg])) {
1430 /* Set an IP address to use with --connect; otherwise use localhost */
1438 puts("Usage: sockfilt [option]\n"
1441 " --logfile [file]\n"
1442 " --pidfile [file]\n"
1447 " --connect [port]\n"
1448 " --addr [address]");
1455 atexit(win32_cleanup);
1457 setmode(fileno(stdin), O_BINARY);
1458 setmode(fileno(stdout), O_BINARY);
1459 setmode(fileno(stderr), O_BINARY);
1462 install_signal_handlers();
1467 sock = socket(AF_INET, SOCK_STREAM, 0);
1470 sock = socket(AF_INET6, SOCK_STREAM, 0);
1473 if(CURL_SOCKET_BAD == sock) {
1475 logmsg("Error creating socket: (%d) %s",
1476 error, strerror(error));
1477 write_stdout("FAIL\n", 5);
1478 goto sockfilt_cleanup;
1482 /* Active mode, we should connect to the given port number */
1487 memset(&me.sa4, 0, sizeof(me.sa4));
1488 me.sa4.sin_family = AF_INET;
1489 me.sa4.sin_port = htons(connectport);
1490 me.sa4.sin_addr.s_addr = INADDR_ANY;
1493 Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1495 rc = connect(sock, &me.sa, sizeof(me.sa4));
1499 memset(&me.sa6, 0, sizeof(me.sa6));
1500 me.sa6.sin6_family = AF_INET6;
1501 me.sa6.sin6_port = htons(connectport);
1504 Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1506 rc = connect(sock, &me.sa, sizeof(me.sa6));
1508 #endif /* ENABLE_IPV6 */
1511 logmsg("Error connecting to port %hu: (%d) %s",
1512 connectport, error, strerror(error));
1513 write_stdout("FAIL\n", 5);
1514 goto sockfilt_cleanup;
1516 logmsg("====> Client connect");
1517 msgsock = sock; /* use this as stream */
1520 /* passive daemon style */
1521 sock = sockdaemon(sock, &port);
1522 if(CURL_SOCKET_BAD == sock) {
1523 write_stdout("FAIL\n", 5);
1524 goto sockfilt_cleanup;
1526 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1529 logmsg("Running %s version", ipv_inuse);
1532 logmsg("Connected to port %hu", connectport);
1534 logmsg("Bound without listening on port %hu", port);
1536 logmsg("Listening on port %hu", port);
1538 wrotepidfile = write_pidfile(pidname);
1540 write_stdout("FAIL\n", 5);
1541 goto sockfilt_cleanup;
1545 juggle_again = juggle(&msgsock, sock, &mode);
1546 } while(juggle_again);
1550 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1553 if(sock != CURL_SOCKET_BAD)
1559 restore_signal_handlers();
1561 if(got_exit_signal) {
1562 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1564 * To properly set the return status of the process we
1565 * must raise the same signal SIGINT or SIGTERM that we
1566 * caught and let the old handler take care of it.
1571 logmsg("============> sockfilt quits");