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