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