1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.144 2017/06/08 13:04:34 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 retval = poll(poll_fd, 1, 30000);
379 if (rp->ai_next != NULL)
381 /* Log this now as we'll try another address next */
382 log_error(LOG_LEVEL_CONNECT,
383 "Could not connect to [%s]:%s: Operation timed out.",
384 csp->http->host_ip_addr_str, service);
389 * This is the last address, don't log this now
390 * as it would result in a duplicated log message.
392 socket_error = ETIMEDOUT;
397 /* wait for connection to complete */
401 memset(&timeout, 0, sizeof(timeout));
404 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
405 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
406 && FD_ISSET(fd, &wfds))
409 socklen_t optlen = sizeof(socket_error);
410 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
414 /* Connection established, no need to try other addresses. */
417 if (rp->ai_next != NULL)
420 * There's another address we can try, so log that this
421 * one didn't work out. If the last one fails, too,
422 * it will get logged outside the loop body so we don't
423 * have to mention it here.
425 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
426 csp->http->host_ip_addr_str, service, strerror(socket_error));
431 socket_error = errno;
432 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
433 "the connection to [%s]:%s: %s; dropping connection.",
434 csp->http->host_ip_addr_str, service, strerror(errno));
438 /* Connection failed, try next address */
442 freeaddrinfo(result);
445 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
446 host, service, strerror(socket_error));
447 csp->error_message = strdup(strerror(socket_error));
448 return(JB_INVALID_SOCKET);
450 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
451 host, csp->http->host_ip_addr_str, service);
457 #else /* ndef HAVE_RFC2553 */
458 /* Pre-getaddrinfo implementation */
460 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
462 struct sockaddr_in inaddr;
466 struct pollfd poll_fd[1];
469 struct timeval tv[1];
471 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
476 struct access_control_addr dst[1];
477 #endif /* def FEATURE_ACL */
479 /* Don't leak memory when retrying. */
480 freez(csp->http->host_ip_addr_str);
482 memset((char *)&inaddr, 0, sizeof inaddr);
484 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
486 csp->http->host_ip_addr_str = strdup("unknown");
487 return(JB_INVALID_SOCKET);
491 dst->addr = ntohl(addr);
494 if (block_acl(dst, csp))
501 return(JB_INVALID_SOCKET);
503 #endif /* def FEATURE_ACL */
505 inaddr.sin_addr.s_addr = addr;
506 inaddr.sin_family = AF_INET;
507 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
510 if (sizeof(inaddr.sin_port) == sizeof(short))
511 #endif /* ndef _WIN32 */
513 inaddr.sin_port = htons((unsigned short) portnum);
518 inaddr.sin_port = htonl((unsigned long)portnum);
520 #endif /* ndef _WIN32 */
522 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
524 if (fd == JB_INVALID_SOCKET)
529 return(JB_INVALID_SOCKET);
534 if (fd >= FD_SETSIZE)
536 log_error(LOG_LEVEL_ERROR,
537 "Server socket number too high to use select(): %d >= %d",
540 return JB_INVALID_SOCKET;
545 set_no_delay_flag(fd);
547 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
548 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
551 fcntl(fd, F_SETFL, flags);
552 #ifdef FEATURE_EXTERNAL_FILTERS
553 mark_socket_for_close_on_execute(fd);
556 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
558 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
561 if (errno == WSAEINPROGRESS)
563 if (sock_errno() == EINPROGRESS)
564 #else /* ifndef _WIN32 */
565 if (errno == EINPROGRESS)
566 #endif /* ndef _WIN32 || __OS2__ */
572 if (sock_errno() != EINTR)
578 return(JB_INVALID_SOCKET);
582 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
586 fcntl(fd, F_SETFL, flags);
588 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
592 poll_fd[0].events = POLLOUT;
594 if (poll(poll_fd, 1, 30000) <= 0)
596 /* wait for connection to complete */
603 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
604 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
608 return(JB_INVALID_SOCKET);
613 #endif /* ndef HAVE_RFC2553 */
616 /*********************************************************************
618 * Function : write_socket
620 * Description : Write the contents of buf (for n bytes) to socket fd.
623 * 1 : fd = file descriptor (aka. handle) of socket to write to.
624 * 2 : buf = pointer to data to be written.
625 * 3 : len = length of data to be written to the socket "fd".
627 * Returns : 0 on success (entire buffer sent).
630 *********************************************************************/
632 int write_socket(jb_socket fd, const char *buf, ssize_t len)
634 int write_socket(jb_socket fd, const char *buf, size_t len)
643 if (!daemon_mode && fd <= 3)
645 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
650 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
653 return (send(fd, buf, (int)len, 0) != (int)len);
654 #elif defined(__BEOS__) || defined(AMIGA)
655 return (send(fd, buf, len, 0) != len);
656 #elif defined(__OS2__)
658 * Break the data up into SOCKET_SEND_MAX chunks for sending...
659 * OS/2 seemed to complain when the chunks were too large.
661 #define SOCKET_SEND_MAX 65000
663 int send_len, send_rc = 0, i = 0;
664 while ((i < len) && (send_rc != -1))
666 if ((i + SOCKET_SEND_MAX) > len)
669 send_len = SOCKET_SEND_MAX;
670 send_rc = send(fd,(char*)buf + i, send_len, 0);
678 return (write(fd, buf, len) != len);
684 /*********************************************************************
686 * Function : read_socket
688 * Description : Read from a TCP/IP socket in a platform independent way.
691 * 1 : fd = file descriptor of the socket to read
692 * 2 : buf = pointer to buffer where data will be written
693 * Must be >= len bytes long.
694 * 3 : len = maximum number of bytes to read
696 * Returns : On success, the number of bytes read is returned (zero
697 * indicates end of file), and the file position is advanced
698 * by this number. It is not an error if this number is
699 * smaller than the number of bytes requested; this may hap-
700 * pen for example because fewer bytes are actually available
701 * right now (maybe because we were close to end-of-file, or
702 * because we are reading from a pipe, or from a terminal,
703 * or because read() was interrupted by a signal). On error,
704 * -1 is returned, and errno is set appropriately. In this
705 * case it is left unspecified whether the file position (if
708 *********************************************************************/
709 int read_socket(jb_socket fd, char *buf, int len)
719 ret = recv(fd, buf, len, 0);
720 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
721 ret = recv(fd, buf, (size_t)len, 0);
723 ret = (int)read(fd, buf, (size_t)len);
728 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
735 /*********************************************************************
737 * Function : data_is_available
739 * Description : Waits for data to arrive on a socket.
742 * 1 : fd = file descriptor of the socket to read
743 * 2 : seconds_to_wait = number of seconds after which we give up.
745 * Returns : TRUE if data arrived in time,
748 *********************************************************************/
749 int data_is_available(jb_socket fd, int seconds_to_wait)
754 struct pollfd poll_fd[1];
757 poll_fd[0].events = POLLIN;
759 n = poll(poll_fd, 1, seconds_to_wait * 1000);
762 struct timeval timeout;
764 memset(&timeout, 0, sizeof(timeout));
765 timeout.tv_sec = seconds_to_wait;
768 /* Copy and pasted from jcc.c ... */
769 memset(&rfds, 0, sizeof(fd_set));
775 n = select(fd+1, &rfds, NULL, NULL, &timeout);
779 * XXX: Do we care about the different error conditions?
781 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
785 /*********************************************************************
787 * Function : close_socket
789 * Description : Closes a TCP/IP socket
792 * 1 : fd = file descriptor of socket to be closed
796 *********************************************************************/
797 void close_socket(jb_socket fd)
799 #if defined(_WIN32) || defined(__BEOS__)
803 #elif defined(__OS2__)
811 /*********************************************************************
813 * Function : drain_and_close_socket
815 * Description : Closes a TCP/IP socket after draining unread data
818 * 1 : fd = file descriptor of the socket to be closed
822 *********************************************************************/
823 void drain_and_close_socket(jb_socket fd)
825 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
826 if (socket_is_still_alive(fd))
829 int bytes_drained_total = 0;
833 /* Apparently Windows has shutdown() but not SHUT_WR. */
837 if (0 != shutdown(fd, SHUT_WR))
839 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
842 #define ARBITRARY_DRAIN_LIMIT 10000
847 if (!data_is_available(fd, 0))
850 * If there is no data available right now, don't try
851 * to drain the socket as read_socket() could block.
856 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
857 if (bytes_drained < 0)
859 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
861 else if (bytes_drained > 0)
863 bytes_drained_total += bytes_drained;
864 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
866 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
870 } while (bytes_drained > 0);
871 if (bytes_drained_total != 0)
873 log_error(LOG_LEVEL_CONNECT,
874 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
883 /*********************************************************************
885 * Function : bind_port
887 * Description : Call socket, set socket options, and listen.
888 * Called by listen_loop to "boot up" our proxy address.
891 * 1 : hostnam = TCP/IP address to bind/listen to
892 * 2 : portnum = port to listen on
893 * 3 : pfd = pointer used to return file descriptor.
895 * Returns : if success, returns 0 and sets *pfd.
896 * if failure, returns -3 if address is in use,
897 * -2 if address unresolvable,
899 *********************************************************************/
900 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
903 struct addrinfo hints;
904 struct addrinfo *result, *rp;
906 * XXX: portnum should be a string to allow symbolic service
907 * names in the configuration file and to avoid the following
913 struct sockaddr_in inaddr;
914 #endif /* def HAVE_RFC2553 */
918 #endif /* ndef _WIN32 */
920 *pfd = JB_INVALID_SOCKET;
923 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
924 if ((-1 == retval) || (sizeof(servnam) <= retval))
926 log_error(LOG_LEVEL_ERROR,
927 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
932 memset(&hints, 0, sizeof(struct addrinfo));
936 * XXX: This is a hack. The right thing to do
937 * would be to bind to both AF_INET and AF_INET6.
938 * This will also fail if there is no AF_INET
941 hints.ai_family = AF_INET;
945 hints.ai_family = AF_UNSPEC;
947 hints.ai_socktype = SOCK_STREAM;
948 hints.ai_flags = AI_PASSIVE;
949 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
950 hints.ai_canonname = NULL;
951 hints.ai_addr = NULL;
952 hints.ai_next = NULL;
954 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
956 log_error(LOG_LEVEL_ERROR,
957 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
961 memset((char *)&inaddr, '\0', sizeof inaddr);
963 inaddr.sin_family = AF_INET;
964 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
966 if (inaddr.sin_addr.s_addr == INADDR_NONE)
972 if (sizeof(inaddr.sin_port) == sizeof(short))
973 #endif /* ndef _WIN32 */
975 inaddr.sin_port = htons((unsigned short) portnum);
980 inaddr.sin_port = htonl((unsigned long) portnum);
982 #endif /* ndef _WIN32 */
983 #endif /* def HAVE_RFC2553 */
986 for (rp = result; rp != NULL; rp = rp->ai_next)
988 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
990 fd = socket(AF_INET, SOCK_STREAM, 0);
991 #endif /* def HAVE_RFC2553 */
994 if (fd == JB_INVALID_SOCKET)
1006 #ifdef FEATURE_EXTERNAL_FILTERS
1007 mark_socket_for_close_on_execute(fd);
1012 * This is not needed for Win32 - in fact, it stops
1013 * duplicate instances of Privoxy from being caught.
1015 * On UNIX, we assume the user is sensible enough not
1016 * to start Privoxy multiple times on the same IP.
1017 * Without this, stopping and restarting Privoxy
1018 * from a script fails.
1019 * Note: SO_REUSEADDR is meant to only take over
1020 * sockets which are *not* in listen state in Linux,
1021 * e.g. sockets in TIME_WAIT. YMMV.
1023 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
1024 #endif /* ndef _WIN32 */
1027 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
1029 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
1033 errno = WSAGetLastError();
1034 if (errno == WSAEADDRINUSE)
1036 if (errno == EADDRINUSE)
1040 freeaddrinfo(result);
1048 #ifndef HAVE_RFC2553
1057 /* bind() succeeded, escape from for-loop */
1059 * XXX: Support multiple listening sockets (e.g. localhost
1060 * resolves to AF_INET and AF_INET6, but only the first address
1067 freeaddrinfo(result);
1070 /* All bind()s failed */
1073 #endif /* ndef HAVE_RFC2553 */
1075 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1090 /*********************************************************************
1092 * Function : get_host_information
1094 * Description : Determines the IP address the client used to
1095 * reach us and the hostname associated with it.
1097 * XXX: Most of the code has been copy and pasted
1098 * from accept_connection() and not all of the
1099 * ifdefs paths have been tested afterwards.
1102 * 1 : afd = File descriptor returned from accept().
1103 * 2 : ip_address = Pointer to return the pointer to
1104 * the ip address string.
1105 * 3 : port = Pointer to return the pointer to
1106 * the TCP port string.
1107 * 4 : hostname = Pointer to return the pointer to
1108 * the hostname or NULL if the caller
1109 * isn't interested in it.
1113 *********************************************************************/
1114 void get_host_information(jb_socket afd, char **ip_address, char **port,
1118 struct sockaddr_storage server;
1121 struct sockaddr_in server;
1122 struct hostent *host = NULL;
1123 #endif /* HAVE_RFC2553 */
1124 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1125 /* according to accept_connection() this fixes a warning. */
1126 int s_length, s_length_provided;
1128 socklen_t s_length, s_length_provided;
1130 #ifndef HAVE_RFC2553
1131 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1132 struct hostent result;
1133 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1134 struct hostent_data hdata;
1136 char hbuf[HOSTENT_BUFFER_SIZE];
1138 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1139 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1140 #endif /* ifndef HAVE_RFC2553 */
1141 s_length = s_length_provided = sizeof(server);
1143 if (NULL != hostname)
1150 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1152 if (s_length > s_length_provided)
1154 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1158 * XXX: Workaround for missing header on Windows when
1159 * configured with --disable-ipv6-support.
1160 * The proper fix is to not use NI_MAXSERV in
1161 * that case. It works by accident on other platforms
1162 * as <netdb.h> is included unconditionally there.
1165 #define NI_MAXSERV 32
1167 *port = malloc_or_die(NI_MAXSERV);
1170 *ip_address = malloc_or_die(NI_MAXHOST);
1171 retval = getnameinfo((struct sockaddr *) &server, s_length,
1172 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1173 NI_NUMERICHOST|NI_NUMERICSERV);
1176 log_error(LOG_LEVEL_ERROR,
1177 "Unable to print my own IP address: %s", gai_strerror(retval));
1183 *ip_address = strdup(inet_ntoa(server.sin_addr));
1184 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1185 #endif /* HAVE_RFC2553 */
1186 if (NULL == hostname)
1189 * We're done here, the caller isn't
1190 * interested in knowing the hostname.
1196 *hostname = malloc_or_die(NI_MAXHOST);
1197 retval = getnameinfo((struct sockaddr *) &server, s_length,
1198 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1201 log_error(LOG_LEVEL_ERROR,
1202 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1206 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1207 gethostbyaddr_r((const char *)&server.sin_addr,
1208 sizeof(server.sin_addr), AF_INET,
1209 &result, hbuf, HOSTENT_BUFFER_SIZE,
1211 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1212 host = gethostbyaddr_r((const char *)&server.sin_addr,
1213 sizeof(server.sin_addr), AF_INET,
1214 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1215 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1216 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1217 sizeof(server.sin_addr), AF_INET,
1226 #elif defined(MUTEX_LOCKS_AVAILABLE)
1227 privoxy_mutex_lock(&resolver_mutex);
1228 host = gethostbyaddr((const char *)&server.sin_addr,
1229 sizeof(server.sin_addr), AF_INET);
1230 privoxy_mutex_unlock(&resolver_mutex);
1232 host = gethostbyaddr((const char *)&server.sin_addr,
1233 sizeof(server.sin_addr), AF_INET);
1237 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1241 *hostname = strdup(host->h_name);
1243 #endif /* else def HAVE_RFC2553 */
1250 /*********************************************************************
1252 * Function : accept_connection
1254 * Description : Accepts a connection on one of possibly multiple
1255 * sockets. The socket(s) to check must have been
1256 * created using bind_port().
1259 * 1 : csp = Client state, cfd, ip_addr_str, and
1260 * ip_addr_long will be set by this routine.
1261 * 2 : fds = File descriptors returned from bind_port
1263 * Returns : when a connection is accepted, it returns 1 (TRUE).
1264 * On an error it returns 0 (FALSE).
1266 *********************************************************************/
1267 int accept_connection(struct client_state * csp, jb_socket fds[])
1270 /* XXX: client is stored directly into csp->tcp_addr */
1271 #define client (csp->tcp_addr)
1273 struct sockaddr_in client;
1276 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1277 /* Wierdness - fix a warning. */
1284 int max_selected_socket;
1286 struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
1287 nfds_t polled_sockets;
1289 fd_set selected_fds;
1292 const char *host_addr;
1293 size_t listen_addr_size;
1295 c_length = sizeof(client);
1298 memset(poll_fds, 0, sizeof(poll_fds));
1302 * Wait for a connection on any socket.
1303 * Return immediately if no socket is listening.
1304 * XXX: Why not treat this as fatal error?
1306 FD_ZERO(&selected_fds);
1308 max_selected_socket = 0;
1309 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1311 if (JB_INVALID_SOCKET != fds[i])
1314 poll_fds[i].fd = fds[i];
1315 poll_fds[i].events = POLLIN;
1318 FD_SET(fds[i], &selected_fds);
1320 if (max_selected_socket < fds[i] + 1)
1322 max_selected_socket = fds[i] + 1;
1326 if (0 == max_selected_socket)
1333 retval = poll(poll_fds, polled_sockets, -1);
1335 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1337 } while (retval < 0 && errno == EINTR);
1342 log_error(LOG_LEVEL_ERROR,
1343 "Waiting on new client failed because select(2) returned 0."
1344 " This should not happen.");
1348 log_error(LOG_LEVEL_ERROR,
1349 "Waiting on new client failed because of problems in select(2): "
1350 "%s.", strerror(errno));
1355 for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
1357 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1360 if (i >= MAX_LISTENING_SOCKETS)
1362 log_error(LOG_LEVEL_ERROR,
1363 "select(2) reported connected clients (number = %u, "
1364 "descriptor boundary = %u), but none found.",
1365 retval, max_selected_socket);
1370 /* Accept selected connection */
1372 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1373 if (afd == JB_INVALID_SOCKET)
1380 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1381 struct accept_filter_arg af_options;
1382 bzero(&af_options, sizeof(af_options));
1383 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1384 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1386 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1387 } while (afd < 0 && errno == EINTR);
1396 struct linger linger_options;
1397 linger_options.l_onoff = 1;
1398 linger_options.l_linger = 5;
1399 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1401 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1408 if (afd >= FD_SETSIZE)
1410 log_error(LOG_LEVEL_ERROR,
1411 "Client socket number too high to use select(): %d >= %d",
1419 #ifdef FEATURE_EXTERNAL_FILTERS
1420 mark_socket_for_close_on_execute(afd);
1423 set_no_delay_flag(afd);
1427 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1428 retval = getnameinfo((struct sockaddr *) &client, c_length,
1429 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1430 if (!csp->ip_addr_str || retval)
1432 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1433 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1434 freez(csp->ip_addr_str);
1438 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1439 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1440 #endif /* def HAVE_RFC2553 */
1443 * Save the name and port of the accepting socket for later lookup.
1445 * The string needs space for strlen(...) + 7 characters:
1446 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1448 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1449 listen_addr_size = strlen(host_addr) + 7;
1450 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1451 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1452 "%s:%d", host_addr, csp->config->hport[i]);
1453 if ((-1 == retval) || listen_addr_size <= retval)
1455 log_error(LOG_LEVEL_ERROR,
1456 "Server name (%s) and port number (%d) ASCII decimal representation"
1457 "don't fit into %d bytes",
1458 host_addr, csp->config->hport[i], listen_addr_size);
1467 /*********************************************************************
1469 * Function : resolve_hostname_to_ip
1471 * Description : Resolve a hostname to an internet tcp/ip address.
1472 * NULL or an empty string resolve to INADDR_ANY.
1475 * 1 : host = hostname to resolve
1477 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1479 *********************************************************************/
1480 unsigned long resolve_hostname_to_ip(const char *host)
1482 struct sockaddr_in inaddr;
1483 struct hostent *hostp;
1484 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1485 struct hostent result;
1486 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1487 char hbuf[HOSTENT_BUFFER_SIZE];
1489 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1490 struct hostent_data hdata;
1491 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1492 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1494 if ((host == NULL) || (*host == '\0'))
1499 memset((char *) &inaddr, 0, sizeof inaddr);
1501 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1503 unsigned int dns_retries = 0;
1504 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1505 while (gethostbyname_r(host, &result, hbuf,
1506 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1507 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1509 log_error(LOG_LEVEL_ERROR,
1510 "Timeout #%u while trying to resolve %s. Trying again.",
1513 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1514 while (NULL == (hostp = gethostbyname_r(host, &result,
1515 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1516 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1518 log_error(LOG_LEVEL_ERROR,
1519 "Timeout #%u while trying to resolve %s. Trying again.",
1522 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1524 * XXX: Doesn't retry in case of soft errors.
1525 * Does this gethostbyname_r version set h_errno?
1527 if (0 == gethostbyname_r(host, &result, &hdata))
1535 #elif defined(MUTEX_LOCKS_AVAILABLE)
1536 privoxy_mutex_lock(&resolver_mutex);
1537 while (NULL == (hostp = gethostbyname(host))
1538 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1540 log_error(LOG_LEVEL_ERROR,
1541 "Timeout #%u while trying to resolve %s. Trying again.",
1544 privoxy_mutex_unlock(&resolver_mutex);
1546 while (NULL == (hostp = gethostbyname(host))
1547 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1549 log_error(LOG_LEVEL_ERROR,
1550 "Timeout #%u while trying to resolve %s. Trying again.",
1553 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1555 * On Mac OSX, if a domain exists but doesn't have a type A
1556 * record associated with it, the h_addr member of the struct
1557 * hostent returned by gethostbyname is NULL, even if h_length
1558 * is 4. Therefore the second test below.
1560 if (hostp == NULL || hostp->h_addr == NULL)
1563 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1564 return(INADDR_NONE);
1566 if (hostp->h_addrtype != AF_INET)
1569 errno = WSAEPROTOTYPE;
1573 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1574 return(INADDR_NONE);
1576 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1578 return(inaddr.sin_addr.s_addr);
1583 /*********************************************************************
1585 * Function : socket_is_still_alive
1587 * Description : Figures out whether or not a socket is still alive.
1590 * 1 : sfd = The socket to check.
1592 * Returns : TRUE for yes, otherwise FALSE.
1594 *********************************************************************/
1595 int socket_is_still_alive(jb_socket sfd)
1598 int no_data_waiting;
1601 struct pollfd poll_fd[1];
1603 memset(poll_fd, 0, sizeof(poll_fd));
1604 poll_fd[0].fd = sfd;
1605 poll_fd[0].events = POLLIN;
1607 poll_result = poll(poll_fd, 1, 0);
1609 if (-1 == poll_result)
1611 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1614 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1616 fd_set readable_fds;
1617 struct timeval timeout;
1620 memset(&timeout, '\0', sizeof(timeout));
1621 FD_ZERO(&readable_fds);
1622 FD_SET(sfd, &readable_fds);
1624 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1627 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1630 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1631 #endif /* def HAVE_POLL */
1633 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1637 #ifdef FEATURE_EXTERNAL_FILTERS
1638 /*********************************************************************
1640 * Function : mark_socket_for_close_on_execute
1642 * Description : Marks a socket for close on execute.
1644 * Used so that external filters have no direct
1645 * access to sockets they shouldn't care about.
1647 * Not implemented for all platforms.
1650 * 1 : fd = The socket to mark
1654 *********************************************************************/
1655 void mark_socket_for_close_on_execute(jb_socket fd)
1657 #ifdef FEATURE_PTHREAD
1660 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1664 log_error(LOG_LEVEL_ERROR,
1665 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1668 #warning "Sockets will be visible to external filters"
1671 #endif /* def FEATURE_EXTERNAL_FILTERS */