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