1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.138 2016/09/27 22:48:28 ler762 Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
6 * Purpose : Contains wrappers for system-specific sockets code,
7 * so that the rest of Junkbuster can be more
8 * OS-independent. Contains #ifdefs to make this work
11 * Copyright : Written by and Copyright (C) 2001-2016 the
12 * Privoxy team. http://www.privoxy.org/
14 * Based on the Internet Junkbuster originally written
15 * by and Copyright (C) 1997 Anonymous Coders and
16 * Junkbusters Corporation. http://www.junkbusters.com
18 * This program is free software; you can redistribute it
19 * and/or modify it under the terms of the GNU General
20 * Public License as published by the Free Software
21 * Foundation; either version 2 of the License, or (at
22 * your option) any later version.
24 * This program is distributed in the hope that it will
25 * be useful, but WITHOUT ANY WARRANTY; without even the
26 * implied warranty of MERCHANTABILITY or FITNESS FOR A
27 * PARTICULAR PURPOSE. See the GNU General Public
28 * License for more details.
30 * The GNU General Public License should be included with
31 * this file. If not, you can view it at
32 * http://www.gnu.org/copyleft/gpl.html
33 * or write to the Free Software Foundation, Inc., 59
34 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 *********************************************************************/
46 #include <sys/types.h>
55 #include <sys/timeb.h>
64 #include <netinet/in.h>
65 #include <sys/ioctl.h>
67 #include <sys/socket.h>
70 #include <netinet/tcp.h>
72 #include <arpa/inet.h>
78 #if defined(__EMX__) || defined (__OS2__)
79 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
97 /* For mutex semaphores only */
100 #include "jbsockets.h"
103 #include "miscutil.h"
105 /* Mac OSX doesn't define AI_NUMERICSESRV */
106 #ifndef AI_NUMERICSERV
107 #define AI_NUMERICSERV 0
110 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
113 * Maximum number of gethostbyname(_r) retries in case of
114 * soft errors (TRY_AGAIN).
115 * XXX: Does it make sense to make this a config option?
117 #define MAX_DNS_RETRIES 10
119 #define MAX_LISTEN_BACKLOG 128
122 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
124 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
127 /*********************************************************************
129 * Function : set_no_delay_flag
131 * Description : Disables TCP coalescence for the given socket.
134 * 1 : fd = The file descriptor to operate on
138 *********************************************************************/
139 static void set_no_delay_flag(int fd)
144 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
146 log_error(LOG_LEVEL_ERROR,
147 "Failed to disable TCP coalescence for socket %d", fd);
150 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
151 #endif /* def TCP_NODELAY */
154 /*********************************************************************
156 * Function : connect_to
158 * Description : Open a socket and connect to it. Will check
159 * that this is allowed according to ACL.
162 * 1 : host = hostname to connect to
163 * 2 : portnum = port to connect to (XXX: should be unsigned)
164 * 3 : csp = Current client state (buffers, headers, etc...)
166 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
169 *********************************************************************/
170 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
173 int forwarded_connect_retries = 0;
178 * XXX: The whole errno overloading is ridiculous and should
179 * be replaced with something sane and thread safe
183 fd = rfc2553_connect_to(host, portnum, csp);
185 fd = no_rfc2553_connect_to(host, portnum, csp);
187 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
188 || (csp->fwd == NULL)
189 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
193 forwarded_connect_retries++;
194 if (csp->config->forwarded_connect_retries != 0)
196 log_error(LOG_LEVEL_ERROR,
197 "Attempt %d of %d to connect to %s failed. Trying again.",
198 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
201 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
207 /* Getaddrinfo implementation */
208 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
210 struct addrinfo hints, *result, *rp;
215 struct timeval timeout;
216 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !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)
304 if (fd >= FD_SETSIZE)
306 log_error(LOG_LEVEL_ERROR,
307 "Server socket number too high to use select(): %d >= %d",
310 freeaddrinfo(result);
311 return JB_INVALID_SOCKET;
315 #ifdef FEATURE_EXTERNAL_FILTERS
316 mark_socket_for_close_on_execute(fd);
319 set_no_delay_flag(fd);
321 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
322 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
325 fcntl(fd, F_SETFL, flags);
327 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
330 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
333 errno = sock_errno();
337 if (errno == WSAEINPROGRESS)
338 #else /* ifndef _WIN32 */
339 if (errno == EINPROGRESS)
340 #endif /* ndef _WIN32 || __OS2__ */
347 socket_error = errno;
358 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
362 fcntl(fd, F_SETFL, flags);
364 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
366 /* wait for connection to complete */
370 memset(&timeout, 0, sizeof(timeout));
373 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
374 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
375 && FD_ISSET(fd, &wfds))
377 socklen_t optlen = sizeof(socket_error);
378 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
382 /* Connection established, no need to try other addresses. */
385 if (rp->ai_next != NULL)
388 * There's another address we can try, so log that this
389 * one didn't work out. If the last one fails, too,
390 * it will get logged outside the loop body so we don't
391 * have to mention it here.
393 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
394 csp->http->host_ip_addr_str, service, strerror(socket_error));
399 socket_error = errno;
400 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
401 "the connection to [%s]:%s: %s; dropping connection.",
402 csp->http->host_ip_addr_str, service, strerror(errno));
406 /* Connection failed, try next address */
410 freeaddrinfo(result);
413 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
414 host, service, strerror(socket_error));
415 csp->error_message = strdup(strerror(socket_error));
416 return(JB_INVALID_SOCKET);
418 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
419 host, csp->http->host_ip_addr_str, service);
425 #else /* ndef HAVE_RFC2553 */
426 /* Pre-getaddrinfo implementation */
428 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
430 struct sockaddr_in inaddr;
434 struct timeval tv[1];
435 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
440 struct access_control_addr dst[1];
441 #endif /* def FEATURE_ACL */
443 /* Don't leak memory when retrying. */
444 freez(csp->http->host_ip_addr_str);
446 memset((char *)&inaddr, 0, sizeof inaddr);
448 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
450 csp->http->host_ip_addr_str = strdup("unknown");
451 return(JB_INVALID_SOCKET);
455 dst->addr = ntohl(addr);
458 if (block_acl(dst, csp))
465 return(JB_INVALID_SOCKET);
467 #endif /* def FEATURE_ACL */
469 inaddr.sin_addr.s_addr = addr;
470 inaddr.sin_family = AF_INET;
471 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
474 if (sizeof(inaddr.sin_port) == sizeof(short))
475 #endif /* ndef _WIN32 */
477 inaddr.sin_port = htons((unsigned short) portnum);
482 inaddr.sin_port = htonl((unsigned long)portnum);
484 #endif /* ndef _WIN32 */
486 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
488 if (fd == JB_INVALID_SOCKET)
493 return(JB_INVALID_SOCKET);
497 if (fd >= FD_SETSIZE)
499 log_error(LOG_LEVEL_ERROR,
500 "Server socket number too high to use select(): %d >= %d",
503 return JB_INVALID_SOCKET;
507 set_no_delay_flag(fd);
509 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
510 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
513 fcntl(fd, F_SETFL, flags);
514 #ifdef FEATURE_EXTERNAL_FILTERS
515 mark_socket_for_close_on_execute(fd);
518 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
520 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
523 if (errno == WSAEINPROGRESS)
525 if (sock_errno() == EINPROGRESS)
526 #else /* ifndef _WIN32 */
527 if (errno == EINPROGRESS)
528 #endif /* ndef _WIN32 || __OS2__ */
534 if (sock_errno() != EINTR)
540 return(JB_INVALID_SOCKET);
544 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
548 fcntl(fd, F_SETFL, flags);
550 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
552 /* wait for connection to complete */
559 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
560 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
563 return(JB_INVALID_SOCKET);
568 #endif /* ndef HAVE_RFC2553 */
571 /*********************************************************************
573 * Function : write_socket
575 * Description : Write the contents of buf (for n bytes) to socket fd.
578 * 1 : fd = file descriptor (aka. handle) of socket to write to.
579 * 2 : buf = pointer to data to be written.
580 * 3 : len = length of data to be written to the socket "fd".
582 * Returns : 0 on success (entire buffer sent).
585 *********************************************************************/
587 int write_socket(jb_socket fd, const char *buf, ssize_t len)
589 int write_socket(jb_socket fd, const char *buf, size_t len)
598 if (!daemon_mode && fd <= 3)
600 log_error(LOG_LEVEL_WRITING, "Pretending to write to socket %d: %N", fd, len, buf);
605 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
608 return (send(fd, buf, (int)len, 0) != (int)len);
609 #elif defined(__BEOS__) || defined(AMIGA)
610 return (send(fd, buf, len, 0) != len);
611 #elif defined(__OS2__)
613 * Break the data up into SOCKET_SEND_MAX chunks for sending...
614 * OS/2 seemed to complain when the chunks were too large.
616 #define SOCKET_SEND_MAX 65000
618 int send_len, send_rc = 0, i = 0;
619 while ((i < len) && (send_rc != -1))
621 if ((i + SOCKET_SEND_MAX) > len)
624 send_len = SOCKET_SEND_MAX;
625 send_rc = send(fd,(char*)buf + i, send_len, 0);
633 return (write(fd, buf, len) != len);
639 /*********************************************************************
641 * Function : read_socket
643 * Description : Read from a TCP/IP socket in a platform independent way.
646 * 1 : fd = file descriptor of the socket to read
647 * 2 : buf = pointer to buffer where data will be written
648 * Must be >= len bytes long.
649 * 3 : len = maximum number of bytes to read
651 * Returns : On success, the number of bytes read is returned (zero
652 * indicates end of file), and the file position is advanced
653 * by this number. It is not an error if this number is
654 * smaller than the number of bytes requested; this may hap-
655 * pen for example because fewer bytes are actually available
656 * right now (maybe because we were close to end-of-file, or
657 * because we are reading from a pipe, or from a terminal,
658 * or because read() was interrupted by a signal). On error,
659 * -1 is returned, and errno is set appropriately. In this
660 * case it is left unspecified whether the file position (if
663 *********************************************************************/
664 int read_socket(jb_socket fd, char *buf, int len)
674 ret = recv(fd, buf, len, 0);
675 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
676 ret = recv(fd, buf, (size_t)len, 0);
678 ret = (int)read(fd, buf, (size_t)len);
683 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
690 /*********************************************************************
692 * Function : data_is_available
694 * Description : Waits for data to arrive on a socket.
697 * 1 : fd = file descriptor of the socket to read
698 * 2 : seconds_to_wait = number of seconds after which we give up.
700 * Returns : TRUE if data arrived in time,
703 *********************************************************************/
704 int data_is_available(jb_socket fd, int seconds_to_wait)
708 struct timeval timeout;
711 memset(&timeout, 0, sizeof(timeout));
712 timeout.tv_sec = seconds_to_wait;
715 /* Copy and pasted from jcc.c ... */
716 memset(&rfds, 0, sizeof(fd_set));
722 n = select(fd+1, &rfds, NULL, NULL, &timeout);
725 * XXX: Do we care about the different error conditions?
727 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
731 /*********************************************************************
733 * Function : close_socket
735 * Description : Closes a TCP/IP socket
738 * 1 : fd = file descriptor of socket to be closed
742 *********************************************************************/
743 void close_socket(jb_socket fd)
745 #if defined(_WIN32) || defined(__BEOS__)
749 #elif defined(__OS2__)
757 /*********************************************************************
759 * Function : drain_and_close_socket
761 * Description : Closes a TCP/IP socket after draining unread data
764 * 1 : fd = file descriptor of the socket to be closed
768 *********************************************************************/
769 void drain_and_close_socket(jb_socket fd)
771 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
772 if (socket_is_still_alive(fd))
775 int bytes_drained_total = 0;
779 /* Apparently Windows has shutdown() but not SHUT_WR. */
783 if (0 != shutdown(fd, SHUT_WR))
785 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
788 #define ARBITRARY_DRAIN_LIMIT 10000
793 if (!data_is_available(fd, 0))
796 * If there is no data available right now, don't try
797 * to drain the socket as read_socket() could block.
802 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
803 if (bytes_drained < 0)
805 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
807 else if (bytes_drained > 0)
809 bytes_drained_total += bytes_drained;
810 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
812 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
816 } while (bytes_drained > 0);
817 if (bytes_drained_total != 0)
819 log_error(LOG_LEVEL_CONNECT,
820 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
829 /*********************************************************************
831 * Function : bind_port
833 * Description : Call socket, set socket options, and listen.
834 * Called by listen_loop to "boot up" our proxy address.
837 * 1 : hostnam = TCP/IP address to bind/listen to
838 * 2 : portnum = port to listen on
839 * 3 : pfd = pointer used to return file descriptor.
841 * Returns : if success, returns 0 and sets *pfd.
842 * if failure, returns -3 if address is in use,
843 * -2 if address unresolvable,
845 *********************************************************************/
846 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
849 struct addrinfo hints;
850 struct addrinfo *result, *rp;
852 * XXX: portnum should be a string to allow symbolic service
853 * names in the configuration file and to avoid the following
859 struct sockaddr_in inaddr;
860 #endif /* def HAVE_RFC2553 */
864 #endif /* ndef _WIN32 */
866 *pfd = JB_INVALID_SOCKET;
869 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
870 if ((-1 == retval) || (sizeof(servnam) <= retval))
872 log_error(LOG_LEVEL_ERROR,
873 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
878 memset(&hints, 0, sizeof(struct addrinfo));
882 * XXX: This is a hack. The right thing to do
883 * would be to bind to both AF_INET and AF_INET6.
884 * This will also fail if there is no AF_INET
887 hints.ai_family = AF_INET;
891 hints.ai_family = AF_UNSPEC;
893 hints.ai_socktype = SOCK_STREAM;
894 hints.ai_flags = AI_PASSIVE;
895 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
896 hints.ai_canonname = NULL;
897 hints.ai_addr = NULL;
898 hints.ai_next = NULL;
900 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
902 log_error(LOG_LEVEL_ERROR,
903 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
907 memset((char *)&inaddr, '\0', sizeof inaddr);
909 inaddr.sin_family = AF_INET;
910 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
912 if (inaddr.sin_addr.s_addr == INADDR_NONE)
918 if (sizeof(inaddr.sin_port) == sizeof(short))
919 #endif /* ndef _WIN32 */
921 inaddr.sin_port = htons((unsigned short) portnum);
926 inaddr.sin_port = htonl((unsigned long) portnum);
928 #endif /* ndef _WIN32 */
929 #endif /* def HAVE_RFC2553 */
932 for (rp = result; rp != NULL; rp = rp->ai_next)
934 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
936 fd = socket(AF_INET, SOCK_STREAM, 0);
937 #endif /* def HAVE_RFC2553 */
940 if (fd == JB_INVALID_SOCKET)
952 #ifdef FEATURE_EXTERNAL_FILTERS
953 mark_socket_for_close_on_execute(fd);
958 * This is not needed for Win32 - in fact, it stops
959 * duplicate instances of Privoxy from being caught.
961 * On UNIX, we assume the user is sensible enough not
962 * to start Privoxy multiple times on the same IP.
963 * Without this, stopping and restarting Privoxy
964 * from a script fails.
965 * Note: SO_REUSEADDR is meant to only take over
966 * sockets which are *not* in listen state in Linux,
967 * e.g. sockets in TIME_WAIT. YMMV.
969 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
970 #endif /* ndef _WIN32 */
973 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
975 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
979 errno = WSAGetLastError();
980 if (errno == WSAEADDRINUSE)
982 if (errno == EADDRINUSE)
986 freeaddrinfo(result);
1003 /* bind() succeeded, escape from for-loop */
1005 * XXX: Support multiple listening sockets (e.g. localhost
1006 * resolves to AF_INET and AF_INET6, but only the first address
1013 freeaddrinfo(result);
1016 /* All bind()s failed */
1019 #endif /* ndef HAVE_RFC2553 */
1021 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1036 /*********************************************************************
1038 * Function : get_host_information
1040 * Description : Determines the IP address the client used to
1041 * reach us and the hostname associated with it.
1043 * XXX: Most of the code has been copy and pasted
1044 * from accept_connection() and not all of the
1045 * ifdefs paths have been tested afterwards.
1048 * 1 : afd = File descriptor returned from accept().
1049 * 2 : ip_address = Pointer to return the pointer to
1050 * the ip address string.
1051 * 3 : port = Pointer to return the pointer to
1052 * the TCP port string.
1053 * 4 : hostname = Pointer to return the pointer to
1054 * the hostname or NULL if the caller
1055 * isn't interested in it.
1059 *********************************************************************/
1060 void get_host_information(jb_socket afd, char **ip_address, char **port,
1064 struct sockaddr_storage server;
1067 struct sockaddr_in server;
1068 struct hostent *host = NULL;
1069 #endif /* HAVE_RFC2553 */
1070 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1071 /* according to accept_connection() this fixes a warning. */
1072 int s_length, s_length_provided;
1074 socklen_t s_length, s_length_provided;
1076 #ifndef HAVE_RFC2553
1077 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1078 struct hostent result;
1079 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1080 struct hostent_data hdata;
1082 char hbuf[HOSTENT_BUFFER_SIZE];
1084 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1085 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1086 #endif /* ifndef HAVE_RFC2553 */
1087 s_length = s_length_provided = sizeof(server);
1089 if (NULL != hostname)
1096 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1098 if (s_length > s_length_provided)
1100 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1104 * XXX: Workaround for missing header on Windows when
1105 * configured with --disable-ipv6-support.
1106 * The proper fix is to not use NI_MAXSERV in
1107 * that case. It works by accident on other platforms
1108 * as <netdb.h> is included unconditionally there.
1111 #define NI_MAXSERV 32
1113 *port = malloc_or_die(NI_MAXSERV);
1116 *ip_address = malloc_or_die(NI_MAXHOST);
1117 retval = getnameinfo((struct sockaddr *) &server, s_length,
1118 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1119 NI_NUMERICHOST|NI_NUMERICSERV);
1122 log_error(LOG_LEVEL_ERROR,
1123 "Unable to print my own IP address: %s", gai_strerror(retval));
1129 *ip_address = strdup(inet_ntoa(server.sin_addr));
1130 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1131 #endif /* HAVE_RFC2553 */
1132 if (NULL == hostname)
1135 * We're done here, the caller isn't
1136 * interested in knowing the hostname.
1142 *hostname = malloc_or_die(NI_MAXHOST);
1143 retval = getnameinfo((struct sockaddr *) &server, s_length,
1144 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1147 log_error(LOG_LEVEL_ERROR,
1148 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1152 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1153 gethostbyaddr_r((const char *)&server.sin_addr,
1154 sizeof(server.sin_addr), AF_INET,
1155 &result, hbuf, HOSTENT_BUFFER_SIZE,
1157 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1158 host = gethostbyaddr_r((const char *)&server.sin_addr,
1159 sizeof(server.sin_addr), AF_INET,
1160 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1161 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1162 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1163 sizeof(server.sin_addr), AF_INET,
1172 #elif defined(MUTEX_LOCKS_AVAILABLE)
1173 privoxy_mutex_lock(&resolver_mutex);
1174 host = gethostbyaddr((const char *)&server.sin_addr,
1175 sizeof(server.sin_addr), AF_INET);
1176 privoxy_mutex_unlock(&resolver_mutex);
1178 host = gethostbyaddr((const char *)&server.sin_addr,
1179 sizeof(server.sin_addr), AF_INET);
1183 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1187 *hostname = strdup(host->h_name);
1189 #endif /* else def HAVE_RFC2553 */
1196 /*********************************************************************
1198 * Function : accept_connection
1200 * Description : Accepts a connection on one of possibly multiple
1201 * sockets. The socket(s) to check must have been
1202 * created using bind_port().
1205 * 1 : csp = Client state, cfd, ip_addr_str, and
1206 * ip_addr_long will be set by this routine.
1207 * 2 : fds = File descriptors returned from bind_port
1209 * Returns : when a connection is accepted, it returns 1 (TRUE).
1210 * On an error it returns 0 (FALSE).
1212 *********************************************************************/
1213 int accept_connection(struct client_state * csp, jb_socket fds[])
1216 /* XXX: client is stored directly into csp->tcp_addr */
1217 #define client (csp->tcp_addr)
1219 struct sockaddr_in client;
1222 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1223 /* Wierdness - fix a warning. */
1230 int max_selected_socket;
1231 fd_set selected_fds;
1233 const char *host_addr;
1234 size_t listen_addr_size;
1236 c_length = sizeof(client);
1239 * Wait for a connection on any socket.
1240 * Return immediately if no socket is listening.
1241 * XXX: Why not treat this as fatal error?
1243 FD_ZERO(&selected_fds);
1244 max_selected_socket = 0;
1245 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1247 if (JB_INVALID_SOCKET != fds[i])
1249 FD_SET(fds[i], &selected_fds);
1250 if (max_selected_socket < fds[i] + 1)
1252 max_selected_socket = fds[i] + 1;
1256 if (0 == max_selected_socket)
1262 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1263 } while (retval < 0 && errno == EINTR);
1268 log_error(LOG_LEVEL_ERROR,
1269 "Waiting on new client failed because select(2) returned 0."
1270 " This should not happen.");
1274 log_error(LOG_LEVEL_ERROR,
1275 "Waiting on new client failed because of problems in select(2): "
1276 "%s.", strerror(errno));
1280 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1282 if (i >= MAX_LISTENING_SOCKETS)
1284 log_error(LOG_LEVEL_ERROR,
1285 "select(2) reported connected clients (number = %u, "
1286 "descriptor boundary = %u), but none found.",
1287 retval, max_selected_socket);
1292 /* Accept selected connection */
1294 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1295 if (afd == JB_INVALID_SOCKET)
1302 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1303 struct accept_filter_arg af_options;
1304 bzero(&af_options, sizeof(af_options));
1305 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1306 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1308 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1309 } while (afd < 0 && errno == EINTR);
1318 struct linger linger_options;
1319 linger_options.l_onoff = 1;
1320 linger_options.l_linger = 5;
1321 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1323 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1329 if (afd >= FD_SETSIZE)
1331 log_error(LOG_LEVEL_ERROR,
1332 "Client socket number too high to use select(): %d >= %d",
1339 #ifdef FEATURE_EXTERNAL_FILTERS
1340 mark_socket_for_close_on_execute(afd);
1343 set_no_delay_flag(afd);
1347 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1348 retval = getnameinfo((struct sockaddr *) &client, c_length,
1349 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1350 if (!csp->ip_addr_str || retval)
1352 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1353 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1354 freez(csp->ip_addr_str);
1358 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1359 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1360 #endif /* def HAVE_RFC2553 */
1363 * Save the name and port of the accepting socket for later lookup.
1365 * The string needs space for strlen(...) + 7 characters:
1366 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1368 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1369 listen_addr_size = strlen(host_addr) + 7;
1370 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1371 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1372 "%s:%d", host_addr, csp->config->hport[i]);
1373 if ((-1 == retval) || listen_addr_size <= retval)
1375 log_error(LOG_LEVEL_ERROR,
1376 "Server name (%s) and port number (%d) ASCII decimal representation"
1377 "don't fit into %d bytes",
1378 host_addr, csp->config->hport[i], listen_addr_size);
1387 /*********************************************************************
1389 * Function : resolve_hostname_to_ip
1391 * Description : Resolve a hostname to an internet tcp/ip address.
1392 * NULL or an empty string resolve to INADDR_ANY.
1395 * 1 : host = hostname to resolve
1397 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1399 *********************************************************************/
1400 unsigned long resolve_hostname_to_ip(const char *host)
1402 struct sockaddr_in inaddr;
1403 struct hostent *hostp;
1404 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1405 struct hostent result;
1406 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1407 char hbuf[HOSTENT_BUFFER_SIZE];
1409 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1410 struct hostent_data hdata;
1411 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1412 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1414 if ((host == NULL) || (*host == '\0'))
1419 memset((char *) &inaddr, 0, sizeof inaddr);
1421 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1423 unsigned int dns_retries = 0;
1424 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1425 while (gethostbyname_r(host, &result, hbuf,
1426 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1427 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1429 log_error(LOG_LEVEL_ERROR,
1430 "Timeout #%u while trying to resolve %s. Trying again.",
1433 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1434 while (NULL == (hostp = gethostbyname_r(host, &result,
1435 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1436 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1438 log_error(LOG_LEVEL_ERROR,
1439 "Timeout #%u while trying to resolve %s. Trying again.",
1442 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1444 * XXX: Doesn't retry in case of soft errors.
1445 * Does this gethostbyname_r version set h_errno?
1447 if (0 == gethostbyname_r(host, &result, &hdata))
1455 #elif defined(MUTEX_LOCKS_AVAILABLE)
1456 privoxy_mutex_lock(&resolver_mutex);
1457 while (NULL == (hostp = gethostbyname(host))
1458 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1460 log_error(LOG_LEVEL_ERROR,
1461 "Timeout #%u while trying to resolve %s. Trying again.",
1464 privoxy_mutex_unlock(&resolver_mutex);
1466 while (NULL == (hostp = gethostbyname(host))
1467 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1469 log_error(LOG_LEVEL_ERROR,
1470 "Timeout #%u while trying to resolve %s. Trying again.",
1473 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1475 * On Mac OSX, if a domain exists but doesn't have a type A
1476 * record associated with it, the h_addr member of the struct
1477 * hostent returned by gethostbyname is NULL, even if h_length
1478 * is 4. Therefore the second test below.
1480 if (hostp == NULL || hostp->h_addr == NULL)
1483 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1484 return(INADDR_NONE);
1486 if (hostp->h_addrtype != AF_INET)
1489 errno = WSAEPROTOTYPE;
1493 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1494 return(INADDR_NONE);
1496 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1498 return(inaddr.sin_addr.s_addr);
1503 /*********************************************************************
1505 * Function : socket_is_still_alive
1507 * Description : Figures out whether or not a socket is still alive.
1510 * 1 : sfd = The socket to check.
1512 * Returns : TRUE for yes, otherwise FALSE.
1514 *********************************************************************/
1515 int socket_is_still_alive(jb_socket sfd)
1518 int no_data_waiting;
1522 struct pollfd poll_fd[1];
1524 memset(poll_fd, 0, sizeof(poll_fd));
1525 poll_fd[0].fd = sfd;
1526 poll_fd[0].events = POLLIN;
1528 poll_result = poll(poll_fd, 1, 0);
1530 if (-1 == poll_result)
1532 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1535 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1537 fd_set readable_fds;
1538 struct timeval timeout;
1541 memset(&timeout, '\0', sizeof(timeout));
1542 FD_ZERO(&readable_fds);
1543 FD_SET(sfd, &readable_fds);
1545 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1548 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1551 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1552 #endif /* def HAVE_POLL */
1554 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1558 #ifdef FEATURE_EXTERNAL_FILTERS
1559 /*********************************************************************
1561 * Function : mark_socket_for_close_on_execute
1563 * Description : Marks a socket for close on execute.
1565 * Used so that external filters have no direct
1566 * access to sockets they shouldn't care about.
1568 * Not implemented for all platforms.
1571 * 1 : fd = The socket to mark
1575 *********************************************************************/
1576 void mark_socket_for_close_on_execute(jb_socket fd)
1578 #ifdef FEATURE_PTHREAD
1581 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1585 log_error(LOG_LEVEL_ERROR,
1586 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1589 #warning "Sockets will be visible to external filters"
1592 #endif /* def FEATURE_EXTERNAL_FILTERS */