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