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