Implement code to move old key files out of the way

pull/921/head
Stephen Shelton 5 years ago
parent db56e17c23
commit 7084dae79a

@ -15,12 +15,33 @@ namespace llarp
bool
KeyManager::initializeFromDisk(bool genIfAbsent)
{
// TODO:
// 1) start with the RouterContact file. We can detect the version from
// this and decide whether or not the existing keys need updating.
// 2) Backup existing files if necessary
// 3) Write new files if necessary
// 4) Load files to be obtained later
RouterContact rc;
if (!rc.Read(m_rcPath.c_str()))
{
LogWarn("Could not read RouterContact at path ", m_rcPath);
return false;
}
if (rc.keyfileVersion < LLARP_KEYFILE_VERSION) {
if (! genIfAbsent) {
LogError("Our RouterContact", m_rcPath, "is out of date");
} else {
LogWarn("Our RouterContact", m_rcPath,
"is out of date, backing up and regenerating private keys");
if (! backupKeyFilesByMoving()) {
LogError("Could not mv some key files, please ensure key files"
" are backed up if needed and remove");
return false;
}
// TODO: generate files
}
}
// TODO: load files
return true;
}
@ -48,4 +69,47 @@ namespace llarp
return true;
}
bool
KeyManager::backupKeyFilesByMoving() const
{
auto findFreeBackupFilename = [](const fs::path& filepath) {
for (int i=0; i<9; i++)
{
std::string ext("." + std::to_string(i) + ".bak");
fs::path newPath = filepath;
newPath += ext;
if (not fs::exists(newPath))
return newPath;
}
return fs::path();
};
std::vector<std::string> files = {
m_rcPath,
m_idKeyPath,
m_encKeyPath,
m_transportKeyPath
};
for (auto& filepath : files)
{
fs::path newFilepath = findFreeBackupFilename(filepath);
if (newFilepath.empty())
{
LogWarn("Could not find an appropriate backup filename for", filepath);
return false;
}
LogInfo("Backing up (moving) key file", filepath, "to", newFilepath, "...");
std::error_code ec;
fs::rename(filepath, newFilepath, ec);
if (ec) {
LogError("Failed to move key file", ec.message());
return false;
}
}
}
} // namespace llarp

@ -67,10 +67,13 @@ namespace llarp
private:
std::string m_rcPath;
std::string m_snKeyPath;
std::string m_idKeyPath;
std::string m_encKeyPath;
std::string m_transportKeyPath;
/// Backup each key file (by copying, e.g. foo -> foo.bak)
bool
backupKeyFilesByMoving() const;
};
} // namespace llarp

Loading…
Cancel
Save