1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.115 2012/10/12 11:17:48 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 + 1, 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__ */
316 socket_error = errno;
327 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
331 fcntl(fd, F_SETFL, flags);
333 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
335 /* wait for connection to complete */
339 memset(&timeout, 0, sizeof(timeout));
342 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
343 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
344 && FD_ISSET(fd, &wfds))
346 socklen_t optlen = sizeof(socket_error);
347 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
351 /* Connection established, no need to try other addresses. */
354 if (rp->ai_next != NULL)
357 * There's another address we can try, so log that this
358 * one didn't work out. If the last one fails, too,
359 * it will get logged outside the loop body so we don't
360 * have to mention it here.
362 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
363 csp->http->host_ip_addr_str, service, strerror(socket_error));
368 socket_error = errno;
369 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
370 "the connection to [%s]:%s: %s; dropping connection.",
371 csp->http->host_ip_addr_str, service, strerror(errno));
375 /* Connection failed, try next address */
379 freeaddrinfo(result);
382 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
383 host, service, strerror(socket_error));
384 csp->error_message = strdup(strerror(socket_error));
385 return(JB_INVALID_SOCKET);
387 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
388 host, csp->http->host_ip_addr_str, service);
394 #else /* ndef HAVE_RFC2553 */
395 /* Pre-getaddrinfo implementation */
397 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
399 struct sockaddr_in inaddr;
403 struct timeval tv[1];
404 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
409 struct access_control_addr dst[1];
410 #endif /* def FEATURE_ACL */
412 /* Don't leak memory when retrying. */
413 freez(csp->http->host_ip_addr_str);
415 memset((char *)&inaddr, 0, sizeof inaddr);
417 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
419 csp->http->host_ip_addr_str = strdup("unknown");
420 return(JB_INVALID_SOCKET);
424 dst->addr = ntohl(addr);
427 if (block_acl(dst, csp))
434 return(JB_INVALID_SOCKET);
436 #endif /* def FEATURE_ACL */
438 inaddr.sin_addr.s_addr = addr;
439 inaddr.sin_family = AF_INET;
440 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
443 if (sizeof(inaddr.sin_port) == sizeof(short))
444 #endif /* ndef _WIN32 */
446 inaddr.sin_port = htons((unsigned short) portnum);
451 inaddr.sin_port = htonl((unsigned long)portnum);
453 #endif /* ndef _WIN32 */
455 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
457 if (fd == JB_INVALID_SOCKET)
462 return(JB_INVALID_SOCKET);
466 { /* turn off TCP coalescence */
468 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
470 #endif /* def TCP_NODELAY */
472 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
473 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
476 fcntl(fd, F_SETFL, flags);
478 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
480 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
483 if (errno == WSAEINPROGRESS)
485 if (sock_errno() == EINPROGRESS)
486 #else /* ifndef _WIN32 */
487 if (errno == EINPROGRESS)
488 #endif /* ndef _WIN32 || __OS2__ */
494 if (sock_errno() != EINTR)
500 return(JB_INVALID_SOCKET);
504 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
508 fcntl(fd, F_SETFL, flags);
510 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
512 /* wait for connection to complete */
519 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
520 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
523 return(JB_INVALID_SOCKET);
528 #endif /* ndef HAVE_RFC2553 */
531 /*********************************************************************
533 * Function : write_socket
535 * Description : Write the contents of buf (for n bytes) to socket fd.
538 * 1 : fd = file descriptor (aka. handle) of socket to write to.
539 * 2 : buf = pointer to data to be written.
540 * 3 : len = length of data to be written to the socket "fd".
542 * Returns : 0 on success (entire buffer sent).
545 *********************************************************************/
547 int write_socket(jb_socket fd, const char *buf, ssize_t len)
549 int write_socket(jb_socket fd, const char *buf, size_t len)
557 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
560 return (send(fd, buf, (int)len, 0) != (int)len);
561 #elif defined(__BEOS__) || defined(AMIGA)
562 return (send(fd, buf, len, 0) != len);
563 #elif defined(__OS2__)
565 * Break the data up into SOCKET_SEND_MAX chunks for sending...
566 * OS/2 seemed to complain when the chunks were too large.
568 #define SOCKET_SEND_MAX 65000
570 int send_len, send_rc = 0, i = 0;
571 while ((i < len) && (send_rc != -1))
573 if ((i + SOCKET_SEND_MAX) > len)
576 send_len = SOCKET_SEND_MAX;
577 send_rc = send(fd,(char*)buf + i, send_len, 0);
585 return (write(fd, buf, len) != len);
591 /*********************************************************************
593 * Function : read_socket
595 * Description : Read from a TCP/IP socket in a platform independent way.
598 * 1 : fd = file descriptor of the socket to read
599 * 2 : buf = pointer to buffer where data will be written
600 * Must be >= len bytes long.
601 * 3 : len = maximum number of bytes to read
603 * Returns : On success, the number of bytes read is returned (zero
604 * indicates end of file), and the file position is advanced
605 * by this number. It is not an error if this number is
606 * smaller than the number of bytes requested; this may hap-
607 * pen for example because fewer bytes are actually available
608 * right now (maybe because we were close to end-of-file, or
609 * because we are reading from a pipe, or from a terminal,
610 * or because read() was interrupted by a signal). On error,
611 * -1 is returned, and errno is set appropriately. In this
612 * case it is left unspecified whether the file position (if
615 *********************************************************************/
616 int read_socket(jb_socket fd, char *buf, int len)
626 ret = recv(fd, buf, len, 0);
627 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
628 ret = recv(fd, buf, (size_t)len, 0);
630 ret = (int)read(fd, buf, (size_t)len);
635 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
642 /*********************************************************************
644 * Function : data_is_available
646 * Description : Waits for data to arrive on a socket.
649 * 1 : fd = file descriptor of the socket to read
650 * 2 : seconds_to_wait = number of seconds after which we give up.
652 * Returns : TRUE if data arrived in time,
655 *********************************************************************/
656 int data_is_available(jb_socket fd, int seconds_to_wait)
660 struct timeval timeout;
663 memset(&timeout, 0, sizeof(timeout));
664 timeout.tv_sec = seconds_to_wait;
667 /* Copy and pasted from jcc.c ... */
668 memset(&rfds, 0, sizeof(fd_set));
674 n = select(fd+1, &rfds, NULL, NULL, &timeout);
677 * XXX: Do we care about the different error conditions?
679 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
683 /*********************************************************************
685 * Function : close_socket
687 * Description : Closes a TCP/IP socket
690 * 1 : fd = file descriptor of socket to be closed
694 *********************************************************************/
695 void close_socket(jb_socket fd)
697 #if defined(_WIN32) || defined(__BEOS__)
701 #elif defined(__OS2__)
709 /*********************************************************************
711 * Function : drain_and_close_socket
713 * Description : Closes a TCP/IP socket after draining unread data
716 * 1 : fd = file descriptor of the socket to be closed
720 *********************************************************************/
721 void drain_and_close_socket(jb_socket fd)
723 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
724 if (socket_is_still_alive(fd))
727 int bytes_drained_total = 0;
731 /* Apparently Windows has shutdown() but not SHUT_WR. */
735 if (0 != shutdown(fd, SHUT_WR))
737 log_error(LOG_LEVEL_ERROR, "Failed to shutdown socket %d %E", fd);
740 #define ARBITRARY_DRAIN_LIMIT 10000
745 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
746 if (bytes_drained < 0)
748 log_error(LOG_LEVEL_ERROR, "Failed to drain socket %d %E", fd);
750 else if (bytes_drained > 0)
752 bytes_drained_total += bytes_drained;
753 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
755 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
759 } while (bytes_drained > 0);
760 if (bytes_drained_total != 0)
762 log_error(LOG_LEVEL_CONNECT,
763 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
772 /*********************************************************************
774 * Function : bind_port
776 * Description : Call socket, set socket options, and listen.
777 * Called by listen_loop to "boot up" our proxy address.
780 * 1 : hostnam = TCP/IP address to bind/listen to
781 * 2 : portnum = port to listen on
782 * 3 : pfd = pointer used to return file descriptor.
784 * Returns : if success, returns 0 and sets *pfd.
785 * if failure, returns -3 if address is in use,
786 * -2 if address unresolvable,
788 *********************************************************************/
789 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
792 struct addrinfo hints;
793 struct addrinfo *result, *rp;
795 * XXX: portnum should be a string to allow symbolic service
796 * names in the configuration file and to avoid the following
802 struct sockaddr_in inaddr;
803 #endif /* def HAVE_RFC2553 */
807 #endif /* ndef _WIN32 */
809 *pfd = JB_INVALID_SOCKET;
812 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
813 if ((-1 == retval) || (sizeof(servnam) <= retval))
815 log_error(LOG_LEVEL_ERROR,
816 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
821 memset(&hints, 0, sizeof(struct addrinfo));
825 * XXX: This is a hack. The right thing to do
826 * would be to bind to both AF_INET and AF_INET6.
827 * This will also fail if there is no AF_INET
830 hints.ai_family = AF_INET;
834 hints.ai_family = AF_UNSPEC;
836 hints.ai_socktype = SOCK_STREAM;
837 hints.ai_flags = AI_PASSIVE;
838 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
839 hints.ai_canonname = NULL;
840 hints.ai_addr = NULL;
841 hints.ai_next = NULL;
843 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
845 log_error(LOG_LEVEL_ERROR,
846 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
850 memset((char *)&inaddr, '\0', sizeof inaddr);
852 inaddr.sin_family = AF_INET;
853 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
855 if (inaddr.sin_addr.s_addr == INADDR_NONE)
861 if (sizeof(inaddr.sin_port) == sizeof(short))
862 #endif /* ndef _WIN32 */
864 inaddr.sin_port = htons((unsigned short) portnum);
869 inaddr.sin_port = htonl((unsigned long) portnum);
871 #endif /* ndef _WIN32 */
872 #endif /* def HAVE_RFC2553 */
875 for (rp = result; rp != NULL; rp = rp->ai_next)
877 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
879 fd = socket(AF_INET, SOCK_STREAM, 0);
880 #endif /* def HAVE_RFC2553 */
883 if (fd == JB_INVALID_SOCKET)
897 * This is not needed for Win32 - in fact, it stops
898 * duplicate instances of Privoxy from being caught.
900 * On UNIX, we assume the user is sensible enough not
901 * to start Privoxy multiple times on the same IP.
902 * Without this, stopping and restarting Privoxy
903 * from a script fails.
904 * Note: SO_REUSEADDR is meant to only take over
905 * sockets which are *not* in listen state in Linux,
906 * e.g. sockets in TIME_WAIT. YMMV.
908 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
909 #endif /* ndef _WIN32 */
912 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
914 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
918 errno = WSAGetLastError();
919 if (errno == WSAEADDRINUSE)
921 if (errno == EADDRINUSE)
925 freeaddrinfo(result);
942 /* bind() succeeded, escape from for-loop */
944 * XXX: Support multiple listening sockets (e.g. localhost
945 * resolves to AF_INET and AF_INET6, but only the first address
952 freeaddrinfo(result);
955 /* All bind()s failed */
958 #endif /* ndef HAVE_RFC2553 */
960 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
974 /*********************************************************************
976 * Function : get_host_information
978 * Description : Determines the IP address the client used to
979 * reach us and the hostname associated with it.
981 * XXX: Most of the code has been copy and pasted
982 * from accept_connection() and not all of the
983 * ifdefs paths have been tested afterwards.
986 * 1 : afd = File descriptor returned from accept().
987 * 2 : ip_address = Pointer to return the pointer to
988 * the ip address string.
989 * 3 : port = Pointer to return the pointer to
990 * the TCP port string.
991 * 4 : hostname = Pointer to return the pointer to
992 * the hostname or NULL if the caller
993 * isn't interested in it.
997 *********************************************************************/
998 void get_host_information(jb_socket afd, char **ip_address, char **port,
1002 struct sockaddr_storage server;
1005 struct sockaddr_in server;
1006 struct hostent *host = NULL;
1007 #endif /* HAVE_RFC2553 */
1008 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1009 /* according to accept_connection() this fixes a warning. */
1010 int s_length, s_length_provided;
1012 socklen_t s_length, s_length_provided;
1014 #ifndef HAVE_RFC2553
1015 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1016 struct hostent result;
1017 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1018 struct hostent_data hdata;
1020 char hbuf[HOSTENT_BUFFER_SIZE];
1022 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1023 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1024 #endif /* ifndef HAVE_RFC2553 */
1025 s_length = s_length_provided = sizeof(server);
1027 if (NULL != hostname)
1034 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1036 if (s_length > s_length_provided)
1038 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1042 * XXX: Workaround for missing header on Windows when
1043 * configured with --disable-ipv6-support.
1044 * The proper fix is to not use NI_MAXSERV in
1045 * that case. It works by accident on other platforms
1046 * as <netdb.h> in included unconditionally there.
1049 #define NI_MAXSERV 32
1051 *port = malloc(NI_MAXSERV);
1054 log_error(LOG_LEVEL_ERROR,
1055 "Out of memory while getting the client's port.");
1059 *ip_address = malloc(NI_MAXHOST);
1060 if (NULL == *ip_address)
1062 log_error(LOG_LEVEL_ERROR,
1063 "Out of memory while getting the client's IP address.");
1067 retval = getnameinfo((struct sockaddr *) &server, s_length,
1068 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1069 NI_NUMERICHOST|NI_NUMERICSERV);
1072 log_error(LOG_LEVEL_ERROR,
1073 "Unable to print my own IP address: %s", gai_strerror(retval));
1079 *ip_address = strdup(inet_ntoa(server.sin_addr));
1080 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1081 #endif /* HAVE_RFC2553 */
1082 if (NULL == hostname)
1085 * We're done here, the caller isn't
1086 * interested in knowing the hostname.
1092 *hostname = malloc(NI_MAXHOST);
1093 if (NULL == *hostname)
1095 log_error(LOG_LEVEL_ERROR,
1096 "Out of memory while getting the client's hostname.");
1099 retval = getnameinfo((struct sockaddr *) &server, s_length,
1100 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1103 log_error(LOG_LEVEL_ERROR,
1104 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1108 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1109 gethostbyaddr_r((const char *)&server.sin_addr,
1110 sizeof(server.sin_addr), AF_INET,
1111 &result, hbuf, HOSTENT_BUFFER_SIZE,
1113 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1114 host = gethostbyaddr_r((const char *)&server.sin_addr,
1115 sizeof(server.sin_addr), AF_INET,
1116 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1117 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1118 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1119 sizeof(server.sin_addr), AF_INET,
1128 #elif defined(MUTEX_LOCKS_AVAILABLE)
1129 privoxy_mutex_lock(&resolver_mutex);
1130 host = gethostbyaddr((const char *)&server.sin_addr,
1131 sizeof(server.sin_addr), AF_INET);
1132 privoxy_mutex_unlock(&resolver_mutex);
1134 host = gethostbyaddr((const char *)&server.sin_addr,
1135 sizeof(server.sin_addr), AF_INET);
1139 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1143 *hostname = strdup(host->h_name);
1145 #endif /* else def HAVE_RFC2553 */
1152 /*********************************************************************
1154 * Function : accept_connection
1156 * Description : Accepts a connection on one of possibly multiple
1157 * sockets. The socket(s) to check must have been
1158 * created using bind_port().
1161 * 1 : csp = Client state, cfd, ip_addr_str, and
1162 * ip_addr_long will be set by this routine.
1163 * 2 : fds = File descriptors returned from bind_port
1165 * Returns : when a connection is accepted, it returns 1 (TRUE).
1166 * On an error it returns 0 (FALSE).
1168 *********************************************************************/
1169 int accept_connection(struct client_state * csp, jb_socket fds[])
1172 /* XXX: client is stored directly into csp->tcp_addr */
1173 #define client (csp->tcp_addr)
1175 struct sockaddr_in client;
1178 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1179 /* Wierdness - fix a warning. */
1186 int max_selected_socket;
1187 fd_set selected_fds;
1190 c_length = sizeof(client);
1193 * Wait for a connection on any socket.
1194 * Return immediately if no socket is listening.
1195 * XXX: Why not treat this as fatal error?
1197 FD_ZERO(&selected_fds);
1198 max_selected_socket = 0;
1199 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1201 if (JB_INVALID_SOCKET != fds[i])
1203 FD_SET(fds[i], &selected_fds);
1204 if (max_selected_socket < fds[i] + 1)
1206 max_selected_socket = fds[i] + 1;
1210 if (0 == max_selected_socket)
1216 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1217 } while (retval < 0 && errno == EINTR);
1222 log_error(LOG_LEVEL_ERROR,
1223 "Waiting on new client failed because select(2) returned 0."
1224 " This should not happen.");
1228 log_error(LOG_LEVEL_ERROR,
1229 "Waiting on new client failed because of problems in select(2): "
1230 "%s.", strerror(errno));
1234 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1236 if (i >= MAX_LISTENING_SOCKETS)
1238 log_error(LOG_LEVEL_ERROR,
1239 "select(2) reported connected clients (number = %u, "
1240 "descriptor boundary = %u), but none found.",
1241 retval, max_selected_socket);
1246 /* Accept selected connection */
1248 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1249 if (afd == JB_INVALID_SOCKET)
1256 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1257 struct accept_filter_arg af_options;
1258 bzero(&af_options, sizeof(af_options));
1259 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1260 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1262 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1263 } while (afd < 1 && errno == EINTR);
1272 csp->ip_addr_str = malloc(NI_MAXHOST);
1273 if (NULL == csp->ip_addr_str)
1275 log_error(LOG_LEVEL_ERROR,
1276 "Out of memory while getting the client's IP address.");
1279 retval = getnameinfo((struct sockaddr *) &client, c_length,
1280 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1281 if (!csp->ip_addr_str || retval)
1283 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1284 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1285 freez(csp->ip_addr_str);
1289 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1290 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1291 #endif /* def HAVE_RFC2553 */
1298 /*********************************************************************
1300 * Function : resolve_hostname_to_ip
1302 * Description : Resolve a hostname to an internet tcp/ip address.
1303 * NULL or an empty string resolve to INADDR_ANY.
1306 * 1 : host = hostname to resolve
1308 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1310 *********************************************************************/
1311 unsigned long resolve_hostname_to_ip(const char *host)
1313 struct sockaddr_in inaddr;
1314 struct hostent *hostp;
1315 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1316 struct hostent result;
1317 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1318 char hbuf[HOSTENT_BUFFER_SIZE];
1320 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1321 struct hostent_data hdata;
1322 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1323 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1325 if ((host == NULL) || (*host == '\0'))
1330 memset((char *) &inaddr, 0, sizeof inaddr);
1332 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1334 unsigned int dns_retries = 0;
1335 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1336 while (gethostbyname_r(host, &result, hbuf,
1337 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1338 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1340 log_error(LOG_LEVEL_ERROR,
1341 "Timeout #%u while trying to resolve %s. Trying again.",
1344 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1345 while (NULL == (hostp = gethostbyname_r(host, &result,
1346 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1347 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1349 log_error(LOG_LEVEL_ERROR,
1350 "Timeout #%u while trying to resolve %s. Trying again.",
1353 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1355 * XXX: Doesn't retry in case of soft errors.
1356 * Does this gethostbyname_r version set h_errno?
1358 if (0 == gethostbyname_r(host, &result, &hdata))
1366 #elif defined(MUTEX_LOCKS_AVAILABLE)
1367 privoxy_mutex_lock(&resolver_mutex);
1368 while (NULL == (hostp = gethostbyname(host))
1369 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1371 log_error(LOG_LEVEL_ERROR,
1372 "Timeout #%u while trying to resolve %s. Trying again.",
1375 privoxy_mutex_unlock(&resolver_mutex);
1377 while (NULL == (hostp = gethostbyname(host))
1378 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1380 log_error(LOG_LEVEL_ERROR,
1381 "Timeout #%u while trying to resolve %s. Trying again.",
1384 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1386 * On Mac OSX, if a domain exists but doesn't have a type A
1387 * record associated with it, the h_addr member of the struct
1388 * hostent returned by gethostbyname is NULL, even if h_length
1389 * is 4. Therefore the second test below.
1391 if (hostp == NULL || hostp->h_addr == NULL)
1394 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1395 return(INADDR_NONE);
1397 if (hostp->h_addrtype != AF_INET)
1400 errno = WSAEPROTOTYPE;
1404 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1405 return(INADDR_NONE);
1407 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1409 return(inaddr.sin_addr.s_addr);
1414 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1415 /*********************************************************************
1417 * Function : socket_is_still_alive
1419 * Description : Figures out whether or not a socket is still alive.
1422 * 1 : sfd = The socket to check.
1424 * Returns : TRUE for yes, otherwise FALSE.
1426 *********************************************************************/
1427 int socket_is_still_alive(jb_socket sfd)
1430 int no_data_waiting;
1434 struct pollfd poll_fd[1];
1436 memset(poll_fd, 0, sizeof(poll_fd));
1437 poll_fd[0].fd = sfd;
1438 poll_fd[0].events = POLLIN;
1440 poll_result = poll(poll_fd, 1, 0);
1442 if (-1 == poll_result)
1444 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1447 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1449 fd_set readable_fds;
1450 struct timeval timeout;
1453 memset(&timeout, '\0', sizeof(timeout));
1454 FD_ZERO(&readable_fds);
1455 FD_SET(sfd, &readable_fds);
1457 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1460 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1463 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1464 #endif /* def HAVE_POLL */
1466 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1468 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */