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