1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.24 2002/03/07 03:51:36 oes 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.24 2002/03/07 03:51:36 oes
39 * - Improved handling of failed DNS lookups
40 * - Fixed compiler warnings etc
42 * Revision 1.23 2002/03/05 00:36:01 jongfoster
43 * Fixing bug 514988 - unable to restart JunkBuster
45 * Revision 1.22 2002/03/04 02:08:02 david__schmidt
46 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
48 * Revision 1.21 2002/01/09 14:32:33 oes
49 * Added support for gethostbyname_r and gethostbyaddr_r.
51 * Revision 1.20 2001/11/16 00:48:48 jongfoster
52 * Enabling duplicate-socket detection for all platforms, not
55 * Revision 1.19 2001/10/25 03:40:47 david__schmidt
56 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
57 * threads to call select() simultaneously. So, it's time to do a real, live,
58 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
59 * (native). Both versions will work, but using __OS2__ offers multi-threading.
61 * Revision 1.18 2001/09/21 23:02:02 david__schmidt
62 * Cleaning up 2 compiler warnings on OS/2.
64 * Revision 1.17 2001/09/13 20:11:46 jongfoster
65 * Fixing 2 compiler warnings under Win32
67 * Revision 1.16 2001/07/30 22:08:36 jongfoster
68 * Tidying up #defines:
69 * - All feature #defines are now of the form FEATURE_xxx
70 * - Permanently turned off WIN_GUI_EDIT
71 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
73 * Revision 1.15 2001/07/29 17:40:43 jongfoster
74 * Fixed compiler warning by adding a cast
76 * Revision 1.14 2001/07/18 13:47:59 oes
77 * Eliminated dirty hack for getsockbyname()
79 * Revision 1.13 2001/07/15 13:56:57 jongfoster
80 * Removing unused local variable.
82 * Revision 1.12 2001/07/01 17:04:11 oes
83 * Bugfix: accept_connection no longer uses the obsolete hstrerror() function
85 * Revision 1.11 2001/06/29 21:45:41 oes
86 * Indentation, CRLF->LF, Tab-> Space
88 * Revision 1.10 2001/06/29 13:29:15 oes
89 * - Added remote (server) host IP to csp->http->host_ip_addr_str
90 * - Added detection of local socket IP and fqdn
91 * - Removed logentry from cancelled commit
93 * Revision 1.9 2001/06/07 23:06:09 jongfoster
94 * The host parameter to connect_to() is now const.
96 * Revision 1.8 2001/06/03 19:12:07 oes
99 * Revision 1.7 2001/05/28 16:14:00 jongfoster
100 * Fixing bug in LOG_LEVEL_LOG
102 * Revision 1.6 2001/05/26 17:28:32 jongfoster
103 * Fixed LOG_LEVEL_LOG
105 * Revision 1.5 2001/05/26 15:26:15 jongfoster
106 * ACL feature now provides more security by immediately dropping
107 * connections from untrusted hosts.
109 * Revision 1.4 2001/05/26 00:37:42 jongfoster
110 * Cosmetic indentation correction.
112 * Revision 1.3 2001/05/25 21:57:54 jongfoster
113 * Now gives a warning under Windows if you try to bind
114 * it to a port that's already in use.
116 * Revision 1.2 2001/05/17 23:01:01 oes
117 * - Cleaned CRLF's from the sources and related files
119 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
120 * Initial import of version 2.9.3 source tree
123 *********************************************************************/
133 #include <sys/types.h>
138 #include <sys/timeb.h>
146 #include <sys/time.h>
147 #include <netinet/in.h>
148 #include <sys/ioctl.h>
150 #include <sys/socket.h>
153 #include <netinet/tcp.h>
155 #include <arpa/inet.h>
161 #if defined(__EMX__) || defined (__OS2__)
162 #include <sys/select.h> /* OS/2/EMX needs a little help with select */
169 #include "jbsockets.h"
173 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
176 /*********************************************************************
178 * Function : connect_to
180 * Description : Open a socket and connect to it. Will check
181 * that this is allowed according to ACL.
184 * 1 : host = hostname to connect to
185 * 2 : portnum = port to connent on
186 * 3 : csp = Current client state (buffers, headers, etc...)
187 * Not modified, only used for source IP and ACL.
189 * Returns : JB_INVALID_SOCKET => failure, else it is the socket
192 *********************************************************************/
193 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
195 struct sockaddr_in inaddr;
199 struct timeval tv[1];
200 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
202 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
205 struct access_control_addr dst[1];
206 #endif /* def FEATURE_ACL */
208 memset((char *)&inaddr, 0, sizeof inaddr);
210 if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
212 csp->http->host_ip_addr_str = strdup("unknown");
213 return(JB_INVALID_SOCKET);
217 dst->addr = ntohl((unsigned long) addr);
220 if (block_acl(dst, csp))
227 return(JB_INVALID_SOCKET);
229 #endif /* def FEATURE_ACL */
231 inaddr.sin_addr.s_addr = addr;
232 inaddr.sin_family = AF_INET;
233 csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
236 if (sizeof(inaddr.sin_port) == sizeof(short))
237 #endif /* ndef _WIN32 */
239 inaddr.sin_port = htons((unsigned short) portnum);
244 inaddr.sin_port = htonl((unsigned long)portnum);
246 #endif /* ndef _WIN32 */
249 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
251 if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
254 return(JB_INVALID_SOCKET);
258 { /* turn off TCP coalescence */
260 setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
262 #endif /* def TCP_NODELAY */
264 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
265 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
268 fcntl(fd, F_SETFL, flags);
270 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
272 while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
275 if (errno == WSAEINPROGRESS)
277 if (sock_errno() == EINPROGRESS)
278 #else /* ifndef _WIN32 */
279 if (errno == EINPROGRESS)
280 #endif /* ndef _WIN32 || __OS2__ */
286 if (sock_errno() != EINTR)
292 return(JB_INVALID_SOCKET);
296 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
300 fcntl(fd, F_SETFL, flags);
302 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
304 /* wait for connection to complete */
311 /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
312 if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
315 return(JB_INVALID_SOCKET);
322 /*********************************************************************
324 * Function : write_socket
326 * Description : Write the contents of buf (for n bytes) to socket fd.
329 * 1 : fd = file descriptor (aka. handle) of socket to write to.
330 * 2 : buf = pointer to data to be written.
331 * 3 : len = length of data to be written to the socket "fd".
333 * Returns : 0 on success (entire buffer sent).
336 *********************************************************************/
337 int write_socket(jb_socket fd, const char *buf, int len)
349 log_error(LOG_LEVEL_LOG, "%N", len, buf);
351 #if defined(_WIN32) || defined(__BEOS__) || defined(AMIGA)
352 return (send(fd, buf, len, 0) != len);
353 #elif defined(__OS2__)
355 * Break the data up into SOCKET_SEND_MAX chunks for sending...
356 * OS/2 seemed to complain when the chunks were too large.
358 #define SOCKET_SEND_MAX 65000
360 int write_len = 0, send_len, send_rc = 0, i = 0;
361 while ((i < len) && (send_rc != -1))
363 if ((i + SOCKET_SEND_MAX) > len)
366 send_len = SOCKET_SEND_MAX;
367 send_rc = send(fd,(char*)buf + i, send_len, 0);
375 return (write(fd, buf, len) != len);
381 /*********************************************************************
383 * Function : read_socket
385 * Description : Read from a TCP/IP socket in a platform independent way.
388 * 1 : fd = file descriptor of the socket to read
389 * 2 : buf = pointer to buffer where data will be written
390 * Must be >= len bytes long.
391 * 3 : len = maximum number of bytes to read
393 * Returns : On success, the number of bytes read is returned (zero
394 * indicates end of file), and the file position is advanced
395 * by this number. It is not an error if this number is
396 * smaller than the number of bytes requested; this may hap-
397 * pen for example because fewer bytes are actually available
398 * right now (maybe because we were close to end-of-file, or
399 * because we are reading from a pipe, or from a terminal,
400 * or because read() was interrupted by a signal). On error,
401 * -1 is returned, and errno is set appropriately. In this
402 * case it is left unspecified whether the file position (if
405 *********************************************************************/
406 int read_socket(jb_socket fd, char *buf, int len)
413 #if defined(_WIN32) || defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
414 return(recv(fd, buf, len, 0));
416 return(read(fd, buf, len));
421 /*********************************************************************
423 * Function : close_socket
425 * Description : Closes a TCP/IP socket
428 * 1 : fd = file descriptor of socket to be closed
432 *********************************************************************/
433 void close_socket(jb_socket fd)
435 #if defined(_WIN32) || defined(__BEOS__)
439 #elif defined(__OS2__)
448 /*********************************************************************
450 * Function : bind_port
452 * Description : Call socket, set socket options, and listen.
453 * Called by listen_loop to "boot up" our proxy address.
456 * 1 : hostnam = TCP/IP address to bind/listen to
457 * 2 : portnum = port to listen on
458 * 3 : pfd = pointer used to return file descriptor.
460 * Returns : if success, returns 0 and sets *pfd.
461 * if failure, returns -3 if address is in use,
462 * -2 if address unresolvable,
464 *********************************************************************/
465 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
467 struct sockaddr_in inaddr;
471 #endif /* ndef _WIN32 */
473 *pfd = JB_INVALID_SOCKET;
475 memset((char *)&inaddr, '\0', sizeof inaddr);
477 inaddr.sin_family = AF_INET;
478 inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
480 if (inaddr.sin_addr.s_addr == INADDR_NONE)
486 if (sizeof(inaddr.sin_port) == sizeof(short))
487 #endif /* ndef _WIN32 */
489 inaddr.sin_port = htons((unsigned short) portnum);
494 inaddr.sin_port = htonl((unsigned long) portnum);
496 #endif /* ndef _WIN32 */
498 fd = socket(AF_INET, SOCK_STREAM, 0);
501 if (fd == JB_INVALID_SOCKET)
511 * This is not needed for Win32 - in fact, it stops
512 * duplicate instances of JunkBuster from being caught.
514 * On UNIX, we assume the user is sensible enough not
515 * to start JunkBuster multiple times on the same IP.
516 * Without this, stopping and restarting JunkBuster
517 * from a script fails.
518 * Note: SO_REUSEADDR is meant to only take over
519 * sockets which are *not* in listen state in Linux,
520 * e.g. sockets in TIME_WAIT. YMMV.
522 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
523 #endif /* ndef _WIN32 */
525 if (bind (fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
529 if (errno == WSAEADDRINUSE)
531 if (errno == EADDRINUSE)
542 while (listen(fd, 5) == -1)
556 /*********************************************************************
558 * Function : accept_connection
560 * Description : Accepts a connection on a socket. Socket must have
561 * been created using bind_port().
564 * 1 : csp = Client state, cfd, ip_addr_str, and
565 * ip_addr_long will be set by this routine.
566 * 2 : fd = file descriptor returned from bind_port
568 * Returns : when a connection is accepted, it returns 1 (TRUE).
569 * On an error it returns 0 (FALSE).
571 *********************************************************************/
572 int accept_connection(struct client_state * csp, jb_socket fd)
574 struct sockaddr_in client, server;
575 struct hostent *host = NULL;
577 size_t c_length, s_length;
578 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) || defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
579 struct hostent result;
580 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
581 struct hostent_data hdata;
583 char hbuf[HOSTENT_BUFFER_SIZE];
585 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
586 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
588 c_length = s_length = sizeof(client);
591 afd = accept (fd, (struct sockaddr *) &client, &c_length);
592 if (afd == JB_INVALID_SOCKET)
599 afd = accept (fd, (struct sockaddr *) &client, &c_length);
600 } while (afd < 1 && errno == EINTR);
608 * Determine the IP-Adress that the client used to reach us
609 * and the hostname associated with that address
611 if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
613 csp->my_ip_addr_str = strdup(inet_ntoa(server.sin_addr));
614 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
615 gethostbyaddr_r((const char *)&server.sin_addr,
616 sizeof(server.sin_addr), AF_INET,
617 &result, hbuf, HOSTENT_BUFFER_SIZE,
619 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
620 host = gethostbyaddr_r((const char *)&server.sin_addr,
621 sizeof(server.sin_addr), AF_INET,
622 &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
623 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
624 if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
625 sizeof(server.sin_addr), AF_INET,
635 host = gethostbyaddr((const char *)&server.sin_addr,
636 sizeof(server.sin_addr), AF_INET);
640 log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
644 csp->my_hostname = strdup(host->h_name);
649 csp->ip_addr_str = strdup(inet_ntoa(client.sin_addr));
650 csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
657 /*********************************************************************
659 * Function : resolve_hostname_to_ip
661 * Description : Resolve a hostname to an internet tcp/ip address.
662 * NULL or an empty string resolve to INADDR_ANY.
665 * 1 : host = hostname to resolve
667 * Returns : INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
669 *********************************************************************/
670 unsigned long resolve_hostname_to_ip(const char *host)
672 struct sockaddr_in inaddr;
673 struct hostent *hostp;
674 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
675 struct hostent result;
676 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
677 char hbuf[HOSTENT_BUFFER_SIZE];
679 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
680 struct hostent_data hdata;
681 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
682 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
684 if ((host == NULL) || (*host == '\0'))
689 memset((char *) &inaddr, 0, sizeof inaddr);
691 if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
693 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
694 gethostbyname_r(host, &result, hbuf,
695 HOSTENT_BUFFER_SIZE, &hostp, &thd_err);
696 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
697 hostp = gethostbyname_r(host, &result, hbuf,
698 HOSTENT_BUFFER_SIZE, &thd_err);
699 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
700 if (0 == gethostbyname_r(host, &result, &hdata))
709 hostp = gethostbyname(host);
710 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
714 log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
717 if (hostp->h_addrtype != AF_INET)
720 errno = WSAEPROTOTYPE;
724 log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
728 (char *) &inaddr.sin_addr,
729 (char *) hostp->h_addr,
730 sizeof(inaddr.sin_addr)
733 return(inaddr.sin_addr.s_addr);