From 86ebb421892b5fd43ebf9cd83a0cd4aed4ac0296 Mon Sep 17 00:00:00 2001 From: Tobias Waldekranz Date: Wed, 18 Dec 2024 16:46:52 +0100 Subject: [PATCH] nft-helper: Terminate on errors - Fix the error detection with `waitpid()`, which returns the PID of the waited process, so `run()` thus always used to return -1. - Return the full wait status info so we can write a better error message about what happened, to the user. - Terminate the program if the ruleset fails to load. - Write an informational message when the ruleset is successfully applied, so that the user can be sure that it has loaded properly. Fix #17 --- src/nft-helper/main.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/nft-helper/main.c b/src/nft-helper/main.c index 078ad73..6e7ae6c 100644 --- a/src/nft-helper/main.c +++ b/src/nft-helper/main.c @@ -21,21 +21,22 @@ int run(char *cmd[]) _exit(execvp(cmd[0], cmd)); } - if (waitpid(pid, &rc, 0)) + if (waitpid(pid, &rc, 0) != pid) return -1; - return WEXITSTATUS(rc); + return rc; } void cb(int signo) { - warnx("got signal %d, calling nft flush ruleset and exit.", signo); + warnx("got signal %d, calling nft flush ruleset and exit", signo); } int main(int argc, char *argv[]) { char *load[] = { "nft", "-f", NULL, NULL }; char *flush[] = { "nft", "flush", "ruleset", NULL }; + int rc; if (argc < 2 || access(argv[1], F_OK)) errx(1, "Missing nft.conf argument.\nUsage:\n\t%s /path/to/nftables.conf", argv[0]); @@ -46,7 +47,18 @@ int main(int argc, char *argv[]) signal(SIGHUP, cb); load[2] = argv[1]; - run(load); + rc = run(load); + if (rc == -1) { + err(1, "Internal error while waiting for ruleset to load"); + } else if (WIFEXITED(rc)) { + rc = WEXITSTATUS(rc); + if (rc) + errx(rc, "Failed to load ruleset, exited with status %d", rc); + } else if (WIFSIGNALED(rc)) { + errx(rc, "Failed to load ruleset, terminated on signal %d", WTERMSIG(rc)); + } + + warnx("Ruleset active"); pause(); run(flush);