Add extracted tools: CitrineOS, OpenOCPP, ShapeShifter

- CitrineOS core extracted (CSMS OCPP 2.0.1)
- OpenOCPP extracted (firmware OCPP 1.6J/2.0.1)
- ShapeShifter library installed (pip install -e)
- ShapeShifter specification extracted
- EVerest extracted

TODO updated with progress
This commit is contained in:
Eric F
2026-06-08 00:38:27 -04:00
parent 468cfeaa50
commit d398a6ced2
7326 changed files with 1177561 additions and 7 deletions

View File

@@ -0,0 +1,60 @@
if(NOT DEFINED sdbus-c++_VERSION_MAJOR AND NOT DISABLE_EDM)
string(REPLACE "." ";" SDBUS_CPP_VERSION_SPLIT ${CPM_PACKAGE_sdbus-cpp_VERSION})
list(GET SDBUS_CPP_VERSION_SPLIT 0 sdbus-c++_VERSION_MAJOR)
endif()
message("Found sdbus-c++ major version: " ${sdbus-c++_VERSION_MAJOR})
add_library(everest_system STATIC)
add_library(everest::system ALIAS everest_system)
ev_register_library_target(everest_system)
target_sources(everest_system
PRIVATE
src/dbus_base.cpp
src/rauc_dbus_base.cpp
src/safe_system.cpp
)
target_include_directories(everest_system
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(everest_system
PRIVATE
everest::log
PUBLIC
SDBusCpp::sdbus-c++
)
target_compile_definitions(everest_system
PRIVATE
SDBUSCPP_MAJOR_VERSION=${sdbus-c++_VERSION_MAJOR}
)
set_target_properties(everest_system PROPERTIES EXPORT_NAME system)
if (DISABLE_EDM)
install(
TARGETS everest_system
EXPORT everest_system-targets
)
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/everest
TYPE INCLUDE
)
evc_setup_package(
NAME everest-everest_system
NAMESPACE everest
EXPORT everest_system-targets
ADDITIONAL_CONTENT
"find_dependency(sdbus-c++)"
)
endif()
if (BUILD_TESTING)
target_compile_definitions(everest_system PUBLIC EVEREST_COVERAGE_ENABLED)
add_subdirectory(tests)
endif()

View File

@@ -0,0 +1,37 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
/**
* \file sdbus-c++ version independent interfaces
*
* The sdbus-c++ library is used to provide a C++ interface to DBus.
* The functions defined here enable code to compile and run against
* version 1.4 or higher of sdbus-c++.
*/
#pragma once
#include <sdbus-c++/sdbus-c++.h>
namespace everest::lib::system::dbus {
using async_method_callback = std::function<void(sdbus::MethodReply reply, std::optional<sdbus::Error> error)>;
using async_property_callback = std::function<void(std::optional<sdbus::Error> error, sdbus::Variant value)>;
// library version independent functions
[[nodiscard]] std::unique_ptr<sdbus::IProxy> createProxy(const char* destination, const char* objectPath);
[[nodiscard]] std::unique_ptr<sdbus::IProxy> createProxy(const char* destination, const char* objectPath,
sdbus::dont_run_event_loop_thread_t);
[[nodiscard]] sdbus::MethodCall createMethodCall(const std::unique_ptr<sdbus::IProxy>& proxy, const char* interfaceName,
const char* methodName);
sdbus::PendingAsyncCall callMethodAsync(const std::unique_ptr<sdbus::IProxy>& proxy, sdbus::MethodCall& method,
async_method_callback handler, uint64_t timeout_us);
sdbus::PendingAsyncCall getPropertyAsync(const std::unique_ptr<sdbus::IProxy>& proxy, async_property_callback handler,
const char* property, const char* interface);
void registerSignalHandler(std::unique_ptr<sdbus::IProxy>& proxy, const char* interfaceName, const char* signalName,
sdbus::signal_handler signalHandler);
void initialise_handlers(const std::unique_ptr<sdbus::IProxy>& proxy, std::function<void(void)> init);
void process_pending(sdbus::IConnection& connection);
} // namespace everest::lib::system::dbus

View File

