/* event handling system, general library
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <glib.h>

#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/un.h>
#include <netinet/in.h>   
#include <arpa/inet.h>
#include <unistd.h>

#include "g_snmp.h"

#include "dae.h"

char version[] = "$Id: dae.c,v 1.18 1999/09/29 15:10:48 remlali Exp $"; /*usefull to 'strings' the binary*/

struct sockaddr_in ddserver;

extern glb_enviroment enviroment;
extern aclist *trapfilter;

extern void debug();

char *load_file(char *filename)
{
char *text;
FILE *fp;
struct stat statb;

	if(!filename || !*filename){
		fprintf(stderr,"Empty filename");
		return 0;
	}

	if (stat(filename, &statb) == -1 || 
	    (statb.st_mode & S_IFMT) != S_IFREG || 
	    !(fp = fopen(filename, "r")))
	  {
	    if((statb.st_mode & S_IFMT) == S_IFREG) 
	      perror(filename);
	    else 
	      fprintf(stderr,"%s: not a regular file\n",filename);
	    return 0;
	}
	if (!( statb.st_size )) 
	  { 
	    text = (char *) NULL;
	    fclose(fp); 
	    return NULL;
	  }
	if (!(text = (char *) g_malloc((unsigned)(statb.st_size+1))))
	  {
	    fprintf(stderr, "Can't allocate enough memory\n");
	    fclose(fp); 
	    return 0;
	  }
	if (!fread(text, sizeof(char), statb.st_size+1, fp))
	  {
	    fprintf(stderr, "Couldn't read file\n");
	    g_free(text);
	    fclose(fp);
	    return 0;
	  }
	text[statb.st_size] = 0;
	fclose(fp);
	return text;
}

char *wordcpy(char *dst, char *src, int w){ /*copy space separated word 'w' to 'dst' from 'src'*/
int i=0,j=0;

  w--;
  *dst = '\0';
  while(1){
    if(!w) break;
      if((*(src+i) == '\0' || *(src+i) == '\n')) return 0; /*leave dst empty*/
      if(*(src+i) == '\"'){
        i++;
        while(*(src+i) != '\"' && !(*(src+i) == '\0' || *(src+i) == '\n')) i++;
        if(!(*(src+i) == '\0' || *(src+i) == '\n')) i++;
        continue;
      }
      if(*(src+i) == ' '){w--;i++; continue;}
      i++;
    }
    if(*(src+i) == '\"'){
    i++;
    while( !(*(src+i) == '\0' || *(src+i) == '\n') && !(*(src+i) == '\"') ){ *(dst+j) = *(src+i);i++;j++;}   /*move each character*/
    *(dst+j) = '\0';
    return dst;
  }
  while( !(*(src+i) == '\0' || *(src+i) == '\n') && !(*(src+i) == ' ') ){ *(dst+j) = *(src+i);i++;j++;}   /*move each character*/
  *(dst+j) = '\0';
  return dst;
}

char *wordcpyt(char *dst, char *src, char *tmp, int w){ /*copy space separated word 'w' to 'dst' from 'src'*/
int i=0,j=0;

  w--;
  *dst = 0;
  while(1){
    if(!w) break;
    if((*(src+i) == '\0' || *(src+i) == '\n')) return 0; /*leave dst empty*/
    if(*(src+i) == *tmp){w--;i++; continue;}
    i++;
  }
  while( !(*(src+i) == '\0' || *(src+i) == '\n') && !(*(src+i) == *tmp) ){ *(dst+j) = *(src+i);i++;j++;}   /*move each character*/
  *(dst+j) = '\0';
  return dst;
}

void restrap(char *line) 
{
  if(!(strncmp(line,"\"",1)))
  {
    if (!(strncmp(line+(strlen(line)-1),"\"",1)))
    {
      strncpy(line,line+1,strlen(line)-2);
      strncpy(line+strlen(line)-2,"\0",1);
    }	
  }
}

