/*
             Common Public License Version 0.5

             THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF
             THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE,
             REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
             RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

             1. DEFINITIONS

             "Contribution" means: 
                   a) in the case of the initial Contributor, the
                   initial code and documentation distributed under
                   this Agreement, and 

                   b) in the case of each subsequent Contributor:
                   i) changes to the Program, and
                   ii) additions to the Program;

                   where such changes and/or additions to the Program
                   originate from and are distributed by that
                   particular Contributor. A Contribution 'originates'
                   from a Contributor if it was added to the Program
                   by such Contributor itself or anyone acting on such
                   Contributor's behalf. Contributions do not include
                   additions to the Program which: (i) are separate
                   modules of software distributed in conjunction with
                   the Program under their own license agreement, and
                   (ii) are not derivative works of the Program.


             "Contributor" means any person or entity that distributes
             the Program.

             "Licensed Patents " mean patent claims licensable by a
             Contributor which are necessarily infringed by the use or
             sale of its Contribution alone or when combined with the
             Program. 

             "Program" means the Contributions distributed in
             accordance with this Agreement.

             "Recipient" means anyone who receives the Program under
             this Agreement, including all Contributors.

             2. GRANT OF RIGHTS

                   a) Subject to the terms of this Agreement, each
                   Contributor hereby grants Recipient a
                   non-exclusive, worldwide, royalty-free copyright
                   license to reproduce, prepare derivative works of,
                   publicly display, publicly perform, distribute and
                   sublicense the Contribution of such Contributor, if
                   any, and such derivative works, in source code and
                   object code form.

                   b) Subject to the terms of this Agreement, each
                   Contributor hereby grants Recipient a
                   non-exclusive, worldwide, royalty-free patent
                   license under Licensed Patents to make, use, sell,
                   offer to sell, import and otherwise transfer the
                   Contribution of such Contributor, if any, in source
                   code and object code form. This patent license
                   shall apply to the combination of the Contribution
                   and the Program if, at the time the Contribution is
                   added by the Contributor, such addition of the
                   Contribution causes such combination to be covered
                   by the Licensed Patents. The patent license shall
                   not apply to any other combinations which include
                   the Contribution. No hardware per se is licensed
                   hereunder.

                   c) Recipient understands that although each
                   Contributor grants the licenses to its
                   Contributions set forth herein, no assurances are
                   provided by any Contributor that the Program does
                   not infringe the patent or other intellectual
                   property rights of any other entity. Each
                   Contributor disclaims any liability to Recipient
                   for claims brought by any other entity based on
                   infringement of intellectual property rights or
                   otherwise. As a condition to exercising the rights
                   and licenses granted hereunder, each Recipient
                   hereby assumes sole responsibility to secure any
                   other intellectual property rights needed, if any.

                   For example, if a third party patent license is
                   required to allow Recipient to distribute the
                   Program, it is Recipient's responsibility to
                   acquire that license before distributing the
                   Program.

                   d) Each Contributor represents that to its
                   knowledge it has sufficient copyright rights in its
                   Contribution, if any, to grant the copyright
                   license set forth in this Agreement.

             3. REQUIREMENTS

             A Contributor may choose to distribute the Program in
             object code form under its own license agreement, provided
             that:
                   a) it complies with the terms and conditions of
                   this Agreement; and

                   b) its license agreement:
                   i) effectively disclaims on behalf of all
                   Contributors all warranties and conditions, express
                   and implied, including warranties or conditions of
                   title and non-infringement, and implied warranties
                   or conditions of merchantability and fitness for a
                   particular purpose;

                   ii) effectively excludes on behalf of all
                   Contributors all liability for damages, including
                   direct, indirect, special, incidental and
                   consequential damages, such as lost profits;

                   iii) states that any provisions which differ from
                   this Agreement are offered by that Contributor
                   alone and not by any other party; and

                   iv) states that source code for the Program is
                   available from such Contributor, and informs
                   licensees how to obtain it in a reasonable manner
                   on or through a medium customarily used for
                   software exchange.

             When the Program is made available in source code form:
                   a) it must be made available under this Agreement;
                   and
                   b) a copy of this Agreement must be included with
                   each copy of the Program. 

             Contributors may not remove or alter any copyright notices
             contained within the Program.

             Each Contributor must identify itself as the originator of
             its Contribution, if any, in a manner that reasonably
             allows subsequent Recipients to identify the originator of
             the Contribution. 


             4. COMMERCIAL DISTRIBUTION

             Commercial distributors of software may accept certain
             responsibilities with respect to end users, business
             partners and the like. While this license is intended to
             facilitate the commercial use of the Program, the
             Contributor who includes the Program in a commercial
             product offering should do so in a manner which does not
             create potential liability for other Contributors.
             Therefore, if a Contributor includes the Program in a
             commercial product offering, such Contributor ("Commercial
             Contributor") hereby agrees to defend and indemnify every
             other Contributor ("Indemnified Contributor") against any
             losses, damages and costs (collectively "Losses") arising
             from claims, lawsuits and other legal actions brought by a
             third party against the Indemnified Contributor to the
             extent caused by the acts or omissions of such Commercial
             Contributor in connection with its distribution of the
             Program in a commercial product offering. The obligations
             in this section do not apply to any claims or Losses
             relating to any actual or alleged intellectual property
             infringement. In order to qualify, an Indemnified
             Contributor must: a) promptly notify the Commercial
             Contributor in writing of such claim, and b) allow the
             Commercial Contributor to control, and cooperate with the
             Commercial Contributor in, the defense and any related
             settlement negotiations. The Indemnified Contributor may
             participate in any such claim at its own expense.


             For example, a Contributor might include the Program in a
             commercial product offering, Product X. That Contributor
             is then a Commercial Contributor. If that Commercial
             Contributor then makes performance claims, or offers
             warranties related to Product X, those performance claims
             and warranties are such Commercial Contributor's
             responsibility alone. Under this section, the Commercial
             Contributor would have to defend claims against the other
             Contributors related to those performance claims and
             warranties, and if a court requires any other Contributor
             to pay any damages as a result, the Commercial Contributor
             must pay those damages.


             5. NO WARRANTY

             EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE
             PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
             WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
             IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
             CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
             FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
             responsible for determining the appropriateness of using
             and distributing the Program and assumes all risks
             associated with its exercise of rights under this
             Agreement, including but not limited to the risks and
             costs of program errors, compliance with applicable laws,
             damage to or loss of data, programs or equipment, and
             unavailability or interruption of operations. 

             6. DISCLAIMER OF LIABILITY
             EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER
             RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY
             FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
             OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
             LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE
             OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
             POSSIBILITY OF SUCH DAMAGES.

             7. GENERAL

             If any provision of this Agreement is invalid or
             unenforceable under applicable law, it shall not affect
             the validity or enforceability of the remainder of the
             terms of this Agreement, and without further action by the
             parties hereto, such provision shall be reformed to the
             minimum extent necessary to make such provision valid and
             enforceable.


             If Recipient institutes patent litigation against a
             Contributor with respect to a patent applicable to
             software (including a cross-claim or counterclaim in a
             lawsuit), then any patent licenses granted by that
             Contributor to such Recipient under this Agreement shall
             terminate as of the date such litigation is filed. In
             addition, If Recipient institutes patent litigation
             against any entity (including a cross-claim or
             counterclaim in a lawsuit) alleging that the Program
             itself (excluding combinations of the Program with other
             software or hardware) infringes such Recipient's
             patent(s), then such Recipient's rights granted under
             Section 2(b) shall terminate as of the date such
             litigation is filed.

             All Recipient's rights under this Agreement shall
             terminate if it fails to comply with any of the material
             terms or conditions of this Agreement and does not cure
             such failure in a reasonable period of time after becoming
             aware of such noncompliance. If all Recipient's rights
             under this Agreement terminate, Recipient agrees to cease
             use and distribution of the Program as soon as reasonably
             practicable. However, Recipient's obligations under this
             Agreement and any licenses granted by Recipient relating
             to the Program shall continue and survive. 

             Everyone is permitted to copy and distribute copies of
             this Agreement, but in order to avoid inconsistency the
             Agreement is copyrighted and may only be modified in the
             following manner. The Agreement Steward reserves the right
             to publish new versions (including revisions) of this
             Agreement from time to time. No one other than the
             Agreement Steward has the right to modify this Agreement.

             IBM is the initial Agreement Steward. IBM may assign the
             responsibility to serve as the Agreement Steward to a
             suitable separate entity. Each new version of the
             Agreement will be given a distinguishing version number.
             The Program (including Contributions) may always be
             distributed subject to the version of the Agreement under
             which it was received. In addition, after a new version of
             the Agreement is published, Contributor may elect to
             distribute the Program (including its Contributions) under
             the new version. Except as expressly stated in Sections
             2(a) and 2(b) above, Recipient receives no rights or
             licenses to the intellectual property of any Contributor
             under this Agreement, whether expressly, by implication,
             estoppel or otherwise. All rights in the Program not
             expressly granted under this Agreement are reserved.


             This Agreement is governed by the laws of the State of New
             York and the intellectual property laws of the United
             States of America. No party to this Agreement will bring a
             legal action under this Agreement more than one year after
             the cause of action arose. Each party waives its rights to
             a jury trial in any resulting litigation. 



*/

