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