1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.26 2002/03/11 22:07:02 david__schmidt 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 * IJBSWA team. http://ijbswa.sourceforge.net
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.26 2002/03/11 22:07:02 david__schmidt
39 * OS/2 port maintenance:
40 * - Fixed EMX build - it had decayed a little
41 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
42 * substituted a memset for now.
44 * Revision 1.25 2002/03/09 20:03:52 jongfoster
45 * - Making various functions return int rather than size_t.
46 * (Undoing a recent change). Since size_t is unsigned on
47 * Windows, functions like read_socket that return -1 on
48 * error cannot return a size_t.
50 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
51 * crashes, and also frequently caused JB to jump to 100%
52 * CPU and stay there. (Because it thought it had just
53 * read ((unsigned)-1) == 4Gb of data...)
55 * - The signature of write_socket has changed, it now simply
56 * returns success=0/failure=nonzero.
58 * - Trying to get rid of a few warnings --with-debug on
59 * Windows, I've introduced a new type "jb_socket". This is
60 * used for the socket file descriptors. On Windows, this
61 * is SOCKET (a typedef for unsigned). Everywhere else, it's
62 * an int. The error value can't be -1 any more, so it's
63 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
64 * Windows it maps to the #define INVALID_SOCKET.)
66 * - The signature of bind_port has changed.
68 * Revision 1.24 2002/03/07 03:51:36 oes
69 * - Improved handling of failed DNS lookups
70 * - Fixed compiler warnings etc
72 * Revision 1.23 2002/03/05 00:36:01 jongfoster
73 * Fixing bug 514988 - unable to restart JunkBuster
75 * Revision 1.22 2002/03/04 02:08:02 david__schmidt
76 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
78 * Revision 1.21 2002/01/09 14:32:33 oes
79 * Added support for gethostbyname_r and gethostbyaddr_r.
81 * Revision 1.20 2001/11/16 00:48:48 jongfoster
82 * Enabling duplicate-socket detection for all platforms, not
85 * Revision 1.19 2001/10/25 03:40:47 david__schmidt
86 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
87 * threads to call select() simultaneously. So, it's time to do a real, live,
88 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
89 * (native). Both versions will work, but using __OS2__ offers multi-threading.
91 * Revision 1.18 2001/09/21 23:02:02 david__schmidt
92 * Cleaning up 2 compiler warnings on OS/2.
94 * Revision 1.17 2001/09/13 20:11:46 jongfoster
95 * Fixing 2 compiler warnings under Win32
97 * Revision 1.16 2001/07/30 22:08:36 jongfoster
98 * Tidying up #defines:
99 * - All feature #defines are now of the form FEATURE_xxx
100 * - Permanently turned off WIN_GUI_EDIT
101 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
103 * Revision 1.15 2001/07/29 17:40:43 jongfoster
104 * Fixed compiler warning by adding a cast
106 * Revision 1.14 2001/07/18 13:47:59 oes
107 * Eliminated dirty hack for getsockbyname()
109 * Revision 1.13 2001/07/15 13:56:57 jongfoster
110 * Removing unused local variable.
112 * Revision 1.12 2001/07/01 17:04:11 oes
113 * Bugfix: accept_connection no longer uses the obsolete hstrerror() function
115 * Revision 1.11 2001/06/29 21:45:41 oes
116 * Indentation, CRLF->LF, Tab-> Space
118 * Revision 1.10 2001/06/29 13:29:15 oes
119 * - Added remote (server) host IP to csp->http->host_ip_addr_str
120 * - Added detection of local socket IP and fqdn
121 * - Removed logentry from cancelled commit
123 * Revision 1.9 2001/06/07 23:06:09 jongfoster
124 * The host parameter to connect_to() is now const.
126 * Revision 1.8 2001/06/03 19:12:07 oes
129 * Revision 1.7 2001/05/28 16:14:00 jongfoster
130 * Fixing bug in LOG_LEVEL_LOG
132 * Revision 1.6 2001/05/26 17:28:32 jongfoster
133 * Fixed LOG_LEVEL_LOG
135 * Revision 1.5 2001/05/26 15:26:15 jongfoster
136 * ACL feature now provides more security by immediately dropping
137 * connections from untrusted hosts.
139 * Revision 1.4 2001/05/26 00:37:42 jongfoster
140 * Cosmetic indentation correction.
142 * Revision 1.3 2001/05/25 21:57:54 jongfoster
143 * Now gives a warning under Windows if you try to bind
144 * it to a port that's already in use.
146 * Revision 1.2 2001/05/17 23:01:01 oes
147 * - Cleaned CRLF's from the sources and related files
149 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
150 * Initial import of version 2.9.3 source tree
153 *********************************************************************/
163 #include <sys/types.h>
168 #include <sys/timeb.h>
176 #include <sys/time.h>
177 #include <netinet/in.h>
178 #include <sys/ioctl.h>
180 #include <sys/socket.h>
183 #include <netinet/tcp.h>
185 #include <arpa/inet.h>
191 #if defined(__EMX__) || defined (__OS2__)
192 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
201 #include "jbsockets.h"
205 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
208 /*********************************************************************
210 * Function : connect_to
212 * Description : Open a socket and connect to it. Will check
213 * that this is allowed according to ACL.
216 * 1 : host = hostname to connect to
217 * 2 : portnum = port to connent on
218 * 3 : csp = Current client state (buffers, headers, etc...)
219 * Not modified, only used for source IP and ACL.
221 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
224 *********************************************************************/
225 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
227 struct sockaddr_in inaddr;
231 struct timeval tv[1];
232 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
234 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
237 struct access_control_addr dst[1];
238 #endif /* def FEATURE_ACL */
240 memset((char *)&inaddr, 0, sizeof inaddr);
242 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
244 csp->http->host_ip_addr_str = strdup("unknown");
245 return(JB_INVALID_SOCKET);
249 dst->addr = ntohl((unsigned long) addr);
252 if (block_acl(dst, csp))
259 return(JB_INVALID_SOCKET);
261 #endif /* def FEATURE_ACL */
263 inaddr.sin_addr.s_addr = addr;
264 inaddr.sin_family = AF_INET;
265 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
268 if (sizeof(inaddr.sin_port) == sizeof(short))
269 #endif /* ndef _WIN32 */
271 inaddr.sin_port = htons((unsigned short) portnum);
276 inaddr.sin_port = htonl((unsigned long)portnum);
278 #endif /* ndef _WIN32 */
281 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
283 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
286 return(JB_INVALID_SOCKET);
290 { /* turn off TCP coalescence */
292 setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
294 #endif /* def TCP_NODELAY */
296 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
297 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
300 fcntl(fd, F_SETFL, flags);
302 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
304 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
307 if (errno == WSAEINPROGRESS)
309 if (sock_errno() == EINPROGRESS)
310 #else /* ifndef _WIN32 */
311 if (errno == EINPROGRESS)
312 #endif /* ndef _WIN32 || __OS2__ */
318 if (sock_errno() != EINTR)
324 return(JB_INVALID_SOCKET);
328 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
332 fcntl(fd, F_SETFL, flags);
334 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
336 /* wait for connection to complete */
343 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
344 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
347 return(JB_INVALID_SOCKET);
354 /*********************************************************************
356 * Function : write_socket
358 * Description : Write the contents of buf (for n bytes) to socket fd.
361 * 1 : fd = file descriptor (aka. handle) of socket to write to.
362 * 2 : buf = pointer to data to be written.
363 * 3 : len = length of data to be written to the socket "fd".
365 * Returns : 0 on success (entire buffer sent).
368 *********************************************************************/
369 int write_socket(jb_socket fd, const char *buf, size_t len)
381 log_error(LOG_LEVEL_LOG, "%N", len, buf);
384 return (send(fd, buf, (int)len, 0) != (int)len);
385 #elif defined(__BEOS__) || defined(AMIGA)
386 return (send(fd, buf, len, 0) != len);
387 #elif defined(__OS2__)
389 * Break the data up into SOCKET_SEND_MAX chunks for sending...
390 * OS/2 seemed to complain when the chunks were too large.
392 #define SOCKET_SEND_MAX 65000
394 int write_len = 0, send_len, send_rc = 0, i = 0;
395 while ((i < len) && (send_rc != -1))
397 if ((i + SOCKET_SEND_MAX) > len)
400 send_len = SOCKET_SEND_MAX;
401 send_rc = send(fd,(char*)buf + i, send_len, 0);
409 return (write(fd, buf, len) != len);
415 /*********************************************************************
417 * Function : read_socket
419 * Description : Read from a TCP/IP socket in a platform independent way.
422 * 1 : fd = file descriptor of the socket to read
423 * 2 : buf = pointer to buffer where data will be written
424 * Must be >= len bytes long.
425 * 3 : len = maximum number of bytes to read
427 * Returns : On success, the number of bytes read is returned (zero
428 * indicates end of file), and the file position is advanced
429 * by this number. It is not an error if this number is
430 * smaller than the number of bytes requested; this may hap-
431 * pen for example because fewer bytes are actually available
432 * right now (maybe because we were close to end-of-file, or
433 * because we are reading from a pipe, or from a terminal,
434 * or because read() was interrupted by a signal). On error,
435 * -1 is returned, and errno is set appropriately. In this
436 * case it is left unspecified whether the file position (if
439 *********************************************************************/
440 int read_socket(jb_socket fd, char *buf, int len)
448 return(recv(fd, buf, len, 0));
449 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
450 return(recv(fd, buf, (size_t)len, 0));
452 return(read(fd, buf, (size_t)len));
457 /*********************************************************************
459 * Function : close_socket
461 * Description : Closes a TCP/IP socket
464 * 1 : fd = file descriptor of socket to be closed
468 *********************************************************************/
469 void close_socket(jb_socket fd)
471 #if defined(_WIN32) || defined(__BEOS__)
475 #elif defined(__OS2__)
484 /*********************************************************************
486 * Function : bind_port
488 * Description : Call socket, set socket options, and listen.
489 * Called by listen_loop to "boot up" our proxy address.
492 * 1 : hostnam = TCP/IP address to bind/listen to
493 * 2 : portnum = port to listen on
494 * 3 : pfd = pointer used to return file descriptor.
496 * Returns : if success, returns 0 and sets *pfd.
497 * if failure, returns -3 if address is in use,
498 * -2 if address unresolvable,
500 *********************************************************************/
501 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
503 struct sockaddr_in inaddr;
507 #endif /* ndef _WIN32 */
509 *pfd = JB_INVALID_SOCKET;
511 memset((char *)&inaddr, '\0', sizeof inaddr);
513 inaddr.sin_family = AF_INET;
514 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
516 if (inaddr.sin_addr.s_addr == INADDR_NONE)
522 if (sizeof(inaddr.sin_port) == sizeof(short))
523 #endif /* ndef _WIN32 */
525 inaddr.sin_port = htons((unsigned short) portnum);
530 inaddr.sin_port = htonl((unsigned long) portnum);
532 #endif /* ndef _WIN32 */
534 fd = socket(AF_INET, SOCK_STREAM, 0);
537 if (fd == JB_INVALID_SOCKET)
547 * This is not needed for Win32 - in fact, it stops
548 * duplicate instances of JunkBuster from being caught.
550 * On UNIX, we assume the user is sensible enough not
551 * to start JunkBuster multiple times on the same IP.
552 * Without this, stopping and restarting JunkBuster
553 * from a script fails.
554 * Note: SO_REUSEADDR is meant to only take over
555 * sockets which are *not* in listen state in Linux,
556 * e.g. sockets in TIME_WAIT. YMMV.
558 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
559 #endif /* ndef _WIN32 */
561 if (bind (fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
565 if (errno == WSAEADDRINUSE)
567 if (errno == EADDRINUSE)
578 while (listen(fd, 5) == -1)
592 /*********************************************************************
594 * Function : accept_connection
596 * Description : Accepts a connection on a socket. Socket must have
597 * been created using bind_port().
600 * 1 : csp = Client state, cfd, ip_addr_str, and
601 * ip_addr_long will be set by this routine.
602 * 2 : fd = file descriptor returned from bind_port
604 * Returns : when a connection is accepted, it returns 1 (TRUE).
605 * On an error it returns 0 (FALSE).
607 *********************************************************************/
608 int accept_connection(struct client_state * csp, jb_socket fd)
610 struct sockaddr_in client, server;
611 struct hostent *host = NULL;
614 /* Microsoft wierdness - fix a warning. */
615 int c_length, s_length;
617 size_t c_length, s_length;
619 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
620 struct hostent result;
621 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
622 struct hostent_data hdata;
624 char hbuf[HOSTENT_BUFFER_SIZE];
626 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
627 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
629 c_length = s_length = sizeof(client);
632 afd = accept (fd, (struct sockaddr *) &client, &c_length);
633 if (afd == JB_INVALID_SOCKET)
640 afd = accept (fd, (struct sockaddr *) &client, &c_length);
641 } while (afd < 1 && errno == EINTR);
649 * Determine the IP-Adress that the client used to reach us
650 * and the hostname associated with that address
652 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
654 csp->my_ip_addr_str = strdup(inet_ntoa(server.sin_addr));
655 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
656 gethostbyaddr_r((const char *)&server.sin_addr,
657 sizeof(server.sin_addr), AF_INET,
658 &result, hbuf, HOSTENT_BUFFER_SIZE,
660 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
661 host = gethostbyaddr_r((const char *)&server.sin_addr,
662 sizeof(server.sin_addr), AF_INET,
663 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
664 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
665 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
666 sizeof(server.sin_addr), AF_INET,
676 host = gethostbyaddr((const char *)&server.sin_addr,
677 sizeof(server.sin_addr), AF_INET);
681 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
685 csp->my_hostname = strdup(host->h_name);
690 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
691 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
698 /*********************************************************************
700 * Function : resolve_hostname_to_ip
702 * Description : Resolve a hostname to an internet tcp/ip address.
703 * NULL or an empty string resolve to INADDR_ANY.
706 * 1 : host = hostname to resolve
708 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
710 *********************************************************************/
711 unsigned long resolve_hostname_to_ip(const char *host)
713 struct sockaddr_in inaddr;
714 struct hostent *hostp;
715 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
716 struct hostent result;
717 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
718 char hbuf[HOSTENT_BUFFER_SIZE];
720 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
721 struct hostent_data hdata;
722 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
723 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
725 if ((host == NULL) || (*host == '\0'))
730 memset((char *) &inaddr, 0, sizeof inaddr);
732 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
734 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
735 gethostbyname_r(host, &result, hbuf,
736 HOSTENT_BUFFER_SIZE, &hostp, &thd_err);
737 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
738 hostp = gethostbyname_r(host, &result, hbuf,
739 HOSTENT_BUFFER_SIZE, &thd_err);
740 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
741 if (0 == gethostbyname_r(host, &result, &hdata))
750 hostp = gethostbyname(host);
751 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
755 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
758 if (hostp->h_addrtype != AF_INET)
761 errno = WSAEPROTOTYPE;
765 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
769 (char *) &inaddr.sin_addr,
770 (char *) hostp->h_addr,
771 sizeof(inaddr.sin_addr)
774 return(inaddr.sin_addr.s_addr);