WIP: Progress toward Link support with example app

This commit is contained in:
Chad Attermann committed 2025-08-23 14:12:13 -06:00
1 parent 11155b5829
commit c3edde10e9
44 files changed
+1608 -939

No files matched your search

+3 -2
View File
@@ -39,9 +39,10 @@ Instructions for command line builds and building of individual example applicat
- [x] Implement Packet proofs
- [x] Successful testing of Transport of both Packets and Links
- [x] Implement memory management appropriate for memory constricted MCUs
- [ ] Implement Link, Resource
- [x] Implement Link
- [ ] Implement Resource
- [ ] Implement Channel and Buffer
- [ ] Add example applications utilizing the C++ API
- [x] Add example applications utilizing the C++ API
- [x] Configure PlatformIO to easily build and upload test applications to board
- [x] Add build tagets for all boards currently supported by RNode
- [ ] Implement new combination caching/storage manager for managing persistent data
@@ -27,6 +27,7 @@ LoRaInterface::LoRaInterface(const char* name /*= "LoRaInterface"*/) : RNS::Inte
_OUT = true;
//p self.bitrate = self.r_sf * ( (4.0/self.r_cr) / (math.pow(2,self.r_sf)/(self.r_bandwidth/1000)) ) * 1000
_bitrate = (double)spreading * ( (4.0/coding) / (pow(2, spreading)/(bandwidth/1000.0)) ) * 1000.0;
_HW_MTU = 508;
}
@@ -32,9 +32,9 @@ public:
LoRaInterface(const char* name = "LoRaInterface");
virtual ~LoRaInterface();
bool start();
void stop();
void loop();
virtual bool start();
virtual void stop();
virtual void loop();
//virtual inline std::string toString() const { return "LoRaInterface[" + name() + "]"; }
@@ -43,7 +43,6 @@ private:
void on_incoming(const RNS::Bytes& data);
private:
const uint16_t HW_MTU = 508;
//uint8_t buffer[Type::Reticulum::MTU] = {0};
const uint8_t message_count = 0;
RNS::Bytes buffer;
@@ -36,6 +36,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
_IN = true;
_OUT = true;
_bitrate = BITRATE_GUESS;
_HW_MTU = 1064;
}
@@ -155,7 +156,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
_remote_address = remote_addr.s_addr;
}
// open udp socket
// create udp socket
TRACE("Opening UDP socket");
_socket = socket( PF_INET, SOCK_DGRAM, 0 );
if (_socket < 0) {
@@ -167,7 +168,14 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
int broadcast = 1;
setsockopt(_socket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
// bind to udp socket for listening
// enable ip/port sharing
int reuse = 1;
setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
#ifdef SO_REUSEPORT
setsockopt(_socket, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse));
#endif
// bind to interface for listening
INFO("Binding UDP socket " + std::to_string(_socket) + " to " + std::string(_local_host) + ":" + std::to_string(_local_port));
sockaddr_in bind_addr;
bind_addr.sin_family = AF_INET;
@@ -44,7 +44,6 @@ protected:
void on_incoming(const RNS::Bytes& data);
private:
const uint16_t HW_MTU = 1064;
//uint8_t buffer[Type::Reticulum::MTU] = {0};
RNS::Bytes _buffer;
@@ -1,49 +1,10 @@
#include "FileSystem.h"
#include "UniversalFileSystem.h"
#include <Utilities/OS.h>
#include <Log.h>
bool FileSystem::init() {
TRACE("FileSystem initializing...");
#ifdef ARDUINO
#ifdef BOARD_ESP32
// Setup FileSystem
INFO("SPIFFS mounting FileSystem");
if (!SPIFFS.begin(true, "")){
ERROR("SPIFFS FileSystem mount failed");
return false;
}
uint32_t size = SPIFFS.totalBytes() / (1024 * 1024);
Serial.print("size: ");
Serial.print(size);
Serial.println(" MB");
uint32_t used = SPIFFS.usedBytes() / (1024 * 1024);
Serial.print("used: ");
Serial.print(used);
Serial.println(" MB");
// ensure FileSystem is writable and format if not
RNS::Bytes test("test");
if (write_file("/test", test) < 4) {
INFO("SPIFFS FileSystem is being formatted, please wait...");
SPIFFS.format();
}
else {
remove_file("/test");
}
DEBUG("SPIFFS FileSystem is ready");
#elif BOARD_NRF52
// Initialize Internal File System
INFO("InternalFS mounting FileSystem");
InternalFS.begin();
INFO("InternalFS FileSystem is ready");
#endif
#endif
return true;
}
#ifdef ARDUINO
void FileSystem::listDir(const char* dir) {
void UniversalFileSystem::listDir(const char* dir) {
Serial.print("DIR: ");
Serial.println(dir);
#ifdef BOARD_ESP32
@@ -87,11 +48,50 @@ void FileSystem::listDir(const char* dir) {
#endif
}
#else
void FileSystem::listDir(const char* dir) {
void UniversalFileSystem::listDir(const char* dir) {
}
#endif
/*virtual*/ bool FileSystem::file_exists(const char* file_path) {
/*virtual*/ bool UniversalFileSystem::init() {
TRACE("UniversalFileSystem initializing...");
#ifdef ARDUINO
#ifdef BOARD_ESP32
// Setup FileSystem
INFO("SPIFFS mounting FileSystem");
if (!SPIFFS.begin(true, "")){
ERROR("SPIFFS FileSystem mount failed");
return false;
}
uint32_t size = SPIFFS.totalBytes() / (1024 * 1024);
Serial.print("size: ");
Serial.print(size);
Serial.println(" MB");
uint32_t used = SPIFFS.usedBytes() / (1024 * 1024);
Serial.print("used: ");
Serial.print(used);
Serial.println(" MB");
// ensure FileSystem is writable and format if not
RNS::Bytes test("test");
if (write_file("/test", test) < 4) {
INFO("SPIFFS FileSystem is being formatted, please wait...");
SPIFFS.format();
}
else {
remove_file("/test");
}
DEBUG("SPIFFS FileSystem is ready");
#elif BOARD_NRF52
// Initialize Internal File System
INFO("InternalFS mounting FileSystem");
InternalFS.begin();
INFO("InternalFS FileSystem is ready");
#endif
#endif
return true;
}
/*virtual*/ bool UniversalFileSystem::file_exists(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
@@ -126,7 +126,7 @@ void FileSystem::listDir(const char* dir) {
}
}
/*virtual*/ size_t FileSystem::read_file(const char* file_path, RNS::Bytes& data) {
/*virtual*/ size_t UniversalFileSystem::read_file(const char* file_path, RNS::Bytes& data) {
size_t read = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
@@ -178,7 +178,7 @@ void FileSystem::listDir(const char* dir) {
return read;
}
/*virtual*/ size_t FileSystem::write_file(const char* file_path, const RNS::Bytes& data) {
/*virtual*/ size_t UniversalFileSystem::write_file(const char* file_path, const RNS::Bytes& data) {
// CBA TODO Replace remove with working truncation
remove_file(file_path);
size_t wrote = 0;
@@ -223,7 +223,7 @@ void FileSystem::listDir(const char* dir) {
return wrote;
}
/*virtual*/ RNS::FileStream FileSystem::open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
/*virtual*/ RNS::FileStream UniversalFileSystem::open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
TRACEF("open_file: opening file %s", file_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
@@ -251,7 +251,7 @@ void FileSystem::listDir(const char* dir) {
return {RNS::Type::NONE};
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
return RNS::FileStream(new UniversalFileStream(file));
#elif BOARD_NRF52
//File file = File(InternalFS);
File* file = new File(InternalFS);
@@ -285,7 +285,7 @@ void FileSystem::listDir(const char* dir) {
// file->truncate(0);
//}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
return RNS::FileStream(new UniversalFileStream(file));
#else
#warning("unsuppoprted");
return RNS::FileStream(RNS::Type::NONE);
@@ -313,11 +313,11 @@ void FileSystem::listDir(const char* dir) {
return {RNS::Type::NONE};
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
return RNS::FileStream(new UniversalFileStream(file));
#endif
}
/*virtual*/ bool FileSystem::remove_file(const char* file_path) {
/*virtual*/ bool UniversalFileSystem::remove_file(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.remove(file_path);
@@ -332,7 +332,7 @@ void FileSystem::listDir(const char* dir) {
#endif
}
/*virtual*/ bool FileSystem::rename_file(const char* from_file_path, const char* to_file_path) {
/*virtual*/ bool UniversalFileSystem::rename_file(const char* from_file_path, const char* to_file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.rename(from_file_path, to_file_path);
@@ -347,7 +347,7 @@ void FileSystem::listDir(const char* dir) {
#endif
}
/*virtua*/ bool FileSystem::directory_exists(const char* directory_path) {
/*virtua*/ bool UniversalFileSystem::directory_exists(const char* directory_path) {
TRACE("directory_exists: checking for existence of directory " + std::string(directory_path));
#ifdef ARDUINO
#ifdef BOARD_ESP32
@@ -378,7 +378,7 @@ void FileSystem::listDir(const char* dir) {
#endif
}
/*virtual*/ bool FileSystem::create_directory(const char* directory_path) {
/*virtual*/ bool UniversalFileSystem::create_directory(const char* directory_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
if (!SPIFFS.mkdir(directory_path)) {
@@ -405,7 +405,7 @@ void FileSystem::listDir(const char* dir) {
#endif
}
/*virtua*/ bool FileSystem::remove_directory(const char* directory_path) {
/*virtua*/ bool UniversalFileSystem::remove_directory(const char* directory_path) {
TRACE("remove_directory: removing directory " + std::string(directory_path));
#ifdef ARDUINO
#ifdef BOARD_ESP32
@@ -430,7 +430,7 @@ void FileSystem::listDir(const char* dir) {
#endif
}
/*virtua*/ std::list<std::string> FileSystem::list_directory(const char* directory_path) {
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path) {
TRACE("list_directory: listing directory " + std::string(directory_path));
std::list<std::string> files;
#ifdef ARDUINO
@@ -467,11 +467,11 @@ void FileSystem::listDir(const char* dir) {
#ifdef BOARD_ESP32
/*virtual*/ size_t FileSystem::storage_size() {
/*virtual*/ size_t UniversalFileSystem::storage_size() {
return SPIFFS.totalBytes();
}
/*virtual*/ size_t FileSystem::storage_available() {
/*virtual*/ size_t UniversalFileSystem::storage_available() {
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
}
@@ -500,12 +500,12 @@ static int usedBytes() {
return config->block_size * usedBlockCount;
}
/*virtual*/ size_t FileSystem::storage_size() {
/*virtual*/ size_t UniversalFileSystem::storage_size() {
//return totalBytes();
return InternalFS.totalBytes();
}
/*virtual*/ size_t FileSystem::storage_available() {
/*virtual*/ size_t UniversalFileSystem::storage_available() {
//return (totalBytes() - usedBytes());
return (InternalFS.totalBytes() - InternalFS.usedBytes());
}
@@ -514,11 +514,11 @@ static int usedBytes() {
#else
/*virtual*/ size_t FileSystem::storage_size() {
/*virtual*/ size_t UniversalFileSystem::storage_size() {
return 0;
}
/*virtual*/ size_t FileSystem::storage_available() {
/*virtual*/ size_t UniversalFileSystem::storage_available() {
return 0;
}
@@ -22,17 +22,16 @@ using namespace Adafruit_LittleFS_Namespace;
#include <unistd.h>
#endif
class FileSystem : public RNS::FileSystemImpl {
class UniversalFileSystem : public RNS::FileSystemImpl {
public:
FileSystem() {}
bool init();
UniversalFileSystem() {}
public:
static void listDir(const char* dir);
public:
virtual bool init();
virtual bool file_exists(const char* file_path);
virtual size_t read_file(const char* file_path, RNS::Bytes& data);
virtual size_t write_file(const char* file_path, const RNS::Bytes& data);
@@ -49,15 +48,15 @@ public:
protected:
#if defined(BOARD_ESP32) || defined(BOARD_NRF52)
class FileStreamImpl : public RNS::FileStreamImpl {
class UniversalFileStream : public RNS::FileStreamImpl {
private:
std::unique_ptr<File> _file;
bool _closed = false;
public:
FileStreamImpl(File* file) : RNS::FileStreamImpl(), _file(file) {}
virtual ~FileStreamImpl() { if (!_closed) close(); }
UniversalFileStream(File* file) : RNS::FileStreamImpl(), _file(file) {}
virtual ~UniversalFileStream() { if (!_closed) close(); }
public:
inline virtual const char* name() { return _file->name(); }
@@ -76,7 +75,7 @@ protected:
};
#else
class FileStreamImpl : public RNS::FileStreamImpl {
class UniversalFileStream : public RNS::FileStreamImpl {
private:
FILE* _file = nullptr;
@@ -85,10 +84,10 @@ protected:
char _filename[1024];
public:
FileStreamImpl(FILE* file) : RNS::FileStreamImpl(), _file(file) {
UniversalFileStream(FILE* file) : RNS::FileStreamImpl(), _file(file) {
_available = size();
}
virtual ~FileStreamImpl() { if (!_closed) close(); }
virtual ~UniversalFileStream() { if (!_closed) close(); }
public:
inline virtual const char* name() {
+10
View File
@@ -0,0 +1,10 @@
name=common
version=0.0.1
author=Chad Attermann <attermann@gmail.com>
maintainer=Chad Attermann <attermann@gmail.com>
sentence=Boilerplate and implementations common to all examples
paragraph=Boilerplate and implementations common to all examples
category=Communication
url=
architectures=*
depends=
+5
View File
@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
+10
View File
@@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}
+67
View File
@@ -0,0 +1,67 @@
{
"files.associations": {
"__bit_reference": "cpp",
"__config": "cpp",
"__hash_table": "cpp",
"__locale": "cpp",
"__node_handle": "cpp",
"__split_buffer": "cpp",
"__threading_support": "cpp",
"__tree": "cpp",
"__verbose_abort": "cpp",
"array": "cpp",
"bitset": "cpp",
"cctype": "cpp",
"cfenv": "cpp",
"charconv": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"complex": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"execution": "cpp",
"forward_list": "cpp",
"fstream": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"list": "cpp",
"locale": "cpp",
"map": "cpp",
"mutex": "cpp",
"new": "cpp",
"optional": "cpp",
"ostream": "cpp",
"queue": "cpp",
"ratio": "cpp",
"set": "cpp",
"shared_mutex": "cpp",
"source_location": "cpp",
"sstream": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"string": "cpp",
"string_view": "cpp",
"strstream": "cpp",
"tuple": "cpp",
"typeindex": "cpp",
"typeinfo": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
"variant": "cpp",
"vector": "cpp",
"algorithm": "cpp"
}
}
+461
View File
@@ -0,0 +1,461 @@
/*
##########################################################
# This RNS example demonstrates how to set up a link to #
# a destination, and pass data back and forth over it. #
##########################################################
*/
#include <UDPInterface.h>
#include <UniversalFileSystem.h>
#include <Reticulum.h>
#include <Interface.h>
#include <Link.h>
#include <Identity.h>
#include <Destination.h>
#include <Packet.h>
#include <Transport.h>
#include <Log.h>
#include <Bytes.h>
#include <Type.h>
#include <Utilities/OS.h>
#ifdef ARDUINO
#include <Arduino.h>
#include <SPIFFS.h>
#else
#include <termios.h>
#include <fcntl.h>
#include <stdio.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <map>
#include <functional>
// Let's define an app name. We'll use this for all
// destinations we create. Since this echo example
// is part of a range of example utilities, we'll put
// them all within the app namespace "example_utilities"
#define APP_NAME "example_utilities"
/*
##########################################################
#### Server Part #########################################
##########################################################
*/
// A reference to the latest client link that connected
RNS::Link latest_client_link({RNS::Type::NONE});
void client_disconnected(RNS::Link& link) {
RNS::log("Client disconnected");
}
void server_packet_received(const RNS::Bytes& message, const RNS::Packet& packet) {
// When data is received over any active link,
// it will all be directed to the last client
// that connected.
std::string text = message.toString();
RNS::log("Received data on the link: "+text);
std::string reply_text = "I received \""+text+"\" over the link";
RNS::Bytes reply_data(reply_text);
// CBA TODO: Add Packet constructor that accepts Link but doesn't require Destination
//RNS::Packet(RNS::Type::NONE, latest_client_link, reply_data).send();
RNS::Packet(latest_client_link.link_destination(), reply_data).send();
}
// When a client establishes a link to our server
// destination, this function will be called with
// a reference to the link.
void client_connected(RNS::Link& link) {
RNS::log("Client connected");
link.set_link_closed_callback(client_disconnected);
link.set_packet_callback(server_packet_received);
latest_client_link = link;
}
void server_loop(RNS::Destination& destination) {
// Let the user know that everything is ready
RNS::log(
"Link example "+
destination.hash().toHex()+
" running, waiting for a connection."
);
RNS::log("Hit enter to manually send an announce (Ctrl-C to quit)");
// We enter a loop that runs until the users exits.
// If the user hits enter, we will announce our server
// destination on the network, which will let clients
// know how to create messages directed towards it.
while (true) {
int c;
while ((c = getchar()) != '\n' && c != EOF);
destination.announce();
RNS::log("Sent announce from "+destination.hash().toHex());
}
}
// This initialisation is executed when the users chooses
// to run as a server
void server() {
// Initialize and register filesystem
RNS::FileSystem universal_filesystem = new UniversalFileSystem();
universal_filesystem.init();
RNS::Utilities::OS::register_filesystem(universal_filesystem);
// Initialize and register interface
RNS::Interface udp_interface = new UDPInterface();
udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY);
RNS::Transport::register_interface(udp_interface);
udp_interface.start();
// Initialize and start Reticulum
RNS::Reticulum reticulum = RNS::Reticulum();
//reticulum.transport_enabled(true);
reticulum.start();
// Randomly create a new identity for our link example
RNS::Identity server_identity = RNS::Identity();
// We create a destination that clients can connect to. We
// want clients to create links to this destination, so we
// need to create a "single" destination type.
RNS::Destination server_destination = RNS::Destination(
server_identity,
RNS::Type::Destination::IN,
RNS::Type::Destination::SINGLE,
APP_NAME,
"linkexample"
);
// We configure a function that will get called every time
// a new client creates a link to this destination.
server_destination.set_link_established_callback(client_connected);
// Everything's ready!
// Let's Wait for client requests or user input
//server_loop(server_destination);
// Let the user know that everything is ready
RNS::log(
"Link example "+
server_destination.hash().toHex()+
" running, waiting for a connection."
);
RNS::log("Hit enter to manually send an announce (Ctrl-C to quit)");
// We enter a loop that runs until the users exits.
// If the user hits enter, we will announce our server
// destination on the network, which will let clients
// know how to create messages directed towards it.
while (true) {
reticulum.loop();
udp_interface.loop();
/*
int c;
while ((c = getchar()) != '\n' && c != EOF);
server_destination.announce();
RNS::log("Sent announce from "+destination.hash().toHex());
*/
}
}
/*
##########################################################
#### Client Part #########################################
##########################################################
*/
// A reference to the server link
RNS::Link server_link({RNS::Type::NONE});
// This function is called when a link
// has been established with the server
void link_established(RNS::Link& link) {
// We store a reference to the link
// instance for later use
server_link = link;
// Inform the user that the server is
// connected
RNS::log("Link established with server, enter some text to send, or \"quit\" to quit");
}
// When a link is closed, we'll inform the
// user, and exit the program
void link_closed(RNS::Link& link) {
if (link.teardown_reason() == RNS::Type::Link::TIMEOUT) {
RNS::log("The link timed out, exiting now");
}
else if (link.teardown_reason() == RNS::Type::Link::DESTINATION_CLOSED) {
RNS::log("The link was closed by the server, exiting now");
}
else {
RNS::log("Link closed, exiting now");
}
//RNS::Reticulum::exit_handler();
//RNS::Utilities::OS::sleep(1.5);
_exit(0);
}
// When a packet is received over the link, we
// simply print out the data.
void client_packet_received(const RNS::Bytes& message, const RNS::Packet& packet) {
std::string text = message.toString();
RNS::log("Received data on the link: "+text);
printf("> ");
fflush(stdout);
}
void client_loop() {
// Wait for the link to become active
while (!server_link) {
RNS::Utilities::OS::sleep(0.1);
}
bool should_quit = false;
while (!should_quit) {
try {
printf("> ");
char *line = NULL;
size_t size;
if (getline(&line, &size, stdin) == -1) {
//printf("No line\n");
continue;
}
std::string text(line);
// Check if we should quit the example
if (text == "quit" || text == "q" || text == "exit") {
should_quit = true;
server_link.teardown();
}
// If not, send the entered text over the link
if (text != "") {
RNS::Bytes data(text);
if (data.size() <= RNS::Type::Link::MDU) {
// CBA TODO: Add Packet constructor that accepts Link but doesn't require Destination
//RNS::Packet(RNS::Type::NONE, server_link, data).send();
RNS::Packet(server_link.link_destination(), data).send();
}
else {
RNS::log(
"Cannot send this packet, the data size of "+
std::to_string(data.size())+" bytes exceeds the link packet MDU of "+
std::to_string(RNS::Type::Link::MDU)+" bytes",
RNS::LOG_ERROR
);
}
}
}
catch (std::exception& e) {
//RNS::log("Error while sending data over the link: "+e.what());
RNS::log("Error while sending data over the link: ");
should_quit = true;
server_link.teardown();
}
}
}
// This initialisation is executed when the users chooses
// to run as a client
void client(const char* destination_hexhash) {
// We need a binary representation of the destination
// hash that was entered on the command line
RNS::Bytes destination_hash;
try {
int dest_len = (RNS::Type::Reticulum::TRUNCATED_HASHLENGTH/8)*2;
if (strlen(destination_hexhash) != dest_len) {
throw std::invalid_argument("Destination length is invalid, must be "+std::to_string(dest_len)+" hexadecimal characters ("+std::to_string(dest_len/2)+" bytes).");
}
destination_hash.assignHex(destination_hexhash);
}
catch (std::exception& e) {
RNS::log("Invalid destination entered. Check your input!", RNS::LOG_ERROR);
return;
}
// Initialize and register filesystem
RNS::FileSystem universal_filesystem = new UniversalFileSystem();
universal_filesystem.init();
RNS::Utilities::OS::register_filesystem(universal_filesystem);
// Initialize and register interface
RNS::Interface udp_interface = new UDPInterface();
udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY);
RNS::Transport::register_interface(udp_interface);
udp_interface.start();
// Initialize and start Reticulum
RNS::Reticulum reticulum = RNS::Reticulum();
//reticulum.transport_enabled(true);
reticulum.start();
// Check if we know a path to the destination
if (!RNS::Transport::has_path(destination_hash)) {
RNS::log("Destination is not yet known. Requesting path and waiting for announce to arrive...");
RNS::Transport::request_path(destination_hash);
while (!RNS::Transport::has_path(destination_hash)) {
reticulum.loop();
udp_interface.loop();
RNS::Utilities::OS::sleep(0.1);
}
}
// Recall the server identity
RNS::Identity server_identity = RNS::Identity::recall(destination_hash);
// Inform the user that we'll begin connecting
RNS::log("Establishing link with server...");
// When the server identity is known, we set
// up a destination
RNS::Destination server_destination = RNS::Destination(
server_identity,
RNS::Type::Destination::OUT,
RNS::Type::Destination::SINGLE,
APP_NAME,
"linkexample"
);
// And create a link
RNS::Link link = RNS::Link(server_destination);
// We set a callback that will get executed
// every time a packet is received over the
// link
link.set_packet_callback(client_packet_received);
// We'll also set up functions to inform the
// user when the link is established or closed
link.set_link_established_callback(link_established);
link.set_link_closed_callback(link_closed);
// Everything is set up, so let's enter a loop
// for the user to interact with the example
//client_loop();
// Wait for the link to become active
RNS::log("Waiting for link to become active...");
//while (!server_link) {
while (true) {
printf(".");
reticulum.loop();
udp_interface.loop();
RNS::Utilities::OS::sleep(0.1);
}
RNS::log("Link is active");
bool should_quit = false;
while (!should_quit) {
reticulum.loop();
udp_interface.loop();
/*
try {
printf("> ");
char *line = NULL;
size_t size;
if (getline(&line, &size, stdin) == -1) {
//printf("No line\n");
continue;
}
std::string text(line);
// Check if we should quit the example
if (text == "quit" || text == "q" || text == "exit") {
should_quit = true;
server_link.teardown();
}
// If not, send the entered text over the link
if (text != "") {
RNS::Bytes data(text);
if (data.size() <= RNS::Type::Link::MDU) {
// CBA TODO: Add Packet constructor that accepts Link but doesn't require Destination
RNS::Packet(RNS::Type::NONE, server_link, data).send();
}
else {
RNS::log(
"Cannot send this packet, the data size of "+
std::to_string(data.size())+" bytes exceeds the link packet MDU of "+
std::to_string(RNS::Type::Link::MDU)+" bytes",
RNS::LOG_ERROR
);
}
}
}
catch (std::exception& e) {
//RNS::log("Error while sending data over the link: "+e.what());
RNS::log("Error while sending data over the link: ");
should_quit = true;
server_link.teardown();
}
*/
}
}
/*
##########################################################
#### Program Startup #####################################
##########################################################
*/
// Signal handler function
void cleanup_handler(int signum) {
if (signum == SIGINT) {
printf("\nCtrl+C detected. Performing cleanup...\n");
printf("Cleanup complete. Exiting.\n");
_exit(0);
}
}
// This part of the program runs at startup,
// and parses input of from the user, and then
// starts up the desired program mode.
int main(int argc, char *argv[]) {
#if defined(MEM_LOG)
RNS::loglevel(RNS::LOG_MEM);
#else
//RNS::loglevel(RNS::LOG_NOTICE);
RNS::loglevel(RNS::LOG_TRACE);
#endif
// Register the signal handler for SIGINT
signal(SIGINT, cleanup_handler);
if (argc <= 1) {
printf("\nMust specify a destination for client mode, or \"-s\" or \"--server\" for server mode.\n\n");
return -1;
}
if (strcmp(argv[1], "--server") == 0 || strcmp(argv[1], "-s") == 0) {
server();
}
else {
client(argv[1]);
}
printf("\nLoop exited. Performing cleanup...\n");
printf("Cleanup complete. Exiting.\n");
return 0;
}
+130
View File
@@ -0,0 +1,130 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
;default_envs = native
;include_dir = ../../src
;src_dir = ../../src
include_dir = .
src_dir = .
[env]
monitor_speed = 115200
upload_speed = 921600
build_type = debug
build_flags =
-DRNS_USE_ALLOCATOR=1
-DRNS_USE_TLSF=1
;-DMEM_LOG
lib_deps =
ArduinoJson@^7.4.2
MsgPack@^0.4.2
https://github.com/attermann/Crypto.git
microReticulum=symlink://../..
common=symlink://../common
[env:native]
platform = native
monitor_port = none
build_flags =
${env.build_flags}
-std=c++11
-g3
-ggdb
-Wall
-Wextra
-Wno-missing-field-initializers
-Wno-format
-Wno-unused-parameter
-I.
-DNATIVE
lib_deps =
${env.lib_deps}
lib_extra_dirs = ../
lib_compat_mode = off
;debug_init_break =
;debug_init_break = tbreak
;debug_tool =
[env:native17]
platform = native
build_unflags = -std=gnu++11
build_flags =
${env.build_flags}
-std=c++17
-g3
-ggdb
-Wall
-Wextra
-Wno-missing-field-initializers
-Wno-format
-Wno-unused-parameter
-I.
-DNATIVE
lib_deps =
${env.lib_deps}
lib_extra_dirs = ../
lib_compat_mode = off
[env:ttgo-lora32-v21]
framework = arduino
platform = espressif32
board = ttgo-lora32-v21
upload_speed = 460800
board_build.partitions = no_ota.csv
build_flags =
${env.build_flags}
-Wall
-Wextra
-Wno-missing-field-initializers
-Wno-format
-I.
-DBOARD_ESP32
lib_deps =
${env.lib_deps}
monitor_filters = esp32_exception_decoder
[env:ttgo-t-beam]
framework = arduino
platform = espressif32
board = ttgo-t-beam
board_build.partitions = no_ota.csv
;board_build.partitions = huge_app.csv
build_flags =
${env.build_flags}
-Wall
-Wextra
-Wno-missing-field-initializers
-Wno-format
-I.
-DBOARD_ESP32
lib_deps =
${env.lib_deps}
monitor_filters = esp32_exception_decoder
[env:wiscore_rak4631]
framework = arduino
platform = nordicnrf52
board = wiscore_rak4631
board_build.partitions = no_ota.csv
board_build.FileSystem = littlefs
build_flags =
${env.build_flags}
-fexceptions
-Wall
;-Wextra
-Wno-missing-field-initializers
-Wno-format
-I.
-DBOARD_NRF52
-DRNS_USE_TLSF=1
build_unflags = -fno-exceptions
lib_deps =
${env.lib_deps}
+8 -8
View File
@@ -1,7 +1,7 @@
//#define NDEBUG
#include "LoRaInterface.h"
#include "FileSystem.h"
#include <LoRaInterface.h>
#include <UniversalFileSystem.h>
#include <Reticulum.h>
#include <Identity.h>
@@ -88,12 +88,12 @@ void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) {
RNS::Reticulum reticulum({RNS::Type::NONE});
RNS::Interface lora_interface(RNS::Type::NONE);
RNS::FileSystem test_filesystem(RNS::Type::NONE);
RNS::FileSystem universal_filesystem(RNS::Type::NONE);
RNS::Identity identity({RNS::Type::NONE});
RNS::Destination destination({RNS::Type::NONE});
LoRaInterface* lora_interface_impl = nullptr;
FileSystem* test_filesystem_impl = nullptr;
UniversalFileSystem* universal_filesystem_impl = nullptr;
//ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits");
//RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits"));
@@ -125,10 +125,10 @@ void reticulum_setup() {
HEAD("Registering FileSystem with OS...", RNS::LOG_TRACE);
test_filesystem_impl = new FileSystem();
test_filesystem = test_filesystem_impl;
((FileSystem*)test_filesystem.get())->init();
RNS::Utilities::OS::register_filesystem(test_filesystem);
universal_filesystem_impl = new UniversalFileSystem();
universal_filesystem = universal_filesystem_impl;
universal_filesystem.init();
RNS::Utilities::OS::register_filesystem(universal_filesystem);
HEAD("Registering LoRaInterface instances with Transport...", RNS::LOG_TRACE);
lora_interface_impl = new LoRaInterface();
+1
View File
@@ -31,6 +31,7 @@ lib_deps =
https://github.com/attermann/Crypto.git
https://github.com/hideakitai/MsgPack.git
microReticulum=symlink://../..
impl=symlink://../impl
[env:native]
platform = native
-525
View File
@@ -1,525 +0,0 @@
#include "FileSystem.h"
#include <Utilities/OS.h>
#include <Log.h>
bool FileSystem::init() {
TRACE("FileSystem initializing...");
#ifdef ARDUINO
#ifdef BOARD_ESP32
// Setup FileSystem
INFO("SPIFFS mounting FileSystem");
if (!SPIFFS.begin(true, "")){
ERROR("SPIFFS FileSystem mount failed");
return false;
}
uint32_t size = SPIFFS.totalBytes() / (1024 * 1024);
Serial.print("size: ");
Serial.print(size);
Serial.println(" MB");
uint32_t used = SPIFFS.usedBytes() / (1024 * 1024);
Serial.print("used: ");
Serial.print(used);
Serial.println(" MB");
// ensure FileSystem is writable and format if not
RNS::Bytes test("test");
if (write_file("/test", test) < 4) {
INFO("SPIFFS FileSystem is being formatted, please wait...");
SPIFFS.format();
}
else {
remove_file("/test");
}
DEBUG("SPIFFS FileSystem is ready");
#elif BOARD_NRF52
// Initialize Internal File System
INFO("InternalFS mounting FileSystem");
InternalFS.begin();
INFO("InternalFS FileSystem is ready");
#endif
#endif
return true;
}
#ifdef ARDUINO
void FileSystem::listDir(const char* dir) {
Serial.print("DIR: ");
Serial.println(dir);
#ifdef BOARD_ESP32
File root = SPIFFS.open(dir);
if (!root) {
Serial.println("Failed to opend directory");
return;
}
File file = root.openNextFile();
while (file) {
if (file.isDirectory()) {
Serial.print(" DIR: ");
}
else {
Serial.print(" FILE: ");
}
Serial.println(file.name());
file.close();
file = root.openNextFile();
}
root.close();
#elif BOARD_NRF52
File root = InternalFS.open(dir);
if (!root) {
Serial.println("Failed to opend directory");
return;
}
File file = root.openNextFile();
while (file) {
if (file.isDirectory()) {
Serial.print(" DIR: ");
}
else {
Serial.print(" FILE: ");
}
Serial.println(file.name());
file.close();
file = root.openNextFile();
}
root.close();
#endif
}
#else
void FileSystem::listDir(const char* dir) {
}
#endif
/*virtual*/ bool FileSystem::file_exists(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(file_path, FILE_O_READ)) {
#else
if (false) {
#endif
#else
// Native
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
#endif
//TRACE("file_exists: file exists, closing file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
file.close();
#endif
#else
// Native
fclose(file);
#endif
return true;
}
else {
ERROR("file_exists: failed to open file " + std::string(file_path));
return false;
}
}
/*virtual*/ size_t FileSystem::read_file(const char* file_path, RNS::Bytes& data) {
size_t read = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
size_t size = file.size();
read = file.readBytes((char*)data.writable(size), size);
#elif BOARD_NRF52
//File file(InternalFS);
//if (file.open(file_path, FILE_O_READ)) {
File file = InternalFS.open(file_path, FILE_O_READ);
if (file) {
size_t size = file.size();
read = file.readBytes((char*)data.writable(size), size);
#else
if (false) {
size_t size = 0;
#endif
#else
// Native
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
//size_t read = fread(data.writable(size), size, 1, file);
read = fread(data.writable(size), 1, size, file);
#endif
TRACE("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path));
if (read != size) {
ERROR("read_file: failed to read file " + std::string(file_path));
data.clear();
}
//TRACE("read_file: closing input file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
file.close();
#endif
#else
// Native
fclose(file);
#endif
}
else {
ERROR("read_file: failed to open input file " + std::string(file_path));
}
return read;
}
/*virtual*/ size_t FileSystem::write_file(const char* file_path, const RNS::Bytes& data) {
// CBA TODO Replace remove with working truncation
remove_file(file_path);
size_t wrote = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_WRITE);
if (file) {
wrote = file.write(data.data(), data.size());
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(file_path, FILE_O_WRITE)) {
wrote = file.write(data.data(), data.size());
#else
if (false) {
#endif
#else
// Native
FILE* file = fopen(file_path, "w");
if (file != nullptr) {
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
wrote = fwrite(data.data(), 1, data.size(), file);
#endif
TRACE("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path));
if (wrote < data.size()) {
WARNING("write_file: not all data was written to file " + std::string(file_path));
}
//TRACE("write_file: closing output file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
file.close();
#endif
#else
// Native
fclose(file);
#endif
}
else {
ERROR("write_file: failed to open output file " + std::string(file_path));
}
return wrote;
}
/*virtual*/ RNS::FileStream FileSystem::open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
TRACEF("open_file: opening file %s", file_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
const char* mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_READ;
}
else if (file_mode == RNS::FileStream::MODE_WRITE) {
mode = FILE_WRITE;
}
else if (file_mode == RNS::FileStream::MODE_APPEND) {
mode = FILE_APPEND;
}
else {
ERRORF("open_file: unsupported mode %d", file_mode);
return {RNS::Type::NONE};
}
TRACEF("open_file: opening file %s in mode %s", file_path, mode);
//// Using copy constructor to create a File* instead of local
//File file = SPIFFS.open(file_path, mode);
//if (!file) {
File* file = new File(SPIFFS.open(file_path, mode));
if (file == null || !(*file)) {
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#elif BOARD_NRF52
//File file = File(InternalFS);
File* file = new File(InternalFS);
int mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_O_READ;
}
else if (file_mode == RNS::FileStream::MODE_WRITE) {
mode = FILE_O_WRITE;
// CBA TODO Replace remove with working truncation
if (InternalFS.exists(file_path)) {
InternalFS.remove(file_path);
}
}
else if (file_mode == RNS::FileStream::MODE_APPEND) {
// CBA This is the default write mode for nrf52 littlefs
mode = FILE_O_WRITE;
}
else {
ERRORF("open_file: unsupported mode %d", file_mode);
return {RNS::Type::NONE};
}
if (!file->open(file_path, mode)) {
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
// Seek to beginning to overwrite (this is failing on nrf52)
//if (file_mode == RNS::FileStream::MODE_WRITE) {
// file->seek(0);
// file->truncate(0);
//}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#else
#warning("unsuppoprted");
return RNS::FileStream(RNS::Type::NONE);
#endif
#else // ARDUINO
// Native
const char* mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = "r";
}
else if (file_mode == RNS::FileStream::MODE_WRITE) {
mode = "w";
}
else if (file_mode == RNS::FileStream::MODE_APPEND) {
mode = "a";
}
else {
ERRORF("open_file: unsupported mode %d", file_mode);
return {RNS::Type::NONE};
}
TRACEF("open_file: opening file %s in mode %s", file_path, mode);
FILE* file = fopen(file_path, mode);
if (file == nullptr) {
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#endif
}
/*virtual*/ bool FileSystem::remove_file(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.remove(file_path);
#elif BOARD_NRF52
return InternalFS.remove(file_path);
#else
return false;
#endif
#else
// Native
return (remove(file_path) == 0);
#endif
}
/*virtual*/ bool FileSystem::rename_file(const char* from_file_path, const char* to_file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.rename(from_file_path, to_file_path);
#elif BOARD_NRF52
return InternalFS.rename(from_file_path, to_file_path);
#else
return false;
#endif
#else
// Native
return (rename(from_file_path, to_file_path) == 0);
#endif
}
/*virtua*/ bool FileSystem::directory_exists(const char* directory_path) {
TRACE("directory_exists: checking for existence of directory " + std::string(directory_path));
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(directory_path, FILE_READ);
if (file) {
bool is_directory = file.isDirectory();
file.close();
return is_directory;
}
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(directory_path, FILE_O_READ)) {
bool is_directory = file.isDirectory();
file.close();
return is_directory;
}
#else
if (false) {
return false;
}
#endif
else {
return false;
}
#else
// Native
return false;
#endif
}
/*virtual*/ bool FileSystem::create_directory(const char* directory_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
if (!SPIFFS.mkdir(directory_path)) {
ERROR("create_directory: failed to create directorty " + std::string(directory_path));
return false;
}
return true;
#elif BOARD_NRF52
if (!InternalFS.mkdir(directory_path)) {
ERROR("create_directory: failed to create directorty " + std::string(directory_path));
return false;
}
return true;
#else
return false;
#endif
#else
// Native
struct stat st = {0};
if (stat(directory_path, &st) == 0) {
return true;
}
return (mkdir(directory_path, 0700) == 0);
#endif
}
/*virtua*/ bool FileSystem::remove_directory(const char* directory_path) {
TRACE("remove_directory: removing directory " + std::string(directory_path));
#ifdef ARDUINO
#ifdef BOARD_ESP32
//if (!LittleFS.rmdir_r(directory_path)) {
if (!SPIFFS.rmdir(directory_path)) {
ERROR("remove_directory: failed to remove directorty " + std::string(directory_path));
return false;
}
return true;
#elif BOARD_NRF52
if (!InternalFS.rmdir_r(directory_path)) {
ERROR("remove_directory: failed to remove directory " + std::string(directory_path));
return false;
}
return true;
#else
return false;
#endif
#else
// Native
return false;
#endif
}
/*virtua*/ std::list<std::string> FileSystem::list_directory(const char* directory_path) {
TRACE("list_directory: listing directory " + std::string(directory_path));
std::list<std::string> files;
#ifdef ARDUINO
#ifdef BOARD_ESP32
File root = SPIFFS.open(directory_path);
#elif BOARD_NRF52
File root = InternalFS.open(directory_path);
#endif
if (!root) {
ERROR("list_directory: failed to open directory " + std::string(directory_path));
return files;
}
File file = root.openNextFile();
while (file) {
if (!file.isDirectory()) {
char* name = (char*)file.name();
files.push_back(name);
}
// CBA Following close required to avoid leaking memory
file.close();
file = root.openNextFile();
}
TRACE("list_directory: returning directory listing");
root.close();
return files;
#else
// Native
return files;
#endif
}
#ifdef ARDUINO
#ifdef BOARD_ESP32
/*virtual*/ size_t FileSystem::storage_size() {
return SPIFFS.totalBytes();
}
/*virtual*/ size_t FileSystem::storage_available() {
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
}
#elif BOARD_NRF52
static int _countLfsBlock(void *p, lfs_block_t block){
lfs_size_t *size = (lfs_size_t*) p;
*size += 1;
return 0;
}
static lfs_ssize_t getUsedBlockCount() {
lfs_size_t size = 0;
lfs_traverse(InternalFS._getFS(), _countLfsBlock, &size);
return size;
}
static int totalBytes() {
const lfs_config* config = InternalFS._getFS()->cfg;
return config->block_size * config->block_count;
}
static int usedBytes() {
const lfs_config* config = InternalFS._getFS()->cfg;
const int usedBlockCount = getUsedBlockCount();
return config->block_size * usedBlockCount;
}
/*virtual*/ size_t FileSystem::storage_size() {
//return totalBytes();
return InternalFS.totalBytes();
}
/*virtual*/ size_t FileSystem::storage_available() {
//return (totalBytes() - usedBytes());
return (InternalFS.totalBytes() - InternalFS.usedBytes());
}
#endif
#else
/*virtual*/ size_t FileSystem::storage_size() {
return 0;
}
/*virtual*/ size_t FileSystem::storage_available() {
return 0;
}
#endif
-184
View File
@@ -1,184 +0,0 @@
#pragma once
#include <FileSystem.h>
#include <FileStream.h>
#include <Bytes.h>
#ifdef ARDUINO
#ifdef BOARD_ESP32
//#include <FS.h>
#include <SPIFFS.h>
#elif BOARD_NRF52
//#include <Adafruit_LittleFS.h>
#include <InternalFileSystem.h>
using namespace Adafruit_LittleFS_Namespace;
#endif
#else
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
class FileSystem : public RNS::FileSystemImpl {
public:
FileSystem() {}
bool init();
public:
static void listDir(const char* dir);
public:
virtual bool file_exists(const char* file_path);
virtual size_t read_file(const char* file_path, RNS::Bytes& data);
virtual size_t write_file(const char* file_path, const RNS::Bytes& data);
virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode);
virtual bool remove_file(const char* file_path);
virtual bool rename_file(const char* from_file_path, const char* to_file_path);
virtual bool directory_exists(const char* directory_path);
virtual bool create_directory(const char* directory_path);
virtual bool remove_directory(const char* directory_path);
virtual std::list<std::string> list_directory(const char* directory_path);
virtual size_t storage_size();
virtual size_t storage_available();
protected:
#if defined(BOARD_ESP32) || defined(BOARD_NRF52)
class FileStreamImpl : public RNS::FileStreamImpl {
private:
std::unique_ptr<File> _file;
bool _closed = false;
public:
FileStreamImpl(File* file) : RNS::FileStreamImpl(), _file(file) {}
virtual ~FileStreamImpl() { if (!_closed) close(); }
public:
inline virtual const char* name() { return _file->name(); }
inline virtual size_t size() { return _file->size(); }
inline virtual void close() { _closed = true; _file->close(); }
// Print overrides
inline virtual size_t write(uint8_t byte) { return _file->write(byte); }
inline virtual size_t write(const uint8_t *buffer, size_t size) { return _file->write(buffer, size); }
// Stream overrides
inline virtual int available() { return _file->available(); }
inline virtual int read() { return _file->read(); }
inline virtual int peek() { return _file->peek(); }
inline virtual void flush() { _file->flush(); }
};
#else
class FileStreamImpl : public RNS::FileStreamImpl {
private:
FILE* _file = nullptr;
bool _closed = false;
size_t _available = 0;
char _filename[1024];
public:
FileStreamImpl(FILE* file) : RNS::FileStreamImpl(), _file(file) {
_available = size();
}
virtual ~FileStreamImpl() { if (!_closed) close(); }
public:
inline virtual const char* name() {
assert(_file);
#if 0
char proclnk[1024];
snprintf(proclnk, sizeof(proclnk), "/proc/self/fd/%d", fileno(_file));
int r = readlink(proclnk, _filename, sizeof(_filename));
if (r < 0) {
return nullptr);
}
_filename[r] = '\0';
return _filename;
#elif 0
if (fcntl(fd, F_GETPATH, _filename) < 0) {
rerturn nullptr;
}
return _filename;
#else
return nullptr;
#endif
}
inline virtual size_t size() {
assert(_file);
struct stat st;
fstat(fileno(_file), &st);
return st.st_size;
}
inline virtual void close() {
assert(_file);
_closed = true;
fclose(_file);
_file = nullptr;
}
// Print overrides
inline virtual size_t write(uint8_t byte) {
assert(_file);
int ch = fputc(byte, _file);
if (ch == EOF) {
return 0;
}
++_available;
return 1;
}
inline virtual size_t write(const uint8_t *buffer, size_t size) {
assert(_file);
size_t wrote = fwrite(buffer, sizeof(uint8_t), size, _file);
_available += wrote;
return wrote;
}
// Stream overrides
inline virtual int available() {
#if 0
assert(_file);
int size = 0;
ioctl(fileno(_file), FIONREAD, &size);
TRACEF("FileStream::available: %d", size);
return size;
#else
return _available;
#endif
}
inline virtual int read() {
if (_available <= 0) {
return EOF;
}
assert(_file);
int ch = fgetc(_file);
TRACEF("FileStream::read: %c", ch);
return ch;
}
inline virtual int peek() {
if (_available <= 0) {
return EOF;
}
assert(_file);
int ch = fgetc(_file);
ungetc(ch, _file);
TRACEF("FileStream::peek: %c", ch);
return ch;
}
inline virtual void flush() {
assert(_file);
fflush(_file);
TRACE("FileStream::flush");
}
};
#endif
};
+9 -16
View File
@@ -1,7 +1,7 @@
//#define NDEBUG
#include "UDPInterface.h"
#include "FileSystem.h"
#include <UDPInterface.h>
#include <UniversalFileSystem.h>
#include <Reticulum.h>
#include <Identity.h>
@@ -89,13 +89,10 @@ void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) {
RNS::Reticulum reticulum({RNS::Type::NONE});
RNS::Interface udp_interface(RNS::Type::NONE);
RNS::FileSystem test_filesystem(RNS::Type::NONE);
RNS::FileSystem universal_filesystem(RNS::Type::NONE);
RNS::Identity identity({RNS::Type::NONE});
RNS::Destination destination({RNS::Type::NONE});
UDPInterface* udp_interface_impl = nullptr;
FileSystem* test_filesystem_impl = nullptr;
//ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits");
//RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits"));
RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler());
@@ -125,19 +122,15 @@ void reticulum_setup() {
// 21.8% baseline here with serial
HEAD("Registering FileSystem with OS...", RNS::LOG_TRACE);
test_filesystem_impl = new FileSystem();
test_filesystem = test_filesystem_impl;
((FileSystem*)test_filesystem.get())->init();
RNS::Utilities::OS::register_filesystem(test_filesystem);
universal_filesystem = new UniversalFileSystem();
universal_filesystem.init();
RNS::Utilities::OS::register_filesystem(universal_filesystem);
HEAD("Registering UDPInterface instances with Transport...", RNS::LOG_TRACE);
udp_interface_impl = new UDPInterface();
udp_interface = udp_interface_impl;
udp_interface = new UDPInterface();
udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY);
RNS::Transport::register_interface(udp_interface);
HEAD("Starting UDPInterface...", RNS::LOG_TRACE);
udp_interface_impl->start();
udp_interface.start();
HEAD("Creating Reticulum instance...", RNS::LOG_TRACE);
//RNS::Reticulum reticulum;
@@ -299,7 +292,7 @@ void setup() {
void loop() {
reticulum.loop();
udp_interface_impl->loop();
udp_interface.loop();
#ifdef ARDUINO
/*
+1
View File
@@ -28,6 +28,7 @@ lib_deps =
https://github.com/attermann/Crypto.git
https://github.com/hideakitai/MsgPack.git
microReticulum=symlink://../..
common=symlink://../common
[env:native]
platform = native
+25
View File
@@ -150,6 +150,19 @@ void testBytesMain() {
assert(memcmp(shrink.data(), "Hello", shrink.size()) == 0);
}
// test trim
HEAD("TestBytes: trim", RNS::LOG_TRACE);
{
RNS::Bytes bytes("Hello World");
TRACE("orig: " + bytes.toString());
assert(bytes.size() == 11);
assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0);
bytes = bytes.left(5);
TRACE("trim: " + bytes.toString());
assert(bytes.size() == 5);
assert(memcmp(bytes.data(), "Hello", bytes.size()) == 0);
}
// test creating bytes from default
{
RNS::Bytes bytes;
@@ -548,6 +561,17 @@ void testConcat() {
}
void testIndex() {
HEAD("testConcat:", RNS::LOG_TRACE);
const RNS::Bytes bytes("Hello");
assert(bytes[0] == 'H');
assert(bytes[1] == 'e');
assert(bytes[2] == 'l');
assert(bytes[3] == 'l');
assert(bytes[4] == '0');
}
void testBytes() {
HEAD("Running testBytes...", RNS::LOG_TRACE);
@@ -565,6 +589,7 @@ void testBytes() {
testFind();
testCompare();
testConcat();
testIndex();
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
+2 -2
View File
@@ -58,10 +58,10 @@ void setup() {
// individiual tests
//testReference();
//testCrypto();
//testBytes();
testBytes();
//testFileSystem();
//testPersistence();
testReticulum();
//testReticulum();
//testObjects();
HEAD("All tests successful!", RNS::LOG_TRACE);
+2 -1
View File
@@ -19,7 +19,8 @@
"license": "Apache-2.0",
"homepage": "https://reticulum.network/",
"dependencies": {
"ArduinoJson": "~6.21.3"
"ArduinoJson": "~7.1.0",
"MsgPack": "~0.4.2"
},
"frameworks": "*",
"platforms": "*",
+13 -2
View File
@@ -25,9 +25,9 @@ build_flags =
-DRNS_USE_FS
-DRNS_PERSIST_PATHS
lib_deps =
ArduinoJson@^6.21.3
ArduinoJson@^7.4.2
MsgPack@^0.4.2
https://github.com/attermann/Crypto.git
https://github.com/hideakitai/MsgPack.git
[env:native]
platform = native
@@ -49,6 +49,17 @@ lib_deps =
${env.lib_deps}
lib_compat_mode = off
[env:native20]
platform = native
build_unflags = -std=gnu++11
build_flags =
${env.build_flags}
-std=c++20
-DNATIVE
lib_deps =
${env.lib_deps}
lib_compat_mode = off
[env:cubecell-gps]
platform = heltec-cubecell
board = cubecell_gps
+16 -2
View File
@@ -118,10 +118,24 @@ MEM("Creating from data-move...");
return compare(bytes) > 0;
}
inline uint8_t& operator[](size_t index) {
if (!_data || index >= _data->size()) {
throw std::out_of_range("Index out of bounds");
}
return (*_data)[index];
}
inline const uint8_t& operator[](size_t index) const {
if (!_data || index >= _data->size()) {
throw std::out_of_range("Index out of bounds");
}
return (*_data)[index];
}
inline operator bool() const {
return (_data && !_data->empty());
}
inline operator Data() const {
inline operator const Data() const {
if (!_data)
return Data();
return *_data.get();
@@ -338,7 +352,7 @@ MEM("Creating from data-move...");
};
// following array function doesn't work without size since it's past as a pointer to the array sizeof() is of the pointer
// following array function doesn't work without size since it's passed as a pointer to the array so sizeof() is of the pointer
//inline Bytes bytesFromArray(const uint8_t arr[]) { return Bytes(arr, sizeof(arr)); }
//inline Bytes bytesFromChunk(const uint8_t* ptr, size_t len) { return Bytes(ptr, len); }
inline Bytes bytesFromChunk(const uint8_t* ptr, size_t len) { return {ptr, len}; }
+39
View File
@@ -47,4 +47,43 @@ namespace RNS { namespace Cryptography {
};
class AES_256_CBC {
public:
static inline const Bytes encrypt(const Bytes& plaintext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
Bytes ciphertext;
cbc.encrypt(ciphertext.writable(plaintext.size()), plaintext.data(), plaintext.size());
return ciphertext;
}
static inline const Bytes decrypt(const Bytes& ciphertext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
Bytes plaintext;
cbc.decrypt(plaintext.writable(ciphertext.size()), ciphertext.data(), ciphertext.size());
return plaintext;
}
// EXPERIMENTAL - overwrites passed buffer
static inline void inplace_encrypt(Bytes& plaintext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
cbc.encrypt((uint8_t*)plaintext.data(), plaintext.data(), plaintext.size());
}
// EXPERIMENTAL - overwrites passed buffer
static inline void inplace_decrypt(Bytes& ciphertext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
cbc.decrypt((uint8_t*)ciphertext.data(), ciphertext.data(), ciphertext.size());
}
};
} }
-2
View File
@@ -19,8 +19,6 @@ namespace RNS { namespace Cryptography {
class Fernet {
public:
static const uint8_t FERNET_OVERHEAD = 48; // Bytes
using Ptr = std::shared_ptr<Fernet>;
public:
+162
View File
@@ -0,0 +1,162 @@
#include "Token.h"
#include "HMAC.h"
#include "PKCS7.h"
#include "AES.h"
#include "../Log.h"
#include <stdexcept>
#include <time.h>
using namespace RNS;
using namespace RNS::Cryptography;
using namespace RNS::Type::Cryptography::Token;
Token::Token(const Bytes& key, token_mode mode /*= AES*/) {
if (!key) {
throw std::invalid_argument("Token key cannot be None");
}
if (key.size() != 32) {
throw std::invalid_argument("Token key must be 32 bytes, not " + std::to_string(key.size()));
}
if (mode == MODE_AES) {
if (key.size() == 32) {
_mode = MODE_AES_128_CBC;
//p self._signing_key = key[:16]
_signing_key = key.left(16);
//p self._encryption_key = key[16:]
_encryption_key = key.mid(16);
}
else if (key.size() == 64) {
_mode = MODE_AES_256_CBC;
//p self._signing_key = key[:32]
_signing_key = key.left(32);
//p self._encryption_key = key[32:]
_encryption_key = key.mid(32);
}
else {
throw std::invalid_argument("Token key must be 32 bytes, not " + std::to_string(key.size()));
}
}
else {
throw std::invalid_argument("Invalid token mode: " + std::to_string(mode));
}
MEM("Token object created");
}
Token::~Token() {
MEM("Token object destroyed");
}
bool Token::verify_hmac(const Bytes& token) {
if (token.size() <= 32) {
throw std::invalid_argument("Cannot verify HMAC on token of only " + std::to_string(token.size()) + " bytes");
}
//received_hmac = token[-32:]
Bytes received_hmac = token.right(32);
DEBUG("Token::verify_hmac: received_hmac: " + received_hmac.toHex());
//expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
Bytes expected_hmac = HMAC::generate(_signing_key, token.left(token.size()-32))->digest();
DEBUG("Token::verify_hmac: expected_hmac: " + expected_hmac.toHex());
return (received_hmac == expected_hmac);
}
const Bytes Token::encrypt(const Bytes& data) {
DEBUG("Token::encrypt: plaintext length: " + std::to_string(data.size()));
Bytes iv = random(16);
//double current_time = OS::time();
TRACE("Token::encrypt: iv: " + iv.toHex());
TRACE("Token::encrypt: plaintext: " + data.toHex());
Bytes ciphertext;
if (_mode == MODE_AES_128_CBC) {
ciphertext = AES_128_CBC::encrypt(
PKCS7::pad(data),
_encryption_key,
iv
);
}
else if (_mode == MODE_AES_256_CBC) {
ciphertext = AES_256_CBC::encrypt(
PKCS7::pad(data),
_encryption_key,
iv
);
}
else {
throw new std::invalid_argument("Invalid token mode "+std::to_string(_mode));
}
DEBUG("Token::encrypt: padded ciphertext length: " + std::to_string(ciphertext.size()));
TRACE("Token::encrypt: ciphertext: " + ciphertext.toHex());
Bytes signed_parts = iv + ciphertext;
//return signed_parts + HMAC::generate(_signing_key, signed_parts)->digest();
Bytes sig(HMAC::generate(_signing_key, signed_parts)->digest());
TRACE("Token::encrypt: sig: " + sig.toHex());
Bytes token(signed_parts + sig);
DEBUG("Token::encrypt: token length: " + std::to_string(token.size()));
return token;
}
const Bytes Token::decrypt(const Bytes& token) {
DEBUG("Token::decrypt: token length: " + std::to_string(token.size()));
if (token.size() < 48) {
throw std::invalid_argument("Cannot decrypt token of only " + std::to_string(token.size()) + " bytes");
}
if (!verify_hmac(token)) {
throw std::invalid_argument("Token token HMAC was invalid");
}
//iv = token[:16]
Bytes iv = token.left(16);
TRACE("Token::decrypt: iv: " + iv.toHex());
//ciphertext = token[16:-32]
Bytes ciphertext = token.mid(16, token.size()-48);
TRACE("Token::decrypt: ciphertext: " + ciphertext.toHex());
try {
Bytes plaintext;
if (_mode == MODE_AES_128_CBC) {
plaintext = PKCS7::unpad(
AES_128_CBC::decrypt(
ciphertext,
_encryption_key,
iv
)
);
}
else if (_mode == MODE_AES_256_CBC) {
plaintext = PKCS7::unpad(
AES_256_CBC::decrypt(
ciphertext,
_encryption_key,
iv
)
);
}
else {
throw new std::invalid_argument("Invalid token mode "+std::to_string(_mode));
}
DEBUG("Token::encrypt: unpadded plaintext length: " + std::to_string(plaintext.size()));
TRACE("Token::decrypt: plaintext: " + plaintext.toHex());
DEBUG("Token::decrypt: plaintext length: " + std::to_string(plaintext.size()));
return plaintext;
}
catch (std::exception& e) {
WARNING("Could not decrypt Token token");
throw std::runtime_error("Could not decrypt Token token");
}
}
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include "Random.h"
#include "../Bytes.h"
#include "../Type.h"
#include <stdint.h>
namespace RNS { namespace Cryptography {
/*
This class provides a slightly modified implementation of the Fernet spec
found at: https://github.com/fernet/spec/blob/master/Spec.md
According to the spec, a Fernet token includes a one byte VERSION and
eight byte TIMESTAMP field at the start of each token. These fields are
not relevant to Reticulum. They are therefore stripped from this
implementation, since they incur overhead and leak initiator metadata.
*/
class Token {
public:
using Ptr = std::shared_ptr<Token>;
public:
static inline const Bytes generate_key(RNS::Type::Cryptography::Token::token_mode mode = RNS::Type::Cryptography::Token::MODE_AES_256_CBC) {
if (mode == RNS::Type::Cryptography::Token::MODE_AES_128_CBC) return random(32);
else if (mode == RNS::Type::Cryptography::Token::MODE_AES_256_CBC) return random(64);
else throw new std::invalid_argument("Invalid token mode: " + std::to_string(mode));
}
public:
Token(const Bytes& key, RNS::Type::Cryptography::Token::token_mode mode = RNS::Type::Cryptography::Token::MODE_AES);
~Token();
public:
bool verify_hmac(const Bytes& token);
const Bytes encrypt(const Bytes& data);
const Bytes decrypt(const Bytes& token);
private:
RNS::Type::Cryptography::Token::token_mode _mode = RNS::Type::Cryptography::Token::MODE_AES_256_CBC;
Bytes _signing_key;
Bytes _encryption_key;
};
} }
+3 -2
View File
@@ -58,7 +58,7 @@ namespace RNS {
public:
class Callbacks {
public:
using link_established = void(*)(const Link& link);
using link_established = void(*)(Link& link);
//using packet = void(*)(uint8_t* data, uint16_t data_len, Packet *packet);
using packet = void(*)(const Bytes& data, const Packet& packet);
using proof_requested = bool(*)(const Packet& packet);
@@ -237,7 +237,8 @@ namespace RNS {
//z _callback = None
//z _proofcallback = None
// CBA _link_id is expected by packet but only present in Link
// CBA LINK
// CBA _link_id is expected by Packet but only present in Link
// CBA TODO determine if Link needs to inherit from Destination or vice-versa
Bytes _link_id;
+2
View File
@@ -20,6 +20,7 @@ namespace RNS {
virtual ~FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object destroyed, this: 0x%X", this); }
protected:
virtual bool init() { return true; }
virtual bool file_exists(const char* file_path) = 0;
virtual size_t read_file(const char* file_path, Bytes& data) = 0;
virtual size_t write_file(const char* file_path, const Bytes& data) = 0;
@@ -90,6 +91,7 @@ namespace RNS {
}
public:
inline bool init() { assert(_impl); return _impl->init(); }
inline bool file_exists(const char* file_path) { assert(_impl); return _impl->file_exists(file_path); }
inline size_t read_file(const char* file_path, Bytes& data) { assert(_impl); return _impl->read_file(file_path, data); }
inline size_t write_file(const char* file_path, const Bytes& data) { assert(_impl); return _impl->write_file(file_path, data); }
+10 -10
View File
@@ -8,7 +8,7 @@
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/HKDF.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include "Cryptography/Random.h"
#include <algorithm>
@@ -513,17 +513,17 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
TRACE("Identity::encrypt: shared key: " + shared_key.toHex());
Bytes derived_key = Cryptography::hkdf(
32,
DERIVED_KEY_LENGTH,
shared_key,
get_salt(),
get_context()
);
TRACE("Identity::encrypt: derived key: " + derived_key.toHex());
Cryptography::Fernet fernet(derived_key);
TRACE("Identity::encrypt: Fernet encrypting data of length " + std::to_string(plaintext.size()));
Cryptography::Token token(derived_key);
TRACE("Identity::encrypt: Token encrypting data of length " + std::to_string(plaintext.size()));
TRACE("Identity::encrypt: plaintext: " + plaintext.toHex());
Bytes ciphertext = fernet.encrypt(plaintext);
Bytes ciphertext = token.encrypt(plaintext);
TRACE("Identity::encrypt: ciphertext: " + ciphertext.toHex());
return ephemeral_pub_bytes + ciphertext;
@@ -561,21 +561,21 @@ const Bytes Identity::decrypt(const Bytes& ciphertext_token) const {
TRACE("Identity::decrypt: shared key: " + shared_key.toHex());
Bytes derived_key = Cryptography::hkdf(
32,
DERIVED_KEY_LENGTH,
shared_key,
get_salt(),
get_context()
);
TRACE("Identity::decrypt: derived key: " + derived_key.toHex());
Cryptography::Fernet fernet(derived_key);
Cryptography::Token token(derived_key);
//ciphertext = ciphertext_token[Identity.KEYSIZE//8//2:]
Bytes ciphertext(ciphertext_token.mid(Type::Identity::KEYSIZE/8/2));
TRACE("Identity::decrypt: Fernet decrypting data of length " + std::to_string(ciphertext.size()));
TRACE("Identity::decrypt: Token decrypting data of length " + std::to_string(ciphertext.size()));
TRACE("Identity::decrypt: ciphertext: " + ciphertext.toHex());
plaintext = fernet.decrypt(ciphertext);
plaintext = token.decrypt(ciphertext);
TRACE("Identity::decrypt: plaintext: " + plaintext.toHex());
//TRACE("Identity::decrypt: Fernet decrypted data of length " + std::to_string(plaintext.size()));
//TRACE("Identity::decrypt: Token decrypted data of length " + std::to_string(plaintext.size()));
}
catch (std::exception& e) {
DEBUG("Decryption by " + toString() + " failed: " + e.what());
+1 -1
View File
@@ -6,7 +6,7 @@
#include "Cryptography/Hashes.h"
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include <map>
#include <string>
+15 -2
View File
@@ -30,7 +30,7 @@ namespace RNS {
Bytes _destination;
double _time = 0;
uint8_t _hops = 0;
double _emitted = 0;
uint64_t _emitted = 0;
Bytes _raw;
};
@@ -43,6 +43,9 @@ namespace RNS {
virtual ~InterfaceImpl() { MEMF("InterfaceImpl object destroyed, this: 0x%X", this); }
protected:
virtual bool start() { return true; }
virtual void stop() {}
virtual void loop() {}
// CBA Virtual override method for custom interface to send outgoing data
virtual void send_outgoing(const Bytes& data) = 0;
@@ -71,6 +74,9 @@ namespace RNS {
Bytes _ifac_identity;
Type::Interface::modes _mode = Type::Interface::MODE_NONE;
uint32_t _bitrate = 0;
uint16_t _HW_MTU = 0;
bool _AUTOCONFIGURE_MTU = false;
bool _FIXED_MTU = false;
double _announce_allowed_at = 0;
float _announce_cap = 0.0;
std::list<AnnounceEntry> _announce_queue;
@@ -145,6 +151,9 @@ namespace RNS {
}
public:
inline bool start() { assert(_impl); return _impl->start(); }
inline void stop() { assert(_impl); return _impl->stop(); }
inline void loop() { assert(_impl); return _impl->loop(); }
inline const Bytes get_hash() const { assert(_impl); return _impl->get_hash(); }
void process_announce_queue();
@@ -158,8 +167,8 @@ namespace RNS {
// Public method to handle data coming in on interface and pass on to impl
void handle_incoming(const Bytes& data);
// getters/setters
protected:
// setters
inline void IN(bool IN) { assert(_impl); _impl->_IN = IN; }
inline void OUT(bool OUT) { assert(_impl); _impl->_OUT = OUT; }
inline void FWD(bool FWD) { assert(_impl); _impl->_FWD = FWD; }
@@ -169,6 +178,7 @@ namespace RNS {
inline void online(bool online) { assert(_impl); _impl->_online = online; }
inline void announce_allowed_at(double announce_allowed_at) { assert(_impl); _impl->_announce_allowed_at = announce_allowed_at; }
public:
// getters
inline bool IN() const { assert(_impl); return _impl->_IN; }
inline bool OUT() const { assert(_impl); return _impl->_OUT; }
inline bool FWD() const { assert(_impl); return _impl->_FWD; }
@@ -179,6 +189,9 @@ namespace RNS {
inline Type::Interface::modes mode() const { assert(_impl); return _impl->_mode; }
inline void mode(Type::Interface::modes mode) { assert(_impl); _impl->_mode = mode; }
inline uint32_t bitrate() const { assert(_impl); return _impl->_bitrate; }
inline uint16_t HW_MTU() const { assert(_impl); return _impl->_HW_MTU; }
inline bool AUTOCONFIGURE_MTU() const { assert(_impl); return _impl->_AUTOCONFIGURE_MTU; }
inline bool FIXED_MTU() const { assert(_impl); return _impl->_FIXED_MTU; }
inline double announce_allowed_at() const { assert(_impl); return _impl->_announce_allowed_at; }
inline float announce_cap() const { assert(_impl); return _impl->_announce_cap; }
inline std::list<AnnounceEntry>& announce_queue() const { assert(_impl); return _impl->_announce_queue; }
+218 -19
View File
@@ -9,7 +9,7 @@
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/HKDF.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include "Cryptography/Random.h"
#define MSGPACK_DEBUGLOG_ENABLE 0
@@ -24,12 +24,16 @@ using namespace RNS::Utilities;
/*static*/ uint8_t Link::resource_strategies = ACCEPT_NONE | ACCEPT_APP | ACCEPT_ALL;
Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::established established_callback /*= nullptr*/, Callbacks::closed closed_callback /*= nullptr*/, const Destination& owner /*= {Type::NONE}*/, const Bytes& peer_pub_bytes /*= {Bytes::NONE}*/, const Bytes& peer_sig_pub_bytes /*= {Bytes::NONE}*/) :
/*static*/ std::set<link_mode> Link::ENABLED_MODES = {MODE_AES256_CBC};
/*static*/ link_mode Link::MODE_DEFAULT = MODE_AES256_CBC;
Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::established established_callback /*= nullptr*/, Callbacks::closed closed_callback /*= nullptr*/, const Destination& owner /*= {Type::NONE}*/, const Bytes& peer_pub_bytes /*= {Bytes::NONE}*/, const Bytes& peer_sig_pub_bytes /*= {Bytes::NONE}*/, link_mode mode /*= MODE_DEFAULT*/) :
_object(new LinkData(destination))
{
assert(_object);
_object->_owner = owner;
_object->_mode = mode;
if (destination && destination.type() != Type::Destination::SINGLE) {
throw std::logic_error("Links can only be established to the \"single\" destination type");
@@ -76,7 +80,18 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
}
if (_object->_initiator) {
_object->_request_data = _object->_pub_bytes + _object->_sig_pub_bytes;
Bytes signalling_bytes;
uint16_t nh_hw_mtu = Transport::next_hop_interface_hw_mtu(destination.hash());
if (RNS::Reticulum::link_mtu_discovery() && nh_hw_mtu) {
signalling_bytes = Link::signalling_bytes(nh_hw_mtu, _object->_mode);
DEBUGF("Signalling link MTU of %d for link", nh_hw_mtu);
}
else {
signalling_bytes = Link::signalling_bytes(RNS::Type::Reticulum::MTU, _object->_mode);
}
TRACEF("Establishing link with mode %d", _object->_mode);
//p self.request_data = self.pub_bytes+self.sig_pub_bytes+signalling_bytes
_object->_request_data = _object->_pub_bytes + _object->_sig_pub_bytes + signalling_bytes;
_object->_packet = Packet(destination, _object->_request_data, RNS::Type::Packet::LINKREQUEST);
_object->_packet.pack();
_object->_establishment_cost += _object->_packet.raw().size();
@@ -98,6 +113,65 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
}
/*static*/ Bytes Link::signalling_bytes(uint16_t mtu, link_mode mode) {
//p if not mode in Link.ENABLED_MODES: raise TypeError(f"Requested link mode {Link.MODE_DESCRIPTIONS[mode]} not enabled")
//if (!(mode & ENABLED_MODES)) throw std::runtime_error("Requested link mode "+std::to_string(mode)+" not enabled");
if (Link::ENABLED_MODES.find(mode) == Link::ENABLED_MODES.end()) throw std::runtime_error("Requested link mode "+std::to_string(mode)+" not enabled");
//p signalling_value = (mtu & Link.MTU_BYTEMASK)+(((mode<<5) & Link.MODE_BYTEMASK)<<16)
//p return struct.pack(">I", signalling_value)[1:]
uint32_t signalling_value = htonl((mtu & MTU_BYTEMASK)+(((mode<<5) & MODE_BYTEMASK)<<16));
Bytes data(((uint8_t*)&signalling_value)+1, 3);
return data;
}
/*static*/ uint16_t Link::mtu_from_lr_packet(const Packet& packet) {
if (packet.data().size() == ECPUBSIZE+LINK_MTU_SIZE) {
return (packet.data()[ECPUBSIZE] << 16) + (packet.data()[ECPUBSIZE+1] << 8) + (packet.data()[ECPUBSIZE+2]) & MTU_BYTEMASK;
}
return 0;
}
/*static*/ uint16_t Link::mtu_from_lp_packet(const Packet& packet) {
//p if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
if (packet.data().size() == RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2+LINK_MTU_SIZE) {
Bytes mtu_bytes = packet.data().mid(RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2, LINK_MTU_SIZE);
return (mtu_bytes[0] << 16) + (mtu_bytes[1] << 8) + (mtu_bytes[2]) & MTU_BYTEMASK;
}
return 0;
}
/*static*/ uint8_t Link::mode_byte(link_mode mode) {
//p if mode in Link.ENABLED_MODES: return (mode << 5) & Link.MODE_BYTEMASK
if (Link::ENABLED_MODES.find(mode) != Link::ENABLED_MODES.end()) return (mode << 5) & MODE_BYTEMASK;
throw std::runtime_error("Requested link mode {mode} not enabled");
}
/*static*/ link_mode Link::mode_from_lr_packet(const Packet& packet) {
if (packet.data().size() > ECPUBSIZE) {
link_mode mode = static_cast<link_mode>((packet.data()[ECPUBSIZE] & MODE_BYTEMASK) >> 5);
return mode;
}
return Link::MODE_DEFAULT;
}
/*static*/ link_mode Link::mode_from_lp_packet(const Packet& packet) {
if (packet.data().size() > RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) {
link_mode mode = static_cast<link_mode>(packet.data()[RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2] >> 5);
return mode;
}
return Link::MODE_DEFAULT;
}
/*static*/ Bytes Link::link_id_from_lr_packet(const Packet& packet) {
Bytes hashable_part = packet.get_hashable_part();
if (packet.data().size() > ECPUBSIZE) {
size_t diff = packet.data().size() - ECPUBSIZE;
//p hashable_part = hashable_part[:-diff]
hashable_part = hashable_part.left(hashable_part.size() - diff);
}
return RNS::Identity::truncated_hash(hashable_part);
}
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
if (data.size() == ECPUBSIZE) {
try {
@@ -149,7 +223,7 @@ void Link::load_peer(const Bytes& peer_pub_bytes, const Bytes& peer_sig_pub_byte
void Link::set_link_id(const Packet& packet) {
assert(_object);
_object->_link_id = packet.getTruncatedHash();
_object->_link_id = Link::link_id_from_lr_packet(packet);
_object->_hash = _object->_link_id;
}
@@ -159,8 +233,13 @@ void Link::handshake() {
_object->_status = Type::Link::HANDSHAKE;
_object->_shared_key = _object->_prv->exchange(_object->_peer_pub_bytes);
uint16_t derived_key_length;
if (_object->_mode == RNS::Type::Link::MODE_AES128_CBC) derived_key_length = 32;
else if (_object->_mode == RNS::Type::Link::MODE_AES256_CBC) derived_key_length = 64;
else throw new std::invalid_argument("Invalid link mode "+std::to_string(_object->_mode)+" on "+toString());
_object->_derived_key = Cryptography::hkdf(
32,
derived_key_length,
_object->_shared_key,
get_salt(),
get_context()
@@ -173,13 +252,15 @@ void Link::handshake() {
void Link::prove() {
assert(_object);
DEBUGF("Link %s requesting proof", link_id().toHex().c_str());
Bytes signed_data =_object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes;
const Bytes signature(_object->_owner.identity().sign(signed_data));
Bytes proof_data = signature + _object->_pub_bytes;
// CBA LINK
//Packet proof(_object->_link_destination, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
Packet proof(_object->_link_destination, *this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
// CBA TODO: Determine which approach is better, passing liunk to packet or passing _link_destination
Packet proof(_object->_link_destination, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
//Packet proof(_object->_link_destination, *this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
proof.send();
_object->_establishment_cost += proof.raw().size();
had_outbound();
@@ -187,6 +268,7 @@ void Link::prove() {
void Link::prove_packet(const Packet& packet) {
assert(_object);
DEBUGF("Link %s proving packet", link_id().toHex().c_str());
const Bytes signature(sign(packet.packet_hash()));
// TODO: Hardcoded as explicit proof for now
// if RNS.Reticulum.should_use_implicit_proof():
@@ -202,21 +284,41 @@ void Link::prove_packet(const Packet& packet) {
void Link::validate_proof(const Packet& packet) {
assert(_object);
DEBUGF("Link %s validating proof", link_id().toHex().c_str());
try {
if (_object->_status == Type::Link::PENDING) {
Bytes packet_data(packet.data());
TRACEF("Link %s: initiator: %d", toString().c_str(), _object->_initiator);
TRACEF("Link %s: size: %d", toString().c_str(), packet_data.size());
Bytes signalling_bytes;
uint16_t confirmed_mtu = 0;
link_mode mode = mode_from_lp_packet(packet);
DEBUGF("Validating link request proof with mode %d", mode);
if (mode != _object->_mode) throw std::runtime_error("Invalid link mode "+std::to_string(mode)+" in link request proof");
//p if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
if (packet_data.size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2+RNS::Type::Link::LINK_MTU_SIZE) {
confirmed_mtu = Link::mtu_from_lp_packet(packet);
signalling_bytes = Link::signalling_bytes(confirmed_mtu, mode);
// CBA TODO Determine best way to deal with packet.data() being read-only
//p packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
packet_data = packet_data.left(RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2);
DEBUGF("Destination confirmed link MTU of %d", confirmed_mtu);
}
//p if _object->_initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+ECPUBSIZE//2:
if (_object->_initiator && packet.data().size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) {
if (_object->_initiator && packet_data.size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) {
//p peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+ECPUBSIZE//2]
const Bytes peer_pub_bytes(packet.data().mid(Type::Identity::SIGLENGTH/8, ECPUBSIZE/2));
const Bytes peer_pub_bytes(packet_data.mid(Type::Identity::SIGLENGTH/8, ECPUBSIZE/2));
//p peer_sig_pub_bytes = _object->_destination.identity.get_public_key()[ECPUBSIZE//2:ECPUBSIZE]
const Bytes peer_sig_pub_bytes(_object->_destination.identity().get_public_key().mid(ECPUBSIZE/2, ECPUBSIZE/2));
TRACEF("Link %s performing handshake", link_id().toHex().c_str());
load_peer(peer_pub_bytes, peer_sig_pub_bytes);
handshake();
_object->_establishment_cost += packet.raw().size();
Bytes signed_data = _object->_link_id + _object->_peer_pub_bytes + _object->_peer_sig_pub_bytes;
const Bytes signature(packet.data().left(Type::Identity::SIGLENGTH/8));
const Bytes signature(packet_data.left(Type::Identity::SIGLENGTH/8));
TRACEF("Link %s validating identity", link_id().toHex().c_str());
if (_object->_destination.identity().validate(signature, signed_data)) {
if (_object->_status != Type::Link::HANDSHAKE) {
throw std::runtime_error("Invalid link state for proof validation: " + _object->_status);
@@ -224,6 +326,9 @@ void Link::validate_proof(const Packet& packet) {
_object->_rtt = OS::time() - _object->_request_time;
_object->_attached_interface = packet.receiving_interface();
_object->__remote_identity = _object->_destination.identity();
if (confirmed_mtu) _object->_mtu = confirmed_mtu;
else _object->_mtu = RNS::Type::Reticulum::MTU;
update_mdu();
_object->_status = Type::Link::ACTIVE;
_object->_activated_at = OS::time();
_object->_last_proof = _object->_activated_at;
@@ -239,12 +344,14 @@ void Link::validate_proof(const Packet& packet) {
MsgPack::Packer packer;
packer.serialize(_object->_rtt);
Bytes rtt_data(packer.data(), packer.size());
TRACEF("***** RTT data size: %d", rtt_data.size());
//p rtt_packet = RNS.Packet(self, rtt_data, context=RNS.Packet.LRRTT)
Packet rtt_packet(_object->_link_destination, rtt_data, Type::Packet::DATA, Type::Packet::LRRTT);
rtt_packet.send();
had_outbound();
if (_object->_callbacks._established != nullptr) {
VERBOSEF("Link %s is established", link_id().toHex().c_str());
//p thread = threading.Thread(target=_object->_callbacks.link_established, args=(self,))
//p thread.daemon = True
//p thread.start()
@@ -255,6 +362,9 @@ void Link::validate_proof(const Packet& packet) {
DEBUGF("Invalid link proof signature received by %s. Ignoring.", toString().c_str());
}
}
else {
DEBUGF("Failed initiator/size check for link proof signature received by %s. Ignoring.", toString().c_str());
}
}
}
catch (std::exception& e) {
@@ -275,6 +385,7 @@ thus preserved. This method can be used for authentication.
*/
void Link::identify(const Identity& identity) {
assert(_object);
DEBUGF("Link %s requesting identity", link_id().toHex().c_str());
if (_object->_initiator && _object->_status == Type::Link::ACTIVE) {
const Bytes signed_data(_object->_link_id + identity.get_public_key());
const Bytes signature(identity.sign(signed_data));
@@ -298,6 +409,7 @@ Sends a request to the remote peer.
*/
const RNS::RequestReceipt Link::request(const Bytes& path, const Bytes& data /*= {Bytes::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/) {
assert(_object);
DEBUGF("Link %s sending request", link_id().toHex().c_str());
const Bytes request_path_hash(Identity::truncated_hash(path));
//p unpacked_request = [OS::time(), request_path_hash, data]
@@ -350,6 +462,13 @@ const RNS::RequestReceipt Link::request(const Bytes& path, const Bytes& data /*=
}
void Link::update_mdu() {
assert(_object);
_object->_mdu = _object->_mtu - RNS::Type::Reticulum::HEADER_MAXSIZE - RNS::Type::Reticulum::IFAC_MIN_SIZE;
//p self.mdu = math.floor((self.mtu-RNS.Reticulum.IFAC_MIN_SIZE-RNS.Reticulum.HEADER_MINSIZE-RNS.Identity.TOKEN_OVERHEAD)/RNS.Identity.AES128_BLOCKSIZE)*RNS.Identity.AES128_BLOCKSIZE - 1
_object->_mdu = std::floor((_object->_mtu-RNS::Type::Reticulum::IFAC_MIN_SIZE-RNS::Type::Reticulum::HEADER_MINSIZE-RNS::Type::Identity::TOKEN_OVERHEAD)/RNS::Type::Identity::AES128_BLOCKSIZE)*RNS::Type::Identity::AES128_BLOCKSIZE - 1;
}
void Link::rtt_packet(const Packet& packet) {
assert(_object);
try {
@@ -398,6 +517,47 @@ float Link::get_establishment_rate() {
return _object->_establishment_rate*8;
}
/*
:returns: The MTU of an established link.
*/
uint16_t Link::get_mtu() {
assert(_object);
if (_object->_status == ACTIVE) {
return _object->_mtu;
}
return 0;
}
/*
:returns: The packet MDU of an established link.
*/
uint16_t Link::get_mdu() {
assert(_object);
if (_object->_status == ACTIVE) {
return _object->_mdu;
}
return 0;
}
/*
:returns: The packet expected in-flight data rate of an established link.
*/
float Link::get_expected_rate() {
assert(_object);
if (_object->_status == ACTIVE) {
return _object->_expected_rate;
}
return 0.0;
}
/*
:returns: The mode of an established link.
*/
link_mode Link::get_mode() {
assert(_object);
return _object->_mode;
}
const Bytes& Link::get_salt() {
assert(_object);
return _object->_link_id;
@@ -407,6 +567,17 @@ const Bytes Link::get_context() {
return {Bytes::NONE};
}
/*
:returns: The time in seconds since this link was established.
*/
double Link::get_age() {
assert(_object);
if (_object->_activated_at) {
return OS::time() - _object->_activated_at;
}
return 0.0;
}
/*
:returns: The time in seconds since last inbound packet on the link. This includes keepalive packets.
*/
@@ -624,6 +795,8 @@ void Link::send_keepalive() {
}
void Link::handle_request(const Bytes& request_id, const ResourceRequest& resource_request) {
assert(_object);
DEBUGF("Link %s handling request", link_id().toHex().c_str());
if (_object->_status == Type::Link::ACTIVE) {
//p requested_at = unpacked_request[0]
//p path_hash = unpacked_request[1]
@@ -1085,16 +1258,16 @@ void Link::receive(const Packet& packet) {
const Bytes Link::encrypt(const Bytes& plaintext) {
assert(_object);
try {
if (!_object->_fernet) {
if (!_object->_token) {
try {
_object->_fernet.reset(new Fernet(_object->_derived_key));
_object->_token.reset(new Token(_object->_derived_key));
}
catch (std::exception& e) {
ERRORF("Could not instantiate Fernet while performin encryption on link %s. The contained exception was: %s", toString().c_str(), e.what());
ERRORF("Could not instantiate Token while performin encryption on link %s. The contained exception was: %s", toString().c_str(), e.what());
throw e;
}
}
return _object->_fernet->encrypt(plaintext);
return _object->_token->encrypt(plaintext);
}
catch (std::exception& e) {
ERRORF("Encryption on link %s failed. The contained exception was: %s", toString().c_str(), e.what());
@@ -1105,10 +1278,10 @@ const Bytes Link::encrypt(const Bytes& plaintext) {
const Bytes Link::decrypt(const Bytes& ciphertext) {
assert(_object);
try {
if (!_object->_fernet) {
_object->_fernet.reset(new Fernet(_object->_derived_key));
if (!_object->_token) {
_object->_token.reset(new Token(_object->_derived_key));
}
return _object->_fernet->decrypt(ciphertext);
return _object->_token->decrypt(ciphertext);
}
catch (std::exception& e) {
ERRORF("Decryption failed on link %s. The contained exception was: %s", toString().c_str(), e.what());
@@ -1186,7 +1359,7 @@ Sets the resource strategy for the link.
*/
void Link::set_resource_strategy(resource_strategy strategy) {
assert(_object);
if ((strategy & resource_strategies) > 0) {
if (!(strategy & resource_strategies)) {
throw std::runtime_error("Unsupported resource strategy");
}
else {
@@ -1253,6 +1426,12 @@ const Destination& Link::destination() const {
return _object->_destination;
}
// CBA LINK
const Destination& Link::link_destination() const {
assert(_object);
return _object->_link_destination;
}
const Bytes& Link::link_id() const {
assert(_object);
return _object->_link_id;
@@ -1263,6 +1442,11 @@ const Bytes& Link::hash() const {
return _object->_hash;
}
uint16_t Link::mtu() const {
assert(_object);
return _object->_mtu;
}
Type::Link::status Link::status() const {
assert(_object);
return _object->_status;
@@ -1293,6 +1477,16 @@ std::set<RNS::RequestReceipt>& Link::pending_requests() const {
return _object->_pending_requests;
}
Type::Link::teardown_reason Link::teardown_reason() const {
assert(_object);
return _object->_teardown_reason;
}
bool Link::initiator() const {
assert(_object);
return _object->_initiator;
}
// setters
void Link::destination(const Destination& destination) {
@@ -1325,6 +1519,11 @@ void Link::last_inbound(double time) {
_object->_last_inbound = time;
}
void Link::status(Type::Link::status status) {
assert(_object);
_object->_status = status;
}
//RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt /*= {Type::NONE}*/, const Resource& resource /*= {Type::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) :
RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt, const Resource& resource, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) :
@@ -1548,7 +1747,7 @@ const Bytes& RequestReceipt::request_id() const {
return _object->_request_id;
}
const size_t RequestReceipt::response_transfer_size() const {
size_t RequestReceipt::response_transfer_size() const {
assert(_object);
return _object->_response_transfer_size;
}
+28 -5
View File
@@ -87,7 +87,7 @@ namespace RNS {
// getters
const Bytes& hash() const;
const Bytes& request_id() const;
const size_t response_transfer_size() const;
size_t response_transfer_size() const;
// setters
void response_size(size_t size);
@@ -112,8 +112,8 @@ namespace RNS {
public:
class Callbacks {
public:
using established = void(*)(const Link& link);
using closed = void(*)(const Link& link);
using established = void(*)(Link& link);
using closed = void(*)(Link& link);
using packet = void(*)(const Bytes& plaintext, const Packet& packet);
using remote_identified = void(*)(const Link& link, const Identity& remote_identity);
using resource = void(*)(const ResourceAdvertisement& resource_advertisement);
@@ -132,6 +132,8 @@ namespace RNS {
public:
static uint8_t resource_strategies;
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
static RNS::Type::Link::link_mode MODE_DEFAULT;
public:
Link(Type::NoneConstructor none) {
@@ -140,8 +142,8 @@ namespace RNS {
Link(const Link& link) : _object(link._object) {
MEM("Link object copy created");
}
Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE});
//Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE});
Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE}, RNS::Type::Link::link_mode mode = MODE_DEFAULT);
//Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE}, RNS::Type::Link::link_mode mode = MODE_DEFAULT);
virtual ~Link(){
MEM("Link object destroyed");
}
@@ -158,7 +160,16 @@ namespace RNS {
}
public:
static Bytes signalling_bytes(uint16_t mtu, RNS::Type::Link::link_mode mode);
static uint16_t mtu_from_lr_packet(const Packet& packet);
static uint16_t mtu_from_lp_packet(const Packet& packet);
static uint8_t mode_byte(RNS::Type::Link::link_mode mode);
static RNS::Type::Link::link_mode mode_from_lr_packet(const Packet& packet);
static RNS::Type::Link::link_mode mode_from_lp_packet(const Packet& packet);
static Bytes link_id_from_lr_packet(const Packet& packet);
static Link validate_request( const Destination& owner, const Bytes& data, const Packet& packet);
public:
void load_peer(const Bytes& peer_pub_bytes, const Bytes& peer_sig_pub_bytes);
void set_link_id(const Packet& packet);
void handshake();
@@ -167,10 +178,16 @@ namespace RNS {
void validate_proof(const Packet& packet);
void identify(const Identity& identity);
const RequestReceipt request(const Bytes& path, const Bytes& data = {Bytes::NONE}, RequestReceipt::Callbacks::response response_callback = nullptr, RequestReceipt::Callbacks::failed failed_callback = nullptr, RequestReceipt::Callbacks::progress progress_callback = nullptr, double timeout = 0.0);
void update_mdu();
void rtt_packet(const Packet& packet);
float get_establishment_rate();
uint16_t get_mtu();
uint16_t get_mdu();
float get_expected_rate();
RNS::Type::Link::link_mode get_mode();
const Bytes& get_salt();
const Bytes get_context();
double get_age();
double no_inbound_for();
double no_outbound_for();
double no_data_for();
@@ -214,15 +231,20 @@ namespace RNS {
// getters
const Destination& destination() const;
// CBA LINK
const Destination& link_destination() const;
const Interface& attached_interface() const;
const Bytes& link_id() const;
const Bytes& hash() const;
uint16_t mtu() const;
Type::Link::status status() const;
double establishment_timeout() const;
uint16_t establishment_cost() const;
double request_time() const;
double last_inbound() const;
std::set<RequestReceipt>& pending_requests() const;
Type::Link::teardown_reason teardown_reason() const;
bool initiator() const;
// setters
void destination(const Destination& destination);
@@ -231,6 +253,7 @@ namespace RNS {
void establishment_cost(uint16_t cost);
void request_time(double time);
void last_inbound(double time);
void status(Type::Link::status status);
protected:
std::shared_ptr<LinkData> _object;
+12 -4
View File
@@ -10,7 +10,7 @@
#include "Destination.h"
#include "Bytes.h"
#include "Type.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include <set>
@@ -18,8 +18,12 @@ namespace RNS {
class LinkData {
public:
LinkData(const Destination& destination) : _destination(destination) {}
virtual ~LinkData() {}
LinkData(const Destination& destination) : _destination(destination) {
MEM("LinkData object copy created");
}
virtual ~LinkData() {
MEM("LinkData object destroyed");
}
private:
Destination _destination;
@@ -30,7 +34,10 @@ namespace RNS {
Bytes _hash;
Type::Link::status _status = Type::Link::PENDING;
RNS::Type::Link::link_mode _mode = Link::MODE_DEFAULT;
double _rtt = 0.0;
uint16_t _mtu = RNS::Type::Reticulum::MTU;
uint16_t _mdu = 0;
uint16_t _establishment_cost = 0;
Link::Callbacks _callbacks;
Type::Link::resource_strategy _resource_strategy = Type::Link::ACCEPT_NONE;
@@ -63,9 +70,10 @@ namespace RNS {
Packet _packet = {Type::NONE};
double _request_time = 0.0;
float _establishment_rate = 0.0;
float _expected_rate = 0.0;
Type::Link::teardown_reason _teardown_reason = Type::Link::TEARDOWN_NONE;
Cryptography::Fernet::Ptr _fernet;
Cryptography::Token::Ptr _token;
Cryptography::X25519PrivateKey::Ptr _prv;
Bytes _prv_bytes;
+29 -7
View File
@@ -17,7 +17,7 @@ ProofDestination::ProofDestination(const Packet& packet) : Destination({Type::NO
{
}
Packet::Packet(const Destination& destination, const Interface& attached_interface, const Bytes& data, types packet_type /*= DATA*/, context_types context /*= CONTEXT_NONE*/, Type::Transport::types transport_type /*= Type::Transport::BROADCAST*/, header_types header_type /*= HEADER_1*/, const Bytes& transport_id /*= {Bytes::NONE}*/, bool create_receipt /*= true*/) :
Packet::Packet(const Destination& destination, const Interface& attached_interface, const Bytes& data, types packet_type /*= DATA*/, context_types context /*= CONTEXT_NONE*/, Type::Transport::types transport_type /*= Type::Transport::BROADCAST*/, header_types header_type /*= HEADER_1*/, const Bytes& transport_id /*= {Bytes::NONE}*/, bool create_receipt /*= true*/, context_flag context_flag /*= FLAG_UNSET*/) :
_object(new Object(destination, attached_interface))
{
@@ -33,6 +33,8 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_packet_type = packet_type;
_object->_transport_type = transport_type;
_object->_context = context;
_object->_context_flag = context_flag;
_object->_transport_id = transport_id;
_object->_data = data;
if (_object->_data.size() > MDU) {
@@ -40,6 +42,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_data.resize(MDU);
}
_object->_flags = get_packed_flags();
_object->_create_receipt = create_receipt;
}
else {
@@ -49,14 +52,32 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_fromPacked = true;
_object->_create_receipt = false;
}
/*p TODO
if destination and destination.type == RNS.Destination.LINK:
self.MTU = destination.mtu
else:
self.MTU = RNS.Reticulum.MTU
*/
// CBA LINK
if (_object->_destination && _object->_destination.type() == Type::Destination::LINK) {
// CBA TODO: Determine if this should actually be calling Link::mtu() !!!
_object->_MTU = _object->_destination.mtu();
}
MEM("Packet object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
Packet::Packet(const Destination& destination, const Link& link, const Bytes& data, Type::Packet::types packet_type /*= Type::Packet::DATA*/, Type::Packet::context_types context /*= Type::Packet::CONTEXT_NONE*/) :
_object(new Object(destination, link))
// CBA LINK
//Packet::Packet(const Link& link, const Bytes& data, Type::Packet::types packet_type /*= Type::Packet::DATA*/, Type::Packet::context_types context /*= Type::Packet::CONTEXT_NONE*/, context_flag context_flag /*= FLAG_UNSET*/) :
/*
_object(new Object(link.destination(), link))
{
TRACE("Creating packet with link...");
_object->_MTU = link.mtu();
MEM("Packet link object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
*/
uint8_t Packet::get_packed_flags() {
@@ -287,6 +308,7 @@ void Packet::pack() {
_object->_raw << _object->_data;
}
// CBA LINK
//p elif self.packet_type == Packet.PROOF and self.destination.type == RNS.Destination.LINK:
else if (_object->_packet_type == PROOF && _object->_destination.type() == Type::Destination::LINK) {
//else if (_object->_packet_type == PROOF && _object->_destination_link) {
// Packet proofs over links are not encrypted
@@ -336,8 +358,8 @@ void Packet::pack() {
}
}
if (_object->_raw.size() > _object->_mtu) {
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_mtu) +" bytes");
if (_object->_raw.size() > _object->_MTU) {
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_MTU) +" bytes");
}
_object->_packed = true;
@@ -534,11 +556,11 @@ const Bytes Packet::get_hashable_part() const {
Bytes hashable_part;
hashable_part << (uint8_t)(_object->_raw.data()[0] & 0b00001111);
if (_object->_header_type == HEADER_2) {
//hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
//p hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
hashable_part << _object->_raw.mid((Type::Identity::TRUNCATED_HASHLENGTH/8)+2);
}
else {
//hashable_part += self.raw[2:];
//p hashable_part += self.raw[2:];
hashable_part << _object->_raw.mid(2);
}
return hashable_part;
+18 -8
View File
@@ -159,7 +159,8 @@ namespace RNS {
Type::Transport::types transport_type = Type::Transport::BROADCAST,
Type::Packet::header_types header_type = Type::Packet::HEADER_1,
const Bytes& transport_id = {Bytes::NONE},
bool create_receipt = true
bool create_receipt = true,
Type::Packet::context_flag context_flag = Type::Packet::FLAG_UNSET
);
Packet(
const Destination& destination,
@@ -169,15 +170,19 @@ namespace RNS {
Type::Transport::types transport_type = Type::Transport::BROADCAST,
Type::Packet::header_types header_type = Type::Packet::HEADER_1,
const Bytes& transport_id = {Bytes::NONE},
bool create_receipt = true
) : Packet(destination, {Type::NONE}, data, packet_type, context, transport_type, header_type, transport_id, create_receipt) {}
bool create_receipt = true,
Type::Packet::context_flag context_flag = Type::Packet::FLAG_UNSET
) : Packet(destination, {Type::NONE}, data, packet_type, context, transport_type, header_type, transport_id, create_receipt, context_flag) {}
// CBA LINK
/*
Packet(
const Destination& destination,
const Link& link,
const Bytes& data,
Type::Packet::types packet_type = Type::Packet::DATA,
Type::Packet::context_types context = Type::Packet::CONTEXT_NONE
Type::Packet::context_types context = Type::Packet::CONTEXT_NONE,
Type::Packet::context_flag context_flag = Type::Packet::FLAG_UNSET
);
*/
virtual ~Packet() {
MEM("Packet object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
@@ -242,6 +247,7 @@ namespace RNS {
inline const Bytes& transport_id() const { assert(_object); return _object->_transport_id; }
inline const Bytes& raw() const { assert(_object); return _object->_raw; }
inline const Bytes& data() const { assert(_object); return _object->_data; }
// CBA LINK
//inline const Link& destination_link() const { assert(_object); return _object->_destination_link; }
//CBA Following method is only used by Resource to access decrypted resource advertisement form Link. Consider a better way.
inline const Bytes& plaintext() { assert(_object); return _object->_plaintext; }
@@ -268,13 +274,14 @@ namespace RNS {
class Object {
public:
Object(const Destination& destination, const Interface& attached_interface) : _destination(destination), _attached_interface(attached_interface) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
// CBA LINK
//Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
virtual ~Object() { MEM("Packet::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
private:
Destination _destination = {Type::NONE};
// CBA LINK
Link _destination_link = {Type::NONE};
//Link _destination_link = {Type::NONE};
Link _link = {Type::NONE};
@@ -286,6 +293,7 @@ namespace RNS {
Type::Destination::types _destination_type = Type::Destination::SINGLE;
Type::Packet::types _packet_type = Type::Packet::DATA;
Type::Packet::context_types _context = Type::Packet::CONTEXT_NONE;
uint8_t _context_flag = Type::Packet::FLAG_UNSET;
uint8_t _flags = 0;
uint8_t _hops = 0;
@@ -299,13 +307,15 @@ namespace RNS {
bool _cached = false; // whether packet has been cached
PacketReceipt _receipt = {Type::NONE};
uint16_t _mtu = Type::Reticulum::MTU;
uint16_t _MTU = Type::Reticulum::MTU;
double _sent_at = 0;
float _rssi = 0.0;
float _snr = 0.0;
float _q = 0.0;
Bytes _packet_hash;
Bytes _ratchet_id;
Bytes _destination_hash;
Bytes _transport_id;
+2
View File
@@ -23,6 +23,8 @@ using namespace RNS::Utilities;
/*static*/ const Reticulum& Reticulum::_instance = {Type::NONE};
/*static*/ bool Reticulum::__transport_enabled = false;
/*static*/ bool Reticulum::__link_mtu_discovery = RNS::Type::Reticulum::LINK_MTU_DISCOVERY;
/*static*/ bool Reticulum::__remote_management_enabled = false;
/*static*/ bool Reticulum::__use_implicit_proof = true;
/*static*/ bool Reticulum::__allow_probes = false;
/*static*/ bool Reticulum::panic_on_interface_error = false;
+27
View File
@@ -36,6 +36,8 @@ namespace RNS {
static const Reticulum& _instance;
static bool __transport_enabled;
static bool __link_mtu_discovery;
static bool __remote_management_enabled;
static bool __use_implicit_proof;
static bool __allow_probes;
static bool panic_on_interface_error;
@@ -112,6 +114,31 @@ namespace RNS {
inline static bool transport_enabled() { return __transport_enabled; }
inline static void transport_enabled(bool transport_enabled) { __transport_enabled = transport_enabled; }
/*
Returns whether link MTU discovery is enabled for the running
instance.
When link MTU discovery is enabled, Reticulum will
automatically upgrade link MTUs to the highest supported
value, increasing transfer speed and efficiency.
:returns: True if link MTU discovery is enabled, False if not.
*/
inline static bool link_mtu_discovery() { return __link_mtu_discovery; }
inline static void link_mtu_discovery(bool link_mtu_discovery) { __link_mtu_discovery = link_mtu_discovery; }
/*
Returns whether remote management is enabled for the
running instance.
When remote management is enabled, authenticated peers
can remotely query and manage this instance.
:returns: True if remote management is enabled, False if not.
*/
inline static bool remote_management_enabled() { return __remote_management_enabled; }
inline static void remote_management_enabled(bool remote_management_enabled) { __remote_management_enabled = remote_management_enabled; }
inline static bool probe_destination_enabled() { return __allow_probes; }
inline static void probe_destination_enabled(bool allow_probes) { __allow_probes = allow_probes; }
+56 -49
View File
@@ -221,7 +221,7 @@ using namespace RNS::Utilities;
}
// TODO
/*
/*p
// Synthesize tunnels for any interfaces wanting it
for interface in Transport.interfaces:
interface.tunnel_id = None
@@ -632,7 +632,7 @@ using namespace RNS::Utilities;
//if hasattr(interface, "ifac_identity") and interface.ifac_identity != None:
if (interface.ifac_identity()) {
// TODO
/*
/*p
// Calculate packet access code
ifac = interface.ifac_identity.sign(raw)[-interface.ifac_size:]
@@ -919,7 +919,7 @@ using namespace RNS::Utilities;
if (packet.hops() > 0) {
// TODO
/*
/*p
if not hasattr(interface, "announce_cap"):
interface.announce_cap = RNS.Reticulum.ANNOUNCE_CAP
@@ -949,7 +949,7 @@ using namespace RNS::Utilities;
bool should_queue = true;
for (auto& entry : interface.announce_queue()) {
if (entry._destination == packet.destination_hash()) {
double emission_timestamp = announce_emitted(packet);
uint64_t emission_timestamp = announce_emitted(packet);
should_queue = false;
if (emission_timestamp > entry._emitted) {
entry._time = outbound_time;
@@ -1160,7 +1160,7 @@ using namespace RNS::Utilities;
}
}
// TODO
/*
/*p
// If interface access codes are enabled,
// we must authenticate each packet.
//if len(raw) > 2:
@@ -1254,7 +1254,7 @@ using namespace RNS::Utilities;
packet.hops(packet.hops() + 1);
// TODO
/*
/*p
if (interface) {
if hasattr(interface, "r_stat_rssi"):
if interface.r_stat_rssi != None:
@@ -1651,7 +1651,7 @@ using namespace RNS::Utilities;
// First, check that the announce is not for a destination
// local to this system, and that hops are less than the max
// CBA TODO determine why packet desitnation hash is being searched in destinations again since we entered this logic becuase it did not exist above
// CBA TODO determine why packet destination hash is being searched in destinations again since we entered this logic becuase it did not exist above
//if (not any(packet.destination_hash == d.hash for d in Transport.destinations) and packet.hops < Transport.PATHFINDER_M+1):
#if defined(DESTINATIONS_SET)
bool found_local = false;
@@ -1666,7 +1666,7 @@ using namespace RNS::Utilities;
auto iter = _destinations.find(packet.destination_hash());
if (iter == _destinations.end() && packet.hops() < (PATHFINDER_M+1)) {
#endif
double announce_emitted = Transport::announce_emitted(packet);
uint64_t announce_emitted = Transport::announce_emitted(packet);
//p random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
Bytes random_blob = packet.data().mid(Type::Identity::KEYSIZE/8 + Type::Identity::NAME_HASH_LENGTH/8, Type::Identity::RANDOM_HASH_LENGTH/8);
@@ -1704,11 +1704,10 @@ using namespace RNS::Utilities;
double now = OS::time();
double path_expires = destination_entry._expires;
double path_announce_emitted = 0;
uint64_t path_announce_emitted = 0;
for (const Bytes& path_random_blob : random_blobs) {
//p path_announce_emitted = max(path_announce_emitted, int.from_bytes(path_random_blob[5:10], "big"))
// CBA TODO
//z path_announce_emitted = std::max(path_announce_emitted, int.from_bytes(path_random_blob[5:10], "big"));
path_announce_emitted = std::max(path_announce_emitted, OS::from_bytes_big_endian(path_random_blob.data() + 5, 5));
if (path_announce_emitted >= announce_emitted) {
break;
}
@@ -1753,7 +1752,7 @@ using namespace RNS::Utilities;
bool rate_blocked = false;
// TODO
/*
/*p
if packet.context != RNS.Packet.PATH_RESPONSE and packet.receiving_interface.announce_rate_target != None:
if not packet.destination_hash in Transport.announce_rate_table:
rate_entry = { "last": now, "rate_violations": 0, "blocked_until": 0, "timestamps": [now]}
@@ -2019,7 +2018,7 @@ using namespace RNS::Utilities;
}
}
if (execute_callback) {
// CBA TODO Why does app data come from recall instead of from this annuonce packet?
// CBA TODO Why does app data come from recall instead of from this announce packet?
handler->received_announce(
packet.destination_hash(),
announce_identity,
@@ -2140,6 +2139,7 @@ using namespace RNS::Utilities;
// This is a link request proof, check if it
// needs to be transported
if ((Reticulum::transport_enabled() || for_local_client_link || from_local_client) && _link_table.find(packet.destination_hash()) != _link_table.end()) {
TRACE("Handling link request proof...");
LinkEntry link_entry = (*_link_table.find(packet.destination_hash())).second;
if (packet.receiving_interface() == link_entry._outbound_interface) {
try {
@@ -2181,10 +2181,15 @@ using namespace RNS::Utilities;
else {
// Check if we can deliver it to a local
// pending link
for (auto& link : _pending_links) {
TRACEF("Handling proof for link request %s", packet.destination_hash().toHex().c_str());
// CBA Must make a copy of _pending_links before traversing since it gets modified
//for (auto link : _pending_links) {
std::set<Link> pending_links(_pending_links);
for (auto& link : pending_links) {
TRACEF("Checking for link request handling by pending link %s", link.link_id().toHex().c_str());
if (link.link_id() == packet.destination_hash()) {
// TODO
//z link.validate_proof(packet);
TRACE("Requesting pending link to validate proof");
const_cast<Link&>(link).validate_proof(packet);
}
}
}
@@ -2193,8 +2198,7 @@ using namespace RNS::Utilities;
TRACE("Transport::inbound: Packet is RESOURCE PROOF");
for (auto& link : _active_links) {
if (link.link_id() == packet.destination_hash()) {
// TODO
//z link.receive(packet);
const_cast<Link&>(link).receive(packet);
}
}
}
@@ -2275,7 +2279,7 @@ using namespace RNS::Utilities;
/*static*/ void Transport::synthesize_tunnel(const Interface& interface) {
// TODO
/*
/*p
Bytes interface_hash = interface.get_hash();
Bytes public_key = _identity.get_public_key();
Bytes random_hash = Identity::get_random_hash();
@@ -2299,7 +2303,7 @@ using namespace RNS::Utilities;
/*static*/ void Transport::tunnel_synthesize_handler(const Bytes& data, const Packet& packet) {
// TODO
/*
/*p
try:
expected_length = RNS.Identity.KEYSIZE//8+RNS.Identity.HASHLENGTH//8+RNS.Reticulum.TRUNCATED_HASHLENGTH//8+RNS.Identity.SIGLENGTH//8
if len(data) == expected_length:
@@ -2326,7 +2330,7 @@ using namespace RNS::Utilities;
/*static*/ void Transport::handle_tunnel(const Bytes& tunnel_id, const Interface& interface) {
// TODO
/*
/*p
expires = time.time() + Transport.DESTINATION_TIMEOUT
if not tunnel_id in Transport.tunnels:
RNS.log("Tunnel endpoint "+RNS.prettyhexrep(tunnel_id)+" established.", RNS.LOG_DEBUG)
@@ -2388,7 +2392,7 @@ using namespace RNS::Utilities;
#elif defined(INTERFACES_MAP)
_interfaces.insert({interface.get_hash(), interface});
#endif
// CBA TODO set or add transport as listener on interface to receive incoming packets
// CBA TODO set or add transport as listener on interface to receive incoming packets?
}
/*static*/ void Transport::deregister_interface(const Interface& interface) {
@@ -2489,9 +2493,7 @@ using namespace RNS::Utilities;
#endif
}
/*static*/ void Transport::register_link(const Link& link) {
// TODO
/*
/*static*/ void Transport::register_link(Link& link) {
TRACE("Transport: Registering link " + link.toString());
if (link.initiator()) {
// CBA ACCUMULATES
@@ -2501,16 +2503,13 @@ using namespace RNS::Utilities;
// CBA ACCUMULATES
_active_links.insert(link);
}
*/
}
/*static*/ void Transport::activate_link(Link& link) {
// TODO
/*
TRACE("Transport: Activating link " + link.toString());
if (_pending_links.find(link) != _pending_links.end()) {
if (link.status() != Type::Link::ACTIVE) {
throw std::runtime_error("Invalid link state for link activation: " + link.status_string());
throw std::runtime_error("Invalid link state for link activation: " + std::to_string(link.status()));
}
_pending_links.erase(link);
// CBA ACCUMULATES
@@ -2520,7 +2519,6 @@ using namespace RNS::Utilities;
else {
ERROR("Attempted to activate a link that was not in the pending table");
}
*/
}
/*
@@ -2776,7 +2774,18 @@ Deregisters an announce handler.
return interface.bitrate();
}
else {
0;
return 0;
}
}
/*static*/ uint16_t Transport::next_hop_interface_hw_mtu(const Bytes& destination_hash) {
const Interface& interface = next_hop_interface(destination_hash);
if (interface) {
if (interface.AUTOCONFIGURE_MTU() || interface.FIXED_MTU()) return interface.HW_MTU();
else return 0;
}
else {
return 0;
}
}
@@ -2879,7 +2888,7 @@ will announce it.
///*static*/ void Transport::request_path(const Bytes& destination_hash, const Interface& on_interface /*= {Type::NONE}*/, const Bytes& tag /*= {}*/, bool recursive /*= false*/) {
/*static*/ void Transport::request_path(const Bytes& destination_hash, const Interface& on_interface, const Bytes& tag /*= {}*/, bool recursive /*= false*/) {
Bytes request_tag;
if (tag) {
if (!tag) {
request_tag = Identity::get_random_hash();
}
else {
@@ -2899,7 +2908,7 @@ will announce it.
if (on_interface && recursive) {
// TODO
/*
/*p
if not hasattr(on_interface, "announce_cap"):
on_interface.announce_cap = RNS.Reticulum.ANNOUNCE_CAP
@@ -3247,7 +3256,7 @@ will announce it.
/*static*/ void Transport::detach_interfaces() {
// TODO
/*
/*p
detachable_interfaces = []
for interface in Transport.interfaces:
@@ -3275,7 +3284,7 @@ will announce it.
/*static*/ void Transport::shared_connection_disappeared() {
// TODO
/*
/*p
for link in Transport.active_links:
link.teardown()
@@ -3294,7 +3303,7 @@ will announce it.
/*static*/ void Transport::shared_connection_reappeared() {
// TODO
/*
/*p
if Transport.owner.is_connected_to_shared_instance:
for registered_destination in Transport.destinations:
if registered_destination.type == RNS.Destination.SINGLE:
@@ -3304,7 +3313,7 @@ will announce it.
/*static*/ void Transport::drop_announce_queues() {
// TODO
/*
/*p
for interface in Transport.interfaces:
if hasattr(interface, "announce_queue") and interface.announce_queue != None:
na = len(interface.announce_queue)
@@ -3319,22 +3328,20 @@ will announce it.
*/
}
/*static*/ bool Transport::announce_emitted(const Packet& packet) {
// TODO
/*
random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
announce_emitted = int.from_bytes(random_blob[5:10], "big")
return announce_emitted
*/
// MOCK
return false;
/*static*/ uint64_t Transport::announce_emitted(const Packet& packet) {
//p random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
//p announce_emitted = int.from_bytes(random_blob[5:10], "big")
Bytes random_blob = packet.data().mid(RNS::Type::Identity::KEYSIZE/8+RNS::Type::Identity::NAME_HASH_LENGTH/8, 10);
if (random_blob) {
return OS::from_bytes_big_endian(random_blob.data() + 5, 5);
}
return 0;
}
/*static*/ void Transport::write_packet_hashlist() {
#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS)
// TODO
/*
/*p
if not Transport.owner.is_connected_to_shared_instance:
if hasattr(Transport, "saving_packet_hashlist"):
wait_interval = 0.2
@@ -3713,7 +3720,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
/*static*/ void Transport::write_tunnel_table() {
#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS)
// TODO
/*
/*p
if not Transport.owner.is_connected_to_shared_instance:
if hasattr(Transport, "saving_tunnel_table"):
wait_interval = 0.2
+4 -2
View File
@@ -314,7 +314,7 @@ namespace RNS {
static void deregister_interface(const Interface& interface);
static void register_destination(Destination& destination);
static void deregister_destination(const Destination& destination);
static void register_link(const Link& link);
static void register_link(Link& link);
static void activate_link(Link& link);
static void register_announce_handler(HAnnounceHandler handler);
static void deregister_announce_handler(HAnnounceHandler handler);
@@ -331,6 +331,7 @@ namespace RNS {
static Bytes next_hop(const Bytes& destination_hash);
static Interface next_hop_interface(const Bytes& destination_hash);
static uint32_t next_hop_interface_bitrate(const Bytes& destination_hash);
static uint16_t next_hop_interface_hw_mtu(const Bytes& destination_hash);
static double next_hop_per_bit_latency(const Bytes& destination_hash);
static double next_hop_per_byte_latency(const Bytes& destination_hash);
static double first_hop_timeout(const Bytes& destination_hash);
@@ -348,7 +349,7 @@ namespace RNS {
static void shared_connection_disappeared();
static void shared_connection_reappeared();
static void drop_announce_queues();
static bool announce_emitted(const Packet& packet);
static uint64_t announce_emitted(const Packet& packet);
static void write_packet_hashlist();
static bool read_path_table();
static bool write_path_table();
@@ -405,6 +406,7 @@ namespace RNS {
#elif defined(DESTINATIONS_MAP)
static std::map<Bytes, Destination> _destinations; // All active destinations
#endif
// CBA TODO: Reconsider using std::set for enforcing uniqueness. Maybe consider std::map keyed on hash instead
static std::set<Link> _pending_links; // Links that are being established
static std::set<Link> _active_links; // Links that are active
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
+79 -7
View File
@@ -1,7 +1,6 @@
#pragma once
#include "Log.h"
#include "Cryptography/Fernet.h"
#include <stdint.h>
@@ -13,12 +12,24 @@ namespace RNS { namespace Type {
};
namespace Persistence {
//static const uint16_t DOCUMENT_MAXSIZE = 1024;
static const uint16_t DOCUMENT_MAXSIZE = 8192;
//static const uint16_t DOCUMENT_MAXSIZE = 16384;
static const uint16_t BUFFER_MAXSIZE = Persistence::DOCUMENT_MAXSIZE * 1.5; // Json write buffer of 1.5 times document seems to be sufficient
}
namespace Cryptography {
namespace Fernet {
static const uint8_t FERNET_OVERHEAD = 48; // Bytes
}
namespace Token {
static const uint8_t TOKEN_OVERHEAD = 48; // Bytes
enum token_mode {
MODE_AES = 0x01,
MODE_AES_128_CBC = 0x02,
MODE_AES_256_CBC = 0x03,
};
}
}
namespace Reticulum {
@@ -38,6 +49,16 @@ namespace RNS { namespace Type {
*/
static const uint16_t MTU = 500;
/*
Whether automatic link MTU discovery is enabled by default in this
release. Link MTU discovery significantly increases throughput over
fast links, but requires all intermediary hops to also support it.
Support for this feature was added in RNS version 0.9.0. This option
will become enabled by default in the near future. Please update your
RNS instances.
*/
static const bool LINK_MTU_DISCOVERY = true;
static const uint16_t MAX_QUEUED_ANNOUNCES = 16384;
static const uint32_t QUEUED_ANNOUNCE_LIFE = 60*60*24;
@@ -104,24 +125,38 @@ namespace RNS { namespace Type {
namespace Identity {
// The curve used for Elliptic Curve DH key exchanges
//static const char CURVE[] = "Curve25519";
static constexpr const char* CURVE = "Curve25519";
// The curve used for Elliptic Curve DH key exchanges
static const uint16_t KEYSIZE = 256*2;
// X25519 key size in bits. A complete key is the concatenation of a 256 bit encryption key, and a 256 bit signing key.
static const uint16_t KEYSIZE = 256*2;
// X.25519 ratchet key size in bits.
static const uint16_t RATCHETSIZE = 256;
/*
The expiry time for received ratchets in seconds, defaults to 30 days. Reticulum will always use the most recently
announced ratchet, and remember it for up to ``RATCHET_EXPIRY`` since receiving it, after which it will be discarded.
If a newer ratchet is announced in the meantime, it will be replace the already known ratchet.
*/
static const uint32_t RATCHET_EXPIRY = 60*60*24*30;
// Non-configurable constants
static const uint8_t FERNET_OVERHEAD = Cryptography::Fernet::FERNET_OVERHEAD;
static const uint8_t TOKEN_OVERHEAD = Cryptography::Token::TOKEN_OVERHEAD;
static const uint8_t AES128_BLOCKSIZE = 16; // In bytes
static const uint16_t HASHLENGTH = Reticulum::HASHLENGTH; // In bits
static const uint16_t SIGLENGTH = KEYSIZE; // In bits
static const uint8_t NAME_HASH_LENGTH = 80;
static const uint8_t RANDOM_HASH_LENGTH = 80;
static const uint16_t TRUNCATED_HASHLENGTH = Reticulum::TRUNCATED_HASHLENGTH; // In bits
// Constant specifying the truncated hash length (in bits) used by Reticulum
// for addressable hashes and other purposes. Non-configurable.
static const uint16_t TRUNCATED_HASHLENGTH = Reticulum::TRUNCATED_HASHLENGTH; // In bits
static const uint16_t DERIVED_KEY_LENGTH = 512/8;
static const uint16_t DERIVED_KEY_LENGTH_LEGACY = 256/8;
}
@@ -169,9 +204,12 @@ namespace RNS { namespace Type {
// Timeout for link establishment in seconds per hop to destination.
static const uint8_t ESTABLISHMENT_TIMEOUT_PER_HOP = Reticulum::DEFAULT_PER_HOP_TIMEOUT;
static const uint8_t LINK_MTU_SIZE = 3;
static const uint8_t TRAFFIC_TIMEOUT_MIN_MS = 5;
// RTT timeout factor used in link timeout calculation.
static const uint16_t TRAFFIC_TIMEOUT_FACTOR = 6;
static const uint16_t KEEPALIVE_TIMEOUT_FACTOR = 4;
static const uint8_t TRAFFIC_TIMEOUT_FACTOR = 6;
static const float KEEPALIVE_MAX_RTT = 1.75;
static const uint8_t KEEPALIVE_TIMEOUT_FACTOR = 4;
// Grace period in seconds used in link timeout calculation.
static const uint8_t STALE_GRACE = 2;
// Interval for sending keep-alive packets on established links in seconds.
@@ -183,8 +221,14 @@ namespace RNS { namespace Type {
``KEEPALIVE_TIMEOUT_FACTOR`` + ``STALE_GRACE``, the link is considered timed out,
and will be torn down.
*/
static const uint8_t STALE_FACTOR = 2;
static const uint16_t STALE_TIME = 2*KEEPALIVE;
static const uint8_t WATCHDOG_MAX_SLEEP = 5;
static const uint64_t MTU_BYTEMASK = 0x1FFFFF;
static const uint8_t MODE_BYTEMASK = 0xE0;
enum status {
PENDING = 0x00,
HANDSHAKE = 0x01,
@@ -206,6 +250,28 @@ namespace RNS { namespace Type {
ACCEPT_ALL = 0x02,
};
enum link_mode {
MODE_AES128_CBC = 0x00,
MODE_AES256_CBC = 0x01,
MODE_AES256_GCM = 0x02,
MODE_OTP_RESERVED = 0x03,
MODE_PQ_RESERVED_1 = 0x04,
MODE_PQ_RESERVED_2 = 0x05,
MODE_PQ_RESERVED_3 = 0x06,
MODE_PQ_RESERVED_4 = 0x07,
};
/*
MODE_DESCRIPTIONS = {MODE_AES128_CBC: "AES_128_CBC",
MODE_AES256_CBC: "AES_256_CBC",
MODE_AES256_GCM: "MODE_AES256_GCM",
MODE_OTP_RESERVED: "MODE_OTP_RESERVED",
MODE_PQ_RESERVED_1: "MODE_PQ_RESERVED_1",
MODE_PQ_RESERVED_2: "MODE_PQ_RESERVED_2",
MODE_PQ_RESERVED_3: "MODE_PQ_RESERVED_3",
MODE_PQ_RESERVED_4: "MODE_PQ_RESERVED_4"}
*/
}
namespace RequestReceipt {
@@ -276,6 +342,12 @@ namespace RNS { namespace Type {
LRPROOF = 0xFF, // Packet is a link request proof
};
// Context flag values
enum context_flag {
FLAG_SET = 0x01,
FLAG_UNSET = 0x00,
};
// This is used to calculate allowable
// payload sizes
static const uint16_t HEADER_MAXSIZE = Reticulum::HEADER_MAXSIZE;
+9 -1
View File
@@ -70,7 +70,15 @@ namespace RNS { namespace Utilities {
//static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
#if defined(RNS_USE_ALLOCATOR)
static inline uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
uint64_t result = 0;
for (size_t i = 0; i < len; ++i) {
result = (result << 8) | data[i];
}
return result;
}
#if defined(RNS_USE_ALLOCATOR)
static void dump_allocator_stats();
#endif