build: Move stuff to be shared to lib/ (nvt_log, socket)
This commit is contained in:
+114
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Logging functions
|
||||
*/
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <syslog.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "nvt_log.h"
|
||||
|
||||
#include <sys/syscall.h>
|
||||
#define gettid() (pid_t)syscall(__NR_gettid)
|
||||
|
||||
char log_level = 0;
|
||||
|
||||
static char log_threshold = LOG_DEBUG;
|
||||
|
||||
static FILE *log_dest = NULL;
|
||||
|
||||
void nvt_log_dest(int dest)
|
||||
{
|
||||
switch (dest)
|
||||
{
|
||||
default:
|
||||
case NVT_LOG_SYSLOG:
|
||||
log_dest = NULL;
|
||||
break;
|
||||
case NVT_LOG_STDOUT:
|
||||
log_dest = stdout;
|
||||
break;
|
||||
case NVT_LOG_STDERR:
|
||||
log_dest = stderr;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void nvt_log_level(int quiet, int level)
|
||||
{
|
||||
if (quiet)
|
||||
log_threshold = LOG_NOTICE;
|
||||
log_level = level;
|
||||
}
|
||||
|
||||
static const char *_hms_txt(char *buf, unsigned int len)
|
||||
{
|
||||
struct timeval tv;
|
||||
unsigned int sod, hh, mm, ss;
|
||||
|
||||
gettimeofday(&tv, NULL);
|
||||
|
||||
sod = tv.tv_sec % (24 * 3600);
|
||||
hh = sod / 3600;
|
||||
mm = (sod - hh * 3600) / 60;
|
||||
ss = sod - hh * 3600 - mm * 60;
|
||||
snprintf(buf, len, "%02d:%02d:%02d.%06d",
|
||||
hh, mm, ss, (unsigned int)tv.tv_usec);
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
void nvt_log(int prio, const char *fmt, ...)
|
||||
{
|
||||
va_list arg;
|
||||
char buf[256], buft[64];
|
||||
const char *eol;
|
||||
int len;
|
||||
|
||||
if (prio > log_threshold)
|
||||
return;
|
||||
|
||||
va_start(arg, fmt);
|
||||
len = vsnprintf(buf, sizeof(buf), fmt, arg);
|
||||
|
||||
if (log_dest)
|
||||
{
|
||||
eol = (len > 0 && buf[len - 1] != '\n') ? "\n" : "";
|
||||
fprintf(log_dest, "%s: [%d] %d: %s%s",
|
||||
_hms_txt(buft, sizeof(buft)), gettid(), prio, buf, eol);
|
||||
}
|
||||
else
|
||||
{
|
||||
syslog(prio, "[%d] %s", gettid(), buf);
|
||||
}
|
||||
|
||||
va_end(arg);
|
||||
}
|
||||
|
||||
#define BPL 16 /* Bytes per line */
|
||||
|
||||
void nvt_log_buf(int prio, const char *txt, const void *ptr_, unsigned int len)
|
||||
{
|
||||
unsigned int ix, i, imax;
|
||||
int l, n;
|
||||
char buf[128];
|
||||
const unsigned char *ptr = ptr_;
|
||||
|
||||
for (ix = 0; ix < len || (len == 0 && ix == 0); ix += BPL)
|
||||
{
|
||||
n = snprintf(buf, sizeof(buf), "%s: %04x:", txt, ix);
|
||||
if (n <= 0)
|
||||
return; /* Just playing it safe */
|
||||
imax = (len - ix < BPL) ? len - ix : BPL;
|
||||
for (i = 0; i < imax; i++)
|
||||
{
|
||||
l = snprintf(buf + n, sizeof(buf) - n, " %02x", *ptr++);
|
||||
if (l <= 0)
|
||||
return; /* Just playing it safe */
|
||||
n += l;
|
||||
}
|
||||
nvt_log(prio, "%s\n", buf);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user