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