#include <signal.h>
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

#define debug 0

#define MAXBUFFER 2048
#define MAXCONNECT 1

extern int errno;

int source2DestinationTransfer(int inputSocket, int outputSocket,
                               char *theBuffer)
{
int charsRead, charsWrote, inBuffer;
static int maxSleep = 5;
int slept = 0;

 if ((charsRead = read(inputSocket, theBuffer, MAXBUFFER)) <= 0)
 {
  if (debug) printf("source2DestinationTransfer(), 0 chars read from socket !\n");
  printf("Disconnected ?\n");
  exit(-1);
 }

 inBuffer = charsRead;
 while ((charsRead) && (slept != maxSleep))
 { 
  charsWrote = write(outputSocket, &theBuffer[inBuffer - charsRead], charsRead);
  if (charsWrote <= 0)
  {
   if (debug) printf("source2DestinationTransfer(), 0 chars wrote to socket !\n");
   printf("Disconnected ?\n");
   exit(-1);
  }
  sleep(1);
  slept++;
  charsRead -= charsWrote;
 }
 if (slept == 5)
 {
  if (debug) printf("source2DestinationTransfer(), 2 much sleep !\n");
  printf("Disconnected ?\n");
  return -1;
 }
 return 1;
}

void signalHandler(int signalNumber)
{
 printf("\nSignal %i received, exiting...\n", signalNumber);
 exit(-1);
}

void signalHandlerForChildExit(int signalNumber)
{
int childId, dummy;

 childId = wait(&dummy);
 printf("\nChild %u exited...\n", childId);
 signal(SIGCHLD, signalHandlerForChildExit);
}


void main(int argc, char **argv)
{
u_long hostAddr;
struct hostent *host;
struct in_addr in;
char **p;
int serverSocket, clientSocket, volatileSocket;
u_short serverPort, clientPort;
struct sockaddr_in serverAddr, clientAddr, volatileAddr;
int volatileAddrSize;
char theBuffer[MAXBUFFER];
fd_set theMainMask, theMask;
pid_t processId;
int tcpNoDelay = 1, optlen = sizeof(int);
static struct timeval timeOut;

 /* Register signal handler */
 signal(SIGINT, signalHandler);

 /* Register signal handler for child exit */
 signal(SIGCHLD, signalHandlerForChildExit);
 
 /* Turn off buffering for i/o */
 setbuf(stdin, NULL);
 setbuf(stdout, NULL);

 /* Rough check on arguments */
 if (argc != 4)
 {
  printf("Usage: %s server server_port local_port\nby pmsac, 1997\n", argv[0]);
  strcmp(argv[0], "\n\nDon't be lame 'zapping' the copyright message :P\n\n");
  exit(-1);
 }
 
 /* Check server */
 if ((int)(hostAddr = inet_addr(argv[1])) == -1)
 {
  if ((host = gethostbyname(argv[1])) == NULL)
  {
   printf("Unknown server: %s\n", argv[1]);
   if (debug) perror("gethostbyname()");
   exit(-1);
  }
 } else
 if ((host = gethostbyaddr((char *)&hostAddr, sizeof (hostAddr), AF_INET))
     == NULL)
 {
  printf("Server information for %s not found\n", argv[1]);
  if (debug) perror("gethostbyaddr()");
  exit(-1);
 }

 if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
 {
  printf("Unable to open client socket\n");
  if (debug) perror("socket()");
  exit(-1);
 }
 
 if (setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (char *)&tcpNoDelay,
                optlen) < 0)
  printf("Warning, not able to set client socket options\n");
 clientPort = atoi(argv[3]);
 clientAddr.sin_family = AF_INET;
 clientAddr.sin_addr.s_addr = htonl(INADDR_ANY);
 clientAddr.sin_port = htons(clientPort);
 bzero(clientAddr.sin_zero, 8); 
 if (bind(clientSocket,
     (struct sockaddr*)&clientAddr, sizeof(struct sockaddr_in)) == -1)
 {
  printf("Unable to bind socket\n");
  if (debug) perror("bind()");
  exit(-1);
 }

 /* Waiting for client connection */
 while(1)
 {
  printf("Listening on port: %u\n", ntohs(clientAddr.sin_port));
  if (listen(clientSocket, 1) == -1)
  {
   printf("Unable to listen over client socket\n");
   if (debug) perror("listen()");
   if (close(clientSocket) == -1)
   {
    printf("Unable to close socket\n");
    if (debug) perror("close()");
   }
   exit(-1);
  }
  if ((volatileSocket = accept(clientSocket, 
                              (struct sockaddr*)&volatileAddr,
                              &volatileAddrSize)) == -1)
  {
   if (errno != EINTR)
   {
    printf("Unable to accept client connection\n");
    if (debug) perror("listen()");
   }
  }
  else
  {
   if (fork() == 0)
   {   
    processId = getpid();
    /* Connection attempt begins here */
    serverPort = atoi(argv[2]);
    p = host->h_addr_list;
    memcpy(&in.s_addr, *p, sizeof (in.s_addr));
    printf("Connection attempt on %s(%s) port %s by %lu\n",
           host->h_name, inet_ntoa(in), argv[2], processId);
    if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
     printf("Unable to open server socket\n");
     if (debug) perror("socket()");
    }

    if (setsockopt(serverSocket, IPPROTO_TCP, TCP_NODELAY, (char *)&tcpNoDelay,
                   optlen) < 0)
     printf("Warning, not able to set server socket options\n");
    bzero(&serverAddr.sin_zero, 8);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = in.s_addr;
    serverAddr.sin_port = htons(serverPort);
    if (connect(serverSocket, (struct sockaddr *)&serverAddr,
                sizeof(struct sockaddr_in)) == -1)
    {
     printf("Unable to connect\n");
     if (debug) perror("connect()");
     if (close(serverSocket) == -1)
     {
      printf("Unable to close socket\n");
      if (debug) perror("close()");
     }
    }
    
    /* Connection successfull */
    printf("%lu - CONNECTED to %s port %s\n", processId, host->h_name, argv[2]);
    
    /* Initialize i/o descriptors mask */
    FD_ZERO(&theMainMask);
    FD_SET(serverSocket, &theMainMask);
    FD_SET(volatileSocket, &theMainMask);
    
    /* i/o cicle */
    while(1)
    {
     timeOut.tv_sec = 30;
     timeOut.tv_usec = 0;
     memcpy(&theMask, &theMainMask, sizeof(theMainMask));
     select(serverSocket+1, &theMask, NULL, NULL, &timeOut);
     if (FD_ISSET(serverSocket, &theMask))
      if (source2DestinationTransfer(serverSocket, volatileSocket, theBuffer)
          == -1)
       break;
      else
       printf("%lu -->\n", processId);
     else
      if (FD_ISSET(volatileSocket, &theMask))
       if (source2DestinationTransfer(volatileSocket, serverSocket, theBuffer)
            == -1)
        break;
       else
        printf("%lu <--\n", processId);
      else
       printf("%lu timedout ?\n", processId);
    }
    /* How the hell did we get here ? */ 
    if (close(serverSocket) == -1)
    {
     printf("Unable to close socket\n");
     if (debug) perror("close()");
     exit(-1);
    } 
   }
  }
 }
 
 if (close(clientSocket) == -1)
 {
  printf("Unable to close socket\n");
  if (debug) perror("close()");
  exit(-1);
 }
 exit(0);
}
