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