/*
   This file is part of the IRC Bounce source code
   copyright (c) 1998 v00d00 Net Services
   and is distributed according to the GNU general public license.

   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.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

   The author (Robert Clark) can be reached at: v00d00@hempseed.com

   This code is based on Irc Proxy (c)1997-98 James Seter
*/

#include "common.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/types.h>

void
nprintf(int s, char *format, ...)
{
   va_list va; char buffer[1024]; int retval;
   va_start(va,format); vsnprintf(buffer,1024,format,va); va_end(va);
   send(s,buffer,strlen(buffer),0);
}

int
do_connect(char *vhostname, char *hostname, u_short port)
{
   int s;
   struct hostent *he;
   struct sockaddr_in sin;

   s=socket(AF_INET,SOCK_STREAM,0);
   if (s<0) return -2;
   memset(&sin,0,sizeof(struct sockaddr_in));
   sin.sin_family=AF_INET;
   sin.sin_addr.s_addr=(*vhostname?inet_addr(vhostname):INADDR_ANY);
   if (sin.sin_addr.s_addr==-1&&*vhostname) {
      he=gethostbyname(vhostname);
      if(he) memcpy(&sin.sin_addr,he->h_addr,he->h_length);
      else sin.sin_addr.s_addr= INADDR_ANY;
   }
   if (bind(s,(struct sockaddr *)&sin,sizeof(struct sockaddr_in))<0) return -1;

   memset(&sin,0,sizeof(struct sockaddr_in));
   sin.sin_family=AF_INET;
   sin.sin_port=htons(port);
   sin.sin_addr.s_addr=inet_addr(hostname);
   if (sin.sin_addr.s_addr==-1) {
      he=gethostbyname(hostname);
      if (!he) return -2;
      memcpy(&sin.sin_addr,he->h_addr,he->h_length);
   }

   if (connect(s,(struct sockaddr *)&sin,sizeof(sin))<0) {
      close(s);
      return -2;
   }
   return s;
}

char *
gethost(struct in_addr *addr)
{
   struct hostent *hp;
   hp=gethostbyaddr((char *)addr,sizeof(struct in_addr),AF_INET);
   if (hp) return hp->h_name;
   else return inet_ntoa(*addr);
}
