#define VERSION "Rerouter Single Spy v1.0, by pmsac, 1997\n"
/*To Compile: define SOLARIS or LINUX */
/*In Solaris: gcc -Wall -O6 -o rerouterSS -lsocket -lnsl rerouterSS.c */
/*In Linux: gcc -Wall -O6 -o rerouterSS rerouterSS.c */

#define SOLARIS
/*#define LINUX*/


#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>

#ifdef LINUX
/* Some warnings but I think they're safe to ignore... */
#include <linux/time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#endif

#define debug 0

#define MAXBUFFER 2048
#define MAXCONNECT 1

#define SERVERARG 1
#define SERVERPORTARG 2
#define LOCALPORTARG 3
#define SPYARG 4
#define SPYSWITCH "-single"
#define MINARGS 4
#define MAXARGS 5


extern int errno;

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

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

 theBuffer[charsRead] = 0;
 if (spyOn)
 {
  printf("%s", theBuffer);
  if (theBuffer[charsRead-1] != '\n')
   printf("\n");
 }

 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");
   return -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 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;
int spyOn = 0;

 /* Register signal handler */
 signal(SIGINT, signalHandler);
 
 /* Turn off buffering for i/o */
 setbuf(stdin, NULL);
 setbuf(stdout, NULL);

 /* Rough check on arguments */
 if ((argc < MINARGS) || (argc > MAXARGS))
 {
  printf("Usage: %s server server_port local_port [%s]\n"
         VERSION,
         argv[0],
         SPYSWITCH);
  strcmp(argv[0], "\n\nDon't be lame 'zapping' the copyright message :P\n\n");
  exit(-1);
 }

 if (argc > SPYARG)
  if (strncmp(argv[SPYARG], SPYSWITCH, 4))
  {
   printf("Invalid option type !\n");
   exit(-1);
  }
  else
   spyOn = 1;
 
 /* Check server */
 if ((int)(hostAddr = inet_addr(argv[SERVERARG])) == -1)
 {
  if ((host = gethostbyname(argv[SERVERARG])) == NULL)
  {
   printf("Unknown server: %s\n", argv[SERVERARG]);
   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[SERVERARG]);
  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[LOCALPORTARG]);
 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, 0) == -1)
  {
   printf("Unable to listen over client socket\n");
   if (debug) perror("listen()");
   if (close(clientSocket) == -1)
   {
    printf("Unable to close client 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
  {
  
   processId = getpid();
   
   /* Connection attempt begins here */
   printf("Connection attempt on %s(%s) port %s by %lu\n",
          host->h_name, inet_ntoa(in), argv[SERVERPORTARG], processId);
          
   serverPort = atoi(argv[SERVERPORTARG]);
   p = host->h_addr_list;
   memcpy(&in.s_addr, *p, sizeof (in.s_addr));
   
   if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
   {
    printf("Unable to open server socket\n");
    if (debug) perror("socket()");
   }
   else
   {
   
    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 server socket\n");
      if (debug) perror("close()");
     }
     if (close(volatileSocket) == -1)
     {
      printf("Unable to close volatile socket\n");
      if (debug) perror("close()");
     }
    }
    else
    { 
     /* Connection successfull */
     printf("%lu - CONNECTED to %s port %s\n", processId, host->h_name,
            argv[SERVERPORTARG]);
     
     /* 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,
                                      spyOn)
           == -1)
        break;
       else
       {
        if (!spyOn) printf("%lu -->\n", processId);
       }
      else
       if (FD_ISSET(volatileSocket, &theMask))
        if (source2DestinationTransfer(volatileSocket, serverSocket, theBuffer,
                                       spyOn)
             == -1)
         break;
        else
        {
         if (!spyOn) printf("%lu <--\n", processId);
        }
       else
        printf("%lu timedout ?\n", processId);
     }
     /* Disconnected ? */ 
     if (close(serverSocket) == -1)
     {
      printf("Unable to close server socket\n");
      if (debug) perror("close()");
     } 
     if (close(volatileSocket) == -1)
     {
      printf("Unable to close volatile socket\n");
      if (debug) perror("close()");
     }
    }
   }
  }
 }
 /* Terminated ? */
 if (close(clientSocket) == -1)
 {
  printf("Unable to close client socket\n");
  if (debug) perror("close()");
   exit(-1);
 }
}
