/*
 * Copyright (c) 1999-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

/* connect.c */

/* Copyright 1999-2000 by Eberhard Mattes <em-gw@windhager.de>
   Donated to the public domain.  No warranty.

   1999-03-17 Initial version
   2000-05-31 copy_bidir() has an additional argument */

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "firewall.h"
#include "libemfw.h"
#include "emio.h"
#include "squid-gw.h"

char **connect_addr_list (const char *hostname)
{
  static octet addr[4];
  octet mask[4];
  struct hostent *h;

  if (ipaddr_parsez ((octet*) hostname, addr, mask, 0) == 0)
    {
      static char *vec[2];
      vec[0] = (char *)addr;
      vec[1] = NULL;
      return vec;
    }
  h = gethostbyname ((char *)hostname);
  if (h == NULL)
    {
      syslog (LLEV, "%.512s host name lookup failed", hostname);
      return NULL;
    }
  if (h->h_addrtype != AF_INET || h->h_length != 4)
    {
      syslog (LLEV, "%.512s: invalid h_addrtype or h_length",
	      hostname);
      return NULL;
    }
  return h->h_addr_list;
}

void http_connect2 (const octet *ipaddr, int port, const char *http_version,
		    int timeout)
{
  struct sockaddr_in addr;
  int fd, r;

  memset (&addr, 0, sizeof (addr));
  addr.sin_family = AF_INET;
  memcpy (&addr.sin_addr, ipaddr, 4);
  addr.sin_port = htons (port);
  fd = socket (AF_INET, SOCK_STREAM, 0);
  if (fd == -1)
    {
      syslog (LLEV, "socket: %s", strerror (errno));
      exit (1);
    }
  if (connect (fd, (struct sockaddr *)&addr, sizeof (addr)) != 0)
    {
      syslog (LLEV, "connect: %s", strerror (errno));
      exit (1);
    }

  emo_printf (c_out, "HTTP/%s 200 Connection established\r\n\r\n",
	      http_version);
  if (emo_flush (c_out) != 0)
    {
      syslog (LLEV, "emo_flush: %s", strerror(errno));
      exit (1);
    }

  r = copy_bidir_emi (NULL, fd, c_in, -1, timeout, CB_EOF1 | CB_EOF2);
  if (r > 0)
    syslog (LLEV, "timeout");
  if (r < 0)
    exit (1);
}
