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)
49 #include "setup.h" /* portability help from the lib directory */
57 #ifdef HAVE_SYS_SOCKET_H
58 #include <sys/socket.h>
60 #ifdef HAVE_NETINET_IN_H
61 #include <netinet/in.h>
63 #ifdef _XOPEN_SOURCE_EXTENDED
64 /* This define is "almost" required to build on HPUX 11 */
65 #include <arpa/inet.h>
71 #define ENABLE_CURLX_PRINTF
72 /* make the curlx header define all printf() functions to use the curlx_*
74 #include "curlx.h" /* from the private lib dir */
76 #include "inet_pton.h"
79 /* include memdebug.h last */
82 #define DEFAULT_PORT 8999
84 #ifndef DEFAULT_LOGFILE
85 #define DEFAULT_LOGFILE "log/sockfilt.log"
89 static volatile int sigpipe; /* Why? It's not used */
92 const char *serverlogfile = (char *)DEFAULT_LOGFILE;
95 bool use_ipv6 = FALSE;
96 unsigned short port = DEFAULT_PORT;
97 unsigned short connectport = 0; /* if non-zero, we activate this mode */
100 PASSIVE_LISTEN, /* as a server waiting for connections */
101 PASSIVE_CONNECT, /* as a server, connected to a client */
102 ACTIVE, /* as a client, connected to a server */
103 ACTIVE_DISCONNECT /* as a client, disconnected from server */
107 * fullread is a wrapper around the read() function. This will repeat the call
108 * to read() until it actually has read the complete number of bytes indicated
109 * in nbytes or it fails with a condition that cannot be handled with a simple
110 * retry of the read call.
113 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
120 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
124 if((error == EINTR) || (error == EAGAIN))
126 logmsg("unrecoverable read() failure: %s", strerror(error));
131 logmsg("got 0 reading from stdin");
137 } while((size_t)nread < nbytes);
140 logmsg("read %ld bytes", (long)nread);
146 * fullwrite is a wrapper around the write() function. This will repeat the
147 * call to write() until it actually has written the complete number of bytes
148 * indicated in nbytes or it fails with a condition that cannot be handled
149 * with a simple retry of the write call.
152 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
159 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
163 if((error == EINTR) || (error == EAGAIN))
165 logmsg("unrecoverable write() failure: %s", strerror(error));
170 logmsg("put 0 writing to stdout");
176 } while((size_t)nwrite < nbytes);
179 logmsg("wrote %ld bytes", (long)nwrite);
185 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
186 * blocking function that will only return TRUE when nbytes have actually been
187 * read or FALSE when an unrecoverable error has been detected. Failure of this
188 * function is an indication that the sockfilt process should terminate.
191 static bool read_stdin(void *buffer, size_t nbytes)
193 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
194 if(nread != (ssize_t)nbytes) {
195 logmsg("exiting...");
202 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
203 * blocking function that will only return TRUE when nbytes have actually been
204 * written or FALSE when an unrecoverable error has been detected. Failure of
205 * this function is an indication that the sockfilt process should terminate.
208 static bool write_stdout(const void *buffer, size_t nbytes)
210 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
211 if(nwrite != (ssize_t)nbytes) {
212 logmsg("exiting...");
218 static void lograw(unsigned char *buffer, ssize_t len)
222 unsigned char *ptr = buffer;
226 for(i=0; i<len; i++) {
229 sprintf(optr, "\\n");
234 sprintf(optr, "\\r");
239 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
246 logmsg("'%s'", data);
252 logmsg("'%s'", data);
256 static void sigpipe_handler(int sig)
258 (void)sig; /* prevent warning */
264 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
266 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
269 static bool juggle(curl_socket_t *sockfdp,
270 curl_socket_t listenfd,
273 struct timeval timeout;
277 curl_socket_t sockfd;
280 ssize_t nread_socket;
281 ssize_t bytes_written;
284 /* 'buffer' is this excessively large only to be able to support things like
285 test 1003 which tests exceedingly large server response lines */
286 unsigned char buffer[17010];
290 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
291 parent ftpserver process has died without killing its sockfilt children */
293 logmsg("process becomes orphan, exiting");
298 timeout.tv_sec = 120;
305 FD_SET(fileno(stdin), &fds_read);
313 /* there's always a socket to wait for */
314 FD_SET(sockfd, &fds_read);
318 case PASSIVE_CONNECT:
321 if(CURL_SOCKET_BAD == sockfd) {
322 /* eeek, we are supposedly connected and then this cannot be -1 ! */
323 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
324 maxfd = 0; /* stdin */
327 /* there's always a socket to wait for */
328 FD_SET(sockfd, &fds_read);
336 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
337 if(CURL_SOCKET_BAD != sockfd) {
338 FD_SET(sockfd, &fds_read);
342 logmsg("No socket to read on");
347 case ACTIVE_DISCONNECT:
349 logmsg("disconnected, no socket to read on");
351 sockfd = CURL_SOCKET_BAD;
354 } /* switch(*mode) */
359 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
361 } while((rc == -1) && (SOCKERRNO == EINTR));
371 if(FD_ISSET(fileno(stdin), &fds_read)) {
372 /* read from stdin, commands/data to be dealt with and possibly passed on
377 4 letter command + LF [mandatory]
379 4-digit hexadecimal data length + LF [if the command takes data]
380 data [the data being as long as set above]
384 DATA - plain pass-thru data
387 if(!read_stdin(buffer, 5))
390 logmsg("Received %c%c%c%c (on stdin)",
391 buffer[0], buffer[1], buffer[2], buffer[3] );
393 if(!memcmp("PING", buffer, 4)) {
394 /* send reply on stdout, just proving we are alive */
395 if(!write_stdout("PONG\n", 5))
399 else if(!memcmp("PORT", buffer, 4)) {
400 /* Question asking us what PORT number we are listening to.
401 Replies to PORT with "IPv[num]/[port]" */
402 sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
403 buffer_len = (ssize_t)strlen((char *)buffer);
404 snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
405 if(!write_stdout(data, 10))
407 if(!write_stdout(buffer, buffer_len))
410 else if(!memcmp("QUIT", buffer, 4)) {
415 else if(!memcmp("DATA", buffer, 4)) {
416 /* data IN => data OUT */
418 if(!read_stdin(buffer, 5))
423 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
424 if (buffer_len > (ssize_t)sizeof(buffer)) {
425 logmsg("ERROR: Buffer size (%ld bytes) too small for data size "
426 "(%ld bytes)", (long)sizeof(buffer), (long)buffer_len);
429 logmsg("> %d bytes data, server => client", buffer_len);
431 if(!read_stdin(buffer, buffer_len))
434 lograw(buffer, buffer_len);
436 if(*mode == PASSIVE_LISTEN) {
437 logmsg("*** We are disconnected!");
438 if(!write_stdout("DISC\n", 5))
442 /* send away on the socket */
443 bytes_written = swrite(sockfd, buffer, buffer_len);
444 if(bytes_written != buffer_len) {
445 logmsg("Not all data was sent. Bytes to send: %d sent: %d",
446 buffer_len, bytes_written);
450 else if(!memcmp("DISC", buffer, 4)) {
452 if(!write_stdout("DISC\n", 5))
454 if(sockfd != CURL_SOCKET_BAD) {
455 logmsg("====> Client forcibly disconnected");
457 *sockfdp = CURL_SOCKET_BAD;
458 if(*mode == PASSIVE_CONNECT)
459 *mode = PASSIVE_LISTEN;
461 *mode = ACTIVE_DISCONNECT;
464 logmsg("attempt to close already dead connection");
470 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
472 if(*mode == PASSIVE_LISTEN) {
473 /* there's no stream set up yet, this is an indication that there's a
474 client connecting. */
475 sockfd = accept(sockfd, NULL, NULL);
476 if(CURL_SOCKET_BAD == sockfd)
477 logmsg("accept() failed");
479 logmsg("====> Client connect");
480 if(!write_stdout("CNCT\n", 5))
482 *sockfdp = sockfd; /* store the new socket */
483 *mode = PASSIVE_CONNECT; /* we have connected */
488 /* read from socket, pass on data to stdout */
489 nread_socket = sread(sockfd, buffer, sizeof(buffer));
491 if(nread_socket <= 0) {
492 logmsg("====> Client disconnect");
493 if(!write_stdout("DISC\n", 5))
496 *sockfdp = CURL_SOCKET_BAD;
497 if(*mode == PASSIVE_CONNECT)
498 *mode = PASSIVE_LISTEN;
500 *mode = ACTIVE_DISCONNECT;
504 snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
505 if(!write_stdout(data, 10))
507 if(!write_stdout(buffer, nread_socket))
510 logmsg("< %d bytes data, client => server", nread_socket);
511 lograw(buffer, nread_socket);
517 static curl_socket_t sockdaemon(curl_socket_t sock,
518 unsigned short *listenport)
520 /* passive daemon style */
521 struct sockaddr_in me;
523 struct sockaddr_in6 me6;
524 #endif /* ENABLE_IPV6 */
535 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
536 (void *)&flag, sizeof(flag));
542 /* should not happen */
544 logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
546 return CURL_SOCKET_BAD;
549 delay *= 2; /* double the sleep for next attempt */
552 } while(rc && maxretr--);
555 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
556 attempt, totdelay, error, strerror(error));
557 logmsg("Continuing anyway...");
563 memset(&me, 0, sizeof(me));
564 me.sin_family = AF_INET;
565 me.sin_addr.s_addr = INADDR_ANY;
566 me.sin_port = htons(*listenport);
567 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
571 memset(&me6, 0, sizeof(me6));
572 me6.sin6_family = AF_INET6;
573 me6.sin6_addr = in6addr_any;
574 me6.sin6_port = htons(*listenport);
575 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
577 #endif /* ENABLE_IPV6 */
580 logmsg("Error binding socket: (%d) %s", error, strerror(error));
582 return CURL_SOCKET_BAD;
586 /* The system picked a port number, now figure out which port we actually
588 /* we succeeded to bind */
589 struct sockaddr_in add;
590 socklen_t socksize = sizeof(add);
592 if(getsockname(sock, (struct sockaddr *) &add,
595 logmsg("getsockname() failed with error: (%d) %s",
596 error, strerror(error));
598 return CURL_SOCKET_BAD;
600 *listenport = ntohs(add.sin_port);
603 /* start accepting connections */
604 rc = listen(sock, 5);
607 logmsg("listen() failed with error: (%d) %s",
608 error, strerror(error));
610 return CURL_SOCKET_BAD;
617 int main(int argc, char *argv[])
619 struct sockaddr_in me;
621 struct sockaddr_in6 me6;
622 #endif /* ENABLE_IPV6 */
624 curl_socket_t msgsock;
625 char *pidname= (char *)".sockfilt.pid";
629 enum sockmode mode = PASSIVE_LISTEN; /* default */
630 const char *addr = NULL;
633 if(!strcmp("--version", argv[arg])) {
634 printf("sockfilt IPv4%s\n",
643 else if(!strcmp("--verbose", argv[arg])) {
647 else if(!strcmp("--pidfile", argv[arg])) {
650 pidname = argv[arg++];
652 else if(!strcmp("--logfile", argv[arg])) {
655 serverlogfile = argv[arg++];
657 else if(!strcmp("--ipv6", argv[arg])) {
663 else if(!strcmp("--ipv4", argv[arg])) {
664 /* for completeness, we support this option as well */
668 else if(!strcmp("--port", argv[arg])) {
671 port = (unsigned short)atoi(argv[arg]);
675 else if(!strcmp("--connect", argv[arg])) {
676 /* Asked to actively connect to the specified local port instead of
677 doing a passive server-style listening. */
680 connectport = (unsigned short)atoi(argv[arg]);
684 else if(!strcmp("--addr", argv[arg])) {
685 /* Set an IP address to use with --connect; otherwise use localhost */
693 puts("Usage: sockfilt [option]\n"
696 " --logfile [file]\n"
697 " --pidfile [file]\n"
701 " --connect [port]\n"
702 " --addr [address]");
709 atexit(win32_cleanup);
714 signal(SIGPIPE, sigpipe_handler);
716 #ifdef HAVE_SIGINTERRUPT
717 siginterrupt(SIGPIPE, 1);
725 sock = socket(AF_INET, SOCK_STREAM, 0);
728 sock = socket(AF_INET6, SOCK_STREAM, 0);
731 if(CURL_SOCKET_BAD == sock) {
733 logmsg("Error creating socket: (%d) %s",
734 error, strerror(error));
739 /* Active mode, we should connect to the given port number */
744 memset(&me, 0, sizeof(me));
745 me.sin_family = AF_INET;
746 me.sin_port = htons(connectport);
747 me.sin_addr.s_addr = INADDR_ANY;
750 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
752 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
756 memset(&me6, 0, sizeof(me6));
757 me6.sin6_family = AF_INET6;
758 me6.sin6_port = htons(connectport);
761 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
763 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
765 #endif /* ENABLE_IPV6 */
768 logmsg("Error connecting to port %d: (%d) %s",
769 port, error, strerror(error));
773 logmsg("====> Client connect");
774 msgsock = sock; /* use this as stream */
777 /* passive daemon style */
778 sock = sockdaemon(sock, &port);
779 if(CURL_SOCKET_BAD == sock)
781 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
784 logmsg("Running IPv%d version",
788 logmsg("Connected to port %d", connectport);
790 logmsg("Listening on port %d", port);
792 if(!write_pidfile(pidname)) {
797 while(juggle(&msgsock, sock, &mode));
802 logmsg("sockfilt exits");