/***************************************
  $Revision: 1.8 $

  Error reporting (er) er.c - library of functions to uniformly report errors.

  Status: NOT REVUED, TESTED, 

  Design and implementation by: Marek Bukowy

  ******************/ /******************
  Copyright (c) 1999                              RIPE NCC
 
  All Rights Reserved
  
  Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose and without fee is hereby granted,
  provided that the above copyright notice appear in all copies and that
  both that copyright notice and this permission notice appear in
  supporting documentation, and that the name of the author not be
  used in advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.
  
  THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
  AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  ***************************************/

#define ER_IMPL
#include "erroutines.h"

char *er_getsev( int sev, int mode )
{
int i;

  for(i=0; er_level_a[i].sev != 0; i++) {
	if (er_level_a[i].sev == sev)  {
	    break;
	}
  }

  switch( mode & 0x03 ) {
	case ER_M_SEVNONE:	/* no severity indication */
		return "";	/* "" goes to program text, so returning a
				  pointer to it is OK */
	case ER_M_SEVCHAR:	/* one-letter severity indication */
		return er_level_a[i].chr;
	case ER_M_SEVLONG: 	/* long severity indication */
		return er_level_a[i].txt;
  }
  return "";
}

char *er_getfacsym(int faccode)
{
int facidx;

  if( faccode != FAC_NONE  )  {
    for (facidx=0; facidx<FAC_LAST; facidx++) {
      if( er_main_err[facidx].code == faccode ) {
        break;
      }
    }
    return  er_main_err[facidx].name;
  } 
  else	return "";
}

/* TWO CONSTANTS DEFINE THE LENGTH OF STRINGS HERE:
   ER_MSGLEN - max length of the line to be logged
   ER_ERRLEN - max length of the error message
*/
char *er_getmsg_parts(int facwhere, int errcode, int mode, 
			char *buf, char *fmttxt, va_list args)
{
int fac, err, sev;
int facidx, erridx;
char erbuf[ER_ERRLEN], thr_str[10], *ermne;

/* init to "" */
erbuf[0] = 0;
ermne = "";

sev = ( errcode & 0xff000000 );		/* not shifted */
fac = ( errcode & 0x00ff0000 ) >> 16;
err = ( errcode & 0x0000ffff );		/* not shifted */

  for (facidx=0; facidx<FAC_LAST; facidx++) {
    if( er_main_err[facidx].code == fac ) {
      break;
    }
  }

  /* now, if we got to the last one and it's not the right one, 
     the system is not configured properly */
  if(facidx==FAC_LAST) {
     assert( er_main_err[facidx].code == fac );	/* just bail out. */
  }

  /* still alive ? OK, build the message ...*/

  /* ... using facidx/erridx if it's not a DEBUG */
  if( sev != ER_SEV_D ) {
    /* OK, go to the module table. bail out if not initialized */
    assert( er_main_err[facidx].errs != NULL );

    for(erridx=0; er_main_err[facidx].errs[erridx].code != -1; erridx++) {
      if( er_main_err[facidx].errs[erridx].code == errcode ) {
       	/* FOUND! now set the error message format using facidx and erridx */

    	/* build error message with arguments */
    	if( mode & ER_M_TEXTLONG ) {
	  fmttxt = er_main_err[facidx].errs[erridx].text;
    	}
	/* set the mnemonic pointer if necessary */ 
	if( mode & ER_M_MNEMONIC ) {
	  ermne = er_main_err[facidx].errs[erridx].mnem;
        }
	break;
      }
    }
    /*	return ""; */
    /* no, do not return: bail out if the code is not defined */
    assert( er_main_err[facidx].errs[erridx].code != -1 );
  }
  else {
    ermne = "DEBUG";
  } 

  /* build the error message using vsnprintf */  
  vsnprintf(erbuf, ER_ERRLEN, fmttxt, args);
  
  sprintf(thr_str, "%d", pthread_self() );

  /* build the actual log message */
  snprintf(buf, ER_MSGLEN, "%s-%s/%s %s-%s-%s %s",
	   (mode & ER_M_PROGNAME) ? er_progname : "",
	   (mode & ER_M_PIDFULL)  ? er_pid : "",
	   (mode & ER_M_THR_ID )  ? thr_str : "",
	   (mode & ER_M_FACSYMB)  ? er_getfacsym(facwhere) : "",
	   er_getsev(sev, mode),
	   ermne,
	   erbuf
	   );	
  return buf;
}

