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