int var_interpret(gchar *dst, gchar *src, int max, trapslot *trap){ /*variable substitution*/
int i,j=0;


  dst[0] = 0;
  for(i=0;;i++, j++){
    if(*(src+i) == '\0') break;
    if(!strncmp(src+i,"$IP",3)){				/*variable $IP is detected*/
      if(!strlen(trap->IP)){
        *(dst+j) = *(src+i);					/*set current dst+j and continue, else for's j++ would leave this dst+j unset*/
        continue;
      }
      if((strlen(trap->IP)+j) > max){			/*destination buffer overflowed*/
        dst[0] = 0;
        return 0;
      }
      strcpy(dst+j, trap->IP);
      j += strlen(trap->IP);
      i += 3;
      *(dst+j) = *(src+i);
      continue;
    }
    *(dst+j) = *(src+i);
  }
  *(dst+j) = 0;
  return strlen(dst);
}

/*
Trap lookup functions, uses conf/trap.conf as database
*/

int trap_lookup(trapslot *trap){
int i=0;
  while(1){
    if(!strlen(enviroment.traptab[i].oid)){
      return 1;               /*not found*/
    }
/*DEBUG*fprintf(stdout,"CMP(%s,%s)\n",enviroment.traptab[i].oid, trap->oid);*/
    if(!strcmp(enviroment.traptab[i].oid,trap->oid) && enviroment.traptab[i].g == trap->g && enviroment.traptab[i].s == trap->s){
      strcpy(trap->script,enviroment.traptab[i].script);
      strcpy(trap->name,enviroment.traptab[i].name);
      strcpy(trap->popup,enviroment.traptab[i].popup);
      trap->eid = enviroment.traptab[i].eid;
      trap->flag = enviroment.traptab[i].flag;
      trap->severity = enviroment.traptab[i].severity;
      return 0;
    }
    i++;
  }
}
/* log functions, to have a logging facility*/

void logstr(FILE *fp, char *text){
time_t i = time(0);
char *date = ctime(&i);
  date[strlen(date)-1] = 0;       /*remove linefeed*/
  fprintf(fp,"%s, %s",date,text);
  fflush(fp);
}

FILE *logopen(char *text){
char buf[200];

  strcpy(buf,enviroment.base);
  strcat(buf,"/log/");
  strcat(buf,text);
  return fopen(buf,"a");
}

/*Access control functions
 *  test_acl	This will take oid/g/s and check to the loaded access list wheter to drop or display trap
 *  load_acl	This loads an access list from (char *filename)
*/

int test_acl(aclist acl, aclist *filter){	/* test if *acl is permitted by the access list loaded by load_acl()*/
int l = 0;
int lm=0;				/*longest match*/
int tlm=0;				/*tested oid longest match*/

int lm10=0;				/*longest match command 10 ( deny oid )*/
int lm13=0;				/*longest match command 13 ( deny oid+g+s )*/
int lm20=0;				/*longest match command 20 ( permit oid )*/
int lm23=0;				/*longest match command 23 ( deny oid+g+s )*/

	if(!filter) return 1;
	while(1){
		if(!filter[l].action) break;					/*no more acl lines to test*/
		if(!strcmp(filter[l].oid,"NULL")) continue;				/*empty slot*/
		lm = strlen(filter[l].oid);						/*get longest match length of current oid in acl file*/
		tlm = strlen(acl.oid);							/*get longest match length of oid beeing tested*/

		if(filter[l].action == 10){ 						/*denial oid  command*/
			if(!strcmp(filter[l].oid,"*")) lm10 = 1;			/*set longest match to smallest possible, because everything else that matches should have a higher match value*/
			if(!strncmp(filter[l].oid, acl.oid, lm))  lm10 = lm;		/*denial longest match found*/
		}	
		else if(filter[l].action == 13){					/*deny oid+g+s command*/
			if(!strcmp(filter[l].oid,"*")) lm13 = 1;			/*set longest match to smallest possible, because everything else that matches should have a higher match value*/
			if(!strncmp(filter[l].oid, acl.oid, lm) && filter[l].g == acl.g && filter[l].s == acl.s) lm13 = lm;	/*permitted longest match found*/
		}
		else if(filter[l].action == 20){					/*permit oid command*/
			if(!strncmp(filter[l].oid, acl.oid, lm))  lm20 = lm;		/*permitted longest match found*/
		}
		else if(filter[l].action == 23){					/*permit oid+g+s command*/
			if(!strcmp(filter[l].oid,"*")) lm23 = 1;			/*set longest match to smallest possible, because everything else that matches should have a higher match value*/
			if(!strncmp(filter[l].oid, acl.oid, lm) && filter[l].g == acl.g && filter[l].s == acl.s)  lm23 = lm;	/*permitted longest match found*/
		}
		l++;
	}
  if(lm23 == 0 && lm13 == 0) return 1;				/*no acl at all was found*/
  if(lm13 >= lm23) return 0;					/*deny oid+g+s was found, actual this is boolean, if they are equal aclist is wrong*/
  if(lm23) return 1;						/*permit oid+g+s was found, so deny oid+g+s (lm23) must be zero*/
  if(lm13 >= lm23) return 0;					/*deny oid is greater or equal than permit oid */
  return 1;							/*else trap is permited*/
}

