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