From dc679ab41fbacd8847227653eea520e24c9c7dcc Mon Sep 17 00:00:00 2001 From: Volker Birk Date: Thu, 25 Jun 2020 20:26:56 +0200 Subject: [PATCH] passphrase cache --- .hgignore | 1 + passphrase_cache.cc | 34 ++++++++++++++++++++++++++++++++++ passphrase_cache.hh | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 passphrase_cache.cc create mode 100644 passphrase_cache.hh diff --git a/.hgignore b/.hgignore index ea86dde..e5cac49 100644 --- a/.hgignore +++ b/.hgignore @@ -1,6 +1,7 @@ syntax: glob *.o *.a +*.d *.swp ws test_adapter diff --git a/passphrase_cache.cc b/passphrase_cache.cc new file mode 100644 index 0000000..e91a3ca --- /dev/null +++ b/passphrase_cache.cc @@ -0,0 +1,34 @@ +#include "passphrase_cache.hh" + +namespace pEp { + void PassphraseCache::add(std::string passphrase) + { + std::lock_guard lock(_mtx); + cleanup(); + _cache.push_back({passphrase, clock::now()}); + } + + bool PassphraseCache::for_each_passphrase(passphrase_callee& callee) + { + std::lock_guard lock(_mtx); + cleanup(); + + for (auto entry : _cache) { + if (callee(entry.passphrase)) + return true; + } + + return false; + } + + void PassphraseCache::cleanup() + { + for (auto entry = _cache.begin(); entry != _cache.end(); ) { + if (entry->tp < clock::now() - _timeout) + _cache.erase(entry); + else + break; + } + } +}; + diff --git a/passphrase_cache.hh b/passphrase_cache.hh new file mode 100644 index 0000000..67749f8 --- /dev/null +++ b/passphrase_cache.hh @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace pEp { + class PassphraseCache { + using clock = std::chrono::system_clock; + using time_point = std::chrono::time_point; + using duration = clock::duration; + + struct cache_entry { + std::string passphrase; + time_point tp; + }; + + std::list _cache; + std::mutex _mtx; + duration _timeout; + + public: + PassphraseCache() : _timeout(std::chrono::minutes(10)) { } + ~PassphraseCache() { } + PassphraseCache(const PassphraseCache& second) : + _cache(second._cache), _timeout(second._timeout) { } + + // adding a passphrase to the cache, which will timeout + void add(std::string passphrase); + + // for each passphrase call the callee until it returns true for a + // matching passphrase or no passphrases are left + // returns true if a passphrase was matching, false otherwise + using passphrase_callee = std::function; + bool for_each_passphrase(passphrase_callee& callee); + + protected: + void cleanup(); + }; +}; +