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