1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.35.2.5 2003/04/29 11:32:54 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/Attic/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 the SourceForge
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.
37 * $Log: jbsockets.c,v $
38 * Revision 1.35.2.5 2003/04/29 11:32:54 oes
39 * Don't rely on h_addr being non-NULL after gethostbyname.
40 * Works around an oddness in Max OSX and closes bug #724796
42 * Revision 1.35.2.4 2003/04/04 12:40:20 oes
43 * Made sure the errno set by bind, not close[socket] is used in
44 * bind_port. Probably fixes bugs #713777, #705562.
46 * Revision 1.35.2.3 2003/03/07 03:41:04 david__schmidt
47 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
49 * Revision 1.35.2.2 2002/11/20 14:37:24 oes
50 * Fixed Win32 error logging in bind_port.
51 * Thanks to Oliver Stoeneberg for the hint.
53 * Revision 1.35.2.1 2002/05/26 23:41:27 joergs
54 * AmigaOS: Fixed wrong type of len in write_socket()
56 * Revision 1.35 2002/04/26 15:50:04 joergs
57 * AmigaOS: No socklen_t, added AMIGA to the systems using int instead.
59 * Revision 1.34 2002/04/08 20:31:41 swa
62 * Revision 1.33 2002/04/03 16:02:18 gliptak
63 * Correcting compile warning with older gcc
65 * Revision 1.32 2002/03/31 17:18:59 jongfoster
66 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
68 * Revision 1.31 2002/03/29 03:33:13 david__schmidt
69 * Fix Mac OSX compiler warnings
71 * Revision 1.30 2002/03/27 14:32:43 david__schmidt
72 * More compiler warning message maintenance
74 * Revision 1.29 2002/03/26 22:29:54 swa
75 * we have a new homepage!
77 * Revision 1.28 2002/03/24 13:25:43 swa
78 * name change related issues
80 * Revision 1.27 2002/03/13 00:27:05 jongfoster
83 * Revision 1.26 2002/03/11 22:07:02 david__schmidt
84 * OS/2 port maintenance:
85 * - Fixed EMX build - it had decayed a little
86 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
87 * substituted a memset for now.
89 * Revision 1.25 2002/03/09 20:03:52 jongfoster
90 * - Making various functions return int rather than size_t.
91 * (Undoing a recent change). Since size_t is unsigned on
92 * Windows, functions like read_socket that return -1 on
93 * error cannot return a size_t.
95 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
96 * crashes, and also frequently caused JB to jump to 100%
97 * CPU and stay there. (Because it thought it had just
98 * read ((unsigned)-1) == 4Gb of data...)
100 * - The signature of write_socket has changed, it now simply
101 * returns success=0/failure=nonzero.
103 * - Trying to get rid of a few warnings --with-debug on
104 * Windows, I've introduced a new type "jb_socket". This is
105 * used for the socket file descriptors. On Windows, this
106 * is SOCKET (a typedef for unsigned). Everywhere else, it's
107 * an int. The error value can't be -1 any more, so it's
108 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
109 * Windows it maps to the #define INVALID_SOCKET.)
111 * - The signature of bind_port has changed.
113 * Revision 1.24 2002/03/07 03:51:36 oes
114 * - Improved handling of failed DNS lookups
115 * - Fixed compiler warnings etc
117 * Revision 1.23 2002/03/05 00:36:01 jongfoster
118 * Fixing bug 514988 - unable to restart Junkbuster
120 * Revision 1.22 2002/03/04 02:08:02 david__schmidt
121 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
123 * Revision 1.21 2002/01/09 14:32:33 oes
124 * Added support for gethostbyname_r and gethostbyaddr_r.
126 * Revision 1.20 2001/11/16 00:48:48 jongfoster
127 * Enabling duplicate-socket detection for all platforms, not
130 * Revision 1.19 2001/10/25 03:40:47 david__schmidt
131 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
132 * threads to call select() simultaneously. So, it's time to do a real, live,
133 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
134 * (native). Both versions will work, but using __OS2__ offers multi-threading.
136 * Revision 1.18 2001/09/21 23:02:02 david__schmidt
137 * Cleaning up 2 compiler warnings on OS/2.
139 * Revision 1.17 2001/09/13 20:11:46 jongfoster
140 * Fixing 2 compiler warnings under Win32
142 * Revision 1.16 2001/07/30 22:08:36 jongfoster
143 * Tidying up #defines:
144 * - All feature #defines are now of the form FEATURE_xxx
145 * - Permanently turned off WIN_GUI_EDIT
146 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
148 * Revision 1.15 2001/07/29 17:40:43 jongfoster
149 * Fixed compiler warning by adding a cast
151 * Revision 1.14 2001/07/18 13:47:59 oes
152 * Eliminated dirty hack for getsockbyname()
154 * Revision 1.13 2001/07/15 13:56:57 jongfoster
155 * Removing unused local variable.
157 * Revision 1.12 2001/07/01 17:04:11 oes
158 * Bugfix: accept_connection no longer uses the obsolete hstrerror() function
160 * Revision 1.11 2001/06/29 21:45:41 oes
161 * Indentation, CRLF->LF, Tab-> Space
163 * Revision 1.10 2001/06/29 13:29:15 oes
164 * - Added remote (server) host IP to csp->http->host_ip_addr_str
165 * - Added detection of local socket IP and fqdn
166 * - Removed logentry from cancelled commit
168 * Revision 1.9 2001/06/07 23:06:09 jongfoster
169 * The host parameter to connect_to() is now const.
171 * Revision 1.8 2001/06/03 19:12:07 oes
174 * Revision 1.7 2001/05/28 16:14:00 jongfoster
175 * Fixing bug in LOG_LEVEL_LOG
177 * Revision 1.6 2001/05/26 17:28:32 jongfoster
178 * Fixed LOG_LEVEL_LOG
180 * Revision 1.5 2001/05/26 15:26:15 jongfoster
181 * ACL feature now provides more security by immediately dropping
182 * connections from untrusted hosts.
184 * Revision 1.4 2001/05/26 00:37:42 jongfoster
185 * Cosmetic indentation correction.
187 * Revision 1.3 2001/05/25 21:57:54 jongfoster
188 * Now gives a warning under Windows if you try to bind
189 * it to a port that's already in use.
191 * Revision 1.2 2001/05/17 23:01:01 oes
192 * - Cleaned CRLF's from the sources and related files
194 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
195 * Initial import of version 2.9.3 source tree
198 *********************************************************************/
208 #include <sys/types.h>
216 #include <sys/timeb.h>
224 #include <sys/time.h>
225 #include <netinet/in.h>
226 #include <sys/ioctl.h>
228 #include <sys/socket.h>
231 #include <netinet/tcp.h>
233 #include <arpa/inet.h>
239 #if defined(__EMX__) || defined (__OS2__)
240 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
251 /* jcc.h is for mutex semaphores only */
252 #endif /* def OSX_DARWIN */
255 #include "jbsockets.h"
259 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
262 /*********************************************************************
264 * Function : connect_to
266 * Description : Open a socket and connect to it. Will check
267 * that this is allowed according to ACL.
270 * 1 : host = hostname to connect to
271 * 2 : portnum = port to connent on
272 * 3 : csp = Current client state (buffers, headers, etc...)
273 * Not modified, only used for source IP and ACL.
275 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
278 *********************************************************************/
279 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
281 struct sockaddr_in inaddr;
285 struct timeval tv[1];
286 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
288 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
291 struct access_control_addr dst[1];
292 #endif /* def FEATURE_ACL */
294 memset((char *)&inaddr, 0, sizeof inaddr);
296 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
298 csp->http->host_ip_addr_str = strdup("unknown");
299 return(JB_INVALID_SOCKET);
303 dst->addr = ntohl((unsigned long) addr);
306 if (block_acl(dst, csp))
313 return(JB_INVALID_SOCKET);
315 #endif /* def FEATURE_ACL */
317 inaddr.sin_addr.s_addr = addr;
318 inaddr.sin_family = AF_INET;
319 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
322 if (sizeof(inaddr.sin_port) == sizeof(short))
323 #endif /* ndef _WIN32 */
325 inaddr.sin_port = htons((unsigned short) portnum);
330 inaddr.sin_port = htonl((unsigned long)portnum);
332 #endif /* ndef _WIN32 */
335 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
337 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
340 return(JB_INVALID_SOCKET);
344 { /* turn off TCP coalescence */
346 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
348 #endif /* def TCP_NODELAY */
350 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
351 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
354 fcntl(fd, F_SETFL, flags);
356 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
358 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
361 if (errno == WSAEINPROGRESS)
363 if (sock_errno() == EINPROGRESS)
364 #else /* ifndef _WIN32 */
365 if (errno == EINPROGRESS)
366 #endif /* ndef _WIN32 || __OS2__ */
372 if (sock_errno() != EINTR)
378 return(JB_INVALID_SOCKET);
382 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
386 fcntl(fd, F_SETFL, flags);
388 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
390 /* wait for connection to complete */
397 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
398 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
401 return(JB_INVALID_SOCKET);
408 /*********************************************************************
410 * Function : write_socket
412 * Description : Write the contents of buf (for n bytes) to socket fd.
415 * 1 : fd = file descriptor (aka. handle) of socket to write to.
416 * 2 : buf = pointer to data to be written.
417 * 3 : len = length of data to be written to the socket "fd".
419 * Returns : 0 on success (entire buffer sent).
422 *********************************************************************/
424 int write_socket(jb_socket fd, const char *buf, ssize_t len)
426 int write_socket(jb_socket fd, const char *buf, size_t len)
439 log_error(LOG_LEVEL_LOG, "%N", len, buf);
442 return (send(fd, buf, (int)len, 0) != (int)len);
443 #elif defined(__BEOS__) || defined(AMIGA)
444 return (send(fd, buf, len, 0) != len);
445 #elif defined(__OS2__)
447 * Break the data up into SOCKET_SEND_MAX chunks for sending...
448 * OS/2 seemed to complain when the chunks were too large.
450 #define SOCKET_SEND_MAX 65000
452 int write_len = 0, send_len, send_rc = 0, i = 0;
453 while ((i < len) && (send_rc != -1))
455 if ((i + SOCKET_SEND_MAX) > len)
458 send_len = SOCKET_SEND_MAX;
459 send_rc = send(fd,(char*)buf + i, send_len, 0);
467 return (write(fd, buf, len) != len);
473 /*********************************************************************
475 * Function : read_socket
477 * Description : Read from a TCP/IP socket in a platform independent way.
480 * 1 : fd = file descriptor of the socket to read
481 * 2 : buf = pointer to buffer where data will be written
482 * Must be >= len bytes long.
483 * 3 : len = maximum number of bytes to read
485 * Returns : On success, the number of bytes read is returned (zero
486 * indicates end of file), and the file position is advanced
487 * by this number. It is not an error if this number is
488 * smaller than the number of bytes requested; this may hap-
489 * pen for example because fewer bytes are actually available
490 * right now (maybe because we were close to end-of-file, or
491 * because we are reading from a pipe, or from a terminal,
492 * or because read() was interrupted by a signal). On error,
493 * -1 is returned, and errno is set appropriately. In this
494 * case it is left unspecified whether the file position (if
497 *********************************************************************/
498 int read_socket(jb_socket fd, char *buf, int len)
506 return(recv(fd, buf, len, 0));
507 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
508 return(recv(fd, buf, (size_t)len, 0));
510 return(read(fd, buf, (size_t)len));
515 /*********************************************************************
517 * Function : close_socket
519 * Description : Closes a TCP/IP socket
522 * 1 : fd = file descriptor of socket to be closed
526 *********************************************************************/
527 void close_socket(jb_socket fd)
529 #if defined(_WIN32) || defined(__BEOS__)
533 #elif defined(__OS2__)
542 /*********************************************************************
544 * Function : bind_port
546 * Description : Call socket, set socket options, and listen.
547 * Called by listen_loop to "boot up" our proxy address.
550 * 1 : hostnam = TCP/IP address to bind/listen to
551 * 2 : portnum = port to listen on
552 * 3 : pfd = pointer used to return file descriptor.
554 * Returns : if success, returns 0 and sets *pfd.
555 * if failure, returns -3 if address is in use,
556 * -2 if address unresolvable,
558 *********************************************************************/
559 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
561 struct sockaddr_in inaddr;
565 #endif /* ndef _WIN32 */
567 *pfd = JB_INVALID_SOCKET;
569 memset((char *)&inaddr, '\0', sizeof inaddr);
571 inaddr.sin_family = AF_INET;
572 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
574 if (inaddr.sin_addr.s_addr == INADDR_NONE)
580 if (sizeof(inaddr.sin_port) == sizeof(short))
581 #endif /* ndef _WIN32 */
583 inaddr.sin_port = htons((unsigned short) portnum);
588 inaddr.sin_port = htonl((unsigned long) portnum);
590 #endif /* ndef _WIN32 */
592 fd = socket(AF_INET, SOCK_STREAM, 0);
595 if (fd == JB_INVALID_SOCKET)
605 * This is not needed for Win32 - in fact, it stops
606 * duplicate instances of Privoxy from being caught.
608 * On UNIX, we assume the user is sensible enough not
609 * to start Junkbuster multiple times on the same IP.
610 * Without this, stopping and restarting Privoxy
611 * from a script fails.
612 * Note: SO_REUSEADDR is meant to only take over
613 * sockets which are *not* in listen state in Linux,
614 * e.g. sockets in TIME_WAIT. YMMV.
616 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
617 #endif /* ndef _WIN32 */
619 if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
622 errno = WSAGetLastError();
623 if (errno == WSAEADDRINUSE)
625 if (errno == EADDRINUSE)
638 while (listen(fd, 5) == -1)
652 /*********************************************************************
654 * Function : accept_connection
656 * Description : Accepts a connection on a socket. Socket must have
657 * been created using bind_port().
660 * 1 : csp = Client state, cfd, ip_addr_str, and
661 * ip_addr_long will be set by this routine.
662 * 2 : fd = file descriptor returned from bind_port
664 * Returns : when a connection is accepted, it returns 1 (TRUE).
665 * On an error it returns 0 (FALSE).
667 *********************************************************************/
668 int accept_connection(struct client_state * csp, jb_socket fd)
670 struct sockaddr_in client, server;
671 struct hostent *host = NULL;
673 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
674 /* Wierdness - fix a warning. */
675 int c_length, s_length;
677 socklen_t c_length, s_length;
679 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
680 struct hostent result;
681 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
682 struct hostent_data hdata;
684 char hbuf[HOSTENT_BUFFER_SIZE];
686 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
687 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
689 c_length = s_length = sizeof(client);
692 afd = accept (fd, (struct sockaddr *) &client, &c_length);
693 if (afd == JB_INVALID_SOCKET)
700 afd = accept (fd, (struct sockaddr *) &client, &c_length);
701 } while (afd < 1 && errno == EINTR);
709 * Determine the IP-Adress that the client used to reach us
710 * and the hostname associated with that address
712 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
714 csp->my_ip_addr_str = strdup(inet_ntoa(server.sin_addr));
715 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
716 gethostbyaddr_r((const char *)&server.sin_addr,
717 sizeof(server.sin_addr), AF_INET,
718 &result, hbuf, HOSTENT_BUFFER_SIZE,
720 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
721 host = gethostbyaddr_r((const char *)&server.sin_addr,
722 sizeof(server.sin_addr), AF_INET,
723 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
724 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
725 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
726 sizeof(server.sin_addr), AF_INET,
735 #elif defined(OSX_DARWIN)
736 pthread_mutex_lock(&gethostbyaddr_mutex);
737 host = gethostbyaddr((const char *)&server.sin_addr,
738 sizeof(server.sin_addr), AF_INET);
739 pthread_mutex_unlock(&gethostbyaddr_mutex);
741 host = gethostbyaddr((const char *)&server.sin_addr,
742 sizeof(server.sin_addr), AF_INET);
746 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
750 csp->my_hostname = strdup(host->h_name);
755 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
756 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
763 /*********************************************************************
765 * Function : resolve_hostname_to_ip
767 * Description : Resolve a hostname to an internet tcp/ip address.
768 * NULL or an empty string resolve to INADDR_ANY.
771 * 1 : host = hostname to resolve
773 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
775 *********************************************************************/
776 unsigned long resolve_hostname_to_ip(const char *host)
778 struct sockaddr_in inaddr;
779 struct hostent *hostp;
780 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
781 struct hostent result;
782 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
783 char hbuf[HOSTENT_BUFFER_SIZE];
785 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
786 struct hostent_data hdata;
787 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
788 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
790 if ((host == NULL) || (*host == '\0'))
795 memset((char *) &inaddr, 0, sizeof inaddr);
797 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
799 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
800 gethostbyname_r(host, &result, hbuf,
801 HOSTENT_BUFFER_SIZE, &hostp, &thd_err);
802 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
803 hostp = gethostbyname_r(host, &result, hbuf,
804 HOSTENT_BUFFER_SIZE, &thd_err);
805 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
806 if (0 == gethostbyname_r(host, &result, &hdata))
815 pthread_mutex_lock(&gethostbyname_mutex);
816 hostp = gethostbyname(host);
817 pthread_mutex_unlock(&gethostbyname_mutex);
819 hostp = gethostbyname(host);
820 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
822 * On Mac OSX, if a domain exists but doesn't have a type A
823 * record associated with it, the h_addr member of the struct
824 * hostent returned by gethostbyname is NULL, even if h_length
825 * is 4. Therefore the second test below.
827 if (hostp == NULL || hostp->h_addr == NULL)
830 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
833 if (hostp->h_addrtype != AF_INET)
836 errno = WSAEPROTOTYPE;
840 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
844 (char *) &inaddr.sin_addr,
845 (char *) hostp->h_addr,
846 sizeof(inaddr.sin_addr)
849 return(inaddr.sin_addr.s_addr);