You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
libpEpAdapter/passphrase_cache.hh

88 lines
2.9 KiB
C++

3 years ago
#pragma once
#include <list>
#include <string>
#include <chrono>
#include <mutex>
#include <functional>
3 years ago
#include <exception>
#include <pEp/message_api.h>
3 years ago
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 {
static const size_t max_len = 250 * 4;
cache_entry(const std::string& p, time_point t);
3 years ago
std::string passphrase;
time_point tp;
};
using cache = std::list<cache_entry>;
3 years ago
cache _cache;
std::string _stored;
3 years ago
std::mutex _mtx;
3 years ago
std::mutex _stored_mtx;
3 years ago
size_t _max_size;
3 years ago
duration _timeout;
cache::iterator _which;
bool first_time;
3 years ago
public:
3 years ago
struct Empty : public std::underflow_error {
Empty() : std::underflow_error("passphrase cache empty") { }
3 years ago
};
3 years ago
struct Exhausted : public std::underflow_error {
Exhausted() : std::underflow_error("out of passphrases") { }
3 years ago
};
3 years ago
3 years ago
PassphraseCache(size_t max_size=20, duration timeout = std::chrono::minutes(10));
3 years ago
~PassphraseCache() { }
PassphraseCache(const PassphraseCache& second);
3 years ago
PassphraseCache& operator=(const PassphraseCache& second);
3 years ago
// adds the passphrase to the cache, which will timeout
// returns a ptr to the passsword entry in the cache. Don't free() it!
const char *add(const std::string& passphrase);
3 years ago
// adds the stored passphrase to the cache, which will not timeout
const char *add_stored(const std::string& passphrase);
// call this function inside the messageToSend() implementation of the adapter
// this function is using latest_passphrase() to test one passphrase after the
// other until the cache is exhausted
// call with reset = true to reset the iterator
static PEP_STATUS config_next_passphrase(bool reset=false, PEP_SESSION session = NULL);
3 years ago
// convenience functions
// i.e.
// status = cache.api(::encrypt_message, session, src, extra, dst, enc_format, flags)
// will call
// status = ::encrypt_message(session, src, extra, dst, enc_format, flags)
// using for_each_passphrase()
template<typename... A> PEP_STATUS api(PEP_STATUS f(PEP_SESSION, A...),
PEP_SESSION session, A... a);
3 years ago
static const char *latest_passphrase(PassphraseCache& _cache);
using passphrase_callee = std::function<bool(std::string)>;
bool for_each_passphrase(const passphrase_callee& callee);
PEP_STATUS ensure_passphrase(PEP_SESSION session, std::string fpr);
3 years ago
3 years ago
protected:
void cleanup();
void refresh(cache::iterator entry);
3 years ago
};
extern PassphraseCache passphrase_cache;
3 years ago
};
#include "passphrase_cache.hxx"