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