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