/* Do authentication with server */
/* ----------------------------- */

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

/* get challenge, and respond */
void doAuth()
{
   long res;        /* final result for our authentication algorithm */
   int count = 0;  /* prevent overflows */

   char *dataptr;  /* pointer to challenge from server */
   char *chalptr;  /* points to actual challenge       */

   char chalval[32]; 
   char readbuf[MAXREADSIZE];

   chalptr = chalval;
   memset(chalval, 0, sizeof(chalval));

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

   recv_data(readbuf, sizeof(readbuf));
   if (strncmp(readbuf, "VERIFY", 6) != 0)
   {
      error("error: was expecting VERIFY.. restarting\n\n");

      if (gotInfoServ == 1) longjmp(reconnect, 1);
      else longjmp(infoconn, 1);
   }

   dataptr = strstr(readbuf, "VERIFY");
   dataptr += 7; /* skip "VERIFY " */

   count = 0;
   while ((*dataptr) && (*dataptr != ' ') &&
          (isprint((int)*dataptr) != 0) && (count < (int)sizeof(chalval))) 
   {
      *chalptr++ = *dataptr++;
      count++;
   }

   res = atol(chalval);
   send_data("VERIFY %ld\n", res);

   /* loop until server tells us success or failure */
   recv_data(readbuf, sizeof(readbuf));

   if (strncmp(readbuf, "SUCCESSFUL verification", 23) == 0)
      (void)printf("%cerified ourselves successfully\n\n",
                  (debugging != 1 ? 'V' : 'v'));

   else
   {
      error("error: expecting \"SUCCESSFUL verification\".."
            "received message was: %s\n%c", readbuf,
            (strchr(readbuf, '\n') == NULL ? '\n' : '\0'));

      debug("now restarting\n");

      if (gotInfoServ == 1) longjmp(reconnect, 1);
      else longjmp(infoconn, 1);
   }
}
