when terminating do it falling through cleanup code
[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 #include "setup.h" /* portability help from the lib directory */
50
51 #ifdef HAVE_SIGNAL_H
52 #include <signal.h>
53 #endif
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif
57 #ifdef HAVE_SYS_SOCKET_H
58 #include <sys/socket.h>
59 #endif
60 #ifdef HAVE_NETINET_IN_H
61 #include <netinet/in.h>
62 #endif
63 #ifdef _XOPEN_SOURCE_EXTENDED
64 /* This define is "almost" required to build on HPUX 11 */
65 #include <arpa/inet.h>
66 #endif
67 #ifdef HAVE_NETDB_H
68 #include <netdb.h>
69 #endif
70
71 #define ENABLE_CURLX_PRINTF
72 /* make the curlx header define all printf() functions to use the curlx_*
73    versions instead */
74 #include "curlx.h" /* from the private lib dir */
75 #include "getpart.h"
76 #include "inet_pton.h"
77 #include "util.h"
78
79 /* include memdebug.h last */
80 #include "memdebug.h"
81
82 #define DEFAULT_PORT 8999
83
84 #ifndef DEFAULT_LOGFILE
85 #define DEFAULT_LOGFILE "log/sockfilt.log"
86 #endif
87
88 #ifdef SIGPIPE
89 static volatile int sigpipe;  /* Why? It's not used */
90 #endif
91
92 const char *serverlogfile = (char *)DEFAULT_LOGFILE;
93
94 bool verbose = FALSE;
95 bool use_ipv6 = FALSE;
96 unsigned short port = DEFAULT_PORT;
97 unsigned short connectport = 0; /* if non-zero, we activate this mode */
98
99 enum sockmode {
100   PASSIVE_LISTEN,    /* as a server waiting for connections */
101   PASSIVE_CONNECT,   /* as a server, connected to a client */
102   ACTIVE,            /* as a client, connected to a server */
103   ACTIVE_DISCONNECT  /* as a client, disconnected from server */
104 };
105
106 /*
107  * fullread is a wrapper around the read() function. This will repeat the call
108  * to read() until it actually has read the complete number of bytes indicated
109  * in nbytes or it fails with a condition that cannot be handled with a simple
110  * retry of the read call.
111  */
112
113 static ssize_t fullread(int filedes, void *buffer, size_t nbytes)
114 {
115   int error;
116   ssize_t rc;
117   ssize_t nread = 0;
118
119   do {
120     rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread);
121
122     if(rc < 0) {
123       error = ERRNO;
124       if((error == EINTR) || (error == EAGAIN))
125         continue;
126       logmsg("unrecoverable read() failure: %s", strerror(error));
127       return -1;
128     }
129
130     if(rc == 0) {
131       logmsg("got 0 reading from stdin");
132       return 0;
133     }
134
135     nread += rc;
136
137   } while((size_t)nread < nbytes);
138
139   if(verbose)
140     logmsg("read %ld bytes", (long)nread);
141
142   return nread;
143 }
144
145 /*
146  * fullwrite is a wrapper around the write() function. This will repeat the
147  * call to write() until it actually has written the complete number of bytes
148  * indicated in nbytes or it fails with a condition that cannot be handled
149  * with a simple retry of the write call.
150  */
151
152 static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes)
153 {
154   int error;
155   ssize_t wc;
156   ssize_t nwrite = 0;
157
158   do {
159     wc = write(filedes, (unsigned char *)buffer + nwrite, nbytes - nwrite);
160
161     if(wc < 0) {
162       error = ERRNO;
163       if((error == EINTR) || (error == EAGAIN))
164         continue;
165       logmsg("unrecoverable write() failure: %s", strerror(error));
166       return -1;
167     }
168
169     if(wc == 0) {
170       logmsg("put 0 writing to stdout");
171       return 0;
172     }
173
174     nwrite += wc;
175
176   } while((size_t)nwrite < nbytes);
177
178   if(verbose)
179     logmsg("wrote %ld bytes", (long)nwrite);
180
181   return nwrite;
182 }
183
184 /*
185  * read_stdin tries to read from stdin nbytes into the given buffer. This is a
186  * blocking function that will only return TRUE when nbytes have actually been
187  * read or FALSE when an unrecoverable error has been detected. Failure of this
188  * function is an indication that the sockfilt process should terminate.
189  */
190
191 static bool read_stdin(void *buffer, size_t nbytes)
192 {
193   ssize_t nread = fullread(fileno(stdin), buffer, nbytes);
194   if(nread != (ssize_t)nbytes) {
195     logmsg("exiting...");
196     return FALSE;
197   }
198   return TRUE;
199 }
200
201 /*
202  * write_stdout tries to write to stdio nbytes from the given buffer. This is a
203  * blocking function that will only return TRUE when nbytes have actually been
204  * written or FALSE when an unrecoverable error has been detected. Failure of
205  * this function is an indication that the sockfilt process should terminate.
206  */
207
208 static bool write_stdout(const void *buffer, size_t nbytes)
209 {
210   ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes);
211   if(nwrite != (ssize_t)nbytes) {
212     logmsg("exiting...");
213     return FALSE;
214   }
215   return TRUE;
216 }
217
218 static void lograw(unsigned char *buffer, ssize_t len)
219 {
220   char data[120];
221   ssize_t i;
222   unsigned char *ptr = buffer;
223   char *optr = data;
224   ssize_t width=0;
225
226   for(i=0; i<len; i++) {
227     switch(ptr[i]) {
228     case '\n':
229       sprintf(optr, "\\n");
230       width += 2;
231       optr += 2;
232       break;
233     case '\r':
234       sprintf(optr, "\\r");
235       width += 2;
236       optr += 2;
237       break;
238     default:
239       sprintf(optr, "%c", (ISGRAPH(ptr[i]) || ptr[i]==0x20) ?ptr[i]:'.');
240       width++;
241       optr++;
242       break;
243     }
244
245     if(width>60) {
246       logmsg("'%s'", data);
247       width = 0;
248       optr = data;
249     }
250   }
251   if(width)
252     logmsg("'%s'", data);
253 }
254
255 #ifdef SIGPIPE
256 static void sigpipe_handler(int sig)
257 {
258   (void)sig; /* prevent warning */
259   sigpipe = 1;
260 }
261 #endif
262
263 /*
264   sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
265
266   if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
267   accept()
268 */
269 static bool juggle(curl_socket_t *sockfdp,
270                    curl_socket_t listenfd,
271                    enum sockmode *mode)
272 {
273   struct timeval timeout;
274   fd_set fds_read;
275   fd_set fds_write;
276   fd_set fds_err;
277   curl_socket_t sockfd;
278   curl_socket_t maxfd;
279   ssize_t rc;
280   ssize_t nread_socket;
281   ssize_t bytes_written;
282   ssize_t buffer_len;
283   int error;
284
285  /* 'buffer' is this excessively large only to be able to support things like
286     test 1003 which tests exceedingly large server response lines */
287   unsigned char buffer[17010];
288   char data[16];
289
290 #ifdef HAVE_GETPPID
291   /* As a last resort, quit if sockfilt process becomes orphan. Just in case
292      parent ftpserver process has died without killing its sockfilt children */
293   if(getppid() <= 1) {
294     logmsg("process becomes orphan, exiting");
295     return FALSE;
296   }
297 #endif
298
299   timeout.tv_sec = 120;
300   timeout.tv_usec = 0;
301
302   FD_ZERO(&fds_read);
303   FD_ZERO(&fds_write);
304   FD_ZERO(&fds_err);
305
306   FD_SET(fileno(stdin), &fds_read);
307
308   switch(*mode) {
309
310   case PASSIVE_LISTEN:
311
312     /* server mode */
313     sockfd = listenfd;
314     /* there's always a socket to wait for */
315     FD_SET(sockfd, &fds_read);
316     maxfd = sockfd;
317     break;
318
319   case PASSIVE_CONNECT:
320
321     sockfd = *sockfdp;
322     if(CURL_SOCKET_BAD == sockfd) {
323       /* eeek, we are supposedly connected and then this cannot be -1 ! */
324       logmsg("socket is -1! on %s:%d", __FILE__, __LINE__);
325       maxfd = 0; /* stdin */
326     }
327     else {
328       /* there's always a socket to wait for */
329       FD_SET(sockfd, &fds_read);
330       maxfd = sockfd;
331     }
332     break;
333
334   case ACTIVE:
335
336     sockfd = *sockfdp;
337     /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */
338     if(CURL_SOCKET_BAD != sockfd) {
339       FD_SET(sockfd, &fds_read);
340       maxfd = sockfd;
341     }
342     else {
343       logmsg("No socket to read on");
344       maxfd = 0;
345     }
346     break;
347
348   case ACTIVE_DISCONNECT:
349
350     logmsg("disconnected, no socket to read on");
351     maxfd = 0;
352     sockfd = CURL_SOCKET_BAD;
353     break;
354
355   } /* switch(*mode) */
356
357
358   do {
359
360     rc = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout);
361
362   } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
363
364   if(rc < 0) {
365     logmsg("select() failed with error: (%d) %s",
366            error, strerror(error));
367     return FALSE;
368   }
369
370   if(rc == 0)
371     /* timeout */
372     return TRUE;
373
374
375   if(FD_ISSET(fileno(stdin), &fds_read)) {
376     /* read from stdin, commands/data to be dealt with and possibly passed on
377        to the socket
378
379        protocol:
380
381        4 letter command + LF [mandatory]
382
383        4-digit hexadecimal data length + LF [if the command takes data]
384        data                       [the data being as long as set above]
385
386        Commands:
387
388        DATA - plain pass-thru data
389     */
390
391     if(!read_stdin(buffer, 5))
392       return FALSE;
393
394     logmsg("Received %c%c%c%c (on stdin)",
395            buffer[0], buffer[1], buffer[2], buffer[3] );
396
397     if(!memcmp("PING", buffer, 4)) {
398       /* send reply on stdout, just proving we are alive */
399       if(!write_stdout("PONG\n", 5))
400         return FALSE;
401     }
402
403     else if(!memcmp("PORT", buffer, 4)) {
404       /* Question asking us what PORT number we are listening to.
405          Replies to PORT with "IPv[num]/[port]" */
406       sprintf((char *)buffer, "IPv%d/%d\n", use_ipv6?6:4, (int)port);
407       buffer_len = (ssize_t)strlen((char *)buffer);
408       snprintf(data, sizeof(data), "PORT\n%04x\n", buffer_len);
409       if(!write_stdout(data, 10))
410         return FALSE;
411       if(!write_stdout(buffer, buffer_len))
412         return FALSE;
413     }
414     else if(!memcmp("QUIT", buffer, 4)) {
415       /* just die */
416       logmsg("quits");
417       return FALSE;
418     }
419     else if(!memcmp("DATA", buffer, 4)) {
420       /* data IN => data OUT */
421
422       if(!read_stdin(buffer, 5))
423         return FALSE;
424
425       buffer[5] = '\0';
426
427       buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16);
428       if (buffer_len > (ssize_t)sizeof(buffer)) {
429         logmsg("ERROR: Buffer size (%ld bytes) too small for data size "
430                "(%ld bytes)", (long)sizeof(buffer), (long)buffer_len);
431         return FALSE;
432       }
433       logmsg("> %d bytes data, server => client", buffer_len);
434
435       if(!read_stdin(buffer, buffer_len))
436         return FALSE;
437
438       lograw(buffer, buffer_len);
439
440       if(*mode == PASSIVE_LISTEN) {
441         logmsg("*** We are disconnected!");
442         if(!write_stdout("DISC\n", 5))
443           return FALSE;
444       }
445       else {
446         /* send away on the socket */
447         bytes_written = swrite(sockfd, buffer, buffer_len);
448         if(bytes_written != buffer_len) {
449           logmsg("Not all data was sent. Bytes to send: %d sent: %d", 
450                  buffer_len, bytes_written);
451         }
452       }
453     }
454     else if(!memcmp("DISC", buffer, 4)) {
455       /* disconnect! */
456       if(!write_stdout("DISC\n", 5))
457         return FALSE;
458       if(sockfd != CURL_SOCKET_BAD) {
459         logmsg("====> Client forcibly disconnected");
460         sclose(sockfd);
461         *sockfdp = CURL_SOCKET_BAD;
462         if(*mode == PASSIVE_CONNECT)
463           *mode = PASSIVE_LISTEN;
464         else
465           *mode = ACTIVE_DISCONNECT;
466       }
467       else
468         logmsg("attempt to close already dead connection");
469       return TRUE;
470     }
471   }
472
473
474   if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) {
475
476     if(*mode == PASSIVE_LISTEN) {
477       /* there's no stream set up yet, this is an indication that there's a
478          client connecting. */
479       sockfd = accept(sockfd, NULL, NULL);
480       if(CURL_SOCKET_BAD == sockfd)
481         logmsg("accept() failed");
482       else {
483         logmsg("====> Client connect");
484         if(!write_stdout("CNCT\n", 5))
485           return FALSE;
486         *sockfdp = sockfd; /* store the new socket */
487         *mode = PASSIVE_CONNECT; /* we have connected */
488       }
489       return TRUE;
490     }
491
492     /* read from socket, pass on data to stdout */
493     nread_socket = sread(sockfd, buffer, sizeof(buffer));
494
495     if(nread_socket <= 0) {
496       logmsg("====> Client disconnect");
497       if(!write_stdout("DISC\n", 5))
498         return FALSE;
499       sclose(sockfd);
500       *sockfdp = CURL_SOCKET_BAD;
501       if(*mode == PASSIVE_CONNECT)
502         *mode = PASSIVE_LISTEN;
503       else
504         *mode = ACTIVE_DISCONNECT;
505       return TRUE;
506     }
507
508     snprintf(data, sizeof(data), "DATA\n%04x\n", nread_socket);
509     if(!write_stdout(data, 10))
510       return FALSE;
511     if(!write_stdout(buffer, nread_socket))
512       return FALSE;
513
514     logmsg("< %d bytes data, client => server", nread_socket);
515     lograw(buffer, nread_socket);
516   }
517
518   return TRUE;
519 }
520
521 static curl_socket_t sockdaemon(curl_socket_t sock,
522                                 unsigned short *listenport)
523 {
524   /* passive daemon style */
525   struct sockaddr_in me;
526 #ifdef ENABLE_IPV6
527   struct sockaddr_in6 me6;
528 #endif /* ENABLE_IPV6 */
529   int flag = 1;
530   int rc;
531   int totdelay = 0;
532   int maxretr = 10;
533   int delay= 20;
534   int attempt = 0;
535   int error = 0;
536
537   do {
538     attempt++;
539     rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
540          (void *)&flag, sizeof(flag));
541     if(rc) {
542       error = SOCKERRNO;
543       if(maxretr) {
544         rc = wait_ms(delay);
545         if(rc) {
546           /* should not happen */
547           error = SOCKERRNO;
548           logmsg("wait_ms() failed: (%d) %s", error, strerror(error));
549           sclose(sock);
550           return CURL_SOCKET_BAD;
551         }
552         totdelay += delay;
553         delay *= 2; /* double the sleep for next attempt */
554       }
555     }
556   } while(rc && maxretr--);
557
558   if(rc) {
559     logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
560            attempt, totdelay, error, strerror(error));
561     logmsg("Continuing anyway...");
562   }
563
564 #ifdef ENABLE_IPV6
565   if(!use_ipv6) {
566 #endif
567     memset(&me, 0, sizeof(me));
568     me.sin_family = AF_INET;
569     me.sin_addr.s_addr = INADDR_ANY;
570     me.sin_port = htons(*listenport);
571     rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
572 #ifdef ENABLE_IPV6
573   }
574   else {
575     memset(&me6, 0, sizeof(me6));
576     me6.sin6_family = AF_INET6;
577     me6.sin6_addr = in6addr_any;
578     me6.sin6_port = htons(*listenport);
579     rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
580   }
581 #endif /* ENABLE_IPV6 */
582   if(rc) {
583     error = SOCKERRNO;
584     logmsg("Error binding socket: (%d) %s", error, strerror(error));
585     sclose(sock);
586     return CURL_SOCKET_BAD;
587   }
588
589   if(!*listenport) {
590     /* The system picked a port number, now figure out which port we actually
591        got */
592     /* we succeeded to bind */
593     struct sockaddr_in add;
594     socklen_t socksize = sizeof(add);
595
596     if(getsockname(sock, (struct sockaddr *) &add,
597                    &socksize)<0) {
598       error = SOCKERRNO;
599       logmsg("getsockname() failed with error: (%d) %s",
600              error, strerror(error));
601       sclose(sock);
602       return CURL_SOCKET_BAD;
603     }
604     *listenport = ntohs(add.sin_port);
605   }
606
607   /* start accepting connections */
608   rc = listen(sock, 5);
609   if(0 != rc) {
610     error = SOCKERRNO;
611     logmsg("listen() failed with error: (%d) %s",
612            error, strerror(error));
613     sclose(sock);
614     return CURL_SOCKET_BAD;
615   }
616
617   return sock;
618 }
619
620
621 int main(int argc, char *argv[])
622 {
623   struct sockaddr_in me;
624 #ifdef ENABLE_IPV6
625   struct sockaddr_in6 me6;
626 #endif /* ENABLE_IPV6 */
627   curl_socket_t sock = CURL_SOCKET_BAD;
628   curl_socket_t msgsock = CURL_SOCKET_BAD;
629   int wrotepidfile = 0;
630   char *pidname= (char *)".sockfilt.pid";
631   int rc;
632   int error;
633   int arg=1;
634   enum sockmode mode = PASSIVE_LISTEN; /* default */
635   const char *addr = NULL;
636
637   while(argc>arg) {
638     if(!strcmp("--version", argv[arg])) {
639       printf("sockfilt IPv4%s\n",
640 #ifdef ENABLE_IPV6
641              "/IPv6"
642 #else
643              ""
644 #endif
645              );
646       return 0;
647     }
648     else if(!strcmp("--verbose", argv[arg])) {
649       verbose = TRUE;
650       arg++;
651     }
652     else if(!strcmp("--pidfile", argv[arg])) {
653       arg++;
654       if(argc>arg)
655         pidname = argv[arg++];
656     }
657     else if(!strcmp("--logfile", argv[arg])) {
658       arg++;
659       if(argc>arg)
660         serverlogfile = argv[arg++];
661     }
662     else if(!strcmp("--ipv6", argv[arg])) {
663 #ifdef ENABLE_IPV6
664       use_ipv6=TRUE;
665 #endif
666       arg++;
667     }
668     else if(!strcmp("--ipv4", argv[arg])) {
669       /* for completeness, we support this option as well */
670       use_ipv6=FALSE;
671       arg++;
672     }
673     else if(!strcmp("--port", argv[arg])) {
674       arg++;
675       if(argc>arg) {
676         port = (unsigned short)atoi(argv[arg]);
677         arg++;
678       }
679     }
680     else if(!strcmp("--connect", argv[arg])) {
681       /* Asked to actively connect to the specified local port instead of
682          doing a passive server-style listening. */
683       arg++;
684       if(argc>arg) {
685         connectport = (unsigned short)atoi(argv[arg]);
686         arg++;
687       }
688     }
689     else if(!strcmp("--addr", argv[arg])) {
690       /* Set an IP address to use with --connect; otherwise use localhost */
691       arg++;
692       if(argc>arg) {
693         addr = argv[arg];
694         arg++;
695       }
696     }
697     else {
698       puts("Usage: sockfilt [option]\n"
699            " --version\n"
700            " --verbose\n"
701            " --logfile [file]\n"
702            " --pidfile [file]\n"
703            " --ipv4\n"
704            " --ipv6\n"
705            " --port [port]\n"
706            " --connect [port]\n"
707            " --addr [address]");
708       return 0;
709     }
710   }
711
712 #ifdef WIN32
713   win32_init();
714   atexit(win32_cleanup);
715 #else
716
717 #ifdef SIGPIPE
718 #ifdef HAVE_SIGNAL
719   signal(SIGPIPE, sigpipe_handler);
720 #endif
721 #ifdef HAVE_SIGINTERRUPT
722   siginterrupt(SIGPIPE, 1);
723 #endif
724 #endif
725 #endif
726
727 #ifdef ENABLE_IPV6
728   if(!use_ipv6)
729 #endif
730     sock = socket(AF_INET, SOCK_STREAM, 0);
731 #ifdef ENABLE_IPV6
732   else
733     sock = socket(AF_INET6, SOCK_STREAM, 0);
734 #endif
735
736   if(CURL_SOCKET_BAD == sock) {
737     error = SOCKERRNO;
738     logmsg("Error creating socket: (%d) %s",
739            error, strerror(error));
740     goto sockfilt_cleanup;
741   }
742
743   if(connectport) {
744     /* Active mode, we should connect to the given port number */
745     mode = ACTIVE;
746 #ifdef ENABLE_IPV6
747     if(!use_ipv6) {
748 #endif
749       memset(&me, 0, sizeof(me));
750       me.sin_family = AF_INET;
751       me.sin_port = htons(connectport);
752       me.sin_addr.s_addr = INADDR_ANY;
753       if (!addr)
754         addr = "127.0.0.1";
755       Curl_inet_pton(AF_INET, addr, &me.sin_addr);
756
757       rc = connect(sock, (struct sockaddr *) &me, sizeof(me));
758 #ifdef ENABLE_IPV6
759     }
760     else {
761       memset(&me6, 0, sizeof(me6));
762       me6.sin6_family = AF_INET6;
763       me6.sin6_port = htons(connectport);
764       if (!addr)
765         addr = "::1";
766       Curl_inet_pton(AF_INET6, addr, &me6.sin6_addr);
767
768       rc = connect(sock, (struct sockaddr *) &me6, sizeof(me6));
769     }
770 #endif /* ENABLE_IPV6 */
771     if(rc) {
772       error = SOCKERRNO;
773       logmsg("Error connecting to port %d: (%d) %s",
774              port, error, strerror(error));
775       goto sockfilt_cleanup;
776     }
777     logmsg("====> Client connect");
778     msgsock = sock; /* use this as stream */
779   }
780   else {
781     /* passive daemon style */
782     sock = sockdaemon(sock, &port);
783     if(CURL_SOCKET_BAD == sock)
784       goto sockfilt_cleanup;
785     msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
786   }
787
788   logmsg("Running IPv%d version",
789          (use_ipv6?6:4));
790
791   if(connectport)
792     logmsg("Connected to port %d", connectport);
793   else
794     logmsg("Listening on port %d", port);
795
796   wrotepidfile = write_pidfile(pidname);
797   if(!wrotepidfile)
798     goto sockfilt_cleanup;
799
800   while(juggle(&msgsock, sock, &mode));
801
802 sockfilt_cleanup:
803
804   if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
805     sclose(msgsock);
806
807   if(sock != CURL_SOCKET_BAD)
808   sclose(sock);
809
810   if(wrotepidfile)
811   unlink(pidname);
812
813   logmsg("============> sockfilt quits");
814   return 0;
815 }
816