3bc67563eb68a0223bba732c188a382031840659
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.52 2009/04/17 11:34: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-2007 the SourceForge
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  * Revisions   :
37  *    $Log: jbsockets.c,v $
38  *    Revision 1.52  2009/04/17 11:34:34  fabiankeil
39  *    Style cosmetics for the IPv6 code.
40  *
41  *    Revision 1.51  2009/04/17 11:27:49  fabiankeil
42  *    Petr Pisar's privoxy-3.0.12-ipv6-3.diff.
43  *
44  *    Revision 1.50  2008/12/20 14:53:55  fabiankeil
45  *    Add config option socket-timeout to control the time
46  *    Privoxy waits for data to arrive on a socket. Useful
47  *    in case of stale ssh tunnels or when fuzz-testing.
48  *
49  *    Revision 1.49  2008/11/10 17:03:57  fabiankeil
50  *    Fix a gcc44 warning and remove a now-obsolete cast.
51  *
52  *    Revision 1.48  2008/09/04 08:13:58  fabiankeil
53  *    Prepare for critical sections on Windows by adding a
54  *    layer of indirection before the pthread mutex functions.
55  *
56  *    Revision 1.47  2008/03/26 18:07:07  fabiankeil
57  *    Add hostname directive. Closes PR#1918189.
58  *
59  *    Revision 1.46  2008/03/21 11:13:57  fabiankeil
60  *    Only gather host information if it's actually needed.
61  *    Also move the code out of accept_connection() so it's less likely
62  *    to delay other incoming connections if the host is misconfigured.
63  *
64  *    Revision 1.45  2007/09/30 16:59:22  fabiankeil
65  *    Set the maximum listen() backlog to 128. Apparently SOMAXCONN is
66  *    neither high enough, nor a hard limit on mingw32. Again for BR#1795281.
67  *
68  *    Revision 1.44  2007/09/15 13:01:31  fabiankeil
69  *    Increase listen() backlog to SOMAXCONN (or 128) to decrease
70  *    chances of dropped connections under load. Problem reported
71  *    and fix suggested by nobody in BR#1795281.
72  *
73  *    Revision 1.43  2007/06/01 18:16:36  fabiankeil
74  *    Use the same mutex for gethostbyname() and gethostbyaddr() to prevent
75  *    deadlocks and crashes on OpenBSD and possibly other OS with neither
76  *    gethostbyname_r() nor gethostaddr_r(). Closes BR#1729174.
77  *    Thanks to Ralf Horstmann for report and solution.
78  *
79  *    Revision 1.42  2007/04/01 17:37:07  fabiankeil
80  *    - Add DNS retries for Solaris and other systems
81  *      whose gethostbyname_r version takes five arguments.
82  *    - Move maximum number of DNS retries into a macro.
83  *
84  *    Revision 1.41  2006/11/13 19:05:51  fabiankeil
85  *    Make pthread mutex locking more generic. Instead of
86  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
87  *    and use mutex locking unless there is an _r function
88  *    available. Better safe than sorry.
89  *
90  *    Fixes "./configure --disable-pthread" and should result
91  *    in less threading-related problems on pthread-using platforms,
92  *    but it still doesn't fix BR#1122404.
93  *
94  *    Revision 1.40  2006/09/02 15:36:42  fabiankeil
95  *    Follow the OpenBSD port's lead and protect the resolve
96  *    functions on OpenBSD as well.
97  *
98  *    Revision 1.39  2006/08/03 02:46:41  david__schmidt
99  *    Incorporate Fabian Keil's patch work:\rhttp://www.fabiankeil.de/sourcecode/privoxy/
100  *
101  *    Revision 1.38  2006/07/18 14:48:46  david__schmidt
102  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
103  *    with what was really the latest development (the v_3_0_branch branch)
104  *
105  *    Revision 1.35.2.8  2006/01/21 16:16:08  david__schmidt
106  *    Thanks to  Edward Carrel for his patch to modernize OSX's\rpthreads support.  See bug #1409623.
107  *
108  *    Revision 1.35.2.7  2005/05/07 21:50:55  david__schmidt
109  *    A few memory leaks plugged (mostly on error paths)
110  *
111  *    Revision 1.35.2.6  2003/12/17 16:34:40  oes
112  *    Cosmetics
113  *
114  *    Revision 1.35.2.5  2003/04/29 11:32:54  oes
115  *    Don't rely on h_addr being non-NULL after gethostbyname.
116  *    Works around an oddness in Max OSX and closes bug #724796
117  *
118  *    Revision 1.35.2.4  2003/04/04 12:40:20  oes
119  *    Made sure the errno set by bind, not close[socket] is used in
120  *    bind_port. Probably fixes bugs #713777, #705562.
121  *
122  *    Revision 1.35.2.3  2003/03/07 03:41:04  david__schmidt
123  *    Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX.  Hopefully this will take care of all of those pesky crash reports.
124  *
125  *    Revision 1.35.2.2  2002/11/20 14:37:24  oes
126  *    Fixed Win32 error logging in bind_port.
127  *    Thanks to Oliver Stoeneberg for the hint.
128  *
129  *    Revision 1.35.2.1  2002/05/26 23:41:27  joergs
130  *    AmigaOS: Fixed wrong type of len in write_socket()
131  *
132  *    Revision 1.35  2002/04/26 15:50:04  joergs
133  *    AmigaOS: No socklen_t, added AMIGA to the systems using int instead.
134  *
135  *    Revision 1.34  2002/04/08 20:31:41  swa
136  *    fixed JB spelling
137  *
138  *    Revision 1.33  2002/04/03 16:02:18  gliptak
139  *    Correcting compile warning with older gcc
140  *
141  *    Revision 1.32  2002/03/31 17:18:59  jongfoster
142  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
143  *
144  *    Revision 1.31  2002/03/29 03:33:13  david__schmidt
145  *    Fix Mac OSX compiler warnings
146  *
147  *    Revision 1.30  2002/03/27 14:32:43  david__schmidt
148  *    More compiler warning message maintenance
149  *
150  *    Revision 1.29  2002/03/26 22:29:54  swa
151  *    we have a new homepage!
152  *
153  *    Revision 1.28  2002/03/24 13:25:43  swa
154  *    name change related issues
155  *
156  *    Revision 1.27  2002/03/13 00:27:05  jongfoster
157  *    Killing warnings
158  *
159  *    Revision 1.26  2002/03/11 22:07:02  david__schmidt
160  *    OS/2 port maintenance:
161  *    - Fixed EMX build - it had decayed a little
162  *    - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
163  *      substituted a memset for now.
164  *
165  *    Revision 1.25  2002/03/09 20:03:52  jongfoster
166  *    - Making various functions return int rather than size_t.
167  *      (Undoing a recent change).  Since size_t is unsigned on
168  *      Windows, functions like read_socket that return -1 on
169  *      error cannot return a size_t.
170  *
171  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
172  *      crashes, and also frequently caused JB to jump to 100%
173  *      CPU and stay there.  (Because it thought it had just
174  *      read ((unsigned)-1) == 4Gb of data...)
175  *
176  *    - The signature of write_socket has changed, it now simply
177  *      returns success=0/failure=nonzero.
178  *
179  *    - Trying to get rid of a few warnings --with-debug on
180  *      Windows, I've introduced a new type "jb_socket".  This is
181  *      used for the socket file descriptors.  On Windows, this
182  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
183  *      an int.  The error value can't be -1 any more, so it's
184  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
185  *      Windows it maps to the #define INVALID_SOCKET.)
186  *
187  *    - The signature of bind_port has changed.
188  *
189  *    Revision 1.24  2002/03/07 03:51:36  oes
190  *     - Improved handling of failed DNS lookups
191  *     - Fixed compiler warnings etc
192  *
193  *    Revision 1.23  2002/03/05 00:36:01  jongfoster
194  *    Fixing bug 514988 - unable to restart Junkbuster
195  *
196  *    Revision 1.22  2002/03/04 02:08:02  david__schmidt
197  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
198  *
199  *    Revision 1.21  2002/01/09 14:32:33  oes
200  *    Added support for gethostbyname_r and gethostbyaddr_r.
201  *
202  *    Revision 1.20  2001/11/16 00:48:48  jongfoster
203  *    Enabling duplicate-socket detection for all platforms, not
204  *    just Win32.
205  *
206  *    Revision 1.19  2001/10/25 03:40:47  david__schmidt
207  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
208  *    threads to call select() simultaneously.  So, it's time to do a real, live,
209  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
210  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
211  *
212  *    Revision 1.18  2001/09/21 23:02:02  david__schmidt
213  *    Cleaning up 2 compiler warnings on OS/2.
214  *
215  *    Revision 1.17  2001/09/13 20:11:46  jongfoster
216  *    Fixing 2 compiler warnings under Win32
217  *
218  *    Revision 1.16  2001/07/30 22:08:36  jongfoster
219  *    Tidying up #defines:
220  *    - All feature #defines are now of the form FEATURE_xxx
221  *    - Permanently turned off WIN_GUI_EDIT
222  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
223  *
224  *    Revision 1.15  2001/07/29 17:40:43  jongfoster
225  *    Fixed compiler warning by adding a cast
226  *
227  *    Revision 1.14  2001/07/18 13:47:59  oes
228  *    Eliminated dirty hack for getsockbyname()
229  *
230  *    Revision 1.13  2001/07/15 13:56:57  jongfoster
231  *    Removing unused local variable.
232  *
233  *    Revision 1.12  2001/07/01 17:04:11  oes
234  *    Bugfix: accept_connection no longer uses the obsolete hstrerror() function
235  *
236  *    Revision 1.11  2001/06/29 21:45:41  oes
237  *    Indentation, CRLF->LF, Tab-> Space
238  *
239  *    Revision 1.10  2001/06/29 13:29:15  oes
240  *    - Added remote (server) host IP to csp->http->host_ip_addr_str
241  *    - Added detection of local socket IP and fqdn
242  *    - Removed logentry from cancelled commit
243  *
244  *    Revision 1.9  2001/06/07 23:06:09  jongfoster
245  *    The host parameter to connect_to() is now const.
246  *
247  *    Revision 1.8  2001/06/03 19:12:07  oes
248  *    filled comment
249  *
250  *    Revision 1.7  2001/05/28 16:14:00  jongfoster
251  *    Fixing bug in LOG_LEVEL_LOG
252  *
253  *    Revision 1.6  2001/05/26 17:28:32  jongfoster
254  *    Fixed LOG_LEVEL_LOG
255  *
256  *    Revision 1.5  2001/05/26 15:26:15  jongfoster
257  *    ACL feature now provides more security by immediately dropping
258  *    connections from untrusted hosts.
259  *
260  *    Revision 1.4  2001/05/26 00:37:42  jongfoster
261  *    Cosmetic indentation correction.
262  *
263  *    Revision 1.3  2001/05/25 21:57:54  jongfoster
264  *    Now gives a warning under Windows if you try to bind
265  *    it to a port that's already in use.
266  *
267  *    Revision 1.2  2001/05/17 23:01:01  oes
268  *     - Cleaned CRLF's from the sources and related files
269  *
270  *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
271  *    Initial import of version 2.9.3 source tree
272  *
273  *
274  *********************************************************************/
275 \f
276
277 #include "config.h"
278
279 #include <stdlib.h>
280 #include <stdio.h>
281 #include <string.h>
282 #include <errno.h>
283 #include <fcntl.h>
284 #include <sys/types.h>
285
286 #ifdef _WIN32
287
288 #ifndef STRICT
289 #define STRICT
290 #endif
291 #include <windows.h>
292 #include <sys/timeb.h>
293 #include <io.h>
294
295 #else
296
297 #ifndef __OS2__
298 #include <unistd.h>
299 #endif
300 #include <sys/time.h>
301 #include <netinet/in.h>
302 #include <sys/ioctl.h>
303 #include <netdb.h>
304 #include <sys/socket.h>
305
306 #ifndef __BEOS__
307 #include <netinet/tcp.h>
308 #ifndef __OS2__
309 #include <arpa/inet.h>
310 #endif
311 #else
312 #include <socket.h>
313 #endif
314
315 #if defined(__EMX__) || defined (__OS2__)
316 #include <sys/select.h>  /* OS/2/EMX needs a little help with select */
317 #ifdef __OS2__
318 #include <nerrno.h>
319 #endif
320 #endif
321
322 #endif
323
324 #include "project.h"
325
326 #ifdef FEATURE_PTHREAD
327 #include "jcc.h"
328 /* jcc.h is for mutex semaphores only */
329 #endif /* def FEATURE_PTHREAD */
330
331 #include "jbsockets.h"
332 #include "filters.h"
333 #include "errlog.h"
334 #include "miscutil.h"
335
336 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
337
338 /*
339  * Maximum number of gethostbyname(_r) retries in case of
340  * soft errors (TRY_AGAIN).
341  * XXX: Does it make sense to make this a config option?
342  */
343 #define MAX_DNS_RETRIES 10
344
345 #define MAX_LISTEN_BACKLOG 128
346
347
348 /*********************************************************************
349  *
350  * Function    :  connect_to
351  *
352  * Description :  Open a socket and connect to it.  Will check
353  *                that this is allowed according to ACL.
354  *
355  * Parameters  :
356  *          1  :  host = hostname to connect to
357  *          2  :  portnum = port to connent on (XXX: should be unsigned)
358  *          3  :  csp = Current client state (buffers, headers, etc...)
359  *                      Not modified, only used for source IP and ACL.
360  *
361  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
362  *                file descriptor.
363  *
364  *********************************************************************/
365 #ifdef HAVE_GETADDRINFO
366 /* Getaddrinfo implementation */
367 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
368 {
369    struct addrinfo hints, *result, *rp;
370    char service[6];
371    int retval;
372    jb_socket fd;
373    fd_set wfds;
374    struct timeval tv[1];
375 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
376    int   flags;
377 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
378    int connect_failed;
379
380 #ifdef FEATURE_ACL
381    struct access_control_addr dst[1];
382 #endif /* def FEATURE_ACL */
383
384    retval = snprintf(service, sizeof(service), "%d", portnum);
385    if ((-1 == retval) || (sizeof(service) <= retval))
386    {
387       log_error(LOG_LEVEL_ERROR,
388          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
389          portnum);
390       csp->http->host_ip_addr_str = strdup("unknown");
391       return(JB_INVALID_SOCKET);
392    }
393
394    memset((char *)&hints, 0, sizeof(hints));
395    hints.ai_family = AF_UNSPEC;
396    hints.ai_socktype = SOCK_STREAM;
397    hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV; /* avoid service look-up */
398    if ((retval = getaddrinfo(host, service, &hints, &result)))
399    {
400       log_error(LOG_LEVEL_INFO,
401          "Can not resolve %s: %s", host, gai_strerror(retval));
402       csp->http->host_ip_addr_str = strdup("unknown");
403       return(JB_INVALID_SOCKET);
404    }
405
406    for (rp = result; rp != NULL; rp = rp->ai_next)
407    {
408
409 #ifdef FEATURE_ACL
410       memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
411
412       if (block_acl(dst, csp))
413       {
414 #ifdef __OS2__
415          errno = SOCEPERM;
416 #else
417          errno = EPERM;
418 #endif
419          continue;
420       }
421 #endif /* def FEATURE_ACL */
422
423       csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
424       retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
425          csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
426       if (!csp->http->host_ip_addr_str || retval)
427       {
428          log_error(LOG_LEVEL_ERROR,
429             "Can not save csp->http->host_ip_addr_str: %s",
430             (csp->http->host_ip_addr_str) ?
431             gai_strerror(retval) : "Insufficient memory");
432          freez(csp->http->host_ip_addr_str);
433          continue;
434       }
435
436 #ifdef _WIN32
437       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
438             JB_INVALID_SOCKET)
439 #else
440       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
441 #endif
442       {
443          continue;
444       }
445
446 #ifdef TCP_NODELAY
447       {  /* turn off TCP coalescence */
448          int mi = 1;
449          setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
450       }
451 #endif /* def TCP_NODELAY */
452
453 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
454       if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
455       {
456          flags |= O_NDELAY;
457          fcntl(fd, F_SETFL, flags);
458       }
459 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
460
461       connect_failed = 0;
462       while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
463       {
464 #ifdef _WIN32
465          if (errno == WSAEINPROGRESS)
466 #elif __OS2__
467          if (sock_errno() == EINPROGRESS)
468 #else /* ifndef _WIN32 */
469          if (errno == EINPROGRESS)
470 #endif /* ndef _WIN32 || __OS2__ */
471          {
472             break;
473          }
474
475 #ifdef __OS2__
476          if (sock_errno() != EINTR)
477 #else
478          if (errno != EINTR)
479 #endif /* __OS2__ */
480          {
481             close_socket(fd);
482             connect_failed = 1;
483             break;
484          }
485       }
486       if (connect_failed)
487       {
488          continue;
489       }
490
491 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
492       if (flags != -1)
493       {
494          flags &= ~O_NDELAY;
495          fcntl(fd, F_SETFL, flags);
496       }
497 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
498
499       /* wait for connection to complete */
500       FD_ZERO(&wfds);
501       FD_SET(fd, &wfds);
502
503       tv->tv_sec  = 30;
504       tv->tv_usec = 0;
505
506       /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
507       if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
508       {
509          close_socket(fd);
510          continue;
511       }
512
513       break; /* for; Connection established; don't try other addresses */
514    }
515
516    freeaddrinfo(result);
517    if (!rp)
518    {
519       log_error(LOG_LEVEL_INFO,
520          "Could not connect to TCP/[%s]:%s", host, service);
521       return(JB_INVALID_SOCKET);
522    }
523    /*
524     * XXX: Current connection verification (EINPROGRESS && select()
525     * for writing) is not sufficient. E.g. on Linux-2.6.27 with glibc-2.6
526     * select returns socket ready for writing, however subsequential
527     * write(2) fails with ENOCONNECT. Read Linux connect(2) man page
528     * about non-blocking sockets.
529     * Thus we can't log here that the socket is connected.
530     */
531    /* log_error(LOG_LEVEL_INFO, "Connected to TCP/[%s]:%s", host, service); */
532
533    return(fd);
534
535 }
536
537 # else /* ndef HAVE_GETADDRINFO */
538 /* Pre-getaddrinfo implementation */
539
540 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
541 {
542    struct sockaddr_in inaddr;
543    jb_socket fd;
544    unsigned int addr;
545    fd_set wfds;
546    struct timeval tv[1];
547 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
548    int   flags;
549 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
550
551 #ifdef FEATURE_ACL
552    struct access_control_addr dst[1];
553 #endif /* def FEATURE_ACL */
554
555    memset((char *)&inaddr, 0, sizeof inaddr);
556
557    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
558    {
559       csp->http->host_ip_addr_str = strdup("unknown");
560       return(JB_INVALID_SOCKET);
561    }
562
563 #ifdef FEATURE_ACL
564    dst->addr = ntohl(addr);
565    dst->port = portnum;
566
567    if (block_acl(dst, csp))
568    {
569 #ifdef __OS2__
570       errno = SOCEPERM;
571 #else
572       errno = EPERM;
573 #endif
574       return(JB_INVALID_SOCKET);
575    }
576 #endif /* def FEATURE_ACL */
577
578    inaddr.sin_addr.s_addr = addr;
579    inaddr.sin_family      = AF_INET;
580    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
581
582 #ifndef _WIN32
583    if (sizeof(inaddr.sin_port) == sizeof(short))
584 #endif /* ndef _WIN32 */
585    {
586       inaddr.sin_port = htons((unsigned short) portnum);
587    }
588 #ifndef _WIN32
589    else
590    {
591       inaddr.sin_port = htonl((unsigned long)portnum);
592    }
593 #endif /* ndef _WIN32 */
594
595 #ifdef _WIN32
596    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
597 #else
598    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
599 #endif
600    {
601       return(JB_INVALID_SOCKET);
602    }
603
604 #ifdef TCP_NODELAY
605    {  /* turn off TCP coalescence */
606       int mi = 1;
607       setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
608    }
609 #endif /* def TCP_NODELAY */
610
611 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
612    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
613    {
614       flags |= O_NDELAY;
615       fcntl(fd, F_SETFL, flags);
616    }
617 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
618
619    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
620    {
621 #ifdef _WIN32
622       if (errno == WSAEINPROGRESS)
623 #elif __OS2__ 
624       if (sock_errno() == EINPROGRESS)
625 #else /* ifndef _WIN32 */
626       if (errno == EINPROGRESS)
627 #endif /* ndef _WIN32 || __OS2__ */
628       {
629          break;
630       }
631
632 #ifdef __OS2__ 
633       if (sock_errno() != EINTR)
634 #else
635       if (errno != EINTR)
636 #endif /* __OS2__ */
637       {
638          close_socket(fd);
639          return(JB_INVALID_SOCKET);
640       }
641    }
642
643 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
644    if (flags != -1)
645    {
646       flags &= ~O_NDELAY;
647       fcntl(fd, F_SETFL, flags);
648    }
649 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
650
651    /* wait for connection to complete */
652    FD_ZERO(&wfds);
653    FD_SET(fd, &wfds);
654
655    tv->tv_sec  = 30;
656    tv->tv_usec = 0;
657
658    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
659    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
660    {
661       close_socket(fd);
662       return(JB_INVALID_SOCKET);
663    }
664    return(fd);
665
666 }
667 #endif /* ndef HAVE_GETADDRINFO */
668
669
670 /*********************************************************************
671  *
672  * Function    :  write_socket
673  *
674  * Description :  Write the contents of buf (for n bytes) to socket fd.
675  *
676  * Parameters  :
677  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
678  *          2  :  buf = pointer to data to be written.
679  *          3  :  len = length of data to be written to the socket "fd".
680  *
681  * Returns     :  0 on success (entire buffer sent).
682  *                nonzero on error.
683  *
684  *********************************************************************/
685 #ifdef AMIGA
686 int write_socket(jb_socket fd, const char *buf, ssize_t len)
687 #else
688 int write_socket(jb_socket fd, const char *buf, size_t len)
689 #endif
690 {
691    if (len == 0)
692    {
693       return 0;
694    }
695
696    if (len < 0) /* constant condition - size_t isn't ever negative */ 
697    {
698       return 1;
699    }
700
701    log_error(LOG_LEVEL_LOG, "%N", len, buf);
702
703 #if defined(_WIN32)
704    return (send(fd, buf, (int)len, 0) != (int)len);
705 #elif defined(__BEOS__) || defined(AMIGA)
706    return (send(fd, buf, len, 0) != len);
707 #elif defined(__OS2__)
708    /*
709     * Break the data up into SOCKET_SEND_MAX chunks for sending...
710     * OS/2 seemed to complain when the chunks were too large.
711     */
712 #define SOCKET_SEND_MAX 65000
713    {
714       int write_len = 0, send_len, send_rc = 0, i = 0;
715       while ((i < len) && (send_rc != -1))
716       {
717          if ((i + SOCKET_SEND_MAX) > len)
718             send_len = len - i;
719          else
720             send_len = SOCKET_SEND_MAX;
721          send_rc = send(fd,(char*)buf + i, send_len, 0);
722          if (send_rc == -1)
723             return 1;
724          i = i + send_len;
725       }
726       return 0;
727    }
728 #else
729    return (write(fd, buf, len) != len);
730 #endif
731
732 }
733
734
735 /*********************************************************************
736  *
737  * Function    :  read_socket
738  *
739  * Description :  Read from a TCP/IP socket in a platform independent way.
740  *
741  * Parameters  :
742  *          1  :  fd = file descriptor of the socket to read
743  *          2  :  buf = pointer to buffer where data will be written
744  *                Must be >= len bytes long.
745  *          3  :  len = maximum number of bytes to read
746  *
747  * Returns     :  On success, the number of bytes read is returned (zero
748  *                indicates end of file), and the file position is advanced
749  *                by this number.  It is not an error if this number is
750  *                smaller than the number of bytes requested; this may hap-
751  *                pen for example because fewer bytes are actually available
752  *                right now (maybe because we were close to end-of-file, or
753  *                because we are reading from a pipe, or from a terminal,
754  *                or because read() was interrupted by a signal).  On error,
755  *                -1 is returned, and errno is set appropriately.  In this
756  *                case it is left unspecified whether the file position (if
757  *                any) changes.
758  *
759  *********************************************************************/
760 int read_socket(jb_socket fd, char *buf, int len)
761 {
762    if (len <= 0)
763    {
764       return(0);
765    }
766
767 #if defined(_WIN32)
768    return(recv(fd, buf, len, 0));
769 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
770    return(recv(fd, buf, (size_t)len, 0));
771 #else
772    return(read(fd, buf, (size_t)len));
773 #endif
774 }
775
776
777 /*********************************************************************
778  *
779  * Function    :  data_is_available
780  *
781  * Description :  Waits for data to arrive on a socket.
782  *
783  * Parameters  :
784  *          1  :  fd = file descriptor of the socket to read
785  *          2  :  seconds_to_wait = number of seconds after which we give up.
786  *
787  * Returns     :  TRUE if data arrived in time,
788  *                FALSE otherwise.
789  *
790  *********************************************************************/
791 int data_is_available(jb_socket fd, int seconds_to_wait)
792 {
793    fd_set rfds;
794    struct timeval timeout;
795    int n;
796
797    memset(&timeout, 0, sizeof(timeout));
798    timeout.tv_sec = seconds_to_wait;
799
800 #ifdef __OS2__
801    /* Copy and pasted from jcc.c ... */
802    memset(&rfds, 0, sizeof(fd_set));
803 #else
804    FD_ZERO(&rfds);
805 #endif
806    FD_SET(fd, &rfds);
807
808    n = select(fd+1, &rfds, NULL, NULL, &timeout);
809
810    /*
811     * XXX: Do we care about the different error conditions?
812     */
813    return (n == 1);
814 }
815
816
817 /*********************************************************************
818  *
819  * Function    :  close_socket
820  *
821  * Description :  Closes a TCP/IP socket
822  *
823  * Parameters  :
824  *          1  :  fd = file descriptor of socket to be closed
825  *
826  * Returns     :  void
827  *
828  *********************************************************************/
829 void close_socket(jb_socket fd)
830 {
831 #if defined(_WIN32) || defined(__BEOS__)
832    closesocket(fd);
833 #elif defined(AMIGA)
834    CloseSocket(fd); 
835 #elif defined(__OS2__)
836    soclose(fd);
837 #else
838    close(fd);
839 #endif
840
841 }
842
843
844 /*********************************************************************
845  *
846  * Function    :  bind_port
847  *
848  * Description :  Call socket, set socket options, and listen.
849  *                Called by listen_loop to "boot up" our proxy address.
850  *
851  * Parameters  :
852  *          1  :  hostnam = TCP/IP address to bind/listen to
853  *          2  :  portnum = port to listen on
854  *          3  :  pfd = pointer used to return file descriptor.
855  *
856  * Returns     :  if success, returns 0 and sets *pfd.
857  *                if failure, returns -3 if address is in use,
858  *                                    -2 if address unresolvable,
859  *                                    -1 otherwise
860  *********************************************************************/
861 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
862 {
863 #ifdef HAVE_GETADDRINFO
864    struct addrinfo hints;
865    struct addrinfo *result, *rp;
866    /*
867     * XXX: portnum should be a string to allow symbolic service
868     * names in the configuration file and to avoid the following
869     * int2string.
870     */
871    char servnam[6];
872    int retval;
873 #else
874    struct sockaddr_in inaddr;
875 #endif /* def HAVE_GETADDRINFO */
876    jb_socket fd;
877 #ifndef _WIN32
878    int one = 1;
879 #endif /* ndef _WIN32 */
880
881    *pfd = JB_INVALID_SOCKET;
882
883 #ifdef HAVE_GETADDRINFO
884    retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
885    if ((-1 == retval) || (sizeof(servnam) <= retval))
886    {
887       log_error(LOG_LEVEL_ERROR,
888          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
889          portnum);
890       return -1;
891    }
892
893    memset(&hints, 0, sizeof(struct addrinfo));
894    if ((hostnam == NULL) || !strcmpic(hostnam, "localhost"))
895    {
896       /*
897        * XXX: This is a hack. The right thing to do
898        * would be to bind to both AF_INET and AF_INET6.
899        * This will also fail if there is no AF_INET
900        * version available.
901        */
902       hints.ai_family = AF_INET;
903    }
904    else
905    {
906       hints.ai_family = AF_UNSPEC;
907    }
908    hints.ai_socktype = SOCK_STREAM;
909    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
910    hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
911    hints.ai_canonname = NULL;
912    hints.ai_addr = NULL;
913    hints.ai_next = NULL;
914
915    if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
916    {
917       log_error(LOG_LEVEL_ERROR,
918          "Can not resolve %s: %s", hostnam, gai_strerror(retval));
919       return -2;
920    }
921 #else
922    memset((char *)&inaddr, '\0', sizeof inaddr);
923
924    inaddr.sin_family      = AF_INET;
925    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
926
927    if (inaddr.sin_addr.s_addr == INADDR_NONE)
928    {
929       return(-2);
930    }
931
932 #ifndef _WIN32
933    if (sizeof(inaddr.sin_port) == sizeof(short))
934 #endif /* ndef _WIN32 */
935    {
936       inaddr.sin_port = htons((unsigned short) portnum);
937    }
938 #ifndef _WIN32
939    else
940    {
941       inaddr.sin_port = htonl((unsigned long) portnum);
942    }
943 #endif /* ndef _WIN32 */
944 #endif /* def HAVE_GETADDRINFO */
945
946 #ifdef HAVE_GETADDRINFO
947    for (rp = result; rp != NULL; rp = rp->ai_next)
948    {
949       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
950 #else
951    fd = socket(AF_INET, SOCK_STREAM, 0);
952 #endif /* def HAVE_GETADDRINFO */
953
954 #ifdef _WIN32
955    if (fd == JB_INVALID_SOCKET)
956 #else
957    if (fd < 0)
958 #endif
959    {
960 #ifdef HAVE_GETADDRINFO
961       continue;
962 #else
963       return(-1);
964 #endif
965    }
966
967 #ifndef _WIN32
968    /*
969     * This is not needed for Win32 - in fact, it stops
970     * duplicate instances of Privoxy from being caught.
971     *
972     * On UNIX, we assume the user is sensible enough not
973     * to start Privoxy multiple times on the same IP.
974     * Without this, stopping and restarting Privoxy
975     * from a script fails.
976     * Note: SO_REUSEADDR is meant to only take over
977     * sockets which are *not* in listen state in Linux,
978     * e.g. sockets in TIME_WAIT. YMMV.
979     */
980    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
981 #endif /* ndef _WIN32 */
982
983 #ifdef HAVE_GETADDRINFO
984    if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
985 #else
986    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
987 #endif
988    {
989 #ifdef _WIN32
990       errno = WSAGetLastError();
991       if (errno == WSAEADDRINUSE)
992 #else
993       if (errno == EADDRINUSE)
994 #endif
995       {
996 #ifdef HAVE_GETADDRINFO
997          freeaddrinfo(result);
998 #endif
999          close_socket(fd);
1000          return(-3);
1001       }
1002       else
1003       {
1004          close_socket(fd);
1005 #ifndef HAVE_GETADDRINFO
1006          return(-1);
1007       }
1008    }
1009 #else
1010       }
1011    }
1012    else
1013    {
1014       /* bind() succeeded, escape from for-loop */
1015       /*
1016        * XXX: Support multiple listening sockets (e.g. localhost
1017        * resolves to AF_INET and AF_INET6, but only the first address
1018        * is used
1019        */
1020       break;
1021    }
1022    }
1023
1024    freeaddrinfo(result);
1025    if (rp == NULL)
1026    {
1027       /* All bind()s failed */
1028       return(-1);
1029    }
1030 #endif /* ndef HAVE_GETADDRINFO */
1031
1032    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1033    {
1034       if (errno != EINTR)
1035       {
1036          return(-1);
1037       }
1038    }
1039
1040    *pfd = fd;
1041    return 0;
1042
1043 }
1044
1045
1046 /*********************************************************************
1047  *
1048  * Function    :  get_host_information
1049  *
1050  * Description :  Determines the IP address the client used to
1051  *                reach us and the hostname associated with it.
1052  *
1053  *                XXX: Most of the code has been copy and pasted
1054  *                from accept_connection() and not all of the
1055  *                ifdefs paths have been tested afterwards.
1056  *
1057  * Parameters  :
1058  *          1  :  afd = File descriptor returned from accept().
1059  *          2  :  ip_address = Pointer to return the pointer to
1060  *                             the ip address string.
1061  *          3  :  hostname =   Pointer to return the pointer to
1062  *                             the hostname or NULL if the caller
1063  *                             isn't interested in it.
1064  *
1065  * Returns     :  void.
1066  *
1067  *********************************************************************/
1068 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
1069 {
1070 #ifdef HAVE_GETNAMEINFO
1071    struct sockaddr_storage server;
1072    int retval;
1073 #else
1074    struct sockaddr_in server;
1075    struct hostent *host = NULL;
1076 #endif /* HAVE_GETNAMEINFO */
1077 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1078    /* according to accept_connection() this fixes a warning. */
1079    int s_length, s_length_provided;
1080 #else
1081    socklen_t s_length, s_length_provided;
1082 #endif
1083 #ifndef HAVE_GETNAMEINFO
1084 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1085    struct hostent result;
1086 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1087    struct hostent_data hdata;
1088 #else
1089    char hbuf[HOSTENT_BUFFER_SIZE];
1090    int thd_err;
1091 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1092 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1093 #endif /* ifndef HAVE_GETNAMEINFO */
1094    s_length = s_length_provided = sizeof(server);
1095
1096    if (NULL != hostname)
1097    {
1098       *hostname = NULL;
1099    }
1100    *ip_address = NULL;
1101
1102    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1103    {
1104       if (s_length > s_length_provided)
1105       {
1106          log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1107          return;
1108       }
1109 #ifdef HAVE_GETNAMEINFO
1110       *ip_address = malloc(NI_MAXHOST);
1111       retval = getnameinfo((struct sockaddr *) &server, s_length,
1112          *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1113       if (retval)
1114       {
1115          log_error(LOG_LEVEL_ERROR,
1116             "Unable to print my own IP address: %s", gai_strerror(retval));
1117          freez(*ip_address);
1118          return;
1119       }
1120 #else
1121       *ip_address = strdup(inet_ntoa(server.sin_addr));
1122 #endif /* HAVE_GETNAMEINFO */
1123       if (NULL == hostname)
1124       {
1125          /*
1126           * We're done here, the caller isn't
1127           * interested in knowing the hostname.
1128           */
1129          return;
1130       }
1131
1132 #ifdef HAVE_GETNAMEINFO
1133       *hostname = malloc(NI_MAXHOST);
1134       retval = getnameinfo((struct sockaddr *) &server, s_length,
1135          *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1136       if (retval)
1137       {
1138          log_error(LOG_LEVEL_ERROR,
1139             "Unable to resolve my own IP address: %s", gai_strerror(retval));
1140          freez(*hostname);
1141       }
1142 #else
1143 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1144       gethostbyaddr_r((const char *)&server.sin_addr,
1145                       sizeof(server.sin_addr), AF_INET,
1146                       &result, hbuf, HOSTENT_BUFFER_SIZE,
1147                       &host, &thd_err);
1148 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1149       host = gethostbyaddr_r((const char *)&server.sin_addr,
1150                       sizeof(server.sin_addr), AF_INET,
1151                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1152 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1153       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1154                                sizeof(server.sin_addr), AF_INET,
1155                                &result, &hdata))
1156       {
1157          host = &result;
1158       }
1159       else
1160       {
1161          host = NULL;
1162       }
1163 #elif FEATURE_PTHREAD
1164       privoxy_mutex_lock(&resolver_mutex);
1165       host = gethostbyaddr((const char *)&server.sin_addr, 
1166                            sizeof(server.sin_addr), AF_INET);
1167       privoxy_mutex_unlock(&resolver_mutex);
1168 #else
1169       host = gethostbyaddr((const char *)&server.sin_addr, 
1170                            sizeof(server.sin_addr), AF_INET);
1171 #endif
1172       if (host == NULL)
1173       {
1174          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1175       }
1176       else
1177       {
1178          *hostname = strdup(host->h_name);
1179       }
1180 #endif /* else def HAVE_GETNAMEINFO */
1181    }
1182
1183    return;
1184 }
1185
1186
1187 /*********************************************************************
1188  *
1189  * Function    :  accept_connection
1190  *
1191  * Description :  Accepts a connection on a socket.  Socket must have
1192  *                been created using bind_port().
1193  *
1194  * Parameters  :
1195  *          1  :  csp = Client state, cfd, ip_addr_str, and 
1196  *                ip_addr_long will be set by this routine.
1197  *          2  :  fd  = file descriptor returned from bind_port
1198  *
1199  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
1200  *                On an error it returns 0 (FALSE).
1201  *
1202  *********************************************************************/
1203 int accept_connection(struct client_state * csp, jb_socket fd)
1204 {
1205 #ifdef HAVE_GETNAMEINFO
1206    /* XXX: client is stored directly into csp->tcp_addr */
1207 #define client (csp->tcp_addr)
1208    int retval;
1209 #else
1210    struct sockaddr_in client;
1211 #endif
1212    jb_socket afd;
1213 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1214    /* Wierdness - fix a warning. */
1215    int c_length;
1216 #else
1217    socklen_t c_length;
1218 #endif
1219
1220    c_length = sizeof(client);
1221
1222 #ifdef _WIN32
1223    afd = accept (fd, (struct sockaddr *) &client, &c_length);
1224    if (afd == JB_INVALID_SOCKET)
1225    {
1226       return 0;
1227    }
1228 #else
1229    do
1230    {
1231       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1232    } while (afd < 1 && errno == EINTR);
1233    if (afd < 0)
1234    {
1235       return 0;
1236    }
1237 #endif
1238
1239    csp->cfd = afd;
1240 #ifdef HAVE_GETNAMEINFO
1241    csp->ip_addr_str = malloc(NI_MAXHOST);
1242    retval = getnameinfo((struct sockaddr *) &client, c_length,
1243          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1244    if (!csp->ip_addr_str || retval)
1245    {
1246       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1247             (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1248       freez(csp->ip_addr_str);
1249    }
1250 #undef client
1251 #else
1252    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1253    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1254 #endif /* def HAVE_GETNAMEINFO */
1255
1256    return 1;
1257
1258 }
1259
1260
1261 /*********************************************************************
1262  *
1263  * Function    :  resolve_hostname_to_ip
1264  *
1265  * Description :  Resolve a hostname to an internet tcp/ip address.
1266  *                NULL or an empty string resolve to INADDR_ANY.
1267  *
1268  * Parameters  :
1269  *          1  :  host = hostname to resolve
1270  *
1271  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1272  *
1273  *********************************************************************/
1274 unsigned long resolve_hostname_to_ip(const char *host)
1275 {
1276    struct sockaddr_in inaddr;
1277    struct hostent *hostp;
1278    unsigned int dns_retries = 0;
1279 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1280    struct hostent result;
1281 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1282    char hbuf[HOSTENT_BUFFER_SIZE];
1283    int thd_err;
1284 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1285    struct hostent_data hdata;
1286 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1287 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1288
1289    if ((host == NULL) || (*host == '\0'))
1290    {
1291       return(INADDR_ANY);
1292    }
1293
1294    memset((char *) &inaddr, 0, sizeof inaddr);
1295
1296    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1297    {
1298 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1299       while (gethostbyname_r(host, &result, hbuf,
1300                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1301              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1302       {   
1303          log_error(LOG_LEVEL_ERROR,
1304             "Timeout #%u while trying to resolve %s. Trying again.",
1305             dns_retries, host);
1306       }
1307 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1308       while (NULL == (hostp = gethostbyname_r(host, &result,
1309                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1310              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1311       {   
1312          log_error(LOG_LEVEL_ERROR,
1313             "Timeout #%u while trying to resolve %s. Trying again.",
1314             dns_retries, host);
1315       }
1316 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1317       /*
1318        * XXX: Doesn't retry in case of soft errors.
1319        * Does this gethostbyname_r version set h_errno?
1320        */
1321       if (0 == gethostbyname_r(host, &result, &hdata))
1322       {
1323          hostp = &result;
1324       }
1325       else
1326       {
1327          hostp = NULL;
1328       }
1329 #elif FEATURE_PTHREAD
1330       privoxy_mutex_lock(&resolver_mutex);
1331       while (NULL == (hostp = gethostbyname(host))
1332              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1333       {   
1334          log_error(LOG_LEVEL_ERROR,
1335             "Timeout #%u while trying to resolve %s. Trying again.",
1336             dns_retries, host);
1337       }
1338       privoxy_mutex_unlock(&resolver_mutex);
1339 #else
1340       while (NULL == (hostp = gethostbyname(host))
1341              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1342       {
1343          log_error(LOG_LEVEL_ERROR,
1344             "Timeout #%u while trying to resolve %s. Trying again.",
1345             dns_retries, host);
1346       }
1347 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1348       /*
1349        * On Mac OSX, if a domain exists but doesn't have a type A
1350        * record associated with it, the h_addr member of the struct
1351        * hostent returned by gethostbyname is NULL, even if h_length
1352        * is 4. Therefore the second test below.
1353        */
1354       if (hostp == NULL || hostp->h_addr == NULL)
1355       {
1356          errno = EINVAL;
1357          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1358          return(INADDR_NONE);
1359       }
1360       if (hostp->h_addrtype != AF_INET)
1361       {
1362 #ifdef _WIN32
1363          errno = WSAEPROTOTYPE;
1364 #else
1365          errno = EPROTOTYPE;
1366 #endif 
1367          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1368          return(INADDR_NONE);
1369       }
1370       memcpy(
1371          (char *) &inaddr.sin_addr,
1372          (char *) hostp->h_addr,
1373          sizeof(inaddr.sin_addr)
1374       );
1375    }
1376    return(inaddr.sin_addr.s_addr);
1377
1378 }
1379
1380
1381 /*
1382   Local Variables:
1383   tab-width: 3
1384   end:
1385 */