Update comments that still mentioned 'show-proxy-args' instead of 'show-status'
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.144 2017/06/08 13:04:34 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
5  *
6  * Purpose     :  Contains wrappers for system-specific sockets code,
7  *                so that the rest of 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 #define MAX_LISTEN_BACKLOG 128
120
121 #ifdef HAVE_RFC2553
122 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
123 #else
124 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
125 #endif
126
127 /*********************************************************************
128  *
129  * Function    :  set_no_delay_flag
130  *
131  * Description :  Disables TCP coalescence for the given socket.
132  *
133  * Parameters  :
134  *          1  :  fd = The file descriptor to operate on
135  *
136  * Returns     :  void
137  *
138  *********************************************************************/
139 static void set_no_delay_flag(int fd)
140 {
141 #ifdef TCP_NODELAY
142    int mi = 1;
143
144    if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
145    {
146       log_error(LOG_LEVEL_ERROR,
147          "Failed to disable TCP coalescence for socket %d", fd);
148    }
149 #else
150 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
151 #endif /* def TCP_NODELAY */
152 }
153
154 /*********************************************************************
155  *
156  * Function    :  connect_to
157  *
158  * Description :  Open a socket and connect to it.  Will check
159  *                that this is allowed according to ACL.
160  *
161  * Parameters  :
162  *          1  :  host = hostname to connect to
163  *          2  :  portnum = port to connect to (XXX: should be unsigned)
164  *          3  :  csp = Current client state (buffers, headers, etc...)
165  *
166  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
167  *                file descriptor.
168  *
169  *********************************************************************/
170 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
171 {
172    jb_socket fd;
173    int forwarded_connect_retries = 0;
174
175    do
176    {
177       /*
178        * XXX: The whole errno overloading is ridiculous and should
179        *      be replaced with something sane and thread safe
180        */
181       /* errno = 0;*/
182 #ifdef HAVE_RFC2553
183       fd = rfc2553_connect_to(host, portnum, csp);
184 #else
185       fd = no_rfc2553_connect_to(host, portnum, csp);
186 #endif
187       if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
188          || (csp->fwd == NULL)
189          || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
190       {
191          break;
192       }
193       forwarded_connect_retries++;
194       if (csp->config->forwarded_connect_retries != 0)
195       {
196          log_error(LOG_LEVEL_ERROR,
197             "Attempt %d of %d to connect to %s failed. Trying again.",
198             forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
199       }
200
201    } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
202
203    return fd;
204 }
205
206 #ifdef HAVE_RFC2553
207 /* Getaddrinfo implementation */
208 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
209 {
210    struct addrinfo hints, *result, *rp;
211    char service[6];
212    int retval;
213    jb_socket fd;
214 #ifdef HAVE_POLL
215    struct pollfd poll_fd[1];
216 #else
217    fd_set wfds;
218    struct timeval timeout;
219 #endif
220 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
221    int   flags;
222 #endif
223    int connect_failed;
224    /*
225     * XXX: Initializeing it here is only necessary
226     *      because not all situations are properly
227     *      covered yet.
228     */
229    int socket_error = 0;
230
231 #ifdef FEATURE_ACL
232    struct access_control_addr dst[1];
233 #endif /* def FEATURE_ACL */
234
235    /* Don't leak memory when retrying. */
236    freez(csp->error_message);
237    freez(csp->http->host_ip_addr_str);
238
239    retval = snprintf(service, sizeof(service), "%d", portnum);
240    if ((-1 == retval) || (sizeof(service) <= retval))
241    {
242       log_error(LOG_LEVEL_ERROR,
243          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
244          portnum);
245       csp->error_message = strdup("Invalid port number");
246       csp->http->host_ip_addr_str = strdup("unknown");
247       return(JB_INVALID_SOCKET);
248    }
249
250    memset((char *)&hints, 0, sizeof(hints));
251    hints.ai_family = AF_UNSPEC;
252    hints.ai_socktype = SOCK_STREAM;
253    hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
254 #ifdef AI_ADDRCONFIG
255    hints.ai_flags |= AI_ADDRCONFIG;
256 #endif
257    if ((retval = getaddrinfo(host, service, &hints, &result)))
258    {
259       log_error(LOG_LEVEL_INFO,
260          "Can not resolve %s: %s", host, gai_strerror(retval));
261       /* XXX: Should find a better way to propagate this error. */
262       errno = EINVAL;
263       csp->error_message = strdup(gai_strerror(retval));
264       csp->http->host_ip_addr_str = strdup("unknown");
265       return(JB_INVALID_SOCKET);
266    }
267
268    csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
269
270    for (rp = result; rp != NULL; rp = rp->ai_next)
271    {
272
273 #ifdef FEATURE_ACL
274       memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
275
276       if (block_acl(dst, csp))
277       {
278 #ifdef __OS2__
279          socket_error = errno = SOCEPERM;
280 #else
281          socket_error = errno = EPERM;
282 #endif
283          continue;
284       }
285 #endif /* def FEATURE_ACL */
286
287       retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
288          csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
289       if (retval)
290       {
291          log_error(LOG_LEVEL_ERROR,
292             "Failed to get the host name from the socket structure: %s",
293             gai_strerror(retval));
294          continue;
295       }
296
297       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
298 #ifdef _WIN32
299       if (fd == JB_INVALID_SOCKET)
300 #else
301       if (fd < 0)
302 #endif
303       {
304          continue;
305       }
306
307 #ifndef HAVE_POLL
308 #ifndef _WIN32
309       if (fd >= FD_SETSIZE)
310       {
311          log_error(LOG_LEVEL_ERROR,
312             "Server socket number too high to use select(): %d >= %d",
313             fd, FD_SETSIZE);
314          close_socket(fd);
315          freeaddrinfo(result);
316          return JB_INVALID_SOCKET;
317       }
318 #endif
319 #endif
320
321 #ifdef FEATURE_EXTERNAL_FILTERS
322       mark_socket_for_close_on_execute(fd);
323 #endif
324
325       set_no_delay_flag(fd);
326
327 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
328       if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
329       {
330          flags |= O_NDELAY;
331          fcntl(fd, F_SETFL, flags);
332       }
333 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
334
335       connect_failed = 0;
336       while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
337       {
338 #ifdef __OS2__
339          errno = sock_errno();
340 #endif /* __OS2__ */
341
342 #ifdef _WIN32
343          if (errno == WSAEINPROGRESS)
344 #else /* ifndef _WIN32 */
345          if (errno == EINPROGRESS)
346 #endif /* ndef _WIN32 || __OS2__ */
347          {
348             break;
349          }
350
351          if (errno != EINTR)
352          {
353             socket_error = errno;
354             close_socket(fd);
355             connect_failed = 1;
356             break;
357          }
358       }
359       if (connect_failed)
360       {
361          continue;
362       }
363
364 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
365       if (flags != -1)
366       {
367          flags &= ~O_NDELAY;
368          fcntl(fd, F_SETFL, flags);
369       }
370 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
371
372 #ifdef HAVE_POLL
373       poll_fd[0].fd = fd;
374       poll_fd[0].events = POLLOUT;
375
376       retval = poll(poll_fd, 1, 30000);
377       if (retval == 0)
378       {
379          if (rp->ai_next != NULL)
380          {
381             /* Log this now as we'll try another address next */
382             log_error(LOG_LEVEL_CONNECT,
383                "Could not connect to [%s]:%s: Operation timed out.",
384                csp->http->host_ip_addr_str, service);
385          }
386          else
387          {
388             /*
389              * This is the last address, don't log this now
390              * as it would result in a duplicated log message.
391              */
392             socket_error = ETIMEDOUT;
393          }
394       }
395       else if (retval > 0)
396 #else
397       /* wait for connection to complete */
398       FD_ZERO(&wfds);
399       FD_SET(fd, &wfds);
400
401       memset(&timeout, 0, sizeof(timeout));
402       timeout.tv_sec  = 30;
403
404       /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
405       if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
406          && FD_ISSET(fd, &wfds))
407 #endif
408       {
409          socklen_t optlen = sizeof(socket_error);
410          if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
411          {
412             if (!socket_error)
413             {
414                /* Connection established, no need to try other addresses. */
415                break;
416             }
417             if (rp->ai_next != NULL)
418             {
419                /*
420                 * There's another address we can try, so log that this
421                 * one didn't work out. If the last one fails, too,
422                 * it will get logged outside the loop body so we don't
423                 * have to mention it here.
424                 */
425                log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
426                   csp->http->host_ip_addr_str, service, strerror(socket_error));
427             }
428          }
429          else
430          {
431             socket_error = errno;
432             log_error(LOG_LEVEL_ERROR, "Could not get the state of "
433                "the connection to [%s]:%s: %s; dropping connection.",
434                csp->http->host_ip_addr_str, service, strerror(errno));
435          }
436       }
437
438       /* Connection failed, try next address */
439       close_socket(fd);
440    }
441
442    freeaddrinfo(result);
443    if (!rp)
444    {
445       log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
446          host, service, strerror(socket_error));
447       csp->error_message = strdup(strerror(socket_error));
448       return(JB_INVALID_SOCKET);
449    }
450    log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
451       host, csp->http->host_ip_addr_str, service);
452
453    return(fd);
454
455 }
456
457 #else /* ndef HAVE_RFC2553 */
458 /* Pre-getaddrinfo implementation */
459
460 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
461 {
462    struct sockaddr_in inaddr;
463    jb_socket fd;
464    unsigned int addr;
465 #ifdef HAVE_POLL
466    struct pollfd poll_fd[1];
467 #else
468    fd_set wfds;
469    struct timeval tv[1];
470 #endif
471 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
472    int   flags;
473 #endif
474
475 #ifdef FEATURE_ACL
476    struct access_control_addr dst[1];
477 #endif /* def FEATURE_ACL */
478
479    /* Don't leak memory when retrying. */
480    freez(csp->http->host_ip_addr_str);
481
482    memset((char *)&inaddr, 0, sizeof inaddr);
483
484    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
485    {
486       csp->http->host_ip_addr_str = strdup("unknown");
487       return(JB_INVALID_SOCKET);
488    }
489
490 #ifdef FEATURE_ACL
491    dst->addr = ntohl(addr);
492    dst->port = portnum;
493
494    if (block_acl(dst, csp))
495    {
496 #ifdef __OS2__
497       errno = SOCEPERM;
498 #else
499       errno = EPERM;
500 #endif
501       return(JB_INVALID_SOCKET);
502    }
503 #endif /* def FEATURE_ACL */
504
505    inaddr.sin_addr.s_addr = addr;
506    inaddr.sin_family      = AF_INET;
507    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
508
509 #ifndef _WIN32
510    if (sizeof(inaddr.sin_port) == sizeof(short))
511 #endif /* ndef _WIN32 */
512    {
513       inaddr.sin_port = htons((unsigned short) portnum);
514    }
515 #ifndef _WIN32
516    else
517    {
518       inaddr.sin_port = htonl((unsigned long)portnum);
519    }
520 #endif /* ndef _WIN32 */
521
522    fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
523 #ifdef _WIN32
524    if (fd == JB_INVALID_SOCKET)
525 #else
526    if (fd < 0)
527 #endif
528    {
529       return(JB_INVALID_SOCKET);
530    }
531
532 #ifndef HAVE_POLL
533 #ifndef _WIN32
534    if (fd >= FD_SETSIZE)
535    {
536       log_error(LOG_LEVEL_ERROR,
537          "Server socket number too high to use select(): %d >= %d",
538          fd, FD_SETSIZE);
539       close_socket(fd);
540       return JB_INVALID_SOCKET;
541    }
542 #endif
543 #endif
544
545    set_no_delay_flag(fd);
546
547 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
548    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
549    {
550       flags |= O_NDELAY;
551       fcntl(fd, F_SETFL, flags);
552 #ifdef FEATURE_EXTERNAL_FILTERS
553       mark_socket_for_close_on_execute(fd);
554 #endif
555    }
556 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
557
558    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
559    {
560 #ifdef _WIN32
561       if (errno == WSAEINPROGRESS)
562 #elif __OS2__
563       if (sock_errno() == EINPROGRESS)
564 #else /* ifndef _WIN32 */
565       if (errno == EINPROGRESS)
566 #endif /* ndef _WIN32 || __OS2__ */
567       {
568          break;
569       }
570
571 #ifdef __OS2__
572       if (sock_errno() != EINTR)
573 #else
574       if (errno != EINTR)
575 #endif /* __OS2__ */
576       {
577          close_socket(fd);
578          return(JB_INVALID_SOCKET);
579       }
580    }
581
582 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
583    if (flags != -1)
584    {
585       flags &= ~O_NDELAY;
586       fcntl(fd, F_SETFL, flags);
587    }
588 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
589
590 #ifdef HAVE_POLL
591    poll_fd[0].fd = fd;
592    poll_fd[0].events = POLLOUT;
593
594    if (poll(poll_fd, 1, 30000) <= 0)
595 #else
596    /* wait for connection to complete */
597    FD_ZERO(&wfds);
598    FD_SET(fd, &wfds);
599
600    tv->tv_sec  = 30;
601    tv->tv_usec = 0;
602
603    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
604    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
605 #endif
606    {
607       close_socket(fd);
608       return(JB_INVALID_SOCKET);
609    }
610    return(fd);
611
612 }
613 #endif /* ndef HAVE_RFC2553 */
614
615
616 /*********************************************************************
617  *
618  * Function    :  write_socket
619  *
620  * Description :  Write the contents of buf (for n bytes) to socket fd.
621  *
622  * Parameters  :
623  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
624  *          2  :  buf = pointer to data to be written.
625  *          3  :  len = length of data to be written to the socket "fd".
626  *
627  * Returns     :  0 on success (entire buffer sent).
628  *                nonzero on error.
629  *
630  *********************************************************************/
631 #ifdef AMIGA
632 int write_socket(jb_socket fd, const char *buf, ssize_t len)
633 #else
634 int write_socket(jb_socket fd, const char *buf, size_t len)
635 #endif
636 {
637    if (len == 0)
638    {
639       return 0;
640    }
641
642 #ifdef FUZZ
643    if (!daemon_mode && fd <= 3)
644    {
645       log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
646       return 0;
647    }
648 #endif
649
650    log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
651
652 #if defined(_WIN32)
653    return (send(fd, buf, (int)len, 0) != (int)len);
654 #elif defined(__BEOS__) || defined(AMIGA)
655    return (send(fd, buf, len, 0) != len);
656 #elif defined(__OS2__)
657    /*
658     * Break the data up into SOCKET_SEND_MAX chunks for sending...
659     * OS/2 seemed to complain when the chunks were too large.
660     */
661 #define SOCKET_SEND_MAX 65000
662    {
663       int send_len, send_rc = 0, i = 0;
664       while ((i < len) && (send_rc != -1))
665       {
666          if ((i + SOCKET_SEND_MAX) > len)
667             send_len = len - i;
668          else
669             send_len = SOCKET_SEND_MAX;
670          send_rc = send(fd,(char*)buf + i, send_len, 0);
671          if (send_rc == -1)
672             return 1;
673          i = i + send_len;
674       }
675       return 0;
676    }
677 #else
678    return (write(fd, buf, len) != len);
679 #endif
680
681 }
682
683
684 /*********************************************************************
685  *
686  * Function    :  read_socket
687  *
688  * Description :  Read from a TCP/IP socket in a platform independent way.
689  *
690  * Parameters  :
691  *          1  :  fd = file descriptor of the socket to read
692  *          2  :  buf = pointer to buffer where data will be written
693  *                Must be >= len bytes long.
694  *          3  :  len = maximum number of bytes to read
695  *
696  * Returns     :  On success, the number of bytes read is returned (zero
697  *                indicates end of file), and the file position is advanced
698  *                by this number.  It is not an error if this number is
699  *                smaller than the number of bytes requested; this may hap-
700  *                pen for example because fewer bytes are actually available
701  *                right now (maybe because we were close to end-of-file, or
702  *                because we are reading from a pipe, or from a terminal,
703  *                or because read() was interrupted by a signal).  On error,
704  *                -1 is returned, and errno is set appropriately.  In this
705  *                case it is left unspecified whether the file position (if
706  *                any) changes.
707  *
708  *********************************************************************/
709 int read_socket(jb_socket fd, char *buf, int len)
710 {
711    int ret;
712
713    if (len <= 0)
714    {
715       return(0);
716    }
717
718 #if defined(_WIN32)
719    ret = recv(fd, buf, len, 0);
720 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
721    ret = recv(fd, buf, (size_t)len, 0);
722 #else
723    ret = (int)read(fd, buf, (size_t)len);
724 #endif
725
726    if (ret > 0)
727    {
728       log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
729    }
730
731    return ret;
732 }
733
734
735 /*********************************************************************
736  *
737  * Function    :  data_is_available
738  *
739  * Description :  Waits for data to arrive on a socket.
740  *
741  * Parameters  :
742  *          1  :  fd = file descriptor of the socket to read
743  *          2  :  seconds_to_wait = number of seconds after which we give up.
744  *
745  * Returns     :  TRUE if data arrived in time,
746  *                FALSE otherwise.
747  *
748  *********************************************************************/
749 int data_is_available(jb_socket fd, int seconds_to_wait)
750 {
751    int n;
752    char buf[10];
753 #ifdef HAVE_POLL
754    struct pollfd poll_fd[1];
755
756    poll_fd[0].fd = fd;
757    poll_fd[0].events = POLLIN;
758
759    n = poll(poll_fd, 1, seconds_to_wait * 1000);
760 #else
761    fd_set rfds;
762    struct timeval timeout;
763
764    memset(&timeout, 0, sizeof(timeout));
765    timeout.tv_sec = seconds_to_wait;
766
767 #ifdef __OS2__
768    /* Copy and pasted from jcc.c ... */
769    memset(&rfds, 0, sizeof(fd_set));
770 #else
771    FD_ZERO(&rfds);
772 #endif
773    FD_SET(fd, &rfds);
774
775    n = select(fd+1, &rfds, NULL, NULL, &timeout);
776 #endif
777
778    /*
779     * XXX: Do we care about the different error conditions?
780     */
781    return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
782 }
783
784
785 /*********************************************************************
786  *
787  * Function    :  close_socket
788  *
789  * Description :  Closes a TCP/IP socket
790  *
791  * Parameters  :
792  *          1  :  fd = file descriptor of socket to be closed
793  *
794  * Returns     :  void
795  *
796  *********************************************************************/
797 void close_socket(jb_socket fd)
798 {
799 #if defined(_WIN32) || defined(__BEOS__)
800    closesocket(fd);
801 #elif defined(AMIGA)
802    CloseSocket(fd);
803 #elif defined(__OS2__)
804    soclose(fd);
805 #else
806    close(fd);
807 #endif
808 }
809
810
811 /*********************************************************************
812  *
813  * Function    :  drain_and_close_socket
814  *
815  * Description :  Closes a TCP/IP socket after draining unread data
816  *
817  * Parameters  :
818  *          1  :  fd = file descriptor of the socket to be closed
819  *
820  * Returns     :  void
821  *
822  *********************************************************************/
823 void drain_and_close_socket(jb_socket fd)
824 {
825 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
826    if (socket_is_still_alive(fd))
827 #endif
828    {
829       int bytes_drained_total = 0;
830       int bytes_drained;
831
832 #ifdef HAVE_SHUTDOWN
833 /* Apparently Windows has shutdown() but not SHUT_WR. */
834 #ifndef SHUT_WR
835 #define SHUT_WR 1
836 #endif
837       if (0 != shutdown(fd, SHUT_WR))
838       {
839          log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
840       }
841 #endif
842 #define ARBITRARY_DRAIN_LIMIT 10000
843       do
844       {
845          char drainage[500];
846
847          if (!data_is_available(fd, 0))
848          {
849             /*
850              * If there is no data available right now, don't try
851              * to drain the socket as read_socket() could block.
852              */
853             break;
854          }
855
856          bytes_drained = read_socket(fd, drainage, sizeof(drainage));
857          if (bytes_drained < 0)
858          {
859             log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
860          }
861          else if (bytes_drained > 0)
862          {
863             bytes_drained_total += bytes_drained;
864             if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
865             {
866                log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
867                break;
868             }
869          }
870       } while (bytes_drained > 0);
871       if (bytes_drained_total != 0)
872       {
873          log_error(LOG_LEVEL_CONNECT,
874             "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
875       }
876    }
877
878    close_socket(fd);
879
880 }
881
882
883 /*********************************************************************
884  *
885  * Function    :  bind_port
886  *
887  * Description :  Call socket, set socket options, and listen.
888  *                Called by listen_loop to "boot up" our proxy address.
889  *
890  * Parameters  :
891  *          1  :  hostnam = TCP/IP address to bind/listen to
892  *          2  :  portnum = port to listen on
893  *          3  :  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, 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, MAX_LISTEN_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 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1381       struct accept_filter_arg af_options;
1382       bzero(&af_options, sizeof(af_options));
1383       strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1384       setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1385 #endif
1386       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1387    } while (afd < 0 && errno == EINTR);
1388    if (afd < 0)
1389    {
1390       return 0;
1391    }
1392 #endif
1393
1394 #ifdef SO_LINGER
1395    {
1396       struct linger linger_options;
1397       linger_options.l_onoff  = 1;
1398       linger_options.l_linger = 5;
1399       if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1400       {
1401          log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1402       }
1403    }
1404 #endif
1405
1406 #ifndef HAVE_POLL
1407 #ifndef _WIN32
1408    if (afd >= FD_SETSIZE)
1409    {
1410       log_error(LOG_LEVEL_ERROR,
1411          "Client socket number too high to use select(): %d >= %d",
1412          afd, FD_SETSIZE);
1413       close_socket(afd);
1414       return 0;
1415    }
1416 #endif
1417 #endif
1418
1419 #ifdef FEATURE_EXTERNAL_FILTERS
1420    mark_socket_for_close_on_execute(afd);
1421 #endif
1422
1423    set_no_delay_flag(afd);
1424
1425    csp->cfd = afd;
1426 #ifdef HAVE_RFC2553
1427    csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1428    retval = getnameinfo((struct sockaddr *) &client, c_length,
1429          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1430    if (!csp->ip_addr_str || retval)
1431    {
1432       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1433          (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1434       freez(csp->ip_addr_str);
1435    }
1436 #undef client
1437 #else
1438    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1439    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1440 #endif /* def HAVE_RFC2553 */
1441
1442    /*
1443     * Save the name and port of the accepting socket for later lookup.
1444     *
1445     * The string needs space for strlen(...) + 7 characters:
1446     * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1447     */
1448    host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1449    listen_addr_size = strlen(host_addr) + 7;
1450    csp->listen_addr_str = malloc_or_die(listen_addr_size);
1451    retval = snprintf(csp->listen_addr_str, listen_addr_size,
1452       "%s:%d", host_addr, csp->config->hport[i]);
1453    if ((-1 == retval) || listen_addr_size <= retval)
1454    {
1455       log_error(LOG_LEVEL_ERROR,
1456          "Server name (%s) and port number (%d) ASCII decimal representation"
1457          "don't fit into %d bytes",
1458          host_addr, csp->config->hport[i], listen_addr_size);
1459       return 0;
1460    }
1461
1462    return 1;
1463
1464 }
1465
1466
1467 /*********************************************************************
1468  *
1469  * Function    :  resolve_hostname_to_ip
1470  *
1471  * Description :  Resolve a hostname to an internet tcp/ip address.
1472  *                NULL or an empty string resolve to INADDR_ANY.
1473  *
1474  * Parameters  :
1475  *          1  :  host = hostname to resolve
1476  *
1477  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1478  *
1479  *********************************************************************/
1480 unsigned long resolve_hostname_to_ip(const char *host)
1481 {
1482    struct sockaddr_in inaddr;
1483    struct hostent *hostp;
1484 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1485    struct hostent result;
1486 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1487    char hbuf[HOSTENT_BUFFER_SIZE];
1488    int thd_err;
1489 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1490    struct hostent_data hdata;
1491 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1492 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1493
1494    if ((host == NULL) || (*host == '\0'))
1495    {
1496       return(INADDR_ANY);
1497    }
1498
1499    memset((char *) &inaddr, 0, sizeof inaddr);
1500
1501    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1502    {
1503       unsigned int dns_retries = 0;
1504 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1505       while (gethostbyname_r(host, &result, hbuf,
1506                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1507              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1508       {
1509          log_error(LOG_LEVEL_ERROR,
1510             "Timeout #%u while trying to resolve %s. Trying again.",
1511             dns_retries, host);
1512       }
1513 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1514       while (NULL == (hostp = gethostbyname_r(host, &result,
1515                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1516              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1517       {
1518          log_error(LOG_LEVEL_ERROR,
1519             "Timeout #%u while trying to resolve %s. Trying again.",
1520             dns_retries, host);
1521       }
1522 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1523       /*
1524        * XXX: Doesn't retry in case of soft errors.
1525        * Does this gethostbyname_r version set h_errno?
1526        */
1527       if (0 == gethostbyname_r(host, &result, &hdata))
1528       {
1529          hostp = &result;
1530       }
1531       else
1532       {
1533          hostp = NULL;
1534       }
1535 #elif defined(MUTEX_LOCKS_AVAILABLE)
1536       privoxy_mutex_lock(&resolver_mutex);
1537       while (NULL == (hostp = gethostbyname(host))
1538              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1539       {
1540          log_error(LOG_LEVEL_ERROR,
1541             "Timeout #%u while trying to resolve %s. Trying again.",
1542             dns_retries, host);
1543       }
1544       privoxy_mutex_unlock(&resolver_mutex);
1545 #else
1546       while (NULL == (hostp = gethostbyname(host))
1547              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1548       {
1549          log_error(LOG_LEVEL_ERROR,
1550             "Timeout #%u while trying to resolve %s. Trying again.",
1551             dns_retries, host);
1552       }
1553 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1554       /*
1555        * On Mac OSX, if a domain exists but doesn't have a type A
1556        * record associated with it, the h_addr member of the struct
1557        * hostent returned by gethostbyname is NULL, even if h_length
1558        * is 4. Therefore the second test below.
1559        */
1560       if (hostp == NULL || hostp->h_addr == NULL)
1561       {
1562          errno = EINVAL;
1563          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1564          return(INADDR_NONE);
1565       }
1566       if (hostp->h_addrtype != AF_INET)
1567       {
1568 #ifdef _WIN32
1569          errno = WSAEPROTOTYPE;
1570 #else
1571          errno = EPROTOTYPE;
1572 #endif
1573          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1574          return(INADDR_NONE);
1575       }
1576       memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1577    }
1578    return(inaddr.sin_addr.s_addr);
1579
1580 }
1581
1582
1583 /*********************************************************************
1584  *
1585  * Function    :  socket_is_still_alive
1586  *
1587  * Description :  Figures out whether or not a socket is still alive.
1588  *
1589  * Parameters  :
1590  *          1  :  sfd = The socket to check.
1591  *
1592  * Returns     :  TRUE for yes, otherwise FALSE.
1593  *
1594  *********************************************************************/
1595 int socket_is_still_alive(jb_socket sfd)
1596 {
1597    char buf[10];
1598    int no_data_waiting;
1599 #ifdef HAVE_POLL
1600    int poll_result;
1601    struct pollfd poll_fd[1];
1602
1603    memset(poll_fd, 0, sizeof(poll_fd));
1604    poll_fd[0].fd = sfd;
1605    poll_fd[0].events = POLLIN;
1606
1607    poll_result = poll(poll_fd, 1, 0);
1608
1609    if (-1 == poll_result)
1610    {
1611       log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1612       return FALSE;
1613    }
1614    no_data_waiting = !(poll_fd[0].revents & POLLIN);
1615 #else
1616    fd_set readable_fds;
1617    struct timeval timeout;
1618    int ret;
1619
1620    memset(&timeout, '\0', sizeof(timeout));
1621    FD_ZERO(&readable_fds);
1622    FD_SET(sfd, &readable_fds);
1623
1624    ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1625    if (ret < 0)
1626    {
1627       log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1628       return FALSE;
1629    }
1630    no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1631 #endif /* def HAVE_POLL */
1632
1633    return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1634 }
1635
1636
1637 #ifdef FEATURE_EXTERNAL_FILTERS
1638 /*********************************************************************
1639  *
1640  * Function    :  mark_socket_for_close_on_execute
1641  *
1642  * Description :  Marks a socket for close on execute.
1643  *
1644  *                Used so that external filters have no direct
1645  *                access to sockets they shouldn't care about.
1646  *
1647  *                Not implemented for all platforms.
1648  *
1649  * Parameters  :
1650  *          1  :  fd = The socket to mark
1651  *
1652  * Returns     :  void.
1653  *
1654  *********************************************************************/
1655 void mark_socket_for_close_on_execute(jb_socket fd)
1656 {
1657 #ifdef FEATURE_PTHREAD
1658    int ret;
1659
1660    ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1661
1662    if (ret == -1)
1663    {
1664       log_error(LOG_LEVEL_ERROR,
1665          "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1666    }
1667 #else
1668 #warning "Sockets will be visible to external filters"
1669 #endif
1670 }
1671 #endif /* def FEATURE_EXTERNAL_FILTERS */
1672
1673 /*
1674   Local Variables:
1675   tab-width: 3
1676   end:
1677 */