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