tests/server/sockfilt.c: Improved log error messages
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 #include "server_setup.h"
23
24 /* Purpose
25  *
26  * 1. Accept a TCP connection on a custom port (ipv4 or ipv6), or connect
27  *    to a given (localhost) port.
28  *
29  * 2. Get commands on STDIN. Pass data on to the TCP stream.
30  *    Get data from TCP stream and pass on to STDOUT.
31  *
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:
36  *
37  * o We want the perl code to work with rather old perl installations, thus
38  *   we cannot use recent perl modules or features.
39  *
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.
42  *
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.
46  *
47  * (Source originally based on sws.c)
48  */
49
50 /*
51  * Signal handling notes for sockfilt
52  * ----------------------------------
53  *
54  * This program is a single-threaded process.
55  *
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.
60  *
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.
66  *
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.
70  *
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.
75  *
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!
81  */
82
83 #ifdef HAVE_SIGNAL_H
84 #include <signal.h>
85 #endif
86 #ifdef HAVE_NETINET_IN_H
87 #include <netinet/in.h>
88 #endif
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
91 #endif
92 #ifdef HAVE_NETDB_H
93 #include <netdb.h>
94 #endif
95
96 #define ENABLE_CURLX_PRINTF
97 /* make the curlx header define all printf() functions to use the curlx_*
98    versions instead */
99 #include "curlx.h" /* from the private lib dir */
100 #include "getpart.h"
101 #include "inet_pton.h"
102 #include "util.h"
103 #include "server_sockaddr.h"
104
105 /* include memdebug.h last */
106 #include "memdebug.h"
107
108 #define DEFAULT_PORT 8999
109
110 #ifndef DEFAULT_LOGFILE
111 #define DEFAULT_LOGFILE "log/sockfilt.log"
112 #endif
113
114 const char *serverlogfile = DEFAULT_LOGFILE;
115
116 static bool verbose = FALSE;
117 static bool bind_only = FALSE;
118 #ifdef ENABLE_IPV6
119 static bool use_ipv6 = FALSE;
120 #endif
121 static const char *ipv_inuse = "IPv4";
122 static unsigned short port = DEFAULT_PORT;
123 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
124
125 enum sockmode {
126   PASSIVE_LISTEN,    /* as a server waiting for connections */
127   PASSIVE_CONNECT,   /* as a server, connected to a client */
128   ACTIVE,            /* as a client, connected to a server */
129   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
130 };
131
132 /* do-nothing macro replacement for systems which lack siginterrupt() */
133
134 #ifndef HAVE_SIGINTERRUPT
135 #define siginterrupt(x,y) do {} while(0)
136 #endif
137
138 /* vars used to keep around previous signal handlers */
139
140 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
141
142 #ifdef SIGHUP
143 static SIGHANDLER_T old_sighup_handler  = SIG_ERR;
144 #endif
145
146 #ifdef SIGPIPE
147 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
148 #endif
149
150 #ifdef SIGALRM
151 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
152 #endif
153
154 #ifdef SIGINT
155 static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
156 #endif
157
158 #ifdef SIGTERM
159 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
160 #endif
161
162 /* var which if set indicates that the program should finish execution */
163
164 SIG_ATOMIC_T got_exit_signal = 0;
165
166 /* if next is set indicates the first signal handled in exit_signal_handler */
167
168 static volatile int exit_signal = 0;
169
170 /* signal handler that will be triggered to indicate that the program
171   should finish its execution in a controlled manner as soon as possible.
172   The first time this is called it will set got_exit_signal to one and
173   store in exit_signal the signal that triggered its execution. */
174
175 static RETSIGTYPE exit_signal_handler(int signum)
176 {
177   int old_errno = ERRNO;
178   if(got_exit_signal == 0) {
179     got_exit_signal = 1;
180     exit_signal = signum;
181   }
182   (void)signal(signum, exit_signal_handler);
183   SET_ERRNO(old_errno);
184 }
185
186 static void install_signal_handlers(void)
187 {
188 #ifdef SIGHUP
189   /* ignore SIGHUP signal */
190   if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
191     logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
192 #endif
193 #ifdef SIGPIPE
194   /* ignore SIGPIPE signal */
195   if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
196     logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
197 #endif
198 #ifdef SIGALRM
199   /* ignore SIGALRM signal */
200   if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
201     logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
202 #endif
203 #ifdef SIGINT
204   /* handle SIGINT signal with our exit_signal_handler */
205   if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
206     logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
207   else
208     siginterrupt(SIGINT, 1);
209 #endif
210 #ifdef SIGTERM
211   /* handle SIGTERM signal with our exit_signal_handler */
212   if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
213     logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
214   else
215     siginterrupt(SIGTERM, 1);
216 #endif
217 }
218
219 static void restore_signal_handlers(void)
220 {
221 #ifdef SIGHUP
222   if(SIG_ERR != old_sighup_handler)
223     (void)signal(SIGHUP, old_sighup_handler);
224 #endif
225 #ifdef SIGPIPE
226   if(SIG_ERR != old_sigpipe_handler)
227     (void)signal(SIGPIPE, old_sigpipe_handler);
228 #endif
229 #ifdef SIGALRM
230   if(SIG_ERR != old_sigalrm_handler)
231     (void)signal(SIGALRM, old_sigalrm_handler);
232 #endif
233 #ifdef SIGINT
234   if(SIG_ERR != old_sigint_handler)
235     (void)signal(SIGINT, old_sigint_handler);
236 #endif
237 #ifdef SIGTERM
238   if(SIG_ERR != old_sigterm_handler)
239     (void)signal(SIGTERM, old_sigterm_handler);
240 #endif
241 }
242
243 /*
244  * fullread is a wrapper around the read() function. This will repeat the call
245  * to read() until it actually has read the complete number of bytes indicated
246  * in nbytes or it fails with a condition that cannot be handled with a simple
247  * retry of the read call.
248  */
249
250 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
251 {
252   int error;
253   ssize_t rc;
254   ssize_t nread = 0;
255
256   do {
257     rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
258
259     if(got_exit_signal) {
260       logmsg("signalled to die");
261       return -1;
262     }
263
264     if(rc < 0) {
265       error = ERRNO;
266       if((error == EINTR) || (error == EAGAIN))
267         continue;
268       logmsg("unrecoverable read() failure: (%d) %s",
269              error, strerror(error));
270       return -1;
271     }
272
273     if(rc == 0) {
274       logmsg("got 0 reading from stdin");
275       return 0;
276     }
277
278     nread += rc;
279
280   } while((size_t)nread < nbytes);
281
282   if(verbose)
283     logmsg("read %zd bytes", nread);
284
285   return nread;
286 }
287
288 /*
289  * fullwrite is a wrapper around the write() function. This will repeat the
290  * call to write() until it actually has written the complete number of bytes
291  * indicated in nbytes or it fails with a condition that cannot be handled
292  * with a simple retry of the write call.
293  */
294
295 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
296 {
297   int error;
298   ssize_t wc;
299   ssize_t nwrite = 0;
300
301   do {
302     wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
303
304     if(got_exit_signal) {
305       logmsg("signalled to die");
306       return -1;
307     }
308
309     if(wc < 0) {
310       error = ERRNO;
311       if((error == EINTR) || (error == EAGAIN))
312         continue;
313       logmsg("unrecoverable write() failure: (%d) %s",
314              error, strerror(error));
315       return -1;
316     }
317
318     if(wc == 0) {
319       logmsg("put 0 writing to stdout");
320       return 0;
321     }
322
323     nwrite += wc;
324
325   } while((size_t)nwrite < nbytes);
326
327   if(verbose)
328     logmsg("wrote %zd bytes", nwrite);
329
330   return nwrite;
331 }
332
333 /*
334  * read_stdin tries to read from stdin nbytes into the given buffer. This is a
335  * blocking function that will only return TRUE when nbytes have actually been
336  * read or FALSE when an unrecoverable error has been detected. Failure of this
337  * function is an indication that the sockfilt process should terminate.
338  */
339
340 static bool read_stdin(void *buffer, size_t nbytes)
341 {
342   ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
343   if(nread != (ssize_t)nbytes) {
344     logmsg("exiting...");
345     return FALSE;
346   }
347   return TRUE;
348 }
349
350 /*
351  * write_stdout tries to write to stdio nbytes from the given buffer. This is a
352  * blocking function that will only return TRUE when nbytes have actually been
353  * written or FALSE when an unrecoverable error has been detected. Failure of
354  * this function is an indication that the sockfilt process should terminate.
355  */
356
357 static bool write_stdout(const void *buffer, size_t nbytes)
358 {
359   ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
360   if(nwrite != (ssize_t)nbytes) {
361     logmsg("exiting...");
362     return FALSE;
363   }
364   return TRUE;
365 }
366
367 static void lograw(unsigned char *buffer, ssize_t len)
368 {
369   char data[120];
370   ssize_t i;
371   unsigned char *ptr = buffer;
372   char *optr = data;
373   ssize_t width=0;
374
375   for(i=0; i<len; i++) {
376     switch(ptr[i]) {
377     case '\n':
378       sprintf(optr, "\\n");
379       width += 2;
380       optr += 2;
381       break;
382     case '\r':
383       sprintf(optr, "\\r");
384       width += 2;
385       optr += 2;
386       break;
387     default:
388       sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
389       width++;
390       optr++;
391       break;
392     }
393
394     if(width>60) {
395       logmsg("'%s'", data);
396       width = 0;
397       optr = data;
398     }
399   }
400   if(width)
401     logmsg("'%s'", data);
402 }
403
404 /*
405  * WinSock select() does not support standard file descriptors,
406  * it can only check SOCKETs. The following function is an attempt
407  * to re-create a select() function with support for other handle types.
408  */
409 #ifdef USE_WINSOCK
410 /*
411  * select() function with support for WINSOCK2 sockets and all
412  * other handle types supported by WaitForMultipleObjectsEx().
413  *
414  * TODO: Differentiate between read/write/except for non-SOCKET handles.
415  *
416  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
417  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
418  */
419 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
420                      fd_set *exceptfds, struct timeval *timeout)
421 {
422   long networkevents;
423   DWORD milliseconds, wait, idx;
424   WSAEVENT wsaevent, *wsaevents;
425   WSANETWORKEVENTS wsanetevents;
426   HANDLE *handles;
427   curl_socket_t *fdarr;
428   int error, fds;
429   DWORD nfd = 0, wsa = 0;
430   int ret = 0;
431
432   if(nfds < 0) {
433     SET_SOCKERRNO(EINVAL);
434     return -1;
435   }
436
437   if(!nfds) {
438     Sleep(1000*timeout->tv_sec + timeout->tv_usec/1000);
439     return 0;
440   }
441
442   /* allocate internal array for the original input handles */
443   fdarr = malloc(nfds * sizeof(curl_socket_t));
444   if(fdarr == NULL) {
445     errno = ENOMEM;
446     return -1;
447   }
448
449   /* allocate internal array for the internal event handles */
450   handles = malloc(nfds * sizeof(HANDLE));
451   if(handles == NULL) {
452     errno = ENOMEM;
453     return -1;
454   }
455
456   /* allocate internal array for the internal WINSOCK2 events */
457   wsaevents = malloc(nfds * sizeof(WSAEVENT));
458   if(wsaevents == NULL) {
459     errno = ENOMEM;
460     return -1;
461   }
462
463   /* loop over the handles in the input descriptor sets */
464   for(fds = 0; fds < nfds; fds++) {
465     networkevents = 0;
466     handles[nfd] = 0;
467
468     if(FD_ISSET(fds, readfds))
469       networkevents |= FD_READ;
470
471     if(FD_ISSET(fds, writefds))
472       networkevents |= FD_WRITE;
473
474     if(FD_ISSET(fds, exceptfds))
475       networkevents |= FD_CLOSE;
476
477     if(networkevents) {
478       fdarr[nfd] = (curl_socket_t)fds;
479       if(fds == fileno(stdin)) {
480         handles[nfd] = GetStdHandle(STD_INPUT_HANDLE);
481       }
482       else if(fds == fileno(stdout)) {
483         handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
484       }
485       else if(fds == fileno(stderr)) {
486         handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
487       }
488       else {
489         wsaevent = WSACreateEvent();
490         if(wsaevent != WSA_INVALID_EVENT) {
491           error = WSAEventSelect(fds, wsaevent, networkevents);
492           if(error != SOCKET_ERROR) {
493             handles[nfd] = wsaevent;
494             wsaevents[wsa++] = wsaevent;
495           }
496           else {
497             handles[nfd] = (HANDLE) fds;
498             WSACloseEvent(wsaevent);
499           }
500         }
501       }
502       nfd++;
503     }
504   }
505
506   /* convert struct timeval to milliseconds */
507   if(timeout) {
508     milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
509   }
510   else {
511     milliseconds = INFINITE;
512   }
513
514   /* wait for one of the internal handles to trigger */
515   wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
516
517   /* loop over the internal handles returned in the descriptors */
518   for(idx = 0; idx < nfd; idx++) {
519     if(wait != WAIT_OBJECT_0 + idx) {
520       /* remove from all descriptor sets since this handle did not trigger */
521       FD_CLR(fdarr[idx], readfds);
522       FD_CLR(fdarr[idx], writefds);
523       FD_CLR(fdarr[idx], exceptfds);
524     }
525     else {
526       /* first try to handle the event with the WINSOCK2 functions */
527       error = WSAEnumNetworkEvents(fdarr[idx], NULL, &wsanetevents);
528       if(error != SOCKET_ERROR) {
529         /* remove from descriptor set if not ready for read */
530         if(!(wsanetevents.lNetworkEvents & FD_READ))
531           FD_CLR(fdarr[idx], readfds);
532
533         /* remove from descriptor set if not ready for write */
534         if(!(wsanetevents.lNetworkEvents & FD_WRITE))
535           FD_CLR(fdarr[idx], writefds);
536
537         /* remove from descriptor set if not exceptional */
538         if(!(wsanetevents.lNetworkEvents & FD_CLOSE))
539           FD_CLR(fdarr[idx], exceptfds);
540       }
541       ret++;
542     }
543   }
544
545   for(idx = 0; idx < wsa; idx++)
546     WSACloseEvent(wsaevents[idx]);
547
548   free(wsaevents);
549   free(handles);
550   free(fdarr);
551
552   return ret;
553 }
554 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
555 #endif
556
557 /*
558   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
559
560   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
561   accept()
562 */
563 static bool juggle(curl_socket_t *sockfdp,
564                    curl_socket_t listenfd,
565                    enum sockmode *mode)
566 {
567   struct timeval timeout;
568   fd_set fds_read;
569   fd_set fds_write;
570   fd_set fds_err;
571   curl_socket_t sockfd = CURL_SOCKET_BAD;
572   int maxfd = -99;
573   ssize_t rc;
574   ssize_t nread_socket;
575   ssize_t bytes_written;
576   ssize_t buffer_len;
577   int error = 0;
578
579  /* 'buffer' is this excessively large only to be able to support things like
580     test 1003 which tests exceedingly large server response lines */
581   unsigned char buffer[17010];
582   char data[16];
583
584   if(got_exit_signal) {
585     logmsg("signalled to die, exiting...");
586     return FALSE;
587   }
588
589 #ifdef HAVE_GETPPID
590   /* As a last resort, quit if sockfilt process becomes orphan. Just in case
591      parent ftpserver process has died without killing its sockfilt children */
592   if(getppid() <= 1) {
593     logmsg("process becomes orphan, exiting");
594     return FALSE;
595   }
596 #endif
597
598   timeout.tv_sec = 120;
599   timeout.tv_usec = 0;
600
601   FD_ZERO(&fds_read);
602   FD_ZERO(&fds_write);
603   FD_ZERO(&fds_err);
604
605   FD_SET((curl_socket_t)fileno(stdin), &fds_read);
606
607   switch(*mode) {
608
609   case PASSIVE_LISTEN:
610
611     /* server mode */
612     sockfd = listenfd;
613     /* there's always a socket to wait for */
614     FD_SET(sockfd, &fds_read);
615     maxfd = (int)sockfd;
616     break;
617
618   case PASSIVE_CONNECT:
619
620     sockfd = *sockfdp;
621     if(CURL_SOCKET_BAD == sockfd) {
622       /* eeek, we are supposedly connected and then this cannot be -1 ! */
623       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
624       maxfd = 0; /* stdin */
625     }
626     else {
627       /* there's always a socket to wait for */
628       FD_SET(sockfd, &fds_read);
629       maxfd = (int)sockfd;
630     }
631     break;
632
633   case ACTIVE:
634
635     sockfd = *sockfdp;
636     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
637     if(CURL_SOCKET_BAD != sockfd) {
638       FD_SET(sockfd, &fds_read);
639       maxfd = (int)sockfd;
640     }
641     else {
642       logmsg("No socket to read on");
643       maxfd = 0;
644     }
645     break;
646
647   case ACTIVE_DISCONNECT:
648
649     logmsg("disconnected, no socket to read on");
650     maxfd = 0;
651     sockfd = CURL_SOCKET_BAD;
652     break;
653
654   } /* switch(*mode) */
655
656
657   do {
658
659     /* select() blocking behavior call on blocking descriptors please */
660
661     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
662
663     if(got_exit_signal) {
664       logmsg("signalled to die, exiting...");
665       return FALSE;
666     }
667
668   } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
669
670   if(rc < 0) {
671     logmsg("select() failed with error: (%d) %s",
672            error, strerror(error));
673     return FALSE;
674   }
675
676   if(rc == 0)
677     /* timeout */
678     return TRUE;
679
680
681   if(FD_ISSET(fileno(stdin), &fds_read)) {
682     /* read from stdin, commands/data to be dealt with and possibly passed on
683        to the socket
684
685        protocol:
686
687        4 letter command + LF [mandatory]
688
689        4-digit hexadecimal data length + LF [if the command takes data]
690        data                       [the data being as long as set above]
691
692        Commands:
693
694        DATA - plain pass-thru data
695     */
696
697     if(!read_stdin(buffer, 5))
698       return FALSE;
699
700     logmsg("Received %c%c%c%c (on stdin)",
701            buffer[0], buffer[1], buffer[2], buffer[3] );
702
703     if(!memcmp("PING", buffer, 4)) {
704       /* send reply on stdout, just proving we are alive */
705       if(!write_stdout("PONG\n", 5))
706         return FALSE;
707     }
708
709     else if(!memcmp("PORT", buffer, 4)) {
710       /* Question asking us what PORT number we are listening to.
711          Replies to PORT with "IPv[num]/[port]" */
712       sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
713       buffer_len = (ssize_t)strlen((char *)buffer);
714       snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
715       if(!write_stdout(data, 10))
716         return FALSE;
717       if(!write_stdout(buffer, buffer_len))
718         return FALSE;
719     }
720     else if(!memcmp("QUIT", buffer, 4)) {
721       /* just die */
722       logmsg("quits");
723       return FALSE;
724     }
725     else if(!memcmp("DATA", buffer, 4)) {
726       /* data IN => data OUT */
727
728       if(!read_stdin(buffer, 5))
729         return FALSE;
730
731       buffer[5] = '\0';
732
733       buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
734       if (buffer_len > (ssize_t)sizeof(buffer)) {
735         logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
736                "(%zd bytes)", sizeof(buffer), buffer_len);
737         return FALSE;
738       }
739       logmsg("> %zd bytes data, server => client", buffer_len);
740
741       if(!read_stdin(buffer, buffer_len))
742         return FALSE;
743
744       lograw(buffer, buffer_len);
745
746       if(*mode == PASSIVE_LISTEN) {
747         logmsg("*** We are disconnected!");
748         if(!write_stdout("DISC\n", 5))
749           return FALSE;
750       }
751       else {
752         /* send away on the socket */
753         bytes_written = swrite(sockfd, buffer, buffer_len);
754         if(bytes_written != buffer_len) {
755           logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
756                  buffer_len, bytes_written);
757         }
758       }
759     }
760     else if(!memcmp("DISC", buffer, 4)) {
761       /* disconnect! */
762       if(!write_stdout("DISC\n", 5))
763         return FALSE;
764       if(sockfd != CURL_SOCKET_BAD) {
765         logmsg("====> Client forcibly disconnected");
766         sclose(sockfd);
767         *sockfdp = CURL_SOCKET_BAD;
768         if(*mode == PASSIVE_CONNECT)
769           *mode = PASSIVE_LISTEN;
770         else
771           *mode = ACTIVE_DISCONNECT;
772       }
773       else
774         logmsg("attempt to close already dead connection");
775       return TRUE;
776     }
777   }
778
779
780   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
781
782     if(*mode == PASSIVE_LISTEN) {
783       /* there's no stream set up yet, this is an indication that there's a
784          client connecting. */
785       listenfd = sockfd;
786       sockfd = accept(listenfd, NULL, NULL);
787       if(CURL_SOCKET_BAD == sockfd) {
788         error = SOCKERRNO;
789         logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
790                listenfd, error, strerror(error));
791       }
792       else {
793         logmsg("====> Client connect");
794         if(!write_stdout("CNCT\n", 5))
795           return FALSE;
796         *sockfdp = sockfd; /* store the new socket */
797         *mode = PASSIVE_CONNECT; /* we have connected */
798       }
799       return TRUE;
800     }
801
802     /* read from socket, pass on data to stdout */
803     nread_socket = sread(sockfd, buffer, sizeof(buffer));
804
805     if(nread_socket <= 0) {
806       logmsg("====> Client disconnect");
807       if(!write_stdout("DISC\n", 5))
808         return FALSE;
809       sclose(sockfd);
810       *sockfdp = CURL_SOCKET_BAD;
811       if(*mode == PASSIVE_CONNECT)
812         *mode = PASSIVE_LISTEN;
813       else
814         *mode = ACTIVE_DISCONNECT;
815       return TRUE;
816     }
817
818     snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
819     if(!write_stdout(data, 10))
820       return FALSE;
821     if(!write_stdout(buffer, nread_socket))
822       return FALSE;
823
824     logmsg("< %zd bytes data, client => server", nread_socket);
825     lograw(buffer, nread_socket);
826   }
827
828   return TRUE;
829 }
830
831 static curl_socket_t sockdaemon(curl_socket_t sock,
832                                 unsigned short *listenport)
833 {
834   /* passive daemon style */
835   srvr_sockaddr_union_t listener;
836   int flag;
837   int rc;
838   int totdelay = 0;
839   int maxretr = 10;
840   int delay= 20;
841   int attempt = 0;
842   int error = 0;
843
844   do {
845     attempt++;
846     flag = 1;
847     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
848          (void *)&flag, sizeof(flag));
849     if(rc) {
850       error = SOCKERRNO;
851       logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
852              error, strerror(error));
853       if(maxretr) {
854         rc = wait_ms(delay);
855         if(rc) {
856           /* should not happen */
857           error = SOCKERRNO;
858           logmsg("wait_ms() failed with error: (%d) %s",
859                  error, strerror(error));
860           sclose(sock);
861           return CURL_SOCKET_BAD;
862         }
863         if(got_exit_signal) {
864           logmsg("signalled to die, exiting...");
865           sclose(sock);
866           return CURL_SOCKET_BAD;
867         }
868         totdelay += delay;
869         delay *= 2; /* double the sleep for next attempt */
870       }
871     }
872   } while(rc && maxretr--);
873
874   if(rc) {
875     logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
876            attempt, totdelay, error, strerror(error));
877     logmsg("Continuing anyway...");
878   }
879
880   /* When the specified listener port is zero, it is actually a
881      request to let the system choose a non-zero available port. */
882
883 #ifdef ENABLE_IPV6
884   if(!use_ipv6) {
885 #endif
886     memset(&listener.sa4, 0, sizeof(listener.sa4));
887     listener.sa4.sin_family = AF_INET;
888     listener.sa4.sin_addr.s_addr = INADDR_ANY;
889     listener.sa4.sin_port = htons(*listenport);
890     rc = bind(sock, &listener.sa, sizeof(listener.sa4));
891 #ifdef ENABLE_IPV6
892   }
893   else {
894     memset(&listener.sa6, 0, sizeof(listener.sa6));
895     listener.sa6.sin6_family = AF_INET6;
896     listener.sa6.sin6_addr = in6addr_any;
897     listener.sa6.sin6_port = htons(*listenport);
898     rc = bind(sock, &listener.sa, sizeof(listener.sa6));
899   }
900 #endif /* ENABLE_IPV6 */
901   if(rc) {
902     error = SOCKERRNO;
903     logmsg("Error binding socket on port %hu: (%d) %s",
904            *listenport, error, strerror(error));
905     sclose(sock);
906     return CURL_SOCKET_BAD;
907   }
908
909   if(!*listenport) {
910     /* The system was supposed to choose a port number, figure out which
911        port we actually got and update the listener port value with it. */
912     curl_socklen_t la_size;
913     srvr_sockaddr_union_t localaddr;
914 #ifdef ENABLE_IPV6
915     if(!use_ipv6)
916 #endif
917       la_size = sizeof(localaddr.sa4);
918 #ifdef ENABLE_IPV6
919     else
920       la_size = sizeof(localaddr.sa6);
921 #endif
922     memset(&localaddr.sa, 0, (size_t)la_size);
923     if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
924       error = SOCKERRNO;
925       logmsg("getsockname() failed with error: (%d) %s",
926              error, strerror(error));
927       sclose(sock);
928       return CURL_SOCKET_BAD;
929     }
930     switch (localaddr.sa.sa_family) {
931     case AF_INET:
932       *listenport = ntohs(localaddr.sa4.sin_port);
933       break;
934 #ifdef ENABLE_IPV6
935     case AF_INET6:
936       *listenport = ntohs(localaddr.sa6.sin6_port);
937       break;
938 #endif
939     default:
940       break;
941     }
942     if(!*listenport) {
943       /* Real failure, listener port shall not be zero beyond this point. */
944       logmsg("Apparently getsockname() succeeded, with listener port zero.");
945       logmsg("A valid reason for this failure is a binary built without");
946       logmsg("proper network library linkage. This might not be the only");
947       logmsg("reason, but double check it before anything else.");
948       sclose(sock);
949       return CURL_SOCKET_BAD;
950     }
951   }
952
953   /* bindonly option forces no listening */
954   if(bind_only) {
955     logmsg("instructed to bind port without listening");
956     return sock;
957   }
958
959   /* start accepting connections */
960   rc = listen(sock, 5);
961   if(0 != rc) {
962     error = SOCKERRNO;
963     logmsg("listen(%d, 5) failed with error: (%d) %s",
964            sock, error, strerror(error));
965     sclose(sock);
966     return CURL_SOCKET_BAD;
967   }
968
969   return sock;
970 }
971
972
973 int main(int argc, char *argv[])
974 {
975   srvr_sockaddr_union_t me;
976   curl_socket_t sock = CURL_SOCKET_BAD;
977   curl_socket_t msgsock = CURL_SOCKET_BAD;
978   int wrotepidfile = 0;
979   char *pidname= (char *)".sockfilt.pid";
980   bool juggle_again;
981   int rc;
982   int error;
983   int arg=1;
984   enum sockmode mode = PASSIVE_LISTEN; /* default */
985   const char *addr = NULL;
986
987   while(argc>arg) {
988     if(!strcmp("--version", argv[arg])) {
989       printf("sockfilt IPv4%s\n",
990 #ifdef ENABLE_IPV6
991              "/IPv6"
992 #else
993              ""
994 #endif
995              );
996       return 0;
997     }
998     else if(!strcmp("--verbose", argv[arg])) {
999       verbose = TRUE;
1000       arg++;
1001     }
1002     else if(!strcmp("--pidfile", argv[arg])) {
1003       arg++;
1004       if(argc>arg)
1005         pidname = argv[arg++];
1006     }
1007     else if(!strcmp("--logfile", argv[arg])) {
1008       arg++;
1009       if(argc>arg)
1010         serverlogfile = argv[arg++];
1011     }
1012     else if(!strcmp("--ipv6", argv[arg])) {
1013 #ifdef ENABLE_IPV6
1014       ipv_inuse = "IPv6";
1015       use_ipv6 = TRUE;
1016 #endif
1017       arg++;
1018     }
1019     else if(!strcmp("--ipv4", argv[arg])) {
1020       /* for completeness, we support this option as well */
1021 #ifdef ENABLE_IPV6
1022       ipv_inuse = "IPv4";
1023       use_ipv6 = FALSE;
1024 #endif
1025       arg++;
1026     }
1027     else if(!strcmp("--bindonly", argv[arg])) {
1028       bind_only = TRUE;
1029       arg++;
1030     }
1031     else if(!strcmp("--port", argv[arg])) {
1032       arg++;
1033       if(argc>arg) {
1034         char *endptr;
1035         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1036         if((endptr != argv[arg] + strlen(argv[arg])) ||
1037            ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1038           fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1039                   argv[arg]);
1040           return 0;
1041         }
1042         port = curlx_ultous(ulnum);
1043         arg++;
1044       }
1045     }
1046     else if(!strcmp("--connect", argv[arg])) {
1047       /* Asked to actively connect to the specified local port instead of
1048          doing a passive server-style listening. */
1049       arg++;
1050       if(argc>arg) {
1051         char *endptr;
1052         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1053         if((endptr != argv[arg] + strlen(argv[arg])) ||
1054            (ulnum < 1025UL) || (ulnum > 65535UL)) {
1055           fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1056                   argv[arg]);
1057           return 0;
1058         }
1059         connectport = curlx_ultous(ulnum);
1060         arg++;
1061       }
1062     }
1063     else if(!strcmp("--addr", argv[arg])) {
1064       /* Set an IP address to use with --connect; otherwise use localhost */
1065       arg++;
1066       if(argc>arg) {
1067         addr = argv[arg];
1068         arg++;
1069       }
1070     }
1071     else {
1072       puts("Usage: sockfilt [option]\n"
1073            " --version\n"
1074            " --verbose\n"
1075            " --logfile [file]\n"
1076            " --pidfile [file]\n"
1077            " --ipv4\n"
1078            " --ipv6\n"
1079            " --bindonly\n"
1080            " --port [port]\n"
1081            " --connect [port]\n"
1082            " --addr [address]");
1083       return 0;
1084     }
1085   }
1086
1087 #ifdef WIN32
1088   win32_init();
1089   atexit(win32_cleanup);
1090 #endif
1091
1092   install_signal_handlers();
1093
1094 #ifdef ENABLE_IPV6
1095   if(!use_ipv6)
1096 #endif
1097     sock = socket(AF_INET, SOCK_STREAM, 0);
1098 #ifdef ENABLE_IPV6
1099   else
1100     sock = socket(AF_INET6, SOCK_STREAM, 0);
1101 #endif
1102
1103   if(CURL_SOCKET_BAD == sock) {
1104     error = SOCKERRNO;
1105     logmsg("Error creating socket: (%d) %s",
1106            error, strerror(error));
1107     write_stdout("FAIL\n", 5);
1108     goto sockfilt_cleanup;
1109   }
1110
1111   if(connectport) {
1112     /* Active mode, we should connect to the given port number */
1113     mode = ACTIVE;
1114 #ifdef ENABLE_IPV6
1115     if(!use_ipv6) {
1116 #endif
1117       memset(&me.sa4, 0, sizeof(me.sa4));
1118       me.sa4.sin_family = AF_INET;
1119       me.sa4.sin_port = htons(connectport);
1120       me.sa4.sin_addr.s_addr = INADDR_ANY;
1121       if (!addr)
1122         addr = "127.0.0.1";
1123       Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1124
1125       rc = connect(sock, &me.sa, sizeof(me.sa4));
1126 #ifdef ENABLE_IPV6
1127     }
1128     else {
1129       memset(&me.sa6, 0, sizeof(me.sa6));
1130       me.sa6.sin6_family = AF_INET6;
1131       me.sa6.sin6_port = htons(connectport);
1132       if (!addr)
1133         addr = "::1";
1134       Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1135
1136       rc = connect(sock, &me.sa, sizeof(me.sa6));
1137     }
1138 #endif /* ENABLE_IPV6 */
1139     if(rc) {
1140       error = SOCKERRNO;
1141       logmsg("Error connecting to port %hu: (%d) %s",
1142              connectport, error, strerror(error));
1143       write_stdout("FAIL\n", 5);
1144       goto sockfilt_cleanup;
1145     }
1146     logmsg("====> Client connect");
1147     msgsock = sock; /* use this as stream */
1148   }
1149   else {
1150     /* passive daemon style */
1151     sock = sockdaemon(sock, &port);
1152     if(CURL_SOCKET_BAD == sock) {
1153       write_stdout("FAIL\n", 5);
1154       goto sockfilt_cleanup;
1155     }
1156     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1157   }
1158
1159   logmsg("Running %s version", ipv_inuse);
1160
1161   if(connectport)
1162     logmsg("Connected to port %hu", connectport);
1163   else if(bind_only)
1164     logmsg("Bound without listening on port %hu", port);
1165   else
1166     logmsg("Listening on port %hu", port);
1167
1168   wrotepidfile = write_pidfile(pidname);
1169   if(!wrotepidfile) {
1170     write_stdout("FAIL\n", 5);
1171     goto sockfilt_cleanup;
1172   }
1173
1174   do {
1175     juggle_again = juggle(&msgsock, sock, &mode);
1176   } while(juggle_again);
1177
1178 sockfilt_cleanup:
1179
1180   if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1181     sclose(msgsock);
1182
1183   if(sock != CURL_SOCKET_BAD)
1184     sclose(sock);
1185
1186   if(wrotepidfile)
1187     unlink(pidname);
1188
1189   restore_signal_handlers();
1190
1191   if(got_exit_signal) {
1192     logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1193     /*
1194      * To properly set the return status of the process we
1195      * must raise the same signal SIGINT or SIGTERM that we
1196      * caught and let the old handler take care of it.
1197      */
1198     raise(exit_signal);
1199   }
1200
1201   logmsg("============> sockfilt quits");
1202   return 0;
1203 }
1204