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