1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2007, 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 static void lograw(unsigned char *buffer, ssize_t len)
105 unsigned char *ptr = buffer;
109 for(i=0; i<len; i++) {
112 sprintf(optr, "\\n");
117 sprintf(optr, "\\r");
122 sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
129 logmsg("'%s'", data);
135 logmsg("'%s'", data);
139 static void sigpipe_handler(int sig)
141 (void)sig; /* prevent warning */
147 unsigned short port = DEFAULT_PORT;
148 unsigned short connectport = 0; /* if non-zero, we activate this mode */
151 PASSIVE_LISTEN, /* as a server waiting for connections */
152 PASSIVE_CONNECT, /* as a server, connected to a client */
153 ACTIVE, /* as a client, connected to a server */
154 ACTIVE_DISCONNECT /* as a client, disconnected from server */
158 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
160 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
163 static int juggle(curl_socket_t *sockfdp,
164 curl_socket_t listenfd,
167 struct timeval timeout;
171 curl_socket_t sockfd;
175 ssize_t nread_socket;
176 ssize_t bytes_written;
179 /* 'buffer' is this excessively large only to be able to support things like
180 test 1003 which tests exceedingly large server response lines */
181 unsigned char buffer[17010];
184 timeout.tv_sec = 120;
191 FD_SET(fileno(stdin), &fds_read);
199 /* there's always a socket to wait for */
200 FD_SET(sockfd, &fds_read);
204 case PASSIVE_CONNECT:
207 if(CURL_SOCKET_BAD == sockfd) {
208 /* eeek, we are supposedly connected and then this cannot be -1 ! */
209 logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
210 maxfd = 0; /* stdin */
213 /* there's always a socket to wait for */
214 FD_SET(sockfd, &fds_read);
222 /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
223 if(CURL_SOCKET_BAD != sockfd) {
224 FD_SET(sockfd, &fds_read);
228 logmsg("No socket to read on");
233 case ACTIVE_DISCONNECT:
235 logmsg("disconnected, no socket to read on");
237 sockfd = CURL_SOCKET_BAD;
240 } /* switch(*mode) */
243 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
244 } while((rc == -1) && (SOCKERRNO == EINTR));
250 case 0: /* timeout! */
255 if(FD_ISSET(fileno(stdin), &fds_read)) {
256 /* read from stdin, commands/data to be dealt with and possibly passed on
261 4 letter command + LF [mandatory]
263 4-digit hexadecimal data length + LF [if the command takes data]
264 data [the data being as long as set above]
268 DATA - plain pass-thru data
270 nread_stdin = read(fileno(stdin), buffer, 5);
271 if(5 == nread_stdin) {
273 logmsg("Received %c%c%c%c (on stdin)",
274 buffer[0], buffer[1], buffer[2], buffer[3] );
276 if(!memcmp("PING", buffer, 4)) {
277 /* send reply on stdout, just proving we are alive */
278 write(fileno(stdout), "PONG\n", 5);
281 else if(!memcmp("PORT", buffer, 4)) {
282 /* Question asking us what PORT number we are listening to.
283 Replies to PORT with "IPv[num]/[port]" */
284 sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
285 buffer_len = (ssize_t)strlen((char *)buffer);
286 snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
287 write(fileno(stdout), data, 10);
288 write(fileno(stdout), buffer, buffer_len);
290 else if(!memcmp("QUIT", buffer, 4)) {
295 else if(!memcmp("DATA", buffer, 4)) {
296 /* data IN => data OUT */
298 if(5 != read(fileno(stdin), buffer, 5))
302 buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
303 if (buffer_len > (ssize_t)sizeof(buffer)) {
304 logmsg("Buffer size %d too small for data size %d",
305 (int)sizeof(buffer), buffer_len);
308 logmsg("> %d bytes data, server => client", buffer_len);
311 * To properly support huge data chunks, we need to repeat the call
312 * to read() until we're done or it fails.
316 /* get data in the buffer at the correct position */
317 ssize_t rc = read(fileno(stdin), &buffer[nread_stdin],
318 buffer_len - nread_stdin);
319 logmsg("read %d bytes", rc);
323 } while (nread_stdin < buffer_len);
325 lograw(buffer, buffer_len);
327 if(*mode == PASSIVE_LISTEN) {
328 logmsg("*** We are disconnected!");
329 write(fileno(stdout), "DISC\n", 5);
332 /* send away on the socket */
333 bytes_written = swrite(sockfd, buffer, buffer_len);
334 if(bytes_written != buffer_len) {
335 logmsg("Not all data was sent. Bytes to send: %d sent: %d",
336 buffer_len, bytes_written);
340 else if(!memcmp("DISC", buffer, 4)) {
342 write(fileno(stdout), "DISC\n", 5);
343 if(sockfd != CURL_SOCKET_BAD) {
344 logmsg("====> Client forcibly disconnected");
346 *sockfdp = CURL_SOCKET_BAD;
347 if(*mode == PASSIVE_CONNECT)
348 *mode = PASSIVE_LISTEN;
350 *mode = ACTIVE_DISCONNECT;
353 logmsg("attempt to close already dead connection");
357 else if(-1 == nread_stdin) {
358 logmsg("read %d from stdin, exiting", nread_stdin);
364 if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
366 if(*mode == PASSIVE_LISTEN) {
367 /* there's no stream set up yet, this is an indication that there's a
368 client connecting. */
369 sockfd = accept(sockfd, NULL, NULL);
370 if(CURL_SOCKET_BAD == sockfd)
371 logmsg("accept() failed");
373 logmsg("====> Client connect");
374 write(fileno(stdout), "CNCT\n", 5);
375 *sockfdp = sockfd; /* store the new socket */
376 *mode = PASSIVE_CONNECT; /* we have connected */
381 /* read from socket, pass on data to stdout */
382 nread_socket = sread(sockfd, buffer, sizeof(buffer));
384 if(nread_socket <= 0) {
385 logmsg("====> Client disconnect");
386 write(fileno(stdout), "DISC\n", 5);
388 *sockfdp = CURL_SOCKET_BAD;
389 if(*mode == PASSIVE_CONNECT)
390 *mode = PASSIVE_LISTEN;
392 *mode = ACTIVE_DISCONNECT;
396 snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
397 write(fileno(stdout), data, 10);
398 write(fileno(stdout), buffer, nread_socket);
400 logmsg("< %d bytes data, client => server", nread_socket);
401 lograw(buffer, nread_socket);
407 static curl_socket_t sockdaemon(curl_socket_t sock,
408 unsigned short *port)
410 /* passive daemon style */
411 struct sockaddr_in me;
413 struct sockaddr_in6 me6;
414 #endif /* ENABLE_IPV6 */
420 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
421 (void *)&flag, sizeof(flag));
422 while ((rc < 0) && maxretr) {
425 delay *= 2; /* double the sleep for next attempt */
426 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
427 (void *)&flag, sizeof(flag));
430 perror("setsockopt(SO_REUSEADDR)");
436 me.sin_family = AF_INET;
437 me.sin_addr.s_addr = INADDR_ANY;
438 me.sin_port = htons(*port);
439 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
443 memset(&me6, 0, sizeof(struct sockaddr_in6));
444 me6.sin6_family = AF_INET6;
445 me6.sin6_addr = in6addr_any;
446 me6.sin6_port = htons(*port);
447 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
449 #endif /* ENABLE_IPV6 */
451 perror("binding stream socket");
452 logmsg("Error binding socket");
453 return CURL_SOCKET_BAD;
457 /* The system picked a port number, now figure out which port we actually
459 /* we succeeded to bind */
460 struct sockaddr_in add;
461 socklen_t socksize = sizeof(add);
463 if(getsockname(sock, (struct sockaddr *) &add,
465 logmsg("getsockname() failed with error: %d", SOCKERRNO);
466 return CURL_SOCKET_BAD;
468 *port = ntohs(add.sin_port);
471 /* start accepting connections */
472 rc = listen(sock, 4);
474 logmsg("listen() failed with error: %d", SOCKERRNO);
476 return CURL_SOCKET_BAD;
482 static curl_socket_t mksock(bool use_ipv6)
490 sock = socket(AF_INET, SOCK_STREAM, 0);
493 sock = socket(AF_INET6, SOCK_STREAM, 0);
496 if (CURL_SOCKET_BAD == sock) {
497 perror("opening stream socket");
498 logmsg("Error opening socket");
505 int main(int argc, char *argv[])
507 struct sockaddr_in me;
509 struct sockaddr_in6 me6;
510 #endif /* ENABLE_IPV6 */
512 curl_socket_t msgsock;
514 char *pidname= (char *)".sockfilt.pid";
518 enum sockmode mode = PASSIVE_LISTEN; /* default */
521 if(!strcmp("--version", argv[arg])) {
522 printf("sockfilt IPv4%s\n",
531 else if(!strcmp("--pidfile", argv[arg])) {
534 pidname = argv[arg++];
536 else if(!strcmp("--logfile", argv[arg])) {
539 serverlogfile = argv[arg++];
541 else if(!strcmp("--ipv6", argv[arg])) {
547 else if(!strcmp("--ipv4", argv[arg])) {
548 /* for completeness, we support this option as well */
552 else if(!strcmp("--port", argv[arg])) {
555 port = (unsigned short)atoi(argv[arg]);
559 else if(!strcmp("--connect", argv[arg])) {
560 /* Asked to actively connect to the specified local port instead of
561 doing a passive server-style listening. */
564 connectport = (unsigned short)atoi(argv[arg]);
569 puts("Usage: sockfilt [option]\n"
571 " --logfile [file]\n"
572 " --pidfile [file]\n"
582 atexit(win32_cleanup);
587 signal(SIGPIPE, sigpipe_handler);
589 #ifdef HAVE_SIGINTERRUPT
590 siginterrupt(SIGPIPE, 1);
596 sock = mksock(use_ipv6);
597 if (CURL_SOCKET_BAD == sock) {
598 logmsg("Error opening socket: %d", SOCKERRNO);
603 /* Active mode, we should connect to the given port number */
608 memset(&me, 0, sizeof(me));
609 me.sin_family = AF_INET;
610 me.sin_port = htons(connectport);
611 me.sin_addr.s_addr = INADDR_ANY;
612 Curl_inet_pton(AF_INET, "127.0.0.1", &me.sin_addr);
614 rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
618 memset(&me6, 0, sizeof(me6));
619 me6.sin6_family = AF_INET6;
620 me6.sin6_port = htons(connectport);
621 Curl_inet_pton(AF_INET6, "::1", &me6.sin6_addr);
623 rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
625 #endif /* ENABLE_IPV6 */
627 perror("connecting stream socket");
628 logmsg("Error connecting to port %d", port);
632 logmsg("====> Client connect");
633 msgsock = sock; /* use this as stream */
636 /* passive daemon style */
637 sock = sockdaemon(sock, &port);
638 if(CURL_SOCKET_BAD == sock)
640 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
643 logmsg("Running IPv%d version",
647 logmsg("Connected to port %d", connectport);
649 logmsg("Listening on port %d", port);
651 pidfile = fopen(pidname, "w");
653 int pid = (int)getpid();
654 fprintf(pidfile, "%d\n", pid);
656 logmsg("Wrote pid %d to %s", pid, pidname);
660 logmsg("fopen() failed with error: %d %s\n", error, strerror(error));
661 logmsg("Error opening file: %s\n", pidname);
662 logmsg("Couldn't write pid file\n");
667 while(juggle(&msgsock, sock, &mode));