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