1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.69 2009/12/15 17:41:36 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)
151 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
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 csp->http->host_ip_addr_str = strdup("unknown");
180 return(JB_INVALID_SOCKET);
183 for (rp = result; rp != NULL; rp = rp->ai_next)
187 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
189 if (block_acl(dst, csp))
198 #endif /* def FEATURE_ACL */
200 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
201 if (NULL == csp->http->host_ip_addr_str)
203 log_error(LOG_LEVEL_ERROR,
204 "Out of memory while getting the server IP address.");
205 return JB_INVALID_SOCKET;
207 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
208 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
209 if (!csp->http->host_ip_addr_str || retval)
211 log_error(LOG_LEVEL_ERROR,
212 "Can not save csp->http->host_ip_addr_str: %s",
213 (csp->http->host_ip_addr_str) ?
214 gai_strerror(retval) : "Insufficient memory");
215 freez(csp->http->host_ip_addr_str);
220 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
223 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
230 { /* turn off TCP coalescence */
232 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
234 #endif /* def TCP_NODELAY */
236 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
237 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
240 fcntl(fd, F_SETFL, flags);
242 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
245 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
248 if (errno == WSAEINPROGRESS)
250 if (sock_errno() == EINPROGRESS)
251 #else /* ifndef _WIN32 */
252 if (errno == EINPROGRESS)
253 #endif /* ndef _WIN32 || __OS2__ */
259 if (sock_errno() != EINTR)
274 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
278 fcntl(fd, F_SETFL, flags);
280 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
282 /* wait for connection to complete */
289 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
290 if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
291 && FD_ISSET(fd, &wfds))
294 * See Linux connect(2) man page for more info
295 * about connecting on non-blocking socket.
298 socklen_t optlen = sizeof(socket_in_error);
299 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
301 if (!socket_in_error)
303 /* Connection established, no need to try other addresses. */
306 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
307 csp->http->host_ip_addr_str, service, strerror(socket_in_error));
311 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
312 "the connection to [%s]:%s: %s; dropping connection.",
313 csp->http->host_ip_addr_str, service, strerror(errno));
317 /* Connection failed, try next address */
321 freeaddrinfo(result);
324 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s.",
326 return(JB_INVALID_SOCKET);
328 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
329 host, csp->http->host_ip_addr_str, service);
335 #else /* ndef HAVE_RFC2553 */
336 /* Pre-getaddrinfo implementation */
338 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
340 struct sockaddr_in inaddr;
344 struct timeval tv[1];
345 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
347 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
350 struct access_control_addr dst[1];
351 #endif /* def FEATURE_ACL */
353 memset((char *)&inaddr, 0, sizeof inaddr);
355 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
357 csp->http->host_ip_addr_str = strdup("unknown");
358 return(JB_INVALID_SOCKET);
362 dst->addr = ntohl(addr);
365 if (block_acl(dst, csp))
372 return(JB_INVALID_SOCKET);
374 #endif /* def FEATURE_ACL */
376 inaddr.sin_addr.s_addr = addr;
377 inaddr.sin_family = AF_INET;
378 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
381 if (sizeof(inaddr.sin_port) == sizeof(short))
382 #endif /* ndef _WIN32 */
384 inaddr.sin_port = htons((unsigned short) portnum);
389 inaddr.sin_port = htonl((unsigned long)portnum);
391 #endif /* ndef _WIN32 */
394 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
396 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
399 return(JB_INVALID_SOCKET);
403 { /* turn off TCP coalescence */
405 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
407 #endif /* def TCP_NODELAY */
409 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
410 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
413 fcntl(fd, F_SETFL, flags);
415 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
417 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
420 if (errno == WSAEINPROGRESS)
422 if (sock_errno() == EINPROGRESS)
423 #else /* ifndef _WIN32 */
424 if (errno == EINPROGRESS)
425 #endif /* ndef _WIN32 || __OS2__ */
431 if (sock_errno() != EINTR)
437 return(JB_INVALID_SOCKET);
441 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
445 fcntl(fd, F_SETFL, flags);
447 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
449 /* wait for connection to complete */
456 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
457 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
460 return(JB_INVALID_SOCKET);
465 #endif /* ndef HAVE_RFC2553 */
468 /*********************************************************************
470 * Function : write_socket
472 * Description : Write the contents of buf (for n bytes) to socket fd.
475 * 1 : fd = file descriptor (aka. handle) of socket to write to.
476 * 2 : buf = pointer to data to be written.
477 * 3 : len = length of data to be written to the socket "fd".
479 * Returns : 0 on success (entire buffer sent).
482 *********************************************************************/
484 int write_socket(jb_socket fd, const char *buf, ssize_t len)
486 int write_socket(jb_socket fd, const char *buf, size_t len)
494 if (len < 0) /* constant condition - size_t isn't ever negative */
499 log_error(LOG_LEVEL_LOG, "%N", len, buf);
502 return (send(fd, buf, (int)len, 0) != (int)len);
503 #elif defined(__BEOS__) || defined(AMIGA)
504 return (send(fd, buf, len, 0) != len);
505 #elif defined(__OS2__)
507 * Break the data up into SOCKET_SEND_MAX chunks for sending...
508 * OS/2 seemed to complain when the chunks were too large.
510 #define SOCKET_SEND_MAX 65000
512 int write_len = 0, send_len, send_rc = 0, i = 0;
513 while ((i < len) && (send_rc != -1))
515 if ((i + SOCKET_SEND_MAX) > len)
518 send_len = SOCKET_SEND_MAX;
519 send_rc = send(fd,(char*)buf + i, send_len, 0);
527 return (write(fd, buf, len) != len);
533 /*********************************************************************
535 * Function : read_socket
537 * Description : Read from a TCP/IP socket in a platform independent way.
540 * 1 : fd = file descriptor of the socket to read
541 * 2 : buf = pointer to buffer where data will be written
542 * Must be >= len bytes long.
543 * 3 : len = maximum number of bytes to read
545 * Returns : On success, the number of bytes read is returned (zero
546 * indicates end of file), and the file position is advanced
547 * by this number. It is not an error if this number is
548 * smaller than the number of bytes requested; this may hap-
549 * pen for example because fewer bytes are actually available
550 * right now (maybe because we were close to end-of-file, or
551 * because we are reading from a pipe, or from a terminal,
552 * or because read() was interrupted by a signal). On error,
553 * -1 is returned, and errno is set appropriately. In this
554 * case it is left unspecified whether the file position (if
557 *********************************************************************/
558 int read_socket(jb_socket fd, char *buf, int len)
566 return(recv(fd, buf, len, 0));
567 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
568 return(recv(fd, buf, (size_t)len, 0));
570 return((int)read(fd, buf, (size_t)len));
575 /*********************************************************************
577 * Function : data_is_available
579 * Description : Waits for data to arrive on a socket.
582 * 1 : fd = file descriptor of the socket to read
583 * 2 : seconds_to_wait = number of seconds after which we give up.
585 * Returns : TRUE if data arrived in time,
588 *********************************************************************/
589 int data_is_available(jb_socket fd, int seconds_to_wait)
593 struct timeval timeout;
596 memset(&timeout, 0, sizeof(timeout));
597 timeout.tv_sec = seconds_to_wait;
600 /* Copy and pasted from jcc.c ... */
601 memset(&rfds, 0, sizeof(fd_set));
607 n = select(fd+1, &rfds, NULL, NULL, &timeout);
610 * XXX: Do we care about the different error conditions?
612 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
616 /*********************************************************************
618 * Function : close_socket
620 * Description : Closes a TCP/IP socket
623 * 1 : fd = file descriptor of socket to be closed
627 *********************************************************************/
628 void close_socket(jb_socket fd)
630 #if defined(_WIN32) || defined(__BEOS__)
634 #elif defined(__OS2__)
643 /*********************************************************************
645 * Function : bind_port
647 * Description : Call socket, set socket options, and listen.
648 * Called by listen_loop to "boot up" our proxy address.
651 * 1 : hostnam = TCP/IP address to bind/listen to
652 * 2 : portnum = port to listen on
653 * 3 : pfd = pointer used to return file descriptor.
655 * Returns : if success, returns 0 and sets *pfd.
656 * if failure, returns -3 if address is in use,
657 * -2 if address unresolvable,
659 *********************************************************************/
660 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
663 struct addrinfo hints;
664 struct addrinfo *result, *rp;
666 * XXX: portnum should be a string to allow symbolic service
667 * names in the configuration file and to avoid the following
673 struct sockaddr_in inaddr;
674 #endif /* def HAVE_RFC2553 */
678 #endif /* ndef _WIN32 */
680 *pfd = JB_INVALID_SOCKET;
683 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
684 if ((-1 == retval) || (sizeof(servnam) <= retval))
686 log_error(LOG_LEVEL_ERROR,
687 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
692 memset(&hints, 0, sizeof(struct addrinfo));
696 * XXX: This is a hack. The right thing to do
697 * would be to bind to both AF_INET and AF_INET6.
698 * This will also fail if there is no AF_INET
701 hints.ai_family = AF_INET;
705 hints.ai_family = AF_UNSPEC;
707 hints.ai_socktype = SOCK_STREAM;
708 hints.ai_flags = AI_PASSIVE;
710 hints.ai_flags |= AI_ADDRCONFIG;
712 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
713 hints.ai_canonname = NULL;
714 hints.ai_addr = NULL;
715 hints.ai_next = NULL;
717 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
719 log_error(LOG_LEVEL_ERROR,
720 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
724 memset((char *)&inaddr, '\0', sizeof inaddr);
726 inaddr.sin_family = AF_INET;
727 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
729 if (inaddr.sin_addr.s_addr == INADDR_NONE)
735 if (sizeof(inaddr.sin_port) == sizeof(short))
736 #endif /* ndef _WIN32 */
738 inaddr.sin_port = htons((unsigned short) portnum);
743 inaddr.sin_port = htonl((unsigned long) portnum);
745 #endif /* ndef _WIN32 */
746 #endif /* def HAVE_RFC2553 */
749 for (rp = result; rp != NULL; rp = rp->ai_next)
751 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
753 fd = socket(AF_INET, SOCK_STREAM, 0);
754 #endif /* def HAVE_RFC2553 */
757 if (fd == JB_INVALID_SOCKET)
771 * This is not needed for Win32 - in fact, it stops
772 * duplicate instances of Privoxy from being caught.
774 * On UNIX, we assume the user is sensible enough not
775 * to start Privoxy multiple times on the same IP.
776 * Without this, stopping and restarting Privoxy
777 * from a script fails.
778 * Note: SO_REUSEADDR is meant to only take over
779 * sockets which are *not* in listen state in Linux,
780 * e.g. sockets in TIME_WAIT. YMMV.
782 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
783 #endif /* ndef _WIN32 */
786 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
788 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
792 errno = WSAGetLastError();
793 if (errno == WSAEADDRINUSE)
795 if (errno == EADDRINUSE)
799 freeaddrinfo(result);
816 /* bind() succeeded, escape from for-loop */
818 * XXX: Support multiple listening sockets (e.g. localhost
819 * resolves to AF_INET and AF_INET6, but only the first address
826 freeaddrinfo(result);
829 /* All bind()s failed */
832 #endif /* ndef HAVE_RFC2553 */
834 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
848 /*********************************************************************
850 * Function : get_host_information
852 * Description : Determines the IP address the client used to
853 * reach us and the hostname associated with it.
855 * XXX: Most of the code has been copy and pasted
856 * from accept_connection() and not all of the
857 * ifdefs paths have been tested afterwards.
860 * 1 : afd = File descriptor returned from accept().
861 * 2 : ip_address = Pointer to return the pointer to
862 * the ip address string.
863 * 3 : hostname = Pointer to return the pointer to
864 * the hostname or NULL if the caller
865 * isn't interested in it.
869 *********************************************************************/
870 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
873 struct sockaddr_storage server;
876 struct sockaddr_in server;
877 struct hostent *host = NULL;
878 #endif /* HAVE_RFC2553 */
879 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
880 /* according to accept_connection() this fixes a warning. */
881 int s_length, s_length_provided;
883 socklen_t s_length, s_length_provided;
886 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
887 struct hostent result;
888 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
889 struct hostent_data hdata;
891 char hbuf[HOSTENT_BUFFER_SIZE];
893 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
894 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
895 #endif /* ifndef HAVE_RFC2553 */
896 s_length = s_length_provided = sizeof(server);
898 if (NULL != hostname)
904 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
906 if (s_length > s_length_provided)
908 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
912 *ip_address = malloc(NI_MAXHOST);
913 if (NULL == *ip_address)
915 log_error(LOG_LEVEL_ERROR,
916 "Out of memory while getting the client's IP address.");
919 retval = getnameinfo((struct sockaddr *) &server, s_length,
920 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
923 log_error(LOG_LEVEL_ERROR,
924 "Unable to print my own IP address: %s", gai_strerror(retval));
929 *ip_address = strdup(inet_ntoa(server.sin_addr));
930 #endif /* HAVE_RFC2553 */
931 if (NULL == hostname)
934 * We're done here, the caller isn't
935 * interested in knowing the hostname.
941 *hostname = malloc(NI_MAXHOST);
942 if (NULL == *hostname)
944 log_error(LOG_LEVEL_ERROR,
945 "Out of memory while getting the client's hostname.");
948 retval = getnameinfo((struct sockaddr *) &server, s_length,
949 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
952 log_error(LOG_LEVEL_ERROR,
953 "Unable to resolve my own IP address: %s", gai_strerror(retval));
957 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
958 gethostbyaddr_r((const char *)&server.sin_addr,
959 sizeof(server.sin_addr), AF_INET,
960 &result, hbuf, HOSTENT_BUFFER_SIZE,
962 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
963 host = gethostbyaddr_r((const char *)&server.sin_addr,
964 sizeof(server.sin_addr), AF_INET,
965 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
966 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
967 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
968 sizeof(server.sin_addr), AF_INET,
977 #elif defined(MUTEX_LOCKS_AVAILABLE)
978 privoxy_mutex_lock(&resolver_mutex);
979 host = gethostbyaddr((const char *)&server.sin_addr,
980 sizeof(server.sin_addr), AF_INET);
981 privoxy_mutex_unlock(&resolver_mutex);
983 host = gethostbyaddr((const char *)&server.sin_addr,
984 sizeof(server.sin_addr), AF_INET);
988 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
992 *hostname = strdup(host->h_name);
994 #endif /* else def HAVE_RFC2553 */
1001 /*********************************************************************
1003 * Function : accept_connection
1005 * Description : Accepts a connection on a socket. Socket must have
1006 * been created using bind_port().
1009 * 1 : csp = Client state, cfd, ip_addr_str, and
1010 * ip_addr_long will be set by this routine.
1011 * 2 : fd = file descriptor returned from bind_port
1013 * Returns : when a connection is accepted, it returns 1 (TRUE).
1014 * On an error it returns 0 (FALSE).
1016 *********************************************************************/
1017 int accept_connection(struct client_state * csp, jb_socket fd)
1020 /* XXX: client is stored directly into csp->tcp_addr */
1021 #define client (csp->tcp_addr)
1024 struct sockaddr_in client;
1027 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1028 /* Wierdness - fix a warning. */
1034 c_length = sizeof(client);
1037 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1038 if (afd == JB_INVALID_SOCKET)
1045 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1046 } while (afd < 1 && errno == EINTR);
1055 csp->ip_addr_str = malloc(NI_MAXHOST);
1056 if (NULL == csp->ip_addr_str)
1058 log_error(LOG_LEVEL_ERROR,
1059 "Out of memory while getting the client's IP address.");
1062 retval = getnameinfo((struct sockaddr *) &client, c_length,
1063 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1064 if (!csp->ip_addr_str || retval)
1066 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1067 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1068 freez(csp->ip_addr_str);
1072 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1073 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1074 #endif /* def HAVE_RFC2553 */
1081 /*********************************************************************
1083 * Function : resolve_hostname_to_ip
1085 * Description : Resolve a hostname to an internet tcp/ip address.
1086 * NULL or an empty string resolve to INADDR_ANY.
1089 * 1 : host = hostname to resolve
1091 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1093 *********************************************************************/
1094 unsigned long resolve_hostname_to_ip(const char *host)
1096 struct sockaddr_in inaddr;
1097 struct hostent *hostp;
1098 unsigned int dns_retries = 0;
1099 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1100 struct hostent result;
1101 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1102 char hbuf[HOSTENT_BUFFER_SIZE];
1104 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1105 struct hostent_data hdata;
1106 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1107 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1109 if ((host == NULL) || (*host == '\0'))
1114 memset((char *) &inaddr, 0, sizeof inaddr);
1116 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1118 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1119 while (gethostbyname_r(host, &result, hbuf,
1120 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1121 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1123 log_error(LOG_LEVEL_ERROR,
1124 "Timeout #%u while trying to resolve %s. Trying again.",
1127 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1128 while (NULL == (hostp = gethostbyname_r(host, &result,
1129 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1130 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1132 log_error(LOG_LEVEL_ERROR,
1133 "Timeout #%u while trying to resolve %s. Trying again.",
1136 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1138 * XXX: Doesn't retry in case of soft errors.
1139 * Does this gethostbyname_r version set h_errno?
1141 if (0 == gethostbyname_r(host, &result, &hdata))
1149 #elif defined(MUTEX_LOCKS_AVAILABLE)
1150 privoxy_mutex_lock(&resolver_mutex);
1151 while (NULL == (hostp = gethostbyname(host))
1152 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1154 log_error(LOG_LEVEL_ERROR,
1155 "Timeout #%u while trying to resolve %s. Trying again.",
1158 privoxy_mutex_unlock(&resolver_mutex);
1160 while (NULL == (hostp = gethostbyname(host))
1161 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1163 log_error(LOG_LEVEL_ERROR,
1164 "Timeout #%u while trying to resolve %s. Trying again.",
1167 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1169 * On Mac OSX, if a domain exists but doesn't have a type A
1170 * record associated with it, the h_addr member of the struct
1171 * hostent returned by gethostbyname is NULL, even if h_length
1172 * is 4. Therefore the second test below.
1174 if (hostp == NULL || hostp->h_addr == NULL)
1177 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1178 return(INADDR_NONE);
1180 if (hostp->h_addrtype != AF_INET)
1183 errno = WSAEPROTOTYPE;
1187 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1188 return(INADDR_NONE);
1191 (char *) &inaddr.sin_addr,
1192 (char *) hostp->h_addr,
1193 sizeof(inaddr.sin_addr)
1196 return(inaddr.sin_addr.s_addr);
1201 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1202 /*********************************************************************
1204 * Function : socket_is_still_usable
1206 * Description : Decides whether or not an open socket is still usable.
1209 * 1 : sfd = The socket to check.
1211 * Returns : TRUE for yes, otherwise FALSE.
1213 *********************************************************************/
1214 int socket_is_still_usable(jb_socket sfd)
1217 int no_data_waiting;
1221 struct pollfd poll_fd[1];
1223 memset(poll_fd, 0, sizeof(poll_fd));
1224 poll_fd[0].fd = sfd;
1225 poll_fd[0].events = POLLIN;
1227 poll_result = poll(poll_fd, 1, 0);
1229 if (-1 == poll_result)
1231 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1234 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1236 fd_set readable_fds;
1237 struct timeval timeout;
1240 memset(&timeout, '\0', sizeof(timeout));
1241 FD_ZERO(&readable_fds);
1242 FD_SET(sfd, &readable_fds);
1244 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1247 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1250 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1251 #endif /* def HAVE_POLL */
1253 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1255 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */