Remove CVS revision logs. TODO item #33.
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.55 2009/05/10 10:12:30 fabiankeil 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-2009 the
12  *                Privoxy team. http://www.privoxy.org/
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  *********************************************************************/
37
38
39 #include "config.h"
40
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <sys/types.h>
47
48 #ifdef _WIN32
49
50 #ifndef STRICT
51 #define STRICT
52 #endif
53 #include <windows.h>
54 #include <sys/timeb.h>
55 #include <io.h>
56
57 #else
58
59 #ifndef __OS2__
60 #include <unistd.h>
61 #endif
62 #include <sys/time.h>
63 #include <netinet/in.h>
64 #include <sys/ioctl.h>
65 #include <netdb.h>
66 #include <sys/socket.h>
67
68 #ifndef __BEOS__
69 #include <netinet/tcp.h>
70 #ifndef __OS2__
71 #include <arpa/inet.h>
72 #endif
73 #else
74 #include <socket.h>
75 #endif
76
77 #if defined(__EMX__) || defined (__OS2__)
78 #include <sys/select.h>  /* OS/2/EMX needs a little help with select */
79 #ifdef __OS2__
80 #include <nerrno.h>
81 #endif
82 #endif
83
84 #endif
85
86 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
87 #ifdef HAVE_POLL
88 #ifdef __GLIBC__
89 #include <sys/poll.h>
90 #else
91 #include <poll.h>
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
94 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
95
96 #include "project.h"
97
98 #ifdef FEATURE_PTHREAD
99 #include "jcc.h"
100 /* jcc.h is for mutex semaphores only */
101 #endif /* def FEATURE_PTHREAD */
102
103 #include "jbsockets.h"
104 #include "filters.h"
105 #include "errlog.h"
106 #include "miscutil.h"
107
108 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
109
110 /*
111  * Maximum number of gethostbyname(_r) retries in case of
112  * soft errors (TRY_AGAIN).
113  * XXX: Does it make sense to make this a config option?
114  */
115 #define MAX_DNS_RETRIES 10
116
117 #define MAX_LISTEN_BACKLOG 128
118
119
120 /*********************************************************************
121  *
122  * Function    :  connect_to
123  *
124  * Description :  Open a socket and connect to it.  Will check
125  *                that this is allowed according to ACL.
126  *
127  * Parameters  :
128  *          1  :  host = hostname to connect to
129  *          2  :  portnum = port to connent on (XXX: should be unsigned)
130  *          3  :  csp = Current client state (buffers, headers, etc...)
131  *                      Not modified, only used for source IP and ACL.
132  *
133  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
134  *                file descriptor.
135  *
136  *********************************************************************/
137 #ifdef HAVE_RFC2553
138 /* Getaddrinfo implementation */
139 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
140 {
141    struct addrinfo hints, *result, *rp;
142    char service[6];
143    int retval;
144    jb_socket fd;
145    fd_set wfds;
146    struct timeval tv[1];
147 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
148    int   flags;
149 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
150    int connect_failed;
151
152 #ifdef FEATURE_ACL
153    struct access_control_addr dst[1];
154 #endif /* def FEATURE_ACL */
155
156    retval = snprintf(service, sizeof(service), "%d", portnum);
157    if ((-1 == retval) || (sizeof(service) <= retval))
158    {
159       log_error(LOG_LEVEL_ERROR,
160          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
161          portnum);
162       csp->http->host_ip_addr_str = strdup("unknown");
163       return(JB_INVALID_SOCKET);
164    }
165
166    memset((char *)&hints, 0, sizeof(hints));
167    hints.ai_family = AF_UNSPEC;
168    hints.ai_socktype = SOCK_STREAM;
169    hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV; /* avoid service look-up */
170    if ((retval = getaddrinfo(host, service, &hints, &result)))
171    {
172       log_error(LOG_LEVEL_INFO,
173          "Can not resolve %s: %s", host, gai_strerror(retval));
174       csp->http->host_ip_addr_str = strdup("unknown");
175       return(JB_INVALID_SOCKET);
176    }
177
178    for (rp = result; rp != NULL; rp = rp->ai_next)
179    {
180
181 #ifdef FEATURE_ACL
182       memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
183
184       if (block_acl(dst, csp))
185       {
186 #ifdef __OS2__
187          errno = SOCEPERM;
188 #else
189          errno = EPERM;
190 #endif
191          continue;
192       }
193 #endif /* def FEATURE_ACL */
194
195       csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
196       retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
197          csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
198       if (!csp->http->host_ip_addr_str || retval)
199       {
200          log_error(LOG_LEVEL_ERROR,
201             "Can not save csp->http->host_ip_addr_str: %s",
202             (csp->http->host_ip_addr_str) ?
203             gai_strerror(retval) : "Insufficient memory");
204          freez(csp->http->host_ip_addr_str);
205          continue;
206       }
207
208 #ifdef _WIN32
209       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
210             JB_INVALID_SOCKET)
211 #else
212       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
213 #endif
214       {
215          continue;
216       }
217
218 #ifdef TCP_NODELAY
219       {  /* turn off TCP coalescence */
220          int mi = 1;
221          setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
222       }
223 #endif /* def TCP_NODELAY */
224
225 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
226       if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
227       {
228          flags |= O_NDELAY;
229          fcntl(fd, F_SETFL, flags);
230       }
231 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
232
233       connect_failed = 0;
234       while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
235       {
236 #ifdef _WIN32
237          if (errno == WSAEINPROGRESS)
238 #elif __OS2__
239          if (sock_errno() == EINPROGRESS)
240 #else /* ifndef _WIN32 */
241          if (errno == EINPROGRESS)
242 #endif /* ndef _WIN32 || __OS2__ */
243          {
244             break;
245          }
246
247 #ifdef __OS2__
248          if (sock_errno() != EINTR)
249 #else
250          if (errno != EINTR)
251 #endif /* __OS2__ */
252          {
253             close_socket(fd);
254             connect_failed = 1;
255             break;
256          }
257       }
258       if (connect_failed)
259       {
260          continue;
261       }
262
263 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
264       if (flags != -1)
265       {
266          flags &= ~O_NDELAY;
267          fcntl(fd, F_SETFL, flags);
268       }
269 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
270
271       /* wait for connection to complete */
272       FD_ZERO(&wfds);
273       FD_SET(fd, &wfds);
274
275       tv->tv_sec  = 30;
276       tv->tv_usec = 0;
277
278       /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
279       if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
280       {
281          close_socket(fd);
282          continue;
283       }
284
285       break; /* for; Connection established; don't try other addresses */
286    }
287
288    freeaddrinfo(result);
289    if (!rp)
290    {
291       log_error(LOG_LEVEL_INFO,
292          "Could not connect to TCP/[%s]:%s", host, service);
293       return(JB_INVALID_SOCKET);
294    }
295    /*
296     * XXX: Current connection verification (EINPROGRESS && select()
297     * for writing) is not sufficient. E.g. on Linux-2.6.27 with glibc-2.6
298     * select returns socket ready for writing, however subsequential
299     * write(2) fails with ENOCONNECT. Read Linux connect(2) man page
300     * about non-blocking sockets.
301     * Thus we can't log here that the socket is connected.
302     */
303    /* log_error(LOG_LEVEL_INFO, "Connected to TCP/[%s]:%s", host, service); */
304
305    return(fd);
306
307 }
308
309 #else /* ndef HAVE_RFC2553 */
310 /* Pre-getaddrinfo implementation */
311
312 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
313 {
314    struct sockaddr_in inaddr;
315    jb_socket fd;
316    unsigned int addr;
317    fd_set wfds;
318    struct timeval tv[1];
319 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
320    int   flags;
321 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
322
323 #ifdef FEATURE_ACL
324    struct access_control_addr dst[1];
325 #endif /* def FEATURE_ACL */
326
327    memset((char *)&inaddr, 0, sizeof inaddr);
328
329    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
330    {
331       csp->http->host_ip_addr_str = strdup("unknown");
332       return(JB_INVALID_SOCKET);
333    }
334
335 #ifdef FEATURE_ACL
336    dst->addr = ntohl(addr);
337    dst->port = portnum;
338
339    if (block_acl(dst, csp))
340    {
341 #ifdef __OS2__
342       errno = SOCEPERM;
343 #else
344       errno = EPERM;
345 #endif
346       return(JB_INVALID_SOCKET);
347    }
348 #endif /* def FEATURE_ACL */
349
350    inaddr.sin_addr.s_addr = addr;
351    inaddr.sin_family      = AF_INET;
352    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
353
354 #ifndef _WIN32
355    if (sizeof(inaddr.sin_port) == sizeof(short))
356 #endif /* ndef _WIN32 */
357    {
358       inaddr.sin_port = htons((unsigned short) portnum);
359    }
360 #ifndef _WIN32
361    else
362    {
363       inaddr.sin_port = htonl((unsigned long)portnum);
364    }
365 #endif /* ndef _WIN32 */
366
367 #ifdef _WIN32
368    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
369 #else
370    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
371 #endif
372    {
373       return(JB_INVALID_SOCKET);
374    }
375
376 #ifdef TCP_NODELAY
377    {  /* turn off TCP coalescence */
378       int mi = 1;
379       setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
380    }
381 #endif /* def TCP_NODELAY */
382
383 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
384    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
385    {
386       flags |= O_NDELAY;
387       fcntl(fd, F_SETFL, flags);
388    }
389 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
390
391    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
392    {
393 #ifdef _WIN32
394       if (errno == WSAEINPROGRESS)
395 #elif __OS2__ 
396       if (sock_errno() == EINPROGRESS)
397 #else /* ifndef _WIN32 */
398       if (errno == EINPROGRESS)
399 #endif /* ndef _WIN32 || __OS2__ */
400       {
401          break;
402       }
403
404 #ifdef __OS2__ 
405       if (sock_errno() != EINTR)
406 #else
407       if (errno != EINTR)
408 #endif /* __OS2__ */
409       {
410          close_socket(fd);
411          return(JB_INVALID_SOCKET);
412       }
413    }
414
415 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
416    if (flags != -1)
417    {
418       flags &= ~O_NDELAY;
419       fcntl(fd, F_SETFL, flags);
420    }
421 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
422
423    /* wait for connection to complete */
424    FD_ZERO(&wfds);
425    FD_SET(fd, &wfds);
426
427    tv->tv_sec  = 30;
428    tv->tv_usec = 0;
429
430    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
431    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
432    {
433       close_socket(fd);
434       return(JB_INVALID_SOCKET);
435    }
436    return(fd);
437
438 }
439 #endif /* ndef HAVE_RFC2553 */
440
441
442 /*********************************************************************
443  *
444  * Function    :  write_socket
445  *
446  * Description :  Write the contents of buf (for n bytes) to socket fd.
447  *
448  * Parameters  :
449  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
450  *          2  :  buf = pointer to data to be written.
451  *          3  :  len = length of data to be written to the socket "fd".
452  *
453  * Returns     :  0 on success (entire buffer sent).
454  *                nonzero on error.
455  *
456  *********************************************************************/
457 #ifdef AMIGA
458 int write_socket(jb_socket fd, const char *buf, ssize_t len)
459 #else
460 int write_socket(jb_socket fd, const char *buf, size_t len)
461 #endif
462 {
463    if (len == 0)
464    {
465       return 0;
466    }
467
468    if (len < 0) /* constant condition - size_t isn't ever negative */ 
469    {
470       return 1;
471    }
472
473    log_error(LOG_LEVEL_LOG, "%N", len, buf);
474
475 #if defined(_WIN32)
476    return (send(fd, buf, (int)len, 0) != (int)len);
477 #elif defined(__BEOS__) || defined(AMIGA)
478    return (send(fd, buf, len, 0) != len);
479 #elif defined(__OS2__)
480    /*
481     * Break the data up into SOCKET_SEND_MAX chunks for sending...
482     * OS/2 seemed to complain when the chunks were too large.
483     */
484 #define SOCKET_SEND_MAX 65000
485    {
486       int write_len = 0, send_len, send_rc = 0, i = 0;
487       while ((i < len) && (send_rc != -1))
488       {
489          if ((i + SOCKET_SEND_MAX) > len)
490             send_len = len - i;
491          else
492             send_len = SOCKET_SEND_MAX;
493          send_rc = send(fd,(char*)buf + i, send_len, 0);
494          if (send_rc == -1)
495             return 1;
496          i = i + send_len;
497       }
498       return 0;
499    }
500 #else
501    return (write(fd, buf, len) != len);
502 #endif
503
504 }
505
506
507 /*********************************************************************
508  *
509  * Function    :  read_socket
510  *
511  * Description :  Read from a TCP/IP socket in a platform independent way.
512  *
513  * Parameters  :
514  *          1  :  fd = file descriptor of the socket to read
515  *          2  :  buf = pointer to buffer where data will be written
516  *                Must be >= len bytes long.
517  *          3  :  len = maximum number of bytes to read
518  *
519  * Returns     :  On success, the number of bytes read is returned (zero
520  *                indicates end of file), and the file position is advanced
521  *                by this number.  It is not an error if this number is
522  *                smaller than the number of bytes requested; this may hap-
523  *                pen for example because fewer bytes are actually available
524  *                right now (maybe because we were close to end-of-file, or
525  *                because we are reading from a pipe, or from a terminal,
526  *                or because read() was interrupted by a signal).  On error,
527  *                -1 is returned, and errno is set appropriately.  In this
528  *                case it is left unspecified whether the file position (if
529  *                any) changes.
530  *
531  *********************************************************************/
532 int read_socket(jb_socket fd, char *buf, int len)
533 {
534    if (len <= 0)
535    {
536       return(0);
537    }
538
539 #if defined(_WIN32)
540    return(recv(fd, buf, len, 0));
541 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
542    return(recv(fd, buf, (size_t)len, 0));
543 #else
544    return(read(fd, buf, (size_t)len));
545 #endif
546 }
547
548
549 /*********************************************************************
550  *
551  * Function    :  data_is_available
552  *
553  * Description :  Waits for data to arrive on a socket.
554  *
555  * Parameters  :
556  *          1  :  fd = file descriptor of the socket to read
557  *          2  :  seconds_to_wait = number of seconds after which we give up.
558  *
559  * Returns     :  TRUE if data arrived in time,
560  *                FALSE otherwise.
561  *
562  *********************************************************************/
563 int data_is_available(jb_socket fd, int seconds_to_wait)
564 {
565    fd_set rfds;
566    struct timeval timeout;
567    int n;
568
569    memset(&timeout, 0, sizeof(timeout));
570    timeout.tv_sec = seconds_to_wait;
571
572 #ifdef __OS2__
573    /* Copy and pasted from jcc.c ... */
574    memset(&rfds, 0, sizeof(fd_set));
575 #else
576    FD_ZERO(&rfds);
577 #endif
578    FD_SET(fd, &rfds);
579
580    n = select(fd+1, &rfds, NULL, NULL, &timeout);
581
582    /*
583     * XXX: Do we care about the different error conditions?
584     */
585    return (n == 1);
586 }
587
588
589 /*********************************************************************
590  *
591  * Function    :  close_socket
592  *
593  * Description :  Closes a TCP/IP socket
594  *
595  * Parameters  :
596  *          1  :  fd = file descriptor of socket to be closed
597  *
598  * Returns     :  void
599  *
600  *********************************************************************/
601 void close_socket(jb_socket fd)
602 {
603 #if defined(_WIN32) || defined(__BEOS__)
604    closesocket(fd);
605 #elif defined(AMIGA)
606    CloseSocket(fd); 
607 #elif defined(__OS2__)
608    soclose(fd);
609 #else
610    close(fd);
611 #endif
612
613 }
614
615
616 /*********************************************************************
617  *
618  * Function    :  bind_port
619  *
620  * Description :  Call socket, set socket options, and listen.
621  *                Called by listen_loop to "boot up" our proxy address.
622  *
623  * Parameters  :
624  *          1  :  hostnam = TCP/IP address to bind/listen to
625  *          2  :  portnum = port to listen on
626  *          3  :  pfd = pointer used to return file descriptor.
627  *
628  * Returns     :  if success, returns 0 and sets *pfd.
629  *                if failure, returns -3 if address is in use,
630  *                                    -2 if address unresolvable,
631  *                                    -1 otherwise
632  *********************************************************************/
633 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
634 {
635 #ifdef HAVE_RFC2553
636    struct addrinfo hints;
637    struct addrinfo *result, *rp;
638    /*
639     * XXX: portnum should be a string to allow symbolic service
640     * names in the configuration file and to avoid the following
641     * int2string.
642     */
643    char servnam[6];
644    int retval;
645 #else
646    struct sockaddr_in inaddr;
647 #endif /* def HAVE_RFC2553 */
648    jb_socket fd;
649 #ifndef _WIN32
650    int one = 1;
651 #endif /* ndef _WIN32 */
652
653    *pfd = JB_INVALID_SOCKET;
654
655 #ifdef HAVE_RFC2553
656    retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
657    if ((-1 == retval) || (sizeof(servnam) <= retval))
658    {
659       log_error(LOG_LEVEL_ERROR,
660          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
661          portnum);
662       return -1;
663    }
664
665    memset(&hints, 0, sizeof(struct addrinfo));
666    if ((hostnam == NULL) || !strcmpic(hostnam, "localhost"))
667    {
668       /*
669        * XXX: This is a hack. The right thing to do
670        * would be to bind to both AF_INET and AF_INET6.
671        * This will also fail if there is no AF_INET
672        * version available.
673        */
674       hints.ai_family = AF_INET;
675    }
676    else
677    {
678       hints.ai_family = AF_UNSPEC;
679    }
680    hints.ai_socktype = SOCK_STREAM;
681    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
682    hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
683    hints.ai_canonname = NULL;
684    hints.ai_addr = NULL;
685    hints.ai_next = NULL;
686
687    if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
688    {
689       log_error(LOG_LEVEL_ERROR,
690          "Can not resolve %s: %s", hostnam, gai_strerror(retval));
691       return -2;
692    }
693 #else
694    memset((char *)&inaddr, '\0', sizeof inaddr);
695
696    inaddr.sin_family      = AF_INET;
697    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
698
699    if (inaddr.sin_addr.s_addr == INADDR_NONE)
700    {
701       return(-2);
702    }
703
704 #ifndef _WIN32
705    if (sizeof(inaddr.sin_port) == sizeof(short))
706 #endif /* ndef _WIN32 */
707    {
708       inaddr.sin_port = htons((unsigned short) portnum);
709    }
710 #ifndef _WIN32
711    else
712    {
713       inaddr.sin_port = htonl((unsigned long) portnum);
714    }
715 #endif /* ndef _WIN32 */
716 #endif /* def HAVE_RFC2553 */
717
718 #ifdef HAVE_RFC2553
719    for (rp = result; rp != NULL; rp = rp->ai_next)
720    {
721       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
722 #else
723    fd = socket(AF_INET, SOCK_STREAM, 0);
724 #endif /* def HAVE_RFC2553 */
725
726 #ifdef _WIN32
727    if (fd == JB_INVALID_SOCKET)
728 #else
729    if (fd < 0)
730 #endif
731    {
732 #ifdef HAVE_RFC2553
733       continue;
734 #else
735       return(-1);
736 #endif
737    }
738
739 #ifndef _WIN32
740    /*
741     * This is not needed for Win32 - in fact, it stops
742     * duplicate instances of Privoxy from being caught.
743     *
744     * On UNIX, we assume the user is sensible enough not
745     * to start Privoxy multiple times on the same IP.
746     * Without this, stopping and restarting Privoxy
747     * from a script fails.
748     * Note: SO_REUSEADDR is meant to only take over
749     * sockets which are *not* in listen state in Linux,
750     * e.g. sockets in TIME_WAIT. YMMV.
751     */
752    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
753 #endif /* ndef _WIN32 */
754
755 #ifdef HAVE_RFC2553
756    if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
757 #else
758    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
759 #endif
760    {
761 #ifdef _WIN32
762       errno = WSAGetLastError();
763       if (errno == WSAEADDRINUSE)
764 #else
765       if (errno == EADDRINUSE)
766 #endif
767       {
768 #ifdef HAVE_RFC2553
769          freeaddrinfo(result);
770 #endif
771          close_socket(fd);
772          return(-3);
773       }
774       else
775       {
776          close_socket(fd);
777 #ifndef HAVE_RFC2553
778          return(-1);
779       }
780    }
781 #else
782       }
783    }
784    else
785    {
786       /* bind() succeeded, escape from for-loop */
787       /*
788        * XXX: Support multiple listening sockets (e.g. localhost
789        * resolves to AF_INET and AF_INET6, but only the first address
790        * is used
791        */
792       break;
793    }
794    }
795
796    freeaddrinfo(result);
797    if (rp == NULL)
798    {
799       /* All bind()s failed */
800       return(-1);
801    }
802 #endif /* ndef HAVE_RFC2553 */
803
804    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
805    {
806       if (errno != EINTR)
807       {
808          return(-1);
809       }
810    }
811
812    *pfd = fd;
813    return 0;
814
815 }
816
817
818 /*********************************************************************
819  *
820  * Function    :  get_host_information
821  *
822  * Description :  Determines the IP address the client used to
823  *                reach us and the hostname associated with it.
824  *
825  *                XXX: Most of the code has been copy and pasted
826  *                from accept_connection() and not all of the
827  *                ifdefs paths have been tested afterwards.
828  *
829  * Parameters  :
830  *          1  :  afd = File descriptor returned from accept().
831  *          2  :  ip_address = Pointer to return the pointer to
832  *                             the ip address string.
833  *          3  :  hostname =   Pointer to return the pointer to
834  *                             the hostname or NULL if the caller
835  *                             isn't interested in it.
836  *
837  * Returns     :  void.
838  *
839  *********************************************************************/
840 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
841 {
842 #ifdef HAVE_RFC2553
843    struct sockaddr_storage server;
844    int retval;
845 #else
846    struct sockaddr_in server;
847    struct hostent *host = NULL;
848 #endif /* HAVE_RFC2553 */
849 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
850    /* according to accept_connection() this fixes a warning. */
851    int s_length, s_length_provided;
852 #else
853    socklen_t s_length, s_length_provided;
854 #endif
855 #ifndef HAVE_RFC2553
856 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
857    struct hostent result;
858 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
859    struct hostent_data hdata;
860 #else
861    char hbuf[HOSTENT_BUFFER_SIZE];
862    int thd_err;
863 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
864 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
865 #endif /* ifndef HAVE_RFC2553 */
866    s_length = s_length_provided = sizeof(server);
867
868    if (NULL != hostname)
869    {
870       *hostname = NULL;
871    }
872    *ip_address = NULL;
873
874    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
875    {
876       if (s_length > s_length_provided)
877       {
878          log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
879          return;
880       }
881 #ifdef HAVE_RFC2553
882       *ip_address = malloc(NI_MAXHOST);
883       retval = getnameinfo((struct sockaddr *) &server, s_length,
884          *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
885       if (retval)
886       {
887          log_error(LOG_LEVEL_ERROR,
888             "Unable to print my own IP address: %s", gai_strerror(retval));
889          freez(*ip_address);
890          return;
891       }
892 #else
893       *ip_address = strdup(inet_ntoa(server.sin_addr));
894 #endif /* HAVE_RFC2553 */
895       if (NULL == hostname)
896       {
897          /*
898           * We're done here, the caller isn't
899           * interested in knowing the hostname.
900           */
901          return;
902       }
903
904 #ifdef HAVE_RFC2553
905       *hostname = malloc(NI_MAXHOST);
906       retval = getnameinfo((struct sockaddr *) &server, s_length,
907          *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
908       if (retval)
909       {
910          log_error(LOG_LEVEL_ERROR,
911             "Unable to resolve my own IP address: %s", gai_strerror(retval));
912          freez(*hostname);
913       }
914 #else
915 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
916       gethostbyaddr_r((const char *)&server.sin_addr,
917                       sizeof(server.sin_addr), AF_INET,
918                       &result, hbuf, HOSTENT_BUFFER_SIZE,
919                       &host, &thd_err);
920 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
921       host = gethostbyaddr_r((const char *)&server.sin_addr,
922                       sizeof(server.sin_addr), AF_INET,
923                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
924 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
925       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
926                                sizeof(server.sin_addr), AF_INET,
927                                &result, &hdata))
928       {
929          host = &result;
930       }
931       else
932       {
933          host = NULL;
934       }
935 #elif FEATURE_PTHREAD
936       privoxy_mutex_lock(&resolver_mutex);
937       host = gethostbyaddr((const char *)&server.sin_addr, 
938                            sizeof(server.sin_addr), AF_INET);
939       privoxy_mutex_unlock(&resolver_mutex);
940 #else
941       host = gethostbyaddr((const char *)&server.sin_addr, 
942                            sizeof(server.sin_addr), AF_INET);
943 #endif
944       if (host == NULL)
945       {
946          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
947       }
948       else
949       {
950          *hostname = strdup(host->h_name);
951       }
952 #endif /* else def HAVE_RFC2553 */
953    }
954
955    return;
956 }
957
958
959 /*********************************************************************
960  *
961  * Function    :  accept_connection
962  *
963  * Description :  Accepts a connection on a socket.  Socket must have
964  *                been created using bind_port().
965  *
966  * Parameters  :
967  *          1  :  csp = Client state, cfd, ip_addr_str, and 
968  *                ip_addr_long will be set by this routine.
969  *          2  :  fd  = file descriptor returned from bind_port
970  *
971  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
972  *                On an error it returns 0 (FALSE).
973  *
974  *********************************************************************/
975 int accept_connection(struct client_state * csp, jb_socket fd)
976 {
977 #ifdef HAVE_RFC2553
978    /* XXX: client is stored directly into csp->tcp_addr */
979 #define client (csp->tcp_addr)
980    int retval;
981 #else
982    struct sockaddr_in client;
983 #endif
984    jb_socket afd;
985 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
986    /* Wierdness - fix a warning. */
987    int c_length;
988 #else
989    socklen_t c_length;
990 #endif
991
992    c_length = sizeof(client);
993
994 #ifdef _WIN32
995    afd = accept (fd, (struct sockaddr *) &client, &c_length);
996    if (afd == JB_INVALID_SOCKET)
997    {
998       return 0;
999    }
1000 #else
1001    do
1002    {
1003       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1004    } while (afd < 1 && errno == EINTR);
1005    if (afd < 0)
1006    {
1007       return 0;
1008    }
1009 #endif
1010
1011    csp->cfd = afd;
1012 #ifdef HAVE_RFC2553
1013    csp->ip_addr_str = malloc(NI_MAXHOST);
1014    retval = getnameinfo((struct sockaddr *) &client, c_length,
1015          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1016    if (!csp->ip_addr_str || retval)
1017    {
1018       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1019             (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1020       freez(csp->ip_addr_str);
1021    }
1022 #undef client
1023 #else
1024    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1025    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1026 #endif /* def HAVE_RFC2553 */
1027
1028    return 1;
1029
1030 }
1031
1032
1033 /*********************************************************************
1034  *
1035  * Function    :  resolve_hostname_to_ip
1036  *
1037  * Description :  Resolve a hostname to an internet tcp/ip address.
1038  *                NULL or an empty string resolve to INADDR_ANY.
1039  *
1040  * Parameters  :
1041  *          1  :  host = hostname to resolve
1042  *
1043  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1044  *
1045  *********************************************************************/
1046 unsigned long resolve_hostname_to_ip(const char *host)
1047 {
1048    struct sockaddr_in inaddr;
1049    struct hostent *hostp;
1050    unsigned int dns_retries = 0;
1051 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1052    struct hostent result;
1053 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1054    char hbuf[HOSTENT_BUFFER_SIZE];
1055    int thd_err;
1056 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1057    struct hostent_data hdata;
1058 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1059 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1060
1061    if ((host == NULL) || (*host == '\0'))
1062    {
1063       return(INADDR_ANY);
1064    }
1065
1066    memset((char *) &inaddr, 0, sizeof inaddr);
1067
1068    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1069    {
1070 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1071       while (gethostbyname_r(host, &result, hbuf,
1072                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1073              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1074       {   
1075          log_error(LOG_LEVEL_ERROR,
1076             "Timeout #%u while trying to resolve %s. Trying again.",
1077             dns_retries, host);
1078       }
1079 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1080       while (NULL == (hostp = gethostbyname_r(host, &result,
1081                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1082              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1083       {   
1084          log_error(LOG_LEVEL_ERROR,
1085             "Timeout #%u while trying to resolve %s. Trying again.",
1086             dns_retries, host);
1087       }
1088 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1089       /*
1090        * XXX: Doesn't retry in case of soft errors.
1091        * Does this gethostbyname_r version set h_errno?
1092        */
1093       if (0 == gethostbyname_r(host, &result, &hdata))
1094       {
1095          hostp = &result;
1096       }
1097       else
1098       {
1099          hostp = NULL;
1100       }
1101 #elif FEATURE_PTHREAD
1102       privoxy_mutex_lock(&resolver_mutex);
1103       while (NULL == (hostp = gethostbyname(host))
1104              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1105       {   
1106          log_error(LOG_LEVEL_ERROR,
1107             "Timeout #%u while trying to resolve %s. Trying again.",
1108             dns_retries, host);
1109       }
1110       privoxy_mutex_unlock(&resolver_mutex);
1111 #else
1112       while (NULL == (hostp = gethostbyname(host))
1113              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1114       {
1115          log_error(LOG_LEVEL_ERROR,
1116             "Timeout #%u while trying to resolve %s. Trying again.",
1117             dns_retries, host);
1118       }
1119 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1120       /*
1121        * On Mac OSX, if a domain exists but doesn't have a type A
1122        * record associated with it, the h_addr member of the struct
1123        * hostent returned by gethostbyname is NULL, even if h_length
1124        * is 4. Therefore the second test below.
1125        */
1126       if (hostp == NULL || hostp->h_addr == NULL)
1127       {
1128          errno = EINVAL;
1129          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1130          return(INADDR_NONE);
1131       }
1132       if (hostp->h_addrtype != AF_INET)
1133       {
1134 #ifdef _WIN32
1135          errno = WSAEPROTOTYPE;
1136 #else
1137          errno = EPROTOTYPE;
1138 #endif 
1139          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1140          return(INADDR_NONE);
1141       }
1142       memcpy(
1143          (char *) &inaddr.sin_addr,
1144          (char *) hostp->h_addr,
1145          sizeof(inaddr.sin_addr)
1146       );
1147    }
1148    return(inaddr.sin_addr.s_addr);
1149
1150 }
1151
1152
1153 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1154 /*********************************************************************
1155  *
1156  * Function    :  socket_is_still_usable
1157  *
1158  * Description :  Decides whether or not an open socket is still usable.
1159  *
1160  * Parameters  :
1161  *          1  :  sfd = The socket to check.
1162  *
1163  * Returns     :  TRUE for yes, otherwise FALSE.
1164  *
1165  *********************************************************************/
1166 int socket_is_still_usable(jb_socket sfd)
1167 {
1168 #ifdef HAVE_POLL
1169    int poll_result;
1170    struct pollfd poll_fd[1];
1171
1172    memset(poll_fd, 0, sizeof(poll_fd));
1173    poll_fd[0].fd = sfd;
1174    poll_fd[0].events = POLLIN;
1175
1176    poll_result = poll(poll_fd, 1, 0);
1177
1178    if (-1 != poll_result)
1179    {
1180       return !(poll_fd[0].revents & POLLIN);
1181    }
1182    else
1183    {
1184       log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1185       return FALSE;
1186    }
1187 #else
1188    fd_set readable_fds;
1189    struct timeval timeout;
1190    int ret;
1191    int socket_is_alive = 0;
1192
1193    memset(&timeout, '\0', sizeof(timeout));
1194    FD_ZERO(&readable_fds);
1195    FD_SET(sfd, &readable_fds);
1196
1197    ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1198    if (ret < 0)
1199    {
1200       log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1201    }
1202
1203    /*
1204     * XXX: I'm not sure why !FD_ISSET() works,
1205     * but apparently it does.
1206     */
1207    socket_is_alive = !FD_ISSET(sfd, &readable_fds);
1208
1209    return socket_is_alive;
1210 #endif /* def HAVE_POLL */
1211 }
1212 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1213
1214
1215 /*
1216   Local Variables:
1217   tab-width: 3
1218   end:
1219 */