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