Skip to content

Commit 86ebb42

Browse files
committed
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
1 parent 25c6cf9 commit 86ebb42

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/nft-helper/main.c

+16-4
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,22 @@ int run(char *cmd[])
2121
_exit(execvp(cmd[0], cmd));
2222
}
2323

24-
if (waitpid(pid, &rc, 0))
24+
if (waitpid(pid, &rc, 0) != pid)
2525
return -1;
2626

27-
return WEXITSTATUS(rc);
27+
return rc;
2828
}
2929

3030
void cb(int signo)
3131
{
32-
warnx("got signal %d, calling nft flush ruleset and exit.", signo);
32+
warnx("got signal %d, calling nft flush ruleset and exit", signo);
3333
}
3434

3535
int main(int argc, char *argv[])
3636
{
3737
char *load[] = { "nft", "-f", NULL, NULL };
3838
char *flush[] = { "nft", "flush", "ruleset", NULL };
39+
int rc;
3940

4041
if (argc < 2 || access(argv[1], F_OK))
4142
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[])
4647
signal(SIGHUP, cb);
4748

4849
load[2] = argv[1];
49-
run(load);
50+
rc = run(load);
51+
if (rc == -1) {
52+
err(1, "Internal error while waiting for ruleset to load");
53+
} else if (WIFEXITED(rc)) {
54+
rc = WEXITSTATUS(rc);
55+
if (rc)
56+
errx(rc, "Failed to load ruleset, exited with status %d", rc);
57+
} else if (WIFSIGNALED(rc)) {
58+
errx(rc, "Failed to load ruleset, terminated on signal %d", WTERMSIG(rc));
59+
}
60+
61+
warnx("Ruleset active");
5062
pause();
5163
run(flush);
5264

0 commit comments

Comments
 (0)