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.
21 * $Id: sockfilt.c,v 1.1.1.1 2008-09-23 16:32:06 hoffman Exp $
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
= (char *)DEFAULT_LOGFILE
;
124 bool verbose
= FALSE
;
125 bool use_ipv6
= FALSE
;
126 unsigned short port
= DEFAULT_PORT
;
127 unsigned short connectport
= 0; /* if non-zero, we activate this mode */
130 PASSIVE_LISTEN
, /* as a server waiting for connections */
131 PASSIVE_CONNECT
, /* as a server, connected to a client */
132 ACTIVE
, /* as a client, connected to a server */
133 ACTIVE_DISCONNECT
/* as a client, disconnected from server */
136 /* do-nothing macro replacement for systems which lack siginterrupt() */
138 #ifndef HAVE_SIGINTERRUPT
139 #define siginterrupt(x,y) do {} while(0)
142 /* vars used to keep around previous signal handlers */
144 typedef RETSIGTYPE (*SIGHANDLER_T
)(int);
146 static SIGHANDLER_T old_sighup_handler
= SIG_ERR
;
147 static SIGHANDLER_T old_sigpipe_handler
= SIG_ERR
;
148 static SIGHANDLER_T old_sigalrm_handler
= SIG_ERR
;
149 static SIGHANDLER_T old_sigint_handler
= SIG_ERR
;
150 static SIGHANDLER_T old_sigterm_handler
= SIG_ERR
;
152 /* var which if set indicates that the program should finish execution */
154 SIG_ATOMIC_T got_exit_signal
= 0;
156 /* if next is set indicates the first signal handled in exit_signal_handler */
158 static volatile int exit_signal
= 0;
160 /* signal handler that will be triggered to indicate that the program
161 should finish its execution in a controlled manner as soon as possible.
162 The first time this is called it will set got_exit_signal to one and
163 store in exit_signal the signal that triggered its execution. */
165 static RETSIGTYPE
exit_signal_handler(int signum
)
167 int old_errno
= ERRNO
;
168 if(got_exit_signal
== 0) {
170 exit_signal
= signum
;
172 (void)signal(signum
, exit_signal_handler
);
173 SET_ERRNO(old_errno
);
176 static void install_signal_handlers(void)
179 /* ignore SIGHUP signal */
180 if((old_sighup_handler
= signal(SIGHUP
, SIG_IGN
)) == SIG_ERR
)
181 logmsg("cannot install SIGHUP handler: 5s", strerror(ERRNO
));
184 /* ignore SIGPIPE signal */
185 if((old_sigpipe_handler
= signal(SIGPIPE
, SIG_IGN
)) == SIG_ERR
)
186 logmsg("cannot install SIGPIPE handler: 5s", strerror(ERRNO
));
189 /* ignore SIGALRM signal */
190 if((old_sigalrm_handler
= signal(SIGALRM
, SIG_IGN
)) == SIG_ERR
)
191 logmsg("cannot install SIGALRM handler: 5s", strerror(ERRNO
));
194 /* handle SIGINT signal with our exit_signal_handler */
195 if((old_sigint_handler
= signal(SIGINT
, exit_signal_handler
)) == SIG_ERR
)
196 logmsg("cannot install SIGINT handler: 5s", strerror(ERRNO
));
198 siginterrupt(SIGINT
, 1);
201 /* handle SIGTERM signal with our exit_signal_handler */
202 if((old_sigterm_handler
= signal(SIGTERM
, exit_signal_handler
)) == SIG_ERR
)
203 logmsg("cannot install SIGTERM handler: 5s", strerror(ERRNO
));
205 siginterrupt(SIGTERM
, 1);
209 static void restore_signal_handlers(void)
212 if(SIG_ERR
!= old_sighup_handler
)
213 (void)signal(SIGHUP
, old_sighup_handler
);
216 if(SIG_ERR
!= old_sigpipe_handler
)
217 (void)signal(SIGPIPE
, old_sigpipe_handler
);
220 if(SIG_ERR
!= old_sigalrm_handler
)
221 (void)signal(SIGALRM
, old_sigalrm_handler
);
224 if(SIG_ERR
!= old_sigint_handler
)
225 (void)signal(SIGINT
, old_sigint_handler
);
228 if(SIG_ERR
!= old_sigterm_handler
)
229 (void)signal(SIGTERM
, old_sigterm_handler
);
234 * fullread is a wrapper around the read() function. This will repeat the call
235 * to read() until it actually has read the complete number of bytes indicated
236 * in nbytes or it fails with a condition that cannot be handled with a simple
237 * retry of the read call.
240 static ssize_t
fullread(int filedes
, void *buffer
, size_t nbytes
)
247 rc
= read(filedes
, (unsigned char *)buffer
+ nread
, nbytes
- nread
);
249 if(got_exit_signal
) {
250 logmsg("signalled to die");
256 if((error
== EINTR
) || (error
== EAGAIN
))
258 logmsg("unrecoverable read() failure: %s", strerror(error
));
263 logmsg("got 0 reading from stdin");
269 } while((size_t)nread
< nbytes
);
272 logmsg("read %ld bytes", (long)nread
);
278 * fullwrite is a wrapper around the write() function. This will repeat the
279 * call to write() until it actually has written the complete number of bytes
280 * indicated in nbytes or it fails with a condition that cannot be handled
281 * with a simple retry of the write call.
284 static ssize_t
fullwrite(int filedes
, const void *buffer
, size_t nbytes
)
291 wc
= write(filedes
, (unsigned char *)buffer
+ nwrite
, nbytes
- nwrite
);
293 if(got_exit_signal
) {
294 logmsg("signalled to die");
300 if((error
== EINTR
) || (error
== EAGAIN
))
302 logmsg("unrecoverable write() failure: %s", strerror(error
));
307 logmsg("put 0 writing to stdout");
313 } while((size_t)nwrite
< nbytes
);
316 logmsg("wrote %ld bytes", (long)nwrite
);
322 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
323 * blocking function that will only return TRUE when nbytes have actually been
324 * read or FALSE when an unrecoverable error has been detected. Failure of this
325 * function is an indication that the sockfilt process should terminate.
328 static bool read_stdin(void *buffer
, size_t nbytes
)
330 ssize_t nread
= fullread(fileno(stdin
), buffer
, nbytes
);
331 if(nread
!= (ssize_t
)nbytes
) {
332 logmsg("exiting...");
339 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
340 * blocking function that will only return TRUE when nbytes have actually been
341 * written or FALSE when an unrecoverable error has been detected. Failure of
342 * this function is an indication that the sockfilt process should terminate.
345 static bool write_stdout(const void *buffer
, size_t nbytes
)
347 ssize_t nwrite
= fullwrite(fileno(stdout
), buffer
, nbytes
);
348 if(nwrite
!= (ssize_t
)nbytes
) {
349 logmsg("exiting...");
355 static void lograw(unsigned char *buffer
, ssize_t len
)
359 unsigned char *ptr
= buffer
;
363 for(i
=0; i
<len
; i
++) {
366 sprintf(optr
, "\\n");
371 sprintf(optr
, "\\r");
376 sprintf(optr
, "%c", (ISGRAPH(ptr
[i
]) || ptr
[i
]==0x20) ?ptr
[i
]:'.');
383 logmsg("'%s'", data
);
389 logmsg("'%s'", data
);
393 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
395 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
398 static bool juggle(curl_socket_t
*sockfdp
,
399 curl_socket_t listenfd
,
402 struct timeval timeout
;
406 curl_socket_t sockfd
;
409 ssize_t nread_socket
;
410 ssize_t bytes_written
;
414 /* 'buffer' is this excessively large only to be able to support things like
415 test 1003 which tests exceedingly large server response lines */
416 unsigned char buffer
[17010];
419 if(got_exit_signal
) {
420 logmsg("signalled to die, exiting...");
425 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
426 parent ftpserver process has died without killing its sockfilt children */
428 logmsg("process becomes orphan, exiting");
433 timeout
.tv_sec
= 120;
440 FD_SET(fileno(stdin
), &fds_read
);
448 /* there's always a socket to wait for */
449 FD_SET(sockfd
, &fds_read
);
453 case PASSIVE_CONNECT
:
456 if(CURL_SOCKET_BAD
== sockfd
) {
457 /* eeek, we are supposedly connected and then this cannot be -1 ! */
458 logmsg("socket is -1! on %s:%d", __FILE__
, __LINE__
);
459 maxfd
= 0; /* stdin */
462 /* there's always a socket to wait for */
463 FD_SET(sockfd
, &fds_read
);
471 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
472 if(CURL_SOCKET_BAD
!= sockfd
) {
473 FD_SET(sockfd
, &fds_read
);
477 logmsg("No socket to read on");
482 case ACTIVE_DISCONNECT
:
484 logmsg("disconnected, no socket to read on");
486 sockfd
= CURL_SOCKET_BAD
;
489 } /* switch(*mode) */
494 rc
= select((int)maxfd
+ 1, &fds_read
, &fds_write
, &fds_err
, &timeout
);
496 if(got_exit_signal
) {
497 logmsg("signalled to die, exiting...");
501 } while((rc
== -1) && ((error
= SOCKERRNO
) == EINTR
));
504 logmsg("select() failed with error: (%d) %s",
505 error
, strerror(error
));
514 if(FD_ISSET(fileno(stdin
), &fds_read
)) {
515 /* read from stdin, commands/data to be dealt with and possibly passed on
520 4 letter command + LF [mandatory]
522 4-digit hexadecimal data length + LF [if the command takes data]
523 data [the data being as long as set above]
527 DATA - plain pass-thru data
530 if(!read_stdin(buffer
, 5))
533 logmsg("Received %c%c%c%c (on stdin)",
534 buffer
[0], buffer
[1], buffer
[2], buffer
[3] );
536 if(!memcmp("PING", buffer
, 4)) {
537 /* send reply on stdout, just proving we are alive */
538 if(!write_stdout("PONG\n", 5))
542 else if(!memcmp("PORT", buffer
, 4)) {
543 /* Question asking us what PORT number we are listening to.
544 Replies to PORT with "IPv[num]/[port]" */
545 sprintf((char *)buffer
, "IPv%d/%d\n", use_ipv6
?6:4, (int)port
);
546 buffer_len
= (ssize_t
)strlen((char *)buffer
);
547 snprintf(data
, sizeof(data
), "PORT\n%04x\n", buffer_len
);
548 if(!write_stdout(data
, 10))
550 if(!write_stdout(buffer
, buffer_len
))
553 else if(!memcmp("QUIT", buffer
, 4)) {
558 else if(!memcmp("DATA", buffer
, 4)) {
559 /* data IN => data OUT */
561 if(!read_stdin(buffer
, 5))
566 buffer_len
= (ssize_t
)strtol((char *)buffer
, NULL
, 16);
567 if (buffer_len
> (ssize_t
)sizeof(buffer
)) {
568 logmsg("ERROR: Buffer size (%ld bytes) too small for data size "
569 "(%ld bytes)", (long)sizeof(buffer
), (long)buffer_len
);
572 logmsg("> %d bytes data, server => client", buffer_len
);
574 if(!read_stdin(buffer
, buffer_len
))
577 lograw(buffer
, buffer_len
);
579 if(*mode
== PASSIVE_LISTEN
) {
580 logmsg("*** We are disconnected!");
581 if(!write_stdout("DISC\n", 5))
585 /* send away on the socket */
586 bytes_written
= swrite(sockfd
, buffer
, buffer_len
);
587 if(bytes_written
!= buffer_len
) {
588 logmsg("Not all data was sent. Bytes to send: %d sent: %d",
589 buffer_len
, bytes_written
);
593 else if(!memcmp("DISC", buffer
, 4)) {
595 if(!write_stdout("DISC\n", 5))
597 if(sockfd
!= CURL_SOCKET_BAD
) {
598 logmsg("====> Client forcibly disconnected");
600 *sockfdp
= CURL_SOCKET_BAD
;
601 if(*mode
== PASSIVE_CONNECT
)
602 *mode
= PASSIVE_LISTEN
;
604 *mode
= ACTIVE_DISCONNECT
;
607 logmsg("attempt to close already dead connection");
613 if((sockfd
!= CURL_SOCKET_BAD
) && (FD_ISSET(sockfd
, &fds_read
)) ) {
615 if(*mode
== PASSIVE_LISTEN
) {
616 /* there's no stream set up yet, this is an indication that there's a
617 client connecting. */
618 sockfd
= accept(sockfd
, NULL
, NULL
);
619 if(CURL_SOCKET_BAD
== sockfd
)
620 logmsg("accept() failed");
622 logmsg("====> Client connect");
623 if(!write_stdout("CNCT\n", 5))
625 *sockfdp
= sockfd
; /* store the new socket */
626 *mode
= PASSIVE_CONNECT
; /* we have connected */
631 /* read from socket, pass on data to stdout */
632 nread_socket
= sread(sockfd
, buffer
, sizeof(buffer
));
634 if(nread_socket
<= 0) {
635 logmsg("====> Client disconnect");
636 if(!write_stdout("DISC\n", 5))
639 *sockfdp
= CURL_SOCKET_BAD
;
640 if(*mode
== PASSIVE_CONNECT
)
641 *mode
= PASSIVE_LISTEN
;
643 *mode
= ACTIVE_DISCONNECT
;
647 snprintf(data
, sizeof(data
), "DATA\n%04x\n", nread_socket
);
648 if(!write_stdout(data
, 10))
650 if(!write_stdout(buffer
, nread_socket
))
653 logmsg("< %d bytes data, client => server", nread_socket
);
654 lograw(buffer
, nread_socket
);
660 static curl_socket_t
sockdaemon(curl_socket_t sock
,
661 unsigned short *listenport
)
663 /* passive daemon style */
664 struct sockaddr_in me
;
666 struct sockaddr_in6 me6
;
667 #endif /* ENABLE_IPV6 */
678 rc
= setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
,
679 (void *)&flag
, sizeof(flag
));
685 /* should not happen */
687 logmsg("wait_ms() failed: (%d) %s", error
, strerror(error
));
689 return CURL_SOCKET_BAD
;
691 if(got_exit_signal
) {
692 logmsg("signalled to die, exiting...");
694 return CURL_SOCKET_BAD
;
697 delay
*= 2; /* double the sleep for next attempt */
700 } while(rc
&& maxretr
--);
703 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
704 attempt
, totdelay
, error
, strerror(error
));
705 logmsg("Continuing anyway...");
711 memset(&me
, 0, sizeof(me
));
712 me
.sin_family
= AF_INET
;
713 me
.sin_addr
.s_addr
= INADDR_ANY
;
714 me
.sin_port
= htons(*listenport
);
715 rc
= bind(sock
, (struct sockaddr
*) &me
, sizeof(me
));
719 memset(&me6
, 0, sizeof(me6
));
720 me6
.sin6_family
= AF_INET6
;
721 me6
.sin6_addr
= in6addr_any
;
722 me6
.sin6_port
= htons(*listenport
);
723 rc
= bind(sock
, (struct sockaddr
*) &me6
, sizeof(me6
));
725 #endif /* ENABLE_IPV6 */
728 logmsg("Error binding socket: (%d) %s", error
, strerror(error
));
730 return CURL_SOCKET_BAD
;
734 /* The system picked a port number, now figure out which port we actually
736 /* we succeeded to bind */
737 struct sockaddr_in add
;
738 socklen_t socksize
= sizeof(add
);
740 if(getsockname(sock
, (struct sockaddr
*) &add
,
743 logmsg("getsockname() failed with error: (%d) %s",
744 error
, strerror(error
));
746 return CURL_SOCKET_BAD
;
748 *listenport
= ntohs(add
.sin_port
);
751 /* start accepting connections */
752 rc
= listen(sock
, 5);
755 logmsg("listen() failed with error: (%d) %s",
756 error
, strerror(error
));
758 return CURL_SOCKET_BAD
;
765 int main(int argc
, char *argv
[])
767 struct sockaddr_in me
;
769 struct sockaddr_in6 me6
;
770 #endif /* ENABLE_IPV6 */
771 curl_socket_t sock
= CURL_SOCKET_BAD
;
772 curl_socket_t msgsock
= CURL_SOCKET_BAD
;
773 int wrotepidfile
= 0;
774 char *pidname
= (char *)".sockfilt.pid";
778 enum sockmode mode
= PASSIVE_LISTEN
; /* default */
779 const char *addr
= NULL
;
782 if(!strcmp("--version", argv
[arg
])) {
783 printf("sockfilt IPv4%s\n",
792 else if(!strcmp("--verbose", argv
[arg
])) {
796 else if(!strcmp("--pidfile", argv
[arg
])) {
799 pidname
= argv
[arg
++];
801 else if(!strcmp("--logfile", argv
[arg
])) {
804 serverlogfile
= argv
[arg
++];
806 else if(!strcmp("--ipv6", argv
[arg
])) {
812 else if(!strcmp("--ipv4", argv
[arg
])) {
813 /* for completeness, we support this option as well */
817 else if(!strcmp("--port", argv
[arg
])) {
820 port
= (unsigned short)atoi(argv
[arg
]);
824 else if(!strcmp("--connect", argv
[arg
])) {
825 /* Asked to actively connect to the specified local port instead of
826 doing a passive server-style listening. */
829 connectport
= (unsigned short)atoi(argv
[arg
]);
833 else if(!strcmp("--addr", argv
[arg
])) {
834 /* Set an IP address to use with --connect; otherwise use localhost */
842 puts("Usage: sockfilt [option]\n"
845 " --logfile [file]\n"
846 " --pidfile [file]\n"
850 " --connect [port]\n"
851 " --addr [address]");
858 atexit(win32_cleanup
);
861 install_signal_handlers();
866 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
869 sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
872 if(CURL_SOCKET_BAD
== sock
) {
874 logmsg("Error creating socket: (%d) %s",
875 error
, strerror(error
));
876 goto sockfilt_cleanup
;
880 /* Active mode, we should connect to the given port number */
885 memset(&me
, 0, sizeof(me
));
886 me
.sin_family
= AF_INET
;
887 me
.sin_port
= htons(connectport
);
888 me
.sin_addr
.s_addr
= INADDR_ANY
;
891 Curl_inet_pton(AF_INET
, addr
, &me
.sin_addr
);
893 rc
= connect(sock
, (struct sockaddr
*) &me
, sizeof(me
));
897 memset(&me6
, 0, sizeof(me6
));
898 me6
.sin6_family
= AF_INET6
;
899 me6
.sin6_port
= htons(connectport
);
902 Curl_inet_pton(AF_INET6
, addr
, &me6
.sin6_addr
);
904 rc
= connect(sock
, (struct sockaddr
*) &me6
, sizeof(me6
));
906 #endif /* ENABLE_IPV6 */
909 logmsg("Error connecting to port %d: (%d) %s",
910 connectport
, error
, strerror(error
));
911 goto sockfilt_cleanup
;
913 logmsg("====> Client connect");
914 msgsock
= sock
; /* use this as stream */
917 /* passive daemon style */
918 sock
= sockdaemon(sock
, &port
);
919 if(CURL_SOCKET_BAD
== sock
)
920 goto sockfilt_cleanup
;
921 msgsock
= CURL_SOCKET_BAD
; /* no stream socket yet */
924 logmsg("Running IPv%d version",
928 logmsg("Connected to port %d", connectport
);
930 logmsg("Listening on port %d", port
);
932 wrotepidfile
= write_pidfile(pidname
);
934 goto sockfilt_cleanup
;
936 while(juggle(&msgsock
, sock
, &mode
));
940 if((msgsock
!= sock
) && (msgsock
!= CURL_SOCKET_BAD
))
943 if(sock
!= CURL_SOCKET_BAD
)
949 restore_signal_handlers();
951 if(got_exit_signal
) {
952 logmsg("============> sockfilt exits with signal (%d)", exit_signal
);
954 * To properly set the return status of the process we
955 * must raise the same signal SIGINT or SIGTERM that we
956 * caught and let the old handler take care of it.
961 logmsg("============> sockfilt quits");