/**********************************************************
 * tcp - upd echo server program 
 *
 * This program is the server side of a udp/tcp echo program.
 * For UDP the server immediately replies.
 * For TCP the server forks a child to handle the request.
 *   The server receives a CHUNKSIZE and then echoes 
 *   the chunk. 
 *
 * Invocation:
 *   ./server 5000 0.0
 *    port:
 *    loss rate:
 *
 * Notes:
 *  -modify the Makefile to add -DDEBUG option or uncomment below
 *  -this TCP server design will support a client that behaves in
 *     any way as long as it sends less than CHUNKSIZE data.
 *     If it sends (much) more, the client must follow the expected
 *     behavior of sending and then receiving a chunk at a time.
 *
 * Revisions
 * $A0: 4/16/2006 : For some reason the select would
 *     occasionally unblock with a UDP event but there would
 *     not be any data.  To get around, change udp socket
 *     to be non-blocking on reads. If we get a udp event
 *     with no data, we just ignore.
 * $A1: 4/16/2006 : For some reason we occasionally got
 *      an error in an accept().  Now we ignore it.
 * $A2: 4/17/2006:  When we get the bogus UDP event
 *     we also detected a bogus event on the tcp socket.
 *     This caused us to block in the accept.  To avoid
 *     changing to a nonblocking TCP socket, we don't
 *     do the accept when we get false udp event.
 *    
 *********************************************************/
#include "echo.h"

void sig_chld(int signo);
void CNTCCode();

int currentNumberOfClients  = 0;

//uncomment this to turn on VERBOSE printf's
//#define DEBUG 0 
//#define XDEBUG 0 



unsigned int getSeed();
int handle_UDP(int sock, double dropRate);
void handle_TCP(int sock);

