/*********************************************************
*
* Module Name: UDP Echo server 
*
* File Name:    UDPEchoServer.c	
*
* Summary:
*  This file contains the echo server code
*  The server loops forever, receives a Data message, finds the session state
*  associated with the session (creates a new session state if it is the first message of a new session).
*  A particular session maps to an instance of a client running a some host (with a Host IP and port)
*  that is interacting with this Server program.  Since this server program must manage any number of 
*  client sessions, it maintains a list of session structures that represents a session's state.
*
*  One the session is either created or found, the next work depends on the mode. 
*        mode 0:  RTT_MODE:   Simply echos back exactly what was received.
*        mode 1:  CBR_MODE:   Does not return anything back to the client.  It updates counters as needed.
*        mode 2:  WINDOW_MODE:  When a DATA MSG arrives (that conains SeqNumber), it replies back with an ACK messages.
*                                The server keeps track of the session's nextExpectedSeqNumber.
*
*                                If the SeqNumber that arrives = sessions->nextExpectedSeqNumber,
*                                if (SeqNumber ==  session->nextExpectedSeqNumber)
*                                    An ACK message containing an RxSeqNumber of SeqNumber++ is sent to the client
*                                    And the session->nextExpectedSeqNumber++
*                                This message is referred to as A NEW ACK since it acknowledges a new message.
*                             
*                                if (SeqNumber <= session->nextExpectedSeqNumber)
*                                 the server issues an ACK message containing an RxSequmber of Se
*                               The server maintains a session state for this session.  variable 
*                               The ACK contains an RxSeqNumber that is either a NEW ACK or a DUP ACK
*                                 NEW ACK:  RxSeqNumber = Simply echos back the SeqNumber number just received incremented by 1
*                                 DUP ACK:   exactly what was received.
*
 and echoe's it back to the client.
*
* Parameters:
*    port :   the port to use.  Port 7 is used by default.
*    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
* 
*    Random Drop Rate :  0-100 represents the random packet loss process to apply to the incoming packet stream
*
* Revisions:
*  $A0 : 2-20-2017 Version 1.2 
*  $A1 : 9/7/2017  Version 1.3
*  $A2 : 928/2017  V 1.4 - added CBR mode
*  $A3 : 11/9/2017  V 1.6 - prep for window mode 
*            Added the random drop param and capability
*  $A4 : 12/3/2017  V 1.7  - interim solution for mode 2
*           search for 'WINDOW MODE' for main code
*           search for 'OUT WINDOW MODE' or  'OUT RTT MODE'  for output to dat file 
*  $A5 :  12/10/2017 - V1.8
*
*
*  Todos:
*
*  -
*********************************************************/
#include "UDPEcho.h"

void CNTCCode();
void exitProcessing(double curTime, int reasonCode);

int sock = -1;                         /* Socket descriptor */
int bStop = 1;;
FILE *newFile = NULL;
double startTime = 0.0;
double lastMessageTime =0.0;  //records time of last recv

//For all client sessions
unsigned int receivedCount = 0;
long long totalBytesReceived =0;	
double oneWayLatencySample=0.0;

//$A3
unsigned int arrivalCount = 0;
unsigned int totalArtificialDropCount=0;

//For the monitoring  (in seconds)
#define MONITOR_INTERVAL 60 
double firstMonInterval = -1;
double lastMonInterval = -1;
unsigned int monByteCount = 0;
unsigned int monLossCount = 0;
unsigned int numberIntervals = 0;

//Used to calculate per session updates
unsigned int numberRTTSamples = 0;
unsigned int numberOfSocketsUsed = 0;
unsigned int numberOutOfOrder=0;


long avgPing = 0.0; /* final mean */
long totalPing = 0.0;

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 debugFlagMask =  0x00000080;

void myUsage(char *myName, int paramCount, char *myVersion)
{
  printf("Usage(V%s,%d): %s [port] [debugFlag] [dropRate] \n", myVersion,paramCount,myName);
}