aclist *load_acl(char *filename)
{				/*load event display access list*/
  char line[200],foo[200];
  FILE *fp;
  int i=0;
  aclist *acl;
  
  if(!(fp = fopen(filename, "r"))) 
    return 0;
  while(fgets(line,200,fp)) 
    i++;
  i++; i++; i++;  			/*this slot is the last empty + 2 for safety, dumb :)*/
  
  if (!(acl = (aclist *) g_malloc((unsigned)(i*(sizeof(aclist))))))
    {
      fprintf (stderr, "Can't alloc enough space for %s", filename);
      fclose(fp);
      return 0;
    }
  
  i=0;
  fseek(fp, 0, SEEK_SET);
  while(fgets(line,200,fp))
    {	/*parse corr.conf*/
      if(line[0] == '#') continue;
      wordcpy(foo,line,1);
      if(!strcmp(foo,"deny"))
	{
	  wordcpy(foo,line,2);
	  if(!strcmp(foo,"oid"))
	    {
	      acl[i].action = 10;
	      wordcpy(foo,line,3);
	      strcpy(acl[i].oid,foo);
	    }
	  else if(!strcmp(foo,"oid+g+s"))
	    {
	      acl[i].action = 13;
	      wordcpy(foo,line,3);
	      strcpy(acl[i].oid,foo);
	      wordcpy(foo,line,4);
	      acl[i].g = atoi(foo);
	      wordcpy(foo,line,5);
	      acl[i].s = atoi(foo);
	    }
	}
      else if(!strcmp(foo,"permit"))
	{
	  wordcpy(foo,line,2);
	  if(!strcmp(foo,"oid"))
	    {
	      acl[i].action = 20;
	      wordcpy(foo,line,3);
	      strcpy(acl[i].oid,foo);
	    }
	  else if(!strcmp(foo,"oid+g+s"))
	    {
	      acl[i].action = 23;
	      wordcpy(foo,line,3);
	      strcpy(acl[i].oid,foo);
	      wordcpy(foo,line,4);
	      acl[i].g = atoi(foo);
	      wordcpy(foo,line,5);
	      acl[i].s = atoi(foo);
	    }
	}
      i++;
    }
  strcpy(acl[i].oid,"");
  acl[i].action = 0;
  fclose(fp);
  return acl;
}
/**
 * save_acl: 
 * @filename: The filename that will hold the trapfilter acl.
 * Save the current trapfilter acl. Note: This will overwrite the @filename.
 *
 **/
