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