1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.136 2016/05/25 10:50:55 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
6 * Purpose : Contains wrappers for system-specific sockets code,
7 * so that the rest of 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>
54 #include <sys/timeb.h>
63 #include <netinet/in.h>
64 #include <sys/ioctl.h>
66 #include <sys/socket.h>
69 #include <netinet/tcp.h>
71 #include <arpa/inet.h>
77 #if defined(__EMX__) || defined (__OS2__)
78 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
91 #endif /* def __GLIBC__ */
92 #endif /* HAVE_POLL */
96 /* For mutex semaphores only */
99 #include "jbsockets.h"
102 #include "miscutil.h"
104 /* Mac OSX doesn't define AI_NUMERICSESRV */
105 #ifndef AI_NUMERICSERV
106 #define AI_NUMERICSERV 0
109 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
112 * Maximum number of gethostbyname(_r) retries in case of
113 * soft errors (TRY_AGAIN).
114 * XXX: Does it make sense to make this a config option?
116 #define MAX_DNS_RETRIES 10
118 #define MAX_LISTEN_BACKLOG 128
121 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
123 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
126 /*********************************************************************
128 * Function : set_no_delay_flag
130 * Description : Disables TCP coalescence for the given socket.
133 * 1 : fd = The file descriptor to operate on
137 *********************************************************************/
138 static void set_no_delay_flag(int fd)
143 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &mi, sizeof(int)))
145 log_error(LOG_LEVEL_ERROR,
146 "Failed to disable TCP coalescence for socket %d", fd);
149 #warning set_no_delay_flag() is a nop due to lack of TCP_NODELAY
150 #endif /* def TCP_NODELAY */
153 /*********************************************************************
155 * Function : connect_to
157 * Description : Open a socket and connect to it. Will check
158 * that this is allowed according to ACL.
161 * 1 : host = hostname to connect to
162 * 2 : portnum = port to connect to (XXX: should be unsigned)
163 * 3 : csp = Current client state (buffers, headers, etc...)
165 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
168 *********************************************************************/
169 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
172 int forwarded_connect_retries = 0;
177 * XXX: The whole errno overloading is ridiculous and should
178 * be replaced with something sane and thread safe
182 fd = rfc2553_connect_to(host, portnum, csp);
184 fd = no_rfc2553_connect_to(host, portnum, csp);
186 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
187 || (csp->fwd == NULL)
188 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
192 forwarded_connect_retries++;
193 if (csp->config->forwarded_connect_retries != 0)
195 log_error(LOG_LEVEL_ERROR,
196 "Attempt %d of %d to connect to %s failed. Trying again.",
197 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
200 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
206 /* Getaddrinfo implementation */
207 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
209 struct addrinfo hints, *result, *rp;
214 struct timeval timeout;
215 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
220 * XXX: Initializeing it here is only necessary
221 * because not all situations are properly
224 int socket_error = 0;
227 struct access_control_addr dst[1];
228 #endif /* def FEATURE_ACL */
230 /* Don't leak memory when retrying. */
231 freez(csp->error_message);
232 freez(csp->http->host_ip_addr_str);
234 retval = snprintf(service, sizeof(service), "%d", portnum);
235 if ((-1 == retval) || (sizeof(service) <= retval))
237 log_error(LOG_LEVEL_ERROR,
238 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
240 csp->error_message = strdup("Invalid port number");
241 csp->http->host_ip_addr_str = strdup("unknown");
242 return(JB_INVALID_SOCKET);
245 memset((char *)&hints, 0, sizeof(hints));
246 hints.ai_family = AF_UNSPEC;
247 hints.ai_socktype = SOCK_STREAM;
248 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
250 hints.ai_flags |= AI_ADDRCONFIG;
252 if ((retval = getaddrinfo(host, service, &hints, &result)))
254 log_error(LOG_LEVEL_INFO,
255 "Can not resolve %s: %s", host, gai_strerror(retval));
256 /* XXX: Should find a better way to propagate this error. */
258 csp->error_message = strdup(gai_strerror(retval));
259 csp->http->host_ip_addr_str = strdup("unknown");
260 return(JB_INVALID_SOCKET);
263 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
265 for (rp = result; rp != NULL; rp = rp->ai_next)
269 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
271 if (block_acl(dst, csp))
274 socket_error = errno = SOCEPERM;
276 socket_error = errno = EPERM;
280 #endif /* def FEATURE_ACL */
282 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
283 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
286 log_error(LOG_LEVEL_ERROR,
287 "Failed to get the host name from the socket structure: %s",
288 gai_strerror(retval));
292 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
294 if (fd == JB_INVALID_SOCKET)
303 if (fd >= FD_SETSIZE)
305 log_error(LOG_LEVEL_ERROR,
306 "Server socket number too high to use select(): %d >= %d",
309 freeaddrinfo(result);
310 return JB_INVALID_SOCKET;
314 #ifdef FEATURE_EXTERNAL_FILTERS
315 mark_socket_for_close_on_execute(fd);
318 set_no_delay_flag(fd);
320 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
321 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
324 fcntl(fd, F_SETFL, flags);
326 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
329 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
332 errno = sock_errno();
336 if (errno == WSAEINPROGRESS)
337 #else /* ifndef _WIN32 */
338 if (errno == EINPROGRESS)
339 #endif /* ndef _WIN32 || __OS2__ */
346 socket_error = errno;
357 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
361 fcntl(fd, F_SETFL, flags);
363 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
365 /* wait for connection to complete */
369 memset(&timeout, 0, sizeof(timeout));
372 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
373 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
374 && FD_ISSET(fd, &wfds))
376 socklen_t optlen = sizeof(socket_error);
377 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
381 /* Connection established, no need to try other addresses. */
384 if (rp->ai_next != NULL)
387 * There's another address we can try, so log that this
388 * one didn't work out. If the last one fails, too,
389 * it will get logged outside the loop body so we don't
390 * have to mention it here.
392 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
393 csp->http->host_ip_addr_str, service, strerror(socket_error));
398 socket_error = errno;
399 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
400 "the connection to [%s]:%s: %s; dropping connection.",
401 csp->http->host_ip_addr_str, service, strerror(errno));
405 /* Connection failed, try next address */
409 freeaddrinfo(result);
412 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
413 host, service, strerror(socket_error));
414 csp->error_message = strdup(strerror(socket_error));
415 return(JB_INVALID_SOCKET);
417 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
418 host, csp->http->host_ip_addr_str, service);
424 #else /* ndef HAVE_RFC2553 */
425 /* Pre-getaddrinfo implementation */
427 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
429 struct sockaddr_in inaddr;
433 struct timeval tv[1];
434 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
439 struct access_control_addr dst[1];
440 #endif /* def FEATURE_ACL */
442 /* Don't leak memory when retrying. */
443 freez(csp->http->host_ip_addr_str);
445 memset((char *)&inaddr, 0, sizeof inaddr);
447 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
449 csp->http->host_ip_addr_str = strdup("unknown");
450 return(JB_INVALID_SOCKET);
454 dst->addr = ntohl(addr);
457 if (block_acl(dst, csp))
464 return(JB_INVALID_SOCKET);
466 #endif /* def FEATURE_ACL */
468 inaddr.sin_addr.s_addr = addr;
469 inaddr.sin_family = AF_INET;
470 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
473 if (sizeof(inaddr.sin_port) == sizeof(short))
474 #endif /* ndef _WIN32 */
476 inaddr.sin_port = htons((unsigned short) portnum);
481 inaddr.sin_port = htonl((unsigned long)portnum);
483 #endif /* ndef _WIN32 */
485 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
487 if (fd == JB_INVALID_SOCKET)
492 return(JB_INVALID_SOCKET);
496 if (fd >= FD_SETSIZE)
498 log_error(LOG_LEVEL_ERROR,
499 "Server socket number too high to use select(): %d >= %d",
502 return JB_INVALID_SOCKET;
506 set_no_delay_flag(fd);
508 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
509 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
512 fcntl(fd, F_SETFL, flags);
513 #ifdef FEATURE_EXTERNAL_FILTERS
514 mark_socket_for_close_on_execute(fd);
517 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
519 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
522 if (errno == WSAEINPROGRESS)
524 if (sock_errno() == EINPROGRESS)
525 #else /* ifndef _WIN32 */
526 if (errno == EINPROGRESS)
527 #endif /* ndef _WIN32 || __OS2__ */
533 if (sock_errno() != EINTR)
539 return(JB_INVALID_SOCKET);
543 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
547 fcntl(fd, F_SETFL, flags);
549 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
551 /* wait for connection to complete */
558 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
559 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
562 return(JB_INVALID_SOCKET);
567 #endif /* ndef HAVE_RFC2553 */
570 /*********************************************************************
572 * Function : write_socket
574 * Description : Write the contents of buf (for n bytes) to socket fd.
577 * 1 : fd = file descriptor (aka. handle) of socket to write to.
578 * 2 : buf = pointer to data to be written.
579 * 3 : len = length of data to be written to the socket "fd".
581 * Returns : 0 on success (entire buffer sent).
584 *********************************************************************/
586 int write_socket(jb_socket fd, const char *buf, ssize_t len)
588 int write_socket(jb_socket fd, const char *buf, size_t len)
596 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
599 return (send(fd, buf, (int)len, 0) != (int)len);
600 #elif defined(__BEOS__) || defined(AMIGA)
601 return (send(fd, buf, len, 0) != len);
602 #elif defined(__OS2__)
604 * Break the data up into SOCKET_SEND_MAX chunks for sending...
605 * OS/2 seemed to complain when the chunks were too large.
607 #define SOCKET_SEND_MAX 65000
609 int send_len, send_rc = 0, i = 0;
610 while ((i < len) && (send_rc != -1))
612 if ((i + SOCKET_SEND_MAX) > len)
615 send_len = SOCKET_SEND_MAX;
616 send_rc = send(fd,(char*)buf + i, send_len, 0);
624 return (write(fd, buf, len) != len);
630 /*********************************************************************
632 * Function : read_socket
634 * Description : Read from a TCP/IP socket in a platform independent way.
637 * 1 : fd = file descriptor of the socket to read
638 * 2 : buf = pointer to buffer where data will be written
639 * Must be >= len bytes long.
640 * 3 : len = maximum number of bytes to read
642 * Returns : On success, the number of bytes read is returned (zero
643 * indicates end of file), and the file position is advanced
644 * by this number. It is not an error if this number is
645 * smaller than the number of bytes requested; this may hap-
646 * pen for example because fewer bytes are actually available
647 * right now (maybe because we were close to end-of-file, or
648 * because we are reading from a pipe, or from a terminal,
649 * or because read() was interrupted by a signal). On error,
650 * -1 is returned, and errno is set appropriately. In this
651 * case it is left unspecified whether the file position (if
654 *********************************************************************/
655 int read_socket(jb_socket fd, char *buf, int len)
665 ret = recv(fd, buf, len, 0);
666 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
667 ret = recv(fd, buf, (size_t)len, 0);
669 ret = (int)read(fd, buf, (size_t)len);
674 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
681 /*********************************************************************
683 * Function : data_is_available
685 * Description : Waits for data to arrive on a socket.
688 * 1 : fd = file descriptor of the socket to read
689 * 2 : seconds_to_wait = number of seconds after which we give up.
691 * Returns : TRUE if data arrived in time,
694 *********************************************************************/
695 int data_is_available(jb_socket fd, int seconds_to_wait)
699 struct timeval timeout;
702 memset(&timeout, 0, sizeof(timeout));
703 timeout.tv_sec = seconds_to_wait;
706 /* Copy and pasted from jcc.c ... */
707 memset(&rfds, 0, sizeof(fd_set));
713 n = select(fd+1, &rfds, NULL, NULL, &timeout);
716 * XXX: Do we care about the different error conditions?
718 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
722 /*********************************************************************
724 * Function : close_socket
726 * Description : Closes a TCP/IP socket
729 * 1 : fd = file descriptor of socket to be closed
733 *********************************************************************/
734 void close_socket(jb_socket fd)
736 #if defined(_WIN32) || defined(__BEOS__)
740 #elif defined(__OS2__)
748 /*********************************************************************
750 * Function : drain_and_close_socket
752 * Description : Closes a TCP/IP socket after draining unread data
755 * 1 : fd = file descriptor of the socket to be closed
759 *********************************************************************/
760 void drain_and_close_socket(jb_socket fd)
762 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
763 if (socket_is_still_alive(fd))
766 int bytes_drained_total = 0;
770 /* Apparently Windows has shutdown() but not SHUT_WR. */
774 if (0 != shutdown(fd, SHUT_WR))
776 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
779 #define ARBITRARY_DRAIN_LIMIT 10000
784 if (!data_is_available(fd, 0))
787 * If there is no data available right now, don't try
788 * to drain the socket as read_socket() could block.
793 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
794 if (bytes_drained < 0)
796 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
798 else if (bytes_drained > 0)
800 bytes_drained_total += bytes_drained;
801 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
803 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
807 } while (bytes_drained > 0);
808 if (bytes_drained_total != 0)
810 log_error(LOG_LEVEL_CONNECT,
811 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
820 /*********************************************************************
822 * Function : bind_port
824 * Description : Call socket, set socket options, and listen.
825 * Called by listen_loop to "boot up" our proxy address.
828 * 1 : hostnam = TCP/IP address to bind/listen to
829 * 2 : portnum = port to listen on
830 * 3 : pfd = pointer used to return file descriptor.
832 * Returns : if success, returns 0 and sets *pfd.
833 * if failure, returns -3 if address is in use,
834 * -2 if address unresolvable,
836 *********************************************************************/
837 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
840 struct addrinfo hints;
841 struct addrinfo *result, *rp;
843 * XXX: portnum should be a string to allow symbolic service
844 * names in the configuration file and to avoid the following
850 struct sockaddr_in inaddr;
851 #endif /* def HAVE_RFC2553 */
855 #endif /* ndef _WIN32 */
857 *pfd = JB_INVALID_SOCKET;
860 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
861 if ((-1 == retval) || (sizeof(servnam) <= retval))
863 log_error(LOG_LEVEL_ERROR,
864 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
869 memset(&hints, 0, sizeof(struct addrinfo));
873 * XXX: This is a hack. The right thing to do
874 * would be to bind to both AF_INET and AF_INET6.
875 * This will also fail if there is no AF_INET
878 hints.ai_family = AF_INET;
882 hints.ai_family = AF_UNSPEC;
884 hints.ai_socktype = SOCK_STREAM;
885 hints.ai_flags = AI_PASSIVE;
886 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
887 hints.ai_canonname = NULL;
888 hints.ai_addr = NULL;
889 hints.ai_next = NULL;
891 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
893 log_error(LOG_LEVEL_ERROR,
894 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
898 memset((char *)&inaddr, '\0', sizeof inaddr);
900 inaddr.sin_family = AF_INET;
901 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
903 if (inaddr.sin_addr.s_addr == INADDR_NONE)
909 if (sizeof(inaddr.sin_port) == sizeof(short))
910 #endif /* ndef _WIN32 */
912 inaddr.sin_port = htons((unsigned short) portnum);
917 inaddr.sin_port = htonl((unsigned long) portnum);
919 #endif /* ndef _WIN32 */
920 #endif /* def HAVE_RFC2553 */
923 for (rp = result; rp != NULL; rp = rp->ai_next)
925 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
927 fd = socket(AF_INET, SOCK_STREAM, 0);
928 #endif /* def HAVE_RFC2553 */
931 if (fd == JB_INVALID_SOCKET)
943 #ifdef FEATURE_EXTERNAL_FILTERS
944 mark_socket_for_close_on_execute(fd);
949 * This is not needed for Win32 - in fact, it stops
950 * duplicate instances of Privoxy from being caught.
952 * On UNIX, we assume the user is sensible enough not
953 * to start Privoxy multiple times on the same IP.
954 * Without this, stopping and restarting Privoxy
955 * from a script fails.
956 * Note: SO_REUSEADDR is meant to only take over
957 * sockets which are *not* in listen state in Linux,
958 * e.g. sockets in TIME_WAIT. YMMV.
960 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
961 #endif /* ndef _WIN32 */
964 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
966 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
970 errno = WSAGetLastError();
971 if (errno == WSAEADDRINUSE)
973 if (errno == EADDRINUSE)
977 freeaddrinfo(result);
994 /* bind() succeeded, escape from for-loop */
996 * XXX: Support multiple listening sockets (e.g. localhost
997 * resolves to AF_INET and AF_INET6, but only the first address
1004 freeaddrinfo(result);
1007 /* All bind()s failed */
1010 #endif /* ndef HAVE_RFC2553 */
1012 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1027 /*********************************************************************
1029 * Function : get_host_information
1031 * Description : Determines the IP address the client used to
1032 * reach us and the hostname associated with it.
1034 * XXX: Most of the code has been copy and pasted
1035 * from accept_connection() and not all of the
1036 * ifdefs paths have been tested afterwards.
1039 * 1 : afd = File descriptor returned from accept().
1040 * 2 : ip_address = Pointer to return the pointer to
1041 * the ip address string.
1042 * 3 : port = Pointer to return the pointer to
1043 * the TCP port string.
1044 * 4 : hostname = Pointer to return the pointer to
1045 * the hostname or NULL if the caller
1046 * isn't interested in it.
1050 *********************************************************************/
1051 void get_host_information(jb_socket afd, char **ip_address, char **port,
1055 struct sockaddr_storage server;
1058 struct sockaddr_in server;
1059 struct hostent *host = NULL;
1060 #endif /* HAVE_RFC2553 */
1061 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1062 /* according to accept_connection() this fixes a warning. */
1063 int s_length, s_length_provided;
1065 socklen_t s_length, s_length_provided;
1067 #ifndef HAVE_RFC2553
1068 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1069 struct hostent result;
1070 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1071 struct hostent_data hdata;
1073 char hbuf[HOSTENT_BUFFER_SIZE];
1075 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1076 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1077 #endif /* ifndef HAVE_RFC2553 */
1078 s_length = s_length_provided = sizeof(server);
1080 if (NULL != hostname)
1087 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1089 if (s_length > s_length_provided)
1091 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1095 * XXX: Workaround for missing header on Windows when
1096 * configured with --disable-ipv6-support.
1097 * The proper fix is to not use NI_MAXSERV in
1098 * that case. It works by accident on other platforms
1099 * as <netdb.h> is included unconditionally there.
1102 #define NI_MAXSERV 32
1104 *port = malloc_or_die(NI_MAXSERV);
1107 *ip_address = malloc_or_die(NI_MAXHOST);
1108 retval = getnameinfo((struct sockaddr *) &server, s_length,
1109 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1110 NI_NUMERICHOST|NI_NUMERICSERV);
1113 log_error(LOG_LEVEL_ERROR,
1114 "Unable to print my own IP address: %s", gai_strerror(retval));
1120 *ip_address = strdup(inet_ntoa(server.sin_addr));
1121 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1122 #endif /* HAVE_RFC2553 */
1123 if (NULL == hostname)
1126 * We're done here, the caller isn't
1127 * interested in knowing the hostname.
1133 *hostname = malloc_or_die(NI_MAXHOST);
1134 retval = getnameinfo((struct sockaddr *) &server, s_length,
1135 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1138 log_error(LOG_LEVEL_ERROR,
1139 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1143 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1144 gethostbyaddr_r((const char *)&server.sin_addr,
1145 sizeof(server.sin_addr), AF_INET,
1146 &result, hbuf, HOSTENT_BUFFER_SIZE,
1148 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1149 host = gethostbyaddr_r((const char *)&server.sin_addr,
1150 sizeof(server.sin_addr), AF_INET,
1151 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1152 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1153 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1154 sizeof(server.sin_addr), AF_INET,
1163 #elif defined(MUTEX_LOCKS_AVAILABLE)
1164 privoxy_mutex_lock(&resolver_mutex);
1165 host = gethostbyaddr((const char *)&server.sin_addr,
1166 sizeof(server.sin_addr), AF_INET);
1167 privoxy_mutex_unlock(&resolver_mutex);
1169 host = gethostbyaddr((const char *)&server.sin_addr,
1170 sizeof(server.sin_addr), AF_INET);
1174 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1178 *hostname = strdup(host->h_name);
1180 #endif /* else def HAVE_RFC2553 */
1187 /*********************************************************************
1189 * Function : accept_connection
1191 * Description : Accepts a connection on one of possibly multiple
1192 * sockets. The socket(s) to check must have been
1193 * created using bind_port().
1196 * 1 : csp = Client state, cfd, ip_addr_str, and
1197 * ip_addr_long will be set by this routine.
1198 * 2 : fds = File descriptors returned from bind_port
1200 * Returns : when a connection is accepted, it returns 1 (TRUE).
1201 * On an error it returns 0 (FALSE).
1203 *********************************************************************/
1204 int accept_connection(struct client_state * csp, jb_socket fds[])
1207 /* XXX: client is stored directly into csp->tcp_addr */
1208 #define client (csp->tcp_addr)
1210 struct sockaddr_in client;
1213 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1214 /* Wierdness - fix a warning. */
1221 int max_selected_socket;
1222 fd_set selected_fds;
1224 const char *host_addr;
1225 size_t listen_addr_size;
1227 c_length = sizeof(client);
1230 * Wait for a connection on any socket.
1231 * Return immediately if no socket is listening.
1232 * XXX: Why not treat this as fatal error?
1234 FD_ZERO(&selected_fds);
1235 max_selected_socket = 0;
1236 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1238 if (JB_INVALID_SOCKET != fds[i])
1240 FD_SET(fds[i], &selected_fds);
1241 if (max_selected_socket < fds[i] + 1)
1243 max_selected_socket = fds[i] + 1;
1247 if (0 == max_selected_socket)
1253 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1254 } while (retval < 0 && errno == EINTR);
1259 log_error(LOG_LEVEL_ERROR,
1260 "Waiting on new client failed because select(2) returned 0."
1261 " This should not happen.");
1265 log_error(LOG_LEVEL_ERROR,
1266 "Waiting on new client failed because of problems in select(2): "
1267 "%s.", strerror(errno));
1271 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1273 if (i >= MAX_LISTENING_SOCKETS)
1275 log_error(LOG_LEVEL_ERROR,
1276 "select(2) reported connected clients (number = %u, "
1277 "descriptor boundary = %u), but none found.",
1278 retval, max_selected_socket);
1283 /* Accept selected connection */
1285 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1286 if (afd == JB_INVALID_SOCKET)
1293 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1294 struct accept_filter_arg af_options;
1295 bzero(&af_options, sizeof(af_options));
1296 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1297 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1299 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1300 } while (afd < 0 && errno == EINTR);
1309 struct linger linger_options;
1310 linger_options.l_onoff = 1;
1311 linger_options.l_linger = 5;
1312 if (0 != setsockopt(afd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1314 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1320 if (afd >= FD_SETSIZE)
1322 log_error(LOG_LEVEL_ERROR,
1323 "Client socket number too high to use select(): %d >= %d",
1330 #ifdef FEATURE_EXTERNAL_FILTERS
1331 mark_socket_for_close_on_execute(afd);
1334 set_no_delay_flag(afd);
1338 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1339 retval = getnameinfo((struct sockaddr *) &client, c_length,
1340 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1341 if (!csp->ip_addr_str || retval)
1343 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1344 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1345 freez(csp->ip_addr_str);
1349 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1350 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1351 #endif /* def HAVE_RFC2553 */
1354 * Save the name and port of the accepting socket for later lookup.
1356 * The string needs space for strlen(...) + 7 characters:
1357 * strlen(haddr[i]) + 1 (':') + 5 (port digits) + 1 ('\0')
1359 host_addr = (csp->config->haddr[i] != NULL) ? csp->config->haddr[i] : "";
1360 listen_addr_size = strlen(host_addr) + 7;
1361 csp->listen_addr_str = malloc_or_die(listen_addr_size);
1362 retval = snprintf(csp->listen_addr_str, listen_addr_size,
1363 "%s:%d", host_addr, csp->config->hport[i]);
1364 if ((-1 == retval) || listen_addr_size <= retval)
1366 log_error(LOG_LEVEL_ERROR,
1367 "Server name (%s) and port number (%d) ASCII decimal representation"
1368 "don't fit into %d bytes",
1369 host_addr, csp->config->hport[i], listen_addr_size);
1378 /*********************************************************************
1380 * Function : resolve_hostname_to_ip
1382 * Description : Resolve a hostname to an internet tcp/ip address.
1383 * NULL or an empty string resolve to INADDR_ANY.
1386 * 1 : host = hostname to resolve
1388 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1390 *********************************************************************/
1391 unsigned long resolve_hostname_to_ip(const char *host)
1393 struct sockaddr_in inaddr;
1394 struct hostent *hostp;
1395 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1396 struct hostent result;
1397 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1398 char hbuf[HOSTENT_BUFFER_SIZE];
1400 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1401 struct hostent_data hdata;
1402 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1403 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1405 if ((host == NULL) || (*host == '\0'))
1410 memset((char *) &inaddr, 0, sizeof inaddr);
1412 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1414 unsigned int dns_retries = 0;
1415 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1416 while (gethostbyname_r(host, &result, hbuf,
1417 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1418 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1420 log_error(LOG_LEVEL_ERROR,
1421 "Timeout #%u while trying to resolve %s. Trying again.",
1424 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1425 while (NULL == (hostp = gethostbyname_r(host, &result,
1426 hbuf, HOSTENT_BUFFER_SIZE, &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_3_ARGS)
1435 * XXX: Doesn't retry in case of soft errors.
1436 * Does this gethostbyname_r version set h_errno?
1438 if (0 == gethostbyname_r(host, &result, &hdata))
1446 #elif defined(MUTEX_LOCKS_AVAILABLE)
1447 privoxy_mutex_lock(&resolver_mutex);
1448 while (NULL == (hostp = gethostbyname(host))
1449 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1451 log_error(LOG_LEVEL_ERROR,
1452 "Timeout #%u while trying to resolve %s. Trying again.",
1455 privoxy_mutex_unlock(&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 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1466 * On Mac OSX, if a domain exists but doesn't have a type A
1467 * record associated with it, the h_addr member of the struct
1468 * hostent returned by gethostbyname is NULL, even if h_length
1469 * is 4. Therefore the second test below.
1471 if (hostp == NULL || hostp->h_addr == NULL)
1474 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1475 return(INADDR_NONE);
1477 if (hostp->h_addrtype != AF_INET)
1480 errno = WSAEPROTOTYPE;
1484 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1485 return(INADDR_NONE);
1487 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1489 return(inaddr.sin_addr.s_addr);
1494 /*********************************************************************
1496 * Function : socket_is_still_alive
1498 * Description : Figures out whether or not a socket is still alive.
1501 * 1 : sfd = The socket to check.
1503 * Returns : TRUE for yes, otherwise FALSE.
1505 *********************************************************************/
1506 int socket_is_still_alive(jb_socket sfd)
1509 int no_data_waiting;
1513 struct pollfd poll_fd[1];
1515 memset(poll_fd, 0, sizeof(poll_fd));
1516 poll_fd[0].fd = sfd;
1517 poll_fd[0].events = POLLIN;
1519 poll_result = poll(poll_fd, 1, 0);
1521 if (-1 == poll_result)
1523 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1526 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1528 fd_set readable_fds;
1529 struct timeval timeout;
1532 memset(&timeout, '\0', sizeof(timeout));
1533 FD_ZERO(&readable_fds);
1534 FD_SET(sfd, &readable_fds);
1536 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1539 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1542 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1543 #endif /* def HAVE_POLL */
1545 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1549 #ifdef FEATURE_EXTERNAL_FILTERS
1550 /*********************************************************************
1552 * Function : mark_socket_for_close_on_execute
1554 * Description : Marks a socket for close on execute.
1556 * Used so that external filters have no direct
1557 * access to sockets they shouldn't care about.
1559 * Not implemented for all platforms.
1562 * 1 : fd = The socket to mark
1566 *********************************************************************/
1567 void mark_socket_for_close_on_execute(jb_socket fd)
1569 #ifdef FEATURE_PTHREAD
1572 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1576 log_error(LOG_LEVEL_ERROR,
1577 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1580 #warning "Sockets will be visible to external filters"
1583 #endif /* def FEATURE_EXTERNAL_FILTERS */