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;
456 FD_SET(fileno(stdin), &fds_read);
464 /* there's always a socket to wait for */
465 FD_SET(sockfd, &fds_read);
469 case PASSIVE_CONNECT:
472 if(CURL_SOCKET_BAD == sockfd) {
473 /* eeek, we are supposedly connected and then this cannot be -1 ! */
474 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
475 maxfd = 0; /* stdin */
478 /* there's always a socket to wait for */
479 FD_SET(sockfd, &fds_read);
487 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
488 if(CURL_SOCKET_BAD != sockfd) {
489 FD_SET(sockfd, &fds_read);
493 logmsg("No socket to read on");
498 case ACTIVE_DISCONNECT:
500 logmsg("disconnected, no socket to read on");
502 sockfd = CURL_SOCKET_BAD;
505 } /* switch(*mode) */
510 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
512 if(got_exit_signal) {
513 logmsg("signalled to die, exiting...");
517 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
520 logmsg("select() failed with error: (%d) %s",
521 error, strerror(error));
530 if(FD_ISSET(fileno(stdin), &fds_read)) {
531 /* read from stdin, commands/data to be dealt with and possibly passed on
536 4 letter command + LF [mandatory]
538 4-digit hexadecimal data length + LF [if the command takes data]
539 data [the data being as long as set above]
543 DATA - plain pass-thru data
546 if(!read_stdin(buffer, 5))
549 logmsg("Received %c%c%c%c (on stdin)",
550 buffer[0], buffer[1], buffer[2], buffer[3] );
552 if(!memcmp("PING", buffer, 4)) {
553 /* send reply on stdout, just proving we are alive */
554 if(!write_stdout("PONG\n", 5))
558 else if(!memcmp("PORT", buffer, 4)) {
559 /* Question asking us what PORT number we are listening to.
560 Replies to PORT with "IPv[num]/[port]" */
561 sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
562 buffer_len = (ssize_t)strlen((char *)buffer);
563 snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
564 if(!write_stdout(data, 10))
566 if(!write_stdout(buffer, buffer_len))
569 else if(!memcmp("QUIT", buffer, 4)) {
574 else if(!memcmp("DATA", buffer, 4)) {
575 /* data IN => data OUT */
577 if(!read_stdin(buffer, 5))
582 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
583 if (buffer_len > (ssize_t)sizeof(buffer)) {
584 logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
585 "(%zd bytes)", sizeof(buffer), buffer_len);
588 logmsg("> %zd bytes data, server => client", buffer_len);
590 if(!read_stdin(buffer, buffer_len))
593 lograw(buffer, buffer_len);
595 if(*mode == PASSIVE_LISTEN) {
596 logmsg("*** We are disconnected!");
597 if(!write_stdout("DISC\n", 5))
601 /* send away on the socket */
602 bytes_written = swrite(sockfd, buffer, buffer_len);
603 if(bytes_written != buffer_len) {
604 logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
605 buffer_len, bytes_written);
609 else if(!memcmp("DISC", buffer, 4)) {
611 if(!write_stdout("DISC\n", 5))
613 if(sockfd != CURL_SOCKET_BAD) {
614 logmsg("====> Client forcibly disconnected");
616 *sockfdp = CURL_SOCKET_BAD;
617 if(*mode == PASSIVE_CONNECT)
618 *mode = PASSIVE_LISTEN;
620 *mode = ACTIVE_DISCONNECT;
623 logmsg("attempt to close already dead connection");
629 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
631 if(*mode == PASSIVE_LISTEN) {
632 /* there's no stream set up yet, this is an indication that there's a
633 client connecting. */
634 sockfd = accept(sockfd, NULL, NULL);
635 if(CURL_SOCKET_BAD == sockfd)
636 logmsg("accept() failed");
638 logmsg("====> Client connect");
639 if(!write_stdout("CNCT\n", 5))
641 *sockfdp = sockfd; /* store the new socket */
642 *mode = PASSIVE_CONNECT; /* we have connected */
647 /* read from socket, pass on data to stdout */
648 nread_socket = sread(sockfd, buffer, sizeof(buffer));
650 if(nread_socket <= 0) {
651 logmsg("====> Client disconnect");
652 if(!write_stdout("DISC\n", 5))
655 *sockfdp = CURL_SOCKET_BAD;
656 if(*mode == PASSIVE_CONNECT)
657 *mode = PASSIVE_LISTEN;
659 *mode = ACTIVE_DISCONNECT;
663 snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
664 if(!write_stdout(data, 10))
666 if(!write_stdout(buffer, nread_socket))
669 logmsg("< %zd bytes data, client => server", nread_socket);
670 lograw(buffer, nread_socket);
676 static curl_socket_t sockdaemon(curl_socket_t sock,
677 unsigned short *listenport)
679 /* passive daemon style */
680 struct sockaddr_in me;
682 struct sockaddr_in6 me6;
683 #endif /* ENABLE_IPV6 */
695 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
696 (void *)&flag, sizeof(flag));
699 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
700 error, strerror(error));
704 /* should not happen */
706 logmsg("wait_ms() failed with error: (%d) %s",
707 error, strerror(error));
709 return CURL_SOCKET_BAD;
711 if(got_exit_signal) {
712 logmsg("signalled to die, exiting...");
714 return CURL_SOCKET_BAD;
717 delay *= 2; /* double the sleep for next attempt */
720 } while(rc && maxretr--);
723 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
724 attempt, totdelay, error, strerror(error));
725 logmsg("Continuing anyway...");
728 /* When the specified listener port is zero, it is actually a
729 request to let the system choose a non-zero available port. */
734 memset(&me, 0, sizeof(me));
735 me.sin_family = AF_INET;
736 me.sin_addr.s_addr = INADDR_ANY;
737 me.sin_port = htons(*listenport);
738 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
742 memset(&me6, 0, sizeof(me6));
743 me6.sin6_family = AF_INET6;
744 me6.sin6_addr = in6addr_any;
745 me6.sin6_port = htons(*listenport);
746 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
748 #endif /* ENABLE_IPV6 */
751 logmsg("Error binding socket: (%d) %s", error, strerror(error));
753 return CURL_SOCKET_BAD;
757 /* The system was supposed to choose a port number, figure out which
758 port we actually got and update the listener port value with it. */
759 curl_socklen_t la_size;
760 struct sockaddr *localaddr;
761 struct sockaddr_in localaddr4;
763 struct sockaddr_in6 localaddr6;
766 la_size = sizeof(localaddr4);
767 localaddr = (struct sockaddr *)&localaddr4;
771 la_size = sizeof(localaddr6);
772 localaddr = (struct sockaddr *)&localaddr6;
775 memset(localaddr, 0, (size_t)la_size);
776 if(getsockname(sock, localaddr, &la_size) < 0) {
778 logmsg("getsockname() failed with error: (%d) %s",
779 error, strerror(error));
781 return CURL_SOCKET_BAD;
783 switch (localaddr->sa_family) {
785 *listenport = ntohs(localaddr4.sin_port);
789 *listenport = ntohs(localaddr6.sin6_port);
796 /* Real failure, listener port shall not be zero beyond this point. */
797 logmsg("Successfull getsockname() but unknown listener port.");
799 return CURL_SOCKET_BAD;
803 /* start accepting connections */
804 rc = listen(sock, 5);
807 logmsg("listen() failed with error: (%d) %s",
808 error, strerror(error));
810 return CURL_SOCKET_BAD;
817 int main(int argc, char *argv[])
819 struct sockaddr_in me;
821 struct sockaddr_in6 me6;
822 #endif /* ENABLE_IPV6 */
823 curl_socket_t sock = CURL_SOCKET_BAD;
824 curl_socket_t msgsock = CURL_SOCKET_BAD;
825 int wrotepidfile = 0;
826 char *pidname= (char *)".sockfilt.pid";
830 enum sockmode mode = PASSIVE_LISTEN; /* default */
831 const char *addr = NULL;
834 if(!strcmp("--version", argv[arg])) {
835 printf("sockfilt IPv4%s\n",
844 else if(!strcmp("--verbose", argv[arg])) {
848 else if(!strcmp("--pidfile", argv[arg])) {
851 pidname = argv[arg++];
853 else if(!strcmp("--logfile", argv[arg])) {
856 serverlogfile = argv[arg++];
858 else if(!strcmp("--ipv6", argv[arg])) {
865 else if(!strcmp("--ipv4", argv[arg])) {
866 /* for completeness, we support this option as well */
873 else if(!strcmp("--port", argv[arg])) {
876 port = (unsigned short)atoi(argv[arg]);
880 else if(!strcmp("--connect", argv[arg])) {
881 /* Asked to actively connect to the specified local port instead of
882 doing a passive server-style listening. */
885 connectport = (unsigned short)atoi(argv[arg]);
889 else if(!strcmp("--addr", argv[arg])) {
890 /* Set an IP address to use with --connect; otherwise use localhost */
898 puts("Usage: sockfilt [option]\n"
901 " --logfile [file]\n"
902 " --pidfile [file]\n"
906 " --connect [port]\n"
907 " --addr [address]");
914 atexit(win32_cleanup);
917 install_signal_handlers();
922 sock = socket(AF_INET, SOCK_STREAM, 0);
925 sock = socket(AF_INET6, SOCK_STREAM, 0);
928 if(CURL_SOCKET_BAD == sock) {
930 logmsg("Error creating socket: (%d) %s",
931 error, strerror(error));
932 goto sockfilt_cleanup;
936 /* Active mode, we should connect to the given port number */
941 memset(&me, 0, sizeof(me));
942 me.sin_family = AF_INET;
943 me.sin_port = htons(connectport);
944 me.sin_addr.s_addr = INADDR_ANY;
947 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
949 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
953 memset(&me6, 0, sizeof(me6));
954 me6.sin6_family = AF_INET6;
955 me6.sin6_port = htons(connectport);
958 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
960 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
962 #endif /* ENABLE_IPV6 */
965 logmsg("Error connecting to port %hu: (%d) %s",
966 connectport, error, strerror(error));
967 goto sockfilt_cleanup;
969 logmsg("====> Client connect");
970 msgsock = sock; /* use this as stream */
973 /* passive daemon style */
974 sock = sockdaemon(sock, &port);
975 if(CURL_SOCKET_BAD == sock)
976 goto sockfilt_cleanup;
977 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
980 logmsg("Running %s version", ipv_inuse);
983 logmsg("Connected to port %hu", connectport);
985 logmsg("Listening on port %hu", port);
987 wrotepidfile = write_pidfile(pidname);
989 goto sockfilt_cleanup;
991 while(juggle(&msgsock, sock, &mode));
995 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
998 if(sock != CURL_SOCKET_BAD)
1004 restore_signal_handlers();
1006 if(got_exit_signal) {
1007 logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1009 * To properly set the return status of the process we
1010 * must raise the same signal SIGINT or SIGTERM that we
1011 * caught and let the old handler take care of it.
1016 logmsg("============> sockfilt quits");