#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include "network.h"
#define TRUE 1
#define FALSE 0
#define EXACT 2


extern int debug;

char *uppercase(s)
char *s;
{
    register char *p;

    for (p = s; *p; p++)
      *p = toupper(*p);
    return(s);
}

char *lowercase(s)
char *s;
{
    register char *p;

    for (p = s; *p; p++)
      *p = tolower(*p);
    return(s);
}

/* for now an "*" means match any number of tokens and a "$" means match one */
 /* assumes the matched part of the host & wildexpr have been removed */
/* can change logic so that if wild expr has a "*" return true otherwise the
token counds must be == */

int right_num_tokens(char *host, char *wildexpr)
{ 
char *cp;   
int hdots = 0, xdots = 0, xlen;

xlen = strlen(wildexpr);
if ((xlen == 1) && (*wildexpr == '*'))  /* single * matches anything */
  return TRUE;
cp = host;
while (cp = (char *) index(cp,'.'))	         /* count dots in hostname */
	  hdots++,cp++;
cp = wildexpr;
while (cp =  (char *) index(cp,'.'))	 /* count dots in wildexpr */
	  xdots++,cp++;
if (debug)
  printf("before case hdots = %d, xdots = %d\n",hdots,xdots);
switch (hdots) 
  {
  case 0:          /* either & or * will match 1 token */
    if (xlen == 1)
      return TRUE;
    else
      return FALSE;
  break;

  case 1:
    if (xdots == 1)
      return TRUE;
    else
      return FALSE;
  break;

  case 2:
    if (xdots == 2)
      return TRUE;
    else if (strchr(wildexpr,'*') && (xdots < 2))
      return TRUE;
    else 
      return FALSE;
  break;

  case 3:
    if (xdots == 3)
      return TRUE;
    else if (strchr(wildexpr,'*') && (xdots < 3))
      return TRUE;
    else 
      return FALSE;
  break;

  default:
    return FALSE; /* error , or maybe we have to do 1 more num */
  break;
  }

}

int hostMatches(char *host,char *realaddr, char *hostexr)
{        /* we are altering the strings here, either make copys to work with
	    or do it before calling */

char  *cp, *wildpart, *explpart,hostexpr[LG_BUFSIZ],realhost[50];
int  len;

strcpy(hostexpr,hostexr);
strcpy(realhost,host);
cp = lowercase(hostexpr);
cp = lowercase(realhost);
cp = (char *) index(hostexpr,' ');  /* null terminate after 1st token */
if (cp)
  *cp = '\0';

if (debug)
  printf("checking hostexpr = <%s>, realhost = <%s>\n",hostexpr,realhost);
cp = hostexpr;
if (isdigit((int) *cp))  /* ip addr */
  {
    cp = hostexpr + strlen(hostexpr) - 1;
     if (*cp == '*' || *cp == '$')       /* wild card */
      {
	while ((cp >= hostexpr) && (*cp == '*' || *cp == '$' 
	     || *cp == '.' )) cp--;    /* move cp to something explicit */
	 cp++;                         /* move to dot */
	if ((cp) && (*cp == '.')) {    /* break into wildpart, explpart */
	  *cp = '\0';
	  cp++;
	  explpart = hostexpr;
	  wildpart = cp;
	}   
	else
	  return FALSE; 	/* bad expression */

	cp = strstr(realaddr,explpart); /* see if the expicit part matches
					   last part of real name */
if (debug)
  printf("explpart = <%s>\n",explpart);
	if (!cp)
	  return FALSE; 
	cp = realaddr + strlen(explpart);
/* need to find the correct place to break */ 

	*cp = '\0'; /* chop off the part of realaddr already matched */
	cp++;
	/* count tokens in realaddr not already matched */
if (debug)
  printf("realleft = <%s>, wildpart = <%s>\n",cp,wildpart);
	if (right_num_tokens(cp,wildpart))
	  return TRUE;
	else 
	  return FALSE;
      }
    else                       /* exact match */
      {
	if (!strcasecmp(realhost,hostexpr))
	  return TRUE;
	else
	  return FALSE;
      }
  }
else             /* hostname */
  {
    if (strcmp(realhost,"") == 0)
      return FALSE;
    if (*cp == '*' || *cp == '$')         /* wild card */
      {
	while (cp && (*cp == '*' || *cp == '$' 
	     || *cp == '.')) cp++;     /* move cp to something explicit */
	if (cp != hostexpr)             /* we moved */
	  cp--; 	                /* now move back to the dot */
	if (*cp == '.') { 	        /* break into wildpart, explpart */
	  *cp = '\0';
	  cp++;
	  explpart = cp;
	  wildpart = hostexpr;
	}  
	else
	  {
	    printf("cp = <%s>\n",cp);
	    return FALSE;  	/* bad expression */
	  }
	  
	cp = strstr(realhost,explpart); /* see if the expicit part matches
					   last part of real name */
if (debug)
  printf("explpart = <%s>\n",explpart);
	if (!cp)
	  return FALSE;
	cp--;
	if (*cp != '.')
	  return FALSE;  	/* bad expression */	  
	*cp = '\0';        /* chop off the part of realhost already matched */
	                   /* count tokens in realhost not already matched */
if (debug)
  printf("realleft = <%s>, wildpart = <%s>\n",realhost,wildpart);
	if (right_num_tokens(realhost,wildpart))
	  return TRUE;
	else 
	  return FALSE;
      }
    else                       /* exact match */
      {
	cp = (char *) index(hostexpr,'.');
	if (!cp)                  /* tack on mit.edu  */
	  {
	    strcat(hostexpr,DEFAULT_DOMAIN);
	  }
	if (!strcasecmp(realhost,hostexpr))
	  return EXACT;
	else
	  return FALSE;
      }
  }
}

