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