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