1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2012, 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"
108 /* include memdebug.h last */
109 #include "memdebug.h"
111 #define DEFAULT_PORT 8999
113 #ifndef DEFAULT_LOGFILE
114 #define DEFAULT_LOGFILE "log/sockfilt.log"
117 const char *serverlogfile = DEFAULT_LOGFILE;
119 static bool verbose = FALSE;
120 static bool bind_only = FALSE;
122 static bool use_ipv6 = FALSE;
124 static const char *ipv_inuse = "IPv4";
125 static unsigned short port = DEFAULT_PORT;
126 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
129 PASSIVE_LISTEN, /* as a server waiting for connections */
130 PASSIVE_CONNECT, /* as a server, connected to a client */
131 ACTIVE, /* as a client, connected to a server */
132 ACTIVE_DISCONNECT /* as a client, disconnected from server */
135 /* do-nothing macro replacement for systems which lack siginterrupt() */
137 #ifndef HAVE_SIGINTERRUPT
138 #define siginterrupt(x,y) do {} while(0)
141 /* vars used to keep around previous signal handlers */
143 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
146 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
150 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
154 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
158 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
162 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
165 /* var which if set indicates that the program should finish execution */
167 SIG_ATOMIC_T got_exit_signal = 0;
169 /* if next is set indicates the first signal handled in exit_signal_handler */
171 static volatile int exit_signal = 0;
173 /* signal handler that will be triggered to indicate that the program
174 should finish its execution in a controlled manner as soon as possible.
175 The first time this is called it will set got_exit_signal to one and
176 store in exit_signal the signal that triggered its execution. */
178 static RETSIGTYPE exit_signal_handler(int signum)
180 int old_errno = ERRNO;
181 if(got_exit_signal == 0) {
183 exit_signal = signum;
185 (void)signal(signum, exit_signal_handler);
186 SET_ERRNO(old_errno);
189 static void install_signal_handlers(void)
192 /* ignore SIGHUP signal */
193 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
194 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
197 /* ignore SIGPIPE signal */
198 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
199 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
202 /* ignore SIGALRM signal */
203 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
204 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
207 /* handle SIGINT signal with our exit_signal_handler */
208 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
209 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
211 siginterrupt(SIGINT, 1);
214 /* handle SIGTERM signal with our exit_signal_handler */
215 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
216 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
218 siginterrupt(SIGTERM, 1);
222 static void restore_signal_handlers(void)
225 if(SIG_ERR != old_sighup_handler)
226 (void)signal(SIGHUP, old_sighup_handler);
229 if(SIG_ERR != old_sigpipe_handler)
230 (void)signal(SIGPIPE, old_sigpipe_handler);
233 if(SIG_ERR != old_sigalrm_handler)
234 (void)signal(SIGALRM, old_sigalrm_handler);
237 if(SIG_ERR != old_sigint_handler)
238 (void)signal(SIGINT, old_sigint_handler);
241 if(SIG_ERR != old_sigterm_handler)
242 (void)signal(SIGTERM, old_sigterm_handler);
247 * fullread is a wrapper around the read() function. This will repeat the call
248 * to read() until it actually has read the complete number of bytes indicated
249 * in nbytes or it fails with a condition that cannot be handled with a simple
250 * retry of the read call.
253 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
260 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
262 if(got_exit_signal) {
263 logmsg("signalled to die");
269 if((error == EINTR) || (error == EAGAIN))
271 logmsg("unrecoverable read() failure: (%d) %s",
272 error, strerror(error));
277 logmsg("got 0 reading from stdin");
283 } while((size_t)nread < nbytes);
286 logmsg("read %zd bytes", nread);
292 * fullwrite is a wrapper around the write() function. This will repeat the
293 * call to write() until it actually has written the complete number of bytes
294 * indicated in nbytes or it fails with a condition that cannot be handled
295 * with a simple retry of the write call.
298 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
305 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
307 if(got_exit_signal) {
308 logmsg("signalled to die");
314 if((error == EINTR) || (error == EAGAIN))
316 logmsg("unrecoverable write() failure: (%d) %s",
317 error, strerror(error));
322 logmsg("put 0 writing to stdout");
328 } while((size_t)nwrite < nbytes);
331 logmsg("wrote %zd bytes", nwrite);
337 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
338 * blocking function that will only return TRUE when nbytes have actually been
339 * read or FALSE when an unrecoverable error has been detected. Failure of this
340 * function is an indication that the sockfilt process should terminate.
343 static bool read_stdin(void *buffer, size_t nbytes)
345 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
346 if(nread != (ssize_t)nbytes) {
347 logmsg("exiting...");
354 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
355 * blocking function that will only return TRUE when nbytes have actually been
356 * written or FALSE when an unrecoverable error has been detected. Failure of
357 * this function is an indication that the sockfilt process should terminate.
360 static bool write_stdout(const void *buffer, size_t nbytes)
362 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
363 if(nwrite != (ssize_t)nbytes) {
364 logmsg("exiting...");
370 static void lograw(unsigned char *buffer, ssize_t len)
374 unsigned char *ptr = buffer;
378 for(i=0; i<len; i++) {
381 sprintf(optr, "\\n");
386 sprintf(optr, "\\r");
391 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
398 logmsg("'%s'", data);
404 logmsg("'%s'", data);
409 * WinSock select() does not support standard file descriptors,
410 * it can only check SOCKETs. The following function is an attempt
411 * to re-create a select() function with support for other handle types.
413 * select() function with support for WINSOCK2 sockets and all
414 * other handle types supported by WaitForMultipleObjectsEx().
416 * TODO: Differentiate between read/write/except for non-SOCKET handles.
418 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
419 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
421 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
422 fd_set *exceptfds, struct timeval *timeout)
425 DWORD milliseconds, wait, idx, avail, events, inputs;
426 WSAEVENT wsaevent, *wsaevents;
427 WSANETWORKEVENTS wsanetevents;
428 INPUT_RECORD *inputrecords;
429 HANDLE handle, *handles;
430 curl_socket_t sock, *fdarr, *wsasocks;
432 DWORD nfd = 0, wsa = 0;
435 /* check if the input value is valid */
437 SET_SOCKERRNO(EINVAL);
441 /* check if we got descriptors, sleep in case we got none */
443 Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
447 /* allocate internal array for the original input handles */
448 fdarr = malloc(nfds * sizeof(curl_socket_t));
450 SET_SOCKERRNO(ENOMEM);
454 /* allocate internal array for the internal event handles */
455 handles = malloc(nfds * sizeof(HANDLE));
456 if(handles == NULL) {
457 SET_SOCKERRNO(ENOMEM);
461 /* allocate internal array for the internal socket handles */
462 wsasocks = malloc(nfds * sizeof(curl_socket_t));
463 if(wsasocks == NULL) {
464 SET_SOCKERRNO(ENOMEM);
468 /* allocate internal array for the internal WINSOCK2 events */
469 wsaevents = malloc(nfds * sizeof(WSAEVENT));
470 if(wsaevents == NULL) {
471 SET_SOCKERRNO(ENOMEM);
475 /* loop over the handles in the input descriptor sets */
476 for(fds = 0; fds < nfds; fds++) {
480 if(FD_ISSET(fds, readfds))
481 networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
483 if(FD_ISSET(fds, writefds))
484 networkevents |= FD_WRITE|FD_CONNECT;
486 if(FD_ISSET(fds, exceptfds))
487 networkevents |= FD_OOB;
489 /* only wait for events for which we actually care */
491 fdarr[nfd] = (curl_socket_t) LongToHandle(fds);
492 if(fds == fileno(stdin)) {
493 handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
495 else if(fds == fileno(stdout)) {
496 handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
498 else if(fds == fileno(stderr)) {
499 handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
502 wsaevent = WSACreateEvent();
503 if(wsaevent != WSA_INVALID_EVENT) {
504 error = WSAEventSelect(fds, wsaevent, networkevents);
505 if(error != SOCKET_ERROR) {
506 handles[nfd] = wsaevent;
507 wsasocks[wsa] = (curl_socket_t) LongToHandle(fds);
508 wsaevents[wsa] = wsaevent;
512 handles[nfd] = LongToHandle(fds);
513 WSACloseEvent(wsaevent);
521 /* convert struct timeval to milliseconds */
523 milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
526 milliseconds = INFINITE;
529 /* wait for one of the internal handles to trigger */
530 wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
532 /* loop over the internal handles returned in the descriptors */
533 for(idx = 0; idx < nfd; idx++) {
534 handle = handles[idx];
536 fds = HandleToLong(sock);
538 /* check if the current internal handle was triggered */
539 if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) >= idx &&
540 WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
541 /* try to handle the event with STD* handle functions */
542 if(fds == fileno(stdin)) {
543 /* check if there is no data in the input buffer */
545 /* check if we are getting data from a PIPE */
546 if(!GetConsoleMode(handle, &avail)) {
547 /* check if there is no data from PIPE input */
548 if(!PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
551 FD_CLR(sock, readfds);
552 } /* check if there is no data from keyboard input */
553 else if (!_kbhit()) {
554 /* check if there are INPUT_RECORDs in the input buffer */
555 if(GetNumberOfConsoleInputEvents(handle, &events)) {
557 /* remove INPUT_RECORDs from the input buffer */
558 inputrecords = (INPUT_RECORD*)malloc(events *
559 sizeof(INPUT_RECORD));
561 if(!ReadConsoleInput(handle, inputrecords,
567 /* check if we got all inputs, otherwise clear buffer */
569 FlushConsoleInputBuffer(handle);
573 /* remove from descriptor set since there is no real data */
574 FD_CLR(sock, readfds);
578 /* stdin is never ready for write or exceptional */
579 FD_CLR(sock, writefds);
580 FD_CLR(sock, exceptfds);
582 else if(fds == fileno(stdout) || fds == fileno(stderr)) {
583 /* stdout and stderr are never ready for read or exceptional */
584 FD_CLR(sock, readfds);
585 FD_CLR(sock, exceptfds);
588 /* try to handle the event with the WINSOCK2 functions */
589 error = WSAEnumNetworkEvents(fds, NULL, &wsanetevents);
590 if(error != SOCKET_ERROR) {
591 /* remove from descriptor set if not ready for read/accept/close */
592 if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
593 FD_CLR(sock, readfds);
595 /* remove from descriptor set if not ready for write/connect */
596 if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
597 FD_CLR(sock, writefds);
599 /* remove from descriptor set if not exceptional */
600 if(!(wsanetevents.lNetworkEvents & FD_OOB))
601 FD_CLR(sock, exceptfds);
605 /* check if the event has not been filtered using specific tests */
606 if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
607 FD_ISSET(sock, exceptfds)) {
612 /* remove from all descriptor sets since this handle did not trigger */
613 FD_CLR(sock, readfds);
614 FD_CLR(sock, writefds);
615 FD_CLR(sock, exceptfds);
619 for(idx = 0; idx < wsa; idx++) {
620 WSAEventSelect(wsasocks[idx], NULL, 0);
621 WSACloseEvent(wsaevents[idx]);
631 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
632 #endif /* USE_WINSOCK */
635 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
637 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
640 static bool juggle(curl_socket_t *sockfdp,
641 curl_socket_t listenfd,
644 struct timeval timeout;
648 curl_socket_t sockfd = CURL_SOCKET_BAD;
651 ssize_t nread_socket;
652 ssize_t bytes_written;
656 /* 'buffer' is this excessively large only to be able to support things like
657 test 1003 which tests exceedingly large server response lines */
658 unsigned char buffer[17010];
661 if(got_exit_signal) {
662 logmsg("signalled to die, exiting...");
667 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
668 parent ftpserver process has died without killing its sockfilt children */
670 logmsg("process becomes orphan, exiting");
675 timeout.tv_sec = 120;
682 FD_SET((curl_socket_t)fileno(stdin), &fds_read);
690 /* there's always a socket to wait for */
691 FD_SET(sockfd, &fds_read);
695 case PASSIVE_CONNECT:
698 if(CURL_SOCKET_BAD == sockfd) {
699 /* eeek, we are supposedly connected and then this cannot be -1 ! */
700 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
701 maxfd = 0; /* stdin */
704 /* there's always a socket to wait for */
705 FD_SET(sockfd, &fds_read);
713 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
714 if(CURL_SOCKET_BAD != sockfd) {
715 FD_SET(sockfd, &fds_read);
719 logmsg("No socket to read on");
724 case ACTIVE_DISCONNECT:
726 logmsg("disconnected, no socket to read on");
728 sockfd = CURL_SOCKET_BAD;
731 } /* switch(*mode) */
736 /* select() blocking behavior call on blocking descriptors please */
738 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
740 if(got_exit_signal) {
741 logmsg("signalled to die, exiting...");
745 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
748 logmsg("select() failed with error: (%d) %s",
749 error, strerror(error));
758 if(FD_ISSET(fileno(stdin), &fds_read)) {
759 /* read from stdin, commands/data to be dealt with and possibly passed on
764 4 letter command + LF [mandatory]
766 4-digit hexadecimal data length + LF [if the command takes data]
767 data [the data being as long as set above]
771 DATA - plain pass-thru data
774 if(!read_stdin(buffer, 5))
777 logmsg("Received %c%c%c%c (on stdin)",
778 buffer[0], buffer[1], buffer[2], buffer[3] );
780 if(!memcmp("PING", buffer, 4)) {
781 /* send reply on stdout, just proving we are alive */
782 if(!write_stdout("PONG\n", 5))
786 else if(!memcmp("PORT", buffer, 4)) {
787 /* Question asking us what PORT number we are listening to.
788 Replies to PORT with "IPv[num]/[port]" */
789 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
790 buffer_len = (ssize_t)strlen((char *)buffer);
791 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
792 if(!write_stdout(data, 10))
794 if(!write_stdout(buffer, buffer_len))
797 else if(!memcmp("QUIT", buffer, 4)) {
802 else if(!memcmp("DATA", buffer, 4)) {
803 /* data IN => data OUT */
805 if(!read_stdin(buffer, 5))
810 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
811 if (buffer_len > (ssize_t)sizeof(buffer)) {
812 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
813 "(%zd bytes)", sizeof(buffer), buffer_len);
816 logmsg("> %zd bytes data, server => client", buffer_len);
818 if(!read_stdin(buffer, buffer_len))
821 lograw(buffer, buffer_len);
823 if(*mode == PASSIVE_LISTEN) {
824 logmsg("*** We are disconnected!");
825 if(!write_stdout("DISC\n", 5))
829 /* send away on the socket */
830 bytes_written = swrite(sockfd, buffer, buffer_len);
831 if(bytes_written != buffer_len) {
832 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
833 buffer_len, bytes_written);
837 else if(!memcmp("DISC", buffer, 4)) {
839 if(!write_stdout("DISC\n", 5))
841 if(sockfd != CURL_SOCKET_BAD) {
842 logmsg("====> Client forcibly disconnected");
844 *sockfdp = CURL_SOCKET_BAD;
845 if(*mode == PASSIVE_CONNECT)
846 *mode = PASSIVE_LISTEN;
848 *mode = ACTIVE_DISCONNECT;
851 logmsg("attempt to close already dead connection");
857 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
859 curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
861 if(*mode == PASSIVE_LISTEN) {
862 /* there's no stream set up yet, this is an indication that there's a
863 client connecting. */
864 newfd = accept(sockfd, NULL, NULL);
865 if(CURL_SOCKET_BAD == newfd) {
867 logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
868 sockfd, error, strerror(error));
871 logmsg("====> Client connect");
872 if(!write_stdout("CNCT\n", 5))
874 *sockfdp = newfd; /* store the new socket */
875 *mode = PASSIVE_CONNECT; /* we have connected */
880 /* read from socket, pass on data to stdout */
881 nread_socket = sread(sockfd, buffer, sizeof(buffer));
883 if(nread_socket <= 0) {
884 logmsg("====> Client disconnect");
885 if(!write_stdout("DISC\n", 5))
888 *sockfdp = CURL_SOCKET_BAD;
889 if(*mode == PASSIVE_CONNECT)
890 *mode = PASSIVE_LISTEN;
892 *mode = ACTIVE_DISCONNECT;
896 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
897 if(!write_stdout(data, 10))
899 if(!write_stdout(buffer, nread_socket))
902 logmsg("< %zd bytes data, client => server", nread_socket);
903 lograw(buffer, nread_socket);
909 static curl_socket_t sockdaemon(curl_socket_t sock,
910 unsigned short *listenport)
912 /* passive daemon style */
913 srvr_sockaddr_union_t listener;
925 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
926 (void *)&flag, sizeof(flag));
929 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
930 error, strerror(error));
934 /* should not happen */
936 logmsg("wait_ms() failed with error: (%d) %s",
937 error, strerror(error));
939 return CURL_SOCKET_BAD;
941 if(got_exit_signal) {
942 logmsg("signalled to die, exiting...");
944 return CURL_SOCKET_BAD;
947 delay *= 2; /* double the sleep for next attempt */
950 } while(rc && maxretr--);
953 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
954 attempt, totdelay, error, strerror(error));
955 logmsg("Continuing anyway...");
958 /* When the specified listener port is zero, it is actually a
959 request to let the system choose a non-zero available port. */
964 memset(&listener.sa4, 0, sizeof(listener.sa4));
965 listener.sa4.sin_family = AF_INET;
966 listener.sa4.sin_addr.s_addr = INADDR_ANY;
967 listener.sa4.sin_port = htons(*listenport);
968 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
972 memset(&listener.sa6, 0, sizeof(listener.sa6));
973 listener.sa6.sin6_family = AF_INET6;
974 listener.sa6.sin6_addr = in6addr_any;
975 listener.sa6.sin6_port = htons(*listenport);
976 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
978 #endif /* ENABLE_IPV6 */
981 logmsg("Error binding socket on port %hu: (%d) %s",
982 *listenport, error, strerror(error));
984 return CURL_SOCKET_BAD;
988 /* The system was supposed to choose a port number, figure out which
989 port we actually got and update the listener port value with it. */
990 curl_socklen_t la_size;
991 srvr_sockaddr_union_t localaddr;
995 la_size = sizeof(localaddr.sa4);
998 la_size = sizeof(localaddr.sa6);
1000 memset(&localaddr.sa, 0, (size_t)la_size);
1001 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1003 logmsg("getsockname() failed with error: (%d) %s",
1004 error, strerror(error));
1006 return CURL_SOCKET_BAD;
1008 switch (localaddr.sa.sa_family) {
1010 *listenport = ntohs(localaddr.sa4.sin_port);
1014 *listenport = ntohs(localaddr.sa6.sin6_port);
1021 /* Real failure, listener port shall not be zero beyond this point. */
1022 logmsg("Apparently getsockname() succeeded, with listener port zero.");
1023 logmsg("A valid reason for this failure is a binary built without");
1024 logmsg("proper network library linkage. This might not be the only");
1025 logmsg("reason, but double check it before anything else.");
1027 return CURL_SOCKET_BAD;
1031 /* bindonly option forces no listening */
1033 logmsg("instructed to bind port without listening");
1037 /* start accepting connections */
1038 rc = listen(sock, 5);
1041 logmsg("listen(%d, 5) failed with error: (%d) %s",
1042 sock, error, strerror(error));
1044 return CURL_SOCKET_BAD;
1051 int main(int argc, char *argv[])
1053 srvr_sockaddr_union_t me;
1054 curl_socket_t sock = CURL_SOCKET_BAD;
1055 curl_socket_t msgsock = CURL_SOCKET_BAD;
1056 int wrotepidfile = 0;
1057 char *pidname= (char *)".sockfilt.pid";
1062 enum sockmode mode = PASSIVE_LISTEN; /* default */
1063 const char *addr = NULL;
1066 if(!strcmp("--version", argv[arg])) {
1067 printf("sockfilt IPv4%s\n",
1076 else if(!strcmp("--verbose", argv[arg])) {
1080 else if(!strcmp("--pidfile", argv[arg])) {
1083 pidname = argv[arg++];
1085 else if(!strcmp("--logfile", argv[arg])) {
1088 serverlogfile = argv[arg++];
1090 else if(!strcmp("--ipv6", argv[arg])) {
1097 else if(!strcmp("--ipv4", argv[arg])) {
1098 /* for completeness, we support this option as well */
1105 else if(!strcmp("--bindonly", argv[arg])) {
1109 else if(!strcmp("--port", argv[arg])) {
1113 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1114 if((endptr != argv[arg] + strlen(argv[arg])) ||
1115 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1116 fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1120 port = curlx_ultous(ulnum);
1124 else if(!strcmp("--connect", argv[arg])) {
1125 /* Asked to actively connect to the specified local port instead of
1126 doing a passive server-style listening. */
1130 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1131 if((endptr != argv[arg] + strlen(argv[arg])) ||
1132 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1133 fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1137 connectport = curlx_ultous(ulnum);
1141 else if(!strcmp("--addr", argv[arg])) {
1142 /* Set an IP address to use with --connect; otherwise use localhost */
1150 puts("Usage: sockfilt [option]\n"
1153 " --logfile [file]\n"
1154 " --pidfile [file]\n"
1159 " --connect [port]\n"
1160 " --addr [address]");
1167 atexit(win32_cleanup);
1169 setmode(fileno(stdin), O_BINARY);
1170 setmode(fileno(stdout), O_BINARY);
1171 setmode(fileno(stderr), O_BINARY);
1174 install_signal_handlers();
1179 sock = socket(AF_INET, SOCK_STREAM, 0);
1182 sock = socket(AF_INET6, SOCK_STREAM, 0);
1185 if(CURL_SOCKET_BAD == sock) {
1187 logmsg("Error creating socket: (%d) %s",
1188 error, strerror(error));
1189 write_stdout("FAIL\n", 5);
1190 goto sockfilt_cleanup;
1194 /* Active mode, we should connect to the given port number */
1199 memset(&me.sa4, 0, sizeof(me.sa4));
1200 me.sa4.sin_family = AF_INET;
1201 me.sa4.sin_port = htons(connectport);
1202 me.sa4.sin_addr.s_addr = INADDR_ANY;
1205 Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1207 rc = connect(sock, &me.sa, sizeof(me.sa4));
1211 memset(&me.sa6, 0, sizeof(me.sa6));
1212 me.sa6.sin6_family = AF_INET6;
1213 me.sa6.sin6_port = htons(connectport);
1216 Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1218 rc = connect(sock, &me.sa, sizeof(me.sa6));
1220 #endif /* ENABLE_IPV6 */
1223 logmsg("Error connecting to port %hu: (%d) %s",
1224 connectport, error, strerror(error));
1225 write_stdout("FAIL\n", 5);
1226 goto sockfilt_cleanup;
1228 logmsg("====> Client connect");
1229 msgsock = sock; /* use this as stream */
1232 /* passive daemon style */
1233 sock = sockdaemon(sock, &port);
1234 if(CURL_SOCKET_BAD == sock) {
1235 write_stdout("FAIL\n", 5);
1236 goto sockfilt_cleanup;
1238 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1241 logmsg("Running %s version", ipv_inuse);
1244 logmsg("Connected to port %hu", connectport);
1246 logmsg("Bound without listening on port %hu", port);
1248 logmsg("Listening on port %hu", port);
1250 wrotepidfile = write_pidfile(pidname);
1252 write_stdout("FAIL\n", 5);
1253 goto sockfilt_cleanup;
1257 juggle_again = juggle(&msgsock, sock, &mode);
1258 } while(juggle_again);
1262 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1265 if(sock != CURL_SOCKET_BAD)
1271 restore_signal_handlers();
1273 if(got_exit_signal) {
1274 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1276 * To properly set the return status of the process we
1277 * must raise the same signal SIGINT or SIGTERM that we
1278 * caught and let the old handler take care of it.
1283 logmsg("============> sockfilt quits");