alertik/alertik.c

84 lines
1.9 KiB
C
Raw Normal View History

2024-05-28 04:14:29 +02:00
/*
* Alertik: a tiny 'syslog' server & notification tool for Mikrotik routers.
* This is free and unencumbered software released into the public domain.
*/
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
2024-05-31 03:28:28 +02:00
#include "alertik.h"
#include "events.h"
2024-07-16 03:16:27 +02:00
#include "env_events.h"
2024-07-16 03:47:57 +02:00
#include "log.h"
2024-07-16 03:16:27 +02:00
#include "notifiers.h"
2024-07-17 03:34:38 +02:00
#include "syslog.h"
2024-05-28 04:14:29 +02:00
/* Misc. */
#define LAST_SENT_THRESHOLD_SECS 10 /* Minimum time (in secs) between two */
2024-07-16 03:16:27 +02:00
time_t time_last_sent_notify; /* notifications. */
2024-05-28 04:14:29 +02:00
static void *handle_messages(void *p)
{
((void)p);
size_t i;
struct log_event ev = {0};
2024-07-17 03:34:38 +02:00
while (syslog_pop_msg_from_fifo(&ev) >= 0) {
2024-05-28 04:14:29 +02:00
print_log_event(&ev);
2024-05-31 03:28:28 +02:00
if ((time(NULL) - time_last_sent_notify) <= LAST_SENT_THRESHOLD_SECS) {
log_msg("ignoring, reason: too many notifications!\n");
continue;
}
2024-05-28 04:14:29 +02:00
/* Check if it belongs to any of our desired events. */
2024-05-31 03:28:28 +02:00
for (i = 0; i < NUM_EVENTS; i++) {
2024-05-28 04:14:29 +02:00
if (strstr(ev.msg, handlers[i].str)) {
handlers[i].hnd(&ev);
break;
}
}
2024-05-31 03:28:28 +02:00
if (i == NUM_EVENTS)
2024-05-28 04:14:29 +02:00
log_msg("> No match!\n");
}
return NULL;
}
int main(void)
{
pthread_t handler;
int fd;
2024-07-16 03:47:57 +02:00
log_init();
2024-07-16 03:16:27 +02:00
setup_notifiers();
init_environment_events();
2024-05-28 04:14:29 +02:00
2024-05-31 01:49:35 +02:00
log_msg(
"Alertik (" GIT_HASH ") (built at " __DATE__ " " __TIME__ ")\n");
log_msg(" (https://github.com/Theldus/alertik)\n");
log_msg("-------------------------------------------------\n");
2024-05-28 04:14:29 +02:00
2024-07-17 03:34:38 +02:00
fd = syslog_create_udp_socket();
2024-05-28 04:14:29 +02:00
if (pthread_create(&handler, NULL, handle_messages, NULL))
panic_errno("Unable to create hanler thread!");
2024-05-31 01:49:35 +02:00
log_msg("Waiting for messages at :%d (UDP)...\n", SYSLOG_PORT);
2024-05-28 04:14:29 +02:00
2024-07-17 03:34:38 +02:00
while (syslog_enqueue_new_upd_msg(fd) >= 0);
2024-05-31 01:49:35 +02:00
return EXIT_SUCCESS;
2024-05-28 04:14:29 +02:00
}