1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.143 2017/06/04 14:37:05 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 Privoxy can be more
8 * OS-independent. Contains #ifdefs to make this work
11 * Copyright : Written by and Copyright (C) 2001-2017 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>
55 #include <sys/timeb.h>
64 #include <netinet/in.h>
65 #include <sys/ioctl.h>
67 #include <sys/socket.h>
70 #include <netinet/tcp.h>
72 #include <arpa/inet.h>
78 #if defined(__EMX__) || defined (__OS2__)
79 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
97 /* For mutex semaphores only */
100 #include "jbsockets.h"
103 #include "miscutil.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 : set_no_delay_flag
131 * Description : Disables TCP coalescence for the given socket.
134 * 1 : fd = The file descriptor to operate on
138 *********************************************************************/
139 static void set_no_delay_flag(int fd)
144 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
146 log_error(LOG_LEVEL_ERROR,
147 "Failed to disable TCP coalescence for socket %d", fd);
150 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
151 #endif /* def TCP_NODELAY */
154 /*********************************************************************
156 * Function : connect_to
158 * Description : Open a socket and connect to it. Will check
159 * that this is allowed according to ACL.
162 * 1 : host = hostname to connect to
163 * 2 : portnum = port to connect to (XXX: should be unsigned)
164 * 3 : csp = Current client state (buffers, headers, etc...)
166 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
169 *********************************************************************/
170 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
173 int forwarded_connect_retries = 0;
178 * XXX: The whole errno overloading is ridiculous and should
179 * be replaced with something sane and thread safe
183 fd = rfc2553_connect_to(host, portnum, csp);
185 fd = no_rfc2553_connect_to(host, portnum, csp);
187 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
188 || (csp->fwd == NULL)
189 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
193 forwarded_connect_retries++;
194 if (csp->config->forwarded_connect_retries != 0)
196 log_error(LOG_LEVEL_ERROR,
197 "Attempt %d of %d to connect to %s failed. Trying again.",
198 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
201 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
207 /* Getaddrinfo implementation */
208 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
210 struct addrinfo hints, *result, *rp;
215 struct pollfd poll_fd[1];
218 struct timeval timeout;
220 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
225 * XXX: Initializeing it here is only necessary
226 * because not all situations are properly
229 int socket_error = 0;
232 struct access_control_addr dst[1];
233 #endif /* def FEATURE_ACL */
235 /* Don't leak memory when retrying. */
236 freez(csp->error_message);
237 freez(csp->http->host_ip_addr_str);
239 retval = snprintf(service, sizeof(service), "%d", portnum);
240 if ((-1 == retval) || (sizeof(service) <= retval))
242 log_error(LOG_LEVEL_ERROR,
243 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
245 csp->error_message = strdup("Invalid port number");
246 csp->http->host_ip_addr_str = strdup("unknown");
247 return(JB_INVALID_SOCKET);
250 memset((char *)&hints, 0, sizeof(hints));
251 hints.ai_family = AF_UNSPEC;
252 hints.ai_socktype = SOCK_STREAM;
253 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
255 hints.ai_flags |= AI_ADDRCONFIG;
257 if ((retval = getaddrinfo(host, service, &hints, &result)))
259 log_error(LOG_LEVEL_INFO,
260 "Can not resolve %s: %s", host, gai_strerror(retval));
261 /* XXX: Should find a better way to propagate this error. */
263 csp->error_message = strdup(gai_strerror(retval));
264 csp->http->host_ip_addr_str = strdup("unknown");
265 return(JB_INVALID_SOCKET);
268 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
270 for (rp = result; rp != NULL; rp = rp->ai_next)
274 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
276 if (block_acl(dst, csp))
279 socket_error = errno = SOCEPERM;
281 socket_error = errno = EPERM;
285 #endif /* def FEATURE_ACL */
287 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
288 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
291 log_error(LOG_LEVEL_ERROR,
292 "Failed to get the host name from the socket structure: %s",
293 gai_strerror(retval));
297 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
299 if (fd == JB_INVALID_SOCKET)
309 if (fd >= FD_SETSIZE)
311 log_error(LOG_LEVEL_ERROR,
312 "Server socket number too high to use select(): %d >= %d",
315 freeaddrinfo(result);
316 return JB_INVALID_SOCKET;
321 #ifdef FEATURE_EXTERNAL_FILTERS
322 mark_socket_for_close_on_execute(fd);
325 set_no_delay_flag(fd);
327 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
328 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
331 fcntl(fd, F_SETFL, flags);
333 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
336 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
339 errno = sock_errno();
343 if (errno == WSAEINPROGRESS)
344 #else /* ifndef _WIN32 */
345 if (errno == EINPROGRESS)
346 #endif /* ndef _WIN32 || __OS2__ */
353 socket_error = errno;
364 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
368 fcntl(fd, F_SETFL, flags);
370 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
374 poll_fd[0].events = POLLOUT;
376 if (poll(poll_fd, 1, 30000) > 0)
378 /* wait for connection to complete */
382 memset(&timeout, 0, sizeof(timeout));
385 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
386 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
387 && FD_ISSET(fd, &wfds))
390 socklen_t optlen = sizeof(socket_error);
391 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
395 /* Connection established, no need to try other addresses. */
398 if (rp->ai_next != NULL)
401 * There's another address we can try, so log that this
402 * one didn't work out. If the last one fails, too,
403 * it will get logged outside the loop body so we don't
404 * have to mention it here.
406 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
407 csp->http->host_ip_addr_str, service, strerror(socket_error));
412 socket_error = errno;
413 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
414 "the connection to [%s]:%s: %s; dropping connection.",
415 csp->http->host_ip_addr_str, service, strerror(errno));
419 /* Connection failed, try next address */
423 freeaddrinfo(result);
426 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
427 host, service, strerror(socket_error));
428 csp->error_message = strdup(strerror(socket_error));
429 return(JB_INVALID_SOCKET);
431 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
432 host, csp->http->host_ip_addr_str, service);
438 #else /* ndef HAVE_RFC2553 */
439 /* Pre-getaddrinfo implementation */
441 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
443 struct sockaddr_in inaddr;
447 struct pollfd poll_fd[1];
450 struct timeval tv[1];
452 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
457 struct access_control_addr dst[1];
458 #endif /* def FEATURE_ACL */
460 /* Don't leak memory when retrying. */
461 freez(csp->http->host_ip_addr_str);
463 memset((char *)&inaddr, 0, sizeof inaddr);
465 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
467 csp->http->host_ip_addr_str = strdup("unknown");
468 return(JB_INVALID_SOCKET);
472 dst->addr = ntohl(addr);
475 if (block_acl(dst, csp))
482 return(JB_INVALID_SOCKET);
484 #endif /* def FEATURE_ACL */
486 inaddr.sin_addr.s_addr = addr;
487 inaddr.sin_family = AF_INET;
488 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
491 if (sizeof(inaddr.sin_port) == sizeof(short))
492 #endif /* ndef _WIN32 */
494 inaddr.sin_port = htons((unsigned short) portnum);
499 inaddr.sin_port = htonl((unsigned long)portnum);
501 #endif /* ndef _WIN32 */
503 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
505 if (fd == JB_INVALID_SOCKET)
510 return(JB_INVALID_SOCKET);
515 if (fd >= FD_SETSIZE)
517 log_error(LOG_LEVEL_ERROR,
518 "Server socket number too high to use select(): %d >= %d",
521 return JB_INVALID_SOCKET;
526 set_no_delay_flag(fd);
528 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
529 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
532 fcntl(fd, F_SETFL, flags);
533 #ifdef FEATURE_EXTERNAL_FILTERS
534 mark_socket_for_close_on_execute(fd);
537 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
539 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
542 if (errno == WSAEINPROGRESS)
544 if (sock_errno() == EINPROGRESS)
545 #else /* ifndef _WIN32 */
546 if (errno == EINPROGRESS)
547 #endif /* ndef _WIN32 || __OS2__ */
553 if (sock_errno() != EINTR)
559 return(JB_INVALID_SOCKET);
563 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
567 fcntl(fd, F_SETFL, flags);
569 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
573 poll_fd[0].events = POLLOUT;
575 if (poll(poll_fd, 1, 30000) <= 0)
577 /* wait for connection to complete */
584 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
585 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
589 return(JB_INVALID_SOCKET);
594 #endif /* ndef HAVE_RFC2553 */
597 /*********************************************************************
599 * Function : write_socket
601 * Description : Write the contents of buf (for n bytes) to socket fd.
604 * 1 : fd = file descriptor (aka. handle) of socket to write to.
605 * 2 : buf = pointer to data to be written.
606 * 3 : len = length of data to be written to the socket "fd".
608 * Returns : 0 on success (entire buffer sent).
611 *********************************************************************/
613 int write_socket(jb_socket fd, const char *buf, ssize_t len)
615 int write_socket(jb_socket fd, const char *buf, size_t len)
624 if (!daemon_mode && fd <= 3)
626 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
631 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
634 return (send(fd, buf, (int)len, 0) != (int)len);
635 #elif defined(__BEOS__) || defined(AMIGA)
636 return (send(fd, buf, len, 0) != len);
637 #elif defined(__OS2__)
639 * Break the data up into SOCKET_SEND_MAX chunks for sending...
640 * OS/2 seemed to complain when the chunks were too large.
642 #define SOCKET_SEND_MAX 65000
644 int send_len, send_rc = 0, i = 0;
645 while ((i < len) && (send_rc != -1))
647 if ((i + SOCKET_SEND_MAX) > len)
650 send_len = SOCKET_SEND_MAX;
651 send_rc = send(fd,(char*)buf + i, send_len, 0);
659 return (write(fd, buf, len) != len);
665 /*********************************************************************
667 * Function : read_socket
669 * Description : Read from a TCP/IP socket in a platform independent way.
672 * 1 : fd = file descriptor of the socket to read
673 * 2 : buf = pointer to buffer where data will be written
674 * Must be >= len bytes long.
675 * 3 : len = maximum number of bytes to read
677 * Returns : On success, the number of bytes read is returned (zero
678 * indicates end of file), and the file position is advanced
679 * by this number. It is not an error if this number is
680 * smaller than the number of bytes requested; this may hap-
681 * pen for example because fewer bytes are actually available
682 * right now (maybe because we were close to end-of-file, or
683 * because we are reading from a pipe, or from a terminal,
684 * or because read() was interrupted by a signal). On error,
685 * -1 is returned, and errno is set appropriately. In this
686 * case it is left unspecified whether the file position (if
689 *********************************************************************/
690 int read_socket(jb_socket fd, char *buf, int len)
700 ret = recv(fd, buf, len, 0);
701 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
702 ret = recv(fd, buf, (size_t)len, 0);
704 ret = (int)read(fd, buf, (size_t)len);
709 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
716 /*********************************************************************
718 * Function : data_is_available
720 * Description : Waits for data to arrive on a socket.
723 * 1 : fd = file descriptor of the socket to read
724 * 2 : seconds_to_wait = number of seconds after which we give up.
726 * Returns : TRUE if data arrived in time,
729 *********************************************************************/
730 int data_is_available(jb_socket fd, int seconds_to_wait)
735 struct pollfd poll_fd[1];
738 poll_fd[0].events = POLLIN;
740 n = poll(poll_fd, 1, seconds_to_wait * 1000);
743 struct timeval timeout;
745 memset(&timeout, 0, sizeof(timeout));
746 timeout.tv_sec = seconds_to_wait;
749 /* Copy and pasted from jcc.c ... */
750 memset(&rfds, 0, sizeof(fd_set));
756 n = select(fd+1, &rfds, NULL, NULL, &timeout);
760 * XXX: Do we care about the different error conditions?
762 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
766 /*********************************************************************
768 * Function : close_socket
770 * Description : Closes a TCP/IP socket
773 * 1 : fd = file descriptor of socket to be closed
777 *********************************************************************/
778 void close_socket(jb_socket fd)
780 #if defined(_WIN32) || defined(__BEOS__)
784 #elif defined(__OS2__)
792 /*********************************************************************
794 * Function : drain_and_close_socket
796 * Description : Closes a TCP/IP socket after draining unread data
799 * 1 : fd = file descriptor of the socket to be closed
803 *********************************************************************/
804 void drain_and_close_socket(jb_socket fd)
806 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
807 if (socket_is_still_alive(fd))
810 int bytes_drained_total = 0;
814 /* Apparently Windows has shutdown() but not SHUT_WR. */
818 if (0 != shutdown(fd, SHUT_WR))
820 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
823 #define ARBITRARY_DRAIN_LIMIT 10000
828 if (!data_is_available(fd, 0))
831 * If there is no data available right now, don't try
832 * to drain the socket as read_socket() could block.
837 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
838 if (bytes_drained < 0)
840 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
842 else if (bytes_drained > 0)
844 bytes_drained_total += bytes_drained;
845 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
847 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
851 } while (bytes_drained > 0);
852 if (bytes_drained_total != 0)
854 log_error(LOG_LEVEL_CONNECT,
855 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
864 /*********************************************************************
866 * Function : bind_port
868 * Description : Call socket, set socket options, and listen.
869 * Called by listen_loop to "boot up" our proxy address.
872 * 1 : hostnam = TCP/IP address to bind/listen to
873 * 2 : portnum = port to listen on
874 * 3 : pfd = pointer used to return file descriptor.
876 * Returns : if success, returns 0 and sets *pfd.
877 * if failure, returns -3 if address is in use,
878 * -2 if address unresolvable,
880 *********************************************************************/
881 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
884 struct addrinfo hints;
885 struct addrinfo *result, *rp;
887 * XXX: portnum should be a string to allow symbolic service
888 * names in the configuration file and to avoid the following
894 struct sockaddr_in inaddr;
895 #endif /* def HAVE_RFC2553 */
899 #endif /* ndef _WIN32 */
901 *pfd = JB_INVALID_SOCKET;
904 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
905 if ((-1 == retval) || (sizeof(servnam) <= retval))
907 log_error(LOG_LEVEL_ERROR,
908 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
913 memset(&hints, 0, sizeof(struct addrinfo));
917 * XXX: This is a hack. The right thing to do
918 * would be to bind to both AF_INET and AF_INET6.
919 * This will also fail if there is no AF_INET
922 hints.ai_family = AF_INET;
926 hints.ai_family = AF_UNSPEC;
928 hints.ai_socktype = SOCK_STREAM;
929 hints.ai_flags = AI_PASSIVE;
930 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
931 hints.ai_canonname = NULL;
932 hints.ai_addr = NULL;
933 hints.ai_next = NULL;
935 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
937 log_error(LOG_LEVEL_ERROR,
938 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
942 memset((char *)&inaddr, '\0', sizeof inaddr);
944 inaddr.sin_family = AF_INET;
945 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
947 if (inaddr.sin_addr.s_addr == INADDR_NONE)
953 if (sizeof(inaddr.sin_port) == sizeof(short))
954 #endif /* ndef _WIN32 */
956 inaddr.sin_port = htons((unsigned short) portnum);
961 inaddr.sin_port = htonl((unsigned long) portnum);
963 #endif /* ndef _WIN32 */
964 #endif /* def HAVE_RFC2553 */
967 for (rp = result; rp != NULL; rp = rp->ai_next)
969 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
971 fd = socket(AF_INET, SOCK_STREAM, 0);
972 #endif /* def HAVE_RFC2553 */
975 if (fd == JB_INVALID_SOCKET)
987 #ifdef FEATURE_EXTERNAL_FILTERS
988 mark_socket_for_close_on_execute(fd);
993 * This is not needed for Win32 - in fact, it stops
994 * duplicate instances of Privoxy from being caught.
996 * On UNIX, we assume the user is sensible enough not
997 * to start Privoxy multiple times on the same IP.
998 * Without this, stopping and restarting Privoxy
999 * from a script fails.
1000 * Note: SO_REUSEADDR is meant to only take over
1001 * sockets which are *not* in listen state in Linux,
1002 * e.g. sockets in TIME_WAIT. YMMV.
1004 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
1005 #endif /* ndef _WIN32 */
1008 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
1010 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
1014 errno = WSAGetLastError();
1015 if (errno == WSAEADDRINUSE)
1017 if (errno == EADDRINUSE)
1021 freeaddrinfo(result);
1029 #ifndef HAVE_RFC2553
1038 /* bind() succeeded, escape from for-loop */
1040 * XXX: Support multiple listening sockets (e.g. localhost
1041 * resolves to AF_INET and AF_INET6, but only the first address
1048 freeaddrinfo(result);
1051 /* All bind()s failed */
1054 #endif /* ndef HAVE_RFC2553 */
1056 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1071 /*********************************************************************
1073 * Function : get_host_information
1075 * Description : Determines the IP address the client used to
1076 * reach us and the hostname associated with it.
1078 * XXX: Most of the code has been copy and pasted
1079 * from accept_connection() and not all of the
1080 * ifdefs paths have been tested afterwards.
1083 * 1 : afd = File descriptor returned from accept().
1084 * 2 : ip_address = Pointer to return the pointer to
1085 * the ip address string.
1086 * 3 : port = Pointer to return the pointer to
1087 * the TCP port string.
1088 * 4 : hostname = Pointer to return the pointer to
1089 * the hostname or NULL if the caller
1090 * isn't interested in it.
1094 *********************************************************************/
1095 void get_host_information(jb_socket afd, char **ip_address, char **port,
1099 struct sockaddr_storage server;
1102 struct sockaddr_in server;
1103 struct hostent *host = NULL;
1104 #endif /* HAVE_RFC2553 */
1105 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1106 /* according to accept_connection() this fixes a warning. */
1107 int s_length, s_length_provided;
1109 socklen_t s_length, s_length_provided;
1111 #ifndef HAVE_RFC2553
1112 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1113 struct hostent result;
1114 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1115 struct hostent_data hdata;
1117 char hbuf[HOSTENT_BUFFER_SIZE];
1119 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1120 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1121 #endif /* ifndef HAVE_RFC2553 */
1122 s_length = s_length_provided = sizeof(server);
1124 if (NULL != hostname)
1131 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1133 if (s_length > s_length_provided)
1135 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1139 * XXX: Workaround for missing header on Windows when
1140 * configured with --disable-ipv6-support.
1141 * The proper fix is to not use NI_MAXSERV in
1142 * that case. It works by accident on other platforms
1143 * as <netdb.h> is included unconditionally there.
1146 #define NI_MAXSERV 32
1148 *port = malloc_or_die(NI_MAXSERV);
1151 *ip_address = malloc_or_die(NI_MAXHOST);
1152 retval = getnameinfo((struct sockaddr *) &server, s_length,
1153 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1154 NI_NUMERICHOST|NI_NUMERICSERV);
1157 log_error(LOG_LEVEL_ERROR,
1158 "Unable to print my own IP address: %s", gai_strerror(retval));
1164 *ip_address = strdup(inet_ntoa(server.sin_addr));
1165 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1166 #endif /* HAVE_RFC2553 */
1167 if (NULL == hostname)
1170 * We're done here, the caller isn't
1171 * interested in knowing the hostname.
1177 *hostname = malloc_or_die(NI_MAXHOST);
1178 retval = getnameinfo((struct sockaddr *) &server, s_length,
1179 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1182 log_error(LOG_LEVEL_ERROR,
1183 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1187 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1188 gethostbyaddr_r((const char *)&server.sin_addr,
1189 sizeof(server.sin_addr), AF_INET,
1190 &result, hbuf, HOSTENT_BUFFER_SIZE,
1192 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1193 host = gethostbyaddr_r((const char *)&server.sin_addr,
1194 sizeof(server.sin_addr), AF_INET,
1195 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1196 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1197 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1198 sizeof(server.sin_addr), AF_INET,
1207 #elif defined(MUTEX_LOCKS_AVAILABLE)
1208 privoxy_mutex_lock(&resolver_mutex);
1209 host = gethostbyaddr((const char *)&server.sin_addr,
1210 sizeof(server.sin_addr), AF_INET);
1211 privoxy_mutex_unlock(&resolver_mutex);
1213 host = gethostbyaddr((const char *)&server.sin_addr,
1214 sizeof(server.sin_addr), AF_INET);
1218 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1222 *hostname = strdup(host->h_name);
1224 #endif /* else def HAVE_RFC2553 */
1231 /*********************************************************************
1233 * Function : accept_connection
1235 * Description : Accepts a connection on one of possibly multiple
1236 * sockets. The socket(s) to check must have been
1237 * created using bind_port().
1240 * 1 : csp = Client state, cfd, ip_addr_str, and
1241 * ip_addr_long will be set by this routine.
1242 * 2 : fds = File descriptors returned from bind_port
1244 * Returns : when a connection is accepted, it returns 1 (TRUE).
1245 * On an error it returns 0 (FALSE).
1247 *********************************************************************/
1248 int accept_connection(struct client_state * csp, jb_socket fds[])
1251 /* XXX: client is stored directly into csp->tcp_addr */
1252 #define client (csp->tcp_addr)
1254 struct sockaddr_in client;
1257 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1258 /* Wierdness - fix a warning. */
1265 int max_selected_socket;
1267 struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
1268 nfds_t polled_sockets;
1270 fd_set selected_fds;
1273 const char *host_addr;
1274 size_t listen_addr_size;
1276 c_length = sizeof(client);
1279 memset(poll_fds, 0, sizeof(poll_fds));
1283 * Wait for a connection on any socket.
1284 * Return immediately if no socket is listening.
1285 * XXX: Why not treat this as fatal error?
1287 FD_ZERO(&selected_fds);
1289 max_selected_socket = 0;
1290 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1292 if (JB_INVALID_SOCKET != fds[i])
1295 poll_fds[i].fd = fds[i];
1296 poll_fds[i].events = POLLIN;
1299 FD_SET(fds[i], &selected_fds);
1301 if (max_selected_socket < fds[i] + 1)
1303 max_selected_socket = fds[i] + 1;
1307 if (0 == max_selected_socket)
1314 retval = poll(poll_fds, polled_sockets, -1);
1316 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1318 } while (retval < 0 && errno == EINTR);
1323 log_error(LOG_LEVEL_ERROR,
1324 "Waiting on new client failed because select(2) returned 0."
1325 " This should not happen.");
1329 log_error(LOG_LEVEL_ERROR,
1330 "Waiting on new client failed because of problems in select(2): "
1331 "%s.", strerror(errno));
1336 for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
1338 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1341 if (i >= MAX_LISTENING_SOCKETS)
1343 log_error(LOG_LEVEL_ERROR,
1344 "select(2) reported connected clients (number = %u, "
1345 "descriptor boundary = %u), but none found.",
1346 retval, max_selected_socket);
1351 /* Accept selected connection */
1353 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1354 if (afd == JB_INVALID_SOCKET)
1361 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1362 struct accept_filter_arg af_options;
1363 bzero(&af_options, sizeof(af_options));
1364 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1365 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1367 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1368 } while (afd < 0 && errno == EINTR);
1377 struct linger linger_options;
1378 linger_options.l_onoff = 1;
1379 linger_options.l_linger = 5;
1380 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1382 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1389 if (afd >= FD_SETSIZE)
1391 log_error(LOG_LEVEL_ERROR,
1392 "Client socket number too high to use select(): %d >= %d",
1400 #ifdef FEATURE_EXTERNAL_FILTERS
1401 mark_socket_for_close_on_execute(afd);
1404 set_no_delay_flag(afd);
1408 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1409 retval = getnameinfo((struct sockaddr *) &client, c_length,
1410 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1411 if (!csp->ip_addr_str || retval)
1413 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1414 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1415 freez(csp->ip_addr_str);
1419 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1420 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1421 #endif /* def HAVE_RFC2553 */
1424 * Save the name and port of the accepting socket for later lookup.
1426 * The string needs space for strlen(...) + 7 characters:
1427 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1429 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1430 listen_addr_size = strlen(host_addr) + 7;
1431 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1432 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1433 "%s:%d", host_addr, csp->config->hport[i]);
1434 if ((-1 == retval) || listen_addr_size <= retval)
1436 log_error(LOG_LEVEL_ERROR,
1437 "Server name (%s) and port number (%d) ASCII decimal representation"
1438 "don't fit into %d bytes",
1439 host_addr, csp->config->hport[i], listen_addr_size);
1448 /*********************************************************************
1450 * Function : resolve_hostname_to_ip
1452 * Description : Resolve a hostname to an internet tcp/ip address.
1453 * NULL or an empty string resolve to INADDR_ANY.
1456 * 1 : host = hostname to resolve
1458 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1460 *********************************************************************/
1461 unsigned long resolve_hostname_to_ip(const char *host)
1463 struct sockaddr_in inaddr;
1464 struct hostent *hostp;
1465 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1466 struct hostent result;
1467 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1468 char hbuf[HOSTENT_BUFFER_SIZE];
1470 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1471 struct hostent_data hdata;
1472 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1473 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1475 if ((host == NULL) || (*host == '\0'))
1480 memset((char *) &inaddr, 0, sizeof inaddr);
1482 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1484 unsigned int dns_retries = 0;
1485 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1486 while (gethostbyname_r(host, &result, hbuf,
1487 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1488 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1490 log_error(LOG_LEVEL_ERROR,
1491 "Timeout #%u while trying to resolve %s. Trying again.",
1494 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1495 while (NULL == (hostp = gethostbyname_r(host, &result,
1496 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1497 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1499 log_error(LOG_LEVEL_ERROR,
1500 "Timeout #%u while trying to resolve %s. Trying again.",
1503 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1505 * XXX: Doesn't retry in case of soft errors.
1506 * Does this gethostbyname_r version set h_errno?
1508 if (0 == gethostbyname_r(host, &result, &hdata))
1516 #elif defined(MUTEX_LOCKS_AVAILABLE)
1517 privoxy_mutex_lock(&resolver_mutex);
1518 while (NULL == (hostp = gethostbyname(host))
1519 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1521 log_error(LOG_LEVEL_ERROR,
1522 "Timeout #%u while trying to resolve %s. Trying again.",
1525 privoxy_mutex_unlock(&resolver_mutex);
1527 while (NULL == (hostp = gethostbyname(host))
1528 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1530 log_error(LOG_LEVEL_ERROR,
1531 "Timeout #%u while trying to resolve %s. Trying again.",
1534 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1536 * On Mac OSX, if a domain exists but doesn't have a type A
1537 * record associated with it, the h_addr member of the struct
1538 * hostent returned by gethostbyname is NULL, even if h_length
1539 * is 4. Therefore the second test below.
1541 if (hostp == NULL || hostp->h_addr == NULL)
1544 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1545 return(INADDR_NONE);
1547 if (hostp->h_addrtype != AF_INET)
1550 errno = WSAEPROTOTYPE;
1554 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1555 return(INADDR_NONE);
1557 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1559 return(inaddr.sin_addr.s_addr);
1564 /*********************************************************************
1566 * Function : socket_is_still_alive
1568 * Description : Figures out whether or not a socket is still alive.
1571 * 1 : sfd = The socket to check.
1573 * Returns : TRUE for yes, otherwise FALSE.
1575 *********************************************************************/
1576 int socket_is_still_alive(jb_socket sfd)
1579 int no_data_waiting;
1582 struct pollfd poll_fd[1];
1584 memset(poll_fd, 0, sizeof(poll_fd));
1585 poll_fd[0].fd = sfd;
1586 poll_fd[0].events = POLLIN;
1588 poll_result = poll(poll_fd, 1, 0);
1590 if (-1 == poll_result)
1592 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1595 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1597 fd_set readable_fds;
1598 struct timeval timeout;
1601 memset(&timeout, '\0', sizeof(timeout));
1602 FD_ZERO(&readable_fds);
1603 FD_SET(sfd, &readable_fds);
1605 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1608 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1611 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1612 #endif /* def HAVE_POLL */
1614 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1618 #ifdef FEATURE_EXTERNAL_FILTERS
1619 /*********************************************************************
1621 * Function : mark_socket_for_close_on_execute
1623 * Description : Marks a socket for close on execute.
1625 * Used so that external filters have no direct
1626 * access to sockets they shouldn't care about.
1628 * Not implemented for all platforms.
1631 * 1 : fd = The socket to mark
1635 *********************************************************************/
1636 void mark_socket_for_close_on_execute(jb_socket fd)
1638 #ifdef FEATURE_PTHREAD
1641 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1645 log_error(LOG_LEVEL_ERROR,
1646 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1649 #warning "Sockets will be visible to external filters"
1652 #endif /* def FEATURE_EXTERNAL_FILTERS */