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