Tidied Process class and moved Application::isRunningAsRoot() function to Process class

This commit is contained in:
Nav
2022-10-05 20:58:25 +01:00
parent f5d75f2ea6
commit 51a3d2fbbb
5 changed files with 49 additions and 21 deletions

View File

@@ -4,6 +4,8 @@
#include <string>
#include <map>
#include "src/Exceptions/Exception.hpp"
namespace Bloom
{
::pid_t Process::getProcessId() {
@@ -14,6 +16,26 @@ namespace Bloom
return getppid();
}
::uid_t Process::getEffectiveUserId(std::optional<::pid_t> processId) {
if (!processId.has_value()) {
processId = Process::getProcessId();
}
const auto processInfo = Process::getProcessInfo(processId.value());
if (!processInfo) {
throw Exceptions::Exception(
"Failed to fetch process info for process ID " + std::to_string(processId.value())
);
}
return static_cast<::uid_t>(processInfo->euid);
}
bool Process::isRunningAsRoot(std::optional<::pid_t> processId) {
return Process::getEffectiveUserId(processId) == 0;
}
bool Process::isManagedByClion(std::optional<::pid_t> parentProcessId) {
if (!parentProcessId.has_value()) {
parentProcessId = Process::getParentProcessId();
@@ -48,16 +70,11 @@ namespace Bloom
}
Process::Proc Process::getProcessInfo(::pid_t processId) {
auto proc = std::unique_ptr<::PROCTAB, decltype(&::closeproc)>(
const auto proc = std::unique_ptr<::PROCTAB, decltype(&::closeproc)>(
::openproc(PROC_FILLSTAT | PROC_FILLARG | PROC_PID, &processId),
::closeproc
);
auto processInfo = Proc(::readproc(proc.get(), NULL), ::freeproc);
if (processInfo == NULL) {
return Proc(nullptr, ::freeproc);
}
return processInfo;
return Proc(::readproc(proc.get(), NULL), ::freeproc);
}
}

View File

@@ -2,6 +2,7 @@
#include <optional>
#include <memory>
#include <sys/types.h>
#include <proc/readproc.h>
namespace Bloom
@@ -23,6 +24,26 @@ namespace Bloom
*/
static ::pid_t getParentProcessId();
/**
* Returns the effective user ID of the given process.
*
* @param processId
* If not provided, this function will use the current process ID.
*
* @return
*/
static ::uid_t getEffectiveUserId(std::optional<::pid_t> processId = std::nullopt);
/**
* Returns true if the given process is running as root.
*
* @param processId
* If not provided, this function will perform the check against the current process.
*
* @return
*/
static bool isRunningAsRoot(std::optional<::pid_t> processId = std::nullopt);
/**
* Returns true if the given process is managed by CLion.
*
@@ -33,7 +54,6 @@ namespace Bloom
*/
static bool isManagedByClion(std::optional<::pid_t> parentProcessId = std::nullopt);
private:
using Proc = std::unique_ptr<::proc_t, decltype(&::freeproc)>;
static Proc getProcessInfo(::pid_t processId);