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