1/***************************************************************************
2 *                                  _   _ ____  _
3 *  Project                     ___| | | |  _ \| |
4 *                             / __| | | | |_) | |
5 *                            | (__| |_| |  _ <| |___
6 *                             \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2011, 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
23/* Purpose
24 *
25 * 1. Accept a TCP connection on a custom port (ipv4 or ipv6), or connect
26 *    to a given (localhost) port.
27 *
28 * 2. Get commands on STDIN. Pass data on to the TCP stream.
29 *    Get data from TCP stream and pass on to STDOUT.
30 *
31 * This program is made to perform all the socket/stream/connection stuff for
32 * the test suite's (perl) FTP server. Previously the perl code did all of
33 * this by its own, but I decided to let this program do the socket layer
34 * because of several things:
35 *
36 * o We want the perl code to work with rather old perl installations, thus
37 *   we cannot use recent perl modules or features.
38 *
39 * o We want IPv6 support for systems that provide it, and doing optional IPv6
40 *   support in perl seems if not impossible so at least awkward.
41 *
42 * o We want FTP-SSL support, which means that a connection that starts with
43 *   plain sockets needs to be able to "go SSL" in the midst. This would also
44 *   require some nasty perl stuff I'd rather avoid.
45 *
46 * (Source originally based on sws.c)
47 */
48
49/*
50 * Signal handling notes for sockfilt
51 * ----------------------------------
52 *
53 * This program is a single-threaded process.
54 *
55 * This program is intended to be highly portable and as such it must be kept as
56 * simple as possible, due to this the only signal handling mechanisms used will
57 * be those of ANSI C, and used only in the most basic form which is good enough
58 * for the purpose of this program.
59 *
60 * For the above reason and the specific needs of this program signals SIGHUP,
61 * SIGPIPE and SIGALRM will be simply ignored on systems where this can be done.
62 * If possible, signals SIGINT and SIGTERM will be handled by this program as an
63 * indication to cleanup and finish execution as soon as possible.  This will be
64 * achieved with a single signal handler 'exit_signal_handler' for both signals.
65 *
66 * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal
67 * will just set to one the global var 'got_exit_signal' storing in global var
68 * 'exit_signal' the signal that triggered this change.
69 *
70 * Nothing fancy that could introduce problems is used, the program at certain
71 * points in its normal flow checks if var 'got_exit_signal' is set and in case
72 * this is true it just makes its way out of loops and functions in structured
73 * and well behaved manner to achieve proper program cleanup and termination.
74 *
75 * Even with the above mechanism implemented it is worthwile to note that other
76 * signals might still be received, or that there might be systems on which it
77 * is not possible to trap and ignore some of the above signals.  This implies
78 * that for increased portability and reliability the program must be coded as
79 * if no signal was being ignored or handled at all.  Enjoy it!
80 */
81
82#define CURL_NO_OLDIES
83
84#include "setup.h" /* portability help from the lib directory */
85
86#ifdef HAVE_SIGNAL_H
87#include <signal.h>
88#endif
89#ifdef HAVE_UNISTD_H
90#include <unistd.h>
91#endif
92#ifdef HAVE_SYS_SOCKET_H
93#include <sys/socket.h>
94#endif
95#ifdef HAVE_NETINET_IN_H
96#include <netinet/in.h>
97#endif
98#ifdef HAVE_ARPA_INET_H
99#include <arpa/inet.h>
100#endif
101#ifdef HAVE_NETDB_H
102#include <netdb.h>
103#endif
104
105#define ENABLE_CURLX_PRINTF
106/* make the curlx header define all printf() functions to use the curlx_*
107   versions instead */
108#include "curlx.h" /* from the private lib dir */
109#include "getpart.h"
110#include "inet_pton.h"
111#include "util.h"
112#include "server_sockaddr.h"
113
114/* include memdebug.h last */
115#include "memdebug.h"
116
117#define DEFAULT_PORT 8999
118
119#ifndef DEFAULT_LOGFILE
120#define DEFAULT_LOGFILE "log/sockfilt.log"
121#endif
122
123const char *serverlogfile = DEFAULT_LOGFILE;
124
125static bool verbose = FALSE;
126static bool bind_only = FALSE;
127#ifdef ENABLE_IPV6
128static bool use_ipv6 = FALSE;
129#endif
130static const char *ipv_inuse = "IPv4";
131static unsigned short port = DEFAULT_PORT;
132static unsigned short connectport = 0; /* if non-zero, we activate this mode */
133
134enum sockmode {
135  PASSIVE_LISTEN,    /* as a server waiting for connections */
136  PASSIVE_CONNECT,   /* as a server, connected to a client */
137  ACTIVE,            /* as a client, connected to a server */
138  ACTIVE_DISCONNECT  /* as a client, disconnected from server */
139};
140
141/* do-nothing macro replacement for systems which lack siginterrupt() */
142
143#ifndef HAVE_SIGINTERRUPT
144#define siginterrupt(x,y) do {} while(0)
145#endif
146
147/* vars used to keep around previous signal handlers */
148
149typedef RETSIGTYPE (*SIGHANDLER_T)(int);
150
151#ifdef SIGHUP
152static SIGHANDLER_T old_sighup_handler  = SIG_ERR;
153#endif
154
155#ifdef SIGPIPE
156static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
157#endif
158
159#ifdef SIGALRM
160static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
161#endif
162
163#ifdef SIGINT
164static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
165#endif
166
167#ifdef SIGTERM
168static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
169#endif
170
171/* var which if set indicates that the program should finish execution */
172
173SIG_ATOMIC_T got_exit_signal = 0;
174
175/* if next is set indicates the first signal handled in exit_signal_handler */
176
177static volatile int exit_signal = 0;
178
179/* signal handler that will be triggered to indicate that the program
180  should finish its execution in a controlled manner as soon as possible.
181  The first time this is called it will set got_exit_signal to one and
182  store in exit_signal the signal that triggered its execution. */
183
184static RETSIGTYPE exit_signal_handler(int signum)
185{
186  int old_errno = ERRNO;
187  if(got_exit_signal == 0) {
188    got_exit_signal = 1;
189    exit_signal = signum;
190  }
191  (void)signal(signum, exit_signal_handler);
192  SET_ERRNO(old_errno);
193}
194
195static void install_signal_handlers(void)
196{
197#ifdef SIGHUP
198  /* ignore SIGHUP signal */
199  if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
200    logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
201#endif
202#ifdef SIGPIPE
203  /* ignore SIGPIPE signal */
204  if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
205    logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
206#endif
207#ifdef SIGALRM
208  /* ignore SIGALRM signal */
209  if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
210    logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
211#endif
212#ifdef SIGINT
213  /* handle SIGINT signal with our exit_signal_handler */
214  if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
215    logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
216  else
217    siginterrupt(SIGINT, 1);
218#endif
219#ifdef SIGTERM
220  /* handle SIGTERM signal with our exit_signal_handler */
221  if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
222    logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
223  else
224    siginterrupt(SIGTERM, 1);
225#endif
226}
227
228static void restore_signal_handlers(void)
229{
230#ifdef SIGHUP
231  if(SIG_ERR != old_sighup_handler)
232    (void)signal(SIGHUP, old_sighup_handler);
233#endif
234#ifdef SIGPIPE
235  if(SIG_ERR != old_sigpipe_handler)
236    (void)signal(SIGPIPE, old_sigpipe_handler);
237#endif
238#ifdef SIGALRM
239  if(SIG_ERR != old_sigalrm_handler)
240    (void)signal(SIGALRM, old_sigalrm_handler);
241#endif
242#ifdef SIGINT
243  if(SIG_ERR != old_sigint_handler)
244    (void)signal(SIGINT, old_sigint_handler);
245#endif
246#ifdef SIGTERM
247  if(SIG_ERR != old_sigterm_handler)
248    (void)signal(SIGTERM, old_sigterm_handler);
249#endif
250}
251
252/*
253 * fullread is a wrapper around the read() function. This will repeat the call
254 * to read() until it actually has read the complete number of bytes indicated
255 * in nbytes or it fails with a condition that cannot be handled with a simple
256 * retry of the read call.
257 */
258
259static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
260{
261  int error;
262  ssize_t rc;
263  ssize_t nread = 0;
264
265  do {
266    rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
267
268    if(got_exit_signal) {
269      logmsg("signalled to die");
270      return -1;
271    }
272
273    if(rc < 0) {
274      error = ERRNO;
275      if((error == EINTR) || (error == EAGAIN))
276        continue;
277      logmsg("unrecoverable read() failure: %s", strerror(error));
278      return -1;
279    }
280
281    if(rc == 0) {
282      logmsg("got 0 reading from stdin");
283      return 0;
284    }
285
286    nread += rc;
287
288  } while((size_t)nread < nbytes);
289
290  if(verbose)
291    logmsg("read %zd bytes", nread);
292
293  return nread;
294}
295
296/*
297 * fullwrite is a wrapper around the write() function. This will repeat the
298 * call to write() until it actually has written the complete number of bytes
299 * indicated in nbytes or it fails with a condition that cannot be handled
300 * with a simple retry of the write call.
301 */
302
303static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
304{
305  int error;
306  ssize_t wc;
307  ssize_t nwrite = 0;
308
309  do {
310    wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
311
312    if(got_exit_signal) {
313      logmsg("signalled to die");
314      return -1;
315    }
316
317    if(wc < 0) {
318      error = ERRNO;
319      if((error == EINTR) || (error == EAGAIN))
320        continue;
321      logmsg("unrecoverable write() failure: %s", strerror(error));
322      return -1;
323    }
324
325    if(wc == 0) {
326      logmsg("put 0 writing to stdout");
327      return 0;
328    }
329
330    nwrite += wc;
331
332  } while((size_t)nwrite < nbytes);
333
334  if(verbose)
335    logmsg("wrote %zd bytes", nwrite);
336
337  return nwrite;
338}
339
340/*
341 * read_stdin tries to read from stdin nbytes into the given buffer. This is a
342 * blocking function that will only return TRUE when nbytes have actually been
343 * read or FALSE when an unrecoverable error has been detected. Failure of this
344 * function is an indication that the sockfilt process should terminate.
345 */
346
347static bool read_stdin(void *buffer, size_t nbytes)
348{
349  ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
350  if(nread != (ssize_t)nbytes) {
351    logmsg("exiting...");
352    return FALSE;
353  }
354  return TRUE;
355}
356
357/*
358 * write_stdout tries to write to stdio nbytes from the given buffer. This is a
359 * blocking function that will only return TRUE when nbytes have actually been
360 * written or FALSE when an unrecoverable error has been detected. Failure of
361 * this function is an indication that the sockfilt process should terminate.
362 */
363
364static bool write_stdout(const void *buffer, size_t nbytes)
365{
366  ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
367  if(nwrite != (ssize_t)nbytes) {
368    logmsg("exiting...");
369    return FALSE;
370  }
371  return TRUE;
372}
373
374static void lograw(unsigned char *buffer, ssize_t len)
375{
376  char data[120];
377  ssize_t i;
378  unsigned char *ptr = buffer;
379  char *optr = data;
380  ssize_t width=0;
381
382  for(i=0; i<len; i++) {
383    switch(ptr[i]) {
384    case '\n':
385      sprintf(optr, "\\n");
386      width += 2;
387      optr += 2;
388      break;
389    case '\r':
390      sprintf(optr, "\\r");
391      width += 2;
392      optr += 2;
393      break;
394    default:
395      sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
396      width++;
397      optr++;
398      break;
399    }
400
401    if(width>60) {
402      logmsg("'%s'", data);
403      width = 0;
404      optr = data;
405    }
406  }
407  if(width)
408    logmsg("'%s'", data);
409}
410
411/*
412  sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
413
414  if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
415  accept()
416*/
417static bool juggle(curl_socket_t *sockfdp,
418                   curl_socket_t listenfd,
419                   enum sockmode *mode)
420{
421  struct timeval timeout;
422  fd_set fds_read;
423  fd_set fds_write;
424  fd_set fds_err;
425  curl_socket_t sockfd = CURL_SOCKET_BAD;
426  curl_socket_t maxfd = CURL_SOCKET_BAD;
427  ssize_t rc;
428  ssize_t nread_socket;
429  ssize_t bytes_written;
430  ssize_t buffer_len;
431  int error = 0;
432
433 /* 'buffer' is this excessively large only to be able to support things like
434    test 1003 which tests exceedingly large server response lines */
435  unsigned char buffer[17010];
436  char data[16];
437
438  if(got_exit_signal) {
439    logmsg("signalled to die, exiting...");
440    return FALSE;
441  }
442
443#ifdef HAVE_GETPPID
444  /* As a last resort, quit if sockfilt process becomes orphan. Just in case
445     parent ftpserver process has died without killing its sockfilt children */
446  if(getppid() <= 1) {
447    logmsg("process becomes orphan, exiting");
448    return FALSE;
449  }
450#endif
451
452  timeout.tv_sec = 120;
453  timeout.tv_usec = 0;
454
455  FD_ZERO(&fds_read);
456  FD_ZERO(&fds_write);
457  FD_ZERO(&fds_err);
458
459#ifdef USE_WINSOCK
460  /*
461  ** WinSock select() does not support standard file descriptors,
462  ** it can only check SOCKETs. Since this program in its current
463  ** state will not work on WinSock based systems, next line is
464  ** commented out to allow warning-free compilation awaiting the
465  ** day it will be fixed to also run on WinSock systems.
466  */
467#else
468  FD_SET(fileno(stdin), &fds_read);
469#endif
470
471  switch(*mode) {
472
473  case PASSIVE_LISTEN:
474
475    /* server mode */
476    sockfd = listenfd;
477    /* there's always a socket to wait for */
478    FD_SET(sockfd, &fds_read);
479    maxfd = sockfd;
480    break;
481
482  case PASSIVE_CONNECT:
483
484    sockfd = *sockfdp;
485    if(CURL_SOCKET_BAD == sockfd) {
486      /* eeek, we are supposedly connected and then this cannot be -1 ! */
487      logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
488      maxfd = 0; /* stdin */
489    }
490    else {
491      /* there's always a socket to wait for */
492      FD_SET(sockfd, &fds_read);
493      maxfd = sockfd;
494    }
495    break;
496
497  case ACTIVE:
498
499    sockfd = *sockfdp;
500    /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
501    if(CURL_SOCKET_BAD != sockfd) {
502      FD_SET(sockfd, &fds_read);
503      maxfd = sockfd;
504    }
505    else {
506      logmsg("No socket to read on");
507      maxfd = 0;
508    }
509    break;
510
511  case ACTIVE_DISCONNECT:
512
513    logmsg("disconnected, no socket to read on");
514    maxfd = 0;
515    sockfd = CURL_SOCKET_BAD;
516    break;
517
518  } /* switch(*mode) */
519
520
521  do {
522
523    rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
524
525    if(got_exit_signal) {
526      logmsg("signalled to die, exiting...");
527      return FALSE;
528    }
529
530  } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
531
532  if(rc < 0) {
533    logmsg("select() failed with error: (%d) %s",
534           error, strerror(error));
535    return FALSE;
536  }
537
538  if(rc == 0)
539    /* timeout */
540    return TRUE;
541
542
543  if(FD_ISSET(fileno(stdin), &fds_read)) {
544    /* read from stdin, commands/data to be dealt with and possibly passed on
545       to the socket
546
547       protocol:
548
549       4 letter command + LF [mandatory]
550
551       4-digit hexadecimal data length + LF [if the command takes data]
552       data                       [the data being as long as set above]
553
554       Commands:
555
556       DATA - plain pass-thru data
557    */
558
559    if(!read_stdin(buffer, 5))
560      return FALSE;
561
562    logmsg("Received %c%c%c%c (on stdin)",
563           buffer[0], buffer[1], buffer[2], buffer[3] );
564
565    if(!memcmp("PING", buffer, 4)) {
566      /* send reply on stdout, just proving we are alive */
567      if(!write_stdout("PONG\n", 5))
568        return FALSE;
569    }
570
571    else if(!memcmp("PORT", buffer, 4)) {
572      /* Question asking us what PORT number we are listening to.
573         Replies to PORT with "IPv[num]/[port]" */
574      sprintf((char *)buffer, "%s/%hu\n", ipv_inuse, port);
575      buffer_len = (ssize_t)strlen((char *)buffer);
576      snprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len);
577      if(!write_stdout(data, 10))
578        return FALSE;
579      if(!write_stdout(buffer, buffer_len))
580        return FALSE;
581    }
582    else if(!memcmp("QUIT", buffer, 4)) {
583      /* just die */
584      logmsg("quits");
585      return FALSE;
586    }
587    else if(!memcmp("DATA", buffer, 4)) {
588      /* data IN => data OUT */
589
590      if(!read_stdin(buffer, 5))
591        return FALSE;
592
593      buffer[5] = '\0';
594
595      buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
596      if (buffer_len > (ssize_t)sizeof(buffer)) {
597        logmsg("ERROR: Buffer size (%zu bytes) too small for data size "
598               "(%zd bytes)", sizeof(buffer), buffer_len);
599        return FALSE;
600      }
601      logmsg("> %zd bytes data, server => client", buffer_len);
602
603      if(!read_stdin(buffer, buffer_len))
604        return FALSE;
605
606      lograw(buffer, buffer_len);
607
608      if(*mode == PASSIVE_LISTEN) {
609        logmsg("*** We are disconnected!");
610        if(!write_stdout("DISC\n", 5))
611          return FALSE;
612      }
613      else {
614        /* send away on the socket */
615        bytes_written = swrite(sockfd, buffer, buffer_len);
616        if(bytes_written != buffer_len) {
617          logmsg("Not all data was sent. Bytes to send: %zd sent: %zd",
618                 buffer_len, bytes_written);
619        }
620      }
621    }
622    else if(!memcmp("DISC", buffer, 4)) {
623      /* disconnect! */
624      if(!write_stdout("DISC\n", 5))
625        return FALSE;
626      if(sockfd != CURL_SOCKET_BAD) {
627        logmsg("====> Client forcibly disconnected");
628        sclose(sockfd);
629        *sockfdp = CURL_SOCKET_BAD;
630        if(*mode == PASSIVE_CONNECT)
631          *mode = PASSIVE_LISTEN;
632        else
633          *mode = ACTIVE_DISCONNECT;
634      }
635      else
636        logmsg("attempt to close already dead connection");
637      return TRUE;
638    }
639  }
640
641
642  if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
643
644    if(*mode == PASSIVE_LISTEN) {
645      /* there's no stream set up yet, this is an indication that there's a
646         client connecting. */
647      sockfd = accept(sockfd, NULL, NULL);
648      if(CURL_SOCKET_BAD == sockfd)
649        logmsg("accept() failed");
650      else {
651        logmsg("====> Client connect");
652        if(!write_stdout("CNCT\n", 5))
653          return FALSE;
654        *sockfdp = sockfd; /* store the new socket */
655        *mode = PASSIVE_CONNECT; /* we have connected */
656      }
657      return TRUE;
658    }
659
660    /* read from socket, pass on data to stdout */
661    nread_socket = sread(sockfd, buffer, sizeof(buffer));
662
663    if(nread_socket <= 0) {
664      logmsg("====> Client disconnect");
665      if(!write_stdout("DISC\n", 5))
666        return FALSE;
667      sclose(sockfd);
668      *sockfdp = CURL_SOCKET_BAD;
669      if(*mode == PASSIVE_CONNECT)
670        *mode = PASSIVE_LISTEN;
671      else
672        *mode = ACTIVE_DISCONNECT;
673      return TRUE;
674    }
675
676    snprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket);
677    if(!write_stdout(data, 10))
678      return FALSE;
679    if(!write_stdout(buffer, nread_socket))
680      return FALSE;
681
682    logmsg("< %zd bytes data, client => server", nread_socket);
683    lograw(buffer, nread_socket);
684  }
685
686  return TRUE;
687}
688
689static curl_socket_t sockdaemon(curl_socket_t sock,
690                                unsigned short *listenport)
691{
692  /* passive daemon style */
693  srvr_sockaddr_union_t listener;
694  int flag;
695  int rc;
696  int totdelay = 0;
697  int maxretr = 10;
698  int delay= 20;
699  int attempt = 0;
700  int error = 0;
701
702  do {
703    attempt++;
704    flag = 1;
705    rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
706         (void *)&flag, sizeof(flag));
707    if(rc) {
708      error = SOCKERRNO;
709      logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
710             error, strerror(error));
711      if(maxretr) {
712        rc = wait_ms(delay);
713        if(rc) {
714          /* should not happen */
715          error = SOCKERRNO;
716          logmsg("wait_ms() failed with error: (%d) %s",
717                 error, strerror(error));
718          sclose(sock);
719          return CURL_SOCKET_BAD;
720        }
721        if(got_exit_signal) {
722          logmsg("signalled to die, exiting...");
723          sclose(sock);
724          return CURL_SOCKET_BAD;
725        }
726        totdelay += delay;
727        delay *= 2; /* double the sleep for next attempt */
728      }
729    }
730  } while(rc && maxretr--);
731
732  if(rc) {
733    logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
734           attempt, totdelay, error, strerror(error));
735    logmsg("Continuing anyway...");
736  }
737
738  /* When the specified listener port is zero, it is actually a
739     request to let the system choose a non-zero available port. */
740
741#ifdef ENABLE_IPV6
742  if(!use_ipv6) {
743#endif
744    memset(&listener.sa4, 0, sizeof(listener.sa4));
745    listener.sa4.sin_family = AF_INET;
746    listener.sa4.sin_addr.s_addr = INADDR_ANY;
747    listener.sa4.sin_port = htons(*listenport);
748    rc = bind(sock, &listener.sa, sizeof(listener.sa4));
749#ifdef ENABLE_IPV6
750  }
751  else {
752    memset(&listener.sa6, 0, sizeof(listener.sa6));
753    listener.sa6.sin6_family = AF_INET6;
754    listener.sa6.sin6_addr = in6addr_any;
755    listener.sa6.sin6_port = htons(*listenport);
756    rc = bind(sock, &listener.sa, sizeof(listener.sa6));
757  }
758#endif /* ENABLE_IPV6 */
759  if(rc) {
760    error = SOCKERRNO;
761    logmsg("Error binding socket on port %hu: (%d) %s",
762           *listenport, error, strerror(error));
763    sclose(sock);
764    return CURL_SOCKET_BAD;
765  }
766
767  if(!*listenport) {
768    /* The system was supposed to choose a port number, figure out which
769       port we actually got and update the listener port value with it. */
770    curl_socklen_t la_size;
771    srvr_sockaddr_union_t localaddr;
772#ifdef ENABLE_IPV6
773    if(!use_ipv6)
774#endif
775      la_size = sizeof(localaddr.sa4);
776#ifdef ENABLE_IPV6
777    else
778      la_size = sizeof(localaddr.sa6);
779#endif
780    memset(&localaddr.sa, 0, (size_t)la_size);
781    if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
782      error = SOCKERRNO;
783      logmsg("getsockname() failed with error: (%d) %s",
784             error, strerror(error));
785      sclose(sock);
786      return CURL_SOCKET_BAD;
787    }
788    switch (localaddr.sa.sa_family) {
789    case AF_INET:
790      *listenport = ntohs(localaddr.sa4.sin_port);
791      break;
792#ifdef ENABLE_IPV6
793    case AF_INET6:
794      *listenport = ntohs(localaddr.sa6.sin6_port);
795      break;
796#endif
797    default:
798      break;
799    }
800    if(!*listenport) {
801      /* Real failure, listener port shall not be zero beyond this point. */
802      logmsg("Apparently getsockname() succeeded, with listener port zero.");
803      logmsg("A valid reason for this failure is a binary built without");
804      logmsg("proper network library linkage. This might not be the only");
805      logmsg("reason, but double check it before anything else.");
806      sclose(sock);
807      return CURL_SOCKET_BAD;
808    }
809  }
810
811  /* bindonly option forces no listening */
812  if(bind_only) {
813    logmsg("instructed to bind port without listening");
814    return sock;
815  }
816
817  /* start accepting connections */
818  rc = listen(sock, 5);
819  if(0 != rc) {
820    error = SOCKERRNO;
821    logmsg("listen() failed with error: (%d) %s",
822           error, strerror(error));
823    sclose(sock);
824    return CURL_SOCKET_BAD;
825  }
826
827  return sock;
828}
829
830
831int main(int argc, char *argv[])
832{
833  srvr_sockaddr_union_t me;
834  curl_socket_t sock = CURL_SOCKET_BAD;
835  curl_socket_t msgsock = CURL_SOCKET_BAD;
836  int wrotepidfile = 0;
837  char *pidname= (char *)".sockfilt.pid";
838  bool juggle_again;
839  int rc;
840  int error;
841  int arg=1;
842  enum sockmode mode = PASSIVE_LISTEN; /* default */
843  const char *addr = NULL;
844
845  while(argc>arg) {
846    if(!strcmp("--version", argv[arg])) {
847      printf("sockfilt IPv4%s\n",
848#ifdef ENABLE_IPV6
849             "/IPv6"
850#else
851             ""
852#endif
853             );
854      return 0;
855    }
856    else if(!strcmp("--verbose", argv[arg])) {
857      verbose = TRUE;
858      arg++;
859    }
860    else if(!strcmp("--pidfile", argv[arg])) {
861      arg++;
862      if(argc>arg)
863        pidname = argv[arg++];
864    }
865    else if(!strcmp("--logfile", argv[arg])) {
866      arg++;
867      if(argc>arg)
868        serverlogfile = argv[arg++];
869    }
870    else if(!strcmp("--ipv6", argv[arg])) {
871#ifdef ENABLE_IPV6
872      ipv_inuse = "IPv6";
873      use_ipv6 = TRUE;
874#endif
875      arg++;
876    }
877    else if(!strcmp("--ipv4", argv[arg])) {
878      /* for completeness, we support this option as well */
879#ifdef ENABLE_IPV6
880      ipv_inuse = "IPv4";
881      use_ipv6 = FALSE;
882#endif
883      arg++;
884    }
885    else if(!strcmp("--bindonly", argv[arg])) {
886      bind_only = TRUE;
887      arg++;
888    }
889    else if(!strcmp("--port", argv[arg])) {
890      arg++;
891      if(argc>arg) {
892        char *endptr;
893        unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
894        if((endptr != argv[arg] + strlen(argv[arg])) ||
895           ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
896          fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
897                  argv[arg]);
898          return 0;
899        }
900        port = curlx_ultous(ulnum);
901        arg++;
902      }
903    }
904    else if(!strcmp("--connect", argv[arg])) {
905      /* Asked to actively connect to the specified local port instead of
906         doing a passive server-style listening. */
907      arg++;
908      if(argc>arg) {
909        char *endptr;
910        unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
911        if((endptr != argv[arg] + strlen(argv[arg])) ||
912           (ulnum < 1025UL) || (ulnum > 65535UL)) {
913          fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
914                  argv[arg]);
915          return 0;
916        }
917        connectport = curlx_ultous(ulnum);
918        arg++;
919      }
920    }
921    else if(!strcmp("--addr", argv[arg])) {
922      /* Set an IP address to use with --connect; otherwise use localhost */
923      arg++;
924      if(argc>arg) {
925        addr = argv[arg];
926        arg++;
927      }
928    }
929    else {
930      puts("Usage: sockfilt [option]\n"
931           " --version\n"
932           " --verbose\n"
933           " --logfile [file]\n"
934           " --pidfile [file]\n"
935           " --ipv4\n"
936           " --ipv6\n"
937           " --bindonly\n"
938           " --port [port]\n"
939           " --connect [port]\n"
940           " --addr [address]");
941      return 0;
942    }
943  }
944
945#ifdef WIN32
946  win32_init();
947  atexit(win32_cleanup);
948#endif
949
950  install_signal_handlers();
951
952#ifdef ENABLE_IPV6
953  if(!use_ipv6)
954#endif
955    sock = socket(AF_INET, SOCK_STREAM, 0);
956#ifdef ENABLE_IPV6
957  else
958    sock = socket(AF_INET6, SOCK_STREAM, 0);
959#endif
960
961  if(CURL_SOCKET_BAD == sock) {
962    error = SOCKERRNO;
963    logmsg("Error creating socket: (%d) %s",
964           error, strerror(error));
965    write_stdout("FAIL\n", 5);
966    goto sockfilt_cleanup;
967  }
968
969  if(connectport) {
970    /* Active mode, we should connect to the given port number */
971    mode = ACTIVE;
972#ifdef ENABLE_IPV6
973    if(!use_ipv6) {
974#endif
975      memset(&me.sa4, 0, sizeof(me.sa4));
976      me.sa4.sin_family = AF_INET;
977      me.sa4.sin_port = htons(connectport);
978      me.sa4.sin_addr.s_addr = INADDR_ANY;
979      if (!addr)
980        addr = "127.0.0.1";
981      Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);
982
983      rc = connect(sock, &me.sa, sizeof(me.sa4));
984#ifdef ENABLE_IPV6
985    }
986    else {
987      memset(&me.sa6, 0, sizeof(me.sa6));
988      me.sa6.sin6_family = AF_INET6;
989      me.sa6.sin6_port = htons(connectport);
990      if (!addr)
991        addr = "::1";
992      Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);
993
994      rc = connect(sock, &me.sa, sizeof(me.sa6));
995    }
996#endif /* ENABLE_IPV6 */
997    if(rc) {
998      error = SOCKERRNO;
999      logmsg("Error connecting to port %hu: (%d) %s",
1000             connectport, error, strerror(error));
1001      write_stdout("FAIL\n", 5);
1002      goto sockfilt_cleanup;
1003    }
1004    logmsg("====> Client connect");
1005    msgsock = sock; /* use this as stream */
1006  }
1007  else {
1008    /* passive daemon style */
1009    sock = sockdaemon(sock, &port);
1010    if(CURL_SOCKET_BAD == sock) {
1011      write_stdout("FAIL\n", 5);
1012      goto sockfilt_cleanup;
1013    }
1014    msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1015  }
1016
1017  logmsg("Running %s version", ipv_inuse);
1018
1019  if(connectport)
1020    logmsg("Connected to port %hu", connectport);
1021  else if(bind_only)
1022    logmsg("Bound without listening on port %hu", port);
1023  else
1024    logmsg("Listening on port %hu", port);
1025
1026  wrotepidfile = write_pidfile(pidname);
1027  if(!wrotepidfile) {
1028    write_stdout("FAIL\n", 5);
1029    goto sockfilt_cleanup;
1030  }
1031
1032  do {
1033    juggle_again = juggle(&msgsock, sock, &mode);
1034  } while(juggle_again);
1035
1036sockfilt_cleanup:
1037
1038  if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1039    sclose(msgsock);
1040
1041  if(sock != CURL_SOCKET_BAD)
1042    sclose(sock);
1043
1044  if(wrotepidfile)
1045    unlink(pidname);
1046
1047  restore_signal_handlers();
1048
1049  if(got_exit_signal) {
1050    logmsg("============> sockfilt exits with signal (%d)", exit_signal);
1051    /*
1052     * To properly set the return status of the process we
1053     * must raise the same signal SIGINT or SIGTERM that we
1054     * caught and let the old handler take care of it.
1055     */
1056    raise(exit_signal);
1057  }
1058
1059  logmsg("============> sockfilt quits");
1060  return 0;
1061}
1062
1063