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