const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.3 2003/06/19 15:58:58 lionel Exp $";
/*********************************************************************
 *
 * File        :  $Source: /ds6/cvs/privoxy/src/jbsockets.c,v $
 *
 * Purpose     :  Contains wrappers for system-specific sockets code,
 *                so that the rest of Junkbuster can be more
 *                OS-independent.  Contains #ifdefs to make this work
 *                on many platforms.
 *
 * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
 *                Privoxy team. http://www.privoxy.org/
 *
 *                Modified by Lionel Elie Mamane <lionel@mamane.lu>
 *                for IPv6 support on 8-9 December 2002, 24 January 2003,
 *                13 February 2003.
 *
 *                Based on the Internet Junkbuster originally written
 *                by and Copyright (C) 1997 Anonymous Coders and 
 *                Junkbusters Corporation.  http://www.junkbusters.com
 *
 *                This program is free software; you can redistribute it 
 *                and/or modify it under the terms of the GNU General
 *                Public License as published by the Free Software
 *                Foundation; either version 2 of the License, or (at
 *                your option) any later version.
 *
 *                This program is distributed in the hope that it will
 *                be useful, but WITHOUT ANY WARRANTY; without even the
 *                implied warranty of MERCHANTABILITY or FITNESS FOR A
 *                PARTICULAR PURPOSE.  See the GNU General Public
 *                License for more details.
 *
 *                The GNU General Public License should be included with
 *                this file.  If not, you can view it at
 *                http://www.gnu.org/copyleft/gpl.html
 *                or write to the Free Software Foundation, Inc., 59
 *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Revisions   :
 *    $Log: jbsockets.c,v $
 *    Revision 1.3  2003/06/19 15:58:58  lionel
 *    Fix mask calculation in fill_acl_addr_mask in IPv6 case
 *    Where there's a sockaddr, there's an addrlen. Fixes portability to (Free)BSD.
 *
 *    Revision 1.2  2003/05/23 11:31:48  lionel
 *    Version 4 of IPv6 support, Lionel 13 Feb 2003
 *
 *    Revision 1.1.1.1  2003/05/23 11:19:16  lionel
 *    Initial import of upstream 13 Feb 2003 CVS
 *
 *    Revision 2.1  2002/12/30 19:56:16  david__schmidt
 *    End of initial drop of statistics console infrastructure.  Data stream
 *    is transmitted on the stats port every interval, provided the data has
 *    changed since the last transmission.  More work probably needs to be
 *    done with regard to multiplatform threading; I stole the thread spawning
 *    code from jcc.c, but haven't been able to test it everywhere.
 *
 *    Revision 2.0  2002/06/04 14:34:21  jongfoster
 *    Moving source files to src/
 *
 *    Revision 1.36  2002/05/26 23:23:10  joergs
 *    AmigaOS: Fixed wrong type for len in write_socket()
 *
 *    Revision 1.35  2002/04/26 15:50:04  joergs
 *    AmigaOS: No socklen_t, added AMIGA to the systems using int instead.
 *
 *    Revision 1.34  2002/04/08 20:31:41  swa
 *    fixed JB spelling
 *
 *    Revision 1.33  2002/04/03 16:02:18  gliptak
 *    Correcting compile warning with older gcc
 *
 *    Revision 1.32  2002/03/31 17:18:59  jongfoster
 *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
 *
 *    Revision 1.31  2002/03/29 03:33:13  david__schmidt
 *    Fix Mac OSX compiler warnings
 *
 *    Revision 1.30  2002/03/27 14:32:43  david__schmidt
 *    More compiler warning message maintenance
 *
 *    Revision 1.29  2002/03/26 22:29:54  swa
 *    we have a new homepage!
 *
 *    Revision 1.28  2002/03/24 13:25:43  swa
 *    name change related issues
 *
 *    Revision 1.27  2002/03/13 00:27:05  jongfoster
 *    Killing warnings
 *
 *    Revision 1.26  2002/03/11 22:07:02  david__schmidt
 *    OS/2 port maintenance:
 *    - Fixed EMX build - it had decayed a little
 *    - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
 *      substituted a memset for now.
 *
 *    Revision 1.25  2002/03/09 20:03:52  jongfoster
 *    - Making various functions return int rather than size_t.
 *      (Undoing a recent change).  Since size_t is unsigned on
 *      Windows, functions like read_socket that return -1 on
 *      error cannot return a size_t.
 *
 *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
 *      crashes, and also frequently caused JB to jump to 100%
 *      CPU and stay there.  (Because it thought it had just
 *      read ((unsigned)-1) == 4Gb of data...)
 *
 *    - The signature of write_socket has changed, it now simply
 *      returns success=0/failure=nonzero.
 *
 *    - Trying to get rid of a few warnings --with-debug on
 *      Windows, I've introduced a new type "jb_socket".  This is
 *      used for the socket file descriptors.  On Windows, this
 *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
 *      an int.  The error value can't be -1 any more, so it's
 *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
 *      Windows it maps to the #define INVALID_SOCKET.)
 *
 *    - The signature of bind_port has changed.
 *
 *    Revision 1.24  2002/03/07 03:51:36  oes
 *     - Improved handling of failed DNS lookups
 *     - Fixed compiler warnings etc
 *
 *    Revision 1.23  2002/03/05 00:36:01  jongfoster
 *    Fixing bug 514988 - unable to restart Junkbuster
 *
 *    Revision 1.22  2002/03/04 02:08:02  david__schmidt
 *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
 *
 *    Revision 1.21  2002/01/09 14:32:33  oes
 *    Added support for gethostbyname_r and gethostbyaddr_r.
 *
 *    Revision 1.20  2001/11/16 00:48:48  jongfoster
 *    Enabling duplicate-socket detection for all platforms, not
 *    just Win32.
 *
 *    Revision 1.19  2001/10/25 03:40:47  david__schmidt
 *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
 *    threads to call select() simultaneously.  So, it's time to do a real, live,
 *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
 *    (native). Both versions will work, but using __OS2__ offers multi-threading.
 *
 *    Revision 1.18  2001/09/21 23:02:02  david__schmidt
 *    Cleaning up 2 compiler warnings on OS/2.
 *
 *    Revision 1.17  2001/09/13 20:11:46  jongfoster
 *    Fixing 2 compiler warnings under Win32
 *
 *    Revision 1.16  2001/07/30 22:08:36  jongfoster
 *    Tidying up #defines:
 *    - All feature #defines are now of the form FEATURE_xxx
 *    - Permanently turned off WIN_GUI_EDIT
 *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
 *
 *    Revision 1.15  2001/07/29 17:40:43  jongfoster
 *    Fixed compiler warning by adding a cast
 *
 *    Revision 1.14  2001/07/18 13:47:59  oes
 *    Eliminated dirty hack for getsockbyname()
 *
 *    Revision 1.13  2001/07/15 13:56:57  jongfoster
 *    Removing unused local variable.
 *
 *    Revision 1.12  2001/07/01 17:04:11  oes
 *    Bugfix: accept_connection no longer uses the obsolete hstrerror() function
 *
 *    Revision 1.11  2001/06/29 21:45:41  oes
 *    Indentation, CRLF->LF, Tab-> Space
 *
 *    Revision 1.10  2001/06/29 13:29:15  oes
 *    - Added remote (server) host IP to csp->http->host_ip_addr_str
 *    - Added detection of local socket IP and fqdn
 *    - Removed logentry from cancelled commit
 *
 *    Revision 1.9  2001/06/07 23:06:09  jongfoster
 *    The host parameter to connect_to() is now const.
 *
 *    Revision 1.8  2001/06/03 19:12:07  oes
 *    filled comment
 *
 *    Revision 1.7  2001/05/28 16:14:00  jongfoster
 *    Fixing bug in LOG_LEVEL_LOG
 *
 *    Revision 1.6  2001/05/26 17:28:32  jongfoster
 *    Fixed LOG_LEVEL_LOG
 *
 *    Revision 1.5  2001/05/26 15:26:15  jongfoster
 *    ACL feature now provides more security by immediately dropping
 *    connections from untrusted hosts.
 *
 *    Revision 1.4  2001/05/26 00:37:42  jongfoster
 *    Cosmetic indentation correction.
 *
 *    Revision 1.3  2001/05/25 21:57:54  jongfoster
 *    Now gives a warning under Windows if you try to bind
 *    it to a port that's already in use.
 *
 *    Revision 1.2  2001/05/17 23:01:01  oes
 *     - Cleaned CRLF's from the sources and related files
 *
 *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
 *    Initial import of version 2.9.3 source tree
 *
 *
 *********************************************************************/


