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