/* (C) COPYRIGHT International Business Machines Corp. 2001          */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/types.h>

#include "log.h"
#include "err.h"
#include "slotmgr.h"
#include "pkcsslotd.h"


#define DEFAULT_PROGRAM_NAME "Program"

#ifndef PROGRAM_NAME
  #define PROGRAM_NAME DEFAULT_PROGRAM_NAME
#endif /* PROGRAM_NAME */


#ifdef DEV

  #ifndef DEFAULT_LOG_FILE
    #define DEFAULT_LOG_FILE "/tmp/" ## PROGRAM_NAME ## ".log"
  #endif /* DEFAULT_LOG_FILE */

#else /* production build */

  #ifndef DEFAULT_LOG_FILE
    #define DEFAULT_LOG_FILE NULL
  #endif /* DEFAULT_LOG_FILE */

#endif /* DEV */


#ifndef LOG_FILE
  #define LOG_FILE DEFAULT_LOG_FILE
#endif /* LOG_FILE */


#ifndef DEFAULT_DEBUG_LEVEL

  /********************* 
     DEFAULT_DEBUG_LEVEL is generally defined in another file (pkcsslotd.h?)
     The #defines here generally won't change much.
   *********************/

  #ifdef DEV
      #define DEFAULT_DEBUG_LEVEL DEBUG_LEVEL0
  #else
      #define DEFAULT_DEBUG_LEVEL DEBUG_NONE
  #endif /* DEFAULT_DEBUG_LEVEL */

