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