/* Nessus
 * Copyright (C) 1998 Renaud Deraison
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *
 * Log.c -- manages the logfile of Nessus
 *
 */
 


#include <includes.h>
#include <stdarg.h>
#ifdef NESSUSNT
#include <time.h>
#include "wstuff.h"
#endif
#include "utils.h"
#include "log.h"

FILE * log;

/* 
 * initialization of the log file
 */
void 
log_init(filename)
  const char * filename;
{
  if((!filename)||(!strncmp(filename, "stderr", 6)))log = stderr;
  else
    {
      check_symlink(filename);
      log = fopen(filename, "a");
      chmod(filename, 0600);
      if(!log)
	{
	  perror("fopen ");
	  print_error("Could not open the logfile, using stderr\n");
	  log = stderr;
	}
    }
#ifndef NESSUSNT
  log_write("started by uid %d\n", getuid());
#else
  log_write("starting up...\n");
#endif
}


/*
 * write into the logfile
 * Nothing fancy here...
 */
void 
log_write(const char * str, ...)
{
  va_list param;
  char * disp = emalloc(4096);
  char * timestr;
  char * tmp;
  time_t t;

  va_start(param, str);
#ifdef HAVE_VSNPRINTF
  vsnprintf(disp, 4095,str, param);
#else
  vsprintf(disp, str, param);
#endif
  while((tmp=strchr(disp, '\n')))tmp[0]=' ';
  t = time(NULL);
  tmp = ctime(&t);
  timestr = emalloc(strlen(tmp)+1);
  strncpy(timestr, tmp, strlen(tmp));
  timestr[strlen(timestr)-1]=0;
  if(disp[strlen(disp)-1]=='\n')disp[strlen(disp)-1]=0;
#ifndef USE_PTHREADS
  fprintf(log, "[%s][%d] %s\n", timestr, getpid(), disp);
#else 
  fprintf(log, "[%s][%d.%d] %s\n", timestr, getpid(), pthread_self(), disp);
#endif
  fflush(log);
  efree(&timestr);
  efree(&disp);
  va_end(param);  
}