int 
save_acl(char *filename)
{			
  gint     l=0;
  FILE    *fp;
  gchar    line[200];
  gint     line_size;

  fp = fopen(filename,"w");
  line_size = sizeof (line);
  while(1)
    {
      if(!trapfilter[l].action) 
	break;
      if(!strcmp(trapfilter[l].oid,"NULL")) 
	continue;
      switch(trapfilter[l].action)
	{
	case 10:
	  snprintf(line, line_size, "deny oid %s\n",trapfilter[l].oid);
	  break;
	case 13:
	  snprintf(line, line_size, "deny oid+g+s %s %d %d\n", 
		  trapfilter[l].oid, trapfilter[l].g, trapfilter[l].s);
	  break;
	case 20:
	  snprintf(line, line_size, "permit oid %s\n", trapfilter[l].oid);
	  break;
	case 23:
	  snprintf(line, line_size, "permit oid+g+s %s %d %d\n",
		   trapfilter[l].oid, trapfilter[l].g, trapfilter[l].s);
	  break;
	default:			/*unsupported action*/
	  fprintf(stderr,"APP_ERR: unsupported action in save_acl()\n");
	  continue;
	}
      fputs(line,fp);
      l++;
    }
  fclose(fp);
  return 0;
}
int 
acl_add_filter(aclist acl, char *filename)
{
  char   line[200];
  FILE   *fp;
  gint   line_size;
  
  if(!filename) 
    return 1;
  fp = fopen(filename,"a");
  line_size = sizeof (line);
  switch(acl.action)
    {
    case 10:
      snprintf(line, line_size,"deny oid %s\n",acl.oid);
      break;
    case 13:
      snprintf(line, line_size,"deny oid+g+s %s %d %d\n",acl.oid,acl.g,acl.s);
      break;
    case 20:
      snprintf(line, line_size, "permit oid %s\n",acl.oid);
      break;
    case 23:
      snprintf(line, line_size,"permit oid+g+s %s %d %d\n", acl.oid, 
	       acl.g,acl.s);
      break;
    default:                        /*unsupported action*/
      fprintf(stderr, 
	      "APP_ERR: unsupported action in acl_add_filter()\n");
      return 1;
    }
  fputs(line,fp);
  fclose(fp);
  return 0;
}
/****************************************************************************
 * SNMP Functions
 ***************************************************************************/
/*
 * converts oid to a text:
 * .1.3.6.1   -->   .internet.dod.org... 
 */
int 
oid2text(char *text, char *oidtext)
{
  gulong  name[SNMP_SIZE_OBJECTID];
  guint   name_len;
  
  name_len = SNMP_SIZE_OBJECTID;
  text[0];
  oidtext[0];
/*
  if (!read_objid(oidtext, name, &name_len))
    {
      return 1; 
    }
  sprint_objid(text, 200, name, name_len);
*/
  return 0;
}
/****************************************************************************
 * Inter-daemon data transfer functions
 ***************************************************************************/

int createsocket(const char *filename, int flag){
struct sockaddr_un name;
int sock;
size_t size;

  sock = socket(PF_UNIX, SOCK_DGRAM, 0);
  if(sock < 0){ 
    perror("socket()");
    return 0;
  }
  name.sun_family = AF_UNIX;
  strcpy(name.sun_path, filename);
  size = (offsetof (struct sockaddr_un, sun_path) + strlen(name.sun_path) + 1);
  if(bind(sock,(struct sockaddr *) &name, size) < 0){ 
    perror("bind()");
    return 0;
  }
  if(flag) fcntl(sock, F_SETFL, O_NONBLOCK);
  return sock;	
}

int sendsocket(int sock, char *dst, char *text){
struct sockaddr_un name;
size_t size;
int nbytes;

  name.sun_family = AF_UNIX;
  strcpy(name.sun_path, dst);
  size = strlen(name.sun_path) + sizeof( name.sun_family);
  nbytes = sendto(sock, text, strlen(text) + 1, 0, (struct sockaddr *) &name, size);
  return 0;
}
int senddsocket(int sock, char *dst, char *data, size_t len){
struct sockaddr_un name;
size_t size;
int nbytes;

  name.sun_family = AF_UNIX;
  strcpy(name.sun_path, dst);
  size = strlen(name.sun_path) + sizeof( name.sun_family);
  nbytes = sendto(sock, data, len + 1, 0, (struct sockaddr *) &name, size);
  return 0;
}

