1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.124 2013/03/20 11:30: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-2011 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"
103 /* Mac OSX doesn't define AI_NUMERICSESRV */
104 #ifndef AI_NUMERICSERV
105 #define AI_NUMERICSERV 0
108 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
111 * Maximum number of gethostbyname(_r) retries in case of
112 * soft errors (TRY_AGAIN).
113 * XXX: Does it make sense to make this a config option?
115 #define MAX_DNS_RETRIES 10
117 #define MAX_LISTEN_BACKLOG 128
120 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
122 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp);
125 /*********************************************************************
127 * Function : connect_to
129 * Description : Open a socket and connect to it. Will check
130 * that this is allowed according to ACL.
133 * 1 : host = hostname to connect to
134 * 2 : portnum = port to connect to (XXX: should be unsigned)
135 * 3 : csp = Current client state (buffers, headers, etc...)
137 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
140 *********************************************************************/
141 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
144 int forwarded_connect_retries = 0;
149 * XXX: The whole errno overloading is ridiculous and should
150 * be replaced with something sane and thread safe
154 fd = rfc2553_connect_to(host, portnum, csp);
156 fd = no_rfc2553_connect_to(host, portnum, csp);
158 if ((fd != JB_INVALID_SOCKET) || (errno == EINVAL)
159 || (csp->fwd == NULL)
160 || ((csp->fwd->forward_host == NULL) && (csp->fwd->type == SOCKS_NONE)))
164 forwarded_connect_retries++;
165 if (csp->config->forwarded_connect_retries != 0)
167 log_error(LOG_LEVEL_ERROR,
168 "Attempt %d of %d to connect to %s failed. Trying again.",
169 forwarded_connect_retries, csp->config->forwarded_connect_retries + 1, host);
172 } while (forwarded_connect_retries < csp->config->forwarded_connect_retries);
178 /* Getaddrinfo implementation */
179 static jb_socket rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
181 struct addrinfo hints, *result, *rp;
186 struct timeval timeout;
187 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
192 * XXX: Initializeing it here is only necessary
193 * because not all situations are properly
196 int socket_error = 0;
199 struct access_control_addr dst[1];
200 #endif /* def FEATURE_ACL */
202 /* Don't leak memory when retrying. */
203 freez(csp->error_message);
204 freez(csp->http->host_ip_addr_str);
206 retval = snprintf(service, sizeof(service), "%d", portnum);
207 if ((-1 == retval) || (sizeof(service) <= retval))
209 log_error(LOG_LEVEL_ERROR,
210 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
212 csp->error_message = strdup("Invalid port number");
213 csp->http->host_ip_addr_str = strdup("unknown");
214 return(JB_INVALID_SOCKET);
217 memset((char *)&hints, 0, sizeof(hints));
218 hints.ai_family = AF_UNSPEC;
219 hints.ai_socktype = SOCK_STREAM;
220 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
222 hints.ai_flags |= AI_ADDRCONFIG;
224 if ((retval = getaddrinfo(host, service, &hints, &result)))
226 log_error(LOG_LEVEL_INFO,
227 "Can not resolve %s: %s", host, gai_strerror(retval));
228 /* XXX: Should find a better way to propagate this error. */
230 csp->error_message = strdup(gai_strerror(retval));
231 csp->http->host_ip_addr_str = strdup("unknown");
232 return(JB_INVALID_SOCKET);
235 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
236 if (NULL == csp->http->host_ip_addr_str)
238 freeaddrinfo(result);
239 log_error(LOG_LEVEL_ERROR,
240 "Out of memory while getting the server IP address.");
241 return JB_INVALID_SOCKET;
244 for (rp = result; rp != NULL; rp = rp->ai_next)
248 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
250 if (block_acl(dst, csp))
253 socket_error = errno = SOCEPERM;
255 socket_error = errno = EPERM;
259 #endif /* def FEATURE_ACL */
261 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
262 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
265 log_error(LOG_LEVEL_ERROR,
266 "Failed to get the host name from the socket structure: %s",
267 gai_strerror(retval));
271 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
273 if (fd == JB_INVALID_SOCKET)
282 if (fd >= FD_SETSIZE)
284 log_error(LOG_LEVEL_ERROR,
285 "Server socket number too high to use select(): %d >= %d",
288 return JB_INVALID_SOCKET;
292 #ifdef FEATURE_EXTERNAL_FILTERS
293 mark_socket_for_close_on_execute(fd);
297 { /* turn off TCP coalescence */
299 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
301 #endif /* def TCP_NODELAY */
303 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
304 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
307 fcntl(fd, F_SETFL, flags);
309 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
312 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
315 errno = sock_errno();
319 if (errno == WSAEINPROGRESS)
320 #else /* ifndef _WIN32 */
321 if (errno == EINPROGRESS)
322 #endif /* ndef _WIN32 || __OS2__ */
329 socket_error = errno;
340 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
344 fcntl(fd, F_SETFL, flags);
346 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
348 /* wait for connection to complete */
352 memset(&timeout, 0, sizeof(timeout));
355 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
356 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
357 && FD_ISSET(fd, &wfds))
359 socklen_t optlen = sizeof(socket_error);
360 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
364 /* Connection established, no need to try other addresses. */
367 if (rp->ai_next != NULL)
370 * There's another address we can try, so log that this
371 * one didn't work out. If the last one fails, too,
372 * it will get logged outside the loop body so we don't
373 * have to mention it here.
375 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
376 csp->http->host_ip_addr_str, service, strerror(socket_error));
381 socket_error = errno;
382 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
383 "the connection to [%s]:%s: %s; dropping connection.",
384 csp->http->host_ip_addr_str, service, strerror(errno));
388 /* Connection failed, try next address */
392 freeaddrinfo(result);
395 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
396 host, service, strerror(socket_error));
397 csp->error_message = strdup(strerror(socket_error));
398 return(JB_INVALID_SOCKET);
400 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
401 host, csp->http->host_ip_addr_str, service);
407 #else /* ndef HAVE_RFC2553 */
408 /* Pre-getaddrinfo implementation */
410 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
412 struct sockaddr_in inaddr;
416 struct timeval tv[1];
417 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
422 struct access_control_addr dst[1];
423 #endif /* def FEATURE_ACL */
425 /* Don't leak memory when retrying. */
426 freez(csp->http->host_ip_addr_str);
428 memset((char *)&inaddr, 0, sizeof inaddr);
430 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
432 csp->http->host_ip_addr_str = strdup("unknown");
433 return(JB_INVALID_SOCKET);
437 dst->addr = ntohl(addr);
440 if (block_acl(dst, csp))
447 return(JB_INVALID_SOCKET);
449 #endif /* def FEATURE_ACL */
451 inaddr.sin_addr.s_addr = addr;
452 inaddr.sin_family = AF_INET;
453 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
456 if (sizeof(inaddr.sin_port) == sizeof(short))
457 #endif /* ndef _WIN32 */
459 inaddr.sin_port = htons((unsigned short) portnum);
464 inaddr.sin_port = htonl((unsigned long)portnum);
466 #endif /* ndef _WIN32 */
468 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
470 if (fd == JB_INVALID_SOCKET)
475 return(JB_INVALID_SOCKET);
479 if (fd >= FD_SETSIZE)
481 log_error(LOG_LEVEL_ERROR,
482 "Server socket number too high to use select(): %d >= %d",
485 return JB_INVALID_SOCKET;
490 { /* turn off TCP coalescence */
492 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
494 #endif /* def TCP_NODELAY */
496 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
497 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
500 fcntl(fd, F_SETFL, flags);
501 #ifdef FEATURE_EXTERNAL_FILTERS
502 mark_socket_for_close_on_execute(fd);
505 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
507 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
510 if (errno == WSAEINPROGRESS)
512 if (sock_errno() == EINPROGRESS)
513 #else /* ifndef _WIN32 */
514 if (errno == EINPROGRESS)
515 #endif /* ndef _WIN32 || __OS2__ */
521 if (sock_errno() != EINTR)
527 return(JB_INVALID_SOCKET);
531 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
535 fcntl(fd, F_SETFL, flags);
537 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
539 /* wait for connection to complete */
546 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
547 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
550 return(JB_INVALID_SOCKET);
555 #endif /* ndef HAVE_RFC2553 */
558 /*********************************************************************
560 * Function : write_socket
562 * Description : Write the contents of buf (for n bytes) to socket fd.
565 * 1 : fd = file descriptor (aka. handle) of socket to write to.
566 * 2 : buf = pointer to data to be written.
567 * 3 : len = length of data to be written to the socket "fd".
569 * Returns : 0 on success (entire buffer sent).
572 *********************************************************************/
574 int write_socket(jb_socket fd, const char *buf, ssize_t len)
576 int write_socket(jb_socket fd, const char *buf, size_t len)
584 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
587 return (send(fd, buf, (int)len, 0) != (int)len);
588 #elif defined(__BEOS__) || defined(AMIGA)
589 return (send(fd, buf, len, 0) != len);
590 #elif defined(__OS2__)
592 * Break the data up into SOCKET_SEND_MAX chunks for sending...
593 * OS/2 seemed to complain when the chunks were too large.
595 #define SOCKET_SEND_MAX 65000
597 int send_len, send_rc = 0, i = 0;
598 while ((i < len) && (send_rc != -1))
600 if ((i + SOCKET_SEND_MAX) > len)
603 send_len = SOCKET_SEND_MAX;
604 send_rc = send(fd,(char*)buf + i, send_len, 0);
612 return (write(fd, buf, len) != len);
618 /*********************************************************************
620 * Function : read_socket
622 * Description : Read from a TCP/IP socket in a platform independent way.
625 * 1 : fd = file descriptor of the socket to read
626 * 2 : buf = pointer to buffer where data will be written
627 * Must be >= len bytes long.
628 * 3 : len = maximum number of bytes to read
630 * Returns : On success, the number of bytes read is returned (zero
631 * indicates end of file), and the file position is advanced
632 * by this number. It is not an error if this number is
633 * smaller than the number of bytes requested; this may hap-
634 * pen for example because fewer bytes are actually available
635 * right now (maybe because we were close to end-of-file, or
636 * because we are reading from a pipe, or from a terminal,
637 * or because read() was interrupted by a signal). On error,
638 * -1 is returned, and errno is set appropriately. In this
639 * case it is left unspecified whether the file position (if
642 *********************************************************************/
643 int read_socket(jb_socket fd, char *buf, int len)
653 ret = recv(fd, buf, len, 0);
654 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
655 ret = recv(fd, buf, (size_t)len, 0);
657 ret = (int)read(fd, buf, (size_t)len);
662 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
669 /*********************************************************************
671 * Function : data_is_available
673 * Description : Waits for data to arrive on a socket.
676 * 1 : fd = file descriptor of the socket to read
677 * 2 : seconds_to_wait = number of seconds after which we give up.
679 * Returns : TRUE if data arrived in time,
682 *********************************************************************/
683 int data_is_available(jb_socket fd, int seconds_to_wait)
687 struct timeval timeout;
690 memset(&timeout, 0, sizeof(timeout));
691 timeout.tv_sec = seconds_to_wait;
694 /* Copy and pasted from jcc.c ... */
695 memset(&rfds, 0, sizeof(fd_set));
701 n = select(fd+1, &rfds, NULL, NULL, &timeout);
704 * XXX: Do we care about the different error conditions?
706 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
710 /*********************************************************************
712 * Function : close_socket
714 * Description : Closes a TCP/IP socket
717 * 1 : fd = file descriptor of socket to be closed
721 *********************************************************************/
722 void close_socket(jb_socket fd)
724 #if defined(_WIN32) || defined(__BEOS__)
728 #elif defined(__OS2__)
736 /*********************************************************************
738 * Function : drain_and_close_socket
740 * Description : Closes a TCP/IP socket after draining unread data
743 * 1 : fd = file descriptor of the socket to be closed
747 *********************************************************************/
748 void drain_and_close_socket(jb_socket fd)
750 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
751 if (socket_is_still_alive(fd))
754 int bytes_drained_total = 0;
758 /* Apparently Windows has shutdown() but not SHUT_WR. */
762 if (0 != shutdown(fd, SHUT_WR))
764 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
767 #define ARBITRARY_DRAIN_LIMIT 10000
772 if (!data_is_available(fd, 0))
775 * If there is no data available right now, don't try
776 * to drain the socket as read_socket() could block.
781 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
782 if (bytes_drained < 0)
784 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
786 else if (bytes_drained > 0)
788 bytes_drained_total += bytes_drained;
789 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
791 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
795 } while (bytes_drained > 0);
796 if (bytes_drained_total != 0)
798 log_error(LOG_LEVEL_CONNECT,
799 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
808 /*********************************************************************
810 * Function : bind_port
812 * Description : Call socket, set socket options, and listen.
813 * Called by listen_loop to "boot up" our proxy address.
816 * 1 : hostnam = TCP/IP address to bind/listen to
817 * 2 : portnum = port to listen on
818 * 3 : pfd = pointer used to return file descriptor.
820 * Returns : if success, returns 0 and sets *pfd.
821 * if failure, returns -3 if address is in use,
822 * -2 if address unresolvable,
824 *********************************************************************/
825 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
828 struct addrinfo hints;
829 struct addrinfo *result, *rp;
831 * XXX: portnum should be a string to allow symbolic service
832 * names in the configuration file and to avoid the following
838 struct sockaddr_in inaddr;
839 #endif /* def HAVE_RFC2553 */
843 #endif /* ndef _WIN32 */
845 *pfd = JB_INVALID_SOCKET;
848 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
849 if ((-1 == retval) || (sizeof(servnam) <= retval))
851 log_error(LOG_LEVEL_ERROR,
852 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
857 memset(&hints, 0, sizeof(struct addrinfo));
861 * XXX: This is a hack. The right thing to do
862 * would be to bind to both AF_INET and AF_INET6.
863 * This will also fail if there is no AF_INET
866 hints.ai_family = AF_INET;
870 hints.ai_family = AF_UNSPEC;
872 hints.ai_socktype = SOCK_STREAM;
873 hints.ai_flags = AI_PASSIVE;
874 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
875 hints.ai_canonname = NULL;
876 hints.ai_addr = NULL;
877 hints.ai_next = NULL;
879 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
881 log_error(LOG_LEVEL_ERROR,
882 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
886 memset((char *)&inaddr, '\0', sizeof inaddr);
888 inaddr.sin_family = AF_INET;
889 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
891 if (inaddr.sin_addr.s_addr == INADDR_NONE)
897 if (sizeof(inaddr.sin_port) == sizeof(short))
898 #endif /* ndef _WIN32 */
900 inaddr.sin_port = htons((unsigned short) portnum);
905 inaddr.sin_port = htonl((unsigned long) portnum);
907 #endif /* ndef _WIN32 */
908 #endif /* def HAVE_RFC2553 */
911 for (rp = result; rp != NULL; rp = rp->ai_next)
913 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
915 fd = socket(AF_INET, SOCK_STREAM, 0);
916 #endif /* def HAVE_RFC2553 */
918 #ifdef FEATURE_EXTERNAL_FILTERS
919 mark_socket_for_close_on_execute(fd);
923 if (fd == JB_INVALID_SOCKET)
937 * This is not needed for Win32 - in fact, it stops
938 * duplicate instances of Privoxy from being caught.
940 * On UNIX, we assume the user is sensible enough not
941 * to start Privoxy multiple times on the same IP.
942 * Without this, stopping and restarting Privoxy
943 * from a script fails.
944 * Note: SO_REUSEADDR is meant to only take over
945 * sockets which are *not* in listen state in Linux,
946 * e.g. sockets in TIME_WAIT. YMMV.
948 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
949 #endif /* ndef _WIN32 */
952 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
954 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
958 errno = WSAGetLastError();
959 if (errno == WSAEADDRINUSE)
961 if (errno == EADDRINUSE)
965 freeaddrinfo(result);
982 /* bind() succeeded, escape from for-loop */
984 * XXX: Support multiple listening sockets (e.g. localhost
985 * resolves to AF_INET and AF_INET6, but only the first address
992 freeaddrinfo(result);
995 /* All bind()s failed */
998 #endif /* ndef HAVE_RFC2553 */
1000 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1014 /*********************************************************************
1016 * Function : get_host_information
1018 * Description : Determines the IP address the client used to
1019 * reach us and the hostname associated with it.
1021 * XXX: Most of the code has been copy and pasted
1022 * from accept_connection() and not all of the
1023 * ifdefs paths have been tested afterwards.
1026 * 1 : afd = File descriptor returned from accept().
1027 * 2 : ip_address = Pointer to return the pointer to
1028 * the ip address string.
1029 * 3 : port = Pointer to return the pointer to
1030 * the TCP port string.
1031 * 4 : hostname = Pointer to return the pointer to
1032 * the hostname or NULL if the caller
1033 * isn't interested in it.
1037 *********************************************************************/
1038 void get_host_information(jb_socket afd, char **ip_address, char **port,
1042 struct sockaddr_storage server;
1045 struct sockaddr_in server;
1046 struct hostent *host = NULL;
1047 #endif /* HAVE_RFC2553 */
1048 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1049 /* according to accept_connection() this fixes a warning. */
1050 int s_length, s_length_provided;
1052 socklen_t s_length, s_length_provided;
1054 #ifndef HAVE_RFC2553
1055 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1056 struct hostent result;
1057 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1058 struct hostent_data hdata;
1060 char hbuf[HOSTENT_BUFFER_SIZE];
1062 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1063 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1064 #endif /* ifndef HAVE_RFC2553 */
1065 s_length = s_length_provided = sizeof(server);
1067 if (NULL != hostname)
1074 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1076 if (s_length > s_length_provided)
1078 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1082 * XXX: Workaround for missing header on Windows when
1083 * configured with --disable-ipv6-support.
1084 * The proper fix is to not use NI_MAXSERV in
1085 * that case. It works by accident on other platforms
1086 * as <netdb.h> is included unconditionally there.
1089 #define NI_MAXSERV 32
1091 *port = malloc(NI_MAXSERV);
1094 log_error(LOG_LEVEL_ERROR,
1095 "Out of memory while getting the client's port.");
1099 *ip_address = malloc(NI_MAXHOST);
1100 if (NULL == *ip_address)
1102 log_error(LOG_LEVEL_ERROR,
1103 "Out of memory while getting the client's IP address.");
1107 retval = getnameinfo((struct sockaddr *) &server, s_length,
1108 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1109 NI_NUMERICHOST|NI_NUMERICSERV);
1112 log_error(LOG_LEVEL_ERROR,
1113 "Unable to print my own IP address: %s", gai_strerror(retval));
1119 *ip_address = strdup(inet_ntoa(server.sin_addr));
1120 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1121 #endif /* HAVE_RFC2553 */
1122 if (NULL == hostname)
1125 * We're done here, the caller isn't
1126 * interested in knowing the hostname.
1132 *hostname = malloc(NI_MAXHOST);
1133 if (NULL == *hostname)
1135 log_error(LOG_LEVEL_ERROR,
1136 "Out of memory while getting the client's hostname.");
1139 retval = getnameinfo((struct sockaddr *) &server, s_length,
1140 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1143 log_error(LOG_LEVEL_ERROR,
1144 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1148 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1149 gethostbyaddr_r((const char *)&server.sin_addr,
1150 sizeof(server.sin_addr), AF_INET,
1151 &result, hbuf, HOSTENT_BUFFER_SIZE,
1153 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1154 host = gethostbyaddr_r((const char *)&server.sin_addr,
1155 sizeof(server.sin_addr), AF_INET,
1156 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1157 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1158 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1159 sizeof(server.sin_addr), AF_INET,
1168 #elif defined(MUTEX_LOCKS_AVAILABLE)
1169 privoxy_mutex_lock(&resolver_mutex);
1170 host = gethostbyaddr((const char *)&server.sin_addr,
1171 sizeof(server.sin_addr), AF_INET);
1172 privoxy_mutex_unlock(&resolver_mutex);
1174 host = gethostbyaddr((const char *)&server.sin_addr,
1175 sizeof(server.sin_addr), AF_INET);
1179 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1183 *hostname = strdup(host->h_name);
1185 #endif /* else def HAVE_RFC2553 */
1192 /*********************************************************************
1194 * Function : accept_connection
1196 * Description : Accepts a connection on one of possibly multiple
1197 * sockets. The socket(s) to check must have been
1198 * created using bind_port().
1201 * 1 : csp = Client state, cfd, ip_addr_str, and
1202 * ip_addr_long will be set by this routine.
1203 * 2 : fds = File descriptors returned from bind_port
1205 * Returns : when a connection is accepted, it returns 1 (TRUE).
1206 * On an error it returns 0 (FALSE).
1208 *********************************************************************/
1209 int accept_connection(struct client_state * csp, jb_socket fds[])
1212 /* XXX: client is stored directly into csp->tcp_addr */
1213 #define client (csp->tcp_addr)
1215 struct sockaddr_in client;
1218 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1219 /* Wierdness - fix a warning. */
1226 int max_selected_socket;
1227 fd_set selected_fds;
1230 c_length = sizeof(client);
1233 * Wait for a connection on any socket.
1234 * Return immediately if no socket is listening.
1235 * XXX: Why not treat this as fatal error?
1237 FD_ZERO(&selected_fds);
1238 max_selected_socket = 0;
1239 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1241 if (JB_INVALID_SOCKET != fds[i])
1243 FD_SET(fds[i], &selected_fds);
1244 if (max_selected_socket < fds[i] + 1)
1246 max_selected_socket = fds[i] + 1;
1250 if (0 == max_selected_socket)
1256 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1257 } while (retval < 0 && errno == EINTR);
1262 log_error(LOG_LEVEL_ERROR,
1263 "Waiting on new client failed because select(2) returned 0."
1264 " This should not happen.");
1268 log_error(LOG_LEVEL_ERROR,
1269 "Waiting on new client failed because of problems in select(2): "
1270 "%s.", strerror(errno));
1274 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1276 if (i >= MAX_LISTENING_SOCKETS)
1278 log_error(LOG_LEVEL_ERROR,
1279 "select(2) reported connected clients (number = %u, "
1280 "descriptor boundary = %u), but none found.",
1281 retval, max_selected_socket);
1286 /* Accept selected connection */
1288 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1289 if (afd == JB_INVALID_SOCKET)
1296 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1297 struct accept_filter_arg af_options;
1298 bzero(&af_options, sizeof(af_options));
1299 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1300 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1302 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1303 } while (afd < 1 && errno == EINTR);
1312 struct linger linger_options;
1313 linger_options.l_onoff = 1;
1314 linger_options.l_linger = 5;
1315 if (0 != setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1317 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1323 if (afd >= FD_SETSIZE)
1325 log_error(LOG_LEVEL_ERROR,
1326 "Client socket number too high to use select(): %d >= %d",
1333 #ifdef FEATURE_EXTERNAL_FILTERS
1334 mark_socket_for_close_on_execute(afd);
1339 csp->ip_addr_str = malloc(NI_MAXHOST);
1340 if (NULL == csp->ip_addr_str)
1342 log_error(LOG_LEVEL_ERROR,
1343 "Out of memory while getting the client's IP address.");
1346 retval = getnameinfo((struct sockaddr *) &client, c_length,
1347 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1348 if (!csp->ip_addr_str || retval)
1350 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1351 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1352 freez(csp->ip_addr_str);
1356 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1357 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1358 #endif /* def HAVE_RFC2553 */
1365 /*********************************************************************
1367 * Function : resolve_hostname_to_ip
1369 * Description : Resolve a hostname to an internet tcp/ip address.
1370 * NULL or an empty string resolve to INADDR_ANY.
1373 * 1 : host = hostname to resolve
1375 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1377 *********************************************************************/
1378 unsigned long resolve_hostname_to_ip(const char *host)
1380 struct sockaddr_in inaddr;
1381 struct hostent *hostp;
1382 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1383 struct hostent result;
1384 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1385 char hbuf[HOSTENT_BUFFER_SIZE];
1387 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1388 struct hostent_data hdata;
1389 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1390 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1392 if ((host == NULL) || (*host == '\0'))
1397 memset((char *) &inaddr, 0, sizeof inaddr);
1399 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1401 unsigned int dns_retries = 0;
1402 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1403 while (gethostbyname_r(host, &result, hbuf,
1404 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1405 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1407 log_error(LOG_LEVEL_ERROR,
1408 "Timeout #%u while trying to resolve %s. Trying again.",
1411 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1412 while (NULL == (hostp = gethostbyname_r(host, &result,
1413 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1414 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1416 log_error(LOG_LEVEL_ERROR,
1417 "Timeout #%u while trying to resolve %s. Trying again.",
1420 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1422 * XXX: Doesn't retry in case of soft errors.
1423 * Does this gethostbyname_r version set h_errno?
1425 if (0 == gethostbyname_r(host, &result, &hdata))
1433 #elif defined(MUTEX_LOCKS_AVAILABLE)
1434 privoxy_mutex_lock(&resolver_mutex);
1435 while (NULL == (hostp = gethostbyname(host))
1436 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1438 log_error(LOG_LEVEL_ERROR,
1439 "Timeout #%u while trying to resolve %s. Trying again.",
1442 privoxy_mutex_unlock(&resolver_mutex);
1444 while (NULL == (hostp = gethostbyname(host))
1445 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1447 log_error(LOG_LEVEL_ERROR,
1448 "Timeout #%u while trying to resolve %s. Trying again.",
1451 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1453 * On Mac OSX, if a domain exists but doesn't have a type A
1454 * record associated with it, the h_addr member of the struct
1455 * hostent returned by gethostbyname is NULL, even if h_length
1456 * is 4. Therefore the second test below.
1458 if (hostp == NULL || hostp->h_addr == NULL)
1461 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1462 return(INADDR_NONE);
1464 if (hostp->h_addrtype != AF_INET)
1467 errno = WSAEPROTOTYPE;
1471 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1472 return(INADDR_NONE);
1474 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1476 return(inaddr.sin_addr.s_addr);
1481 /*********************************************************************
1483 * Function : socket_is_still_alive
1485 * Description : Figures out whether or not a socket is still alive.
1488 * 1 : sfd = The socket to check.
1490 * Returns : TRUE for yes, otherwise FALSE.
1492 *********************************************************************/
1493 int socket_is_still_alive(jb_socket sfd)
1496 int no_data_waiting;
1500 struct pollfd poll_fd[1];
1502 memset(poll_fd, 0, sizeof(poll_fd));
1503 poll_fd[0].fd = sfd;
1504 poll_fd[0].events = POLLIN;
1506 poll_result = poll(poll_fd, 1, 0);
1508 if (-1 == poll_result)
1510 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1513 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1515 fd_set readable_fds;
1516 struct timeval timeout;
1519 memset(&timeout, '\0', sizeof(timeout));
1520 FD_ZERO(&readable_fds);
1521 FD_SET(sfd, &readable_fds);
1523 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1526 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1529 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1530 #endif /* def HAVE_POLL */
1532 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1536 #ifdef FEATURE_EXTERNAL_FILTERS
1537 /*********************************************************************
1539 * Function : mark_socket_for_close_on_execute
1541 * Description : Marks a socket for close on execute.
1543 * Used so that external filters have no direct
1544 * access to sockets they shouldn't care about.
1546 * Not implemented for all platforms.
1549 * 1 : fd = The socket to mark
1553 *********************************************************************/
1554 void mark_socket_for_close_on_execute(jb_socket fd)
1556 #ifdef FEATURE_PTHREAD
1559 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1563 log_error(LOG_LEVEL_ERROR,
1564 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1567 #warning "Sockets will be visible to external filters"
1570 #endif /* def FEATURE_EXTERNAL_FILTERS */