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