1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.104 2011/07/04 17:47:29 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 * XXX: The whole errno overloading is ridiculous and should
152 * be replaced with something sane and thread safe
156 fd = rfc2553_connect_to(host, portnum, csp);
158 fd = no_rfc2553_connect_to(host, portnum, csp);
160 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
161 || (csp->fwd == NULL)
162 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
166 forwarded_connect_retries++;
167 if (csp->config->forwarded_connect_retries != 0)
169 log_error(LOG_LEVEL_ERROR,
170 "Attempt %d of %d to connect to %s failed. Trying again.",
171 forwarded_connect_retries, csp->config->forwarded_connect_retries, host);
174 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
180 /* Getaddrinfo implementation */
181 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
183 struct addrinfo hints, *result, *rp;
188 struct timeval timeout;
189 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
194 * XXX: Initializeing it here is only necessary
195 * because not all situations are properly
198 int socket_error = 0;
201 struct access_control_addr dst[1];
202 #endif /* def FEATURE_ACL */
204 /* Don't leak memory when retrying. */
205 freez(csp->error_message);
206 freez(csp->http->host_ip_addr_str);
208 retval = snprintf(service, sizeof(service), "%d", portnum);
209 if ((-1 == retval) || (sizeof(service) <= retval))
211 log_error(LOG_LEVEL_ERROR,
212 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
214 csp->error_message = strdup("Invalid port number");
215 csp->http->host_ip_addr_str = strdup("unknown");
216 return(JB_INVALID_SOCKET);
219 memset((char *)&hints, 0, sizeof(hints));
220 hints.ai_family = AF_UNSPEC;
221 hints.ai_socktype = SOCK_STREAM;
222 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
224 hints.ai_flags |= AI_ADDRCONFIG;
226 if ((retval = getaddrinfo(host, service, &hints, &result)))
228 log_error(LOG_LEVEL_INFO,
229 "Can not resolve %s: %s", host, gai_strerror(retval));
230 /* XXX: Should find a better way to propagate this error. */
232 csp->error_message = strdup(gai_strerror(retval));
233 csp->http->host_ip_addr_str = strdup("unknown");
234 return(JB_INVALID_SOCKET);
237 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
238 if (NULL == csp->http->host_ip_addr_str)
240 freeaddrinfo(result);
241 log_error(LOG_LEVEL_ERROR,
242 "Out of memory while getting the server IP address.");
243 return JB_INVALID_SOCKET;
246 for (rp = result; rp != NULL; rp = rp->ai_next)
250 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
252 if (block_acl(dst, csp))
255 socket_error = errno = SOCEPERM;
257 socket_error = errno = EPERM;
261 #endif /* def FEATURE_ACL */
263 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
264 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
267 log_error(LOG_LEVEL_ERROR,
268 "Failed to get the host name from the socket structure: %s",
269 gai_strerror(retval));
273 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
275 if (fd == JB_INVALID_SOCKET)
284 { /* turn off TCP coalescence */
286 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
288 #endif /* def TCP_NODELAY */
290 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
291 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
294 fcntl(fd, F_SETFL, flags);
296 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
299 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
302 errno = sock_errno();
306 if (errno == WSAEINPROGRESS)
307 #else /* ifndef _WIN32 */
308 if (errno == EINPROGRESS)
309 #endif /* ndef _WIN32 || __OS2__ */
326 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
330 fcntl(fd, F_SETFL, flags);
332 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
334 /* wait for connection to complete */
338 memset(&timeout, 0, sizeof(timeout));
341 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
342 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
343 && FD_ISSET(fd, &wfds))
345 socklen_t optlen = sizeof(socket_error);
346 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
350 /* Connection established, no need to try other addresses. */
353 if (rp->ai_next != NULL)
356 * There's another address we can try, so log that this
357 * one didn't work out. If the last one fails, too,
358 * it will get logged outside the loop body so we don't
359 * have to mention it here.
361 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
362 csp->http->host_ip_addr_str, service, strerror(socket_error));
367 socket_error = errno;
368 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
369 "the connection to [%s]:%s: %s; dropping connection.",
370 csp->http->host_ip_addr_str, service, strerror(errno));
374 /* Connection failed, try next address */
378 freeaddrinfo(result);
381 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
382 host, service, strerror(socket_error));
383 csp->error_message = strdup(strerror(socket_error));
384 return(JB_INVALID_SOCKET);
386 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
387 host, csp->http->host_ip_addr_str, service);
393 #else /* ndef HAVE_RFC2553 */
394 /* Pre-getaddrinfo implementation */
396 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
398 struct sockaddr_in inaddr;
402 struct timeval tv[1];
403 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
408 struct access_control_addr dst[1];
409 #endif /* def FEATURE_ACL */
411 /* Don't leak memory when retrying. */
412 freez(csp->http->host_ip_addr_str);
414 memset((char *)&inaddr, 0, sizeof inaddr);
416 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
418 csp->http->host_ip_addr_str = strdup("unknown");
419 return(JB_INVALID_SOCKET);
423 dst->addr = ntohl(addr);
426 if (block_acl(dst, csp))
433 return(JB_INVALID_SOCKET);
435 #endif /* def FEATURE_ACL */
437 inaddr.sin_addr.s_addr = addr;
438 inaddr.sin_family = AF_INET;
439 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
442 if (sizeof(inaddr.sin_port) == sizeof(short))
443 #endif /* ndef _WIN32 */
445 inaddr.sin_port = htons((unsigned short) portnum);
450 inaddr.sin_port = htonl((unsigned long)portnum);
452 #endif /* ndef _WIN32 */
454 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
456 if (fd == JB_INVALID_SOCKET)
461 return(JB_INVALID_SOCKET);
465 { /* turn off TCP coalescence */
467 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
469 #endif /* def TCP_NODELAY */
471 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
472 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
475 fcntl(fd, F_SETFL, flags);
477 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
479 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
482 if (errno == WSAEINPROGRESS)
484 if (sock_errno() == EINPROGRESS)
485 #else /* ifndef _WIN32 */
486 if (errno == EINPROGRESS)
487 #endif /* ndef _WIN32 || __OS2__ */
493 if (sock_errno() != EINTR)
499 return(JB_INVALID_SOCKET);
503 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
507 fcntl(fd, F_SETFL, flags);
509 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
511 /* wait for connection to complete */
518 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
519 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
522 return(JB_INVALID_SOCKET);
527 #endif /* ndef HAVE_RFC2553 */
530 /*********************************************************************
532 * Function : write_socket
534 * Description : Write the contents of buf (for n bytes) to socket fd.
537 * 1 : fd = file descriptor (aka. handle) of socket to write to.
538 * 2 : buf = pointer to data to be written.
539 * 3 : len = length of data to be written to the socket "fd".
541 * Returns : 0 on success (entire buffer sent).
544 *********************************************************************/
546 int write_socket(jb_socket fd, const char *buf, ssize_t len)
548 int write_socket(jb_socket fd, const char *buf, size_t len)
556 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
559 return (send(fd, buf, (int)len, 0) != (int)len);
560 #elif defined(__BEOS__) || defined(AMIGA)
561 return (send(fd, buf, len, 0) != len);
562 #elif defined(__OS2__)
564 * Break the data up into SOCKET_SEND_MAX chunks for sending...
565 * OS/2 seemed to complain when the chunks were too large.
567 #define SOCKET_SEND_MAX 65000
569 int send_len, send_rc = 0, i = 0;
570 while ((i < len) && (send_rc != -1))
572 if ((i + SOCKET_SEND_MAX) > len)
575 send_len = SOCKET_SEND_MAX;
576 send_rc = send(fd,(char*)buf + i, send_len, 0);
584 return (write(fd, buf, len) != len);
590 /*********************************************************************
592 * Function : read_socket
594 * Description : Read from a TCP/IP socket in a platform independent way.
597 * 1 : fd = file descriptor of the socket to read
598 * 2 : buf = pointer to buffer where data will be written
599 * Must be >= len bytes long.
600 * 3 : len = maximum number of bytes to read
602 * Returns : On success, the number of bytes read is returned (zero
603 * indicates end of file), and the file position is advanced
604 * by this number. It is not an error if this number is
605 * smaller than the number of bytes requested; this may hap-
606 * pen for example because fewer bytes are actually available
607 * right now (maybe because we were close to end-of-file, or
608 * because we are reading from a pipe, or from a terminal,
609 * or because read() was interrupted by a signal). On error,
610 * -1 is returned, and errno is set appropriately. In this
611 * case it is left unspecified whether the file position (if
614 *********************************************************************/
615 int read_socket(jb_socket fd, char *buf, int len)
625 ret = recv(fd, buf, len, 0);
626 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
627 ret = recv(fd, buf, (size_t)len, 0);
629 ret = (int)read(fd, buf, (size_t)len);
634 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
641 /*********************************************************************
643 * Function : data_is_available
645 * Description : Waits for data to arrive on a socket.
648 * 1 : fd = file descriptor of the socket to read
649 * 2 : seconds_to_wait = number of seconds after which we give up.
651 * Returns : TRUE if data arrived in time,
654 *********************************************************************/
655 int data_is_available(jb_socket fd, int seconds_to_wait)
659 struct timeval timeout;
662 memset(&timeout, 0, sizeof(timeout));
663 timeout.tv_sec = seconds_to_wait;
666 /* Copy and pasted from jcc.c ... */
667 memset(&rfds, 0, sizeof(fd_set));
673 n = select(fd+1, &rfds, NULL, NULL, &timeout);
676 * XXX: Do we care about the different error conditions?
678 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
682 /*********************************************************************
684 * Function : close_socket
686 * Description : Closes a TCP/IP socket
689 * 1 : fd = file descriptor of socket to be closed
693 *********************************************************************/
694 void close_socket(jb_socket fd)
696 #if defined(_WIN32) || defined(__BEOS__)
700 #elif defined(__OS2__)
709 /*********************************************************************
711 * Function : bind_port
713 * Description : Call socket, set socket options, and listen.
714 * Called by listen_loop to "boot up" our proxy address.
717 * 1 : hostnam = TCP/IP address to bind/listen to
718 * 2 : portnum = port to listen on
719 * 3 : pfd = pointer used to return file descriptor.
721 * Returns : if success, returns 0 and sets *pfd.
722 * if failure, returns -3 if address is in use,
723 * -2 if address unresolvable,
725 *********************************************************************/
726 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
729 struct addrinfo hints;
730 struct addrinfo *result, *rp;
732 * XXX: portnum should be a string to allow symbolic service
733 * names in the configuration file and to avoid the following
739 struct sockaddr_in inaddr;
740 #endif /* def HAVE_RFC2553 */
744 #endif /* ndef _WIN32 */
746 *pfd = JB_INVALID_SOCKET;
749 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
750 if ((-1 == retval) || (sizeof(servnam) <= retval))
752 log_error(LOG_LEVEL_ERROR,
753 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
758 memset(&hints, 0, sizeof(struct addrinfo));
762 * XXX: This is a hack. The right thing to do
763 * would be to bind to both AF_INET and AF_INET6.
764 * This will also fail if there is no AF_INET
767 hints.ai_family = AF_INET;
771 hints.ai_family = AF_UNSPEC;
773 hints.ai_socktype = SOCK_STREAM;
774 hints.ai_flags = AI_PASSIVE;
775 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
776 hints.ai_canonname = NULL;
777 hints.ai_addr = NULL;
778 hints.ai_next = NULL;
780 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
782 log_error(LOG_LEVEL_ERROR,
783 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
787 memset((char *)&inaddr, '\0', sizeof inaddr);
789 inaddr.sin_family = AF_INET;
790 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
792 if (inaddr.sin_addr.s_addr == INADDR_NONE)
798 if (sizeof(inaddr.sin_port) == sizeof(short))
799 #endif /* ndef _WIN32 */
801 inaddr.sin_port = htons((unsigned short) portnum);
806 inaddr.sin_port = htonl((unsigned long) portnum);
808 #endif /* ndef _WIN32 */
809 #endif /* def HAVE_RFC2553 */
812 for (rp = result; rp != NULL; rp = rp->ai_next)
814 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
816 fd = socket(AF_INET, SOCK_STREAM, 0);
817 #endif /* def HAVE_RFC2553 */
820 if (fd == JB_INVALID_SOCKET)
834 * This is not needed for Win32 - in fact, it stops
835 * duplicate instances of Privoxy from being caught.
837 * On UNIX, we assume the user is sensible enough not
838 * to start Privoxy multiple times on the same IP.
839 * Without this, stopping and restarting Privoxy
840 * from a script fails.
841 * Note: SO_REUSEADDR is meant to only take over
842 * sockets which are *not* in listen state in Linux,
843 * e.g. sockets in TIME_WAIT. YMMV.
845 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
846 #endif /* ndef _WIN32 */
849 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
851 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
855 errno = WSAGetLastError();
856 if (errno == WSAEADDRINUSE)
858 if (errno == EADDRINUSE)
862 freeaddrinfo(result);
879 /* bind() succeeded, escape from for-loop */
881 * XXX: Support multiple listening sockets (e.g. localhost
882 * resolves to AF_INET and AF_INET6, but only the first address
889 freeaddrinfo(result);
892 /* All bind()s failed */
895 #endif /* ndef HAVE_RFC2553 */
897 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
911 /*********************************************************************
913 * Function : get_host_information
915 * Description : Determines the IP address the client used to
916 * reach us and the hostname associated with it.
918 * XXX: Most of the code has been copy and pasted
919 * from accept_connection() and not all of the
920 * ifdefs paths have been tested afterwards.
923 * 1 : afd = File descriptor returned from accept().
924 * 2 : ip_address = Pointer to return the pointer to
925 * the ip address string.
926 * 3 : port = Pointer to return the pointer to
927 * the TCP port string.
928 * 4 : hostname = Pointer to return the pointer to
929 * the hostname or NULL if the caller
930 * isn't interested in it.
934 *********************************************************************/
935 void get_host_information(jb_socket afd, char **ip_address, char **port,
939 struct sockaddr_storage server;
942 struct sockaddr_in server;
943 struct hostent *host = NULL;
944 #endif /* HAVE_RFC2553 */
945 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
946 /* according to accept_connection() this fixes a warning. */
947 int s_length, s_length_provided;
949 socklen_t s_length, s_length_provided;
952 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
953 struct hostent result;
954 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
955 struct hostent_data hdata;
957 char hbuf[HOSTENT_BUFFER_SIZE];
959 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
960 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
961 #endif /* ifndef HAVE_RFC2553 */
962 s_length = s_length_provided = sizeof(server);
964 if (NULL != hostname)
971 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
973 if (s_length > s_length_provided)
975 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
978 *port = malloc(NI_MAXSERV);
981 log_error(LOG_LEVEL_ERROR,
982 "Out of memory while getting the client's port.");
986 *ip_address = malloc(NI_MAXHOST);
987 if (NULL == *ip_address)
989 log_error(LOG_LEVEL_ERROR,
990 "Out of memory while getting the client's IP address.");
994 retval = getnameinfo((struct sockaddr *) &server, s_length,
995 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
996 NI_NUMERICHOST|NI_NUMERICSERV);
999 log_error(LOG_LEVEL_ERROR,
1000 "Unable to print my own IP address: %s", gai_strerror(retval));
1006 *ip_address = strdup(inet_ntoa(server.sin_addr));
1007 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1008 *port[NI_MAXSERV - 1] = '\0';
1009 #endif /* HAVE_RFC2553 */
1010 if (NULL == hostname)
1013 * We're done here, the caller isn't
1014 * interested in knowing the hostname.
1020 *hostname = malloc(NI_MAXHOST);
1021 if (NULL == *hostname)
1023 log_error(LOG_LEVEL_ERROR,
1024 "Out of memory while getting the client's hostname.");
1027 retval = getnameinfo((struct sockaddr *) &server, s_length,
1028 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1031 log_error(LOG_LEVEL_ERROR,
1032 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1036 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1037 gethostbyaddr_r((const char *)&server.sin_addr,
1038 sizeof(server.sin_addr), AF_INET,
1039 &result, hbuf, HOSTENT_BUFFER_SIZE,
1041 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1042 host = gethostbyaddr_r((const char *)&server.sin_addr,
1043 sizeof(server.sin_addr), AF_INET,
1044 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1045 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1046 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1047 sizeof(server.sin_addr), AF_INET,
1056 #elif defined(MUTEX_LOCKS_AVAILABLE)
1057 privoxy_mutex_lock(&resolver_mutex);
1058 host = gethostbyaddr((const char *)&server.sin_addr,
1059 sizeof(server.sin_addr), AF_INET);
1060 privoxy_mutex_unlock(&resolver_mutex);
1062 host = gethostbyaddr((const char *)&server.sin_addr,
1063 sizeof(server.sin_addr), AF_INET);
1067 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1071 *hostname = strdup(host->h_name);
1073 #endif /* else def HAVE_RFC2553 */
1080 /*********************************************************************
1082 * Function : accept_connection
1084 * Description : Accepts a connection on one of more socket. Sockets
1085 * must have been created using bind_port().
1088 * 1 : csp = Client state, cfd, ip_addr_str, and
1089 * ip_addr_long will be set by this routine.
1090 * 2 : fds = File descriptors returned from bind_port
1092 * Returns : when a connection is accepted, it returns 1 (TRUE).
1093 * On an error it returns 0 (FALSE).
1095 *********************************************************************/
1096 int accept_connection(struct client_state * csp, jb_socket fds[])
1099 /* XXX: client is stored directly into csp->tcp_addr */
1100 #define client (csp->tcp_addr)
1102 struct sockaddr_in client;
1105 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1106 /* Wierdness - fix a warning. */
1113 int max_selected_socket;
1114 fd_set selected_fds;
1117 c_length = sizeof(client);
1119 /* Wait for a connection on any socket. Return immediately if no socket is
1121 FD_ZERO(&selected_fds);
1122 max_selected_socket = 0;
1123 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1125 if (JB_INVALID_SOCKET != fds[i])
1127 FD_SET(fds[i], &selected_fds);
1128 if (max_selected_socket < fds[i] + 1)
1130 max_selected_socket = fds[i] + 1;
1134 if (0 == max_selected_socket)
1140 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1141 } while (retval < 0 && errno == EINTR);
1146 log_error(LOG_LEVEL_ERROR,
1147 "Waiting on new client failed because select(2) returned 0."
1148 " This should not happen.");
1152 log_error(LOG_LEVEL_ERROR,
1153 "Waiting on new client failed because of problems in select(2): "
1154 "%s.", strerror(errno));
1158 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1160 if (i >= MAX_LISTENING_SOCKETS)
1162 log_error(LOG_LEVEL_ERROR,
1163 "select(2) reported connected clients (number = %u, "
1164 "descriptor boundary = %u), but none found.",
1165 retval, max_selected_socket);
1170 /* Accept selected connection */
1172 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1173 if (afd == JB_INVALID_SOCKET)
1180 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1181 struct accept_filter_arg af_options;
1182 bzero(&af_options, sizeof(af_options));
1183 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1184 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1186 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1187 } while (afd < 1 && errno == EINTR);
1196 csp->ip_addr_str = malloc(NI_MAXHOST);
1197 if (NULL == csp->ip_addr_str)
1199 log_error(LOG_LEVEL_ERROR,
1200 "Out of memory while getting the client's IP address.");
1203 retval = getnameinfo((struct sockaddr *) &client, c_length,
1204 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1205 if (!csp->ip_addr_str || retval)
1207 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1208 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1209 freez(csp->ip_addr_str);
1213 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1214 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1215 #endif /* def HAVE_RFC2553 */
1222 /*********************************************************************
1224 * Function : resolve_hostname_to_ip
1226 * Description : Resolve a hostname to an internet tcp/ip address.
1227 * NULL or an empty string resolve to INADDR_ANY.
1230 * 1 : host = hostname to resolve
1232 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1234 *********************************************************************/
1235 unsigned long resolve_hostname_to_ip(const char *host)
1237 struct sockaddr_in inaddr;
1238 struct hostent *hostp;
1239 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1240 struct hostent result;
1241 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1242 char hbuf[HOSTENT_BUFFER_SIZE];
1244 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1245 struct hostent_data hdata;
1246 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1247 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1249 if ((host == NULL) || (*host == '\0'))
1254 memset((char *) &inaddr, 0, sizeof inaddr);
1256 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1258 unsigned int dns_retries = 0;
1259 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1260 while (gethostbyname_r(host, &result, hbuf,
1261 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1262 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1264 log_error(LOG_LEVEL_ERROR,
1265 "Timeout #%u while trying to resolve %s. Trying again.",
1268 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1269 while (NULL == (hostp = gethostbyname_r(host, &result,
1270 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1271 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1273 log_error(LOG_LEVEL_ERROR,
1274 "Timeout #%u while trying to resolve %s. Trying again.",
1277 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1279 * XXX: Doesn't retry in case of soft errors.
1280 * Does this gethostbyname_r version set h_errno?
1282 if (0 == gethostbyname_r(host, &result, &hdata))
1290 #elif defined(MUTEX_LOCKS_AVAILABLE)
1291 privoxy_mutex_lock(&resolver_mutex);
1292 while (NULL == (hostp = gethostbyname(host))
1293 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1295 log_error(LOG_LEVEL_ERROR,
1296 "Timeout #%u while trying to resolve %s. Trying again.",
1299 privoxy_mutex_unlock(&resolver_mutex);
1301 while (NULL == (hostp = gethostbyname(host))
1302 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1304 log_error(LOG_LEVEL_ERROR,
1305 "Timeout #%u while trying to resolve %s. Trying again.",
1308 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1310 * On Mac OSX, if a domain exists but doesn't have a type A
1311 * record associated with it, the h_addr member of the struct
1312 * hostent returned by gethostbyname is NULL, even if h_length
1313 * is 4. Therefore the second test below.
1315 if (hostp == NULL || hostp->h_addr == NULL)
1318 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1319 return(INADDR_NONE);
1321 if (hostp->h_addrtype != AF_INET)
1324 errno = WSAEPROTOTYPE;
1328 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1329 return(INADDR_NONE);
1332 (char *) &inaddr.sin_addr,
1333 (char *) hostp->h_addr,
1334 sizeof(inaddr.sin_addr)
1337 return(inaddr.sin_addr.s_addr);
1342 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1343 /*********************************************************************
1345 * Function : socket_is_still_alive
1347 * Description : Figures out whether or not a socket is still alive.
1350 * 1 : sfd = The socket to check.
1352 * Returns : TRUE for yes, otherwise FALSE.
1354 *********************************************************************/
1355 int socket_is_still_alive(jb_socket sfd)
1358 int no_data_waiting;
1362 struct pollfd poll_fd[1];
1364 memset(poll_fd, 0, sizeof(poll_fd));
1365 poll_fd[0].fd = sfd;
1366 poll_fd[0].events = POLLIN;
1368 poll_result = poll(poll_fd, 1, 0);
1370 if (-1 == poll_result)
1372 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1375 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1377 fd_set readable_fds;
1378 struct timeval timeout;
1381 memset(&timeout, '\0', sizeof(timeout));
1382 FD_ZERO(&readable_fds);
1383 FD_SET(sfd, &readable_fds);
1385 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1388 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1391 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1392 #endif /* def HAVE_POLL */
1394 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1396 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */