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