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 */
59 #include <sys/types.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_NETINET_IN_H
68 #include <netinet/in.h>
70 #ifdef _XOPEN_SOURCE_EXTENDED
71 /* This define is "almost" required to build on HPUX 11 */
72 #include <arpa/inet.h>
78 #define ENABLE_CURLX_PRINTF
79 /* make the curlx header define all printf() functions to use the curlx_*
81 #include "curlx.h" /* from the private lib dir */
83 #include "inet_pton.h"
86 /* include memdebug.h last */
89 #define DEFAULT_PORT 8999
91 #ifndef DEFAULT_LOGFILE
92 #define DEFAULT_LOGFILE "log/sockfilt.log"
96 static volatile int sigpipe; /* Why? It's not used */
99 const char *serverlogfile = (char *)DEFAULT_LOGFILE;
101 bool verbose = FALSE;
102 bool use_ipv6 = FALSE;
103 unsigned short port = DEFAULT_PORT;
104 unsigned short connectport = 0; /* if non-zero, we activate this mode */
107 PASSIVE_LISTEN, /* as a server waiting for connections */
108 PASSIVE_CONNECT, /* as a server, connected to a client */
109 ACTIVE, /* as a client, connected to a server */
110 ACTIVE_DISCONNECT /* as a client, disconnected from server */
114 * fullread is a wrapper around the read() function. This will repeat the call
115 * to read() until it actually has read the complete number of bytes indicated
116 * in nbytes or it fails with a condition that cannot be handled with a simple
117 * retry of the read call.
120 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
127 rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
131 if((error == EINTR) || (error == EAGAIN))
133 logmsg("unrecoverable read() failure: %s", strerror(error));
138 logmsg("got 0 reading from stdin");
144 } while((size_t)nread < nbytes);
147 logmsg("read %ld bytes", (long)nread);
153 * fullwrite is a wrapper around the write() function. This will repeat the
154 * call to write() until it actually has written the complete number of bytes
155 * indicated in nbytes or it fails with a condition that cannot be handled
156 * with a simple retry of the write call.
159 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
166 wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
170 if((error == EINTR) || (error == EAGAIN))
172 logmsg("unrecoverable write() failure: %s", strerror(error));
177 logmsg("put 0 writing to stdout");
183 } while((size_t)nwrite < nbytes);
186 logmsg("wrote %ld bytes", (long)nwrite);
192 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
193 * blocking function that will only return TRUE when nbytes have actually been
194 * read or FALSE when an unrecoverable error has been detected. Failure of this
195 * function is an indication that the sockfilt process should terminate.
198 static bool read_stdin(void *buffer, size_t nbytes)
200 ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
201 if(nread != (ssize_t)nbytes) {
202 logmsg("exiting...");
209 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
210 * blocking function that will only return TRUE when nbytes have actually been
211 * written or FALSE when an unrecoverable error has been detected. Failure of
212 * this function is an indication that the sockfilt process should terminate.
215 static bool write_stdout(const void *buffer, size_t nbytes)
217 ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
218 if(nwrite != (ssize_t)nbytes) {
219 logmsg("exiting...");
225 static void lograw(unsigned char *buffer, ssize_t len)
229 unsigned char *ptr = buffer;
233 for(i=0; i<len; i++) {
236 sprintf(optr, "\\n");
241 sprintf(optr, "\\r");
246 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
253 logmsg("'%s'", data);
259 logmsg("'%s'", data);
263 static void sigpipe_handler(int sig)
265 (void)sig; /* prevent warning */
271 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
273 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
276 static bool juggle(curl_socket_t *sockfdp,
277 curl_socket_t listenfd,
280 struct timeval timeout;
284 curl_socket_t sockfd;
287 ssize_t nread_socket;
288 ssize_t bytes_written;
291 /* 'buffer' is this excessively large only to be able to support things like
292 test 1003 which tests exceedingly large server response lines */
293 unsigned char buffer[17010];
297 /* As a last resort, quit if sockfilt process becomes orphan. Just in case
298 parent ftpserver process has died without killing its sockfilt children */
300 logmsg("process becomes orphan, exiting");
305 timeout.tv_sec = 120;
312 FD_SET(fileno(stdin), &fds_read);
320 /* there's always a socket to wait for */
321 FD_SET(sockfd, &fds_read);
325 case PASSIVE_CONNECT:
328 if(CURL_SOCKET_BAD == sockfd) {
329 /* eeek, we are supposedly connected and then this cannot be -1 ! */
330 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
331 maxfd = 0; /* stdin */
334 /* there's always a socket to wait for */
335 FD_SET(sockfd, &fds_read);
343 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
344 if(CURL_SOCKET_BAD != sockfd) {
345 FD_SET(sockfd, &fds_read);
349 logmsg("No socket to read on");
354 case ACTIVE_DISCONNECT:
356 logmsg("disconnected, no socket to read on");
358 sockfd = CURL_SOCKET_BAD;
361 } /* switch(*mode) */
366 rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
368 } while((rc == -1) && (SOCKERRNO == EINTR));
378 if(FD_ISSET(fileno(stdin), &fds_read)) {
379 /* read from stdin, commands/data to be dealt with and possibly passed on
384 4 letter command + LF [mandatory]
386 4-digit hexadecimal data length + LF [if the command takes data]
387 data [the data being as long as set above]
391 DATA - plain pass-thru data
394 if(!read_stdin(buffer, 5))
397 logmsg("Received %c%c%c%c (on stdin)",
398 buffer[0], buffer[1], buffer[2], buffer[3] );
400 if(!memcmp("PING", buffer, 4)) {
401 /* send reply on stdout, just proving we are alive */
402 if(!write_stdout("PONG\n", 5))
406 else if(!memcmp("PORT", buffer, 4)) {
407 /* Question asking us what PORT number we are listening to.
408 Replies to PORT with "IPv[num]/[port]" */
409 sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
410 buffer_len = (ssize_t)strlen((char *)buffer);
411 snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
412 if(!write_stdout(data, 10))
414 if(!write_stdout(buffer, buffer_len))
417 else if(!memcmp("QUIT", buffer, 4)) {
422 else if(!memcmp("DATA", buffer, 4)) {
423 /* data IN => data OUT */
425 if(!read_stdin(buffer, 5))
430 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
431 if (buffer_len > (ssize_t)sizeof(buffer)) {
432 logmsg("ERROR: Buffer size (%ld bytes) too small for data size "
433 "(%ld bytes)", (long)sizeof(buffer), (long)buffer_len);
436 logmsg("> %d bytes data, server => client", buffer_len);
438 if(!read_stdin(buffer, buffer_len))
441 lograw(buffer, buffer_len);
443 if(*mode == PASSIVE_LISTEN) {
444 logmsg("*** We are disconnected!");
445 if(!write_stdout("DISC\n", 5))
449 /* send away on the socket */
450 bytes_written = swrite(sockfd, buffer, buffer_len);
451 if(bytes_written != buffer_len) {
452 logmsg("Not all data was sent. Bytes to send: %d sent: %d",
453 buffer_len, bytes_written);
457 else if(!memcmp("DISC", buffer, 4)) {
459 if(!write_stdout("DISC\n", 5))
461 if(sockfd != CURL_SOCKET_BAD) {
462 logmsg("====> Client forcibly disconnected");
464 *sockfdp = CURL_SOCKET_BAD;
465 if(*mode == PASSIVE_CONNECT)
466 *mode = PASSIVE_LISTEN;
468 *mode = ACTIVE_DISCONNECT;
471 logmsg("attempt to close already dead connection");
477 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
479 if(*mode == PASSIVE_LISTEN) {
480 /* there's no stream set up yet, this is an indication that there's a
481 client connecting. */
482 sockfd = accept(sockfd, NULL, NULL);
483 if(CURL_SOCKET_BAD == sockfd)
484 logmsg("accept() failed");
486 logmsg("====> Client connect");
487 if(!write_stdout("CNCT\n", 5))
489 *sockfdp = sockfd; /* store the new socket */
490 *mode = PASSIVE_CONNECT; /* we have connected */
495 /* read from socket, pass on data to stdout */
496 nread_socket = sread(sockfd, buffer, sizeof(buffer));
498 if(nread_socket <= 0) {
499 logmsg("====> Client disconnect");
500 if(!write_stdout("DISC\n", 5))
503 *sockfdp = CURL_SOCKET_BAD;
504 if(*mode == PASSIVE_CONNECT)
505 *mode = PASSIVE_LISTEN;
507 *mode = ACTIVE_DISCONNECT;
511 snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
512 if(!write_stdout(data, 10))
514 if(!write_stdout(buffer, nread_socket))
517 logmsg("< %d bytes data, client => server", nread_socket);
518 lograw(buffer, nread_socket);
524 static curl_socket_t sockdaemon(curl_socket_t sock,
525 unsigned short *listenport)
527 /* passive daemon style */
528 struct sockaddr_in me;
530 struct sockaddr_in6 me6;
531 #endif /* ENABLE_IPV6 */
542 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
543 (void *)&flag, sizeof(flag));
549 /* should not happen */
551 logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
553 return CURL_SOCKET_BAD;
556 delay *= 2; /* double the sleep for next attempt */
559 } while(rc && maxretr--);
562 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
563 attempt, totdelay, error, strerror(error));
564 logmsg("Continuing anyway...");
570 memset(&me, 0, sizeof(me));
571 me.sin_family = AF_INET;
572 me.sin_addr.s_addr = INADDR_ANY;
573 me.sin_port = htons(*listenport);
574 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
578 memset(&me6, 0, sizeof(me6));
579 me6.sin6_family = AF_INET6;
580 me6.sin6_addr = in6addr_any;
581 me6.sin6_port = htons(*listenport);
582 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
584 #endif /* ENABLE_IPV6 */
587 logmsg("Error binding socket: (%d) %s", error, strerror(error));
589 return CURL_SOCKET_BAD;
593 /* The system picked a port number, now figure out which port we actually
595 /* we succeeded to bind */
596 struct sockaddr_in add;
597 socklen_t socksize = sizeof(add);
599 if(getsockname(sock, (struct sockaddr *) &add,
602 logmsg("getsockname() failed with error: (%d) %s",
603 error, strerror(error));
605 return CURL_SOCKET_BAD;
607 *listenport = ntohs(add.sin_port);
610 /* start accepting connections */
611 rc = listen(sock, 5);
614 logmsg("listen() failed with error: (%d) %s",
615 error, strerror(error));
617 return CURL_SOCKET_BAD;
624 int main(int argc, char *argv[])
626 struct sockaddr_in me;
628 struct sockaddr_in6 me6;
629 #endif /* ENABLE_IPV6 */
631 curl_socket_t msgsock;
632 char *pidname= (char *)".sockfilt.pid";
636 enum sockmode mode = PASSIVE_LISTEN; /* default */
637 const char *addr = NULL;
640 if(!strcmp("--version", argv[arg])) {
641 printf("sockfilt IPv4%s\n",
650 else if(!strcmp("--verbose", argv[arg])) {
654 else if(!strcmp("--pidfile", argv[arg])) {
657 pidname = argv[arg++];
659 else if(!strcmp("--logfile", argv[arg])) {
662 serverlogfile = argv[arg++];
664 else if(!strcmp("--ipv6", argv[arg])) {
670 else if(!strcmp("--ipv4", argv[arg])) {
671 /* for completeness, we support this option as well */
675 else if(!strcmp("--port", argv[arg])) {
678 port = (unsigned short)atoi(argv[arg]);
682 else if(!strcmp("--connect", argv[arg])) {
683 /* Asked to actively connect to the specified local port instead of
684 doing a passive server-style listening. */
687 connectport = (unsigned short)atoi(argv[arg]);
691 else if(!strcmp("--addr", argv[arg])) {
692 /* Set an IP address to use with --connect; otherwise use localhost */
700 puts("Usage: sockfilt [option]\n"
703 " --logfile [file]\n"
704 " --pidfile [file]\n"
708 " --connect [port]\n"
709 " --addr [address]");
716 atexit(win32_cleanup);
721 signal(SIGPIPE, sigpipe_handler);
723 #ifdef HAVE_SIGINTERRUPT
724 siginterrupt(SIGPIPE, 1);
732 sock = socket(AF_INET, SOCK_STREAM, 0);
735 sock = socket(AF_INET6, SOCK_STREAM, 0);
738 if(CURL_SOCKET_BAD == sock) {
740 logmsg("Error creating socket: (%d) %s",
741 error, strerror(error));
746 /* Active mode, we should connect to the given port number */
751 memset(&me, 0, sizeof(me));
752 me.sin_family = AF_INET;
753 me.sin_port = htons(connectport);
754 me.sin_addr.s_addr = INADDR_ANY;
757 Curl_inet_pton(AF_INET, addr, &me.sin_addr);
759 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
763 memset(&me6, 0, sizeof(me6));
764 me6.sin6_family = AF_INET6;
765 me6.sin6_port = htons(connectport);
768 Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
770 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
772 #endif /* ENABLE_IPV6 */
775 logmsg("Error connecting to port %d: (%d) %s",
776 port, error, strerror(error));
780 logmsg("====> Client connect");
781 msgsock = sock; /* use this as stream */
784 /* passive daemon style */
785 sock = sockdaemon(sock, &port);
786 if(CURL_SOCKET_BAD == sock)
788 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
791 logmsg("Running IPv%d version",
795 logmsg("Connected to port %d", connectport);
797 logmsg("Listening on port %d", port);
799 if(!write_pidfile(pidname)) {
804 while(juggle(&msgsock, sock, &mode));
809 logmsg("sockfilt exits");