1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.99 2011/04/19 13:00:47 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-2011 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 /* For mutex semaphores only */
101 #include "jbsockets.h"
105 /* Mac OSX doesn't define AI_NUMERICSESRV */
106 #ifndef AI_NUMERICSERV
107 #define AI_NUMERICSERV 0
110 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
113 * Maximum number of gethostbyname(_r) retries in case of
114 * soft errors (TRY_AGAIN).
115 * XXX: Does it make sense to make this a config option?
117 #define MAX_DNS_RETRIES 10
119 #define MAX_LISTEN_BACKLOG 128
122 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
124 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
127 /*********************************************************************
129 * Function : connect_to
131 * Description : Open a socket and connect to it. Will check
132 * that this is allowed according to ACL.
135 * 1 : host = hostname to connect to
136 * 2 : portnum = port to connent on (XXX: should be unsigned)
137 * 3 : csp = Current client state (buffers, headers, etc...)
139 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
142 *********************************************************************/
143 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
146 int forwarded_connect_retries = 0;
151 * XXX: The whole errno overloading is ridiculous and should
152 * be replaced with something sane and thread safe
156 fd = rfc2553_connect_to(host, portnum, csp);
158 fd = no_rfc2553_connect_to(host, portnum, csp);
160 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
161 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
165 forwarded_connect_retries++;
166 if (csp->config->forwarded_connect_retries != 0)
168 log_error(LOG_LEVEL_ERROR,
169 "Attempt %d of %d to connect to %s failed. Trying again.",
170 forwarded_connect_retries, csp->config->forwarded_connect_retries, host);
173 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
179 /* Getaddrinfo implementation */
180 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
182 struct addrinfo hints, *result, *rp;
187 struct timeval timeout;
188 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
193 * XXX: Initializeing it here is only necessary
194 * because not all situations are properly
197 int socket_error = 0;
200 struct access_control_addr dst[1];
201 #endif /* def FEATURE_ACL */
203 /* Don't leak memory when retrying. */
204 freez(csp->error_message);
205 freez(csp->http->host_ip_addr_str);
207 retval = snprintf(service, sizeof(service), "%d", portnum);
208 if ((-1 == retval) || (sizeof(service) <= retval))
210 log_error(LOG_LEVEL_ERROR,
211 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
213 csp->error_message = strdup("Invalid port number");
214 csp->http->host_ip_addr_str = strdup("unknown");
215 return(JB_INVALID_SOCKET);
218 memset((char *)&hints, 0, sizeof(hints));
219 hints.ai_family = AF_UNSPEC;
220 hints.ai_socktype = SOCK_STREAM;
221 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
223 hints.ai_flags |= AI_ADDRCONFIG;
225 if ((retval = getaddrinfo(host, service, &hints, &result)))
227 log_error(LOG_LEVEL_INFO,
228 "Can not resolve %s: %s", host, gai_strerror(retval));
229 /* XXX: Should find a better way to propagate this error. */
231 csp->error_message = strdup(gai_strerror(retval));
232 csp->http->host_ip_addr_str = strdup("unknown");
233 return(JB_INVALID_SOCKET);
236 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
237 if (NULL == csp->http->host_ip_addr_str)
239 freeaddrinfo(result);
240 log_error(LOG_LEVEL_ERROR,
241 "Out of memory while getting the server IP address.");
242 return JB_INVALID_SOCKET;
245 for (rp = result; rp != NULL; rp = rp->ai_next)
249 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
251 if (block_acl(dst, csp))
254 socket_error = errno = SOCEPERM;
256 socket_error = errno = EPERM;
260 #endif /* def FEATURE_ACL */
262 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
263 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
266 log_error(LOG_LEVEL_ERROR,
267 "Failed to get the host name from the socket structure: %s",
268 gai_strerror(retval));
272 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
274 if (fd == JB_INVALID_SOCKET)
283 { /* turn off TCP coalescence */
285 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
287 #endif /* def TCP_NODELAY */
289 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
290 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
293 fcntl(fd, F_SETFL, flags);
295 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
298 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
301 errno = sock_errno();
305 if (errno == WSAEINPROGRESS)
306 #else /* ifndef _WIN32 */
307 if (errno == EINPROGRESS)
308 #endif /* ndef _WIN32 || __OS2__ */
325 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
329 fcntl(fd, F_SETFL, flags);
331 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
333 /* wait for connection to complete */
337 memset(&timeout, 0, sizeof(timeout));
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))
344 socklen_t optlen = sizeof(socket_error);
345 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
349 /* Connection established, no need to try other addresses. */
352 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
353 csp->http->host_ip_addr_str, service, strerror(socket_error));
357 socket_error = errno;
358 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
359 "the connection to [%s]:%s: %s; dropping connection.",
360 csp->http->host_ip_addr_str, service, strerror(errno));
364 /* Connection failed, try next address */
368 freeaddrinfo(result);
371 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
372 host, service, strerror(socket_error));
373 csp->error_message = strdup(strerror(socket_error));
374 return(JB_INVALID_SOCKET);
376 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
377 host, csp->http->host_ip_addr_str, service);
383 #else /* ndef HAVE_RFC2553 */
384 /* Pre-getaddrinfo implementation */
386 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
388 struct sockaddr_in inaddr;
392 struct timeval tv[1];
393 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
398 struct access_control_addr dst[1];
399 #endif /* def FEATURE_ACL */
401 /* Don't leak memory when retrying. */
402 freez(csp->http->host_ip_addr_str);
404 memset((char *)&inaddr, 0, sizeof inaddr);
406 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
408 csp->http->host_ip_addr_str = strdup("unknown");
409 return(JB_INVALID_SOCKET);
413 dst->addr = ntohl(addr);
416 if (block_acl(dst, csp))
423 return(JB_INVALID_SOCKET);
425 #endif /* def FEATURE_ACL */
427 inaddr.sin_addr.s_addr = addr;
428 inaddr.sin_family = AF_INET;
429 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
432 if (sizeof(inaddr.sin_port) == sizeof(short))
433 #endif /* ndef _WIN32 */
435 inaddr.sin_port = htons((unsigned short) portnum);
440 inaddr.sin_port = htonl((unsigned long)portnum);
442 #endif /* ndef _WIN32 */
444 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
446 if (fd == JB_INVALID_SOCKET)
451 return(JB_INVALID_SOCKET);
455 { /* turn off TCP coalescence */
457 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
459 #endif /* def TCP_NODELAY */
461 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
462 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
465 fcntl(fd, F_SETFL, flags);
467 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
469 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
472 if (errno == WSAEINPROGRESS)
474 if (sock_errno() == EINPROGRESS)
475 #else /* ifndef _WIN32 */
476 if (errno == EINPROGRESS)
477 #endif /* ndef _WIN32 || __OS2__ */
483 if (sock_errno() != EINTR)
489 return(JB_INVALID_SOCKET);
493 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
497 fcntl(fd, F_SETFL, flags);
499 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
501 /* wait for connection to complete */
508 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
509 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
512 return(JB_INVALID_SOCKET);
517 #endif /* ndef HAVE_RFC2553 */
520 /*********************************************************************
522 * Function : write_socket
524 * Description : Write the contents of buf (for n bytes) to socket fd.
527 * 1 : fd = file descriptor (aka. handle) of socket to write to.
528 * 2 : buf = pointer to data to be written.
529 * 3 : len = length of data to be written to the socket "fd".
531 * Returns : 0 on success (entire buffer sent).
534 *********************************************************************/
536 int write_socket(jb_socket fd, const char *buf, ssize_t len)
538 int write_socket(jb_socket fd, const char *buf, size_t len)
546 if (len < 0) /* constant condition - size_t isn't ever negative */
551 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
554 return (send(fd, buf, (int)len, 0) != (int)len);
555 #elif defined(__BEOS__) || defined(AMIGA)
556 return (send(fd, buf, len, 0) != len);
557 #elif defined(__OS2__)
559 * Break the data up into SOCKET_SEND_MAX chunks for sending...
560 * OS/2 seemed to complain when the chunks were too large.
562 #define SOCKET_SEND_MAX 65000
564 int send_len, send_rc = 0, i = 0;
565 while ((i < len) && (send_rc != -1))
567 if ((i + SOCKET_SEND_MAX) > len)
570 send_len = SOCKET_SEND_MAX;
571 send_rc = send(fd,(char*)buf + i, send_len, 0);
579 return (write(fd, buf, len) != len);
585 /*********************************************************************
587 * Function : read_socket
589 * Description : Read from a TCP/IP socket in a platform independent way.
592 * 1 : fd = file descriptor of the socket to read
593 * 2 : buf = pointer to buffer where data will be written
594 * Must be >= len bytes long.
595 * 3 : len = maximum number of bytes to read
597 * Returns : On success, the number of bytes read is returned (zero
598 * indicates end of file), and the file position is advanced
599 * by this number. It is not an error if this number is
600 * smaller than the number of bytes requested; this may hap-
601 * pen for example because fewer bytes are actually available
602 * right now (maybe because we were close to end-of-file, or
603 * because we are reading from a pipe, or from a terminal,
604 * or because read() was interrupted by a signal). On error,
605 * -1 is returned, and errno is set appropriately. In this
606 * case it is left unspecified whether the file position (if
609 *********************************************************************/
610 int read_socket(jb_socket fd, char *buf, int len)
620 ret = recv(fd, buf, len, 0);
621 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
622 ret = recv(fd, buf, (size_t)len, 0);
624 ret = (int)read(fd, buf, (size_t)len);
629 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
636 /*********************************************************************
638 * Function : data_is_available
640 * Description : Waits for data to arrive on a socket.
643 * 1 : fd = file descriptor of the socket to read
644 * 2 : seconds_to_wait = number of seconds after which we give up.
646 * Returns : TRUE if data arrived in time,
649 *********************************************************************/
650 int data_is_available(jb_socket fd, int seconds_to_wait)
654 struct timeval timeout;
657 memset(&timeout, 0, sizeof(timeout));
658 timeout.tv_sec = seconds_to_wait;
661 /* Copy and pasted from jcc.c ... */
662 memset(&rfds, 0, sizeof(fd_set));
668 n = select(fd+1, &rfds, NULL, NULL, &timeout);
671 * XXX: Do we care about the different error conditions?
673 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
677 /*********************************************************************
679 * Function : close_socket
681 * Description : Closes a TCP/IP socket
684 * 1 : fd = file descriptor of socket to be closed
688 *********************************************************************/
689 void close_socket(jb_socket fd)
691 #if defined(_WIN32) || defined(__BEOS__)
695 #elif defined(__OS2__)
704 /*********************************************************************
706 * Function : bind_port
708 * Description : Call socket, set socket options, and listen.
709 * Called by listen_loop to "boot up" our proxy address.
712 * 1 : hostnam = TCP/IP address to bind/listen to
713 * 2 : portnum = port to listen on
714 * 3 : pfd = pointer used to return file descriptor.
716 * Returns : if success, returns 0 and sets *pfd.
717 * if failure, returns -3 if address is in use,
718 * -2 if address unresolvable,
720 *********************************************************************/
721 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
724 struct addrinfo hints;
725 struct addrinfo *result, *rp;
727 * XXX: portnum should be a string to allow symbolic service
728 * names in the configuration file and to avoid the following
734 struct sockaddr_in inaddr;
735 #endif /* def HAVE_RFC2553 */
739 #endif /* ndef _WIN32 */
741 *pfd = JB_INVALID_SOCKET;
744 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
745 if ((-1 == retval) || (sizeof(servnam) <= retval))
747 log_error(LOG_LEVEL_ERROR,
748 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
753 memset(&hints, 0, sizeof(struct addrinfo));
757 * XXX: This is a hack. The right thing to do
758 * would be to bind to both AF_INET and AF_INET6.
759 * This will also fail if there is no AF_INET
762 hints.ai_family = AF_INET;
766 hints.ai_family = AF_UNSPEC;
768 hints.ai_socktype = SOCK_STREAM;
769 hints.ai_flags = AI_PASSIVE;
771 hints.ai_flags |= AI_ADDRCONFIG;
773 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
774 hints.ai_canonname = NULL;
775 hints.ai_addr = NULL;
776 hints.ai_next = NULL;
778 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
780 log_error(LOG_LEVEL_ERROR,
781 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
785 memset((char *)&inaddr, '\0', sizeof inaddr);
787 inaddr.sin_family = AF_INET;
788 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
790 if (inaddr.sin_addr.s_addr == INADDR_NONE)
796 if (sizeof(inaddr.sin_port) == sizeof(short))
797 #endif /* ndef _WIN32 */
799 inaddr.sin_port = htons((unsigned short) portnum);
804 inaddr.sin_port = htonl((unsigned long) portnum);
806 #endif /* ndef _WIN32 */
807 #endif /* def HAVE_RFC2553 */
810 for (rp = result; rp != NULL; rp = rp->ai_next)
812 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
814 fd = socket(AF_INET, SOCK_STREAM, 0);
815 #endif /* def HAVE_RFC2553 */
818 if (fd == JB_INVALID_SOCKET)
832 * This is not needed for Win32 - in fact, it stops
833 * duplicate instances of Privoxy from being caught.
835 * On UNIX, we assume the user is sensible enough not
836 * to start Privoxy multiple times on the same IP.
837 * Without this, stopping and restarting Privoxy
838 * from a script fails.
839 * Note: SO_REUSEADDR is meant to only take over
840 * sockets which are *not* in listen state in Linux,
841 * e.g. sockets in TIME_WAIT. YMMV.
843 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
844 #endif /* ndef _WIN32 */
847 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
849 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
853 errno = WSAGetLastError();
854 if (errno == WSAEADDRINUSE)
856 if (errno == EADDRINUSE)
860 freeaddrinfo(result);
877 /* bind() succeeded, escape from for-loop */
879 * XXX: Support multiple listening sockets (e.g. localhost
880 * resolves to AF_INET and AF_INET6, but only the first address
887 freeaddrinfo(result);
890 /* All bind()s failed */
893 #endif /* ndef HAVE_RFC2553 */
895 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
909 /*********************************************************************
911 * Function : get_host_information
913 * Description : Determines the IP address the client used to
914 * reach us and the hostname associated with it.
916 * XXX: Most of the code has been copy and pasted
917 * from accept_connection() and not all of the
918 * ifdefs paths have been tested afterwards.
921 * 1 : afd = File descriptor returned from accept().
922 * 2 : ip_address = Pointer to return the pointer to
923 * the ip address string.
924 * 3 : hostname = Pointer to return the pointer to
925 * the hostname or NULL if the caller
926 * isn't interested in it.
930 *********************************************************************/
931 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
934 struct sockaddr_storage server;
937 struct sockaddr_in server;
938 struct hostent *host = NULL;
939 #endif /* HAVE_RFC2553 */
940 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
941 /* according to accept_connection() this fixes a warning. */
942 int s_length, s_length_provided;
944 socklen_t s_length, s_length_provided;
947 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
948 struct hostent result;
949 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
950 struct hostent_data hdata;
952 char hbuf[HOSTENT_BUFFER_SIZE];
954 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
955 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
956 #endif /* ifndef HAVE_RFC2553 */
957 s_length = s_length_provided = sizeof(server);
959 if (NULL != hostname)
965 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
967 if (s_length > s_length_provided)
969 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
973 *ip_address = malloc(NI_MAXHOST);
974 if (NULL == *ip_address)
976 log_error(LOG_LEVEL_ERROR,
977 "Out of memory while getting the client's IP address.");
980 retval = getnameinfo((struct sockaddr *) &server, s_length,
981 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
984 log_error(LOG_LEVEL_ERROR,
985 "Unable to print my own IP address: %s", gai_strerror(retval));
990 *ip_address = strdup(inet_ntoa(server.sin_addr));
991 #endif /* HAVE_RFC2553 */
992 if (NULL == hostname)
995 * We're done here, the caller isn't
996 * interested in knowing the hostname.
1002 *hostname = malloc(NI_MAXHOST);
1003 if (NULL == *hostname)
1005 log_error(LOG_LEVEL_ERROR,
1006 "Out of memory while getting the client's hostname.");
1009 retval = getnameinfo((struct sockaddr *) &server, s_length,
1010 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1013 log_error(LOG_LEVEL_ERROR,
1014 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1018 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1019 gethostbyaddr_r((const char *)&server.sin_addr,
1020 sizeof(server.sin_addr), AF_INET,
1021 &result, hbuf, HOSTENT_BUFFER_SIZE,
1023 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1024 host = gethostbyaddr_r((const char *)&server.sin_addr,
1025 sizeof(server.sin_addr), AF_INET,
1026 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1027 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1028 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1029 sizeof(server.sin_addr), AF_INET,
1038 #elif defined(MUTEX_LOCKS_AVAILABLE)
1039 privoxy_mutex_lock(&resolver_mutex);
1040 host = gethostbyaddr((const char *)&server.sin_addr,
1041 sizeof(server.sin_addr), AF_INET);
1042 privoxy_mutex_unlock(&resolver_mutex);
1044 host = gethostbyaddr((const char *)&server.sin_addr,
1045 sizeof(server.sin_addr), AF_INET);
1049 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1053 *hostname = strdup(host->h_name);
1055 #endif /* else def HAVE_RFC2553 */
1062 /*********************************************************************
1064 * Function : accept_connection
1066 * Description : Accepts a connection on a socket. Socket must have
1067 * been created using bind_port().
1070 * 1 : csp = Client state, cfd, ip_addr_str, and
1071 * ip_addr_long will be set by this routine.
1072 * 2 : fd = file descriptor returned from bind_port
1074 * Returns : when a connection is accepted, it returns 1 (TRUE).
1075 * On an error it returns 0 (FALSE).
1077 *********************************************************************/
1078 int accept_connection(struct client_state * csp, jb_socket fd)
1081 /* XXX: client is stored directly into csp->tcp_addr */
1082 #define client (csp->tcp_addr)
1085 struct sockaddr_in client;
1088 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1089 /* Wierdness - fix a warning. */
1095 c_length = sizeof(client);
1098 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1099 if (afd == JB_INVALID_SOCKET)
1106 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1107 struct accept_filter_arg af_options;
1108 bzero(&af_options, sizeof(af_options));
1109 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1110 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1112 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1113 } while (afd < 1 && errno == EINTR);
1122 csp->ip_addr_str = malloc(NI_MAXHOST);
1123 if (NULL == csp->ip_addr_str)
1125 log_error(LOG_LEVEL_ERROR,
1126 "Out of memory while getting the client's IP address.");
1129 retval = getnameinfo((struct sockaddr *) &client, c_length,
1130 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1131 if (!csp->ip_addr_str || retval)
1133 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1134 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1135 freez(csp->ip_addr_str);
1139 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1140 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1141 #endif /* def HAVE_RFC2553 */
1148 /*********************************************************************
1150 * Function : resolve_hostname_to_ip
1152 * Description : Resolve a hostname to an internet tcp/ip address.
1153 * NULL or an empty string resolve to INADDR_ANY.
1156 * 1 : host = hostname to resolve
1158 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1160 *********************************************************************/
1161 unsigned long resolve_hostname_to_ip(const char *host)
1163 struct sockaddr_in inaddr;
1164 struct hostent *hostp;
1165 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1166 struct hostent result;
1167 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1168 char hbuf[HOSTENT_BUFFER_SIZE];
1170 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1171 struct hostent_data hdata;
1172 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1173 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1175 if ((host == NULL) || (*host == '\0'))
1180 memset((char *) &inaddr, 0, sizeof inaddr);
1182 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1184 unsigned int dns_retries = 0;
1185 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1186 while (gethostbyname_r(host, &result, hbuf,
1187 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1188 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1190 log_error(LOG_LEVEL_ERROR,
1191 "Timeout #%u while trying to resolve %s. Trying again.",
1194 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1195 while (NULL == (hostp = gethostbyname_r(host, &result,
1196 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1197 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1199 log_error(LOG_LEVEL_ERROR,
1200 "Timeout #%u while trying to resolve %s. Trying again.",
1203 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1205 * XXX: Doesn't retry in case of soft errors.
1206 * Does this gethostbyname_r version set h_errno?
1208 if (0 == gethostbyname_r(host, &result, &hdata))
1216 #elif defined(MUTEX_LOCKS_AVAILABLE)
1217 privoxy_mutex_lock(&resolver_mutex);
1218 while (NULL == (hostp = gethostbyname(host))
1219 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1221 log_error(LOG_LEVEL_ERROR,
1222 "Timeout #%u while trying to resolve %s. Trying again.",
1225 privoxy_mutex_unlock(&resolver_mutex);
1227 while (NULL == (hostp = gethostbyname(host))
1228 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1230 log_error(LOG_LEVEL_ERROR,
1231 "Timeout #%u while trying to resolve %s. Trying again.",
1234 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1236 * On Mac OSX, if a domain exists but doesn't have a type A
1237 * record associated with it, the h_addr member of the struct
1238 * hostent returned by gethostbyname is NULL, even if h_length
1239 * is 4. Therefore the second test below.
1241 if (hostp == NULL || hostp->h_addr == NULL)
1244 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1245 return(INADDR_NONE);
1247 if (hostp->h_addrtype != AF_INET)
1250 errno = WSAEPROTOTYPE;
1254 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1255 return(INADDR_NONE);
1258 (char *) &inaddr.sin_addr,
1259 (char *) hostp->h_addr,
1260 sizeof(inaddr.sin_addr)
1263 return(inaddr.sin_addr.s_addr);
1268 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1269 /*********************************************************************
1271 * Function : socket_is_still_alive
1273 * Description : Figures out whether or not a socket is still alive.
1276 * 1 : sfd = The socket to check.
1278 * Returns : TRUE for yes, otherwise FALSE.
1280 *********************************************************************/
1281 int socket_is_still_alive(jb_socket sfd)
1284 int no_data_waiting;
1288 struct pollfd poll_fd[1];
1290 memset(poll_fd, 0, sizeof(poll_fd));
1291 poll_fd[0].fd = sfd;
1292 poll_fd[0].events = POLLIN;
1294 poll_result = poll(poll_fd, 1, 0);
1296 if (-1 == poll_result)
1298 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1301 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1303 fd_set readable_fds;
1304 struct timeval timeout;
1307 memset(&timeout, '\0', sizeof(timeout));
1308 FD_ZERO(&readable_fds);
1309 FD_SET(sfd, &readable_fds);
1311 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1314 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1317 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1318 #endif /* def HAVE_POLL */
1320 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1322 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */