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);
149 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
150 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
151 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
152 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
153 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
155 /* var which if set indicates that the program should finish execution */
157 SIG_ATOMIC_T got_exit_signal = 0;
159 /* if next is set indicates the first signal handled in exit_signal_handler */
161 static volatile int exit_signal = 0;
163 /* signal handler that will be triggered to indicate that the program
164 should finish its execution in a controlled manner as soon as possible.
165 The first time this is called it will set got_exit_signal to one and
166 store in exit_signal the signal that triggered its execution. */
168 static RETSIGTYPE exit_signal_handler(int signum)
170 int old_errno = ERRNO;
171 if(got_exit_signal == 0) {
173 exit_signal = signum;
175 (void)signal(signum, exit_signal_handler);
176 SET_ERRNO(old_errno);
179 static void install_signal_handlers(void)
182 /* ignore SIGHUP signal */
183 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
184 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
187 /* ignore SIGPIPE signal */
188 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
189 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
192 /* ignore SIGALRM signal */
193 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
194 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
197 /* handle SIGINT signal with our exit_signal_handler */
198 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
199 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
201 siginterrupt(SIGINT, 1);
204 /* handle SIGTERM signal with our exit_signal_handler */
205 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
206 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
208 siginterrupt(SIGTERM, 1);
212 static void restore_signal_handlers(void)
215 if(SIG_ERR != old_sighup_handler)
216 (void)signal(SIGHUP, old_sighup_handler);
219 if(SIG_ERR != old_sigpipe_handler)
220 (void)signal(SIGPIPE, old_sigpipe_handler);
223 if(SIG_ERR != old_sigalrm_handler)
224 (void)signal(SIGALRM, old_sigalrm_handler);
227 if(SIG_ERR != old_sigint_handler)
228 (void)signal(SIGINT, old_sigint_handler);
231 if(SIG_ERR != old_sigterm_handler)
232 (void)signal(SIGTERM, old_sigterm_handler);
237 * fullread is a wrapper around the read() function. This will repeat the call
238 * to read() until it actually has read the complete number of bytes indicated
239 * in nbytes or it fails with a condition that cannot be handled with a simple
240 * retry of the read call.
243 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
250 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
252 if(got_exit_signal) {
253 logmsg("signalled to die");
259 if((error == EINTR) || (error == EAGAIN))
261 logmsg("unrecoverable read() failure: %s", strerror(error));
266 logmsg("got 0 reading from stdin");
272 } while((size_t)nread < nbytes);
275 logmsg("read %zd bytes", nread);
281 * fullwrite is a wrapper around the write() function. This will repeat the
282 * call to write() until it actually has written the complete number of bytes
283 * indicated in nbytes or it fails with a condition that cannot be handled
284 * with a simple retry of the write call.
287 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
294 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
296 if(got_exit_signal) {
297 logmsg("signalled to die");
303 if((error == EINTR) || (error == EAGAIN))
305 logmsg("unrecoverable write() failure: %s", strerror(error));
310 logmsg("put 0 writing to stdout");
316 } while((size_t)nwrite < nbytes);
319 logmsg("wrote %zd bytes", nwrite);
325 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
326 * blocking function that will only return TRUE when nbytes have actually been
327 * read or FALSE when an unrecoverable error has been detected. Failure of this
328 * function is an indication that the sockfilt process should terminate.
331 static bool read_stdin(void *buffer, size_t nbytes)
333 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
334 if(nread != (ssize_t)nbytes) {
335 logmsg("exiting...");
342 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
343 * blocking function that will only return TRUE when nbytes have actually been
344 * written or FALSE when an unrecoverable error has been detected. Failure of
345 * this function is an indication that the sockfilt process should terminate.
348 static bool write_stdout(const void *buffer, size_t nbytes)
350 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
351 if(nwrite != (ssize_t)nbytes) {
352 logmsg("exiting...");
358 static void lograw(unsigned char *buffer, ssize_t len)
362 unsigned char *ptr = buffer;
366 for(i=0; i<len; i++) {
369 sprintf(optr, "\\n");
374 sprintf(optr, "\\r");
379 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
386 logmsg("'%s'", data);
392 logmsg("'%s'", data);
396 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
398 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
401 static bool juggle(curl_socket_t *sockfdp,
402 curl_socket_t listenfd,
405 struct timeval timeout;
409 curl_socket_t sockfd = CURL_SOCKET_BAD;
410 curl_socket_t maxfd = CURL_SOCKET_BAD;
412 ssize_t nread_socket;
413 ssize_t bytes_written;
417 /* 'buffer' is this excessively large only to be able to support things like
418 test 1003 which tests exceedingly large server response lines */
419 unsigned char buffer[17010];
422 if(got_exit_signal) {
423 logmsg("signalled to die, exiting...");
428 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
429 parent ftpserver process has died without killing its sockfilt children */
431 logmsg("process becomes orphan, exiting");
436 timeout.tv_sec = 120;
443 FD_SET(fileno(stdin), &fds_read);
451 /* there's always a socket to wait for */
452 FD_SET(sockfd, &fds_read);
456 case PASSIVE_CONNECT:
459 if(CURL_SOCKET_BAD == sockfd) {
460 /* eeek, we are supposedly connected and then this cannot be -1 ! */
461 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
462 maxfd = 0; /* stdin */
465 /* there's always a socket to wait for */
466 FD_SET(sockfd, &fds_read);
474 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
475 if(CURL_SOCKET_BAD != sockfd) {
476 FD_SET(sockfd, &fds_read);
480 logmsg("No socket to read on");
485 case ACTIVE_DISCONNECT:
487 logmsg("disconnected, no socket to read on");
489 sockfd = CURL_SOCKET_BAD;
492 } /* switch(*mode) */
497 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
499 if(got_exit_signal) {
500 logmsg("signalled to die, exiting...");
504 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
507 logmsg("select() failed with error: (%d) %s",
508 error, strerror(error));
517 if(FD_ISSET(fileno(stdin), &fds_read)) {
518 /* read from stdin, commands/data to be dealt with and possibly passed on
523 4 letter command + LF [mandatory]
525 4-digit hexadecimal data length + LF [if the command takes data]
526 data [the data being as long as set above]
530 DATA - plain pass-thru data
533 if(!read_stdin(buffer, 5))
536 logmsg("Received %c%c%c%c (on stdin)",
537 buffer[0], buffer[1], buffer[2], buffer[3] );
539 if(!memcmp("PING", buffer, 4)) {
540 /* send reply on stdout, just proving we are alive */
541 if(!write_stdout("PONG\n", 5))
545 else if(!memcmp("PORT", buffer, 4)) {
546 /* Question asking us what PORT number we are listening to.
547 Replies to PORT with "IPv[num]/[port]" */
548 sprintf((char *)buffer, "%s/%d\n", ipv_inuse, (int)port);
549 buffer_len = (ssize_t)strlen((char *)buffer);
550 snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
551 if(!write_stdout(data, 10))
553 if(!write_stdout(buffer, buffer_len))
556 else if(!memcmp("QUIT", buffer, 4)) {
561 else if(!memcmp("DATA", buffer, 4)) {
562 /* data IN => data OUT */
564 if(!read_stdin(buffer, 5))
569 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
570 if (buffer_len > (ssize_t)sizeof(buffer)) {
571 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
572 "(%zd bytes)", sizeof(buffer), buffer_len);
575 logmsg("> %zd bytes data, server => client", buffer_len);
577 if(!read_stdin(buffer, buffer_len))
580 lograw(buffer, buffer_len);
582 if(*mode == PASSIVE_LISTEN) {
583 logmsg("*** We are disconnected!");
584 if(!write_stdout("DISC\n", 5))
588 /* send away on the socket */
589 bytes_written = swrite(sockfd, buffer, buffer_len);
590 if(bytes_written != buffer_len) {
591 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
592 buffer_len, bytes_written);
596 else if(!memcmp("DISC", buffer, 4)) {
598 if(!write_stdout("DISC\n", 5))
600 if(sockfd != CURL_SOCKET_BAD) {
601 logmsg("====> Client forcibly disconnected");
603 *sockfdp = CURL_SOCKET_BAD;
604 if(*mode == PASSIVE_CONNECT)
605 *mode = PASSIVE_LISTEN;
607 *mode = ACTIVE_DISCONNECT;
610 logmsg("attempt to close already dead connection");
616 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
618 if(*mode == PASSIVE_LISTEN) {
619 /* there's no stream set up yet, this is an indication that there's a
620 client connecting. */
621 sockfd = accept(sockfd, NULL, NULL);
622 if(CURL_SOCKET_BAD == sockfd)
623 logmsg("accept() failed");
625 logmsg("====> Client connect");
626 if(!write_stdout("CNCT\n", 5))
628 *sockfdp = sockfd; /* store the new socket */
629 *mode = PASSIVE_CONNECT; /* we have connected */
634 /* read from socket, pass on data to stdout */
635 nread_socket = sread(sockfd, buffer, sizeof(buffer));
637 if(nread_socket <= 0) {
638 logmsg("====> Client disconnect");
639 if(!write_stdout("DISC\n", 5))
642 *sockfdp = CURL_SOCKET_BAD;
643 if(*mode == PASSIVE_CONNECT)
644 *mode = PASSIVE_LISTEN;
646 *mode = ACTIVE_DISCONNECT;
650 snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
651 if(!write_stdout(data, 10))
653 if(!write_stdout(buffer, nread_socket))
656 logmsg("< %zd bytes data, client => server", nread_socket);
657 lograw(buffer, nread_socket);
663 static curl_socket_t sockdaemon(curl_socket_t sock,
664 unsigned short *listenport)
666 /* passive daemon style */
667 struct sockaddr_in me;
669 struct sockaddr_in6 me6;
670 #endif /* ENABLE_IPV6 */
681 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
682 (void *)&flag, sizeof(flag));
688 /* should not happen */
690 logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
692 return CURL_SOCKET_BAD;
694 if(got_exit_signal) {
695 logmsg("signalled to die, exiting...");
697 return CURL_SOCKET_BAD;
700 delay *= 2; /* double the sleep for next attempt */
703 } while(rc && maxretr--);
706 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
707 attempt, totdelay, error, strerror(error));
708 logmsg("Continuing anyway...");
714 memset(&me, 0, sizeof(me));
715 me.sin_family = AF_INET;
716 me.sin_addr.s_addr = INADDR_ANY;
717 me.sin_port = htons(*listenport);
718 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
722 memset(&me6, 0, sizeof(me6));
723 me6.sin6_family = AF_INET6;
724 me6.sin6_addr = in6addr_any;
725 me6.sin6_port = htons(*listenport);
726 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
728 #endif /* ENABLE_IPV6 */
731 logmsg("Error binding socket: (%d) %s", error, strerror(error));
733 return CURL_SOCKET_BAD;
737 /* The system picked a port number, now figure out which port we actually
739 /* we succeeded to bind */
740 struct sockaddr_in add;
741 socklen_t socksize = sizeof(add);
743 if(getsockname(sock, (struct sockaddr *) &add,
746 logmsg("getsockname() failed with error: (%d) %s",
747 error, strerror(error));
749 return CURL_SOCKET_BAD;
751 *listenport = ntohs(add.sin_port);
754 /* start accepting connections */
755 rc = listen(sock, 5);
758 logmsg("listen() failed with error: (%d) %s",
759 error, strerror(error));
761 return CURL_SOCKET_BAD;
768 int main(int argc, char *argv[])
770 struct sockaddr_in me;
772 struct sockaddr_in6 me6;
773 #endif /* ENABLE_IPV6 */
774 curl_socket_t sock = CURL_SOCKET_BAD;
775 curl_socket_t msgsock = CURL_SOCKET_BAD;
776 int wrotepidfile = 0;
777 char *pidname= (char *)".sockfilt.pid";
781 enum sockmode mode = PASSIVE_LISTEN; /* default */
782 const char *addr = NULL;
785 if(!strcmp("--version", argv[arg])) {
786 printf("sockfilt IPv4%s\n",
795 else if(!strcmp("--verbose", argv[arg])) {
799 else if(!strcmp("--pidfile", argv[arg])) {
802 pidname = argv[arg++];
804 else if(!strcmp("--logfile", argv[arg])) {
807 serverlogfile = argv[arg++];
809 else if(!strcmp("--ipv6", argv[arg])) {
816 else if(!strcmp("--ipv4", argv[arg])) {
817 /* for completeness, we support this option as well */
824 else if(!strcmp("--port", argv[arg])) {
827 port = (unsigned short)atoi(argv[arg]);
831 else if(!strcmp("--connect", argv[arg])) {
832 /* Asked to actively connect to the specified local port instead of
833 doing a passive server-style listening. */
836 connectport = (unsigned short)atoi(argv[arg]);
840 else if(!strcmp("--addr", argv[arg])) {
841 /* Set an IP address to use with --connect; otherwise use localhost */
849 puts("Usage: sockfilt [option]\n"
852 " --logfile [file]\n"
853 " --pidfile [file]\n"
857 " --connect [port]\n"
858 " --addr [address]");
865 atexit(win32_cleanup);
868 install_signal_handlers();
873 sock = socket(AF_INET, SOCK_STREAM, 0);
876 sock = socket(AF_INET6, SOCK_STREAM, 0);
879 if(CURL_SOCKET_BAD == sock) {
881 logmsg("Error creating socket: (%d) %s",
882 error, strerror(error));
883 goto sockfilt_cleanup;
887 /* Active mode, we should connect to the given port number */
892 memset(&me, 0, sizeof(me));
893 me.sin_family = AF_INET;
894 me.sin_port = htons(connectport);
895 me.sin_addr.s_addr = INADDR_ANY;
898 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
900 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
904 memset(&me6, 0, sizeof(me6));
905 me6.sin6_family = AF_INET6;
906 me6.sin6_port = htons(connectport);
909 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
911 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
913 #endif /* ENABLE_IPV6 */
916 logmsg("Error connecting to port %hu: (%d) %s",
917 connectport, error, strerror(error));
918 goto sockfilt_cleanup;
920 logmsg("====> Client connect");
921 msgsock = sock; /* use this as stream */
924 /* passive daemon style */
925 sock = sockdaemon(sock, &port);
926 if(CURL_SOCKET_BAD == sock)
927 goto sockfilt_cleanup;
928 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
931 logmsg("Running %s version", ipv_inuse);
934 logmsg("Connected to port %hu", connectport);
936 logmsg("Listening on port %hu", port);
938 wrotepidfile = write_pidfile(pidname);
940 goto sockfilt_cleanup;
942 while(juggle(&msgsock, sock, &mode));
946 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
949 if(sock != CURL_SOCKET_BAD)
955 restore_signal_handlers();
957 if(got_exit_signal) {
958 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
960 * To properly set the return status of the process we
961 * must raise the same signal SIGINT or SIGTERM that we
962 * caught and let the old handler take care of it.
967 logmsg("============> sockfilt quits");