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