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