Only use sudo when we are not `user`

This commit is contained in:
Amos Bird 2020-08-27 11:58:05 +08:00
parent 7ea5364299
commit b968f0c339
No known key found for this signature in database
GPG Key ID: 80D430DCBECFEDB4
1 changed files with 9 additions and 3 deletions

View File

@ -3,6 +3,7 @@
#include <boost/program_options.hpp>
#include <sys/stat.h>
#include <pwd.h>
#if defined(__linux__)
#include <syscall.h>
@ -643,9 +644,14 @@ namespace
if (!user.empty())
{
bool need_sudo = geteuid() != 0;
if (need_sudo)
command = fmt::format("sudo -u '{}' {}", user, command);
bool may_need_sudo = geteuid() != 0;
if (may_need_sudo)
{
struct passwd *p = getpwuid(geteuid());
// Only use sudo when we are not the given user
if (p == nullptr || std::string(p->pw_name) != user)
command = fmt::format("sudo -u '{}' {}", user, command);
}
else
command = fmt::format("su -s /bin/sh '{}' -c '{}'", user, command);
}