/*********************************************************
* Module Name: UDP Echo client source 
*
* File Name:    UDPEchoClient2.c
*
* Summary:
*  This file contains the client portion of a client/server
*         UDP-based performance tool.
*  
* Usage :   ./ client  
*             <Server IP> 
*             <Server Port> 
*             [<Message Size (bytes)>] 
*             [<# of iterations>] 
*             [<Debug Flag (default : 129)>]\n", 
*             [mode 0] [<Iteration Delay (usecs)>] 
*             [mode 1] [targetSendRate]
*             [mode 2] [Window Mode]
*
*    debugFlag: contains two pieces of information.
*               -To log samples in an output file
*               -The debugLevel which controls how much info is displayed
*
*               To log samples, set the 8th bit of the debugFlag. E.g., 128.
*               The debugLevel is set by anding the debugFlag with 0x7f                
*       
*               By default, this is 129 which sets debugLevel to 1 and creates samples file.
* 
*    0:  serious error messages only
*    1:  adds start msg and final results  and warnings
*    2:  shows iteration results
*    3:  debug information
*
*    Example:  Value 129 sets debugLevel to 1 and creates samples file
*
*
* Revisions:
*
* $A0:  2/19/2017  
*         -Version 1.2
*         -iteration delay arguement interpreted as number of microseconds
*         -added debug level param (optional)
*         -reused socket except for when errors occur
*
* $A1:   2/28/17
* $A2 : 9/7/2017  Version 1.3
* $A3 : 9/27/2017 V1.4 - add CBR mode
* $A4 : 11/9/2017 V1.6 - prepparing for mode 2 - window mode
*********************************************************/
#include "UDPEcho.h"

void clientCNTCCode();
void CatchAlarm(int ignored);
void exitProcessing(double curTime);


//Define this globally so our async handlers can access

char *serverIP = NULL;                   /* IP address of server */
int sock = -1;                         /* Socket descriptor */
int bStop;
FILE *newFile = NULL;
double startTime = 0.0;
double endTime = 0.0;

unsigned int numberOfTimeOuts=0;
unsigned int numberOfTrials=0; /*counts number of attempts */
unsigned int numberOfSocketsUsed = 0;
unsigned int numberLost=0;
unsigned int numberOutOfOrder=0;
double avgLoss = 0.0;
long long totalBytesSent =0;	

//$A3
unsigned int targetSendRate = 0;
unsigned short mode = RTT_MODE;

//$A4
unsigned int W=1;
int maxW = -1;

//RTT as a long
long avgPing = 0.0; /* final mean */
long totalPing = 0.0;
unsigned int numberRTTSamples = 0;

//RTT as a double
double curRTT = 0.0;
double sumOfCurRTT = 0.0;
double meanCurRTT = 0.0; /* final mean */
double smoothedRTT = 0.0;

unsigned int debugLevel = 1;
unsigned int createDataFileFlag = 0;
unsigned int errorCount = 0;  /* each loop iteration, any/all errors increment */
unsigned int  outOfOrderArrivals = 0;


void myUsage(char *myName, int paramCount, char *myVersion)
{

  printf("Usage: %s V%s): [Server IP] [Server Port] [Message Size (bytes)] [# of iterations] [Debug Flag (default : 129)]   \n",  
         myName,myVersion);
  printf("\t\t[mode 0 ECHO MODE] [iteration delay (usecs)] \n");
  printf("\t\t[mode 1 CBR MODE ] [target send rate (bps)] \n");
  printf("\t\t[mode 2 WINDOW MODE] [max Window (number packets)] \n");

}


