Made both JunkBuster projects depend on vc_dftables, so it is built
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.11 2001/06/29 21:45:41 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
5  *
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
9  *                on many platforms.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
12  *                IJBSWA team.  http://ijbswa.sourceforge.net
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and 
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
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.
23  *
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.
29  *
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.
35  *
36  * Revisions   :
37  *    $Log: jbsockets.c,v $
38  *    Revision 1.11  2001/06/29 21:45:41  oes
39  *    Indentation, CRLF->LF, Tab-> Space
40  *
41  *    Revision 1.10  2001/06/29 13:29:15  oes
42  *    - Added remote (server) host IP to csp->http->host_ip_addr_str
43  *    - Added detection of local socket IP and fqdn
44  *    - Removed logentry from cancelled commit
45  *
46  *    Revision 1.9  2001/06/07 23:06:09  jongfoster
47  *    The host parameter to connect_to() is now const.
48  *
49  *    Revision 1.8  2001/06/03 19:12:07  oes
50  *    filled comment
51  *
52  *    Revision 1.7  2001/05/28 16:14:00  jongfoster
53  *    Fixing bug in LOG_LEVEL_LOG
54  *
55  *    Revision 1.6  2001/05/26 17:28:32  jongfoster
56  *    Fixed LOG_LEVEL_LOG
57  *
58  *    Revision 1.5  2001/05/26 15:26:15  jongfoster
59  *    ACL feature now provides more security by immediately dropping
60  *    connections from untrusted hosts.
61  *
62  *    Revision 1.4  2001/05/26 00:37:42  jongfoster
63  *    Cosmetic indentation correction.
64  *
65  *    Revision 1.3  2001/05/25 21:57:54  jongfoster
66  *    Now gives a warning under Windows if you try to bind
67  *    it to a port that's already in use.
68  *
69  *    Revision 1.2  2001/05/17 23:01:01  oes
70  *     - Cleaned CRLF's from the sources and related files
71  *
72  *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
73  *    Initial import of version 2.9.3 source tree
74  *
75  *
76  *********************************************************************/
77 \f
78
79 #include "config.h"
80
81 #include <stdlib.h>
82 #include <stdio.h>
83 #include <string.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <sys/types.h>
87
88 #ifdef _WIN32
89
90 #include <windows.h>
91 #include <sys/timeb.h>
92 #include <io.h>
93
94 #else
95
96 #include <unistd.h>
97 #include <sys/time.h>
98 #include <netinet/in.h>
99 #include <sys/ioctl.h>
100 #include <netdb.h>
101 #include <sys/socket.h>
102
103 #ifndef __BEOS__
104 #include <netinet/tcp.h>
105 #include <arpa/inet.h>
106 #else
107 #include <socket.h>
108 #endif
109
110 #endif
111
112 #include "project.h"
113 #include "jbsockets.h"
114 #include "filters.h"
115 #include "errlog.h"
116
117 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
118
119
120 /*********************************************************************
121  *
122  * Function    :  connect_to
123  *
124  * Description :  Open a socket and connect to it.  Will check
125  *                that this is allowed according to ACL.
126  *
127  * Parameters  :
128  *          1  :  host = hostname to connect to
129  *          2  :  portnum = port to connent on
130  *          3  :  csp = Current client state (buffers, headers, etc...)
131  *                      Not modified, only used for source IP and ACL.
132  *
133  * Returns     :  -1 => failure, else it is the socket file descriptor.
134  *
135  *********************************************************************/
136 int connect_to(const char *host, int portnum, struct client_state *csp)
137 {
138    struct sockaddr_in inaddr;
139    int   fd, addr;
140    fd_set wfds;
141    struct timeval tv[1];
142 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
143    int   flags;
144 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
145
146 #ifdef ACL_FILES
147    struct access_control_addr dst[1];
148 #endif /* def ACL_FILES */
149
150    memset((char *)&inaddr, 0, sizeof inaddr);
151
152    if ((addr = resolve_hostname_to_ip(host)) == -1)
153    {
154       csp->http->host_ip_addr_str = strdup("unknown");
155       return(-1);
156    }
157
158 #ifdef ACL_FILES
159    dst->addr = ntohl(addr);
160    dst->port = portnum;
161
162    if (block_acl(dst, csp))
163    {
164       errno = EPERM;
165       return(-1);
166    }
167 #endif /* def ACL_FILES */
168
169    inaddr.sin_addr.s_addr = addr;
170    inaddr.sin_family      = AF_INET;
171    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
172
173    if (sizeof(inaddr.sin_port) == sizeof(short))
174    {
175       inaddr.sin_port = htons((short)portnum);
176    }
177    else
178    {
179       inaddr.sin_port = htonl(portnum);
180    }
181
182    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
183    {
184       return(-1);
185    }
186
187 #ifdef TCP_NODELAY
188    {  /* turn off TCP coalescence */
189       int mi = 1;
190       setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
191    }
192 #endif /* def TCP_NODELAY */
193
194 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
195    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
196    {
197       flags |= O_NDELAY;
198       fcntl(fd, F_SETFL, flags);
199    }
200 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
201
202    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == -1)
203    {
204 #ifdef _WIN32
205       if (errno == WSAEINPROGRESS)
206 #else /* ifndef _WIN32 */
207       if (errno == EINPROGRESS)
208 #endif /* ndef _WIN32 */
209       {
210          break;
211       }
212
213       if (errno != EINTR)
214       {
215          close_socket(fd);
216          return(-1);
217       }
218    }
219
220 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
221    if (flags != -1)
222    {
223       flags &= ~O_NDELAY;
224       fcntl(fd, F_SETFL, flags);
225    }
226 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
227
228    /* wait for connection to complete */
229    FD_ZERO(&wfds);
230    FD_SET(fd, &wfds);
231
232    tv->tv_sec  = 30;
233    tv->tv_usec = 0;
234
235    if (select(fd + 1, NULL, &wfds, NULL, tv) <= 0)
236    {
237       close_socket(fd);
238       return(-1);
239    }
240    return(fd);
241
242 }
243
244
245 /*********************************************************************
246  *
247  * Function    :  write_socket
248  *
249  * Description :  Write the contents of buf (for n bytes) to socket fd.
250  *
251  * Parameters  :
252  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
253  *          2  :  buf = pointer to data to be written.
254  *          3  :  len = length of data to be written to the socket "fd".
255  *
256  * Returns     :  Win32 & Unix: If no error occurs, returns the total number of
257  *                bytes sent, which can be less than the number
258  *                indicated by len. Otherwise, returns (-1).
259  *
260  *********************************************************************/
261 int write_socket(int fd, const char *buf, int len)
262 {
263    if (len <= 0)
264    {
265       return(0);
266    }
267
268    log_error(LOG_LEVEL_LOG, "%N", len, buf);
269
270 #if defined(_WIN32) || defined(__BEOS__) || defined(AMIGA)
271    return( send(fd, buf, len, 0));
272 #else
273    return( write(fd, buf, len));
274 #endif
275
276 }
277
278
279 /*********************************************************************
280  *
281  * Function    :  read_socket
282  *
283  * Description :  Read from a TCP/IP socket in a platform independent way.
284  *
285  * Parameters  :
286  *          1  :  fd = file descriptor of the socket to read
287  *          2  :  buf = pointer to buffer where data will be written
288  *                Must be >= len bytes long.
289  *          3  :  len = maximum number of bytes to read
290  *
291  * Returns     :  On success, the number of bytes read is returned (zero
292  *                indicates end of file), and the file position is advanced
293  *                by this number.  It is not an error if this number is
294  *                smaller than the number of bytes requested; this may hap-
295  *                pen for example because fewer bytes are actually available
296  *                right now (maybe because we were close to end-of-file, or
297  *                because we are reading from a pipe, or from a terminal),
298  *                or because read() was interrupted by a signal.  On error,
299  *                -1 is returned, and errno is set appropriately.  In this
300  *                case it is left unspecified whether the file position (if
301  *                any) changes.
302  *
303  *********************************************************************/
304 int read_socket(int fd, char *buf, int len)
305 {
306    if (len <= 0)
307    {
308       return(0);
309    }
310
311 #if defined(_WIN32) || defined(__BEOS__) || defined(AMIGA)
312    return( recv(fd, buf, len, 0));
313 #else
314    return( read(fd, buf, len));
315 #endif
316 }
317
318
319 /*********************************************************************
320  *
321  * Function    :  close_socket
322  *
323  * Description :  Closes a TCP/IP socket
324  *
325  * Parameters  :
326  *          1  :  fd = file descriptor of socket to be closed
327  *
328  * Returns     :  void
329  *
330  *********************************************************************/
331 void close_socket(int fd)
332 {
333 #if defined(_WIN32) || defined(__BEOS__)
334    closesocket(fd);
335 #elif defined(AMIGA)
336    CloseSocket(fd); 
337 #else
338    close(fd);
339 #endif
340
341 }
342
343
344 /*********************************************************************
345  *
346  * Function    :  bind_port
347  *
348  * Description :  Call socket, set socket options, and listen.
349  *                Called by listen_loop to "boot up" our proxy address.
350  *
351  * Parameters  :
352  *          1  :  hostnam = TCP/IP address to bind/listen to
353  *          2  :  portnum = port to listen on
354  *
355  * Returns     :  if success, return file descriptor
356  *                if failure, returns -2 if address is in use, otherwise -1
357  *
358  *********************************************************************/
359 int bind_port(const char *hostnam, int portnum)
360 {
361    struct sockaddr_in inaddr;
362    int fd;
363    int one = 1;
364
365    memset((char *)&inaddr, '\0', sizeof inaddr);
366
367    inaddr.sin_family      = AF_INET;
368    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
369
370    if (sizeof(inaddr.sin_port) == sizeof(short))
371    {
372       inaddr.sin_port = htons((short)portnum);
373    }
374    else
375    {
376       inaddr.sin_port = htonl(portnum);
377    }
378
379    fd = socket(AF_INET, SOCK_STREAM, 0);
380
381    if (fd < 0)
382    {
383       return(-1);
384    }
385
386 #ifndef _WIN32
387    /*
388     * FIXME: This is not needed for Win32 - in fact, it stops
389     * duplicate instances of JunkBuster from being caught.
390     * Is this really needed under UNIX, or should it be taked out?
391     * -- Jon
392     */
393    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
394 #endif /* ndef _WIN32 */
395
396    if (bind (fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
397    {
398       close_socket (fd);
399 #ifdef _WIN32
400       if (errno == WSAEADDRINUSE)
401 #else
402       if (errno == EADDRINUSE)
403 #endif
404       {
405          return(-2);
406       }
407       else
408       {
409          return(-1);
410       }
411    }
412
413    while (listen(fd, 5) == -1)
414    {
415       if (errno != EINTR)
416       {
417          return(-1);
418       }
419    }
420
421    return fd;
422
423 }
424
425
426 /*********************************************************************
427  *
428  * Function    :  accept_connection
429  *
430  * Description :  Accepts a connection on a socket.  Socket must have
431  *                been created using bind_port().
432  *
433  * Parameters  :
434  *          1  :  csp = Client state, cfd, ip_addr_str, and 
435  *                ip_addr_long will be set by this routine.
436  *          2  :  fd  = file descriptor returned from bind_port
437  *
438  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
439  *                On an error it returns 0 (FALSE).
440  *
441  *********************************************************************/
442 int accept_connection(struct client_state * csp, int fd)
443 {
444    struct sockaddr raddr, laddr;
445    struct sockaddr_in *rap = (struct sockaddr_in *) &raddr;
446    struct sockaddr_in *lap = (struct sockaddr_in *) &laddr;
447    struct hostent *host = NULL;
448    int   afd, raddrlen, laddrlen;
449    char *p;
450
451    raddrlen = sizeof raddr;
452    do
453    {
454       afd = accept (fd, &raddr, &raddrlen);
455    } while (afd < 1 && errno == EINTR);
456
457    if (afd < 0)
458    {
459       return 0;
460    }
461
462    /* 
463     * Determine the IP-Adress that the client used to reach us
464     * and the hostname associated with that address
465     */
466    if (!getsockname(afd, &laddr, &laddrlen))
467    {
468       csp->my_ip_addr_str = strdup(inet_ntoa(lap->sin_addr));
469
470       host = gethostbyaddr(laddr.sa_data + 2, 4, AF_INET);
471       if (host == NULL)
472       {
473          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
474       }
475       else
476       {
477          csp->my_hostname = strdup(host->h_name);
478       }
479    }
480
481    csp->cfd    = afd;
482    csp->ip_addr_str  = strdup(inet_ntoa(rap->sin_addr));
483    csp->ip_addr_long = ntohl(rap->sin_addr.s_addr);
484
485    return 1;
486
487 }
488
489
490 /*********************************************************************
491  *
492  * Function    :  resolve_hostname_to_ip
493  *
494  * Description :  Resolve a hostname to an internet tcp/ip address.
495  *                NULL or an empty string resolve to INADDR_ANY.
496  *
497  * Parameters  :
498  *          1  :  host = hostname to resolve
499  *
500  * Returns     :  -1 => failure, INADDR_ANY or tcp/ip address if succesful.
501  *
502  *********************************************************************/
503 int resolve_hostname_to_ip(const char *host)
504 {
505    struct sockaddr_in inaddr;
506    struct hostent *hostp;
507
508    if ((host == NULL) || (*host == '\0'))
509    {
510       return(INADDR_ANY);
511    }
512
513    memset((char *) &inaddr, 0, sizeof inaddr);
514
515    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
516    {
517       if ((hostp = gethostbyname(host)) == NULL)
518       {
519          errno = EINVAL;
520          return(-1);
521       }
522       if (hostp->h_addrtype != AF_INET)
523       {
524 #ifdef _WIN32
525          errno = WSAEPROTOTYPE;
526 #else
527          errno = EPROTOTYPE;
528 #endif
529          return(-1);
530       }
531       memcpy(
532          (char *) &inaddr.sin_addr,
533          (char *) hostp->h_addr,
534          sizeof(inaddr.sin_addr)
535       );
536    }
537    return(inaddr.sin_addr.s_addr);
538
539 }
540
541
542 /*
543   Local Variables:
544   tab-width: 3
545   end:
546 */