void ER_setpath(er_path_t *newset)
{
  /* initialise the mutex if not yet initialised */

  if( er_pathlist_mutex_initialised == 0 ) {
    pthread_mutex_init( &er_pathlist_mutex, NULL );
  }
  
  pthread_mutex_lock( &er_pathlist_mutex );
  memcpy( & er_provisional_struct, newset, sizeof(er_path_t));  
  pthread_mutex_unlock( &er_pathlist_mutex );
}

void er_logit(int facwhere, er_mask_t asp, int mode, int errcode, char *msg)
{
  char 	buf[ER_MSGLEN], tmbuf[32];
  struct timeval tval;
  struct tm tmstr;

  if ( mode & ER_M_DATETIME ) {
    gettimeofday(&tval, NULL);
    localtime_r( & tval.tv_sec, & tmstr);

    /*    strcpy(tmbuf, ctime(&tm)+11); */
    sprintf(tmbuf, "%02d:%02d:%02d", 
	    tmstr.tm_hour, tmstr.tm_min, tmstr.tm_sec);
  } else {
    tmbuf[0]=0;
  }

  snprintf(buf, ER_MSGLEN, "%s %s\n", tmbuf, msg );
  /* OK, now dispatch the message to all different paths */
  
  /* MUTEX :

     So, while the most of the work is done composing the message
     according to the format set in the path descriptor (mode),
     the output should also be locked.

     here the mutex associated with the path should be set.
     However, another mutex should be already used to protect other threads 
     from reading the path description while it is modified by the master
     thread. An RW lock can be used for this.
          
     Fortunately, fputs is MT-Safe in Solaris.
  */
 

  /* for now we have at most one :-) */ 
  if(  er_provisional_struct.fdes == NULL ) {
    fputs(buf,stderr);
  }
  else {
    /* someone has really set something! */
    if( errcode >= er_provisional_struct.sev
	|| asp & er_provisional_struct.asp
	)
      {
	fputs(buf, er_provisional_struct.fdes);
      }
  }
  
  
  
}


int ER_is_traced(int facwhere, er_mask_t asp) 
{
int i;

  /* pthread_mutex_lock( &er_pathlist_mutex ); */
  i = er_provisional_struct.asp;
  /* pthread_mutex_unlock( &er_pathlist_mutex ); */

  i &= asp;
  return i;
}

int ER_anybody_wants( int facwhere, int errcode, er_mask_t asp )
{
int i;

  pthread_mutex_lock( &er_pathlist_mutex );
  i = ( errcode >= er_provisional_struct.sev );
  pthread_mutex_unlock( &er_pathlist_mutex );

  return i;
}

int er_get_printmode(er_path_t *pathstruct) 
{
int i;

  pthread_mutex_lock( &er_pathlist_mutex );
  if(  pathstruct->fdes == NULL ) {
    /* default mode */
    i = ER_M_DEFAULT;
  }
  else {
    i = pathstruct->mode;
  }
  pthread_mutex_unlock( &er_pathlist_mutex );

  return i;
}

void ER_perror(int facwhere, int errcode, ...)
{
  char 	erbuf[ER_MSGLEN];
  int     pmode;
  va_list ap;

  if( ER_anybody_wants( facwhere, errcode, 0 ) ) {      /* uses pathlist mutex */

    pmode = er_get_printmode( & er_provisional_struct );/* uses pathlist mutex */

    /* now, this takes most time: */
    va_start(ap, errcode);
    er_getmsg_parts(facwhere, errcode, pmode, erbuf, NULL, ap );
    va_end(ap);
    
    /* actually, here will be a loop once there are more paths possible. */
    er_logit(facwhere, 
	   0,			       /* empty aspect mask for errors */
	   pmode,
	   errcode, 
	   erbuf);				/* empty debug message */
  }
}

void ER_dbg_va( int facwhere, er_mask_t asp, char *txt, ...)
{
  char    erbuf[ER_MSGLEN];
  int pmode;
  va_list   ap;

  if( ER_is_traced( facwhere, asp ) ) {
    
    pmode = er_get_printmode( & er_provisional_struct );
    
    va_start(ap, txt);
    er_getmsg_parts(facwhere, ER_SEV_D, pmode, erbuf, txt, ap );
    va_end(ap);
    
    er_logit(facwhere, asp, pmode, ER_SEV_D, erbuf);
  }
}


/* Set GLOBAL VARIABLES == can be done only by the master thread */
void ER_init(int argc, char **argv)
{
char *er_slash;	

  er_slash = rindex(argv[0],'/'); 			       
  strncpy(er_progname, (er_slash != NULL) ? er_slash+1 : argv[0], 31);
  er_progname[31] = 0;

  snprintf(er_pid, 10, "%d", getpid());

}
