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