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