@@ -0,0 +1,223 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#pragma once
#include <sdbus-c++/sdbus-c++.h>
#include <everest/system/dbus_base.hpp>
#include <cstdint>
#include <string>
#include <string_view>
namespace everest::lib::system::rauc_dbus {
namespace defaults {
constexpr const char* service_domain = "de.pengutronix.rauc";
constexpr const char* object_path = "/";
} // namespace defaults
namespace interface {
constexpr const char* Installer = "de.pengutronix.rauc.Installer";
constexpr const char* DBus_Properties = "org.freedesktop.DBus.Properties";
} // namespace interface
namespace property {
constexpr const char* Progress = "Progress";
constexpr const char* Operation = "Operation";
constexpr const char* LastError = "LastError";
constexpr const char* BootSlot = "BootSlot";
} // namespace property
namespace signal {
constexpr const char* PropertiesChanged = "PropertiesChanged";
constexpr const char* Completed = "Completed";
} // namespace signal
namespace method {
constexpr const char* InstallBundle = "InstallBundle";
constexpr const char* InspectBundle = "InspectBundle";
constexpr const char* Mark = "Mark";
constexpr const char* GetSlotStatus = "GetSlotStatus";
constexpr const char* GetPrimary = "GetPrimary";
} // namespace method
namespace rauc_messages {
struct Progress {
int percent;
std::string description;
int level;
};
struct CmdResult {
bool success;
std::string error_msg;
};
enum class Operation {
Unknown,
Idle,
Installing
};
struct UpdateTransaction {
std::int32_t request_id;
std::string boot_slot;
std::string primary_slot;
};
enum class HealthCheckStatus {
ScriptExitedWithError,
ScriptNotExecutable,
ScriptNotSet,
ScriptTerminatedBySignal,
SetupFailed,
Success,
UnknownError
};
Operation string_to_operation(const std::string_view& s);
// Stream operators are needed for type conversion in sdbus
sdbus::Message& operator<<(sdbus::Message& msg, const Progress& items);
sdbus::Message& operator>>(sdbus::Message& msg, Progress& items);
} // namespace rauc_messages
// ----------------------------------------------------------------------------
// Base class
class RaucBase {
public:
using property_cb = dbus::async_property_callback;
using method_cb = dbus::async_method_callback;
using slot_info_t = std::map<std::string, std::map<std::string, std::string>>;
struct CurrentState {
rauc_messages::HealthCheckStatus system_health_rc;
std::string boot_slot;
std::string primary_slot;
};
RaucBase();
RaucBase(sdbus::dont_run_event_loop_thread_t);
void configure(const std::string& verify_update_script_path = "");
bool check_previous_transaction(const CurrentState& current, const rauc_messages::UpdateTransaction& saved);
// methods
sdbus::PendingAsyncCall install_bundle(method_cb handler, const std::string& filename, uint64_t timeout_us);
sdbus::PendingAsyncCall mark(method_cb handler, const std::string& mark, const std::string& slot,
uint64_t timeout_us);
// properties
sdbus::PendingAsyncCall get_boot_slot(property_cb handler) const;
protected:
std::unique_ptr<sdbus::IProxy> proxy;
using slots_t = std::vector<sdbus::Struct<std::string, std::map<std::string, sdbus::Variant>>>;
static slot_info_t convert(slots_t& slots);
rauc_messages::HealthCheckStatus check_system_health();
// methods
sdbus::PendingAsyncCall get_primary_slot(method_cb handler, uint64_t timeout_us);
sdbus::PendingAsyncCall get_slot_status(method_cb handler, uint64_t timeout_us);
// properties
sdbus::PendingAsyncCall get_last_error(property_cb handler) const;
sdbus::PendingAsyncCall get_operation(property_cb handler) const;
sdbus::PendingAsyncCall get_progress(property_cb handler) const;
virtual bool decide_if_good(const rauc_messages::UpdateTransaction& saved, const CurrentState& current);
virtual void configure_handlers() = 0;
private:
std::string verify_update_script_path;
};
// ----------------------------------------------------------------------------
// Synchronous base class
class RaucBaseSync : public RaucBase {
public:
using RaucBase::RaucBase;
rauc_messages::UpdateTransaction create_transaction(std::int32_t request_id, uint64_t timeout_us);
bool check_previous_transaction(const rauc_messages::UpdateTransaction& saved, uint64_t timeout_us);
// methods
rauc_messages::CmdResult install_bundle(const std::string& filename, uint64_t timeout_us);
void mark(const std::string& mark, const std::string& slot, uint64_t timeout_us);
// properties
std::string get_boot_slot() const;
protected:
// methods
std::string get_primary_slot(uint64_t timeout_us);
slot_info_t get_slot_status(uint64_t timeout_us);
// properties
std::string get_last_error() const;
rauc_messages::Operation get_operation() const;
rauc_messages::Progress get_progress() const;
};
// ----------------------------------------------------------------------------
// Asynchronous base class
class RaucBaseAsync : public RaucBase {
public:
using RaucBase::RaucBase;
// methods
bool install_bundle(const std::string& filename, uint64_t timeout_us);
bool mark(const std::string& mark, const std::string& slot, uint64_t timeout_us);
// properties
bool get_boot_slot();
protected:
sdbus::PendingAsyncCall active_request;
// methods
bool get_primary_slot(uint64_t timeout_us);
bool get_slot_status(uint64_t timeout_us);
// properties
bool get_last_error();
bool get_operation();
bool get_progress();
// callbacks
enum class error_t : std::uint8_t {
install_bundle,
mark,
boot_slot,
primary_slot,
slot_status,
last_error,
operation,
progress
};
virtual void cb_install_bundle() = 0;
virtual void cb_mark() = 0;
virtual void cb_boot_slot(const std::string_view& value) = 0;
virtual void cb_primary_slot(const std::string_view& value) = 0;
virtual void cb_slot_status(const slot_info_t& value) = 0;
virtual void cb_last_error(const std::string_view& value) = 0;
virtual void cb_operation(rauc_messages::Operation value) = 0;
virtual void cb_progress(const rauc_messages::Progress& value) = 0;
virtual void cb_error(error_t fn, const std::string_view& error) = 0;
};
} // namespace everest::lib::system::rauc_dbus
namespace sdbus {
template <>
struct signature_of<everest::lib::system::rauc_dbus::rauc_messages::Progress>
: signature_of<Struct<int, std::string, int>> {};
} // namespace sdbus

View File

