/*
Copyright (c) 2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/


/**	@file	ualog.c	Logging functions.
*/


/** In the ualog module. */
#define UALOG_C	1



#include "useraudi.h"




#line 52 "ualog.ctr"




/**	Texts used by this module.
*/
static char *kw[] = {
  /*  0 */ "\n",
  /*  1 */ " ",
  /*  2 */ "a",
  /*  3 */ "w",
  /*  4 */ "# %04d-%02d-%02d %02d:%02d:%02d\n",
  /*  5 */ "ERROR: ",
  /*  6 */ "Warning: ",
  /*  7 */ "useraud",
  /*  8 */ "Configuration file \"",
  /*  9 */ "\" ok.",
  /* 10 */ "Failed to read configuration file \"",
  /* 11 */ "\"!",
  /* 12 */ "Syntax error!",
  /* 13 */ "Syntax error (redefined value)!",
  /* 14 */ "Not enough memory (RAM/swap)!",
  /* 15 */ "fork() failed!",
  /* 16 */ "Socket name not configured, using default.",
  /* 17 */ "Log file name not configured, using default.",
  /* 18 */ "Database name not configured, using default.",
  /* 19 */ "PRNG seed file name not configured, using default.",
  /* 20 */ "Backend not supported (libraries missing?)!",
  /* 21 */ "Backend initialization failed!",
  /* 22 */ "Backend failed to process configuration line!",
  /* 23 */ "Backend configuration is incomplete!",
  /* 24 */ "Backend configured without function!",
  /* 25 */ "At least one usable backend is necessary!",
  /* 26 */ "Database cleanup operation started.",
  /* 27 */ "Database cleanup operation finished.",
  /* 28 */ "Inspection of database entries started.",
  /* 29 */ "Inspection of database entries finished.",
  /* 30 */ "Deletion of expired database entries started.",
  /* 31 */ "Deletion of expired database entries finished.",
  /* 32 */ "",
  /* 33 */ " entries deleted.",
  /* 34 */ "User \"",
  /* 35 */ "\" not found!",
  /* 36 */ "Group \"",
  /* 37 */ "Failed to create parent directory for\n\"",
  /* 38 */ "\"!",
  /* 39 */ "Failed to seed PRNG!",
  /* 40 */ "Socket name not configured!",
  /* 41 */ "Database name not configured!",
  /* 42 */ "Socket name too long:\n\"",
  /* 43 */ "\"!",
  /* 44 */ "Failed to open database\n\"",
  /* 45 */ "Failed to create socket!",
  /* 46 */ "Failed to bind local address:\n\"",
  /* 47 */ "Failed to listen for incoming connection request!",
  /* 48 */ "Failed to accept incoming connection request!",
  /* 49 */ "\"",
  /* 50 */ "\" is not a directory!",
  /* 51 */ "Failed to change owner of \"",
  /* 52 */ "Failed to create directory \"",
  /* 53 */ "Unknown configuration key!",
  /* 54 */ "Empty configuration key!",
  /* 55 */ "Missing value in configuration line!",
  /* 56 */ "Entering service mode.",
  /* 57 */ "Leaving  service mode.",
  /* 58 */ "Configuration file was changed, need to re-read.",
  NULL
};


/** Abbreviation. */
typedef char *PCHAR;

/** Number of elements in kw array. */
static size_t sz_kw = sizeof(kw)/sizeof(PCHAR);

/** Flag: Debug mode on (1) or off (0). */
static int debug_mode = 0;


void
ualog_set_debug DK_P1(int,f) {
  debug_mode = f;
}



/**	Send log message to syslog service.
	@param	ll	Log level (DK_LOG_LEVEL_xxx).
	@param	msg	Array of texts.
	@param	n	Number of texts in the array.
*/
static
void
log_to_syslog DK_P3(int,ll, char **,msg, int,n) {
  char	buffer[USERAUD_LINESIZE];
  char 	**ptr;
  int	i;
  int	is_first;
  int	sll;
  size_t	sz;
  ptr = msg; sz = 0;
  
  for(i = 0; i < n; i++) {
    if(*ptr) {
      sz += strlen(*ptr);
    }
    ptr++;
  }
  if(sz < sizeof(buffer)) {
    ptr = msg; is_first = 1;
    for(i = 0; i < n; i++) {
      if(*ptr) {
        if(is_first) {
	  strcpy(buffer, *ptr);
	} else {
	  strcat(buffer, *ptr);
	}
	is_first = 0;
	ptr++;
      }
    }
    sll = LOG_INFO;
    if(ll <= DK_LOG_LEVEL_WARNING) {
      sll = LOG_WARNING;
      if(ll <= DK_LOG_LEVEL_ERROR) {
        sll = LOG_ERR;
      }
    }
    openlog(kw[7], LOG_PID, LOG_AUTH);
    syslog(sll, "%s", buffer);
    closelog();
  } 
}



