#include "headers.h" /* has all important stuff */

/* this file does the authentication stuff */

/* authenticate client */
void authClient(char *str, const int len)
{
   int count = 0;  /* used to prevent overflows         */

   long res;       /* result of new challenge           */
   long chal;      /* will contain the random challenge */

   char *keyptr;   /* pointer into key                  */
   char *dataptr;  /* pointer into readbuf              */

   char key[32];   /* will hold their final value       */
   char readbuf[MAXREADSIZE];

   keyptr = key, dataptr = readbuf;

   memset(key, 0, sizeof(key));
   memset(readbuf, 0, sizeof(readbuf));

   strncpy(readbuf, str, len);

   getID(readbuf);  /* do some stuff with the client ID */
                    /* will set the client.ID           */

   if (debugging == 1)
   {
      (void)putchar('\n');
      (void)write(dblogfd, "\n", 1);
   }

   /* generate a random challenge */
   chal = random();

   debug("sending random challenge to client..\n");

   /* send client a challenge (with ID1) */
   send_data((clients[curClient]).sockfd, "VERIFY %ld\n", chal);

   timeout = 0, errors = 0;

   memset(readbuf, 0, sizeof(readbuf)); /* [re]clear buffer */
   recv_data((clients[curClient]).sockfd, readbuf, sizeof(readbuf)-1, 0);

   (void)alarm(0);

   if ((timeout == 1) || (errors == 1) || (strncmp(readbuf, "VERIFY", 6) != 0))
   {
      errors = 1;
      return;
   }

   dataptr = strstr(readbuf, "VERIFY");
   dataptr += 7; /* skip "VERIFY " */
   
   count = 0;
   while ((*dataptr) && (isprint(*dataptr) != 0) && 
          (count < (int)sizeof(key)))
   {
      *keyptr++ = *dataptr++;
      count++;
   }

   res = atol(key);
   if (res != chal)
   {
      if (debugging == 1)
      {
         putchar('\n');
         (void)write(dblogfd, "\n", 1);
      }

      debug("client returned invalid verification #..\n");

      signal(SIGPIPE, SIG_IGN);

      send_data((clients[curClient]).sockfd, "ERROR: %s\n", VERERROR);
      (void)sleep(MAXPAUSE); /* give them time to handle this */

      errors = 1;
      return;
   }

   else
   {
      /* -- now authenticated -- */
      if (debugging == 1)
      {
         putchar('\n');
         (void)write(dblogfd, "\n", 1);
      }

      debug("client successfully verified...\n"); 
      send_data((clients[curClient]).sockfd, "SUCCESSFUL verification\n");
   }
}


/* ----------------------- */
