1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2014, 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 http://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 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.
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.
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.
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.
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!
86 #ifdef HAVE_NETINET_IN_H
87 #include <netinet/in.h>
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
96 #define ENABLE_CURLX_PRINTF
97 /* make the curlx header define all printf() functions to use the curlx_*
99 #include "curlx.h" /* from the private lib dir */
101 #include "inet_pton.h"
103 #include "server_sockaddr.h"
104 #include "warnless.h"
106 /* include memdebug.h last */
107 #include "memdebug.h"
111 #define EINTR 4 /* errno.h value */
113 #define EAGAIN 11 /* errno.h value */
115 #define ENOMEM 12 /* errno.h value */
117 #define EINVAL 22 /* errno.h value */
120 #define DEFAULT_PORT 8999
122 #ifndef DEFAULT_LOGFILE
123 #define DEFAULT_LOGFILE "log/sockfilt.log"
126 const char *serverlogfile = DEFAULT_LOGFILE;
128 static bool verbose = FALSE;
129 static bool bind_only = FALSE;
131 static bool use_ipv6 = FALSE;
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 */
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 */
144 /* do-nothing macro replacement for systems which lack siginterrupt() */
146 #ifndef HAVE_SIGINTERRUPT
147 #define siginterrupt(x,y) do {} while(0)
150 /* vars used to keep around previous signal handlers */
152 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
155 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
159 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
163 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
167 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
171 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
174 #if defined(SIGBREAK) && defined(WIN32)
175 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
178 /* var which if set indicates that the program should finish execution */
180 SIG_ATOMIC_T got_exit_signal = 0;
182 /* if next is set indicates the first signal handled in exit_signal_handler */
184 static volatile int exit_signal = 0;
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. */
191 static RETSIGTYPE exit_signal_handler(int signum)
193 int old_errno = errno;
194 if(got_exit_signal == 0) {
196 exit_signal = signum;
198 (void)signal(signum, exit_signal_handler);
202 static void install_signal_handlers(void)
205 /* ignore SIGHUP signal */
206 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
207 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
210 /* ignore SIGPIPE signal */
211 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
212 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
215 /* ignore SIGALRM signal */
216 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
217 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
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));
224 siginterrupt(SIGINT, 1);
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));
231 siginterrupt(SIGTERM, 1);
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));
238 siginterrupt(SIGBREAK, 1);
242 static void restore_signal_handlers(void)
245 if(SIG_ERR != old_sighup_handler)
246 (void)signal(SIGHUP, old_sighup_handler);
249 if(SIG_ERR != old_sigpipe_handler)
250 (void)signal(SIGPIPE, old_sigpipe_handler);
253 if(SIG_ERR != old_sigalrm_handler)
254 (void)signal(SIGALRM, old_sigalrm_handler);
257 if(SIG_ERR != old_sigint_handler)
258 (void)signal(SIGINT, old_sigint_handler);
261 if(SIG_ERR != old_sigterm_handler)
262 (void)signal(SIGTERM, old_sigterm_handler);
264 #if defined(SIGBREAK) && defined(WIN32)
265 if(SIG_ERR != old_sigbreak_handler)
266 (void)signal(SIGBREAK, old_sigbreak_handler);
272 * read-wrapper to support reading from stdin on Windows.
274 static ssize_t read_wincon(int fd, void *buf, size_t count)
276 HANDLE handle = NULL;
277 DWORD mode, rcount = 0;
280 if(fd == fileno(stdin)) {
281 handle = GetStdHandle(STD_INPUT_HANDLE);
284 return read(fd, buf, count);
287 if(GetConsoleMode(handle, &mode)) {
288 success = ReadConsole(handle, buf, count, &rcount, NULL);
291 success = ReadFile(handle, buf, count, &rcount, NULL);
297 errno = GetLastError();
301 #define read(a,b,c) read_wincon(a,b,c)
304 * write-wrapper to support writing to stdout and stderr on Windows.
306 static ssize_t write_wincon(int fd, const void *buf, size_t count)
308 HANDLE handle = NULL;
309 DWORD mode, wcount = 0;
312 if(fd == fileno(stdout)) {
313 handle = GetStdHandle(STD_OUTPUT_HANDLE);
315 else if(fd == fileno(stderr)) {
316 handle = GetStdHandle(STD_ERROR_HANDLE);
319 return write(fd, buf, count);
322 if(GetConsoleMode(handle, &mode)) {
323 success = WriteConsole(handle, buf, count, &wcount, NULL);
326 success = WriteFile(handle, buf, count, &wcount, NULL);
332 errno = GetLastError();
336 #define write(a,b,c) write_wincon(a,b,c)
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.
346 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
353 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
355 if(got_exit_signal) {
356 logmsg("signalled to die");
362 if((error == EINTR) || (error == EAGAIN))
364 logmsg("reading from file descriptor: %d,", filedes);
365 logmsg("unrecoverable read() failure: (%d) %s",
366 error, strerror(error));
371 logmsg("got 0 reading from stdin");
377 } while((size_t)nread < nbytes);
380 logmsg("read %zd bytes", nread);
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.
392 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
399 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
401 if(got_exit_signal) {
402 logmsg("signalled to die");
408 if((error == EINTR) || (error == EAGAIN))
410 logmsg("writing to file descriptor: %d,", filedes);
411 logmsg("unrecoverable write() failure: (%d) %s",
412 error, strerror(error));
417 logmsg("put 0 writing to stdout");
423 } while((size_t)nwrite < nbytes);
426 logmsg("wrote %zd bytes", nwrite);
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.
438 static bool read_stdin(void *buffer, size_t nbytes)
440 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
441 if(nread != (ssize_t)nbytes) {
442 logmsg("exiting...");
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.
455 static bool write_stdout(const void *buffer, size_t nbytes)
457 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
458 if(nwrite != (ssize_t)nbytes) {
459 logmsg("exiting...");
465 static void lograw(unsigned char *buffer, ssize_t len)
469 unsigned char *ptr = buffer;
473 for(i=0; i<len; i++) {
476 sprintf(optr, "\\n");
481 sprintf(optr, "\\r");
486 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
493 logmsg("'%s'", data);
499 logmsg("'%s'", data);
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.
508 * select() function with support for WINSOCK2 sockets and all
509 * other handle types supported by WaitForMultipleObjectsEx().
511 * TODO: Differentiate between read/write/except for non-SOCKET handles.
513 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
514 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
516 static DWORD WINAPI select_ws_stdin_wait_thread(LPVOID lpParameter)
518 INPUT_RECORD inputrecord;
522 handle = (HANDLE) lpParameter;
524 if(GetConsoleMode(handle, &length)) {
525 while(WaitForSingleObjectEx(handle, INFINITE, FALSE) == WAIT_OBJECT_0) {
526 if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
527 if(length == 1 && inputrecord.EventType != KEY_EVENT)
528 ReadConsoleInput(handle, &inputrecord, 1, &length);
535 ReadFile(handle, NULL, 0, &length, NULL);
539 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
540 fd_set *exceptfds, struct timeval *timeout)
542 DWORD milliseconds, wait, idx;
543 WSAEVENT wsaevent, *wsaevents;
544 WSANETWORKEVENTS wsanetevents;
545 HANDLE handle, *handles;
546 curl_socket_t sock, *fdarr, *wsasocks;
549 DWORD nfd = 0, wsa = 0;
552 /* check if the input value is valid */
558 /* check if we got descriptors, sleep in case we got none */
560 Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
564 /* allocate internal array for the original input handles */
565 fdarr = malloc(nfds * sizeof(curl_socket_t));
571 /* allocate internal array for the internal event handles */
572 handles = malloc(nfds * sizeof(HANDLE));
573 if(handles == NULL) {
579 /* allocate internal array for the internal socket handles */
580 wsasocks = malloc(nfds * sizeof(curl_socket_t));
581 if(wsasocks == NULL) {
588 /* allocate internal array for the internal WINSOCK2 events */
589 wsaevents = malloc(nfds * sizeof(WSAEVENT));
590 if(wsaevents == NULL) {
598 /* loop over the handles in the input descriptor sets */
599 for(fds = 0; fds < nfds; fds++) {
603 if(FD_ISSET(fds, readfds))
604 networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
606 if(FD_ISSET(fds, writefds))
607 networkevents |= FD_WRITE|FD_CONNECT;
609 if(FD_ISSET(fds, exceptfds))
610 networkevents |= FD_OOB|FD_CLOSE;
612 /* only wait for events for which we actually care */
614 fdarr[nfd] = curlx_sitosk(fds);
615 if(fds == fileno(stdin)) {
616 handles[nfd] = CreateThread(NULL, 0,
617 &select_ws_stdin_wait_thread,
618 GetStdHandle(STD_INPUT_HANDLE),
621 else if(fds == fileno(stdout)) {
622 handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
624 else if(fds == fileno(stderr)) {
625 handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
628 wsaevent = WSACreateEvent();
629 if(wsaevent != WSA_INVALID_EVENT) {
630 error = WSAEventSelect(fds, wsaevent, networkevents);
631 if(error != SOCKET_ERROR) {
632 handles[nfd] = wsaevent;
633 wsasocks[wsa] = curlx_sitosk(fds);
634 wsaevents[wsa] = wsaevent;
638 handles[nfd] = (HANDLE) curlx_sitosk(fds);
639 WSACloseEvent(wsaevent);
647 /* convert struct timeval to milliseconds */
649 milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
652 milliseconds = INFINITE;
655 /* wait for one of the internal handles to trigger */
656 wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
658 /* loop over the internal handles returned in the descriptors */
659 for(idx = 0; idx < nfd; idx++) {
660 handle = handles[idx];
662 fds = curlx_sktosi(sock);
664 /* check if the current internal handle was triggered */
665 if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
666 WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
667 /* first handle stdin, stdout and stderr */
668 if(fds == fileno(stdin)) {
669 /* stdin is never ready for write or exceptional */
670 FD_CLR(sock, writefds);
671 FD_CLR(sock, exceptfds);
673 else if(fds == fileno(stdout) || fds == fileno(stderr)) {
674 /* stdout and stderr are never ready for read or exceptional */
675 FD_CLR(sock, readfds);
676 FD_CLR(sock, exceptfds);
679 /* try to handle the event with the WINSOCK2 functions */
680 error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
681 if(error != SOCKET_ERROR) {
682 /* remove from descriptor set if not ready for read/accept/close */
683 if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
684 FD_CLR(sock, readfds);
686 /* remove from descriptor set if not ready for write/connect */
687 if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
688 FD_CLR(sock, writefds);
691 * use exceptfds together with readfds to signal
692 * that the connection was closed by the client.
694 * Reason: FD_CLOSE is only signaled once, sometimes
695 * at the same time as FD_READ with data being available.
696 * This means that recv/sread is not reliable to detect
697 * that the connection is closed.
699 /* remove from descriptor set if not exceptional */
700 if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
701 FD_CLR(sock, exceptfds);
705 /* check if the event has not been filtered using specific tests */
706 if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
707 FD_ISSET(sock, exceptfds)) {
712 /* remove from all descriptor sets since this handle did not trigger */
713 FD_CLR(sock, readfds);
714 FD_CLR(sock, writefds);
715 FD_CLR(sock, exceptfds);
719 for(idx = 0; idx < wsa; idx++) {
720 WSAEventSelect(wsasocks[idx], NULL, 0);
721 WSACloseEvent(wsaevents[idx]);
731 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
732 #endif /* USE_WINSOCK */
735 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
737 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
740 static bool juggle(curl_socket_t *sockfdp,
741 curl_socket_t listenfd,
744 struct timeval timeout;
748 curl_socket_t sockfd = CURL_SOCKET_BAD;
751 ssize_t nread_socket;
752 ssize_t bytes_written;
756 /* 'buffer' is this excessively large only to be able to support things like
757 test 1003 which tests exceedingly large server response lines */
758 unsigned char buffer[17010];
761 if(got_exit_signal) {
762 logmsg("signalled to die, exiting...");
767 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
768 parent ftpserver process has died without killing its sockfilt children */
770 logmsg("process becomes orphan, exiting");
775 timeout.tv_sec = 120;
782 FD_SET((curl_socket_t)fileno(stdin), &fds_read);
790 /* there's always a socket to wait for */
791 FD_SET(sockfd, &fds_read);
795 case PASSIVE_CONNECT:
798 if(CURL_SOCKET_BAD == sockfd) {
799 /* eeek, we are supposedly connected and then this cannot be -1 ! */
800 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
801 maxfd = 0; /* stdin */
804 /* there's always a socket to wait for */
805 FD_SET(sockfd, &fds_read);
807 FD_SET(sockfd, &fds_err);
816 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
817 if(CURL_SOCKET_BAD != sockfd) {
818 FD_SET(sockfd, &fds_read);
820 FD_SET(sockfd, &fds_err);
825 logmsg("No socket to read on");
830 case ACTIVE_DISCONNECT:
832 logmsg("disconnected, no socket to read on");
834 sockfd = CURL_SOCKET_BAD;
837 } /* switch(*mode) */
842 /* select() blocking behavior call on blocking descriptors please */
844 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
846 if(got_exit_signal) {
847 logmsg("signalled to die, exiting...");
851 } while((rc == -1) && ((error = errno) == EINTR));
854 logmsg("select() failed with error: (%d) %s",
855 error, strerror(error));
864 if(FD_ISSET(fileno(stdin), &fds_read)) {
865 /* read from stdin, commands/data to be dealt with and possibly passed on
870 4 letter command + LF [mandatory]
872 4-digit hexadecimal data length + LF [if the command takes data]
873 data [the data being as long as set above]
877 DATA - plain pass-thru data
880 if(!read_stdin(buffer, 5))
883 logmsg("Received %c%c%c%c (on stdin)",
884 buffer[0], buffer[1], buffer[2], buffer[3] );
886 if(!memcmp("PING", buffer, 4)) {
887 /* send reply on stdout, just proving we are alive */
888 if(!write_stdout("PONG\n", 5))
892 else if(!memcmp("PORT", buffer, 4)) {
893 /* Question asking us what PORT number we are listening to.
894 Replies to PORT with "IPv[num]/[port]" */
895 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
896 buffer_len = (ssize_t)strlen((char *)buffer);
897 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
898 if(!write_stdout(data, 10))
900 if(!write_stdout(buffer, buffer_len))
903 else if(!memcmp("QUIT", buffer, 4)) {
908 else if(!memcmp("DATA", buffer, 4)) {
909 /* data IN => data OUT */
911 if(!read_stdin(buffer, 5))
916 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
917 if (buffer_len > (ssize_t)sizeof(buffer)) {
918 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
919 "(%zd bytes)", sizeof(buffer), buffer_len);
922 logmsg("> %zd bytes data, server => client", buffer_len);
924 if(!read_stdin(buffer, buffer_len))
927 lograw(buffer, buffer_len);
929 if(*mode == PASSIVE_LISTEN) {
930 logmsg("*** We are disconnected!");
931 if(!write_stdout("DISC\n", 5))
935 /* send away on the socket */
936 bytes_written = swrite(sockfd, buffer, buffer_len);
937 if(bytes_written != buffer_len) {
938 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
939 buffer_len, bytes_written);
943 else if(!memcmp("DISC", buffer, 4)) {
945 if(!write_stdout("DISC\n", 5))
947 if(sockfd != CURL_SOCKET_BAD) {
948 logmsg("====> Client forcibly disconnected");
950 *sockfdp = CURL_SOCKET_BAD;
951 if(*mode == PASSIVE_CONNECT)
952 *mode = PASSIVE_LISTEN;
954 *mode = ACTIVE_DISCONNECT;
957 logmsg("attempt to close already dead connection");
963 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
965 curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
967 if(*mode == PASSIVE_LISTEN) {
968 /* there's no stream set up yet, this is an indication that there's a
969 client connecting. */
970 newfd = accept(sockfd, NULL, NULL);
971 if(CURL_SOCKET_BAD == newfd) {
973 logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
974 sockfd, error, strerror(error));
977 logmsg("====> Client connect");
978 if(!write_stdout("CNCT\n", 5))
980 *sockfdp = newfd; /* store the new socket */
981 *mode = PASSIVE_CONNECT; /* we have connected */
986 /* read from socket, pass on data to stdout */
987 nread_socket = sread(sockfd, buffer, sizeof(buffer));
989 if(nread_socket > 0) {
990 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
991 if(!write_stdout(data, 10))
993 if(!write_stdout(buffer, nread_socket))
996 logmsg("< %zd bytes data, client => server", nread_socket);
997 lograw(buffer, nread_socket);
1000 if(nread_socket <= 0
1002 || FD_ISSET(sockfd, &fds_err)
1005 logmsg("====> Client disconnect");
1006 if(!write_stdout("DISC\n", 5))
1009 *sockfdp = CURL_SOCKET_BAD;
1010 if(*mode == PASSIVE_CONNECT)
1011 *mode = PASSIVE_LISTEN;
1013 *mode = ACTIVE_DISCONNECT;
1021 static curl_socket_t sockdaemon(curl_socket_t sock,
1022 unsigned short *listenport)
1024 /* passive daemon style */
1025 srvr_sockaddr_union_t listener;
1037 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1038 (void *)&flag, sizeof(flag));
1041 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1042 error, strerror(error));
1044 rc = wait_ms(delay);
1046 /* should not happen */
1048 logmsg("wait_ms() failed with error: (%d) %s",
1049 error, strerror(error));
1051 return CURL_SOCKET_BAD;
1053 if(got_exit_signal) {
1054 logmsg("signalled to die, exiting...");
1056 return CURL_SOCKET_BAD;
1059 delay *= 2; /* double the sleep for next attempt */
1062 } while(rc && maxretr--);
1065 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
1066 attempt, totdelay, error, strerror(error));
1067 logmsg("Continuing anyway...");
1070 /* When the specified listener port is zero, it is actually a
1071 request to let the system choose a non-zero available port. */
1076 memset(&listener.sa4, 0, sizeof(listener.sa4));
1077 listener.sa4.sin_family = AF_INET;
1078 listener.sa4.sin_addr.s_addr = INADDR_ANY;
1079 listener.sa4.sin_port = htons(*listenport);
1080 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
1084 memset(&listener.sa6, 0, sizeof(listener.sa6));
1085 listener.sa6.sin6_family = AF_INET6;
1086 listener.sa6.sin6_addr = in6addr_any;
1087 listener.sa6.sin6_port = htons(*listenport);
1088 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
1090 #endif /* ENABLE_IPV6 */
1093 logmsg("Error binding socket on port %hu: (%d) %s",
1094 *listenport, error, strerror(error));
1096 return CURL_SOCKET_BAD;
1100 /* The system was supposed to choose a port number, figure out which
1101 port we actually got and update the listener port value with it. */
1102 curl_socklen_t la_size;
1103 srvr_sockaddr_union_t localaddr;
1107 la_size = sizeof(localaddr.sa4);
1110 la_size = sizeof(localaddr.sa6);
1112 memset(&localaddr.sa, 0, (size_t)la_size);
1113 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1115 logmsg("getsockname() failed with error: (%d) %s",
1116 error, strerror(error));
1118 return CURL_SOCKET_BAD;
1120 switch (localaddr.sa.sa_family) {
1122 *listenport = ntohs(localaddr.sa4.sin_port);
1126 *listenport = ntohs(localaddr.sa6.sin6_port);
1133 /* Real failure, listener port shall not be zero beyond this point. */
1134 logmsg("Apparently getsockname() succeeded, with listener port zero.");
1135 logmsg("A valid reason for this failure is a binary built without");
1136 logmsg("proper network library linkage. This might not be the only");
1137 logmsg("reason, but double check it before anything else.");
1139 return CURL_SOCKET_BAD;
1143 /* bindonly option forces no listening */
1145 logmsg("instructed to bind port without listening");
1149 /* start accepting connections */
1150 rc = listen(sock, 5);
1153 logmsg("listen(%d, 5) failed with error: (%d) %s",
1154 sock, error, strerror(error));
1156 return CURL_SOCKET_BAD;
1163 int main(int argc, char *argv[])
1165 srvr_sockaddr_union_t me;
1166 curl_socket_t sock = CURL_SOCKET_BAD;
1167 curl_socket_t msgsock = CURL_SOCKET_BAD;
1168 int wrotepidfile = 0;
1169 char *pidname= (char *)".sockfilt.pid";
1174 enum sockmode mode = PASSIVE_LISTEN; /* default */
1175 const char *addr = NULL;
1178 if(!strcmp("--version", argv[arg])) {
1179 printf("sockfilt IPv4%s\n",
1188 else if(!strcmp("--verbose", argv[arg])) {
1192 else if(!strcmp("--pidfile", argv[arg])) {
1195 pidname = argv[arg++];
1197 else if(!strcmp("--logfile", argv[arg])) {
1200 serverlogfile = argv[arg++];
1202 else if(!strcmp("--ipv6", argv[arg])) {
1209 else if(!strcmp("--ipv4", argv[arg])) {
1210 /* for completeness, we support this option as well */
1217 else if(!strcmp("--bindonly", argv[arg])) {
1221 else if(!strcmp("--port", argv[arg])) {
1225 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1226 if((endptr != argv[arg] + strlen(argv[arg])) ||
1227 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1228 fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1232 port = curlx_ultous(ulnum);
1236 else if(!strcmp("--connect", argv[arg])) {
1237 /* Asked to actively connect to the specified local port instead of
1238 doing a passive server-style listening. */
1242 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1243 if((endptr != argv[arg] + strlen(argv[arg])) ||
1244 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1245 fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1249 connectport = curlx_ultous(ulnum);
1253 else if(!strcmp("--addr", argv[arg])) {
1254 /* Set an IP address to use with --connect; otherwise use localhost */
1262 puts("Usage: sockfilt [option]\n"
1265 " --logfile [file]\n"
1266 " --pidfile [file]\n"
1271 " --connect [port]\n"
1272 " --addr [address]");
1279 atexit(win32_cleanup);
1281 setmode(fileno(stdin), O_BINARY);
1282 setmode(fileno(stdout), O_BINARY);
1283 setmode(fileno(stderr), O_BINARY);
1286 install_signal_handlers();
1291 sock = socket(AF_INET, SOCK_STREAM, 0);
1294 sock = socket(AF_INET6, SOCK_STREAM, 0);
1297 if(CURL_SOCKET_BAD == sock) {
1299 logmsg("Error creating socket: (%d) %s",
1300 error, strerror(error));
1301 write_stdout("FAIL\n", 5);
1302 goto sockfilt_cleanup;
1306 /* Active mode, we should connect to the given port number */
1311 memset(&me.sa4, 0, sizeof(me.sa4));
1312 me.sa4.sin_family = AF_INET;
1313 me.sa4.sin_port = htons(connectport);
1314 me.sa4.sin_addr.s_addr = INADDR_ANY;
1317 Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1319 rc = connect(sock, &me.sa, sizeof(me.sa4));
1323 memset(&me.sa6, 0, sizeof(me.sa6));
1324 me.sa6.sin6_family = AF_INET6;
1325 me.sa6.sin6_port = htons(connectport);
1328 Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1330 rc = connect(sock, &me.sa, sizeof(me.sa6));
1332 #endif /* ENABLE_IPV6 */
1335 logmsg("Error connecting to port %hu: (%d) %s",
1336 connectport, error, strerror(error));
1337 write_stdout("FAIL\n", 5);
1338 goto sockfilt_cleanup;
1340 logmsg("====> Client connect");
1341 msgsock = sock; /* use this as stream */
1344 /* passive daemon style */
1345 sock = sockdaemon(sock, &port);
1346 if(CURL_SOCKET_BAD == sock) {
1347 write_stdout("FAIL\n", 5);
1348 goto sockfilt_cleanup;
1350 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1353 logmsg("Running %s version", ipv_inuse);
1356 logmsg("Connected to port %hu", connectport);
1358 logmsg("Bound without listening on port %hu", port);
1360 logmsg("Listening on port %hu", port);
1362 wrotepidfile = write_pidfile(pidname);
1364 write_stdout("FAIL\n", 5);
1365 goto sockfilt_cleanup;
1369 juggle_again = juggle(&msgsock, sock, &mode);
1370 } while(juggle_again);
1374 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1377 if(sock != CURL_SOCKET_BAD)
1383 restore_signal_handlers();
1385 if(got_exit_signal) {
1386 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1388 * To properly set the return status of the process we
1389 * must raise the same signal SIGINT or SIGTERM that we
1390 * caught and let the old handler take care of it.
1395 logmsg("============> sockfilt quits");