1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, 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 _XOPEN_SOURCE_EXTENDED
98 /* This define is "almost" required to build on HPUX 11 */
99 #include <arpa/inet.h>
105 #define ENABLE_CURLX_PRINTF
106 /* make the curlx header define all printf() functions to use the curlx_*
108 #include "curlx.h" /* from the private lib dir */
110 #include "inet_pton.h"
113 /* include memdebug.h last */
114 #include "memdebug.h"
116 #define DEFAULT_PORT 8999
118 #ifndef DEFAULT_LOGFILE
119 #define DEFAULT_LOGFILE "log/sockfilt.log"
122 const char *serverlogfile = DEFAULT_LOGFILE;
124 static bool verbose = FALSE;
126 static bool use_ipv6 = FALSE;
128 static const char *ipv_inuse = "IPv4";
129 static unsigned short port = DEFAULT_PORT;
130 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
133 PASSIVE_LISTEN, /* as a server waiting for connections */
134 PASSIVE_CONNECT, /* as a server, connected to a client */
135 ACTIVE, /* as a client, connected to a server */
136 ACTIVE_DISCONNECT /* as a client, disconnected from server */
139 /* do-nothing macro replacement for systems which lack siginterrupt() */
141 #ifndef HAVE_SIGINTERRUPT
142 #define siginterrupt(x,y) do {} while(0)
145 /* vars used to keep around previous signal handlers */
147 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
150 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
154 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
158 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
162 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
166 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
169 /* var which if set indicates that the program should finish execution */
171 SIG_ATOMIC_T got_exit_signal = 0;
173 /* if next is set indicates the first signal handled in exit_signal_handler */
175 static volatile int exit_signal = 0;
177 /* signal handler that will be triggered to indicate that the program
178 should finish its execution in a controlled manner as soon as possible.
179 The first time this is called it will set got_exit_signal to one and
180 store in exit_signal the signal that triggered its execution. */
182 static RETSIGTYPE exit_signal_handler(int signum)
184 int old_errno = ERRNO;
185 if(got_exit_signal == 0) {
187 exit_signal = signum;
189 (void)signal(signum, exit_signal_handler);
190 SET_ERRNO(old_errno);
193 static void install_signal_handlers(void)
196 /* ignore SIGHUP signal */
197 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
198 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
201 /* ignore SIGPIPE signal */
202 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
203 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
206 /* ignore SIGALRM signal */
207 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
208 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
211 /* handle SIGINT signal with our exit_signal_handler */
212 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
213 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
215 siginterrupt(SIGINT, 1);
218 /* handle SIGTERM signal with our exit_signal_handler */
219 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
220 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
222 siginterrupt(SIGTERM, 1);
226 static void restore_signal_handlers(void)
229 if(SIG_ERR != old_sighup_handler)
230 (void)signal(SIGHUP, old_sighup_handler);
233 if(SIG_ERR != old_sigpipe_handler)
234 (void)signal(SIGPIPE, old_sigpipe_handler);
237 if(SIG_ERR != old_sigalrm_handler)
238 (void)signal(SIGALRM, old_sigalrm_handler);
241 if(SIG_ERR != old_sigint_handler)
242 (void)signal(SIGINT, old_sigint_handler);
245 if(SIG_ERR != old_sigterm_handler)
246 (void)signal(SIGTERM, old_sigterm_handler);
251 * fullread is a wrapper around the read() function. This will repeat the call
252 * to read() until it actually has read the complete number of bytes indicated
253 * in nbytes or it fails with a condition that cannot be handled with a simple
254 * retry of the read call.
257 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
264 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
266 if(got_exit_signal) {
267 logmsg("signalled to die");
273 if((error == EINTR) || (error == EAGAIN))
275 logmsg("unrecoverable read() failure: %s", strerror(error));
280 logmsg("got 0 reading from stdin");
286 } while((size_t)nread < nbytes);
289 logmsg("read %zd bytes", nread);
295 * fullwrite is a wrapper around the write() function. This will repeat the
296 * call to write() until it actually has written the complete number of bytes
297 * indicated in nbytes or it fails with a condition that cannot be handled
298 * with a simple retry of the write call.
301 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
308 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
310 if(got_exit_signal) {
311 logmsg("signalled to die");
317 if((error == EINTR) || (error == EAGAIN))
319 logmsg("unrecoverable write() failure: %s", 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 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
412 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
415 static bool juggle(curl_socket_t *sockfdp,
416 curl_socket_t listenfd,
419 struct timeval timeout;
423 curl_socket_t sockfd = CURL_SOCKET_BAD;
424 curl_socket_t maxfd = CURL_SOCKET_BAD;
426 ssize_t nread_socket;
427 ssize_t bytes_written;
431 /* 'buffer' is this excessively large only to be able to support things like
432 test 1003 which tests exceedingly large server response lines */
433 unsigned char buffer[17010];
436 if(got_exit_signal) {
437 logmsg("signalled to die, exiting...");
442 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
443 parent ftpserver process has died without killing its sockfilt children */
445 logmsg("process becomes orphan, exiting");
450 timeout.tv_sec = 120;
457 FD_SET(fileno(stdin), &fds_read);
465 /* there's always a socket to wait for */
466 FD_SET(sockfd, &fds_read);
470 case PASSIVE_CONNECT:
473 if(CURL_SOCKET_BAD == sockfd) {
474 /* eeek, we are supposedly connected and then this cannot be -1 ! */
475 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
476 maxfd = 0; /* stdin */
479 /* there's always a socket to wait for */
480 FD_SET(sockfd, &fds_read);
488 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
489 if(CURL_SOCKET_BAD != sockfd) {
490 FD_SET(sockfd, &fds_read);
494 logmsg("No socket to read on");
499 case ACTIVE_DISCONNECT:
501 logmsg("disconnected, no socket to read on");
503 sockfd = CURL_SOCKET_BAD;
506 } /* switch(*mode) */
511 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
513 if(got_exit_signal) {
514 logmsg("signalled to die, exiting...");
518 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
521 logmsg("select() failed with error: (%d) %s",
522 error, strerror(error));
531 if(FD_ISSET(fileno(stdin), &fds_read)) {
532 /* read from stdin, commands/data to be dealt with and possibly passed on
537 4 letter command + LF [mandatory]
539 4-digit hexadecimal data length + LF [if the command takes data]
540 data [the data being as long as set above]
544 DATA - plain pass-thru data
547 if(!read_stdin(buffer, 5))
550 logmsg("Received %c%c%c%c (on stdin)",
551 buffer[0], buffer[1], buffer[2], buffer[3] );
553 if(!memcmp("PING", buffer, 4)) {
554 /* send reply on stdout, just proving we are alive */
555 if(!write_stdout("PONG\n", 5))
559 else if(!memcmp("PORT", buffer, 4)) {
560 /* Question asking us what PORT number we are listening to.
561 Replies to PORT with "IPv[num]/[port]" */
562 sprintf((char *)buffer, "%s/%d\n", ipv_inuse, (int)port);
563 buffer_len = (ssize_t)strlen((char *)buffer);
564 snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
565 if(!write_stdout(data, 10))
567 if(!write_stdout(buffer, buffer_len))
570 else if(!memcmp("QUIT", buffer, 4)) {
575 else if(!memcmp("DATA", buffer, 4)) {
576 /* data IN => data OUT */
578 if(!read_stdin(buffer, 5))
583 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
584 if (buffer_len > (ssize_t)sizeof(buffer)) {
585 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
586 "(%zd bytes)", sizeof(buffer), buffer_len);
589 logmsg("> %zd bytes data, server => client", buffer_len);
591 if(!read_stdin(buffer, buffer_len))
594 lograw(buffer, buffer_len);
596 if(*mode == PASSIVE_LISTEN) {
597 logmsg("*** We are disconnected!");
598 if(!write_stdout("DISC\n", 5))
602 /* send away on the socket */
603 bytes_written = swrite(sockfd, buffer, buffer_len);
604 if(bytes_written != buffer_len) {
605 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
606 buffer_len, bytes_written);
610 else if(!memcmp("DISC", buffer, 4)) {
612 if(!write_stdout("DISC\n", 5))
614 if(sockfd != CURL_SOCKET_BAD) {
615 logmsg("====> Client forcibly disconnected");
617 *sockfdp = CURL_SOCKET_BAD;
618 if(*mode == PASSIVE_CONNECT)
619 *mode = PASSIVE_LISTEN;
621 *mode = ACTIVE_DISCONNECT;
624 logmsg("attempt to close already dead connection");
630 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
632 if(*mode == PASSIVE_LISTEN) {
633 /* there's no stream set up yet, this is an indication that there's a
634 client connecting. */
635 sockfd = accept(sockfd, NULL, NULL);
636 if(CURL_SOCKET_BAD == sockfd)
637 logmsg("accept() failed");
639 logmsg("====> Client connect");
640 if(!write_stdout("CNCT\n", 5))
642 *sockfdp = sockfd; /* store the new socket */
643 *mode = PASSIVE_CONNECT; /* we have connected */
648 /* read from socket, pass on data to stdout */
649 nread_socket = sread(sockfd, buffer, sizeof(buffer));
651 if(nread_socket <= 0) {
652 logmsg("====> Client disconnect");
653 if(!write_stdout("DISC\n", 5))
656 *sockfdp = CURL_SOCKET_BAD;
657 if(*mode == PASSIVE_CONNECT)
658 *mode = PASSIVE_LISTEN;
660 *mode = ACTIVE_DISCONNECT;
664 snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
665 if(!write_stdout(data, 10))
667 if(!write_stdout(buffer, nread_socket))
670 logmsg("< %zd bytes data, client => server", nread_socket);
671 lograw(buffer, nread_socket);
677 static curl_socket_t sockdaemon(curl_socket_t sock,
678 unsigned short *listenport)
680 /* passive daemon style */
681 struct sockaddr_in me;
683 struct sockaddr_in6 me6;
684 #endif /* ENABLE_IPV6 */
695 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
696 (void *)&flag, sizeof(flag));
702 /* should not happen */
704 logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
706 return CURL_SOCKET_BAD;
708 if(got_exit_signal) {
709 logmsg("signalled to die, exiting...");
711 return CURL_SOCKET_BAD;
714 delay *= 2; /* double the sleep for next attempt */
717 } while(rc && maxretr--);
720 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
721 attempt, totdelay, error, strerror(error));
722 logmsg("Continuing anyway...");
728 memset(&me, 0, sizeof(me));
729 me.sin_family = AF_INET;
730 me.sin_addr.s_addr = INADDR_ANY;
731 me.sin_port = htons(*listenport);
732 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
736 memset(&me6, 0, sizeof(me6));
737 me6.sin6_family = AF_INET6;
738 me6.sin6_addr = in6addr_any;
739 me6.sin6_port = htons(*listenport);
740 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
742 #endif /* ENABLE_IPV6 */
745 logmsg("Error binding socket: (%d) %s", error, strerror(error));
747 return CURL_SOCKET_BAD;
751 /* The system picked a port number, now figure out which port we actually
753 /* we succeeded to bind */
754 struct sockaddr_in add;
755 socklen_t socksize = sizeof(add);
757 if(getsockname(sock, (struct sockaddr *) &add,
760 logmsg("getsockname() failed with error: (%d) %s",
761 error, strerror(error));
763 return CURL_SOCKET_BAD;
765 *listenport = ntohs(add.sin_port);
768 /* start accepting connections */
769 rc = listen(sock, 5);
772 logmsg("listen() failed with error: (%d) %s",
773 error, strerror(error));
775 return CURL_SOCKET_BAD;
782 int main(int argc, char *argv[])
784 struct sockaddr_in me;
786 struct sockaddr_in6 me6;
787 #endif /* ENABLE_IPV6 */
788 curl_socket_t sock = CURL_SOCKET_BAD;
789 curl_socket_t msgsock = CURL_SOCKET_BAD;
790 int wrotepidfile = 0;
791 char *pidname= (char *)".sockfilt.pid";
795 enum sockmode mode = PASSIVE_LISTEN; /* default */
796 const char *addr = NULL;
799 if(!strcmp("--version", argv[arg])) {
800 printf("sockfilt IPv4%s\n",
809 else if(!strcmp("--verbose", argv[arg])) {
813 else if(!strcmp("--pidfile", argv[arg])) {
816 pidname = argv[arg++];
818 else if(!strcmp("--logfile", argv[arg])) {
821 serverlogfile = argv[arg++];
823 else if(!strcmp("--ipv6", argv[arg])) {
830 else if(!strcmp("--ipv4", argv[arg])) {
831 /* for completeness, we support this option as well */
838 else if(!strcmp("--port", argv[arg])) {
841 port = (unsigned short)atoi(argv[arg]);
845 else if(!strcmp("--connect", argv[arg])) {
846 /* Asked to actively connect to the specified local port instead of
847 doing a passive server-style listening. */
850 connectport = (unsigned short)atoi(argv[arg]);
854 else if(!strcmp("--addr", argv[arg])) {
855 /* Set an IP address to use with --connect; otherwise use localhost */
863 puts("Usage: sockfilt [option]\n"
866 " --logfile [file]\n"
867 " --pidfile [file]\n"
871 " --connect [port]\n"
872 " --addr [address]");
879 atexit(win32_cleanup);
882 install_signal_handlers();
887 sock = socket(AF_INET, SOCK_STREAM, 0);
890 sock = socket(AF_INET6, SOCK_STREAM, 0);
893 if(CURL_SOCKET_BAD == sock) {
895 logmsg("Error creating socket: (%d) %s",
896 error, strerror(error));
897 goto sockfilt_cleanup;
901 /* Active mode, we should connect to the given port number */
906 memset(&me, 0, sizeof(me));
907 me.sin_family = AF_INET;
908 me.sin_port = htons(connectport);
909 me.sin_addr.s_addr = INADDR_ANY;
912 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
914 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
918 memset(&me6, 0, sizeof(me6));
919 me6.sin6_family = AF_INET6;
920 me6.sin6_port = htons(connectport);
923 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
925 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
927 #endif /* ENABLE_IPV6 */
930 logmsg("Error connecting to port %hu: (%d) %s",
931 connectport, error, strerror(error));
932 goto sockfilt_cleanup;
934 logmsg("====> Client connect");
935 msgsock = sock; /* use this as stream */
938 /* passive daemon style */
939 sock = sockdaemon(sock, &port);
940 if(CURL_SOCKET_BAD == sock)
941 goto sockfilt_cleanup;
942 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
945 logmsg("Running %s version", ipv_inuse);
948 logmsg("Connected to port %hu", connectport);
950 logmsg("Listening on port %hu", port);
952 wrotepidfile = write_pidfile(pidname);
954 goto sockfilt_cleanup;
956 while(juggle(&msgsock, sock, &mode));
960 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
963 if(sock != CURL_SOCKET_BAD)
969 restore_signal_handlers();
971 if(got_exit_signal) {
972 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
974 * To properly set the return status of the process we
975 * must raise the same signal SIGINT or SIGTERM that we
976 * caught and let the old handler take care of it.
981 logmsg("============> sockfilt quits");