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