neocomm/src/node.cpp

114 lines
2.8 KiB
C++
Raw Normal View History

2018-03-30 11:11:29 +00:00
/*
* Copyright (C) 2018 Ortega Froysa, Nicolás <nortega@themusicinnoise.net>
* Author: Ortega Froysa, Nicolás <nortega@themusicinnoise.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "neocomm/node.hpp"
2018-04-01 14:29:40 +00:00
#include <iostream>
#include <fstream>
#include <stdexcept>
2018-03-30 11:11:29 +00:00
neocomm::node::node(unsigned short port) {
2018-04-01 14:29:40 +00:00
#ifdef WOE32
gnutls_global_init();
#endif
try {
dht_node.run(port,
dht::crypto::generateIdentity(), true);
}
catch(const std::exception &e)
{
// rethrow exception
throw e;
}
}
neocomm::node::node(const std::string &node_file,
unsigned short port) {
#ifdef WOE32
gnutls_global_init();
#endif
try {
dht_node.run(port,
dht::crypto::generateIdentity(), true);
}
catch(const std::exception &e)
{
// rethrow exception
throw e;
}
import_nodes(node_file);
2018-03-30 11:11:29 +00:00
}
neocomm::node::~node() {
dht_node.join();
2018-04-01 14:29:40 +00:00
#ifdef WOE32
gnutls_global_deinit();
#endif
}
void neocomm::node::connect(const std::string &address,
unsigned short port) {
if(not dht_node.isRunning())
throw std::runtime_error("Node is not yet running.");
dht_node.bootstrap(address, std::to_string(port));
}
void neocomm::node::import_nodes(
const std::string &node_file) {
if(not dht_node.isRunning())
throw std::runtime_error("Node is not yet running.");
msgpack::unpacker upak;
{
std::ifstream import_file(node_file, std::ios::binary
bitor std::ios::ate);
if(not import_file.is_open())
{
throw std::runtime_error("Failed to open file " +
node_file);
}
auto file_size = import_file.tellg();
import_file.seekg(0, std::ios::beg);
upak.reserve_buffer(file_size);
import_file.read(upak.buffer(), file_size);
}
msgpack::object_handle obj_handler;
while(upak.next(obj_handler))
{
auto imported_nodes =
obj_handler.get().as<
std::vector<dht::NodeExport>>();
dht_node.bootstrap(imported_nodes);
}
}
void neocomm::node::export_nodes(
const std::string &node_file) {
if(not dht_node.isRunning())
throw std::runtime_error("Node is not yet running.");
std::ofstream export_file(node_file, std::ios::binary);
if(not export_file.is_open())
{
throw std::runtime_error("Failed to open file " +
node_file);
}
msgpack::pack(export_file, dht_node.exportNodes());
2018-03-30 11:11:29 +00:00
}