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