cgi_error_disabled(): Use status code 403 and an appropriate response line
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.138 2016/09/27 22:48:28 ler762 Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
5  *
6  * Purpose     :  Contains wrappers for system-specific sockets code,
7  *                so that the rest of Junkbuster can be more
8  *                OS-independent.  Contains #ifdefs to make this work
9  *                on many platforms.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001-2016 the
12  *                Privoxy team. http://www.privoxy.org/
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
18  *                This program is free software; you can redistribute it
19  *                and/or modify it under the terms of the GNU General
20  *                Public License as published by the Free Software
21  *                Foundation; either version 2 of the License, or (at
22  *                your option) any later version.
23  *
24  *                This program is distributed in the hope that it will
25  *                be useful, but WITHOUT ANY WARRANTY; without even the
26  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
27  *                PARTICULAR PURPOSE.  See the GNU General Public
28  *                License for more details.
29  *
30  *                The GNU General Public License should be included with
31  *                this file.  If not, you can view it at
32  *                http://www.gnu.org/copyleft/gpl.html
33  *                or write to the Free Software Foundation, Inc., 59
34  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
35  *
36  *********************************************************************/
37
38
39 #include "config.h"
40
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <sys/types.h>
47
48 #ifdef _WIN32
49
50 #ifndef STRICT
51 #define STRICT
52 #endif
53 #include <winsock2.h>
54 #include <windows.h>
55 #include <sys/timeb.h>
56 #include <io.h>
57
58 #else
59
60 #ifndef __OS2__
61 #include <unistd.h>
62 #endif
63 #include <sys/time.h>
64 #include <netinet/in.h>
65 #include <sys/ioctl.h>
66 #include <netdb.h>
67 #include <sys/socket.h>
68
69 #ifndef __BEOS__
70 #include <netinet/tcp.h>
71 #ifndef __OS2__
72 #include <arpa/inet.h>
73 #endif
74 #else
75 #include <socket.h>
76 #endif
77
78 #if defined(__EMX__) || defined (__OS2__)
79 #include <sys/select.h>  /* OS/2/EMX needs a little help with select */
80 #ifdef __OS2__
81 #include <nerrno.h>
82 #endif
83 #endif
84
85 #endif
86
87 #ifdef HAVE_POLL
88 #ifdef __GLIBC__
89 #include <sys/poll.h>
90 #else
91 #include <poll.h>
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
94
95 #include "project.h"
96
97 /* For mutex semaphores only */
98 #include "jcc.h"
99
100 #include "jbsockets.h"
101 #include "filters.h"
102 #include "errlog.h"
103 #include "miscutil.h"
104
105 /* Mac OSX doesn't define AI_NUMERICSESRV */
106 #ifndef AI_NUMERICSERV
107 #define AI_NUMERICSERV 0
108 #endif
109
110 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
111
112 /*
113  * Maximum number of gethostbyname(_r) retries in case of
114  * soft errors (TRY_AGAIN).
115  * XXX: Does it make sense to make this a config option?
116  */
117 #define MAX_DNS_RETRIES 10
118
119 #define MAX_LISTEN_BACKLOG 128
120
121 #ifdef HAVE_RFC2553
122 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
123 #else
124 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
125 #endif
126
127 /*********************************************************************
128  *
129  * Function    :  set_no_delay_flag
130  *
131  * Description :  Disables TCP coalescence for the given socket.
132  *
133  * Parameters  :
134  *          1  :  fd = The file descriptor to operate on
135  *
136  * Returns     :  void
137  *
138  *********************************************************************/
139 static void set_no_delay_flag(int fd)
140 {
141 #ifdef TCP_NODELAY
142    int mi = 1;
143
144    if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
145    {
146       log_error(LOG_LEVEL_ERROR,
147          "Failed to disable TCP coalescence for socket %d", fd);
148    }
149 #else
150 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
151 #endif /* def TCP_NODELAY */
152 }
153
154 /*********************************************************************
155  *
156  * Function    :  connect_to
157  *
158  * Description :  Open a socket and connect to it.  Will check
159  *                that this is allowed according to ACL.
160  *
161  * Parameters  :
162  *          1  :  host = hostname to connect to
163  *          2  :  portnum = port to connect to (XXX: should be unsigned)
164  *          3  :  csp = Current client state (buffers, headers, etc...)
165  *
166  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
167  *                file descriptor.
168  *
169  *********************************************************************/
170 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
171 {
172    jb_socket fd;
173    int forwarded_connect_retries = 0;
174
175    do
176    {
177       /*
178        * XXX: The whole errno overloading is ridiculous and should
179        *      be replaced with something sane and thread safe
180        */
181       /* errno = 0;*/
182 #ifdef HAVE_RFC2553
183       fd = rfc2553_connect_to(host, portnum, csp);
184 #else
185       fd = no_rfc2553_connect_to(host, portnum, csp);
186 #endif
187       if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
188          || (csp->fwd == NULL)
189          || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
190       {
191          break;
192       }
193       forwarded_connect_retries++;
194       if (csp->config->forwarded_connect_retries != 0)
195       {
196          log_error(LOG_LEVEL_ERROR,
197             "Attempt %d of %d to connect to %s failed. Trying again.",
198             forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
199       }
200
201    } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
202
203    return fd;
204 }
205
206 #ifdef HAVE_RFC2553
207 /* Getaddrinfo implementation */
208 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
209 {
210    struct addrinfo hints, *result, *rp;
211    char service[6];
212    int retval;
213    jb_socket fd;
214    fd_set wfds;
215    struct timeval timeout;
216 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
217    int   flags;
218 #endif
219    int connect_failed;
220    /*
221     * XXX: Initializeing it here is only necessary
222     *      because not all situations are properly
223     *      covered yet.
224     */
225    int socket_error = 0;
226
227 #ifdef FEATURE_ACL
228    struct access_control_addr dst[1];
229 #endif /* def FEATURE_ACL */
230
231    /* Don't leak memory when retrying. */
232    freez(csp->error_message);
233    freez(csp->http->host_ip_addr_str);
234
235    retval = snprintf(service, sizeof(service), "%d", portnum);
236    if ((-1 == retval) || (sizeof(service) <= retval))
237    {
238       log_error(LOG_LEVEL_ERROR,
239          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
240          portnum);
241       csp->error_message = strdup("Invalid port number");
242       csp->http->host_ip_addr_str = strdup("unknown");
243       return(JB_INVALID_SOCKET);
244    }
245
246    memset((char *)&hints, 0, sizeof(hints));
247    hints.ai_family = AF_UNSPEC;
248    hints.ai_socktype = SOCK_STREAM;
249    hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
250 #ifdef AI_ADDRCONFIG
251    hints.ai_flags |= AI_ADDRCONFIG;
252 #endif
253    if ((retval = getaddrinfo(host, service, &hints, &result)))
254    {
255       log_error(LOG_LEVEL_INFO,
256          "Can not resolve %s: %s", host, gai_strerror(retval));
257       /* XXX: Should find a better way to propagate this error. */
258       errno = EINVAL;
259       csp->error_message = strdup(gai_strerror(retval));
260       csp->http->host_ip_addr_str = strdup("unknown");
261       return(JB_INVALID_SOCKET);
262    }
263
264    csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
265
266    for (rp = result; rp != NULL; rp = rp->ai_next)
267    {
268
269 #ifdef FEATURE_ACL
270       memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
271
272       if (block_acl(dst, csp))
273       {
274 #ifdef __OS2__
275          socket_error = errno = SOCEPERM;
276 #else
277          socket_error = errno = EPERM;
278 #endif
279          continue;
280       }
281 #endif /* def FEATURE_ACL */
282
283       retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
284          csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
285       if (retval)
286       {
287          log_error(LOG_LEVEL_ERROR,
288             "Failed to get the host name from the socket structure: %s",
289             gai_strerror(retval));
290          continue;
291       }
292
293       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
294 #ifdef _WIN32
295       if (fd == JB_INVALID_SOCKET)
296 #else
297       if (fd < 0)
298 #endif
299       {
300          continue;
301       }
302
303 #ifndef _WIN32
304       if (fd >= FD_SETSIZE)
305       {
306          log_error(LOG_LEVEL_ERROR,
307             "Server socket number too high to use select(): %d >= %d",
308             fd, FD_SETSIZE);
309          close_socket(fd);
310          freeaddrinfo(result);
311          return JB_INVALID_SOCKET;
312       }
313 #endif
314
315 #ifdef FEATURE_EXTERNAL_FILTERS
316       mark_socket_for_close_on_execute(fd);
317 #endif
318
319       set_no_delay_flag(fd);
320
321 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
322       if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
323       {
324          flags |= O_NDELAY;
325          fcntl(fd, F_SETFL, flags);
326       }
327 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
328
329       connect_failed = 0;
330       while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
331       {
332 #ifdef __OS2__
333          errno = sock_errno();
334 #endif /* __OS2__ */
335
336 #ifdef _WIN32
337          if (errno == WSAEINPROGRESS)
338 #else /* ifndef _WIN32 */
339          if (errno == EINPROGRESS)
340 #endif /* ndef _WIN32 || __OS2__ */
341          {
342             break;
343          }
344
345          if (errno != EINTR)
346          {
347             socket_error = errno;
348             close_socket(fd);
349             connect_failed = 1;
350             break;
351          }
352       }
353       if (connect_failed)
354       {
355          continue;
356       }
357
358 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
359       if (flags != -1)
360       {
361          flags &= ~O_NDELAY;
362          fcntl(fd, F_SETFL, flags);
363       }
364 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
365
366       /* wait for connection to complete */
367       FD_ZERO(&wfds);
368       FD_SET(fd, &wfds);
369
370       memset(&timeout, 0, sizeof(timeout));
371       timeout.tv_sec  = 30;
372
373       /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
374       if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
375          && FD_ISSET(fd, &wfds))
376       {
377          socklen_t optlen = sizeof(socket_error);
378          if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
379          {
380             if (!socket_error)
381             {
382                /* Connection established, no need to try other addresses. */
383                break;
384             }
385             if (rp->ai_next != NULL)
386             {
387                /*
388                 * There's another address we can try, so log that this
389                 * one didn't work out. If the last one fails, too,
390                 * it will get logged outside the loop body so we don't
391                 * have to mention it here.
392                 */
393                log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
394                   csp->http->host_ip_addr_str, service, strerror(socket_error));
395             }
396          }
397          else
398          {
399             socket_error = errno;
400             log_error(LOG_LEVEL_ERROR, "Could not get the state of "
401                "the connection to [%s]:%s: %s; dropping connection.",
402                csp->http->host_ip_addr_str, service, strerror(errno));
403          }
404       }
405
406       /* Connection failed, try next address */
407       close_socket(fd);
408    }
409
410    freeaddrinfo(result);
411    if (!rp)
412    {
413       log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
414          host, service, strerror(socket_error));
415       csp->error_message = strdup(strerror(socket_error));
416       return(JB_INVALID_SOCKET);
417    }
418    log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
419       host, csp->http->host_ip_addr_str, service);
420
421    return(fd);
422
423 }
424
425 #else /* ndef HAVE_RFC2553 */
426 /* Pre-getaddrinfo implementation */
427
428 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
429 {
430    struct sockaddr_in inaddr;
431    jb_socket fd;
432    unsigned int addr;
433    fd_set wfds;
434    struct timeval tv[1];
435 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
436    int   flags;
437 #endif
438
439 #ifdef FEATURE_ACL
440    struct access_control_addr dst[1];
441 #endif /* def FEATURE_ACL */
442
443    /* Don't leak memory when retrying. */
444    freez(csp->http->host_ip_addr_str);
445
446    memset((char *)&inaddr, 0, sizeof inaddr);
447
448    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
449    {
450       csp->http->host_ip_addr_str = strdup("unknown");
451       return(JB_INVALID_SOCKET);
452    }
453
454 #ifdef FEATURE_ACL
455    dst->addr = ntohl(addr);
456    dst->port = portnum;
457
458    if (block_acl(dst, csp))
459    {
460 #ifdef __OS2__
461       errno = SOCEPERM;
462 #else
463       errno = EPERM;
464 #endif
465       return(JB_INVALID_SOCKET);
466    }
467 #endif /* def FEATURE_ACL */
468
469    inaddr.sin_addr.s_addr = addr;
470    inaddr.sin_family      = AF_INET;
471    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
472
473 #ifndef _WIN32
474    if (sizeof(inaddr.sin_port) == sizeof(short))
475 #endif /* ndef _WIN32 */
476    {
477       inaddr.sin_port = htons((unsigned short) portnum);
478    }
479 #ifndef _WIN32
480    else
481    {
482       inaddr.sin_port = htonl((unsigned long)portnum);
483    }
484 #endif /* ndef _WIN32 */
485
486    fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
487 #ifdef _WIN32
488    if (fd == JB_INVALID_SOCKET)
489 #else
490    if (fd < 0)
491 #endif
492    {
493       return(JB_INVALID_SOCKET);
494    }
495
496 #ifndef _WIN32
497    if (fd >= FD_SETSIZE)
498    {
499       log_error(LOG_LEVEL_ERROR,
500          "Server socket number too high to use select(): %d >= %d",
501          fd, FD_SETSIZE);
502       close_socket(fd);
503       return JB_INVALID_SOCKET;
504    }
505 #endif
506
507    set_no_delay_flag(fd);
508
509 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
510    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
511    {
512       flags |= O_NDELAY;
513       fcntl(fd, F_SETFL, flags);
514 #ifdef FEATURE_EXTERNAL_FILTERS
515       mark_socket_for_close_on_execute(fd);
516 #endif
517    }
518 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
519
520    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
521    {
522 #ifdef _WIN32
523       if (errno == WSAEINPROGRESS)
524 #elif __OS2__
525       if (sock_errno() == EINPROGRESS)
526 #else /* ifndef _WIN32 */
527       if (errno == EINPROGRESS)
528 #endif /* ndef _WIN32 || __OS2__ */
529       {
530          break;
531       }
532
533 #ifdef __OS2__
534       if (sock_errno() != EINTR)
535 #else
536       if (errno != EINTR)
537 #endif /* __OS2__ */
538       {
539          close_socket(fd);
540          return(JB_INVALID_SOCKET);
541       }
542    }
543
544 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
545    if (flags != -1)
546    {
547       flags &= ~O_NDELAY;
548       fcntl(fd, F_SETFL, flags);
549    }
550 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
551
552    /* wait for connection to complete */
553    FD_ZERO(&wfds);
554    FD_SET(fd, &wfds);
555
556    tv->tv_sec  = 30;
557    tv->tv_usec = 0;
558
559    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
560    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
561    {
562       close_socket(fd);
563       return(JB_INVALID_SOCKET);
564    }
565    return(fd);
566
567 }
568 #endif /* ndef HAVE_RFC2553 */
569
570
571 /*********************************************************************
572  *
573  * Function    :  write_socket
574  *
575  * Description :  Write the contents of buf (for n bytes) to socket fd.
576  *
577  * Parameters  :
578  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
579  *          2  :  buf = pointer to data to be written.
580  *          3  :  len = length of data to be written to the socket "fd".
581  *
582  * Returns     :  0 on success (entire buffer sent).
583  *                nonzero on error.
584  *
585  *********************************************************************/
586 #ifdef AMIGA
587 int write_socket(jb_socket fd, const char *buf, ssize_t len)
588 #else
589 int write_socket(jb_socket fd, const char *buf, size_t len)
590 #endif
591 {
592    if (len == 0)
593    {
594       return 0;
595    }
596
597 #ifdef FUZZ
598    if (!daemon_mode && fd <= 3)
599    {
600       log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
601       return 0;
602    }
603 #endif
604
605    log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
606
607 #if defined(_WIN32)
608    return (send(fd, buf, (int)len, 0) != (int)len);
609 #elif defined(__BEOS__) || defined(AMIGA)
610    return (send(fd, buf, len, 0) != len);
611 #elif defined(__OS2__)
612    /*
613     * Break the data up into SOCKET_SEND_MAX chunks for sending...
614     * OS/2 seemed to complain when the chunks were too large.
615     */
616 #define SOCKET_SEND_MAX 65000
617    {
618       int send_len, send_rc = 0, i = 0;
619       while ((i < len) && (send_rc != -1))
620       {
621          if ((i + SOCKET_SEND_MAX) > len)
622             send_len = len - i;
623          else
624             send_len = SOCKET_SEND_MAX;
625          send_rc = send(fd,(char*)buf + i, send_len, 0);
626          if (send_rc == -1)
627             return 1;
628          i = i + send_len;
629       }
630       return 0;
631    }
632 #else
633    return (write(fd, buf, len) != len);
634 #endif
635
636 }
637
638
639 /*********************************************************************
640  *
641  * Function    :  read_socket
642  *
643  * Description :  Read from a TCP/IP socket in a platform independent way.
644  *
645  * Parameters  :
646  *          1  :  fd = file descriptor of the socket to read
647  *          2  :  buf = pointer to buffer where data will be written
648  *                Must be >= len bytes long.
649  *          3  :  len = maximum number of bytes to read
650  *
651  * Returns     :  On success, the number of bytes read is returned (zero
652  *                indicates end of file), and the file position is advanced
653  *                by this number.  It is not an error if this number is
654  *                smaller than the number of bytes requested; this may hap-
655  *                pen for example because fewer bytes are actually available
656  *                right now (maybe because we were close to end-of-file, or
657  *                because we are reading from a pipe, or from a terminal,
658  *                or because read() was interrupted by a signal).  On error,
659  *                -1 is returned, and errno is set appropriately.  In this
660  *                case it is left unspecified whether the file position (if
661  *                any) changes.
662  *
663  *********************************************************************/
664 int read_socket(jb_socket fd, char *buf, int len)
665 {
666    int ret;
667
668    if (len <= 0)
669    {
670       return(0);
671    }
672
673 #if defined(_WIN32)
674    ret = recv(fd, buf, len, 0);
675 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
676    ret = recv(fd, buf, (size_t)len, 0);
677 #else
678    ret = (int)read(fd, buf, (size_t)len);
679 #endif
680
681    if (ret > 0)
682    {
683       log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
684    }
685
686    return ret;
687 }
688
689
690 /*********************************************************************
691  *
692  * Function    :  data_is_available
693  *
694  * Description :  Waits for data to arrive on a socket.
695  *
696  * Parameters  :
697  *          1  :  fd = file descriptor of the socket to read
698  *          2  :  seconds_to_wait = number of seconds after which we give up.
699  *
700  * Returns     :  TRUE if data arrived in time,
701  *                FALSE otherwise.
702  *
703  *********************************************************************/
704 int data_is_available(jb_socket fd, int seconds_to_wait)
705 {
706    char buf[10];
707    fd_set rfds;
708    struct timeval timeout;
709    int n;
710
711    memset(&timeout, 0, sizeof(timeout));
712    timeout.tv_sec = seconds_to_wait;
713
714 #ifdef __OS2__
715    /* Copy and pasted from jcc.c ... */
716    memset(&rfds, 0, sizeof(fd_set));
717 #else
718    FD_ZERO(&rfds);
719 #endif
720    FD_SET(fd, &rfds);
721
722    n = select(fd+1, &rfds, NULL, NULL, &timeout);
723
724    /*
725     * XXX: Do we care about the different error conditions?
726     */
727    return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
728 }
729
730
731 /*********************************************************************
732  *
733  * Function    :  close_socket
734  *
735  * Description :  Closes a TCP/IP socket
736  *
737  * Parameters  :
738  *          1  :  fd = file descriptor of socket to be closed
739  *
740  * Returns     :  void
741  *
742  *********************************************************************/
743 void close_socket(jb_socket fd)
744 {
745 #if defined(_WIN32) || defined(__BEOS__)
746    closesocket(fd);
747 #elif defined(AMIGA)
748    CloseSocket(fd);
749 #elif defined(__OS2__)
750    soclose(fd);
751 #else
752    close(fd);
753 #endif
754 }
755
756
757 /*********************************************************************
758  *
759  * Function    :  drain_and_close_socket
760  *
761  * Description :  Closes a TCP/IP socket after draining unread data
762  *
763  * Parameters  :
764  *          1  :  fd = file descriptor of the socket to be closed
765  *
766  * Returns     :  void
767  *
768  *********************************************************************/
769 void drain_and_close_socket(jb_socket fd)
770 {
771 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
772    if (socket_is_still_alive(fd))
773 #endif
774    {
775       int bytes_drained_total = 0;
776       int bytes_drained;
777
778 #ifdef HAVE_SHUTDOWN
779 /* Apparently Windows has shutdown() but not SHUT_WR. */
780 #ifndef SHUT_WR
781 #define SHUT_WR 1
782 #endif
783       if (0 != shutdown(fd, SHUT_WR))
784       {
785          log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
786       }
787 #endif
788 #define ARBITRARY_DRAIN_LIMIT 10000
789       do
790       {
791          char drainage[500];
792
793          if (!data_is_available(fd, 0))
794          {
795             /*
796              * If there is no data available right now, don't try
797              * to drain the socket as read_socket() could block.
798              */
799             break;
800          }
801
802          bytes_drained = read_socket(fd, drainage, sizeof(drainage));
803          if (bytes_drained < 0)
804          {
805             log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
806          }
807          else if (bytes_drained > 0)
808          {
809             bytes_drained_total += bytes_drained;
810             if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
811             {
812                log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
813                break;
814             }
815          }
816       } while (bytes_drained > 0);
817       if (bytes_drained_total != 0)
818       {
819          log_error(LOG_LEVEL_CONNECT,
820             "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
821       }
822    }
823
824    close_socket(fd);
825
826 }
827
828
829 /*********************************************************************
830  *
831  * Function    :  bind_port
832  *
833  * Description :  Call socket, set socket options, and listen.
834  *                Called by listen_loop to "boot up" our proxy address.
835  *
836  * Parameters  :
837  *          1  :  hostnam = TCP/IP address to bind/listen to
838  *          2  :  portnum = port to listen on
839  *          3  :  pfd = pointer used to return file descriptor.
840  *
841  * Returns     :  if success, returns 0 and sets *pfd.
842  *                if failure, returns -3 if address is in use,
843  *                                    -2 if address unresolvable,
844  *                                    -1 otherwise
845  *********************************************************************/
846 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
847 {
848 #ifdef HAVE_RFC2553
849    struct addrinfo hints;
850    struct addrinfo *result, *rp;
851    /*
852     * XXX: portnum should be a string to allow symbolic service
853     * names in the configuration file and to avoid the following
854     * int2string.
855     */
856    char servnam[6];
857    int retval;
858 #else
859    struct sockaddr_in inaddr;
860 #endif /* def HAVE_RFC2553 */
861    jb_socket fd;
862 #ifndef _WIN32
863    int one = 1;
864 #endif /* ndef _WIN32 */
865
866    *pfd = JB_INVALID_SOCKET;
867
868 #ifdef HAVE_RFC2553
869    retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
870    if ((-1 == retval) || (sizeof(servnam) <= retval))
871    {
872       log_error(LOG_LEVEL_ERROR,
873          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
874          portnum);
875       return -1;
876    }
877
878    memset(&hints, 0, sizeof(struct addrinfo));
879    if (hostnam == NULL)
880    {
881       /*
882        * XXX: This is a hack. The right thing to do
883        * would be to bind to both AF_INET and AF_INET6.
884        * This will also fail if there is no AF_INET
885        * version available.
886        */
887       hints.ai_family = AF_INET;
888    }
889    else
890    {
891       hints.ai_family = AF_UNSPEC;
892    }
893    hints.ai_socktype = SOCK_STREAM;
894    hints.ai_flags = AI_PASSIVE;
895    hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
896    hints.ai_canonname = NULL;
897    hints.ai_addr = NULL;
898    hints.ai_next = NULL;
899
900    if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
901    {
902       log_error(LOG_LEVEL_ERROR,
903          "Can not resolve %s: %s", hostnam, gai_strerror(retval));
904       return -2;
905    }
906 #else
907    memset((char *)&inaddr, '\0', sizeof inaddr);
908
909    inaddr.sin_family      = AF_INET;
910    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
911
912    if (inaddr.sin_addr.s_addr == INADDR_NONE)
913    {
914       return(-2);
915    }
916
917 #ifndef _WIN32
918    if (sizeof(inaddr.sin_port) == sizeof(short))
919 #endif /* ndef _WIN32 */
920    {
921       inaddr.sin_port = htons((unsigned short) portnum);
922    }
923 #ifndef _WIN32
924    else
925    {
926       inaddr.sin_port = htonl((unsigned long) portnum);
927    }
928 #endif /* ndef _WIN32 */
929 #endif /* def HAVE_RFC2553 */
930
931 #ifdef HAVE_RFC2553
932    for (rp = result; rp != NULL; rp = rp->ai_next)
933    {
934       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
935 #else
936    fd = socket(AF_INET, SOCK_STREAM, 0);
937 #endif /* def HAVE_RFC2553 */
938
939 #ifdef _WIN32
940    if (fd == JB_INVALID_SOCKET)
941 #else
942    if (fd < 0)
943 #endif
944    {
945 #ifdef HAVE_RFC2553
946       continue;
947 #else
948       return(-1);
949 #endif
950    }
951
952 #ifdef FEATURE_EXTERNAL_FILTERS
953    mark_socket_for_close_on_execute(fd);
954 #endif
955
956 #ifndef _WIN32
957    /*
958     * This is not needed for Win32 - in fact, it stops
959     * duplicate instances of Privoxy from being caught.
960     *
961     * On UNIX, we assume the user is sensible enough not
962     * to start Privoxy multiple times on the same IP.
963     * Without this, stopping and restarting Privoxy
964     * from a script fails.
965     * Note: SO_REUSEADDR is meant to only take over
966     * sockets which are *not* in listen state in Linux,
967     * e.g. sockets in TIME_WAIT. YMMV.
968     */
969    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
970 #endif /* ndef _WIN32 */
971
972 #ifdef HAVE_RFC2553
973    if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
974 #else
975    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
976 #endif
977    {
978 #ifdef _WIN32
979       errno = WSAGetLastError();
980       if (errno == WSAEADDRINUSE)
981 #else
982       if (errno == EADDRINUSE)
983 #endif
984       {
985 #ifdef HAVE_RFC2553
986          freeaddrinfo(result);
987 #endif
988          close_socket(fd);
989          return(-3);
990       }
991       else
992       {
993          close_socket(fd);
994 #ifndef HAVE_RFC2553
995          return(-1);
996       }
997    }
998 #else
999       }
1000    }
1001    else
1002    {
1003       /* bind() succeeded, escape from for-loop */
1004       /*
1005        * XXX: Support multiple listening sockets (e.g. localhost
1006        * resolves to AF_INET and AF_INET6, but only the first address
1007        * is used
1008        */
1009       break;
1010    }
1011    }
1012
1013    freeaddrinfo(result);
1014    if (rp == NULL)
1015    {
1016       /* All bind()s failed */
1017       return(-1);
1018    }
1019 #endif /* ndef HAVE_RFC2553 */
1020
1021    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1022    {
1023       if (errno != EINTR)
1024       {
1025          close_socket(fd);
1026          return(-1);
1027       }
1028    }
1029
1030    *pfd = fd;
1031    return 0;
1032
1033 }
1034
1035
1036 /*********************************************************************
1037  *
1038  * Function    :  get_host_information
1039  *
1040  * Description :  Determines the IP address the client used to
1041  *                reach us and the hostname associated with it.
1042  *
1043  *                XXX: Most of the code has been copy and pasted
1044  *                from accept_connection() and not all of the
1045  *                ifdefs paths have been tested afterwards.
1046  *
1047  * Parameters  :
1048  *          1  :  afd = File descriptor returned from accept().
1049  *          2  :  ip_address = Pointer to return the pointer to
1050  *                             the ip address string.
1051  *          3  :  port =       Pointer to return the pointer to
1052  *                             the TCP port string.
1053  *          4  :  hostname =   Pointer to return the pointer to
1054  *                             the hostname or NULL if the caller
1055  *                             isn't interested in it.
1056  *
1057  * Returns     :  void.
1058  *
1059  *********************************************************************/
1060 void get_host_information(jb_socket afd, char **ip_address, char **port,
1061                           char **hostname)
1062 {
1063 #ifdef HAVE_RFC2553
1064    struct sockaddr_storage server;
1065    int retval;
1066 #else
1067    struct sockaddr_in server;
1068    struct hostent *host = NULL;
1069 #endif /* HAVE_RFC2553 */
1070 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1071    /* according to accept_connection() this fixes a warning. */
1072    int s_length, s_length_provided;
1073 #else
1074    socklen_t s_length, s_length_provided;
1075 #endif
1076 #ifndef HAVE_RFC2553
1077 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1078    struct hostent result;
1079 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1080    struct hostent_data hdata;
1081 #else
1082    char hbuf[HOSTENT_BUFFER_SIZE];
1083    int thd_err;
1084 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1085 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1086 #endif /* ifndef HAVE_RFC2553 */
1087    s_length = s_length_provided = sizeof(server);
1088
1089    if (NULL != hostname)
1090    {
1091       *hostname = NULL;
1092    }
1093    *ip_address = NULL;
1094    *port = NULL;
1095
1096    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1097    {
1098       if (s_length > s_length_provided)
1099       {
1100          log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1101          return;
1102       }
1103 /*
1104  * XXX: Workaround for missing header on Windows when
1105  *      configured with --disable-ipv6-support.
1106  *      The proper fix is to not use NI_MAXSERV in
1107  *      that case. It works by accident on other platforms
1108  *      as <netdb.h> is included unconditionally there.
1109  */
1110 #ifndef NI_MAXSERV
1111 #define NI_MAXSERV 32
1112 #endif
1113       *port = malloc_or_die(NI_MAXSERV);
1114
1115 #ifdef HAVE_RFC2553
1116       *ip_address = malloc_or_die(NI_MAXHOST);
1117       retval = getnameinfo((struct sockaddr *) &server, s_length,
1118          *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1119          NI_NUMERICHOST|NI_NUMERICSERV);
1120       if (retval)
1121       {
1122          log_error(LOG_LEVEL_ERROR,
1123             "Unable to print my own IP address: %s", gai_strerror(retval));
1124          freez(*ip_address);
1125          freez(*port);
1126          return;
1127       }
1128 #else
1129       *ip_address = strdup(inet_ntoa(server.sin_addr));
1130       snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1131 #endif /* HAVE_RFC2553 */
1132       if (NULL == hostname)
1133       {
1134          /*
1135           * We're done here, the caller isn't
1136           * interested in knowing the hostname.
1137           */
1138          return;
1139       }
1140
1141 #ifdef HAVE_RFC2553
1142       *hostname = malloc_or_die(NI_MAXHOST);
1143       retval = getnameinfo((struct sockaddr *) &server, s_length,
1144          *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1145       if (retval)
1146       {
1147          log_error(LOG_LEVEL_ERROR,
1148             "Unable to resolve my own IP address: %s", gai_strerror(retval));
1149          freez(*hostname);
1150       }
1151 #else
1152 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1153       gethostbyaddr_r((const char *)&server.sin_addr,
1154                       sizeof(server.sin_addr), AF_INET,
1155                       &result, hbuf, HOSTENT_BUFFER_SIZE,
1156                       &host, &thd_err);
1157 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1158       host = gethostbyaddr_r((const char *)&server.sin_addr,
1159                       sizeof(server.sin_addr), AF_INET,
1160                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1161 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1162       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1163                                sizeof(server.sin_addr), AF_INET,
1164                                &result, &hdata))
1165       {
1166          host = &result;
1167       }
1168       else
1169       {
1170          host = NULL;
1171       }
1172 #elif defined(MUTEX_LOCKS_AVAILABLE)
1173       privoxy_mutex_lock(&resolver_mutex);
1174       host = gethostbyaddr((const char *)&server.sin_addr,
1175                            sizeof(server.sin_addr), AF_INET);
1176       privoxy_mutex_unlock(&resolver_mutex);
1177 #else
1178       host = gethostbyaddr((const char *)&server.sin_addr,
1179                            sizeof(server.sin_addr), AF_INET);
1180 #endif
1181       if (host == NULL)
1182       {
1183          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1184       }
1185       else
1186       {
1187          *hostname = strdup(host->h_name);
1188       }
1189 #endif /* else def HAVE_RFC2553 */
1190    }
1191
1192    return;
1193 }
1194
1195
1196 /*********************************************************************
1197  *
1198  * Function    :  accept_connection
1199  *
1200  * Description :  Accepts a connection on one of possibly multiple
1201  *                sockets. The socket(s) to check must have been
1202  *                created using bind_port().
1203  *
1204  * Parameters  :
1205  *          1  :  csp = Client state, cfd, ip_addr_str, and
1206  *                      ip_addr_long will be set by this routine.
1207  *          2  :  fds = File descriptors returned from bind_port
1208  *
1209  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
1210  *                On an error it returns 0 (FALSE).
1211  *
1212  *********************************************************************/
1213 int accept_connection(struct client_state * csp, jb_socket fds[])
1214 {
1215 #ifdef HAVE_RFC2553
1216    /* XXX: client is stored directly into csp->tcp_addr */
1217 #define client (csp->tcp_addr)
1218 #else
1219    struct sockaddr_in client;
1220 #endif
1221    jb_socket afd;
1222 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1223    /* Wierdness - fix a warning. */
1224    int c_length;
1225 #else
1226    socklen_t c_length;
1227 #endif
1228    int retval;
1229    int i;
1230    int max_selected_socket;
1231    fd_set selected_fds;
1232    jb_socket fd;
1233    const char *host_addr;
1234    size_t listen_addr_size;
1235
1236    c_length = sizeof(client);
1237
1238    /*
1239     * Wait for a connection on any socket.
1240     * Return immediately if no socket is listening.
1241     * XXX: Why not treat this as fatal error?
1242     */
1243    FD_ZERO(&selected_fds);
1244    max_selected_socket = 0;
1245    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1246    {
1247       if (JB_INVALID_SOCKET != fds[i])
1248       {
1249          FD_SET(fds[i], &selected_fds);
1250          if (max_selected_socket < fds[i] + 1)
1251          {
1252             max_selected_socket = fds[i] + 1;
1253          }
1254       }
1255    }
1256    if (0 == max_selected_socket)
1257    {
1258       return 0;
1259    }
1260    do
1261    {
1262       retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1263    } while (retval < 0 && errno == EINTR);
1264    if (retval <= 0)
1265    {
1266       if (0 == retval)
1267       {
1268          log_error(LOG_LEVEL_ERROR,
1269             "Waiting on new client failed because select(2) returned 0."
1270             " This should not happen.");
1271       }
1272       else
1273       {
1274          log_error(LOG_LEVEL_ERROR,
1275             "Waiting on new client failed because of problems in select(2): "
1276             "%s.", strerror(errno));
1277       }
1278       return 0;
1279    }
1280    for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1281          i++);
1282    if (i >= MAX_LISTENING_SOCKETS)
1283    {
1284       log_error(LOG_LEVEL_ERROR,
1285          "select(2) reported connected clients (number = %u, "
1286          "descriptor boundary = %u), but none found.",
1287          retval, max_selected_socket);
1288       return 0;
1289    }
1290    fd = fds[i];
1291
1292    /* Accept selected connection */
1293 #ifdef _WIN32
1294    afd = accept (fd, (struct sockaddr *) &client, &c_length);
1295    if (afd == JB_INVALID_SOCKET)
1296    {
1297       return 0;
1298    }
1299 #else
1300    do
1301    {
1302 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1303       struct accept_filter_arg af_options;
1304       bzero(&af_options, sizeof(af_options));
1305       strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1306       setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1307 #endif
1308       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1309    } while (afd < 0 && errno == EINTR);
1310    if (afd < 0)
1311    {
1312       return 0;
1313    }
1314 #endif
1315
1316 #ifdef SO_LINGER
1317    {
1318       struct linger linger_options;
1319       linger_options.l_onoff  = 1;
1320       linger_options.l_linger = 5;
1321       if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1322       {
1323          log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1324       }
1325    }
1326 #endif
1327
1328 #ifndef _WIN32
1329    if (afd >= FD_SETSIZE)
1330    {
1331       log_error(LOG_LEVEL_ERROR,
1332          "Client socket number too high to use select(): %d >= %d",
1333          afd, FD_SETSIZE);
1334       close_socket(afd);
1335       return 0;
1336    }
1337 #endif
1338
1339 #ifdef FEATURE_EXTERNAL_FILTERS
1340    mark_socket_for_close_on_execute(afd);
1341 #endif
1342
1343    set_no_delay_flag(afd);
1344
1345    csp->cfd = afd;
1346 #ifdef HAVE_RFC2553
1347    csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1348    retval = getnameinfo((struct sockaddr *) &client, c_length,
1349          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1350    if (!csp->ip_addr_str || retval)
1351    {
1352       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1353          (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1354       freez(csp->ip_addr_str);
1355    }
1356 #undef client
1357 #else
1358    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1359    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1360 #endif /* def HAVE_RFC2553 */
1361
1362    /*
1363     * Save the name and port of the accepting socket for later lookup.
1364     *
1365     * The string needs space for strlen(...) + 7 characters:
1366     * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1367     */
1368    host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1369    listen_addr_size = strlen(host_addr) + 7;
1370    csp->listen_addr_str = malloc_or_die(listen_addr_size);
1371    retval = snprintf(csp->listen_addr_str, listen_addr_size,
1372       "%s:%d", host_addr, csp->config->hport[i]);
1373    if ((-1 == retval) || listen_addr_size <= retval)
1374    {
1375       log_error(LOG_LEVEL_ERROR,
1376          "Server name (%s) and port number (%d) ASCII decimal representation"
1377          "don't fit into %d bytes",
1378          host_addr, csp->config->hport[i], listen_addr_size);
1379       return 0;
1380    }
1381
1382    return 1;
1383
1384 }
1385
1386
1387 /*********************************************************************
1388  *
1389  * Function    :  resolve_hostname_to_ip
1390  *
1391  * Description :  Resolve a hostname to an internet tcp/ip address.
1392  *                NULL or an empty string resolve to INADDR_ANY.
1393  *
1394  * Parameters  :
1395  *          1  :  host = hostname to resolve
1396  *
1397  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1398  *
1399  *********************************************************************/
1400 unsigned long resolve_hostname_to_ip(const char *host)
1401 {
1402    struct sockaddr_in inaddr;
1403    struct hostent *hostp;
1404 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1405    struct hostent result;
1406 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1407    char hbuf[HOSTENT_BUFFER_SIZE];
1408    int thd_err;
1409 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1410    struct hostent_data hdata;
1411 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1412 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1413
1414    if ((host == NULL) || (*host == '\0'))
1415    {
1416       return(INADDR_ANY);
1417    }
1418
1419    memset((char *) &inaddr, 0, sizeof inaddr);
1420
1421    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1422    {
1423       unsigned int dns_retries = 0;
1424 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1425       while (gethostbyname_r(host, &result, hbuf,
1426                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1427              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1428       {
1429          log_error(LOG_LEVEL_ERROR,
1430             "Timeout #%u while trying to resolve %s. Trying again.",
1431             dns_retries, host);
1432       }
1433 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1434       while (NULL == (hostp = gethostbyname_r(host, &result,
1435                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1436              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1437       {
1438          log_error(LOG_LEVEL_ERROR,
1439             "Timeout #%u while trying to resolve %s. Trying again.",
1440             dns_retries, host);
1441       }
1442 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1443       /*
1444        * XXX: Doesn't retry in case of soft errors.
1445        * Does this gethostbyname_r version set h_errno?
1446        */
1447       if (0 == gethostbyname_r(host, &result, &hdata))
1448       {
1449          hostp = &result;
1450       }
1451       else
1452       {
1453          hostp = NULL;
1454       }
1455 #elif defined(MUTEX_LOCKS_AVAILABLE)
1456       privoxy_mutex_lock(&resolver_mutex);
1457       while (NULL == (hostp = gethostbyname(host))
1458              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1459       {
1460          log_error(LOG_LEVEL_ERROR,
1461             "Timeout #%u while trying to resolve %s. Trying again.",
1462             dns_retries, host);
1463       }
1464       privoxy_mutex_unlock(&resolver_mutex);
1465 #else
1466       while (NULL == (hostp = gethostbyname(host))
1467              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1468       {
1469          log_error(LOG_LEVEL_ERROR,
1470             "Timeout #%u while trying to resolve %s. Trying again.",
1471             dns_retries, host);
1472       }
1473 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1474       /*
1475        * On Mac OSX, if a domain exists but doesn't have a type A
1476        * record associated with it, the h_addr member of the struct
1477        * hostent returned by gethostbyname is NULL, even if h_length
1478        * is 4. Therefore the second test below.
1479        */
1480       if (hostp == NULL || hostp->h_addr == NULL)
1481       {
1482          errno = EINVAL;
1483          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1484          return(INADDR_NONE);
1485       }
1486       if (hostp->h_addrtype != AF_INET)
1487       {
1488 #ifdef _WIN32
1489          errno = WSAEPROTOTYPE;
1490 #else
1491          errno = EPROTOTYPE;
1492 #endif
1493          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1494          return(INADDR_NONE);
1495       }
1496       memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1497    }
1498    return(inaddr.sin_addr.s_addr);
1499
1500 }
1501
1502
1503 /*********************************************************************
1504  *
1505  * Function    :  socket_is_still_alive
1506  *
1507  * Description :  Figures out whether or not a socket is still alive.
1508  *
1509  * Parameters  :
1510  *          1  :  sfd = The socket to check.
1511  *
1512  * Returns     :  TRUE for yes, otherwise FALSE.
1513  *
1514  *********************************************************************/
1515 int socket_is_still_alive(jb_socket sfd)
1516 {
1517    char buf[10];
1518    int no_data_waiting;
1519
1520 #ifdef HAVE_POLL
1521    int poll_result;
1522    struct pollfd poll_fd[1];
1523
1524    memset(poll_fd, 0, sizeof(poll_fd));
1525    poll_fd[0].fd = sfd;
1526    poll_fd[0].events = POLLIN;
1527
1528    poll_result = poll(poll_fd, 1, 0);
1529
1530    if (-1 == poll_result)
1531    {
1532       log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1533       return FALSE;
1534    }
1535    no_data_waiting = !(poll_fd[0].revents & POLLIN);
1536 #else
1537    fd_set readable_fds;
1538    struct timeval timeout;
1539    int ret;
1540
1541    memset(&timeout, '\0', sizeof(timeout));
1542    FD_ZERO(&readable_fds);
1543    FD_SET(sfd, &readable_fds);
1544
1545    ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1546    if (ret < 0)
1547    {
1548       log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1549       return FALSE;
1550    }
1551    no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1552 #endif /* def HAVE_POLL */
1553
1554    return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1555 }
1556
1557
1558 #ifdef FEATURE_EXTERNAL_FILTERS
1559 /*********************************************************************
1560  *
1561  * Function    :  mark_socket_for_close_on_execute
1562  *
1563  * Description :  Marks a socket for close on execute.
1564  *
1565  *                Used so that external filters have no direct
1566  *                access to sockets they shouldn't care about.
1567  *
1568  *                Not implemented for all platforms.
1569  *
1570  * Parameters  :
1571  *          1  :  fd = The socket to mark
1572  *
1573  * Returns     :  void.
1574  *
1575  *********************************************************************/
1576 void mark_socket_for_close_on_execute(jb_socket fd)
1577 {
1578 #ifdef FEATURE_PTHREAD
1579    int ret;
1580
1581    ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1582
1583    if (ret == -1)
1584    {
1585       log_error(LOG_LEVEL_ERROR,
1586          "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1587    }
1588 #else
1589 #warning "Sockets will be visible to external filters"
1590 #endif
1591 }
1592 #endif /* def FEATURE_EXTERNAL_FILTERS */
1593
1594 /*
1595   Local Variables:
1596   tab-width: 3
1597   end:
1598 */