#endif /* DEFAULT_DEBUG_LEVEL */



static u_int32                   DefaultLogOption                   = ( LOG_CONS | LOG_NOWAIT | LOG_ODELAY | LOG_PID );
static BOOL                      Initialized                        = FALSE;
static BOOL                      LoggingInitialized                 = FALSE;
static u_int32                   SysDebugLevel                      = DEFAULT_DEBUG_LEVEL;
static char                     *ProgramName                        = PROGRAM_NAME;
static LoggingFacilityInfo       LogInfo[MAX_LOGGING_FACILITIES];
static LogHandle                 hLogDebug;
static LogHandle                 hLogErr;
static LogHandle                 hLogLog;
static LogHandle                 hLogTrace;
static LogHandle                 hLogWarn;
static LogHandle                 hLogInfo;
                   

static LoggingFacility SystemLogFacilities[]   = { 
                                                   { "  DEBUG",   &hLogDebug,   LOG_FILE,  TRUE,  LOG_DEBUG    }, 
						   { "   INFO",   &hLogInfo,    LOG_FILE,  TRUE,  LOG_INFO     },
                                                   { "  TRACE",   &hLogTrace,   LOG_FILE,  TRUE,  LOG_INFO     },
                                                   { "    LOG",   &hLogLog,     LOG_FILE,  TRUE,  LOG_NOTICE   },
                                                   { "WARNING",   &hLogWarn,    LOG_FILE,  TRUE,  LOG_WARNING  }, 
                                                   { "  ERROR",   &hLogErr,     LOG_FILE,  TRUE,  LOG_ERR      }
                                                 };



/*****************************************
 *        Function Prototypes            *
 *****************************************/

