Daemonizing

This commit is contained in:
Chris Josten 2020-12-08 07:43:53 +01:00
parent c829fe7b03
commit 619a0e8b9a

View file

@ -5,10 +5,13 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/seccomp.h>
#define LOGF(x, ...) do { logf_impl(x, __FILE__, __LINE__, __func__, __VA_ARGS__); } while(0);
#define LOG(x) do { log_impl(x, __FILE__, __LINE__, __func__); } while(0);
@ -29,16 +32,21 @@ typedef struct mbuf {
} mbuf_t;
const char *log_path = "/var/log/kerstman.log";
FILE *log_file = NULL;
void log_impl(const char *message, const char *file, int line, const char *func) {
fprintf(stderr, "%s:%d:%s: %s\n", file, line, func, message);
fprintf(log_file, "%s:%d:%s: %s\n", file, line, func, message);
fflush(log_file);
}
void logf_impl(const char *message, const char *file, int line, const char *func, ...) {
va_list args;
va_start(args, func);
fprintf(stderr, "%s:%d %s: ", file, line, func);
vfprintf(stderr, message, args);
fprintf(stderr, "\n");
fprintf(log_file, "%s:%d %s: ", file, line, func);
vfprintf(log_file, message, args);
fprintf(log_file, "\n");
va_end(args);
fflush(log_file);
}
int quit_if_fail(int err, const char *failMessage) {
@ -153,6 +161,7 @@ int do_command_loop(mbuf_t *mbuf) {
}
int main(int argc, char *argv[]) {
log_file = stderr;
if (argc < 3) {
const char *format = "GEBRUIK: %s [ADRES] [POORT]";
size_t length = strlen(argv[0]) + strlen(format);
@ -164,6 +173,30 @@ int main(int argc, char *argv[]) {
}
LOG("Kerstezel starten");
// Daemonize
pid_t pid;
pid = quit_if_fail(fork(), "Kon niet vorken");
if (pid > 0) exit(EXIT_SUCCESS);
quit_if_fail(chdir("/"), "Kon werkmap niet veranderen");
quit_if_fail(setsid(), "Kon sid niet veranderen");
// Zorg ervoor dat de daemon geen TTY kan bemachtigen
pid = quit_if_fail(fork(), "Kon niet vorken");
if (pid > 0) exit(EXIT_SUCCESS);
log_file = fopen(log_path, "a");
if (log_file == NULL) {
// Kan niet loggen lol
exit(EXIT_FAILURE);
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT) < 0) {
LOGF("Kon seccomp niet aanroepen: %s", strerror(errno));
}
struct addrinfo hints, *servinfo, *p;
memset(&hints, 0, sizeof(struct addrinfo));