1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.73 2010/04/23 11:53:48 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 /* 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 /*********************************************************************
124 * Function : connect_to
126 * Description : Open a socket and connect to it. Will check
127 * that this is allowed according to ACL.
130 * 1 : host = hostname to connect to
131 * 2 : portnum = port to connent on (XXX: should be unsigned)
132 * 3 : csp = Current client state (buffers, headers, etc...)
133 * Not modified, only used for source IP and ACL.
135 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
138 *********************************************************************/
140 /* Getaddrinfo implementation */
141 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
143 struct addrinfo hints, *result, *rp;
148 struct timeval tv[1];
149 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
155 struct access_control_addr dst[1];
156 #endif /* def FEATURE_ACL */
158 retval = snprintf(service, sizeof(service), "%d", portnum);
159 if ((-1 == retval) || (sizeof(service) <= retval))
161 log_error(LOG_LEVEL_ERROR,
162 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
164 csp->http->host_ip_addr_str = strdup("unknown");
165 return(JB_INVALID_SOCKET);
168 memset((char *)&hints, 0, sizeof(hints));
169 hints.ai_family = AF_UNSPEC;
170 hints.ai_socktype = SOCK_STREAM;
171 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
173 hints.ai_flags |= AI_ADDRCONFIG;
175 if ((retval = getaddrinfo(host, service, &hints, &result)))
177 log_error(LOG_LEVEL_INFO,
178 "Can not resolve %s: %s", host, gai_strerror(retval));
179 /* XXX: Should find a better way to propagate this error. */
181 csp->http->host_ip_addr_str = strdup("unknown");
182 return(JB_INVALID_SOCKET);
185 for (rp = result; rp != NULL; rp = rp->ai_next)
189 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
191 if (block_acl(dst, csp))
200 #endif /* def FEATURE_ACL */
202 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
203 if (NULL == csp->http->host_ip_addr_str)
205 log_error(LOG_LEVEL_ERROR,
206 "Out of memory while getting the server IP address.");
207 return JB_INVALID_SOCKET;
209 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
210 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
211 if (!csp->http->host_ip_addr_str || retval)
213 log_error(LOG_LEVEL_ERROR,
214 "Can not save csp->http->host_ip_addr_str: %s",
215 (csp->http->host_ip_addr_str) ?
216 gai_strerror(retval) : "Insufficient memory");
217 freez(csp->http->host_ip_addr_str);
222 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
225 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
232 { /* turn off TCP coalescence */
234 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
236 #endif /* def TCP_NODELAY */
238 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
239 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
242 fcntl(fd, F_SETFL, flags);
244 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
247 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
250 if (errno == WSAEINPROGRESS)
252 if (sock_errno() == EINPROGRESS)
253 #else /* ifndef _WIN32 */
254 if (errno == EINPROGRESS)
255 #endif /* ndef _WIN32 || __OS2__ */
261 if (sock_errno() != EINTR)
276 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
280 fcntl(fd, F_SETFL, flags);
282 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
284 /* wait for connection to complete */
291 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
292 if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
293 && FD_ISSET(fd, &wfds))
296 * See Linux connect(2) man page for more info
297 * about connecting on non-blocking socket.
300 socklen_t optlen = sizeof(socket_in_error);
301 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
303 if (!socket_in_error)
305 /* Connection established, no need to try other addresses. */
308 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
309 csp->http->host_ip_addr_str, service, strerror(socket_in_error));
313 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
314 "the connection to [%s]:%s: %s; dropping connection.",
315 csp->http->host_ip_addr_str, service, strerror(errno));
319 /* Connection failed, try next address */
323 freeaddrinfo(result);
326 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s.",
328 return(JB_INVALID_SOCKET);
330 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
331 host, csp->http->host_ip_addr_str, service);
337 #else /* ndef HAVE_RFC2553 */
338 /* Pre-getaddrinfo implementation */
340 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
342 struct sockaddr_in inaddr;
346 struct timeval tv[1];
347 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
352 struct access_control_addr dst[1];
353 #endif /* def FEATURE_ACL */
355 memset((char *)&inaddr, 0, sizeof inaddr);
357 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
359 csp->http->host_ip_addr_str = strdup("unknown");
360 return(JB_INVALID_SOCKET);
364 dst->addr = ntohl(addr);
367 if (block_acl(dst, csp))
374 return(JB_INVALID_SOCKET);
376 #endif /* def FEATURE_ACL */
378 inaddr.sin_addr.s_addr = addr;
379 inaddr.sin_family = AF_INET;
380 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
383 if (sizeof(inaddr.sin_port) == sizeof(short))
384 #endif /* ndef _WIN32 */
386 inaddr.sin_port = htons((unsigned short) portnum);
391 inaddr.sin_port = htonl((unsigned long)portnum);
393 #endif /* ndef _WIN32 */
396 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
398 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
401 return(JB_INVALID_SOCKET);
405 { /* turn off TCP coalescence */
407 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
409 #endif /* def TCP_NODELAY */
411 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
412 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
415 fcntl(fd, F_SETFL, flags);
417 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
419 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
422 if (errno == WSAEINPROGRESS)
424 if (sock_errno() == EINPROGRESS)
425 #else /* ifndef _WIN32 */
426 if (errno == EINPROGRESS)
427 #endif /* ndef _WIN32 || __OS2__ */
433 if (sock_errno() != EINTR)
439 return(JB_INVALID_SOCKET);
443 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
447 fcntl(fd, F_SETFL, flags);
449 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
451 /* wait for connection to complete */
458 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
459 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
462 return(JB_INVALID_SOCKET);
467 #endif /* ndef HAVE_RFC2553 */
470 /*********************************************************************
472 * Function : write_socket
474 * Description : Write the contents of buf (for n bytes) to socket fd.
477 * 1 : fd = file descriptor (aka. handle) of socket to write to.
478 * 2 : buf = pointer to data to be written.
479 * 3 : len = length of data to be written to the socket "fd".
481 * Returns : 0 on success (entire buffer sent).
484 *********************************************************************/
486 int write_socket(jb_socket fd, const char *buf, ssize_t len)
488 int write_socket(jb_socket fd, const char *buf, size_t len)
496 if (len < 0) /* constant condition - size_t isn't ever negative */
501 log_error(LOG_LEVEL_LOG, "%N", len, buf);
504 return (send(fd, buf, (int)len, 0) != (int)len);
505 #elif defined(__BEOS__) || defined(AMIGA)
506 return (send(fd, buf, len, 0) != len);
507 #elif defined(__OS2__)
509 * Break the data up into SOCKET_SEND_MAX chunks for sending...
510 * OS/2 seemed to complain when the chunks were too large.
512 #define SOCKET_SEND_MAX 65000
514 int write_len = 0, send_len, send_rc = 0, i = 0;
515 while ((i < len) && (send_rc != -1))
517 if ((i + SOCKET_SEND_MAX) > len)
520 send_len = SOCKET_SEND_MAX;
521 send_rc = send(fd,(char*)buf + i, send_len, 0);
529 return (write(fd, buf, len) != len);
535 /*********************************************************************
537 * Function : read_socket
539 * Description : Read from a TCP/IP socket in a platform independent way.
542 * 1 : fd = file descriptor of the socket to read
543 * 2 : buf = pointer to buffer where data will be written
544 * Must be >= len bytes long.
545 * 3 : len = maximum number of bytes to read
547 * Returns : On success, the number of bytes read is returned (zero
548 * indicates end of file), and the file position is advanced
549 * by this number. It is not an error if this number is
550 * smaller than the number of bytes requested; this may hap-
551 * pen for example because fewer bytes are actually available
552 * right now (maybe because we were close to end-of-file, or
553 * because we are reading from a pipe, or from a terminal,
554 * or because read() was interrupted by a signal). On error,
555 * -1 is returned, and errno is set appropriately. In this
556 * case it is left unspecified whether the file position (if
559 *********************************************************************/
560 int read_socket(jb_socket fd, char *buf, int len)
568 return(recv(fd, buf, len, 0));
569 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
570 return(recv(fd, buf, (size_t)len, 0));
572 return((int)read(fd, buf, (size_t)len));
577 /*********************************************************************
579 * Function : data_is_available
581 * Description : Waits for data to arrive on a socket.
584 * 1 : fd = file descriptor of the socket to read
585 * 2 : seconds_to_wait = number of seconds after which we give up.
587 * Returns : TRUE if data arrived in time,
590 *********************************************************************/
591 int data_is_available(jb_socket fd, int seconds_to_wait)
595 struct timeval timeout;
598 memset(&timeout, 0, sizeof(timeout));
599 timeout.tv_sec = seconds_to_wait;
602 /* Copy and pasted from jcc.c ... */
603 memset(&rfds, 0, sizeof(fd_set));
609 n = select(fd+1, &rfds, NULL, NULL, &timeout);
612 * XXX: Do we care about the different error conditions?
614 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
618 /*********************************************************************
620 * Function : close_socket
622 * Description : Closes a TCP/IP socket
625 * 1 : fd = file descriptor of socket to be closed
629 *********************************************************************/
630 void close_socket(jb_socket fd)
632 #if defined(_WIN32) || defined(__BEOS__)
636 #elif defined(__OS2__)
645 /*********************************************************************
647 * Function : bind_port
649 * Description : Call socket, set socket options, and listen.
650 * Called by listen_loop to "boot up" our proxy address.
653 * 1 : hostnam = TCP/IP address to bind/listen to
654 * 2 : portnum = port to listen on
655 * 3 : pfd = pointer used to return file descriptor.
657 * Returns : if success, returns 0 and sets *pfd.
658 * if failure, returns -3 if address is in use,
659 * -2 if address unresolvable,
661 *********************************************************************/
662 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
665 struct addrinfo hints;
666 struct addrinfo *result, *rp;
668 * XXX: portnum should be a string to allow symbolic service
669 * names in the configuration file and to avoid the following
675 struct sockaddr_in inaddr;
676 #endif /* def HAVE_RFC2553 */
680 #endif /* ndef _WIN32 */
682 *pfd = JB_INVALID_SOCKET;
685 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
686 if ((-1 == retval) || (sizeof(servnam) <= retval))
688 log_error(LOG_LEVEL_ERROR,
689 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
694 memset(&hints, 0, sizeof(struct addrinfo));
698 * XXX: This is a hack. The right thing to do
699 * would be to bind to both AF_INET and AF_INET6.
700 * This will also fail if there is no AF_INET
703 hints.ai_family = AF_INET;
707 hints.ai_family = AF_UNSPEC;
709 hints.ai_socktype = SOCK_STREAM;
710 hints.ai_flags = AI_PASSIVE;
712 hints.ai_flags |= AI_ADDRCONFIG;
714 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
715 hints.ai_canonname = NULL;
716 hints.ai_addr = NULL;
717 hints.ai_next = NULL;
719 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
721 log_error(LOG_LEVEL_ERROR,
722 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
726 memset((char *)&inaddr, '\0', sizeof inaddr);
728 inaddr.sin_family = AF_INET;
729 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
731 if (inaddr.sin_addr.s_addr == INADDR_NONE)
737 if (sizeof(inaddr.sin_port) == sizeof(short))
738 #endif /* ndef _WIN32 */
740 inaddr.sin_port = htons((unsigned short) portnum);
745 inaddr.sin_port = htonl((unsigned long) portnum);
747 #endif /* ndef _WIN32 */
748 #endif /* def HAVE_RFC2553 */
751 for (rp = result; rp != NULL; rp = rp->ai_next)
753 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
755 fd = socket(AF_INET, SOCK_STREAM, 0);
756 #endif /* def HAVE_RFC2553 */
759 if (fd == JB_INVALID_SOCKET)
773 * This is not needed for Win32 - in fact, it stops
774 * duplicate instances of Privoxy from being caught.
776 * On UNIX, we assume the user is sensible enough not
777 * to start Privoxy multiple times on the same IP.
778 * Without this, stopping and restarting Privoxy
779 * from a script fails.
780 * Note: SO_REUSEADDR is meant to only take over
781 * sockets which are *not* in listen state in Linux,
782 * e.g. sockets in TIME_WAIT. YMMV.
784 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
785 #endif /* ndef _WIN32 */
788 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
790 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
794 errno = WSAGetLastError();
795 if (errno == WSAEADDRINUSE)
797 if (errno == EADDRINUSE)
801 freeaddrinfo(result);
818 /* bind() succeeded, escape from for-loop */
820 * XXX: Support multiple listening sockets (e.g. localhost
821 * resolves to AF_INET and AF_INET6, but only the first address
828 freeaddrinfo(result);
831 /* All bind()s failed */
834 #endif /* ndef HAVE_RFC2553 */
836 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
850 /*********************************************************************
852 * Function : get_host_information
854 * Description : Determines the IP address the client used to
855 * reach us and the hostname associated with it.
857 * XXX: Most of the code has been copy and pasted
858 * from accept_connection() and not all of the
859 * ifdefs paths have been tested afterwards.
862 * 1 : afd = File descriptor returned from accept().
863 * 2 : ip_address = Pointer to return the pointer to
864 * the ip address string.
865 * 3 : hostname = Pointer to return the pointer to
866 * the hostname or NULL if the caller
867 * isn't interested in it.
871 *********************************************************************/
872 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
875 struct sockaddr_storage server;
878 struct sockaddr_in server;
879 struct hostent *host = NULL;
880 #endif /* HAVE_RFC2553 */
881 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
882 /* according to accept_connection() this fixes a warning. */
883 int s_length, s_length_provided;
885 socklen_t s_length, s_length_provided;
888 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
889 struct hostent result;
890 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
891 struct hostent_data hdata;
893 char hbuf[HOSTENT_BUFFER_SIZE];
895 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
896 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
897 #endif /* ifndef HAVE_RFC2553 */
898 s_length = s_length_provided = sizeof(server);
900 if (NULL != hostname)
906 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
908 if (s_length > s_length_provided)
910 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
914 *ip_address = malloc(NI_MAXHOST);
915 if (NULL == *ip_address)
917 log_error(LOG_LEVEL_ERROR,
918 "Out of memory while getting the client's IP address.");
921 retval = getnameinfo((struct sockaddr *) &server, s_length,
922 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
925 log_error(LOG_LEVEL_ERROR,
926 "Unable to print my own IP address: %s", gai_strerror(retval));
931 *ip_address = strdup(inet_ntoa(server.sin_addr));
932 #endif /* HAVE_RFC2553 */
933 if (NULL == hostname)
936 * We're done here, the caller isn't
937 * interested in knowing the hostname.
943 *hostname = malloc(NI_MAXHOST);
944 if (NULL == *hostname)
946 log_error(LOG_LEVEL_ERROR,
947 "Out of memory while getting the client's hostname.");
950 retval = getnameinfo((struct sockaddr *) &server, s_length,
951 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
954 log_error(LOG_LEVEL_ERROR,
955 "Unable to resolve my own IP address: %s", gai_strerror(retval));
959 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
960 gethostbyaddr_r((const char *)&server.sin_addr,
961 sizeof(server.sin_addr), AF_INET,
962 &result, hbuf, HOSTENT_BUFFER_SIZE,
964 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
965 host = gethostbyaddr_r((const char *)&server.sin_addr,
966 sizeof(server.sin_addr), AF_INET,
967 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
968 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
969 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
970 sizeof(server.sin_addr), AF_INET,
979 #elif defined(MUTEX_LOCKS_AVAILABLE)
980 privoxy_mutex_lock(&resolver_mutex);
981 host = gethostbyaddr((const char *)&server.sin_addr,
982 sizeof(server.sin_addr), AF_INET);
983 privoxy_mutex_unlock(&resolver_mutex);
985 host = gethostbyaddr((const char *)&server.sin_addr,
986 sizeof(server.sin_addr), AF_INET);
990 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
994 *hostname = strdup(host->h_name);
996 #endif /* else def HAVE_RFC2553 */
1003 /*********************************************************************
1005 * Function : accept_connection
1007 * Description : Accepts a connection on a socket. Socket must have
1008 * been created using bind_port().
1011 * 1 : csp = Client state, cfd, ip_addr_str, and
1012 * ip_addr_long will be set by this routine.
1013 * 2 : fd = file descriptor returned from bind_port
1015 * Returns : when a connection is accepted, it returns 1 (TRUE).
1016 * On an error it returns 0 (FALSE).
1018 *********************************************************************/
1019 int accept_connection(struct client_state * csp, jb_socket fd)
1022 /* XXX: client is stored directly into csp->tcp_addr */
1023 #define client (csp->tcp_addr)
1026 struct sockaddr_in client;
1029 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1030 /* Wierdness - fix a warning. */
1036 c_length = sizeof(client);
1039 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1040 if (afd == JB_INVALID_SOCKET)
1047 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1048 struct accept_filter_arg af_options;
1049 bzero(&af_options, sizeof(af_options));
1050 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1051 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1053 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1054 } while (afd < 1 && errno == EINTR);
1063 csp->ip_addr_str = malloc(NI_MAXHOST);
1064 if (NULL == csp->ip_addr_str)
1066 log_error(LOG_LEVEL_ERROR,
1067 "Out of memory while getting the client's IP address.");
1070 retval = getnameinfo((struct sockaddr *) &client, c_length,
1071 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1072 if (!csp->ip_addr_str || retval)
1074 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1075 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1076 freez(csp->ip_addr_str);
1080 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1081 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1082 #endif /* def HAVE_RFC2553 */
1089 /*********************************************************************
1091 * Function : resolve_hostname_to_ip
1093 * Description : Resolve a hostname to an internet tcp/ip address.
1094 * NULL or an empty string resolve to INADDR_ANY.
1097 * 1 : host = hostname to resolve
1099 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1101 *********************************************************************/
1102 unsigned long resolve_hostname_to_ip(const char *host)
1104 struct sockaddr_in inaddr;
1105 struct hostent *hostp;
1106 unsigned int dns_retries = 0;
1107 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1108 struct hostent result;
1109 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1110 char hbuf[HOSTENT_BUFFER_SIZE];
1112 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1113 struct hostent_data hdata;
1114 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1115 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1117 if ((host == NULL) || (*host == '\0'))
1122 memset((char *) &inaddr, 0, sizeof inaddr);
1124 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1126 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1127 while (gethostbyname_r(host, &result, hbuf,
1128 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1129 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1131 log_error(LOG_LEVEL_ERROR,
1132 "Timeout #%u while trying to resolve %s. Trying again.",
1135 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1136 while (NULL == (hostp = gethostbyname_r(host, &result,
1137 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1138 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1140 log_error(LOG_LEVEL_ERROR,
1141 "Timeout #%u while trying to resolve %s. Trying again.",
1144 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1146 * XXX: Doesn't retry in case of soft errors.
1147 * Does this gethostbyname_r version set h_errno?
1149 if (0 == gethostbyname_r(host, &result, &hdata))
1157 #elif defined(MUTEX_LOCKS_AVAILABLE)
1158 privoxy_mutex_lock(&resolver_mutex);
1159 while (NULL == (hostp = gethostbyname(host))
1160 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1162 log_error(LOG_LEVEL_ERROR,
1163 "Timeout #%u while trying to resolve %s. Trying again.",
1166 privoxy_mutex_unlock(&resolver_mutex);
1168 while (NULL == (hostp = gethostbyname(host))
1169 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1171 log_error(LOG_LEVEL_ERROR,
1172 "Timeout #%u while trying to resolve %s. Trying again.",
1175 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1177 * On Mac OSX, if a domain exists but doesn't have a type A
1178 * record associated with it, the h_addr member of the struct
1179 * hostent returned by gethostbyname is NULL, even if h_length
1180 * is 4. Therefore the second test below.
1182 if (hostp == NULL || hostp->h_addr == NULL)
1185 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1186 return(INADDR_NONE);
1188 if (hostp->h_addrtype != AF_INET)
1191 errno = WSAEPROTOTYPE;
1195 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1196 return(INADDR_NONE);
1199 (char *) &inaddr.sin_addr,
1200 (char *) hostp->h_addr,
1201 sizeof(inaddr.sin_addr)
1204 return(inaddr.sin_addr.s_addr);
1209 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1210 /*********************************************************************
1212 * Function : socket_is_still_alive
1214 * Description : Figures out whether or not a socket is still alive.
1217 * 1 : sfd = The socket to check.
1219 * Returns : TRUE for yes, otherwise FALSE.
1221 *********************************************************************/
1222 int socket_is_still_alive(jb_socket sfd)
1225 int no_data_waiting;
1229 struct pollfd poll_fd[1];
1231 memset(poll_fd, 0, sizeof(poll_fd));
1232 poll_fd[0].fd = sfd;
1233 poll_fd[0].events = POLLIN;
1235 poll_result = poll(poll_fd, 1, 0);
1237 if (-1 == poll_result)
1239 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1242 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1244 fd_set readable_fds;
1245 struct timeval timeout;
1248 memset(&timeout, '\0', sizeof(timeout));
1249 FD_ZERO(&readable_fds);
1250 FD_SET(sfd, &readable_fds);
1252 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1255 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1258 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1259 #endif /* def HAVE_POLL */
1261 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1263 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */