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