void
ualog DK_P4(UAC *,u, int,ll, char **,msg, int,n) {
  static int is_first = 1;
  static time_t	time_file = (time_t)0;
  static time_t time_stdout = (time_t)0;
  time_t time_current;
  struct tm *tm;
  int i;
  char **ptr;
  FILE *fipo;
  int must_print_time = 0;
  
  if((u) && (msg) && (n)) {
    if(ll <= u->ll_file) {
      time(&time_current);
      if(time_current > time_file) {
        must_print_time = 1;
      }
      if(u->logname) {
        fipo = dksf_fopen(u->logname, kw[ is_first ? 3 : 2 ]);
	is_first = 0;
	if(fipo) {
	  if(must_print_time) {
	    tm = localtime(&time_current);
	    if(tm) {
	      fprintf(
	        fipo, kw[4], (1900 + tm->tm_year), (tm->tm_mon + 1),
	        tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec
	      );
	      time_file = time_current;
	    }
	  }
	  if(ll <= DK_LOG_LEVEL_ERROR) {
	    fputs(kw[5], fipo);
	  } else {
	    if(ll == DK_LOG_LEVEL_WARNING) {
	      fputs(kw[6], fipo);
	    }
	  }
	  ptr = msg;
	  for(i = 0; i < n; i++) {
	    if(*ptr) {
	      fputs(*ptr, fipo);
	    }
	    ptr++;
	  }
	  fputs(kw[0], fipo);
	  fclose(fipo);
	}
      }
    }
    if(ll <= u->ll_syslog) {
      log_to_syslog(ll, msg, n);
    }
  } else {
    if((msg) && (n > 0)) {
      if(ll <= DK_LOG_LEVEL_ERROR) {
        log_to_syslog(ll, msg, n);
      }
    }
  }
  if(debug_mode) {
    time(&time_current);
    if(time_current > time_stdout) {
      tm = localtime(&time_current);
      if(tm) {
        fprintf(
	  stdout, kw[4], (1900 + tm->tm_year), (tm->tm_mon + 1),
	  tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec
	);
	time_stdout = time_current;
      }
    }
    if(ll <= DK_LOG_LEVEL_ERROR) {
      fputs(kw[5], stdout);
    } else {
      if(ll == DK_LOG_LEVEL_WARNING) {
        fputs(kw[6], stdout);
      }
    }
    ptr = msg;
    for(i = 0; i < n; i++) {
      if(*ptr) {
        fputs(*ptr, stdout);
      }
      ptr++;
    }
    fputs(kw[0], stdout);
  } 
}



void
ualog_1 DK_P3(UAC *,u, int,ll, size_t,i) {
  char *msg[2];
  
  if(i < sz_kw) {
    msg[0] = kw[i]; msg[1] = NULL;
    ualog(u, ll, msg, 1);
  } 
}



void
ualog_3 DK_P5(UAC *,u, int,ll, size_t,i1, size_t,i2, char *,s) {
  char *msg[4];
  
  if((i1 < sz_kw) && (i2 < sz_kw)) {
    msg[0] = kw[i1];
    msg[1] = s;
    msg[2] = kw[i2];
    msg[3] = NULL;
    ualog(u,ll,msg,3);
  } 
}



void
ualog_file_lineno_1 DK_P5(UAC *,u,int,ll,char *,fn,unsigned long,l,size_t,i)
{
  char *msg[5];
  char buffer[64];
  
  if(i < sz_kw) {
    sprintf(buffer, ":%lu: ", l);
    msg[0] = fn;
    msg[1] = buffer;
    msg[2] = kw[i];
    ualog(u,ll,msg,3);
  } 
}



