1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.29 2002/03/26 22:29:54 swa 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 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.29 2002/03/26 22:29:54 swa
39 * we have a new homepage!
41 * Revision 1.28 2002/03/24 13:25:43 swa
42 * name change related issues
44 * Revision 1.27 2002/03/13 00:27:05 jongfoster
47 * Revision 1.26 2002/03/11 22:07:02 david__schmidt
48 * OS/2 port maintenance:
49 * - Fixed EMX build - it had decayed a little
50 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
51 * substituted a memset for now.
53 * Revision 1.25 2002/03/09 20:03:52 jongfoster
54 * - Making various functions return int rather than size_t.
55 * (Undoing a recent change). Since size_t is unsigned on
56 * Windows, functions like read_socket that return -1 on
57 * error cannot return a size_t.
59 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
60 * crashes, and also frequently caused JB to jump to 100%
61 * CPU and stay there. (Because it thought it had just
62 * read ((unsigned)-1) == 4Gb of data...)
64 * - The signature of write_socket has changed, it now simply
65 * returns success=0/failure=nonzero.
67 * - Trying to get rid of a few warnings --with-debug on
68 * Windows, I've introduced a new type "jb_socket". This is
69 * used for the socket file descriptors. On Windows, this
70 * is SOCKET (a typedef for unsigned). Everywhere else, it's
71 * an int. The error value can't be -1 any more, so it's
72 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
73 * Windows it maps to the #define INVALID_SOCKET.)
75 * - The signature of bind_port has changed.
77 * Revision 1.24 2002/03/07 03:51:36 oes
78 * - Improved handling of failed DNS lookups
79 * - Fixed compiler warnings etc
81 * Revision 1.23 2002/03/05 00:36:01 jongfoster
82 * Fixing bug 514988 - unable to restart JunkBuster
84 * Revision 1.22 2002/03/04 02:08:02 david__schmidt
85 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
87 * Revision 1.21 2002/01/09 14:32:33 oes
88 * Added support for gethostbyname_r and gethostbyaddr_r.
90 * Revision 1.20 2001/11/16 00:48:48 jongfoster
91 * Enabling duplicate-socket detection for all platforms, not
94 * Revision 1.19 2001/10/25 03:40:47 david__schmidt
95 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
96 * threads to call select() simultaneously. So, it's time to do a real, live,
97 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
98 * (native). Both versions will work, but using __OS2__ offers multi-threading.
100 * Revision 1.18 2001/09/21 23:02:02 david__schmidt
101 * Cleaning up 2 compiler warnings on OS/2.
103 * Revision 1.17 2001/09/13 20:11:46 jongfoster
104 * Fixing 2 compiler warnings under Win32
106 * Revision 1.16 2001/07/30 22:08:36 jongfoster
107 * Tidying up #defines:
108 * - All feature #defines are now of the form FEATURE_xxx
109 * - Permanently turned off WIN_GUI_EDIT
110 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
112 * Revision 1.15 2001/07/29 17:40:43 jongfoster
113 * Fixed compiler warning by adding a cast
115 * Revision 1.14 2001/07/18 13:47:59 oes
116 * Eliminated dirty hack for getsockbyname()
118 * Revision 1.13 2001/07/15 13:56:57 jongfoster
119 * Removing unused local variable.
121 * Revision 1.12 2001/07/01 17:04:11 oes
122 * Bugfix: accept_connection no longer uses the obsolete hstrerror() function
124 * Revision 1.11 2001/06/29 21:45:41 oes
125 * Indentation, CRLF->LF, Tab-> Space
127 * Revision 1.10 2001/06/29 13:29:15 oes
128 * - Added remote (server) host IP to csp->http->host_ip_addr_str
129 * - Added detection of local socket IP and fqdn
130 * - Removed logentry from cancelled commit
132 * Revision 1.9 2001/06/07 23:06:09 jongfoster
133 * The host parameter to connect_to() is now const.
135 * Revision 1.8 2001/06/03 19:12:07 oes
138 * Revision 1.7 2001/05/28 16:14:00 jongfoster
139 * Fixing bug in LOG_LEVEL_LOG
141 * Revision 1.6 2001/05/26 17:28:32 jongfoster
142 * Fixed LOG_LEVEL_LOG
144 * Revision 1.5 2001/05/26 15:26:15 jongfoster
145 * ACL feature now provides more security by immediately dropping
146 * connections from untrusted hosts.
148 * Revision 1.4 2001/05/26 00:37:42 jongfoster
149 * Cosmetic indentation correction.
151 * Revision 1.3 2001/05/25 21:57:54 jongfoster
152 * Now gives a warning under Windows if you try to bind
153 * it to a port that's already in use.
155 * Revision 1.2 2001/05/17 23:01:01 oes
156 * - Cleaned CRLF's from the sources and related files
158 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
159 * Initial import of version 2.9.3 source tree
162 *********************************************************************/
172 #include <sys/types.h>
177 #include <sys/timeb.h>
185 #include <sys/time.h>
186 #include <netinet/in.h>
187 #include <sys/ioctl.h>
189 #include <sys/socket.h>
192 #include <netinet/tcp.h>
194 #include <arpa/inet.h>
200 #if defined(__EMX__) || defined (__OS2__)
201 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
210 #include "jbsockets.h"
214 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
217 /*********************************************************************
219 * Function : connect_to
221 * Description : Open a socket and connect to it. Will check
222 * that this is allowed according to ACL.
225 * 1 : host = hostname to connect to
226 * 2 : portnum = port to connent on
227 * 3 : csp = Current client state (buffers, headers, etc...)
228 * Not modified, only used for source IP and ACL.
230 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
233 *********************************************************************/
234 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
236 struct sockaddr_in inaddr;
240 struct timeval tv[1];
241 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
243 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
246 struct access_control_addr dst[1];
247 #endif /* def FEATURE_ACL */
249 memset((char *)&inaddr, 0, sizeof inaddr);
251 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
253 csp->http->host_ip_addr_str = strdup("unknown");
254 return(JB_INVALID_SOCKET);
258 dst->addr = ntohl((unsigned long) addr);
261 if (block_acl(dst, csp))
268 return(JB_INVALID_SOCKET);
270 #endif /* def FEATURE_ACL */
272 inaddr.sin_addr.s_addr = addr;
273 inaddr.sin_family = AF_INET;
274 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
277 if (sizeof(inaddr.sin_port) == sizeof(short))
278 #endif /* ndef _WIN32 */
280 inaddr.sin_port = htons((unsigned short) portnum);
285 inaddr.sin_port = htonl((unsigned long)portnum);
287 #endif /* ndef _WIN32 */
290 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
292 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
295 return(JB_INVALID_SOCKET);
299 { /* turn off TCP coalescence */
301 setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
303 #endif /* def TCP_NODELAY */
305 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
306 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
309 fcntl(fd, F_SETFL, flags);
311 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
313 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
316 if (errno == WSAEINPROGRESS)
318 if (sock_errno() == EINPROGRESS)
319 #else /* ifndef _WIN32 */
320 if (errno == EINPROGRESS)
321 #endif /* ndef _WIN32 || __OS2__ */
327 if (sock_errno() != EINTR)
333 return(JB_INVALID_SOCKET);
337 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
341 fcntl(fd, F_SETFL, flags);
343 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
345 /* wait for connection to complete */
352 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
353 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
356 return(JB_INVALID_SOCKET);
363 /*********************************************************************
365 * Function : write_socket
367 * Description : Write the contents of buf (for n bytes) to socket fd.
370 * 1 : fd = file descriptor (aka. handle) of socket to write to.
371 * 2 : buf = pointer to data to be written.
372 * 3 : len = length of data to be written to the socket "fd".
374 * Returns : 0 on success (entire buffer sent).
377 *********************************************************************/
378 int write_socket(jb_socket fd, const char *buf, size_t len)
390 log_error(LOG_LEVEL_LOG, "%N", len, buf);
393 return (send(fd, buf, (int)len, 0) != (int)len);
394 #elif defined(__BEOS__) || defined(AMIGA)
395 return (send(fd, buf, len, 0) != len);
396 #elif defined(__OS2__)
398 * Break the data up into SOCKET_SEND_MAX chunks for sending...
399 * OS/2 seemed to complain when the chunks were too large.
401 #define SOCKET_SEND_MAX 65000
403 int write_len = 0, send_len, send_rc = 0, i = 0;
404 while ((i < len) && (send_rc != -1))
406 if ((i + SOCKET_SEND_MAX) > len)
409 send_len = SOCKET_SEND_MAX;
410 send_rc = send(fd,(char*)buf + i, send_len, 0);
418 return (write(fd, buf, len) != len);
424 /*********************************************************************
426 * Function : read_socket
428 * Description : Read from a TCP/IP socket in a platform independent way.
431 * 1 : fd = file descriptor of the socket to read
432 * 2 : buf = pointer to buffer where data will be written
433 * Must be >= len bytes long.
434 * 3 : len = maximum number of bytes to read
436 * Returns : On success, the number of bytes read is returned (zero
437 * indicates end of file), and the file position is advanced
438 * by this number. It is not an error if this number is
439 * smaller than the number of bytes requested; this may hap-
440 * pen for example because fewer bytes are actually available
441 * right now (maybe because we were close to end-of-file, or
442 * because we are reading from a pipe, or from a terminal,
443 * or because read() was interrupted by a signal). On error,
444 * -1 is returned, and errno is set appropriately. In this
445 * case it is left unspecified whether the file position (if
448 *********************************************************************/
449 int read_socket(jb_socket fd, char *buf, int len)
457 return(recv(fd, buf, len, 0));
458 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
459 return(recv(fd, buf, (size_t)len, 0));
461 return(read(fd, buf, (size_t)len));
466 /*********************************************************************
468 * Function : close_socket
470 * Description : Closes a TCP/IP socket
473 * 1 : fd = file descriptor of socket to be closed
477 *********************************************************************/
478 void close_socket(jb_socket fd)
480 #if defined(_WIN32) || defined(__BEOS__)
484 #elif defined(__OS2__)
493 /*********************************************************************
495 * Function : bind_port
497 * Description : Call socket, set socket options, and listen.
498 * Called by listen_loop to "boot up" our proxy address.
501 * 1 : hostnam = TCP/IP address to bind/listen to
502 * 2 : portnum = port to listen on
503 * 3 : pfd = pointer used to return file descriptor.
505 * Returns : if success, returns 0 and sets *pfd.
506 * if failure, returns -3 if address is in use,
507 * -2 if address unresolvable,
509 *********************************************************************/
510 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
512 struct sockaddr_in inaddr;
516 #endif /* ndef _WIN32 */
518 *pfd = JB_INVALID_SOCKET;
520 memset((char *)&inaddr, '\0', sizeof inaddr);
522 inaddr.sin_family = AF_INET;
523 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
525 if (inaddr.sin_addr.s_addr == INADDR_NONE)
531 if (sizeof(inaddr.sin_port) == sizeof(short))
532 #endif /* ndef _WIN32 */
534 inaddr.sin_port = htons((unsigned short) portnum);
539 inaddr.sin_port = htonl((unsigned long) portnum);
541 #endif /* ndef _WIN32 */
543 fd = socket(AF_INET, SOCK_STREAM, 0);
546 if (fd == JB_INVALID_SOCKET)
556 * This is not needed for Win32 - in fact, it stops
557 * duplicate instances of JunkBuster from being caught.
559 * On UNIX, we assume the user is sensible enough not
560 * to start JunkBuster multiple times on the same IP.
561 * Without this, stopping and restarting JunkBuster
562 * from a script fails.
563 * Note: SO_REUSEADDR is meant to only take over
564 * sockets which are *not* in listen state in Linux,
565 * e.g. sockets in TIME_WAIT. YMMV.
567 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
568 #endif /* ndef _WIN32 */
570 if (bind (fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
574 if (errno == WSAEADDRINUSE)
576 if (errno == EADDRINUSE)
587 while (listen(fd, 5) == -1)
601 /*********************************************************************
603 * Function : accept_connection
605 * Description : Accepts a connection on a socket. Socket must have
606 * been created using bind_port().
609 * 1 : csp = Client state, cfd, ip_addr_str, and
610 * ip_addr_long will be set by this routine.
611 * 2 : fd = file descriptor returned from bind_port
613 * Returns : when a connection is accepted, it returns 1 (TRUE).
614 * On an error it returns 0 (FALSE).
616 *********************************************************************/
617 int accept_connection(struct client_state * csp, jb_socket fd)
619 struct sockaddr_in client, server;
620 struct hostent *host = NULL;
622 #if defined(_WIN32) || defined(__OS2__)
623 /* Wierdness - fix a warning. */
624 int c_length, s_length;
626 size_t c_length, s_length;
628 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
629 struct hostent result;
630 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
631 struct hostent_data hdata;
633 char hbuf[HOSTENT_BUFFER_SIZE];
635 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
636 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
638 c_length = s_length = sizeof(client);
641 afd = accept (fd, (struct sockaddr *) &client, &c_length);
642 if (afd == JB_INVALID_SOCKET)
649 afd = accept (fd, (struct sockaddr *) &client, &c_length);
650 } while (afd < 1 && errno == EINTR);
658 * Determine the IP-Adress that the client used to reach us
659 * and the hostname associated with that address
661 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
663 csp->my_ip_addr_str = strdup(inet_ntoa(server.sin_addr));
664 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
665 gethostbyaddr_r((const char *)&server.sin_addr,
666 sizeof(server.sin_addr), AF_INET,
667 &result, hbuf, HOSTENT_BUFFER_SIZE,
669 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
670 host = gethostbyaddr_r((const char *)&server.sin_addr,
671 sizeof(server.sin_addr), AF_INET,
672 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
673 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
674 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
675 sizeof(server.sin_addr), AF_INET,
685 host = gethostbyaddr((const char *)&server.sin_addr,
686 sizeof(server.sin_addr), AF_INET);
690 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
694 csp->my_hostname = strdup(host->h_name);
699 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
700 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
707 /*********************************************************************
709 * Function : resolve_hostname_to_ip
711 * Description : Resolve a hostname to an internet tcp/ip address.
712 * NULL or an empty string resolve to INADDR_ANY.
715 * 1 : host = hostname to resolve
717 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
719 *********************************************************************/
720 unsigned long resolve_hostname_to_ip(const char *host)
722 struct sockaddr_in inaddr;
723 struct hostent *hostp;
724 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
725 struct hostent result;
726 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
727 char hbuf[HOSTENT_BUFFER_SIZE];
729 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
730 struct hostent_data hdata;
731 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
732 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
734 if ((host == NULL) || (*host == '\0'))
739 memset((char *) &inaddr, 0, sizeof inaddr);
741 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
743 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
744 gethostbyname_r(host, &result, hbuf,
745 HOSTENT_BUFFER_SIZE, &hostp, &thd_err);
746 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
747 hostp = gethostbyname_r(host, &result, hbuf,
748 HOSTENT_BUFFER_SIZE, &thd_err);
749 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
750 if (0 == gethostbyname_r(host, &result, &hdata))
759 hostp = gethostbyname(host);
760 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
764 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
767 if (hostp->h_addrtype != AF_INET)
770 errno = WSAEPROTOTYPE;
774 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
778 (char *) &inaddr.sin_addr,
779 (char *) hostp->h_addr,
780 sizeof(inaddr.sin_addr)
783 return(inaddr.sin_addr.s_addr);