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