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