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;
199 struct pollfd poll_fd[1];
200 #if !defined(_WIN32) && !defined(__BEOS__)
205 * XXX: Initializing it here is only necessary
206 * because not all situations are properly
209 int socket_error = 0;
212 struct access_control_addr dst[1];
213 #endif /* def FEATURE_ACL */
215 /* Don't leak memory when retrying. */
216 freez(csp->error_message);
217 freez(csp->http->host_ip_addr_str);
219 retval = snprintf(service, sizeof(service), "%d", portnum);
220 if ((-1 == retval) || (sizeof(service) <= retval))
222 log_error(LOG_LEVEL_ERROR,
223 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
225 csp->error_message = strdup("Invalid port number");
226 csp->http->host_ip_addr_str = strdup("unknown");
227 return(JB_INVALID_SOCKET);
230 memset((char *)&hints, 0, sizeof(hints));
231 hints.ai_family = AF_UNSPEC;
232 hints.ai_socktype = SOCK_STREAM;
233 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
235 hints.ai_flags |= AI_ADDRCONFIG;
237 if ((retval = getaddrinfo(host, service, &hints, &result)))
239 log_error(LOG_LEVEL_INFO,
240 "Can not resolve %s: %s", host, gai_strerror(retval));
241 csp->error_message = strdup(gai_strerror(retval));
242 csp->http->host_ip_addr_str = strdup("unknown");
243 /* XXX: Should find a better way to propagate this error. */
245 return(JB_INVALID_SOCKET);
248 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
250 for (rp = result; rp != NULL; rp = rp->ai_next)
254 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
256 if (block_acl(dst, csp))
258 socket_error = errno = EPERM;
261 #endif /* def FEATURE_ACL */
263 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
264 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
267 log_error(LOG_LEVEL_ERROR,
268 "Failed to get the host name from the socket structure: %s",
269 gai_strerror(retval));
273 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
275 if (fd == JB_INVALID_SOCKET)
283 #ifdef FEATURE_EXTERNAL_FILTERS
284 mark_socket_for_close_on_execute(fd);
287 set_no_delay_flag(fd);
289 #if !defined(_WIN32) && !defined(__BEOS__)
290 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
293 fcntl(fd, F_SETFL, flags);
295 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
298 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
301 if (errno == WSAEINPROGRESS)
302 #else /* ifndef _WIN32 */
303 if (errno == EINPROGRESS)
304 #endif /* ndef _WIN32 */
311 socket_error = errno;
322 #if !defined(_WIN32) && !defined(__BEOS__)
326 fcntl(fd, F_SETFL, flags);
328 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
331 poll_fd[0].events = POLLOUT;
333 retval = poll(poll_fd, 1, 30000);
336 if (rp->ai_next != NULL)
338 /* Log this now as we'll try another address next */
339 log_error(LOG_LEVEL_CONNECT,
340 "Could not connect to [%s]:%s: Operation timed out.",
341 csp->http->host_ip_addr_str, service);
346 * This is the last address, don't log this now
347 * as it would result in a duplicated log message.
349 socket_error = ETIMEDOUT;
354 socklen_t optlen = sizeof(socket_error);
355 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
359 /* Connection established, no need to try other addresses. */
362 if (rp->ai_next != NULL)
365 * There's another address we can try, so log that this
366 * one didn't work out. If the last one fails, too,
367 * it will get logged outside the loop body so we don't
368 * have to mention it here.
370 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
371 csp->http->host_ip_addr_str, service, strerror(socket_error));
376 socket_error = errno;
377 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
378 "the connection to [%s]:%s: %s; dropping connection.",
379 csp->http->host_ip_addr_str, service, strerror(errno));
383 /* Connection failed, try next address */
387 freeaddrinfo(result);
390 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
391 host, service, strerror(socket_error));
392 csp->error_message = strdup(strerror(socket_error));
393 return(JB_INVALID_SOCKET);
395 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
396 host, csp->http->host_ip_addr_str, service);
402 #else /* ndef HAVE_RFC2553 */
403 /* Pre-getaddrinfo implementation */
405 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
407 struct sockaddr_in inaddr;
410 struct pollfd poll_fd[1];
411 #if !defined(_WIN32) && !defined(__BEOS__)
416 struct access_control_addr dst[1];
417 #endif /* def FEATURE_ACL */
419 /* Don't leak memory when retrying. */
420 freez(csp->http->host_ip_addr_str);
422 memset((char *)&inaddr, 0, sizeof inaddr);
424 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
426 csp->http->host_ip_addr_str = strdup("unknown");
427 return(JB_INVALID_SOCKET);
431 dst->addr = ntohl(addr);
434 if (block_acl(dst, csp))
437 return(JB_INVALID_SOCKET);
439 #endif /* def FEATURE_ACL */
441 inaddr.sin_addr.s_addr = addr;
442 inaddr.sin_family = AF_INET;
443 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
446 if (sizeof(inaddr.sin_port) == sizeof(short))
447 #endif /* ndef _WIN32 */
449 inaddr.sin_port = htons((unsigned short) portnum);
454 inaddr.sin_port = htonl((unsigned long)portnum);
456 #endif /* ndef _WIN32 */
458 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
460 if (fd == JB_INVALID_SOCKET)
465 return(JB_INVALID_SOCKET);
468 set_no_delay_flag(fd);
470 #if !defined(_WIN32) && !defined(__BEOS__)
471 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
474 fcntl(fd, F_SETFL, flags);
475 #ifdef FEATURE_EXTERNAL_FILTERS
476 mark_socket_for_close_on_execute(fd);
479 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
481 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
484 if (errno == WSAEINPROGRESS)
485 #else /* ifndef _WIN32 */
486 if (errno == EINPROGRESS)
487 #endif /* ndef _WIN32 */
495 return(JB_INVALID_SOCKET);
499 #if !defined(_WIN32) && !defined(__BEOS__)
503 fcntl(fd, F_SETFL, flags);
505 #endif /* !defined(_WIN32) && !defined(__BEOS__) */
508 poll_fd[0].events = POLLOUT;
510 if (poll(poll_fd, 1, 30000) <= 0)
513 return(JB_INVALID_SOCKET);
518 #endif /* ndef HAVE_RFC2553 */
521 /*********************************************************************
523 * Function : write_socket
525 * Description : Write the contents of buf (for n bytes) to socket fd.
528 * 1 : fd = file descriptor (aka. handle) of socket to write to.
529 * 2 : buf = pointer to data to be written.
530 * 3 : len = length of data to be written to the socket "fd".
532 * Returns : 0 on success (entire buffer sent).
535 *********************************************************************/
536 int write_socket(jb_socket fd, const char *buf, size_t len)
544 if (!daemon_mode && fd <= 3)
546 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
551 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
554 return (send(fd, buf, (int)len, 0) != (int)len);
555 #elif defined(__BEOS__)
556 return (send(fd, buf, len, 0) != len);
558 return (write(fd, buf, len) != len);
564 /*********************************************************************
566 * Function : write_socket_delayed
568 * Description : Write the contents of buf (for n bytes) to
569 * socket fd, optionally delaying the operation.
572 * 1 : fd = File descriptor (aka. handle) of socket to write to.
573 * 2 : buf = Pointer to data to be written.
574 * 3 : len = Length of data to be written to the socket "fd".
575 * 4 : delay = Delay in milliseconds.
577 * Returns : 0 on success (entire buffer sent).
580 *********************************************************************/
581 int write_socket_delayed(jb_socket fd, const char *buf, size_t len, unsigned int delay)
587 return write_socket(fd, buf, len);
593 enum {MAX_WRITE_LENGTH = 10};
595 if ((i + MAX_WRITE_LENGTH) > len)
597 write_length = len - i;
601 write_length = MAX_WRITE_LENGTH;
604 privoxy_millisleep(delay);
606 if (write_socket(fd, buf + i, write_length) != 0)
618 /*********************************************************************
620 * Function : read_socket
622 * Description : Read from a TCP/IP socket in a platform independent way.
625 * 1 : fd = file descriptor of the socket to read
626 * 2 : buf = pointer to buffer where data will be written
627 * Must be >= len bytes long.
628 * 3 : len = maximum number of bytes to read
630 * Returns : On success, the number of bytes read is returned (zero
631 * indicates end of file), and the file position is advanced
632 * by this number. It is not an error if this number is
633 * smaller than the number of bytes requested; this may hap-
634 * pen for example because fewer bytes are actually available
635 * right now (maybe because we were close to end-of-file, or
636 * because we are reading from a pipe, or from a terminal,
637 * or because read() was interrupted by a signal). On error,
638 * -1 is returned, and errno is set appropriately. In this
639 * case it is left unspecified whether the file position (if
642 *********************************************************************/
643 int read_socket(jb_socket fd, char *buf, int len)
653 ret = recv(fd, buf, len, 0);
654 #elif defined(__BEOS__)
655 ret = recv(fd, buf, (size_t)len, 0);
657 ret = (int)read(fd, buf, (size_t)len);
662 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
669 /*********************************************************************
671 * Function : data_is_available
673 * Description : Waits for data to arrive on a socket.
676 * 1 : fd = file descriptor of the socket to read
677 * 2 : seconds_to_wait = number of seconds after which we give up.
679 * Returns : TRUE if data arrived in time,
682 *********************************************************************/
683 int data_is_available(jb_socket fd, int seconds_to_wait)
687 struct pollfd poll_fd[1];
690 poll_fd[0].events = POLLIN;
692 n = poll(poll_fd, 1, seconds_to_wait * 1000);
695 * XXX: Do we care about the different error conditions?
697 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
701 /*********************************************************************
703 * Function : close_socket
705 * Description : Closes a TCP/IP socket
708 * 1 : fd = file descriptor of socket to be closed
712 *********************************************************************/
713 void close_socket(jb_socket fd)
715 #if defined(_WIN32) || defined(__BEOS__)
723 /*********************************************************************
725 * Function : drain_and_close_socket
727 * Description : Closes a TCP/IP socket after draining unread data
730 * 1 : fd = file descriptor of the socket to be closed
734 *********************************************************************/
735 void drain_and_close_socket(jb_socket fd)
737 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
738 if (socket_is_still_alive(fd))
741 int bytes_drained_total = 0;
745 /* Apparently Windows has shutdown() but not SHUT_WR. */
749 if (0 != shutdown(fd, SHUT_WR))
751 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
754 #define ARBITRARY_DRAIN_LIMIT 10000
759 if (!data_is_available(fd, 0))
762 * If there is no data available right now, don't try
763 * to drain the socket as read_socket() could block.
768 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
769 if (bytes_drained < 0)
771 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
773 else if (bytes_drained > 0)
775 bytes_drained_total += bytes_drained;
776 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
778 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
782 } while (bytes_drained > 0);
783 if (bytes_drained_total != 0)
785 log_error(LOG_LEVEL_CONNECT,
786 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
795 /*********************************************************************
797 * Function : bind_port
799 * Description : Call socket, set socket options, and listen.
800 * Called by listen_loop to "boot up" our proxy address.
803 * 1 : hostnam = TCP/IP address to bind/listen to
804 * 2 : portnum = port to listen on
805 * 3 : backlog = Listen backlog
806 * 4 : pfd = pointer used to return file descriptor.
808 * Returns : if success, returns 0 and sets *pfd.
809 * if failure, returns -3 if address is in use,
810 * -2 if address unresolvable,
812 *********************************************************************/
813 int bind_port(const char *hostnam, int portnum, int backlog, jb_socket *pfd)
816 struct addrinfo hints;
817 struct addrinfo *result, *rp;
819 * XXX: portnum should be a string to allow symbolic service
820 * names in the configuration file and to avoid the following
826 struct sockaddr_in inaddr;
827 #endif /* def HAVE_RFC2553 */
831 #endif /* ndef _WIN32 */
833 *pfd = JB_INVALID_SOCKET;
836 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
837 if ((-1 == retval) || (sizeof(servnam) <= retval))
839 log_error(LOG_LEVEL_ERROR,
840 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
845 memset(&hints, 0, sizeof(struct addrinfo));
849 * XXX: This is a hack. The right thing to do
850 * would be to bind to both AF_INET and AF_INET6.
851 * This will also fail if there is no AF_INET
854 hints.ai_family = AF_INET;
858 hints.ai_family = AF_UNSPEC;
860 hints.ai_socktype = SOCK_STREAM;
861 hints.ai_flags = AI_PASSIVE;
862 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
863 hints.ai_canonname = NULL;
864 hints.ai_addr = NULL;
865 hints.ai_next = NULL;
867 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
869 log_error(LOG_LEVEL_ERROR,
870 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
874 memset((char *)&inaddr, '\0', sizeof inaddr);
876 inaddr.sin_family = AF_INET;
877 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
879 if (inaddr.sin_addr.s_addr == INADDR_NONE)
885 if (sizeof(inaddr.sin_port) == sizeof(short))
886 #endif /* ndef _WIN32 */
888 inaddr.sin_port = htons((unsigned short) portnum);
893 inaddr.sin_port = htonl((unsigned long) portnum);
895 #endif /* ndef _WIN32 */
896 #endif /* def HAVE_RFC2553 */
899 for (rp = result; rp != NULL; rp = rp->ai_next)
901 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
903 fd = socket(AF_INET, SOCK_STREAM, 0);
904 #endif /* def HAVE_RFC2553 */
907 if (fd == JB_INVALID_SOCKET)
919 #ifdef FEATURE_EXTERNAL_FILTERS
920 mark_socket_for_close_on_execute(fd);
925 * This is not needed for Win32 - in fact, it stops
926 * duplicate instances of Privoxy from being caught.
928 * On UNIX, we assume the user is sensible enough not
929 * to start Privoxy multiple times on the same IP.
930 * Without this, stopping and restarting Privoxy
931 * from a script fails.
932 * Note: SO_REUSEADDR is meant to only take over
933 * sockets which are *not* in listen state in Linux,
934 * e.g. sockets in TIME_WAIT. YMMV.
936 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
937 #endif /* ndef _WIN32 */
940 setsockopt(fd, IPPROTO_IP, IP_FREEBIND, (char *)&one, sizeof(one));
944 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
946 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
950 errno = WSAGetLastError();
951 if (errno == WSAEADDRINUSE)
953 if (errno == EADDRINUSE)
957 freeaddrinfo(result);
974 /* bind() succeeded, escape from for-loop */
976 * XXX: Support multiple listening sockets (e.g. localhost
977 * resolves to AF_INET and AF_INET6, but only the first address
984 freeaddrinfo(result);
987 /* All bind()s failed */
990 #endif /* ndef HAVE_RFC2553 */
992 while (listen(fd, backlog) == -1)
1007 /*********************************************************************
1009 * Function : get_host_information
1011 * Description : Determines the IP address the client used to
1012 * reach us and the hostname associated with it.
1014 * XXX: Most of the code has been copy and pasted
1015 * from accept_connection() and not all of the
1016 * ifdefs paths have been tested afterwards.
1019 * 1 : afd = File descriptor returned from accept().
1020 * 2 : ip_address = Pointer to return the pointer to
1021 * the ip address string.
1022 * 3 : port = Pointer to return the pointer to
1023 * the TCP port string.
1024 * 4 : hostname = Pointer to return the pointer to
1025 * the hostname or NULL if the caller
1026 * isn't interested in it.
1030 *********************************************************************/
1031 void get_host_information(jb_socket afd, char **ip_address, char **port,
1035 struct sockaddr_storage server;
1038 struct sockaddr_in server;
1039 struct hostent *host = NULL;
1040 #endif /* HAVE_RFC2553 */
1042 /* according to accept_connection() this fixes a warning. */
1043 int s_length, s_length_provided;
1045 socklen_t s_length, s_length_provided;
1047 #ifndef HAVE_RFC2553
1048 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1049 struct hostent result;
1050 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1051 struct hostent_data hdata;
1053 char hbuf[HOSTENT_BUFFER_SIZE];
1055 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1056 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1057 #endif /* ifndef HAVE_RFC2553 */
1058 s_length = s_length_provided = sizeof(server);
1060 if (NULL != hostname)
1067 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1069 if (s_length > s_length_provided)
1071 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1075 * XXX: Workaround for missing header on Windows when
1076 * configured with --disable-ipv6-support.
1077 * The proper fix is to not use NI_MAXSERV in
1078 * that case. It works by accident on other platforms
1079 * as <netdb.h> is included unconditionally there.
1082 #define NI_MAXSERV 32
1084 *port = malloc_or_die(NI_MAXSERV);
1087 *ip_address = malloc_or_die(NI_MAXHOST);
1088 retval = getnameinfo((struct sockaddr *) &server, s_length,
1089 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1090 NI_NUMERICHOST|NI_NUMERICSERV);
1093 log_error(LOG_LEVEL_ERROR,
1094 "Unable to print my own IP address: %s", gai_strerror(retval));
1100 *ip_address = strdup(inet_ntoa(server.sin_addr));
1101 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1102 #endif /* HAVE_RFC2553 */
1103 if (NULL == hostname)
1106 * We're done here, the caller isn't
1107 * interested in knowing the hostname.
1113 *hostname = malloc_or_die(NI_MAXHOST);
1114 retval = getnameinfo((struct sockaddr *) &server, s_length,
1115 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1118 log_error(LOG_LEVEL_ERROR,
1119 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1123 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1124 gethostbyaddr_r((const char *)&server.sin_addr,
1125 sizeof(server.sin_addr), AF_INET,
1126 &result, hbuf, HOSTENT_BUFFER_SIZE,
1128 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1129 host = gethostbyaddr_r((const char *)&server.sin_addr,
1130 sizeof(server.sin_addr), AF_INET,
1131 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1132 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1133 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1134 sizeof(server.sin_addr), AF_INET,
1143 #elif defined(MUTEX_LOCKS_AVAILABLE)
1144 privoxy_mutex_lock(&resolver_mutex);
1145 host = gethostbyaddr((const char *)&server.sin_addr,
1146 sizeof(server.sin_addr), AF_INET);
1147 privoxy_mutex_unlock(&resolver_mutex);
1149 host = gethostbyaddr((const char *)&server.sin_addr,
1150 sizeof(server.sin_addr), AF_INET);
1154 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1158 *hostname = strdup(host->h_name);
1160 #endif /* else def HAVE_RFC2553 */
1167 /*********************************************************************
1169 * Function : accept_connection
1171 * Description : Accepts a connection on one of possibly multiple
1172 * sockets. The socket(s) to check must have been
1173 * created using bind_port().
1176 * 1 : csp = Client state, cfd, ip_addr_str, and
1177 * ip_addr_long will be set by this routine.
1178 * 2 : fds = File descriptors returned from bind_port
1180 * Returns : when a connection is accepted, it returns 1 (TRUE).
1181 * On an error it returns 0 (FALSE).
1183 *********************************************************************/
1184 int accept_connection(struct client_state * csp, jb_socket fds[])
1187 /* XXX: client is stored directly into csp->tcp_addr */
1188 #define client (csp->tcp_addr)
1190 struct sockaddr_in client;
1194 /* Weirdness - fix a warning. */
1201 int max_selected_socket;
1202 struct pollfd poll_fds[MAX_LISTENING_SOCKETS];
1203 nfds_t polled_sockets;
1205 const char *host_addr;
1206 size_t listen_addr_size;
1208 c_length = sizeof(client);
1210 memset(poll_fds, 0, sizeof(poll_fds));
1212 max_selected_socket = 0;
1213 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1215 if (JB_INVALID_SOCKET != fds[i])
1217 poll_fds[i].fd = fds[i];
1218 poll_fds[i].events = POLLIN;
1220 if (max_selected_socket < fds[i] + 1)
1222 max_selected_socket = fds[i] + 1;
1226 if (0 == max_selected_socket)
1232 retval = poll(poll_fds, polled_sockets, -1);
1233 } while (retval < 0 && errno == EINTR);
1238 log_error(LOG_LEVEL_ERROR,
1239 "Waiting on new client failed because poll(2) returned 0."
1240 " This should not happen.");
1244 log_error(LOG_LEVEL_ERROR,
1245 "Waiting on new client failed because of problems in poll(2): "
1246 "%s.", strerror(errno));
1250 for (i = 0; i < MAX_LISTENING_SOCKETS && (poll_fds[i].revents == 0); i++);
1251 if (i >= MAX_LISTENING_SOCKETS)
1253 log_error(LOG_LEVEL_ERROR,
1254 "poll(2) reported connected clients (number = %u, "
1255 "descriptor boundary = %u), but none found.",
1256 retval, max_selected_socket);
1261 /* Accept selected connection */
1263 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1264 if (afd == JB_INVALID_SOCKET)
1271 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1272 } while (afd < 0 && errno == EINTR);
1281 struct linger linger_options;
1282 linger_options.l_onoff = 1;
1283 linger_options.l_linger = 5;
1284 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1286 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1291 #ifdef FEATURE_EXTERNAL_FILTERS
1292 mark_socket_for_close_on_execute(afd);
1295 set_no_delay_flag(afd);
1299 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1300 retval = getnameinfo((struct sockaddr *) &client, c_length,
1301 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1302 if (!csp->ip_addr_str || retval)
1304 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1305 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1306 freez(csp->ip_addr_str);
1310 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1311 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1312 #endif /* def HAVE_RFC2553 */
1315 * Save the name and port of the accepting socket for later lookup.
1317 * The string needs space for strlen(...) + 7 characters:
1318 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1320 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1321 listen_addr_size = strlen(host_addr) + 7;
1322 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1323 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1324 "%s:%d", host_addr, csp->config->hport[i]);
1325 if ((-1 == retval) || listen_addr_size <= retval)
1327 log_error(LOG_LEVEL_ERROR,
1328 "Server name (%s) and port number (%d) ASCII decimal representation"
1329 "don't fit into %lu bytes",
1330 host_addr, csp->config->hport[i], listen_addr_size);
1339 /*********************************************************************
1341 * Function : resolve_hostname_to_ip
1343 * Description : Resolve a hostname to an internet tcp/ip address.
1344 * NULL or an empty string resolve to INADDR_ANY.
1347 * 1 : host = hostname to resolve
1349 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1351 *********************************************************************/
1352 unsigned long resolve_hostname_to_ip(const char *host)
1354 struct sockaddr_in inaddr;
1355 struct hostent *hostp;
1356 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1357 struct hostent result;
1358 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1359 char hbuf[HOSTENT_BUFFER_SIZE];
1361 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1362 struct hostent_data hdata;
1363 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1364 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1366 if ((host == NULL) || (*host == '\0'))
1371 memset((char *) &inaddr, 0, sizeof inaddr);
1373 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1375 unsigned int dns_retries = 0;
1376 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1377 while (gethostbyname_r(host, &result, hbuf,
1378 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1379 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1381 log_error(LOG_LEVEL_ERROR,
1382 "Timeout #%u while trying to resolve %s. Trying again.",
1385 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1386 while (NULL == (hostp = gethostbyname_r(host, &result,
1387 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1388 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1390 log_error(LOG_LEVEL_ERROR,
1391 "Timeout #%u while trying to resolve %s. Trying again.",
1394 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1396 * XXX: Doesn't retry in case of soft errors.
1397 * Does this gethostbyname_r version set h_errno?
1399 if (0 == gethostbyname_r(host, &result, &hdata))
1407 #elif defined(MUTEX_LOCKS_AVAILABLE)
1408 privoxy_mutex_lock(&resolver_mutex);
1409 while (NULL == (hostp = gethostbyname(host))
1410 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1412 log_error(LOG_LEVEL_ERROR,
1413 "Timeout #%u while trying to resolve %s. Trying again.",
1416 privoxy_mutex_unlock(&resolver_mutex);
1418 while (NULL == (hostp = gethostbyname(host))
1419 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1421 log_error(LOG_LEVEL_ERROR,
1422 "Timeout #%u while trying to resolve %s. Trying again.",
1425 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1427 * On Mac OSX, if a domain exists but doesn't have a type A
1428 * record associated with it, the h_addr member of the struct
1429 * hostent returned by gethostbyname is NULL, even if h_length
1430 * is 4. Therefore the second test below.
1432 if (hostp == NULL || hostp->h_addr == NULL)
1435 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1436 return(INADDR_NONE);
1438 if (hostp->h_addrtype != AF_INET)
1441 errno = WSAEPROTOTYPE;
1445 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1446 return(INADDR_NONE);
1448 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1450 return(inaddr.sin_addr.s_addr);
1455 /*********************************************************************
1457 * Function : socket_is_still_alive
1459 * Description : Figures out whether or not a socket is still alive.
1462 * 1 : sfd = The socket to check.
1464 * Returns : TRUE for yes, otherwise FALSE.
1466 *********************************************************************/
1467 int socket_is_still_alive(jb_socket sfd)
1470 int no_data_waiting;
1472 struct pollfd poll_fd[1];
1474 memset(poll_fd, 0, sizeof(poll_fd));
1475 poll_fd[0].fd = sfd;
1476 poll_fd[0].events = POLLIN;
1478 poll_result = poll(poll_fd, 1, 0);
1480 if (-1 == poll_result)
1482 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1485 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1487 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1491 #ifdef FEATURE_EXTERNAL_FILTERS
1492 /*********************************************************************
1494 * Function : mark_socket_for_close_on_execute
1496 * Description : Marks a socket for close on execute.
1498 * Used so that external filters have no direct
1499 * access to sockets they shouldn't care about.
1501 * Not implemented for all platforms.
1504 * 1 : fd = The socket to mark
1508 *********************************************************************/
1509 void mark_socket_for_close_on_execute(jb_socket fd)
1511 #ifdef FEATURE_PTHREAD
1514 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1518 log_error(LOG_LEVEL_ERROR,
1519 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1522 #warning "Sockets will be visible to external filters"
1525 #endif /* def FEATURE_EXTERNAL_FILTERS */