@@ -0,0 +1,84 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#pragma once
#include <cstdlib>
#include <initializer_list>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace everest::lib::system {
// An enum to describe the overall outcome
typedef enum {
CMD_SUCCESS, // Ran and exited normally
CMD_TERMINATED, // Terminated by signal
CMD_SETUP_FAILED // Setup failed (fork, ...)
} CommandExecutionStatus;
// Execution result type
typedef struct {
CommandExecutionStatus status;
int code; // Child's exit code (if CMD_SUCCESS) OR terminating signal (CMD_TERMINATED) OR errno (CMD_SETUP_FAILED)
bool timeout; // Command timed out
} CommandResult;
std::string cmd_execution_status_to_string(const CommandExecutionStatus& status);
std::string command_string_repr(std::string pathname, std::vector<std::string> args);
std::string command_string_repr(std::string_view pathname, std::initializer_list<std::string_view> args);
/// @brief convenience c++ function for safe_system_c
/// @param fd - file descriptor for stdout
/// @param pathname - the command to run
/// @param args - the arguments
/// @return exit code, 128 + signal number, errno ...
CommandResult safe_system(int fd, const std::string& pathname_str, std::vector<std::string>* args, int timeout_s = 30);
/// @brief convenience c++ function for safe_system_c
/// @param pathname - the command to run
/// @param args - the arguments
/// @return exit code, 128 + signal number, errno ...
inline CommandResult safe_system(const std::string& pathname_str, std::vector<std::string>* args, int timeout_s = 30) {
return safe_system(-1, pathname_str, args, timeout_s);
}
/// @brief convenience c++ function for safe_system_c
/// @param fd - file descriptor for stdout
/// @param pathname - the command to run (accepts std::string_view, literals, std::string)
/// @param args - the arguments (accepts initializer_list of std::string_view, literals, std::string)
/// @return exit code, 128 + signal number, errno ...
CommandResult safe_system(int fd, std::string_view pathname, std::initializer_list<std::string_view> args,
int timeout_s = 30);
/// @brief convenience c++ function for safe_system_c
/// @param pathname - the command to run (accepts std::string_view, literals, std::string)
/// @param args - the arguments (accepts initializer_list of std::string_view, literals, std::string)
/// @return exit code, 128 + signal number, errno ...
inline CommandResult safe_system(std::string_view pathname, std::initializer_list<std::string_view> args,
int timeout_s = 30) {
return safe_system(-1, pathname, args, timeout_s);
}
/// @brief splits a given command line (cmd + args) into its components, respecting quoting
/// @param command - the commandline to be split
/// @return a vector
std::pair<std::string, std::vector<std::string>> split_command_line(const std::string& command);
/// @brief update the exit status from a child process
/// @param status - the exit status
/// @return updated status taking into account signals and other exit conditions
constexpr int update_exit_status(int status) {
int updated_status = status;
if (WIFEXITED(status)) {
updated_status = WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
updated_status = WTERMSIG(status) + 128;
}
return updated_status;
}
} // namespace everest::lib::system

View File

@@ -0,0 +1,113 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#include <everest/system/dbus_base.hpp>
namespace everest::lib::system::dbus {
void initialise_handlers(const std::unique_ptr<sdbus::IProxy>& proxy, std::function<void(void)> init) {
init();
#if SDBUSCPP_MAJOR_VERSION == 1
proxy->finishRegistration();
#endif
}
void process_pending(sdbus::IConnection& connection) {
for (;;) {
#if SDBUSCPP_MAJOR_VERSION == 1
if (!connection.processPendingRequest()) {
break;
}
#else
if (!connection.processPendingEvent()) {
break;
}
#endif
}
}
std::unique_ptr<sdbus::IProxy> createProxy(const char* destination, const char* objectPath) {
std::unique_ptr<sdbus::IProxy> result;
#if SDBUSCPP_MAJOR_VERSION == 1
result = sdbus::createProxy(destination, objectPath);
#else
auto sname = sdbus::ServiceName{destination};
auto opath = sdbus::ObjectPath{objectPath};
result = sdbus::createProxy(sname, opath);
#endif
return result;
}
std::unique_ptr<sdbus::IProxy> createProxy(const char* destination, const char* objectPath,
sdbus::dont_run_event_loop_thread_t) {
std::unique_ptr<sdbus::IProxy> result;
#if SDBUSCPP_MAJOR_VERSION == 1
result = sdbus::createProxy(destination, objectPath, sdbus::dont_run_event_loop_thread);
#else
auto sname = sdbus::ServiceName{destination};
auto opath = sdbus::ObjectPath{objectPath};
result = sdbus::createProxy(sname, opath, sdbus::dont_run_event_loop_thread);
#endif
return result;
}
sdbus::MethodCall createMethodCall(const std::unique_ptr<sdbus::IProxy>& proxy, const char* interfaceName,
const char* methodName) {
sdbus::MethodCall result;
#if SDBUSCPP_MAJOR_VERSION == 1
result = proxy->createMethodCall(interfaceName, methodName);
#else
auto iname = sdbus::InterfaceName{interfaceName};
auto mname = sdbus::MethodName{methodName};
result = proxy->createMethodCall(iname, mname);
#endif
return result;
}
sdbus::PendingAsyncCall callMethodAsync(const std::unique_ptr<sdbus::IProxy>& proxy, sdbus::MethodCall& method,
async_method_callback handler, uint64_t timeout_us) {
sdbus::PendingAsyncCall result;
#if SDBUSCPP_MAJOR_VERSION == 1
auto invoke = [handler](sdbus::MethodReply reply, const sdbus::Error* error) {
std::optional<sdbus::Error> err;
if (error != nullptr) {
err = *error;
}
handler(reply, err);
};
result = proxy->callMethod(method, invoke, timeout_us);
#else
result = proxy->callMethodAsync(method, handler, timeout_us);
#endif
return result;
}
sdbus::PendingAsyncCall getPropertyAsync(const std::unique_ptr<sdbus::IProxy>& proxy, async_property_callback handler,
const char* property, const char* interface) {
sdbus::PendingAsyncCall result;
#if SDBUSCPP_MAJOR_VERSION == 1
auto invoke = [handler](const sdbus::Error* error, sdbus::Variant value) {
std::optional<sdbus::Error> err;
if (error != nullptr) {
err = *error;
}
handler(err, value);
};
#else
auto& invoke = handler;
#endif
return proxy->getPropertyAsync(property).onInterface(interface).uponReplyInvoke(invoke);
}
void registerSignalHandler(std::unique_ptr<sdbus::IProxy>& proxy, const char* interfaceName, const char* signalName,
sdbus::signal_handler signalHandler) {
#if SDBUSCPP_MAJOR_VERSION == 1
proxy->registerSignalHandler(interfaceName, signalName, signalHandler);
#else
auto iname = sdbus::InterfaceName{interfaceName};
auto sname = sdbus::SignalName{signalName};
proxy->registerSignalHandler(iname, sname, signalHandler);
#endif
}
} // namespace everest::lib::system::dbus

