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