/* user context stuff */ 

#include "server.h"
#include "sfrp.h"
#include <strings.h>
#include <syslog.h>
#include <sys/types.h>
#include <hesiod.h>

UserContext* context_list[MAXCONNECTIONS];

uc_init()
{
  bzero( context_list, sizeof(UserContext*)*MAXCONNECTIONS);
}

UserContext *uc_make()
{
  UserContext *uc;
  int i;

  for(i = 0; i < MAXCONNECTIONS; i++) 
    if(!context_list[i]) break;

  if(i == MAXCONNECTIONS) {
    syslog(LOG_ALERT, "Too many connections");
    return 0; /* no more connections allowed */
  }
  
  uc = (UserContext*)malloc(sizeof(UserContext));
  bzero(uc, sizeof(UserContext));
  context_list[i] = uc;
  uc->list_index = i;
  return uc;
}

void uc_free(uc)
     UserContext* uc;
{
  context_list[uc->list_index] = 0;
  free(uc);
}

uc_rehash_fd(fds)
     fd_set *fds;
{
  int i;
  for(i = 0 ; i < MAXCONNECTIONS; i++) {
    if(context_list[i]) {
      FD_SET(context_list[i]->sock, fds);
    }
  }
}

UserContext *fd_to_uc(fds)
     fd_set *fds;
{
  int i;
  for(i = 0; i < MAXCONNECTIONS; i++) {
    if(context_list[i]) {
      if(FD_ISSET(context_list[i]->sock, fds)) 
	return context_list[i];
    }
  }
  
  syslog(LOG_ALERT, "Coudln't find the uc in fd_to_uc");
  return 0;
}


initialize_user(uc)
     UserContext *uc;
{
  char *ptr;
  char **hes;

  if(check_authentication(uc->sock, uc->name, uc->instance, uc->realm)) {
    sfrp_output(uc, "Authentication failed.  Run kinit and try again.\n", ERROUT, 0);
    close_connection(uc);
    return;
  }


  /* get uid */
  hes = hes_resolve(uc->name, "PASSWD");
  if(!hes) {
    sfrp_output(uc, "You don't have a hesiod passwd entry. talk to olc!\n", ERROUT, 0);
    syslog(LOG_ALERT, "no passwd entry for user %s", uc->name);
    close_connection(uc);
    return;
  }
  
  ptr = index(*hes, ':');
  ptr = index(ptr + 1, ':');
  uc->uid = atoi(ptr+1);
  syslog(LOG_INFO, "user's uid = %d", uc->uid);


}
