1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2009, 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 #include "setup.h" /* portability help from the lib directory */
91 #ifdef HAVE_SYS_SOCKET_H
92 #include <sys/socket.h>
94 #ifdef HAVE_NETINET_IN_H
95 #include <netinet/in.h>
97 #ifdef HAVE_ARPA_INET_H
98 #include <arpa/inet.h>
104 #define ENABLE_CURLX_PRINTF
105 /* make the curlx header define all printf() functions to use the curlx_*
107 #include "curlx.h" /* from the private lib dir */
109 #include "inet_pton.h"
112 /* include memdebug.h last */
113 #include "memdebug.h"
115 #define DEFAULT_PORT 8999
117 #ifndef DEFAULT_LOGFILE
118 #define DEFAULT_LOGFILE "log/sockfilt.log"
121 const char *serverlogfile = DEFAULT_LOGFILE;
123 static bool verbose = FALSE;
125 static bool use_ipv6 = FALSE;
127 static const char *ipv_inuse = "IPv4";
128 static unsigned short port = DEFAULT_PORT;
129 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
132 PASSIVE_LISTEN, /* as a server waiting for connections */
133 PASSIVE_CONNECT, /* as a server, connected to a client */
134 ACTIVE, /* as a client, connected to a server */
135 ACTIVE_DISCONNECT /* as a client, disconnected from server */
138 /* do-nothing macro replacement for systems which lack siginterrupt() */
140 #ifndef HAVE_SIGINTERRUPT
141 #define siginterrupt(x,y) do {} while(0)
144 /* vars used to keep around previous signal handlers */
146 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
149 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
153 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
157 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
161 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
165 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
168 /* var which if set indicates that the program should finish execution */
170 SIG_ATOMIC_T got_exit_signal = 0;
172 /* if next is set indicates the first signal handled in exit_signal_handler */
174 static volatile int exit_signal = 0;
176 /* signal handler that will be triggered to indicate that the program
177 should finish its execution in a controlled manner as soon as possible.
178 The first time this is called it will set got_exit_signal to one and
179 store in exit_signal the signal that triggered its execution. */
181 static RETSIGTYPE exit_signal_handler(int signum)
183 int old_errno = ERRNO;
184 if(got_exit_signal == 0) {
186 exit_signal = signum;
188 (void)signal(signum, exit_signal_handler);
189 SET_ERRNO(old_errno);
192 static void install_signal_handlers(void)
195 /* ignore SIGHUP signal */
196 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
197 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
200 /* ignore SIGPIPE signal */
201 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
202 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
205 /* ignore SIGALRM signal */
206 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
207 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
210 /* handle SIGINT signal with our exit_signal_handler */
211 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
212 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
214 siginterrupt(SIGINT, 1);
217 /* handle SIGTERM signal with our exit_signal_handler */
218 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
219 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
221 siginterrupt(SIGTERM, 1);
225 static void restore_signal_handlers(void)
228 if(SIG_ERR != old_sighup_handler)
229 (void)signal(SIGHUP, old_sighup_handler);
232 if(SIG_ERR != old_sigpipe_handler)
233 (void)signal(SIGPIPE, old_sigpipe_handler);
236 if(SIG_ERR != old_sigalrm_handler)
237 (void)signal(SIGALRM, old_sigalrm_handler);
240 if(SIG_ERR != old_sigint_handler)
241 (void)signal(SIGINT, old_sigint_handler);
244 if(SIG_ERR != old_sigterm_handler)
245 (void)signal(SIGTERM, old_sigterm_handler);
250 * fullread is a wrapper around the read() function. This will repeat the call
251 * to read() until it actually has read the complete number of bytes indicated
252 * in nbytes or it fails with a condition that cannot be handled with a simple
253 * retry of the read call.
256 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
263 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
265 if(got_exit_signal) {
266 logmsg("signalled to die");
272 if((error == EINTR) || (error == EAGAIN))
274 logmsg("unrecoverable read() failure: %s", 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: %s", strerror(error));
323 logmsg("put 0 writing to stdout");
329 } while((size_t)nwrite < nbytes);
332 logmsg("wrote %zd bytes", nwrite);
338 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
339 * blocking function that will only return TRUE when nbytes have actually been
340 * read or FALSE when an unrecoverable error has been detected. Failure of this
341 * function is an indication that the sockfilt process should terminate.
344 static bool read_stdin(void *buffer, size_t nbytes)
346 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
347 if(nread != (ssize_t)nbytes) {
348 logmsg("exiting...");
355 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
356 * blocking function that will only return TRUE when nbytes have actually been
357 * written or FALSE when an unrecoverable error has been detected. Failure of
358 * this function is an indication that the sockfilt process should terminate.
361 static bool write_stdout(const void *buffer, size_t nbytes)
363 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
364 if(nwrite != (ssize_t)nbytes) {
365 logmsg("exiting...");
371 static void lograw(unsigned char *buffer, ssize_t len)
375 unsigned char *ptr = buffer;
379 for(i=0; i<len; i++) {
382 sprintf(optr, "\\n");
387 sprintf(optr, "\\r");
392 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
399 logmsg("'%s'", data);
405 logmsg("'%s'", data);
409 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
411 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
414 static bool juggle(curl_socket_t *sockfdp,
415 curl_socket_t listenfd,
418 struct timeval timeout;
422 curl_socket_t sockfd = CURL_SOCKET_BAD;
423 curl_socket_t maxfd = CURL_SOCKET_BAD;
425 ssize_t nread_socket;
426 ssize_t bytes_written;
430 /* 'buffer' is this excessively large only to be able to support things like
431 test 1003 which tests exceedingly large server response lines */
432 unsigned char buffer[17010];
435 if(got_exit_signal) {
436 logmsg("signalled to die, exiting...");
441 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
442 parent ftpserver process has died without killing its sockfilt children */
444 logmsg("process becomes orphan, exiting");
449 timeout.tv_sec = 120;
458 ** WinSock select() does not support standard file descriptors,
459 ** it can only check SOCKETs. Since this program in its current
460 ** state will not work on WinSock based systems, next line is
461 ** commented out to allow warning-free compilation awaiting the
462 ** day it will be fixed to also run on WinSock systems.
465 FD_SET(fileno(stdin), &fds_read);
474 /* there's always a socket to wait for */
475 FD_SET(sockfd, &fds_read);
479 case PASSIVE_CONNECT:
482 if(CURL_SOCKET_BAD == sockfd) {
483 /* eeek, we are supposedly connected and then this cannot be -1 ! */
484 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
485 maxfd = 0; /* stdin */
488 /* there's always a socket to wait for */
489 FD_SET(sockfd, &fds_read);
497 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
498 if(CURL_SOCKET_BAD != sockfd) {
499 FD_SET(sockfd, &fds_read);
503 logmsg("No socket to read on");
508 case ACTIVE_DISCONNECT:
510 logmsg("disconnected, no socket to read on");
512 sockfd = CURL_SOCKET_BAD;
515 } /* switch(*mode) */
520 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
522 if(got_exit_signal) {
523 logmsg("signalled to die, exiting...");
527 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
530 logmsg("select() failed with error: (%d) %s",
531 error, strerror(error));
540 if(FD_ISSET(fileno(stdin), &fds_read)) {
541 /* read from stdin, commands/data to be dealt with and possibly passed on
546 4 letter command + LF [mandatory]
548 4-digit hexadecimal data length + LF [if the command takes data]
549 data [the data being as long as set above]
553 DATA - plain pass-thru data
556 if(!read_stdin(buffer, 5))
559 logmsg("Received %c%c%c%c (on stdin)",
560 buffer[0], buffer[1], buffer[2], buffer[3] );
562 if(!memcmp("PING", buffer, 4)) {
563 /* send reply on stdout, just proving we are alive */
564 if(!write_stdout("PONG\n", 5))
568 else if(!memcmp("PORT", buffer, 4)) {
569 /* Question asking us what PORT number we are listening to.
570 Replies to PORT with "IPv[num]/[port]" */
571 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
572 buffer_len = (ssize_t)strlen((char *)buffer);
573 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
574 if(!write_stdout(data, 10))
576 if(!write_stdout(buffer, buffer_len))
579 else if(!memcmp("QUIT", buffer, 4)) {
584 else if(!memcmp("DATA", buffer, 4)) {
585 /* data IN => data OUT */
587 if(!read_stdin(buffer, 5))
592 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
593 if (buffer_len > (ssize_t)sizeof(buffer)) {
594 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
595 "(%zd bytes)", sizeof(buffer), buffer_len);
598 logmsg("> %zd bytes data, server => client", buffer_len);
600 if(!read_stdin(buffer, buffer_len))
603 lograw(buffer, buffer_len);
605 if(*mode == PASSIVE_LISTEN) {
606 logmsg("*** We are disconnected!");
607 if(!write_stdout("DISC\n", 5))
611 /* send away on the socket */
612 bytes_written = swrite(sockfd, buffer, buffer_len);
613 if(bytes_written != buffer_len) {
614 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
615 buffer_len, bytes_written);
619 else if(!memcmp("DISC", buffer, 4)) {
621 if(!write_stdout("DISC\n", 5))
623 if(sockfd != CURL_SOCKET_BAD) {
624 logmsg("====> Client forcibly disconnected");
626 *sockfdp = CURL_SOCKET_BAD;
627 if(*mode == PASSIVE_CONNECT)
628 *mode = PASSIVE_LISTEN;
630 *mode = ACTIVE_DISCONNECT;
633 logmsg("attempt to close already dead connection");
639 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
641 if(*mode == PASSIVE_LISTEN) {
642 /* there's no stream set up yet, this is an indication that there's a
643 client connecting. */
644 sockfd = accept(sockfd, NULL, NULL);
645 if(CURL_SOCKET_BAD == sockfd)
646 logmsg("accept() failed");
648 logmsg("====> Client connect");
649 if(!write_stdout("CNCT\n", 5))
651 *sockfdp = sockfd; /* store the new socket */
652 *mode = PASSIVE_CONNECT; /* we have connected */
657 /* read from socket, pass on data to stdout */
658 nread_socket = sread(sockfd, buffer, sizeof(buffer));
660 if(nread_socket <= 0) {
661 logmsg("====> Client disconnect");
662 if(!write_stdout("DISC\n", 5))
665 *sockfdp = CURL_SOCKET_BAD;
666 if(*mode == PASSIVE_CONNECT)
667 *mode = PASSIVE_LISTEN;
669 *mode = ACTIVE_DISCONNECT;
673 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
674 if(!write_stdout(data, 10))
676 if(!write_stdout(buffer, nread_socket))
679 logmsg("< %zd bytes data, client => server", nread_socket);
680 lograw(buffer, nread_socket);
686 static curl_socket_t sockdaemon(curl_socket_t sock,
687 unsigned short *listenport)
689 /* passive daemon style */
690 struct sockaddr_in me;
692 struct sockaddr_in6 me6;
693 #endif /* ENABLE_IPV6 */
705 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
706 (void *)&flag, sizeof(flag));
709 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
710 error, strerror(error));
714 /* should not happen */
716 logmsg("wait_ms() failed with error: (%d) %s",
717 error, strerror(error));
719 return CURL_SOCKET_BAD;
721 if(got_exit_signal) {
722 logmsg("signalled to die, exiting...");
724 return CURL_SOCKET_BAD;
727 delay *= 2; /* double the sleep for next attempt */
730 } while(rc && maxretr--);
733 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
734 attempt, totdelay, error, strerror(error));
735 logmsg("Continuing anyway...");
738 /* When the specified listener port is zero, it is actually a
739 request to let the system choose a non-zero available port. */
744 memset(&me, 0, sizeof(me));
745 me.sin_family = AF_INET;
746 me.sin_addr.s_addr = INADDR_ANY;
747 me.sin_port = htons(*listenport);
748 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
752 memset(&me6, 0, sizeof(me6));
753 me6.sin6_family = AF_INET6;
754 me6.sin6_addr = in6addr_any;
755 me6.sin6_port = htons(*listenport);
756 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
758 #endif /* ENABLE_IPV6 */
761 logmsg("Error binding socket: (%d) %s", error, strerror(error));
763 return CURL_SOCKET_BAD;
767 /* The system was supposed to choose a port number, figure out which
768 port we actually got and update the listener port value with it. */
769 curl_socklen_t la_size;
770 struct sockaddr *localaddr;
771 struct sockaddr_in localaddr4;
773 struct sockaddr_in6 localaddr6;
776 la_size = sizeof(localaddr4);
777 localaddr = (struct sockaddr *)&localaddr4;
781 la_size = sizeof(localaddr6);
782 localaddr = (struct sockaddr *)&localaddr6;
785 memset(localaddr, 0, (size_t)la_size);
786 if(getsockname(sock, localaddr, &la_size) < 0) {
788 logmsg("getsockname() failed with error: (%d) %s",
789 error, strerror(error));
791 return CURL_SOCKET_BAD;
793 switch (localaddr->sa_family) {
795 *listenport = ntohs(localaddr4.sin_port);
799 *listenport = ntohs(localaddr6.sin6_port);
806 /* Real failure, listener port shall not be zero beyond this point. */
807 logmsg("Apparently getsockname() succeeded, with listener port zero.");
808 logmsg("A valid reason for this failure is a binary built without");
809 logmsg("proper network library linkage. This might not be the only");
810 logmsg("reason, but double check it before anything else.");
812 return CURL_SOCKET_BAD;
816 /* start accepting connections */
817 rc = listen(sock, 5);
820 logmsg("listen() failed with error: (%d) %s",
821 error, strerror(error));
823 return CURL_SOCKET_BAD;
830 int main(int argc, char *argv[])
832 struct sockaddr_in me;
834 struct sockaddr_in6 me6;
835 #endif /* ENABLE_IPV6 */
836 curl_socket_t sock = CURL_SOCKET_BAD;
837 curl_socket_t msgsock = CURL_SOCKET_BAD;
838 int wrotepidfile = 0;
839 char *pidname= (char *)".sockfilt.pid";
843 enum sockmode mode = PASSIVE_LISTEN; /* default */
844 const char *addr = NULL;
847 if(!strcmp("--version", argv[arg])) {
848 printf("sockfilt IPv4%s\n",
857 else if(!strcmp("--verbose", argv[arg])) {
861 else if(!strcmp("--pidfile", argv[arg])) {
864 pidname = argv[arg++];
866 else if(!strcmp("--logfile", argv[arg])) {
869 serverlogfile = argv[arg++];
871 else if(!strcmp("--ipv6", argv[arg])) {
878 else if(!strcmp("--ipv4", argv[arg])) {
879 /* for completeness, we support this option as well */
886 else if(!strcmp("--port", argv[arg])) {
889 port = (unsigned short)atoi(argv[arg]);
893 else if(!strcmp("--connect", argv[arg])) {
894 /* Asked to actively connect to the specified local port instead of
895 doing a passive server-style listening. */
898 connectport = (unsigned short)atoi(argv[arg]);
902 else if(!strcmp("--addr", argv[arg])) {
903 /* Set an IP address to use with --connect; otherwise use localhost */
911 puts("Usage: sockfilt [option]\n"
914 " --logfile [file]\n"
915 " --pidfile [file]\n"
919 " --connect [port]\n"
920 " --addr [address]");
927 atexit(win32_cleanup);
930 install_signal_handlers();
935 sock = socket(AF_INET, SOCK_STREAM, 0);
938 sock = socket(AF_INET6, SOCK_STREAM, 0);
941 if(CURL_SOCKET_BAD == sock) {
943 logmsg("Error creating socket: (%d) %s",
944 error, strerror(error));
945 goto sockfilt_cleanup;
949 /* Active mode, we should connect to the given port number */
954 memset(&me, 0, sizeof(me));
955 me.sin_family = AF_INET;
956 me.sin_port = htons(connectport);
957 me.sin_addr.s_addr = INADDR_ANY;
960 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
962 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
966 memset(&me6, 0, sizeof(me6));
967 me6.sin6_family = AF_INET6;
968 me6.sin6_port = htons(connectport);
971 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
973 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
975 #endif /* ENABLE_IPV6 */
978 logmsg("Error connecting to port %hu: (%d) %s",
979 connectport, error, strerror(error));
980 goto sockfilt_cleanup;
982 logmsg("====> Client connect");
983 msgsock = sock; /* use this as stream */
986 /* passive daemon style */
987 sock = sockdaemon(sock, &port);
988 if(CURL_SOCKET_BAD == sock)
989 goto sockfilt_cleanup;
990 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
993 logmsg("Running %s version", ipv_inuse);
996 logmsg("Connected to port %hu", connectport);
998 logmsg("Listening on port %hu", port);
1000 wrotepidfile = write_pidfile(pidname);
1002 goto sockfilt_cleanup;
1004 while(juggle(&msgsock, sock, &mode));
1008 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1011 if(sock != CURL_SOCKET_BAD)
1017 restore_signal_handlers();
1019 if(got_exit_signal) {
1020 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1022 * To properly set the return status of the process we
1023 * must raise the same signal SIGINT or SIGTERM that we
1024 * caught and let the old handler take care of it.
1029 logmsg("============> sockfilt quits");