1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.79 2010/07/26 11:30:09 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-2010 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 */
86 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
94 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
98 /* For mutex semaphores only */
101 #include "jbsockets.h"
105 /* Mac OSX doesn't define AI_NUMERICSESRV */
106 #ifndef AI_NUMERICSERV
107 #define AI_NUMERICSERV 0
110 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
113 * Maximum number of gethostbyname(_r) retries in case of
114 * soft errors (TRY_AGAIN).
115 * XXX: Does it make sense to make this a config option?
117 #define MAX_DNS_RETRIES 10
119 #define MAX_LISTEN_BACKLOG 128
122 /*********************************************************************
124 * Function : connect_to
126 * Description : Open a socket and connect to it. Will check
127 * that this is allowed according to ACL.
130 * 1 : host = hostname to connect to
131 * 2 : portnum = port to connent on (XXX: should be unsigned)
132 * 3 : csp = Current client state (buffers, headers, etc...)
134 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
137 *********************************************************************/
139 /* Getaddrinfo implementation */
140 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
142 struct addrinfo hints, *result, *rp;
147 struct timeval tv[1];
148 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
154 struct access_control_addr dst[1];
155 #endif /* def FEATURE_ACL */
157 retval = snprintf(service, sizeof(service), "%d", portnum);
158 if ((-1 == retval) || (sizeof(service) <= retval))
160 log_error(LOG_LEVEL_ERROR,
161 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
163 csp->http->host_ip_addr_str = strdup("unknown");
164 return(JB_INVALID_SOCKET);
167 memset((char *)&hints, 0, sizeof(hints));
168 hints.ai_family = AF_UNSPEC;
169 hints.ai_socktype = SOCK_STREAM;
170 hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
172 hints.ai_flags |= AI_ADDRCONFIG;
174 if ((retval = getaddrinfo(host, service, &hints, &result)))
176 log_error(LOG_LEVEL_INFO,
177 "Can not resolve %s: %s", host, gai_strerror(retval));
178 /* XXX: Should find a better way to propagate this error. */
180 csp->http->host_ip_addr_str = strdup("unknown");
181 return(JB_INVALID_SOCKET);
184 for (rp = result; rp != NULL; rp = rp->ai_next)
188 memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
190 if (block_acl(dst, csp))
199 #endif /* def FEATURE_ACL */
201 csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
202 if (NULL == csp->http->host_ip_addr_str)
204 log_error(LOG_LEVEL_ERROR,
205 "Out of memory while getting the server IP address.");
206 return JB_INVALID_SOCKET;
208 retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
209 csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
210 if (!csp->http->host_ip_addr_str || retval)
212 log_error(LOG_LEVEL_ERROR,
213 "Can not save csp->http->host_ip_addr_str: %s",
214 (csp->http->host_ip_addr_str) ?
215 gai_strerror(retval) : "Insufficient memory");
216 freez(csp->http->host_ip_addr_str);
221 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
224 if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
231 { /* turn off TCP coalescence */
233 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
235 #endif /* def TCP_NODELAY */
237 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
238 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
241 fcntl(fd, F_SETFL, flags);
243 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
246 while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
249 if (errno == WSAEINPROGRESS)
251 if (sock_errno() == EINPROGRESS)
252 #else /* ifndef _WIN32 */
253 if (errno == EINPROGRESS)
254 #endif /* ndef _WIN32 || __OS2__ */
260 if (sock_errno() != EINTR)
275 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
279 fcntl(fd, F_SETFL, flags);
281 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
283 /* wait for connection to complete */
290 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
291 if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
292 && FD_ISSET(fd, &wfds))
295 * See Linux connect(2) man page for more info
296 * about connecting on non-blocking socket.
299 socklen_t optlen = sizeof(socket_in_error);
300 if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
302 if (!socket_in_error)
304 /* Connection established, no need to try other addresses. */
307 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
308 csp->http->host_ip_addr_str, service, strerror(socket_in_error));
312 log_error(LOG_LEVEL_ERROR, "Could not get the state of "
313 "the connection to [%s]:%s: %s; dropping connection.",
314 csp->http->host_ip_addr_str, service, strerror(errno));
318 /* Connection failed, try next address */
322 freeaddrinfo(result);
325 log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s.",
327 return(JB_INVALID_SOCKET);
329 log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
330 host, csp->http->host_ip_addr_str, service);
336 #else /* ndef HAVE_RFC2553 */
337 /* Pre-getaddrinfo implementation */
339 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
341 struct sockaddr_in inaddr;
345 struct timeval tv[1];
346 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
351 struct access_control_addr dst[1];
352 #endif /* def FEATURE_ACL */
354 memset((char *)&inaddr, 0, sizeof inaddr);
356 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
358 csp->http->host_ip_addr_str = strdup("unknown");
359 return(JB_INVALID_SOCKET);
363 dst->addr = ntohl(addr);
366 if (block_acl(dst, csp))
373 return(JB_INVALID_SOCKET);
375 #endif /* def FEATURE_ACL */
377 inaddr.sin_addr.s_addr = addr;
378 inaddr.sin_family = AF_INET;
379 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
382 if (sizeof(inaddr.sin_port) == sizeof(short))
383 #endif /* ndef _WIN32 */
385 inaddr.sin_port = htons((unsigned short) portnum);
390 inaddr.sin_port = htonl((unsigned long)portnum);
392 #endif /* ndef _WIN32 */
395 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
397 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
400 return(JB_INVALID_SOCKET);
404 { /* turn off TCP coalescence */
406 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
408 #endif /* def TCP_NODELAY */
410 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
411 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
414 fcntl(fd, F_SETFL, flags);
416 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
418 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
421 if (errno == WSAEINPROGRESS)
423 if (sock_errno() == EINPROGRESS)
424 #else /* ifndef _WIN32 */
425 if (errno == EINPROGRESS)
426 #endif /* ndef _WIN32 || __OS2__ */
432 if (sock_errno() != EINTR)
438 return(JB_INVALID_SOCKET);
442 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
446 fcntl(fd, F_SETFL, flags);
448 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
450 /* wait for connection to complete */
457 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
458 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
461 return(JB_INVALID_SOCKET);
466 #endif /* ndef HAVE_RFC2553 */
469 /*********************************************************************
471 * Function : write_socket
473 * Description : Write the contents of buf (for n bytes) to socket fd.
476 * 1 : fd = file descriptor (aka. handle) of socket to write to.
477 * 2 : buf = pointer to data to be written.
478 * 3 : len = length of data to be written to the socket "fd".
480 * Returns : 0 on success (entire buffer sent).
483 *********************************************************************/
485 int write_socket(jb_socket fd, const char *buf, ssize_t len)
487 int write_socket(jb_socket fd, const char *buf, size_t len)
495 if (len < 0) /* constant condition - size_t isn't ever negative */
500 log_error(LOG_LEVEL_WRITING, "to socket %d: %N", fd, len, buf);
503 return (send(fd, buf, (int)len, 0) != (int)len);
504 #elif defined(__BEOS__) || defined(AMIGA)
505 return (send(fd, buf, len, 0) != len);
506 #elif defined(__OS2__)
508 * Break the data up into SOCKET_SEND_MAX chunks for sending...
509 * OS/2 seemed to complain when the chunks were too large.
511 #define SOCKET_SEND_MAX 65000
513 int send_len, send_rc = 0, i = 0;
514 while ((i < len) && (send_rc != -1))
516 if ((i + SOCKET_SEND_MAX) > len)
519 send_len = SOCKET_SEND_MAX;
520 send_rc = send(fd,(char*)buf + i, send_len, 0);
528 return (write(fd, buf, len) != len);
534 /*********************************************************************
536 * Function : read_socket
538 * Description : Read from a TCP/IP socket in a platform independent way.
541 * 1 : fd = file descriptor of the socket to read
542 * 2 : buf = pointer to buffer where data will be written
543 * Must be >= len bytes long.
544 * 3 : len = maximum number of bytes to read
546 * Returns : On success, the number of bytes read is returned (zero
547 * indicates end of file), and the file position is advanced
548 * by this number. It is not an error if this number is
549 * smaller than the number of bytes requested; this may hap-
550 * pen for example because fewer bytes are actually available
551 * right now (maybe because we were close to end-of-file, or
552 * because we are reading from a pipe, or from a terminal,
553 * or because read() was interrupted by a signal). On error,
554 * -1 is returned, and errno is set appropriately. In this
555 * case it is left unspecified whether the file position (if
558 *********************************************************************/
559 int read_socket(jb_socket fd, char *buf, int len)
569 ret = recv(fd, buf, len, 0);
570 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
571 ret = recv(fd, buf, (size_t)len, 0);
573 ret = (int)read(fd, buf, (size_t)len);
578 log_error(LOG_LEVEL_RECEIVED, "from socket %d: %N", fd, ret, buf);
585 /*********************************************************************
587 * Function : data_is_available
589 * Description : Waits for data to arrive on a socket.
592 * 1 : fd = file descriptor of the socket to read
593 * 2 : seconds_to_wait = number of seconds after which we give up.
595 * Returns : TRUE if data arrived in time,
598 *********************************************************************/
599 int data_is_available(jb_socket fd, int seconds_to_wait)
603 struct timeval timeout;
606 memset(&timeout, 0, sizeof(timeout));
607 timeout.tv_sec = seconds_to_wait;
610 /* Copy and pasted from jcc.c ... */
611 memset(&rfds, 0, sizeof(fd_set));
617 n = select(fd+1, &rfds, NULL, NULL, &timeout);
620 * XXX: Do we care about the different error conditions?
622 return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
626 /*********************************************************************
628 * Function : close_socket
630 * Description : Closes a TCP/IP socket
633 * 1 : fd = file descriptor of socket to be closed
637 *********************************************************************/
638 void close_socket(jb_socket fd)
640 #if defined(_WIN32) || defined(__BEOS__)
644 #elif defined(__OS2__)
653 /*********************************************************************
655 * Function : bind_port
657 * Description : Call socket, set socket options, and listen.
658 * Called by listen_loop to "boot up" our proxy address.
661 * 1 : hostnam = TCP/IP address to bind/listen to
662 * 2 : portnum = port to listen on
663 * 3 : pfd = pointer used to return file descriptor.
665 * Returns : if success, returns 0 and sets *pfd.
666 * if failure, returns -3 if address is in use,
667 * -2 if address unresolvable,
669 *********************************************************************/
670 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
673 struct addrinfo hints;
674 struct addrinfo *result, *rp;
676 * XXX: portnum should be a string to allow symbolic service
677 * names in the configuration file and to avoid the following
683 struct sockaddr_in inaddr;
684 #endif /* def HAVE_RFC2553 */
688 #endif /* ndef _WIN32 */
690 *pfd = JB_INVALID_SOCKET;
693 retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
694 if ((-1 == retval) || (sizeof(servnam) <= retval))
696 log_error(LOG_LEVEL_ERROR,
697 "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
702 memset(&hints, 0, sizeof(struct addrinfo));
706 * XXX: This is a hack. The right thing to do
707 * would be to bind to both AF_INET and AF_INET6.
708 * This will also fail if there is no AF_INET
711 hints.ai_family = AF_INET;
715 hints.ai_family = AF_UNSPEC;
717 hints.ai_socktype = SOCK_STREAM;
718 hints.ai_flags = AI_PASSIVE;
720 hints.ai_flags |= AI_ADDRCONFIG;
722 hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
723 hints.ai_canonname = NULL;
724 hints.ai_addr = NULL;
725 hints.ai_next = NULL;
727 if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
729 log_error(LOG_LEVEL_ERROR,
730 "Can not resolve %s: %s", hostnam, gai_strerror(retval));
734 memset((char *)&inaddr, '\0', sizeof inaddr);
736 inaddr.sin_family = AF_INET;
737 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
739 if (inaddr.sin_addr.s_addr == INADDR_NONE)
745 if (sizeof(inaddr.sin_port) == sizeof(short))
746 #endif /* ndef _WIN32 */
748 inaddr.sin_port = htons((unsigned short) portnum);
753 inaddr.sin_port = htonl((unsigned long) portnum);
755 #endif /* ndef _WIN32 */
756 #endif /* def HAVE_RFC2553 */
759 for (rp = result; rp != NULL; rp = rp->ai_next)
761 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
763 fd = socket(AF_INET, SOCK_STREAM, 0);
764 #endif /* def HAVE_RFC2553 */
767 if (fd == JB_INVALID_SOCKET)
781 * This is not needed for Win32 - in fact, it stops
782 * duplicate instances of Privoxy from being caught.
784 * On UNIX, we assume the user is sensible enough not
785 * to start Privoxy multiple times on the same IP.
786 * Without this, stopping and restarting Privoxy
787 * from a script fails.
788 * Note: SO_REUSEADDR is meant to only take over
789 * sockets which are *not* in listen state in Linux,
790 * e.g. sockets in TIME_WAIT. YMMV.
792 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
793 #endif /* ndef _WIN32 */
796 if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
798 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
802 errno = WSAGetLastError();
803 if (errno == WSAEADDRINUSE)
805 if (errno == EADDRINUSE)
809 freeaddrinfo(result);
826 /* bind() succeeded, escape from for-loop */
828 * XXX: Support multiple listening sockets (e.g. localhost
829 * resolves to AF_INET and AF_INET6, but only the first address
836 freeaddrinfo(result);
839 /* All bind()s failed */
842 #endif /* ndef HAVE_RFC2553 */
844 while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
858 /*********************************************************************
860 * Function : get_host_information
862 * Description : Determines the IP address the client used to
863 * reach us and the hostname associated with it.
865 * XXX: Most of the code has been copy and pasted
866 * from accept_connection() and not all of the
867 * ifdefs paths have been tested afterwards.
870 * 1 : afd = File descriptor returned from accept().
871 * 2 : ip_address = Pointer to return the pointer to
872 * the ip address string.
873 * 3 : hostname = Pointer to return the pointer to
874 * the hostname or NULL if the caller
875 * isn't interested in it.
879 *********************************************************************/
880 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
883 struct sockaddr_storage server;
886 struct sockaddr_in server;
887 struct hostent *host = NULL;
888 #endif /* HAVE_RFC2553 */
889 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
890 /* according to accept_connection() this fixes a warning. */
891 int s_length, s_length_provided;
893 socklen_t s_length, s_length_provided;
896 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
897 struct hostent result;
898 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
899 struct hostent_data hdata;
901 char hbuf[HOSTENT_BUFFER_SIZE];
903 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
904 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
905 #endif /* ifndef HAVE_RFC2553 */
906 s_length = s_length_provided = sizeof(server);
908 if (NULL != hostname)
914 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
916 if (s_length > s_length_provided)
918 log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
922 *ip_address = malloc(NI_MAXHOST);
923 if (NULL == *ip_address)
925 log_error(LOG_LEVEL_ERROR,
926 "Out of memory while getting the client's IP address.");
929 retval = getnameinfo((struct sockaddr *) &server, s_length,
930 *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
933 log_error(LOG_LEVEL_ERROR,
934 "Unable to print my own IP address: %s", gai_strerror(retval));
939 *ip_address = strdup(inet_ntoa(server.sin_addr));
940 #endif /* HAVE_RFC2553 */
941 if (NULL == hostname)
944 * We're done here, the caller isn't
945 * interested in knowing the hostname.
951 *hostname = malloc(NI_MAXHOST);
952 if (NULL == *hostname)
954 log_error(LOG_LEVEL_ERROR,
955 "Out of memory while getting the client's hostname.");
958 retval = getnameinfo((struct sockaddr *) &server, s_length,
959 *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
962 log_error(LOG_LEVEL_ERROR,
963 "Unable to resolve my own IP address: %s", gai_strerror(retval));
967 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
968 gethostbyaddr_r((const char *)&server.sin_addr,
969 sizeof(server.sin_addr), AF_INET,
970 &result, hbuf, HOSTENT_BUFFER_SIZE,
972 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
973 host = gethostbyaddr_r((const char *)&server.sin_addr,
974 sizeof(server.sin_addr), AF_INET,
975 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
976 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
977 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
978 sizeof(server.sin_addr), AF_INET,
987 #elif defined(MUTEX_LOCKS_AVAILABLE)
988 privoxy_mutex_lock(&resolver_mutex);
989 host = gethostbyaddr((const char *)&server.sin_addr,
990 sizeof(server.sin_addr), AF_INET);
991 privoxy_mutex_unlock(&resolver_mutex);
993 host = gethostbyaddr((const char *)&server.sin_addr,
994 sizeof(server.sin_addr), AF_INET);
998 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
1002 *hostname = strdup(host->h_name);
1004 #endif /* else def HAVE_RFC2553 */
1011 /*********************************************************************
1013 * Function : accept_connection
1015 * Description : Accepts a connection on a socket. Socket must have
1016 * been created using bind_port().
1019 * 1 : csp = Client state, cfd, ip_addr_str, and
1020 * ip_addr_long will be set by this routine.
1021 * 2 : fd = file descriptor returned from bind_port
1023 * Returns : when a connection is accepted, it returns 1 (TRUE).
1024 * On an error it returns 0 (FALSE).
1026 *********************************************************************/
1027 int accept_connection(struct client_state * csp, jb_socket fd)
1030 /* XXX: client is stored directly into csp->tcp_addr */
1031 #define client (csp->tcp_addr)
1034 struct sockaddr_in client;
1037 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1038 /* Wierdness - fix a warning. */
1044 c_length = sizeof(client);
1047 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1048 if (afd == JB_INVALID_SOCKET)
1055 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1056 struct accept_filter_arg af_options;
1057 bzero(&af_options, sizeof(af_options));
1058 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1059 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1061 afd = accept (fd, (struct sockaddr *) &client, &c_length);
1062 } while (afd < 1 && errno == EINTR);
1071 csp->ip_addr_str = malloc(NI_MAXHOST);
1072 if (NULL == csp->ip_addr_str)
1074 log_error(LOG_LEVEL_ERROR,
1075 "Out of memory while getting the client's IP address.");
1078 retval = getnameinfo((struct sockaddr *) &client, c_length,
1079 csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1080 if (!csp->ip_addr_str || retval)
1082 log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1083 (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1084 freez(csp->ip_addr_str);
1088 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
1089 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1090 #endif /* def HAVE_RFC2553 */
1097 /*********************************************************************
1099 * Function : resolve_hostname_to_ip
1101 * Description : Resolve a hostname to an internet tcp/ip address.
1102 * NULL or an empty string resolve to INADDR_ANY.
1105 * 1 : host = hostname to resolve
1107 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1109 *********************************************************************/
1110 unsigned long resolve_hostname_to_ip(const char *host)
1112 struct sockaddr_in inaddr;
1113 struct hostent *hostp;
1114 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1115 struct hostent result;
1116 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1117 char hbuf[HOSTENT_BUFFER_SIZE];
1119 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1120 struct hostent_data hdata;
1121 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1122 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1124 if ((host == NULL) || (*host == '\0'))
1129 memset((char *) &inaddr, 0, sizeof inaddr);
1131 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1133 unsigned int dns_retries = 0;
1134 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1135 while (gethostbyname_r(host, &result, hbuf,
1136 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1137 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1139 log_error(LOG_LEVEL_ERROR,
1140 "Timeout #%u while trying to resolve %s. Trying again.",
1143 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1144 while (NULL == (hostp = gethostbyname_r(host, &result,
1145 hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1146 && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1148 log_error(LOG_LEVEL_ERROR,
1149 "Timeout #%u while trying to resolve %s. Trying again.",
1152 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1154 * XXX: Doesn't retry in case of soft errors.
1155 * Does this gethostbyname_r version set h_errno?
1157 if (0 == gethostbyname_r(host, &result, &hdata))
1165 #elif defined(MUTEX_LOCKS_AVAILABLE)
1166 privoxy_mutex_lock(&resolver_mutex);
1167 while (NULL == (hostp = gethostbyname(host))
1168 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1170 log_error(LOG_LEVEL_ERROR,
1171 "Timeout #%u while trying to resolve %s. Trying again.",
1174 privoxy_mutex_unlock(&resolver_mutex);
1176 while (NULL == (hostp = gethostbyname(host))
1177 && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1179 log_error(LOG_LEVEL_ERROR,
1180 "Timeout #%u while trying to resolve %s. Trying again.",
1183 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1185 * On Mac OSX, if a domain exists but doesn't have a type A
1186 * record associated with it, the h_addr member of the struct
1187 * hostent returned by gethostbyname is NULL, even if h_length
1188 * is 4. Therefore the second test below.
1190 if (hostp == NULL || hostp->h_addr == NULL)
1193 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1194 return(INADDR_NONE);
1196 if (hostp->h_addrtype != AF_INET)
1199 errno = WSAEPROTOTYPE;
1203 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1204 return(INADDR_NONE);
1207 (char *) &inaddr.sin_addr,
1208 (char *) hostp->h_addr,
1209 sizeof(inaddr.sin_addr)
1212 return(inaddr.sin_addr.s_addr);
1217 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1218 /*********************************************************************
1220 * Function : socket_is_still_alive
1222 * Description : Figures out whether or not a socket is still alive.
1225 * 1 : sfd = The socket to check.
1227 * Returns : TRUE for yes, otherwise FALSE.
1229 *********************************************************************/
1230 int socket_is_still_alive(jb_socket sfd)
1233 int no_data_waiting;
1237 struct pollfd poll_fd[1];
1239 memset(poll_fd, 0, sizeof(poll_fd));
1240 poll_fd[0].fd = sfd;
1241 poll_fd[0].events = POLLIN;
1243 poll_result = poll(poll_fd, 1, 0);
1245 if (-1 == poll_result)
1247 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1250 no_data_waiting = !(poll_fd[0].revents & POLLIN);
1252 fd_set readable_fds;
1253 struct timeval timeout;
1256 memset(&timeout, '\0', sizeof(timeout));
1257 FD_ZERO(&readable_fds);
1258 FD_SET(sfd, &readable_fds);
1260 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1263 log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1266 no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1267 #endif /* def HAVE_POLL */
1269 return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1271 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */