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