int main(int argc, char *argv[])
{
    int sock_tcp,sock_udp;                      
    fd_set sock_set;
    struct sockaddr_in servAddr; 
    unsigned short port;    
    double dropRate;
    struct sigaction myAction;       /* Signal handler specification structure */
    int sock_flags;

    int rc = 0;

    if (argc != 3)         /* Test for correct number of parameters */
    {
       printf("Usage:  %s port dropRate\n", argv[0]);
       exit(1);
    }

    signal (SIGINT,CNTCCode);

    (void)srand(getSeed());
	
    port = atoi(argv[1]);  
    dropRate = atof(argv[2]);

    /* Create socket for UDP*/
    if ((sock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        DieWithError("socket() udp failed");
//$A0
    sock_flags = fcntl(sock_udp,F_GETFL,0);
    fcntl(sock_udp, F_SETFL, sock_flags | O_NONBLOCK);

    /* Create socket for TCP*/
    if ((sock_tcp = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
       DieWithError("socket() tcp failed");
    
    /* Construct local address structure */
    memset(&servAddr, 0, sizeof(servAddr));   /* Zero out structure */
    servAddr.sin_family = AF_INET;                /* Internet address family */
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
    servAddr.sin_port = htons(port);      /* Local port */

    /* Bind to the local address */
    if (bind(sock_tcp, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
        DieWithError("bind() failed");
	
    if (bind(sock_udp, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
        DieWithError("bind() failed");
	
    /* Mark TCP socket to listen */
    if (listen(sock_tcp, 5) < 0)
        DieWithError("listen() failed");

    /* Set ChildExitSignalHandler() as handler function */
    myAction.sa_handler =  sig_chld;
    if (sigfillset(&myAction.sa_mask) < 0)   /* mask all signals */
      DieWithError("sigfillset() failed");
      /* SA_RESTART causes interrupted system calls to be restarted */
      myAction.sa_flags = SA_RESTART;
     /* Set signal disposition for child-termination signals */
     if (sigaction(SIGCHLD, &myAction, 0) < 0)
      DieWithError("sigaction() failed");

    for (;;) /* Run forever */
    {

        int max_d = (sock_tcp > sock_udp) ? sock_tcp : sock_udp; 
        FD_ZERO(&sock_set);
        FD_SET(sock_tcp,&sock_set);
        FD_SET(sock_udp,&sock_set);

#ifdef DEBUG
        printf("parent: Enter SELECT \n");
#endif
        rc = select(max_d + 1,&sock_set,NULL,NULL,0);
        if (rc == 0) {
            continue;
        } else {
          if (rc < 0) {
#ifdef DEBUG
           printf("parent: UNBLOCKED from SELECT with errno:%d (WILL IGNORE) \n",errno);
#endif
            continue;
          }
//$A2: This is used as a flag to catch 'bogus' UDP and TCP events.
//     If we unblock, detect a UDP event but no data we set rc to 1
//     to indicate a problem.  If there is also a TCP event, this
//     flag prevents the TCP code from issuing the accept.  If
//     we don't do this, we block in the accept and will miss
//     further UDP packets until a new TCP Cx unblocks us.
           rc = 0;
#ifdef DEBUG
           printf("parent: UNBLOCKED from SELECT \n");
#endif
            if (FD_ISSET(sock_udp,&sock_set)) {
                rc = handle_UDP(sock_udp, dropRate); 
#ifdef DEBUG
                printf("parent: return from handle_UDP: %d \n",rc);
#endif
                if (rc == 1)
                {
#ifdef DEBUG
                  printf("parent: recover from false UDP event \n");
#endif
                }
            } 
            if (FD_ISSET(sock_tcp, &sock_set)) {
                int cli;
                struct sockaddr_in cliAddr;
                int cliAddrLen = sizeof(cliAddr);
                pid_t cpid;

#ifdef DEBUG
               printf("Parent: About to do an accept  \n");
#endif

//$A2
                if (rc == 1)
                {
#ifdef DEBUG
                  printf("parent:  Also there's a TCP event --  don't do accept \n");
#endif
                  continue;
                }
//$A1
                if( (cli = accept(sock_tcp, (struct sockaddr *) &cliAddr,&cliAddrLen)) < 0)
                {
                   if(errno != EWOULDBLOCK) 
                   {
                     fprintf(stderr,"EchoServer: errno %d in accept, will IGNORE\n",errno);
                     close(cli);
                     continue;
//                 DieWithError("accept() failed");
                   }
                }
                
                if ((cpid = fork()) < 0) 
                    DieWithError("fork() error");
                
                currentNumberOfClients++;
                if (cpid == 0) {
                   close(sock_tcp);
                   handle_TCP(cli);
                   close(cli);
#ifdef DEBUG
                   printf("Child: Exiting a child process \n");
#endif
                   exit(0);
                } 
#ifdef DEBUG
                printf("Parent:Handling TCP client(total#:%d) %s in child process %d\n",
                       currentNumberOfClients,inet_ntoa(cliAddr.sin_addr), (int) cpid);
#endif
                close(cli);
            } 

        }
    }
    return 0;
}

void sig_chld(int sig) {
pid_t   pid;
int stat;

  while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) {
    if (currentNumberOfClients > 0)
      currentNumberOfClients--;
#ifdef DEBUG
    printf("sigchldwaitpid:  %d terminated, currentNumberOfClients %d\n", (int) pid,currentNumberOfClients);
#endif
  }
  return;
}

unsigned int getSeed() {
	struct timeval curTime;
	(void) gettimeofday (&curTime, (struct timezone *) NULL);
	return curTime.tv_usec;
}

/*
 *   rc =  void handle_UDP(int sock, double dropRate) {
 *   rc = 0 if successeful
 *        else a 1 means ignore
*/
int handle_UDP(int sock, double dropRate) 
{
    int rc = 0;      
    int recvSize;
    char buf[CHUNKSIZE];
    struct sockaddr_in cliAddr;
    int cliAddrLen = sizeof(cliAddr);

#ifdef DEBUG
    printf("handle_UDP: about to rx  %d bytes \n",CHUNKSIZE);
#endif
    if( (recvSize = recvfrom(sock, buf, CHUNKSIZE, 0,
               (struct sockaddr *) &cliAddr, &cliAddrLen)) < 0) {
//$A0 - catch the error that occurs if there is no data...
      if(errno != EWOULDBLOCK) 
        DieWithError("recvfrom() failed");
      else {
#ifdef DEBUG
         printf("Handling UDP NO DATA, recvSize:%d\n",recvSize);
#endif
        return(1);
      }
    }
#ifdef DEBUG
    printf("Handling UDP client %s, received %d bytes \n", inet_ntoa(cliAddr.sin_addr),recvSize);
#endif
    if(dropRate)
        if(rand() < (RAND_MAX * dropRate)) 
            return(rc);
    
    if(sendto(sock, buf, recvSize, 0, 
               (struct sockaddr *) &cliAddr, cliAddrLen) != recvSize)
        DieWithError("sendto() diff bytes than expected");

  return(rc);
}

void handle_TCP(int sock) {
    
    int recvSize;
    char buf[CHUNKSIZE];
    int cur;

    if((recvSize = recv(sock, buf, CHUNKSIZE, 0)) < 0)
    {
        DieWithError("recv() tcp failed");
    }

#ifdef DEBUG
   printf("Child:handle_TCP(pid:%d): received first %d bytes  \n",(int)getpid(),recvSize);
#endif

    while (recvSize > 0) {
        if ((cur = send(sock, buf, recvSize, 0)) < 0)
          DieWithError("send() tcp error");
//        if (send(sock, buf, recvSize, 0) != recvSize)
        if ( (recvSize = recv(sock, buf, CHUNKSIZE, 0)) < 0)
          DieWithError("recv() tcp error");
    }
   
}

void CNTCCode() {
  printf("mainProgram:  CNT-C Interrupt,  exiting....\n");
  exit(0);
}

