182382b33b5ca6efee277214cd61a9bfbf387688
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.137 2016/08/22 14:50:18 fabiankeil 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    log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
598
599 #if defined(_WIN32)
600    return (send(fd, buf, (int)len, 0) != (int)len);
601 #elif defined(__BEOS__) || defined(AMIGA)
602    return (send(fd, buf, len, 0) != len);
603 #elif defined(__OS2__)
604    /*
605     * Break the data up into SOCKET_SEND_MAX chunks for sending...
606     * OS/2 seemed to complain when the chunks were too large.
607     */
608 #define SOCKET_SEND_MAX 65000
609    {
610       int send_len, send_rc = 0, i = 0;
611       while ((i < len) && (send_rc != -1))
612       {
613          if ((i + SOCKET_SEND_MAX) > len)
614             send_len = len - i;
615          else
616             send_len = SOCKET_SEND_MAX;
617          send_rc = send(fd,(char*)buf + i, send_len, 0);
618          if (send_rc == -1)
619             return 1;
620          i = i + send_len;
621       }
622       return 0;
623    }
624 #else
625    return (write(fd, buf, len) != len);
626 #endif
627
628 }
629
630
631 /*********************************************************************
632  *
633  * Function    :  read_socket
634  *
635  * Description :  Read from a TCP/IP socket in a platform independent way.
636  *
637  * Parameters  :
638  *          1  :  fd = file descriptor of the socket to read
639  *          2  :  buf = pointer to buffer where data will be written
640  *                Must be >= len bytes long.
641  *          3  :  len = maximum number of bytes to read
642  *
643  * Returns     :  On success, the number of bytes read is returned (zero
644  *                indicates end of file), and the file position is advanced
645  *                by this number.  It is not an error if this number is
646  *                smaller than the number of bytes requested; this may hap-
647  *                pen for example because fewer bytes are actually available
648  *                right now (maybe because we were close to end-of-file, or
649  *                because we are reading from a pipe, or from a terminal,
650  *                or because read() was interrupted by a signal).  On error,
651  *                -1 is returned, and errno is set appropriately.  In this
652  *                case it is left unspecified whether the file position (if
653  *                any) changes.
654  *
655  *********************************************************************/
656 int read_socket(jb_socket fd, char *buf, int len)
657 {
658    int ret;
659
660    if (len <= 0)
661    {
662       return(0);
663    }
664
665 #if defined(_WIN32)
666    ret = recv(fd, buf, len, 0);
667 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
668    ret = recv(fd, buf, (size_t)len, 0);
669 #else
670    ret = (int)read(fd, buf, (size_t)len);
671 #endif
672
673    if (ret > 0)
674    {
675       log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
676    }
677
678    return ret;
679 }
680
681
682 /*********************************************************************
683  *
684  * Function    :  data_is_available
685  *
686  * Description :  Waits for data to arrive on a socket.
687  *
688  * Parameters  :
689  *          1  :  fd = file descriptor of the socket to read
690  *          2  :  seconds_to_wait = number of seconds after which we give up.
691  *
692  * Returns     :  TRUE if data arrived in time,
693  *                FALSE otherwise.
694  *
695  *********************************************************************/
696 int data_is_available(jb_socket fd, int seconds_to_wait)
697 {
698    char buf[10];
699    fd_set rfds;
700    struct timeval timeout;
701    int n;
702
703    memset(&timeout, 0, sizeof(timeout));
704    timeout.tv_sec = seconds_to_wait;
705
706 #ifdef __OS2__
707    /* Copy and pasted from jcc.c ... */
708    memset(&rfds, 0, sizeof(fd_set));
709 #else
710    FD_ZERO(&rfds);
711 #endif
712    FD_SET(fd, &rfds);
713
714    n = select(fd+1, &rfds, NULL, NULL, &timeout);
715
716    /*
717     * XXX: Do we care about the different error conditions?
718     */
719    return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
720 }
721
722
723 /*********************************************************************
724  *
725  * Function    :  close_socket
726  *
727  * Description :  Closes a TCP/IP socket
728  *
729  * Parameters  :
730  *          1  :  fd = file descriptor of socket to be closed
731  *
732  * Returns     :  void
733  *
734  *********************************************************************/
735 void close_socket(jb_socket fd)
736 {
737 #if defined(_WIN32) || defined(__BEOS__)
738    closesocket(fd);
739 #elif defined(AMIGA)
740    CloseSocket(fd);
741 #elif defined(__OS2__)
742    soclose(fd);
743 #else
744    close(fd);
745 #endif
746 }
747
748
749 /*********************************************************************
750  *
751  * Function    :  drain_and_close_socket
752  *
753  * Description :  Closes a TCP/IP socket after draining unread data
754  *
755  * Parameters  :
756  *          1  :  fd = file descriptor of the socket to be closed
757  *
758  * Returns     :  void
759  *
760  *********************************************************************/
761 void drain_and_close_socket(jb_socket fd)
762 {
763 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
764    if (socket_is_still_alive(fd))
765 #endif
766    {
767       int bytes_drained_total = 0;
768       int bytes_drained;
769
770 #ifdef HAVE_SHUTDOWN
771 /* Apparently Windows has shutdown() but not SHUT_WR. */
772 #ifndef SHUT_WR
773 #define SHUT_WR 1
774 #endif
775       if (0 != shutdown(fd, SHUT_WR))
776       {
777          log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
778       }
779 #endif
780 #define ARBITRARY_DRAIN_LIMIT 10000
781       do
782       {
783          char drainage[500];
784
785          if (!data_is_available(fd, 0))
786          {
787             /*
788              * If there is no data available right now, don't try
789              * to drain the socket as read_socket() could block.
790              */
791             break;
792          }
793
794          bytes_drained = read_socket(fd, drainage, sizeof(drainage));
795          if (bytes_drained < 0)
796          {
797             log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
798          }
799          else if (bytes_drained > 0)
800          {
801             bytes_drained_total += bytes_drained;
802             if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
803             {
804                log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
805                break;
806             }
807          }
808       } while (bytes_drained > 0);
809       if (bytes_drained_total != 0)
810       {
811          log_error(LOG_LEVEL_CONNECT,
812             "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
813       }
814    }
815
816    close_socket(fd);
817
818 }
819
820
821 /*********************************************************************
822  *
823  * Function    :  bind_port
824  *
825  * Description :  Call socket, set socket options, and listen.
826  *                Called by listen_loop to "boot up" our proxy address.
827  *
828  * Parameters  :
829  *          1  :  hostnam = TCP/IP address to bind/listen to
830  *          2  :  portnum = port to listen on
831  *          3  :  pfd = pointer used to return file descriptor.
832  *
833  * Returns     :  if success, returns 0 and sets *pfd.
834  *                if failure, returns -3 if address is in use,
835  *                                    -2 if address unresolvable,
836  *                                    -1 otherwise
837  *********************************************************************/
838 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
839 {
840 #ifdef HAVE_RFC2553
841    struct addrinfo hints;
842    struct addrinfo *result, *rp;
843    /*
844     * XXX: portnum should be a string to allow symbolic service
845     * names in the configuration file and to avoid the following
846     * int2string.
847     */
848    char servnam[6];
849    int retval;
850 #else
851    struct sockaddr_in inaddr;
852 #endif /* def HAVE_RFC2553 */
853    jb_socket fd;
854 #ifndef _WIN32
855    int one = 1;
856 #endif /* ndef _WIN32 */
857
858    *pfd = JB_INVALID_SOCKET;
859
860 #ifdef HAVE_RFC2553
861    retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
862    if ((-1 == retval) || (sizeof(servnam) <= retval))
863    {
864       log_error(LOG_LEVEL_ERROR,
865          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
866          portnum);
867       return -1;
868    }
869
870    memset(&hints, 0, sizeof(struct addrinfo));
871    if (hostnam == NULL)
872    {
873       /*
874        * XXX: This is a hack. The right thing to do
875        * would be to bind to both AF_INET and AF_INET6.
876        * This will also fail if there is no AF_INET
877        * version available.
878        */
879       hints.ai_family = AF_INET;
880    }
881    else
882    {
883       hints.ai_family = AF_UNSPEC;
884    }
885    hints.ai_socktype = SOCK_STREAM;
886    hints.ai_flags = AI_PASSIVE;
887    hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
888    hints.ai_canonname = NULL;
889    hints.ai_addr = NULL;
890    hints.ai_next = NULL;
891
892    if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
893    {
894       log_error(LOG_LEVEL_ERROR,
895          "Can not resolve %s: %s", hostnam, gai_strerror(retval));
896       return -2;
897    }
898 #else
899    memset((char *)&inaddr, '\0', sizeof inaddr);
900
901    inaddr.sin_family      = AF_INET;
902    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
903
904    if (inaddr.sin_addr.s_addr == INADDR_NONE)
905    {
906       return(-2);
907    }
908
909 #ifndef _WIN32
910    if (sizeof(inaddr.sin_port) == sizeof(short))
911 #endif /* ndef _WIN32 */
912    {
913       inaddr.sin_port = htons((unsigned short) portnum);
914    }
915 #ifndef _WIN32
916    else
917    {
918       inaddr.sin_port = htonl((unsigned long) portnum);
919    }
920 #endif /* ndef _WIN32 */
921 #endif /* def HAVE_RFC2553 */
922
923 #ifdef HAVE_RFC2553
924    for (rp = result; rp != NULL; rp = rp->ai_next)
925    {
926       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
927 #else
928    fd = socket(AF_INET, SOCK_STREAM, 0);
929 #endif /* def HAVE_RFC2553 */
930
931 #ifdef _WIN32
932    if (fd == JB_INVALID_SOCKET)
933 #else
934    if (fd < 0)
935 #endif
936    {
937 #ifdef HAVE_RFC2553
938       continue;
939 #else
940       return(-1);
941 #endif
942    }
943
944 #ifdef FEATURE_EXTERNAL_FILTERS
945    mark_socket_for_close_on_execute(fd);
946 #endif
947
948 #ifndef _WIN32
949    /*
950     * This is not needed for Win32 - in fact, it stops
951     * duplicate instances of Privoxy from being caught.
952     *
953     * On UNIX, we assume the user is sensible enough not
954     * to start Privoxy multiple times on the same IP.
955     * Without this, stopping and restarting Privoxy
956     * from a script fails.
957     * Note: SO_REUSEADDR is meant to only take over
958     * sockets which are *not* in listen state in Linux,
959     * e.g. sockets in TIME_WAIT. YMMV.
960     */
961    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
962 #endif /* ndef _WIN32 */
963
964 #ifdef HAVE_RFC2553
965    if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
966 #else
967    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
968 #endif
969    {
970 #ifdef _WIN32
971       errno = WSAGetLastError();
972       if (errno == WSAEADDRINUSE)
973 #else
974       if (errno == EADDRINUSE)
975 #endif
976       {
977 #ifdef HAVE_RFC2553
978          freeaddrinfo(result);
979 #endif
980          close_socket(fd);
981          return(-3);
982       }
983       else
984       {
985          close_socket(fd);
986 #ifndef HAVE_RFC2553
987          return(-1);
988       }
989    }
990 #else
991       }
992    }
993    else
994    {
995       /* bind() succeeded, escape from for-loop */
996       /*
997        * XXX: Support multiple listening sockets (e.g. localhost
998        * resolves to AF_INET and AF_INET6, but only the first address
999        * is used
1000        */
1001       break;
1002    }
1003    }
1004
1005    freeaddrinfo(result);
1006    if (rp == NULL)
1007    {
1008       /* All bind()s failed */
1009       return(-1);
1010    }
1011 #endif /* ndef HAVE_RFC2553 */
1012
1013    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1014    {
1015       if (errno != EINTR)
1016       {
1017          close_socket(fd);
1018          return(-1);
1019       }
1020    }
1021
1022    *pfd = fd;
1023    return 0;
1024
1025 }
1026
1027
1028 /*********************************************************************
1029  *
1030  * Function    :  get_host_information
1031  *
1032  * Description :  Determines the IP address the client used to
1033  *                reach us and the hostname associated with it.
1034  *
1035  *                XXX: Most of the code has been copy and pasted
1036  *                from accept_connection() and not all of the
1037  *                ifdefs paths have been tested afterwards.
1038  *
1039  * Parameters  :
1040  *          1  :  afd = File descriptor returned from accept().
1041  *          2  :  ip_address = Pointer to return the pointer to
1042  *                             the ip address string.
1043  *          3  :  port =       Pointer to return the pointer to
1044  *                             the TCP port string.
1045  *          4  :  hostname =   Pointer to return the pointer to
1046  *                             the hostname or NULL if the caller
1047  *                             isn't interested in it.
1048  *
1049  * Returns     :  void.
1050  *
1051  *********************************************************************/
1052 void get_host_information(jb_socket afd, char **ip_address, char **port,
1053                           char **hostname)
1054 {
1055 #ifdef HAVE_RFC2553
1056    struct sockaddr_storage server;
1057    int retval;
1058 #else
1059    struct sockaddr_in server;
1060    struct hostent *host = NULL;
1061 #endif /* HAVE_RFC2553 */
1062 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1063    /* according to accept_connection() this fixes a warning. */
1064    int s_length, s_length_provided;
1065 #else
1066    socklen_t s_length, s_length_provided;
1067 #endif
1068 #ifndef HAVE_RFC2553
1069 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1070    struct hostent result;
1071 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1072    struct hostent_data hdata;
1073 #else
1074    char hbuf[HOSTENT_BUFFER_SIZE];
1075    int thd_err;
1076 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1077 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1078 #endif /* ifndef HAVE_RFC2553 */
1079    s_length = s_length_provided = sizeof(server);
1080
1081    if (NULL != hostname)
1082    {
1083       *hostname = NULL;
1084    }
1085    *ip_address = NULL;
1086    *port = NULL;
1087
1088    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1089    {
1090       if (s_length > s_length_provided)
1091       {
1092          log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1093          return;
1094       }
1095 /*
1096  * XXX: Workaround for missing header on Windows when
1097  *      configured with --disable-ipv6-support.
1098  *      The proper fix is to not use NI_MAXSERV in
1099  *      that case. It works by accident on other platforms
1100  *      as <netdb.h> is included unconditionally there.
1101  */
1102 #ifndef NI_MAXSERV
1103 #define NI_MAXSERV 32
1104 #endif
1105       *port = malloc_or_die(NI_MAXSERV);
1106
1107 #ifdef HAVE_RFC2553
1108       *ip_address = malloc_or_die(NI_MAXHOST);
1109       retval = getnameinfo((struct sockaddr *) &server, s_length,
1110          *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1111          NI_NUMERICHOST|NI_NUMERICSERV);
1112       if (retval)
1113       {
1114          log_error(LOG_LEVEL_ERROR,
1115             "Unable to print my own IP address: %s", gai_strerror(retval));
1116          freez(*ip_address);
1117          freez(*port);
1118          return;
1119       }
1120 #else
1121       *ip_address = strdup(inet_ntoa(server.sin_addr));
1122       snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1123 #endif /* HAVE_RFC2553 */
1124       if (NULL == hostname)
1125       {
1126          /*
1127           * We're done here, the caller isn't
1128           * interested in knowing the hostname.
1129           */
1130          return;
1131       }
1132
1133 #ifdef HAVE_RFC2553
1134       *hostname = malloc_or_die(NI_MAXHOST);
1135       retval = getnameinfo((struct sockaddr *) &server, s_length,
1136          *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1137       if (retval)
1138       {
1139          log_error(LOG_LEVEL_ERROR,
1140             "Unable to resolve my own IP address: %s", gai_strerror(retval));
1141          freez(*hostname);
1142       }
1143 #else
1144 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1145       gethostbyaddr_r((const char *)&server.sin_addr,
1146                       sizeof(server.sin_addr), AF_INET,
1147                       &result, hbuf, HOSTENT_BUFFER_SIZE,
1148                       &host, &thd_err);
1149 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1150       host = gethostbyaddr_r((const char *)&server.sin_addr,
1151                       sizeof(server.sin_addr), AF_INET,
1152                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1153 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1154       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1155                                sizeof(server.sin_addr), AF_INET,
1156                                &result, &hdata))
1157       {
1158          host = &result;
1159       }
1160       else
1161       {
1162          host = NULL;
1163       }
1164 #elif defined(MUTEX_LOCKS_AVAILABLE)
1165       privoxy_mutex_lock(&resolver_mutex);
1166       host = gethostbyaddr((const char *)&server.sin_addr,
1167                            sizeof(server.sin_addr), AF_INET);
1168       privoxy_mutex_unlock(&resolver_mutex);
1169 #else
1170       host = gethostbyaddr((const char *)&server.sin_addr,
1171                            sizeof(server.sin_addr), AF_INET);
1172 #endif
1173       if (host == NULL)
1174       {
1175          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1176       }
1177       else
1178       {
1179          *hostname = strdup(host->h_name);
1180       }
1181 #endif /* else def HAVE_RFC2553 */
1182    }
1183
1184    return;
1185 }
1186
1187
1188 /*********************************************************************
1189  *
1190  * Function    :  accept_connection
1191  *
1192  * Description :  Accepts a connection on one of possibly multiple
1193  *                sockets. The socket(s) to check must have been
1194  *                created using bind_port().
1195  *
1196  * Parameters  :
1197  *          1  :  csp = Client state, cfd, ip_addr_str, and
1198  *                      ip_addr_long will be set by this routine.
1199  *          2  :  fds = File descriptors returned from bind_port
1200  *
1201  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
1202  *                On an error it returns 0 (FALSE).
1203  *
1204  *********************************************************************/
1205 int accept_connection(struct client_state * csp, jb_socket fds[])
1206 {
1207 #ifdef HAVE_RFC2553
1208    /* XXX: client is stored directly into csp->tcp_addr */
1209 #define client (csp->tcp_addr)
1210 #else
1211    struct sockaddr_in client;
1212 #endif
1213    jb_socket afd;
1214 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1215    /* Wierdness - fix a warning. */
1216    int c_length;
1217 #else
1218    socklen_t c_length;
1219 #endif
1220    int retval;
1221    int i;
1222    int max_selected_socket;
1223    fd_set selected_fds;
1224    jb_socket fd;
1225    const char *host_addr;
1226    size_t listen_addr_size;
1227
1228    c_length = sizeof(client);
1229
1230    /*
1231     * Wait for a connection on any socket.
1232     * Return immediately if no socket is listening.
1233     * XXX: Why not treat this as fatal error?
1234     */
1235    FD_ZERO(&selected_fds);
1236    max_selected_socket = 0;
1237    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1238    {
1239       if (JB_INVALID_SOCKET != fds[i])
1240       {
1241          FD_SET(fds[i], &selected_fds);
1242          if (max_selected_socket < fds[i] + 1)
1243          {
1244             max_selected_socket = fds[i] + 1;
1245          }
1246       }
1247    }
1248    if (0 == max_selected_socket)
1249    {
1250       return 0;
1251    }
1252    do
1253    {
1254       retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1255    } while (retval < 0 && errno == EINTR);
1256    if (retval <= 0)
1257    {
1258       if (0 == retval)
1259       {
1260          log_error(LOG_LEVEL_ERROR,
1261             "Waiting on new client failed because select(2) returned 0."
1262             " This should not happen.");
1263       }
1264       else
1265       {
1266          log_error(LOG_LEVEL_ERROR,
1267             "Waiting on new client failed because of problems in select(2): "
1268             "%s.", strerror(errno));
1269       }
1270       return 0;
1271    }
1272    for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1273          i++);
1274    if (i >= MAX_LISTENING_SOCKETS)
1275    {
1276       log_error(LOG_LEVEL_ERROR,
1277          "select(2) reported connected clients (number = %u, "
1278          "descriptor boundary = %u), but none found.",
1279          retval, max_selected_socket);
1280       return 0;
1281    }
1282    fd = fds[i];
1283
1284    /* Accept selected connection */
1285 #ifdef _WIN32
1286    afd = accept (fd, (struct sockaddr *) &client, &c_length);
1287    if (afd == JB_INVALID_SOCKET)
1288    {
1289       return 0;
1290    }
1291 #else
1292    do
1293    {
1294 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1295       struct accept_filter_arg af_options;
1296       bzero(&af_options, sizeof(af_options));
1297       strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1298       setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1299 #endif
1300       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1301    } while (afd < 0 && errno == EINTR);
1302    if (afd < 0)
1303    {
1304       return 0;
1305    }
1306 #endif
1307
1308 #ifdef SO_LINGER
1309    {
1310       struct linger linger_options;
1311       linger_options.l_onoff  = 1;
1312       linger_options.l_linger = 5;
1313       if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1314       {
1315          log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1316       }
1317    }
1318 #endif
1319
1320 #ifndef _WIN32
1321    if (afd >= FD_SETSIZE)
1322    {
1323       log_error(LOG_LEVEL_ERROR,
1324          "Client socket number too high to use select(): %d >= %d",
1325          afd, FD_SETSIZE);
1326       close_socket(afd);
1327       return 0;
1328    }
1329 #endif
1330
1331 #ifdef FEATURE_EXTERNAL_FILTERS
1332    mark_socket_for_close_on_execute(afd);
1333 #endif
1334
1335    set_no_delay_flag(afd);
1336
1337    csp->cfd = afd;
1338 #ifdef HAVE_RFC2553
1339    csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1340    retval = getnameinfo((struct sockaddr *) &client, c_length,
1341          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1342    if (!csp->ip_addr_str || retval)
1343    {
1344       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1345          (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1346       freez(csp->ip_addr_str);
1347    }
1348 #undef client
1349 #else
1350    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1351    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1352 #endif /* def HAVE_RFC2553 */
1353
1354    /*
1355     * Save the name and port of the accepting socket for later lookup.
1356     *
1357     * The string needs space for strlen(...) + 7 characters:
1358     * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1359     */
1360    host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1361    listen_addr_size = strlen(host_addr) + 7;
1362    csp->listen_addr_str = malloc_or_die(listen_addr_size);
1363    retval = snprintf(csp->listen_addr_str, listen_addr_size,
1364       "%s:%d", host_addr, csp->config->hport[i]);
1365    if ((-1 == retval) || listen_addr_size <= retval)
1366    {
1367       log_error(LOG_LEVEL_ERROR,
1368          "Server name (%s) and port number (%d) ASCII decimal representation"
1369          "don't fit into %d bytes",
1370          host_addr, csp->config->hport[i], listen_addr_size);
1371       return 0;
1372    }
1373
1374    return 1;
1375
1376 }
1377
1378
1379 /*********************************************************************
1380  *
1381  * Function    :  resolve_hostname_to_ip
1382  *
1383  * Description :  Resolve a hostname to an internet tcp/ip address.
1384  *                NULL or an empty string resolve to INADDR_ANY.
1385  *
1386  * Parameters  :
1387  *          1  :  host = hostname to resolve
1388  *
1389  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1390  *
1391  *********************************************************************/
1392 unsigned long resolve_hostname_to_ip(const char *host)
1393 {
1394    struct sockaddr_in inaddr;
1395    struct hostent *hostp;
1396 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1397    struct hostent result;
1398 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1399    char hbuf[HOSTENT_BUFFER_SIZE];
1400    int thd_err;
1401 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1402    struct hostent_data hdata;
1403 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1404 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1405
1406    if ((host == NULL) || (*host == '\0'))
1407    {
1408       return(INADDR_ANY);
1409    }
1410
1411    memset((char *) &inaddr, 0, sizeof inaddr);
1412
1413    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1414    {
1415       unsigned int dns_retries = 0;
1416 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1417       while (gethostbyname_r(host, &result, hbuf,
1418                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1419              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1420       {
1421          log_error(LOG_LEVEL_ERROR,
1422             "Timeout #%u while trying to resolve %s. Trying again.",
1423             dns_retries, host);
1424       }
1425 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1426       while (NULL == (hostp = gethostbyname_r(host, &result,
1427                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1428              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1429       {
1430          log_error(LOG_LEVEL_ERROR,
1431             "Timeout #%u while trying to resolve %s. Trying again.",
1432             dns_retries, host);
1433       }
1434 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1435       /*
1436        * XXX: Doesn't retry in case of soft errors.
1437        * Does this gethostbyname_r version set h_errno?
1438        */
1439       if (0 == gethostbyname_r(host, &result, &hdata))
1440       {
1441          hostp = &result;
1442       }
1443       else
1444       {
1445          hostp = NULL;
1446       }
1447 #elif defined(MUTEX_LOCKS_AVAILABLE)
1448       privoxy_mutex_lock(&resolver_mutex);
1449       while (NULL == (hostp = gethostbyname(host))
1450              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1451       {
1452          log_error(LOG_LEVEL_ERROR,
1453             "Timeout #%u while trying to resolve %s. Trying again.",
1454             dns_retries, host);
1455       }
1456       privoxy_mutex_unlock(&resolver_mutex);
1457 #else
1458       while (NULL == (hostp = gethostbyname(host))
1459              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1460       {
1461          log_error(LOG_LEVEL_ERROR,
1462             "Timeout #%u while trying to resolve %s. Trying again.",
1463             dns_retries, host);
1464       }
1465 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1466       /*
1467        * On Mac OSX, if a domain exists but doesn't have a type A
1468        * record associated with it, the h_addr member of the struct
1469        * hostent returned by gethostbyname is NULL, even if h_length
1470        * is 4. Therefore the second test below.
1471        */
1472       if (hostp == NULL || hostp->h_addr == NULL)
1473       {
1474          errno = EINVAL;
1475          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1476          return(INADDR_NONE);
1477       }
1478       if (hostp->h_addrtype != AF_INET)
1479       {
1480 #ifdef _WIN32
1481          errno = WSAEPROTOTYPE;
1482 #else
1483          errno = EPROTOTYPE;
1484 #endif
1485          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1486          return(INADDR_NONE);
1487       }
1488       memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1489    }
1490    return(inaddr.sin_addr.s_addr);
1491
1492 }
1493
1494
1495 /*********************************************************************
1496  *
1497  * Function    :  socket_is_still_alive
1498  *
1499  * Description :  Figures out whether or not a socket is still alive.
1500  *
1501  * Parameters  :
1502  *          1  :  sfd = The socket to check.
1503  *
1504  * Returns     :  TRUE for yes, otherwise FALSE.
1505  *
1506  *********************************************************************/
1507 int socket_is_still_alive(jb_socket sfd)
1508 {
1509    char buf[10];
1510    int no_data_waiting;
1511
1512 #ifdef HAVE_POLL
1513    int poll_result;
1514    struct pollfd poll_fd[1];
1515
1516    memset(poll_fd, 0, sizeof(poll_fd));
1517    poll_fd[0].fd = sfd;
1518    poll_fd[0].events = POLLIN;
1519
1520    poll_result = poll(poll_fd, 1, 0);
1521
1522    if (-1 == poll_result)
1523    {
1524       log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1525       return FALSE;
1526    }
1527    no_data_waiting = !(poll_fd[0].revents & POLLIN);
1528 #else
1529    fd_set readable_fds;
1530    struct timeval timeout;
1531    int ret;
1532
1533    memset(&timeout, '\0', sizeof(timeout));
1534    FD_ZERO(&readable_fds);
1535    FD_SET(sfd, &readable_fds);
1536
1537    ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1538    if (ret < 0)
1539    {
1540       log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1541       return FALSE;
1542    }
1543    no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1544 #endif /* def HAVE_POLL */
1545
1546    return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1547 }
1548
1549
1550 #ifdef FEATURE_EXTERNAL_FILTERS
1551 /*********************************************************************
1552  *
1553  * Function    :  mark_socket_for_close_on_execute
1554  *
1555  * Description :  Marks a socket for close on execute.
1556  *
1557  *                Used so that external filters have no direct
1558  *                access to sockets they shouldn't care about.
1559  *
1560  *                Not implemented for all platforms.
1561  *
1562  * Parameters  :
1563  *          1  :  fd = The socket to mark
1564  *
1565  * Returns     :  void.
1566  *
1567  *********************************************************************/
1568 void mark_socket_for_close_on_execute(jb_socket fd)
1569 {
1570 #ifdef FEATURE_PTHREAD
1571    int ret;
1572
1573    ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1574
1575    if (ret == -1)
1576    {
1577       log_error(LOG_LEVEL_ERROR,
1578          "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1579    }
1580 #else
1581 #warning "Sockets will be visible to external filters"
1582 #endif
1583 }
1584 #endif /* def FEATURE_EXTERNAL_FILTERS */
1585
1586 /*
1587   Local Variables:
1588   tab-width: 3
1589   end:
1590 */