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