sockfilt.c: zero initialize variable
[platform/upstream/curl.git] / tests / server / sockfilt.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 #include "server_setup.h"
23
24 /* Purpose
25  *
26  * 1. Accept a TCP connection on a custom port (ipv4 or ipv6), or connect
27  *    to a given (localhost) port.
28  *
29  * 2. Get commands on STDIN. Pass data on to the TCP stream.
30  *    Get data from TCP stream and pass on to STDOUT.
31  *
32  * This program is made to perform all the socket/stream/connection stuff for
33  * the test suite's (perl) FTP server. Previously the perl code did all of
34  * this by its own, but I decided to let this program do the socket layer
35  * because of several things:
36  *
37  * o We want the perl code to work with rather old perl installations, thus
38  *   we cannot use recent perl modules or features.
39  *
40  * o We want IPv6 support for systems that provide it, and doing optional IPv6
41  *   support in perl seems if not impossible so at least awkward.
42  *
43  * o We want FTP-SSL support, which means that a connection that starts with
44  *   plain sockets needs to be able to "go SSL" in the midst. This would also
45  *   require some nasty perl stuff I'd rather avoid.
46  *
47  * (Source originally based on sws.c)
48  */
49
50 /*
51  * Signal handling notes for sockfilt
52  * ----------------------------------
53  *
54  * This program is a single-threaded process.
55  *
56  * This program is intended to be highly portable and as such it must be kept as
57  * simple as possible, due to this the only signal handling mechanisms used will
58  * be those of ANSI C, and used only in the most basic form which is good enough
59  * for the purpose of this program.
60  *
61  * For the above reason and the specific needs of this program signals SIGHUP,
62  * SIGPIPE and SIGALRM will be simply ignored on systems where this can be done.
63  * If possible, signals SIGINT and SIGTERM will be handled by this program as an
64  * indication to cleanup and finish execution as soon as possible.  This will be
65  * achieved with a single signal handler 'exit_signal_handler' for both signals.
66  *
67  * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal
68  * will just set to one the global var 'got_exit_signal' storing in global var
69  * 'exit_signal' the signal that triggered this change.
70  *
71  * Nothing fancy that could introduce problems is used, the program at certain
72  * points in its normal flow checks if var 'got_exit_signal' is set and in case
73  * this is true it just makes its way out of loops and functions in structured
74  * and well behaved manner to achieve proper program cleanup and termination.
75  *
76  * Even with the above mechanism implemented it is worthwile to note that other
77  * signals might still be received, or that there might be systems on which it
78  * is not possible to trap and ignore some of the above signals.  This implies
79  * that for increased portability and reliability the program must be coded as
80  * if no signal was being ignored or handled at all.  Enjoy it!
81  */
82
83 #ifdef HAVE_SIGNAL_H
84 #include <signal.h>
85 #endif
86 #ifdef HAVE_NETINET_IN_H
87 #include <netinet/in.h>
88 #endif
89 #ifdef HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
91 #endif
92 #ifdef HAVE_NETDB_H
93 #include <netdb.h>
94 #endif
95
96 #define ENABLE_CURLX_PRINTF
97 /* make the curlx header define all printf() functions to use the curlx_*
98    versions instead */
99 #include "curlx.h" /* from the private lib dir */
100 #include "getpart.h"
101 #include "inet_pton.h"
102 #include "util.h"
103 #include "server_sockaddr.h"
104 #include "warnless.h"
105
106 /* include memdebug.h last */
107 #include "memdebug.h"
108
109 #ifdef USE_WINSOCK
110 #undef  EINTR
111 #define EINTR    4 /* errno.h value */
112 #undef  EAGAIN
113 #define EAGAIN  11 /* errno.h value */
114 #undef  ENOMEM
115 #define ENOMEM  12 /* errno.h value */
116 #undef  EINVAL
117 #define EINVAL  22 /* errno.h value */
118 #endif
119
120 #define DEFAULT_PORT 8999
121
122 #ifndef DEFAULT_LOGFILE
123 #define DEFAULT_LOGFILE "log/sockfilt.log"
124 #endif
125
126 const char *serverlogfile = DEFAULT_LOGFILE;
127
128 static bool verbose = FALSE;
129 static bool bind_only = FALSE;
130 #ifdef ENABLE_IPV6
131 static bool use_ipv6 = FALSE;
132 #endif
133 static const char *ipv_inuse = "IPv4";
134 static unsigned short port = DEFAULT_PORT;
135 static unsigned short connectport = 0; /* if non-zero, we activate this mode */
136
137 enum sockmode {
138   PASSIVE_LISTEN,    /* as a server waiting for connections */
139   PASSIVE_CONNECT,   /* as a server, connected to a client */
140   ACTIVE,            /* as a client, connected to a server */
141   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
142 };
143
144 /* do-nothing macro replacement for systems which lack siginterrupt() */
145
146 #ifndef HAVE_SIGINTERRUPT
147 #define siginterrupt(x,y) do {} while(0)
148 #endif
149
150 /* vars used to keep around previous signal handlers */
151
152 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
153
154 #ifdef SIGHUP
155 static SIGHANDLER_T old_sighup_handler  = SIG_ERR;
156 #endif
157
158 #ifdef SIGPIPE
159 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
160 #endif
161
162 #ifdef SIGALRM
163 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
164 #endif
165
166 #ifdef SIGINT
167 static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
168 #endif
169
170 #ifdef SIGTERM
171 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
172 #endif
173
174 #if defined(SIGBREAK) && defined(WIN32)
175 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
176 #endif
177
178 /* var which if set indicates that the program should finish execution */
179
180 SIG_ATOMIC_T got_exit_signal = 0;
181
182 /* if next is set indicates the first signal handled in exit_signal_handler */
183
184 static volatile int exit_signal = 0;
185
186 /* signal handler that will be triggered to indicate that the program
187   should finish its execution in a controlled manner as soon as possible.
188   The first time this is called it will set got_exit_signal to one and
189   store in exit_signal the signal that triggered its execution. */
190
191 static RETSIGTYPE exit_signal_handler(int signum)
192 {
193   int old_errno = errno;
194   if(got_exit_signal == 0) {
195     got_exit_signal = 1;
196     exit_signal = signum;
197   }
198   (void)signal(signum, exit_signal_handler);
199   errno = old_errno;
200 }
201
202 static void install_signal_handlers(void)
203 {
204 #ifdef SIGHUP
205   /* ignore SIGHUP signal */
206   if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
207     logmsg("cannot install SIGHUP handler: %s", strerror(errno));
208 #endif
209 #ifdef SIGPIPE
210   /* ignore SIGPIPE signal */
211   if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
212     logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
213 #endif
214 #ifdef SIGALRM
215   /* ignore SIGALRM signal */
216   if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
217     logmsg("cannot install SIGALRM handler: %s", strerror(errno));
218 #endif
219 #ifdef SIGINT
220   /* handle SIGINT signal with our exit_signal_handler */
221   if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
222     logmsg("cannot install SIGINT handler: %s", strerror(errno));
223   else
224     siginterrupt(SIGINT, 1);
225 #endif
226 #ifdef SIGTERM
227   /* handle SIGTERM signal with our exit_signal_handler */
228   if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
229     logmsg("cannot install SIGTERM handler: %s", strerror(errno));
230   else
231     siginterrupt(SIGTERM, 1);
232 #endif
233 #if defined(SIGBREAK) && defined(WIN32)
234   /* handle SIGBREAK signal with our exit_signal_handler */
235   if((old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler)) == SIG_ERR)
236     logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
237   else
238     siginterrupt(SIGBREAK, 1);
239 #endif
240 }
241
242 static void restore_signal_handlers(void)
243 {
244 #ifdef SIGHUP
245   if(SIG_ERR != old_sighup_handler)
246     (void)signal(SIGHUP, old_sighup_handler);
247 #endif
248 #ifdef SIGPIPE
249   if(SIG_ERR != old_sigpipe_handler)
250     (void)signal(SIGPIPE, old_sigpipe_handler);
251 #endif
252 #ifdef SIGALRM
253   if(SIG_ERR != old_sigalrm_handler)
254     (void)signal(SIGALRM, old_sigalrm_handler);
255 #endif
256 #ifdef SIGINT
257   if(SIG_ERR != old_sigint_handler)
258     (void)signal(SIGINT, old_sigint_handler);
259 #endif
260 #ifdef SIGTERM
261   if(SIG_ERR != old_sigterm_handler)
262     (void)signal(SIGTERM, old_sigterm_handler);
263 #endif
264 #if defined(SIGBREAK) && defined(WIN32)
265   if(SIG_ERR != old_sigbreak_handler)
266     (void)signal(SIGBREAK, old_sigbreak_handler);
267 #endif
268 }
269
270 #ifdef WIN32
271 /*
272  * read-wrapper to support reading from stdin on Windows.
273  */
274 static ssize_t read_wincon(int fd, void *buf, size_t count)
275 {
276   HANDLE handle = NULL;
277   DWORD mode, rcount = 0;
278   BOOL success;
279
280   if(fd == fileno(stdin)) {
281     handle = GetStdHandle(STD_INPUT_HANDLE);
282   }
283   else {
284     return read(fd, buf, count);
285   }
286
287   if(GetConsoleMode(handle, &mode)) {
288     success = ReadConsole(handle, buf, count, &rcount, NULL);
289   }
290   else {
291     success = ReadFile(handle, buf, count, &rcount, NULL);
292   }
293   if(success) {
294     return rcount;
295   }
296
297   errno = GetLastError();
298   return -1;
299 }
300 #undef  read
301 #define read(a,b,c) read_wincon(a,b,c)
302
303 /*
304  * write-wrapper to support writing to stdout and stderr on Windows.
305  */
306 static ssize_t write_wincon(int fd, const void *buf, size_t count)
307 {
308   HANDLE handle = NULL;
309   DWORD mode, wcount = 0;
310   BOOL success;
311
312   if(fd == fileno(stdout)) {
313     handle = GetStdHandle(STD_OUTPUT_HANDLE);
314   }
315   else if(fd == fileno(stderr)) {
316     handle = GetStdHandle(STD_ERROR_HANDLE);
317   }
318   else {
319     return write(fd, buf, count);
320   }
321
322   if(GetConsoleMode(handle, &mode)) {
323     success = WriteConsole(handle, buf, count, &wcount, NULL);
324   }
325   else {
326     success = WriteFile(handle, buf, count, &wcount, NULL);
327   }
328   if(success) {
329     return wcount;
330   }
331
332   errno = GetLastError();
333   return -1;
334 }
335 #undef  write
336 #define write(a,b,c) write_wincon(a,b,c)
337 #endif
338
339 /*
340  * fullread is a wrapper around the read() function. This will repeat the call
341  * to read() until it actually has read the complete number of bytes indicated
342  * in nbytes or it fails with a condition that cannot be handled with a simple
343  * retry of the read call.
344  */
345
346 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
347 {
348   int error;
349   ssize_t rc;
350   ssize_t nread = 0;
351
352   do {
353     rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
354
355     if(got_exit_signal) {
356       logmsg("signalled to die");
357       return -1;
358     }
359
360     if(rc < 0) {
361       error = errno;
362       if((error == EINTR) || (error == EAGAIN))
363         continue;
364       logmsg("reading from file descriptor: %d,", filedes);
365       logmsg("unrecoverable read() failure: (%d) %s",
366              error, strerror(error));
367       return -1;
368     }
369
370     if(rc == 0) {
371       logmsg("got 0 reading from stdin");
372       return 0;
373     }
374
375     nread += rc;
376
377   } while((size_t)nread < nbytes);
378
379   if(verbose)
380     logmsg("read %zd bytes", nread);
381
382   return nread;
383 }
384
385 /*
386  * fullwrite is a wrapper around the write() function. This will repeat the
387  * call to write() until it actually has written the complete number of bytes
388  * indicated in nbytes or it fails with a condition that cannot be handled
389  * with a simple retry of the write call.
390  */
391
392 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
393 {
394   int error;
395   ssize_t wc;
396   ssize_t nwrite = 0;
397
398   do {
399     wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
400
401     if(got_exit_signal) {
402       logmsg("signalled to die");
403       return -1;
404     }
405
406     if(wc < 0) {
407       error = errno;
408       if((error == EINTR) || (error == EAGAIN))
409         continue;
410       logmsg("writing to file descriptor: %d,", filedes);
411       logmsg("unrecoverable write() failure: (%d) %s",
412              error, strerror(error));
413       return -1;
414     }
415
416     if(wc == 0) {
417       logmsg("put 0 writing to stdout");
418       return 0;
419     }
420
421     nwrite += wc;
422
423   } while((size_t)nwrite < nbytes);
424
425   if(verbose)
426     logmsg("wrote %zd bytes", nwrite);
427
428   return nwrite;
429 }
430
431 /*
432  * read_stdin tries to read from stdin nbytes into the given buffer. This is a
433  * blocking function that will only return TRUE when nbytes have actually been
434  * read or FALSE when an unrecoverable error has been detected. Failure of this
435  * function is an indication that the sockfilt process should terminate.
436  */
437
438 static bool read_stdin(void *buffer, size_t nbytes)
439 {
440   ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
441   if(nread != (ssize_t)nbytes) {
442     logmsg("exiting...");
443     return FALSE;
444   }
445   return TRUE;
446 }
447
448 /*
449  * write_stdout tries to write to stdio nbytes from the given buffer. This is a
450  * blocking function that will only return TRUE when nbytes have actually been
451  * written or FALSE when an unrecoverable error has been detected. Failure of
452  * this function is an indication that the sockfilt process should terminate.
453  */
454
455 static bool write_stdout(const void *buffer, size_t nbytes)
456 {
457   ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
458   if(nwrite != (ssize_t)nbytes) {
459     logmsg("exiting...");
460     return FALSE;
461   }
462   return TRUE;
463 }
464
465 static void lograw(unsigned char *buffer, ssize_t len)
466 {
467   char data[120];
468   ssize_t i;
469   unsigned char *ptr = buffer;
470   char *optr = data;
471   ssize_t width=0;
472
473   for(i=0; i<len; i++) {
474     switch(ptr[i]) {
475     case '\n':
476       sprintf(optr, "\\n");
477       width += 2;
478       optr += 2;
479       break;
480     case '\r':
481       sprintf(optr, "\\r");
482       width += 2;
483       optr += 2;
484       break;
485     default:
486       sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
487       width++;
488       optr++;
489       break;
490     }
491
492     if(width>60) {
493       logmsg("'%s'", data);
494       width = 0;
495       optr = data;
496     }
497   }
498   if(width)
499     logmsg("'%s'", data);
500 }
501
502 #ifdef USE_WINSOCK
503 /*
504  * WinSock select() does not support standard file descriptors,
505  * it can only check SOCKETs. The following function is an attempt
506  * to re-create a select() function with support for other handle types.
507  *
508  * select() function with support for WINSOCK2 sockets and all
509  * other handle types supported by WaitForMultipleObjectsEx().
510  *
511  * TODO: Differentiate between read/write/except for non-SOCKET handles.
512  *
513  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx
514  * http://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx
515  */
516 static DWORD WINAPI select_ws_stdin_wait_thread(LPVOID lpParameter)
517 {
518   HANDLE handle, handles[2];
519   INPUT_RECORD inputrecord;
520   LARGE_INTEGER size, pos;
521   DWORD type, length;
522
523   handle = GetStdHandle(STD_INPUT_HANDLE);
524   handles[0] = (HANDLE) lpParameter;
525   handles[1] = handle;
526   type = GetFileType(handle);
527
528   switch(type) {
529     case FILE_TYPE_DISK:
530       while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
531             == WAIT_OBJECT_0 + 1) {
532         size.QuadPart = 0;
533         if(GetFileSizeEx(handle, &size)) {
534           pos.QuadPart = 0;
535           if(SetFilePointerEx(handle, pos, &pos, FILE_CURRENT)) {
536             if(size.QuadPart == pos.QuadPart)
537               SleepEx(100, FALSE);
538             else
539               break;
540           }
541           else
542             break;
543         }
544         else
545           break;
546       }
547       break;
548
549     case FILE_TYPE_CHAR:
550       while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
551             == WAIT_OBJECT_0 + 1) {
552         if(GetConsoleMode(handle, &length)) {
553           length = 0;
554           if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
555             if(length == 1 && inputrecord.EventType != KEY_EVENT)
556               ReadConsoleInput(handle, &inputrecord, 1, &length);
557             else
558               break;
559           }
560           else
561             break;
562         }
563         else
564           break;
565       }
566       break;
567
568     case FILE_TYPE_PIPE:
569       while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
570             == WAIT_OBJECT_0 + 1) {
571         if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
572           if(length == 0)
573             SleepEx(100, FALSE);
574           else
575             break;
576         }
577         else {
578           if(GetLastError() == ERROR_BROKEN_PIPE)
579             SleepEx(100, FALSE);
580           else
581             break;
582         }
583       }
584       break;
585
586     default:
587       WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE);
588       break;
589   }
590
591   return 0;
592 }
593 static int select_ws(int nfds, fd_set *readfds, fd_set *writefds,
594                      fd_set *exceptfds, struct timeval *timeout)
595 {
596   DWORD milliseconds, wait, idx;
597   WSAEVENT wsaevent, *wsaevents;
598   WSANETWORKEVENTS wsanetevents;
599   HANDLE handle, *handles;
600   curl_socket_t sock, *fdarr, *wsasocks;
601   long networkevents;
602   int error, fds;
603   HANDLE threadevent = NULL, threadhandle = NULL;
604   DWORD nfd = 0, wsa = 0;
605   int ret = 0;
606
607   /* check if the input value is valid */
608   if(nfds < 0) {
609     errno = EINVAL;
610     return -1;
611   }
612
613   /* check if we got descriptors, sleep in case we got none */
614   if(!nfds) {
615     Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
616     return 0;
617   }
618
619   /* allocate internal array for the original input handles */
620   fdarr = malloc(nfds * sizeof(curl_socket_t));
621   if(fdarr == NULL) {
622     errno = ENOMEM;
623     return -1;
624   }
625
626   /* allocate internal array for the internal event handles */
627   handles = malloc(nfds * sizeof(HANDLE));
628   if(handles == NULL) {
629     free(fdarr);
630     errno = ENOMEM;
631     return -1;
632   }
633
634   /* allocate internal array for the internal socket handles */
635   wsasocks = malloc(nfds * sizeof(curl_socket_t));
636   if(wsasocks == NULL) {
637     free(handles);
638     free(fdarr);
639     errno = ENOMEM;
640     return -1;
641   }
642
643   /* allocate internal array for the internal WINSOCK2 events */
644   wsaevents = malloc(nfds * sizeof(WSAEVENT));
645   if(wsaevents == NULL) {
646     free(wsasocks);
647     free(handles);
648     free(fdarr);
649     errno = ENOMEM;
650     return -1;
651   }
652
653   /* loop over the handles in the input descriptor sets */
654   for(fds = 0; fds < nfds; fds++) {
655     networkevents = 0;
656     handles[nfd] = 0;
657
658     if(FD_ISSET(fds, readfds))
659       networkevents |= FD_READ|FD_ACCEPT|FD_CLOSE;
660
661     if(FD_ISSET(fds, writefds))
662       networkevents |= FD_WRITE|FD_CONNECT;
663
664     if(FD_ISSET(fds, exceptfds))
665       networkevents |= FD_OOB|FD_CLOSE;
666
667     /* only wait for events for which we actually care */
668     if(networkevents) {
669       fdarr[nfd] = curlx_sitosk(fds);
670       if(fds == fileno(stdin)) {
671         threadevent = CreateEvent(NULL, TRUE, FALSE, NULL);
672         threadhandle = CreateThread(NULL, 0,
673                                     &select_ws_stdin_wait_thread,
674                                     threadevent, 0, NULL);
675         handles[nfd] = threadhandle;
676       }
677       else if(fds == fileno(stdout)) {
678         handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE);
679       }
680       else if(fds == fileno(stderr)) {
681         handles[nfd] = GetStdHandle(STD_ERROR_HANDLE);
682       }
683       else {
684         wsaevent = WSACreateEvent();
685         if(wsaevent != WSA_INVALID_EVENT) {
686           error = WSAEventSelect(fds, wsaevent, networkevents);
687           if(error != SOCKET_ERROR) {
688             handles[nfd] = wsaevent;
689             wsasocks[wsa] = curlx_sitosk(fds);
690             wsaevents[wsa] = wsaevent;
691             wsa++;
692           }
693           else {
694             handles[nfd] = (HANDLE) curlx_sitosk(fds);
695             WSACloseEvent(wsaevent);
696           }
697         }
698       }
699       nfd++;
700     }
701   }
702
703   /* convert struct timeval to milliseconds */
704   if(timeout) {
705     milliseconds = ((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000));
706   }
707   else {
708     milliseconds = INFINITE;
709   }
710
711   /* wait for one of the internal handles to trigger */
712   wait = WaitForMultipleObjectsEx(nfd, handles, FALSE, milliseconds, FALSE);
713
714   /* signal the event handle for the waiting thread */
715   if(threadevent) {
716     SetEvent(threadevent);
717   }
718
719   /* loop over the internal handles returned in the descriptors */
720   for(idx = 0; idx < nfd; idx++) {
721     handle = handles[idx];
722     sock = fdarr[idx];
723     fds = curlx_sktosi(sock);
724
725     /* check if the current internal handle was triggered */
726     if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= idx &&
727        WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) {
728       /* first handle stdin, stdout and stderr */
729       if(fds == fileno(stdin)) {
730         /* stdin is never ready for write or exceptional */
731         FD_CLR(sock, writefds);
732         FD_CLR(sock, exceptfds);
733       }
734       else if(fds == fileno(stdout) || fds == fileno(stderr)) {
735         /* stdout and stderr are never ready for read or exceptional */
736         FD_CLR(sock, readfds);
737         FD_CLR(sock, exceptfds);
738       }
739       else {
740         /* try to handle the event with the WINSOCK2 functions */
741         wsanetevents.lNetworkEvents = 0;
742         error = WSAEnumNetworkEvents(fds, handle, &wsanetevents);
743         if(error != SOCKET_ERROR) {
744           /* remove from descriptor set if not ready for read/accept/close */
745           if(!(wsanetevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE)))
746             FD_CLR(sock, readfds);
747
748           /* remove from descriptor set if not ready for write/connect */
749           if(!(wsanetevents.lNetworkEvents & (FD_WRITE|FD_CONNECT)))
750             FD_CLR(sock, writefds);
751
752           /* HACK:
753            * use exceptfds together with readfds to signal
754            * that the connection was closed by the client.
755            *
756            * Reason: FD_CLOSE is only signaled once, sometimes
757            * at the same time as FD_READ with data being available.
758            * This means that recv/sread is not reliable to detect
759            * that the connection is closed.
760            */
761           /* remove from descriptor set if not exceptional */
762           if(!(wsanetevents.lNetworkEvents & (FD_OOB|FD_CLOSE)))
763             FD_CLR(sock, exceptfds);
764         }
765       }
766
767       /* check if the event has not been filtered using specific tests */
768       if(FD_ISSET(sock, readfds) || FD_ISSET(sock, writefds) ||
769          FD_ISSET(sock, exceptfds)) {
770         ret++;
771       }
772     }
773     else {
774       /* remove from all descriptor sets since this handle did not trigger */
775       FD_CLR(sock, readfds);
776       FD_CLR(sock, writefds);
777       FD_CLR(sock, exceptfds);
778     }
779   }
780
781   for(idx = 0; idx < wsa; idx++) {
782     WSAEventSelect(wsasocks[idx], NULL, 0);
783     WSACloseEvent(wsaevents[idx]);
784   }
785
786   if(threadhandle) {
787     WaitForSingleObject(threadhandle, INFINITE);
788     CloseHandle(threadhandle);
789   }
790   if(threadevent) {
791     CloseHandle(threadevent);
792   }
793
794   free(wsaevents);
795   free(wsasocks);
796   free(handles);
797   free(fdarr);
798
799   return ret;
800 }
801 #define select(a,b,c,d,e) select_ws(a,b,c,d,e)
802 #endif  /* USE_WINSOCK */
803
804 /*
805   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
806
807   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
808   accept()
809 */
810 static bool juggle(curl_socket_t *sockfdp,
811                    curl_socket_t listenfd,
812                    enum sockmode *mode)
813 {
814   struct timeval timeout;
815   fd_set fds_read;
816   fd_set fds_write;
817   fd_set fds_err;
818   curl_socket_t sockfd = CURL_SOCKET_BAD;
819   int maxfd = -99;
820   ssize_t rc;
821   ssize_t nread_socket;
822   ssize_t bytes_written;
823   ssize_t buffer_len;
824   int error = 0;
825
826  /* 'buffer' is this excessively large only to be able to support things like
827     test 1003 which tests exceedingly large server response lines */
828   unsigned char buffer[17010];
829   char data[16];
830
831   if(got_exit_signal) {
832     logmsg("signalled to die, exiting...");
833     return FALSE;
834   }
835
836 #ifdef HAVE_GETPPID
837   /* As a last resort, quit if sockfilt process becomes orphan. Just in case
838      parent ftpserver process has died without killing its sockfilt children */
839   if(getppid() <= 1) {
840     logmsg("process becomes orphan, exiting");
841     return FALSE;
842   }
843 #endif
844
845   timeout.tv_sec = 120;
846   timeout.tv_usec = 0;
847
848   FD_ZERO(&fds_read);
849   FD_ZERO(&fds_write);
850   FD_ZERO(&fds_err);
851
852   FD_SET((curl_socket_t)fileno(stdin), &fds_read);
853
854   switch(*mode) {
855
856   case PASSIVE_LISTEN:
857
858     /* server mode */
859     sockfd = listenfd;
860     /* there's always a socket to wait for */
861     FD_SET(sockfd, &fds_read);
862     maxfd = (int)sockfd;
863     break;
864
865   case PASSIVE_CONNECT:
866
867     sockfd = *sockfdp;
868     if(CURL_SOCKET_BAD == sockfd) {
869       /* eeek, we are supposedly connected and then this cannot be -1 ! */
870       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
871       maxfd = 0; /* stdin */
872     }
873     else {
874       /* there's always a socket to wait for */
875       FD_SET(sockfd, &fds_read);
876 #ifdef USE_WINSOCK
877       FD_SET(sockfd, &fds_err);
878 #endif
879       maxfd = (int)sockfd;
880     }
881     break;
882
883   case ACTIVE:
884
885     sockfd = *sockfdp;
886     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
887     if(CURL_SOCKET_BAD != sockfd) {
888       FD_SET(sockfd, &fds_read);
889 #ifdef USE_WINSOCK
890       FD_SET(sockfd, &fds_err);
891 #endif
892       maxfd = (int)sockfd;
893     }
894     else {
895       logmsg("No socket to read on");
896       maxfd = 0;
897     }
898     break;
899
900   case ACTIVE_DISCONNECT:
901
902     logmsg("disconnected, no socket to read on");
903     maxfd = 0;
904     sockfd = CURL_SOCKET_BAD;
905     break;
906
907   } /* switch(*mode) */
908
909
910   do {
911
912     /* select() blocking behavior call on blocking descriptors please */
913
914     rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
915
916     if(got_exit_signal) {
917       logmsg("signalled to die, exiting...");
918       return FALSE;
919     }
920
921   } while((rc == -1) && ((error = errno) == EINTR));
922
923   if(rc < 0) {
924     logmsg("select() failed with error: (%d) %s",
925            error, strerror(error));
926     return FALSE;
927   }
928
929   if(rc == 0)
930     /* timeout */
931     return TRUE;
932
933
934   if(FD_ISSET(fileno(stdin), &fds_read)) {
935     /* read from stdin, commands/data to be dealt with and possibly passed on
936        to the socket
937
938        protocol:
939
940        4 letter command + LF [mandatory]
941
942        4-digit hexadecimal data length + LF [if the command takes data]
943        data                       [the data being as long as set above]
944
945        Commands:
946
947        DATA - plain pass-thru data
948     */
949
950     if(!read_stdin(buffer, 5))
951       return FALSE;
952
953     logmsg("Received %c%c%c%c (on stdin)",
954            buffer[0], buffer[1], buffer[2], buffer[3] );
955
956     if(!memcmp("PING", buffer, 4)) {
957       /* send reply on stdout, just proving we are alive */
958       if(!write_stdout("PONG\n", 5))
959         return FALSE;
960     }
961
962     else if(!memcmp("PORT", buffer, 4)) {
963       /* Question asking us what PORT number we are listening to.
964          Replies to PORT with "IPv[num]/[port]" */
965       sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
966       buffer_len = (ssize_t)strlen((char *)buffer);
967       snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
968       if(!write_stdout(data, 10))
969         return FALSE;
970       if(!write_stdout(buffer, buffer_len))
971         return FALSE;
972     }
973     else if(!memcmp("QUIT", buffer, 4)) {
974       /* just die */
975       logmsg("quits");
976       return FALSE;
977     }
978     else if(!memcmp("DATA", buffer, 4)) {
979       /* data IN => data OUT */
980
981       if(!read_stdin(buffer, 5))
982         return FALSE;
983
984       buffer[5] = '\0';
985
986       buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
987       if (buffer_len > (ssize_t)sizeof(buffer)) {
988         logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
989                "(%zd bytes)", sizeof(buffer), buffer_len);
990         return FALSE;
991       }
992       logmsg("> %zd bytes data, server => client", buffer_len);
993
994       if(!read_stdin(buffer, buffer_len))
995         return FALSE;
996
997       lograw(buffer, buffer_len);
998
999       if(*mode == PASSIVE_LISTEN) {
1000         logmsg("*** We are disconnected!");
1001         if(!write_stdout("DISC\n", 5))
1002           return FALSE;
1003       }
1004       else {
1005         /* send away on the socket */
1006         bytes_written = swrite(sockfd, buffer, buffer_len);
1007         if(bytes_written != buffer_len) {
1008           logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
1009                  buffer_len, bytes_written);
1010         }
1011       }
1012     }
1013     else if(!memcmp("DISC", buffer, 4)) {
1014       /* disconnect! */
1015       if(!write_stdout("DISC\n", 5))
1016         return FALSE;
1017       if(sockfd != CURL_SOCKET_BAD) {
1018         logmsg("====> Client forcibly disconnected");
1019         sclose(sockfd);
1020         *sockfdp = CURL_SOCKET_BAD;
1021         if(*mode == PASSIVE_CONNECT)
1022           *mode = PASSIVE_LISTEN;
1023         else
1024           *mode = ACTIVE_DISCONNECT;
1025       }
1026       else
1027         logmsg("attempt to close already dead connection");
1028       return TRUE;
1029     }
1030   }
1031
1032
1033   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
1034
1035     curl_socket_t newfd = CURL_SOCKET_BAD; /* newly accepted socket */
1036
1037     if(*mode == PASSIVE_LISTEN) {
1038       /* there's no stream set up yet, this is an indication that there's a
1039          client connecting. */
1040       newfd = accept(sockfd, NULL, NULL);
1041       if(CURL_SOCKET_BAD == newfd) {
1042         error = SOCKERRNO;
1043         logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s",
1044                sockfd, error, strerror(error));
1045       }
1046       else {
1047         logmsg("====> Client connect");
1048         if(!write_stdout("CNCT\n", 5))
1049           return FALSE;
1050         *sockfdp = newfd; /* store the new socket */
1051         *mode = PASSIVE_CONNECT; /* we have connected */
1052       }
1053       return TRUE;
1054     }
1055
1056     /* read from socket, pass on data to stdout */
1057     nread_socket = sread(sockfd, buffer, sizeof(buffer));
1058
1059     if(nread_socket > 0) {
1060       snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
1061       if(!write_stdout(data, 10))
1062         return FALSE;
1063       if(!write_stdout(buffer, nread_socket))
1064         return FALSE;
1065
1066       logmsg("< %zd bytes data, client => server", nread_socket);
1067       lograw(buffer, nread_socket);
1068     }
1069
1070     if(nread_socket <= 0
1071 #ifdef USE_WINSOCK
1072        || FD_ISSET(sockfd, &fds_err)
1073 #endif
1074        ) {
1075       logmsg("====> Client disconnect");
1076       if(!write_stdout("DISC\n", 5))
1077         return FALSE;
1078       sclose(sockfd);
1079       *sockfdp = CURL_SOCKET_BAD;
1080       if(*mode == PASSIVE_CONNECT)
1081         *mode = PASSIVE_LISTEN;
1082       else
1083         *mode = ACTIVE_DISCONNECT;
1084       return TRUE;
1085     }
1086   }
1087
1088   return TRUE;
1089 }
1090
1091 static curl_socket_t sockdaemon(curl_socket_t sock,
1092                                 unsigned short *listenport)
1093 {
1094   /* passive daemon style */
1095   srvr_sockaddr_union_t listener;
1096   int flag;
1097   int rc;
1098   int totdelay = 0;
1099   int maxretr = 10;
1100   int delay= 20;
1101   int attempt = 0;
1102   int error = 0;
1103
1104   do {
1105     attempt++;
1106     flag = 1;
1107     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1108          (void *)&flag, sizeof(flag));
1109     if(rc) {
1110       error = SOCKERRNO;
1111       logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1112              error, strerror(error));
1113       if(maxretr) {
1114         rc = wait_ms(delay);
1115         if(rc) {
1116           /* should not happen */
1117           error = errno;
1118           logmsg("wait_ms() failed with error: (%d) %s",
1119                  error, strerror(error));
1120           sclose(sock);
1121           return CURL_SOCKET_BAD;
1122         }
1123         if(got_exit_signal) {
1124           logmsg("signalled to die, exiting...");
1125           sclose(sock);
1126           return CURL_SOCKET_BAD;
1127         }
1128         totdelay += delay;
1129         delay *= 2; /* double the sleep for next attempt */
1130       }
1131     }
1132   } while(rc && maxretr--);
1133
1134   if(rc) {
1135     logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
1136            attempt, totdelay, error, strerror(error));
1137     logmsg("Continuing anyway...");
1138   }
1139
1140   /* When the specified listener port is zero, it is actually a
1141      request to let the system choose a non-zero available port. */
1142
1143 #ifdef ENABLE_IPV6
1144   if(!use_ipv6) {
1145 #endif
1146     memset(&listener.sa4, 0, sizeof(listener.sa4));
1147     listener.sa4.sin_family = AF_INET;
1148     listener.sa4.sin_addr.s_addr = INADDR_ANY;
1149     listener.sa4.sin_port = htons(*listenport);
1150     rc = bind(sock, &listener.sa, sizeof(listener.sa4));
1151 #ifdef ENABLE_IPV6
1152   }
1153   else {
1154     memset(&listener.sa6, 0, sizeof(listener.sa6));
1155     listener.sa6.sin6_family = AF_INET6;
1156     listener.sa6.sin6_addr = in6addr_any;
1157     listener.sa6.sin6_port = htons(*listenport);
1158     rc = bind(sock, &listener.sa, sizeof(listener.sa6));
1159   }
1160 #endif /* ENABLE_IPV6 */
1161   if(rc) {
1162     error = SOCKERRNO;
1163     logmsg("Error binding socket on port %hu: (%d) %s",
1164            *listenport, error, strerror(error));
1165     sclose(sock);
1166     return CURL_SOCKET_BAD;
1167   }
1168
1169   if(!*listenport) {
1170     /* The system was supposed to choose a port number, figure out which
1171        port we actually got and update the listener port value with it. */
1172     curl_socklen_t la_size;
1173     srvr_sockaddr_union_t localaddr;
1174 #ifdef ENABLE_IPV6
1175     if(!use_ipv6)
1176 #endif
1177       la_size = sizeof(localaddr.sa4);
1178 #ifdef ENABLE_IPV6
1179     else
1180       la_size = sizeof(localaddr.sa6);
1181 #endif
1182     memset(&localaddr.sa, 0, (size_t)la_size);
1183     if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
1184       error = SOCKERRNO;
1185       logmsg("getsockname() failed with error: (%d) %s",
1186              error, strerror(error));
1187       sclose(sock);
1188       return CURL_SOCKET_BAD;
1189     }
1190     switch (localaddr.sa.sa_family) {
1191     case AF_INET:
1192       *listenport = ntohs(localaddr.sa4.sin_port);
1193       break;
1194 #ifdef ENABLE_IPV6
1195     case AF_INET6:
1196       *listenport = ntohs(localaddr.sa6.sin6_port);
1197       break;
1198 #endif
1199     default:
1200       break;
1201     }
1202     if(!*listenport) {
1203       /* Real failure, listener port shall not be zero beyond this point. */
1204       logmsg("Apparently getsockname() succeeded, with listener port zero.");
1205       logmsg("A valid reason for this failure is a binary built without");
1206       logmsg("proper network library linkage. This might not be the only");
1207       logmsg("reason, but double check it before anything else.");
1208       sclose(sock);
1209       return CURL_SOCKET_BAD;
1210     }
1211   }
1212
1213   /* bindonly option forces no listening */
1214   if(bind_only) {
1215     logmsg("instructed to bind port without listening");
1216     return sock;
1217   }
1218
1219   /* start accepting connections */
1220   rc = listen(sock, 5);
1221   if(0 != rc) {
1222     error = SOCKERRNO;
1223     logmsg("listen(%d, 5) failed with error: (%d) %s",
1224            sock, error, strerror(error));
1225     sclose(sock);
1226     return CURL_SOCKET_BAD;
1227   }
1228
1229   return sock;
1230 }
1231
1232
1233 int main(int argc, char *argv[])
1234 {
1235   srvr_sockaddr_union_t me;
1236   curl_socket_t sock = CURL_SOCKET_BAD;
1237   curl_socket_t msgsock = CURL_SOCKET_BAD;
1238   int wrotepidfile = 0;
1239   char *pidname= (char *)".sockfilt.pid";
1240   bool juggle_again;
1241   int rc;
1242   int error;
1243   int arg=1;
1244   enum sockmode mode = PASSIVE_LISTEN; /* default */
1245   const char *addr = NULL;
1246
1247   while(argc>arg) {
1248     if(!strcmp("--version", argv[arg])) {
1249       printf("sockfilt IPv4%s\n",
1250 #ifdef ENABLE_IPV6
1251              "/IPv6"
1252 #else
1253              ""
1254 #endif
1255              );
1256       return 0;
1257     }
1258     else if(!strcmp("--verbose", argv[arg])) {
1259       verbose = TRUE;
1260       arg++;
1261     }
1262     else if(!strcmp("--pidfile", argv[arg])) {
1263       arg++;
1264       if(argc>arg)
1265         pidname = argv[arg++];
1266     }
1267     else if(!strcmp("--logfile", argv[arg])) {
1268       arg++;
1269       if(argc>arg)
1270         serverlogfile = argv[arg++];
1271     }
1272     else if(!strcmp("--ipv6", argv[arg])) {
1273 #ifdef ENABLE_IPV6
1274       ipv_inuse = "IPv6";
1275       use_ipv6 = TRUE;
1276 #endif
1277       arg++;
1278     }
1279     else if(!strcmp("--ipv4", argv[arg])) {
1280       /* for completeness, we support this option as well */
1281 #ifdef ENABLE_IPV6
1282       ipv_inuse = "IPv4";
1283       use_ipv6 = FALSE;
1284 #endif
1285       arg++;
1286     }
1287     else if(!strcmp("--bindonly", argv[arg])) {
1288       bind_only = TRUE;
1289       arg++;
1290     }
1291     else if(!strcmp("--port", argv[arg])) {
1292       arg++;
1293       if(argc>arg) {
1294         char *endptr;
1295         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1296         if((endptr != argv[arg] + strlen(argv[arg])) ||
1297            ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
1298           fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
1299                   argv[arg]);
1300           return 0;
1301         }
1302         port = curlx_ultous(ulnum);
1303         arg++;
1304       }
1305     }
1306     else if(!strcmp("--connect", argv[arg])) {
1307       /* Asked to actively connect to the specified local port instead of
1308          doing a passive server-style listening. */
1309       arg++;
1310       if(argc>arg) {
1311         char *endptr;
1312         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1313         if((endptr != argv[arg] + strlen(argv[arg])) ||
1314            (ulnum < 1025UL) || (ulnum > 65535UL)) {
1315           fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
1316                   argv[arg]);
1317           return 0;
1318         }
1319         connectport = curlx_ultous(ulnum);
1320         arg++;
1321       }
1322     }
1323     else if(!strcmp("--addr", argv[arg])) {
1324       /* Set an IP address to use with --connect; otherwise use localhost */
1325       arg++;
1326       if(argc>arg) {
1327         addr = argv[arg];
1328         arg++;
1329       }
1330     }
1331     else {
1332       puts("Usage: sockfilt [option]\n"
1333            " --version\n"
1334            " --verbose\n"
1335            " --logfile [file]\n"
1336            " --pidfile [file]\n"
1337            " --ipv4\n"
1338            " --ipv6\n"
1339            " --bindonly\n"
1340            " --port [port]\n"
1341            " --connect [port]\n"
1342            " --addr [address]");
1343       return 0;
1344     }
1345   }
1346
1347 #ifdef WIN32
1348   win32_init();
1349   atexit(win32_cleanup);
1350
1351   setmode(fileno(stdin), O_BINARY);
1352   setmode(fileno(stdout), O_BINARY);
1353   setmode(fileno(stderr), O_BINARY);
1354 #endif
1355
1356   install_signal_handlers();
1357
1358 #ifdef ENABLE_IPV6
1359   if(!use_ipv6)
1360 #endif
1361     sock = socket(AF_INET, SOCK_STREAM, 0);
1362 #ifdef ENABLE_IPV6
1363   else
1364     sock = socket(AF_INET6, SOCK_STREAM, 0);
1365 #endif
1366
1367   if(CURL_SOCKET_BAD == sock) {
1368     error = SOCKERRNO;
1369     logmsg("Error creating socket: (%d) %s",
1370            error, strerror(error));
1371     write_stdout("FAIL\n", 5);
1372     goto sockfilt_cleanup;
1373   }
1374
1375   if(connectport) {
1376     /* Active mode, we should connect to the given port number */
1377     mode = ACTIVE;
1378 #ifdef ENABLE_IPV6
1379     if(!use_ipv6) {
1380 #endif
1381       memset(&me.sa4, 0, sizeof(me.sa4));
1382       me.sa4.sin_family = AF_INET;
1383       me.sa4.sin_port = htons(connectport);
1384       me.sa4.sin_addr.s_addr = INADDR_ANY;
1385       if (!addr)
1386         addr = "127.0.0.1";
1387       Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
1388
1389       rc = connect(sock, &me.sa, sizeof(me.sa4));
1390 #ifdef ENABLE_IPV6
1391     }
1392     else {
1393       memset(&me.sa6, 0, sizeof(me.sa6));
1394       me.sa6.sin6_family = AF_INET6;
1395       me.sa6.sin6_port = htons(connectport);
1396       if (!addr)
1397         addr = "::1";
1398       Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
1399
1400       rc = connect(sock, &me.sa, sizeof(me.sa6));
1401     }
1402 #endif /* ENABLE_IPV6 */
1403     if(rc) {
1404       error = SOCKERRNO;
1405       logmsg("Error connecting to port %hu: (%d) %s",
1406              connectport, error, strerror(error));
1407       write_stdout("FAIL\n", 5);
1408       goto sockfilt_cleanup;
1409     }
1410     logmsg("====> Client connect");
1411     msgsock = sock; /* use this as stream */
1412   }
1413   else {
1414     /* passive daemon style */
1415     sock = sockdaemon(sock, &port);
1416     if(CURL_SOCKET_BAD == sock) {
1417       write_stdout("FAIL\n", 5);
1418       goto sockfilt_cleanup;
1419     }
1420     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1421   }
1422
1423   logmsg("Running %s version", ipv_inuse);
1424
1425   if(connectport)
1426     logmsg("Connected to port %hu", connectport);
1427   else if(bind_only)
1428     logmsg("Bound without listening on port %hu", port);
1429   else
1430     logmsg("Listening on port %hu", port);
1431
1432   wrotepidfile = write_pidfile(pidname);
1433   if(!wrotepidfile) {
1434     write_stdout("FAIL\n", 5);
1435     goto sockfilt_cleanup;
1436   }
1437
1438   do {
1439     juggle_again = juggle(&msgsock, sock, &mode);
1440   } while(juggle_again);
1441
1442 sockfilt_cleanup:
1443
1444   if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1445     sclose(msgsock);
1446
1447   if(sock != CURL_SOCKET_BAD)
1448     sclose(sock);
1449
1450   if(wrotepidfile)
1451     unlink(pidname);
1452
1453   restore_signal_handlers();
1454
1455   if(got_exit_signal) {
1456     logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1457     /*
1458      * To properly set the return status of the process we
1459      * must raise the same signal SIGINT or SIGTERM that we
1460      * caught and let the old handler take care of it.
1461      */
1462     raise(exit_signal);
1463   }
1464
1465   logmsg("============> sockfilt quits");
1466   return 0;
1467 }
1468