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.
lokinet/llarp/nodedb.cpp

160 lines
2.7 KiB
C++

6 years ago
#include <llarp/nodedb.h>
#include <llarp/router_contact.h>
#include <fstream>
6 years ago
#include <map>
#include "buffer.hpp"
6 years ago
#include "crypto.hpp"
#include "fs.hpp"
6 years ago
#include "mem.hpp"
6 years ago
static const char skiplist_subdirs[] = "0123456789ABCDEF";
struct llarp_nodedb
{
llarp_nodedb(llarp_crypto *c) : crypto(c)
{
}
6 years ago
llarp_crypto *crypto;
std::map< llarp::pubkey, llarp_rc * > entries;
6 years ago
void
Clear()
6 years ago
{
auto itr = entries.begin();
while(itr != entries.end())
{
delete itr->second;
6 years ago
itr = entries.erase(itr);
}
}
ssize_t
Load(const fs::path &path)
{
6 years ago
std::error_code ec;
if(!fs::exists(path, ec))
{
6 years ago
return -1;
}
ssize_t loaded = 0;
6 years ago
for(const char &ch : skiplist_subdirs)
{
6 years ago
std::string p;
p += ch;
fs::path sub = path / p;
for(auto &f : fs::directory_iterator(sub))
{
6 years ago
ssize_t l = loadSubdir(f);
if(l > 0)
loaded += l;
6 years ago
}
}
return loaded;
}
bool
loadfile(const fs::path &fpath)
{
std::ifstream f(fpath, std::ios::binary);
if(!f.is_open())
return false;
byte_t tmp[MAX_RC_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
f.seekg(0, std::ios::end);
size_t sz = f.tellg();
f.seekg(0, std::ios::beg);
if(sz > buf.sz)
6 years ago
return false;
// TODO: error checking
f.read((char *)buf.base, sz);
buf.sz = sz;
llarp_rc *rc = new llarp_rc;
llarp::Zero(rc, sizeof(llarp_rc));
if(llarp_rc_bdecode(rc, &buf))
{
if(llarp_rc_verify_sig(crypto, rc))
{
6 years ago
llarp::pubkey pk;
memcpy(pk.data(), rc->pubkey, pk.size());
entries[pk] = rc;
return true;
}
}
llarp_rc_free(rc);
delete rc;
6 years ago
return false;
}
6 years ago
ssize_t
loadSubdir(const fs::path &dir)
{
6 years ago
ssize_t sz = 0;
for(auto &path : fs::directory_iterator(dir))
{
if(loadfile(path))
sz++;
6 years ago
}
return sz;
}
};
extern "C" {
struct llarp_nodedb *
llarp_nodedb_new(struct llarp_crypto *crypto)
{
return new llarp_nodedb(crypto);
6 years ago
}
6 years ago
void
llarp_nodedb_free(struct llarp_nodedb **n)
{
if(*n)
6 years ago
{
auto i = *n;
*n = nullptr;
i->Clear();
delete i;
6 years ago
}
6 years ago
}
6 years ago
bool
llarp_nodedb_ensure_dir(const char *dir)
{
6 years ago
fs::path path(dir);
std::error_code ec;
if(!fs::exists(dir, ec))
fs::create_directories(path, ec);
6 years ago
if(ec)
return false;
6 years ago
if(!fs::is_directory(path))
return false;
6 years ago
for(const char &ch : skiplist_subdirs)
{
6 years ago
std::string p;
p += ch;
fs::path sub = path / p;
6 years ago
fs::create_directory(sub, ec);
if(ec)
return false;
6 years ago
}
6 years ago
return true;
}
ssize_t
llarp_nodedb_load_dir(struct llarp_nodedb *n, const char *dir)
{
6 years ago
return n->Load(dir);
}
6 years ago
}