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