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 TCP coalescence for the given socket.
132 * 1 : fd = The file descriptor to operate on
136 *********************************************************************/
137 static void set_no_delay_flag(int fd)
142 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
144 log_error(LOG_LEVEL_ERROR,
145 "Failed to disable TCP coalescence for socket %d", fd);
148 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
149 #endif /* def TCP_NODELAY */
152 /*********************************************************************
154 * Function : connect_to
156 * Description : Open a socket and connect to it. Will check
157 * that this is allowed according to ACL.
160 * 1 : host = hostname to connect to
161 * 2 : portnum = port to connect to (XXX: should be unsigned)
162 * 3 : csp = Current client state (buffers, headers, etc...)
164 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
167 *********************************************************************/
168 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
171 int forwarded_connect_retries = 0;
176 * XXX: The whole errno overloading is ridiculous and should
177 * be replaced with something sane and thread safe
181 fd = rfc2553_connect_to(host, portnum, csp);
183 fd = no_rfc2553_connect_to(host, portnum, csp);
185 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
186 || (csp->fwd == NULL)
187 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
191 forwarded_connect_retries++;
192 if (csp->config->forwarded_connect_retries != 0)
194 log_error(LOG_LEVEL_ERROR,
195 "Attempt %d of %d to connect to %s failed. Trying again.",
196 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
199 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
205 /* Getaddrinfo implementation */
206 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
208 struct addrinfo hints, *result, *rp;
213 struct pollfd poll_fd[1];
216 struct timeval timeout;
218 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
223 * XXX: Initializeing it here is only necessary
224 * because not all situations are properly
227 int socket_error = 0;
230 struct access_control_addr dst[1];
231 #endif /* def FEATURE_ACL */
233 /* Don't leak memory when retrying. */
234 freez(csp->error_message);
235 freez(csp->http->host_ip_addr_str);
237 retval = snprintf(service, sizeof(service), "%d", portnum);
238 if ((-1 == retval) || (sizeof(service) <= retval))
240 log_error(LOG_LEVEL_ERROR,
241 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
243 csp->error_message = strdup("Invalid port number");
244 csp->http->host_ip_addr_str = strdup("unknown");
245 return(JB_INVALID_SOCKET);
248 memset((char *)&hints, 0, sizeof(hints));
249 hints.ai_family = AF_UNSPEC;
250 hints.ai_socktype = SOCK_STREAM;
251 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
253 hints.ai_flags |= AI_ADDRCONFIG;
255 if ((retval = getaddrinfo(host, service, &hints, &result)))
257 log_error(LOG_LEVEL_INFO,
258 "Can not resolve %s: %s", host, gai_strerror(retval));
259 /* XXX: Should find a better way to propagate this error. */
261 csp->error_message = strdup(gai_strerror(retval));
262 csp->http->host_ip_addr_str = strdup("unknown");
263 return(JB_INVALID_SOCKET);
266 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
268 for (rp = result; rp != NULL; rp = rp->ai_next)
272 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
274 if (block_acl(dst, csp))
277 socket_error = errno = SOCEPERM;
279 socket_error = errno = EPERM;
283 #endif /* def FEATURE_ACL */
285 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
286 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
289 log_error(LOG_LEVEL_ERROR,
290 "Failed to get the host name from the socket structure: %s",
291 gai_strerror(retval));
295 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
297 if (fd == JB_INVALID_SOCKET)
307 if (fd >= FD_SETSIZE)
309 log_error(LOG_LEVEL_ERROR,
310 "Server socket number too high to use select(): %d >= %d",
313 freeaddrinfo(result);
314 return JB_INVALID_SOCKET;
319 #ifdef FEATURE_EXTERNAL_FILTERS
320 mark_socket_for_close_on_execute(fd);
323 set_no_delay_flag(fd);
325 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
326 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
329 fcntl(fd, F_SETFL, flags);
331 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
334 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
337 errno = sock_errno();
341 if (errno == WSAEINPROGRESS)
342 #else /* ifndef _WIN32 */
343 if (errno == EINPROGRESS)
344 #endif /* ndef _WIN32 || __OS2__ */
351 socket_error = errno;
362 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
366 fcntl(fd, F_SETFL, flags);
368 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
372 poll_fd[0].events = POLLOUT;
374 retval = poll(poll_fd, 1, 30000);
377 if (rp->ai_next != NULL)
379 /* Log this now as we'll try another address next */
380 log_error(LOG_LEVEL_CONNECT,
381 "Could not connect to [%s]:%s: Operation timed out.",
382 csp->http->host_ip_addr_str, service);
387 * This is the last address, don't log this now
388 * as it would result in a duplicated log message.
390 socket_error = ETIMEDOUT;
395 /* wait for connection to complete */
399 memset(&timeout, 0, sizeof(timeout));
402 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
403 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
404 && FD_ISSET(fd, &wfds))
407 socklen_t optlen = sizeof(socket_error);
408 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
412 /* Connection established, no need to try other addresses. */
415 if (rp->ai_next != NULL)
418 * There's another address we can try, so log that this
419 * one didn't work out. If the last one fails, too,
420 * it will get logged outside the loop body so we don't
421 * have to mention it here.
423 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
424 csp->http->host_ip_addr_str, service, strerror(socket_error));
429 socket_error = errno;
430 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
431 "the connection to [%s]:%s: %s; dropping connection.",
432 csp->http->host_ip_addr_str, service, strerror(errno));
436 /* Connection failed, try next address */
440 freeaddrinfo(result);
443 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
444 host, service, strerror(socket_error));
445 csp->error_message = strdup(strerror(socket_error));
446 return(JB_INVALID_SOCKET);
448 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
449 host, csp->http->host_ip_addr_str, service);
455 #else /* ndef HAVE_RFC2553 */
456 /* Pre-getaddrinfo implementation */
458 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
460 struct sockaddr_in inaddr;
464 struct pollfd poll_fd[1];
467 struct timeval tv[1];
469 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
474 struct access_control_addr dst[1];
475 #endif /* def FEATURE_ACL */
477 /* Don't leak memory when retrying. */
478 freez(csp->http->host_ip_addr_str);
480 memset((char *)&inaddr, 0, sizeof inaddr);
482 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
484 csp->http->host_ip_addr_str = strdup("unknown");
485 return(JB_INVALID_SOCKET);
489 dst->addr = ntohl(addr);
492 if (block_acl(dst, csp))
499 return(JB_INVALID_SOCKET);
501 #endif /* def FEATURE_ACL */
503 inaddr.sin_addr.s_addr = addr;
504 inaddr.sin_family = AF_INET;
505 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
508 if (sizeof(inaddr.sin_port) == sizeof(short))
509 #endif /* ndef _WIN32 */
511 inaddr.sin_port = htons((unsigned short) portnum);
516 inaddr.sin_port = htonl((unsigned long)portnum);
518 #endif /* ndef _WIN32 */
520 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
522 if (fd == JB_INVALID_SOCKET)
527 return(JB_INVALID_SOCKET);
532 if (fd >= FD_SETSIZE)
534 log_error(LOG_LEVEL_ERROR,
535 "Server socket number too high to use select(): %d >= %d",
538 return JB_INVALID_SOCKET;
543 set_no_delay_flag(fd);
545 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
546 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
549 fcntl(fd, F_SETFL, flags);
550 #ifdef FEATURE_EXTERNAL_FILTERS
551 mark_socket_for_close_on_execute(fd);
554 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
556 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
559 if (errno == WSAEINPROGRESS)
561 if (sock_errno() == EINPROGRESS)
562 #else /* ifndef _WIN32 */
563 if (errno == EINPROGRESS)
564 #endif /* ndef _WIN32 || __OS2__ */
570 if (sock_errno() != EINTR)
576 return(JB_INVALID_SOCKET);
580 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
584 fcntl(fd, F_SETFL, flags);
586 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
590 poll_fd[0].events = POLLOUT;
592 if (poll(poll_fd, 1, 30000) <= 0)
594 /* wait for connection to complete */
601 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
602 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
606 return(JB_INVALID_SOCKET);
611 #endif /* ndef HAVE_RFC2553 */
614 /*********************************************************************
616 * Function : write_socket
618 * Description : Write the contents of buf (for n bytes) to socket fd.
621 * 1 : fd = file descriptor (aka. handle) of socket to write to.
622 * 2 : buf = pointer to data to be written.
623 * 3 : len = length of data to be written to the socket "fd".
625 * Returns : 0 on success (entire buffer sent).
628 *********************************************************************/
630 int write_socket(jb_socket fd, const char *buf, ssize_t len)
632 int write_socket(jb_socket fd, const char *buf, size_t len)
641 if (!daemon_mode && fd <= 3)
643 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
648 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
651 return (send(fd, buf, (int)len, 0) != (int)len);
652 #elif defined(__BEOS__) || defined(AMIGA)
653 return (send(fd, buf, len, 0) != len);
654 #elif defined(__OS2__)
656 * Break the data up into SOCKET_SEND_MAX chunks for sending...
657 * OS/2 seemed to complain when the chunks were too large.
659 #define SOCKET_SEND_MAX 65000
661 int send_len, send_rc = 0, i = 0;
662 while ((i < len) && (send_rc != -1))
664 if ((i + SOCKET_SEND_MAX) > len)
667 send_len = SOCKET_SEND_MAX;
668 send_rc = send(fd,(char*)buf + i, send_len, 0);
676 return (write(fd, buf, len) != len);
682 /*********************************************************************
684 * Function : read_socket
686 * Description : Read from a TCP/IP socket in a platform independent way.
689 * 1 : fd = file descriptor of the socket to read
690 * 2 : buf = pointer to buffer where data will be written
691 * Must be >= len bytes long.
692 * 3 : len = maximum number of bytes to read
694 * Returns : On success, the number of bytes read is returned (zero
695 * indicates end of file), and the file position is advanced
696 * by this number. It is not an error if this number is
697 * smaller than the number of bytes requested; this may hap-
698 * pen for example because fewer bytes are actually available
699 * right now (maybe because we were close to end-of-file, or
700 * because we are reading from a pipe, or from a terminal,
701 * or because read() was interrupted by a signal). On error,
702 * -1 is returned, and errno is set appropriately. In this
703 * case it is left unspecified whether the file position (if
706 *********************************************************************/
707 int read_socket(jb_socket fd, char *buf, int len)
717 ret = recv(fd, buf, len, 0);
718 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
719 ret = recv(fd, buf, (size_t)len, 0);
721 ret = (int)read(fd, buf, (size_t)len);
726 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
733 /*********************************************************************
735 * Function : data_is_available
737 * Description : Waits for data to arrive on a socket.
740 * 1 : fd = file descriptor of the socket to read
741 * 2 : seconds_to_wait = number of seconds after which we give up.
743 * Returns : TRUE if data arrived in time,
746 *********************************************************************/
747 int data_is_available(jb_socket fd, int seconds_to_wait)
752 struct pollfd poll_fd[1];
755 poll_fd[0].events = POLLIN;
757 n = poll(poll_fd, 1, seconds_to_wait * 1000);
760 struct timeval timeout;
762 memset(&timeout, 0, sizeof(timeout));
763 timeout.tv_sec = seconds_to_wait;
766 /* Copy and pasted from jcc.c ... */
767 memset(&rfds, 0, sizeof(fd_set));
773 n = select(fd+1, &rfds, NULL, NULL, &timeout);
777 * XXX: Do we care about the different error conditions?
779 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
783 /*********************************************************************
785 * Function : close_socket
787 * Description : Closes a TCP/IP socket
790 * 1 : fd = file descriptor of socket to be closed
794 *********************************************************************/
795 void close_socket(jb_socket fd)
797 #if defined(_WIN32) || defined(__BEOS__)
801 #elif defined(__OS2__)
809 /*********************************************************************
811 * Function : drain_and_close_socket
813 * Description : Closes a TCP/IP socket after draining unread data
816 * 1 : fd = file descriptor of the socket to be closed
820 *********************************************************************/
821 void drain_and_close_socket(jb_socket fd)
823 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
824 if (socket_is_still_alive(fd))
827 int bytes_drained_total = 0;
831 /* Apparently Windows has shutdown() but not SHUT_WR. */
835 if (0 != shutdown(fd, SHUT_WR))
837 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
840 #define ARBITRARY_DRAIN_LIMIT 10000
845 if (!data_is_available(fd, 0))
848 * If there is no data available right now, don't try
849 * to drain the socket as read_socket() could block.
854 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
855 if (bytes_drained < 0)
857 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
859 else if (bytes_drained > 0)
861 bytes_drained_total += bytes_drained;
862 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
864 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
868 } while (bytes_drained > 0);
869 if (bytes_drained_total != 0)
871 log_error(LOG_LEVEL_CONNECT,
872 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
881 /*********************************************************************
883 * Function : bind_port
885 * Description : Call socket, set socket options, and listen.
886 * Called by listen_loop to "boot up" our proxy address.
889 * 1 : hostnam = TCP/IP address to bind/listen to
890 * 2 : portnum = port to listen on
891 * 3 : backlog = Listen backlog
892 * 4 : pfd = pointer used to return file descriptor.
894 * Returns : if success, returns 0 and sets *pfd.
895 * if failure, returns -3 if address is in use,
896 * -2 if address unresolvable,
898 *********************************************************************/
899 int bind_port(const char *hostnam, int portnum, int backlog, jb_socket *pfd)
902 struct addrinfo hints;
903 struct addrinfo *result, *rp;
905 * XXX: portnum should be a string to allow symbolic service
906 * names in the configuration file and to avoid the following
912 struct sockaddr_in inaddr;
913 #endif /* def HAVE_RFC2553 */
917 #endif /* ndef _WIN32 */
919 *pfd = JB_INVALID_SOCKET;
922 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
923 if ((-1 == retval) || (sizeof(servnam) <= retval))
925 log_error(LOG_LEVEL_ERROR,
926 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
931 memset(&hints, 0, sizeof(struct addrinfo));
935 * XXX: This is a hack. The right thing to do
936 * would be to bind to both AF_INET and AF_INET6.
937 * This will also fail if there is no AF_INET
940 hints.ai_family = AF_INET;
944 hints.ai_family = AF_UNSPEC;
946 hints.ai_socktype = SOCK_STREAM;
947 hints.ai_flags = AI_PASSIVE;
948 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
949 hints.ai_canonname = NULL;
950 hints.ai_addr = NULL;
951 hints.ai_next = NULL;
953 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
955 log_error(LOG_LEVEL_ERROR,
956 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
960 memset((char *)&inaddr, '\0', sizeof inaddr);
962 inaddr.sin_family = AF_INET;
963 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
965 if (inaddr.sin_addr.s_addr == INADDR_NONE)
971 if (sizeof(inaddr.sin_port) == sizeof(short))
972 #endif /* ndef _WIN32 */
974 inaddr.sin_port = htons((unsigned short) portnum);
979 inaddr.sin_port = htonl((unsigned long) portnum);
981 #endif /* ndef _WIN32 */
982 #endif /* def HAVE_RFC2553 */
985 for (rp = result; rp != NULL; rp = rp->ai_next)
987 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
989 fd = socket(AF_INET, SOCK_STREAM, 0);
990 #endif /* def HAVE_RFC2553 */
993 if (fd == JB_INVALID_SOCKET)
1005 #ifdef FEATURE_EXTERNAL_FILTERS
1006 mark_socket_for_close_on_execute(fd);
1011 * This is not needed for Win32 - in fact, it stops
1012 * duplicate instances of Privoxy from being caught.
1014 * On UNIX, we assume the user is sensible enough not
1015 * to start Privoxy multiple times on the same IP.
1016 * Without this, stopping and restarting Privoxy
1017 * from a script fails.
1018 * Note: SO_REUSEADDR is meant to only take over
1019 * sockets which are *not* in listen state in Linux,
1020 * e.g. sockets in TIME_WAIT. YMMV.
1022 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
1023 #endif /* ndef _WIN32 */
1026 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
1028 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
1032 errno = WSAGetLastError();
1033 if (errno == WSAEADDRINUSE)
1035 if (errno == EADDRINUSE)
1039 freeaddrinfo(result);
1047 #ifndef HAVE_RFC2553
1056 /* bind() succeeded, escape from for-loop */
1058 * XXX: Support multiple listening sockets (e.g. localhost
1059 * resolves to AF_INET and AF_INET6, but only the first address
1066 freeaddrinfo(result);
1069 /* All bind()s failed */
1072 #endif /* ndef HAVE_RFC2553 */
1074 while (listen(fd, backlog) == -1)
1089 /*********************************************************************
1091 * Function : get_host_information
1093 * Description : Determines the IP address the client used to
1094 * reach us and the hostname associated with it.
1096 * XXX: Most of the code has been copy and pasted
1097 * from accept_connection() and not all of the
1098 * ifdefs paths have been tested afterwards.
1101 * 1 : afd = File descriptor returned from accept().
1102 * 2 : ip_address = Pointer to return the pointer to
1103 * the ip address string.
1104 * 3 : port = Pointer to return the pointer to
1105 * the TCP port string.
1106 * 4 : hostname = Pointer to return the pointer to
1107 * the hostname or NULL if the caller
1108 * isn't interested in it.
1112 *********************************************************************/
1113 void get_host_information(jb_socket afd, char **ip_address, char **port,
1117 struct sockaddr_storage server;
1120 struct sockaddr_in server;
1121 struct hostent *host = NULL;
1122 #endif /* HAVE_RFC2553 */
1123 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1124 /* according to accept_connection() this fixes a warning. */
1125 int s_length, s_length_provided;
1127 socklen_t s_length, s_length_provided;
1129 #ifndef HAVE_RFC2553
1130 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1131 struct hostent result;
1132 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1133 struct hostent_data hdata;
1135 char hbuf[HOSTENT_BUFFER_SIZE];
1137 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1138 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1139 #endif /* ifndef HAVE_RFC2553 */
1140 s_length = s_length_provided = sizeof(server);
1142 if (NULL != hostname)
1149 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1151 if (s_length > s_length_provided)
1153 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1157 * XXX: Workaround for missing header on Windows when
1158 * configured with --disable-ipv6-support.
1159 * The proper fix is to not use NI_MAXSERV in
1160 * that case. It works by accident on other platforms
1161 * as <netdb.h> is included unconditionally there.
1164 #define NI_MAXSERV 32
1166 *port = malloc_or_die(NI_MAXSERV);
1169 *ip_address = malloc_or_die(NI_MAXHOST);
1170 retval = getnameinfo((struct sockaddr *) &server, s_length,
1171 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1172 NI_NUMERICHOST|NI_NUMERICSERV);
1175 log_error(LOG_LEVEL_ERROR,
1176 "Unable to print my own IP address: %s", gai_strerror(retval));
1182 *ip_address = strdup(inet_ntoa(server.sin_addr));
1183 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1184 #endif /* HAVE_RFC2553 */
1185 if (NULL == hostname)
1188 * We're done here, the caller isn't
1189 * interested in knowing the hostname.
1195 *hostname = malloc_or_die(NI_MAXHOST);
1196 retval = getnameinfo((struct sockaddr *) &server, s_length,
1197 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1200 log_error(LOG_LEVEL_ERROR,
1201 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1205 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1206 gethostbyaddr_r((const char *)&server.sin_addr,
1207 sizeof(server.sin_addr), AF_INET,
1208 &result, hbuf, HOSTENT_BUFFER_SIZE,
1210 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1211 host = gethostbyaddr_r((const char *)&server.sin_addr,
1212 sizeof(server.sin_addr), AF_INET,
1213 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1214 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1215 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1216 sizeof(server.sin_addr), AF_INET,
1225 #elif defined(MUTEX_LOCKS_AVAILABLE)
1226 privoxy_mutex_lock(&resolver_mutex);
1227 host = gethostbyaddr((const char *)&server.sin_addr,
1228 sizeof(server.sin_addr), AF_INET);
1229 privoxy_mutex_unlock(&resolver_mutex);
1231 host = gethostbyaddr((const char *)&server.sin_addr,
1232 sizeof(server.sin_addr), AF_INET);
1236 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1240 *hostname = strdup(host->h_name);
1242 #endif /* else def HAVE_RFC2553 */
1249 /*********************************************************************
1251 * Function : accept_connection
1253 * Description : Accepts a connection on one of possibly multiple
1254 * sockets. The socket(s) to check must have been
1255 * created using bind_port().
1258 * 1 : csp = Client state, cfd, ip_addr_str, and
1259 * ip_addr_long will be set by this routine.
1260 * 2 : fds = File descriptors returned from bind_port
1262 * Returns : when a connection is accepted, it returns 1 (TRUE).
1263 * On an error it returns 0 (FALSE).
1265 *********************************************************************/
1266 int accept_connection(struct client_state * csp, jb_socket fds[])
1269 /* XXX: client is stored directly into csp->tcp_addr */
1270 #define client (csp->tcp_addr)
1272 struct sockaddr_in client;
1275 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1276 /* Wierdness - fix a warning. */
1283 int max_selected_socket;
1285 struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
1286 nfds_t polled_sockets;
1288 fd_set selected_fds;
1291 const char *host_addr;
1292 size_t listen_addr_size;
1294 c_length = sizeof(client);
1297 memset(poll_fds, 0, sizeof(poll_fds));
1301 * Wait for a connection on any socket.
1302 * Return immediately if no socket is listening.
1303 * XXX: Why not treat this as fatal error?
1305 FD_ZERO(&selected_fds);
1307 max_selected_socket = 0;
1308 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1310 if (JB_INVALID_SOCKET != fds[i])
1313 poll_fds[i].fd = fds[i];
1314 poll_fds[i].events = POLLIN;
1317 FD_SET(fds[i], &selected_fds);
1319 if (max_selected_socket < fds[i] + 1)
1321 max_selected_socket = fds[i] + 1;
1325 if (0 == max_selected_socket)
1332 retval = poll(poll_fds, polled_sockets, -1);
1334 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1336 } while (retval < 0 && errno == EINTR);
1341 log_error(LOG_LEVEL_ERROR,
1342 "Waiting on new client failed because select(2) returned 0."
1343 " This should not happen.");
1347 log_error(LOG_LEVEL_ERROR,
1348 "Waiting on new client failed because of problems in select(2): "
1349 "%s.", strerror(errno));
1354 for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
1356 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1359 if (i >= MAX_LISTENING_SOCKETS)
1361 log_error(LOG_LEVEL_ERROR,
1362 "select(2) reported connected clients (number = %u, "
1363 "descriptor boundary = %u), but none found.",
1364 retval, max_selected_socket);
1369 /* Accept selected connection */
1371 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1372 if (afd == JB_INVALID_SOCKET)
1379 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1380 } while (afd < 0 && errno == EINTR);
1389 struct linger linger_options;
1390 linger_options.l_onoff = 1;
1391 linger_options.l_linger = 5;
1392 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1394 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1401 if (afd >= FD_SETSIZE)
1403 log_error(LOG_LEVEL_ERROR,
1404 "Client socket number too high to use select(): %d >= %d",
1412 #ifdef FEATURE_EXTERNAL_FILTERS
1413 mark_socket_for_close_on_execute(afd);
1416 set_no_delay_flag(afd);
1420 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1421 retval = getnameinfo((struct sockaddr *) &client, c_length,
1422 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1423 if (!csp->ip_addr_str || retval)
1425 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1426 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1427 freez(csp->ip_addr_str);
1431 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1432 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1433 #endif /* def HAVE_RFC2553 */
1436 * Save the name and port of the accepting socket for later lookup.
1438 * The string needs space for strlen(...) + 7 characters:
1439 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1441 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1442 listen_addr_size = strlen(host_addr) + 7;
1443 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1444 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1445 "%s:%d", host_addr, csp->config->hport[i]);
1446 if ((-1 == retval) || listen_addr_size <= retval)
1448 log_error(LOG_LEVEL_ERROR,
1449 "Server name (%s) and port number (%d) ASCII decimal representation"
1450 "don't fit into %d bytes",
1451 host_addr, csp->config->hport[i], listen_addr_size);
1460 /*********************************************************************
1462 * Function : resolve_hostname_to_ip
1464 * Description : Resolve a hostname to an internet tcp/ip address.
1465 * NULL or an empty string resolve to INADDR_ANY.
1468 * 1 : host = hostname to resolve
1470 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1472 *********************************************************************/
1473 unsigned long resolve_hostname_to_ip(const char *host)
1475 struct sockaddr_in inaddr;
1476 struct hostent *hostp;
1477 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1478 struct hostent result;
1479 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1480 char hbuf[HOSTENT_BUFFER_SIZE];
1482 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1483 struct hostent_data hdata;
1484 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1485 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1487 if ((host == NULL) || (*host == '\0'))
1492 memset((char *) &inaddr, 0, sizeof inaddr);
1494 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1496 unsigned int dns_retries = 0;
1497 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1498 while (gethostbyname_r(host, &result, hbuf,
1499 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1500 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1502 log_error(LOG_LEVEL_ERROR,
1503 "Timeout #%u while trying to resolve %s. Trying again.",
1506 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1507 while (NULL == (hostp = gethostbyname_r(host, &result,
1508 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1509 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1511 log_error(LOG_LEVEL_ERROR,
1512 "Timeout #%u while trying to resolve %s. Trying again.",
1515 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1517 * XXX: Doesn't retry in case of soft errors.
1518 * Does this gethostbyname_r version set h_errno?
1520 if (0 == gethostbyname_r(host, &result, &hdata))
1528 #elif defined(MUTEX_LOCKS_AVAILABLE)
1529 privoxy_mutex_lock(&resolver_mutex);
1530 while (NULL == (hostp = gethostbyname(host))
1531 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1533 log_error(LOG_LEVEL_ERROR,
1534 "Timeout #%u while trying to resolve %s. Trying again.",
1537 privoxy_mutex_unlock(&resolver_mutex);
1539 while (NULL == (hostp = gethostbyname(host))
1540 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1542 log_error(LOG_LEVEL_ERROR,
1543 "Timeout #%u while trying to resolve %s. Trying again.",
1546 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1548 * On Mac OSX, if a domain exists but doesn't have a type A
1549 * record associated with it, the h_addr member of the struct
1550 * hostent returned by gethostbyname is NULL, even if h_length
1551 * is 4. Therefore the second test below.
1553 if (hostp == NULL || hostp->h_addr == NULL)
1556 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1557 return(INADDR_NONE);
1559 if (hostp->h_addrtype != AF_INET)
1562 errno = WSAEPROTOTYPE;
1566 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1567 return(INADDR_NONE);
1569 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1571 return(inaddr.sin_addr.s_addr);
1576 /*********************************************************************
1578 * Function : socket_is_still_alive
1580 * Description : Figures out whether or not a socket is still alive.
1583 * 1 : sfd = The socket to check.
1585 * Returns : TRUE for yes, otherwise FALSE.
1587 *********************************************************************/
1588 int socket_is_still_alive(jb_socket sfd)
1591 int no_data_waiting;
1594 struct pollfd poll_fd[1];
1596 memset(poll_fd, 0, sizeof(poll_fd));
1597 poll_fd[0].fd = sfd;
1598 poll_fd[0].events = POLLIN;
1600 poll_result = poll(poll_fd, 1, 0);
1602 if (-1 == poll_result)
1604 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1607 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1609 fd_set readable_fds;
1610 struct timeval timeout;
1613 memset(&timeout, '\0', sizeof(timeout));
1614 FD_ZERO(&readable_fds);
1615 FD_SET(sfd, &readable_fds);
1617 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1620 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1623 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1624 #endif /* def HAVE_POLL */
1626 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1630 #ifdef FEATURE_EXTERNAL_FILTERS
1631 /*********************************************************************
1633 * Function : mark_socket_for_close_on_execute
1635 * Description : Marks a socket for close on execute.
1637 * Used so that external filters have no direct
1638 * access to sockets they shouldn't care about.
1640 * Not implemented for all platforms.
1643 * 1 : fd = The socket to mark
1647 *********************************************************************/
1648 void mark_socket_for_close_on_execute(jb_socket fd)
1650 #ifdef FEATURE_PTHREAD
1653 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1657 log_error(LOG_LEVEL_ERROR,
1658 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1661 #warning "Sockets will be visible to external filters"
1664 #endif /* def FEATURE_EXTERNAL_FILTERS */