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