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