View File

@@ -0,0 +1,473 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#include <everest/logging.hpp>
#include <everest/system/dbus_base.hpp>
#include <everest/system/rauc_dbus_base.hpp>
#include <everest/system/safe_system.hpp>
#include <string>
#include <string_view>
namespace {
using namespace everest::lib::system;
using namespace everest::lib::system::rauc_dbus;
using namespace everest::lib::system::rauc_dbus::rauc_messages;
sdbus::PendingAsyncCall get_property_async(RaucBase::property_cb handler, const std::unique_ptr<sdbus::IProxy>& proxy,
const char* property, const char* interface) {
sdbus::PendingAsyncCall result;
try {
result = dbus::getPropertyAsync(proxy, handler, property, interface);
} catch (const sdbus::Error& e) {
EVLOG_error << "getPropertyAsync '" << property << "': " << e.what();
}
return result;
}
sdbus::PendingAsyncCall call_method_async(RaucBase::method_cb handler, const std::unique_ptr<sdbus::IProxy>& proxy,
const char* interface, const char* method, uint64_t timeout_us) {
sdbus::PendingAsyncCall result;
try {
auto m = dbus::createMethodCall(proxy, interface, method);
result = dbus::callMethodAsync(proxy, m, handler, timeout_us);
} catch (const sdbus::Error& e) {
EVLOG_error << "callMethodAsync '" << method << "': " << e.what();
}
return result;
}
template <typename T>
CmdResult get_property(T& result, const std::unique_ptr<sdbus::IProxy>& proxy, const char* property,
const char* interface) {
CmdResult res{false, {}};
try {
result = proxy->getProperty(property).onInterface(interface).get<T>();
res.success = true;
} catch (const sdbus::Error& e) {
EVLOG_error << "getProperty '" << property << "': " << e.what();
res.error_msg = e.getMessage();
}
return res;
}
template <typename T>
CmdResult call_method(T& result, const std::unique_ptr<sdbus::IProxy>& proxy, sdbus::MethodCall& method,
const char* m_str, uint64_t timeout_us) {
CmdResult res{false, {}};
try {
auto reply = proxy->callMethod(method, timeout_us);
if (!reply.isEmpty()) {
reply >> result;
res.success = true;
}
} catch (const sdbus::Error& e) {
EVLOG_error << "callMethod '" << m_str << "': " << e.what();
res.error_msg = e.getMessage();
}
return res;
}
CmdResult call_method(const std::unique_ptr<sdbus::IProxy>& proxy, sdbus::MethodCall& method, const char* m_str,
uint64_t timeout_us) {
CmdResult res{false, {}};
try {
proxy->callMethod(method, timeout_us);
res.success = true;
} catch (const sdbus::Error& e) {
EVLOG_error << "callMethod '" << m_str << "': " << e.what();
res.error_msg = e.getMessage();
}
return res;
}
} // namespace
namespace everest::lib::system::rauc_dbus {
namespace rauc_messages {
sdbus::Message& operator<<(sdbus::Message& msg, const Progress& items) {
return msg << sdbus::Struct{std::forward_as_tuple(items.percent, items.description, items.level)};
}
sdbus::Message& operator>>(sdbus::Message& msg, Progress& items) {
sdbus::Struct s{std::forward_as_tuple(items.percent, items.description, items.level)};
return msg >> s;
}
Operation string_to_operation(const std::string_view& s) {
if (s == "idle") {
return rauc_messages::Operation::Idle;
}
if (s == "installing") {
return rauc_messages::Operation::Installing;
}
if (!s.empty()) {
EVLOG_warning << "Unknown rauc operation: " << s;
}
return rauc_messages::Operation::Unknown;
}
} // namespace rauc_messages
// ----------------------------------------------------------------------------
// class RaucBase
RaucBase::RaucBase() {
// Create proxy object, this will start an internal event loop thread
proxy = dbus::createProxy(defaults::service_domain, defaults::object_path);
}
RaucBase::RaucBase(sdbus::dont_run_event_loop_thread_t) {
// Create proxy object, using an external event loop
proxy = dbus::createProxy(defaults::service_domain, defaults::object_path, sdbus::dont_run_event_loop_thread);
}
void RaucBase::configure(const std::string& verify_update_script_path) {
this->verify_update_script_path = verify_update_script_path;
try {
dbus::initialise_handlers(proxy, [this]() { configure_handlers(); });
} catch (const sdbus::Error& e) {
EVLOG_error << "RaucBase::configure: " << e.getMessage();
}
}
// Call on boot and pass a previous transaction that was not closed yet
bool RaucBase::check_previous_transaction(const CurrentState& current, const rauc_messages::UpdateTransaction& saved) {
bool result{false};
const std::string state = "boot=" + current.boot_slot + " primary=" + current.primary_slot;
const std::string transaction = "transaction boot=" + saved.boot_slot + " primary=" + saved.primary_slot +
" id=" + std::to_string(saved.request_id);
if (decide_if_good(saved, current)) {
EVLOG_info << "We have booted into the new updated slot (" << state << "), update was successful ("
<< transaction << ") Marking good";
// Mark this slot as good in RAUC
result = true;
} else {
EVLOG_error << "We have booted into the old fall back slot (" << state << "), update was not successful ("
<< transaction << ')';
}
return result;
}
sdbus::PendingAsyncCall RaucBase::get_boot_slot(property_cb handler) const {
return get_property_async(handler, proxy, property::BootSlot, interface::Installer);
}
sdbus::PendingAsyncCall RaucBase::install_bundle(method_cb handler, const std::string& filename, uint64_t timeout_us) {
sdbus::PendingAsyncCall result;
try {
auto method = dbus::createMethodCall(proxy, interface::Installer, method::InstallBundle);
std::map<std::string, sdbus::Variant> parameters;
method << filename << parameters;
result = dbus::callMethodAsync(proxy, method, handler, timeout_us);
} catch (const sdbus::Error& e) {
EVLOG_error << "RaucBase::install_bundle: " << e.what();
}
return result;
}
sdbus::PendingAsyncCall RaucBase::mark(method_cb handler, const std::string& mark, const std::string& slot,
uint64_t timeout_us) {
sdbus::PendingAsyncCall result;
try {
auto method = dbus::createMethodCall(proxy, interface::Installer, method::Mark);
method << mark << slot;
result = dbus::callMethodAsync(proxy, method, handler, timeout_us);
} catch (const sdbus::Error& e) {
EVLOG_error << "RaucBase::mark: " << e.what();
}
return result;
}
RaucBase::slot_info_t RaucBase::convert(slots_t& slots) {
slot_info_t result;
for (const auto& [n, v] : slots) {
std::map<std::string, std::string> nv_dict;
for (const auto& [nn, vv] : v) {
try {
if (nn == "size") {
nv_dict[nn] = std::to_string(vv.get<std::uint64_t>());
} else if (nn == "installed.count") {
nv_dict[nn] = std::to_string(vv.get<std::uint32_t>());
} else {
nv_dict[nn] = vv.get<std::string>();
}
} catch (...) {
nv_dict[nn] = {};
}
}
result[n] = std::move(nv_dict);
}
return result;
}
rauc_messages::HealthCheckStatus RaucBase::check_system_health() {
// checking the success or failure of an OTA update following reboot
using namespace rauc_messages;
if (verify_update_script_path.empty()) {
return HealthCheckStatus::ScriptNotSet;
}
if (access(verify_update_script_path.c_str(), X_OK) != 0) {
EVLOG_error << "Health check script '" << verify_update_script_path << "' not executable";
return HealthCheckStatus::ScriptNotExecutable;
}
const auto res = everest::lib::system::safe_system(verify_update_script_path, {verify_update_script_path});
switch (res.status) {
case everest::lib::system::CMD_SETUP_FAILED:
EVLOG_error << "Health check script '" << verify_update_script_path << "' setup failed, errno: " << res.code;
return HealthCheckStatus::SetupFailed;
case everest::lib::system::CMD_TERMINATED:
EVLOG_error << "Health check script '" << verify_update_script_path << "' terminated by signal: " << res.code;
return HealthCheckStatus::ScriptTerminatedBySignal;
case everest::lib::system::CMD_SUCCESS:
if (res.code == 0) {
EVLOG_debug << "Health check script '" << verify_update_script_path << "' returned success";
return HealthCheckStatus::Success;
} else {
EVLOG_error << "Health check script '" << verify_update_script_path
<< "' returned error code: " << res.code;
return HealthCheckStatus::ScriptExitedWithError;
}
}
// Should not reach here
return HealthCheckStatus::UnknownError;
}
sdbus::PendingAsyncCall RaucBase::get_operation(property_cb handler) const {
return get_property_async(handler, proxy, property::Operation, interface::Installer);
}
sdbus::PendingAsyncCall RaucBase::get_last_error(property_cb handler) const {
return get_property_async(handler, proxy, property::LastError, interface::Installer);
}
sdbus::PendingAsyncCall RaucBase::get_primary_slot(method_cb handler, uint64_t timeout_us) {
return call_method_async(handler, proxy, interface::Installer, method::GetPrimary, timeout_us);
}
sdbus::PendingAsyncCall RaucBase::get_slot_status(method_cb handler, uint64_t timeout_us) {
return call_method_async(handler, proxy, interface::Installer, method::GetSlotStatus, timeout_us);
}
sdbus::PendingAsyncCall RaucBase::get_progress(property_cb handler) const {
return get_property_async(handler, proxy, property::Progress, interface::Installer);
}
bool RaucBase::decide_if_good(const rauc_messages::UpdateTransaction& saved, const CurrentState& current) {
// check that the boot slot has changed and update script ran successfully or was not set
if (saved.boot_slot == current.boot_slot) {
return false;
}
if (current.system_health_rc != rauc_messages::HealthCheckStatus::Success and
current.system_health_rc != rauc_messages::HealthCheckStatus::ScriptNotSet) {
return false;
}
return true;
}
// ----------------------------------------------------------------------------
// class RaucBaseSync
rauc_messages::UpdateTransaction RaucBaseSync::create_transaction(std::int32_t request_id, uint64_t timeout_us) {
return {request_id, get_boot_slot(), get_primary_slot(timeout_us)};
}
bool RaucBaseSync::check_previous_transaction(const rauc_messages::UpdateTransaction& saved, uint64_t timeout_us) {
const CurrentState current{check_system_health(), get_boot_slot(), get_primary_slot(timeout_us)};
const auto res = RaucBase::check_previous_transaction(current, saved);
if (res) {
mark("good", "booted", timeout_us);
}
return res;
}
rauc_messages::CmdResult RaucBaseSync::install_bundle(const std::string& filename, uint64_t timeout_us) {
auto method = dbus::createMethodCall(proxy, interface::Installer, method::InstallBundle);
std::map<std::string, sdbus::Variant> parameters;
method << filename << parameters;
return call_method(proxy, method, method::InstallBundle, timeout_us);
}
void RaucBaseSync::mark(const std::string& mark, const std::string& slot, uint64_t timeout_us) {
auto method = dbus::createMethodCall(proxy, interface::Installer, method::Mark);
method << mark << slot;
call_method(proxy, method, method::Mark, timeout_us);
}
std::string RaucBaseSync::get_boot_slot() const {
std::string result;
get_property(result, proxy, property::BootSlot, interface::Installer);
return result;
}
std::string RaucBaseSync::get_primary_slot(uint64_t timeout_us) {
std::string result;
auto method = dbus::createMethodCall(proxy, interface::Installer, method::GetPrimary);
call_method(result, proxy, method, method::GetPrimary, timeout_us);
return result;
}
std::map<std::string, std::map<std::string, std::string>> RaucBaseSync::get_slot_status(uint64_t timeout_us) {
// a(sa{sv})
slots_t slots;
auto method = dbus::createMethodCall(proxy, interface::Installer, method::GetSlotStatus);
call_method(slots, proxy, method, method::GetSlotStatus, timeout_us);
return convert(slots);
}
std::string RaucBaseSync::get_last_error() const {
std::string result;
get_property(result, proxy, property::LastError, interface::Installer);
return result;
}
rauc_messages::Operation RaucBaseSync::get_operation() const {
std::string result;
get_property(result, proxy, property::Operation, interface::Installer);
return rauc_messages::string_to_operation(result);
}
rauc_messages::Progress RaucBaseSync::get_progress() const {
rauc_messages::Progress result{0, {}, 0};
get_property(result, proxy, property::Progress, interface::Installer);
return result;
}
// ----------------------------------------------------------------------------
// class RaucBaseAsync
bool RaucBaseAsync::install_bundle(const std::string& filename, uint64_t timeout_us) {
auto handler = [this](sdbus::MethodReply reply, std::optional<sdbus::Error> error) {
if (error) {
cb_error(error_t::install_bundle, error->getMessage());
} else {
cb_install_bundle();
}
};
active_request = RaucBase::install_bundle(handler, filename, timeout_us);
return active_request.isPending();
}
bool RaucBaseAsync::mark(const std::string& mark, const std::string& slot, uint64_t timeout_us) {
auto handler = [this](sdbus::MethodReply reply, std::optional<sdbus::Error> error) {
if (error) {
cb_error(error_t::mark, error->getMessage());
} else {
cb_mark();
}
};
active_request = RaucBase::mark(handler, mark, slot, timeout_us);
return active_request.isPending();
}
bool RaucBaseAsync::get_boot_slot() {
auto handler = [this](std::optional<sdbus::Error> error, sdbus::Variant value) {
if (error) {
cb_error(error_t::boot_slot, error.value().getMessage());
} else {
try {
cb_boot_slot(value.get<std::string>());
} catch (const sdbus::Error& e) {
std::string e_str = "Exception: " + e.getMessage();
cb_error(error_t::boot_slot, e_str);
}
}
};
active_request = RaucBase::get_boot_slot(handler);
return active_request.isPending();
}
bool RaucBaseAsync::get_primary_slot(uint64_t timeout_us) {
auto handler = [this](sdbus::MethodReply reply, std::optional<sdbus::Error> error) {
if (error) {
cb_error(error_t::primary_slot, error->getMessage());
} else {
try {
std::string slot;
reply >> slot;
cb_primary_slot(slot);
} catch (const sdbus::Error& e) {
std::string e_str = "Exception: " + e.getMessage();
cb_error(error_t::primary_slot, e_str);
}
}
};
active_request = RaucBase::get_primary_slot(handler, timeout_us);
return active_request.isPending();
}
bool RaucBaseAsync::get_slot_status(uint64_t timeout_us) {
auto handler = [this](sdbus::MethodReply reply, std::optional<sdbus::Error> error) {
if (error) {
cb_error(error_t::slot_status, error->getMessage());
} else {
try {
slots_t slots;
reply >> slots;
cb_slot_status(convert(slots));
} catch (const sdbus::Error& e) {
std::string e_str = "Exception: " + e.getMessage();
cb_error(error_t::slot_status, e_str);
}
}
};
active_request = RaucBase::get_slot_status(handler, timeout_us);
return active_request.isPending();
}
bool RaucBaseAsync::get_last_error() {
auto handler = [this](std::optional<sdbus::Error> error, sdbus::Variant value) {
if (error) {
cb_error(error_t::last_error, error.value().getMessage());
} else {
try {
cb_last_error(value.get<std::string>());
} catch (const sdbus::Error& e) {
std::string e_str = "Exception: " + e.getMessage();
cb_error(error_t::last_error, e_str);
}
}
};
active_request = RaucBase::get_last_error(handler);
return active_request.isPending();
}
bool RaucBaseAsync::get_operation() {
auto handler = [this](std::optional<sdbus::Error> error, sdbus::Variant value) {
if (error) {
cb_error(error_t::operation, error.value().getMessage());
} else {
try {
cb_operation(string_to_operation(value.get<std::string>()));
} catch (const sdbus::Error& e) {
std::string e_str = "Exception: " + e.getMessage();
cb_error(error_t::operation, e_str);
}
}
};
active_request = RaucBase::get_operation(handler);
return active_request.isPending();
}
bool RaucBaseAsync::get_progress() {
auto handler = [this](std::optional<sdbus::Error> error, sdbus::Variant value) {
if (error) {
cb_error(error_t::progress, error.value().getMessage());
} else {
try {
cb_progress(value.get<rauc_messages::Progress>());
} catch (const sdbus::Error& e) {
std::string e_str = "Exception: " + e.getMessage();
cb_error(error_t::progress, e_str);
}
}
};
active_request = RaucBase::get_progress(handler);
return active_request.isPending();
}
} // namespace everest::lib::system::rauc_dbus

