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