int trap_decode(char *pipestring, trapslot *trap){
int pz = 5, k, traplen, ta;
struct in_addr ip;
int soi;

  memset(trap, 0, sizeof(trapslot));

  if((pipestring[5] != '\123')) return 0;
  pz += sizeof(char);

  memcpy(&(trap->severity), &(pipestring[pz]),sizeof(int));          /*severity*/
  pz +=sizeof(int);

  memcpy(&(trap->timestamp), &(pipestring[pz]),sizeof(int));          /*trap timestamp from block*/
  pz += sizeof(int);

  memcpy(&ip,&(pipestring[pz]),sizeof(struct in_addr));
  strcpy(trap->IP,inet_ntoa(ip));
  pz += sizeof(int);

  memcpy(&(trap->g),&(pipestring[pz]),sizeof(int));
  pz += sizeof(int);
  memcpy(&(trap->s),&(pipestring[pz]),sizeof(int));
  pz += sizeof(int);

  memcpy(&ta,&(pipestring[pz]),sizeof(int));
  pz += sizeof(int);
  if(ta>130) return 0; 				/*buffer overflow*/
  memcpy(trap->oid,&(pipestring[pz]),ta);
  trap->oid[ta] = 0;
  pz += ta;
  traplen = ta;

  for(k=0;3>k;k++){					/*process trap arguments, only 4 are supported*/
    if(pipestring[pz] == '\xff'){ 			/*end of block*/
      traplen += sizeof(char); 
      break;
    }
    memcpy(&ta,&(pipestring[pz]),sizeof(int));    	/* var OID len */
    pz += sizeof(int);
    if(ta > 130) ta = 130;				/*OID shouldn't exceed 128bytes, better be paranoid than core dump*/
    memcpy(trap->argoid[k],&(pipestring[pz]),ta);    	/*get oid string*/
    trap->argoid[k][ta] = 0;
    pz += ta;
    traplen += ta + sizeof(int) + sizeof(char) + sizeof(char); /*OID + OID_len + EndOfBlock + value type */
    switch(pipestring[pz]){                    
    case 1:                    				/*32bit unsigned counter*/
      pz += sizeof(char);
      memcpy(&ta,&(pipestring[pz]),sizeof(int));	/* var value type len*/
      pz += sizeof(int);
      memcpy(&soi,&(pipestring[pz]),ta);      		/* var value */
      snprintf(trap->argdat[k],200,"%u",soi);
      pz += ta;
      traplen += sizeof(int) + ta;
      break;
    case 2:                                         	/* ASCIIZ */
      pz += sizeof(char);
      memcpy(&ta,&(pipestring[pz]),sizeof(int));      	/* var value type len */
      pz += sizeof(int);
      if(ta > 200) ta = 200;				/*exceeded buffer limit*/
      memcpy(trap->argdat[k],&(pipestring[pz]),ta);    	/* var value */
      trap->argdat[k][ta] = 0;
      pz += ta;
      traplen += sizeof(int) + ta;
      break;
    default:                				/* unsupported trap type */
      fprintf(stderr,"Unsupported trap type (oid: %s)\n",trap->argoid[k]);
      trap->argoid[k][0] = 0;				/*reset OID that contains a nonsupported data*/
      break;
    }
  }
  traplen += 10; 					/*safety*/
  return ++traplen;
}

/*
 * global functions
 */

char *make_pathname(char *base, char *name){
char *ptr;
int s;

	s = strlen(enviroment.base);
	s += strlen(name);
	if(!(ptr = (char *) malloc((unsigned)s+1))){
		fprintf(stderr,"Cant alloc memory for holding a filename\n");
	}
	ptr[0] = 0;
	strcpy(ptr ,enviroment.base);
	strcat(ptr,name);
	return ptr;
}

