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>
101 #define ENABLE_CURLX_PRINTF
102 /* make the curlx header define all printf() functions to use the curlx_*
104 #include "curlx.h" /* from the private lib dir */
106 #include "inet_pton.h"
108 #include "server_sockaddr.h"
110 /* include memdebug.h last */
111 #include "memdebug.h"
113 #define DEFAULT_PORT 8999
115 #ifndef DEFAULT_LOGFILE
116 #define DEFAULT_LOGFILE "log/sockfilt.log"
119 const char *serverlogfile = DEFAULT_LOGFILE;
121 static bool verbose = FALSE;
122 static bool bind_only = FALSE;
124 static bool use_ipv6 = FALSE;
126 static const char *ipv_inuse = "IPv4";
127 static unsigned short port = DEFAULT_PORT;
128 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
131 PASSIVE_LISTEN, /* as a server waiting for connections */
132 PASSIVE_CONNECT, /* as a server, connected to a client */
133 ACTIVE, /* as a client, connected to a server */
134 ACTIVE_DISCONNECT /* as a client, disconnected from server */
137 /* do-nothing macro replacement for systems which lack siginterrupt() */
139 #ifndef HAVE_SIGINTERRUPT
140 #define siginterrupt(x,y) do {} while(0)
143 /* vars used to keep around previous signal handlers */
145 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
148 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
152 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
156 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
160 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
164 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
167 /* var which if set indicates that the program should finish execution */
169 SIG_ATOMIC_T got_exit_signal = 0;
171 /* if next is set indicates the first signal handled in exit_signal_handler */
173 static volatile int exit_signal = 0;
175 /* signal handler that will be triggered to indicate that the program
176 should finish its execution in a controlled manner as soon as possible.
177 The first time this is called it will set got_exit_signal to one and
178 store in exit_signal the signal that triggered its execution. */
180 static RETSIGTYPE exit_signal_handler(int signum)
182 int old_errno = ERRNO;
183 if(got_exit_signal == 0) {
185 exit_signal = signum;
187 (void)signal(signum, exit_signal_handler);
188 SET_ERRNO(old_errno);
191 static void install_signal_handlers(void)
194 /* ignore SIGHUP signal */
195 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
196 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
199 /* ignore SIGPIPE signal */
200 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
201 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
204 /* ignore SIGALRM signal */
205 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
206 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
209 /* handle SIGINT signal with our exit_signal_handler */
210 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
211 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
213 siginterrupt(SIGINT, 1);
216 /* handle SIGTERM signal with our exit_signal_handler */
217 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
218 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
220 siginterrupt(SIGTERM, 1);
224 static void restore_signal_handlers(void)
227 if(SIG_ERR != old_sighup_handler)
228 (void)signal(SIGHUP, old_sighup_handler);
231 if(SIG_ERR != old_sigpipe_handler)
232 (void)signal(SIGPIPE, old_sigpipe_handler);
235 if(SIG_ERR != old_sigalrm_handler)
236 (void)signal(SIGALRM, old_sigalrm_handler);
239 if(SIG_ERR != old_sigint_handler)
240 (void)signal(SIGINT, old_sigint_handler);
243 if(SIG_ERR != old_sigterm_handler)
244 (void)signal(SIGTERM, old_sigterm_handler);
249 * fullread is a wrapper around the read() function. This will repeat the call
250 * to read() until it actually has read the complete number of bytes indicated
251 * in nbytes or it fails with a condition that cannot be handled with a simple
252 * retry of the read call.
255 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
262 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
264 if(got_exit_signal) {
265 logmsg("signalled to die");
271 if((error == EINTR) || (error == EAGAIN))
273 logmsg("unrecoverable read() failure: (%d) %s",
274 error, strerror(error));
279 logmsg("got 0 reading from stdin");
285 } while((size_t)nread < nbytes);
288 logmsg("read %zd bytes", nread);
294 * fullwrite is a wrapper around the write() function. This will repeat the
295 * call to write() until it actually has written the complete number of bytes
296 * indicated in nbytes or it fails with a condition that cannot be handled
297 * with a simple retry of the write call.
300 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
307 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
309 if(got_exit_signal) {
310 logmsg("signalled to die");
316 if((error == EINTR) || (error == EAGAIN))
318 logmsg("unrecoverable write() failure: (%d) %s",
319 error, strerror(error));
324 logmsg("put 0 writing to stdout");
330 } while((size_t)nwrite < nbytes);
333 logmsg("wrote %zd bytes", nwrite);
339 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
340 * blocking function that will only return TRUE when nbytes have actually been
341 * read or FALSE when an unrecoverable error has been detected. Failure of this
342 * function is an indication that the sockfilt process should terminate.
345 static bool read_stdin(void *buffer, size_t nbytes)
347 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
348 if(nread != (ssize_t)nbytes) {
349 logmsg("exiting...");
356 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
357 * blocking function that will only return TRUE when nbytes have actually been
358 * written or FALSE when an unrecoverable error has been detected. Failure of
359 * this function is an indication that the sockfilt process should terminate.
362 static bool write_stdout(const void *buffer, size_t nbytes)
364 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
365 if(nwrite != (ssize_t)nbytes) {
366 logmsg("exiting...");
372 static void lograw(unsigned char *buffer, ssize_t len)
376 unsigned char *ptr = buffer;
380 for(i=0; i<len; i++) {
383 sprintf(optr, "\\n");
388 sprintf(optr, "\\r");
393 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
400 logmsg("'%s'", data);
406 logmsg("'%s'", data);
410 * WinSock select() does not support standard file descriptors,
411 * it can only check SOCKETs. The following function is an attempt
412 * to re-create a select() function with support for other handle types.
416 * select() function with support for WINSOCK2 sockets and all
417 * other handle types supported by WaitForMultipleObjectsEx().
419 * TODO: Differentiate between read/write/except for non-SOCKET handles.
421 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
422 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
424 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
425 fd_set *exceptfds, struct timeval *timeout)
428 DWORD milliseconds, wait, idx, avail, events, inputs;
429 WSAEVENT wsaevent, *wsaevents;
430 WSANETWORKEVENTS wsanetevents;
431 INPUT_RECORD *inputrecords;
432 HANDLE handle, *handles;
433 curl_socket_t sock, *fdarr, *wsasocks;
435 DWORD nfd = 0, wsa = 0;
438 /* check if the input value is valid */
440 SET_SOCKERRNO(EINVAL);
444 /* check if we got descriptors, sleep in case we got none */
446 Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
450 /* allocate internal array for the original input handles */
451 fdarr = malloc(nfds * sizeof(curl_socket_t));
453 SET_SOCKERRNO(ENOMEM);
457 /* allocate internal array for the internal event handles */
458 handles = malloc(nfds * sizeof(HANDLE));
459 if(handles == NULL) {
460 SET_SOCKERRNO(ENOMEM);
464 /* allocate internal array for the internal socket handles */
465 wsasocks = malloc(nfds * sizeof(curl_socket_t));
466 if(wsasocks == NULL) {
467 SET_SOCKERRNO(ENOMEM);
471 /* allocate internal array for the internal WINSOCK2 events */
472 wsaevents = malloc(nfds * sizeof(WSAEVENT));
473 if(wsaevents == NULL) {
474 SET_SOCKERRNO(ENOMEM);
478 /* loop over the handles in the input descriptor sets */
479 for(fds = 0; fds < nfds; fds++) {
483 if(FD_ISSET(fds, readfds))
484 networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
486 if(FD_ISSET(fds, writefds))
487 networkevents |= FD_WRITE|FD_CONNECT;
489 if(FD_ISSET(fds, exceptfds))
490 networkevents |= FD_OOB;
492 /* only wait for events for which we actually care */
494 fdarr[nfd] = (curl_socket_t)fds;
495 if(fds == fileno(stdin)) {
496 handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
498 else if(fds == fileno(stdout)) {
499 handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
501 else if(fds == fileno(stderr)) {
502 handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
505 wsaevent = WSACreateEvent();
506 if(wsaevent != WSA_INVALID_EVENT) {
507 error = WSAEventSelect(fds, wsaevent, networkevents);
508 if(error != SOCKET_ERROR) {
509 handles[nfd] = wsaevent;
510 wsasocks[wsa] = (curl_socket_t)fds;
511 wsaevents[wsa] = wsaevent;
515 handles[nfd] = (HANDLE)fds;
516 WSACloseEvent(wsaevent);
524 /* convert struct timeval to milliseconds */
526 milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
529 milliseconds = INFINITE;
532 /* wait for one of the internal handles to trigger */
533 wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
535 /* loop over the internal handles returned in the descriptors */
536 for(idx = 0; idx < nfd; idx++) {
538 handle = handles[idx];
539 sock = (curl_socket_t)fds;
541 /* check if the current internal handle was triggered */
542 if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) >= idx &&
543 WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
544 /* try to handle the event with STD* handle functions */
545 if(fds == fileno(stdin)) {
546 /* check if there is no data in the input buffer */
548 /* check if we are getting data from a PIPE */
549 if(!GetConsoleMode(handle, &avail)) {
550 /* check if there is no data from PIPE input */
551 if(!PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
554 FD_CLR(sock, readfds);
555 } /* check if there is no data from keyboard input */
556 else if (!_kbhit()) {
557 /* check if there are INPUT_RECORDs in the input buffer */
558 if(GetNumberOfConsoleInputEvents(handle, &events)) {
560 /* remove INPUT_RECORDs from the input buffer */
561 inputrecords = (INPUT_RECORD*)malloc(events *
562 sizeof(INPUT_RECORD));
564 if(!ReadConsoleInput(handle, inputrecords,
570 /* check if we got all inputs, otherwise clear buffer */
572 FlushConsoleInputBuffer(handle);
576 /* remove from descriptor set since there is no real data */
577 FD_CLR(sock, readfds);
581 /* stdin is never ready for write or exceptional */
582 FD_CLR(sock, writefds);
583 FD_CLR(sock, exceptfds);
585 else if(fds == fileno(stdout) || fds == fileno(stderr)) {
586 /* stdout and stderr are never ready for read or exceptional */
587 FD_CLR(sock, readfds);
588 FD_CLR(sock, exceptfds);
591 /* try to handle the event with the WINSOCK2 functions */
592 error = WSAEnumNetworkEvents(fds, NULL, &wsanetevents);
593 if(error != SOCKET_ERROR) {
594 /* remove from descriptor set if not ready for read/accept/close */
595 if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
596 FD_CLR(sock, readfds);
598 /* remove from descriptor set if not ready for write/connect */
599 if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
600 FD_CLR(sock, writefds);
602 /* remove from descriptor set if not exceptional */
603 if(!(wsanetevents.lNetworkEvents & FD_OOB))
604 FD_CLR(sock, exceptfds);
608 /* check if the event has not been filtered using specific tests */
609 if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
610 FD_ISSET(sock, exceptfds)) {
615 /* remove from all descriptor sets since this handle did not trigger */
616 FD_CLR(sock, readfds);
617 FD_CLR(sock, writefds);
618 FD_CLR(sock, exceptfds);
622 for(idx = 0; idx < wsa; idx++) {
623 WSAEventSelect(wsasocks[idx], NULL, 0);
624 WSACloseEvent(wsaevents[idx]);
634 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
638 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
640 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
643 static bool juggle(curl_socket_t *sockfdp,
644 curl_socket_t listenfd,
647 struct timeval timeout;
651 curl_socket_t sockfd = CURL_SOCKET_BAD;
654 ssize_t nread_socket;
655 ssize_t bytes_written;
659 /* 'buffer' is this excessively large only to be able to support things like
660 test 1003 which tests exceedingly large server response lines */
661 unsigned char buffer[17010];
664 if(got_exit_signal) {
665 logmsg("signalled to die, exiting...");
670 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
671 parent ftpserver process has died without killing its sockfilt children */
673 logmsg("process becomes orphan, exiting");
678 timeout.tv_sec = 120;
685 FD_SET((curl_socket_t)fileno(stdin), &fds_read);
693 /* there's always a socket to wait for */
694 FD_SET(sockfd, &fds_read);
698 case PASSIVE_CONNECT:
701 if(CURL_SOCKET_BAD == sockfd) {
702 /* eeek, we are supposedly connected and then this cannot be -1 ! */
703 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
704 maxfd = 0; /* stdin */
707 /* there's always a socket to wait for */
708 FD_SET(sockfd, &fds_read);
716 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
717 if(CURL_SOCKET_BAD != sockfd) {
718 FD_SET(sockfd, &fds_read);
722 logmsg("No socket to read on");
727 case ACTIVE_DISCONNECT:
729 logmsg("disconnected, no socket to read on");
731 sockfd = CURL_SOCKET_BAD;
734 } /* switch(*mode) */
739 /* select() blocking behavior call on blocking descriptors please */
741 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
743 if(got_exit_signal) {
744 logmsg("signalled to die, exiting...");
748 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
751 logmsg("select() failed with error: (%d) %s",
752 error, strerror(error));
761 if(FD_ISSET(fileno(stdin), &fds_read)) {
762 /* read from stdin, commands/data to be dealt with and possibly passed on
767 4 letter command + LF [mandatory]
769 4-digit hexadecimal data length + LF [if the command takes data]
770 data [the data being as long as set above]
774 DATA - plain pass-thru data
777 if(!read_stdin(buffer, 5))
780 logmsg("Received %c%c%c%c (on stdin)",
781 buffer[0], buffer[1], buffer[2], buffer[3] );
783 if(!memcmp("PING", buffer, 4)) {
784 /* send reply on stdout, just proving we are alive */
785 if(!write_stdout("PONG\n", 5))
789 else if(!memcmp("PORT", buffer, 4)) {
790 /* Question asking us what PORT number we are listening to.
791 Replies to PORT with "IPv[num]/[port]" */
792 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
793 buffer_len = (ssize_t)strlen((char *)buffer);
794 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
795 if(!write_stdout(data, 10))
797 if(!write_stdout(buffer, buffer_len))
800 else if(!memcmp("QUIT", buffer, 4)) {
805 else if(!memcmp("DATA", buffer, 4)) {
806 /* data IN => data OUT */
808 if(!read_stdin(buffer, 5))
813 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
814 if (buffer_len > (ssize_t)sizeof(buffer)) {
815 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
816 "(%zd bytes)", sizeof(buffer), buffer_len);
819 logmsg("> %zd bytes data, server => client", buffer_len);
821 if(!read_stdin(buffer, buffer_len))
824 lograw(buffer, buffer_len);
826 if(*mode == PASSIVE_LISTEN) {
827 logmsg("*** We are disconnected!");
828 if(!write_stdout("DISC\n", 5))
832 /* send away on the socket */
833 bytes_written = swrite(sockfd, buffer, buffer_len);
834 if(bytes_written != buffer_len) {
835 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
836 buffer_len, bytes_written);
840 else if(!memcmp("DISC", buffer, 4)) {
842 if(!write_stdout("DISC\n", 5))
844 if(sockfd != CURL_SOCKET_BAD) {
845 logmsg("====> Client forcibly disconnected");
847 *sockfdp = CURL_SOCKET_BAD;
848 if(*mode == PASSIVE_CONNECT)
849 *mode = PASSIVE_LISTEN;
851 *mode = ACTIVE_DISCONNECT;
854 logmsg("attempt to close already dead connection");
860 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
862 if(*mode == PASSIVE_LISTEN) {
863 /* there's no stream set up yet, this is an indication that there's a
864 client connecting. */
866 sockfd = accept(listenfd, NULL, NULL);
867 if(CURL_SOCKET_BAD == sockfd) {
869 logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
870 listenfd, error, strerror(error));
873 logmsg("====> Client connect");
874 if(!write_stdout("CNCT\n", 5))
876 *sockfdp = sockfd; /* store the new socket */
877 *mode = PASSIVE_CONNECT; /* we have connected */
882 /* read from socket, pass on data to stdout */
883 nread_socket = sread(sockfd, buffer, sizeof(buffer));
885 if(nread_socket <= 0) {
886 logmsg("====> Client disconnect");
887 if(!write_stdout("DISC\n", 5))
890 *sockfdp = CURL_SOCKET_BAD;
891 if(*mode == PASSIVE_CONNECT)
892 *mode = PASSIVE_LISTEN;
894 *mode = ACTIVE_DISCONNECT;
898 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
899 if(!write_stdout(data, 10))
901 if(!write_stdout(buffer, nread_socket))
904 logmsg("< %zd bytes data, client => server", nread_socket);
905 lograw(buffer, nread_socket);
911 static curl_socket_t sockdaemon(curl_socket_t sock,
912 unsigned short *listenport)
914 /* passive daemon style */
915 srvr_sockaddr_union_t listener;
927 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
928 (void *)&flag, sizeof(flag));
931 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
932 error, strerror(error));
936 /* should not happen */
938 logmsg("wait_ms() failed with error: (%d) %s",
939 error, strerror(error));
941 return CURL_SOCKET_BAD;
943 if(got_exit_signal) {
944 logmsg("signalled to die, exiting...");
946 return CURL_SOCKET_BAD;
949 delay *= 2; /* double the sleep for next attempt */
952 } while(rc && maxretr--);
955 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
956 attempt, totdelay, error, strerror(error));
957 logmsg("Continuing anyway...");
960 /* When the specified listener port is zero, it is actually a
961 request to let the system choose a non-zero available port. */
966 memset(&listener.sa4, 0, sizeof(listener.sa4));
967 listener.sa4.sin_family = AF_INET;
968 listener.sa4.sin_addr.s_addr = INADDR_ANY;
969 listener.sa4.sin_port = htons(*listenport);
970 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
974 memset(&listener.sa6, 0, sizeof(listener.sa6));
975 listener.sa6.sin6_family = AF_INET6;
976 listener.sa6.sin6_addr = in6addr_any;
977 listener.sa6.sin6_port = htons(*listenport);
978 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
980 #endif /* ENABLE_IPV6 */
983 logmsg("Error binding socket on port %hu: (%d) %s",
984 *listenport, error, strerror(error));
986 return CURL_SOCKET_BAD;
990 /* The system was supposed to choose a port number, figure out which
991 port we actually got and update the listener port value with it. */
992 curl_socklen_t la_size;
993 srvr_sockaddr_union_t localaddr;
997 la_size = sizeof(localaddr.sa4);
1000 la_size = sizeof(localaddr.sa6);
1002 memset(&localaddr.sa, 0, (size_t)la_size);
1003 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1005 logmsg("getsockname() failed with error: (%d) %s",
1006 error, strerror(error));
1008 return CURL_SOCKET_BAD;
1010 switch (localaddr.sa.sa_family) {
1012 *listenport = ntohs(localaddr.sa4.sin_port);
1016 *listenport = ntohs(localaddr.sa6.sin6_port);
1023 /* Real failure, listener port shall not be zero beyond this point. */
1024 logmsg("Apparently getsockname() succeeded, with listener port zero.");
1025 logmsg("A valid reason for this failure is a binary built without");
1026 logmsg("proper network library linkage. This might not be the only");
1027 logmsg("reason, but double check it before anything else.");
1029 return CURL_SOCKET_BAD;
1033 /* bindonly option forces no listening */
1035 logmsg("instructed to bind port without listening");
1039 /* start accepting connections */
1040 rc = listen(sock, 5);
1043 logmsg("listen(%d, 5) failed with error: (%d) %s",
1044 sock, error, strerror(error));
1046 return CURL_SOCKET_BAD;
1053 int main(int argc, char *argv[])
1055 srvr_sockaddr_union_t me;
1056 curl_socket_t sock = CURL_SOCKET_BAD;
1057 curl_socket_t msgsock = CURL_SOCKET_BAD;
1058 int wrotepidfile = 0;
1059 char *pidname= (char *)".sockfilt.pid";
1064 enum sockmode mode = PASSIVE_LISTEN; /* default */
1065 const char *addr = NULL;
1068 if(!strcmp("--version", argv[arg])) {
1069 printf("sockfilt IPv4%s\n",
1078 else if(!strcmp("--verbose", argv[arg])) {
1082 else if(!strcmp("--pidfile", argv[arg])) {
1085 pidname = argv[arg++];
1087 else if(!strcmp("--logfile", argv[arg])) {
1090 serverlogfile = argv[arg++];
1092 else if(!strcmp("--ipv6", argv[arg])) {
1099 else if(!strcmp("--ipv4", argv[arg])) {
1100 /* for completeness, we support this option as well */
1107 else if(!strcmp("--bindonly", argv[arg])) {
1111 else if(!strcmp("--port", argv[arg])) {
1115 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1116 if((endptr != argv[arg] + strlen(argv[arg])) ||
1117 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1118 fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1122 port = curlx_ultous(ulnum);
1126 else if(!strcmp("--connect", argv[arg])) {
1127 /* Asked to actively connect to the specified local port instead of
1128 doing a passive server-style listening. */
1132 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1133 if((endptr != argv[arg] + strlen(argv[arg])) ||
1134 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1135 fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1139 connectport = curlx_ultous(ulnum);
1143 else if(!strcmp("--addr", argv[arg])) {
1144 /* Set an IP address to use with --connect; otherwise use localhost */
1152 puts("Usage: sockfilt [option]\n"
1155 " --logfile [file]\n"
1156 " --pidfile [file]\n"
1161 " --connect [port]\n"
1162 " --addr [address]");
1169 atexit(win32_cleanup);
1171 setmode(fileno(stdin), O_BINARY);
1172 setmode(fileno(stdout), O_BINARY);
1173 setmode(fileno(stderr), O_BINARY);
1176 install_signal_handlers();
1181 sock = socket(AF_INET, SOCK_STREAM, 0);
1184 sock = socket(AF_INET6, SOCK_STREAM, 0);
1187 if(CURL_SOCKET_BAD == sock) {
1189 logmsg("Error creating socket: (%d) %s",
1190 error, strerror(error));
1191 write_stdout("FAIL\n", 5);
1192 goto sockfilt_cleanup;
1196 /* Active mode, we should connect to the given port number */
1201 memset(&me.sa4, 0, sizeof(me.sa4));
1202 me.sa4.sin_family = AF_INET;
1203 me.sa4.sin_port = htons(connectport);
1204 me.sa4.sin_addr.s_addr = INADDR_ANY;
1207 Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1209 rc = connect(sock, &me.sa, sizeof(me.sa4));
1213 memset(&me.sa6, 0, sizeof(me.sa6));
1214 me.sa6.sin6_family = AF_INET6;
1215 me.sa6.sin6_port = htons(connectport);
1218 Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1220 rc = connect(sock, &me.sa, sizeof(me.sa6));
1222 #endif /* ENABLE_IPV6 */
1225 logmsg("Error connecting to port %hu: (%d) %s",
1226 connectport, error, strerror(error));
1227 write_stdout("FAIL\n", 5);
1228 goto sockfilt_cleanup;
1230 logmsg("====> Client connect");
1231 msgsock = sock; /* use this as stream */
1234 /* passive daemon style */
1235 sock = sockdaemon(sock, &port);
1236 if(CURL_SOCKET_BAD == sock) {
1237 write_stdout("FAIL\n", 5);
1238 goto sockfilt_cleanup;
1240 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1243 logmsg("Running %s version", ipv_inuse);
1246 logmsg("Connected to port %hu", connectport);
1248 logmsg("Bound without listening on port %hu", port);
1250 logmsg("Listening on port %hu", port);
1252 wrotepidfile = write_pidfile(pidname);
1254 write_stdout("FAIL\n", 5);
1255 goto sockfilt_cleanup;
1259 juggle_again = juggle(&msgsock, sock, &mode);
1260 } while(juggle_again);
1264 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1267 if(sock != CURL_SOCKET_BAD)
1273 restore_signal_handlers();
1275 if(got_exit_signal) {
1276 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1278 * To properly set the return status of the process we
1279 * must raise the same signal SIGINT or SIGTERM that we
1280 * caught and let the old handler take care of it.
1285 logmsg("============> sockfilt quits");