1 #include "config.h" 2 3 #include "ldap_mapper_serialize.hpp" 4 5 #include <cereal/archives/binary.hpp> 6 #include <cereal/types/string.hpp> 7 #include <phosphor-logging/lg2.hpp> 8 9 #include <fstream> 10 11 // Register class version 12 // From cereal documentation; 13 // "This macro should be placed at global scope" 14 CEREAL_CLASS_VERSION(phosphor::ldap::LDAPMapperEntry, CLASS_VERSION); 15 16 namespace phosphor 17 { 18 namespace ldap 19 { 20 21 /** @brief Function required by Cereal to perform serialization. 22 * 23 * @tparam Archive - Cereal archive type (binary in this case). 24 * @param[in] archive - reference to cereal archive. 25 * @param[in] entry- const reference to LDAP mapper entry 26 * @param[in] version - Class version that enables handling a serialized data 27 * across code levels 28 */ 29 template <class Archive> 30 void save(Archive& archive, const LDAPMapperEntry& entry, 31 const std::uint32_t /*version*/) 32 { 33 archive(entry.groupName(), entry.privilege()); 34 } 35 36 /** @brief Function required by Cereal to perform deserialization. 37 * 38 * @tparam Archive - Cereal archive type (binary in our case). 39 * @param[in] archive - reference to cereal archive. 40 * @param[out] entry - LDAP mapper entry to be read 41 * @param[in] version - Class version that enables handling a serialized data 42 * across code levels 43 */ 44 template <class Archive> 45 void load(Archive& archive, LDAPMapperEntry& entry, 46 const std::uint32_t /*version*/) 47 { 48 std::string groupName{}; 49 std::string privilege{}; 50 51 archive(groupName, privilege); 52 53 entry.sdbusplus::xyz::openbmc_project::User::server::PrivilegeMapperEntry:: 54 groupName(groupName, true); 55 entry.sdbusplus::xyz::openbmc_project::User::server::PrivilegeMapperEntry:: 56 privilege(privilege, true); 57 } 58 59 fs::path serialize(const LDAPMapperEntry& entry, const fs::path& path) 60 { 61 fs::create_directories(path.parent_path()); 62 std::ofstream os(path.c_str(), std::ios::binary | std::ios::out); 63 cereal::BinaryOutputArchive oarchive(os); 64 oarchive(entry); 65 return path; 66 } 67 68 bool deserialize(const fs::path& path, LDAPMapperEntry& entry) 69 { 70 try 71 { 72 if (fs::exists(path)) 73 { 74 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary); 75 cereal::BinaryInputArchive iarchive(is); 76 iarchive(entry); 77 return true; 78 } 79 return false; 80 } 81 catch (const cereal::Exception& e) 82 { 83 lg2::error("Failed to deserialize {FILE}: {ERR}", "FILE", path, "ERR", 84 e); 85 fs::remove(path); 86 return false; 87 } 88 catch (const std::length_error& e) 89 { 90 lg2::error("Failed to deserialize {FILE}: {ERR}", "FILE", path, "ERR", 91 e); 92 fs::remove(path); 93 return false; 94 } 95 } 96 97 } // namespace ldap 98 } // namespace phosphor 99