int load_enviroment(){
char line[200],entity[200],value[200];
char *env;
FILE *fp;

	env = getenv("DAE_BASE");
	if(!env) {
		fprintf(stderr,"Error: enviroment variable: DAE_BASE is not set.\n");
		exit(1); /*critical*/
	}

	enviroment.trapd_unknown_traps = 1;
	enviroment.trapd_log_unknown_traps = 1;
	enviroment.corrd_log = 1;
	enviroment.evdpysrvd_log = 1;
	enviroment.evdpysrvd_poll = 300;		/*default timeout/poll of event displays (in seconds) */
	enviroment.gxevents_max_traps = 100;		/*default number of traps gxevents will display before removing*/
	enviroment.gxevents_lookup = 0;			/*default don't lookup hostname from IP*/
        enviroment.popup_date = 0;			/*default to negative*/

	strcpy(line,env);
	strcat(line,"/conf/nb.conf");

	if(!(fp = fopen(line, "r"))) return 1;
	while(fgets(line,200,fp)){
		if(line[0] == '#') continue;
		wordcpy(entity,line,1);		/* first check if it is a define statement */
		if(!strcmp(entity,"CORRD_LOG")) enviroment.corrd_log = 1;
		else if(!strcmp(entity,"TRAP_UNKNOWN_TRAPS")) enviroment.trapd_unknown_traps = 1;
		else if(!strcmp(entity,"TRAP_LOG_UNKNOWN_TRAPS")) enviroment.trapd_log_unknown_traps = 1;
		else if(!strcmp(entity,"EVDPYSRVD_LOG")) enviroment.evdpysrvd_log = 1;
		else if(!strcmp(entity,"POPUP_DATE"))  enviroment.popup_date = 1;
		else if(!strcmp(entity,"GXEVENTS_LOOKUP"))  enviroment.gxevents_lookup = 1;
		else {
			wordcpyt(entity,line,"=",1);
			wordcpyt(value,line,"=",2);
			restrap(value);
			if(!strcmp("DATABASE_HOST",entity)) strcpy(enviroment.host, value);
			else if(!strcmp("DATABASE_NAME",entity)) strcpy(enviroment.name, value);
			else if(!strcmp("DATABASE_USER",entity)) strcpy(enviroment.user, value);
			else if(!strcmp("DATABASE_PASS",entity)) strcpy(enviroment.passwd, value);
			else if(!strcmp("BASE",entity))          strcpy(enviroment.base, value);
			else if(!strcmp("EVDPYSRVD_POLL",entity)) enviroment.evdpysrvd_poll = atoi(value);
			else if(!strcmp("TRAP_DEFAULT_SEVERITY",entity)) enviroment.severity = atoi(value);
			else if(!strcmp("POPUP_EXEC",entity))  enviroment.popup_exec = strdup(value);
			else if(!strcmp("GXEVENTS_MAX_TRAPS",entity))  enviroment.gxevents_max_traps = atoi(value);
		}
	}

	enviroment.actiond = make_pathname(enviroment.base, "/sockets/actiond");
	enviroment.corrd = make_pathname(enviroment.base, "/sockets/corrd");
	enviroment.crond = make_pathname(enviroment.base, "/sockets/crond");
	enviroment.evdpysrvd = make_pathname(enviroment.base, "/sockets/evdpysrvd");
	enviroment.gxdhd = make_pathname(enviroment.base, "/sockets/gxdhd");
	enviroment.pdud = make_pathname(enviroment.base, "/sockets/pdud");
	enviroment.trapd = make_pathname(enviroment.base, "/sockets/trapd");

	fclose(fp);
	return 0;
}

