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