1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
5 * Purpose : Contains wrappers for system-specific sockets code,
6 * so that the rest of Privoxy can be more
7 * OS-independent. Contains #ifdefs to make this work
10 * Copyright : Written by and Copyright (C) 2001-2017 the
11 * Privoxy team. http://www.privoxy.org/
13 * Based on the Internet Junkbuster originally written
14 * by and Copyright (C) 1997 Anonymous Coders and
15 * Junkbusters Corporation. http://www.junkbusters.com
17 * This program is free software; you can redistribute it
18 * and/or modify it under the terms of the GNU General
19 * Public License as published by the Free Software
20 * Foundation; either version 2 of the License, or (at
21 * your option) any later version.
23 * This program is distributed in the hope that it will
24 * be useful, but WITHOUT ANY WARRANTY; without even the
25 * implied warranty of MERCHANTABILITY or FITNESS FOR A
26 * PARTICULAR PURPOSE. See the GNU General Public
27 * License for more details.
29 * The GNU General Public License should be included with
30 * this file. If not, you can view it at
31 * http://www.gnu.org/copyleft/gpl.html
32 * or write to the Free Software Foundation, Inc., 59
33 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 *********************************************************************/
45 #include <sys/types.h>
54 #include <sys/timeb.h>
63 #include <netinet/in.h>
64 #include <sys/ioctl.h>
66 #include <sys/socket.h>
69 #include <netinet/tcp.h>
71 #include <arpa/inet.h>
77 #if defined(__EMX__) || defined (__OS2__)
78 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
91 #endif /* def __GLIBC__ */
92 #endif /* HAVE_POLL */
96 /* For mutex semaphores only */
99 #include "jbsockets.h"
102 #include "miscutil.h"
104 /* Mac OSX doesn't define AI_NUMERICSESRV */
105 #ifndef AI_NUMERICSERV
106 #define AI_NUMERICSERV 0
110 * Maximum number of gethostbyname(_r) retries in case of
111 * soft errors (TRY_AGAIN).
112 * XXX: Does it make sense to make this a config option?
114 #define MAX_DNS_RETRIES 10
117 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
119 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
122 /*********************************************************************
124 * Function : set_no_delay_flag
126 * Description : Disables the Nagle algorithm (TCP send coalescence)
127 * for the given socket.
130 * 1 : fd = The file descriptor to operate on
134 *********************************************************************/
135 static void set_no_delay_flag(int fd)
140 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
142 log_error(LOG_LEVEL_ERROR,
143 "Failed to disable TCP coalescence for socket %d", fd);
146 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
147 #endif /* def TCP_NODELAY */
150 /*********************************************************************
152 * Function : connect_to
154 * Description : Open a socket and connect to it. Will check
155 * that this is allowed according to ACL.
158 * 1 : host = hostname to connect to
159 * 2 : portnum = port to connect to (XXX: should be unsigned)
160 * 3 : csp = Current client state (buffers, headers, etc...)
162 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
165 *********************************************************************/
166 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
169 int forwarded_connect_retries = 0;
174 * XXX: The whole errno overloading is ridiculous and should
175 * be replaced with something sane and thread safe
179 fd = rfc2553_connect_to(host, portnum, csp);
181 fd = no_rfc2553_connect_to(host, portnum, csp);
183 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
184 || (csp->fwd == NULL)
185 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
189 forwarded_connect_retries++;
190 if (csp->config->forwarded_connect_retries != 0)
192 log_error(LOG_LEVEL_ERROR,
193 "Attempt %d of %d to connect to %s failed. Trying again.",
194 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
197 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
203 /* Getaddrinfo implementation */
204 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
206 struct addrinfo hints, *result, *rp;
211 struct pollfd poll_fd[1];
214 struct timeval timeout;
216 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
221 * XXX: Initializeing it here is only necessary
222 * because not all situations are properly
225 int socket_error = 0;
228 struct access_control_addr dst[1];
229 #endif /* def FEATURE_ACL */
231 /* Don't leak memory when retrying. */
232 freez(csp->error_message);
233 freez(csp->http->host_ip_addr_str);
235 retval = snprintf(service, sizeof(service), "%d", portnum);
236 if ((-1 == retval) || (sizeof(service) <= retval))
238 log_error(LOG_LEVEL_ERROR,
239 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
241 csp->error_message = strdup("Invalid port number");
242 csp->http->host_ip_addr_str = strdup("unknown");
243 return(JB_INVALID_SOCKET);
246 memset((char *)&hints, 0, sizeof(hints));
247 hints.ai_family = AF_UNSPEC;
248 hints.ai_socktype = SOCK_STREAM;
249 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
251 hints.ai_flags |= AI_ADDRCONFIG;
253 if ((retval = getaddrinfo(host, service, &hints, &result)))
255 log_error(LOG_LEVEL_INFO,
256 "Can not resolve %s: %s", host, gai_strerror(retval));
257 /* XXX: Should find a better way to propagate this error. */
259 csp->error_message = strdup(gai_strerror(retval));
260 csp->http->host_ip_addr_str = strdup("unknown");
261 return(JB_INVALID_SOCKET);
264 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
266 for (rp = result; rp != NULL; rp = rp->ai_next)
270 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
272 if (block_acl(dst, csp))
275 socket_error = errno = SOCEPERM;
277 socket_error = errno = EPERM;
281 #endif /* def FEATURE_ACL */
283 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
284 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
287 log_error(LOG_LEVEL_ERROR,
288 "Failed to get the host name from the socket structure: %s",
289 gai_strerror(retval));
293 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
295 if (fd == JB_INVALID_SOCKET)
305 if (fd >= FD_SETSIZE)
307 log_error(LOG_LEVEL_ERROR,
308 "Server socket number too high to use select(): %d >= %d",
311 freeaddrinfo(result);
312 return JB_INVALID_SOCKET;
317 #ifdef FEATURE_EXTERNAL_FILTERS
318 mark_socket_for_close_on_execute(fd);
321 set_no_delay_flag(fd);
323 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
324 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
327 fcntl(fd, F_SETFL, flags);
329 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__) */
332 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
335 errno = sock_errno();
339 if (errno == WSAEINPROGRESS)
340 #else /* ifndef _WIN32 */
341 if (errno == EINPROGRESS)
342 #endif /* ndef _WIN32 || __OS2__ */
349 socket_error = errno;
360 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
364 fcntl(fd, F_SETFL, flags);
366 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__) */
370 poll_fd[0].events = POLLOUT;
372 retval = poll(poll_fd, 1, 30000);
375 if (rp->ai_next != NULL)
377 /* Log this now as we'll try another address next */
378 log_error(LOG_LEVEL_CONNECT,
379 "Could not connect to [%s]:%s: Operation timed out.",
380 csp->http->host_ip_addr_str, service);
385 * This is the last address, don't log this now
386 * as it would result in a duplicated log message.
388 socket_error = ETIMEDOUT;
393 /* wait for connection to complete */
397 memset(&timeout, 0, sizeof(timeout));
400 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
401 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
402 && FD_ISSET(fd, &wfds))
405 socklen_t optlen = sizeof(socket_error);
406 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
410 /* Connection established, no need to try other addresses. */
413 if (rp->ai_next != NULL)
416 * There's another address we can try, so log that this
417 * one didn't work out. If the last one fails, too,
418 * it will get logged outside the loop body so we don't
419 * have to mention it here.
421 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
422 csp->http->host_ip_addr_str, service, strerror(socket_error));
427 socket_error = errno;
428 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
429 "the connection to [%s]:%s: %s; dropping connection.",
430 csp->http->host_ip_addr_str, service, strerror(errno));
434 /* Connection failed, try next address */
438 freeaddrinfo(result);
441 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
442 host, service, strerror(socket_error));
443 csp->error_message = strdup(strerror(socket_error));
444 return(JB_INVALID_SOCKET);
446 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
447 host, csp->http->host_ip_addr_str, service);
453 #else /* ndef HAVE_RFC2553 */
454 /* Pre-getaddrinfo implementation */
456 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
458 struct sockaddr_in inaddr;
462 struct pollfd poll_fd[1];
465 struct timeval tv[1];
467 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
472 struct access_control_addr dst[1];
473 #endif /* def FEATURE_ACL */
475 /* Don't leak memory when retrying. */
476 freez(csp->http->host_ip_addr_str);
478 memset((char *)&inaddr, 0, sizeof inaddr);
480 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
482 csp->http->host_ip_addr_str = strdup("unknown");
483 return(JB_INVALID_SOCKET);
487 dst->addr = ntohl(addr);
490 if (block_acl(dst, csp))
497 return(JB_INVALID_SOCKET);
499 #endif /* def FEATURE_ACL */
501 inaddr.sin_addr.s_addr = addr;
502 inaddr.sin_family = AF_INET;
503 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
506 if (sizeof(inaddr.sin_port) == sizeof(short))
507 #endif /* ndef _WIN32 */
509 inaddr.sin_port = htons((unsigned short) portnum);
514 inaddr.sin_port = htonl((unsigned long)portnum);
516 #endif /* ndef _WIN32 */
518 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
520 if (fd == JB_INVALID_SOCKET)
525 return(JB_INVALID_SOCKET);
530 if (fd >= FD_SETSIZE)
532 log_error(LOG_LEVEL_ERROR,
533 "Server socket number too high to use select(): %d >= %d",
536 return JB_INVALID_SOCKET;
541 set_no_delay_flag(fd);
543 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
544 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
547 fcntl(fd, F_SETFL, flags);
548 #ifdef FEATURE_EXTERNAL_FILTERS
549 mark_socket_for_close_on_execute(fd);
552 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__) */
554 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
557 if (errno == WSAEINPROGRESS)
559 if (sock_errno() == EINPROGRESS)
560 #else /* ifndef _WIN32 */
561 if (errno == EINPROGRESS)
562 #endif /* ndef _WIN32 || __OS2__ */
568 if (sock_errno() != EINTR)
574 return(JB_INVALID_SOCKET);
578 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
582 fcntl(fd, F_SETFL, flags);
584 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__) */
588 poll_fd[0].events = POLLOUT;
590 if (poll(poll_fd, 1, 30000) <= 0)
592 /* wait for connection to complete */
599 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
600 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
604 return(JB_INVALID_SOCKET);
609 #endif /* ndef HAVE_RFC2553 */
612 /*********************************************************************
614 * Function : write_socket
616 * Description : Write the contents of buf (for n bytes) to socket fd.
619 * 1 : fd = file descriptor (aka. handle) of socket to write to.
620 * 2 : buf = pointer to data to be written.
621 * 3 : len = length of data to be written to the socket "fd".
623 * Returns : 0 on success (entire buffer sent).
626 *********************************************************************/
627 int write_socket(jb_socket fd, const char *buf, size_t len)
635 if (!daemon_mode && fd <= 3)
637 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
642 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
645 return (send(fd, buf, (int)len, 0) != (int)len);
646 #elif defined(__BEOS__)
647 return (send(fd, buf, len, 0) != len);
648 #elif defined(__OS2__)
650 * Break the data up into SOCKET_SEND_MAX chunks for sending...
651 * OS/2 seemed to complain when the chunks were too large.
653 #define SOCKET_SEND_MAX 65000
655 int send_len, send_rc = 0, i = 0;
656 while ((i < len) && (send_rc != -1))
658 if ((i + SOCKET_SEND_MAX) > len)
661 send_len = SOCKET_SEND_MAX;
662 send_rc = send(fd,(char*)buf + i, send_len, 0);
670 return (write(fd, buf, len) != len);
676 /*********************************************************************
678 * Function : write_socket_delayed
680 * Description : Write the contents of buf (for n bytes) to
681 * socket fd, optionally delaying the operation.
684 * 1 : fd = File descriptor (aka. handle) of socket to write to.
685 * 2 : buf = Pointer to data to be written.
686 * 3 : len = Length of data to be written to the socket "fd".
687 * 4 : delay = Delay in milliseconds.
689 * Returns : 0 on success (entire buffer sent).
692 *********************************************************************/
693 int write_socket_delayed(jb_socket fd, const char *buf, size_t len, unsigned int delay)
699 return write_socket(fd, buf, len);
705 enum {MAX_WRITE_LENGTH = 10};
707 if ((i + MAX_WRITE_LENGTH) > len)
709 write_length = len - i;
713 write_length = MAX_WRITE_LENGTH;
716 privoxy_millisleep(delay);
718 if (write_socket(fd, buf + i, write_length) != 0)
730 /*********************************************************************
732 * Function : read_socket
734 * Description : Read from a TCP/IP socket in a platform independent way.
737 * 1 : fd = file descriptor of the socket to read
738 * 2 : buf = pointer to buffer where data will be written
739 * Must be >= len bytes long.
740 * 3 : len = maximum number of bytes to read
742 * Returns : On success, the number of bytes read is returned (zero
743 * indicates end of file), and the file position is advanced
744 * by this number. It is not an error if this number is
745 * smaller than the number of bytes requested; this may hap-
746 * pen for example because fewer bytes are actually available
747 * right now (maybe because we were close to end-of-file, or
748 * because we are reading from a pipe, or from a terminal,
749 * or because read() was interrupted by a signal). On error,
750 * -1 is returned, and errno is set appropriately. In this
751 * case it is left unspecified whether the file position (if
754 *********************************************************************/
755 int read_socket(jb_socket fd, char *buf, int len)
765 ret = recv(fd, buf, len, 0);
766 #elif defined(__BEOS__) || defined(__OS2__)
767 ret = recv(fd, buf, (size_t)len, 0);
769 ret = (int)read(fd, buf, (size_t)len);
774 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
781 /*********************************************************************
783 * Function : data_is_available
785 * Description : Waits for data to arrive on a socket.
788 * 1 : fd = file descriptor of the socket to read
789 * 2 : seconds_to_wait = number of seconds after which we give up.
791 * Returns : TRUE if data arrived in time,
794 *********************************************************************/
795 int data_is_available(jb_socket fd, int seconds_to_wait)
800 struct pollfd poll_fd[1];
803 poll_fd[0].events = POLLIN;
805 n = poll(poll_fd, 1, seconds_to_wait * 1000);
808 struct timeval timeout;
810 memset(&timeout, 0, sizeof(timeout));
811 timeout.tv_sec = seconds_to_wait;
814 /* Copy and pasted from jcc.c ... */
815 memset(&rfds, 0, sizeof(fd_set));
821 n = select(fd+1, &rfds, NULL, NULL, &timeout);
825 * XXX: Do we care about the different error conditions?
827 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
831 /*********************************************************************
833 * Function : close_socket
835 * Description : Closes a TCP/IP socket
838 * 1 : fd = file descriptor of socket to be closed
842 *********************************************************************/
843 void close_socket(jb_socket fd)
845 #if defined(_WIN32) || defined(__BEOS__)
847 #elif defined(__OS2__)
855 /*********************************************************************
857 * Function : drain_and_close_socket
859 * Description : Closes a TCP/IP socket after draining unread data
862 * 1 : fd = file descriptor of the socket to be closed
866 *********************************************************************/
867 void drain_and_close_socket(jb_socket fd)
869 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
870 if (socket_is_still_alive(fd))
873 int bytes_drained_total = 0;
877 /* Apparently Windows has shutdown() but not SHUT_WR. */
881 if (0 != shutdown(fd, SHUT_WR))
883 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
886 #define ARBITRARY_DRAIN_LIMIT 10000
891 if (!data_is_available(fd, 0))
894 * If there is no data available right now, don't try
895 * to drain the socket as read_socket() could block.
900 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
901 if (bytes_drained < 0)
903 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
905 else if (bytes_drained > 0)
907 bytes_drained_total += bytes_drained;
908 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
910 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
914 } while (bytes_drained > 0);
915 if (bytes_drained_total != 0)
917 log_error(LOG_LEVEL_CONNECT,
918 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
927 /*********************************************************************
929 * Function : bind_port
931 * Description : Call socket, set socket options, and listen.
932 * Called by listen_loop to "boot up" our proxy address.
935 * 1 : hostnam = TCP/IP address to bind/listen to
936 * 2 : portnum = port to listen on
937 * 3 : backlog = Listen backlog
938 * 4 : pfd = pointer used to return file descriptor.
940 * Returns : if success, returns 0 and sets *pfd.
941 * if failure, returns -3 if address is in use,
942 * -2 if address unresolvable,
944 *********************************************************************/
945 int bind_port(const char *hostnam, int portnum, int backlog, jb_socket *pfd)
948 struct addrinfo hints;
949 struct addrinfo *result, *rp;
951 * XXX: portnum should be a string to allow symbolic service
952 * names in the configuration file and to avoid the following
958 struct sockaddr_in inaddr;
959 #endif /* def HAVE_RFC2553 */
963 #endif /* ndef _WIN32 */
965 *pfd = JB_INVALID_SOCKET;
968 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
969 if ((-1 == retval) || (sizeof(servnam) <= retval))
971 log_error(LOG_LEVEL_ERROR,
972 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
977 memset(&hints, 0, sizeof(struct addrinfo));
981 * XXX: This is a hack. The right thing to do
982 * would be to bind to both AF_INET and AF_INET6.
983 * This will also fail if there is no AF_INET
986 hints.ai_family = AF_INET;
990 hints.ai_family = AF_UNSPEC;
992 hints.ai_socktype = SOCK_STREAM;
993 hints.ai_flags = AI_PASSIVE;
994 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
995 hints.ai_canonname = NULL;
996 hints.ai_addr = NULL;
997 hints.ai_next = NULL;
999 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
1001 log_error(LOG_LEVEL_ERROR,
1002 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
1006 memset((char *)&inaddr, '\0', sizeof inaddr);
1008 inaddr.sin_family = AF_INET;
1009 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
1011 if (inaddr.sin_addr.s_addr == INADDR_NONE)
1017 if (sizeof(inaddr.sin_port) == sizeof(short))
1018 #endif /* ndef _WIN32 */
1020 inaddr.sin_port = htons((unsigned short) portnum);
1025 inaddr.sin_port = htonl((unsigned long) portnum);
1027 #endif /* ndef _WIN32 */
1028 #endif /* def HAVE_RFC2553 */
1031 for (rp = result; rp != NULL; rp = rp->ai_next)
1033 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1035 fd = socket(AF_INET, SOCK_STREAM, 0);
1036 #endif /* def HAVE_RFC2553 */
1039 if (fd == JB_INVALID_SOCKET)
1051 #ifdef FEATURE_EXTERNAL_FILTERS
1052 mark_socket_for_close_on_execute(fd);
1057 * This is not needed for Win32 - in fact, it stops
1058 * duplicate instances of Privoxy from being caught.
1060 * On UNIX, we assume the user is sensible enough not
1061 * to start Privoxy multiple times on the same IP.
1062 * Without this, stopping and restarting Privoxy
1063 * from a script fails.
1064 * Note: SO_REUSEADDR is meant to only take over
1065 * sockets which are *not* in listen state in Linux,
1066 * e.g. sockets in TIME_WAIT. YMMV.
1068 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
1069 #endif /* ndef _WIN32 */
1072 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
1074 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
1078 errno = WSAGetLastError();
1079 if (errno == WSAEADDRINUSE)
1081 if (errno == EADDRINUSE)
1085 freeaddrinfo(result);
1093 #ifndef HAVE_RFC2553
1102 /* bind() succeeded, escape from for-loop */
1104 * XXX: Support multiple listening sockets (e.g. localhost
1105 * resolves to AF_INET and AF_INET6, but only the first address
1112 freeaddrinfo(result);
1115 /* All bind()s failed */
1118 #endif /* ndef HAVE_RFC2553 */
1120 while (listen(fd, backlog) == -1)
1135 /*********************************************************************
1137 * Function : get_host_information
1139 * Description : Determines the IP address the client used to
1140 * reach us and the hostname associated with it.
1142 * XXX: Most of the code has been copy and pasted
1143 * from accept_connection() and not all of the
1144 * ifdefs paths have been tested afterwards.
1147 * 1 : afd = File descriptor returned from accept().
1148 * 2 : ip_address = Pointer to return the pointer to
1149 * the ip address string.
1150 * 3 : port = Pointer to return the pointer to
1151 * the TCP port string.
1152 * 4 : hostname = Pointer to return the pointer to
1153 * the hostname or NULL if the caller
1154 * isn't interested in it.
1158 *********************************************************************/
1159 void get_host_information(jb_socket afd, char **ip_address, char **port,
1163 struct sockaddr_storage server;
1166 struct sockaddr_in server;
1167 struct hostent *host = NULL;
1168 #endif /* HAVE_RFC2553 */
1169 #if defined(_WIN32) || defined(__OS2__)
1170 /* according to accept_connection() this fixes a warning. */
1171 int s_length, s_length_provided;
1173 socklen_t s_length, s_length_provided;
1175 #ifndef HAVE_RFC2553
1176 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1177 struct hostent result;
1178 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1179 struct hostent_data hdata;
1181 char hbuf[HOSTENT_BUFFER_SIZE];
1183 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1184 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1185 #endif /* ifndef HAVE_RFC2553 */
1186 s_length = s_length_provided = sizeof(server);
1188 if (NULL != hostname)
1195 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1197 if (s_length > s_length_provided)
1199 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1203 * XXX: Workaround for missing header on Windows when
1204 * configured with --disable-ipv6-support.
1205 * The proper fix is to not use NI_MAXSERV in
1206 * that case. It works by accident on other platforms
1207 * as <netdb.h> is included unconditionally there.
1210 #define NI_MAXSERV 32
1212 *port = malloc_or_die(NI_MAXSERV);
1215 *ip_address = malloc_or_die(NI_MAXHOST);
1216 retval = getnameinfo((struct sockaddr *) &server, s_length,
1217 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1218 NI_NUMERICHOST|NI_NUMERICSERV);
1221 log_error(LOG_LEVEL_ERROR,
1222 "Unable to print my own IP address: %s", gai_strerror(retval));
1228 *ip_address = strdup(inet_ntoa(server.sin_addr));
1229 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1230 #endif /* HAVE_RFC2553 */
1231 if (NULL == hostname)
1234 * We're done here, the caller isn't
1235 * interested in knowing the hostname.
1241 *hostname = malloc_or_die(NI_MAXHOST);
1242 retval = getnameinfo((struct sockaddr *) &server, s_length,
1243 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1246 log_error(LOG_LEVEL_ERROR,
1247 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1251 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1252 gethostbyaddr_r((const char *)&server.sin_addr,
1253 sizeof(server.sin_addr), AF_INET,
1254 &result, hbuf, HOSTENT_BUFFER_SIZE,
1256 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1257 host = gethostbyaddr_r((const char *)&server.sin_addr,
1258 sizeof(server.sin_addr), AF_INET,
1259 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1260 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1261 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1262 sizeof(server.sin_addr), AF_INET,
1271 #elif defined(MUTEX_LOCKS_AVAILABLE)
1272 privoxy_mutex_lock(&resolver_mutex);
1273 host = gethostbyaddr((const char *)&server.sin_addr,
1274 sizeof(server.sin_addr), AF_INET);
1275 privoxy_mutex_unlock(&resolver_mutex);
1277 host = gethostbyaddr((const char *)&server.sin_addr,
1278 sizeof(server.sin_addr), AF_INET);
1282 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1286 *hostname = strdup(host->h_name);
1288 #endif /* else def HAVE_RFC2553 */
1295 /*********************************************************************
1297 * Function : accept_connection
1299 * Description : Accepts a connection on one of possibly multiple
1300 * sockets. The socket(s) to check must have been
1301 * created using bind_port().
1304 * 1 : csp = Client state, cfd, ip_addr_str, and
1305 * ip_addr_long will be set by this routine.
1306 * 2 : fds = File descriptors returned from bind_port
1308 * Returns : when a connection is accepted, it returns 1 (TRUE).
1309 * On an error it returns 0 (FALSE).
1311 *********************************************************************/
1312 int accept_connection(struct client_state * csp, jb_socket fds[])
1315 /* XXX: client is stored directly into csp->tcp_addr */
1316 #define client (csp->tcp_addr)
1318 struct sockaddr_in client;
1321 #if defined(_WIN32) || defined(__OS2__)
1322 /* Wierdness - fix a warning. */
1329 int max_selected_socket;
1331 struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
1332 nfds_t polled_sockets;
1334 fd_set selected_fds;
1337 const char *host_addr;
1338 size_t listen_addr_size;
1340 c_length = sizeof(client);
1343 memset(poll_fds, 0, sizeof(poll_fds));
1347 * Wait for a connection on any socket.
1348 * Return immediately if no socket is listening.
1349 * XXX: Why not treat this as fatal error?
1351 FD_ZERO(&selected_fds);
1353 max_selected_socket = 0;
1354 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1356 if (JB_INVALID_SOCKET != fds[i])
1359 poll_fds[i].fd = fds[i];
1360 poll_fds[i].events = POLLIN;
1363 FD_SET(fds[i], &selected_fds);
1365 if (max_selected_socket < fds[i] + 1)
1367 max_selected_socket = fds[i] + 1;
1371 if (0 == max_selected_socket)
1378 retval = poll(poll_fds, polled_sockets, -1);
1380 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1382 } while (retval < 0 && errno == EINTR);
1387 log_error(LOG_LEVEL_ERROR,
1388 "Waiting on new client failed because select(2) returned 0."
1389 " This should not happen.");
1393 log_error(LOG_LEVEL_ERROR,
1394 "Waiting on new client failed because of problems in select(2): "
1395 "%s.", strerror(errno));
1400 for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
1402 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1405 if (i >= MAX_LISTENING_SOCKETS)
1407 log_error(LOG_LEVEL_ERROR,
1408 "select(2) reported connected clients (number = %u, "
1409 "descriptor boundary = %u), but none found.",
1410 retval, max_selected_socket);
1415 /* Accept selected connection */
1417 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1418 if (afd == JB_INVALID_SOCKET)
1425 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1426 } while (afd < 0 && errno == EINTR);
1435 struct linger linger_options;
1436 linger_options.l_onoff = 1;
1437 linger_options.l_linger = 5;
1438 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1440 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1447 if (afd >= FD_SETSIZE)
1449 log_error(LOG_LEVEL_ERROR,
1450 "Client socket number too high to use select(): %d >= %d",
1458 #ifdef FEATURE_EXTERNAL_FILTERS
1459 mark_socket_for_close_on_execute(afd);
1462 set_no_delay_flag(afd);
1466 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1467 retval = getnameinfo((struct sockaddr *) &client, c_length,
1468 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1469 if (!csp->ip_addr_str || retval)
1471 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1472 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1473 freez(csp->ip_addr_str);
1477 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1478 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1479 #endif /* def HAVE_RFC2553 */
1482 * Save the name and port of the accepting socket for later lookup.
1484 * The string needs space for strlen(...) + 7 characters:
1485 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1487 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1488 listen_addr_size = strlen(host_addr) + 7;
1489 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1490 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1491 "%s:%d", host_addr, csp->config->hport[i]);
1492 if ((-1 == retval) || listen_addr_size <= retval)
1494 log_error(LOG_LEVEL_ERROR,
1495 "Server name (%s) and port number (%d) ASCII decimal representation"
1496 "don't fit into %d bytes",
1497 host_addr, csp->config->hport[i], listen_addr_size);
1506 /*********************************************************************
1508 * Function : resolve_hostname_to_ip
1510 * Description : Resolve a hostname to an internet tcp/ip address.
1511 * NULL or an empty string resolve to INADDR_ANY.
1514 * 1 : host = hostname to resolve
1516 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1518 *********************************************************************/
1519 unsigned long resolve_hostname_to_ip(const char *host)
1521 struct sockaddr_in inaddr;
1522 struct hostent *hostp;
1523 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1524 struct hostent result;
1525 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1526 char hbuf[HOSTENT_BUFFER_SIZE];
1528 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1529 struct hostent_data hdata;
1530 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1531 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1533 if ((host == NULL) || (*host == '\0'))
1538 memset((char *) &inaddr, 0, sizeof inaddr);
1540 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1542 unsigned int dns_retries = 0;
1543 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1544 while (gethostbyname_r(host, &result, hbuf,
1545 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1546 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1548 log_error(LOG_LEVEL_ERROR,
1549 "Timeout #%u while trying to resolve %s. Trying again.",
1552 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1553 while (NULL == (hostp = gethostbyname_r(host, &result,
1554 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1555 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1557 log_error(LOG_LEVEL_ERROR,
1558 "Timeout #%u while trying to resolve %s. Trying again.",
1561 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1563 * XXX: Doesn't retry in case of soft errors.
1564 * Does this gethostbyname_r version set h_errno?
1566 if (0 == gethostbyname_r(host, &result, &hdata))
1574 #elif defined(MUTEX_LOCKS_AVAILABLE)
1575 privoxy_mutex_lock(&resolver_mutex);
1576 while (NULL == (hostp = gethostbyname(host))
1577 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1579 log_error(LOG_LEVEL_ERROR,
1580 "Timeout #%u while trying to resolve %s. Trying again.",
1583 privoxy_mutex_unlock(&resolver_mutex);
1585 while (NULL == (hostp = gethostbyname(host))
1586 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1588 log_error(LOG_LEVEL_ERROR,
1589 "Timeout #%u while trying to resolve %s. Trying again.",
1592 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1594 * On Mac OSX, if a domain exists but doesn't have a type A
1595 * record associated with it, the h_addr member of the struct
1596 * hostent returned by gethostbyname is NULL, even if h_length
1597 * is 4. Therefore the second test below.
1599 if (hostp == NULL || hostp->h_addr == NULL)
1602 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1603 return(INADDR_NONE);
1605 if (hostp->h_addrtype != AF_INET)
1608 errno = WSAEPROTOTYPE;
1612 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1613 return(INADDR_NONE);
1615 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1617 return(inaddr.sin_addr.s_addr);
1622 /*********************************************************************
1624 * Function : socket_is_still_alive
1626 * Description : Figures out whether or not a socket is still alive.
1629 * 1 : sfd = The socket to check.
1631 * Returns : TRUE for yes, otherwise FALSE.
1633 *********************************************************************/
1634 int socket_is_still_alive(jb_socket sfd)
1637 int no_data_waiting;
1640 struct pollfd poll_fd[1];
1642 memset(poll_fd, 0, sizeof(poll_fd));
1643 poll_fd[0].fd = sfd;
1644 poll_fd[0].events = POLLIN;
1646 poll_result = poll(poll_fd, 1, 0);
1648 if (-1 == poll_result)
1650 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1653 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1655 fd_set readable_fds;
1656 struct timeval timeout;
1659 memset(&timeout, '\0', sizeof(timeout));
1660 FD_ZERO(&readable_fds);
1661 FD_SET(sfd, &readable_fds);
1663 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1666 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1669 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1670 #endif /* def HAVE_POLL */
1672 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1676 #ifdef FEATURE_EXTERNAL_FILTERS
1677 /*********************************************************************
1679 * Function : mark_socket_for_close_on_execute
1681 * Description : Marks a socket for close on execute.
1683 * Used so that external filters have no direct
1684 * access to sockets they shouldn't care about.
1686 * Not implemented for all platforms.
1689 * 1 : fd = The socket to mark
1693 *********************************************************************/
1694 void mark_socket_for_close_on_execute(jb_socket fd)
1696 #ifdef FEATURE_PTHREAD
1699 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1703 log_error(LOG_LEVEL_ERROR,
1704 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1707 #warning "Sockets will be visible to external filters"
1710 #endif /* def FEATURE_EXTERNAL_FILTERS */