#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>

#ifdef _WIN32

#ifndef STRICT
#define STRICT
#endif
#include <windows.h>
#include <sys/timeb.h>
#include <io.h>

#else

#ifndef __OS2__
#include <unistd.h>
#endif
#include <sys/time.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <sys/socket.h>

#ifndef __BEOS__
#include <netinet/tcp.h>
#ifndef __OS2__
#include <arpa/inet.h>
#endif
#else
#include <socket.h>
#endif

#if defined(__EMX__) || defined (__OS2__)
#include <sys/select.h>  /* OS/2/EMX needs a little help with select */
#ifdef __OS2__
#include <nerrno.h>
#endif
#endif

#endif

#include "project.h"
#include "jbsockets.h"
#include "filters.h"
#include "errlog.h"
#include "addrlist.h"

const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;


/*********************************************************************
 *
 * Function    :  connect_to
 *
 * Description :  Open a socket and connect to it.  Will check
 *                that this is allowed according to ACL.
 *
 * Parameters  :
 *          0  :  host = hostname to connect to
 *          1  :  port = port to connect on, as string
 *          2  :  portnum = port to connect on, as integer
 *          3  :  csp = Current client state (buffers, headers, etc...)
 *
 * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
 *                file descriptor.
 *
 *********************************************************************/
