1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.66 2009/09/06 15:22:31 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"
104 #include "miscutil.h"
106 /* Mac OSX doesn't define AI_NUMERICSESRV */
107 #ifndef AI_NUMERICSERV
108 #define AI_NUMERICSERV 0
111 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
114 * Maximum number of gethostbyname(_r) retries in case of
115 * soft errors (TRY_AGAIN).
116 * XXX: Does it make sense to make this a config option?
118 #define MAX_DNS_RETRIES 10
120 #define MAX_LISTEN_BACKLOG 128
123 /*********************************************************************
125 * Function : connect_to
127 * Description : Open a socket and connect to it. Will check
128 * that this is allowed according to ACL.
131 * 1 : host = hostname to connect to
132 * 2 : portnum = port to connent on (XXX: should be unsigned)
133 * 3 : csp = Current client state (buffers, headers, etc...)
134 * Not modified, only used for source IP and ACL.
136 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
139 *********************************************************************/
141 /* Getaddrinfo implementation */
142 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
144 struct addrinfo hints, *result, *rp;
149 struct timeval tv[1];
150 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
152 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
156 struct access_control_addr dst[1];
157 #endif /* def FEATURE_ACL */
159 retval = snprintf(service, sizeof(service), "%d", portnum);
160 if ((-1 == retval) || (sizeof(service) <= retval))
162 log_error(LOG_LEVEL_ERROR,
163 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
165 csp->http->host_ip_addr_str = strdup("unknown");
166 return(JB_INVALID_SOCKET);
169 memset((char *)&hints, 0, sizeof(hints));
170 hints.ai_family = AF_UNSPEC;
171 hints.ai_socktype = SOCK_STREAM;
172 hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV; /* avoid service look-up */
173 if ((retval = getaddrinfo(host, service, &hints, &result)))
175 log_error(LOG_LEVEL_INFO,
176 "Can not resolve %s: %s", host, gai_strerror(retval));
177 csp->http->host_ip_addr_str = strdup("unknown");
178 return(JB_INVALID_SOCKET);
181 for (rp = result; rp != NULL; rp = rp->ai_next)
185 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
187 if (block_acl(dst, csp))
196 #endif /* def FEATURE_ACL */
198 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
199 if (NULL == csp->http->host_ip_addr_str)
201 log_error(LOG_LEVEL_ERROR,
202 "Out of memory while getting the server IP address.");
203 return JB_INVALID_SOCKET;
205 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
206 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
207 if (!csp->http->host_ip_addr_str || retval)
209 log_error(LOG_LEVEL_ERROR,
210 "Can not save csp->http->host_ip_addr_str: %s",
211 (csp->http->host_ip_addr_str) ?
212 gai_strerror(retval) : "Insufficient memory");
213 freez(csp->http->host_ip_addr_str);
218 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
221 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
228 { /* turn off TCP coalescence */
230 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
232 #endif /* def TCP_NODELAY */
234 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
235 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
238 fcntl(fd, F_SETFL, flags);
240 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
243 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
246 if (errno == WSAEINPROGRESS)
248 if (sock_errno() == EINPROGRESS)
249 #else /* ifndef _WIN32 */
250 if (errno == EINPROGRESS)
251 #endif /* ndef _WIN32 || __OS2__ */
257 if (sock_errno() != EINTR)
272 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
276 fcntl(fd, F_SETFL, flags);
278 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
280 /* wait for connection to complete */
287 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
288 if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
289 && FD_ISSET(fd, &wfds))
292 * See Linux connect(2) man page for more info
293 * about connecting on non-blocking socket.
296 socklen_t optlen = sizeof(socket_in_error);
297 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
299 if (!socket_in_error)
301 /* Connection established, no need to try other addresses. */
304 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
305 csp->http->host_ip_addr_str, service, strerror(socket_in_error));
309 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
310 "the connection to [%s]:%s: %s; dropping connection.",
311 csp->http->host_ip_addr_str, service, strerror(errno));
315 /* Connection failed, try next address */
319 freeaddrinfo(result);
322 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s.",
324 return(JB_INVALID_SOCKET);
326 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
327 host, csp->http->host_ip_addr_str, service);
333 #else /* ndef HAVE_RFC2553 */
334 /* Pre-getaddrinfo implementation */
336 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
338 struct sockaddr_in inaddr;
342 struct timeval tv[1];
343 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
345 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
348 struct access_control_addr dst[1];
349 #endif /* def FEATURE_ACL */
351 memset((char *)&inaddr, 0, sizeof inaddr);
353 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
355 csp->http->host_ip_addr_str = strdup("unknown");
356 return(JB_INVALID_SOCKET);
360 dst->addr = ntohl(addr);
363 if (block_acl(dst, csp))
370 return(JB_INVALID_SOCKET);
372 #endif /* def FEATURE_ACL */
374 inaddr.sin_addr.s_addr = addr;
375 inaddr.sin_family = AF_INET;
376 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
379 if (sizeof(inaddr.sin_port) == sizeof(short))
380 #endif /* ndef _WIN32 */
382 inaddr.sin_port = htons((unsigned short) portnum);
387 inaddr.sin_port = htonl((unsigned long)portnum);
389 #endif /* ndef _WIN32 */
392 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
394 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
397 return(JB_INVALID_SOCKET);
401 { /* turn off TCP coalescence */
403 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
405 #endif /* def TCP_NODELAY */
407 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
408 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
411 fcntl(fd, F_SETFL, flags);
413 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
415 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
418 if (errno == WSAEINPROGRESS)
420 if (sock_errno() == EINPROGRESS)
421 #else /* ifndef _WIN32 */
422 if (errno == EINPROGRESS)
423 #endif /* ndef _WIN32 || __OS2__ */
429 if (sock_errno() != EINTR)
435 return(JB_INVALID_SOCKET);
439 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
443 fcntl(fd, F_SETFL, flags);
445 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
447 /* wait for connection to complete */
454 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
455 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
458 return(JB_INVALID_SOCKET);
463 #endif /* ndef HAVE_RFC2553 */
466 /*********************************************************************
468 * Function : write_socket
470 * Description : Write the contents of buf (for n bytes) to socket fd.
473 * 1 : fd = file descriptor (aka. handle) of socket to write to.
474 * 2 : buf = pointer to data to be written.
475 * 3 : len = length of data to be written to the socket "fd".
477 * Returns : 0 on success (entire buffer sent).
480 *********************************************************************/
482 int write_socket(jb_socket fd, const char *buf, ssize_t len)
484 int write_socket(jb_socket fd, const char *buf, size_t len)
492 if (len < 0) /* constant condition - size_t isn't ever negative */
497 log_error(LOG_LEVEL_LOG, "%N", len, buf);
500 return (send(fd, buf, (int)len, 0) != (int)len);
501 #elif defined(__BEOS__) || defined(AMIGA)
502 return (send(fd, buf, len, 0) != len);
503 #elif defined(__OS2__)
505 * Break the data up into SOCKET_SEND_MAX chunks for sending...
506 * OS/2 seemed to complain when the chunks were too large.
508 #define SOCKET_SEND_MAX 65000
510 int write_len = 0, send_len, send_rc = 0, i = 0;
511 while ((i < len) && (send_rc != -1))
513 if ((i + SOCKET_SEND_MAX) > len)
516 send_len = SOCKET_SEND_MAX;
517 send_rc = send(fd,(char*)buf + i, send_len, 0);
525 return (write(fd, buf, len) != len);
531 /*********************************************************************
533 * Function : read_socket
535 * Description : Read from a TCP/IP socket in a platform independent way.
538 * 1 : fd = file descriptor of the socket to read
539 * 2 : buf = pointer to buffer where data will be written
540 * Must be >= len bytes long.
541 * 3 : len = maximum number of bytes to read
543 * Returns : On success, the number of bytes read is returned (zero
544 * indicates end of file), and the file position is advanced
545 * by this number. It is not an error if this number is
546 * smaller than the number of bytes requested; this may hap-
547 * pen for example because fewer bytes are actually available
548 * right now (maybe because we were close to end-of-file, or
549 * because we are reading from a pipe, or from a terminal,
550 * or because read() was interrupted by a signal). On error,
551 * -1 is returned, and errno is set appropriately. In this
552 * case it is left unspecified whether the file position (if
555 *********************************************************************/
556 int read_socket(jb_socket fd, char *buf, int len)
564 return(recv(fd, buf, len, 0));
565 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
566 return(recv(fd, buf, (size_t)len, 0));
568 return((int)read(fd, buf, (size_t)len));
573 /*********************************************************************
575 * Function : data_is_available
577 * Description : Waits for data to arrive on a socket.
580 * 1 : fd = file descriptor of the socket to read
581 * 2 : seconds_to_wait = number of seconds after which we give up.
583 * Returns : TRUE if data arrived in time,
586 *********************************************************************/
587 int data_is_available(jb_socket fd, int seconds_to_wait)
591 struct timeval timeout;
594 memset(&timeout, 0, sizeof(timeout));
595 timeout.tv_sec = seconds_to_wait;
598 /* Copy and pasted from jcc.c ... */
599 memset(&rfds, 0, sizeof(fd_set));
605 n = select(fd+1, &rfds, NULL, NULL, &timeout);
608 * XXX: Do we care about the different error conditions?
610 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
614 /*********************************************************************
616 * Function : close_socket
618 * Description : Closes a TCP/IP socket
621 * 1 : fd = file descriptor of socket to be closed
625 *********************************************************************/
626 void close_socket(jb_socket fd)
628 #if defined(_WIN32) || defined(__BEOS__)
632 #elif defined(__OS2__)
641 /*********************************************************************
643 * Function : bind_port
645 * Description : Call socket, set socket options, and listen.
646 * Called by listen_loop to "boot up" our proxy address.
649 * 1 : hostnam = TCP/IP address to bind/listen to
650 * 2 : portnum = port to listen on
651 * 3 : pfd = pointer used to return file descriptor.
653 * Returns : if success, returns 0 and sets *pfd.
654 * if failure, returns -3 if address is in use,
655 * -2 if address unresolvable,
657 *********************************************************************/
658 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
661 struct addrinfo hints;
662 struct addrinfo *result, *rp;
664 * XXX: portnum should be a string to allow symbolic service
665 * names in the configuration file and to avoid the following
671 struct sockaddr_in inaddr;
672 #endif /* def HAVE_RFC2553 */
676 #endif /* ndef _WIN32 */
678 *pfd = JB_INVALID_SOCKET;
681 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
682 if ((-1 == retval) || (sizeof(servnam) <= retval))
684 log_error(LOG_LEVEL_ERROR,
685 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
690 memset(&hints, 0, sizeof(struct addrinfo));
691 if ((hostnam == NULL) || !strcmpic(hostnam, "localhost"))
694 * XXX: This is a hack. The right thing to do
695 * would be to bind to both AF_INET and AF_INET6.
696 * This will also fail if there is no AF_INET
699 hints.ai_family = AF_INET;
703 hints.ai_family = AF_UNSPEC;
705 hints.ai_socktype = SOCK_STREAM;
706 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
707 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
708 hints.ai_canonname = NULL;
709 hints.ai_addr = NULL;
710 hints.ai_next = NULL;
712 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
714 log_error(LOG_LEVEL_ERROR,
715 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
719 memset((char *)&inaddr, '\0', sizeof inaddr);
721 inaddr.sin_family = AF_INET;
722 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
724 if (inaddr.sin_addr.s_addr == INADDR_NONE)
730 if (sizeof(inaddr.sin_port) == sizeof(short))
731 #endif /* ndef _WIN32 */
733 inaddr.sin_port = htons((unsigned short) portnum);
738 inaddr.sin_port = htonl((unsigned long) portnum);
740 #endif /* ndef _WIN32 */
741 #endif /* def HAVE_RFC2553 */
744 for (rp = result; rp != NULL; rp = rp->ai_next)
746 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
748 fd = socket(AF_INET, SOCK_STREAM, 0);
749 #endif /* def HAVE_RFC2553 */
752 if (fd == JB_INVALID_SOCKET)
766 * This is not needed for Win32 - in fact, it stops
767 * duplicate instances of Privoxy from being caught.
769 * On UNIX, we assume the user is sensible enough not
770 * to start Privoxy multiple times on the same IP.
771 * Without this, stopping and restarting Privoxy
772 * from a script fails.
773 * Note: SO_REUSEADDR is meant to only take over
774 * sockets which are *not* in listen state in Linux,
775 * e.g. sockets in TIME_WAIT. YMMV.
777 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
778 #endif /* ndef _WIN32 */
781 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
783 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
787 errno = WSAGetLastError();
788 if (errno == WSAEADDRINUSE)
790 if (errno == EADDRINUSE)
794 freeaddrinfo(result);
811 /* bind() succeeded, escape from for-loop */
813 * XXX: Support multiple listening sockets (e.g. localhost
814 * resolves to AF_INET and AF_INET6, but only the first address
821 freeaddrinfo(result);
824 /* All bind()s failed */
827 #endif /* ndef HAVE_RFC2553 */
829 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
843 /*********************************************************************
845 * Function : get_host_information
847 * Description : Determines the IP address the client used to
848 * reach us and the hostname associated with it.
850 * XXX: Most of the code has been copy and pasted
851 * from accept_connection() and not all of the
852 * ifdefs paths have been tested afterwards.
855 * 1 : afd = File descriptor returned from accept().
856 * 2 : ip_address = Pointer to return the pointer to
857 * the ip address string.
858 * 3 : hostname = Pointer to return the pointer to
859 * the hostname or NULL if the caller
860 * isn't interested in it.
864 *********************************************************************/
865 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
868 struct sockaddr_storage server;
871 struct sockaddr_in server;
872 struct hostent *host = NULL;
873 #endif /* HAVE_RFC2553 */
874 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
875 /* according to accept_connection() this fixes a warning. */
876 int s_length, s_length_provided;
878 socklen_t s_length, s_length_provided;
881 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
882 struct hostent result;
883 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
884 struct hostent_data hdata;
886 char hbuf[HOSTENT_BUFFER_SIZE];
888 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
889 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
890 #endif /* ifndef HAVE_RFC2553 */
891 s_length = s_length_provided = sizeof(server);
893 if (NULL != hostname)
899 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
901 if (s_length > s_length_provided)
903 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
907 *ip_address = malloc(NI_MAXHOST);
908 if (NULL == *ip_address)
910 log_error(LOG_LEVEL_ERROR,
911 "Out of memory while getting the client's IP address.");
914 retval = getnameinfo((struct sockaddr *) &server, s_length,
915 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
918 log_error(LOG_LEVEL_ERROR,
919 "Unable to print my own IP address: %s", gai_strerror(retval));
924 *ip_address = strdup(inet_ntoa(server.sin_addr));
925 #endif /* HAVE_RFC2553 */
926 if (NULL == hostname)
929 * We're done here, the caller isn't
930 * interested in knowing the hostname.
936 *hostname = malloc(NI_MAXHOST);
937 if (NULL == *hostname)
939 log_error(LOG_LEVEL_ERROR,
940 "Out of memory while getting the client's hostname.");
943 retval = getnameinfo((struct sockaddr *) &server, s_length,
944 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
947 log_error(LOG_LEVEL_ERROR,
948 "Unable to resolve my own IP address: %s", gai_strerror(retval));
952 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
953 gethostbyaddr_r((const char *)&server.sin_addr,
954 sizeof(server.sin_addr), AF_INET,
955 &result, hbuf, HOSTENT_BUFFER_SIZE,
957 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
958 host = gethostbyaddr_r((const char *)&server.sin_addr,
959 sizeof(server.sin_addr), AF_INET,
960 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
961 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
962 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
963 sizeof(server.sin_addr), AF_INET,
972 #elif defined(MUTEX_LOCKS_AVAILABLE)
973 privoxy_mutex_lock(&resolver_mutex);
974 host = gethostbyaddr((const char *)&server.sin_addr,
975 sizeof(server.sin_addr), AF_INET);
976 privoxy_mutex_unlock(&resolver_mutex);
978 host = gethostbyaddr((const char *)&server.sin_addr,
979 sizeof(server.sin_addr), AF_INET);
983 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
987 *hostname = strdup(host->h_name);
989 #endif /* else def HAVE_RFC2553 */
996 /*********************************************************************
998 * Function : accept_connection
1000 * Description : Accepts a connection on a socket. Socket must have
1001 * been created using bind_port().
1004 * 1 : csp = Client state, cfd, ip_addr_str, and
1005 * ip_addr_long will be set by this routine.
1006 * 2 : fd = file descriptor returned from bind_port
1008 * Returns : when a connection is accepted, it returns 1 (TRUE).
1009 * On an error it returns 0 (FALSE).
1011 *********************************************************************/
1012 int accept_connection(struct client_state * csp, jb_socket fd)
1015 /* XXX: client is stored directly into csp->tcp_addr */
1016 #define client (csp->tcp_addr)
1019 struct sockaddr_in client;
1022 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1023 /* Wierdness - fix a warning. */
1029 c_length = sizeof(client);
1032 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1033 if (afd == JB_INVALID_SOCKET)
1040 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1041 } while (afd < 1 && errno == EINTR);
1050 csp->ip_addr_str = malloc(NI_MAXHOST);
1051 if (NULL == csp->ip_addr_str)
1053 log_error(LOG_LEVEL_ERROR,
1054 "Out of memory while getting the client's IP address.");
1057 retval = getnameinfo((struct sockaddr *) &client, c_length,
1058 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1059 if (!csp->ip_addr_str || retval)
1061 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1062 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1063 freez(csp->ip_addr_str);
1067 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1068 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1069 #endif /* def HAVE_RFC2553 */
1076 /*********************************************************************
1078 * Function : resolve_hostname_to_ip
1080 * Description : Resolve a hostname to an internet tcp/ip address.
1081 * NULL or an empty string resolve to INADDR_ANY.
1084 * 1 : host = hostname to resolve
1086 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1088 *********************************************************************/
1089 unsigned long resolve_hostname_to_ip(const char *host)
1091 struct sockaddr_in inaddr;
1092 struct hostent *hostp;
1093 unsigned int dns_retries = 0;
1094 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1095 struct hostent result;
1096 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1097 char hbuf[HOSTENT_BUFFER_SIZE];
1099 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1100 struct hostent_data hdata;
1101 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1102 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1104 if ((host == NULL) || (*host == '\0'))
1109 memset((char *) &inaddr, 0, sizeof inaddr);
1111 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1113 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1114 while (gethostbyname_r(host, &result, hbuf,
1115 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1116 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1118 log_error(LOG_LEVEL_ERROR,
1119 "Timeout #%u while trying to resolve %s. Trying again.",
1122 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1123 while (NULL == (hostp = gethostbyname_r(host, &result,
1124 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1125 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1127 log_error(LOG_LEVEL_ERROR,
1128 "Timeout #%u while trying to resolve %s. Trying again.",
1131 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1133 * XXX: Doesn't retry in case of soft errors.
1134 * Does this gethostbyname_r version set h_errno?
1136 if (0 == gethostbyname_r(host, &result, &hdata))
1144 #elif defined(MUTEX_LOCKS_AVAILABLE)
1145 privoxy_mutex_lock(&resolver_mutex);
1146 while (NULL == (hostp = gethostbyname(host))
1147 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1149 log_error(LOG_LEVEL_ERROR,
1150 "Timeout #%u while trying to resolve %s. Trying again.",
1153 privoxy_mutex_unlock(&resolver_mutex);
1155 while (NULL == (hostp = gethostbyname(host))
1156 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1158 log_error(LOG_LEVEL_ERROR,
1159 "Timeout #%u while trying to resolve %s. Trying again.",
1162 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1164 * On Mac OSX, if a domain exists but doesn't have a type A
1165 * record associated with it, the h_addr member of the struct
1166 * hostent returned by gethostbyname is NULL, even if h_length
1167 * is 4. Therefore the second test below.
1169 if (hostp == NULL || hostp->h_addr == NULL)
1172 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1173 return(INADDR_NONE);
1175 if (hostp->h_addrtype != AF_INET)
1178 errno = WSAEPROTOTYPE;
1182 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1183 return(INADDR_NONE);
1186 (char *) &inaddr.sin_addr,
1187 (char *) hostp->h_addr,
1188 sizeof(inaddr.sin_addr)
1191 return(inaddr.sin_addr.s_addr);
1196 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1197 /*********************************************************************
1199 * Function : socket_is_still_usable
1201 * Description : Decides whether or not an open socket is still usable.
1204 * 1 : sfd = The socket to check.
1206 * Returns : TRUE for yes, otherwise FALSE.
1208 *********************************************************************/
1209 int socket_is_still_usable(jb_socket sfd)
1212 int no_data_waiting;
1216 struct pollfd poll_fd[1];
1218 memset(poll_fd, 0, sizeof(poll_fd));
1219 poll_fd[0].fd = sfd;
1220 poll_fd[0].events = POLLIN;
1222 poll_result = poll(poll_fd, 1, 0);
1224 if (-1 == poll_result)
1226 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1229 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1231 fd_set readable_fds;
1232 struct timeval timeout;
1235 memset(&timeout, '\0', sizeof(timeout));
1236 FD_ZERO(&readable_fds);
1237 FD_SET(sfd, &readable_fds);
1239 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1242 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1245 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1246 #endif /* def HAVE_POLL */
1248 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1250 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */