1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, 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.
22 ***************************************************************************/
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!
83 #define CURL_NO_OLDIES
85 #include "setup.h" /* portability help from the lib directory */
93 #ifdef HAVE_SYS_SOCKET_H
94 #include <sys/socket.h>
96 #ifdef HAVE_NETINET_IN_H
97 #include <netinet/in.h>
99 #ifdef HAVE_ARPA_INET_H
100 #include <arpa/inet.h>
106 #define ENABLE_CURLX_PRINTF
107 /* make the curlx header define all printf() functions to use the curlx_*
109 #include "curlx.h" /* from the private lib dir */
111 #include "inet_pton.h"
114 /* include memdebug.h last */
115 #include "memdebug.h"
117 #define DEFAULT_PORT 8999
119 #ifndef DEFAULT_LOGFILE
120 #define DEFAULT_LOGFILE "log/sockfilt.log"
123 const char *serverlogfile = DEFAULT_LOGFILE;
125 static bool verbose = FALSE;
127 static bool use_ipv6 = FALSE;
129 static const char *ipv_inuse = "IPv4";
130 static unsigned short port = DEFAULT_PORT;
131 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
134 PASSIVE_LISTEN, /* as a server waiting for connections */
135 PASSIVE_CONNECT, /* as a server, connected to a client */
136 ACTIVE, /* as a client, connected to a server */
137 ACTIVE_DISCONNECT /* as a client, disconnected from server */
140 /* do-nothing macro replacement for systems which lack siginterrupt() */
142 #ifndef HAVE_SIGINTERRUPT
143 #define siginterrupt(x,y) do {} while(0)
146 /* vars used to keep around previous signal handlers */
148 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
151 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
155 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
159 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
163 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
167 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
170 /* var which if set indicates that the program should finish execution */
172 SIG_ATOMIC_T got_exit_signal = 0;
174 /* if next is set indicates the first signal handled in exit_signal_handler */
176 static volatile int exit_signal = 0;
178 /* signal handler that will be triggered to indicate that the program
179 should finish its execution in a controlled manner as soon as possible.
180 The first time this is called it will set got_exit_signal to one and
181 store in exit_signal the signal that triggered its execution. */
183 static RETSIGTYPE exit_signal_handler(int signum)
185 int old_errno = ERRNO;
186 if(got_exit_signal == 0) {
188 exit_signal = signum;
190 (void)signal(signum, exit_signal_handler);
191 SET_ERRNO(old_errno);
194 static void install_signal_handlers(void)
197 /* ignore SIGHUP signal */
198 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
199 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
202 /* ignore SIGPIPE signal */
203 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
204 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
207 /* ignore SIGALRM signal */
208 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
209 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
212 /* handle SIGINT signal with our exit_signal_handler */
213 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
214 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
216 siginterrupt(SIGINT, 1);
219 /* handle SIGTERM signal with our exit_signal_handler */
220 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
221 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
223 siginterrupt(SIGTERM, 1);
227 static void restore_signal_handlers(void)
230 if(SIG_ERR != old_sighup_handler)
231 (void)signal(SIGHUP, old_sighup_handler);
234 if(SIG_ERR != old_sigpipe_handler)
235 (void)signal(SIGPIPE, old_sigpipe_handler);
238 if(SIG_ERR != old_sigalrm_handler)
239 (void)signal(SIGALRM, old_sigalrm_handler);
242 if(SIG_ERR != old_sigint_handler)
243 (void)signal(SIGINT, old_sigint_handler);
246 if(SIG_ERR != old_sigterm_handler)
247 (void)signal(SIGTERM, old_sigterm_handler);
252 * fullread is a wrapper around the read() function. This will repeat the call
253 * to read() until it actually has read the complete number of bytes indicated
254 * in nbytes or it fails with a condition that cannot be handled with a simple
255 * retry of the read call.
258 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
265 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
267 if(got_exit_signal) {
268 logmsg("signalled to die");
274 if((error == EINTR) || (error == EAGAIN))
276 logmsg("unrecoverable read() failure: %s", strerror(error));
281 logmsg("got 0 reading from stdin");
287 } while((size_t)nread < nbytes);
290 logmsg("read %zd bytes", nread);
296 * fullwrite is a wrapper around the write() function. This will repeat the
297 * call to write() until it actually has written the complete number of bytes
298 * indicated in nbytes or it fails with a condition that cannot be handled
299 * with a simple retry of the write call.
302 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
309 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
311 if(got_exit_signal) {
312 logmsg("signalled to die");
318 if((error == EINTR) || (error == EAGAIN))
320 logmsg("unrecoverable write() failure: %s", strerror(error));
325 logmsg("put 0 writing to stdout");
331 } while((size_t)nwrite < nbytes);
334 logmsg("wrote %zd bytes", nwrite);
340 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
341 * blocking function that will only return TRUE when nbytes have actually been
342 * read or FALSE when an unrecoverable error has been detected. Failure of this
343 * function is an indication that the sockfilt process should terminate.
346 static bool read_stdin(void *buffer, size_t nbytes)
348 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
349 if(nread != (ssize_t)nbytes) {
350 logmsg("exiting...");
357 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
358 * blocking function that will only return TRUE when nbytes have actually been
359 * written or FALSE when an unrecoverable error has been detected. Failure of
360 * this function is an indication that the sockfilt process should terminate.
363 static bool write_stdout(const void *buffer, size_t nbytes)
365 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
366 if(nwrite != (ssize_t)nbytes) {
367 logmsg("exiting...");
373 static void lograw(unsigned char *buffer, ssize_t len)
377 unsigned char *ptr = buffer;
381 for(i=0; i<len; i++) {
384 sprintf(optr, "\\n");
389 sprintf(optr, "\\r");
394 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
401 logmsg("'%s'", data);
407 logmsg("'%s'", data);
411 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
413 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
416 static bool juggle(curl_socket_t *sockfdp,
417 curl_socket_t listenfd,
420 struct timeval timeout;
424 curl_socket_t sockfd = CURL_SOCKET_BAD;
425 curl_socket_t maxfd = CURL_SOCKET_BAD;
427 ssize_t nread_socket;
428 ssize_t bytes_written;
432 /* 'buffer' is this excessively large only to be able to support things like
433 test 1003 which tests exceedingly large server response lines */
434 unsigned char buffer[17010];
437 if(got_exit_signal) {
438 logmsg("signalled to die, exiting...");
443 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
444 parent ftpserver process has died without killing its sockfilt children */
446 logmsg("process becomes orphan, exiting");
451 timeout.tv_sec = 120;
460 ** WinSock select() does not support standard file descriptors,
461 ** it can only check SOCKETs. Since this program in its current
462 ** state will not work on WinSock based systems, next line is
463 ** commented out to allow warning-free compilation awaiting the
464 ** day it will be fixed to also run on WinSock systems.
467 FD_SET(fileno(stdin), &fds_read);
476 /* there's always a socket to wait for */
477 FD_SET(sockfd, &fds_read);
481 case PASSIVE_CONNECT:
484 if(CURL_SOCKET_BAD == sockfd) {
485 /* eeek, we are supposedly connected and then this cannot be -1 ! */
486 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
487 maxfd = 0; /* stdin */
490 /* there's always a socket to wait for */
491 FD_SET(sockfd, &fds_read);
499 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
500 if(CURL_SOCKET_BAD != sockfd) {
501 FD_SET(sockfd, &fds_read);
505 logmsg("No socket to read on");
510 case ACTIVE_DISCONNECT:
512 logmsg("disconnected, no socket to read on");
514 sockfd = CURL_SOCKET_BAD;
517 } /* switch(*mode) */
522 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
524 if(got_exit_signal) {
525 logmsg("signalled to die, exiting...");
529 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
532 logmsg("select() failed with error: (%d) %s",
533 error, strerror(error));
542 if(FD_ISSET(fileno(stdin), &fds_read)) {
543 /* read from stdin, commands/data to be dealt with and possibly passed on
548 4 letter command + LF [mandatory]
550 4-digit hexadecimal data length + LF [if the command takes data]
551 data [the data being as long as set above]
555 DATA - plain pass-thru data
558 if(!read_stdin(buffer, 5))
561 logmsg("Received %c%c%c%c (on stdin)",
562 buffer[0], buffer[1], buffer[2], buffer[3] );
564 if(!memcmp("PING", buffer, 4)) {
565 /* send reply on stdout, just proving we are alive */
566 if(!write_stdout("PONG\n", 5))
570 else if(!memcmp("PORT", buffer, 4)) {
571 /* Question asking us what PORT number we are listening to.
572 Replies to PORT with "IPv[num]/[port]" */
573 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
574 buffer_len = (ssize_t)strlen((char *)buffer);
575 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
576 if(!write_stdout(data, 10))
578 if(!write_stdout(buffer, buffer_len))
581 else if(!memcmp("QUIT", buffer, 4)) {
586 else if(!memcmp("DATA", buffer, 4)) {
587 /* data IN => data OUT */
589 if(!read_stdin(buffer, 5))
594 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
595 if (buffer_len > (ssize_t)sizeof(buffer)) {
596 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
597 "(%zd bytes)", sizeof(buffer), buffer_len);
600 logmsg("> %zd bytes data, server => client", buffer_len);
602 if(!read_stdin(buffer, buffer_len))
605 lograw(buffer, buffer_len);
607 if(*mode == PASSIVE_LISTEN) {
608 logmsg("*** We are disconnected!");
609 if(!write_stdout("DISC\n", 5))
613 /* send away on the socket */
614 bytes_written = swrite(sockfd, buffer, buffer_len);
615 if(bytes_written != buffer_len) {
616 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
617 buffer_len, bytes_written);
621 else if(!memcmp("DISC", buffer, 4)) {
623 if(!write_stdout("DISC\n", 5))
625 if(sockfd != CURL_SOCKET_BAD) {
626 logmsg("====> Client forcibly disconnected");
628 *sockfdp = CURL_SOCKET_BAD;
629 if(*mode == PASSIVE_CONNECT)
630 *mode = PASSIVE_LISTEN;
632 *mode = ACTIVE_DISCONNECT;
635 logmsg("attempt to close already dead connection");
641 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
643 if(*mode == PASSIVE_LISTEN) {
644 /* there's no stream set up yet, this is an indication that there's a
645 client connecting. */
646 sockfd = accept(sockfd, NULL, NULL);
647 if(CURL_SOCKET_BAD == sockfd)
648 logmsg("accept() failed");
650 logmsg("====> Client connect");
651 if(!write_stdout("CNCT\n", 5))
653 *sockfdp = sockfd; /* store the new socket */
654 *mode = PASSIVE_CONNECT; /* we have connected */
659 /* read from socket, pass on data to stdout */
660 nread_socket = sread(sockfd, buffer, sizeof(buffer));
662 if(nread_socket <= 0) {
663 logmsg("====> Client disconnect");
664 if(!write_stdout("DISC\n", 5))
667 *sockfdp = CURL_SOCKET_BAD;
668 if(*mode == PASSIVE_CONNECT)
669 *mode = PASSIVE_LISTEN;
671 *mode = ACTIVE_DISCONNECT;
675 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
676 if(!write_stdout(data, 10))
678 if(!write_stdout(buffer, nread_socket))
681 logmsg("< %zd bytes data, client => server", nread_socket);
682 lograw(buffer, nread_socket);
688 static curl_socket_t sockdaemon(curl_socket_t sock,
689 unsigned short *listenport)
691 /* passive daemon style */
692 struct sockaddr_in me;
694 struct sockaddr_in6 me6;
695 #endif /* ENABLE_IPV6 */
707 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
708 (void *)&flag, sizeof(flag));
711 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
712 error, strerror(error));
716 /* should not happen */
718 logmsg("wait_ms() failed with error: (%d) %s",
719 error, strerror(error));
721 return CURL_SOCKET_BAD;
723 if(got_exit_signal) {
724 logmsg("signalled to die, exiting...");
726 return CURL_SOCKET_BAD;
729 delay *= 2; /* double the sleep for next attempt */
732 } while(rc && maxretr--);
735 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
736 attempt, totdelay, error, strerror(error));
737 logmsg("Continuing anyway...");
740 /* When the specified listener port is zero, it is actually a
741 request to let the system choose a non-zero available port. */
746 memset(&me, 0, sizeof(me));
747 me.sin_family = AF_INET;
748 me.sin_addr.s_addr = INADDR_ANY;
749 me.sin_port = htons(*listenport);
750 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
754 memset(&me6, 0, sizeof(me6));
755 me6.sin6_family = AF_INET6;
756 me6.sin6_addr = in6addr_any;
757 me6.sin6_port = htons(*listenport);
758 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
760 #endif /* ENABLE_IPV6 */
763 logmsg("Error binding socket on port %hu: (%d) %s",
764 *listenport, error, strerror(error));
766 return CURL_SOCKET_BAD;
770 /* The system was supposed to choose a port number, figure out which
771 port we actually got and update the listener port value with it. */
772 curl_socklen_t la_size;
773 struct sockaddr *localaddr;
774 struct sockaddr_in localaddr4;
776 struct sockaddr_in6 localaddr6;
779 la_size = sizeof(localaddr4);
780 localaddr = (struct sockaddr *)&localaddr4;
784 la_size = sizeof(localaddr6);
785 localaddr = (struct sockaddr *)&localaddr6;
788 memset(localaddr, 0, (size_t)la_size);
789 if(getsockname(sock, localaddr, &la_size) < 0) {
791 logmsg("getsockname() failed with error: (%d) %s",
792 error, strerror(error));
794 return CURL_SOCKET_BAD;
796 switch (localaddr->sa_family) {
798 *listenport = ntohs(localaddr4.sin_port);
802 *listenport = ntohs(localaddr6.sin6_port);
809 /* Real failure, listener port shall not be zero beyond this point. */
810 logmsg("Apparently getsockname() succeeded, with listener port zero.");
811 logmsg("A valid reason for this failure is a binary built without");
812 logmsg("proper network library linkage. This might not be the only");
813 logmsg("reason, but double check it before anything else.");
815 return CURL_SOCKET_BAD;
819 /* start accepting connections */
820 rc = listen(sock, 5);
823 logmsg("listen() failed with error: (%d) %s",
824 error, strerror(error));
826 return CURL_SOCKET_BAD;
833 int main(int argc, char *argv[])
835 struct sockaddr_in me;
837 struct sockaddr_in6 me6;
838 #endif /* ENABLE_IPV6 */
839 curl_socket_t sock = CURL_SOCKET_BAD;
840 curl_socket_t msgsock = CURL_SOCKET_BAD;
841 int wrotepidfile = 0;
842 char *pidname= (char *)".sockfilt.pid";
847 enum sockmode mode = PASSIVE_LISTEN; /* default */
848 const char *addr = NULL;
851 if(!strcmp("--version", argv[arg])) {
852 printf("sockfilt IPv4%s\n",
861 else if(!strcmp("--verbose", argv[arg])) {
865 else if(!strcmp("--pidfile", argv[arg])) {
868 pidname = argv[arg++];
870 else if(!strcmp("--logfile", argv[arg])) {
873 serverlogfile = argv[arg++];
875 else if(!strcmp("--ipv6", argv[arg])) {
882 else if(!strcmp("--ipv4", argv[arg])) {
883 /* for completeness, we support this option as well */
890 else if(!strcmp("--port", argv[arg])) {
893 port = (unsigned short)atoi(argv[arg]);
897 else if(!strcmp("--connect", argv[arg])) {
898 /* Asked to actively connect to the specified local port instead of
899 doing a passive server-style listening. */
902 connectport = (unsigned short)atoi(argv[arg]);
906 else if(!strcmp("--addr", argv[arg])) {
907 /* Set an IP address to use with --connect; otherwise use localhost */
915 puts("Usage: sockfilt [option]\n"
918 " --logfile [file]\n"
919 " --pidfile [file]\n"
923 " --connect [port]\n"
924 " --addr [address]");
931 atexit(win32_cleanup);
934 install_signal_handlers();
939 sock = socket(AF_INET, SOCK_STREAM, 0);
942 sock = socket(AF_INET6, SOCK_STREAM, 0);
945 if(CURL_SOCKET_BAD == sock) {
947 logmsg("Error creating socket: (%d) %s",
948 error, strerror(error));
949 goto sockfilt_cleanup;
953 /* Active mode, we should connect to the given port number */
958 memset(&me, 0, sizeof(me));
959 me.sin_family = AF_INET;
960 me.sin_port = htons(connectport);
961 me.sin_addr.s_addr = INADDR_ANY;
964 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
966 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
970 memset(&me6, 0, sizeof(me6));
971 me6.sin6_family = AF_INET6;
972 me6.sin6_port = htons(connectport);
975 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
977 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
979 #endif /* ENABLE_IPV6 */
982 logmsg("Error connecting to port %hu: (%d) %s",
983 connectport, error, strerror(error));
984 goto sockfilt_cleanup;
986 logmsg("====> Client connect");
987 msgsock = sock; /* use this as stream */
990 /* passive daemon style */
991 sock = sockdaemon(sock, &port);
992 if(CURL_SOCKET_BAD == sock)
993 goto sockfilt_cleanup;
994 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
997 logmsg("Running %s version", ipv_inuse);
1000 logmsg("Connected to port %hu", connectport);
1002 logmsg("Listening on port %hu", port);
1004 wrotepidfile = write_pidfile(pidname);
1006 goto sockfilt_cleanup;
1009 juggle_again = juggle(&msgsock, sock, &mode);
1010 } while(juggle_again);
1014 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1017 if(sock != CURL_SOCKET_BAD)
1023 restore_signal_handlers();
1025 if(got_exit_signal) {
1026 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1028 * To properly set the return status of the process we
1029 * must raise the same signal SIGINT or SIGTERM that we
1030 * caught and let the old handler take care of it.
1035 logmsg("============> sockfilt quits");