1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.91 2011/03/27 13:57:28 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 fd = rfc2553_connect_to(host, portnum, csp);
153 fd = no_rfc2553_connect_to(host, portnum, csp);
155 if ((fd != JB_INVALID_SOCKET) || (errno != EINVAL))
159 forwarded_connect_retries++;
160 log_error(LOG_LEVEL_ERROR,
161 "Attempt %d of %d to connect to %s failed. Trying again.",
162 forwarded_connect_retries, csp->config->forwarded_connect_retries, host);
164 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
170 /* Getaddrinfo implementation */
171 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
173 struct addrinfo hints, *result, *rp;
178 struct timeval tv[1];
179 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
186 struct access_control_addr dst[1];
187 #endif /* def FEATURE_ACL */
189 /* Don't leak memory when retrying. */
190 freez(csp->error_message);
191 freez(csp->http->host_ip_addr_str);
193 retval = snprintf(service, sizeof(service), "%d", portnum);
194 if ((-1 == retval) || (sizeof(service) <= retval))
196 log_error(LOG_LEVEL_ERROR,
197 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
199 csp->error_message = strdup("Invalid port number");
200 csp->http->host_ip_addr_str = strdup("unknown");
201 return(JB_INVALID_SOCKET);
204 memset((char *)&hints, 0, sizeof(hints));
205 hints.ai_family = AF_UNSPEC;
206 hints.ai_socktype = SOCK_STREAM;
207 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
209 hints.ai_flags |= AI_ADDRCONFIG;
211 if ((retval = getaddrinfo(host, service, &hints, &result)))
213 log_error(LOG_LEVEL_INFO,
214 "Can not resolve %s: %s", host, gai_strerror(retval));
215 /* XXX: Should find a better way to propagate this error. */
217 csp->error_message = strdup(gai_strerror(retval));
218 csp->http->host_ip_addr_str = strdup("unknown");
219 return(JB_INVALID_SOCKET);
222 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
223 if (NULL == csp->http->host_ip_addr_str)
225 log_error(LOG_LEVEL_ERROR,
226 "Out of memory while getting the server IP address.");
227 return JB_INVALID_SOCKET;
230 for (rp = result; rp != NULL; rp = rp->ai_next)
234 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
236 if (block_acl(dst, csp))
239 socket_error = errno = SOCEPERM;
241 socket_error = errno = EPERM;
245 #endif /* def FEATURE_ACL */
247 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
248 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
251 log_error(LOG_LEVEL_ERROR,
252 "Can not save csp->http->host_ip_addr_str: %s",
253 gai_strerror(retval));
257 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
259 if (fd == JB_INVALID_SOCKET)
268 { /* turn off TCP coalescence */
270 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
272 #endif /* def TCP_NODELAY */
274 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
275 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
278 fcntl(fd, F_SETFL, flags);
280 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
283 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
286 errno = sock_errno();
290 if (errno == WSAEINPROGRESS)
291 #else /* ifndef _WIN32 */
292 if (errno == EINPROGRESS)
293 #endif /* ndef _WIN32 || __OS2__ */
310 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
314 fcntl(fd, F_SETFL, flags);
316 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
318 /* wait for connection to complete */
325 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
326 if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
327 && FD_ISSET(fd, &wfds))
329 socklen_t optlen = sizeof(socket_error);
330 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
334 /* Connection established, no need to try other addresses. */
337 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
338 csp->http->host_ip_addr_str, service, strerror(socket_error));
342 socket_error = errno;
343 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
344 "the connection to [%s]:%s: %s; dropping connection.",
345 csp->http->host_ip_addr_str, service, strerror(errno));
349 /* Connection failed, try next address */
353 freeaddrinfo(result);
356 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
357 host, service, strerror(socket_error));
358 csp->error_message = strdup(strerror(socket_error));
359 return(JB_INVALID_SOCKET);
361 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
362 host, csp->http->host_ip_addr_str, service);
368 #else /* ndef HAVE_RFC2553 */
369 /* Pre-getaddrinfo implementation */
371 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
373 struct sockaddr_in inaddr;
377 struct timeval tv[1];
378 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
383 struct access_control_addr dst[1];
384 #endif /* def FEATURE_ACL */
386 /* Don't leak memory when retrying. */
387 freez(csp->http->host_ip_addr_str);
389 memset((char *)&inaddr, 0, sizeof inaddr);
391 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
393 csp->http->host_ip_addr_str = strdup("unknown");
394 return(JB_INVALID_SOCKET);
398 dst->addr = ntohl(addr);
401 if (block_acl(dst, csp))
408 return(JB_INVALID_SOCKET);
410 #endif /* def FEATURE_ACL */
412 inaddr.sin_addr.s_addr = addr;
413 inaddr.sin_family = AF_INET;
414 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
417 if (sizeof(inaddr.sin_port) == sizeof(short))
418 #endif /* ndef _WIN32 */
420 inaddr.sin_port = htons((unsigned short) portnum);
425 inaddr.sin_port = htonl((unsigned long)portnum);
427 #endif /* ndef _WIN32 */
429 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
431 if (fd == JB_INVALID_SOCKET)
436 return(JB_INVALID_SOCKET);
440 { /* turn off TCP coalescence */
442 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
444 #endif /* def TCP_NODELAY */
446 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
447 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
450 fcntl(fd, F_SETFL, flags);
452 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
454 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
457 if (errno == WSAEINPROGRESS)
459 if (sock_errno() == EINPROGRESS)
460 #else /* ifndef _WIN32 */
461 if (errno == EINPROGRESS)
462 #endif /* ndef _WIN32 || __OS2__ */
468 if (sock_errno() != EINTR)
474 return(JB_INVALID_SOCKET);
478 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
482 fcntl(fd, F_SETFL, flags);
484 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
486 /* wait for connection to complete */
493 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
494 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
497 return(JB_INVALID_SOCKET);
502 #endif /* ndef HAVE_RFC2553 */
505 /*********************************************************************
507 * Function : write_socket
509 * Description : Write the contents of buf (for n bytes) to socket fd.
512 * 1 : fd = file descriptor (aka. handle) of socket to write to.
513 * 2 : buf = pointer to data to be written.
514 * 3 : len = length of data to be written to the socket "fd".
516 * Returns : 0 on success (entire buffer sent).
519 *********************************************************************/
521 int write_socket(jb_socket fd, const char *buf, ssize_t len)
523 int write_socket(jb_socket fd, const char *buf, size_t len)
531 if (len < 0) /* constant condition - size_t isn't ever negative */
536 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
539 return (send(fd, buf, (int)len, 0) != (int)len);
540 #elif defined(__BEOS__) || defined(AMIGA)
541 return (send(fd, buf, len, 0) != len);
542 #elif defined(__OS2__)
544 * Break the data up into SOCKET_SEND_MAX chunks for sending...
545 * OS/2 seemed to complain when the chunks were too large.
547 #define SOCKET_SEND_MAX 65000
549 int send_len, send_rc = 0, i = 0;
550 while ((i < len) && (send_rc != -1))
552 if ((i + SOCKET_SEND_MAX) > len)
555 send_len = SOCKET_SEND_MAX;
556 send_rc = send(fd,(char*)buf + i, send_len, 0);
564 return (write(fd, buf, len) != len);
570 /*********************************************************************
572 * Function : read_socket
574 * Description : Read from a TCP/IP socket in a platform independent way.
577 * 1 : fd = file descriptor of the socket to read
578 * 2 : buf = pointer to buffer where data will be written
579 * Must be >= len bytes long.
580 * 3 : len = maximum number of bytes to read
582 * Returns : On success, the number of bytes read is returned (zero
583 * indicates end of file), and the file position is advanced
584 * by this number. It is not an error if this number is
585 * smaller than the number of bytes requested; this may hap-
586 * pen for example because fewer bytes are actually available
587 * right now (maybe because we were close to end-of-file, or
588 * because we are reading from a pipe, or from a terminal,
589 * or because read() was interrupted by a signal). On error,
590 * -1 is returned, and errno is set appropriately. In this
591 * case it is left unspecified whether the file position (if
594 *********************************************************************/
595 int read_socket(jb_socket fd, char *buf, int len)
605 ret = recv(fd, buf, len, 0);
606 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
607 ret = recv(fd, buf, (size_t)len, 0);
609 ret = (int)read(fd, buf, (size_t)len);
614 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
621 /*********************************************************************
623 * Function : data_is_available
625 * Description : Waits for data to arrive on a socket.
628 * 1 : fd = file descriptor of the socket to read
629 * 2 : seconds_to_wait = number of seconds after which we give up.
631 * Returns : TRUE if data arrived in time,
634 *********************************************************************/
635 int data_is_available(jb_socket fd, int seconds_to_wait)
639 struct timeval timeout;
642 memset(&timeout, 0, sizeof(timeout));
643 timeout.tv_sec = seconds_to_wait;
646 /* Copy and pasted from jcc.c ... */
647 memset(&rfds, 0, sizeof(fd_set));
653 n = select(fd+1, &rfds, NULL, NULL, &timeout);
656 * XXX: Do we care about the different error conditions?
658 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
662 /*********************************************************************
664 * Function : close_socket
666 * Description : Closes a TCP/IP socket
669 * 1 : fd = file descriptor of socket to be closed
673 *********************************************************************/
674 void close_socket(jb_socket fd)
676 #if defined(_WIN32) || defined(__BEOS__)
680 #elif defined(__OS2__)
689 /*********************************************************************
691 * Function : bind_port
693 * Description : Call socket, set socket options, and listen.
694 * Called by listen_loop to "boot up" our proxy address.
697 * 1 : hostnam = TCP/IP address to bind/listen to
698 * 2 : portnum = port to listen on
699 * 3 : pfd = pointer used to return file descriptor.
701 * Returns : if success, returns 0 and sets *pfd.
702 * if failure, returns -3 if address is in use,
703 * -2 if address unresolvable,
705 *********************************************************************/
706 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
709 struct addrinfo hints;
710 struct addrinfo *result, *rp;
712 * XXX: portnum should be a string to allow symbolic service
713 * names in the configuration file and to avoid the following
719 struct sockaddr_in inaddr;
720 #endif /* def HAVE_RFC2553 */
724 #endif /* ndef _WIN32 */
726 *pfd = JB_INVALID_SOCKET;
729 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
730 if ((-1 == retval) || (sizeof(servnam) <= retval))
732 log_error(LOG_LEVEL_ERROR,
733 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
738 memset(&hints, 0, sizeof(struct addrinfo));
742 * XXX: This is a hack. The right thing to do
743 * would be to bind to both AF_INET and AF_INET6.
744 * This will also fail if there is no AF_INET
747 hints.ai_family = AF_INET;
751 hints.ai_family = AF_UNSPEC;
753 hints.ai_socktype = SOCK_STREAM;
754 hints.ai_flags = AI_PASSIVE;
756 hints.ai_flags |= AI_ADDRCONFIG;
758 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
759 hints.ai_canonname = NULL;
760 hints.ai_addr = NULL;
761 hints.ai_next = NULL;
763 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
765 log_error(LOG_LEVEL_ERROR,
766 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
770 memset((char *)&inaddr, '\0', sizeof inaddr);
772 inaddr.sin_family = AF_INET;
773 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
775 if (inaddr.sin_addr.s_addr == INADDR_NONE)
781 if (sizeof(inaddr.sin_port) == sizeof(short))
782 #endif /* ndef _WIN32 */
784 inaddr.sin_port = htons((unsigned short) portnum);
789 inaddr.sin_port = htonl((unsigned long) portnum);
791 #endif /* ndef _WIN32 */
792 #endif /* def HAVE_RFC2553 */
795 for (rp = result; rp != NULL; rp = rp->ai_next)
797 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
799 fd = socket(AF_INET, SOCK_STREAM, 0);
800 #endif /* def HAVE_RFC2553 */
803 if (fd == JB_INVALID_SOCKET)
817 * This is not needed for Win32 - in fact, it stops
818 * duplicate instances of Privoxy from being caught.
820 * On UNIX, we assume the user is sensible enough not
821 * to start Privoxy multiple times on the same IP.
822 * Without this, stopping and restarting Privoxy
823 * from a script fails.
824 * Note: SO_REUSEADDR is meant to only take over
825 * sockets which are *not* in listen state in Linux,
826 * e.g. sockets in TIME_WAIT. YMMV.
828 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
829 #endif /* ndef _WIN32 */
832 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
834 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
838 errno = WSAGetLastError();
839 if (errno == WSAEADDRINUSE)
841 if (errno == EADDRINUSE)
845 freeaddrinfo(result);
862 /* bind() succeeded, escape from for-loop */
864 * XXX: Support multiple listening sockets (e.g. localhost
865 * resolves to AF_INET and AF_INET6, but only the first address
872 freeaddrinfo(result);
875 /* All bind()s failed */
878 #endif /* ndef HAVE_RFC2553 */
880 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
894 /*********************************************************************
896 * Function : get_host_information
898 * Description : Determines the IP address the client used to
899 * reach us and the hostname associated with it.
901 * XXX: Most of the code has been copy and pasted
902 * from accept_connection() and not all of the
903 * ifdefs paths have been tested afterwards.
906 * 1 : afd = File descriptor returned from accept().
907 * 2 : ip_address = Pointer to return the pointer to
908 * the ip address string.
909 * 3 : hostname = Pointer to return the pointer to
910 * the hostname or NULL if the caller
911 * isn't interested in it.
915 *********************************************************************/
916 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
919 struct sockaddr_storage server;
922 struct sockaddr_in server;
923 struct hostent *host = NULL;
924 #endif /* HAVE_RFC2553 */
925 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
926 /* according to accept_connection() this fixes a warning. */
927 int s_length, s_length_provided;
929 socklen_t s_length, s_length_provided;
932 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
933 struct hostent result;
934 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
935 struct hostent_data hdata;
937 char hbuf[HOSTENT_BUFFER_SIZE];
939 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
940 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
941 #endif /* ifndef HAVE_RFC2553 */
942 s_length = s_length_provided = sizeof(server);
944 if (NULL != hostname)
950 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
952 if (s_length > s_length_provided)
954 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
958 *ip_address = malloc(NI_MAXHOST);
959 if (NULL == *ip_address)
961 log_error(LOG_LEVEL_ERROR,
962 "Out of memory while getting the client's IP address.");
965 retval = getnameinfo((struct sockaddr *) &server, s_length,
966 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
969 log_error(LOG_LEVEL_ERROR,
970 "Unable to print my own IP address: %s", gai_strerror(retval));
975 *ip_address = strdup(inet_ntoa(server.sin_addr));
976 #endif /* HAVE_RFC2553 */
977 if (NULL == hostname)
980 * We're done here, the caller isn't
981 * interested in knowing the hostname.
987 *hostname = malloc(NI_MAXHOST);
988 if (NULL == *hostname)
990 log_error(LOG_LEVEL_ERROR,
991 "Out of memory while getting the client's hostname.");
994 retval = getnameinfo((struct sockaddr *) &server, s_length,
995 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
998 log_error(LOG_LEVEL_ERROR,
999 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1003 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1004 gethostbyaddr_r((const char *)&server.sin_addr,
1005 sizeof(server.sin_addr), AF_INET,
1006 &result, hbuf, HOSTENT_BUFFER_SIZE,
1008 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1009 host = gethostbyaddr_r((const char *)&server.sin_addr,
1010 sizeof(server.sin_addr), AF_INET,
1011 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1012 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1013 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1014 sizeof(server.sin_addr), AF_INET,
1023 #elif defined(MUTEX_LOCKS_AVAILABLE)
1024 privoxy_mutex_lock(&resolver_mutex);
1025 host = gethostbyaddr((const char *)&server.sin_addr,
1026 sizeof(server.sin_addr), AF_INET);
1027 privoxy_mutex_unlock(&resolver_mutex);
1029 host = gethostbyaddr((const char *)&server.sin_addr,
1030 sizeof(server.sin_addr), AF_INET);
1034 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1038 *hostname = strdup(host->h_name);
1040 #endif /* else def HAVE_RFC2553 */
1047 /*********************************************************************
1049 * Function : accept_connection
1051 * Description : Accepts a connection on a socket. Socket must have
1052 * been created using bind_port().
1055 * 1 : csp = Client state, cfd, ip_addr_str, and
1056 * ip_addr_long will be set by this routine.
1057 * 2 : fd = file descriptor returned from bind_port
1059 * Returns : when a connection is accepted, it returns 1 (TRUE).
1060 * On an error it returns 0 (FALSE).
1062 *********************************************************************/
1063 int accept_connection(struct client_state * csp, jb_socket fd)
1066 /* XXX: client is stored directly into csp->tcp_addr */
1067 #define client (csp->tcp_addr)
1070 struct sockaddr_in client;
1073 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1074 /* Wierdness - fix a warning. */
1080 c_length = sizeof(client);
1083 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1084 if (afd == JB_INVALID_SOCKET)
1091 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1092 struct accept_filter_arg af_options;
1093 bzero(&af_options, sizeof(af_options));
1094 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1095 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1097 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1098 } while (afd < 1 && errno == EINTR);
1107 csp->ip_addr_str = malloc(NI_MAXHOST);
1108 if (NULL == csp->ip_addr_str)
1110 log_error(LOG_LEVEL_ERROR,
1111 "Out of memory while getting the client's IP address.");
1114 retval = getnameinfo((struct sockaddr *) &client, c_length,
1115 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1116 if (!csp->ip_addr_str || retval)
1118 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1119 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1120 freez(csp->ip_addr_str);
1124 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1125 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1126 #endif /* def HAVE_RFC2553 */
1133 /*********************************************************************
1135 * Function : resolve_hostname_to_ip
1137 * Description : Resolve a hostname to an internet tcp/ip address.
1138 * NULL or an empty string resolve to INADDR_ANY.
1141 * 1 : host = hostname to resolve
1143 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1145 *********************************************************************/
1146 unsigned long resolve_hostname_to_ip(const char *host)
1148 struct sockaddr_in inaddr;
1149 struct hostent *hostp;
1150 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1151 struct hostent result;
1152 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1153 char hbuf[HOSTENT_BUFFER_SIZE];
1155 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1156 struct hostent_data hdata;
1157 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1158 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1160 if ((host == NULL) || (*host == '\0'))
1165 memset((char *) &inaddr, 0, sizeof inaddr);
1167 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1169 unsigned int dns_retries = 0;
1170 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1171 while (gethostbyname_r(host, &result, hbuf,
1172 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1173 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1175 log_error(LOG_LEVEL_ERROR,
1176 "Timeout #%u while trying to resolve %s. Trying again.",
1179 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1180 while (NULL == (hostp = gethostbyname_r(host, &result,
1181 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1182 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1184 log_error(LOG_LEVEL_ERROR,
1185 "Timeout #%u while trying to resolve %s. Trying again.",
1188 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1190 * XXX: Doesn't retry in case of soft errors.
1191 * Does this gethostbyname_r version set h_errno?
1193 if (0 == gethostbyname_r(host, &result, &hdata))
1201 #elif defined(MUTEX_LOCKS_AVAILABLE)
1202 privoxy_mutex_lock(&resolver_mutex);
1203 while (NULL == (hostp = gethostbyname(host))
1204 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1206 log_error(LOG_LEVEL_ERROR,
1207 "Timeout #%u while trying to resolve %s. Trying again.",
1210 privoxy_mutex_unlock(&resolver_mutex);
1212 while (NULL == (hostp = gethostbyname(host))
1213 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1215 log_error(LOG_LEVEL_ERROR,
1216 "Timeout #%u while trying to resolve %s. Trying again.",
1219 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1221 * On Mac OSX, if a domain exists but doesn't have a type A
1222 * record associated with it, the h_addr member of the struct
1223 * hostent returned by gethostbyname is NULL, even if h_length
1224 * is 4. Therefore the second test below.
1226 if (hostp == NULL || hostp->h_addr == NULL)
1229 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1230 return(INADDR_NONE);
1232 if (hostp->h_addrtype != AF_INET)
1235 errno = WSAEPROTOTYPE;
1239 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1240 return(INADDR_NONE);
1243 (char *) &inaddr.sin_addr,
1244 (char *) hostp->h_addr,
1245 sizeof(inaddr.sin_addr)
1248 return(inaddr.sin_addr.s_addr);
1253 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1254 /*********************************************************************
1256 * Function : socket_is_still_alive
1258 * Description : Figures out whether or not a socket is still alive.
1261 * 1 : sfd = The socket to check.
1263 * Returns : TRUE for yes, otherwise FALSE.
1265 *********************************************************************/
1266 int socket_is_still_alive(jb_socket sfd)
1269 int no_data_waiting;
1273 struct pollfd poll_fd[1];
1275 memset(poll_fd, 0, sizeof(poll_fd));
1276 poll_fd[0].fd = sfd;
1277 poll_fd[0].events = POLLIN;
1279 poll_result = poll(poll_fd, 1, 0);
1281 if (-1 == poll_result)
1283 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1286 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1288 fd_set readable_fds;
1289 struct timeval timeout;
1292 memset(&timeout, '\0', sizeof(timeout));
1293 FD_ZERO(&readable_fds);
1294 FD_SET(sfd, &readable_fds);
1296 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1299 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1302 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1303 #endif /* def HAVE_POLL */
1305 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1307 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */