/* common.c       Copyright (c) 2000-2003 Nagy Daniel
 *
 * $Date: 2003/11/11 13:55:44 $
 * $Revision: 1.2 $
 *
 * Common functions
 *
 *
 * 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 Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include "tcp.h"
#include "config.h"

/* external functions, data */
extern Config GlobalConfig;		/* configuration variables */
extern unsigned short Configuration;    /* configuration variables */


/*
 * Fatal error handler
 */
void fatal(const char *fmt, ...)
{
va_list ap;
char *buf;

   buf = malloc(2048);
   va_start(ap, fmt);
   vsprintf(buf, fmt, ap);
   va_end(ap);
   puts(buf);
   free(buf);
   sock_close(&GlobalConfig.s);
   exit(255);
}


/*
 * Connect to remote host via TCP
 */
void TCPConnect(char *remotehost, unsigned short remoteport)
{
unsigned short localport;
longword remoteip;

   /* Allocate local port */
   localport = (rand() % 512) + 512;
   if(Configuration & NONPRIVILEGED_PORT)
      localport = localport + 512;

   sock_init(); /* Initialize socket */

   /* Resolve hostname */
   if((remoteip = resolve(remotehost)) == 0)
      fatal("Unable to resolve `%s'", remotehost);

   /* Open TCP */
   if(!tcp_open(&GlobalConfig.s, localport, remoteip, remoteport, NULL))
      fatal("Unable to open TCP connection");

   /* Negotiate TCP connection */
   if(Configuration & VERBOSE_MODE)
      puts("Waiting for remote host to connect...");

   while(!sock_established(&GlobalConfig.s))
      if(!tcp_tick(&GlobalConfig.s))
         fatal("Remote host closed connection");
}