int load_trapconf(){
char line[200],foo[200];
char *filename = "./conf/trap.conf";
FILE *fp;
int i=0,f;

	strcpy(line,enviroment.base);
	strcat(line,"/conf/trap.conf");
	if(!(fp = fopen(line,"r"))) return 1;
	while(fgets(line,200,fp)) i++;
	i++; i++; i++;	/*this slot is the last empty + 2 for safety*/

	if (!(enviroment.traptab = (trap_slot *) malloc((unsigned)(i*(sizeof(trap_slot)))))){
		fprintf (stderr, "Can't alloc enough space for %s", filename);
		fclose (fp);
		return 1;
	}
	fseek(fp,0,SEEK_SET);
	i=0;
	while(fgets(line,200,fp)){
		if(line[0] == '#') continue;		/*skip remarks in trap.conf*/

		wordcpy(foo,line,1);			/*OID*/
		strcpy(enviroment.traptab[i].oid, foo);

		wordcpy(foo,line,2);			/*generic*/
		f = atoi(foo);
		enviroment.traptab[i].g = f;

		wordcpy(foo,line,3);			/*specific*/
		f = atoi(foo);
		enviroment.traptab[i].s = f;

		wordcpy(foo,line,4);			/* name (name found in mib)*/
		strcpy(enviroment.traptab[i].name, foo);

		wordcpy(foo,line,5);			/*Script*/
		strcpy(enviroment.traptab[i].script, foo);

		wordcpy(foo,line,6);			/*Popup*/
		strcpy(enviroment.traptab[i].popup, foo);

		wordcpy(foo,line,7);			/*EID*/
		f = atoi(foo);
		enviroment.traptab[i].eid = f;

		wordcpy(foo,line,8);			/*Flags*/
		f = atoi(foo);
		enviroment.traptab[i].flag = f;

		wordcpy(foo,line,9);			/*Severity*/
		f = atoi(foo);
		enviroment.traptab[i].severity = f;

		i++;
	}
	strcpy(enviroment.traptab[i].oid,"");		/*terminate*/
	fclose(fp);
	return 0;
}
corr_slot *load_corrconf(){
char line[200],foo[200];
char *filename = "./conf/corr.conf";
FILE *fp;
int i=0;
corr_slot *corret, *cortmp;

	strcpy(line,enviroment.base);
	strcat(line,"/conf/corr.conf");
	if(!(fp = fopen(line,"r"))) return 1;
	while(fgets(line,200,fp)) i++;
	i++; i++; i++;

	if (!(corret = (corr_slot *) malloc((unsigned)(i*(sizeof(corr_slot)))))){
		fprintf (stderr, "Can't alloc enough space for %s", filename);
		fclose (fp);
		return 1;
	}
	fseek(fp,0,SEEK_SET);
	cortmp = corret;
	while(fgets(line,200,fp)){
		if(line[0] == '#') continue;

		wordcpy(foo,line,1);	/*IP-mask*/
		strcpy(corret->mask, foo);

		wordcpy(foo,line,2);	/*corr file*/
		strcpy(corret->file, foo);


		corret++;
	}
	corret->file[0] = 0;
	fclose(fp);
	return cortmp;
}

/*
* Database daemon client
*/

int dd_connect(char *IP){
int sock;

  sock = socket(PF_INET, SOCK_STREAM,0);
  if(sock < 0) return -1;
  ddserver.sin_family = AF_INET;
  ddserver.sin_port = 4000;
  ddserver.sin_addr.s_addr = inet_addr(IP);
  fprintf(stderr,"1");
  if(0 > connect(sock, (struct sockaddr *) &ddserver, sizeof(ddserver))) return -1;
  fprintf(stderr,"2");
  return sock;
}

void dd_disconnect(int sock){
  close(sock);
}

char *dd_read(int sock, int *size){
char *bulk,*blk1=0;
int nbytes;
int s = 1001;
int n=0;

  if (!(bulk = (char *) malloc ((unsigned char)(1000)))) return -1;
  fprintf(stderr,"dae:read\n");
  *size = read(sock, bulk, 1000);
  fprintf(stderr,"dae:done-read\n");
  if(*size == -1) return -1;
  return bulk;

readagain:
        if (!(bulk = (char *) malloc ((unsigned char)(s)))) return -1;
        if(blk1){
                memcpy(bulk,blk1,n);
                free(blk1);	
        }
        blk1 = bulk;	
        nbytes = read(sock, bulk+n, 1000);
        n += nbytes;
        switch(nbytes){
                case -1:        /*error*/
                        free(bulk);
			return -1;
                case 0:         /*no more to read*/
                        return bulk;
                default:        /*more to read*/
                        s += 1001;
                        goto readagain;
                        break;
        }
}

int dd_write(int sock, int datalen, char *data){
int nbytes;

  nbytes = write(sock, data, datalen + 1);
  if(nbytes < 0) return -1;
  return nbytes;
}
