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