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