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. https://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>
61 #include <netinet/in.h>
62 #include <sys/ioctl.h>
64 #include <sys/socket.h>
67 #include <netinet/tcp.h>
68 #include <arpa/inet.h>
80 #endif /* def __GLIBC__ */
81 #endif /* HAVE_POLL */
85 /* For mutex semaphores only */
88 #include "jbsockets.h"
93 /* Mac OSX doesn't define AI_NUMERICSESRV */
94 #ifndef AI_NUMERICSERV
95 #define AI_NUMERICSERV 0
99 * Maximum number of gethostbyname(_r) retries in case of
100 * soft errors (TRY_AGAIN).
101 * XXX: Does it make sense to make this a config option?
103 #define MAX_DNS_RETRIES 10
106 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
108 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
111 /*********************************************************************
113 * Function : set_no_delay_flag
115 * Description : Disables the Nagle algorithm (TCP send coalescence)
116 * for the given socket.
119 * 1 : fd = The file descriptor to operate on
123 *********************************************************************/
124 static void set_no_delay_flag(int fd)
129 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
131 log_error(LOG_LEVEL_ERROR,
132 "Failed to disable TCP coalescence for socket %d", fd);
135 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
136 #endif /* def TCP_NODELAY */
139 /*********************************************************************
141 * Function : connect_to
143 * Description : Open a socket and connect to it. Will check
144 * that this is allowed according to ACL.
147 * 1 : host = hostname to connect to
148 * 2 : portnum = port to connect to (XXX: should be unsigned)
149 * 3 : csp = Current client state (buffers, headers, etc...)
151 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
154 *********************************************************************/
155 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
158 int forwarded_connect_retries = 0;
163 * XXX: The whole errno overloading is ridiculous and should
164 * be replaced with something sane and thread safe
168 fd = rfc2553_connect_to(host, portnum, csp);
170 fd = no_rfc2553_connect_to(host, portnum, csp);
172 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
173 || (csp->fwd == NULL)
174 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
178 forwarded_connect_retries++;
179 if (csp->config->forwarded_connect_retries != 0)
181 log_error(LOG_LEVEL_ERROR,
182 "Attempt %d of %d to connect to %s failed. Trying again.",
183 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
186 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
192 /* Getaddrinfo implementation */
193 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
195 struct addrinfo hints, *result, *rp;
200 struct pollfd poll_fd[1];
203 struct timeval timeout;
205 #if !defined(_WIN32) && !defined(__BEOS__)
210 * XXX: Initializing it here is only necessary
211 * because not all situations are properly
214 int socket_error = 0;
217 struct access_control_addr dst[1];
218 #endif /* def FEATURE_ACL */
220 /* Don't leak memory when retrying. */
221 freez(csp->error_message);
222 freez(csp->http->host_ip_addr_str);
224 retval = snprintf(service, sizeof(service), "%d", portnum);
225 if ((-1 == retval) || (sizeof(service) <= retval))
227 log_error(LOG_LEVEL_ERROR,
228 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
230 csp->error_message = strdup("Invalid port number");
231 csp->http->host_ip_addr_str = strdup("unknown");
232 return(JB_INVALID_SOCKET);
235 memset((char *)&hints, 0, sizeof(hints));
236 hints.ai_family = AF_UNSPEC;
237 hints.ai_socktype = SOCK_STREAM;
238 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
240 hints.ai_flags |= AI_ADDRCONFIG;
242 if ((retval = getaddrinfo(host, service, &hints, &result)))
244 log_error(LOG_LEVEL_INFO,
245 "Can not resolve %s: %s", host, gai_strerror(retval));
246 csp->error_message = strdup(gai_strerror(retval));
247 csp->http->host_ip_addr_str = strdup("unknown");
248 /* XXX: Should find a better way to propagate this error. */
250 return(JB_INVALID_SOCKET);
253 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
255 for (rp = result; rp != NULL; rp = rp->ai_next)
259 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
261 if (block_acl(dst, csp))
263 socket_error = errno = EPERM;
266 #endif /* def FEATURE_ACL */
268 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
269 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
272 log_error(LOG_LEVEL_ERROR,
273 "Failed to get the host name from the socket structure: %s",
274 gai_strerror(retval));
278 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
280 if (fd == JB_INVALID_SOCKET)
290 if (fd >= FD_SETSIZE)
292 log_error(LOG_LEVEL_ERROR,
293 "Server socket number too high to use select(): %d >= %d",
296 freeaddrinfo(result);
297 return JB_INVALID_SOCKET;
302 #ifdef FEATURE_EXTERNAL_FILTERS
303 mark_socket_for_close_on_execute(fd);
306 set_no_delay_flag(fd);
308 #if !defined(_WIN32) && !defined(__BEOS__)
309 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
312 fcntl(fd, F_SETFL, flags);
314 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
317 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
320 if (errno == WSAEINPROGRESS)
321 #else /* ifndef _WIN32 */
322 if (errno == EINPROGRESS)
323 #endif /* ndef _WIN32 */
330 socket_error = errno;
341 #if !defined(_WIN32) && !defined(__BEOS__)
345 fcntl(fd, F_SETFL, flags);
347 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
351 poll_fd[0].events = POLLOUT;
353 retval = poll(poll_fd, 1, 30000);
356 if (rp->ai_next != NULL)
358 /* Log this now as we'll try another address next */
359 log_error(LOG_LEVEL_CONNECT,
360 "Could not connect to [%s]:%s: Operation timed out.",
361 csp->http->host_ip_addr_str, service);
366 * This is the last address, don't log this now
367 * as it would result in a duplicated log message.
369 socket_error = ETIMEDOUT;
374 /* wait for connection to complete */
378 memset(&timeout, 0, sizeof(timeout));
381 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
382 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
383 && FD_ISSET(fd, &wfds))
386 socklen_t optlen = sizeof(socket_error);
387 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
391 /* Connection established, no need to try other addresses. */
394 if (rp->ai_next != NULL)
397 * There's another address we can try, so log that this
398 * one didn't work out. If the last one fails, too,
399 * it will get logged outside the loop body so we don't
400 * have to mention it here.
402 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
403 csp->http->host_ip_addr_str, service, strerror(socket_error));
408 socket_error = errno;
409 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
410 "the connection to [%s]:%s: %s; dropping connection.",
411 csp->http->host_ip_addr_str, service, strerror(errno));
415 /* Connection failed, try next address */
419 freeaddrinfo(result);
422 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
423 host, service, strerror(socket_error));
424 csp->error_message = strdup(strerror(socket_error));
425 return(JB_INVALID_SOCKET);
427 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
428 host, csp->http->host_ip_addr_str, service);
434 #else /* ndef HAVE_RFC2553 */
435 /* Pre-getaddrinfo implementation */
437 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
439 struct sockaddr_in inaddr;
443 struct pollfd poll_fd[1];
446 struct timeval tv[1];
448 #if !defined(_WIN32) && !defined(__BEOS__)
453 struct access_control_addr dst[1];
454 #endif /* def FEATURE_ACL */
456 /* Don't leak memory when retrying. */
457 freez(csp->http->host_ip_addr_str);
459 memset((char *)&inaddr, 0, sizeof inaddr);
461 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
463 csp->http->host_ip_addr_str = strdup("unknown");
464 return(JB_INVALID_SOCKET);
468 dst->addr = ntohl(addr);
471 if (block_acl(dst, csp))
474 return(JB_INVALID_SOCKET);
476 #endif /* def FEATURE_ACL */
478 inaddr.sin_addr.s_addr = addr;
479 inaddr.sin_family = AF_INET;
480 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
483 if (sizeof(inaddr.sin_port) == sizeof(short))
484 #endif /* ndef _WIN32 */
486 inaddr.sin_port = htons((unsigned short) portnum);
491 inaddr.sin_port = htonl((unsigned long)portnum);
493 #endif /* ndef _WIN32 */
495 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
497 if (fd == JB_INVALID_SOCKET)
502 return(JB_INVALID_SOCKET);
507 if (fd >= FD_SETSIZE)
509 log_error(LOG_LEVEL_ERROR,
510 "Server socket number too high to use select(): %d >= %d",
513 return JB_INVALID_SOCKET;
518 set_no_delay_flag(fd);
520 #if !defined(_WIN32) && !defined(__BEOS__)
521 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
524 fcntl(fd, F_SETFL, flags);
525 #ifdef FEATURE_EXTERNAL_FILTERS
526 mark_socket_for_close_on_execute(fd);
529 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
531 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
534 if (errno == WSAEINPROGRESS)
535 #else /* ifndef _WIN32 */
536 if (errno == EINPROGRESS)
537 #endif /* ndef _WIN32 */
545 return(JB_INVALID_SOCKET);
549 #if !defined(_WIN32) && !defined(__BEOS__)
553 fcntl(fd, F_SETFL, flags);
555 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
559 poll_fd[0].events = POLLOUT;
561 if (poll(poll_fd, 1, 30000) <= 0)
563 /* wait for connection to complete */
570 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
571 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
575 return(JB_INVALID_SOCKET);
580 #endif /* ndef HAVE_RFC2553 */
583 /*********************************************************************
585 * Function : write_socket
587 * Description : Write the contents of buf (for n bytes) to socket fd.
590 * 1 : fd = file descriptor (aka. handle) of socket to write to.
591 * 2 : buf = pointer to data to be written.
592 * 3 : len = length of data to be written to the socket "fd".
594 * Returns : 0 on success (entire buffer sent).
597 *********************************************************************/
598 int write_socket(jb_socket fd, const char *buf, size_t len)
606 if (!daemon_mode && fd <= 3)
608 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
613 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
616 return (send(fd, buf, (int)len, 0) != (int)len);
617 #elif defined(__BEOS__)
618 return (send(fd, buf, len, 0) != len);
620 return (write(fd, buf, len) != len);
626 /*********************************************************************
628 * Function : write_socket_delayed
630 * Description : Write the contents of buf (for n bytes) to
631 * socket fd, optionally delaying the operation.
634 * 1 : fd = File descriptor (aka. handle) of socket to write to.
635 * 2 : buf = Pointer to data to be written.
636 * 3 : len = Length of data to be written to the socket "fd".
637 * 4 : delay = Delay in milliseconds.
639 * Returns : 0 on success (entire buffer sent).
642 *********************************************************************/
643 int write_socket_delayed(jb_socket fd, const char *buf, size_t len, unsigned int delay)
649 return write_socket(fd, buf, len);
655 enum {MAX_WRITE_LENGTH = 10};
657 if ((i + MAX_WRITE_LENGTH) > len)
659 write_length = len - i;
663 write_length = MAX_WRITE_LENGTH;
666 privoxy_millisleep(delay);
668 if (write_socket(fd, buf + i, write_length) != 0)
680 /*********************************************************************
682 * Function : read_socket
684 * Description : Read from a TCP/IP socket in a platform independent way.
687 * 1 : fd = file descriptor of the socket to read
688 * 2 : buf = pointer to buffer where data will be written
689 * Must be >= len bytes long.
690 * 3 : len = maximum number of bytes to read
692 * Returns : On success, the number of bytes read is returned (zero
693 * indicates end of file), and the file position is advanced
694 * by this number. It is not an error if this number is
695 * smaller than the number of bytes requested; this may hap-
696 * pen for example because fewer bytes are actually available
697 * right now (maybe because we were close to end-of-file, or
698 * because we are reading from a pipe, or from a terminal,
699 * or because read() was interrupted by a signal). On error,
700 * -1 is returned, and errno is set appropriately. In this
701 * case it is left unspecified whether the file position (if
704 *********************************************************************/
705 int read_socket(jb_socket fd, char *buf, int len)
715 ret = recv(fd, buf, len, 0);
716 #elif defined(__BEOS__)
717 ret = recv(fd, buf, (size_t)len, 0);
719 ret = (int)read(fd, buf, (size_t)len);
724 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
731 /*********************************************************************
733 * Function : data_is_available
735 * Description : Waits for data to arrive on a socket.
738 * 1 : fd = file descriptor of the socket to read
739 * 2 : seconds_to_wait = number of seconds after which we give up.
741 * Returns : TRUE if data arrived in time,
744 *********************************************************************/
745 int data_is_available(jb_socket fd, int seconds_to_wait)
750 struct pollfd poll_fd[1];
753 poll_fd[0].events = POLLIN;
755 n = poll(poll_fd, 1, seconds_to_wait * 1000);
758 struct timeval timeout;
760 memset(&timeout, 0, sizeof(timeout));
761 timeout.tv_sec = seconds_to_wait;
766 n = select(fd+1, &rfds, NULL, NULL, &timeout);
770 * XXX: Do we care about the different error conditions?
772 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
776 /*********************************************************************
778 * Function : close_socket
780 * Description : Closes a TCP/IP socket
783 * 1 : fd = file descriptor of socket to be closed
787 *********************************************************************/
788 void close_socket(jb_socket fd)
790 #if defined(_WIN32) || defined(__BEOS__)
798 /*********************************************************************
800 * Function : drain_and_close_socket
802 * Description : Closes a TCP/IP socket after draining unread data
805 * 1 : fd = file descriptor of the socket to be closed
809 *********************************************************************/
810 void drain_and_close_socket(jb_socket fd)
812 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
813 if (socket_is_still_alive(fd))
816 int bytes_drained_total = 0;
820 /* Apparently Windows has shutdown() but not SHUT_WR. */
824 if (0 != shutdown(fd, SHUT_WR))
826 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
829 #define ARBITRARY_DRAIN_LIMIT 10000
834 if (!data_is_available(fd, 0))
837 * If there is no data available right now, don't try
838 * to drain the socket as read_socket() could block.
843 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
844 if (bytes_drained < 0)
846 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
848 else if (bytes_drained > 0)
850 bytes_drained_total += bytes_drained;
851 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
853 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d.", fd);
857 } while (bytes_drained > 0);
858 if (bytes_drained_total != 0)
860 log_error(LOG_LEVEL_CONNECT,
861 "Drained %d bytes before closing socket %d.", bytes_drained_total, fd);
870 /*********************************************************************
872 * Function : bind_port
874 * Description : Call socket, set socket options, and listen.
875 * Called by listen_loop to "boot up" our proxy address.
878 * 1 : hostnam = TCP/IP address to bind/listen to
879 * 2 : portnum = port to listen on
880 * 3 : backlog = Listen backlog
881 * 4 : pfd = pointer used to return file descriptor.
883 * Returns : if success, returns 0 and sets *pfd.
884 * if failure, returns -3 if address is in use,
885 * -2 if address unresolvable,
887 *********************************************************************/
888 int bind_port(const char *hostnam, int portnum, int backlog, jb_socket *pfd)
891 struct addrinfo hints;
892 struct addrinfo *result, *rp;
894 * XXX: portnum should be a string to allow symbolic service
895 * names in the configuration file and to avoid the following
901 struct sockaddr_in inaddr;
902 #endif /* def HAVE_RFC2553 */
906 #endif /* ndef _WIN32 */
908 *pfd = JB_INVALID_SOCKET;
911 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
912 if ((-1 == retval) || (sizeof(servnam) <= retval))
914 log_error(LOG_LEVEL_ERROR,
915 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes.",
920 memset(&hints, 0, sizeof(struct addrinfo));
924 * XXX: This is a hack. The right thing to do
925 * would be to bind to both AF_INET and AF_INET6.
926 * This will also fail if there is no AF_INET
929 hints.ai_family = AF_INET;
933 hints.ai_family = AF_UNSPEC;
935 hints.ai_socktype = SOCK_STREAM;
936 hints.ai_flags = AI_PASSIVE;
937 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
938 hints.ai_canonname = NULL;
939 hints.ai_addr = NULL;
940 hints.ai_next = NULL;
942 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
944 log_error(LOG_LEVEL_ERROR,
945 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
949 memset((char *)&inaddr, '\0', sizeof inaddr);
951 inaddr.sin_family = AF_INET;
952 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
954 if (inaddr.sin_addr.s_addr == INADDR_NONE)
960 if (sizeof(inaddr.sin_port) == sizeof(short))
961 #endif /* ndef _WIN32 */
963 inaddr.sin_port = htons((unsigned short) portnum);
968 inaddr.sin_port = htonl((unsigned long) portnum);
970 #endif /* ndef _WIN32 */
971 #endif /* def HAVE_RFC2553 */
974 for (rp = result; rp != NULL; rp = rp->ai_next)
976 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
978 fd = socket(AF_INET, SOCK_STREAM, 0);
979 #endif /* def HAVE_RFC2553 */
982 if (fd == JB_INVALID_SOCKET)
994 #ifdef FEATURE_EXTERNAL_FILTERS
995 mark_socket_for_close_on_execute(fd);
1000 * This is not needed for Win32 - in fact, it stops
1001 * duplicate instances of Privoxy from being caught.
1003 * On UNIX, we assume the user is sensible enough not
1004 * to start Privoxy multiple times on the same IP.
1005 * Without this, stopping and restarting Privoxy
1006 * from a script fails.
1007 * Note: SO_REUSEADDR is meant to only take over
1008 * sockets which are *not* in listen state in Linux,
1009 * e.g. sockets in TIME_WAIT. YMMV.
1011 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
1012 #endif /* ndef _WIN32 */
1015 setsockopt(fd, IPPROTO_IP, IP_FREEBIND, (char *)&one, sizeof(one));
1019 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
1021 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
1025 errno = WSAGetLastError();
1026 if (errno == WSAEADDRINUSE)
1028 if (errno == EADDRINUSE)
1032 freeaddrinfo(result);
1040 #ifndef HAVE_RFC2553
1049 /* bind() succeeded, escape from for-loop */
1051 * XXX: Support multiple listening sockets (e.g. localhost
1052 * resolves to AF_INET and AF_INET6, but only the first address
1059 freeaddrinfo(result);
1062 /* All bind()s failed */
1065 #endif /* ndef HAVE_RFC2553 */
1067 while (listen(fd, backlog) == -1)
1082 /*********************************************************************
1084 * Function : get_host_information
1086 * Description : Determines the IP address the client used to
1087 * reach us and the hostname associated with it.
1089 * XXX: Most of the code has been copy and pasted
1090 * from accept_connection() and not all of the
1091 * ifdefs paths have been tested afterwards.
1094 * 1 : afd = File descriptor returned from accept().
1095 * 2 : ip_address = Pointer to return the pointer to
1096 * the ip address string.
1097 * 3 : port = Pointer to return the pointer to
1098 * the TCP port string.
1099 * 4 : hostname = Pointer to return the pointer to
1100 * the hostname or NULL if the caller
1101 * isn't interested in it.
1105 *********************************************************************/
1106 void get_host_information(jb_socket afd, char **ip_address, char **port,
1110 struct sockaddr_storage server;
1113 struct sockaddr_in server;
1114 struct hostent *host = NULL;
1115 #endif /* HAVE_RFC2553 */
1117 /* according to accept_connection() this fixes a warning. */
1118 int s_length, s_length_provided;
1120 socklen_t s_length, s_length_provided;
1122 #ifndef HAVE_RFC2553
1123 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1124 struct hostent result;
1125 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1126 struct hostent_data hdata;
1128 char hbuf[HOSTENT_BUFFER_SIZE];
1130 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1131 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1132 #endif /* ifndef HAVE_RFC2553 */
1133 s_length = s_length_provided = sizeof(server);
1135 if (NULL != hostname)
1142 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1144 if (s_length > s_length_provided)
1146 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1150 * XXX: Workaround for missing header on Windows when
1151 * configured with --disable-ipv6-support.
1152 * The proper fix is to not use NI_MAXSERV in
1153 * that case. It works by accident on other platforms
1154 * as <netdb.h> is included unconditionally there.
1157 #define NI_MAXSERV 32
1159 *port = malloc_or_die(NI_MAXSERV);
1162 *ip_address = malloc_or_die(NI_MAXHOST);
1163 retval = getnameinfo((struct sockaddr *) &server, s_length,
1164 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1165 NI_NUMERICHOST|NI_NUMERICSERV);
1168 log_error(LOG_LEVEL_ERROR,
1169 "Unable to print my own IP address: %s", gai_strerror(retval));
1175 *ip_address = strdup(inet_ntoa(server.sin_addr));
1176 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1177 #endif /* HAVE_RFC2553 */
1178 if (NULL == hostname)
1181 * We're done here, the caller isn't
1182 * interested in knowing the hostname.
1188 *hostname = malloc_or_die(NI_MAXHOST);
1189 retval = getnameinfo((struct sockaddr *) &server, s_length,
1190 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1193 log_error(LOG_LEVEL_ERROR,
1194 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1198 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1199 gethostbyaddr_r((const char *)&server.sin_addr,
1200 sizeof(server.sin_addr), AF_INET,
1201 &result, hbuf, HOSTENT_BUFFER_SIZE,
1203 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1204 host = gethostbyaddr_r((const char *)&server.sin_addr,
1205 sizeof(server.sin_addr), AF_INET,
1206 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1207 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1208 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1209 sizeof(server.sin_addr), AF_INET,
1218 #elif defined(MUTEX_LOCKS_AVAILABLE)
1219 privoxy_mutex_lock(&resolver_mutex);
1220 host = gethostbyaddr((const char *)&server.sin_addr,
1221 sizeof(server.sin_addr), AF_INET);
1222 privoxy_mutex_unlock(&resolver_mutex);
1224 host = gethostbyaddr((const char *)&server.sin_addr,
1225 sizeof(server.sin_addr), AF_INET);
1229 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1233 *hostname = strdup(host->h_name);
1235 #endif /* else def HAVE_RFC2553 */
1242 /*********************************************************************
1244 * Function : accept_connection
1246 * Description : Accepts a connection on one of possibly multiple
1247 * sockets. The socket(s) to check must have been
1248 * created using bind_port().
1251 * 1 : csp = Client state, cfd, ip_addr_str, and
1252 * ip_addr_long will be set by this routine.
1253 * 2 : fds = File descriptors returned from bind_port
1255 * Returns : when a connection is accepted, it returns 1 (TRUE).
1256 * On an error it returns 0 (FALSE).
1258 *********************************************************************/
1259 int accept_connection(struct client_state * csp, jb_socket fds[])
1262 /* XXX: client is stored directly into csp->tcp_addr */
1263 #define client (csp->tcp_addr)
1265 struct sockaddr_in client;
1269 /* Weirdness - fix a warning. */
1276 int max_selected_socket;
1278 struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
1279 nfds_t polled_sockets;
1281 fd_set selected_fds;
1284 const char *host_addr;
1285 size_t listen_addr_size;
1287 c_length = sizeof(client);
1290 memset(poll_fds, 0, sizeof(poll_fds));
1294 * Wait for a connection on any socket.
1295 * Return immediately if no socket is listening.
1296 * XXX: Why not treat this as fatal error?
1298 FD_ZERO(&selected_fds);
1300 max_selected_socket = 0;
1301 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1303 if (JB_INVALID_SOCKET != fds[i])
1306 poll_fds[i].fd = fds[i];
1307 poll_fds[i].events = POLLIN;
1310 FD_SET(fds[i], &selected_fds);
1312 if (max_selected_socket < fds[i] + 1)
1314 max_selected_socket = fds[i] + 1;
1318 if (0 == max_selected_socket)
1325 retval = poll(poll_fds, polled_sockets, -1);
1327 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1329 } while (retval < 0 && errno == EINTR);
1334 log_error(LOG_LEVEL_ERROR,
1335 "Waiting on new client failed because select(2) returned 0."
1336 " This should not happen.");
1340 log_error(LOG_LEVEL_ERROR,
1341 "Waiting on new client failed because of problems in select(2): "
1342 "%s.", strerror(errno));
1347 for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
1349 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1352 if (i >= MAX_LISTENING_SOCKETS)
1354 log_error(LOG_LEVEL_ERROR,
1355 "select(2) reported connected clients (number = %u, "
1356 "descriptor boundary = %u), but none found.",
1357 retval, max_selected_socket);
1362 /* Accept selected connection */
1364 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1365 if (afd == JB_INVALID_SOCKET)
1372 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1373 } while (afd < 0 && errno == EINTR);
1382 struct linger linger_options;
1383 linger_options.l_onoff = 1;
1384 linger_options.l_linger = 5;
1385 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1387 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1394 if (afd >= FD_SETSIZE)
1396 log_error(LOG_LEVEL_ERROR,
1397 "Client socket number too high to use select(): %d >= %d",
1405 #ifdef FEATURE_EXTERNAL_FILTERS
1406 mark_socket_for_close_on_execute(afd);
1409 set_no_delay_flag(afd);
1413 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1414 retval = getnameinfo((struct sockaddr *) &client, c_length,
1415 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1416 if (!csp->ip_addr_str || retval)
1418 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1419 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1420 freez(csp->ip_addr_str);
1424 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1425 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1426 #endif /* def HAVE_RFC2553 */
1429 * Save the name and port of the accepting socket for later lookup.
1431 * The string needs space for strlen(...) + 7 characters:
1432 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1434 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1435 listen_addr_size = strlen(host_addr) + 7;
1436 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1437 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1438 "%s:%d", host_addr, csp->config->hport[i]);
1439 if ((-1 == retval) || listen_addr_size <= retval)
1441 log_error(LOG_LEVEL_ERROR,
1442 "Server name (%s) and port number (%d) ASCII decimal representation "
1443 "don't fit into %lu bytes",
1444 host_addr, csp->config->hport[i], listen_addr_size);
1453 /*********************************************************************
1455 * Function : resolve_hostname_to_ip
1457 * Description : Resolve a hostname to an internet tcp/ip address.
1458 * NULL or an empty string resolve to INADDR_ANY.
1461 * 1 : host = hostname to resolve
1463 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1465 *********************************************************************/
1466 unsigned long resolve_hostname_to_ip(const char *host)
1468 struct sockaddr_in inaddr;
1469 struct hostent *hostp;
1470 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1471 struct hostent result;
1472 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1473 char hbuf[HOSTENT_BUFFER_SIZE];
1475 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1476 struct hostent_data hdata;
1477 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1478 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1480 if ((host == NULL) || (*host == '\0'))
1485 memset((char *) &inaddr, 0, sizeof inaddr);
1487 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1489 unsigned int dns_retries = 0;
1490 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1491 while (gethostbyname_r(host, &result, hbuf,
1492 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1493 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1495 log_error(LOG_LEVEL_ERROR,
1496 "Timeout #%u while trying to resolve %s. Trying again.",
1499 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1500 while (NULL == (hostp = gethostbyname_r(host, &result,
1501 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1502 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1504 log_error(LOG_LEVEL_ERROR,
1505 "Timeout #%u while trying to resolve %s. Trying again.",
1508 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1510 * XXX: Doesn't retry in case of soft errors.
1511 * Does this gethostbyname_r version set h_errno?
1513 if (0 == gethostbyname_r(host, &result, &hdata))
1521 #elif defined(MUTEX_LOCKS_AVAILABLE)
1522 privoxy_mutex_lock(&resolver_mutex);
1523 while (NULL == (hostp = gethostbyname(host))
1524 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1526 log_error(LOG_LEVEL_ERROR,
1527 "Timeout #%u while trying to resolve %s. Trying again.",
1530 privoxy_mutex_unlock(&resolver_mutex);
1532 while (NULL == (hostp = gethostbyname(host))
1533 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1535 log_error(LOG_LEVEL_ERROR,
1536 "Timeout #%u while trying to resolve %s. Trying again.",
1539 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1541 * On Mac OSX, if a domain exists but doesn't have a type A
1542 * record associated with it, the h_addr member of the struct
1543 * hostent returned by gethostbyname is NULL, even if h_length
1544 * is 4. Therefore the second test below.
1546 if (hostp == NULL || hostp->h_addr == NULL)
1549 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1550 return(INADDR_NONE);
1552 if (hostp->h_addrtype != AF_INET)
1555 errno = WSAEPROTOTYPE;
1559 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1560 return(INADDR_NONE);
1562 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1564 return(inaddr.sin_addr.s_addr);
1569 /*********************************************************************
1571 * Function : socket_is_still_alive
1573 * Description : Figures out whether or not a socket is still alive.
1576 * 1 : sfd = The socket to check.
1578 * Returns : TRUE for yes, otherwise FALSE.
1580 *********************************************************************/
1581 int socket_is_still_alive(jb_socket sfd)
1584 int no_data_waiting;
1587 struct pollfd poll_fd[1];
1589 memset(poll_fd, 0, sizeof(poll_fd));
1590 poll_fd[0].fd = sfd;
1591 poll_fd[0].events = POLLIN;
1593 poll_result = poll(poll_fd, 1, 0);
1595 if (-1 == poll_result)
1597 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1600 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1602 fd_set readable_fds;
1603 struct timeval timeout;
1606 memset(&timeout, '\0', sizeof(timeout));
1607 FD_ZERO(&readable_fds);
1608 FD_SET(sfd, &readable_fds);
1610 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1613 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1616 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1617 #endif /* def HAVE_POLL */
1619 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1623 #ifdef FEATURE_EXTERNAL_FILTERS
1624 /*********************************************************************
1626 * Function : mark_socket_for_close_on_execute
1628 * Description : Marks a socket for close on execute.
1630 * Used so that external filters have no direct
1631 * access to sockets they shouldn't care about.
1633 * Not implemented for all platforms.
1636 * 1 : fd = The socket to mark
1640 *********************************************************************/
1641 void mark_socket_for_close_on_execute(jb_socket fd)
1643 #ifdef FEATURE_PTHREAD
1646 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1650 log_error(LOG_LEVEL_ERROR,
1651 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1654 #warning "Sockets will be visible to external filters"
1657 #endif /* def FEATURE_EXTERNAL_FILTERS */