/*********************************************************
*
* Module Name: UDP Echo server 
*
* File Name:    UDPEchoServer.c	
*
* Summary:
*  This file contains the echo server code
*  The server loops forever, receives a message 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
*            
*
*
*
* Revisions:
*  $A0 : 2-20-2017 Version 1.2 
*  $A1 : 9/7/2017  Version 1.3
*
*********************************************************/
#include "UDPEcho.h"

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

int sock = -1;                         /* Socket descriptor */
int bStop = 1;;
FILE *newFile = NULL;
double startTime = 0.0;
double endTime = 0.0;
double  duration = 0.0;
unsigned int largestSeqRecv = 0;
unsigned int receivedCount = 0;

unsigned int numberRTTSamples = 0;
unsigned int numberOfSocketsUsed = 0;
unsigned int numberOutOfOrder=0;

long avgPing = 0.0; /* final mean */
long totalPing = 0.0;
long minPing = 100000000;
long maxPing = 0;

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

double RTTSample = 0.0;
double sumOfRTTSamples = 0.0;
double meanRTTSample = 0.0; /* final mean */

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


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[ECHOMAX];        /* Buffer for echo string */
    unsigned short echoServPort;     /* Server port */
    int recvMsgSize;                 /* Size of received message */
    char dataFile[] = "EchoServer.dat";
    unsigned int debugFlag = 129;
    unsigned int loopCount = 0;
    unsigned int errorCount = 0;
    unsigned int RxSeqNumber = 0;
    int *RxSeqNumberPtr = (int *)echoBuffer;
    int rc = 0;
    double curTime = 0.0;

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

    if (argc < 2)         /* Test for correct number of parameters */
    {
        printf("%s: Usage: <UDP SERVER PORT> <debug flag> \n", argv[0]);
        exit(1);
    }

    signal (SIGINT, CNTCCode);

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

    if (argc == 3) {        /* see if debug level set ... */
      debugFlag = atoi(argv[2]);
      debugLevel = (debugFlag & 0x0000007f); 
    }

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

    if (debugLevel > 0) {
      printf("UDPEchoServer(#args:%d): port:%d  debugLevel:%d debugFlag:%d createFlag:%d \n",
          argc,echoServPort, 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);
      }
    }

    /* 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(1);
    }

    /* 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(1);
    }
  
    while ( bStop != 1) 
    {
      loopCount++;
      curTime = timestamp();
      /* Set the size of the in-out parameter */
      cliAddrLen = sizeof(echoClntAddr);

      /* Block until receive message from a client */
      recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen);
      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;
      }

      receivedCount++;

      RxSeqNumber = (unsigned int)ntohl( (unsigned int)(*RxSeqNumberPtr) );
      if (largestSeqRecv < RxSeqNumber)
        largestSeqRecv = RxSeqNumber;

      if (debugLevel > 3) {
        printf("UDPEchoServer(%f):(%d,%d),rxed %d bytes, RxSeqNumber:%d  errorCount:%d \n",
            curTime,loopCount,receivedCount, recvMsgSize, RxSeqNumber, errorCount);
      }


      /* Send received datagram back to the client */
      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;
      }

      if (debugLevel > 2) {
        printf("UDPEchoServer:(%f)(%d,%d) sent %d bytes, seqNumber:%d  errorCount:%d, rc:%d  \n",
               curTime,loopCount,receivedCount, recvMsgSize,RxSeqNumber, errorCount, rc);
      }
      if (createDataFileFlag == 1 ) {
        fprintf(newFile,"%f %d %d %d %d %d\n",
               curTime,RxSeqNumber,recvMsgSize,largestSeqRecv, receivedCount,errorCount);
      }
    }
    //If we get here, we are supposed to end....
    printf("UDPEchoServer:(%f)(%d,%d) WARNING:  Ending Loop  \n", curTime,loopCount,receivedCount);
    //exitProcessing(curTime);
    exit(0);
}


void CNTCCode() {

  bStop = 1;
  exitProcessing(timestamp());
  exit(0);
}


void exitProcessing(double curTime) {
  unsigned int numberLost=0;
  double avgLoss = 0.0;

  endTime = curTime;
  duration = endTime - startTime;
  if (sock != -1) 
    close(sock);
  sock = -1;
  numberLost = largestSeqRecv - receivedCount;

  if (numberLost != 0) 
    avgLoss = ((double)numberLost*100)/largestSeqRecv;

  if (debugLevel >0) {
    printf("UDPEcho2Server: %f  avgLoss:%2.5f  largestSeqRecv: %d  receivedCount:%d \n",
       duration, avgLoss, largestSeqRecv, receivedCount);
   }
  if (newFile != NULL) {
    fflush(newFile);
    fclose(newFile);
  }
}





