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