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