Skip to content

Commit

Permalink
nft-helper: Terminate on errors
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
wkz committed Dec 18, 2024
1 parent 25c6cf9 commit 86ebb42
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/nft-helper/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand All @@ -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);

Expand Down

0 comments on commit 86ebb42

Please sign in to comment.