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