| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "sysfswriter.h" |
| 5 | |
| 6 | #include "common/fileutils.h" |
| 7 | #include <exception> |
| 8 | #include <fstream> |
| 9 | #include <spdlog/spdlog.h> |
| 10 | |
| 11 | void SysfsWriter::write(std::filesystem::path const &sysfsEntry, |
| 12 | std::string const &value) |
| 13 | { |
| 14 | if (!Utils::File::isFilePathValid(sysfsEntry)) { |
| 15 | SPDLOG_DEBUG("Invalid file path {}", sysfsEntry.c_str()); |
| 16 | return; |
| 17 | } |
| 18 | |
| 19 | if (!isSysfsPath(sysfsEntry)) { |
| 20 | SPDLOG_DEBUG("{} is not a sysfs path. Value {} wont be written.", |
| 21 | sysfsEntry.c_str(), value); |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | std::ofstream file(sysfsEntry); |
| 26 | if (!file.is_open()) { |
| 27 | SPDLOG_DEBUG("Cannot write {} to file {}", value, sysfsEntry.c_str()); |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | file << value << std::endl; |
| 32 | } |
| 33 | |
| 34 | bool SysfsWriter::isSysfsPath(std::filesystem::path const &path) const |
| 35 | { |
| 36 | try { |
| 37 | // check whether canonical path starts with '/sys' |
| 38 | return std::filesystem::canonical(path).string().compare( |
| 39 | 0, sysfsPath.length(), sysfsPath) == 0; |
| 40 | } |
| 41 | catch (std::exception const &e) { |
| 42 | SPDLOG_DEBUG(e.what()); |
| 43 | } |
| 44 | return false; |
| 45 | } |