summaryrefslogtreecommitdiff
path: root/ext4_utils/unencrypted_properties.h
blob: 80f41df426b28ac88bce61522d4615e02369cb40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <string>
#include <fstream>

// key names for properties we use
namespace properties {
    extern const char* key;
    extern const char* ref;
    extern const char* type;
    extern const char* password;
}

/**
 * Class to store data on the unencrypted folder of a device.
 * Note that the folder must exist before this class is constructed.
 * All names must be valid single level (no '/') file or directory names
 * Data is organized hierarchically so we can get a child folder
 */
class UnencryptedProperties
{
public:
    // Opens properties folder on named device.
    // If folder does not exist, construction will succeed, but all
    // getters will return default properties and setters will fail.
    UnencryptedProperties(const char* device);

    // Get named object. Return default if object does not exist or error.
    template<typename t> t Get(const char* name, t default_value = t());

    // Set named object. Return true if success, false otherwise
    template<typename t> bool Set(const char* name, t const& value);

    // Get child properties
    UnencryptedProperties GetChild(const char* name);

    // Remove named object
    bool Remove(const char* name);

    // Get path of folder
    std::string const& GetPath() const {return folder_;}
private:
    UnencryptedProperties();
    bool OK() const;
    std::string folder_;
};


template<typename t> t UnencryptedProperties::Get(const char* name,
                                                  t default_value)
{
    if (!OK()) return default_value;
    t value = default_value;
    std::ifstream(folder_ + "/" + name) >> value;
    return value;
}

template<typename t> bool UnencryptedProperties::Set(const char* name,
                                                     t const& value)
{
    if (!OK()) return false;
    std::ofstream o(folder_ + "/" + name);
    o << value;
    return !o.fail();
}

// Specialized getters/setters for strings
template<> std::string UnencryptedProperties::Get(const char* name,
                                      std::string default_value);

template<> bool UnencryptedProperties::Set(const char* name,
                                           std::string const& value);