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