int host_authorized(int sock, char *filename)
{
int gotresult = 0,rc,negative = FALSE, positive = FALSE,negacl, length;
char *cp,aclline[LG_BUFSIZ],*hostname,*hostaddr;
FILE *authfile;
struct sockaddr_in	sname;
struct hostent		*host;

/*
 * get hostname & ip address from socket
 */

length = sizeof(sname);
if (getpeername(sock, &sname, &length))
  perror("getpeername");

/*
 * return a pointer to the structure hostent, which contains host
 * information ie. name of host, host address type (AF_INET), length
 * of address	
 */


host = gethostbyaddr(&sname.sin_addr, sizeof(sname.sin_addr), AF_INET);
hostaddr = inet_ntoa(sname.sin_addr);
hostname = host->h_name;
if (debug)
  printf("hostname = <%s>, hostaddr = <%s>",hostname,hostaddr);

  authfile = fopen(filename, "r");
  if (!authfile) {
    perror(filename);
    return 0;
  }
cp = aclline;
while (fgets(cp, BUFSIZ, authfile)) 
  {
    if (*cp == '#')
      continue;  /* comment line */
    cp = (char *) index(cp,'\n');
    if (!cp)
      break;
    *cp = ' ';
    cp++;
  }
fclose(authfile);

if (debug)
  printf("<%s>\n",aclline);

cp = aclline;

while (*cp != '\0') {
  while (isspace(*cp)) cp++;
  if  (*cp == '\0')
    break;
  if (*cp == '-')
    {
      negacl = TRUE;
      cp++;
    }
  else
    negacl = FALSE;

  if (*cp != '#')   /* if not a group */
    {
      if (rc = hostMatches(hostname,hostaddr,cp))
	{
/* if explicit return immediately else wait until all tokens are parsed */
	  if ((negacl) && (rc == EXACT))
	    return FALSE; 
	  else if ((negacl) && (!gotresult))
	    negative = TRUE, gotresult++; 
	  else if (rc == EXACT)
	    return TRUE;
	  else if (!gotresult)
	    positive = TRUE, gotresult++;
	}
    }
  while (!isspace(*cp) && (*cp != '\0')) cp++;
}

if (negative)
  return FALSE;
return positive;
}


/********************************************************************/
/*   PRECEDENCE ETC  ----

     An explicit reference to a particular user or host on an acl line
     has the highest precendence. After that it is strictly LEFT to RIGHT.
     The same hold true for memberships in groups.

*/
/*******************************************************************/
