1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.130 2014/10/18 11:28:05 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-2014 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 : connect_to
130 * Description : Open a socket and connect to it. Will check
131 * that this is allowed according to ACL.
134 * 1 : host = hostname to connect to
135 * 2 : portnum = port to connect to (XXX: should be unsigned)
136 * 3 : csp = Current client state (buffers, headers, etc...)
138 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
141 *********************************************************************/
142 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
145 int forwarded_connect_retries = 0;
150 * XXX: The whole errno overloading is ridiculous and should
151 * be replaced with something sane and thread safe
155 fd = rfc2553_connect_to(host, portnum, csp);
157 fd = no_rfc2553_connect_to(host, portnum, csp);
159 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
160 || (csp->fwd == NULL)
161 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
165 forwarded_connect_retries++;
166 if (csp->config->forwarded_connect_retries != 0)
168 log_error(LOG_LEVEL_ERROR,
169 "Attempt %d of %d to connect to %s failed. Trying again.",
170 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
173 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
179 /* Getaddrinfo implementation */
180 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
182 struct addrinfo hints, *result, *rp;
187 struct timeval timeout;
188 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
193 * XXX: Initializeing it here is only necessary
194 * because not all situations are properly
197 int socket_error = 0;
200 struct access_control_addr dst[1];
201 #endif /* def FEATURE_ACL */
203 /* Don't leak memory when retrying. */
204 freez(csp->error_message);
205 freez(csp->http->host_ip_addr_str);
207 retval = snprintf(service, sizeof(service), "%d", portnum);
208 if ((-1 == retval) || (sizeof(service) <= retval))
210 log_error(LOG_LEVEL_ERROR,
211 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
213 csp->error_message = strdup("Invalid port number");
214 csp->http->host_ip_addr_str = strdup("unknown");
215 return(JB_INVALID_SOCKET);
218 memset((char *)&hints, 0, sizeof(hints));
219 hints.ai_family = AF_UNSPEC;
220 hints.ai_socktype = SOCK_STREAM;
221 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
223 hints.ai_flags |= AI_ADDRCONFIG;
225 if ((retval = getaddrinfo(host, service, &hints, &result)))
227 log_error(LOG_LEVEL_INFO,
228 "Can not resolve %s: %s", host, gai_strerror(retval));
229 /* XXX: Should find a better way to propagate this error. */
231 csp->error_message = strdup(gai_strerror(retval));
232 csp->http->host_ip_addr_str = strdup("unknown");
233 return(JB_INVALID_SOCKET);
236 csp->http->host_ip_addr_str = malloc_or_die(NI_MAXHOST);
238 for (rp = result; rp != NULL; rp = rp->ai_next)
242 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
244 if (block_acl(dst, csp))
247 socket_error = errno = SOCEPERM;
249 socket_error = errno = EPERM;
253 #endif /* def FEATURE_ACL */
255 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
256 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
259 log_error(LOG_LEVEL_ERROR,
260 "Failed to get the host name from the socket structure: %s",
261 gai_strerror(retval));
265 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
267 if (fd == JB_INVALID_SOCKET)
276 if (fd >= FD_SETSIZE)
278 log_error(LOG_LEVEL_ERROR,
279 "Server socket number too high to use select(): %d >= %d",
282 freeaddrinfo(result);
283 return JB_INVALID_SOCKET;
287 #ifdef FEATURE_EXTERNAL_FILTERS
288 mark_socket_for_close_on_execute(fd);
292 { /* turn off TCP coalescence */
294 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
296 #endif /* def TCP_NODELAY */
298 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
299 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
302 fcntl(fd, F_SETFL, flags);
304 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
307 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
310 errno = sock_errno();
314 if (errno == WSAEINPROGRESS)
315 #else /* ifndef _WIN32 */
316 if (errno == EINPROGRESS)
317 #endif /* ndef _WIN32 || __OS2__ */
324 socket_error = errno;
335 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
339 fcntl(fd, F_SETFL, flags);
341 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
343 /* wait for connection to complete */
347 memset(&timeout, 0, sizeof(timeout));
350 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
351 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
352 && FD_ISSET(fd, &wfds))
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;
411 struct timeval tv[1];
412 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
417 struct access_control_addr dst[1];
418 #endif /* def FEATURE_ACL */
420 /* Don't leak memory when retrying. */
421 freez(csp->http->host_ip_addr_str);
423 memset((char *)&inaddr, 0, sizeof inaddr);
425 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
427 csp->http->host_ip_addr_str = strdup("unknown");
428 return(JB_INVALID_SOCKET);
432 dst->addr = ntohl(addr);
435 if (block_acl(dst, csp))
442 return(JB_INVALID_SOCKET);
444 #endif /* def FEATURE_ACL */
446 inaddr.sin_addr.s_addr = addr;
447 inaddr.sin_family = AF_INET;
448 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
451 if (sizeof(inaddr.sin_port) == sizeof(short))
452 #endif /* ndef _WIN32 */
454 inaddr.sin_port = htons((unsigned short) portnum);
459 inaddr.sin_port = htonl((unsigned long)portnum);
461 #endif /* ndef _WIN32 */
463 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
465 if (fd == JB_INVALID_SOCKET)
470 return(JB_INVALID_SOCKET);
474 if (fd >= FD_SETSIZE)
476 log_error(LOG_LEVEL_ERROR,
477 "Server socket number too high to use select(): %d >= %d",
480 return JB_INVALID_SOCKET;
485 { /* turn off TCP coalescence */
487 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
489 #endif /* def TCP_NODELAY */
491 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
492 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
495 fcntl(fd, F_SETFL, flags);
496 #ifdef FEATURE_EXTERNAL_FILTERS
497 mark_socket_for_close_on_execute(fd);
500 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
502 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
505 if (errno == WSAEINPROGRESS)
507 if (sock_errno() == EINPROGRESS)
508 #else /* ifndef _WIN32 */
509 if (errno == EINPROGRESS)
510 #endif /* ndef _WIN32 || __OS2__ */
516 if (sock_errno() != EINTR)
522 return(JB_INVALID_SOCKET);
526 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
530 fcntl(fd, F_SETFL, flags);
532 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
534 /* wait for connection to complete */
541 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
542 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
545 return(JB_INVALID_SOCKET);
550 #endif /* ndef HAVE_RFC2553 */
553 /*********************************************************************
555 * Function : write_socket
557 * Description : Write the contents of buf (for n bytes) to socket fd.
560 * 1 : fd = file descriptor (aka. handle) of socket to write to.
561 * 2 : buf = pointer to data to be written.
562 * 3 : len = length of data to be written to the socket "fd".
564 * Returns : 0 on success (entire buffer sent).
567 *********************************************************************/
569 int write_socket(jb_socket fd, const char *buf, ssize_t len)
571 int write_socket(jb_socket fd, const char *buf, size_t len)
579 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
582 return (send(fd, buf, (int)len, 0) != (int)len);
583 #elif defined(__BEOS__) || defined(AMIGA)
584 return (send(fd, buf, len, 0) != len);
585 #elif defined(__OS2__)
587 * Break the data up into SOCKET_SEND_MAX chunks for sending...
588 * OS/2 seemed to complain when the chunks were too large.
590 #define SOCKET_SEND_MAX 65000
592 int send_len, send_rc = 0, i = 0;
593 while ((i < len) && (send_rc != -1))
595 if ((i + SOCKET_SEND_MAX) > len)
598 send_len = SOCKET_SEND_MAX;
599 send_rc = send(fd,(char*)buf + i, send_len, 0);
607 return (write(fd, buf, len) != len);
613 /*********************************************************************
615 * Function : read_socket
617 * Description : Read from a TCP/IP socket in a platform independent way.
620 * 1 : fd = file descriptor of the socket to read
621 * 2 : buf = pointer to buffer where data will be written
622 * Must be >= len bytes long.
623 * 3 : len = maximum number of bytes to read
625 * Returns : On success, the number of bytes read is returned (zero
626 * indicates end of file), and the file position is advanced
627 * by this number. It is not an error if this number is
628 * smaller than the number of bytes requested; this may hap-
629 * pen for example because fewer bytes are actually available
630 * right now (maybe because we were close to end-of-file, or
631 * because we are reading from a pipe, or from a terminal,
632 * or because read() was interrupted by a signal). On error,
633 * -1 is returned, and errno is set appropriately. In this
634 * case it is left unspecified whether the file position (if
637 *********************************************************************/
638 int read_socket(jb_socket fd, char *buf, int len)
648 ret = recv(fd, buf, len, 0);
649 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
650 ret = recv(fd, buf, (size_t)len, 0);
652 ret = (int)read(fd, buf, (size_t)len);
657 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
664 /*********************************************************************
666 * Function : data_is_available
668 * Description : Waits for data to arrive on a socket.
671 * 1 : fd = file descriptor of the socket to read
672 * 2 : seconds_to_wait = number of seconds after which we give up.
674 * Returns : TRUE if data arrived in time,
677 *********************************************************************/
678 int data_is_available(jb_socket fd, int seconds_to_wait)
682 struct timeval timeout;
685 memset(&timeout, 0, sizeof(timeout));
686 timeout.tv_sec = seconds_to_wait;
689 /* Copy and pasted from jcc.c ... */
690 memset(&rfds, 0, sizeof(fd_set));
696 n = select(fd+1, &rfds, NULL, NULL, &timeout);
699 * XXX: Do we care about the different error conditions?
701 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
705 /*********************************************************************
707 * Function : close_socket
709 * Description : Closes a TCP/IP socket
712 * 1 : fd = file descriptor of socket to be closed
716 *********************************************************************/
717 void close_socket(jb_socket fd)
719 #if defined(_WIN32) || defined(__BEOS__)
723 #elif defined(__OS2__)
731 /*********************************************************************
733 * Function : drain_and_close_socket
735 * Description : Closes a TCP/IP socket after draining unread data
738 * 1 : fd = file descriptor of the socket to be closed
742 *********************************************************************/
743 void drain_and_close_socket(jb_socket fd)
745 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
746 if (socket_is_still_alive(fd))
749 int bytes_drained_total = 0;
753 /* Apparently Windows has shutdown() but not SHUT_WR. */
757 if (0 != shutdown(fd, SHUT_WR))
759 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
762 #define ARBITRARY_DRAIN_LIMIT 10000
767 if (!data_is_available(fd, 0))
770 * If there is no data available right now, don't try
771 * to drain the socket as read_socket() could block.
776 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
777 if (bytes_drained < 0)
779 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
781 else if (bytes_drained > 0)
783 bytes_drained_total += bytes_drained;
784 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
786 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
790 } while (bytes_drained > 0);
791 if (bytes_drained_total != 0)
793 log_error(LOG_LEVEL_CONNECT,
794 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
803 /*********************************************************************
805 * Function : bind_port
807 * Description : Call socket, set socket options, and listen.
808 * Called by listen_loop to "boot up" our proxy address.
811 * 1 : hostnam = TCP/IP address to bind/listen to
812 * 2 : portnum = port to listen on
813 * 3 : pfd = pointer used to return file descriptor.
815 * Returns : if success, returns 0 and sets *pfd.
816 * if failure, returns -3 if address is in use,
817 * -2 if address unresolvable,
819 *********************************************************************/
820 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
823 struct addrinfo hints;
824 struct addrinfo *result, *rp;
826 * XXX: portnum should be a string to allow symbolic service
827 * names in the configuration file and to avoid the following
833 struct sockaddr_in inaddr;
834 #endif /* def HAVE_RFC2553 */
838 #endif /* ndef _WIN32 */
840 *pfd = JB_INVALID_SOCKET;
843 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
844 if ((-1 == retval) || (sizeof(servnam) <= retval))
846 log_error(LOG_LEVEL_ERROR,
847 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
852 memset(&hints, 0, sizeof(struct addrinfo));
856 * XXX: This is a hack. The right thing to do
857 * would be to bind to both AF_INET and AF_INET6.
858 * This will also fail if there is no AF_INET
861 hints.ai_family = AF_INET;
865 hints.ai_family = AF_UNSPEC;
867 hints.ai_socktype = SOCK_STREAM;
868 hints.ai_flags = AI_PASSIVE;
869 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
870 hints.ai_canonname = NULL;
871 hints.ai_addr = NULL;
872 hints.ai_next = NULL;
874 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
876 log_error(LOG_LEVEL_ERROR,
877 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
881 memset((char *)&inaddr, '\0', sizeof inaddr);
883 inaddr.sin_family = AF_INET;
884 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
886 if (inaddr.sin_addr.s_addr == INADDR_NONE)
892 if (sizeof(inaddr.sin_port) == sizeof(short))
893 #endif /* ndef _WIN32 */
895 inaddr.sin_port = htons((unsigned short) portnum);
900 inaddr.sin_port = htonl((unsigned long) portnum);
902 #endif /* ndef _WIN32 */
903 #endif /* def HAVE_RFC2553 */
906 for (rp = result; rp != NULL; rp = rp->ai_next)
908 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
910 fd = socket(AF_INET, SOCK_STREAM, 0);
911 #endif /* def HAVE_RFC2553 */
914 if (fd == JB_INVALID_SOCKET)
926 #ifdef FEATURE_EXTERNAL_FILTERS
927 mark_socket_for_close_on_execute(fd);
932 * This is not needed for Win32 - in fact, it stops
933 * duplicate instances of Privoxy from being caught.
935 * On UNIX, we assume the user is sensible enough not
936 * to start Privoxy multiple times on the same IP.
937 * Without this, stopping and restarting Privoxy
938 * from a script fails.
939 * Note: SO_REUSEADDR is meant to only take over
940 * sockets which are *not* in listen state in Linux,
941 * e.g. sockets in TIME_WAIT. YMMV.
943 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
944 #endif /* ndef _WIN32 */
947 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
949 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
953 errno = WSAGetLastError();
954 if (errno == WSAEADDRINUSE)
956 if (errno == EADDRINUSE)
960 freeaddrinfo(result);
977 /* bind() succeeded, escape from for-loop */
979 * XXX: Support multiple listening sockets (e.g. localhost
980 * resolves to AF_INET and AF_INET6, but only the first address
987 freeaddrinfo(result);
990 /* All bind()s failed */
993 #endif /* ndef HAVE_RFC2553 */
995 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1010 /*********************************************************************
1012 * Function : get_host_information
1014 * Description : Determines the IP address the client used to
1015 * reach us and the hostname associated with it.
1017 * XXX: Most of the code has been copy and pasted
1018 * from accept_connection() and not all of the
1019 * ifdefs paths have been tested afterwards.
1022 * 1 : afd = File descriptor returned from accept().
1023 * 2 : ip_address = Pointer to return the pointer to
1024 * the ip address string.
1025 * 3 : port = Pointer to return the pointer to
1026 * the TCP port string.
1027 * 4 : hostname = Pointer to return the pointer to
1028 * the hostname or NULL if the caller
1029 * isn't interested in it.
1033 *********************************************************************/
1034 void get_host_information(jb_socket afd, char **ip_address, char **port,
1038 struct sockaddr_storage server;
1041 struct sockaddr_in server;
1042 struct hostent *host = NULL;
1043 #endif /* HAVE_RFC2553 */
1044 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1045 /* according to accept_connection() this fixes a warning. */
1046 int s_length, s_length_provided;
1048 socklen_t s_length, s_length_provided;
1050 #ifndef HAVE_RFC2553
1051 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1052 struct hostent result;
1053 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1054 struct hostent_data hdata;
1056 char hbuf[HOSTENT_BUFFER_SIZE];
1058 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1059 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1060 #endif /* ifndef HAVE_RFC2553 */
1061 s_length = s_length_provided = sizeof(server);
1063 if (NULL != hostname)
1070 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1072 if (s_length > s_length_provided)
1074 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1078 * XXX: Workaround for missing header on Windows when
1079 * configured with --disable-ipv6-support.
1080 * The proper fix is to not use NI_MAXSERV in
1081 * that case. It works by accident on other platforms
1082 * as <netdb.h> is included unconditionally there.
1085 #define NI_MAXSERV 32
1087 *port = malloc_or_die(NI_MAXSERV);
1090 *ip_address = malloc_or_die(NI_MAXHOST);
1091 retval = getnameinfo((struct sockaddr *) &server, s_length,
1092 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1093 NI_NUMERICHOST|NI_NUMERICSERV);
1096 log_error(LOG_LEVEL_ERROR,
1097 "Unable to print my own IP address: %s", gai_strerror(retval));
1103 *ip_address = strdup(inet_ntoa(server.sin_addr));
1104 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1105 #endif /* HAVE_RFC2553 */
1106 if (NULL == hostname)
1109 * We're done here, the caller isn't
1110 * interested in knowing the hostname.
1116 *hostname = malloc_or_die(NI_MAXHOST);
1117 retval = getnameinfo((struct sockaddr *) &server, s_length,
1118 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1121 log_error(LOG_LEVEL_ERROR,
1122 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1126 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1127 gethostbyaddr_r((const char *)&server.sin_addr,
1128 sizeof(server.sin_addr), AF_INET,
1129 &result, hbuf, HOSTENT_BUFFER_SIZE,
1131 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1132 host = gethostbyaddr_r((const char *)&server.sin_addr,
1133 sizeof(server.sin_addr), AF_INET,
1134 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1135 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1136 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1137 sizeof(server.sin_addr), AF_INET,
1146 #elif defined(MUTEX_LOCKS_AVAILABLE)
1147 privoxy_mutex_lock(&resolver_mutex);
1148 host = gethostbyaddr((const char *)&server.sin_addr,
1149 sizeof(server.sin_addr), AF_INET);
1150 privoxy_mutex_unlock(&resolver_mutex);
1152 host = gethostbyaddr((const char *)&server.sin_addr,
1153 sizeof(server.sin_addr), AF_INET);
1157 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1161 *hostname = strdup(host->h_name);
1163 #endif /* else def HAVE_RFC2553 */
1170 /*********************************************************************
1172 * Function : accept_connection
1174 * Description : Accepts a connection on one of possibly multiple
1175 * sockets. The socket(s) to check must have been
1176 * created using bind_port().
1179 * 1 : csp = Client state, cfd, ip_addr_str, and
1180 * ip_addr_long will be set by this routine.
1181 * 2 : fds = File descriptors returned from bind_port
1183 * Returns : when a connection is accepted, it returns 1 (TRUE).
1184 * On an error it returns 0 (FALSE).
1186 *********************************************************************/
1187 int accept_connection(struct client_state * csp, jb_socket fds[])
1190 /* XXX: client is stored directly into csp->tcp_addr */
1191 #define client (csp->tcp_addr)
1193 struct sockaddr_in client;
1196 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1197 /* Wierdness - fix a warning. */
1204 int max_selected_socket;
1205 fd_set selected_fds;
1208 c_length = sizeof(client);
1211 * Wait for a connection on any socket.
1212 * Return immediately if no socket is listening.
1213 * XXX: Why not treat this as fatal error?
1215 FD_ZERO(&selected_fds);
1216 max_selected_socket = 0;
1217 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1219 if (JB_INVALID_SOCKET != fds[i])
1221 FD_SET(fds[i], &selected_fds);
1222 if (max_selected_socket < fds[i] + 1)
1224 max_selected_socket = fds[i] + 1;
1228 if (0 == max_selected_socket)
1234 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1235 } while (retval < 0 && errno == EINTR);
1240 log_error(LOG_LEVEL_ERROR,
1241 "Waiting on new client failed because select(2) returned 0."
1242 " This should not happen.");
1246 log_error(LOG_LEVEL_ERROR,
1247 "Waiting on new client failed because of problems in select(2): "
1248 "%s.", strerror(errno));
1252 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1254 if (i >= MAX_LISTENING_SOCKETS)
1256 log_error(LOG_LEVEL_ERROR,
1257 "select(2) reported connected clients (number = %u, "
1258 "descriptor boundary = %u), but none found.",
1259 retval, max_selected_socket);
1264 /* Accept selected connection */
1266 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1267 if (afd == JB_INVALID_SOCKET)
1274 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1275 struct accept_filter_arg af_options;
1276 bzero(&af_options, sizeof(af_options));
1277 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1278 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1280 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1281 } while (afd < 0 && errno == EINTR);
1290 struct linger linger_options;
1291 linger_options.l_onoff = 1;
1292 linger_options.l_linger = 5;
1293 if (0 != setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1295 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1301 if (afd >= FD_SETSIZE)
1303 log_error(LOG_LEVEL_ERROR,
1304 "Client socket number too high to use select(): %d >= %d",
1311 #ifdef FEATURE_EXTERNAL_FILTERS
1312 mark_socket_for_close_on_execute(afd);
1317 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1318 retval = getnameinfo((struct sockaddr *) &client, c_length,
1319 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1320 if (!csp->ip_addr_str || retval)
1322 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1323 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1324 freez(csp->ip_addr_str);
1328 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1329 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1330 #endif /* def HAVE_RFC2553 */
1337 /*********************************************************************
1339 * Function : resolve_hostname_to_ip
1341 * Description : Resolve a hostname to an internet tcp/ip address.
1342 * NULL or an empty string resolve to INADDR_ANY.
1345 * 1 : host = hostname to resolve
1347 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1349 *********************************************************************/
1350 unsigned long resolve_hostname_to_ip(const char *host)
1352 struct sockaddr_in inaddr;
1353 struct hostent *hostp;
1354 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1355 struct hostent result;
1356 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1357 char hbuf[HOSTENT_BUFFER_SIZE];
1359 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1360 struct hostent_data hdata;
1361 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1362 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1364 if ((host == NULL) || (*host == '\0'))
1369 memset((char *) &inaddr, 0, sizeof inaddr);
1371 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1373 unsigned int dns_retries = 0;
1374 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1375 while (gethostbyname_r(host, &result, hbuf,
1376 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1377 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1379 log_error(LOG_LEVEL_ERROR,
1380 "Timeout #%u while trying to resolve %s. Trying again.",
1383 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1384 while (NULL == (hostp = gethostbyname_r(host, &result,
1385 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1386 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1388 log_error(LOG_LEVEL_ERROR,
1389 "Timeout #%u while trying to resolve %s. Trying again.",
1392 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1394 * XXX: Doesn't retry in case of soft errors.
1395 * Does this gethostbyname_r version set h_errno?
1397 if (0 == gethostbyname_r(host, &result, &hdata))
1405 #elif defined(MUTEX_LOCKS_AVAILABLE)
1406 privoxy_mutex_lock(&resolver_mutex);
1407 while (NULL == (hostp = gethostbyname(host))
1408 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1410 log_error(LOG_LEVEL_ERROR,
1411 "Timeout #%u while trying to resolve %s. Trying again.",
1414 privoxy_mutex_unlock(&resolver_mutex);
1416 while (NULL == (hostp = gethostbyname(host))
1417 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1419 log_error(LOG_LEVEL_ERROR,
1420 "Timeout #%u while trying to resolve %s. Trying again.",
1423 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1425 * On Mac OSX, if a domain exists but doesn't have a type A
1426 * record associated with it, the h_addr member of the struct
1427 * hostent returned by gethostbyname is NULL, even if h_length
1428 * is 4. Therefore the second test below.
1430 if (hostp == NULL || hostp->h_addr == NULL)
1433 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1434 return(INADDR_NONE);
1436 if (hostp->h_addrtype != AF_INET)
1439 errno = WSAEPROTOTYPE;
1443 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1444 return(INADDR_NONE);
1446 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1448 return(inaddr.sin_addr.s_addr);
1453 /*********************************************************************
1455 * Function : socket_is_still_alive
1457 * Description : Figures out whether or not a socket is still alive.
1460 * 1 : sfd = The socket to check.
1462 * Returns : TRUE for yes, otherwise FALSE.
1464 *********************************************************************/
1465 int socket_is_still_alive(jb_socket sfd)
1468 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 fd_set readable_fds;
1488 struct timeval timeout;
1491 memset(&timeout, '\0', sizeof(timeout));
1492 FD_ZERO(&readable_fds);
1493 FD_SET(sfd, &readable_fds);
1495 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1498 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1501 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1502 #endif /* def HAVE_POLL */
1504 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1508 #ifdef FEATURE_EXTERNAL_FILTERS
1509 /*********************************************************************
1511 * Function : mark_socket_for_close_on_execute
1513 * Description : Marks a socket for close on execute.
1515 * Used so that external filters have no direct
1516 * access to sockets they shouldn't care about.
1518 * Not implemented for all platforms.
1521 * 1 : fd = The socket to mark
1525 *********************************************************************/
1526 void mark_socket_for_close_on_execute(jb_socket fd)
1528 #ifdef FEATURE_PTHREAD
1531 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1535 log_error(LOG_LEVEL_ERROR,
1536 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1539 #warning "Sockets will be visible to external filters"
1542 #endif /* def FEATURE_EXTERNAL_FILTERS */