1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.56 2009/05/16 13:27:20 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
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
11 * Copyright : Written by and Copyright (C) 2001-2009 the
12 * Privoxy team. http://www.privoxy.org/
14 * Based on the Internet Junkbuster originally written
15 * by and Copyright (C) 1997 Anonymous Coders and
16 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
36 *********************************************************************/
46 #include <sys/types.h>
54 #include <sys/timeb.h>
63 #include <netinet/in.h>
64 #include <sys/ioctl.h>
66 #include <sys/socket.h>
69 #include <netinet/tcp.h>
71 #include <arpa/inet.h>
77 #if defined(__EMX__) || defined (__OS2__)
78 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
86 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
94 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
98 #ifdef FEATURE_PTHREAD
100 /* jcc.h is for mutex semaphores only */
101 #endif /* def FEATURE_PTHREAD */
103 #include "jbsockets.h"
106 #include "miscutil.h"
108 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
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?
115 #define MAX_DNS_RETRIES 10
117 #define MAX_LISTEN_BACKLOG 128
120 /*********************************************************************
122 * Function : connect_to
124 * Description : Open a socket and connect to it. Will check
125 * that this is allowed according to ACL.
128 * 1 : host = hostname to connect to
129 * 2 : portnum = port to connent on (XXX: should be unsigned)
130 * 3 : csp = Current client state (buffers, headers, etc...)
131 * Not modified, only used for source IP and ACL.
133 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
136 *********************************************************************/
138 /* Getaddrinfo implementation */
139 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
141 struct addrinfo hints, *result, *rp;
146 struct timeval tv[1];
147 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
149 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
153 struct access_control_addr dst[1];
154 #endif /* def FEATURE_ACL */
156 retval = snprintf(service, sizeof(service), "%d", portnum);
157 if ((-1 == retval) || (sizeof(service) <= retval))
159 log_error(LOG_LEVEL_ERROR,
160 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
162 csp->http->host_ip_addr_str = strdup("unknown");
163 return(JB_INVALID_SOCKET);
166 memset((char *)&hints, 0, sizeof(hints));
167 hints.ai_family = AF_UNSPEC;
168 hints.ai_socktype = SOCK_STREAM;
169 hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV; /* avoid service look-up */
170 if ((retval = getaddrinfo(host, service, &hints, &result)))
172 log_error(LOG_LEVEL_INFO,
173 "Can not resolve %s: %s", host, gai_strerror(retval));
174 csp->http->host_ip_addr_str = strdup("unknown");
175 return(JB_INVALID_SOCKET);
178 for (rp = result; rp != NULL; rp = rp->ai_next)
182 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
184 if (block_acl(dst, csp))
193 #endif /* def FEATURE_ACL */
195 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
196 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
197 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
198 if (!csp->http->host_ip_addr_str || retval)
200 log_error(LOG_LEVEL_ERROR,
201 "Can not save csp->http->host_ip_addr_str: %s",
202 (csp->http->host_ip_addr_str) ?
203 gai_strerror(retval) : "Insufficient memory");
204 freez(csp->http->host_ip_addr_str);
209 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
212 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
219 { /* turn off TCP coalescence */
221 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
223 #endif /* def TCP_NODELAY */
225 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
226 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
229 fcntl(fd, F_SETFL, flags);
231 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
234 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
237 if (errno == WSAEINPROGRESS)
239 if (sock_errno() == EINPROGRESS)
240 #else /* ifndef _WIN32 */
241 if (errno == EINPROGRESS)
242 #endif /* ndef _WIN32 || __OS2__ */
248 if (sock_errno() != EINTR)
263 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
267 fcntl(fd, F_SETFL, flags);
269 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
271 /* wait for connection to complete */
278 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
279 if (select((int)fd + 1, NULL, &wfds, NULL, tv) > 0 &&
282 /* See Linux connect(2) man page for more info about connecting on
283 * non-blocking socket. */
285 socklen_t optlen = sizeof(socket_in_error);
286 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
288 if (!socket_in_error)
290 break; /* for; Connection established; don't try other addresses */
292 log_error(LOG_LEVEL_INFO, "Could not connect to TCP/[%s]:%s: %s",
293 csp->http->host_ip_addr_str, service,
294 strerror(socket_in_error));
298 log_error(LOG_LEVEL_ERROR,
299 "Could not get state of TCP connection to [%s]:%s: %s;"
300 " dropping connection",
301 csp->http->host_ip_addr_str, service, strerror(errno));
305 /* Connection failed, try next address */
309 freeaddrinfo(result);
312 log_error(LOG_LEVEL_INFO,
313 "Could not connect to TCP/[%s]:%s", host, service);
314 return(JB_INVALID_SOCKET);
316 log_error(LOG_LEVEL_INFO, "Connected to TCP/%s[%s]:%s", host,
317 csp->http->host_ip_addr_str, service);
323 #else /* ndef HAVE_RFC2553 */
324 /* Pre-getaddrinfo implementation */
326 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
328 struct sockaddr_in inaddr;
332 struct timeval tv[1];
333 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
335 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
338 struct access_control_addr dst[1];
339 #endif /* def FEATURE_ACL */
341 memset((char *)&inaddr, 0, sizeof inaddr);
343 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
345 csp->http->host_ip_addr_str = strdup("unknown");
346 return(JB_INVALID_SOCKET);
350 dst->addr = ntohl(addr);
353 if (block_acl(dst, csp))
360 return(JB_INVALID_SOCKET);
362 #endif /* def FEATURE_ACL */
364 inaddr.sin_addr.s_addr = addr;
365 inaddr.sin_family = AF_INET;
366 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
369 if (sizeof(inaddr.sin_port) == sizeof(short))
370 #endif /* ndef _WIN32 */
372 inaddr.sin_port = htons((unsigned short) portnum);
377 inaddr.sin_port = htonl((unsigned long)portnum);
379 #endif /* ndef _WIN32 */
382 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
384 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
387 return(JB_INVALID_SOCKET);
391 { /* turn off TCP coalescence */
393 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
395 #endif /* def TCP_NODELAY */
397 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
398 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
401 fcntl(fd, F_SETFL, flags);
403 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
405 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
408 if (errno == WSAEINPROGRESS)
410 if (sock_errno() == EINPROGRESS)
411 #else /* ifndef _WIN32 */
412 if (errno == EINPROGRESS)
413 #endif /* ndef _WIN32 || __OS2__ */
419 if (sock_errno() != EINTR)
425 return(JB_INVALID_SOCKET);
429 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
433 fcntl(fd, F_SETFL, flags);
435 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
437 /* wait for connection to complete */
444 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
445 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
448 return(JB_INVALID_SOCKET);
453 #endif /* ndef HAVE_RFC2553 */
456 /*********************************************************************
458 * Function : write_socket
460 * Description : Write the contents of buf (for n bytes) to socket fd.
463 * 1 : fd = file descriptor (aka. handle) of socket to write to.
464 * 2 : buf = pointer to data to be written.
465 * 3 : len = length of data to be written to the socket "fd".
467 * Returns : 0 on success (entire buffer sent).
470 *********************************************************************/
472 int write_socket(jb_socket fd, const char *buf, ssize_t len)
474 int write_socket(jb_socket fd, const char *buf, size_t len)
482 if (len < 0) /* constant condition - size_t isn't ever negative */
487 log_error(LOG_LEVEL_LOG, "%N", len, buf);
490 return (send(fd, buf, (int)len, 0) != (int)len);
491 #elif defined(__BEOS__) || defined(AMIGA)
492 return (send(fd, buf, len, 0) != len);
493 #elif defined(__OS2__)
495 * Break the data up into SOCKET_SEND_MAX chunks for sending...
496 * OS/2 seemed to complain when the chunks were too large.
498 #define SOCKET_SEND_MAX 65000
500 int write_len = 0, send_len, send_rc = 0, i = 0;
501 while ((i < len) && (send_rc != -1))
503 if ((i + SOCKET_SEND_MAX) > len)
506 send_len = SOCKET_SEND_MAX;
507 send_rc = send(fd,(char*)buf + i, send_len, 0);
515 return (write(fd, buf, len) != len);
521 /*********************************************************************
523 * Function : read_socket
525 * Description : Read from a TCP/IP socket in a platform independent way.
528 * 1 : fd = file descriptor of the socket to read
529 * 2 : buf = pointer to buffer where data will be written
530 * Must be >= len bytes long.
531 * 3 : len = maximum number of bytes to read
533 * Returns : On success, the number of bytes read is returned (zero
534 * indicates end of file), and the file position is advanced
535 * by this number. It is not an error if this number is
536 * smaller than the number of bytes requested; this may hap-
537 * pen for example because fewer bytes are actually available
538 * right now (maybe because we were close to end-of-file, or
539 * because we are reading from a pipe, or from a terminal,
540 * or because read() was interrupted by a signal). On error,
541 * -1 is returned, and errno is set appropriately. In this
542 * case it is left unspecified whether the file position (if
545 *********************************************************************/
546 int read_socket(jb_socket fd, char *buf, int len)
554 return(recv(fd, buf, len, 0));
555 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
556 return(recv(fd, buf, (size_t)len, 0));
558 return(read(fd, buf, (size_t)len));
563 /*********************************************************************
565 * Function : data_is_available
567 * Description : Waits for data to arrive on a socket.
570 * 1 : fd = file descriptor of the socket to read
571 * 2 : seconds_to_wait = number of seconds after which we give up.
573 * Returns : TRUE if data arrived in time,
576 *********************************************************************/
577 int data_is_available(jb_socket fd, int seconds_to_wait)
580 struct timeval timeout;
583 memset(&timeout, 0, sizeof(timeout));
584 timeout.tv_sec = seconds_to_wait;
587 /* Copy and pasted from jcc.c ... */
588 memset(&rfds, 0, sizeof(fd_set));
594 n = select(fd+1, &rfds, NULL, NULL, &timeout);
597 * XXX: Do we care about the different error conditions?
603 /*********************************************************************
605 * Function : close_socket
607 * Description : Closes a TCP/IP socket
610 * 1 : fd = file descriptor of socket to be closed
614 *********************************************************************/
615 void close_socket(jb_socket fd)
617 #if defined(_WIN32) || defined(__BEOS__)
621 #elif defined(__OS2__)
630 /*********************************************************************
632 * Function : bind_port
634 * Description : Call socket, set socket options, and listen.
635 * Called by listen_loop to "boot up" our proxy address.
638 * 1 : hostnam = TCP/IP address to bind/listen to
639 * 2 : portnum = port to listen on
640 * 3 : pfd = pointer used to return file descriptor.
642 * Returns : if success, returns 0 and sets *pfd.
643 * if failure, returns -3 if address is in use,
644 * -2 if address unresolvable,
646 *********************************************************************/
647 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
650 struct addrinfo hints;
651 struct addrinfo *result, *rp;
653 * XXX: portnum should be a string to allow symbolic service
654 * names in the configuration file and to avoid the following
660 struct sockaddr_in inaddr;
661 #endif /* def HAVE_RFC2553 */
665 #endif /* ndef _WIN32 */
667 *pfd = JB_INVALID_SOCKET;
670 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
671 if ((-1 == retval) || (sizeof(servnam) <= retval))
673 log_error(LOG_LEVEL_ERROR,
674 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
679 memset(&hints, 0, sizeof(struct addrinfo));
680 if ((hostnam == NULL) || !strcmpic(hostnam, "localhost"))
683 * XXX: This is a hack. The right thing to do
684 * would be to bind to both AF_INET and AF_INET6.
685 * This will also fail if there is no AF_INET
688 hints.ai_family = AF_INET;
692 hints.ai_family = AF_UNSPEC;
694 hints.ai_socktype = SOCK_STREAM;
695 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
696 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
697 hints.ai_canonname = NULL;
698 hints.ai_addr = NULL;
699 hints.ai_next = NULL;
701 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
703 log_error(LOG_LEVEL_ERROR,
704 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
708 memset((char *)&inaddr, '\0', sizeof inaddr);
710 inaddr.sin_family = AF_INET;
711 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
713 if (inaddr.sin_addr.s_addr == INADDR_NONE)
719 if (sizeof(inaddr.sin_port) == sizeof(short))
720 #endif /* ndef _WIN32 */
722 inaddr.sin_port = htons((unsigned short) portnum);
727 inaddr.sin_port = htonl((unsigned long) portnum);
729 #endif /* ndef _WIN32 */
730 #endif /* def HAVE_RFC2553 */
733 for (rp = result; rp != NULL; rp = rp->ai_next)
735 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
737 fd = socket(AF_INET, SOCK_STREAM, 0);
738 #endif /* def HAVE_RFC2553 */
741 if (fd == JB_INVALID_SOCKET)
755 * This is not needed for Win32 - in fact, it stops
756 * duplicate instances of Privoxy from being caught.
758 * On UNIX, we assume the user is sensible enough not
759 * to start Privoxy multiple times on the same IP.
760 * Without this, stopping and restarting Privoxy
761 * from a script fails.
762 * Note: SO_REUSEADDR is meant to only take over
763 * sockets which are *not* in listen state in Linux,
764 * e.g. sockets in TIME_WAIT. YMMV.
766 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
767 #endif /* ndef _WIN32 */
770 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
772 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
776 errno = WSAGetLastError();
777 if (errno == WSAEADDRINUSE)
779 if (errno == EADDRINUSE)
783 freeaddrinfo(result);
800 /* bind() succeeded, escape from for-loop */
802 * XXX: Support multiple listening sockets (e.g. localhost
803 * resolves to AF_INET and AF_INET6, but only the first address
810 freeaddrinfo(result);
813 /* All bind()s failed */
816 #endif /* ndef HAVE_RFC2553 */
818 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
832 /*********************************************************************
834 * Function : get_host_information
836 * Description : Determines the IP address the client used to
837 * reach us and the hostname associated with it.
839 * XXX: Most of the code has been copy and pasted
840 * from accept_connection() and not all of the
841 * ifdefs paths have been tested afterwards.
844 * 1 : afd = File descriptor returned from accept().
845 * 2 : ip_address = Pointer to return the pointer to
846 * the ip address string.
847 * 3 : hostname = Pointer to return the pointer to
848 * the hostname or NULL if the caller
849 * isn't interested in it.
853 *********************************************************************/
854 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
857 struct sockaddr_storage server;
860 struct sockaddr_in server;
861 struct hostent *host = NULL;
862 #endif /* HAVE_RFC2553 */
863 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
864 /* according to accept_connection() this fixes a warning. */
865 int s_length, s_length_provided;
867 socklen_t s_length, s_length_provided;
870 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
871 struct hostent result;
872 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
873 struct hostent_data hdata;
875 char hbuf[HOSTENT_BUFFER_SIZE];
877 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
878 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
879 #endif /* ifndef HAVE_RFC2553 */
880 s_length = s_length_provided = sizeof(server);
882 if (NULL != hostname)
888 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
890 if (s_length > s_length_provided)
892 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
896 *ip_address = malloc(NI_MAXHOST);
897 retval = getnameinfo((struct sockaddr *) &server, s_length,
898 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
901 log_error(LOG_LEVEL_ERROR,
902 "Unable to print my own IP address: %s", gai_strerror(retval));
907 *ip_address = strdup(inet_ntoa(server.sin_addr));
908 #endif /* HAVE_RFC2553 */
909 if (NULL == hostname)
912 * We're done here, the caller isn't
913 * interested in knowing the hostname.
919 *hostname = malloc(NI_MAXHOST);
920 retval = getnameinfo((struct sockaddr *) &server, s_length,
921 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
924 log_error(LOG_LEVEL_ERROR,
925 "Unable to resolve my own IP address: %s", gai_strerror(retval));
929 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
930 gethostbyaddr_r((const char *)&server.sin_addr,
931 sizeof(server.sin_addr), AF_INET,
932 &result, hbuf, HOSTENT_BUFFER_SIZE,
934 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
935 host = gethostbyaddr_r((const char *)&server.sin_addr,
936 sizeof(server.sin_addr), AF_INET,
937 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
938 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
939 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
940 sizeof(server.sin_addr), AF_INET,
949 #elif FEATURE_PTHREAD
950 privoxy_mutex_lock(&resolver_mutex);
951 host = gethostbyaddr((const char *)&server.sin_addr,
952 sizeof(server.sin_addr), AF_INET);
953 privoxy_mutex_unlock(&resolver_mutex);
955 host = gethostbyaddr((const char *)&server.sin_addr,
956 sizeof(server.sin_addr), AF_INET);
960 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
964 *hostname = strdup(host->h_name);
966 #endif /* else def HAVE_RFC2553 */
973 /*********************************************************************
975 * Function : accept_connection
977 * Description : Accepts a connection on a socket. Socket must have
978 * been created using bind_port().
981 * 1 : csp = Client state, cfd, ip_addr_str, and
982 * ip_addr_long will be set by this routine.
983 * 2 : fd = file descriptor returned from bind_port
985 * Returns : when a connection is accepted, it returns 1 (TRUE).
986 * On an error it returns 0 (FALSE).
988 *********************************************************************/
989 int accept_connection(struct client_state * csp, jb_socket fd)
992 /* XXX: client is stored directly into csp->tcp_addr */
993 #define client (csp->tcp_addr)
996 struct sockaddr_in client;
999 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1000 /* Wierdness - fix a warning. */
1006 c_length = sizeof(client);
1009 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1010 if (afd == JB_INVALID_SOCKET)
1017 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1018 } while (afd < 1 && errno == EINTR);
1027 csp->ip_addr_str = malloc(NI_MAXHOST);
1028 retval = getnameinfo((struct sockaddr *) &client, c_length,
1029 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1030 if (!csp->ip_addr_str || retval)
1032 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1033 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1034 freez(csp->ip_addr_str);
1038 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1039 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1040 #endif /* def HAVE_RFC2553 */
1047 /*********************************************************************
1049 * Function : resolve_hostname_to_ip
1051 * Description : Resolve a hostname to an internet tcp/ip address.
1052 * NULL or an empty string resolve to INADDR_ANY.
1055 * 1 : host = hostname to resolve
1057 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1059 *********************************************************************/
1060 unsigned long resolve_hostname_to_ip(const char *host)
1062 struct sockaddr_in inaddr;
1063 struct hostent *hostp;
1064 unsigned int dns_retries = 0;
1065 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1066 struct hostent result;
1067 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1068 char hbuf[HOSTENT_BUFFER_SIZE];
1070 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1071 struct hostent_data hdata;
1072 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1073 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1075 if ((host == NULL) || (*host == '\0'))
1080 memset((char *) &inaddr, 0, sizeof inaddr);
1082 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1084 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1085 while (gethostbyname_r(host, &result, hbuf,
1086 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1087 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1089 log_error(LOG_LEVEL_ERROR,
1090 "Timeout #%u while trying to resolve %s. Trying again.",
1093 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1094 while (NULL == (hostp = gethostbyname_r(host, &result,
1095 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1096 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1098 log_error(LOG_LEVEL_ERROR,
1099 "Timeout #%u while trying to resolve %s. Trying again.",
1102 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1104 * XXX: Doesn't retry in case of soft errors.
1105 * Does this gethostbyname_r version set h_errno?
1107 if (0 == gethostbyname_r(host, &result, &hdata))
1115 #elif FEATURE_PTHREAD
1116 privoxy_mutex_lock(&resolver_mutex);
1117 while (NULL == (hostp = gethostbyname(host))
1118 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1120 log_error(LOG_LEVEL_ERROR,
1121 "Timeout #%u while trying to resolve %s. Trying again.",
1124 privoxy_mutex_unlock(&resolver_mutex);
1126 while (NULL == (hostp = gethostbyname(host))
1127 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1129 log_error(LOG_LEVEL_ERROR,
1130 "Timeout #%u while trying to resolve %s. Trying again.",
1133 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1135 * On Mac OSX, if a domain exists but doesn't have a type A
1136 * record associated with it, the h_addr member of the struct
1137 * hostent returned by gethostbyname is NULL, even if h_length
1138 * is 4. Therefore the second test below.
1140 if (hostp == NULL || hostp->h_addr == NULL)
1143 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1144 return(INADDR_NONE);
1146 if (hostp->h_addrtype != AF_INET)
1149 errno = WSAEPROTOTYPE;
1153 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1154 return(INADDR_NONE);
1157 (char *) &inaddr.sin_addr,
1158 (char *) hostp->h_addr,
1159 sizeof(inaddr.sin_addr)
1162 return(inaddr.sin_addr.s_addr);
1167 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1168 /*********************************************************************
1170 * Function : socket_is_still_usable
1172 * Description : Decides whether or not an open socket is still usable.
1175 * 1 : sfd = The socket to check.
1177 * Returns : TRUE for yes, otherwise FALSE.
1179 *********************************************************************/
1180 int socket_is_still_usable(jb_socket sfd)
1184 struct pollfd poll_fd[1];
1186 memset(poll_fd, 0, sizeof(poll_fd));
1187 poll_fd[0].fd = sfd;
1188 poll_fd[0].events = POLLIN;
1190 poll_result = poll(poll_fd, 1, 0);
1192 if (-1 != poll_result)
1194 return !(poll_fd[0].revents & POLLIN);
1198 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1202 fd_set readable_fds;
1203 struct timeval timeout;
1205 int socket_is_alive = 0;
1207 memset(&timeout, '\0', sizeof(timeout));
1208 FD_ZERO(&readable_fds);
1209 FD_SET(sfd, &readable_fds);
1211 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1214 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1218 * XXX: I'm not sure why !FD_ISSET() works,
1219 * but apparently it does.
1221 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
1223 return socket_is_alive;
1224 #endif /* def HAVE_POLL */
1226 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */