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