static int                      InitDataStructs           ( void );
static BOOL                     InitLogging               ( void );
static pLoggingFacilityInfo     GetLogInfoPtr             ( LogHandle   hLog );
static BOOL                     GetFreeLogInfo            ( pLogHandle  Dest );
static void                     CloseAllLoggingFacilities ( void );
static BOOL                     SyslogOpen                ( pLoggingFacilityInfo pInfo );



/*************************************************************
 *  GetCurrentTimeString -
 * 
 *     Writes the current date & time into *Buffer
 * 
 *************************************************************/

BOOL GetCurrentTimeString ( char *Buffer ) {
  /* Note: The specs for ctime_r and asctime_r say that Buffer needs to be 26 characters long.  Not sure if that includes a triling NULL - SCM */

  time_t t;
  struct tm   tm;

  ASSERT(Buffer != NULL);

  time(&t);
  localtime_r(&t, &tm);
  asctime_r( &tm , &(Buffer[0]) );
  /* asctime_r puts a \n at the end, so we'll remove that */
  Buffer[strlen(Buffer)-1] = '\0';
  return TRUE;

}



/***********************************************************************
 *  InitDataStructs - 
 *  
 *  Called durining initalization to set up the LogInfo array
 *  
 ***********************************************************************/

static int InitDataStructs ( void ) {
  
  unsigned int i;

  for ( i = 0; i < (sizeof(LogInfo) / sizeof(LogInfo[0])); i++ ) {
    LogInfo[i].Initialized    = FALSE;
    LogInfo[i].Descrip[0]     = '\0';
    LogInfo[i].LogOption      = DefaultLogOption;
  }

  Initialized = TRUE;

  return TRUE;

}





/**********************************************************************
 *  GetFreeLogInfo -
 *  
 *  Return the handle for the next available Log Facility structure
 *  
 *  After calling this function, the facility will be marked as in use
 *
 ***********************************************************************/

static BOOL GetFreeLogInfo ( pLogHandle Dest ) {

  u_int32 i;

  if ( ! Initialized ) {
    InitDataStructs();
  }

  for ( i = 0; i < ( sizeof(LogInfo) / sizeof(LogInfo[0]) ); i++ ) {
    if ( LogInfo[i].Initialized == FALSE ) {
      /* 
	 Set this here so that we don't return the same identifier twice
	 in the case where GetFreeLogInfo() is called twice in a row
       */
      LogInfo[i].Initialized = TRUE;
      *Dest = i;
      return TRUE;
    }
  }
#ifdef DEV
  fprintf(stderr, "No available thread logging structs.\n");
#endif
  return FALSE;

}





/**********************************************************************
 *  GetLogInfoPtr -
 *  
 *  Given a handle, return a pointer to the appropriate LoggingFacilityInfo structure
 *  
 ***********************************************************************/

static pLoggingFacilityInfo GetLogInfoPtr ( LogHandle hLog ) {

  if ( hLog >= (sizeof(LogInfo) / sizeof(LogInfo[0]) ) ) {
#ifdef DEV
    fprintf(stderr, "Illegal LogHandle value: %#X\n", hLog);
#endif
    return NULL;
  }

  if ( LogInfo[hLog].Initialized != TRUE ) {
#ifdef DEV
    fprintf(stderr, "GetLogInfoPtr() called for a non-initialized handle\n");
#endif
    return NULL;
  }

  return &(LogInfo[hLog]);

}




/***********************************************************************
 *  NewLoggingFacility -
 *  
 *  Given an ID ( char string which will appear in the messages ),
 *  open a logging facility and return a handle to it in
 *  pLoggingStuff->phLog
 *
 ***********************************************************************/

