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