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