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