/*************************************************************
*
* Function: Main program for  UDPEcho  server
*           
*  Parameters:
*      serverPort : port to use 
        reflects drop rate applied to arriving data.
*                   Param is a number [0, 100] 
*      debugFlag =  specifies the level of debug info displayed
*      dropRate =   random packet drop rate applied to arriving data.
*              Param is a double 0 - 1.0 
*              If not specified, it is 0
*
* outputs:  success or failure
*
* notes: 
*
***************************************************************/
int main(int argc, char *argv[])
{
    struct sockaddr_in echoServAddr; /* Local address */
    struct sockaddr_in echoClntAddr; /* Client address */
    unsigned int cliAddrLen;         /* Length of incoming message */


    char echoBuffer[MAX_DATA_BUFFER];      /* Buffer for sending and receiving   */
    unsigned short echoServPort;     /* Server port */
    int recvMsgSize;                 /* Size of received message */
    char dataFile[] = "Server.dat";
    unsigned int debugFlag = 129;
    unsigned int loopCount = 0;
    unsigned int errorCount = 0;


//$A5
    unsigned int RxSeqNumberToSend = 1;  //the RxSeqNumber to send next for this session
    unsigned int RxSeqNumber = 0;  //the RxSeqNumber most recently arrived
    unsigned int *RxSeqNumberPtr = (unsigned int *)echoBuffer;
//$A2
    unsigned short RxMode = RTT_MODE;
    unsigned short *RxModePtr = (unsigned short *)&echoBuffer[4];
    session *mySession = NULL;
    int  NextExpectedDataRxed = FALSE;  //TRUE if the data seq number is the next expected
    unsigned short *MsgTypePtr = (unsigned short *)&echoBuffer[6];
    unsigned int *TimeSentSecondsPtr = (unsigned int *)&echoBuffer[8];
    unsigned int *TimeSentUSecondsPtr = (unsigned int *)&echoBuffer[12];
    unsigned short *MsgSizePtr = (unsigned short *)&echoBuffer[16];
    unsigned short *dataSizePtr = (unsigned short *)&echoBuffer[18];


//$A4
    unsigned short msgType = DATAMSG; 
    unsigned int   sendTimeSeconds = 0;
    unsigned int   sendTimeUSeconds  = 0;
    unsigned short msgSize = 0;
    unsigned short dataSize = 0;
    double RxMsgSendTime = 0.0;
 
    int rc = 0;
    double curTime = 0.0;
//$A3
    double dropRate = 0.0;

    bStop = 0;
    startTime = timestamp();
    curTime = startTime;

    if (argc < 2)         /* Needs at least the port number */ 
    {
      myUsage(argv[0],argc, Version);
      exit(EXIT_FAILURE);
    }

    echoServPort = atoi(argv[1]);  /* First arg:  local port */
    signal (SIGINT, CNTCCode);

    if (argc > 2) {        /* get debugFlag and set the Level */
      debugFlag = atoi(argv[2]);
      debugLevel = (debugFlag & 0x0000007f); 
    }

    if (argc == 4) {     
      dropRate= atof(argv[3]);
      //seed randomly
      (void)srand(getSeed());
    }


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

    if (createDataFileFlag == 1 ) {
      newFile = fopen(dataFile, "w");
      if ((newFile ) == NULL) {
        printf("UDPEchoServer(%s): HARD ERROR failed fopen of file %s,  errno:%d \n", 
             argv[0],dataFile,errno);
        exit(EXIT_FAILURE);
      } 
    }
    //JJM for testing 
    if (createDataFileFlag == 1 ) {
       fprintf(newFile, "curTime, RxMode, inet_ntoa(echoClntAddr.sin_addr),ntohs(echoClntAddr.sin_port), RxSeqNumberToSend, rc, oneWayLatencySample,  mySession->largestSeqNumRxed, mySession->messagesReceived,errorCount, getNumberSessions()\n");
    }

    /* Create socket for sending/receiving datagrams */
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
      errorCount++;
      printf("UDPEchoServer(%f): HARD ERROR : Failure on socket call errorCount:%d  errno:%d \n", 
              curTime,errorCount,  errno);
      exit(EXIT_FAILURE);
    }

    /* Construct local address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */
    echoServAddr.sin_family = AF_INET;                /* Internet address family */
    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
    echoServAddr.sin_port = htons(echoServPort);      /* Local port */

    rc = bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr));
    /* Bind to the local address */
    if (rc < 0) {
      errorCount++;
      printf("UDPEchoServer(%f): HARD ERROR : bind to port %d error, errorCount:%d  errno:%d \n", 
           curTime,echoServPort,errorCount,  errno);
      exit(EXIT_FAILURE);
    }
  
    while ( bStop != 1) 
    {

      //First do the items that need to be done for all modes ...
      loopCount++;
      /* Set the size of the in-out parameter */
      cliAddrLen = sizeof(echoClntAddr);

      /* Block until receive message from a client */
      recvMsgSize = recvfrom(sock, echoBuffer, MAX_DATA_BUFFER, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen);
      curTime = timestamp();
      if (recvMsgSize < 0)
      {
        errorCount++;
        printf("UDPEchoServer(%f)(%d) HARD ERROR : error recvfrom  errorCount%d  errno:%d \n", 
              curTime,loopCount, errorCount,  errno);
        if (createDataFileFlag == 1 ) {
            fprintf(newFile,"UDPEchoServer(%f)(%d) HARD ERROR : error recvfrom  errorCount%d  errno:%d \n", 
              curTime,loopCount, errorCount,  errno);
        }
        continue;
      } else if (recvMsgSize < DATAMsgHdrSize) {
        printf("UDPEchoServer(%f): HARD ERROR : rx'ed partial data?? recvMsgSize :%d min :%d  \n", 
           curTime, recvMsgSize, DATAMsgHdrSize);
        exit(EXIT_FAILURE);
      } 

      //we know we received a valid data frame
      RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
      RxMode = (unsigned short )ntohs( (unsigned short )(*RxModePtr));
      msgType = ntohs(*MsgTypePtr);
      msgSize = ntohs(*MsgSizePtr);
      dataSize = ntohs(*dataSizePtr);
      sendTimeSeconds = ntohl(*TimeSentSecondsPtr);
      sendTimeUSeconds = ntohl(*TimeSentUSecondsPtr);

      RxMsgSendTime =  ((double)sendTimeSeconds + ((double)sendTimeUSeconds / 1000000));
      oneWayLatencySample= curTime - RxMsgSendTime;
 
      if (debugLevel > 2) {
            printf("UDPEchoServer(%f):(%d,%d) :DataMsg(recvSize:%d): Rxseq:%d,msgSize:%d dataSize:%d \n",
              curTime,loopCount,receivedCount,recvMsgSize, RxSeqNumber, 
              msgSize,dataSize);
            printf("UDPEchoServer(%f):DataMsg: RxMsgSendTime:%f,  latency:%3.6f \n",
              curTime, RxMsgSendTime, oneWayLatencySample);
      }


       //we've successfully rxed a msg,...now see if we want to randomly drop it
      //Randomly drop the message that arrived
      //the rand() function returns a RN [0,RAND_MAX]
      if(dropRate) {
        if(rand() < (RAND_MAX * dropRate)) {
          totalArtificialDropCount++;
          continue;
        }
       arrivalCount++;
      }
      //Check if Session already exists
      lastMessageTime =curTime;
      mySession = findSession(echoClntAddr.sin_addr, echoClntAddr.sin_port);

      if(mySession == NULL) // If not added already, create a session
      {
        mySession = createSession(echoClntAddr.sin_addr, echoClntAddr.sin_port, RxMode);
      }


      //Tracks total number received from all clients
      receivedCount++;
      totalBytesReceived += recvMsgSize;

      NextExpectedDataRxed =  FALSE;


      //for very first segment received
      if (mySession->messagesReceived == 0) {
        mySession->nextExpectedSeqNumber = RxSeqNumber;
        mySession->largestSeqNumRxed =  RxSeqNumber;
      }

      //Update largest seq num
      if (RxSeqNumber > mySession->largestSeqNumRxed) {
        mySession->largestSeqNumRxed =  RxSeqNumber;
      }

      //the arrival is a 'new' and next expected segment  
      if (RxSeqNumber == mySession->nextExpectedSeqNumber) {
        mySession->nextExpectedSeqNumber++;
        NextExpectedDataRxed = TRUE;
      }

      //the arrival is a 'new' but not next expected segment  
      if ( RxSeqNumber > mySession->nextExpectedSeqNumber) {
        mySession->largestSeqNumRxed = RxSeqNumber;
        mySession->outOfOrderArrivals++;
      }

      //the arrival is an 'old' segment 
      if (RxSeqNumber < mySession->nextExpectedSeqNumber) {
        mySession->duplicateSeqNumbers++;
      }

      mySession->lastSeqNumRxed = RxSeqNumber;

      oneWayLatencySample= curTime - RxMsgSendTime;
      mySession->oneWayLatencySampleSUM+= oneWayLatencySample;
      mySession->sampleSumCount++;

      //ERROR CHECK
      if (mySession->mode != RxMode) { 
        printf("UDPEchoServer(%f): HARD ERROR msg arrival mode (RxMode:%d)  does not match session mode (%d)  \n", 
           curTime, RxMode, mySession->mode);
        exit(EXIT_FAILURE);
      }

      //Update session info 
      gettimeofday(&(mySession->lastRxTime), NULL);
      mySession->messagesReceived++;
      mySession->bytesReceived += recvMsgSize;

      mySession->messagesLost = mySession->largestSeqNumRxed - mySession->messagesReceived;


      if (debugLevel > 2) {
        if (NextExpectedDataRxed == TRUE)
          printf("UDPEchoServer(%f):(%d,%d) EXPECTED! Rxseq:%d   %d bytes, Rxmode:%d errorCount:%d #sessions:%d \n",
              curTime,loopCount,receivedCount,RxSeqNumber, 
              recvMsgSize, RxMode,errorCount, getNumberSessions());
        else
          printf("UDPEchoServer(%f):(%d,%d) NOT EXPECTED! Arrived Rxseq:%d NextExpected:%d  %d bytes, Rxmode:%d errorCount:%d #sessions:%d \n",
              curTime,loopCount,receivedCount,RxSeqNumber,mySession->nextExpectedSeqNumber,
              recvMsgSize, RxMode, errorCount, getNumberSessions());

        displaySession(mySession,FALSE);
      }


      if (RxMode == RTT_MODE) {
        /* Send received datagram back to the client */
        // Note: we don't update any field.....
        rc = sendto(sock, echoBuffer, recvMsgSize, 0,  (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr));

        if ( rc != recvMsgSize) 
        {
          errorCount++;
          printf("UDPEchoServer(%f):(%d) HARD ERROR : error sending %d bytes to client %s, errorCount%d, rc:%d  errno:%d \n", 
              curTime,loopCount,recvMsgSize, inet_ntoa(echoClntAddr.sin_addr), errorCount, rc,  errno);
          if (createDataFileFlag == 1 ) {
            fprintf(newFile,"UDPEchoServer(%f):(%d) HARD ERROR : error sending %d bytes to client %s, errorCount%d  rc:%d, errno:%d \n", 
              curTime,loopCount,recvMsgSize, inet_ntoa(echoClntAddr.sin_addr), errorCount, rc,  errno);
          }
          continue;
        }

        //$A4 TODO:  have mode 0 send MsgHdr so we can obtain a onewaylatency
        if (debugLevel > 1) {
          printf("%f %d %s %d %d %d %3.6f %d %d %d %d\n",
               curTime, RxMode, inet_ntoa(echoClntAddr.sin_addr),ntohs(echoClntAddr.sin_port),
               RxSeqNumber, recvMsgSize, oneWayLatencySample,  
               mySession->largestSeqNumRxed, mySession->messagesReceived,errorCount, getNumberSessions());
        }
        // OUT RTT MODE  
        if (createDataFileFlag == 1 ) {
          fprintf(newFile,"%f %d %s %d %d %d %3.6f %d %d %d %d \n",
               curTime, RxMode, inet_ntoa(echoClntAddr.sin_addr),ntohs(echoClntAddr.sin_port),
               RxSeqNumber, recvMsgSize, oneWayLatencySample, 
               mySession->largestSeqNumRxed, mySession->messagesReceived,errorCount, getNumberSessions());
        }

      } else if (RxMode == CBR_MODE) {
        lastMessageTime =curTime;
        //TODO  : Add support for the  MONITOR 
        //        Each Interval, compute avg stats

      } else if (RxMode == WINDOW_MODE) 
      {
        //WINDOW MODE

          // Return an ACK of next expected seq number 
          RxSeqNumberToSend  = mySession->nextExpectedSeqNumber;
          *RxSeqNumberPtr  =  htonl(RxSeqNumberToSend);
          *MsgSizePtr =  htons(ACKMsgSize);

          //Adjust seqnum in outbound ACK to be the next expected seq number and size of msg
          rc = sendto(sock, echoBuffer, ACKMsgSize,  0,  (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr));

          if ( rc != ACKMsgSize) 
          {
              errorCount++;
              printf("UDPEchoServer(%f):(%d) HARD ERROR : error sending %d bytes ACK to client %s, errorCount%d, rc:%d  errno:%d \n", 
                curTime,loopCount,recvMsgSize, inet_ntoa(echoClntAddr.sin_addr), errorCount, rc,  errno);
      
              if (createDataFileFlag == 1 ) {
                fprintf(newFile,"UDPEchoServer(%f):(%d) HARD ERROR : error sending %d bytes to client %s, errorCount%d  rc:%d, errno:%d \n", 
                  curTime,loopCount,recvMsgSize, inet_ntoa(echoClntAddr.sin_addr), errorCount, rc,  errno);
              }
              continue;
          } else {
              //else, sent ACK msg!!
              if (debugLevel > 1) {
                printf("STATE: %f %d %s %d %d %d %3.6f %d %d %d %d\n",
                     curTime, RxMode, inet_ntoa(echoClntAddr.sin_addr),ntohs(echoClntAddr.sin_port),
                     RxSeqNumberToSend, rc, oneWayLatencySample,  
                     mySession->largestSeqNumRxed, mySession->messagesReceived,errorCount, getNumberSessions());
              }
              if (createDataFileFlag == 1 ) {
                // OUT WINDOW MODE  
                fprintf(newFile,"%f %d %s %d %d %d %3.6f %d %d %d %d\n",
                     curTime, RxMode, inet_ntoa(echoClntAddr.sin_addr),ntohs(echoClntAddr.sin_port),
                     RxSeqNumberToSend, rc, oneWayLatencySample,  
                     mySession->largestSeqNumRxed, mySession->messagesReceived,errorCount, getNumberSessions());
              }

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

    //Since the loop only terminates upon CNTC, we've already called exitProcessing...
    // no need to call ...exitProcessing(timestamp(),MAIN_SUCCESS_EXIT);

    if (rc == SUCCESS) {
      printf("UDPEchoServer:(%f)(%d,%d) Exiting SUCCESSFULLY  \n", curTime,loopCount,receivedCount);
      exit(EXIT_SUCCESS);
    }
    else { 
      printf("UDPEchoServer:(%f)(%d,%d) Exiting with a FAILURE ?? rc:%d  \n", curTime,loopCount,receivedCount,rc);
      exit(EXIT_FAILURE);
    }

}


void CNTCCode() {

  bStop = 1;
  exitProcessing(timestamp(),CNTC_EXIT);
  exit(EXIT_SUCCESS);
}


/***********************************************************
* Function: void exitProcessing(double curTime, int reasonCode) 
*
* Explanation:  This is called when the program it to terminate. 
*  It computes final statistics and printf out results.
*
* inputs: passed the curTime
*     reasonCode: indicates who calls and why ...
*         MAIN_SUCCESS_EXIT : main program exits with no errors
*         MAIN_ERROR_EXIT 2: main program exits in error
*         CNTC_EXIT 3 :    signal handler called to terminate program
*
* outputs:
*    
* notes: 
*  It is assumed that the caller will issue the exit
*
***********************************************************/
void exitProcessing(double curTime, int reasonCode) 
{

  double  duration;
  double totalThroughput=0.0;
  double artificialDropRate =0.0;
//double endTime = curTime;
// duration = endTime - startTime;
  duration = lastMessageTime - startTime;

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

  if (duration > 0.0)
    totalThroughput = ((double )totalBytesReceived)*8 / duration;

  if (arrivalCount > 0)
     artificialDropRate =  (double)totalArtificialDropCount / (double)arrivalCount;

  if (debugLevel >0) {
    printf("UDPEcho2Server:exitProcessing(%f:%d)  #sessions:%d, receivedCount:%d, totalBytesRxed:%lld, aggregateThroughput: %9.0f, artificialDropRate=:%0.3f \n",
       duration, reasonCode, getNumberSessions(), receivedCount, totalBytesReceived, totalThroughput,artificialDropRate);
  }

  displayAllSessions(FALSE);

  if (newFile != NULL) {
    printf("UDPEcho2Server:exitProcessing(%f:%d) fflush and close file \n",
       duration,reasonCode);
    fflush(newFile);
    fclose(newFile);
  }
}