View File

@@ -0,0 +1,235 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#include <everest/system/safe_system.hpp>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <stdexcept>
namespace {
constexpr int STRERROR_BUF_SIZE = 128;
inline void kill_and_wait(int pid_fd) {
syscall(SYS_pidfd_send_signal, pid_fd, SIGKILL, NULL, 0);
siginfo_t status_info;
#ifndef P_PIDFD
waitid(static_cast<idtype_t>(3), pid_fd, &status_info, WEXITED);
#else
waitid(P_PIDFD, pid_fd, &status_info, WEXITED);
#endif
}
everest::lib::system::CommandResult wait_for_process(int pid, int timeout_s) {
using CmdExecStatus = everest::lib::system::CommandExecutionStatus;
using CmdResult = everest::lib::system::CommandResult;
CmdResult result{CmdExecStatus::CMD_SETUP_FAILED, 0, false};
// Try to get a pid file descriptor
int pid_fd = syscall(SYS_pidfd_open, pid, 0);
if (pid_fd == -1) {
result.code = errno;
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
return result;
}
// Try to open an epoll fd
int epoll_fd = epoll_create1(0);
if (epoll_fd == -1) {
result.code = errno;
kill_and_wait(pid_fd);
close(pid_fd);
return result;
}
// Setup epoll
struct epoll_event event_mask {};
event_mask.events = EPOLLIN; // Process exit is signaled via EPOLLIN
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, pid_fd, &event_mask) == -1) {
result.code = errno;
kill_and_wait(pid_fd);
close(pid_fd);
close(epoll_fd);
return result;
}
// Await either timeout or natural exit of process
struct epoll_event event {};
int timeout_ms = timeout_s * 1000;
int event_count = epoll_wait(epoll_fd, &event, 1, timeout_ms);
if (event_count == 0) {
// Nothing happened -> timed out and process still runs
syscall(SYS_pidfd_send_signal, pid_fd, SIGKILL, NULL, 0);
result.timeout = true;
}
// Reap the child and get its final status
siginfo_t status_info;
#ifndef P_PIDFD
if (waitid(static_cast<idtype_t>(3), pid_fd, &status_info, WEXITED) != -1) {
#else
if (waitid(P_PIDFD, pid_fd, &status_info, WEXITED) != -1) {
#endif
if (status_info.si_code == CLD_EXITED) {
result.status = CmdExecStatus::CMD_SUCCESS;
} else if (status_info.si_code == CLD_KILLED) {
result.status = CmdExecStatus::CMD_TERMINATED;
}
result.code = status_info.si_status;
} else {
result.status = CmdExecStatus::CMD_SETUP_FAILED;
result.code = errno;
}
close(pid_fd);
close(epoll_fd);
return result;
}
everest::lib::system::CommandResult safe_system_command(int fd, const char* pathname, char* const argv[],
int timeout_s) {
using CmdExecStatus = everest::lib::system::CommandExecutionStatus;
pid_t pid = fork();
if (pid == -1) {
return {CmdExecStatus::CMD_SETUP_FAILED, errno, false};
} else if (pid == 0) {
// child process
// keep stdout and stderr available
(void)close(STDIN_FILENO);
if (fd != -1) {
(void)dup2(fd, STDOUT_FILENO);
}
if (execv(pathname, argv) == -1) {
// if this is executed, execv did not replace the process
perror("execv in safe_system_command failed");
_exit(EXIT_FAILURE);
}
}
// parent process
return wait_for_process(pid, timeout_s);
}
} // namespace
namespace everest::lib::system {
std::string cmd_execution_status_to_string(const CommandExecutionStatus& status) {
switch (status) {
case CommandExecutionStatus::CMD_SUCCESS:
return "CMD_SUCCESS";
case CommandExecutionStatus::CMD_TERMINATED:
return "CMD_TERMINATED";
case CommandExecutionStatus::CMD_SETUP_FAILED:
return "CMD_SETUP_FAILED";
default:
return "CMD_UNKNOWN_STATUS";
}
}
std::string command_string_repr(std::string pathname, std::vector<std::string> args) {
std::string ret{pathname};
for (const auto& item : args) {
ret.push_back(' ');
ret.append(item);
}
return ret;
}
std::string command_string_repr(std::string_view pathname, std::initializer_list<std::string_view> args) {
std::vector<std::string> arg_v(args.begin(), args.end());
return command_string_repr(std::string(pathname), arg_v);
}
CommandResult safe_system(int fd, const std::string& pathname_str, std::vector<std::string>* args, int timeout_s) {
std::vector<char*> argv;
std::transform(args->begin(), args->end(), std::back_inserter(argv), [](std::string& s) { return s.data(); });
argv.push_back(nullptr);
return safe_system_command(fd, pathname_str.c_str(), argv.data(), timeout_s);
}
CommandResult safe_system(int fd, std::string_view pathname, std::initializer_list<std::string_view> args,
int timeout_s) {
std::string pathname_str{pathname};
std::vector<std::string> argv_str{args.begin(), args.end()};
return safe_system(fd, pathname_str, &argv_str, timeout_s);
}
std::pair<std::string, std::vector<std::string>> split_command_line(const std::string& command) {
auto whitespace = [](char c) { return std::isspace(c); };
auto any = [](char c) { return std::isspace(c) || c == '"' || c == '\''; };
if (std::any_of(command.cbegin(), command.cend(), [](char c) { return c == '\\'; })) {
throw std::runtime_error("Command lines containg '\\' are considered invalid.");
}
std::vector<std::string> results;
auto from = std::find_if_not(command.cbegin(), command.cend(), whitespace);
if (from == command.cend()) {
throw std::runtime_error("Empty command line string.");
}
results.emplace_back("");
auto to = command.cend();
while (true) {
auto& current_token = results.back();
auto current = std::find_if(from, to, any);
std::copy(from, current, std::back_inserter(current_token));
// If at the end, stop searching
if (current == to) {
break;
}
if (*current == '"' || *current == '\'') {
from = std::next(current);
auto closing = std::find_if(std::next(current), to, [&](char c) { return c == *current; });
if (closing == to) {
throw std::runtime_error(std::string("Unmatched ") + *current);
}
std::copy(std::next(current), closing, std::back_inserter(current_token));
from = std::next(closing);
} else {
// it's a whitespace
from = std::find_if_not(std::next(current), to, whitespace);
if (from == to) {
break;
}
results.emplace_back("");
}
if (from >= to) {
break;
}
}
std::string path{results[0]};
size_t last_separator_pos = path.find_last_of("/\\");
std::string_view executable_name =
(last_separator_pos == std::string::npos) ? path : std::string_view(path).substr(last_separator_pos + 1);
// Create the final required string
results[0] = std::string(executable_name);
return {path, results};
}
} // namespace everest::lib::system

View File

@@ -0,0 +1,17 @@
set(TEST_TARGET_NAME ${PROJECT_NAME}_system_tests)
add_executable(${TEST_TARGET_NAME}
system_test.cpp
)
target_link_libraries(${TEST_TARGET_NAME}
PRIVATE
GTest::gtest_main
everest::system
SDBusCpp::sdbus-c++
)
include(GoogleTest)
gtest_discover_tests(${TEST_TARGET_NAME})
ev_register_test_target(${TEST_TARGET_NAME})

View File

@@ -0,0 +1,194 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#include <everest/system/safe_system.hpp>
#include <gtest/gtest.h>
namespace {
TEST(SplitCommand, single_word) {
std::string cmd{"command"};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, multi_word) {
std::string cmd{"command and arg"};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command", "and", "arg"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, leading_and_trailing_spaces) {
std::string cmd{" leading and trailing spaces "};
std::pair<std::string, std::vector<std::string>> expected_result = {"leading",
{"leading", "and", "trailing", "spaces"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, quoted) {
std::string cmd{" \"leading\" \"and\" 'trailing' 'spaces' "};
std::pair<std::string, std::vector<std::string>> expected_result = {"leading",
{"leading", "and", "trailing", "spaces"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, quoted_whitespace) {
std::string cmd{" \"leading and\" 'trailing spaces' "};
std::pair<std::string, std::vector<std::string>> expected_result = {"leading and",
{"leading and", "trailing spaces"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, string_with_double_quotes_inside) {
std::string cmd{"echo 'A string with \"double quotes\" inside'"};
std::pair<std::string, std::vector<std::string>> expected_result = {
"echo", {"echo", "A string with \"double quotes\" inside"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, string_with_single_quotes_inside) {
std::string cmd{"echo \"A string with 'single quotes' inside\""};
std::pair<std::string, std::vector<std::string>> expected_result = {
"echo", {"echo", "A string with 'single quotes' inside"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, non_separated_double_quotes) {
std::string cmd{"command arg1\"foo\"bar arg2"};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command", "arg1foobar", "arg2"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, non_separated_single_quotes) {
std::string cmd{"command arg1'foo'bar arg2"};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command", "arg1foobar", "arg2"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, empty_double_quoted_arg) {
std::string cmd{"command \"\" arg2"};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command", "", "arg2"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, empty_single_quoted_arg) {
std::string cmd{"command \'\' arg2"};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command", "", "arg2"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, non_separated_empty_quoted) {
std::string cmd{"command arg1\'\' arg2\"\""};
std::pair<std::string, std::vector<std::string>> expected_result = {"command", {"command", "arg1", "arg2"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, real_life_case_01) {
std::string cmd{"/usr/bin/ls -l /home/user"};
std::pair<std::string, std::vector<std::string>> expected_result = {"/usr/bin/ls", {"ls", "-l", "/home/user"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, real_life_case_02) {
std::string cmd{"/usr/bin/cp \"/path with spaces/to/file.txt\" \"/another path/\""};
std::pair<std::string, std::vector<std::string>> expected_result = {
"/usr/bin/cp", {"cp", "/path with spaces/to/file.txt", "/another path/"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, real_life_case_03) {
std::string cmd{"/usr/bin/ls -l /home/user\" \""};
std::pair<std::string, std::vector<std::string>> expected_result = {"/usr/bin/ls", {"ls", "-l", "/home/user "}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, real_life_case_04) {
std::string cmd{"/usr/sbin/shutdown -r now"};
std::pair<std::string, std::vector<std::string>> expected_result = {"/usr/sbin/shutdown",
{"shutdown", "-r", "now"}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, empty) {
std::string cmd{""};
EXPECT_THROW(everest::lib::system::split_command_line(cmd), std::runtime_error);
}
TEST(SplitCommand, whitespace_only) {
std::string cmd{" "};
EXPECT_THROW(everest::lib::system::split_command_line(cmd), std::runtime_error);
}
TEST(SplitCommand, quoted_whitespace_only) {
std::string cmd{"\" \""};
std::pair<std::string, std::vector<std::string>> expected_result = {" ", {" "}};
auto result = everest::lib::system::split_command_line(cmd);
EXPECT_EQ(result, expected_result);
}
TEST(SplitCommand, literal_backslash) {
std::string cmd{"ls \\\" file \\\""};
EXPECT_THROW(everest::lib::system::split_command_line(cmd), std::runtime_error);
}
TEST(SplitCommand, unmatched_quote) {
std::string cmd{"/usr/bin/ls -l /home/user\" "};
EXPECT_THROW(everest::lib::system::split_command_line(cmd), std::runtime_error);
}
} // namespace