1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.127 2014/06/03 10:27:56 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 return JB_INVALID_SOCKET;
286 #ifdef FEATURE_EXTERNAL_FILTERS
287 mark_socket_for_close_on_execute(fd);
291 { /* turn off TCP coalescence */
293 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
295 #endif /* def TCP_NODELAY */
297 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
298 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
301 fcntl(fd, F_SETFL, flags);
303 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
306 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
309 errno = sock_errno();
313 if (errno == WSAEINPROGRESS)
314 #else /* ifndef _WIN32 */
315 if (errno == EINPROGRESS)
316 #endif /* ndef _WIN32 || __OS2__ */
323 socket_error = errno;
334 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
338 fcntl(fd, F_SETFL, flags);
340 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
342 /* wait for connection to complete */
346 memset(&timeout, 0, sizeof(timeout));
349 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
350 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
351 && FD_ISSET(fd, &wfds))
353 socklen_t optlen = sizeof(socket_error);
354 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
358 /* Connection established, no need to try other addresses. */
361 if (rp->ai_next != NULL)
364 * There's another address we can try, so log that this
365 * one didn't work out. If the last one fails, too,
366 * it will get logged outside the loop body so we don't
367 * have to mention it here.
369 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
370 csp->http->host_ip_addr_str, service, strerror(socket_error));
375 socket_error = errno;
376 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
377 "the connection to [%s]:%s: %s; dropping connection.",
378 csp->http->host_ip_addr_str, service, strerror(errno));
382 /* Connection failed, try next address */
386 freeaddrinfo(result);
389 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
390 host, service, strerror(socket_error));
391 csp->error_message = strdup(strerror(socket_error));
392 return(JB_INVALID_SOCKET);
394 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
395 host, csp->http->host_ip_addr_str, service);
401 #else /* ndef HAVE_RFC2553 */
402 /* Pre-getaddrinfo implementation */
404 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
406 struct sockaddr_in inaddr;
410 struct timeval tv[1];
411 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
416 struct access_control_addr dst[1];
417 #endif /* def FEATURE_ACL */
419 /* Don't leak memory when retrying. */
420 freez(csp->http->host_ip_addr_str);
422 memset((char *)&inaddr, 0, sizeof inaddr);
424 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
426 csp->http->host_ip_addr_str = strdup("unknown");
427 return(JB_INVALID_SOCKET);
431 dst->addr = ntohl(addr);
434 if (block_acl(dst, csp))
441 return(JB_INVALID_SOCKET);
443 #endif /* def FEATURE_ACL */
445 inaddr.sin_addr.s_addr = addr;
446 inaddr.sin_family = AF_INET;
447 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
450 if (sizeof(inaddr.sin_port) == sizeof(short))
451 #endif /* ndef _WIN32 */
453 inaddr.sin_port = htons((unsigned short) portnum);
458 inaddr.sin_port = htonl((unsigned long)portnum);
460 #endif /* ndef _WIN32 */
462 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
464 if (fd == JB_INVALID_SOCKET)
469 return(JB_INVALID_SOCKET);
473 if (fd >= FD_SETSIZE)
475 log_error(LOG_LEVEL_ERROR,
476 "Server socket number too high to use select(): %d >= %d",
479 return JB_INVALID_SOCKET;
484 { /* turn off TCP coalescence */
486 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
488 #endif /* def TCP_NODELAY */
490 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
491 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
494 fcntl(fd, F_SETFL, flags);
495 #ifdef FEATURE_EXTERNAL_FILTERS
496 mark_socket_for_close_on_execute(fd);
499 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
501 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
504 if (errno == WSAEINPROGRESS)
506 if (sock_errno() == EINPROGRESS)
507 #else /* ifndef _WIN32 */
508 if (errno == EINPROGRESS)
509 #endif /* ndef _WIN32 || __OS2__ */
515 if (sock_errno() != EINTR)
521 return(JB_INVALID_SOCKET);
525 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
529 fcntl(fd, F_SETFL, flags);
531 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
533 /* wait for connection to complete */
540 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
541 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
544 return(JB_INVALID_SOCKET);
549 #endif /* ndef HAVE_RFC2553 */
552 /*********************************************************************
554 * Function : write_socket
556 * Description : Write the contents of buf (for n bytes) to socket fd.
559 * 1 : fd = file descriptor (aka. handle) of socket to write to.
560 * 2 : buf = pointer to data to be written.
561 * 3 : len = length of data to be written to the socket "fd".
563 * Returns : 0 on success (entire buffer sent).
566 *********************************************************************/
568 int write_socket(jb_socket fd, const char *buf, ssize_t len)
570 int write_socket(jb_socket fd, const char *buf, size_t len)
578 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
581 return (send(fd, buf, (int)len, 0) != (int)len);
582 #elif defined(__BEOS__) || defined(AMIGA)
583 return (send(fd, buf, len, 0) != len);
584 #elif defined(__OS2__)
586 * Break the data up into SOCKET_SEND_MAX chunks for sending...
587 * OS/2 seemed to complain when the chunks were too large.
589 #define SOCKET_SEND_MAX 65000
591 int send_len, send_rc = 0, i = 0;
592 while ((i < len) && (send_rc != -1))
594 if ((i + SOCKET_SEND_MAX) > len)
597 send_len = SOCKET_SEND_MAX;
598 send_rc = send(fd,(char*)buf + i, send_len, 0);
606 return (write(fd, buf, len) != len);
612 /*********************************************************************
614 * Function : read_socket
616 * Description : Read from a TCP/IP socket in a platform independent way.
619 * 1 : fd = file descriptor of the socket to read
620 * 2 : buf = pointer to buffer where data will be written
621 * Must be >= len bytes long.
622 * 3 : len = maximum number of bytes to read
624 * Returns : On success, the number of bytes read is returned (zero
625 * indicates end of file), and the file position is advanced
626 * by this number. It is not an error if this number is
627 * smaller than the number of bytes requested; this may hap-
628 * pen for example because fewer bytes are actually available
629 * right now (maybe because we were close to end-of-file, or
630 * because we are reading from a pipe, or from a terminal,
631 * or because read() was interrupted by a signal). On error,
632 * -1 is returned, and errno is set appropriately. In this
633 * case it is left unspecified whether the file position (if
636 *********************************************************************/
637 int read_socket(jb_socket fd, char *buf, int len)
647 ret = recv(fd, buf, len, 0);
648 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
649 ret = recv(fd, buf, (size_t)len, 0);
651 ret = (int)read(fd, buf, (size_t)len);
656 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
663 /*********************************************************************
665 * Function : data_is_available
667 * Description : Waits for data to arrive on a socket.
670 * 1 : fd = file descriptor of the socket to read
671 * 2 : seconds_to_wait = number of seconds after which we give up.
673 * Returns : TRUE if data arrived in time,
676 *********************************************************************/
677 int data_is_available(jb_socket fd, int seconds_to_wait)
681 struct timeval timeout;
684 memset(&timeout, 0, sizeof(timeout));
685 timeout.tv_sec = seconds_to_wait;
688 /* Copy and pasted from jcc.c ... */
689 memset(&rfds, 0, sizeof(fd_set));
695 n = select(fd+1, &rfds, NULL, NULL, &timeout);
698 * XXX: Do we care about the different error conditions?
700 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
704 /*********************************************************************
706 * Function : close_socket
708 * Description : Closes a TCP/IP socket
711 * 1 : fd = file descriptor of socket to be closed
715 *********************************************************************/
716 void close_socket(jb_socket fd)
718 #if defined(_WIN32) || defined(__BEOS__)
722 #elif defined(__OS2__)
730 /*********************************************************************
732 * Function : drain_and_close_socket
734 * Description : Closes a TCP/IP socket after draining unread data
737 * 1 : fd = file descriptor of the socket to be closed
741 *********************************************************************/
742 void drain_and_close_socket(jb_socket fd)
744 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
745 if (socket_is_still_alive(fd))
748 int bytes_drained_total = 0;
752 /* Apparently Windows has shutdown() but not SHUT_WR. */
756 if (0 != shutdown(fd, SHUT_WR))
758 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
761 #define ARBITRARY_DRAIN_LIMIT 10000
766 if (!data_is_available(fd, 0))
769 * If there is no data available right now, don't try
770 * to drain the socket as read_socket() could block.
775 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
776 if (bytes_drained < 0)
778 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
780 else if (bytes_drained > 0)
782 bytes_drained_total += bytes_drained;
783 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
785 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
789 } while (bytes_drained > 0);
790 if (bytes_drained_total != 0)
792 log_error(LOG_LEVEL_CONNECT,
793 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
802 /*********************************************************************
804 * Function : bind_port
806 * Description : Call socket, set socket options, and listen.
807 * Called by listen_loop to "boot up" our proxy address.
810 * 1 : hostnam = TCP/IP address to bind/listen to
811 * 2 : portnum = port to listen on
812 * 3 : pfd = pointer used to return file descriptor.
814 * Returns : if success, returns 0 and sets *pfd.
815 * if failure, returns -3 if address is in use,
816 * -2 if address unresolvable,
818 *********************************************************************/
819 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
822 struct addrinfo hints;
823 struct addrinfo *result, *rp;
825 * XXX: portnum should be a string to allow symbolic service
826 * names in the configuration file and to avoid the following
832 struct sockaddr_in inaddr;
833 #endif /* def HAVE_RFC2553 */
837 #endif /* ndef _WIN32 */
839 *pfd = JB_INVALID_SOCKET;
842 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
843 if ((-1 == retval) || (sizeof(servnam) <= retval))
845 log_error(LOG_LEVEL_ERROR,
846 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
851 memset(&hints, 0, sizeof(struct addrinfo));
855 * XXX: This is a hack. The right thing to do
856 * would be to bind to both AF_INET and AF_INET6.
857 * This will also fail if there is no AF_INET
860 hints.ai_family = AF_INET;
864 hints.ai_family = AF_UNSPEC;
866 hints.ai_socktype = SOCK_STREAM;
867 hints.ai_flags = AI_PASSIVE;
868 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
869 hints.ai_canonname = NULL;
870 hints.ai_addr = NULL;
871 hints.ai_next = NULL;
873 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
875 log_error(LOG_LEVEL_ERROR,
876 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
880 memset((char *)&inaddr, '\0', sizeof inaddr);
882 inaddr.sin_family = AF_INET;
883 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
885 if (inaddr.sin_addr.s_addr == INADDR_NONE)
891 if (sizeof(inaddr.sin_port) == sizeof(short))
892 #endif /* ndef _WIN32 */
894 inaddr.sin_port = htons((unsigned short) portnum);
899 inaddr.sin_port = htonl((unsigned long) portnum);
901 #endif /* ndef _WIN32 */
902 #endif /* def HAVE_RFC2553 */
905 for (rp = result; rp != NULL; rp = rp->ai_next)
907 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
909 fd = socket(AF_INET, SOCK_STREAM, 0);
910 #endif /* def HAVE_RFC2553 */
912 #ifdef FEATURE_EXTERNAL_FILTERS
913 mark_socket_for_close_on_execute(fd);
917 if (fd == JB_INVALID_SOCKET)
931 * This is not needed for Win32 - in fact, it stops
932 * duplicate instances of Privoxy from being caught.
934 * On UNIX, we assume the user is sensible enough not
935 * to start Privoxy multiple times on the same IP.
936 * Without this, stopping and restarting Privoxy
937 * from a script fails.
938 * Note: SO_REUSEADDR is meant to only take over
939 * sockets which are *not* in listen state in Linux,
940 * e.g. sockets in TIME_WAIT. YMMV.
942 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
943 #endif /* ndef _WIN32 */
946 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
948 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
952 errno = WSAGetLastError();
953 if (errno == WSAEADDRINUSE)
955 if (errno == EADDRINUSE)
959 freeaddrinfo(result);
976 /* bind() succeeded, escape from for-loop */
978 * XXX: Support multiple listening sockets (e.g. localhost
979 * resolves to AF_INET and AF_INET6, but only the first address
986 freeaddrinfo(result);
989 /* All bind()s failed */
992 #endif /* ndef HAVE_RFC2553 */
994 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
1008 /*********************************************************************
1010 * Function : get_host_information
1012 * Description : Determines the IP address the client used to
1013 * reach us and the hostname associated with it.
1015 * XXX: Most of the code has been copy and pasted
1016 * from accept_connection() and not all of the
1017 * ifdefs paths have been tested afterwards.
1020 * 1 : afd = File descriptor returned from accept().
1021 * 2 : ip_address = Pointer to return the pointer to
1022 * the ip address string.
1023 * 3 : port = Pointer to return the pointer to
1024 * the TCP port string.
1025 * 4 : hostname = Pointer to return the pointer to
1026 * the hostname or NULL if the caller
1027 * isn't interested in it.
1031 *********************************************************************/
1032 void get_host_information(jb_socket afd, char **ip_address, char **port,
1036 struct sockaddr_storage server;
1039 struct sockaddr_in server;
1040 struct hostent *host = NULL;
1041 #endif /* HAVE_RFC2553 */
1042 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1043 /* according to accept_connection() this fixes a warning. */
1044 int s_length, s_length_provided;
1046 socklen_t s_length, s_length_provided;
1048 #ifndef HAVE_RFC2553
1049 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1050 struct hostent result;
1051 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1052 struct hostent_data hdata;
1054 char hbuf[HOSTENT_BUFFER_SIZE];
1056 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1057 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1058 #endif /* ifndef HAVE_RFC2553 */
1059 s_length = s_length_provided = sizeof(server);
1061 if (NULL != hostname)
1068 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1070 if (s_length > s_length_provided)
1072 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1076 * XXX: Workaround for missing header on Windows when
1077 * configured with --disable-ipv6-support.
1078 * The proper fix is to not use NI_MAXSERV in
1079 * that case. It works by accident on other platforms
1080 * as <netdb.h> is included unconditionally there.
1083 #define NI_MAXSERV 32
1085 *port = malloc_or_die(NI_MAXSERV);
1088 *ip_address = malloc_or_die(NI_MAXHOST);
1089 retval = getnameinfo((struct sockaddr *) &server, s_length,
1090 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1091 NI_NUMERICHOST|NI_NUMERICSERV);
1094 log_error(LOG_LEVEL_ERROR,
1095 "Unable to print my own IP address: %s", gai_strerror(retval));
1101 *ip_address = strdup(inet_ntoa(server.sin_addr));
1102 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1103 #endif /* HAVE_RFC2553 */
1104 if (NULL == hostname)
1107 * We're done here, the caller isn't
1108 * interested in knowing the hostname.
1114 *hostname = malloc_or_die(NI_MAXHOST);
1115 retval = getnameinfo((struct sockaddr *) &server, s_length,
1116 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1119 log_error(LOG_LEVEL_ERROR,
1120 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1124 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1125 gethostbyaddr_r((const char *)&server.sin_addr,
1126 sizeof(server.sin_addr), AF_INET,
1127 &result, hbuf, HOSTENT_BUFFER_SIZE,
1129 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1130 host = gethostbyaddr_r((const char *)&server.sin_addr,
1131 sizeof(server.sin_addr), AF_INET,
1132 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1133 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1134 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1135 sizeof(server.sin_addr), AF_INET,
1144 #elif defined(MUTEX_LOCKS_AVAILABLE)
1145 privoxy_mutex_lock(&resolver_mutex);
1146 host = gethostbyaddr((const char *)&server.sin_addr,
1147 sizeof(server.sin_addr), AF_INET);
1148 privoxy_mutex_unlock(&resolver_mutex);
1150 host = gethostbyaddr((const char *)&server.sin_addr,
1151 sizeof(server.sin_addr), AF_INET);
1155 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1159 *hostname = strdup(host->h_name);
1161 #endif /* else def HAVE_RFC2553 */
1168 /*********************************************************************
1170 * Function : accept_connection
1172 * Description : Accepts a connection on one of possibly multiple
1173 * sockets. The socket(s) to check must have been
1174 * created using bind_port().
1177 * 1 : csp = Client state, cfd, ip_addr_str, and
1178 * ip_addr_long will be set by this routine.
1179 * 2 : fds = File descriptors returned from bind_port
1181 * Returns : when a connection is accepted, it returns 1 (TRUE).
1182 * On an error it returns 0 (FALSE).
1184 *********************************************************************/
1185 int accept_connection(struct client_state * csp, jb_socket fds[])
1188 /* XXX: client is stored directly into csp->tcp_addr */
1189 #define client (csp->tcp_addr)
1191 struct sockaddr_in client;
1194 #if defined(_WIN32) || defined(__OS2__) || defined(AMIGA)
1195 /* Wierdness - fix a warning. */
1202 int max_selected_socket;
1203 fd_set selected_fds;
1206 c_length = sizeof(client);
1209 * Wait for a connection on any socket.
1210 * Return immediately if no socket is listening.
1211 * XXX: Why not treat this as fatal error?
1213 FD_ZERO(&selected_fds);
1214 max_selected_socket = 0;
1215 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1217 if (JB_INVALID_SOCKET != fds[i])
1219 FD_SET(fds[i], &selected_fds);
1220 if (max_selected_socket < fds[i] + 1)
1222 max_selected_socket = fds[i] + 1;
1226 if (0 == max_selected_socket)
1232 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1233 } while (retval < 0 && errno == EINTR);
1238 log_error(LOG_LEVEL_ERROR,
1239 "Waiting on new client failed because select(2) returned 0."
1240 " This should not happen.");
1244 log_error(LOG_LEVEL_ERROR,
1245 "Waiting on new client failed because of problems in select(2): "
1246 "%s.", strerror(errno));
1250 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1252 if (i >= MAX_LISTENING_SOCKETS)
1254 log_error(LOG_LEVEL_ERROR,
1255 "select(2) reported connected clients (number = %u, "
1256 "descriptor boundary = %u), but none found.",
1257 retval, max_selected_socket);
1262 /* Accept selected connection */
1264 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1265 if (afd == JB_INVALID_SOCKET)
1272 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1273 struct accept_filter_arg af_options;
1274 bzero(&af_options, sizeof(af_options));
1275 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1276 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1278 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1279 } while (afd < 0 && errno == EINTR);
1288 struct linger linger_options;
1289 linger_options.l_onoff = 1;
1290 linger_options.l_linger = 5;
1291 if (0 != setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1293 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1299 if (afd >= FD_SETSIZE)
1301 log_error(LOG_LEVEL_ERROR,
1302 "Client socket number too high to use select(): %d >= %d",
1309 #ifdef FEATURE_EXTERNAL_FILTERS
1310 mark_socket_for_close_on_execute(afd);
1315 csp->ip_addr_str = malloc_or_die(NI_MAXHOST);
1316 retval = getnameinfo((struct sockaddr *) &client, c_length,
1317 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1318 if (!csp->ip_addr_str || retval)
1320 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1321 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1322 freez(csp->ip_addr_str);
1326 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1327 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1328 #endif /* def HAVE_RFC2553 */
1335 /*********************************************************************
1337 * Function : resolve_hostname_to_ip
1339 * Description : Resolve a hostname to an internet tcp/ip address.
1340 * NULL or an empty string resolve to INADDR_ANY.
1343 * 1 : host = hostname to resolve
1345 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1347 *********************************************************************/
1348 unsigned long resolve_hostname_to_ip(const char *host)
1350 struct sockaddr_in inaddr;
1351 struct hostent *hostp;
1352 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1353 struct hostent result;
1354 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1355 char hbuf[HOSTENT_BUFFER_SIZE];
1357 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1358 struct hostent_data hdata;
1359 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1360 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1362 if ((host == NULL) || (*host == '\0'))
1367 memset((char *) &inaddr, 0, sizeof inaddr);
1369 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1371 unsigned int dns_retries = 0;
1372 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1373 while (gethostbyname_r(host, &result, hbuf,
1374 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1375 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1377 log_error(LOG_LEVEL_ERROR,
1378 "Timeout #%u while trying to resolve %s. Trying again.",
1381 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1382 while (NULL == (hostp = gethostbyname_r(host, &result,
1383 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1384 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1386 log_error(LOG_LEVEL_ERROR,
1387 "Timeout #%u while trying to resolve %s. Trying again.",
1390 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1392 * XXX: Doesn't retry in case of soft errors.
1393 * Does this gethostbyname_r version set h_errno?
1395 if (0 == gethostbyname_r(host, &result, &hdata))
1403 #elif defined(MUTEX_LOCKS_AVAILABLE)
1404 privoxy_mutex_lock(&resolver_mutex);
1405 while (NULL == (hostp = gethostbyname(host))
1406 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1408 log_error(LOG_LEVEL_ERROR,
1409 "Timeout #%u while trying to resolve %s. Trying again.",
1412 privoxy_mutex_unlock(&resolver_mutex);
1414 while (NULL == (hostp = gethostbyname(host))
1415 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1417 log_error(LOG_LEVEL_ERROR,
1418 "Timeout #%u while trying to resolve %s. Trying again.",
1421 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1423 * On Mac OSX, if a domain exists but doesn't have a type A
1424 * record associated with it, the h_addr member of the struct
1425 * hostent returned by gethostbyname is NULL, even if h_length
1426 * is 4. Therefore the second test below.
1428 if (hostp == NULL || hostp->h_addr == NULL)
1431 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1432 return(INADDR_NONE);
1434 if (hostp->h_addrtype != AF_INET)
1437 errno = WSAEPROTOTYPE;
1441 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1442 return(INADDR_NONE);
1444 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1446 return(inaddr.sin_addr.s_addr);
1451 /*********************************************************************
1453 * Function : socket_is_still_alive
1455 * Description : Figures out whether or not a socket is still alive.
1458 * 1 : sfd = The socket to check.
1460 * Returns : TRUE for yes, otherwise FALSE.
1462 *********************************************************************/
1463 int socket_is_still_alive(jb_socket sfd)
1466 int no_data_waiting;
1470 struct pollfd poll_fd[1];
1472 memset(poll_fd, 0, sizeof(poll_fd));
1473 poll_fd[0].fd = sfd;
1474 poll_fd[0].events = POLLIN;
1476 poll_result = poll(poll_fd, 1, 0);
1478 if (-1 == poll_result)
1480 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1483 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1485 fd_set readable_fds;
1486 struct timeval timeout;
1489 memset(&timeout, '\0', sizeof(timeout));
1490 FD_ZERO(&readable_fds);
1491 FD_SET(sfd, &readable_fds);
1493 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1496 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1499 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1500 #endif /* def HAVE_POLL */
1502 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1506 #ifdef FEATURE_EXTERNAL_FILTERS
1507 /*********************************************************************
1509 * Function : mark_socket_for_close_on_execute
1511 * Description : Marks a socket for close on execute.
1513 * Used so that external filters have no direct
1514 * access to sockets they shouldn't care about.
1516 * Not implemented for all platforms.
1519 * 1 : fd = The socket to mark
1523 *********************************************************************/
1524 void mark_socket_for_close_on_execute(jb_socket fd)
1526 #ifdef FEATURE_PTHREAD
1529 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
1533 log_error(LOG_LEVEL_ERROR,
1534 "fcntl(%d, F_SETFD, FD_CLOEXEC) failed", fd);
1537 #warning "Sockets will be visible to external filters"
1540 #endif /* def FEATURE_EXTERNAL_FILTERS */