Files
BloomPatched/src/Helpers/Process.cpp

85 lines
2.4 KiB
C++
Raw Normal View History

2022-09-15 00:30:59 +01:00
#include "Process.hpp"
#include <unistd.h>
#include <string>
#include <map>
2022-09-15 00:30:59 +01:00
#include "src/Exceptions/Exception.hpp"
2022-09-15 00:30:59 +01:00
namespace Bloom
{
::pid_t Process::getProcessId() {
return getpid();
}
::pid_t Process::getParentProcessId() {
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> processId) {
if (!processId.has_value()) {
processId = Process::getProcessId();
}
static auto cachedResultsByProcessId = std::map<::pid_t, bool>();
2022-12-03 22:16:21 +00:00
const auto cachedResultIt = cachedResultsByProcessId.find(*processId);
2022-09-15 00:30:59 +01:00
2022-12-03 22:16:21 +00:00
if (cachedResultIt != cachedResultsByProcessId.end()) {
return cachedResultIt->second;
2022-09-15 00:30:59 +01:00
}
// Start with the parent process and walk the tree until we find CLion
const auto processInfo = Process::getProcessInfo(*processId);
2022-09-15 00:30:59 +01:00
if (!processInfo) {
cachedResultsByProcessId[*processId] = false;
return false;
}
auto pid = processInfo->ppid;
2022-09-15 00:30:59 +01:00
while (const auto processInfo = Process::getProcessInfo(pid)) {
const auto commandLine = std::string(processInfo->cmd);
2022-09-15 00:30:59 +01:00
if (commandLine.find("clion.sh") != std::string::npos) {
cachedResultsByProcessId[*processId] = true;
2022-09-15 00:30:59 +01:00
return true;
}
pid = processInfo->ppid;
2022-09-15 00:30:59 +01:00
}
cachedResultsByProcessId[*processId] = false;
2022-09-15 00:30:59 +01:00
return false;
}
2022-10-01 21:01:37 +01:00
Process::Proc Process::getProcessInfo(::pid_t processId) {
const auto proc = std::unique_ptr<::PROCTAB, decltype(&::closeproc)>(
::openproc(PROC_FILLSTAT | PROC_FILLARG | PROC_PID, &processId),
::closeproc
);
2022-09-15 00:30:59 +01:00
return Proc(::readproc(proc.get(), NULL), ::freeproc);
2022-09-15 00:30:59 +01:00
}
}