1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.94 2011/03/27 14:02:53 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))
164 forwarded_connect_retries++;
165 log_error(LOG_LEVEL_ERROR,
166 "Attempt %d of %d to connect to %s failed. Trying again.",
167 forwarded_connect_retries, csp->config->forwarded_connect_retries, host);
169 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
175 /* Getaddrinfo implementation */
176 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
178 struct addrinfo hints, *result, *rp;
183 struct timeval timeout;
184 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
191 struct access_control_addr dst[1];
192 #endif /* def FEATURE_ACL */
194 /* Don't leak memory when retrying. */
195 freez(csp->error_message);
196 freez(csp->http->host_ip_addr_str);
198 retval = snprintf(service, sizeof(service), "%d", portnum);
199 if ((-1 == retval) || (sizeof(service) <= retval))
201 log_error(LOG_LEVEL_ERROR,
202 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
204 csp->error_message = strdup("Invalid port number");
205 csp->http->host_ip_addr_str = strdup("unknown");
206 return(JB_INVALID_SOCKET);
209 memset((char *)&hints, 0, sizeof(hints));
210 hints.ai_family = AF_UNSPEC;
211 hints.ai_socktype = SOCK_STREAM;
212 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
214 hints.ai_flags |= AI_ADDRCONFIG;
216 if ((retval = getaddrinfo(host, service, &hints, &result)))
218 log_error(LOG_LEVEL_INFO,
219 "Can not resolve %s: %s", host, gai_strerror(retval));
220 /* XXX: Should find a better way to propagate this error. */
222 csp->error_message = strdup(gai_strerror(retval));
223 csp->http->host_ip_addr_str = strdup("unknown");
224 return(JB_INVALID_SOCKET);
227 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
228 if (NULL == csp->http->host_ip_addr_str)
230 log_error(LOG_LEVEL_ERROR,
231 "Out of memory while getting the server IP address.");
232 return JB_INVALID_SOCKET;
235 for (rp = result; rp != NULL; rp = rp->ai_next)
239 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
241 if (block_acl(dst, csp))
244 socket_error = errno = SOCEPERM;
246 socket_error = errno = EPERM;
250 #endif /* def FEATURE_ACL */
252 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
253 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
256 log_error(LOG_LEVEL_ERROR,
257 "Failed to get the host name from the socket structure: %s",
258 gai_strerror(retval));
262 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
264 if (fd == JB_INVALID_SOCKET)
273 { /* turn off TCP coalescence */
275 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
277 #endif /* def TCP_NODELAY */
279 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
280 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
283 fcntl(fd, F_SETFL, flags);
285 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
288 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
291 errno = sock_errno();
295 if (errno == WSAEINPROGRESS)
296 #else /* ifndef _WIN32 */
297 if (errno == EINPROGRESS)
298 #endif /* ndef _WIN32 || __OS2__ */
315 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
319 fcntl(fd, F_SETFL, flags);
321 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
323 /* wait for connection to complete */
327 memset(&timeout, 0, sizeof(timeout));
330 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
331 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
332 && FD_ISSET(fd, &wfds))
334 socklen_t optlen = sizeof(socket_error);
335 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
339 /* Connection established, no need to try other addresses. */
342 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
343 csp->http->host_ip_addr_str, service, strerror(socket_error));
347 socket_error = errno;
348 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
349 "the connection to [%s]:%s: %s; dropping connection.",
350 csp->http->host_ip_addr_str, service, strerror(errno));
354 /* Connection failed, try next address */
358 freeaddrinfo(result);
361 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
362 host, service, strerror(socket_error));
363 csp->error_message = strdup(strerror(socket_error));
364 return(JB_INVALID_SOCKET);
366 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
367 host, csp->http->host_ip_addr_str, service);
373 #else /* ndef HAVE_RFC2553 */
374 /* Pre-getaddrinfo implementation */
376 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
378 struct sockaddr_in inaddr;
382 struct timeval tv[1];
383 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
388 struct access_control_addr dst[1];
389 #endif /* def FEATURE_ACL */
391 /* Don't leak memory when retrying. */
392 freez(csp->http->host_ip_addr_str);
394 memset((char *)&inaddr, 0, sizeof inaddr);
396 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
398 csp->http->host_ip_addr_str = strdup("unknown");
399 return(JB_INVALID_SOCKET);
403 dst->addr = ntohl(addr);
406 if (block_acl(dst, csp))
413 return(JB_INVALID_SOCKET);
415 #endif /* def FEATURE_ACL */
417 inaddr.sin_addr.s_addr = addr;
418 inaddr.sin_family = AF_INET;
419 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
422 if (sizeof(inaddr.sin_port) == sizeof(short))
423 #endif /* ndef _WIN32 */
425 inaddr.sin_port = htons((unsigned short) portnum);
430 inaddr.sin_port = htonl((unsigned long)portnum);
432 #endif /* ndef _WIN32 */
434 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
436 if (fd == JB_INVALID_SOCKET)
441 return(JB_INVALID_SOCKET);
445 { /* turn off TCP coalescence */
447 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
449 #endif /* def TCP_NODELAY */
451 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
452 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
455 fcntl(fd, F_SETFL, flags);
457 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
459 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
462 if (errno == WSAEINPROGRESS)
464 if (sock_errno() == EINPROGRESS)
465 #else /* ifndef _WIN32 */
466 if (errno == EINPROGRESS)
467 #endif /* ndef _WIN32 || __OS2__ */
473 if (sock_errno() != EINTR)
479 return(JB_INVALID_SOCKET);
483 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
487 fcntl(fd, F_SETFL, flags);
489 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
491 /* wait for connection to complete */
498 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
499 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
502 return(JB_INVALID_SOCKET);
507 #endif /* ndef HAVE_RFC2553 */
510 /*********************************************************************
512 * Function : write_socket
514 * Description : Write the contents of buf (for n bytes) to socket fd.
517 * 1 : fd = file descriptor (aka. handle) of socket to write to.
518 * 2 : buf = pointer to data to be written.
519 * 3 : len = length of data to be written to the socket "fd".
521 * Returns : 0 on success (entire buffer sent).
524 *********************************************************************/
526 int write_socket(jb_socket fd, const char *buf, ssize_t len)
528 int write_socket(jb_socket fd, const char *buf, size_t len)
536 if (len < 0) /* constant condition - size_t isn't ever negative */
541 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
544 return (send(fd, buf, (int)len, 0) != (int)len);
545 #elif defined(__BEOS__) || defined(AMIGA)
546 return (send(fd, buf, len, 0) != len);
547 #elif defined(__OS2__)
549 * Break the data up into SOCKET_SEND_MAX chunks for sending...
550 * OS/2 seemed to complain when the chunks were too large.
552 #define SOCKET_SEND_MAX 65000
554 int send_len, send_rc = 0, i = 0;
555 while ((i < len) && (send_rc != -1))
557 if ((i + SOCKET_SEND_MAX) > len)
560 send_len = SOCKET_SEND_MAX;
561 send_rc = send(fd,(char*)buf + i, send_len, 0);
569 return (write(fd, buf, len) != len);
575 /*********************************************************************
577 * Function : read_socket
579 * Description : Read from a TCP/IP socket in a platform independent way.
582 * 1 : fd = file descriptor of the socket to read
583 * 2 : buf = pointer to buffer where data will be written
584 * Must be >= len bytes long.
585 * 3 : len = maximum number of bytes to read
587 * Returns : On success, the number of bytes read is returned (zero
588 * indicates end of file), and the file position is advanced
589 * by this number. It is not an error if this number is
590 * smaller than the number of bytes requested; this may hap-
591 * pen for example because fewer bytes are actually available
592 * right now (maybe because we were close to end-of-file, or
593 * because we are reading from a pipe, or from a terminal,
594 * or because read() was interrupted by a signal). On error,
595 * -1 is returned, and errno is set appropriately. In this
596 * case it is left unspecified whether the file position (if
599 *********************************************************************/
600 int read_socket(jb_socket fd, char *buf, int len)
610 ret = recv(fd, buf, len, 0);
611 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
612 ret = recv(fd, buf, (size_t)len, 0);
614 ret = (int)read(fd, buf, (size_t)len);
619 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
626 /*********************************************************************
628 * Function : data_is_available
630 * Description : Waits for data to arrive on a socket.
633 * 1 : fd = file descriptor of the socket to read
634 * 2 : seconds_to_wait = number of seconds after which we give up.
636 * Returns : TRUE if data arrived in time,
639 *********************************************************************/
640 int data_is_available(jb_socket fd, int seconds_to_wait)
644 struct timeval timeout;
647 memset(&timeout, 0, sizeof(timeout));
648 timeout.tv_sec = seconds_to_wait;
651 /* Copy and pasted from jcc.c ... */
652 memset(&rfds, 0, sizeof(fd_set));
658 n = select(fd+1, &rfds, NULL, NULL, &timeout);
661 * XXX: Do we care about the different error conditions?
663 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
667 /*********************************************************************
669 * Function : close_socket
671 * Description : Closes a TCP/IP socket
674 * 1 : fd = file descriptor of socket to be closed
678 *********************************************************************/
679 void close_socket(jb_socket fd)
681 #if defined(_WIN32) || defined(__BEOS__)
685 #elif defined(__OS2__)
694 /*********************************************************************
696 * Function : bind_port
698 * Description : Call socket, set socket options, and listen.
699 * Called by listen_loop to "boot up" our proxy address.
702 * 1 : hostnam = TCP/IP address to bind/listen to
703 * 2 : portnum = port to listen on
704 * 3 : pfd = pointer used to return file descriptor.
706 * Returns : if success, returns 0 and sets *pfd.
707 * if failure, returns -3 if address is in use,
708 * -2 if address unresolvable,
710 *********************************************************************/
711 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
714 struct addrinfo hints;
715 struct addrinfo *result, *rp;
717 * XXX: portnum should be a string to allow symbolic service
718 * names in the configuration file and to avoid the following
724 struct sockaddr_in inaddr;
725 #endif /* def HAVE_RFC2553 */
729 #endif /* ndef _WIN32 */
731 *pfd = JB_INVALID_SOCKET;
734 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
735 if ((-1 == retval) || (sizeof(servnam) <= retval))
737 log_error(LOG_LEVEL_ERROR,
738 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
743 memset(&hints, 0, sizeof(struct addrinfo));
747 * XXX: This is a hack. The right thing to do
748 * would be to bind to both AF_INET and AF_INET6.
749 * This will also fail if there is no AF_INET
752 hints.ai_family = AF_INET;
756 hints.ai_family = AF_UNSPEC;
758 hints.ai_socktype = SOCK_STREAM;
759 hints.ai_flags = AI_PASSIVE;
761 hints.ai_flags |= AI_ADDRCONFIG;
763 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
764 hints.ai_canonname = NULL;
765 hints.ai_addr = NULL;
766 hints.ai_next = NULL;
768 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
770 log_error(LOG_LEVEL_ERROR,
771 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
775 memset((char *)&inaddr, '\0', sizeof inaddr);
777 inaddr.sin_family = AF_INET;
778 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
780 if (inaddr.sin_addr.s_addr == INADDR_NONE)
786 if (sizeof(inaddr.sin_port) == sizeof(short))
787 #endif /* ndef _WIN32 */
789 inaddr.sin_port = htons((unsigned short) portnum);
794 inaddr.sin_port = htonl((unsigned long) portnum);
796 #endif /* ndef _WIN32 */
797 #endif /* def HAVE_RFC2553 */
800 for (rp = result; rp != NULL; rp = rp->ai_next)
802 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
804 fd = socket(AF_INET, SOCK_STREAM, 0);
805 #endif /* def HAVE_RFC2553 */
808 if (fd == JB_INVALID_SOCKET)
822 * This is not needed for Win32 - in fact, it stops
823 * duplicate instances of Privoxy from being caught.
825 * On UNIX, we assume the user is sensible enough not
826 * to start Privoxy multiple times on the same IP.
827 * Without this, stopping and restarting Privoxy
828 * from a script fails.
829 * Note: SO_REUSEADDR is meant to only take over
830 * sockets which are *not* in listen state in Linux,
831 * e.g. sockets in TIME_WAIT. YMMV.
833 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
834 #endif /* ndef _WIN32 */
837 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
839 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
843 errno = WSAGetLastError();
844 if (errno == WSAEADDRINUSE)
846 if (errno == EADDRINUSE)
850 freeaddrinfo(result);
867 /* bind() succeeded, escape from for-loop */
869 * XXX: Support multiple listening sockets (e.g. localhost
870 * resolves to AF_INET and AF_INET6, but only the first address
877 freeaddrinfo(result);
880 /* All bind()s failed */
883 #endif /* ndef HAVE_RFC2553 */
885 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
899 /*********************************************************************
901 * Function : get_host_information
903 * Description : Determines the IP address the client used to
904 * reach us and the hostname associated with it.
906 * XXX: Most of the code has been copy and pasted
907 * from accept_connection() and not all of the
908 * ifdefs paths have been tested afterwards.
911 * 1 : afd = File descriptor returned from accept().
912 * 2 : ip_address = Pointer to return the pointer to
913 * the ip address string.
914 * 3 : hostname = Pointer to return the pointer to
915 * the hostname or NULL if the caller
916 * isn't interested in it.
920 *********************************************************************/
921 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
924 struct sockaddr_storage server;
927 struct sockaddr_in server;
928 struct hostent *host = NULL;
929 #endif /* HAVE_RFC2553 */
930 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
931 /* according to accept_connection() this fixes a warning. */
932 int s_length, s_length_provided;
934 socklen_t s_length, s_length_provided;
937 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
938 struct hostent result;
939 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
940 struct hostent_data hdata;
942 char hbuf[HOSTENT_BUFFER_SIZE];
944 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
945 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
946 #endif /* ifndef HAVE_RFC2553 */
947 s_length = s_length_provided = sizeof(server);
949 if (NULL != hostname)
955 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
957 if (s_length > s_length_provided)
959 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
963 *ip_address = malloc(NI_MAXHOST);
964 if (NULL == *ip_address)
966 log_error(LOG_LEVEL_ERROR,
967 "Out of memory while getting the client's IP address.");
970 retval = getnameinfo((struct sockaddr *) &server, s_length,
971 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
974 log_error(LOG_LEVEL_ERROR,
975 "Unable to print my own IP address: %s", gai_strerror(retval));
980 *ip_address = strdup(inet_ntoa(server.sin_addr));
981 #endif /* HAVE_RFC2553 */
982 if (NULL == hostname)
985 * We're done here, the caller isn't
986 * interested in knowing the hostname.
992 *hostname = malloc(NI_MAXHOST);
993 if (NULL == *hostname)
995 log_error(LOG_LEVEL_ERROR,
996 "Out of memory while getting the client's hostname.");
999 retval = getnameinfo((struct sockaddr *) &server, s_length,
1000 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1003 log_error(LOG_LEVEL_ERROR,
1004 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1008 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1009 gethostbyaddr_r((const char *)&server.sin_addr,
1010 sizeof(server.sin_addr), AF_INET,
1011 &result, hbuf, HOSTENT_BUFFER_SIZE,
1013 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1014 host = gethostbyaddr_r((const char *)&server.sin_addr,
1015 sizeof(server.sin_addr), AF_INET,
1016 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1017 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1018 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1019 sizeof(server.sin_addr), AF_INET,
1028 #elif defined(MUTEX_LOCKS_AVAILABLE)
1029 privoxy_mutex_lock(&resolver_mutex);
1030 host = gethostbyaddr((const char *)&server.sin_addr,
1031 sizeof(server.sin_addr), AF_INET);
1032 privoxy_mutex_unlock(&resolver_mutex);
1034 host = gethostbyaddr((const char *)&server.sin_addr,
1035 sizeof(server.sin_addr), AF_INET);
1039 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1043 *hostname = strdup(host->h_name);
1045 #endif /* else def HAVE_RFC2553 */
1052 /*********************************************************************
1054 * Function : accept_connection
1056 * Description : Accepts a connection on a socket. Socket must have
1057 * been created using bind_port().
1060 * 1 : csp = Client state, cfd, ip_addr_str, and
1061 * ip_addr_long will be set by this routine.
1062 * 2 : fd = file descriptor returned from bind_port
1064 * Returns : when a connection is accepted, it returns 1 (TRUE).
1065 * On an error it returns 0 (FALSE).
1067 *********************************************************************/
1068 int accept_connection(struct client_state * csp, jb_socket fd)
1071 /* XXX: client is stored directly into csp->tcp_addr */
1072 #define client (csp->tcp_addr)
1075 struct sockaddr_in client;
1078 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1079 /* Wierdness - fix a warning. */
1085 c_length = sizeof(client);
1088 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1089 if (afd == JB_INVALID_SOCKET)
1096 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1097 struct accept_filter_arg af_options;
1098 bzero(&af_options, sizeof(af_options));
1099 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1100 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1102 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1103 } while (afd < 1 && errno == EINTR);
1112 csp->ip_addr_str = malloc(NI_MAXHOST);
1113 if (NULL == csp->ip_addr_str)
1115 log_error(LOG_LEVEL_ERROR,
1116 "Out of memory while getting the client's IP address.");
1119 retval = getnameinfo((struct sockaddr *) &client, c_length,
1120 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1121 if (!csp->ip_addr_str || retval)
1123 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1124 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1125 freez(csp->ip_addr_str);
1129 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1130 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1131 #endif /* def HAVE_RFC2553 */
1138 /*********************************************************************
1140 * Function : resolve_hostname_to_ip
1142 * Description : Resolve a hostname to an internet tcp/ip address.
1143 * NULL or an empty string resolve to INADDR_ANY.
1146 * 1 : host = hostname to resolve
1148 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1150 *********************************************************************/
1151 unsigned long resolve_hostname_to_ip(const char *host)
1153 struct sockaddr_in inaddr;
1154 struct hostent *hostp;
1155 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1156 struct hostent result;
1157 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1158 char hbuf[HOSTENT_BUFFER_SIZE];
1160 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1161 struct hostent_data hdata;
1162 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1163 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1165 if ((host == NULL) || (*host == '\0'))
1170 memset((char *) &inaddr, 0, sizeof inaddr);
1172 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1174 unsigned int dns_retries = 0;
1175 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1176 while (gethostbyname_r(host, &result, hbuf,
1177 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1178 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1180 log_error(LOG_LEVEL_ERROR,
1181 "Timeout #%u while trying to resolve %s. Trying again.",
1184 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1185 while (NULL == (hostp = gethostbyname_r(host, &result,
1186 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1187 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1189 log_error(LOG_LEVEL_ERROR,
1190 "Timeout #%u while trying to resolve %s. Trying again.",
1193 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1195 * XXX: Doesn't retry in case of soft errors.
1196 * Does this gethostbyname_r version set h_errno?
1198 if (0 == gethostbyname_r(host, &result, &hdata))
1206 #elif defined(MUTEX_LOCKS_AVAILABLE)
1207 privoxy_mutex_lock(&resolver_mutex);
1208 while (NULL == (hostp = gethostbyname(host))
1209 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1211 log_error(LOG_LEVEL_ERROR,
1212 "Timeout #%u while trying to resolve %s. Trying again.",
1215 privoxy_mutex_unlock(&resolver_mutex);
1217 while (NULL == (hostp = gethostbyname(host))
1218 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1220 log_error(LOG_LEVEL_ERROR,
1221 "Timeout #%u while trying to resolve %s. Trying again.",
1224 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1226 * On Mac OSX, if a domain exists but doesn't have a type A
1227 * record associated with it, the h_addr member of the struct
1228 * hostent returned by gethostbyname is NULL, even if h_length
1229 * is 4. Therefore the second test below.
1231 if (hostp == NULL || hostp->h_addr == NULL)
1234 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1235 return(INADDR_NONE);
1237 if (hostp->h_addrtype != AF_INET)
1240 errno = WSAEPROTOTYPE;
1244 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1245 return(INADDR_NONE);
1248 (char *) &inaddr.sin_addr,
1249 (char *) hostp->h_addr,
1250 sizeof(inaddr.sin_addr)
1253 return(inaddr.sin_addr.s_addr);
1258 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1259 /*********************************************************************
1261 * Function : socket_is_still_alive
1263 * Description : Figures out whether or not a socket is still alive.
1266 * 1 : sfd = The socket to check.
1268 * Returns : TRUE for yes, otherwise FALSE.
1270 *********************************************************************/
1271 int socket_is_still_alive(jb_socket sfd)
1274 int no_data_waiting;
1278 struct pollfd poll_fd[1];
1280 memset(poll_fd, 0, sizeof(poll_fd));
1281 poll_fd[0].fd = sfd;
1282 poll_fd[0].events = POLLIN;
1284 poll_result = poll(poll_fd, 1, 0);
1286 if (-1 == poll_result)
1288 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1291 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1293 fd_set readable_fds;
1294 struct timeval timeout;
1297 memset(&timeout, '\0', sizeof(timeout));
1298 FD_ZERO(&readable_fds);
1299 FD_SET(sfd, &readable_fds);
1301 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1304 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1307 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1308 #endif /* def HAVE_POLL */
1310 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1312 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */