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