BOOL NewLoggingFacility ( char *ID, pLoggingFacility pStuff ) {

  pLoggingFacilityInfo      pInfo = NULL;
  LogHandle                 hLog;
  pLogHandle                Result;

  /* See if there's room in the array.  This'd be nice if it were dynamically allocated */
  if ( ! GetFreeLogInfo(&hLog) ) {
    return FALSE;
  }
  
  /* Get a pointer to the syslog_data structure */
  if ( (pInfo = GetLogInfoPtr(hLog)) == NULL ) {
    return FALSE;
  }

  Result              = pStuff->phLog;


  /* 
      Set this before the filename is checked because we
      may want to use the descrip and/or filename in the logs
   */
  pInfo->UseSyslog    = pStuff->UseSyslog;
  pInfo->LogOption    = DefaultLogOption;
  pInfo->pid          = 0;
  pInfo->LogLevel     = pStuff->LogLevel;

  sprintf( pInfo->Descrip, "%s %s", pStuff->Label, ID );

  /* ensure that the last character is a NULL */
  pInfo->Descrip[sizeof(pInfo->Descrip)-1] = '\0';




  /* Some sanity checking on filename... */
  if ( (pStuff->Filename != NULL) && (strlen(pStuff->Filename) > 0) ) {

    FILE *fd;

    #if TRUNCATE_LOGS_ON_START

    /* 
     *  Truncating files on the start will present problems if the user creates
     *  their own logging facilities after the program's been running for a while
     *  But the non-syslog logging is intended for debug purposes only, anyway.
     * 
     */

      char FileMode[] = "w"; 
    #else
      char FileMode[] = "a"; 
    #endif /* TRUNCATE_LOGS_ON_START */

    if ( ( fd = fopen((pStuff->Filename), FileMode ) ) == NULL ) {
#ifdef DEV
      fprintf(stderr, "%s could not be opened\n", pStuff->Filename);
#endif
      pInfo->Filename     = NULL;
    } else {
	/* Tag the file */

	char buf[100];

	GetCurrentTimeString( &(buf[0]) );

#ifdef DEV
        #if TRUNCATE_LOGS_ON_START
          /* buf contains the date stamp */
	  fprintf(fd, "********* %s %s truncated *********\n", buf, pStuff->Filename);
	#else 
	  fprintf(fd, "********* %s \"%s\" logging to %s *********\n", buf, pInfo->Descrip, pStuff->Filename);
        #endif /* TRUNCATE_LOGS_ON_START */
#endif

	fflush(fd);
	fclose(fd);
	pInfo->Filename     = pStuff->Filename;
    }

  } else {

    pInfo->Filename       = NULL;

  }


  if ( pInfo->UseSyslog ) {
    /* open the logging facility */
    if (! SyslogOpen( pInfo ) ) {
      return FALSE;
    }
  }

  /* Redundant; Initialized is set to 1 in GetFreeLogInfo */
  pInfo->Initialized = TRUE;
  *Result = hLog;

  return TRUE;

}




/***********************************************************************
 *  CloseLoggingFacility -
 *  
 *  Closes the logging facility whose handle is hLog.
 *  Sets up the data structure for reuse later if desired
 * 
 ***********************************************************************/

BOOL CloseLoggingFacility ( LogHandle hLog ) {

  pLoggingFacilityInfo      pInfo               = NULL;

  if ( (pInfo = GetLogInfoPtr(hLog)) == NULL ) {
    return FALSE;
  }

  pInfo->Descrip[0]     = '\0';
  pInfo->LogOption      = 0;
  pInfo->Filename       = NULL;
  pInfo->pid            = 0;

  if ( pInfo->UseSyslog ) {
    closelog(  );
  }

  pInfo->Initialized    = FALSE;

  return TRUE;

}




/*****************************************
 * CloseAllLoggingFacilities - 
 * 
 * Closes down all the logging stuff we've set up
 *****************************************/
static void CloseAllLoggingFacilities ( void ) {
  u_int32      i = 0;

  for ( i = 0; i < (sizeof(LogInfo) / sizeof(LogInfo[0])); i++ ) {
    /* Makes assumption that these handles all are sequential.  Bad Style */
    if ( LogInfo[i].Initialized ) {
      CloseLoggingFacility(i);
    }
  }

  return;

}

/***********************************************************************
 *  PKCS_Log -
 *
 *  The primitive logging function which logs a message on hLog
 *
 ***********************************************************************/

