a287c765218b66bcf8df18e2d127cb6e8c7fce20
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.86 2011/03/27 13:55:09 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 Junkbuster 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-2010 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 <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 FEATURE_CONNECTION_KEEP_ALIVE
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 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
95
96 #include "project.h"
97
98 /* For mutex semaphores only */
99 #include "jcc.h"
100
101 #include "jbsockets.h"
102 #include "filters.h"
103 #include "errlog.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    :  connect_to
130  *
131  * Description :  Open a socket and connect to it.  Will check
132  *                that this is allowed according to ACL.
133  *
134  * Parameters  :
135  *          1  :  host = hostname to connect to
136  *          2  :  portnum = port to connent on (XXX: should be unsigned)
137  *          3  :  csp = Current client state (buffers, headers, etc...)
138  *
139  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
140  *                file descriptor.
141  *
142  *********************************************************************/
143 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
144 {
145    jb_socket fd;
146    int forwarded_connect_retries = 0;
147
148    do
149    {
150 #ifdef HAVE_RFC2553
151       fd = rfc2553_connect_to(host, portnum, csp);
152 #else
153       fd = no_rfc2553_connect_to(host, portnum, csp);
154 #endif
155       if ((fd != JB_INVALID_SOCKET) || (errno != EINVAL))
156       {
157          break;
158       }
159       forwarded_connect_retries++;
160       log_error(LOG_LEVEL_ERROR,
161          "Attempt %d of %d to connect to %s failed. Trying again.",
162          forwarded_connect_retries, csp->config->forwarded_connect_retries, host);
163
164    } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
165
166    return fd;
167 }
168
169 #ifdef HAVE_RFC2553
170 /* Getaddrinfo implementation */
171 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
172 {
173    struct addrinfo hints, *result, *rp;
174    char service[6];
175    int retval;
176    jb_socket fd;
177    fd_set wfds;
178    struct timeval tv[1];
179 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
180    int   flags;
181 #endif
182    int connect_failed;
183    int socket_error;
184
185 #ifdef FEATURE_ACL
186    struct access_control_addr dst[1];
187 #endif /* def FEATURE_ACL */
188
189    /* Don't leak memory when retrying. */
190    freez(csp->error_message);
191
192    retval = snprintf(service, sizeof(service), "%d", portnum);
193    if ((-1 == retval) || (sizeof(service) <= retval))
194    {
195       log_error(LOG_LEVEL_ERROR,
196          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
197          portnum);
198       csp->error_message = strdup("Invalid port number");
199       csp->http->host_ip_addr_str = strdup("unknown");
200       return(JB_INVALID_SOCKET);
201    }
202
203    memset((char *)&hints, 0, sizeof(hints));
204    hints.ai_family = AF_UNSPEC;
205    hints.ai_socktype = SOCK_STREAM;
206    hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
207 #ifdef AI_ADDRCONFIG
208    hints.ai_flags |= AI_ADDRCONFIG;
209 #endif
210    if ((retval = getaddrinfo(host, service, &hints, &result)))
211    {
212       log_error(LOG_LEVEL_INFO,
213          "Can not resolve %s: %s", host, gai_strerror(retval));
214       /* XXX: Should find a better way to propagate this error. */
215       errno = EINVAL;
216       csp->error_message = strdup(gai_strerror(retval));
217       csp->http->host_ip_addr_str = strdup("unknown");
218       return(JB_INVALID_SOCKET);
219    }
220
221    csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
222    if (NULL == csp->http->host_ip_addr_str)
223    {
224       log_error(LOG_LEVEL_ERROR,
225          "Out of memory while getting the server IP address.");
226       return JB_INVALID_SOCKET;
227    }
228
229    for (rp = result; rp != NULL; rp = rp->ai_next)
230    {
231
232 #ifdef FEATURE_ACL
233       memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
234
235       if (block_acl(dst, csp))
236       {
237 #ifdef __OS2__
238          socket_error = errno = SOCEPERM;
239 #else
240          socket_error = errno = EPERM;
241 #endif
242          continue;
243       }
244 #endif /* def FEATURE_ACL */
245
246       retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
247          csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
248       if (retval)
249       {
250          log_error(LOG_LEVEL_ERROR,
251             "Can not save csp->http->host_ip_addr_str: %s",
252             gai_strerror(retval));
253          continue;
254       }
255
256 #ifdef _WIN32
257       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
258             JB_INVALID_SOCKET)
259 #else
260       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
261 #endif
262       {
263          continue;
264       }
265
266 #ifdef TCP_NODELAY
267       {  /* turn off TCP coalescence */
268          int mi = 1;
269          setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
270       }
271 #endif /* def TCP_NODELAY */
272
273 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
274       if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
275       {
276          flags |= O_NDELAY;
277          fcntl(fd, F_SETFL, flags);
278       }
279 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
280
281       connect_failed = 0;
282       while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
283       {
284 #ifdef _WIN32
285          if (errno == WSAEINPROGRESS)
286 #elif __OS2__
287          if (sock_errno() == EINPROGRESS)
288 #else /* ifndef _WIN32 */
289          if (errno == EINPROGRESS)
290 #endif /* ndef _WIN32 || __OS2__ */
291          {
292             break;
293          }
294
295 #ifdef __OS2__
296          if (sock_errno() != EINTR)
297 #else
298          if (errno != EINTR)
299 #endif /* __OS2__ */
300          {
301             close_socket(fd);
302             connect_failed = 1;
303             break;
304          }
305       }
306       if (connect_failed)
307       {
308          continue;
309       }
310
311 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
312       if (flags != -1)
313       {
314          flags &= ~O_NDELAY;
315          fcntl(fd, F_SETFL, flags);
316       }
317 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
318
319       /* wait for connection to complete */
320       FD_ZERO(&wfds);
321       FD_SET(fd, &wfds);
322
323       tv->tv_sec  = 30;
324       tv->tv_usec = 0;
325
326       /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
327       if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
328          && FD_ISSET(fd, &wfds))
329       {
330          socklen_t optlen = sizeof(socket_error);
331          if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
332          {
333             if (!socket_error)
334             {
335                /* Connection established, no need to try other addresses. */
336                break;
337             }
338             log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
339                csp->http->host_ip_addr_str, service, strerror(socket_error));
340          }
341          else
342          {
343             socket_error = errno;
344             log_error(LOG_LEVEL_ERROR, "Could not get the state of "
345                "the connection to [%s]:%s: %s; dropping connection.",
346                csp->http->host_ip_addr_str, service, strerror(errno));
347          }
348       }
349
350       /* Connection failed, try next address */
351       close_socket(fd);
352    }
353
354    freeaddrinfo(result);
355    if (!rp)
356    {
357       log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
358          host, service, strerror(socket_error));
359       csp->error_message = strdup(strerror(socket_error));
360       return(JB_INVALID_SOCKET);
361    }
362    log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
363       host, csp->http->host_ip_addr_str, service);
364
365    return(fd);
366
367 }
368
369 #else /* ndef HAVE_RFC2553 */
370 /* Pre-getaddrinfo implementation */
371
372 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
373 {
374    struct sockaddr_in inaddr;
375    jb_socket fd;
376    unsigned int addr;
377    fd_set wfds;
378    struct timeval tv[1];
379 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
380    int   flags;
381 #endif
382
383 #ifdef FEATURE_ACL
384    struct access_control_addr dst[1];
385 #endif /* def FEATURE_ACL */
386
387    memset((char *)&inaddr, 0, sizeof inaddr);
388
389    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
390    {
391       csp->http->host_ip_addr_str = strdup("unknown");
392       return(JB_INVALID_SOCKET);
393    }
394
395 #ifdef FEATURE_ACL
396    dst->addr = ntohl(addr);
397    dst->port = portnum;
398
399    if (block_acl(dst, csp))
400    {
401 #ifdef __OS2__
402       errno = SOCEPERM;
403 #else
404       errno = EPERM;
405 #endif
406       return(JB_INVALID_SOCKET);
407    }
408 #endif /* def FEATURE_ACL */
409
410    inaddr.sin_addr.s_addr = addr;
411    inaddr.sin_family      = AF_INET;
412    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
413
414 #ifndef _WIN32
415    if (sizeof(inaddr.sin_port) == sizeof(short))
416 #endif /* ndef _WIN32 */
417    {
418       inaddr.sin_port = htons((unsigned short) portnum);
419    }
420 #ifndef _WIN32
421    else
422    {
423       inaddr.sin_port = htonl((unsigned long)portnum);
424    }
425 #endif /* ndef _WIN32 */
426
427 #ifdef _WIN32
428    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
429 #else
430    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
431 #endif
432    {
433       return(JB_INVALID_SOCKET);
434    }
435
436 #ifdef TCP_NODELAY
437    {  /* turn off TCP coalescence */
438       int mi = 1;
439       setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
440    }
441 #endif /* def TCP_NODELAY */
442
443 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
444    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
445    {
446       flags |= O_NDELAY;
447       fcntl(fd, F_SETFL, flags);
448    }
449 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
450
451    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
452    {
453 #ifdef _WIN32
454       if (errno == WSAEINPROGRESS)
455 #elif __OS2__ 
456       if (sock_errno() == EINPROGRESS)
457 #else /* ifndef _WIN32 */
458       if (errno == EINPROGRESS)
459 #endif /* ndef _WIN32 || __OS2__ */
460       {
461          break;
462       }
463
464 #ifdef __OS2__ 
465       if (sock_errno() != EINTR)
466 #else
467       if (errno != EINTR)
468 #endif /* __OS2__ */
469       {
470          close_socket(fd);
471          return(JB_INVALID_SOCKET);
472       }
473    }
474
475 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
476    if (flags != -1)
477    {
478       flags &= ~O_NDELAY;
479       fcntl(fd, F_SETFL, flags);
480    }
481 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
482
483    /* wait for connection to complete */
484    FD_ZERO(&wfds);
485    FD_SET(fd, &wfds);
486
487    tv->tv_sec  = 30;
488    tv->tv_usec = 0;
489
490    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
491    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
492    {
493       close_socket(fd);
494       return(JB_INVALID_SOCKET);
495    }
496    return(fd);
497
498 }
499 #endif /* ndef HAVE_RFC2553 */
500
501
502 /*********************************************************************
503  *
504  * Function    :  write_socket
505  *
506  * Description :  Write the contents of buf (for n bytes) to socket fd.
507  *
508  * Parameters  :
509  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
510  *          2  :  buf = pointer to data to be written.
511  *          3  :  len = length of data to be written to the socket "fd".
512  *
513  * Returns     :  0 on success (entire buffer sent).
514  *                nonzero on error.
515  *
516  *********************************************************************/
517 #ifdef AMIGA
518 int write_socket(jb_socket fd, const char *buf, ssize_t len)
519 #else
520 int write_socket(jb_socket fd, const char *buf, size_t len)
521 #endif
522 {
523    if (len == 0)
524    {
525       return 0;
526    }
527
528    if (len < 0) /* constant condition - size_t isn't ever negative */ 
529    {
530       return 1;
531    }
532
533    log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
534
535 #if defined(_WIN32)
536    return (send(fd, buf, (int)len, 0) != (int)len);
537 #elif defined(__BEOS__) || defined(AMIGA)
538    return (send(fd, buf, len, 0) != len);
539 #elif defined(__OS2__)
540    /*
541     * Break the data up into SOCKET_SEND_MAX chunks for sending...
542     * OS/2 seemed to complain when the chunks were too large.
543     */
544 #define SOCKET_SEND_MAX 65000
545    {
546       int send_len, send_rc = 0, i = 0;
547       while ((i < len) && (send_rc != -1))
548       {
549          if ((i + SOCKET_SEND_MAX) > len)
550             send_len = len - i;
551          else
552             send_len = SOCKET_SEND_MAX;
553          send_rc = send(fd,(char*)buf + i, send_len, 0);
554          if (send_rc == -1)
555             return 1;
556          i = i + send_len;
557       }
558       return 0;
559    }
560 #else
561    return (write(fd, buf, len) != len);
562 #endif
563
564 }
565
566
567 /*********************************************************************
568  *
569  * Function    :  read_socket
570  *
571  * Description :  Read from a TCP/IP socket in a platform independent way.
572  *
573  * Parameters  :
574  *          1  :  fd = file descriptor of the socket to read
575  *          2  :  buf = pointer to buffer where data will be written
576  *                Must be >= len bytes long.
577  *          3  :  len = maximum number of bytes to read
578  *
579  * Returns     :  On success, the number of bytes read is returned (zero
580  *                indicates end of file), and the file position is advanced
581  *                by this number.  It is not an error if this number is
582  *                smaller than the number of bytes requested; this may hap-
583  *                pen for example because fewer bytes are actually available
584  *                right now (maybe because we were close to end-of-file, or
585  *                because we are reading from a pipe, or from a terminal,
586  *                or because read() was interrupted by a signal).  On error,
587  *                -1 is returned, and errno is set appropriately.  In this
588  *                case it is left unspecified whether the file position (if
589  *                any) changes.
590  *
591  *********************************************************************/
592 int read_socket(jb_socket fd, char *buf, int len)
593 {
594    int ret;
595
596    if (len <= 0)
597    {
598       return(0);
599    }
600
601 #if defined(_WIN32)
602    ret = recv(fd, buf, len, 0);
603 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
604    ret = recv(fd, buf, (size_t)len, 0);
605 #else
606    ret = (int)read(fd, buf, (size_t)len);
607 #endif
608
609    if (ret > 0)
610    {
611       log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
612    }
613
614    return ret;
615 }
616
617
618 /*********************************************************************
619  *
620  * Function    :  data_is_available
621  *
622  * Description :  Waits for data to arrive on a socket.
623  *
624  * Parameters  :
625  *          1  :  fd = file descriptor of the socket to read
626  *          2  :  seconds_to_wait = number of seconds after which we give up.
627  *
628  * Returns     :  TRUE if data arrived in time,
629  *                FALSE otherwise.
630  *
631  *********************************************************************/
632 int data_is_available(jb_socket fd, int seconds_to_wait)
633 {
634    char buf[10];
635    fd_set rfds;
636    struct timeval timeout;
637    int n;
638
639    memset(&timeout, 0, sizeof(timeout));
640    timeout.tv_sec = seconds_to_wait;
641
642 #ifdef __OS2__
643    /* Copy and pasted from jcc.c ... */
644    memset(&rfds, 0, sizeof(fd_set));
645 #else
646    FD_ZERO(&rfds);
647 #endif
648    FD_SET(fd, &rfds);
649
650    n = select(fd+1, &rfds, NULL, NULL, &timeout);
651
652    /*
653     * XXX: Do we care about the different error conditions?
654     */
655    return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
656 }
657
658
659 /*********************************************************************
660  *
661  * Function    :  close_socket
662  *
663  * Description :  Closes a TCP/IP socket
664  *
665  * Parameters  :
666  *          1  :  fd = file descriptor of socket to be closed
667  *
668  * Returns     :  void
669  *
670  *********************************************************************/
671 void close_socket(jb_socket fd)
672 {
673 #if defined(_WIN32) || defined(__BEOS__)
674    closesocket(fd);
675 #elif defined(AMIGA)
676    CloseSocket(fd); 
677 #elif defined(__OS2__)
678    soclose(fd);
679 #else
680    close(fd);
681 #endif
682
683 }
684
685
686 /*********************************************************************
687  *
688  * Function    :  bind_port
689  *
690  * Description :  Call socket, set socket options, and listen.
691  *                Called by listen_loop to "boot up" our proxy address.
692  *
693  * Parameters  :
694  *          1  :  hostnam = TCP/IP address to bind/listen to
695  *          2  :  portnum = port to listen on
696  *          3  :  pfd = pointer used to return file descriptor.
697  *
698  * Returns     :  if success, returns 0 and sets *pfd.
699  *                if failure, returns -3 if address is in use,
700  *                                    -2 if address unresolvable,
701  *                                    -1 otherwise
702  *********************************************************************/
703 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
704 {
705 #ifdef HAVE_RFC2553
706    struct addrinfo hints;
707    struct addrinfo *result, *rp;
708    /*
709     * XXX: portnum should be a string to allow symbolic service
710     * names in the configuration file and to avoid the following
711     * int2string.
712     */
713    char servnam[6];
714    int retval;
715 #else
716    struct sockaddr_in inaddr;
717 #endif /* def HAVE_RFC2553 */
718    jb_socket fd;
719 #ifndef _WIN32
720    int one = 1;
721 #endif /* ndef _WIN32 */
722
723    *pfd = JB_INVALID_SOCKET;
724
725 #ifdef HAVE_RFC2553
726    retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
727    if ((-1 == retval) || (sizeof(servnam) <= retval))
728    {
729       log_error(LOG_LEVEL_ERROR,
730          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
731          portnum);
732       return -1;
733    }
734
735    memset(&hints, 0, sizeof(struct addrinfo));
736    if (hostnam == NULL)
737    {
738       /*
739        * XXX: This is a hack. The right thing to do
740        * would be to bind to both AF_INET and AF_INET6.
741        * This will also fail if there is no AF_INET
742        * version available.
743        */
744       hints.ai_family = AF_INET;
745    }
746    else
747    {
748       hints.ai_family = AF_UNSPEC;
749    }
750    hints.ai_socktype = SOCK_STREAM;
751    hints.ai_flags = AI_PASSIVE;
752 #ifdef AI_ADDRCONFIG
753    hints.ai_flags |= AI_ADDRCONFIG;
754 #endif
755    hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
756    hints.ai_canonname = NULL;
757    hints.ai_addr = NULL;
758    hints.ai_next = NULL;
759
760    if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
761    {
762       log_error(LOG_LEVEL_ERROR,
763          "Can not resolve %s: %s", hostnam, gai_strerror(retval));
764       return -2;
765    }
766 #else
767    memset((char *)&inaddr, '\0', sizeof inaddr);
768
769    inaddr.sin_family      = AF_INET;
770    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
771
772    if (inaddr.sin_addr.s_addr == INADDR_NONE)
773    {
774       return(-2);
775    }
776
777 #ifndef _WIN32
778    if (sizeof(inaddr.sin_port) == sizeof(short))
779 #endif /* ndef _WIN32 */
780    {
781       inaddr.sin_port = htons((unsigned short) portnum);
782    }
783 #ifndef _WIN32
784    else
785    {
786       inaddr.sin_port = htonl((unsigned long) portnum);
787    }
788 #endif /* ndef _WIN32 */
789 #endif /* def HAVE_RFC2553 */
790
791 #ifdef HAVE_RFC2553
792    for (rp = result; rp != NULL; rp = rp->ai_next)
793    {
794       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
795 #else
796    fd = socket(AF_INET, SOCK_STREAM, 0);
797 #endif /* def HAVE_RFC2553 */
798
799 #ifdef _WIN32
800    if (fd == JB_INVALID_SOCKET)
801 #else
802    if (fd < 0)
803 #endif
804    {
805 #ifdef HAVE_RFC2553
806       continue;
807 #else
808       return(-1);
809 #endif
810    }
811
812 #ifndef _WIN32
813    /*
814     * This is not needed for Win32 - in fact, it stops
815     * duplicate instances of Privoxy from being caught.
816     *
817     * On UNIX, we assume the user is sensible enough not
818     * to start Privoxy multiple times on the same IP.
819     * Without this, stopping and restarting Privoxy
820     * from a script fails.
821     * Note: SO_REUSEADDR is meant to only take over
822     * sockets which are *not* in listen state in Linux,
823     * e.g. sockets in TIME_WAIT. YMMV.
824     */
825    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
826 #endif /* ndef _WIN32 */
827
828 #ifdef HAVE_RFC2553
829    if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
830 #else
831    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
832 #endif
833    {
834 #ifdef _WIN32
835       errno = WSAGetLastError();
836       if (errno == WSAEADDRINUSE)
837 #else
838       if (errno == EADDRINUSE)
839 #endif
840       {
841 #ifdef HAVE_RFC2553
842          freeaddrinfo(result);
843 #endif
844          close_socket(fd);
845          return(-3);
846       }
847       else
848       {
849          close_socket(fd);
850 #ifndef HAVE_RFC2553
851          return(-1);
852       }
853    }
854 #else
855       }
856    }
857    else
858    {
859       /* bind() succeeded, escape from for-loop */
860       /*
861        * XXX: Support multiple listening sockets (e.g. localhost
862        * resolves to AF_INET and AF_INET6, but only the first address
863        * is used
864        */
865       break;
866    }
867    }
868
869    freeaddrinfo(result);
870    if (rp == NULL)
871    {
872       /* All bind()s failed */
873       return(-1);
874    }
875 #endif /* ndef HAVE_RFC2553 */
876
877    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
878    {
879       if (errno != EINTR)
880       {
881          return(-1);
882       }
883    }
884
885    *pfd = fd;
886    return 0;
887
888 }
889
890
891 /*********************************************************************
892  *
893  * Function    :  get_host_information
894  *
895  * Description :  Determines the IP address the client used to
896  *                reach us and the hostname associated with it.
897  *
898  *                XXX: Most of the code has been copy and pasted
899  *                from accept_connection() and not all of the
900  *                ifdefs paths have been tested afterwards.
901  *
902  * Parameters  :
903  *          1  :  afd = File descriptor returned from accept().
904  *          2  :  ip_address = Pointer to return the pointer to
905  *                             the ip address string.
906  *          3  :  hostname =   Pointer to return the pointer to
907  *                             the hostname or NULL if the caller
908  *                             isn't interested in it.
909  *
910  * Returns     :  void.
911  *
912  *********************************************************************/
913 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
914 {
915 #ifdef HAVE_RFC2553
916    struct sockaddr_storage server;
917    int retval;
918 #else
919    struct sockaddr_in server;
920    struct hostent *host = NULL;
921 #endif /* HAVE_RFC2553 */
922 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
923    /* according to accept_connection() this fixes a warning. */
924    int s_length, s_length_provided;
925 #else
926    socklen_t s_length, s_length_provided;
927 #endif
928 #ifndef HAVE_RFC2553
929 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
930    struct hostent result;
931 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
932    struct hostent_data hdata;
933 #else
934    char hbuf[HOSTENT_BUFFER_SIZE];
935    int thd_err;
936 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
937 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
938 #endif /* ifndef HAVE_RFC2553 */
939    s_length = s_length_provided = sizeof(server);
940
941    if (NULL != hostname)
942    {
943       *hostname = NULL;
944    }
945    *ip_address = NULL;
946
947    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
948    {
949       if (s_length > s_length_provided)
950       {
951          log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
952          return;
953       }
954 #ifdef HAVE_RFC2553
955       *ip_address = malloc(NI_MAXHOST);
956       if (NULL == *ip_address)
957       {
958          log_error(LOG_LEVEL_ERROR,
959             "Out of memory while getting the client's IP address.");
960          return;
961       }
962       retval = getnameinfo((struct sockaddr *) &server, s_length,
963          *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
964       if (retval)
965       {
966          log_error(LOG_LEVEL_ERROR,
967             "Unable to print my own IP address: %s", gai_strerror(retval));
968          freez(*ip_address);
969          return;
970       }
971 #else
972       *ip_address = strdup(inet_ntoa(server.sin_addr));
973 #endif /* HAVE_RFC2553 */
974       if (NULL == hostname)
975       {
976          /*
977           * We're done here, the caller isn't
978           * interested in knowing the hostname.
979           */
980          return;
981       }
982
983 #ifdef HAVE_RFC2553
984       *hostname = malloc(NI_MAXHOST);
985       if (NULL == *hostname)
986       {
987          log_error(LOG_LEVEL_ERROR,
988             "Out of memory while getting the client's hostname.");
989          return;
990       }
991       retval = getnameinfo((struct sockaddr *) &server, s_length,
992          *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
993       if (retval)
994       {
995          log_error(LOG_LEVEL_ERROR,
996             "Unable to resolve my own IP address: %s", gai_strerror(retval));
997          freez(*hostname);
998       }
999 #else
1000 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1001       gethostbyaddr_r((const char *)&server.sin_addr,
1002                       sizeof(server.sin_addr), AF_INET,
1003                       &result, hbuf, HOSTENT_BUFFER_SIZE,
1004                       &host, &thd_err);
1005 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1006       host = gethostbyaddr_r((const char *)&server.sin_addr,
1007                       sizeof(server.sin_addr), AF_INET,
1008                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1009 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1010       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1011                                sizeof(server.sin_addr), AF_INET,
1012                                &result, &hdata))
1013       {
1014          host = &result;
1015       }
1016       else
1017       {
1018          host = NULL;
1019       }
1020 #elif defined(MUTEX_LOCKS_AVAILABLE)
1021       privoxy_mutex_lock(&resolver_mutex);
1022       host = gethostbyaddr((const char *)&server.sin_addr, 
1023                            sizeof(server.sin_addr), AF_INET);
1024       privoxy_mutex_unlock(&resolver_mutex);
1025 #else
1026       host = gethostbyaddr((const char *)&server.sin_addr, 
1027                            sizeof(server.sin_addr), AF_INET);
1028 #endif
1029       if (host == NULL)
1030       {
1031          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1032       }
1033       else
1034       {
1035          *hostname = strdup(host->h_name);
1036       }
1037 #endif /* else def HAVE_RFC2553 */
1038    }
1039
1040    return;
1041 }
1042
1043
1044 /*********************************************************************
1045  *
1046  * Function    :  accept_connection
1047  *
1048  * Description :  Accepts a connection on a socket.  Socket must have
1049  *                been created using bind_port().
1050  *
1051  * Parameters  :
1052  *          1  :  csp = Client state, cfd, ip_addr_str, and 
1053  *                ip_addr_long will be set by this routine.
1054  *          2  :  fd  = file descriptor returned from bind_port
1055  *
1056  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
1057  *                On an error it returns 0 (FALSE).
1058  *
1059  *********************************************************************/
1060 int accept_connection(struct client_state * csp, jb_socket fd)
1061 {
1062 #ifdef HAVE_RFC2553
1063    /* XXX: client is stored directly into csp->tcp_addr */
1064 #define client (csp->tcp_addr)
1065    int retval;
1066 #else
1067    struct sockaddr_in client;
1068 #endif
1069    jb_socket afd;
1070 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1071    /* Wierdness - fix a warning. */
1072    int c_length;
1073 #else
1074    socklen_t c_length;
1075 #endif
1076
1077    c_length = sizeof(client);
1078
1079 #ifdef _WIN32
1080    afd = accept (fd, (struct sockaddr *) &client, &c_length);
1081    if (afd == JB_INVALID_SOCKET)
1082    {
1083       return 0;
1084    }
1085 #else
1086    do
1087    {
1088 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1089       struct accept_filter_arg af_options;
1090       bzero(&af_options, sizeof(af_options));
1091       strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1092       setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1093 #endif
1094       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1095    } while (afd < 1 && errno == EINTR);
1096    if (afd < 0)
1097    {
1098       return 0;
1099    }
1100 #endif
1101
1102    csp->cfd = afd;
1103 #ifdef HAVE_RFC2553
1104    csp->ip_addr_str = malloc(NI_MAXHOST);
1105    if (NULL == csp->ip_addr_str)
1106    {
1107       log_error(LOG_LEVEL_ERROR,
1108          "Out of memory while getting the client's IP address.");
1109       return 0;
1110    }
1111    retval = getnameinfo((struct sockaddr *) &client, c_length,
1112          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1113    if (!csp->ip_addr_str || retval)
1114    {
1115       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1116             (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1117       freez(csp->ip_addr_str);
1118    }
1119 #undef client
1120 #else
1121    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1122    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1123 #endif /* def HAVE_RFC2553 */
1124
1125    return 1;
1126
1127 }
1128
1129
1130 /*********************************************************************
1131  *
1132  * Function    :  resolve_hostname_to_ip
1133  *
1134  * Description :  Resolve a hostname to an internet tcp/ip address.
1135  *                NULL or an empty string resolve to INADDR_ANY.
1136  *
1137  * Parameters  :
1138  *          1  :  host = hostname to resolve
1139  *
1140  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1141  *
1142  *********************************************************************/
1143 unsigned long resolve_hostname_to_ip(const char *host)
1144 {
1145    struct sockaddr_in inaddr;
1146    struct hostent *hostp;
1147 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1148    struct hostent result;
1149 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1150    char hbuf[HOSTENT_BUFFER_SIZE];
1151    int thd_err;
1152 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1153    struct hostent_data hdata;
1154 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1155 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1156
1157    if ((host == NULL) || (*host == '\0'))
1158    {
1159       return(INADDR_ANY);
1160    }
1161
1162    memset((char *) &inaddr, 0, sizeof inaddr);
1163
1164    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1165    {
1166       unsigned int dns_retries = 0;
1167 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1168       while (gethostbyname_r(host, &result, hbuf,
1169                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1170              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1171       {   
1172          log_error(LOG_LEVEL_ERROR,
1173             "Timeout #%u while trying to resolve %s. Trying again.",
1174             dns_retries, host);
1175       }
1176 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1177       while (NULL == (hostp = gethostbyname_r(host, &result,
1178                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1179              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1180       {   
1181          log_error(LOG_LEVEL_ERROR,
1182             "Timeout #%u while trying to resolve %s. Trying again.",
1183             dns_retries, host);
1184       }
1185 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1186       /*
1187        * XXX: Doesn't retry in case of soft errors.
1188        * Does this gethostbyname_r version set h_errno?
1189        */
1190       if (0 == gethostbyname_r(host, &result, &hdata))
1191       {
1192          hostp = &result;
1193       }
1194       else
1195       {
1196          hostp = NULL;
1197       }
1198 #elif defined(MUTEX_LOCKS_AVAILABLE)
1199       privoxy_mutex_lock(&resolver_mutex);
1200       while (NULL == (hostp = gethostbyname(host))
1201              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1202       {   
1203          log_error(LOG_LEVEL_ERROR,
1204             "Timeout #%u while trying to resolve %s. Trying again.",
1205             dns_retries, host);
1206       }
1207       privoxy_mutex_unlock(&resolver_mutex);
1208 #else
1209       while (NULL == (hostp = gethostbyname(host))
1210              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1211       {
1212          log_error(LOG_LEVEL_ERROR,
1213             "Timeout #%u while trying to resolve %s. Trying again.",
1214             dns_retries, host);
1215       }
1216 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1217       /*
1218        * On Mac OSX, if a domain exists but doesn't have a type A
1219        * record associated with it, the h_addr member of the struct
1220        * hostent returned by gethostbyname is NULL, even if h_length
1221        * is 4. Therefore the second test below.
1222        */
1223       if (hostp == NULL || hostp->h_addr == NULL)
1224       {
1225          errno = EINVAL;
1226          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1227          return(INADDR_NONE);
1228       }
1229       if (hostp->h_addrtype != AF_INET)
1230       {
1231 #ifdef _WIN32
1232          errno = WSAEPROTOTYPE;
1233 #else
1234          errno = EPROTOTYPE;
1235 #endif 
1236          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1237          return(INADDR_NONE);
1238       }
1239       memcpy(
1240          (char *) &inaddr.sin_addr,
1241          (char *) hostp->h_addr,
1242          sizeof(inaddr.sin_addr)
1243       );
1244    }
1245    return(inaddr.sin_addr.s_addr);
1246
1247 }
1248
1249
1250 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1251 /*********************************************************************
1252  *
1253  * Function    :  socket_is_still_alive
1254  *
1255  * Description :  Figures out whether or not a socket is still alive.
1256  *
1257  * Parameters  :
1258  *          1  :  sfd = The socket to check.
1259  *
1260  * Returns     :  TRUE for yes, otherwise FALSE.
1261  *
1262  *********************************************************************/
1263 int socket_is_still_alive(jb_socket sfd)
1264 {
1265    char buf[10];
1266    int no_data_waiting;
1267
1268 #ifdef HAVE_POLL
1269    int poll_result;
1270    struct pollfd poll_fd[1];
1271
1272    memset(poll_fd, 0, sizeof(poll_fd));
1273    poll_fd[0].fd = sfd;
1274    poll_fd[0].events = POLLIN;
1275
1276    poll_result = poll(poll_fd, 1, 0);
1277
1278    if (-1 == poll_result)
1279    {
1280       log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1281       return FALSE;
1282    }
1283    no_data_waiting = !(poll_fd[0].revents & POLLIN);
1284 #else
1285    fd_set readable_fds;
1286    struct timeval timeout;
1287    int ret;
1288
1289    memset(&timeout, '\0', sizeof(timeout));
1290    FD_ZERO(&readable_fds);
1291    FD_SET(sfd, &readable_fds);
1292
1293    ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1294    if (ret < 0)
1295    {
1296       log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1297       return FALSE;
1298    }
1299    no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1300 #endif /* def HAVE_POLL */
1301
1302    return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1303 }
1304 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1305
1306
1307 /*
1308   Local Variables:
1309   tab-width: 3
1310   end:
1311 */