From 168f5bf1d86c62c1fc62a7c79890a874e47b2e21 Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Wed, 2 Jul 2025 14:25:42 +0200 Subject: [PATCH] log: new function, log_parse() Converts from syslog priority string format to facility and level. Signed-off-by: Joachim Wiberg --- src/log.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/log.h | 1 + 2 files changed, 71 insertions(+) diff --git a/src/log.c b/src/log.c index 7eb80d62..7a50b6f4 100644 --- a/src/log.c +++ b/src/log.c @@ -32,6 +32,9 @@ # include #endif +#define SYSLOG_NAMES +#include + #include "finit.h" #include "helpers.h" #include "log.h" @@ -106,6 +109,73 @@ static const char *l2s(int prio) return "UNK"; } +static int s2f(const char *str) +{ + for (int i = 0; facilitynames[i].c_name; i++) { + if (string_match(facilitynames[i].c_name, str)) + return facilitynames[i].c_val; + } + + return -1; +} + +static int s2l(const char *str) +{ + for (int i = 0; prioritynames[i].c_name; i++) { + if (string_match(prioritynames[i].c_name, str)) + return prioritynames[i].c_val; + } + + return -1; +} + +/* + * Parse syslog facility.priority strings into their numerical values + * using arrays defined in . Note, the 'prio' argument may + * be one of: + * + * - facility.level + * - facility + * - level + * + * It is up to the callee to assign defaults to 'facility' and 'level' + * before calling this function. If There is any match the respective + * facility or level will be assigned and this function returns OK. + */ +int log_parse(char *prio, int *facility, int *level) +{ + char *fac = prio, *lvl; + int f = -1; + int l = -1; + + if (!prio || !facility || !level) + return -1; + + lvl = strchr(prio, '.'); + if (lvl) { + *lvl = 0; + lvl++; + } + + if (lvl && *lvl) + l = s2l(lvl); + + f = s2f(fac); + if (l < 0) + l = s2l(fac); + + if (l < 0 && f <= 0) + return -1; + + if (l <= LOG_DEBUG) + *level = l; + + if (f <= LOG_LOCAL7) + *facility = f; + + return 0; +} + /* * Log to /dev/kmsg until syslogd has started, then openlog() * and continue logging as a regular daemon. diff --git a/src/log.h b/src/log.h index 4a449484..ee6097f9 100644 --- a/src/log.h +++ b/src/log.h @@ -78,6 +78,7 @@ void log_init (void); void log_exit (void); void log_debug(void); +int log_parse(char *prio, int *facility, int *level); void logit (int prio, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); void flog (char *file, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));