jb_socket connect_to_one_ip(struct sockaddr_storage *addr, size_t addrlen, const char *host, unsigned long portnum, struct client_state *csp)
{
#ifdef FEATURE_ACL
   if (csp)
   {
      struct access_control_addr dst[1];
      char hostname[NI_MAXHOST];
      char port[NI_MAXSERV];
      if (getnameinfo((struct sockaddr*)addr, addrlen, hostname, NI_MAXHOST,
                      port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0)
      {
         log_error(LOG_LEVEL_ERROR, "connect: Could not get string address and port back from sockaddr because %E");
         strncpy(hostname,"unknown",NI_MAXHOST);
         strncpy(port,"unknown",NI_MAXSERV);
      }

      csp->http->host_ip_addr_str = strdup(hostname);

      dst->addr = *addr;
      dst->addrlen = addrlen;
      dst->port = portnum;

      if (block_acl(dst, csp))
      {
#ifdef __OS2__
         errno = SOCEPERM;
#else
         errno = EPERM;
#endif
         return(JB_INVALID_SOCKET);
      }


   }
#endif /* def FEATURE_ACL */

   {
      jb_socket fd;

#ifdef _WIN32
      if ((fd = socket(addr->ss_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
#else
      if ((fd = socket(addr->ss_family, SOCK_STREAM, 6)) < 0)
#endif
      {
         return(JB_INVALID_SOCKET);
      }

#ifdef TCP_NODELAY
      {  /* turn off TCP coalescence */
         int mi = 1;
         setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
      }
#endif /* def TCP_NODELAY */

#if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
      {
         int flags;

         if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
         {
            flags |= O_NDELAY;
            fcntl(fd, F_SETFL, flags);
         }
      }
#endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */

      while (connect(fd, (struct sockaddr *) addr, addrlen) == JB_INVALID_SOCKET)
      {
#ifdef _WIN32
         if (errno == WSAEINPROGRESS)
#elif __OS2__ 
         if (sock_errno() == EINPROGRESS)
#else /* ifndef _WIN32 */
         if (errno == EINPROGRESS)
#endif /* ndef _WIN32 || __OS2__ */
         {
            break;
         }

#ifdef __OS2__ 
         if (sock_errno() != EINTR)
#else
         if (errno != EINTR)
#endif /* __OS2__ */
         {
            close_socket(fd);
            return(JB_INVALID_SOCKET);
         }
      }

#if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
      {
         int flags;
         if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
         {
            flags &= ~O_NDELAY;
            fcntl(fd, F_SETFL, flags);
         }
      }
#endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */

      {
         fd_set wfds;
         struct timeval tv[1];

         /* wait for connection to complete */
         FD_ZERO(&wfds);
         FD_SET(fd, &wfds);

         tv->tv_sec  = 30;
         tv->tv_usec = 0;

         /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
         if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
         {
            close_socket(fd);
            return(JB_INVALID_SOCKET);
         }
#if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
         else
         {
            int connect_result;
            socklen_t connect_result_len = sizeof connect_result;

            if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &connect_result, &connect_result_len) != 0)
            {
               log_error(LOG_LEVEL_ERROR, "Could not determine whether connection to %s port %d was successful because %E. Assuming failure.",
                         csp->http->host_ip_addr_str, portnum);
               close_socket(fd);
               return(JB_INVALID_SOCKET);
            }
            else if( connect_result != 0 )
            {
               log_error(LOG_LEVEL_CONNECT, "Connection to %s port %d failed because %s.",
                         csp->http->host_ip_addr_str, portnum, strerror(connect_result));
               close_socket(fd);
               return(JB_INVALID_SOCKET);
            }
         }
#endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
      }
      return(fd);
   }
}

jb_socket connect_to(const char *host, const char *port, unsigned long portnum, int pf, struct client_state *csp)
{
   jb_socket fd = JB_INVALID_SOCKET;
   struct sockaddr_storage addr;
   addr_list *addrs, *addrs_to_try;

   addrs = resolve_hostname_to_ip(host,port,pf);

   if (is_nil_addr_list(addrs))
   {
      errno = EINVAL;
      return fd;
   }

   for(addrs_to_try=addrs;
       !is_nil_addr_list(addrs_to_try);
       addrs_to_try = tail_addr_list(addrs_to_try))
   {
      size_t addrlen;
      memset((char *)&addr, 0, sizeof addr);
      cpy_head_addr_list(addrs_to_try, &addr,&addrlen);
      fd = connect_to_one_ip(&addr, addrlen, host, portnum, csp);
      if (fd != JB_INVALID_SOCKET)
         break;
   }

   if (fd == JB_INVALID_SOCKET)
   {
      csp->http->host_ip_addr_str = strdup("unknown");
   }

   destroy_addr_list(addrs);
   return fd;
}


/*********************************************************************
 *
 * Function    :  write_socket
 *
 * Description :  Write the contents of buf (for n bytes) to socket fd.
 *
 * Parameters  :
 *          1  :  fd = file descriptor (aka. handle) of socket to write to.
 *          2  :  buf = pointer to data to be written.
 *          3  :  len = length of data to be written to the socket "fd".
 *
 * Returns     :  0 on success (entire buffer sent).
 *                nonzero on error.
 *
 *********************************************************************/
#ifdef AMIGA
int write_socket(jb_socket fd, const char *buf, ssize_t len)
#else
int write_socket(jb_socket fd, const char *buf, size_t len)
#endif
{
   if (len == 0)
   {
      return 0;
   }

   if (len < 0)
   {
      return 1;
   }

   log_error(LOG_LEVEL_LOG, "%N", len, buf);

#if defined(_WIN32)
   return (send(fd, buf, (int)len, 0) != (int)len);
#elif defined(__BEOS__) || defined(AMIGA)
   return (send(fd, buf, len, 0) != len);
#elif defined(__OS2__)
   /*
    * Break the data up into SOCKET_SEND_MAX chunks for sending...
    * OS/2 seemed to complain when the chunks were too large.
    */
#define SOCKET_SEND_MAX 65000
   {
      int write_len = 0, send_len, send_rc = 0, i = 0;
      while ((i < len) && (send_rc != -1))
      {
         if ((i + SOCKET_SEND_MAX) > len)
            send_len = len - i;
         else
            send_len = SOCKET_SEND_MAX;
         send_rc = send(fd,(char*)buf + i, send_len, 0);
         if (send_rc == -1)
            return 1;
         i = i + send_len;
      }
      return 0;
   }
#else
   return (write(fd, buf, len) != len);
#endif

}


/*********************************************************************
 *
 * Function    :  read_socket
 *
 * Description :  Read from a TCP/IP socket in a platform independent way.
 *
 * Parameters  :
 *          1  :  fd = file descriptor of the socket to read
 *          2  :  buf = pointer to buffer where data will be written
 *                Must be >= len bytes long.
 *          3  :  len = maximum number of bytes to read
 *
 * Returns     :  On success, the number of bytes read is returned (zero
 *                indicates end of file), and the file position is advanced
 *                by this number.  It is not an error if this number is
 *                smaller than the number of bytes requested; this may hap-
 *                pen for example because fewer bytes are actually available
 *                right now (maybe because we were close to end-of-file, or
 *                because we are reading from a pipe, or from a terminal,
 *                or because read() was interrupted by a signal).  On error,
 *                -1 is returned, and errno is set appropriately.  In this
 *                case it is left unspecified whether the file position (if
 *                any) changes.
 *
 *********************************************************************/
int read_socket(jb_socket fd, char *buf, int len)
{
   if (len <= 0)
   {
      return(0);
   }

#if defined(_WIN32)
   return(recv(fd, buf, len, 0));
#elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
   return(recv(fd, buf, (size_t)len, 0));
#else
   return(read(fd, buf, (size_t)len));
#endif
}


/*********************************************************************
 *
 * Function    :  close_socket
 *
 * Description :  Closes a TCP/IP socket
 *
 * Parameters  :
 *          1  :  fd = file descriptor of socket to be closed
 *
 * Returns     :  void
 *
 *********************************************************************/
void close_socket(jb_socket fd)
{
#if defined(_WIN32) || defined(__BEOS__)
   closesocket(fd);
#elif defined(AMIGA)
   CloseSocket(fd); 
#elif defined(__OS2__)
   soclose(fd);
#else
   close(fd);
#endif

}


/*********************************************************************
 *
 * Function    :  bind_port_one_ip
 *
 * Description :  Call socket, set socket options, and listen.
 *
 * Parameters  :
 *          0  :  addr = TCP/IP address and port to bind/listen to
 *          1  :  fds = jb_socket_set where the new socket should go
 *
 * Returns     :  if success returns 0 and adds sockets to fds.
 *                if failure, returns -3 if address is in use,
 *                                    -2 if memory error
 *                                    -1 otherwise
 *********************************************************************/
int bind_port_one_ip(struct sockaddr *addr, const socklen_t addr_len, jb_socket_set *fds)
{
   jb_socket fd;
   int flags;
#ifndef _WIN32
   int one = 1;
#endif /* ndef _WIN32 */

   fd = JB_INVALID_SOCKET;

   fd = socket(addr->sa_family, SOCK_STREAM, 6);

#ifdef _WIN32
   if (fd == JB_INVALID_SOCKET)
#else
   if (fd < 0)
#endif
   {
      return(-1);
   }

#ifndef _WIN32
   /*
    * This is not needed for Win32 - in fact, it stops
    * duplicate instances of Junkbuster from being caught.
    *
    * On UNIX, we assume the user is sensible enough not
    * to start Junkbuster multiple times on the same IP.
    * Without this, stopping and restarting Junkbuster
    * from a script fails.
    * Note: SO_REUSEADDR is meant to only take over
    * sockets which are *not* in listen state in Linux,
    * e.g. sockets in TIME_WAIT. YMMV.
    */
   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
#endif /* ndef _WIN32 */
   /* As we are now listening on more than one socket,
    * this is important: The only way to be sure accept
    * won't block!!
    */
   if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
   {
      flags |= O_NONBLOCK;
      fcntl(fd, F_SETFL, flags);
   }
   
   if (bind (fd, addr, addr_len) < 0)
   {
      close_socket (fd);
#ifdef _WIN32
      if (errno == WSAEADDRINUSE)
#else
      if (errno == EADDRINUSE)
#endif
      {
         return(-3);
      }
      else
      {
         return(-1);
      }
   }

   while (listen(fd, 25) == -1)
   {
      if (errno != EINTR)
      {
         return(-1);
      }
   }

   if (jb_socket_set_add(fds,fd) != 0)
   {
      close_socket(fd);
      return -2;
   }
   return 0;
}

/*********************************************************************
 *
 * Function    :  bind_port
 *
 * Description :  Call bind_port_one_ip on all addresses host resolves to
 *                Called by listen_loop to "boot up" our proxy address.
 *
 * Parameters  :
 *          0  :  host = TCP/IP hostname to bind/listen to
 *          1  :  port = port to listen to, as string
 *          2  :  fds = socket set the sockets should be added to
 *
 * Returns     :  if success on at least one address resolving from hostnam,
 *                 returns 0 and adds sockets to fds.
 *                if failure, returns non-zero
 *********************************************************************/
int bind_port(const char *host, const char *port, int pf, jb_socket_set *fds)
{
   int result;
   int failure = 1;
   struct sockaddr_storage addr;
   struct sockaddr * const addr_addr = (struct sockaddr *)&addr;
   addr_list *addrs, *addrs_to_try;

   const char * const log_host = (host != NULL) ? host : "ADDR_ANY";

   addrs = resolve_hostname_to_ip(host,port,pf);

   if (is_nil_addr_list(addrs))
      log_error(LOG_LEVEL_ERROR, "can't bind to %s:%s: " 
                "Name resolution didn't give any address",
                log_host, port);

   log_error(LOG_LEVEL_INFO, "Binding to %s:%s...",  log_host, port);

   for(addrs_to_try=addrs;
       !is_nil_addr_list(addrs_to_try);
       addrs_to_try = tail_addr_list(addrs_to_try))
   {
      char numeric_hostname[NI_MAXHOST];
      char numeric_port[NI_MAXSERV];
      size_t addrlen;
      memset((char *)addr_addr, 0, sizeof addr);
      cpy_head_addr_list(addrs_to_try, &addr, &addrlen);
      result = getnameinfo(addr_addr, addrlen, numeric_hostname, NI_MAXHOST,
                           numeric_port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV);
      if (result != 0)
      {
         log_error(LOG_LEVEL_ERROR, "bind: Could not get string address and port back from sockaddr because %E");
         strncpy(numeric_hostname,"unknown",NI_MAXHOST);
         strncpy(numeric_port,"unknown",NI_MAXSERV);
      }
      result = bind_port_one_ip(addr_addr, addrlen, fds);
      if( result == 0 )
      {
         failure = 0;
         log_error(LOG_LEVEL_INFO, "Successfully bound to %s:%s", numeric_hostname, numeric_port);
      }
      else
      {
         switch(result)
         {
         case -3 :
            log_error(LOG_LEVEL_ERROR, "can't bind to %s:%s (%s:%s): "
                      "There may be another Privoxy or some other "
                      "proxy running on port %s",
                      log_host, port, numeric_hostname, numeric_port, numeric_port);
         case -2 :
            log_error(LOG_LEVEL_ERROR, "can't bind to %s:%s (%s:%s): "
                      "Out of memory",
                      log_host, port, numeric_hostname, numeric_port);

         default :
            log_error(LOG_LEVEL_ERROR, "can't bind to %s:%s: because %E",
                      log_host, numeric_port);
         }
      }
   }

   destroy_addr_list(addrs);
   return failure;
}

/*********************************************************************
 *
 * Function    :  accept_connection
 *
 * Description :  Accepts a connection on a socket.  Socket must have
 *                been created using bind_port().
 *
 * Parameters  :
 *          1  :  csp = Client state, cfd, ip_addr_str, and 
 *                ip_addr_long will be set by this routine.
 *          2  :  fd  = file descriptor returned from bind_port
 *
 * Returns     :  when a connection is accepted, it returns 1 (TRUE).
 *                On an error it returns 0 (FALSE).
 *
 *********************************************************************/
int accept_connection(struct client_state * csp, jb_socket fd)
{
   struct sockaddr_storage client, server;
   jb_socket afd;
#if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
   /* Wierdness - fix a warning. */
   int c_length, s_length;
#else
   socklen_t c_length, s_length;
#endif
   int flags;

   c_length = s_length = sizeof(client);

#ifdef _WIN32
   afd = accept (fd, (struct sockaddr *) &client, &c_length);
   if (afd == JB_INVALID_SOCKET)
   {
      return 0;
   }
#else
   do
   {
      afd = accept (fd, (struct sockaddr *) &client, &c_length);
   } while (afd < 1 && errno == EINTR);
   if (afd < 0)
   {
      return 0;
   }
#endif
   /* If we inherited O_NONBLOCK from the listening fd, unset it */
   if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
   {
      flags &= ~O_NONBLOCK;
      fcntl(fd, F_SETFL, flags);
   }

   /* 
    * Determine the IP-Adress that the client used to reach us
    * and the hostname associated with that address
    */
   if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
   {
      char hostname[NI_MAXHOST];
      char port[NI_MAXSERV];

      if (getnameinfo((struct sockaddr *)&server, s_length, hostname, NI_MAXHOST,
                      port, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) != 0)
      {
         log_error(LOG_LEVEL_ERROR, "accept: Could not get string address and port back from server sockaddr because %E");
         strncpy(hostname,"unknown IP",NI_MAXHOST);
         strncpy(port,"unknown port",NI_MAXSERV);
      }
      csp->my_ip_addr_str = strdup(hostname);
      csp->my_port_str = strdup(port);

      if (getnameinfo((struct sockaddr *)&server, s_length, hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD) != 0)
      {
         log_error(LOG_LEVEL_ERROR, "accept: Could not get my own hostname because %E");
         strncpy(hostname,"unknown host",NI_MAXHOST);
      }
      csp->my_hostname = strdup(hostname);
   }
   else
   {
      log_error(LOG_LEVEL_ERROR, "accept: Could not get sockaddr from socket fd because %E");
   }

   csp->cfd    = afd;
   {
      char hostname[NI_MAXHOST];

      if (getnameinfo((struct sockaddr *)&client, c_length, hostname, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) != 0)
      {
         log_error(LOG_LEVEL_ERROR, "accept: Could not get client IP address string because %E");
         strncpy(hostname,"unknown IP",NI_MAXHOST);
      }
      csp->my_ip_addr_str = strdup(hostname);

      if (getnameinfo((struct sockaddr *)&server, s_length, hostname, NI_MAXHOST, NULL, 0, 0) != 0)
      {
         log_error(LOG_LEVEL_ERROR, "accept: Could not get my own hostname because %E");
         strncpy(hostname,"unknown host",NI_MAXHOST);
      }
      csp->ip_addr_str = strdup(hostname);
   }
   csp->ip_addr_addr = client;

   return 1;

}


/*********************************************************************
 *
 * Function    :  resolve_hostname_to_ip
 *
 * Description :  Resolve a hostname to a list of internet tcp/ip addresses.
 *
 * Parameters  :
 *          0  :  host = hostname to resolve
 *          1  :  result = where to store the result
 *          2  :  pf = preferred address family. PF_UNSPEC for no preference (recommended).
 *
 *
 * Returns     :  A (possibly empty) list of adresses
 *
 *********************************************************************/
addr_list *resolve_hostname_to_ip(const char *host, const char *port, int pf)
{
   /* TODO 
    * Do all supported platforms have "getaddrinfo"?
    */
    
   struct addrinfo hints, *res0;
   int result;
   memset(&hints, 0, sizeof(hints));
   hints.ai_family = pf;
   hints.ai_socktype = SOCK_STREAM;

   result = getaddrinfo(host, port, &hints, &res0);
   if ( result != 0 )
   {
      log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s because %s", host,gai_strerror(result));
      if (result == EAI_SYSTEM)
         log_error(LOG_LEVEL_ERROR, "The system error is %E");
      return NULL;
   }
   else
      if (res0==0)
         log_error(LOG_LEVEL_ERROR, "Problem in resolving hostname %s: succeeded, but no information returned", host);

   return res0;
}

/*
  Local Variables:
  tab-width: 3
  c-file-style: "stroustrup"
  c-basic-offset: 3
  indent-tabs-mode: nil
  end:
*/

