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 #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"
105 /* include memdebug.h last */
106 #include "memdebug.h"
108 #define DEFAULT_PORT 8999
110 #ifndef DEFAULT_LOGFILE
111 #define DEFAULT_LOGFILE "log/sockfilt.log"
114 const char *serverlogfile = DEFAULT_LOGFILE;
116 static bool verbose = FALSE;
117 static bool bind_only = FALSE;
119 static bool use_ipv6 = FALSE;
121 static const char *ipv_inuse = "IPv4";
122 static unsigned short port = DEFAULT_PORT;
123 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
126 PASSIVE_LISTEN, /* as a server waiting for connections */
127 PASSIVE_CONNECT, /* as a server, connected to a client */
128 ACTIVE, /* as a client, connected to a server */
129 ACTIVE_DISCONNECT /* as a client, disconnected from server */
132 /* do-nothing macro replacement for systems which lack siginterrupt() */
134 #ifndef HAVE_SIGINTERRUPT
135 #define siginterrupt(x,y) do {} while(0)
138 /* vars used to keep around previous signal handlers */
140 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
143 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
147 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
151 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
155 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
159 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
162 /* var which if set indicates that the program should finish execution */
164 SIG_ATOMIC_T got_exit_signal = 0;
166 /* if next is set indicates the first signal handled in exit_signal_handler */
168 static volatile int exit_signal = 0;
170 /* signal handler that will be triggered to indicate that the program
171 should finish its execution in a controlled manner as soon as possible.
172 The first time this is called it will set got_exit_signal to one and
173 store in exit_signal the signal that triggered its execution. */
175 static RETSIGTYPE exit_signal_handler(int signum)
177 int old_errno = ERRNO;
178 if(got_exit_signal == 0) {
180 exit_signal = signum;
182 (void)signal(signum, exit_signal_handler);
183 SET_ERRNO(old_errno);
186 static void install_signal_handlers(void)
189 /* ignore SIGHUP signal */
190 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
191 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
194 /* ignore SIGPIPE signal */
195 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
196 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
199 /* ignore SIGALRM signal */
200 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
201 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
204 /* handle SIGINT signal with our exit_signal_handler */
205 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
206 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
208 siginterrupt(SIGINT, 1);
211 /* handle SIGTERM signal with our exit_signal_handler */
212 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
213 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
215 siginterrupt(SIGTERM, 1);
219 static void restore_signal_handlers(void)
222 if(SIG_ERR != old_sighup_handler)
223 (void)signal(SIGHUP, old_sighup_handler);
226 if(SIG_ERR != old_sigpipe_handler)
227 (void)signal(SIGPIPE, old_sigpipe_handler);
230 if(SIG_ERR != old_sigalrm_handler)
231 (void)signal(SIGALRM, old_sigalrm_handler);
234 if(SIG_ERR != old_sigint_handler)
235 (void)signal(SIGINT, old_sigint_handler);
238 if(SIG_ERR != old_sigterm_handler)
239 (void)signal(SIGTERM, old_sigterm_handler);
244 * fullread is a wrapper around the read() function. This will repeat the call
245 * to read() until it actually has read the complete number of bytes indicated
246 * in nbytes or it fails with a condition that cannot be handled with a simple
247 * retry of the read call.
250 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
257 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
259 if(got_exit_signal) {
260 logmsg("signalled to die");
266 if((error == EINTR) || (error == EAGAIN))
268 logmsg("unrecoverable read() failure: %s", strerror(error));
273 logmsg("got 0 reading from stdin");
279 } while((size_t)nread < nbytes);
282 logmsg("read %zd bytes", nread);
288 * fullwrite is a wrapper around the write() function. This will repeat the
289 * call to write() until it actually has written the complete number of bytes
290 * indicated in nbytes or it fails with a condition that cannot be handled
291 * with a simple retry of the write call.
294 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
301 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
303 if(got_exit_signal) {
304 logmsg("signalled to die");
310 if((error == EINTR) || (error == EAGAIN))
312 logmsg("unrecoverable write() failure: %s", strerror(error));
317 logmsg("put 0 writing to stdout");
323 } while((size_t)nwrite < nbytes);
326 logmsg("wrote %zd bytes", nwrite);
332 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
333 * blocking function that will only return TRUE when nbytes have actually been
334 * read or FALSE when an unrecoverable error has been detected. Failure of this
335 * function is an indication that the sockfilt process should terminate.
338 static bool read_stdin(void *buffer, size_t nbytes)
340 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
341 if(nread != (ssize_t)nbytes) {
342 logmsg("exiting...");
349 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
350 * blocking function that will only return TRUE when nbytes have actually been
351 * written or FALSE when an unrecoverable error has been detected. Failure of
352 * this function is an indication that the sockfilt process should terminate.
355 static bool write_stdout(const void *buffer, size_t nbytes)
357 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
358 if(nwrite != (ssize_t)nbytes) {
359 logmsg("exiting...");
365 static void lograw(unsigned char *buffer, ssize_t len)
369 unsigned char *ptr = buffer;
373 for(i=0; i<len; i++) {
376 sprintf(optr, "\\n");
381 sprintf(optr, "\\r");
386 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
393 logmsg("'%s'", data);
399 logmsg("'%s'", data);
403 * WinSock select() does not support standard file descriptors,
404 * it can only check SOCKETs. The following function is an attempt
405 * to re-create a select() function with support for other handle types.
409 * select() function with support for WINSOCK2 sockets and all
410 * other handle types supported by WaitForMultipleObjectsEx().
412 * TODO: Differentiate between read/write/except for non-SOCKET handles.
414 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
415 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
417 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
418 fd_set *exceptfds, struct timeval *timeout)
420 int ret = 0, fds = 0, nfd = 0, idx = 0, wsa = 0, error = 0;
422 DWORD milliseconds, wait;
423 WSAEVENT wsaevent, *wsaevents;
424 WSANETWORKEVENTS wsanetevents;
428 /* allocate internal array for the original input handles */
429 fdarr = malloc(sizeof(int)*nfds);
435 /* allocate internal array for the internal event handles */
436 handles = malloc(sizeof(HANDLE)*nfds);
437 if(handles == NULL) {
442 /* allocate internal array for the internal WINSOCK2 events */
443 wsaevents = malloc(sizeof(WSAEVENT)*nfds);
444 if(wsaevents == NULL) {
449 /* loop over the handles in the input descriptor sets */
450 for(fds = 0; fds < nfds; fds++) {
454 if(FD_ISSET(fds, readfds))
455 networkevents |= FD_READ;
457 if(FD_ISSET(fds, writefds))
458 networkevents |= FD_WRITE;
460 if(FD_ISSET(fds, exceptfds))
461 networkevents |= FD_CLOSE;
465 if(fds == fileno(stdin)) {
466 handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
468 else if(fds == fileno(stdout)) {
469 handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
471 else if(fds == fileno(stderr)) {
472 handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
475 wsaevent = WSACreateEvent();
476 if(wsaevent != WSA_INVALID_EVENT) {
477 error = WSAEventSelect(fds, wsaevent, networkevents);
478 if(error != SOCKET_ERROR) {
479 handles[nfd] = wsaevent;
480 wsaevents[wsa++] = wsaevent;
483 handles[nfd] = (HANDLE) fds;
484 WSACloseEvent(wsaevent);
492 /* convert struct timeval to milliseconds */
494 milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
497 milliseconds = INFINITE;
500 /* wait for one of the internal handles to trigger */
501 wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
503 /* loop over the internal handles returned in the descriptors */
504 for(idx = 0; idx < nfd; idx++) {
505 if(wait != WAIT_OBJECT_0 + idx) {
506 /* remove from all descriptor sets since this handle did not trigger */
507 FD_CLR(fdarr[idx], readfds);
508 FD_CLR(fdarr[idx], writefds);
509 FD_CLR(fdarr[idx], exceptfds);
512 /* first try to handle the event with the WINSOCK2 functions */
513 error = WSAEnumNetworkEvents(fdarr[idx], NULL, &wsanetevents);
514 if(error != SOCKET_ERROR) {
515 /* remove from descriptor set if not ready for read */
516 if(!(wsanetevents.lNetworkEvents & FD_READ))
517 FD_CLR(fdarr[idx], readfds);
519 /* remove from descriptor set if not ready for write */
520 if(!(wsanetevents.lNetworkEvents & FD_WRITE))
521 FD_CLR(fdarr[idx], writefds);
523 /* remove from descriptor set if not exceptional */
524 if(!(wsanetevents.lNetworkEvents & FD_CLOSE))
525 FD_CLR(fdarr[idx], exceptfds);
531 for(idx = 0; idx < wsa; idx++)
532 WSACloseEvent(wsaevents[idx]);
543 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
545 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
548 static bool juggle(curl_socket_t *sockfdp,
549 curl_socket_t listenfd,
552 struct timeval timeout;
556 curl_socket_t sockfd = CURL_SOCKET_BAD;
557 curl_socket_t maxfd = CURL_SOCKET_BAD;
559 ssize_t nread_socket;
560 ssize_t bytes_written;
564 /* 'buffer' is this excessively large only to be able to support things like
565 test 1003 which tests exceedingly large server response lines */
566 unsigned char buffer[17010];
569 if(got_exit_signal) {
570 logmsg("signalled to die, exiting...");
575 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
576 parent ftpserver process has died without killing its sockfilt children */
578 logmsg("process becomes orphan, exiting");
583 timeout.tv_sec = 120;
590 FD_SET(fileno(stdin), &fds_read);
598 /* there's always a socket to wait for */
599 FD_SET(sockfd, &fds_read);
603 case PASSIVE_CONNECT:
606 if(CURL_SOCKET_BAD == sockfd) {
607 /* eeek, we are supposedly connected and then this cannot be -1 ! */
608 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
609 maxfd = 0; /* stdin */
612 /* there's always a socket to wait for */
613 FD_SET(sockfd, &fds_read);
621 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
622 if(CURL_SOCKET_BAD != sockfd) {
623 FD_SET(sockfd, &fds_read);
627 logmsg("No socket to read on");
632 case ACTIVE_DISCONNECT:
634 logmsg("disconnected, no socket to read on");
636 sockfd = CURL_SOCKET_BAD;
639 } /* switch(*mode) */
645 rc = select_ws((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
647 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
650 if(got_exit_signal) {
651 logmsg("signalled to die, exiting...");
655 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
658 logmsg("select() failed with error: (%d) %s",
659 error, strerror(error));
668 if(FD_ISSET(fileno(stdin), &fds_read)) {
669 /* read from stdin, commands/data to be dealt with and possibly passed on
674 4 letter command + LF [mandatory]
676 4-digit hexadecimal data length + LF [if the command takes data]
677 data [the data being as long as set above]
681 DATA - plain pass-thru data
684 if(!read_stdin(buffer, 5))
687 logmsg("Received %c%c%c%c (on stdin)",
688 buffer[0], buffer[1], buffer[2], buffer[3] );
690 if(!memcmp("PING", buffer, 4)) {
691 /* send reply on stdout, just proving we are alive */
692 if(!write_stdout("PONG\n", 5))
696 else if(!memcmp("PORT", buffer, 4)) {
697 /* Question asking us what PORT number we are listening to.
698 Replies to PORT with "IPv[num]/[port]" */
699 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
700 buffer_len = (ssize_t)strlen((char *)buffer);
701 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
702 if(!write_stdout(data, 10))
704 if(!write_stdout(buffer, buffer_len))
707 else if(!memcmp("QUIT", buffer, 4)) {
712 else if(!memcmp("DATA", buffer, 4)) {
713 /* data IN => data OUT */
715 if(!read_stdin(buffer, 5))
720 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
721 if (buffer_len > (ssize_t)sizeof(buffer)) {
722 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
723 "(%zd bytes)", sizeof(buffer), buffer_len);
726 logmsg("> %zd bytes data, server => client", buffer_len);
728 if(!read_stdin(buffer, buffer_len))
731 lograw(buffer, buffer_len);
733 if(*mode == PASSIVE_LISTEN) {
734 logmsg("*** We are disconnected!");
735 if(!write_stdout("DISC\n", 5))
739 /* send away on the socket */
740 bytes_written = swrite(sockfd, buffer, buffer_len);
741 if(bytes_written != buffer_len) {
742 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
743 buffer_len, bytes_written);
747 else if(!memcmp("DISC", buffer, 4)) {
749 if(!write_stdout("DISC\n", 5))
751 if(sockfd != CURL_SOCKET_BAD) {
752 logmsg("====> Client forcibly disconnected");
754 *sockfdp = CURL_SOCKET_BAD;
755 if(*mode == PASSIVE_CONNECT)
756 *mode = PASSIVE_LISTEN;
758 *mode = ACTIVE_DISCONNECT;
761 logmsg("attempt to close already dead connection");
767 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
769 if(*mode == PASSIVE_LISTEN) {
770 /* there's no stream set up yet, this is an indication that there's a
771 client connecting. */
772 sockfd = accept(sockfd, NULL, NULL);
773 if(CURL_SOCKET_BAD == sockfd)
774 logmsg("accept() failed");
776 logmsg("====> Client connect");
777 if(!write_stdout("CNCT\n", 5))
779 *sockfdp = sockfd; /* store the new socket */
780 *mode = PASSIVE_CONNECT; /* we have connected */
785 /* read from socket, pass on data to stdout */
786 nread_socket = sread(sockfd, buffer, sizeof(buffer));
788 if(nread_socket <= 0) {
789 logmsg("====> Client disconnect");
790 if(!write_stdout("DISC\n", 5))
793 *sockfdp = CURL_SOCKET_BAD;
794 if(*mode == PASSIVE_CONNECT)
795 *mode = PASSIVE_LISTEN;
797 *mode = ACTIVE_DISCONNECT;
801 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
802 if(!write_stdout(data, 10))
804 if(!write_stdout(buffer, nread_socket))
807 logmsg("< %zd bytes data, client => server", nread_socket);
808 lograw(buffer, nread_socket);
814 static curl_socket_t sockdaemon(curl_socket_t sock,
815 unsigned short *listenport)
817 /* passive daemon style */
818 srvr_sockaddr_union_t listener;
830 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
831 (void *)&flag, sizeof(flag));
834 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
835 error, strerror(error));
839 /* should not happen */
841 logmsg("wait_ms() failed with error: (%d) %s",
842 error, strerror(error));
844 return CURL_SOCKET_BAD;
846 if(got_exit_signal) {
847 logmsg("signalled to die, exiting...");
849 return CURL_SOCKET_BAD;
852 delay *= 2; /* double the sleep for next attempt */
855 } while(rc && maxretr--);
858 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
859 attempt, totdelay, error, strerror(error));
860 logmsg("Continuing anyway...");
863 /* When the specified listener port is zero, it is actually a
864 request to let the system choose a non-zero available port. */
869 memset(&listener.sa4, 0, sizeof(listener.sa4));
870 listener.sa4.sin_family = AF_INET;
871 listener.sa4.sin_addr.s_addr = INADDR_ANY;
872 listener.sa4.sin_port = htons(*listenport);
873 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
877 memset(&listener.sa6, 0, sizeof(listener.sa6));
878 listener.sa6.sin6_family = AF_INET6;
879 listener.sa6.sin6_addr = in6addr_any;
880 listener.sa6.sin6_port = htons(*listenport);
881 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
883 #endif /* ENABLE_IPV6 */
886 logmsg("Error binding socket on port %hu: (%d) %s",
887 *listenport, error, strerror(error));
889 return CURL_SOCKET_BAD;
893 /* The system was supposed to choose a port number, figure out which
894 port we actually got and update the listener port value with it. */
895 curl_socklen_t la_size;
896 srvr_sockaddr_union_t localaddr;
900 la_size = sizeof(localaddr.sa4);
903 la_size = sizeof(localaddr.sa6);
905 memset(&localaddr.sa, 0, (size_t)la_size);
906 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
908 logmsg("getsockname() failed with error: (%d) %s",
909 error, strerror(error));
911 return CURL_SOCKET_BAD;
913 switch (localaddr.sa.sa_family) {
915 *listenport = ntohs(localaddr.sa4.sin_port);
919 *listenport = ntohs(localaddr.sa6.sin6_port);
926 /* Real failure, listener port shall not be zero beyond this point. */
927 logmsg("Apparently getsockname() succeeded, with listener port zero.");
928 logmsg("A valid reason for this failure is a binary built without");
929 logmsg("proper network library linkage. This might not be the only");
930 logmsg("reason, but double check it before anything else.");
932 return CURL_SOCKET_BAD;
936 /* bindonly option forces no listening */
938 logmsg("instructed to bind port without listening");
942 /* start accepting connections */
943 rc = listen(sock, 5);
946 logmsg("listen() failed with error: (%d) %s",
947 error, strerror(error));
949 return CURL_SOCKET_BAD;
956 int main(int argc, char *argv[])
958 srvr_sockaddr_union_t me;
959 curl_socket_t sock = CURL_SOCKET_BAD;
960 curl_socket_t msgsock = CURL_SOCKET_BAD;
961 int wrotepidfile = 0;
962 char *pidname= (char *)".sockfilt.pid";
967 enum sockmode mode = PASSIVE_LISTEN; /* default */
968 const char *addr = NULL;
971 if(!strcmp("--version", argv[arg])) {
972 printf("sockfilt IPv4%s\n",
981 else if(!strcmp("--verbose", argv[arg])) {
985 else if(!strcmp("--pidfile", argv[arg])) {
988 pidname = argv[arg++];
990 else if(!strcmp("--logfile", argv[arg])) {
993 serverlogfile = argv[arg++];
995 else if(!strcmp("--ipv6", argv[arg])) {
1002 else if(!strcmp("--ipv4", argv[arg])) {
1003 /* for completeness, we support this option as well */
1010 else if(!strcmp("--bindonly", argv[arg])) {
1014 else if(!strcmp("--port", argv[arg])) {
1018 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1019 if((endptr != argv[arg] + strlen(argv[arg])) ||
1020 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1021 fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1025 port = curlx_ultous(ulnum);
1029 else if(!strcmp("--connect", argv[arg])) {
1030 /* Asked to actively connect to the specified local port instead of
1031 doing a passive server-style listening. */
1035 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1036 if((endptr != argv[arg] + strlen(argv[arg])) ||
1037 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1038 fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1042 connectport = curlx_ultous(ulnum);
1046 else if(!strcmp("--addr", argv[arg])) {
1047 /* Set an IP address to use with --connect; otherwise use localhost */
1055 puts("Usage: sockfilt [option]\n"
1058 " --logfile [file]\n"
1059 " --pidfile [file]\n"
1064 " --connect [port]\n"
1065 " --addr [address]");
1072 atexit(win32_cleanup);
1075 install_signal_handlers();
1080 sock = socket(AF_INET, SOCK_STREAM, 0);
1083 sock = socket(AF_INET6, SOCK_STREAM, 0);
1086 if(CURL_SOCKET_BAD == sock) {
1088 logmsg("Error creating socket: (%d) %s",
1089 error, strerror(error));
1090 write_stdout("FAIL\n", 5);
1091 goto sockfilt_cleanup;
1095 /* Active mode, we should connect to the given port number */
1100 memset(&me.sa4, 0, sizeof(me.sa4));
1101 me.sa4.sin_family = AF_INET;
1102 me.sa4.sin_port = htons(connectport);
1103 me.sa4.sin_addr.s_addr = INADDR_ANY;
1106 Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1108 rc = connect(sock, &me.sa, sizeof(me.sa4));
1112 memset(&me.sa6, 0, sizeof(me.sa6));
1113 me.sa6.sin6_family = AF_INET6;
1114 me.sa6.sin6_port = htons(connectport);
1117 Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1119 rc = connect(sock, &me.sa, sizeof(me.sa6));
1121 #endif /* ENABLE_IPV6 */
1124 logmsg("Error connecting to port %hu: (%d) %s",
1125 connectport, error, strerror(error));
1126 write_stdout("FAIL\n", 5);
1127 goto sockfilt_cleanup;
1129 logmsg("====> Client connect");
1130 msgsock = sock; /* use this as stream */
1133 /* passive daemon style */
1134 sock = sockdaemon(sock, &port);
1135 if(CURL_SOCKET_BAD == sock) {
1136 write_stdout("FAIL\n", 5);
1137 goto sockfilt_cleanup;
1139 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1142 logmsg("Running %s version", ipv_inuse);
1145 logmsg("Connected to port %hu", connectport);
1147 logmsg("Bound without listening on port %hu", port);
1149 logmsg("Listening on port %hu", port);
1151 wrotepidfile = write_pidfile(pidname);
1153 write_stdout("FAIL\n", 5);
1154 goto sockfilt_cleanup;
1158 juggle_again = juggle(&msgsock, sock, &mode);
1159 } while(juggle_again);
1163 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1166 if(sock != CURL_SOCKET_BAD)
1172 restore_signal_handlers();
1174 if(got_exit_signal) {
1175 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1177 * To properly set the return status of the process we
1178 * must raise the same signal SIGINT or SIGTERM that we
1179 * caught and let the old handler take care of it.
1184 logmsg("============> sockfilt quits");