1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, 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 #include <conio.h> /* for _kbhit() used in select_ws() */
99 #define ENABLE_CURLX_PRINTF
100 /* make the curlx header define all printf() functions to use the curlx_*
102 #include "curlx.h" /* from the private lib dir */
104 #include "inet_pton.h"
106 #include "server_sockaddr.h"
107 #include "warnless.h"
109 /* include memdebug.h last */
110 #include "memdebug.h"
114 #define EINTR 4 /* errno.h value */
116 #define EAGAIN 11 /* errno.h value */
118 #define ENOMEM 12 /* errno.h value */
120 #define EINVAL 22 /* errno.h value */
123 #define DEFAULT_PORT 8999
125 #ifndef DEFAULT_LOGFILE
126 #define DEFAULT_LOGFILE "log/sockfilt.log"
129 const char *serverlogfile = DEFAULT_LOGFILE;
131 static bool verbose = FALSE;
132 static bool bind_only = FALSE;
134 static bool use_ipv6 = FALSE;
136 static const char *ipv_inuse = "IPv4";
137 static unsigned short port = DEFAULT_PORT;
138 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
141 PASSIVE_LISTEN, /* as a server waiting for connections */
142 PASSIVE_CONNECT, /* as a server, connected to a client */
143 ACTIVE, /* as a client, connected to a server */
144 ACTIVE_DISCONNECT /* as a client, disconnected from server */
147 /* do-nothing macro replacement for systems which lack siginterrupt() */
149 #ifndef HAVE_SIGINTERRUPT
150 #define siginterrupt(x,y) do {} while(0)
153 /* vars used to keep around previous signal handlers */
155 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
158 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
162 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
166 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
170 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
174 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
177 #if defined(SIGBREAK) && defined(WIN32)
178 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
181 /* var which if set indicates that the program should finish execution */
183 SIG_ATOMIC_T got_exit_signal = 0;
185 /* if next is set indicates the first signal handled in exit_signal_handler */
187 static volatile int exit_signal = 0;
189 /* signal handler that will be triggered to indicate that the program
190 should finish its execution in a controlled manner as soon as possible.
191 The first time this is called it will set got_exit_signal to one and
192 store in exit_signal the signal that triggered its execution. */
194 static RETSIGTYPE exit_signal_handler(int signum)
196 int old_errno = errno;
197 if(got_exit_signal == 0) {
199 exit_signal = signum;
201 (void)signal(signum, exit_signal_handler);
205 static void install_signal_handlers(void)
208 /* ignore SIGHUP signal */
209 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
210 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
213 /* ignore SIGPIPE signal */
214 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
215 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
218 /* ignore SIGALRM signal */
219 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
220 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
223 /* handle SIGINT signal with our exit_signal_handler */
224 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
225 logmsg("cannot install SIGINT handler: %s", strerror(errno));
227 siginterrupt(SIGINT, 1);
230 /* handle SIGTERM signal with our exit_signal_handler */
231 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
232 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
234 siginterrupt(SIGTERM, 1);
236 #if defined(SIGBREAK) && defined(WIN32)
237 /* handle SIGBREAK signal with our exit_signal_handler */
238 if((old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler)) == SIG_ERR)
239 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
241 siginterrupt(SIGBREAK, 1);
245 static void restore_signal_handlers(void)
248 if(SIG_ERR != old_sighup_handler)
249 (void)signal(SIGHUP, old_sighup_handler);
252 if(SIG_ERR != old_sigpipe_handler)
253 (void)signal(SIGPIPE, old_sigpipe_handler);
256 if(SIG_ERR != old_sigalrm_handler)
257 (void)signal(SIGALRM, old_sigalrm_handler);
260 if(SIG_ERR != old_sigint_handler)
261 (void)signal(SIGINT, old_sigint_handler);
264 if(SIG_ERR != old_sigterm_handler)
265 (void)signal(SIGTERM, old_sigterm_handler);
267 #if defined(SIGBREAK) && defined(WIN32)
268 if(SIG_ERR != old_sigbreak_handler)
269 (void)signal(SIGBREAK, old_sigbreak_handler);
275 * read-wrapper to support reading from stdin on Windows.
277 static ssize_t read_wincon(int fd, void *buf, size_t count)
279 HANDLE handle = NULL;
280 DWORD mode, rcount = 0;
283 if(fd == fileno(stdin)) {
284 handle = GetStdHandle(STD_INPUT_HANDLE);
287 return read(fd, buf, count);
290 if(GetConsoleMode(handle, &mode)) {
291 success = ReadConsole(handle, buf, count, &rcount, NULL);
294 success = ReadFile(handle, buf, count, &rcount, NULL);
300 errno = GetLastError();
303 #define read(a,b,c) read_wincon(a,b,c)
306 * write-wrapper to support writing to stdout and stderr on Windows.
308 static ssize_t write_wincon(int fd, const void *buf, size_t count)
310 HANDLE handle = NULL;
311 DWORD mode, wcount = 0;
314 if(fd == fileno(stdout)) {
315 handle = GetStdHandle(STD_OUTPUT_HANDLE);
317 else if(fd == fileno(stderr)) {
318 handle = GetStdHandle(STD_ERROR_HANDLE);
321 return write(fd, buf, count);
324 if(GetConsoleMode(handle, &mode)) {
325 success = WriteConsole(handle, buf, count, &wcount, NULL);
328 success = WriteFile(handle, buf, count, &wcount, NULL);
334 errno = GetLastError();
337 #define write(a,b,c) write_wincon(a,b,c)
341 * fullread is a wrapper around the read() function. This will repeat the call
342 * to read() until it actually has read the complete number of bytes indicated
343 * in nbytes or it fails with a condition that cannot be handled with a simple
344 * retry of the read call.
347 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
354 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
356 if(got_exit_signal) {
357 logmsg("signalled to die");
363 if((error == EINTR) || (error == EAGAIN))
365 logmsg("reading from file descriptor: %d,", filedes);
366 logmsg("unrecoverable read() failure: (%d) %s",
367 error, strerror(error));
372 logmsg("got 0 reading from stdin");
378 } while((size_t)nread < nbytes);
381 logmsg("read %zd bytes", nread);
387 * fullwrite is a wrapper around the write() function. This will repeat the
388 * call to write() until it actually has written the complete number of bytes
389 * indicated in nbytes or it fails with a condition that cannot be handled
390 * with a simple retry of the write call.
393 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
400 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
402 if(got_exit_signal) {
403 logmsg("signalled to die");
409 if((error == EINTR) || (error == EAGAIN))
411 logmsg("writing to file descriptor: %d,", filedes);
412 logmsg("unrecoverable write() failure: (%d) %s",
413 error, strerror(error));
418 logmsg("put 0 writing to stdout");
424 } while((size_t)nwrite < nbytes);
427 logmsg("wrote %zd bytes", nwrite);
433 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
434 * blocking function that will only return TRUE when nbytes have actually been
435 * read or FALSE when an unrecoverable error has been detected. Failure of this
436 * function is an indication that the sockfilt process should terminate.
439 static bool read_stdin(void *buffer, size_t nbytes)
441 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
442 if(nread != (ssize_t)nbytes) {
443 logmsg("exiting...");
450 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
451 * blocking function that will only return TRUE when nbytes have actually been
452 * written or FALSE when an unrecoverable error has been detected. Failure of
453 * this function is an indication that the sockfilt process should terminate.
456 static bool write_stdout(const void *buffer, size_t nbytes)
458 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
459 if(nwrite != (ssize_t)nbytes) {
460 logmsg("exiting...");
466 static void lograw(unsigned char *buffer, ssize_t len)
470 unsigned char *ptr = buffer;
474 for(i=0; i<len; i++) {
477 sprintf(optr, "\\n");
482 sprintf(optr, "\\r");
487 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
494 logmsg("'%s'", data);
500 logmsg("'%s'", data);
505 * WinSock select() does not support standard file descriptors,
506 * it can only check SOCKETs. The following function is an attempt
507 * to re-create a select() function with support for other handle types.
509 * select() function with support for WINSOCK2 sockets and all
510 * other handle types supported by WaitForMultipleObjectsEx().
512 * TODO: Differentiate between read/write/except for non-SOCKET handles.
514 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
515 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
517 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
518 fd_set *exceptfds, struct timeval *timeout)
521 DWORD milliseconds, wait, idx, mode, avail, events, inputs;
522 WSAEVENT wsaevent, *wsaevents;
523 WSANETWORKEVENTS wsanetevents;
524 INPUT_RECORD *inputrecords;
525 HANDLE handle, *handles;
526 curl_socket_t sock, *fdarr, *wsasocks;
528 DWORD nfd = 0, wsa = 0;
531 /* check if the input value is valid */
537 /* check if we got descriptors, sleep in case we got none */
539 Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
543 /* allocate internal array for the original input handles */
544 fdarr = malloc(nfds * sizeof(curl_socket_t));
550 /* allocate internal array for the internal event handles */
551 handles = malloc(nfds * sizeof(HANDLE));
552 if(handles == NULL) {
557 /* allocate internal array for the internal socket handles */
558 wsasocks = malloc(nfds * sizeof(curl_socket_t));
559 if(wsasocks == NULL) {
564 /* allocate internal array for the internal WINSOCK2 events */
565 wsaevents = malloc(nfds * sizeof(WSAEVENT));
566 if(wsaevents == NULL) {
571 /* loop over the handles in the input descriptor sets */
572 for(fds = 0; fds < nfds; fds++) {
576 if(FD_ISSET(fds, readfds))
577 networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
579 if(FD_ISSET(fds, writefds))
580 networkevents |= FD_WRITE|FD_CONNECT;
582 if(FD_ISSET(fds, exceptfds))
583 networkevents |= FD_OOB;
585 /* only wait for events for which we actually care */
587 fdarr[nfd] = curlx_sitosk(fds);
588 if(fds == fileno(stdin)) {
589 handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
591 else if(fds == fileno(stdout)) {
592 handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
594 else if(fds == fileno(stderr)) {
595 handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
598 wsaevent = WSACreateEvent();
599 if(wsaevent != WSA_INVALID_EVENT) {
600 error = WSAEventSelect(fds, wsaevent, networkevents);
601 if(error != SOCKET_ERROR) {
602 handles[nfd] = wsaevent;
603 wsasocks[wsa] = curlx_sitosk(fds);
604 wsaevents[wsa] = wsaevent;
608 handles[nfd] = (HANDLE) curlx_sitosk(fds);
609 WSACloseEvent(wsaevent);
617 /* convert struct timeval to milliseconds */
619 milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
622 milliseconds = INFINITE;
625 /* wait for one of the internal handles to trigger */
626 wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
628 /* loop over the internal handles returned in the descriptors */
629 for(idx = 0; idx < nfd; idx++) {
630 handle = handles[idx];
632 fds = curlx_sktosi(sock);
634 /* check if the current internal handle was triggered */
635 if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) >= idx &&
636 WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
637 /* try to handle the event with STD* handle functions */
638 if(fds == fileno(stdin)) {
639 /* check if there is no data in the input buffer */
641 /* check if we are getting data from a PIPE */
642 if(!GetConsoleMode(handle, &mode)) {
643 /* check if there is no data from PIPE input */
644 if(!PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
647 FD_CLR(sock, readfds);
648 } /* check if there is no data from keyboard input */
649 else if (!_kbhit()) {
650 /* check if there are INPUT_RECORDs in the input buffer */
651 if(GetNumberOfConsoleInputEvents(handle, &events)) {
653 /* remove INPUT_RECORDs from the input buffer */
654 inputrecords = (INPUT_RECORD*)malloc(events *
655 sizeof(INPUT_RECORD));
657 if(!ReadConsoleInput(handle, inputrecords,
663 /* check if we got all inputs, otherwise clear buffer */
665 FlushConsoleInputBuffer(handle);
669 /* remove from descriptor set since there is no real data */
670 FD_CLR(sock, readfds);
674 /* stdin is never ready for write or exceptional */
675 FD_CLR(sock, writefds);
676 FD_CLR(sock, exceptfds);
678 else if(fds == fileno(stdout) || fds == fileno(stderr)) {
679 /* stdout and stderr are never ready for read or exceptional */
680 FD_CLR(sock, readfds);
681 FD_CLR(sock, exceptfds);
684 /* try to handle the event with the WINSOCK2 functions */
685 error = WSAEnumNetworkEvents(fds, NULL, &wsanetevents);
686 if(error != SOCKET_ERROR) {
687 /* remove from descriptor set if not ready for read/accept/close */
688 if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
689 FD_CLR(sock, readfds);
691 /* remove from descriptor set if not ready for write/connect */
692 if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
693 FD_CLR(sock, writefds);
695 /* remove from descriptor set if not exceptional */
696 if(!(wsanetevents.lNetworkEvents & FD_OOB))
697 FD_CLR(sock, exceptfds);
701 /* check if the event has not been filtered using specific tests */
702 if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
703 FD_ISSET(sock, exceptfds)) {
708 /* remove from all descriptor sets since this handle did not trigger */
709 FD_CLR(sock, readfds);
710 FD_CLR(sock, writefds);
711 FD_CLR(sock, exceptfds);
715 for(idx = 0; idx < wsa; idx++) {
716 WSAEventSelect(wsasocks[idx], NULL, 0);
717 WSACloseEvent(wsaevents[idx]);
727 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
728 #endif /* USE_WINSOCK */
731 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
733 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
736 static bool juggle(curl_socket_t *sockfdp,
737 curl_socket_t listenfd,
740 struct timeval timeout;
744 curl_socket_t sockfd = CURL_SOCKET_BAD;
747 ssize_t nread_socket;
748 ssize_t bytes_written;
752 /* 'buffer' is this excessively large only to be able to support things like
753 test 1003 which tests exceedingly large server response lines */
754 unsigned char buffer[17010];
757 if(got_exit_signal) {
758 logmsg("signalled to die, exiting...");
763 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
764 parent ftpserver process has died without killing its sockfilt children */
766 logmsg("process becomes orphan, exiting");
771 timeout.tv_sec = 120;
778 FD_SET((curl_socket_t)fileno(stdin), &fds_read);
786 /* there's always a socket to wait for */
787 FD_SET(sockfd, &fds_read);
791 case PASSIVE_CONNECT:
794 if(CURL_SOCKET_BAD == sockfd) {
795 /* eeek, we are supposedly connected and then this cannot be -1 ! */
796 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
797 maxfd = 0; /* stdin */
800 /* there's always a socket to wait for */
801 FD_SET(sockfd, &fds_read);
809 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
810 if(CURL_SOCKET_BAD != sockfd) {
811 FD_SET(sockfd, &fds_read);
815 logmsg("No socket to read on");
820 case ACTIVE_DISCONNECT:
822 logmsg("disconnected, no socket to read on");
824 sockfd = CURL_SOCKET_BAD;
827 } /* switch(*mode) */
832 /* select() blocking behavior call on blocking descriptors please */
834 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
836 if(got_exit_signal) {
837 logmsg("signalled to die, exiting...");
841 } while((rc == -1) && ((error = errno) == EINTR));
844 logmsg("select() failed with error: (%d) %s",
845 error, strerror(error));
854 if(FD_ISSET(fileno(stdin), &fds_read)) {
855 /* read from stdin, commands/data to be dealt with and possibly passed on
860 4 letter command + LF [mandatory]
862 4-digit hexadecimal data length + LF [if the command takes data]
863 data [the data being as long as set above]
867 DATA - plain pass-thru data
870 if(!read_stdin(buffer, 5))
873 logmsg("Received %c%c%c%c (on stdin)",
874 buffer[0], buffer[1], buffer[2], buffer[3] );
876 if(!memcmp("PING", buffer, 4)) {
877 /* send reply on stdout, just proving we are alive */
878 if(!write_stdout("PONG\n", 5))
882 else if(!memcmp("PORT", buffer, 4)) {
883 /* Question asking us what PORT number we are listening to.
884 Replies to PORT with "IPv[num]/[port]" */
885 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
886 buffer_len = (ssize_t)strlen((char *)buffer);
887 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
888 if(!write_stdout(data, 10))
890 if(!write_stdout(buffer, buffer_len))
893 else if(!memcmp("QUIT", buffer, 4)) {
898 else if(!memcmp("DATA", buffer, 4)) {
899 /* data IN => data OUT */
901 if(!read_stdin(buffer, 5))
906 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
907 if (buffer_len > (ssize_t)sizeof(buffer)) {
908 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
909 "(%zd bytes)", sizeof(buffer), buffer_len);
912 logmsg("> %zd bytes data, server => client", buffer_len);
914 if(!read_stdin(buffer, buffer_len))
917 lograw(buffer, buffer_len);
919 if(*mode == PASSIVE_LISTEN) {
920 logmsg("*** We are disconnected!");
921 if(!write_stdout("DISC\n", 5))
925 /* send away on the socket */
926 bytes_written = swrite(sockfd, buffer, buffer_len);
927 if(bytes_written != buffer_len) {
928 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
929 buffer_len, bytes_written);
933 else if(!memcmp("DISC", buffer, 4)) {
935 if(!write_stdout("DISC\n", 5))
937 if(sockfd != CURL_SOCKET_BAD) {
938 logmsg("====> Client forcibly disconnected");
940 *sockfdp = CURL_SOCKET_BAD;
941 if(*mode == PASSIVE_CONNECT)
942 *mode = PASSIVE_LISTEN;
944 *mode = ACTIVE_DISCONNECT;
947 logmsg("attempt to close already dead connection");
953 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
955 curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
957 if(*mode == PASSIVE_LISTEN) {
958 /* there's no stream set up yet, this is an indication that there's a
959 client connecting. */
960 newfd = accept(sockfd, NULL, NULL);
961 if(CURL_SOCKET_BAD == newfd) {
963 logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
964 sockfd, error, strerror(error));
967 logmsg("====> Client connect");
968 if(!write_stdout("CNCT\n", 5))
970 *sockfdp = newfd; /* store the new socket */
971 *mode = PASSIVE_CONNECT; /* we have connected */
976 /* read from socket, pass on data to stdout */
977 nread_socket = sread(sockfd, buffer, sizeof(buffer));
979 if(nread_socket <= 0) {
980 logmsg("====> Client disconnect");
981 if(!write_stdout("DISC\n", 5))
984 *sockfdp = CURL_SOCKET_BAD;
985 if(*mode == PASSIVE_CONNECT)
986 *mode = PASSIVE_LISTEN;
988 *mode = ACTIVE_DISCONNECT;
992 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
993 if(!write_stdout(data, 10))
995 if(!write_stdout(buffer, nread_socket))
998 logmsg("< %zd bytes data, client => server", nread_socket);
999 lograw(buffer, nread_socket);
1005 static curl_socket_t sockdaemon(curl_socket_t sock,
1006 unsigned short *listenport)
1008 /* passive daemon style */
1009 srvr_sockaddr_union_t listener;
1021 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1022 (void *)&flag, sizeof(flag));
1025 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1026 error, strerror(error));
1028 rc = wait_ms(delay);
1030 /* should not happen */
1032 logmsg("wait_ms() failed with error: (%d) %s",
1033 error, strerror(error));
1035 return CURL_SOCKET_BAD;
1037 if(got_exit_signal) {
1038 logmsg("signalled to die, exiting...");
1040 return CURL_SOCKET_BAD;
1043 delay *= 2; /* double the sleep for next attempt */
1046 } while(rc && maxretr--);
1049 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
1050 attempt, totdelay, error, strerror(error));
1051 logmsg("Continuing anyway...");
1054 /* When the specified listener port is zero, it is actually a
1055 request to let the system choose a non-zero available port. */
1060 memset(&listener.sa4, 0, sizeof(listener.sa4));
1061 listener.sa4.sin_family = AF_INET;
1062 listener.sa4.sin_addr.s_addr = INADDR_ANY;
1063 listener.sa4.sin_port = htons(*listenport);
1064 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
1068 memset(&listener.sa6, 0, sizeof(listener.sa6));
1069 listener.sa6.sin6_family = AF_INET6;
1070 listener.sa6.sin6_addr = in6addr_any;
1071 listener.sa6.sin6_port = htons(*listenport);
1072 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
1074 #endif /* ENABLE_IPV6 */
1077 logmsg("Error binding socket on port %hu: (%d) %s",
1078 *listenport, error, strerror(error));
1080 return CURL_SOCKET_BAD;
1084 /* The system was supposed to choose a port number, figure out which
1085 port we actually got and update the listener port value with it. */
1086 curl_socklen_t la_size;
1087 srvr_sockaddr_union_t localaddr;
1091 la_size = sizeof(localaddr.sa4);
1094 la_size = sizeof(localaddr.sa6);
1096 memset(&localaddr.sa, 0, (size_t)la_size);
1097 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1099 logmsg("getsockname() failed with error: (%d) %s",
1100 error, strerror(error));
1102 return CURL_SOCKET_BAD;
1104 switch (localaddr.sa.sa_family) {
1106 *listenport = ntohs(localaddr.sa4.sin_port);
1110 *listenport = ntohs(localaddr.sa6.sin6_port);
1117 /* Real failure, listener port shall not be zero beyond this point. */
1118 logmsg("Apparently getsockname() succeeded, with listener port zero.");
1119 logmsg("A valid reason for this failure is a binary built without");
1120 logmsg("proper network library linkage. This might not be the only");
1121 logmsg("reason, but double check it before anything else.");
1123 return CURL_SOCKET_BAD;
1127 /* bindonly option forces no listening */
1129 logmsg("instructed to bind port without listening");
1133 /* start accepting connections */
1134 rc = listen(sock, 5);
1137 logmsg("listen(%d, 5) failed with error: (%d) %s",
1138 sock, error, strerror(error));
1140 return CURL_SOCKET_BAD;
1147 int main(int argc, char *argv[])
1149 srvr_sockaddr_union_t me;
1150 curl_socket_t sock = CURL_SOCKET_BAD;
1151 curl_socket_t msgsock = CURL_SOCKET_BAD;
1152 int wrotepidfile = 0;
1153 char *pidname= (char *)".sockfilt.pid";
1158 enum sockmode mode = PASSIVE_LISTEN; /* default */
1159 const char *addr = NULL;
1162 if(!strcmp("--version", argv[arg])) {
1163 printf("sockfilt IPv4%s\n",
1172 else if(!strcmp("--verbose", argv[arg])) {
1176 else if(!strcmp("--pidfile", argv[arg])) {
1179 pidname = argv[arg++];
1181 else if(!strcmp("--logfile", argv[arg])) {
1184 serverlogfile = argv[arg++];
1186 else if(!strcmp("--ipv6", argv[arg])) {
1193 else if(!strcmp("--ipv4", argv[arg])) {
1194 /* for completeness, we support this option as well */
1201 else if(!strcmp("--bindonly", argv[arg])) {
1205 else if(!strcmp("--port", argv[arg])) {
1209 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1210 if((endptr != argv[arg] + strlen(argv[arg])) ||
1211 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1212 fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1216 port = curlx_ultous(ulnum);
1220 else if(!strcmp("--connect", argv[arg])) {
1221 /* Asked to actively connect to the specified local port instead of
1222 doing a passive server-style listening. */
1226 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1227 if((endptr != argv[arg] + strlen(argv[arg])) ||
1228 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1229 fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1233 connectport = curlx_ultous(ulnum);
1237 else if(!strcmp("--addr", argv[arg])) {
1238 /* Set an IP address to use with --connect; otherwise use localhost */
1246 puts("Usage: sockfilt [option]\n"
1249 " --logfile [file]\n"
1250 " --pidfile [file]\n"
1255 " --connect [port]\n"
1256 " --addr [address]");
1263 atexit(win32_cleanup);
1265 setmode(fileno(stdin), O_BINARY);
1266 setmode(fileno(stdout), O_BINARY);
1267 setmode(fileno(stderr), O_BINARY);
1270 install_signal_handlers();
1275 sock = socket(AF_INET, SOCK_STREAM, 0);
1278 sock = socket(AF_INET6, SOCK_STREAM, 0);
1281 if(CURL_SOCKET_BAD == sock) {
1283 logmsg("Error creating socket: (%d) %s",
1284 error, strerror(error));
1285 write_stdout("FAIL\n", 5);
1286 goto sockfilt_cleanup;
1290 /* Active mode, we should connect to the given port number */
1295 memset(&me.sa4, 0, sizeof(me.sa4));
1296 me.sa4.sin_family = AF_INET;
1297 me.sa4.sin_port = htons(connectport);
1298 me.sa4.sin_addr.s_addr = INADDR_ANY;
1301 Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1303 rc = connect(sock, &me.sa, sizeof(me.sa4));
1307 memset(&me.sa6, 0, sizeof(me.sa6));
1308 me.sa6.sin6_family = AF_INET6;
1309 me.sa6.sin6_port = htons(connectport);
1312 Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1314 rc = connect(sock, &me.sa, sizeof(me.sa6));
1316 #endif /* ENABLE_IPV6 */
1319 logmsg("Error connecting to port %hu: (%d) %s",
1320 connectport, error, strerror(error));
1321 write_stdout("FAIL\n", 5);
1322 goto sockfilt_cleanup;
1324 logmsg("====> Client connect");
1325 msgsock = sock; /* use this as stream */
1328 /* passive daemon style */
1329 sock = sockdaemon(sock, &port);
1330 if(CURL_SOCKET_BAD == sock) {
1331 write_stdout("FAIL\n", 5);
1332 goto sockfilt_cleanup;
1334 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1337 logmsg("Running %s version", ipv_inuse);
1340 logmsg("Connected to port %hu", connectport);
1342 logmsg("Bound without listening on port %hu", port);
1344 logmsg("Listening on port %hu", port);
1346 wrotepidfile = write_pidfile(pidname);
1348 write_stdout("FAIL\n", 5);
1349 goto sockfilt_cleanup;
1353 juggle_again = juggle(&msgsock, sock, &mode);
1354 } while(juggle_again);
1358 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1361 if(sock != CURL_SOCKET_BAD)
1367 restore_signal_handlers();
1369 if(got_exit_signal) {
1370 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1372 * To properly set the return status of the process we
1373 * must raise the same signal SIGINT or SIGTERM that we
1374 * caught and let the old handler take care of it.
1379 logmsg("============> sockfilt quits");