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;
285 /* 'buffer' is this excessively large only to be able to support things like
286 test 1003 which tests exceedingly large server response lines */
287 unsigned char buffer[17010];
291 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
292 parent ftpserver process has died without killing its sockfilt children */
294 logmsg("process becomes orphan, exiting");
299 timeout.tv_sec = 120;
306 FD_SET(fileno(stdin), &fds_read);
314 /* there's always a socket to wait for */
315 FD_SET(sockfd, &fds_read);
319 case PASSIVE_CONNECT:
322 if(CURL_SOCKET_BAD == sockfd) {
323 /* eeek, we are supposedly connected and then this cannot be -1 ! */
324 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
325 maxfd = 0; /* stdin */
328 /* there's always a socket to wait for */
329 FD_SET(sockfd, &fds_read);
337 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
338 if(CURL_SOCKET_BAD != sockfd) {
339 FD_SET(sockfd, &fds_read);
343 logmsg("No socket to read on");
348 case ACTIVE_DISCONNECT:
350 logmsg("disconnected, no socket to read on");
352 sockfd = CURL_SOCKET_BAD;
355 } /* switch(*mode) */
360 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
362 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
365 logmsg("select() failed with error: (%d) %s",
366 error, strerror(error));
375 if(FD_ISSET(fileno(stdin), &fds_read)) {
376 /* read from stdin, commands/data to be dealt with and possibly passed on
381 4 letter command + LF [mandatory]
383 4-digit hexadecimal data length + LF [if the command takes data]
384 data [the data being as long as set above]
388 DATA - plain pass-thru data
391 if(!read_stdin(buffer, 5))
394 logmsg("Received %c%c%c%c (on stdin)",
395 buffer[0], buffer[1], buffer[2], buffer[3] );
397 if(!memcmp("PING", buffer, 4)) {
398 /* send reply on stdout, just proving we are alive */
399 if(!write_stdout("PONG\n", 5))
403 else if(!memcmp("PORT", buffer, 4)) {
404 /* Question asking us what PORT number we are listening to.
405 Replies to PORT with "IPv[num]/[port]" */
406 sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
407 buffer_len = (ssize_t)strlen((char *)buffer);
408 snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
409 if(!write_stdout(data, 10))
411 if(!write_stdout(buffer, buffer_len))
414 else if(!memcmp("QUIT", buffer, 4)) {
419 else if(!memcmp("DATA", buffer, 4)) {
420 /* data IN => data OUT */
422 if(!read_stdin(buffer, 5))
427 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
428 if (buffer_len > (ssize_t)sizeof(buffer)) {
429 logmsg("ERROR: Buffer size (%ld bytes) too small for data size "
430 "(%ld bytes)", (long)sizeof(buffer), (long)buffer_len);
433 logmsg("> %d bytes data, server => client", buffer_len);
435 if(!read_stdin(buffer, buffer_len))
438 lograw(buffer, buffer_len);
440 if(*mode == PASSIVE_LISTEN) {
441 logmsg("*** We are disconnected!");
442 if(!write_stdout("DISC\n", 5))
446 /* send away on the socket */
447 bytes_written = swrite(sockfd, buffer, buffer_len);
448 if(bytes_written != buffer_len) {
449 logmsg("Not all data was sent. Bytes to send: %d sent: %d",
450 buffer_len, bytes_written);
454 else if(!memcmp("DISC", buffer, 4)) {
456 if(!write_stdout("DISC\n", 5))
458 if(sockfd != CURL_SOCKET_BAD) {
459 logmsg("====> Client forcibly disconnected");
461 *sockfdp = CURL_SOCKET_BAD;
462 if(*mode == PASSIVE_CONNECT)
463 *mode = PASSIVE_LISTEN;
465 *mode = ACTIVE_DISCONNECT;
468 logmsg("attempt to close already dead connection");
474 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
476 if(*mode == PASSIVE_LISTEN) {
477 /* there's no stream set up yet, this is an indication that there's a
478 client connecting. */
479 sockfd = accept(sockfd, NULL, NULL);
480 if(CURL_SOCKET_BAD == sockfd)
481 logmsg("accept() failed");
483 logmsg("====> Client connect");
484 if(!write_stdout("CNCT\n", 5))
486 *sockfdp = sockfd; /* store the new socket */
487 *mode = PASSIVE_CONNECT; /* we have connected */
492 /* read from socket, pass on data to stdout */
493 nread_socket = sread(sockfd, buffer, sizeof(buffer));
495 if(nread_socket <= 0) {
496 logmsg("====> Client disconnect");
497 if(!write_stdout("DISC\n", 5))
500 *sockfdp = CURL_SOCKET_BAD;
501 if(*mode == PASSIVE_CONNECT)
502 *mode = PASSIVE_LISTEN;
504 *mode = ACTIVE_DISCONNECT;
508 snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
509 if(!write_stdout(data, 10))
511 if(!write_stdout(buffer, nread_socket))
514 logmsg("< %d bytes data, client => server", nread_socket);
515 lograw(buffer, nread_socket);
521 static curl_socket_t sockdaemon(curl_socket_t sock,
522 unsigned short *listenport)
524 /* passive daemon style */
525 struct sockaddr_in me;
527 struct sockaddr_in6 me6;
528 #endif /* ENABLE_IPV6 */
539 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
540 (void *)&flag, sizeof(flag));
546 /* should not happen */
548 logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
550 return CURL_SOCKET_BAD;
553 delay *= 2; /* double the sleep for next attempt */
556 } while(rc && maxretr--);
559 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
560 attempt, totdelay, error, strerror(error));
561 logmsg("Continuing anyway...");
567 memset(&me, 0, sizeof(me));
568 me.sin_family = AF_INET;
569 me.sin_addr.s_addr = INADDR_ANY;
570 me.sin_port = htons(*listenport);
571 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
575 memset(&me6, 0, sizeof(me6));
576 me6.sin6_family = AF_INET6;
577 me6.sin6_addr = in6addr_any;
578 me6.sin6_port = htons(*listenport);
579 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
581 #endif /* ENABLE_IPV6 */
584 logmsg("Error binding socket: (%d) %s", error, strerror(error));
586 return CURL_SOCKET_BAD;
590 /* The system picked a port number, now figure out which port we actually
592 /* we succeeded to bind */
593 struct sockaddr_in add;
594 socklen_t socksize = sizeof(add);
596 if(getsockname(sock, (struct sockaddr *) &add,
599 logmsg("getsockname() failed with error: (%d) %s",
600 error, strerror(error));
602 return CURL_SOCKET_BAD;
604 *listenport = ntohs(add.sin_port);
607 /* start accepting connections */
608 rc = listen(sock, 5);
611 logmsg("listen() failed with error: (%d) %s",
612 error, strerror(error));
614 return CURL_SOCKET_BAD;
621 int main(int argc, char *argv[])
623 struct sockaddr_in me;
625 struct sockaddr_in6 me6;
626 #endif /* ENABLE_IPV6 */
627 curl_socket_t sock = CURL_SOCKET_BAD;
628 curl_socket_t msgsock = CURL_SOCKET_BAD;
629 int wrotepidfile = 0;
630 char *pidname= (char *)".sockfilt.pid";
634 enum sockmode mode = PASSIVE_LISTEN; /* default */
635 const char *addr = NULL;
638 if(!strcmp("--version", argv[arg])) {
639 printf("sockfilt IPv4%s\n",
648 else if(!strcmp("--verbose", argv[arg])) {
652 else if(!strcmp("--pidfile", argv[arg])) {
655 pidname = argv[arg++];
657 else if(!strcmp("--logfile", argv[arg])) {
660 serverlogfile = argv[arg++];
662 else if(!strcmp("--ipv6", argv[arg])) {
668 else if(!strcmp("--ipv4", argv[arg])) {
669 /* for completeness, we support this option as well */
673 else if(!strcmp("--port", argv[arg])) {
676 port = (unsigned short)atoi(argv[arg]);
680 else if(!strcmp("--connect", argv[arg])) {
681 /* Asked to actively connect to the specified local port instead of
682 doing a passive server-style listening. */
685 connectport = (unsigned short)atoi(argv[arg]);
689 else if(!strcmp("--addr", argv[arg])) {
690 /* Set an IP address to use with --connect; otherwise use localhost */
698 puts("Usage: sockfilt [option]\n"
701 " --logfile [file]\n"
702 " --pidfile [file]\n"
706 " --connect [port]\n"
707 " --addr [address]");
714 atexit(win32_cleanup);
719 signal(SIGPIPE, sigpipe_handler);
721 #ifdef HAVE_SIGINTERRUPT
722 siginterrupt(SIGPIPE, 1);
730 sock = socket(AF_INET, SOCK_STREAM, 0);
733 sock = socket(AF_INET6, SOCK_STREAM, 0);
736 if(CURL_SOCKET_BAD == sock) {
738 logmsg("Error creating socket: (%d) %s",
739 error, strerror(error));
740 goto sockfilt_cleanup;
744 /* Active mode, we should connect to the given port number */
749 memset(&me, 0, sizeof(me));
750 me.sin_family = AF_INET;
751 me.sin_port = htons(connectport);
752 me.sin_addr.s_addr = INADDR_ANY;
755 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
757 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
761 memset(&me6, 0, sizeof(me6));
762 me6.sin6_family = AF_INET6;
763 me6.sin6_port = htons(connectport);
766 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
768 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
770 #endif /* ENABLE_IPV6 */
773 logmsg("Error connecting to port %d: (%d) %s",
774 port, error, strerror(error));
775 goto sockfilt_cleanup;
777 logmsg("====> Client connect");
778 msgsock = sock; /* use this as stream */
781 /* passive daemon style */
782 sock = sockdaemon(sock, &port);
783 if(CURL_SOCKET_BAD == sock)
784 goto sockfilt_cleanup;
785 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
788 logmsg("Running IPv%d version",
792 logmsg("Connected to port %d", connectport);
794 logmsg("Listening on port %d", port);
796 wrotepidfile = write_pidfile(pidname);
798 goto sockfilt_cleanup;
800 while(juggle(&msgsock, sock, &mode));
804 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
807 if(sock != CURL_SOCKET_BAD)
813 logmsg("============> sockfilt quits");