/*************************************************************
*
* Function: Main program for  UDPEcho client
*           
* inputs: 
*  char *  serverIP = argv[1]; 
*  unsigned int  serverPort = atoi(argv[2]);
*  long  iteration delay atoll(argv[3]);
*  unsigned int messageSize = atoi(argv[4]);
*  unsigned int nIterations = atoi(argv[5]);
*  unsigned int debugFlag = atoi(argv[6]);
*  Usage :   client  
*             <Server IP> 
*             <Server Port> 
*             [<Iteration Delay (usecs)>] 
*             [<Message Size (bytes)>] 
*             [<# of iterations>] 
*             [<Debug Flag (default : 129)>]\n", 
*
*
* outputs:  
*
* notes: 
*
***************************************************************/
int main(int argc, char *argv[])
{
  struct sockaddr_in serverAddress; /* Echo server address */
  struct sockaddr_in clientAddress; /* Source address of echo */ 
  unsigned int clientAddressSize = 0;   /* In-out of address size for recvfrom() */
  unsigned short serverPort;        /* Echo server port */

  char *echoString;                /* String to send to echo server */
  char echoBuffer[ECHOMAX+1];      /* Buffer for receiving echoed string */
  int echoStringLen;               /* Length of string to echo */
  int respStringLen;               /* Length of received response */
  struct hostent *thehost;	     /* Hostent from gethostbyname() */

  //At least 64 bits 
  long long delay = 1000000;	     /* Iteration delay in microseconds */
  double iterationDelay = 1.0;	     /* Iteration delay in seconds */
  int messageSize = 32;                  /* PacketSize*/

  unsigned int debugFlag = 129;
  char dataFile[] = "RTT.dat";
  double curTime = 0.0;


  //Used to compute the RTT
  struct timeval *theTime1;
  struct timeval *theTime2;
  struct timeval TV1, TV2;
  long usec1, usec2, curPing;

  //Needed for the alarm timer
  struct sigaction myaction;

  //Maintains the next seq number to use
  unsigned int seqNumber = 1;
  unsigned int *seqNumberPtr;

  //Holds the seq number of a received message
  unsigned int RxSeqNumber = 1;
  unsigned int *RxSeqNumberPtr;


  //This points to the location in the message to send
  unsigned short *modePtr;

  int nIterations = -1;
  unsigned int totalReceivedMsgs = 0;
  unsigned int largestSeqSent = 0;

  int rc  = SUCCESS;
  int loopFlag = 1;

  //tmp variables used for various calculations...
  int i = 0;

  theTime1 = &TV1;
  theTime2 = &TV2;

  //Initialize values
  numberOfTimeOuts = 0;
  numberOfTrials = 0;
  totalPing =0;
  bStop = 0;

  curTime = timestamp();
//  startTime = timestamp();
//  curTime = startTime;
  unsigned int debugFlagMask =  0x00000080;

  if ((argc <= 3 || argc > 8))    
  {
    myUsage(argv[0],argc, Version);
    exit(1);
  }

  signal (SIGINT, clientCNTCCode);

  serverIP = argv[1];           /* First arg: server IP address (dotted quad) */
  serverPort = atoi(argv[2]);   /* Second arg: server port */
  messageSize = atoi(argv[3]);
  if (messageSize > ECHOMAX)
    messageSize = ECHOMAX;
  nIterations = atoi(argv[4]);
  debugFlag = atoi(argv[5]);
  debugLevel = (debugFlag & 0x0000007f); 
  mode = atoi(argv[6]);
  switch(mode) {
    case RTT_MODE:
      delay = atoll(argv[7]);
    break;

    case CBR_MODE:
      targetSendRate = atoi(argv[7]);
    break;

    case WINDOW_MODE:
      maxW = atoi(argv[7]);
    break;

    default:
      printf("UDPEchoClient: HARD ERROR bad mode param %d \n", mode);
      myUsage(argv[0],argc, Version);
      exit(1);
  }

  if (debugFlag && debugFlagMask)
    createDataFileFlag = 1;
  else 
    createDataFileFlag = 0;

  if (debugLevel > 0) {
    printf("UDPEchoClient(#args:%d): mode:%d debugLevel:%d debugFlag:%d createFlag:%d \n",
          argc,mode, debugLevel, debugFlag, createDataFileFlag);
  }

  if (createDataFileFlag == 1 ) {
    newFile = fopen(dataFile, "w");
    if ((newFile ) == NULL) {
      printf("UDPEchoClient(%s): HARD ERROR failed fopen of file %s,  errno:%d \n", 
             argv[0],dataFile,errno);
      exit(1);
    }
  }

  //For both modes, we can just do this once.  
  //Place the iterationDelay in units of seconds
  if ( mode == RTT_MODE) {
    iterationDelay = ((double)delay)/1000000;/* Iteration delay in seconds */
  } else if ( mode == CBR_MODE) {
    if (targetSendRate > 0) {
      iterationDelay =  (((double)messageSize)*8) / (double)targetSendRate;
    } else {
      printf("UDPEchoClient(%s): HARD ERROR BAD targetSendRate? %d \n", argv[0],targetSendRate);
      exit(1);
    }
  } else { 
    printf("UDPEchoClient(%s): HARD ERROR BAD MODE ?? %d \n", argv[0],mode);
    exit(1);
  }
 



  if (debugLevel > 0) {
      printf("UDPEchoClient(%s): IP:port:%s:%d #params:%d  %lld  %f %d %d %d %d %d \n", 
        argv[0],  serverIP, serverPort, argc,
        delay, iterationDelay, messageSize, nIterations, debugFlag, mode, targetSendRate);
  }


  myaction.sa_handler = CatchAlarm;
  if (sigfillset(&myaction.sa_mask) < 0){
    errorCount++;
    printf("UDPEchoClient(%s): HARD ERROR sigfillset failed:  errno:%d \n", 
             argv[0],errno);
    exit(1);
  }

  myaction.sa_flags = 0;

  if (sigaction(SIGALRM, &myaction, 0) < 0)  {
    errorCount++;
    printf("UDPEchoClient(%s): HARD ERROR sigaction failed:  errno:%d \n", 
             argv[0],errno);
    exit(1);
  }

  /* Set up the echo string */

  echoStringLen = messageSize;
  echoString = (char *) echoBuffer;

  for (i=0; i<messageSize; i++) {
     echoString[i] = 0;
  }

//$A3
//These will point to the Msg to be sent
  seqNumberPtr = (unsigned int *)echoString;
  modePtr =  (unsigned short *)&echoString[sizeof(seqNumber)];
//Just need to do this 1 time
  *modePtr =  htons(mode);

//These will point to the Msg that is received
  echoString[messageSize-1]='\0';
  RxSeqNumberPtr = (unsigned int *)echoBuffer;


  /* Construct the server address structure */
  memset(&serverAddress, 0, sizeof(serverAddress));    /* Zero out structure */
  serverAddress.sin_family = AF_INET;                 /* Internet addr family */
  serverAddress.sin_addr.s_addr = (in_addr_t)inet_addr(serverIP);  /* Server IP address */
    
    /* If user gave a dotted decimal address, we need to resolve it  */
  if (serverAddress.sin_addr.s_addr == -1) {
      thehost = gethostbyname(serverIP);
      serverAddress.sin_addr.s_addr = *((unsigned long *) thehost->h_addr_list[0]);
  }
    
  serverAddress.sin_port   = htons(serverPort);     /* Server port */
  /* Create a datagram/UDP socket */
  if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
//  if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)) < 0) {
      errorCount++;
      DieWithError("socket() failed");
  } else 
      numberOfSocketsUsed++;
  
  nIterations--;

  if (mode == RTT_MODE) {
    while ( (loopFlag>0) && (bStop != 1)) 
    {

    if (nIterations > 0) { 
      nIterations--;
      loopFlag = 1;
    } 
    else if (nIterations == 0) 
      loopFlag = 0;
    else 
      loopFlag = 1;

    if (errorCount > ERROR_LIMIT) {
        if (debugLevel > 1) {
          printf("UDPEchoClient:(%f): WARNING :  errorCount %d, hit ERROR_LIMIT \n ",
                 curTime,errorCount);
        }
        errorCount = 0;
        //try to reset things.....
        /* Create a datagram/UDP socket */
        if (sock != -1) 
          close(sock);
        sock = -1;
        if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
          errorCount++;
          printf("UDPEchoClient:(%f): HARD ERROR errorCount %d, socket reset failed, errno:%d \n ",
                 curTime,errorCount,errno);
          exit(1);
        } else 
          numberOfSocketsUsed++;
    }
    numberOfTrials++;
    largestSeqSent = seqNumber;
    //update seq number in the msg in network byte order
    *seqNumberPtr = (unsigned int)htonl(seqNumber++); 
    //$A3
    //update the mode...actually just need to do this once as it never changes 
    //*modePtr =  htons(mode);

    if (debugLevel > 2) {
      printf("UDPEchoClient: iteration:%d, sending seq and mode: %d %d  \n", numberOfTrials, largestSeqSent, mode);
    }

    //
    gettimeofday(theTime1, NULL);
    curTime = convertTimeval(theTime1);
    if (startTime == 0.0 ) {
        startTime = curTime;
    }

     /* Send the string to the server */
      if (debugLevel > 2) {
        printf("UDPEchoClient: Sending seqNum:%d (%d bytes) to the server: %s, next seq#timed:%d \n", 
             seqNumber - 1, echoStringLen,serverIP, outOfOrderArrivals);
      }

      rc =sendto(sock, echoString, echoStringLen, 0, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
      if (rc < 0) 
      {
          errorCount++;
          printf("UDPEchoClient:(%f) HARD error: : send error (tried %d bytes), errno:%d \n",curTime,echoStringLen,errno);
          continue; 
      } 
      else 
      {
        totalBytesSent += (long long)rc;
        //Else the send succeeded
        if (debugLevel > 2) {
          printf("UDPEchoClient: Sent completed, rc = %d \n",rc);
        }

        clientAddressSize = sizeof(clientAddress);
        alarm(TIMEOUT);    //set the timeout 

        /* Recv a response, client address/port will be filled in on return */
        respStringLen = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *) &clientAddress, &clientAddressSize);
        alarm(0);            //clear the timeout 

        if (respStringLen < 0) 
        {
          //Handle error conditions....errno is the global that is set by the system
          //to reflect the specific error
          if (errno == EINTR) 
          { 
            numberOfTimeOuts++; 
            if (debugLevel > 2) {
              printf("UDPEchoClient:(%f) WARNING :Received Timeout !! #TOs:%d errorCount:%d  \n",
                   curTime,numberOfTimeOuts,errorCount);
            }
            continue; 
          } else {
            errorCount++;
            printf("UDPEchoClient:(%f) WARNING : Rx error errorCount:%d, errno:%d  \n",
                   curTime,errorCount,errno);
            continue; 
          }
        } 
        else 
        {
          if (respStringLen != echoStringLen) 
          {
            errorCount++;
            printf("UDPEchoClient:(%f) WARNING : Rx'ed (%d) less than expected %d)  errorCount:%d  \n",
                   curTime,respStringLen, echoStringLen,errorCount);
            continue; 
          }
        } 


        //If we get here, either no error or we aren't worried about an error....move forward:
        if (debugLevel > 2) {
          printf("UDPEchoClient:(%f): Received %d bytes from  %s \n", curTime, respStringLen, serverIP);
        }


        gettimeofday(theTime2, NULL);
        curTime = convertTimeval(theTime2);
        //gettimeofday(&receivedTime, NULL);
        //curTime = convertTimeval(&receivedTime);
        totalReceivedMsgs++;

        RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
        if (debugLevel > 2) {
          printf("UDPEchoClient: Received seqNumber: %d , and outOfOrderArrivals:%d, errorCount:%d \n",
              RxSeqNumber,outOfOrderArrivals,errorCount);
        }

        //Three possibilities between actual SeqN and expected: less than, equal, GT
        // Norm is they are equal.  GT is not possible. LT  would be a false 
        if (RxSeqNumber > largestSeqSent) {
            printf("UDPEchoClient2:(%f): HARD ERROR:  RxSeqNumber:%d largestSeqSent:%d  \n",
              curTime,  RxSeqNumber, largestSeqSent);
            exit(1);
        }

        //the arrival is an 'old' ACK
        if (RxSeqNumber< largestSeqSent) {
          outOfOrderArrivals++;
        } 


        //Warning: the following are longs and not doubles....
        usec2 = (theTime2->tv_sec) * 1000000 + (theTime2->tv_usec);
        usec1 = (theTime1->tv_sec) * 1000000 + (theTime1->tv_usec);
        curPing = (usec2 - usec1);
        totalPing += curPing;

        curRTT = ((double)curPing) / 1000000;
        smoothedRTT  = 0.5 * smoothedRTT + 0.5*curRTT;
        sumOfCurRTT += curRTT;
        numberRTTSamples++;

        numberLost = numberOfTrials - numberRTTSamples;

        if (debugLevel > 2) {
          printf("UDPEchoClient2(%f): curRTT:%f, smoothRTT:%f currPing:%ld  RxSeqNumber:%d #TOs:%d #Lost:%d, #Errors:%d \n",
               curTime,curRTT, smoothedRTT, curPing, RxSeqNumber, numberOfTimeOuts,numberLost, errorCount);
        }


        if (debugLevel > 1) {
          printf("%f %3.6f %d %3.6f %d %d %d %d %d\n", 
               curTime,curRTT, RxSeqNumber, 
               smoothedRTT, RxSeqNumber, largestSeqSent, numberOfTimeOuts,numberLost, errorCount);
        }
        if (createDataFileFlag == 1 ) {
          fprintf(newFile,"%f %3.9f %d  %3.9f %d %d %d %d %d\n", 
               curTime,curRTT, RxSeqNumber,smoothedRTT, RxSeqNumber, largestSeqSent, numberOfTimeOuts,numberLost, errorCount);
        }

      }

      //Delay the correct amount of time
      rc = myDelay(iterationDelay);
      if (rc == ERROR){
        printf("UDPEchoClient2:(%f): HARD ERROR:  myDelay returned an error ???   \n", curTime);
        exit(1);
      }

    }  //end while
  } else if (mode == CBR_MODE) {

    startTime = timestamp();
    while ( (loopFlag>0) && (bStop != 1)) 
    {
      if (nIterations > 0) { 
        nIterations--;
        loopFlag = 1;
      } 
      else if (nIterations == 0) 
        loopFlag = 0;
      else 
        loopFlag = 1;

      numberOfTrials++;
      largestSeqSent = seqNumber;
      //update seq number in the msg in network byte order
      *seqNumberPtr = (unsigned int)htonl(seqNumber++); 
//$A3
      //update the mode...actually just need to do this once as it never changes 
      //*modePtr =  htons(mode);

      if (debugLevel > 2) {
        printf("UDPEchoClient: iteration:%d, sending seq and mode: %d %d  \n", numberOfTrials, largestSeqSent, mode);
      }

      rc =sendto(sock, echoString, echoStringLen, 0, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
      if (rc < 0) 
      {
          errorCount++;
          printf("UDPEchoClient:(%f) HARD error: : send error (tried %d bytes), errno:%d \n",curTime,echoStringLen,errno);
          continue; 
      } else {
        totalBytesSent += (long long)rc;
      }

      rc = myDelay(iterationDelay);

    }  //end while 

  } else if (mode == WINDOW_MODE) {

  } else {
    printf("UDPEchoClient:(%f): HARD ERROR: Bad mode :  %d \n",
       curTime, mode);
    exit(1);
  }

  //If we get here, we've ended because iterations finished
  if (debugLevel > 2) {
       printf("UDPEchoClient2: Finished %d iterations \n", nIterations);
              
  }
  exitProcessing(curTime);
  exit(0);
}

