1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.57 2009/05/19 17:18:52 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)
280 && FD_ISSET(fd, &wfds))
283 * See Linux connect(2) man page for more info
284 * about connecting on non-blocking socket.
287 socklen_t optlen = sizeof(socket_in_error);
288 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
290 if (!socket_in_error)
292 /* Connection established, no need to try other addresses. */
295 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
296 csp->http->host_ip_addr_str, service, strerror(socket_in_error));
300 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
301 "the connection to [%s]:%s: %s; dropping connection.",
302 csp->http->host_ip_addr_str, service, strerror(errno));
306 /* Connection failed, try next address */
310 freeaddrinfo(result);
313 log_error(LOG_LEVEL_INFO, "Could not connect to [%s]:%s.",
315 return(JB_INVALID_SOCKET);
317 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
318 host, csp->http->host_ip_addr_str, service);
324 #else /* ndef HAVE_RFC2553 */
325 /* Pre-getaddrinfo implementation */
327 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
329 struct sockaddr_in inaddr;
333 struct timeval tv[1];
334 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
336 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
339 struct access_control_addr dst[1];
340 #endif /* def FEATURE_ACL */
342 memset((char *)&inaddr, 0, sizeof inaddr);
344 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
346 csp->http->host_ip_addr_str = strdup("unknown");
347 return(JB_INVALID_SOCKET);
351 dst->addr = ntohl(addr);
354 if (block_acl(dst, csp))
361 return(JB_INVALID_SOCKET);
363 #endif /* def FEATURE_ACL */
365 inaddr.sin_addr.s_addr = addr;
366 inaddr.sin_family = AF_INET;
367 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
370 if (sizeof(inaddr.sin_port) == sizeof(short))
371 #endif /* ndef _WIN32 */
373 inaddr.sin_port = htons((unsigned short) portnum);
378 inaddr.sin_port = htonl((unsigned long)portnum);
380 #endif /* ndef _WIN32 */
383 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
385 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
388 return(JB_INVALID_SOCKET);
392 { /* turn off TCP coalescence */
394 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
396 #endif /* def TCP_NODELAY */
398 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
399 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
402 fcntl(fd, F_SETFL, flags);
404 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
406 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
409 if (errno == WSAEINPROGRESS)
411 if (sock_errno() == EINPROGRESS)
412 #else /* ifndef _WIN32 */
413 if (errno == EINPROGRESS)
414 #endif /* ndef _WIN32 || __OS2__ */
420 if (sock_errno() != EINTR)
426 return(JB_INVALID_SOCKET);
430 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
434 fcntl(fd, F_SETFL, flags);
436 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
438 /* wait for connection to complete */
445 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
446 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
449 return(JB_INVALID_SOCKET);
454 #endif /* ndef HAVE_RFC2553 */
457 /*********************************************************************
459 * Function : write_socket
461 * Description : Write the contents of buf (for n bytes) to socket fd.
464 * 1 : fd = file descriptor (aka. handle) of socket to write to.
465 * 2 : buf = pointer to data to be written.
466 * 3 : len = length of data to be written to the socket "fd".
468 * Returns : 0 on success (entire buffer sent).
471 *********************************************************************/
473 int write_socket(jb_socket fd, const char *buf, ssize_t len)
475 int write_socket(jb_socket fd, const char *buf, size_t len)
483 if (len < 0) /* constant condition - size_t isn't ever negative */
488 log_error(LOG_LEVEL_LOG, "%N", len, buf);
491 return (send(fd, buf, (int)len, 0) != (int)len);
492 #elif defined(__BEOS__) || defined(AMIGA)
493 return (send(fd, buf, len, 0) != len);
494 #elif defined(__OS2__)
496 * Break the data up into SOCKET_SEND_MAX chunks for sending...
497 * OS/2 seemed to complain when the chunks were too large.
499 #define SOCKET_SEND_MAX 65000
501 int write_len = 0, send_len, send_rc = 0, i = 0;
502 while ((i < len) && (send_rc != -1))
504 if ((i + SOCKET_SEND_MAX) > len)
507 send_len = SOCKET_SEND_MAX;
508 send_rc = send(fd,(char*)buf + i, send_len, 0);
516 return (write(fd, buf, len) != len);
522 /*********************************************************************
524 * Function : read_socket
526 * Description : Read from a TCP/IP socket in a platform independent way.
529 * 1 : fd = file descriptor of the socket to read
530 * 2 : buf = pointer to buffer where data will be written
531 * Must be >= len bytes long.
532 * 3 : len = maximum number of bytes to read
534 * Returns : On success, the number of bytes read is returned (zero
535 * indicates end of file), and the file position is advanced
536 * by this number. It is not an error if this number is
537 * smaller than the number of bytes requested; this may hap-
538 * pen for example because fewer bytes are actually available
539 * right now (maybe because we were close to end-of-file, or
540 * because we are reading from a pipe, or from a terminal,
541 * or because read() was interrupted by a signal). On error,
542 * -1 is returned, and errno is set appropriately. In this
543 * case it is left unspecified whether the file position (if
546 *********************************************************************/
547 int read_socket(jb_socket fd, char *buf, int len)
555 return(recv(fd, buf, len, 0));
556 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
557 return(recv(fd, buf, (size_t)len, 0));
559 return(read(fd, buf, (size_t)len));
564 /*********************************************************************
566 * Function : data_is_available
568 * Description : Waits for data to arrive on a socket.
571 * 1 : fd = file descriptor of the socket to read
572 * 2 : seconds_to_wait = number of seconds after which we give up.
574 * Returns : TRUE if data arrived in time,
577 *********************************************************************/
578 int data_is_available(jb_socket fd, int seconds_to_wait)
581 struct timeval timeout;
584 memset(&timeout, 0, sizeof(timeout));
585 timeout.tv_sec = seconds_to_wait;
588 /* Copy and pasted from jcc.c ... */
589 memset(&rfds, 0, sizeof(fd_set));
595 n = select(fd+1, &rfds, NULL, NULL, &timeout);
598 * XXX: Do we care about the different error conditions?
604 /*********************************************************************
606 * Function : close_socket
608 * Description : Closes a TCP/IP socket
611 * 1 : fd = file descriptor of socket to be closed
615 *********************************************************************/
616 void close_socket(jb_socket fd)
618 #if defined(_WIN32) || defined(__BEOS__)
622 #elif defined(__OS2__)
631 /*********************************************************************
633 * Function : bind_port
635 * Description : Call socket, set socket options, and listen.
636 * Called by listen_loop to "boot up" our proxy address.
639 * 1 : hostnam = TCP/IP address to bind/listen to
640 * 2 : portnum = port to listen on
641 * 3 : pfd = pointer used to return file descriptor.
643 * Returns : if success, returns 0 and sets *pfd.
644 * if failure, returns -3 if address is in use,
645 * -2 if address unresolvable,
647 *********************************************************************/
648 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
651 struct addrinfo hints;
652 struct addrinfo *result, *rp;
654 * XXX: portnum should be a string to allow symbolic service
655 * names in the configuration file and to avoid the following
661 struct sockaddr_in inaddr;
662 #endif /* def HAVE_RFC2553 */
666 #endif /* ndef _WIN32 */
668 *pfd = JB_INVALID_SOCKET;
671 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
672 if ((-1 == retval) || (sizeof(servnam) <= retval))
674 log_error(LOG_LEVEL_ERROR,
675 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
680 memset(&hints, 0, sizeof(struct addrinfo));
681 if ((hostnam == NULL) || !strcmpic(hostnam, "localhost"))
684 * XXX: This is a hack. The right thing to do
685 * would be to bind to both AF_INET and AF_INET6.
686 * This will also fail if there is no AF_INET
689 hints.ai_family = AF_INET;
693 hints.ai_family = AF_UNSPEC;
695 hints.ai_socktype = SOCK_STREAM;
696 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
697 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
698 hints.ai_canonname = NULL;
699 hints.ai_addr = NULL;
700 hints.ai_next = NULL;
702 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
704 log_error(LOG_LEVEL_ERROR,
705 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
709 memset((char *)&inaddr, '\0', sizeof inaddr);
711 inaddr.sin_family = AF_INET;
712 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
714 if (inaddr.sin_addr.s_addr == INADDR_NONE)
720 if (sizeof(inaddr.sin_port) == sizeof(short))
721 #endif /* ndef _WIN32 */
723 inaddr.sin_port = htons((unsigned short) portnum);
728 inaddr.sin_port = htonl((unsigned long) portnum);
730 #endif /* ndef _WIN32 */
731 #endif /* def HAVE_RFC2553 */
734 for (rp = result; rp != NULL; rp = rp->ai_next)
736 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
738 fd = socket(AF_INET, SOCK_STREAM, 0);
739 #endif /* def HAVE_RFC2553 */
742 if (fd == JB_INVALID_SOCKET)
756 * This is not needed for Win32 - in fact, it stops
757 * duplicate instances of Privoxy from being caught.
759 * On UNIX, we assume the user is sensible enough not
760 * to start Privoxy multiple times on the same IP.
761 * Without this, stopping and restarting Privoxy
762 * from a script fails.
763 * Note: SO_REUSEADDR is meant to only take over
764 * sockets which are *not* in listen state in Linux,
765 * e.g. sockets in TIME_WAIT. YMMV.
767 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
768 #endif /* ndef _WIN32 */
771 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
773 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
777 errno = WSAGetLastError();
778 if (errno == WSAEADDRINUSE)
780 if (errno == EADDRINUSE)
784 freeaddrinfo(result);
801 /* bind() succeeded, escape from for-loop */
803 * XXX: Support multiple listening sockets (e.g. localhost
804 * resolves to AF_INET and AF_INET6, but only the first address
811 freeaddrinfo(result);
814 /* All bind()s failed */
817 #endif /* ndef HAVE_RFC2553 */
819 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
833 /*********************************************************************
835 * Function : get_host_information
837 * Description : Determines the IP address the client used to
838 * reach us and the hostname associated with it.
840 * XXX: Most of the code has been copy and pasted
841 * from accept_connection() and not all of the
842 * ifdefs paths have been tested afterwards.
845 * 1 : afd = File descriptor returned from accept().
846 * 2 : ip_address = Pointer to return the pointer to
847 * the ip address string.
848 * 3 : hostname = Pointer to return the pointer to
849 * the hostname or NULL if the caller
850 * isn't interested in it.
854 *********************************************************************/
855 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
858 struct sockaddr_storage server;
861 struct sockaddr_in server;
862 struct hostent *host = NULL;
863 #endif /* HAVE_RFC2553 */
864 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
865 /* according to accept_connection() this fixes a warning. */
866 int s_length, s_length_provided;
868 socklen_t s_length, s_length_provided;
871 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
872 struct hostent result;
873 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
874 struct hostent_data hdata;
876 char hbuf[HOSTENT_BUFFER_SIZE];
878 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
879 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
880 #endif /* ifndef HAVE_RFC2553 */
881 s_length = s_length_provided = sizeof(server);
883 if (NULL != hostname)
889 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
891 if (s_length > s_length_provided)
893 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
897 *ip_address = malloc(NI_MAXHOST);
898 retval = getnameinfo((struct sockaddr *) &server, s_length,
899 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
902 log_error(LOG_LEVEL_ERROR,
903 "Unable to print my own IP address: %s", gai_strerror(retval));
908 *ip_address = strdup(inet_ntoa(server.sin_addr));
909 #endif /* HAVE_RFC2553 */
910 if (NULL == hostname)
913 * We're done here, the caller isn't
914 * interested in knowing the hostname.
920 *hostname = malloc(NI_MAXHOST);
921 retval = getnameinfo((struct sockaddr *) &server, s_length,
922 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
925 log_error(LOG_LEVEL_ERROR,
926 "Unable to resolve my own IP address: %s", gai_strerror(retval));
930 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
931 gethostbyaddr_r((const char *)&server.sin_addr,
932 sizeof(server.sin_addr), AF_INET,
933 &result, hbuf, HOSTENT_BUFFER_SIZE,
935 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
936 host = gethostbyaddr_r((const char *)&server.sin_addr,
937 sizeof(server.sin_addr), AF_INET,
938 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
939 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
940 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
941 sizeof(server.sin_addr), AF_INET,
950 #elif FEATURE_PTHREAD
951 privoxy_mutex_lock(&resolver_mutex);
952 host = gethostbyaddr((const char *)&server.sin_addr,
953 sizeof(server.sin_addr), AF_INET);
954 privoxy_mutex_unlock(&resolver_mutex);
956 host = gethostbyaddr((const char *)&server.sin_addr,
957 sizeof(server.sin_addr), AF_INET);
961 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
965 *hostname = strdup(host->h_name);
967 #endif /* else def HAVE_RFC2553 */
974 /*********************************************************************
976 * Function : accept_connection
978 * Description : Accepts a connection on a socket. Socket must have
979 * been created using bind_port().
982 * 1 : csp = Client state, cfd, ip_addr_str, and
983 * ip_addr_long will be set by this routine.
984 * 2 : fd = file descriptor returned from bind_port
986 * Returns : when a connection is accepted, it returns 1 (TRUE).
987 * On an error it returns 0 (FALSE).
989 *********************************************************************/
990 int accept_connection(struct client_state * csp, jb_socket fd)
993 /* XXX: client is stored directly into csp->tcp_addr */
994 #define client (csp->tcp_addr)
997 struct sockaddr_in client;
1000 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1001 /* Wierdness - fix a warning. */
1007 c_length = sizeof(client);
1010 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1011 if (afd == JB_INVALID_SOCKET)
1018 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1019 } while (afd < 1 && errno == EINTR);
1028 csp->ip_addr_str = malloc(NI_MAXHOST);
1029 retval = getnameinfo((struct sockaddr *) &client, c_length,
1030 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1031 if (!csp->ip_addr_str || retval)
1033 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1034 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1035 freez(csp->ip_addr_str);
1039 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1040 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1041 #endif /* def HAVE_RFC2553 */
1048 /*********************************************************************
1050 * Function : resolve_hostname_to_ip
1052 * Description : Resolve a hostname to an internet tcp/ip address.
1053 * NULL or an empty string resolve to INADDR_ANY.
1056 * 1 : host = hostname to resolve
1058 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1060 *********************************************************************/
1061 unsigned long resolve_hostname_to_ip(const char *host)
1063 struct sockaddr_in inaddr;
1064 struct hostent *hostp;
1065 unsigned int dns_retries = 0;
1066 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1067 struct hostent result;
1068 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1069 char hbuf[HOSTENT_BUFFER_SIZE];
1071 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1072 struct hostent_data hdata;
1073 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1074 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1076 if ((host == NULL) || (*host == '\0'))
1081 memset((char *) &inaddr, 0, sizeof inaddr);
1083 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1085 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1086 while (gethostbyname_r(host, &result, hbuf,
1087 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1088 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1090 log_error(LOG_LEVEL_ERROR,
1091 "Timeout #%u while trying to resolve %s. Trying again.",
1094 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1095 while (NULL == (hostp = gethostbyname_r(host, &result,
1096 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1097 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1099 log_error(LOG_LEVEL_ERROR,
1100 "Timeout #%u while trying to resolve %s. Trying again.",
1103 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1105 * XXX: Doesn't retry in case of soft errors.
1106 * Does this gethostbyname_r version set h_errno?
1108 if (0 == gethostbyname_r(host, &result, &hdata))
1116 #elif FEATURE_PTHREAD
1117 privoxy_mutex_lock(&resolver_mutex);
1118 while (NULL == (hostp = gethostbyname(host))
1119 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1121 log_error(LOG_LEVEL_ERROR,
1122 "Timeout #%u while trying to resolve %s. Trying again.",
1125 privoxy_mutex_unlock(&resolver_mutex);
1127 while (NULL == (hostp = gethostbyname(host))
1128 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1130 log_error(LOG_LEVEL_ERROR,
1131 "Timeout #%u while trying to resolve %s. Trying again.",
1134 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1136 * On Mac OSX, if a domain exists but doesn't have a type A
1137 * record associated with it, the h_addr member of the struct
1138 * hostent returned by gethostbyname is NULL, even if h_length
1139 * is 4. Therefore the second test below.
1141 if (hostp == NULL || hostp->h_addr == NULL)
1144 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1145 return(INADDR_NONE);
1147 if (hostp->h_addrtype != AF_INET)
1150 errno = WSAEPROTOTYPE;
1154 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1155 return(INADDR_NONE);
1158 (char *) &inaddr.sin_addr,
1159 (char *) hostp->h_addr,
1160 sizeof(inaddr.sin_addr)
1163 return(inaddr.sin_addr.s_addr);
1168 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1169 /*********************************************************************
1171 * Function : socket_is_still_usable
1173 * Description : Decides whether or not an open socket is still usable.
1176 * 1 : sfd = The socket to check.
1178 * Returns : TRUE for yes, otherwise FALSE.
1180 *********************************************************************/
1181 int socket_is_still_usable(jb_socket sfd)
1185 struct pollfd poll_fd[1];
1187 memset(poll_fd, 0, sizeof(poll_fd));
1188 poll_fd[0].fd = sfd;
1189 poll_fd[0].events = POLLIN;
1191 poll_result = poll(poll_fd, 1, 0);
1193 if (-1 != poll_result)
1195 return !(poll_fd[0].revents & POLLIN);
1199 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1203 fd_set readable_fds;
1204 struct timeval timeout;
1206 int socket_is_alive = 0;
1208 memset(&timeout, '\0', sizeof(timeout));
1209 FD_ZERO(&readable_fds);
1210 FD_SET(sfd, &readable_fds);
1212 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1215 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1219 * XXX: I'm not sure why !FD_ISSET() works,
1220 * but apparently it does.
1222 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
1224 return socket_is_alive;
1225 #endif /* def HAVE_POLL */
1227 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */