/* angst - util.c
 * by Patroklos Argyroudis <argp@bsd.gr>
 *
 * Miscellaneous functions.
 *
 * $Id: util.c,v 1.6 2001/02/05 03:23:04 argp Exp $
 */ 

#include "angst.h"

void
xprintf(char *msg, ...)
{
 char buffer[SMALBUF];
 va_list args;
   
 va_start(args, msg);
 vsnprintf(buffer, SMALBUF, msg, args);
      
 fprintf(stderr, "%s", buffer);
 va_end(args);
 exit(EXIT_FAILURE);
}

void
init_buf(char x[], int size) 
{
 register int n;

 for(n = 0; n < size; n++)
 {
  x[n] = '\0';
 } 
}

int
daemonize(const char *path)
{
 pid_t pid;

 if((signal(SIGTTOU, SIG_IGN)) == SIG_ERR)
  xprintf("signal error\n");

 if((signal(SIGTTIN, SIG_IGN)) == SIG_ERR)
  xprintf("signal error\n");

 if((signal(SIGTSTP, SIG_IGN)) == SIG_ERR)
  xprintf("signal error\n");

 if((signal(SIGHUP, SIG_IGN)) == SIG_ERR)
  xprintf("signal error\n");

 if((pid = fork()) < 0)
  return(-1);
 else if(pid != 0)
  exit(0);

 if(setsid() == -1)
  xprintf("setsid error\n");

 if(chdir(path) == -1)
  xprintf("chdir error\n");

 umask(0);
 return(0);
}

char *
build_expression(char *arg)
{
 int i = 0, portn = 0;
 int n = 0, slen = 0;
 char *p, *tokens[TOKENS];
 char *last;
 char tstr[BUFSIZE];
 static char filter[BUFSIZE] = "arp or (tcp and (";
 
 for((p = strtok_r(arg, ",", &last)); p; (p = strtok_r(NULL, ",", &last)), i++)
 {
  if(i < (TOKENS - 1))
   tokens[i] = p;
 }
 
 tokens[i] = NULL;
 
 for(n = 0; n < i; n++)
 {
  portn = atoi(tokens[n]);
  
  if(portn < FPORT || portn > LPORT)
   xprintf("error: invalid port number: %d\n", portn);
  else
  {
   snprintf(tstr, (sizeof(tstr) - 1), "dst port %d or ", portn);
   strlcat(filter, tstr, sizeof(filter));
  }
 }
 
 slen = strlen(filter);
 filter[(slen - 4)] = ')';
 filter[(slen - 3)] = ')';
 filter[(slen - 2)] = '\0';
 
 return(filter);
}

#ifdef DEBUG
char *
format_hwaddr(u_char *ea)
{
 static char fea[EASIZE];
   
 sprintf(fea, "%02x:%02x:%02x:%02x:%02x:%02x", ea[0], ea[1], ea[2], ea[3], ea[4], ea[5]);
 return(fea);
}
#endif /* DEBUG */     

/* EOF */