BOOL PKCS_Log ( pLogHandle phLog, char *Format, va_list ap ) {

  char                    Buffer[PATH_MAX];
  pLoggingFacilityInfo    pInfo;

  if ( Format == NULL ) { return FALSE; }

  if ( (pInfo = GetLogInfoPtr(*phLog)) == NULL ) {
    return FALSE;
  }

  if ( (pInfo->pid != getpid() ) && (pInfo->UseSyslog) ) {
    /* Looks like our PID changed since the last call.  We have to re-open */
    if (! SyslogOpen(pInfo) ) {
      return FALSE;
    }
  }

  if ( vsprintf(&(Buffer[0]), Format, ap) < 0 ) {
    /* Error reporting functions should be rather robust, don't you think? */
    /* vsprintf reporting an error */
    //fprintf(stderr, "PKCS_ErrLog - vsprintf error for format string %s\n", Format);
    return FALSE;
  }

  /* Get rid of trailing newlines. */
  while ( strlen(Buffer) && (Buffer[strlen(Buffer)-1] == '\n') ) {
    Buffer[strlen(Buffer)-1] = '\0';
  }



  // Development work only.   No loging to anything other than syslog for
  // production level code

  /* 
     1/17/00 SCM - If we're not a daemon, we need to print something to stderr for
     warnings and errors regardless of development/production.  This is for errors
     that occur during startup.  I'll agree that we don't need to write to a log
     file in production mode, however.
   */

  /* 
     Production mode:   Write to stderr if we're not a daemon, and the priority of the message is at least LOG_WARNING
     Development mode:  Write to stderr if we're not a daemon
   */
    
  if ( ! IsDaemon() ) {
    BOOL WriteNow;

    #ifdef DEV 
        WriteNow = TRUE;
    #else
	WriteNow = (pInfo->LogLevel <= LOG_WARNING);
    #endif /* DEV */

    if ( WriteNow ) {
      fprintf(stderr, "%s[%d.%d]: %s\n", pInfo->Descrip, getpid(), (int)pthread_self(), Buffer);
    }

  }



  /* Don't log to a separate log file in production mode */
  #ifdef DEV
  if ( pInfo->Filename != NULL ) {

    FILE *fd;

    if ( (fd = fopen ( pInfo->Filename, "a+" ) ) == NULL ) {
      fprintf(stderr, "PKCS_Log: fopen failed for %s\n", pInfo->Filename);
    } else {
      char buf[32]; /* Specs say 26-character array */

      GetCurrentTimeString( &(buf[0]) );

      /* Date/Time stamp, descrip, Error message */
      fprintf ( fd, "%s %s[%d.%d]: ", buf, pInfo->Descrip, getpid(), pthread_self() );
      fprintf ( fd, "%s\n", Buffer);
      fflush  ( fd );
      fclose  ( fd );
    }

  } /* end if pInfo->Filename */
  #endif /* DEV */



  /* Always log to syslog, if we're using it */
  if ( pInfo->UseSyslog ) {
    syslog(pInfo->LogLevel, "%s", Buffer);
  }

  return TRUE;

}



/****************************************************************************
 * 
 *  Would like to have a generic function to which I pass the hLog where I'd
 *  like to do the logging and have a #defined macro which passes it along...
 * 
 *  But the preprocessor and variable # args don't work & play well together
 * 
 ****************************************************************************/



/*****************************************
 * DbgLog - 
 * 
 *   Log messages using the debug facility
 *****************************************/

void DbgLog ( u_int32 DebugLevel, char *Format, ... ) {

  va_list ap;

  if ( DebugLevel > SysDebugLevel ) { return; }
  if ( ! LoggingInitialized ) {
    InitLogging();
  }

  va_start( ap, Format );
  PKCS_Log( &hLogDebug, Format, ap);
  va_end ( ap ) ;
  return;

}



/*****************************************
 * ErrLog -
 * 
 *   Log Messges using the error facility
 *****************************************/

void ErrLog ( char *Format, ... ) {
  va_list ap;

  if ( ! LoggingInitialized ) {
    InitLogging();
  }
  va_start( ap, Format );
  PKCS_Log( &hLogErr, Format, ap);
  va_end ( ap ) ;
  return;
  
}

/*****************************************
 * LogLog -
 * 
 *   Log messages using the log facility
 *****************************************/
void LogLog ( char *Format, ... ) {
  va_list ap;

  if ( ! LoggingInitialized ) {
    InitLogging();
  }
  va_start( ap, Format );
  PKCS_Log( &hLogLog, Format, ap);
  va_end ( ap ) ;
  return;
  
}