void CatchAlarm(int ignored) 
{ 
  if (debugLevel > 2) {
    printf("UDPEchoClient2:CatchAlarm:(signal:%d): #iterations:%d,  #timeouts:%d \n", 
          ignored, numberOfTrials,numberOfTimeOuts);
  }

}

void clientCNTCCode() {

  bStop = 1;
  if (debugLevel > 2) {
    printf("UDPEchoClient2:CNTC: #iterations:%d,  #timeouts:%d \n", 
           numberOfTrials,numberOfTimeOuts);
  }
  exitProcessing(timestamp());
  exit(0);
}


void exitProcessing(double curTime) {

  endTime = curTime;
  double duration = endTime - startTime;
  double actualSendRate = 0;


  if (sock != -1) 
    close(sock);

  sock = -1;
  numberLost = numberOfTrials - numberRTTSamples;

  if (duration > 0.0)
    actualSendRate = ((double )totalBytesSent)*8 / duration;

  if (numberRTTSamples != 0) {
    avgPing = (totalPing/numberRTTSamples);
    meanCurRTT = (sumOfCurRTT/numberRTTSamples);
  }
  if (numberOfTrials != 0) 
    avgLoss = (((double)numberOfTimeOuts*100)/numberOfTrials);

  if (mode == RTT_MODE) {
    if (debugLevel > 0) {
        printf("UDPEcho2Client:(%f):RTT_MODE: Sent:%d meanCurRTT:%3.9f (avgPing:%ld) smoothedRTT:%3.9f, avgLoss:%2.5f, actualSendRate:%9.0f\n",
             duration,numberOfTrials, meanCurRTT, avgPing,  smoothedRTT, avgLoss, actualSendRate);
    }
  } else {
    if (debugLevel > 0) {
        printf("UDPEcho2Client:(%f):CBR_MODE: SentMsgs:%d TotalBytes:%lld actualSendRate:%9.0f\n",
             duration,numberOfTrials, totalBytesSent, actualSendRate);
    }
  }

  if (debugLevel > 2) {
    printf("UDPEcho2Client(%f:%s) attempts/samples/#Lost/#TOs/NumberNewSockets: :%d:%d:%d:%d:%d #errors:%d \n", 
       duration,serverIP,numberOfTrials,numberRTTSamples,numberLost, outOfOrderArrivals,numberOfSocketsUsed,errorCount);
  }
  if (newFile != NULL) {
    fflush(newFile);
    fclose(newFile);
  }
}



