1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.118 2012/10/21 12:44:58 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 connent on (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 { /* turn off TCP coalescence */
284 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
286 #endif /* def TCP_NODELAY */
288 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
289 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
292 fcntl(fd, F_SETFL, flags);
294 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
297 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
300 errno = sock_errno();
304 if (errno == WSAEINPROGRESS)
305 #else /* ifndef _WIN32 */
306 if (errno == EINPROGRESS)
307 #endif /* ndef _WIN32 || __OS2__ */
314 socket_error = errno;
325 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
329 fcntl(fd, F_SETFL, flags);
331 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
333 /* wait for connection to complete */
337 memset(&timeout, 0, sizeof(timeout));
340 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
341 if ((select((int)fd + 1, NULL, &wfds, NULL, &timeout) > 0)
342 && FD_ISSET(fd, &wfds))
344 socklen_t optlen = sizeof(socket_error);
345 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &optlen))
349 /* Connection established, no need to try other addresses. */
352 if (rp->ai_next != NULL)
355 * There's another address we can try, so log that this
356 * one didn't work out. If the last one fails, too,
357 * it will get logged outside the loop body so we don't
358 * have to mention it here.
360 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
361 csp->http->host_ip_addr_str, service, strerror(socket_error));
366 socket_error = errno;
367 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
368 "the connection to [%s]:%s: %s; dropping connection.",
369 csp->http->host_ip_addr_str, service, strerror(errno));
373 /* Connection failed, try next address */
377 freeaddrinfo(result);
380 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
381 host, service, strerror(socket_error));
382 csp->error_message = strdup(strerror(socket_error));
383 return(JB_INVALID_SOCKET);
385 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
386 host, csp->http->host_ip_addr_str, service);
392 #else /* ndef HAVE_RFC2553 */
393 /* Pre-getaddrinfo implementation */
395 static jb_socket no_rfc2553_connect_to(const char *host, int portnum, struct client_state *csp)
397 struct sockaddr_in inaddr;
401 struct timeval tv[1];
402 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
407 struct access_control_addr dst[1];
408 #endif /* def FEATURE_ACL */
410 /* Don't leak memory when retrying. */
411 freez(csp->http->host_ip_addr_str);
413 memset((char *)&inaddr, 0, sizeof inaddr);
415 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
417 csp->http->host_ip_addr_str = strdup("unknown");
418 return(JB_INVALID_SOCKET);
422 dst->addr = ntohl(addr);
425 if (block_acl(dst, csp))
432 return(JB_INVALID_SOCKET);
434 #endif /* def FEATURE_ACL */
436 inaddr.sin_addr.s_addr = addr;
437 inaddr.sin_family = AF_INET;
438 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
441 if (sizeof(inaddr.sin_port) == sizeof(short))
442 #endif /* ndef _WIN32 */
444 inaddr.sin_port = htons((unsigned short) portnum);
449 inaddr.sin_port = htonl((unsigned long)portnum);
451 #endif /* ndef _WIN32 */
453 fd = socket(inaddr.sin_family, SOCK_STREAM, 0);
455 if (fd == JB_INVALID_SOCKET)
460 return(JB_INVALID_SOCKET);
464 { /* turn off TCP coalescence */
466 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
468 #endif /* def TCP_NODELAY */
470 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
471 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
474 fcntl(fd, F_SETFL, flags);
476 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
478 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
481 if (errno == WSAEINPROGRESS)
483 if (sock_errno() == EINPROGRESS)
484 #else /* ifndef _WIN32 */
485 if (errno == EINPROGRESS)
486 #endif /* ndef _WIN32 || __OS2__ */
492 if (sock_errno() != EINTR)
498 return(JB_INVALID_SOCKET);
502 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
506 fcntl(fd, F_SETFL, flags);
508 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
510 /* wait for connection to complete */
517 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Weird! */
518 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
521 return(JB_INVALID_SOCKET);
526 #endif /* ndef HAVE_RFC2553 */
529 /*********************************************************************
531 * Function : write_socket
533 * Description : Write the contents of buf (for n bytes) to socket fd.
536 * 1 : fd = file descriptor (aka. handle) of socket to write to.
537 * 2 : buf = pointer to data to be written.
538 * 3 : len = length of data to be written to the socket "fd".
540 * Returns : 0 on success (entire buffer sent).
543 *********************************************************************/
545 int write_socket(jb_socket fd, const char *buf, ssize_t len)
547 int write_socket(jb_socket fd, const char *buf, size_t len)
555 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
558 return (send(fd, buf, (int)len, 0) != (int)len);
559 #elif defined(__BEOS__) || defined(AMIGA)
560 return (send(fd, buf, len, 0) != len);
561 #elif defined(__OS2__)
563 * Break the data up into SOCKET_SEND_MAX chunks for sending...
564 * OS/2 seemed to complain when the chunks were too large.
566 #define SOCKET_SEND_MAX 65000
568 int send_len, send_rc = 0, i = 0;
569 while ((i < len) && (send_rc != -1))
571 if ((i + SOCKET_SEND_MAX) > len)
574 send_len = SOCKET_SEND_MAX;
575 send_rc = send(fd,(char*)buf + i, send_len, 0);
583 return (write(fd, buf, len) != len);
589 /*********************************************************************
591 * Function : read_socket
593 * Description : Read from a TCP/IP socket in a platform independent way.
596 * 1 : fd = file descriptor of the socket to read
597 * 2 : buf = pointer to buffer where data will be written
598 * Must be >= len bytes long.
599 * 3 : len = maximum number of bytes to read
601 * Returns : On success, the number of bytes read is returned (zero
602 * indicates end of file), and the file position is advanced
603 * by this number. It is not an error if this number is
604 * smaller than the number of bytes requested; this may hap-
605 * pen for example because fewer bytes are actually available
606 * right now (maybe because we were close to end-of-file, or
607 * because we are reading from a pipe, or from a terminal,
608 * or because read() was interrupted by a signal). On error,
609 * -1 is returned, and errno is set appropriately. In this
610 * case it is left unspecified whether the file position (if
613 *********************************************************************/
614 int read_socket(jb_socket fd, char *buf, int len)
624 ret = recv(fd, buf, len, 0);
625 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
626 ret = recv(fd, buf, (size_t)len, 0);
628 ret = (int)read(fd, buf, (size_t)len);
633 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
640 /*********************************************************************
642 * Function : data_is_available
644 * Description : Waits for data to arrive on a socket.
647 * 1 : fd = file descriptor of the socket to read
648 * 2 : seconds_to_wait = number of seconds after which we give up.
650 * Returns : TRUE if data arrived in time,
653 *********************************************************************/
654 int data_is_available(jb_socket fd, int seconds_to_wait)
658 struct timeval timeout;
661 memset(&timeout, 0, sizeof(timeout));
662 timeout.tv_sec = seconds_to_wait;
665 /* Copy and pasted from jcc.c ... */
666 memset(&rfds, 0, sizeof(fd_set));
672 n = select(fd+1, &rfds, NULL, NULL, &timeout);
675 * XXX: Do we care about the different error conditions?
677 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
681 /*********************************************************************
683 * Function : close_socket
685 * Description : Closes a TCP/IP socket
688 * 1 : fd = file descriptor of socket to be closed
692 *********************************************************************/
693 void close_socket(jb_socket fd)
695 #if defined(_WIN32) || defined(__BEOS__)
699 #elif defined(__OS2__)
707 /*********************************************************************
709 * Function : drain_and_close_socket
711 * Description : Closes a TCP/IP socket after draining unread data
714 * 1 : fd = file descriptor of the socket to be closed
718 *********************************************************************/
719 void drain_and_close_socket(jb_socket fd)
721 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
722 if (socket_is_still_alive(fd))
725 int bytes_drained_total = 0;
729 /* Apparently Windows has shutdown() but not SHUT_WR. */
733 if (0 != shutdown(fd, SHUT_WR))
735 log_error(LOG_LEVEL_CONNECT, "Failed to shutdown socket %d: %E", fd);
738 #define ARBITRARY_DRAIN_LIMIT 10000
743 bytes_drained = read_socket(fd, drainage, sizeof(drainage));
744 if (bytes_drained < 0)
746 log_error(LOG_LEVEL_CONNECT, "Failed to drain socket %d: %E", fd);
748 else if (bytes_drained > 0)
750 bytes_drained_total += bytes_drained;
751 if (bytes_drained_total > ARBITRARY_DRAIN_LIMIT)
753 log_error(LOG_LEVEL_CONNECT, "Giving up draining socket %d", fd);
757 } while (bytes_drained > 0);
758 if (bytes_drained_total != 0)
760 log_error(LOG_LEVEL_CONNECT,
761 "Drained %d bytes before closing socket %d", bytes_drained_total, fd);
770 /*********************************************************************
772 * Function : bind_port
774 * Description : Call socket, set socket options, and listen.
775 * Called by listen_loop to "boot up" our proxy address.
778 * 1 : hostnam = TCP/IP address to bind/listen to
779 * 2 : portnum = port to listen on
780 * 3 : pfd = pointer used to return file descriptor.
782 * Returns : if success, returns 0 and sets *pfd.
783 * if failure, returns -3 if address is in use,
784 * -2 if address unresolvable,
786 *********************************************************************/
787 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
790 struct addrinfo hints;
791 struct addrinfo *result, *rp;
793 * XXX: portnum should be a string to allow symbolic service
794 * names in the configuration file and to avoid the following
800 struct sockaddr_in inaddr;
801 #endif /* def HAVE_RFC2553 */
805 #endif /* ndef _WIN32 */
807 *pfd = JB_INVALID_SOCKET;
810 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
811 if ((-1 == retval) || (sizeof(servnam) <= retval))
813 log_error(LOG_LEVEL_ERROR,
814 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
819 memset(&hints, 0, sizeof(struct addrinfo));
823 * XXX: This is a hack. The right thing to do
824 * would be to bind to both AF_INET and AF_INET6.
825 * This will also fail if there is no AF_INET
828 hints.ai_family = AF_INET;
832 hints.ai_family = AF_UNSPEC;
834 hints.ai_socktype = SOCK_STREAM;
835 hints.ai_flags = AI_PASSIVE;
836 hints.ai_protocol = 0; /* Really any stream protocol or TCP only */
837 hints.ai_canonname = NULL;
838 hints.ai_addr = NULL;
839 hints.ai_next = NULL;
841 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
843 log_error(LOG_LEVEL_ERROR,
844 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
848 memset((char *)&inaddr, '\0', sizeof inaddr);
850 inaddr.sin_family = AF_INET;
851 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
853 if (inaddr.sin_addr.s_addr == INADDR_NONE)
859 if (sizeof(inaddr.sin_port) == sizeof(short))
860 #endif /* ndef _WIN32 */
862 inaddr.sin_port = htons((unsigned short) portnum);
867 inaddr.sin_port = htonl((unsigned long) portnum);
869 #endif /* ndef _WIN32 */
870 #endif /* def HAVE_RFC2553 */
873 for (rp = result; rp != NULL; rp = rp->ai_next)
875 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
877 fd = socket(AF_INET, SOCK_STREAM, 0);
878 #endif /* def HAVE_RFC2553 */
881 if (fd == JB_INVALID_SOCKET)
895 * This is not needed for Win32 - in fact, it stops
896 * duplicate instances of Privoxy from being caught.
898 * On UNIX, we assume the user is sensible enough not
899 * to start Privoxy multiple times on the same IP.
900 * Without this, stopping and restarting Privoxy
901 * from a script fails.
902 * Note: SO_REUSEADDR is meant to only take over
903 * sockets which are *not* in listen state in Linux,
904 * e.g. sockets in TIME_WAIT. YMMV.
906 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
907 #endif /* ndef _WIN32 */
910 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
912 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
916 errno = WSAGetLastError();
917 if (errno == WSAEADDRINUSE)
919 if (errno == EADDRINUSE)
923 freeaddrinfo(result);
940 /* bind() succeeded, escape from for-loop */
942 * XXX: Support multiple listening sockets (e.g. localhost
943 * resolves to AF_INET and AF_INET6, but only the first address
950 freeaddrinfo(result);
953 /* All bind()s failed */
956 #endif /* ndef HAVE_RFC2553 */
958 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
972 /*********************************************************************
974 * Function : get_host_information
976 * Description : Determines the IP address the client used to
977 * reach us and the hostname associated with it.
979 * XXX: Most of the code has been copy and pasted
980 * from accept_connection() and not all of the
981 * ifdefs paths have been tested afterwards.
984 * 1 : afd = File descriptor returned from accept().
985 * 2 : ip_address = Pointer to return the pointer to
986 * the ip address string.
987 * 3 : port = Pointer to return the pointer to
988 * the TCP port string.
989 * 4 : hostname = Pointer to return the pointer to
990 * the hostname or NULL if the caller
991 * isn't interested in it.
995 *********************************************************************/
996 void get_host_information(jb_socket afd, char **ip_address, char **port,
1000 struct sockaddr_storage server;
1003 struct sockaddr_in server;
1004 struct hostent *host = NULL;
1005 #endif /* HAVE_RFC2553 */
1006 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1007 /* according to accept_connection() this fixes a warning. */
1008 int s_length, s_length_provided;
1010 socklen_t s_length, s_length_provided;
1012 #ifndef HAVE_RFC2553
1013 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1014 struct hostent result;
1015 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1016 struct hostent_data hdata;
1018 char hbuf[HOSTENT_BUFFER_SIZE];
1020 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
1021 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
1022 #endif /* ifndef HAVE_RFC2553 */
1023 s_length = s_length_provided = sizeof(server);
1025 if (NULL != hostname)
1032 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
1034 if (s_length > s_length_provided)
1036 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
1040 * XXX: Workaround for missing header on Windows when
1041 * configured with --disable-ipv6-support.
1042 * The proper fix is to not use NI_MAXSERV in
1043 * that case. It works by accident on other platforms
1044 * as <netdb.h> in included unconditionally there.
1047 #define NI_MAXSERV 32
1049 *port = malloc(NI_MAXSERV);
1052 log_error(LOG_LEVEL_ERROR,
1053 "Out of memory while getting the client's port.");
1057 *ip_address = malloc(NI_MAXHOST);
1058 if (NULL == *ip_address)
1060 log_error(LOG_LEVEL_ERROR,
1061 "Out of memory while getting the client's IP address.");
1065 retval = getnameinfo((struct sockaddr *) &server, s_length,
1066 *ip_address, NI_MAXHOST, *port, NI_MAXSERV,
1067 NI_NUMERICHOST|NI_NUMERICSERV);
1070 log_error(LOG_LEVEL_ERROR,
1071 "Unable to print my own IP address: %s", gai_strerror(retval));
1077 *ip_address = strdup(inet_ntoa(server.sin_addr));
1078 snprintf(*port, NI_MAXSERV, "%hu", ntohs(server.sin_port));
1079 #endif /* HAVE_RFC2553 */
1080 if (NULL == hostname)
1083 * We're done here, the caller isn't
1084 * interested in knowing the hostname.
1090 *hostname = malloc(NI_MAXHOST);
1091 if (NULL == *hostname)
1093 log_error(LOG_LEVEL_ERROR,
1094 "Out of memory while getting the client's hostname.");
1097 retval = getnameinfo((struct sockaddr *) &server, s_length,
1098 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
1101 log_error(LOG_LEVEL_ERROR,
1102 "Unable to resolve my own IP address: %s", gai_strerror(retval));
1106 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
1107 gethostbyaddr_r((const char *)&server.sin_addr,
1108 sizeof(server.sin_addr), AF_INET,
1109 &result, hbuf, HOSTENT_BUFFER_SIZE,
1111 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
1112 host = gethostbyaddr_r((const char *)&server.sin_addr,
1113 sizeof(server.sin_addr), AF_INET,
1114 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
1115 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
1116 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
1117 sizeof(server.sin_addr), AF_INET,
1126 #elif defined(MUTEX_LOCKS_AVAILABLE)
1127 privoxy_mutex_lock(&resolver_mutex);
1128 host = gethostbyaddr((const char *)&server.sin_addr,
1129 sizeof(server.sin_addr), AF_INET);
1130 privoxy_mutex_unlock(&resolver_mutex);
1132 host = gethostbyaddr((const char *)&server.sin_addr,
1133 sizeof(server.sin_addr), AF_INET);
1137 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1141 *hostname = strdup(host->h_name);
1143 #endif /* else def HAVE_RFC2553 */
1150 /*********************************************************************
1152 * Function : accept_connection
1154 * Description : Accepts a connection on one of possibly multiple
1155 * sockets. The socket(s) to check must have been
1156 * created using bind_port().
1159 * 1 : csp = Client state, cfd, ip_addr_str, and
1160 * ip_addr_long will be set by this routine.
1161 * 2 : fds = File descriptors returned from bind_port
1163 * Returns : when a connection is accepted, it returns 1 (TRUE).
1164 * On an error it returns 0 (FALSE).
1166 *********************************************************************/
1167 int accept_connection(struct client_state * csp, jb_socket fds[])
1170 /* XXX: client is stored directly into csp->tcp_addr */
1171 #define client (csp->tcp_addr)
1173 struct sockaddr_in client;
1176 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1177 /* Wierdness - fix a warning. */
1184 int max_selected_socket;
1185 fd_set selected_fds;
1188 c_length = sizeof(client);
1191 * Wait for a connection on any socket.
1192 * Return immediately if no socket is listening.
1193 * XXX: Why not treat this as fatal error?
1195 FD_ZERO(&selected_fds);
1196 max_selected_socket = 0;
1197 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
1199 if (JB_INVALID_SOCKET != fds[i])
1201 FD_SET(fds[i], &selected_fds);
1202 if (max_selected_socket < fds[i] + 1)
1204 max_selected_socket = fds[i] + 1;
1208 if (0 == max_selected_socket)
1214 retval = select(max_selected_socket, &selected_fds, NULL, NULL, NULL);
1215 } while (retval < 0 && errno == EINTR);
1220 log_error(LOG_LEVEL_ERROR,
1221 "Waiting on new client failed because select(2) returned 0."
1222 " This should not happen.");
1226 log_error(LOG_LEVEL_ERROR,
1227 "Waiting on new client failed because of problems in select(2): "
1228 "%s.", strerror(errno));
1232 for (i = 0; i < MAX_LISTENING_SOCKETS && !FD_ISSET(fds[i], &selected_fds);
1234 if (i >= MAX_LISTENING_SOCKETS)
1236 log_error(LOG_LEVEL_ERROR,
1237 "select(2) reported connected clients (number = %u, "
1238 "descriptor boundary = %u), but none found.",
1239 retval, max_selected_socket);
1244 /* Accept selected connection */
1246 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1247 if (afd == JB_INVALID_SOCKET)
1254 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1255 struct accept_filter_arg af_options;
1256 bzero(&af_options, sizeof(af_options));
1257 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1258 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1260 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1261 } while (afd < 1 && errno == EINTR);
1270 struct linger linger_options;
1271 linger_options.l_onoff = 1;
1272 linger_options.l_linger = 5;
1273 if (0 != setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger_options, sizeof(linger_options)))
1275 log_error(LOG_LEVEL_ERROR, "Setting SO_LINGER on socket %d failed.", afd);
1282 csp->ip_addr_str = malloc(NI_MAXHOST);
1283 if (NULL == csp->ip_addr_str)
1285 log_error(LOG_LEVEL_ERROR,
1286 "Out of memory while getting the client's IP address.");
1289 retval = getnameinfo((struct sockaddr *) &client, c_length,
1290 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1291 if (!csp->ip_addr_str || retval)
1293 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1294 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1295 freez(csp->ip_addr_str);
1299 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1300 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1301 #endif /* def HAVE_RFC2553 */
1308 /*********************************************************************
1310 * Function : resolve_hostname_to_ip
1312 * Description : Resolve a hostname to an internet tcp/ip address.
1313 * NULL or an empty string resolve to INADDR_ANY.
1316 * 1 : host = hostname to resolve
1318 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if successful.
1320 *********************************************************************/
1321 unsigned long resolve_hostname_to_ip(const char *host)
1323 struct sockaddr_in inaddr;
1324 struct hostent *hostp;
1325 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1326 struct hostent result;
1327 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1328 char hbuf[HOSTENT_BUFFER_SIZE];
1330 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1331 struct hostent_data hdata;
1332 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1333 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1335 if ((host == NULL) || (*host == '\0'))
1340 memset((char *) &inaddr, 0, sizeof inaddr);
1342 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1344 unsigned int dns_retries = 0;
1345 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1346 while (gethostbyname_r(host, &result, hbuf,
1347 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1348 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1350 log_error(LOG_LEVEL_ERROR,
1351 "Timeout #%u while trying to resolve %s. Trying again.",
1354 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1355 while (NULL == (hostp = gethostbyname_r(host, &result,
1356 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1357 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1359 log_error(LOG_LEVEL_ERROR,
1360 "Timeout #%u while trying to resolve %s. Trying again.",
1363 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1365 * XXX: Doesn't retry in case of soft errors.
1366 * Does this gethostbyname_r version set h_errno?
1368 if (0 == gethostbyname_r(host, &result, &hdata))
1376 #elif defined(MUTEX_LOCKS_AVAILABLE)
1377 privoxy_mutex_lock(&resolver_mutex);
1378 while (NULL == (hostp = gethostbyname(host))
1379 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1381 log_error(LOG_LEVEL_ERROR,
1382 "Timeout #%u while trying to resolve %s. Trying again.",
1385 privoxy_mutex_unlock(&resolver_mutex);
1387 while (NULL == (hostp = gethostbyname(host))
1388 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1390 log_error(LOG_LEVEL_ERROR,
1391 "Timeout #%u while trying to resolve %s. Trying again.",
1394 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1396 * On Mac OSX, if a domain exists but doesn't have a type A
1397 * record associated with it, the h_addr member of the struct
1398 * hostent returned by gethostbyname is NULL, even if h_length
1399 * is 4. Therefore the second test below.
1401 if (hostp == NULL || hostp->h_addr == NULL)
1404 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1405 return(INADDR_NONE);
1407 if (hostp->h_addrtype != AF_INET)
1410 errno = WSAEPROTOTYPE;
1414 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1415 return(INADDR_NONE);
1417 memcpy((char *)&inaddr.sin_addr, (char *)hostp->h_addr, sizeof(inaddr.sin_addr));
1419 return(inaddr.sin_addr.s_addr);
1424 /*********************************************************************
1426 * Function : socket_is_still_alive
1428 * Description : Figures out whether or not a socket is still alive.
1431 * 1 : sfd = The socket to check.
1433 * Returns : TRUE for yes, otherwise FALSE.
1435 *********************************************************************/
1436 int socket_is_still_alive(jb_socket sfd)
1439 int no_data_waiting;
1443 struct pollfd poll_fd[1];
1445 memset(poll_fd, 0, sizeof(poll_fd));
1446 poll_fd[0].fd = sfd;
1447 poll_fd[0].events = POLLIN;
1449 poll_result = poll(poll_fd, 1, 0);
1451 if (-1 == poll_result)
1453 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1456 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1458 fd_set readable_fds;
1459 struct timeval timeout;
1462 memset(&timeout, '\0', sizeof(timeout));
1463 FD_ZERO(&readable_fds);
1464 FD_SET(sfd, &readable_fds);
1466 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1469 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1472 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1473 #endif /* def HAVE_POLL */
1475 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));