/*****************************************
 * WarnLog - 
 * 
 *   Log messages using the warning facility
 *****************************************/
void WarnLog ( char *Format, ... ) {
  va_list ap;

  if ( ! LoggingInitialized ) {
    InitLogging();
  }
  va_start( ap, Format );
  PKCS_Log( &hLogWarn, Format, ap);
  va_end ( ap ) ;
  return;
  
}

/*****************************************
 * TraceLog - 
 * 
 *   Log messages using the trace facility
 *****************************************/
void TraceLog ( char *Format, ... ) {
  va_list ap;

  if ( ! LoggingInitialized ) {
    InitLogging();
  }
  va_start( ap, Format );
  PKCS_Log( &hLogTrace, Format, ap);
  va_end ( ap ) ;
  return;
  
}




/*****************************************
 * InfoLog - 
 * 
 *   Log messages using the info facility
 *****************************************/

void InfoLog ( char *Format, ... ) {
  va_list ap;

  if ( ! LoggingInitialized ) {
    InitLogging();
  }
  va_start( ap, Format );
  PKCS_Log( &hLogInfo, Format, ap);
  va_end ( ap ) ;
  return;
  
}



/***********************************************************************
 * InitLogging -
 * 
 *   Sets up the various logging facilities.  Must be called before
 *   any of the logging functions can be used.
 ***********************************************************************/

static BOOL InitLogging ( void ) {
  
  unsigned int i;
  char *s = ProgramName;


  /* if ProgramName is NULL, we'll just print the level... */
  if ( ProgramName == NULL ) {
    s = "";
  }

  /* Set up logging for all the facilities in SystemLogFacilities[] */
  for ( i = 0; i < ( sizeof(SystemLogFacilities) / (sizeof(SystemLogFacilities[0])) ); i++ ) {

    if (! NewLoggingFacility(s, &(SystemLogFacilities[i]) ) ) {
#ifdef DEV
      fprintf(stderr, "InitLogging: NewLoggingFacility failed: %s\n", s);
#endif
      return FALSE;
    }

  } /* end for i */

  atexit(CloseAllLoggingFacilities);
  LoggingInitialized = TRUE;
  return TRUE;

}



/*************************************************************
 * SetDebugLevel - 
 *
 *
 *  Sets the level at which debug messages get logged to Val.
 *  Returns the old value
 *************************************************************/

u_int32 SetDebugLevel ( u_int32 Val ) {
  u_int32  OldVal = SysDebugLevel;

  SysDebugLevel = Val;
  return OldVal;
}




/*************************************************************
 * GetDebugLevel 
 * 
 *   Returns the level at which the program will log debug messages
 *
 *************************************************************/

u_int32 GetDebugLevel ( void ) {
  return SysDebugLevel;
}



#if 0
int main ( int argc, char *argv[], char *envp[] ) {

  ErrLog("This is an error test, attempt 1");
  DbgLog(DEBUG_LEVEL0, "This is a DEBUG test level 0, attempt 1");
  DbgLog(DEBUG_LEVEL1, "This is a DEBUG test level 1, attempt 1");
  SetDebugLevel(DEBUG_NONE);
  DbgLog(DEBUG_LEVEL1, "This is a DEBUG test level 1, attempt 2");
  DbgLog(DEBUG_LEVEL0, "This is a DEBUG test level 0, attempt 2");
  ErrLog("This is an error test, attempt 2");
  return 0;

}
#endif /* 0 */



static BOOL SyslogOpen ( pLoggingFacilityInfo pInfo ) {

  ASSERT(pInfo != NULL);

  if ( !( pInfo->UseSyslog ) ) {
    /* it's not really an error to call SyslogOpen for a facility that doesn't use it */
    return TRUE;
  }

  if ( pInfo->pid != 0 ) {
    /* We've been initialized before, so close the previous instance */
    closelog();
  }

  /* Default to log all messages. */
  setlogmask( LOG_UPTO(LOG_DEBUG));
 
  /* Mark this as having been set by this process */
  pInfo->pid = getpid();

  return TRUE;

}
