passphrase cache
parent
fc145ef33c
commit
dc679ab41f
@ -0,0 +1,34 @@
|
||||
#include "passphrase_cache.hh"
|
||||
|
||||
namespace pEp {
|
||||
void PassphraseCache::add(std::string passphrase)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mtx);
|
||||
cleanup();
|
||||
_cache.push_back({passphrase, clock::now()});
|
||||
}
|
||||
|
||||
bool PassphraseCache::for_each_passphrase(passphrase_callee& callee)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <functional>
|
||||
|
||||
namespace pEp {
|
||||
class PassphraseCache {
|
||||
using clock = std::chrono::system_clock;
|
||||
using time_point = std::chrono::time_point<clock>;
|
||||
using duration = clock::duration;
|
||||
|
||||
struct cache_entry {
|
||||
std::string passphrase;
|
||||
time_point tp;
|
||||
};
|
||||
|
||||
std::list<cache_entry> _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(std::string)>;
|
||||
bool for_each_passphrase(passphrase_callee& callee);
|
||||
|
||||
protected:
|
||||
void cleanup();
|
||||
};
|
||||
};
|
||||
|
Loading…
Reference in New Issue