1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.147 2017/06/26 12:12:55 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
120 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
122 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
125 /*********************************************************************
127 * Function : set_no_delay_flag
129 * Description : Disables the Nagle algorithm (TCP send coalescence)
130 * for the given socket.
133 * 1 : fd = The file descriptor to operate on
137 *********************************************************************/
138 static void set_no_delay_flag(int fd)
143 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
145 log_error(LOG_LEVEL_ERROR,
146 "Failed to disable TCP coalescence for socket %d", fd);
149 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
150 #endif /* def TCP_NODELAY */
153 /*********************************************************************
155 * Function : connect_to
157 * Description : Open a socket and connect to it. Will check
158 * that this is allowed according to ACL.
161 * 1 : host = hostname to connect to
162 * 2 : portnum = port to connect to (XXX: should be unsigned)
163 * 3 : csp = Current client state (buffers, headers, etc...)
165 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
168 *********************************************************************/
169 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
172 int forwarded_connect_retries = 0;
177 * XXX: The whole errno overloading is ridiculous and should
178 * be replaced with something sane and thread safe
182 fd = rfc2553_connect_to(host, portnum, csp);
184 fd = no_rfc2553_connect_to(host, portnum, csp);
186 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
187 || (csp->fwd == NULL)
188 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
192 forwarded_connect_retries++;
193 if (csp->config->forwarded_connect_retries != 0)
195 log_error(LOG_LEVEL_ERROR,
196 "Attempt %d of %d to connect to %s failed. Trying again.",
197 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
200 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
206 /* Getaddrinfo implementation */
207 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
209 struct addrinfo hints, *result, *rp;
214 struct pollfd poll_fd[1];
217 struct timeval timeout;
219 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
224 * XXX: Initializeing it here is only necessary
225 * because not all situations are properly
228 int socket_error = 0;
231 struct access_control_addr dst[1];
232 #endif /* def FEATURE_ACL */
234 /* Don't leak memory when retrying. */
235 freez(csp->error_message);
236 freez(csp->http->host_ip_addr_str);
238 retval = snprintf(service, sizeof(service), "%d", portnum);
239 if ((-1 == retval) || (sizeof(service) <= retval))
241 log_error(LOG_LEVEL_ERROR,
242 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
244 csp->error_message = strdup("Invalid port number");
245 csp->http->host_ip_addr_str = strdup("unknown");
246 return(JB_INVALID_SOCKET);
249 memset((char *)&hints, 0, sizeof(hints));
250 hints.ai_family = AF_UNSPEC;
251 hints.ai_socktype = SOCK_STREAM;
252 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
254 hints.ai_flags |= AI_ADDRCONFIG;
256 if ((retval = getaddrinfo(host, service, &hints, &result)))
258 log_error(LOG_LEVEL_INFO,
259 "Can not resolve %s: %s", host, gai_strerror(retval));
260 /* XXX: Should find a better way to propagate this error. */
262 csp->error_message = strdup(gai_strerror(retval));
263 csp->http->host_ip_addr_str = strdup("unknown");
264 return(JB_INVALID_SOCKET);
267 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
269 for (rp = result; rp != NULL; rp = rp->ai_next)
273 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
275 if (block_acl(dst, csp))
278 socket_error = errno = SOCEPERM;
280 socket_error = errno = EPERM;
284 #endif /* def FEATURE_ACL */
286 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
287 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
290 log_error(LOG_LEVEL_ERROR,
291 "Failed to get the host name from the socket structure: %s",
292 gai_strerror(retval));
296 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
298 if (fd == JB_INVALID_SOCKET)
308 if (fd >= FD_SETSIZE)
310 log_error(LOG_LEVEL_ERROR,
311 "Server socket number too high to use select(): %d >= %d",
314 freeaddrinfo(result);
315 return JB_INVALID_SOCKET;
320 #ifdef FEATURE_EXTERNAL_FILTERS
321 mark_socket_for_close_on_execute(fd);
324 set_no_delay_flag(fd);
326 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
327 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
330 fcntl(fd, F_SETFL, flags);
332 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
335 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
338 errno = sock_errno();
342 if (errno == WSAEINPROGRESS)
343 #else /* ifndef _WIN32 */
344 if (errno == EINPROGRESS)
345 #endif /* ndef _WIN32 || __OS2__ */
352 socket_error = errno;
363 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
367 fcntl(fd, F_SETFL, flags);
369 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
373 poll_fd[0].events = POLLOUT;
375 retval = poll(poll_fd, 1, 30000);
378 if (rp->ai_next != NULL)
380 /* Log this now as we'll try another address next */
381 log_error(LOG_LEVEL_CONNECT,
382 "Could not connect to [%s]:%s: Operation timed out.",
383 csp->http->host_ip_addr_str, service);
388 * This is the last address, don't log this now
389 * as it would result in a duplicated log message.
391 socket_error = ETIMEDOUT;
396 /* wait for connection to complete */
400 memset(&timeout, 0, sizeof(timeout));
403 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
404 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
405 && FD_ISSET(fd, &wfds))
408 socklen_t optlen = sizeof(socket_error);
409 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
413 /* Connection established, no need to try other addresses. */
416 if (rp->ai_next != NULL)
419 * There's another address we can try, so log that this
420 * one didn't work out. If the last one fails, too,
421 * it will get logged outside the loop body so we don't
422 * have to mention it here.
424 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
425 csp->http->host_ip_addr_str, service, strerror(socket_error));
430 socket_error = errno;
431 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
432 "the connection to [%s]:%s: %s; dropping connection.",
433 csp->http->host_ip_addr_str, service, strerror(errno));
437 /* Connection failed, try next address */
441 freeaddrinfo(result);
444 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
445 host, service, strerror(socket_error));
446 csp->error_message = strdup(strerror(socket_error));
447 return(JB_INVALID_SOCKET);
449 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
450 host, csp->http->host_ip_addr_str, service);
456 #else /* ndef HAVE_RFC2553 */
457 /* Pre-getaddrinfo implementation */
459 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
461 struct sockaddr_in inaddr;
465 struct pollfd poll_fd[1];
468 struct timeval tv[1];
470 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
475 struct access_control_addr dst[1];
476 #endif /* def FEATURE_ACL */
478 /* Don't leak memory when retrying. */
479 freez(csp->http->host_ip_addr_str);
481 memset((char *)&inaddr, 0, sizeof inaddr);
483 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
485 csp->http->host_ip_addr_str = strdup("unknown");
486 return(JB_INVALID_SOCKET);
490 dst->addr = ntohl(addr);
493 if (block_acl(dst, csp))
500 return(JB_INVALID_SOCKET);
502 #endif /* def FEATURE_ACL */
504 inaddr.sin_addr.s_addr = addr;
505 inaddr.sin_family = AF_INET;
506 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
509 if (sizeof(inaddr.sin_port) == sizeof(short))
510 #endif /* ndef _WIN32 */
512 inaddr.sin_port = htons((unsigned short) portnum);
517 inaddr.sin_port = htonl((unsigned long)portnum);
519 #endif /* ndef _WIN32 */
521 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
523 if (fd == JB_INVALID_SOCKET)
528 return(JB_INVALID_SOCKET);
533 if (fd >= FD_SETSIZE)
535 log_error(LOG_LEVEL_ERROR,
536 "Server socket number too high to use select(): %d >= %d",
539 return JB_INVALID_SOCKET;
544 set_no_delay_flag(fd);
546 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
547 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
550 fcntl(fd, F_SETFL, flags);
551 #ifdef FEATURE_EXTERNAL_FILTERS
552 mark_socket_for_close_on_execute(fd);
555 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
557 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
560 if (errno == WSAEINPROGRESS)
562 if (sock_errno() == EINPROGRESS)
563 #else /* ifndef _WIN32 */
564 if (errno == EINPROGRESS)
565 #endif /* ndef _WIN32 || __OS2__ */
571 if (sock_errno() != EINTR)
577 return(JB_INVALID_SOCKET);
581 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
585 fcntl(fd, F_SETFL, flags);
587 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
591 poll_fd[0].events = POLLOUT;
593 if (poll(poll_fd, 1, 30000) <= 0)
595 /* wait for connection to complete */
602 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
603 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
607 return(JB_INVALID_SOCKET);
612 #endif /* ndef HAVE_RFC2553 */
615 /*********************************************************************
617 * Function : write_socket
619 * Description : Write the contents of buf (for n bytes) to socket fd.
622 * 1 : fd = file descriptor (aka. handle) of socket to write to.
623 * 2 : buf = pointer to data to be written.
624 * 3 : len = length of data to be written to the socket "fd".
626 * Returns : 0 on success (entire buffer sent).
629 *********************************************************************/
631 int write_socket(jb_socket fd, const char *buf, ssize_t len)
633 int write_socket(jb_socket fd, const char *buf, size_t len)
642 if (!daemon_mode && fd <= 3)
644 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
649 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
652 return (send(fd, buf, (int)len, 0) != (int)len);
653 #elif defined(__BEOS__) || defined(AMIGA)
654 return (send(fd, buf, len, 0) != len);
655 #elif defined(__OS2__)
657 * Break the data up into SOCKET_SEND_MAX chunks for sending...
658 * OS/2 seemed to complain when the chunks were too large.
660 #define SOCKET_SEND_MAX 65000
662 int send_len, send_rc = 0, i = 0;
663 while ((i < len) && (send_rc != -1))
665 if ((i + SOCKET_SEND_MAX) > len)
668 send_len = SOCKET_SEND_MAX;
669 send_rc = send(fd,(char*)buf + i, send_len, 0);
677 return (write(fd, buf, len) != len);
683 /*********************************************************************
685 * Function : read_socket
687 * Description : Read from a TCP/IP socket in a platform independent way.
690 * 1 : fd = file descriptor of the socket to read
691 * 2 : buf = pointer to buffer where data will be written
692 * Must be >= len bytes long.
693 * 3 : len = maximum number of bytes to read
695 * Returns : On success, the number of bytes read is returned (zero
696 * indicates end of file), and the file position is advanced
697 * by this number. It is not an error if this number is
698 * smaller than the number of bytes requested; this may hap-
699 * pen for example because fewer bytes are actually available
700 * right now (maybe because we were close to end-of-file, or
701 * because we are reading from a pipe, or from a terminal,
702 * or because read() was interrupted by a signal). On error,
703 * -1 is returned, and errno is set appropriately. In this
704 * case it is left unspecified whether the file position (if
707 *********************************************************************/
708 int read_socket(jb_socket fd, char *buf, int len)
718 ret = recv(fd, buf, len, 0);
719 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
720 ret = recv(fd, buf, (size_t)len, 0);
722 ret = (int)read(fd, buf, (size_t)len);
727 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
734 /*********************************************************************
736 * Function : data_is_available
738 * Description : Waits for data to arrive on a socket.
741 * 1 : fd = file descriptor of the socket to read
742 * 2 : seconds_to_wait = number of seconds after which we give up.
744 * Returns : TRUE if data arrived in time,
747 *********************************************************************/
748 int data_is_available(jb_socket fd, int seconds_to_wait)
753 struct pollfd poll_fd[1];
756 poll_fd[0].events = POLLIN;
758 n = poll(poll_fd, 1, seconds_to_wait * 1000);
761 struct timeval timeout;
763 memset(&timeout, 0, sizeof(timeout));
764 timeout.tv_sec = seconds_to_wait;
767 /* Copy and pasted from jcc.c ... */
768 memset(&rfds, 0, sizeof(fd_set));
774 n = select(fd+1, &rfds, NULL, NULL, &timeout);
778 * XXX: Do we care about the different error conditions?
780 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
784 /*********************************************************************
786 * Function : close_socket
788 * Description : Closes a TCP/IP socket
791 * 1 : fd = file descriptor of socket to be closed
795 *********************************************************************/
796 void close_socket(jb_socket fd)
798 #if defined(_WIN32) || defined(__BEOS__)
802 #elif defined(__OS2__)
810 /*********************************************************************
812 * Function : drain_and_close_socket
814 * Description : Closes a TCP/IP socket after draining unread data
817 * 1 : fd = file descriptor of the socket to be closed
821 *********************************************************************/
822 void drain_and_close_socket(jb_socket fd)
824 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
825 if (socket_is_still_alive(fd))
828 int bytes_drained_total = 0;
832 /* Apparently Windows has shutdown() but not SHUT_WR. */
836 if (0 != shutdown(fd, SHUT_WR))
838 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
841 #define ARBITRARY_DRAIN_LIMIT 10000
846 if (!data_is_available(fd, 0))
849 * If there is no data available right now, don't try
850 * to drain the socket as read_socket() could block.
855 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
856 if (bytes_drained < 0)
858 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
860 else if (bytes_drained > 0)
862 bytes_drained_total += bytes_drained;
863 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
865 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
869 } while (bytes_drained > 0);
870 if (bytes_drained_total != 0)
872 log_error(LOG_LEVEL_CONNECT,
873 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
882 /*********************************************************************
884 * Function : bind_port
886 * Description : Call socket, set socket options, and listen.
887 * Called by listen_loop to "boot up" our proxy address.
890 * 1 : hostnam = TCP/IP address to bind/listen to
891 * 2 : portnum = port to listen on
892 * 3 : backlog = Listen backlog
893 * 4 : 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, int backlog, 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, 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 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1381 } while (afd < 0 && errno == EINTR);
1390 struct linger linger_options;
1391 linger_options.l_onoff = 1;
1392 linger_options.l_linger = 5;
1393 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1395 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1402 if (afd >= FD_SETSIZE)
1404 log_error(LOG_LEVEL_ERROR,
1405 "Client socket number too high to use select(): %d >= %d",
1413 #ifdef FEATURE_EXTERNAL_FILTERS
1414 mark_socket_for_close_on_execute(afd);
1417 set_no_delay_flag(afd);
1421 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1422 retval = getnameinfo((struct sockaddr *) &client, c_length,
1423 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1424 if (!csp->ip_addr_str || retval)
1426 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1427 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1428 freez(csp->ip_addr_str);
1432 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1433 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1434 #endif /* def HAVE_RFC2553 */
1437 * Save the name and port of the accepting socket for later lookup.
1439 * The string needs space for strlen(...) + 7 characters:
1440 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1442 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1443 listen_addr_size = strlen(host_addr) + 7;
1444 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1445 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1446 "%s:%d", host_addr, csp->config->hport[i]);
1447 if ((-1 == retval) || listen_addr_size <= retval)
1449 log_error(LOG_LEVEL_ERROR,
1450 "Server name (%s) and port number (%d) ASCII decimal representation"
1451 "don't fit into %d bytes",
1452 host_addr, csp->config->hport[i], listen_addr_size);
1461 /*********************************************************************
1463 * Function : resolve_hostname_to_ip
1465 * Description : Resolve a hostname to an internet tcp/ip address.
1466 * NULL or an empty string resolve to INADDR_ANY.
1469 * 1 : host = hostname to resolve
1471 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1473 *********************************************************************/
1474 unsigned long resolve_hostname_to_ip(const char *host)
1476 struct sockaddr_in inaddr;
1477 struct hostent *hostp;
1478 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1479 struct hostent result;
1480 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1481 char hbuf[HOSTENT_BUFFER_SIZE];
1483 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1484 struct hostent_data hdata;
1485 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1486 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1488 if ((host == NULL) || (*host == '\0'))
1493 memset((char *) &inaddr, 0, sizeof inaddr);
1495 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1497 unsigned int dns_retries = 0;
1498 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1499 while (gethostbyname_r(host, &result, hbuf,
1500 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1501 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1503 log_error(LOG_LEVEL_ERROR,
1504 "Timeout #%u while trying to resolve %s. Trying again.",
1507 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1508 while (NULL == (hostp = gethostbyname_r(host, &result,
1509 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1510 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1512 log_error(LOG_LEVEL_ERROR,
1513 "Timeout #%u while trying to resolve %s. Trying again.",
1516 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1518 * XXX: Doesn't retry in case of soft errors.
1519 * Does this gethostbyname_r version set h_errno?
1521 if (0 == gethostbyname_r(host, &result, &hdata))
1529 #elif defined(MUTEX_LOCKS_AVAILABLE)
1530 privoxy_mutex_lock(&resolver_mutex);
1531 while (NULL == (hostp = gethostbyname(host))
1532 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1534 log_error(LOG_LEVEL_ERROR,
1535 "Timeout #%u while trying to resolve %s. Trying again.",
1538 privoxy_mutex_unlock(&resolver_mutex);
1540 while (NULL == (hostp = gethostbyname(host))
1541 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1543 log_error(LOG_LEVEL_ERROR,
1544 "Timeout #%u while trying to resolve %s. Trying again.",
1547 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1549 * On Mac OSX, if a domain exists but doesn't have a type A
1550 * record associated with it, the h_addr member of the struct
1551 * hostent returned by gethostbyname is NULL, even if h_length
1552 * is 4. Therefore the second test below.
1554 if (hostp == NULL || hostp->h_addr == NULL)
1557 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1558 return(INADDR_NONE);
1560 if (hostp->h_addrtype != AF_INET)
1563 errno = WSAEPROTOTYPE;
1567 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1568 return(INADDR_NONE);
1570 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1572 return(inaddr.sin_addr.s_addr);
1577 /*********************************************************************
1579 * Function : socket_is_still_alive
1581 * Description : Figures out whether or not a socket is still alive.
1584 * 1 : sfd = The socket to check.
1586 * Returns : TRUE for yes, otherwise FALSE.
1588 *********************************************************************/
1589 int socket_is_still_alive(jb_socket sfd)
1592 int no_data_waiting;
1595 struct pollfd poll_fd[1];
1597 memset(poll_fd, 0, sizeof(poll_fd));
1598 poll_fd[0].fd = sfd;
1599 poll_fd[0].events = POLLIN;
1601 poll_result = poll(poll_fd, 1, 0);
1603 if (-1 == poll_result)
1605 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1608 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1610 fd_set readable_fds;
1611 struct timeval timeout;
1614 memset(&timeout, '\0', sizeof(timeout));
1615 FD_ZERO(&readable_fds);
1616 FD_SET(sfd, &readable_fds);
1618 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1621 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1624 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1625 #endif /* def HAVE_POLL */
1627 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1631 #ifdef FEATURE_EXTERNAL_FILTERS
1632 /*********************************************************************
1634 * Function : mark_socket_for_close_on_execute
1636 * Description : Marks a socket for close on execute.
1638 * Used so that external filters have no direct
1639 * access to sockets they shouldn't care about.
1641 * Not implemented for all platforms.
1644 * 1 : fd = The socket to mark
1648 *********************************************************************/
1649 void mark_socket_for_close_on_execute(jb_socket fd)
1651 #ifdef FEATURE_PTHREAD
1654 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1658 log_error(LOG_LEVEL_ERROR,
1659 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1662 #warning "Sockets will be visible to external filters"
1665 #endif /* def FEATURE_EXTERNAL_FILTERS */