Replace redundent error handling

This commit is contained in:
madmaurice 2021-01-15 20:22:22 +01:00
parent 6806d43759
commit d1664d03f8

46
main.c
View file

@ -12,6 +12,12 @@
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
@ -19,26 +25,15 @@ void drop_root(void)
// be able to drop group once we dropped user
gid_t gid = getgid();
if (setresgid(-1,gid,gid) == -1)
{
int err = errno;
printf("Failed to drop root privileges with setresgid (%d)\n", err);
exit(err);
}
fatal("Failed to drop root privileges with setresgid", errno);
uid_t uid = getuid();
if (setresuid(-1,uid,uid) == -1)
{
int err = errno;
printf("Failed to drop root privileges with setresuid (%d)\n", err);
exit(err);
}
fatal("Failed to drop root privileges with setresuid", errno);
// sanity check
if (seteuid(0) != -1)
{
printf("Sanity check failed. I was able to regain root.\n");
exit(1);
}
fatal("Sanity check failed. Able to regain root", 42);
}
struct sigaction forward_signal_descriptor;
@ -79,9 +74,7 @@ int main(int argc, const char** argv)
// next fork shall be in a new pid namespace
if (unshare(CLONE_NEWPID) != 0)
{
err = errno;
printf("Failed to unshare pid namespace (%d)\n", err);
return err;
fatal("Failed to unshare pid namespace", errno);
}
// Drop root privileges, we only needed those for the unshare call.
@ -91,9 +84,7 @@ int main(int argc, const char** argv)
if (pid == -1)
{
int err = errno;
printf("Failed to fork (%d)\n", err);
return err;
fatal("Failed to fork", errno);
}
if (pid != 0)
@ -113,9 +104,7 @@ int main(int argc, const char** argv)
int status;
if (waitpid(pid, &status, 0) == -1)
{
err = errno;
printf("Failed to wait (%d)\n", err);
return err;
fatal("Failed to wait for init process", errno);
}
return WEXITSTATUS(status);
@ -128,6 +117,11 @@ int main(int argc, const char** argv)
// if the forked child exits then exit.
pid = fork();
if (pid == -1)
{
fatal("Failed to fork in init process", errno);
}
if (pid != 0)
{
/// Init process
@ -149,8 +143,7 @@ int main(int argc, const char** argv)
pid_child = first_child;
if (sigaction(SIGTERM, &forward_signal_descriptor, NULL) == -1)
{
printf("Unable to setup signal forward in init. Aborting.\n");
return 1;
fatal("Unable to setup signal forward in init", 1);
}
// wait could be interrupt due to a signal. In that case just call wait again.
@ -178,8 +171,7 @@ int main(int argc, const char** argv)
if (execvp(newargs[0], newargs) == -1)
{
printf("Failed to exec (%d)\n", err);
return err;
fatal("Failed to exec", errno);
}
}
}