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