1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.84 2011/03/27 13:53:49 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-2010 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__)
185 struct access_control_addr dst[1];
186 #endif /* def FEATURE_ACL */
188 retval = snprintf(service, sizeof(service), "%d", portnum);
189 if ((-1 == retval) || (sizeof(service) <= retval))
191 log_error(LOG_LEVEL_ERROR,
192 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
194 csp->http->host_ip_addr_str = strdup("unknown");
195 return(JB_INVALID_SOCKET);
198 memset((char *)&hints, 0, sizeof(hints));
199 hints.ai_family = AF_UNSPEC;
200 hints.ai_socktype = SOCK_STREAM;
201 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
203 hints.ai_flags |= AI_ADDRCONFIG;
205 if ((retval = getaddrinfo(host, service, &hints, &result)))
207 log_error(LOG_LEVEL_INFO,
208 "Can not resolve %s: %s", host, gai_strerror(retval));
209 /* XXX: Should find a better way to propagate this error. */
211 csp->http->host_ip_addr_str = strdup("unknown");
212 return(JB_INVALID_SOCKET);
215 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
216 if (NULL == csp->http->host_ip_addr_str)
218 log_error(LOG_LEVEL_ERROR,
219 "Out of memory while getting the server IP address.");
220 return JB_INVALID_SOCKET;
223 for (rp = result; rp != NULL; rp = rp->ai_next)
227 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
229 if (block_acl(dst, csp))
238 #endif /* def FEATURE_ACL */
240 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
241 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
244 log_error(LOG_LEVEL_ERROR,
245 "Can not save csp->http->host_ip_addr_str: %s",
246 gai_strerror(retval));
251 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
254 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
261 { /* turn off TCP coalescence */
263 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
265 #endif /* def TCP_NODELAY */
267 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
268 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
271 fcntl(fd, F_SETFL, flags);
273 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
276 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
279 if (errno == WSAEINPROGRESS)
281 if (sock_errno() == EINPROGRESS)
282 #else /* ifndef _WIN32 */
283 if (errno == EINPROGRESS)
284 #endif /* ndef _WIN32 || __OS2__ */
290 if (sock_errno() != EINTR)
305 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
309 fcntl(fd, F_SETFL, flags);
311 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
313 /* wait for connection to complete */
320 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
321 if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
322 && FD_ISSET(fd, &wfds))
325 socklen_t optlen = sizeof(socket_in_error);
326 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
328 if (!socket_in_error)
330 /* Connection established, no need to try other addresses. */
333 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
334 csp->http->host_ip_addr_str, service, strerror(socket_in_error));
338 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
339 "the connection to [%s]:%s: %s; dropping connection.",
340 csp->http->host_ip_addr_str, service, strerror(errno));
344 /* Connection failed, try next address */
348 freeaddrinfo(result);
351 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s.",
353 return(JB_INVALID_SOCKET);
355 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
356 host, csp->http->host_ip_addr_str, service);
362 #else /* ndef HAVE_RFC2553 */
363 /* Pre-getaddrinfo implementation */
365 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
367 struct sockaddr_in inaddr;
371 struct timeval tv[1];
372 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
377 struct access_control_addr dst[1];
378 #endif /* def FEATURE_ACL */
380 memset((char *)&inaddr, 0, sizeof inaddr);
382 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
384 csp->http->host_ip_addr_str = strdup("unknown");
385 return(JB_INVALID_SOCKET);
389 dst->addr = ntohl(addr);
392 if (block_acl(dst, csp))
399 return(JB_INVALID_SOCKET);
401 #endif /* def FEATURE_ACL */
403 inaddr.sin_addr.s_addr = addr;
404 inaddr.sin_family = AF_INET;
405 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
408 if (sizeof(inaddr.sin_port) == sizeof(short))
409 #endif /* ndef _WIN32 */
411 inaddr.sin_port = htons((unsigned short) portnum);
416 inaddr.sin_port = htonl((unsigned long)portnum);
418 #endif /* ndef _WIN32 */
421 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
423 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
426 return(JB_INVALID_SOCKET);
430 { /* turn off TCP coalescence */
432 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
434 #endif /* def TCP_NODELAY */
436 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
437 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
440 fcntl(fd, F_SETFL, flags);
442 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
444 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
447 if (errno == WSAEINPROGRESS)
449 if (sock_errno() == EINPROGRESS)
450 #else /* ifndef _WIN32 */
451 if (errno == EINPROGRESS)
452 #endif /* ndef _WIN32 || __OS2__ */
458 if (sock_errno() != EINTR)
464 return(JB_INVALID_SOCKET);
468 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
472 fcntl(fd, F_SETFL, flags);
474 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
476 /* wait for connection to complete */
483 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
484 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
487 return(JB_INVALID_SOCKET);
492 #endif /* ndef HAVE_RFC2553 */
495 /*********************************************************************
497 * Function : write_socket
499 * Description : Write the contents of buf (for n bytes) to socket fd.
502 * 1 : fd = file descriptor (aka. handle) of socket to write to.
503 * 2 : buf = pointer to data to be written.
504 * 3 : len = length of data to be written to the socket "fd".
506 * Returns : 0 on success (entire buffer sent).
509 *********************************************************************/
511 int write_socket(jb_socket fd, const char *buf, ssize_t len)
513 int write_socket(jb_socket fd, const char *buf, size_t len)
521 if (len < 0) /* constant condition - size_t isn't ever negative */
526 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
529 return (send(fd, buf, (int)len, 0) != (int)len);
530 #elif defined(__BEOS__) || defined(AMIGA)
531 return (send(fd, buf, len, 0) != len);
532 #elif defined(__OS2__)
534 * Break the data up into SOCKET_SEND_MAX chunks for sending...
535 * OS/2 seemed to complain when the chunks were too large.
537 #define SOCKET_SEND_MAX 65000
539 int send_len, send_rc = 0, i = 0;
540 while ((i < len) && (send_rc != -1))
542 if ((i + SOCKET_SEND_MAX) > len)
545 send_len = SOCKET_SEND_MAX;
546 send_rc = send(fd,(char*)buf + i, send_len, 0);
554 return (write(fd, buf, len) != len);
560 /*********************************************************************
562 * Function : read_socket
564 * Description : Read from a TCP/IP socket in a platform independent way.
567 * 1 : fd = file descriptor of the socket to read
568 * 2 : buf = pointer to buffer where data will be written
569 * Must be >= len bytes long.
570 * 3 : len = maximum number of bytes to read
572 * Returns : On success, the number of bytes read is returned (zero
573 * indicates end of file), and the file position is advanced
574 * by this number. It is not an error if this number is
575 * smaller than the number of bytes requested; this may hap-
576 * pen for example because fewer bytes are actually available
577 * right now (maybe because we were close to end-of-file, or
578 * because we are reading from a pipe, or from a terminal,
579 * or because read() was interrupted by a signal). On error,
580 * -1 is returned, and errno is set appropriately. In this
581 * case it is left unspecified whether the file position (if
584 *********************************************************************/
585 int read_socket(jb_socket fd, char *buf, int len)
595 ret = recv(fd, buf, len, 0);
596 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
597 ret = recv(fd, buf, (size_t)len, 0);
599 ret = (int)read(fd, buf, (size_t)len);
604 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
611 /*********************************************************************
613 * Function : data_is_available
615 * Description : Waits for data to arrive on a socket.
618 * 1 : fd = file descriptor of the socket to read
619 * 2 : seconds_to_wait = number of seconds after which we give up.
621 * Returns : TRUE if data arrived in time,
624 *********************************************************************/
625 int data_is_available(jb_socket fd, int seconds_to_wait)
629 struct timeval timeout;
632 memset(&timeout, 0, sizeof(timeout));
633 timeout.tv_sec = seconds_to_wait;
636 /* Copy and pasted from jcc.c ... */
637 memset(&rfds, 0, sizeof(fd_set));
643 n = select(fd+1, &rfds, NULL, NULL, &timeout);
646 * XXX: Do we care about the different error conditions?
648 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
652 /*********************************************************************
654 * Function : close_socket
656 * Description : Closes a TCP/IP socket
659 * 1 : fd = file descriptor of socket to be closed
663 *********************************************************************/
664 void close_socket(jb_socket fd)
666 #if defined(_WIN32) || defined(__BEOS__)
670 #elif defined(__OS2__)
679 /*********************************************************************
681 * Function : bind_port
683 * Description : Call socket, set socket options, and listen.
684 * Called by listen_loop to "boot up" our proxy address.
687 * 1 : hostnam = TCP/IP address to bind/listen to
688 * 2 : portnum = port to listen on
689 * 3 : pfd = pointer used to return file descriptor.
691 * Returns : if success, returns 0 and sets *pfd.
692 * if failure, returns -3 if address is in use,
693 * -2 if address unresolvable,
695 *********************************************************************/
696 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
699 struct addrinfo hints;
700 struct addrinfo *result, *rp;
702 * XXX: portnum should be a string to allow symbolic service
703 * names in the configuration file and to avoid the following
709 struct sockaddr_in inaddr;
710 #endif /* def HAVE_RFC2553 */
714 #endif /* ndef _WIN32 */
716 *pfd = JB_INVALID_SOCKET;
719 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
720 if ((-1 == retval) || (sizeof(servnam) <= retval))
722 log_error(LOG_LEVEL_ERROR,
723 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
728 memset(&hints, 0, sizeof(struct addrinfo));
732 * XXX: This is a hack. The right thing to do
733 * would be to bind to both AF_INET and AF_INET6.
734 * This will also fail if there is no AF_INET
737 hints.ai_family = AF_INET;
741 hints.ai_family = AF_UNSPEC;
743 hints.ai_socktype = SOCK_STREAM;
744 hints.ai_flags = AI_PASSIVE;
746 hints.ai_flags |= AI_ADDRCONFIG;
748 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
749 hints.ai_canonname = NULL;
750 hints.ai_addr = NULL;
751 hints.ai_next = NULL;
753 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
755 log_error(LOG_LEVEL_ERROR,
756 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
760 memset((char *)&inaddr, '\0', sizeof inaddr);
762 inaddr.sin_family = AF_INET;
763 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
765 if (inaddr.sin_addr.s_addr == INADDR_NONE)
771 if (sizeof(inaddr.sin_port) == sizeof(short))
772 #endif /* ndef _WIN32 */
774 inaddr.sin_port = htons((unsigned short) portnum);
779 inaddr.sin_port = htonl((unsigned long) portnum);
781 #endif /* ndef _WIN32 */
782 #endif /* def HAVE_RFC2553 */
785 for (rp = result; rp != NULL; rp = rp->ai_next)
787 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
789 fd = socket(AF_INET, SOCK_STREAM, 0);
790 #endif /* def HAVE_RFC2553 */
793 if (fd == JB_INVALID_SOCKET)
807 * This is not needed for Win32 - in fact, it stops
808 * duplicate instances of Privoxy from being caught.
810 * On UNIX, we assume the user is sensible enough not
811 * to start Privoxy multiple times on the same IP.
812 * Without this, stopping and restarting Privoxy
813 * from a script fails.
814 * Note: SO_REUSEADDR is meant to only take over
815 * sockets which are *not* in listen state in Linux,
816 * e.g. sockets in TIME_WAIT. YMMV.
818 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
819 #endif /* ndef _WIN32 */
822 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
824 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
828 errno = WSAGetLastError();
829 if (errno == WSAEADDRINUSE)
831 if (errno == EADDRINUSE)
835 freeaddrinfo(result);
852 /* bind() succeeded, escape from for-loop */
854 * XXX: Support multiple listening sockets (e.g. localhost
855 * resolves to AF_INET and AF_INET6, but only the first address
862 freeaddrinfo(result);
865 /* All bind()s failed */
868 #endif /* ndef HAVE_RFC2553 */
870 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
884 /*********************************************************************
886 * Function : get_host_information
888 * Description : Determines the IP address the client used to
889 * reach us and the hostname associated with it.
891 * XXX: Most of the code has been copy and pasted
892 * from accept_connection() and not all of the
893 * ifdefs paths have been tested afterwards.
896 * 1 : afd = File descriptor returned from accept().
897 * 2 : ip_address = Pointer to return the pointer to
898 * the ip address string.
899 * 3 : hostname = Pointer to return the pointer to
900 * the hostname or NULL if the caller
901 * isn't interested in it.
905 *********************************************************************/
906 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
909 struct sockaddr_storage server;
912 struct sockaddr_in server;
913 struct hostent *host = NULL;
914 #endif /* HAVE_RFC2553 */
915 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
916 /* according to accept_connection() this fixes a warning. */
917 int s_length, s_length_provided;
919 socklen_t s_length, s_length_provided;
922 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
923 struct hostent result;
924 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
925 struct hostent_data hdata;
927 char hbuf[HOSTENT_BUFFER_SIZE];
929 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
930 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
931 #endif /* ifndef HAVE_RFC2553 */
932 s_length = s_length_provided = sizeof(server);
934 if (NULL != hostname)
940 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
942 if (s_length > s_length_provided)
944 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
948 *ip_address = malloc(NI_MAXHOST);
949 if (NULL == *ip_address)
951 log_error(LOG_LEVEL_ERROR,
952 "Out of memory while getting the client's IP address.");
955 retval = getnameinfo((struct sockaddr *) &server, s_length,
956 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
959 log_error(LOG_LEVEL_ERROR,
960 "Unable to print my own IP address: %s", gai_strerror(retval));
965 *ip_address = strdup(inet_ntoa(server.sin_addr));
966 #endif /* HAVE_RFC2553 */
967 if (NULL == hostname)
970 * We're done here, the caller isn't
971 * interested in knowing the hostname.
977 *hostname = malloc(NI_MAXHOST);
978 if (NULL == *hostname)
980 log_error(LOG_LEVEL_ERROR,
981 "Out of memory while getting the client's hostname.");
984 retval = getnameinfo((struct sockaddr *) &server, s_length,
985 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
988 log_error(LOG_LEVEL_ERROR,
989 "Unable to resolve my own IP address: %s", gai_strerror(retval));
993 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
994 gethostbyaddr_r((const char *)&server.sin_addr,
995 sizeof(server.sin_addr), AF_INET,
996 &result, hbuf, HOSTENT_BUFFER_SIZE,
998 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
999 host = gethostbyaddr_r((const char *)&server.sin_addr,
1000 sizeof(server.sin_addr), AF_INET,
1001 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1002 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1003 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1004 sizeof(server.sin_addr), AF_INET,
1013 #elif defined(MUTEX_LOCKS_AVAILABLE)
1014 privoxy_mutex_lock(&resolver_mutex);
1015 host = gethostbyaddr((const char *)&server.sin_addr,
1016 sizeof(server.sin_addr), AF_INET);
1017 privoxy_mutex_unlock(&resolver_mutex);
1019 host = gethostbyaddr((const char *)&server.sin_addr,
1020 sizeof(server.sin_addr), AF_INET);
1024 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1028 *hostname = strdup(host->h_name);
1030 #endif /* else def HAVE_RFC2553 */
1037 /*********************************************************************
1039 * Function : accept_connection
1041 * Description : Accepts a connection on a socket. Socket must have
1042 * been created using bind_port().
1045 * 1 : csp = Client state, cfd, ip_addr_str, and
1046 * ip_addr_long will be set by this routine.
1047 * 2 : fd = file descriptor returned from bind_port
1049 * Returns : when a connection is accepted, it returns 1 (TRUE).
1050 * On an error it returns 0 (FALSE).
1052 *********************************************************************/
1053 int accept_connection(struct client_state * csp, jb_socket fd)
1056 /* XXX: client is stored directly into csp->tcp_addr */
1057 #define client (csp->tcp_addr)
1060 struct sockaddr_in client;
1063 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1064 /* Wierdness - fix a warning. */
1070 c_length = sizeof(client);
1073 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1074 if (afd == JB_INVALID_SOCKET)
1081 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1082 struct accept_filter_arg af_options;
1083 bzero(&af_options, sizeof(af_options));
1084 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1085 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1087 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1088 } while (afd < 1 && errno == EINTR);
1097 csp->ip_addr_str = malloc(NI_MAXHOST);
1098 if (NULL == csp->ip_addr_str)
1100 log_error(LOG_LEVEL_ERROR,
1101 "Out of memory while getting the client's IP address.");
1104 retval = getnameinfo((struct sockaddr *) &client, c_length,
1105 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1106 if (!csp->ip_addr_str || retval)
1108 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1109 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1110 freez(csp->ip_addr_str);
1114 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1115 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1116 #endif /* def HAVE_RFC2553 */
1123 /*********************************************************************
1125 * Function : resolve_hostname_to_ip
1127 * Description : Resolve a hostname to an internet tcp/ip address.
1128 * NULL or an empty string resolve to INADDR_ANY.
1131 * 1 : host = hostname to resolve
1133 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1135 *********************************************************************/
1136 unsigned long resolve_hostname_to_ip(const char *host)
1138 struct sockaddr_in inaddr;
1139 struct hostent *hostp;
1140 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1141 struct hostent result;
1142 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1143 char hbuf[HOSTENT_BUFFER_SIZE];
1145 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1146 struct hostent_data hdata;
1147 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1148 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1150 if ((host == NULL) || (*host == '\0'))
1155 memset((char *) &inaddr, 0, sizeof inaddr);
1157 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1159 unsigned int dns_retries = 0;
1160 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1161 while (gethostbyname_r(host, &result, hbuf,
1162 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1163 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1165 log_error(LOG_LEVEL_ERROR,
1166 "Timeout #%u while trying to resolve %s. Trying again.",
1169 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1170 while (NULL == (hostp = gethostbyname_r(host, &result,
1171 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1172 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1174 log_error(LOG_LEVEL_ERROR,
1175 "Timeout #%u while trying to resolve %s. Trying again.",
1178 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1180 * XXX: Doesn't retry in case of soft errors.
1181 * Does this gethostbyname_r version set h_errno?
1183 if (0 == gethostbyname_r(host, &result, &hdata))
1191 #elif defined(MUTEX_LOCKS_AVAILABLE)
1192 privoxy_mutex_lock(&resolver_mutex);
1193 while (NULL == (hostp = gethostbyname(host))
1194 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1196 log_error(LOG_LEVEL_ERROR,
1197 "Timeout #%u while trying to resolve %s. Trying again.",
1200 privoxy_mutex_unlock(&resolver_mutex);
1202 while (NULL == (hostp = gethostbyname(host))
1203 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1205 log_error(LOG_LEVEL_ERROR,
1206 "Timeout #%u while trying to resolve %s. Trying again.",
1209 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1211 * On Mac OSX, if a domain exists but doesn't have a type A
1212 * record associated with it, the h_addr member of the struct
1213 * hostent returned by gethostbyname is NULL, even if h_length
1214 * is 4. Therefore the second test below.
1216 if (hostp == NULL || hostp->h_addr == NULL)
1219 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1220 return(INADDR_NONE);
1222 if (hostp->h_addrtype != AF_INET)
1225 errno = WSAEPROTOTYPE;
1229 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1230 return(INADDR_NONE);
1233 (char *) &inaddr.sin_addr,
1234 (char *) hostp->h_addr,
1235 sizeof(inaddr.sin_addr)
1238 return(inaddr.sin_addr.s_addr);
1243 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1244 /*********************************************************************
1246 * Function : socket_is_still_alive
1248 * Description : Figures out whether or not a socket is still alive.
1251 * 1 : sfd = The socket to check.
1253 * Returns : TRUE for yes, otherwise FALSE.
1255 *********************************************************************/
1256 int socket_is_still_alive(jb_socket sfd)
1259 int no_data_waiting;
1263 struct pollfd poll_fd[1];
1265 memset(poll_fd, 0, sizeof(poll_fd));
1266 poll_fd[0].fd = sfd;
1267 poll_fd[0].events = POLLIN;
1269 poll_result = poll(poll_fd, 1, 0);
1271 if (-1 == poll_result)
1273 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1276 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1278 fd_set readable_fds;
1279 struct timeval timeout;
1282 memset(&timeout, '\0', sizeof(timeout));
1283 FD_ZERO(&readable_fds);
1284 FD_SET(sfd, &readable_fds);
1286 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1289 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1292 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1293 #endif /* def HAVE_POLL */
1295 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1297 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */