diff --git a/main.c b/main.c index 2d80b57..1336d06 100644 --- a/main.c +++ b/main.c @@ -2,6 +2,7 @@ #define _GNU_SOURCE #include #include +#include #include #include #include @@ -12,12 +13,6 @@ pid_t pid_child; -void fatal(const char* str, int errcode) -{ - printf("%s (%d)\n", str, errcode); - exit(errcode); -} - void drop_root(void) { /// Drop root privileges @@ -25,15 +20,15 @@ void drop_root(void) // be able to drop group once we dropped user gid_t gid = getgid(); if (setresgid(-1,gid,gid) == -1) - fatal("Failed to drop root privileges with setresgid", errno); + err(errno, "Failed to drop root privileges with setresgid"); uid_t uid = getuid(); if (setresuid(-1,uid,uid) == -1) - fatal("Failed to drop root privileges with setresuid", errno); + err(errno, "Failed to drop root privileges with setresuid"); // sanity check if (seteuid(0) != -1) - fatal("Sanity check failed. Able to regain root", 42); + errx(1, "Sanity check failed. Able to regain root"); } struct sigaction forward_signal_descriptor; @@ -48,8 +43,6 @@ void forward_signal(int sig) int main(int argc, char* const* argv) { - int err; - forward_signal_descriptor.sa_flags = SA_RESTART; forward_signal_descriptor.sa_handler = &forward_signal; @@ -64,7 +57,7 @@ int main(int argc, char* const* argv) // next fork shall be in a new pid namespace if (unshare(CLONE_NEWPID) != 0) { - fatal("Failed to unshare pid namespace", errno); + err(errno, "Failed to unshare pid namespace"); } // Drop root privileges, we only needed those for the unshare call. @@ -74,7 +67,7 @@ int main(int argc, char* const* argv) if (pid == -1) { - fatal("Failed to fork", errno); + err(errno, "Failed to fork"); } if (pid != 0) @@ -94,7 +87,7 @@ int main(int argc, char* const* argv) int status; if (waitpid(pid, &status, 0) == -1) { - fatal("Failed to wait for init process", errno); + err(errno, "Failed to wait for init process"); } return WEXITSTATUS(status); @@ -109,7 +102,7 @@ int main(int argc, char* const* argv) pid = fork(); if (pid == -1) { - fatal("Failed to fork in init process", errno); + err(errno, "Failed to fork in init process"); } if (pid != 0) @@ -133,18 +126,19 @@ int main(int argc, char* const* argv) pid_child = first_child; if (sigaction(SIGTERM, &forward_signal_descriptor, NULL) == -1) { - fatal("Unable to setup signal forward in init", 1); + err(1, "Unable to setup signal forward in init"); } + int wait_errno; // wait could be interrupt due to a signal. In that case just call wait again. do { exited_child = wait(&child_status); - err = errno; - } while (!(exited_child == first_child || (exited_child == -1 && err == ECHILD))); + wait_errno = errno; + } while (!(exited_child == first_child || (exited_child == -1 && wait_errno == ECHILD))); if (exited_child == -1) { - return err; + err(wait_errno, "Error while waiting for subprocess"); } else { @@ -159,7 +153,7 @@ int main(int argc, char* const* argv) if (execvp(argv[0], argv) == -1) { - fatal("Failed to exec", errno); + err(errno, "Failed to exec"); } } }