mirror of
https://github.com/ratspeak/microReticulum
synced 2026-11-22 23:10:38 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9bee2701b | ||
|
|
83b88146f4 | ||
|
|
3ddf3c362b | ||
|
|
15b9f13db6 | ||
|
|
dd1e04ab53 | ||
|
|
858010cee0 | ||
|
|
670820a41e | ||
|
|
afc5496d0e | ||
|
|
290a1336eb | ||
|
|
1cadb453eb | ||
|
|
e13b300b0c | ||
|
|
753dce608e | ||
|
|
9d6bbac9a6 | ||
|
|
e93e71dc69 |
No files matched your search
@@ -3,3 +3,5 @@
|
||||
.vscode/c_cpp_properties.json
|
||||
.vscode/launch.json
|
||||
.vscode/ipch
|
||||
destination_table
|
||||
cache/
|
||||
@@ -1,5 +1,12 @@
|
||||
# microReticulum
|
||||
|
||||
This Ratspeak fork is retained for the legacy rsDeck, rsPager and rsCardputer
|
||||
firmware. Current handheld firmware is developed in
|
||||
[Ratspeak Handheld](https://github.com/ratspeak/ratspeak-handheld), using
|
||||
[rsReticulumLite](https://github.com/ratspeak/rsReticulumLite) and
|
||||
[rsLXMFLite](https://github.com/ratspeak/rsLXMFLite). The upstream-derived notes
|
||||
below describe the retained C++ library.
|
||||
|
||||
Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs.
|
||||
|
||||
Note that this is a library implementing the Reticulum Network Stack and not a useful application on its own. For an actual application, see [microReticulum_Firmware](https://github.com/attermann/microReticulum_Firmware) which is a version of RNode firmware that implements a Reticulm Transport Node.
|
||||
@@ -35,7 +42,7 @@ Each class of allocator pool can have a separate buffer size:
|
||||
|
||||
"POOL" allocators use TLSF (Two-Level Segregate Fit) for efficient management of constrained MCU memory with minimal fragmentation.
|
||||
|
||||
The allocator for each class can be configured using build flags in `platformio.ini, for example:
|
||||
The allocator for each class can be configured using build flags in `platformio.ini`, for example:
|
||||
|
||||
```
|
||||
[env]
|
||||
@@ -55,7 +62,7 @@ Building and uploading to hardware is simple through the VSCode PlatformIO IDE
|
||||
- In PlatformIO, select the environment for intended board
|
||||
- Build, Upload, and Monitor to observe application logging
|
||||
|
||||
Instructions for command line builds and building of individual example applications coming soon.
|
||||
Command-line build and test commands are listed below.
|
||||
|
||||
## PlatformIO Command Line
|
||||
|
||||
|
||||
+13
-1
@@ -27,5 +27,17 @@
|
||||
"export": {},
|
||||
"exclude": [
|
||||
".github"
|
||||
]
|
||||
],
|
||||
"build": {
|
||||
"srcFilter": [
|
||||
"+<*>",
|
||||
"-<Compression/blocksort.c>",
|
||||
"-<Compression/bz2_compress.c>",
|
||||
"-<Compression/bz2_decompress.c>",
|
||||
"-<Compression/bzlib.c>",
|
||||
"-<Compression/crctable.c>",
|
||||
"-<Compression/huffman.c>",
|
||||
"-<Compression/randtable.c>"
|
||||
]
|
||||
}
|
||||
}
|
||||
+16
-70
@@ -1,84 +1,30 @@
|
||||
/// BZ2 compression implementation using vendored libbzip2.
|
||||
/// BZ2 compression shim — no-op on this build.
|
||||
///
|
||||
/// The vendored libbzip2 is intentionally NOT linked on embedded targets:
|
||||
/// bzip2's working-set memory and decode-table state are too large for
|
||||
/// MCU-class devices (a single decompress can use multiples of available
|
||||
/// SRAM). The functions below are kept so callers in Resource.cpp can
|
||||
/// still link against this symbol surface without any conditional
|
||||
/// compilation, but they never compress and never decompress.
|
||||
///
|
||||
/// To re-introduce a portable compression scheme later, replace these
|
||||
/// implementations with something MCU-safe (e.g. heatshrink or LZ4) and
|
||||
/// negotiate support through the LXMF announce capability list, NOT bz2.
|
||||
|
||||
#include "BZ2.h"
|
||||
|
||||
extern "C" {
|
||||
#include "bzlib.h"
|
||||
}
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
|
||||
namespace RNS {
|
||||
namespace Compression {
|
||||
|
||||
Bytes bz2_compress(const uint8_t* data, size_t len) {
|
||||
if (len == 0) return Bytes();
|
||||
|
||||
// bz2 output can be slightly larger than input for incompressible data
|
||||
unsigned int dest_len = (unsigned int)(len + len / 100 + 600);
|
||||
char* dest = (char*)malloc(dest_len);
|
||||
if (!dest) return Bytes();
|
||||
|
||||
int ret = BZ2_bzBuffToBuffCompress(
|
||||
dest, &dest_len,
|
||||
(char*)data, (unsigned int)len,
|
||||
9, // blockSize100k (1-9, 9 = best compression)
|
||||
0, // verbosity
|
||||
30 // workFactor (default)
|
||||
);
|
||||
|
||||
if (ret != BZ_OK) {
|
||||
free(dest);
|
||||
return Bytes();
|
||||
}
|
||||
|
||||
Bytes result((const uint8_t*)dest, dest_len);
|
||||
free(dest);
|
||||
return result;
|
||||
Bytes bz2_compress(const uint8_t* /*data*/, size_t /*len*/) {
|
||||
return Bytes();
|
||||
}
|
||||
|
||||
Bytes bz2_decompress(const uint8_t* data, size_t len, size_t max_size) {
|
||||
if (len == 0) return Bytes();
|
||||
|
||||
// Try with progressively larger buffers
|
||||
size_t multipliers[] = {4, 16, 64, 256};
|
||||
for (size_t mult : multipliers) {
|
||||
unsigned int dest_len = (unsigned int)(len * mult);
|
||||
if (dest_len < 1024) dest_len = 1024;
|
||||
if (max_size > 0 && dest_len > (unsigned int)max_size) dest_len = (unsigned int)max_size;
|
||||
|
||||
char* dest = (char*)malloc(dest_len);
|
||||
if (!dest) return Bytes();
|
||||
|
||||
int ret = BZ2_bzBuffToBuffDecompress(
|
||||
dest, &dest_len,
|
||||
(char*)data, (unsigned int)len,
|
||||
0, 0 // small=0, verbosity=0
|
||||
);
|
||||
|
||||
if (ret == BZ_OK) {
|
||||
if (max_size > 0 && dest_len > (unsigned int)max_size) {
|
||||
free(dest);
|
||||
return Bytes();
|
||||
}
|
||||
Bytes result((const uint8_t*)dest, dest_len);
|
||||
free(dest);
|
||||
return result;
|
||||
}
|
||||
|
||||
free(dest);
|
||||
if (ret != BZ_OUTBUFF_FULL) return Bytes(); // Unrecoverable error
|
||||
}
|
||||
|
||||
Bytes bz2_decompress(const uint8_t* /*data*/, size_t /*len*/, size_t /*max_size*/) {
|
||||
return Bytes();
|
||||
}
|
||||
|
||||
CompressResult try_compress(const Bytes& data) {
|
||||
Bytes compressed = bz2_compress(data);
|
||||
if (compressed.size() > 0 && compressed.size() < data.size()) {
|
||||
return { compressed, true };
|
||||
}
|
||||
return { data, false };
|
||||
}
|
||||
|
||||
|
||||
+3
-1094
File diff suppressed because it is too large.
Load diff
@@ -1,672 +1,3 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Compression machinery (not incl block sorting) ---*/
|
||||
/*--- compress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
/* CHANGES
|
||||
0.9.0 -- original version.
|
||||
0.9.0a/b -- no changes in this file.
|
||||
0.9.0c -- changed setting of nGroups in sendMTFValues()
|
||||
so as to do a bit better on small files
|
||||
*/
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
/*--- Bit stream I/O ---*/
|
||||
/*---------------------------------------------------*/
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_bsInitWrite ( EState* s )
|
||||
{
|
||||
s->bsLive = 0;
|
||||
s->bsBuff = 0;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void bsFinishWrite ( EState* s )
|
||||
{
|
||||
while (s->bsLive > 0) {
|
||||
s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24);
|
||||
s->numZ++;
|
||||
s->bsBuff <<= 8;
|
||||
s->bsLive -= 8;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define bsNEEDW(nz) \
|
||||
{ \
|
||||
while (s->bsLive >= 8) { \
|
||||
s->zbits[s->numZ] \
|
||||
= (UChar)(s->bsBuff >> 24); \
|
||||
s->numZ++; \
|
||||
s->bsBuff <<= 8; \
|
||||
s->bsLive -= 8; \
|
||||
} \
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
__inline__
|
||||
void bsW ( EState* s, Int32 n, UInt32 v )
|
||||
{
|
||||
bsNEEDW ( n );
|
||||
s->bsBuff |= (v << (32 - s->bsLive - n));
|
||||
s->bsLive += n;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void bsPutUInt32 ( EState* s, UInt32 u )
|
||||
{
|
||||
bsW ( s, 8, (u >> 24) & 0xffL );
|
||||
bsW ( s, 8, (u >> 16) & 0xffL );
|
||||
bsW ( s, 8, (u >> 8) & 0xffL );
|
||||
bsW ( s, 8, u & 0xffL );
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void bsPutUChar ( EState* s, UChar c )
|
||||
{
|
||||
bsW( s, 8, (UInt32)c );
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
/*--- The back end proper ---*/
|
||||
/*---------------------------------------------------*/
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void makeMaps_e ( EState* s )
|
||||
{
|
||||
Int32 i;
|
||||
s->nInUse = 0;
|
||||
for (i = 0; i < 256; i++)
|
||||
if (s->inUse[i]) {
|
||||
s->unseqToSeq[i] = s->nInUse;
|
||||
s->nInUse++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void generateMTFValues ( EState* s )
|
||||
{
|
||||
UChar yy[256];
|
||||
Int32 i, j;
|
||||
Int32 zPend;
|
||||
Int32 wr;
|
||||
Int32 EOB;
|
||||
|
||||
/*
|
||||
After sorting (eg, here),
|
||||
s->arr1 [ 0 .. s->nblock-1 ] holds sorted order,
|
||||
and
|
||||
((UChar*)s->arr2) [ 0 .. s->nblock-1 ]
|
||||
holds the original block data.
|
||||
|
||||
The first thing to do is generate the MTF values,
|
||||
and put them in
|
||||
((UInt16*)s->arr1) [ 0 .. s->nblock-1 ].
|
||||
Because there are strictly fewer or equal MTF values
|
||||
than block values, ptr values in this area are overwritten
|
||||
with MTF values only when they are no longer needed.
|
||||
|
||||
The final compressed bitstream is generated into the
|
||||
area starting at
|
||||
(UChar*) (&((UChar*)s->arr2)[s->nblock])
|
||||
|
||||
These storage aliases are set up in bzCompressInit(),
|
||||
except for the last one, which is arranged in
|
||||
compressBlock().
|
||||
*/
|
||||
UInt32* ptr = s->ptr;
|
||||
UChar* block = s->block;
|
||||
UInt16* mtfv = s->mtfv;
|
||||
|
||||
makeMaps_e ( s );
|
||||
EOB = s->nInUse+1;
|
||||
|
||||
for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0;
|
||||
|
||||
wr = 0;
|
||||
zPend = 0;
|
||||
for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i;
|
||||
|
||||
for (i = 0; i < s->nblock; i++) {
|
||||
UChar ll_i;
|
||||
AssertD ( wr <= i, "generateMTFValues(1)" );
|
||||
j = ptr[i]-1; if (j < 0) j += s->nblock;
|
||||
ll_i = s->unseqToSeq[block[j]];
|
||||
AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" );
|
||||
|
||||
if (yy[0] == ll_i) {
|
||||
zPend++;
|
||||
} else {
|
||||
|
||||
if (zPend > 0) {
|
||||
zPend--;
|
||||
while (True) {
|
||||
if (zPend & 1) {
|
||||
mtfv[wr] = BZ_RUNB; wr++;
|
||||
s->mtfFreq[BZ_RUNB]++;
|
||||
} else {
|
||||
mtfv[wr] = BZ_RUNA; wr++;
|
||||
s->mtfFreq[BZ_RUNA]++;
|
||||
}
|
||||
if (zPend < 2) break;
|
||||
zPend = (zPend - 2) / 2;
|
||||
};
|
||||
zPend = 0;
|
||||
}
|
||||
{
|
||||
register UChar rtmp;
|
||||
register UChar* ryy_j;
|
||||
register UChar rll_i;
|
||||
rtmp = yy[1];
|
||||
yy[1] = yy[0];
|
||||
ryy_j = &(yy[1]);
|
||||
rll_i = ll_i;
|
||||
while ( rll_i != rtmp ) {
|
||||
register UChar rtmp2;
|
||||
ryy_j++;
|
||||
rtmp2 = rtmp;
|
||||
rtmp = *ryy_j;
|
||||
*ryy_j = rtmp2;
|
||||
};
|
||||
yy[0] = rtmp;
|
||||
j = ryy_j - &(yy[0]);
|
||||
mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (zPend > 0) {
|
||||
zPend--;
|
||||
while (True) {
|
||||
if (zPend & 1) {
|
||||
mtfv[wr] = BZ_RUNB; wr++;
|
||||
s->mtfFreq[BZ_RUNB]++;
|
||||
} else {
|
||||
mtfv[wr] = BZ_RUNA; wr++;
|
||||
s->mtfFreq[BZ_RUNA]++;
|
||||
}
|
||||
if (zPend < 2) break;
|
||||
zPend = (zPend - 2) / 2;
|
||||
};
|
||||
zPend = 0;
|
||||
}
|
||||
|
||||
mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++;
|
||||
|
||||
s->nMTF = wr;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define BZ_LESSER_ICOST 0
|
||||
#define BZ_GREATER_ICOST 15
|
||||
|
||||
static
|
||||
void sendMTFValues ( EState* s )
|
||||
{
|
||||
Int32 v, t, i, j, gs, ge, totc, bt, bc, iter;
|
||||
Int32 nSelectors, alphaSize, minLen, maxLen, selCtr;
|
||||
Int32 nGroups, nBytes;
|
||||
|
||||
/*--
|
||||
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
is a global since the decoder also needs it.
|
||||
|
||||
Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
are also globals only used in this proc.
|
||||
Made global to keep stack frame size small.
|
||||
--*/
|
||||
|
||||
|
||||
UInt16 cost[BZ_N_GROUPS];
|
||||
Int32 fave[BZ_N_GROUPS];
|
||||
|
||||
UInt16* mtfv = s->mtfv;
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf3( " %d in block, %d after MTF & 1-2 coding, "
|
||||
"%d+2 syms in use\n",
|
||||
s->nblock, s->nMTF, s->nInUse );
|
||||
|
||||
alphaSize = s->nInUse+2;
|
||||
for (t = 0; t < BZ_N_GROUPS; t++)
|
||||
for (v = 0; v < alphaSize; v++)
|
||||
s->len[t][v] = BZ_GREATER_ICOST;
|
||||
|
||||
/*--- Decide how many coding tables to use ---*/
|
||||
AssertH ( s->nMTF > 0, 3001 );
|
||||
if (s->nMTF < 200) nGroups = 2; else
|
||||
if (s->nMTF < 600) nGroups = 3; else
|
||||
if (s->nMTF < 1200) nGroups = 4; else
|
||||
if (s->nMTF < 2400) nGroups = 5; else
|
||||
nGroups = 6;
|
||||
|
||||
/*--- Generate an initial set of coding tables ---*/
|
||||
{
|
||||
Int32 nPart, remF, tFreq, aFreq;
|
||||
|
||||
nPart = nGroups;
|
||||
remF = s->nMTF;
|
||||
gs = 0;
|
||||
while (nPart > 0) {
|
||||
tFreq = remF / nPart;
|
||||
ge = gs-1;
|
||||
aFreq = 0;
|
||||
while (aFreq < tFreq && ge < alphaSize-1) {
|
||||
ge++;
|
||||
aFreq += s->mtfFreq[ge];
|
||||
}
|
||||
|
||||
if (ge > gs
|
||||
&& nPart != nGroups && nPart != 1
|
||||
&& ((nGroups-nPart) % 2 == 1)) {
|
||||
aFreq -= s->mtfFreq[ge];
|
||||
ge--;
|
||||
}
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf5( " initial group %d, [%d .. %d], "
|
||||
"has %d syms (%4.1f%%)\n",
|
||||
nPart, gs, ge, aFreq,
|
||||
(100.0 * (float)aFreq) / (float)(s->nMTF) );
|
||||
|
||||
for (v = 0; v < alphaSize; v++)
|
||||
if (v >= gs && v <= ge)
|
||||
s->len[nPart-1][v] = BZ_LESSER_ICOST; else
|
||||
s->len[nPart-1][v] = BZ_GREATER_ICOST;
|
||||
|
||||
nPart--;
|
||||
gs = ge+1;
|
||||
remF -= aFreq;
|
||||
}
|
||||
}
|
||||
|
||||
/*---
|
||||
Iterate up to BZ_N_ITERS times to improve the tables.
|
||||
---*/
|
||||
for (iter = 0; iter < BZ_N_ITERS; iter++) {
|
||||
|
||||
for (t = 0; t < nGroups; t++) fave[t] = 0;
|
||||
|
||||
for (t = 0; t < nGroups; t++)
|
||||
for (v = 0; v < alphaSize; v++)
|
||||
s->rfreq[t][v] = 0;
|
||||
|
||||
/*---
|
||||
Set up an auxiliary length table which is used to fast-track
|
||||
the common case (nGroups == 6).
|
||||
---*/
|
||||
if (nGroups == 6) {
|
||||
for (v = 0; v < alphaSize; v++) {
|
||||
s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v];
|
||||
s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v];
|
||||
s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v];
|
||||
}
|
||||
}
|
||||
|
||||
nSelectors = 0;
|
||||
totc = 0;
|
||||
gs = 0;
|
||||
while (True) {
|
||||
|
||||
/*--- Set group start & end marks. --*/
|
||||
if (gs >= s->nMTF) break;
|
||||
ge = gs + BZ_G_SIZE - 1;
|
||||
if (ge >= s->nMTF) ge = s->nMTF-1;
|
||||
|
||||
/*--
|
||||
Calculate the cost of this group as coded
|
||||
by each of the coding tables.
|
||||
--*/
|
||||
for (t = 0; t < nGroups; t++) cost[t] = 0;
|
||||
|
||||
if (nGroups == 6 && 50 == ge-gs+1) {
|
||||
/*--- fast track the common case ---*/
|
||||
register UInt32 cost01, cost23, cost45;
|
||||
register UInt16 icv;
|
||||
cost01 = cost23 = cost45 = 0;
|
||||
|
||||
# define BZ_ITER(nn) \
|
||||
icv = mtfv[gs+(nn)]; \
|
||||
cost01 += s->len_pack[icv][0]; \
|
||||
cost23 += s->len_pack[icv][1]; \
|
||||
cost45 += s->len_pack[icv][2]; \
|
||||
|
||||
BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4);
|
||||
BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9);
|
||||
BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14);
|
||||
BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19);
|
||||
BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24);
|
||||
BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29);
|
||||
BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34);
|
||||
BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39);
|
||||
BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44);
|
||||
BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49);
|
||||
|
||||
# undef BZ_ITER
|
||||
|
||||
cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16;
|
||||
cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16;
|
||||
cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16;
|
||||
|
||||
} else {
|
||||
/*--- slow version which correctly handles all situations ---*/
|
||||
for (i = gs; i <= ge; i++) {
|
||||
UInt16 icv = mtfv[i];
|
||||
for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv];
|
||||
}
|
||||
}
|
||||
|
||||
/*--
|
||||
Find the coding table which is best for this group,
|
||||
and record its identity in the selector table.
|
||||
--*/
|
||||
bc = 999999999; bt = -1;
|
||||
for (t = 0; t < nGroups; t++)
|
||||
if (cost[t] < bc) { bc = cost[t]; bt = t; };
|
||||
totc += bc;
|
||||
fave[bt]++;
|
||||
s->selector[nSelectors] = bt;
|
||||
nSelectors++;
|
||||
|
||||
/*--
|
||||
Increment the symbol frequencies for the selected table.
|
||||
--*/
|
||||
if (nGroups == 6 && 50 == ge-gs+1) {
|
||||
/*--- fast track the common case ---*/
|
||||
|
||||
# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++
|
||||
|
||||
BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4);
|
||||
BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9);
|
||||
BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14);
|
||||
BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19);
|
||||
BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24);
|
||||
BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29);
|
||||
BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34);
|
||||
BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39);
|
||||
BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44);
|
||||
BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49);
|
||||
|
||||
# undef BZ_ITUR
|
||||
|
||||
} else {
|
||||
/*--- slow version which correctly handles all situations ---*/
|
||||
for (i = gs; i <= ge; i++)
|
||||
s->rfreq[bt][ mtfv[i] ]++;
|
||||
}
|
||||
|
||||
gs = ge+1;
|
||||
}
|
||||
if (s->verbosity >= 3) {
|
||||
VPrintf2 ( " pass %d: size is %d, grp uses are ",
|
||||
iter+1, totc/8 );
|
||||
for (t = 0; t < nGroups; t++)
|
||||
VPrintf1 ( "%d ", fave[t] );
|
||||
VPrintf0 ( "\n" );
|
||||
}
|
||||
|
||||
/*--
|
||||
Recompute the tables based on the accumulated frequencies.
|
||||
--*/
|
||||
/* maxLen was changed from 20 to 17 in bzip2-1.0.3. See
|
||||
comment in huffman.c for details. */
|
||||
for (t = 0; t < nGroups; t++)
|
||||
BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]),
|
||||
alphaSize, 17 /*20*/ );
|
||||
}
|
||||
|
||||
|
||||
AssertH( nGroups < 8, 3002 );
|
||||
AssertH( nSelectors < 32768 &&
|
||||
nSelectors <= BZ_MAX_SELECTORS,
|
||||
3003 );
|
||||
|
||||
|
||||
/*--- Compute MTF values for the selectors. ---*/
|
||||
{
|
||||
UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp;
|
||||
for (i = 0; i < nGroups; i++) pos[i] = i;
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
ll_i = s->selector[i];
|
||||
j = 0;
|
||||
tmp = pos[j];
|
||||
while ( ll_i != tmp ) {
|
||||
j++;
|
||||
tmp2 = tmp;
|
||||
tmp = pos[j];
|
||||
pos[j] = tmp2;
|
||||
};
|
||||
pos[0] = tmp;
|
||||
s->selectorMtf[i] = j;
|
||||
}
|
||||
};
|
||||
|
||||
/*--- Assign actual codes for the tables. --*/
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
minLen = 32;
|
||||
maxLen = 0;
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
|
||||
if (s->len[t][i] < minLen) minLen = s->len[t][i];
|
||||
}
|
||||
AssertH ( !(maxLen > 17 /*20*/ ), 3004 );
|
||||
AssertH ( !(minLen < 1), 3005 );
|
||||
BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]),
|
||||
minLen, maxLen, alphaSize );
|
||||
}
|
||||
|
||||
/*--- Transmit the mapping table. ---*/
|
||||
{
|
||||
Bool inUse16[16];
|
||||
for (i = 0; i < 16; i++) {
|
||||
inUse16[i] = False;
|
||||
for (j = 0; j < 16; j++)
|
||||
if (s->inUse[i * 16 + j]) inUse16[i] = True;
|
||||
}
|
||||
|
||||
nBytes = s->numZ;
|
||||
for (i = 0; i < 16; i++)
|
||||
if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0);
|
||||
|
||||
for (i = 0; i < 16; i++)
|
||||
if (inUse16[i])
|
||||
for (j = 0; j < 16; j++) {
|
||||
if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0);
|
||||
}
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes );
|
||||
}
|
||||
|
||||
/*--- Now the selectors. ---*/
|
||||
nBytes = s->numZ;
|
||||
bsW ( s, 3, nGroups );
|
||||
bsW ( s, 15, nSelectors );
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1);
|
||||
bsW(s,1,0);
|
||||
}
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1( "selectors %d, ", s->numZ-nBytes );
|
||||
|
||||
/*--- Now the coding tables. ---*/
|
||||
nBytes = s->numZ;
|
||||
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
Int32 curr = s->len[t][0];
|
||||
bsW ( s, 5, curr );
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ };
|
||||
while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ };
|
||||
bsW ( s, 1, 0 );
|
||||
}
|
||||
}
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1 ( "code lengths %d, ", s->numZ-nBytes );
|
||||
|
||||
/*--- And finally, the block data proper ---*/
|
||||
nBytes = s->numZ;
|
||||
selCtr = 0;
|
||||
gs = 0;
|
||||
while (True) {
|
||||
if (gs >= s->nMTF) break;
|
||||
ge = gs + BZ_G_SIZE - 1;
|
||||
if (ge >= s->nMTF) ge = s->nMTF-1;
|
||||
AssertH ( s->selector[selCtr] < nGroups, 3006 );
|
||||
|
||||
if (nGroups == 6 && 50 == ge-gs+1) {
|
||||
/*--- fast track the common case ---*/
|
||||
UInt16 mtfv_i;
|
||||
UChar* s_len_sel_selCtr
|
||||
= &(s->len[s->selector[selCtr]][0]);
|
||||
Int32* s_code_sel_selCtr
|
||||
= &(s->code[s->selector[selCtr]][0]);
|
||||
|
||||
# define BZ_ITAH(nn) \
|
||||
mtfv_i = mtfv[gs+(nn)]; \
|
||||
bsW ( s, \
|
||||
s_len_sel_selCtr[mtfv_i], \
|
||||
s_code_sel_selCtr[mtfv_i] )
|
||||
|
||||
BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4);
|
||||
BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9);
|
||||
BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14);
|
||||
BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19);
|
||||
BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24);
|
||||
BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29);
|
||||
BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34);
|
||||
BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39);
|
||||
BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44);
|
||||
BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49);
|
||||
|
||||
# undef BZ_ITAH
|
||||
|
||||
} else {
|
||||
/*--- slow version which correctly handles all situations ---*/
|
||||
for (i = gs; i <= ge; i++) {
|
||||
bsW ( s,
|
||||
s->len [s->selector[selCtr]] [mtfv[i]],
|
||||
s->code [s->selector[selCtr]] [mtfv[i]] );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
gs = ge+1;
|
||||
selCtr++;
|
||||
}
|
||||
AssertH( selCtr == nSelectors, 3007 );
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1( "codes %d\n", s->numZ-nBytes );
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_compressBlock ( EState* s, Bool is_last_block )
|
||||
{
|
||||
if (s->nblock > 0) {
|
||||
|
||||
BZ_FINALISE_CRC ( s->blockCRC );
|
||||
s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31);
|
||||
s->combinedCRC ^= s->blockCRC;
|
||||
if (s->blockNo > 1) s->numZ = 0;
|
||||
|
||||
if (s->verbosity >= 2)
|
||||
VPrintf4( " block %d: crc = 0x%08x, "
|
||||
"combined CRC = 0x%08x, size = %d\n",
|
||||
s->blockNo, s->blockCRC, s->combinedCRC, s->nblock );
|
||||
|
||||
BZ2_blockSort ( s );
|
||||
}
|
||||
|
||||
s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]);
|
||||
|
||||
/*-- If this is the first block, create the stream header. --*/
|
||||
if (s->blockNo == 1) {
|
||||
BZ2_bsInitWrite ( s );
|
||||
bsPutUChar ( s, BZ_HDR_B );
|
||||
bsPutUChar ( s, BZ_HDR_Z );
|
||||
bsPutUChar ( s, BZ_HDR_h );
|
||||
bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) );
|
||||
}
|
||||
|
||||
if (s->nblock > 0) {
|
||||
|
||||
bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 );
|
||||
bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 );
|
||||
bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 );
|
||||
|
||||
/*-- Now the block's CRC, so it is in a known place. --*/
|
||||
bsPutUInt32 ( s, s->blockCRC );
|
||||
|
||||
/*--
|
||||
Now a single bit indicating (non-)randomisation.
|
||||
As of version 0.9.5, we use a better sorting algorithm
|
||||
which makes randomisation unnecessary. So always set
|
||||
the randomised bit to 'no'. Of course, the decoder
|
||||
still needs to be able to handle randomised blocks
|
||||
so as to maintain backwards compatibility with
|
||||
older versions of bzip2.
|
||||
--*/
|
||||
bsW(s,1,0);
|
||||
|
||||
bsW ( s, 24, s->origPtr );
|
||||
generateMTFValues ( s );
|
||||
sendMTFValues ( s );
|
||||
}
|
||||
|
||||
|
||||
/*-- If this is the last block, add the stream trailer. --*/
|
||||
if (is_last_block) {
|
||||
|
||||
bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 );
|
||||
bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 );
|
||||
bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 );
|
||||
bsPutUInt32 ( s, s->combinedCRC );
|
||||
if (s->verbosity >= 2)
|
||||
VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC );
|
||||
bsFinishWrite ( s );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end compress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
/* bzip2 source intentionally removed on this fork.
|
||||
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||
@@ -1,652 +1,3 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Decompression machinery ---*/
|
||||
/*--- decompress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void makeMaps_d ( DState* s )
|
||||
{
|
||||
Int32 i;
|
||||
s->nInUse = 0;
|
||||
for (i = 0; i < 256; i++)
|
||||
if (s->inUse[i]) {
|
||||
s->seqToUnseq[s->nInUse] = i;
|
||||
s->nInUse++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define RETURN(rrr) \
|
||||
{ retVal = rrr; goto save_state_and_return; };
|
||||
|
||||
#define GET_BITS(lll,vvv,nnn) \
|
||||
case lll: s->state = lll; \
|
||||
while (True) { \
|
||||
if (s->bsLive >= nnn) { \
|
||||
UInt32 v; \
|
||||
v = (s->bsBuff >> \
|
||||
(s->bsLive-nnn)) & ((1 << nnn)-1); \
|
||||
s->bsLive -= nnn; \
|
||||
vvv = v; \
|
||||
break; \
|
||||
} \
|
||||
if (s->strm->avail_in == 0) RETURN(BZ_OK); \
|
||||
s->bsBuff \
|
||||
= (s->bsBuff << 8) | \
|
||||
((UInt32) \
|
||||
(*((UChar*)(s->strm->next_in)))); \
|
||||
s->bsLive += 8; \
|
||||
s->strm->next_in++; \
|
||||
s->strm->avail_in--; \
|
||||
s->strm->total_in_lo32++; \
|
||||
if (s->strm->total_in_lo32 == 0) \
|
||||
s->strm->total_in_hi32++; \
|
||||
}
|
||||
|
||||
#define GET_UCHAR(lll,uuu) \
|
||||
GET_BITS(lll,uuu,8)
|
||||
|
||||
#define GET_BIT(lll,uuu) \
|
||||
GET_BITS(lll,uuu,1)
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define GET_MTF_VAL(label1,label2,lval) \
|
||||
{ \
|
||||
if (groupPos == 0) { \
|
||||
groupNo++; \
|
||||
if (groupNo >= nSelectors) \
|
||||
RETURN(BZ_DATA_ERROR); \
|
||||
groupPos = BZ_G_SIZE; \
|
||||
gSel = s->selector[groupNo]; \
|
||||
gMinlen = s->minLens[gSel]; \
|
||||
gLimit = &(s->limit[gSel][0]); \
|
||||
gPerm = &(s->perm[gSel][0]); \
|
||||
gBase = &(s->base[gSel][0]); \
|
||||
} \
|
||||
groupPos--; \
|
||||
zn = gMinlen; \
|
||||
GET_BITS(label1, zvec, zn); \
|
||||
while (1) { \
|
||||
if (zn > 20 /* the longest code */) \
|
||||
RETURN(BZ_DATA_ERROR); \
|
||||
if (zvec <= gLimit[zn]) break; \
|
||||
zn++; \
|
||||
GET_BIT(label2, zj); \
|
||||
zvec = (zvec << 1) | zj; \
|
||||
}; \
|
||||
if (zvec - gBase[zn] < 0 \
|
||||
|| zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \
|
||||
RETURN(BZ_DATA_ERROR); \
|
||||
lval = gPerm[zvec - gBase[zn]]; \
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
Int32 BZ2_decompress ( DState* s )
|
||||
{
|
||||
UChar uc;
|
||||
Int32 retVal;
|
||||
Int32 minLen, maxLen;
|
||||
bz_stream* strm = s->strm;
|
||||
|
||||
/* stuff that needs to be saved/restored */
|
||||
Int32 i;
|
||||
Int32 j;
|
||||
Int32 t;
|
||||
Int32 alphaSize;
|
||||
Int32 nGroups;
|
||||
Int32 nSelectors;
|
||||
Int32 EOB;
|
||||
Int32 groupNo;
|
||||
Int32 groupPos;
|
||||
Int32 nextSym;
|
||||
Int32 nblockMAX;
|
||||
Int32 nblock;
|
||||
Int32 es;
|
||||
Int32 N;
|
||||
Int32 curr;
|
||||
Int32 zt;
|
||||
Int32 zn;
|
||||
Int32 zvec;
|
||||
Int32 zj;
|
||||
Int32 gSel;
|
||||
Int32 gMinlen;
|
||||
Int32* gLimit;
|
||||
Int32* gBase;
|
||||
Int32* gPerm;
|
||||
|
||||
if (s->state == BZ_X_MAGIC_1) {
|
||||
/*initialise the save area*/
|
||||
s->save_i = 0;
|
||||
s->save_j = 0;
|
||||
s->save_t = 0;
|
||||
s->save_alphaSize = 0;
|
||||
s->save_nGroups = 0;
|
||||
s->save_nSelectors = 0;
|
||||
s->save_EOB = 0;
|
||||
s->save_groupNo = 0;
|
||||
s->save_groupPos = 0;
|
||||
s->save_nextSym = 0;
|
||||
s->save_nblockMAX = 0;
|
||||
s->save_nblock = 0;
|
||||
s->save_es = 0;
|
||||
s->save_N = 0;
|
||||
s->save_curr = 0;
|
||||
s->save_zt = 0;
|
||||
s->save_zn = 0;
|
||||
s->save_zvec = 0;
|
||||
s->save_zj = 0;
|
||||
s->save_gSel = 0;
|
||||
s->save_gMinlen = 0;
|
||||
s->save_gLimit = NULL;
|
||||
s->save_gBase = NULL;
|
||||
s->save_gPerm = NULL;
|
||||
}
|
||||
|
||||
/*restore from the save area*/
|
||||
i = s->save_i;
|
||||
j = s->save_j;
|
||||
t = s->save_t;
|
||||
alphaSize = s->save_alphaSize;
|
||||
nGroups = s->save_nGroups;
|
||||
nSelectors = s->save_nSelectors;
|
||||
EOB = s->save_EOB;
|
||||
groupNo = s->save_groupNo;
|
||||
groupPos = s->save_groupPos;
|
||||
nextSym = s->save_nextSym;
|
||||
nblockMAX = s->save_nblockMAX;
|
||||
nblock = s->save_nblock;
|
||||
es = s->save_es;
|
||||
N = s->save_N;
|
||||
curr = s->save_curr;
|
||||
zt = s->save_zt;
|
||||
zn = s->save_zn;
|
||||
zvec = s->save_zvec;
|
||||
zj = s->save_zj;
|
||||
gSel = s->save_gSel;
|
||||
gMinlen = s->save_gMinlen;
|
||||
gLimit = s->save_gLimit;
|
||||
gBase = s->save_gBase;
|
||||
gPerm = s->save_gPerm;
|
||||
|
||||
retVal = BZ_OK;
|
||||
|
||||
switch (s->state) {
|
||||
|
||||
GET_UCHAR(BZ_X_MAGIC_1, uc);
|
||||
if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
|
||||
GET_UCHAR(BZ_X_MAGIC_2, uc);
|
||||
if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
|
||||
GET_UCHAR(BZ_X_MAGIC_3, uc)
|
||||
if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
|
||||
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
|
||||
if (s->blockSize100k < (BZ_HDR_0 + 1) ||
|
||||
s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
s->blockSize100k -= BZ_HDR_0;
|
||||
|
||||
if (s->smallDecompress) {
|
||||
s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
|
||||
s->ll4 = BZALLOC(
|
||||
((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
|
||||
);
|
||||
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
|
||||
} else {
|
||||
s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );
|
||||
if (s->tt == NULL) RETURN(BZ_MEM_ERROR);
|
||||
}
|
||||
|
||||
GET_UCHAR(BZ_X_BLKHDR_1, uc);
|
||||
|
||||
if (uc == 0x17) goto endhdr_2;
|
||||
if (uc != 0x31) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_2, uc);
|
||||
if (uc != 0x41) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_3, uc);
|
||||
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_4, uc);
|
||||
if (uc != 0x26) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_5, uc);
|
||||
if (uc != 0x53) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_6, uc);
|
||||
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
|
||||
|
||||
s->currBlockNo++;
|
||||
if (s->verbosity >= 2)
|
||||
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
|
||||
|
||||
s->storedBlockCRC = 0;
|
||||
GET_UCHAR(BZ_X_BCRC_1, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_BCRC_2, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_BCRC_3, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_BCRC_4, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
|
||||
GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);
|
||||
|
||||
s->origPtr = 0;
|
||||
GET_UCHAR(BZ_X_ORIGPTR_1, uc);
|
||||
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
|
||||
GET_UCHAR(BZ_X_ORIGPTR_2, uc);
|
||||
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
|
||||
GET_UCHAR(BZ_X_ORIGPTR_3, uc);
|
||||
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
|
||||
|
||||
if (s->origPtr < 0)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
if (s->origPtr > 10 + 100000*s->blockSize100k)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
|
||||
/*--- Receive the mapping table ---*/
|
||||
for (i = 0; i < 16; i++) {
|
||||
GET_BIT(BZ_X_MAPPING_1, uc);
|
||||
if (uc == 1)
|
||||
s->inUse16[i] = True; else
|
||||
s->inUse16[i] = False;
|
||||
}
|
||||
|
||||
for (i = 0; i < 256; i++) s->inUse[i] = False;
|
||||
|
||||
for (i = 0; i < 16; i++)
|
||||
if (s->inUse16[i])
|
||||
for (j = 0; j < 16; j++) {
|
||||
GET_BIT(BZ_X_MAPPING_2, uc);
|
||||
if (uc == 1) s->inUse[i * 16 + j] = True;
|
||||
}
|
||||
makeMaps_d ( s );
|
||||
if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);
|
||||
alphaSize = s->nInUse+2;
|
||||
|
||||
/*--- Now the selectors ---*/
|
||||
GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);
|
||||
if (nGroups < 2 || nGroups > BZ_N_GROUPS) RETURN(BZ_DATA_ERROR);
|
||||
GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);
|
||||
if (nSelectors < 1) RETURN(BZ_DATA_ERROR);
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
j = 0;
|
||||
while (True) {
|
||||
GET_BIT(BZ_X_SELECTOR_3, uc);
|
||||
if (uc == 0) break;
|
||||
j++;
|
||||
if (j >= nGroups) RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
/* Having more than BZ_MAX_SELECTORS doesn't make much sense
|
||||
since they will never be used, but some implementations might
|
||||
"round up" the number of selectors, so just ignore those. */
|
||||
if (i < BZ_MAX_SELECTORS)
|
||||
s->selectorMtf[i] = j;
|
||||
}
|
||||
if (nSelectors > BZ_MAX_SELECTORS)
|
||||
nSelectors = BZ_MAX_SELECTORS;
|
||||
|
||||
/*--- Undo the MTF values for the selectors. ---*/
|
||||
{
|
||||
UChar pos[BZ_N_GROUPS], tmp, v;
|
||||
for (v = 0; v < nGroups; v++) pos[v] = v;
|
||||
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
v = s->selectorMtf[i];
|
||||
tmp = pos[v];
|
||||
while (v > 0) { pos[v] = pos[v-1]; v--; }
|
||||
pos[0] = tmp;
|
||||
s->selector[i] = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
/*--- Now the coding tables ---*/
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
GET_BITS(BZ_X_CODING_1, curr, 5);
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
while (True) {
|
||||
if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);
|
||||
GET_BIT(BZ_X_CODING_2, uc);
|
||||
if (uc == 0) break;
|
||||
GET_BIT(BZ_X_CODING_3, uc);
|
||||
if (uc == 0) curr++; else curr--;
|
||||
}
|
||||
s->len[t][i] = curr;
|
||||
}
|
||||
}
|
||||
|
||||
/*--- Create the Huffman decoding tables ---*/
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
minLen = 32;
|
||||
maxLen = 0;
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
|
||||
if (s->len[t][i] < minLen) minLen = s->len[t][i];
|
||||
}
|
||||
BZ2_hbCreateDecodeTables (
|
||||
&(s->limit[t][0]),
|
||||
&(s->base[t][0]),
|
||||
&(s->perm[t][0]),
|
||||
&(s->len[t][0]),
|
||||
minLen, maxLen, alphaSize
|
||||
);
|
||||
s->minLens[t] = minLen;
|
||||
}
|
||||
|
||||
/*--- Now the MTF values ---*/
|
||||
|
||||
EOB = s->nInUse+1;
|
||||
nblockMAX = 100000 * s->blockSize100k;
|
||||
groupNo = -1;
|
||||
groupPos = 0;
|
||||
|
||||
for (i = 0; i <= 255; i++) s->unzftab[i] = 0;
|
||||
|
||||
/*-- MTF init --*/
|
||||
{
|
||||
Int32 ii, jj, kk;
|
||||
kk = MTFA_SIZE-1;
|
||||
for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {
|
||||
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
|
||||
s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);
|
||||
kk--;
|
||||
}
|
||||
s->mtfbase[ii] = kk + 1;
|
||||
}
|
||||
}
|
||||
/*-- end MTF init --*/
|
||||
|
||||
nblock = 0;
|
||||
GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);
|
||||
|
||||
while (True) {
|
||||
|
||||
if (nextSym == EOB) break;
|
||||
|
||||
if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {
|
||||
|
||||
es = -1;
|
||||
N = 1;
|
||||
do {
|
||||
/* Check that N doesn't get too big, so that es doesn't
|
||||
go negative. The maximum value that can be
|
||||
RUNA/RUNB encoded is equal to the block size (post
|
||||
the initial RLE), viz, 900k, so bounding N at 2
|
||||
million should guard against overflow without
|
||||
rejecting any legitimate inputs. */
|
||||
if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);
|
||||
if (nextSym == BZ_RUNA) es = es + (0+1) * N; else
|
||||
if (nextSym == BZ_RUNB) es = es + (1+1) * N;
|
||||
N = N * 2;
|
||||
GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);
|
||||
}
|
||||
while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);
|
||||
|
||||
es++;
|
||||
uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];
|
||||
s->unzftab[uc] += es;
|
||||
|
||||
if (s->smallDecompress)
|
||||
while (es > 0) {
|
||||
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
|
||||
s->ll16[nblock] = (UInt16)uc;
|
||||
nblock++;
|
||||
es--;
|
||||
}
|
||||
else
|
||||
while (es > 0) {
|
||||
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
|
||||
s->tt[nblock] = (UInt32)uc;
|
||||
nblock++;
|
||||
es--;
|
||||
};
|
||||
|
||||
continue;
|
||||
|
||||
} else {
|
||||
|
||||
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
|
||||
|
||||
/*-- uc = MTF ( nextSym-1 ) --*/
|
||||
{
|
||||
Int32 ii, jj, kk, pp, lno, off;
|
||||
UInt32 nn;
|
||||
nn = (UInt32)(nextSym - 1);
|
||||
|
||||
if (nn < MTFL_SIZE) {
|
||||
/* avoid general-case expense */
|
||||
pp = s->mtfbase[0];
|
||||
uc = s->mtfa[pp+nn];
|
||||
while (nn > 3) {
|
||||
Int32 z = pp+nn;
|
||||
s->mtfa[(z) ] = s->mtfa[(z)-1];
|
||||
s->mtfa[(z)-1] = s->mtfa[(z)-2];
|
||||
s->mtfa[(z)-2] = s->mtfa[(z)-3];
|
||||
s->mtfa[(z)-3] = s->mtfa[(z)-4];
|
||||
nn -= 4;
|
||||
}
|
||||
while (nn > 0) {
|
||||
s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
|
||||
};
|
||||
s->mtfa[pp] = uc;
|
||||
} else {
|
||||
/* general case */
|
||||
lno = nn / MTFL_SIZE;
|
||||
off = nn % MTFL_SIZE;
|
||||
pp = s->mtfbase[lno] + off;
|
||||
uc = s->mtfa[pp];
|
||||
while (pp > s->mtfbase[lno]) {
|
||||
s->mtfa[pp] = s->mtfa[pp-1]; pp--;
|
||||
};
|
||||
s->mtfbase[lno]++;
|
||||
while (lno > 0) {
|
||||
s->mtfbase[lno]--;
|
||||
s->mtfa[s->mtfbase[lno]]
|
||||
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
|
||||
lno--;
|
||||
}
|
||||
s->mtfbase[0]--;
|
||||
s->mtfa[s->mtfbase[0]] = uc;
|
||||
if (s->mtfbase[0] == 0) {
|
||||
kk = MTFA_SIZE-1;
|
||||
for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {
|
||||
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
|
||||
s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];
|
||||
kk--;
|
||||
}
|
||||
s->mtfbase[ii] = kk + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*-- end uc = MTF ( nextSym-1 ) --*/
|
||||
|
||||
s->unzftab[s->seqToUnseq[uc]]++;
|
||||
if (s->smallDecompress)
|
||||
s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else
|
||||
s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);
|
||||
nblock++;
|
||||
|
||||
GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
/* Now we know what nblock is, we can do a better sanity
|
||||
check on s->origPtr.
|
||||
*/
|
||||
if (s->origPtr < 0 || s->origPtr >= nblock)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
|
||||
/*-- Set up cftab to facilitate generation of T^(-1) --*/
|
||||
/* Check: unzftab entries in range. */
|
||||
for (i = 0; i <= 255; i++) {
|
||||
if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
/* Actually generate cftab. */
|
||||
s->cftab[0] = 0;
|
||||
for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];
|
||||
for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];
|
||||
/* Check: cftab entries in range. */
|
||||
for (i = 0; i <= 256; i++) {
|
||||
if (s->cftab[i] < 0 || s->cftab[i] > nblock) {
|
||||
/* s->cftab[i] can legitimately be == nblock */
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
}
|
||||
/* Check: cftab entries non-descending. */
|
||||
for (i = 1; i <= 256; i++) {
|
||||
if (s->cftab[i-1] > s->cftab[i]) {
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
s->state_out_len = 0;
|
||||
s->state_out_ch = 0;
|
||||
BZ_INITIALISE_CRC ( s->calculatedBlockCRC );
|
||||
s->state = BZ_X_OUTPUT;
|
||||
if (s->verbosity >= 2) VPrintf0 ( "rt+rld" );
|
||||
|
||||
if (s->smallDecompress) {
|
||||
|
||||
/*-- Make a copy of cftab, used in generation of T --*/
|
||||
for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];
|
||||
|
||||
/*-- compute the T vector --*/
|
||||
for (i = 0; i < nblock; i++) {
|
||||
uc = (UChar)(s->ll16[i]);
|
||||
SET_LL(i, s->cftabCopy[uc]);
|
||||
s->cftabCopy[uc]++;
|
||||
}
|
||||
|
||||
/*-- Compute T^(-1) by pointer reversal on T --*/
|
||||
i = s->origPtr;
|
||||
j = GET_LL(i);
|
||||
do {
|
||||
Int32 tmp = GET_LL(j);
|
||||
SET_LL(j, i);
|
||||
i = j;
|
||||
j = tmp;
|
||||
}
|
||||
while (i != s->origPtr);
|
||||
|
||||
s->tPos = s->origPtr;
|
||||
s->nblock_used = 0;
|
||||
if (s->blockRandomised) {
|
||||
BZ_RAND_INIT_MASK;
|
||||
BZ_GET_SMALL(s->k0); s->nblock_used++;
|
||||
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
|
||||
} else {
|
||||
BZ_GET_SMALL(s->k0); s->nblock_used++;
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
/*-- compute the T^(-1) vector --*/
|
||||
for (i = 0; i < nblock; i++) {
|
||||
uc = (UChar)(s->tt[i] & 0xff);
|
||||
s->tt[s->cftab[uc]] |= (i << 8);
|
||||
s->cftab[uc]++;
|
||||
}
|
||||
|
||||
s->tPos = s->tt[s->origPtr] >> 8;
|
||||
s->nblock_used = 0;
|
||||
if (s->blockRandomised) {
|
||||
BZ_RAND_INIT_MASK;
|
||||
BZ_GET_FAST(s->k0); s->nblock_used++;
|
||||
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
|
||||
} else {
|
||||
BZ_GET_FAST(s->k0); s->nblock_used++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
RETURN(BZ_OK);
|
||||
|
||||
|
||||
|
||||
endhdr_2:
|
||||
|
||||
GET_UCHAR(BZ_X_ENDHDR_2, uc);
|
||||
if (uc != 0x72) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_3, uc);
|
||||
if (uc != 0x45) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_4, uc);
|
||||
if (uc != 0x38) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_5, uc);
|
||||
if (uc != 0x50) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_6, uc);
|
||||
if (uc != 0x90) RETURN(BZ_DATA_ERROR);
|
||||
|
||||
s->storedCombinedCRC = 0;
|
||||
GET_UCHAR(BZ_X_CCRC_1, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_CCRC_2, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_CCRC_3, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_CCRC_4, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
|
||||
s->state = BZ_X_IDLE;
|
||||
RETURN(BZ_STREAM_END);
|
||||
|
||||
default: AssertH ( False, 4001 );
|
||||
}
|
||||
|
||||
AssertH ( False, 4002 );
|
||||
|
||||
save_state_and_return:
|
||||
|
||||
s->save_i = i;
|
||||
s->save_j = j;
|
||||
s->save_t = t;
|
||||
s->save_alphaSize = alphaSize;
|
||||
s->save_nGroups = nGroups;
|
||||
s->save_nSelectors = nSelectors;
|
||||
s->save_EOB = EOB;
|
||||
s->save_groupNo = groupNo;
|
||||
s->save_groupPos = groupPos;
|
||||
s->save_nextSym = nextSym;
|
||||
s->save_nblockMAX = nblockMAX;
|
||||
s->save_nblock = nblock;
|
||||
s->save_es = es;
|
||||
s->save_N = N;
|
||||
s->save_curr = curr;
|
||||
s->save_zt = zt;
|
||||
s->save_zn = zn;
|
||||
s->save_zvec = zvec;
|
||||
s->save_zj = zj;
|
||||
s->save_gSel = gSel;
|
||||
s->save_gMinlen = gMinlen;
|
||||
s->save_gLimit = gLimit;
|
||||
s->save_gBase = gBase;
|
||||
s->save_gPerm = gPerm;
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end decompress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
/* bzip2 source intentionally removed on this fork.
|
||||
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||
+3
-1572
File diff suppressed because it is too large.
Load diff
+3
-104
@@ -1,104 +1,3 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Table for doing CRCs ---*/
|
||||
/*--- crctable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
/*--
|
||||
I think this is an implementation of the AUTODIN-II,
|
||||
Ethernet & FDDI 32-bit CRC standard. Vaguely derived
|
||||
from code by Rob Warnock, in Section 51 of the
|
||||
comp.compression FAQ.
|
||||
--*/
|
||||
|
||||
UInt32 BZ2_crc32Table[256] = {
|
||||
|
||||
/*-- Ugly, innit? --*/
|
||||
|
||||
0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L,
|
||||
0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L,
|
||||
0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L,
|
||||
0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL,
|
||||
0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L,
|
||||
0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L,
|
||||
0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L,
|
||||
0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL,
|
||||
0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L,
|
||||
0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L,
|
||||
0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L,
|
||||
0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL,
|
||||
0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L,
|
||||
0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L,
|
||||
0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L,
|
||||
0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL,
|
||||
0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL,
|
||||
0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L,
|
||||
0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L,
|
||||
0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL,
|
||||
0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL,
|
||||
0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L,
|
||||
0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L,
|
||||
0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL,
|
||||
0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL,
|
||||
0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L,
|
||||
0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L,
|
||||
0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL,
|
||||
0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL,
|
||||
0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L,
|
||||
0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L,
|
||||
0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL,
|
||||
0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L,
|
||||
0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL,
|
||||
0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL,
|
||||
0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L,
|
||||
0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L,
|
||||
0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL,
|
||||
0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL,
|
||||
0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L,
|
||||
0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L,
|
||||
0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL,
|
||||
0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL,
|
||||
0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L,
|
||||
0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L,
|
||||
0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL,
|
||||
0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL,
|
||||
0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L,
|
||||
0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L,
|
||||
0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL,
|
||||
0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L,
|
||||
0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L,
|
||||
0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L,
|
||||
0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL,
|
||||
0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L,
|
||||
0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L,
|
||||
0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L,
|
||||
0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL,
|
||||
0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L,
|
||||
0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L,
|
||||
0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L,
|
||||
0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL,
|
||||
0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L,
|
||||
0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L
|
||||
};
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end crctable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
/* bzip2 source intentionally removed on this fork.
|
||||
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||
+3
-205
@@ -1,205 +1,3 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Huffman coding low-level stuff ---*/
|
||||
/*--- huffman.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define WEIGHTOF(zz0) ((zz0) & 0xffffff00)
|
||||
#define DEPTHOF(zz1) ((zz1) & 0x000000ff)
|
||||
#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3))
|
||||
|
||||
#define ADDWEIGHTS(zw1,zw2) \
|
||||
(WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \
|
||||
(1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2)))
|
||||
|
||||
#define UPHEAP(z) \
|
||||
{ \
|
||||
Int32 zz, tmp; \
|
||||
zz = z; tmp = heap[zz]; \
|
||||
while (weight[tmp] < weight[heap[zz >> 1]]) { \
|
||||
heap[zz] = heap[zz >> 1]; \
|
||||
zz >>= 1; \
|
||||
} \
|
||||
heap[zz] = tmp; \
|
||||
}
|
||||
|
||||
#define DOWNHEAP(z) \
|
||||
{ \
|
||||
Int32 zz, yy, tmp; \
|
||||
zz = z; tmp = heap[zz]; \
|
||||
while (True) { \
|
||||
yy = zz << 1; \
|
||||
if (yy > nHeap) break; \
|
||||
if (yy < nHeap && \
|
||||
weight[heap[yy+1]] < weight[heap[yy]]) \
|
||||
yy++; \
|
||||
if (weight[tmp] < weight[heap[yy]]) break; \
|
||||
heap[zz] = heap[yy]; \
|
||||
zz = yy; \
|
||||
} \
|
||||
heap[zz] = tmp; \
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_hbMakeCodeLengths ( UChar *len,
|
||||
Int32 *freq,
|
||||
Int32 alphaSize,
|
||||
Int32 maxLen )
|
||||
{
|
||||
/*--
|
||||
Nodes and heap entries run from 1. Entry 0
|
||||
for both the heap and nodes is a sentinel.
|
||||
--*/
|
||||
Int32 nNodes, nHeap, n1, n2, i, j, k;
|
||||
Bool tooLong;
|
||||
|
||||
Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ];
|
||||
Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ];
|
||||
Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ];
|
||||
|
||||
for (i = 0; i < alphaSize; i++)
|
||||
weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
|
||||
|
||||
while (True) {
|
||||
|
||||
nNodes = alphaSize;
|
||||
nHeap = 0;
|
||||
|
||||
heap[0] = 0;
|
||||
weight[0] = 0;
|
||||
parent[0] = -2;
|
||||
|
||||
for (i = 1; i <= alphaSize; i++) {
|
||||
parent[i] = -1;
|
||||
nHeap++;
|
||||
heap[nHeap] = i;
|
||||
UPHEAP(nHeap);
|
||||
}
|
||||
|
||||
AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 );
|
||||
|
||||
while (nHeap > 1) {
|
||||
n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
|
||||
n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
|
||||
nNodes++;
|
||||
parent[n1] = parent[n2] = nNodes;
|
||||
weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]);
|
||||
parent[nNodes] = -1;
|
||||
nHeap++;
|
||||
heap[nHeap] = nNodes;
|
||||
UPHEAP(nHeap);
|
||||
}
|
||||
|
||||
AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 );
|
||||
|
||||
tooLong = False;
|
||||
for (i = 1; i <= alphaSize; i++) {
|
||||
j = 0;
|
||||
k = i;
|
||||
while (parent[k] >= 0) { k = parent[k]; j++; }
|
||||
len[i-1] = j;
|
||||
if (j > maxLen) tooLong = True;
|
||||
}
|
||||
|
||||
if (! tooLong) break;
|
||||
|
||||
/* 17 Oct 04: keep-going condition for the following loop used
|
||||
to be 'i < alphaSize', which missed the last element,
|
||||
theoretically leading to the possibility of the compressor
|
||||
looping. However, this count-scaling step is only needed if
|
||||
one of the generated Huffman code words is longer than
|
||||
maxLen, which up to and including version 1.0.2 was 20 bits,
|
||||
which is extremely unlikely. In version 1.0.3 maxLen was
|
||||
changed to 17 bits, which has minimal effect on compression
|
||||
ratio, but does mean this scaling step is used from time to
|
||||
time, enough to verify that it works.
|
||||
|
||||
This means that bzip2-1.0.3 and later will only produce
|
||||
Huffman codes with a maximum length of 17 bits. However, in
|
||||
order to preserve backwards compatibility with bitstreams
|
||||
produced by versions pre-1.0.3, the decompressor must still
|
||||
handle lengths of up to 20. */
|
||||
|
||||
for (i = 1; i <= alphaSize; i++) {
|
||||
j = weight[i] >> 8;
|
||||
j = 1 + (j / 2);
|
||||
weight[i] = j << 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_hbAssignCodes ( Int32 *code,
|
||||
UChar *length,
|
||||
Int32 minLen,
|
||||
Int32 maxLen,
|
||||
Int32 alphaSize )
|
||||
{
|
||||
Int32 n, vec, i;
|
||||
|
||||
vec = 0;
|
||||
for (n = minLen; n <= maxLen; n++) {
|
||||
for (i = 0; i < alphaSize; i++)
|
||||
if (length[i] == n) { code[i] = vec; vec++; };
|
||||
vec <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_hbCreateDecodeTables ( Int32 *limit,
|
||||
Int32 *base,
|
||||
Int32 *perm,
|
||||
UChar *length,
|
||||
Int32 minLen,
|
||||
Int32 maxLen,
|
||||
Int32 alphaSize )
|
||||
{
|
||||
Int32 pp, i, j, vec;
|
||||
|
||||
pp = 0;
|
||||
for (i = minLen; i <= maxLen; i++)
|
||||
for (j = 0; j < alphaSize; j++)
|
||||
if (length[j] == i) { perm[pp] = j; pp++; };
|
||||
|
||||
for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0;
|
||||
for (i = 0; i < alphaSize; i++) base[length[i]+1]++;
|
||||
|
||||
for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1];
|
||||
|
||||
for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0;
|
||||
vec = 0;
|
||||
|
||||
for (i = minLen; i <= maxLen; i++) {
|
||||
vec += (base[i+1] - base[i]);
|
||||
limit[i] = vec-1;
|
||||
vec <<= 1;
|
||||
}
|
||||
for (i = minLen + 1; i <= maxLen; i++)
|
||||
base[i] = ((limit[i-1] + 1) << 1) - base[i];
|
||||
}
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end huffman.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
/* bzip2 source intentionally removed on this fork.
|
||||
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||
@@ -1,84 +1,3 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Table for randomising repetitive blocks ---*/
|
||||
/*--- randtable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
|
||||
/*---------------------------------------------*/
|
||||
Int32 BZ2_rNums[512] = {
|
||||
619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
|
||||
985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
|
||||
733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
|
||||
419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
|
||||
878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
|
||||
862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
|
||||
150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
|
||||
170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
|
||||
73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
|
||||
909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
|
||||
641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
|
||||
161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
|
||||
382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
|
||||
98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
|
||||
227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
|
||||
469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
|
||||
184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
|
||||
715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
|
||||
951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
|
||||
652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
|
||||
645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
|
||||
609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
|
||||
653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
|
||||
411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
|
||||
170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
|
||||
857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
|
||||
669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
|
||||
944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
|
||||
344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
|
||||
897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
|
||||
433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
|
||||
686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
|
||||
946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
|
||||
978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
|
||||
680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
|
||||
707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
|
||||
297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
|
||||
134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
|
||||
343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
|
||||
140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
|
||||
170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
|
||||
369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
|
||||
804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
|
||||
896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
|
||||
661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
|
||||
768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
|
||||
61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
|
||||
372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
|
||||
780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
|
||||
920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
|
||||
645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
|
||||
936, 638
|
||||
};
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end randtable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
/* bzip2 source intentionally removed on this fork.
|
||||
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||
+39
-10
@@ -262,9 +262,24 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
|
||||
else {
|
||||
Bytes destination_hash = _object->_hash;
|
||||
//p random_hash = Identity::get_random_hash()[0:5] + int(time.time()).to_bytes(5, "big")
|
||||
// 5 random bytes + 5 big-endian timestamp bytes (matches Python reference)
|
||||
// 5 random bytes + 5 big-endian epoch timestamp bytes (matches Python reference)
|
||||
// CRITICAL: Must use Unix epoch (like Python's time.time()), NOT OS::time()
|
||||
// which returns uptime on Arduino. Python Transport compares these timestamps
|
||||
// for announce freshness — uptime-based values cause re-announces to be
|
||||
// rejected by nodes that have cached a previous epoch-based timestamp.
|
||||
Bytes random_part = Cryptography::random(5);
|
||||
#ifdef ARDUINO
|
||||
// On ESP32, time(nullptr) returns Unix epoch after NTP sync,
|
||||
// or ~0 before sync. Either is better than millis()-based uptime.
|
||||
uint64_t ts = (uint64_t)::time(nullptr);
|
||||
if (ts < 1700000000) {
|
||||
// NTP not yet synced — fall back to OS::time() (uptime seconds).
|
||||
// Not ideal, but the announce will still work for first-time paths.
|
||||
ts = (uint64_t)OS::time();
|
||||
}
|
||||
#else
|
||||
uint64_t ts = (uint64_t)OS::time();
|
||||
#endif
|
||||
uint8_t time_bytes[5];
|
||||
time_bytes[0] = (ts >> 32) & 0xFF;
|
||||
time_bytes[1] = (ts >> 24) & 0xFF;
|
||||
@@ -279,26 +294,27 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
|
||||
}
|
||||
|
||||
Bytes signed_data;
|
||||
//TRACEF("Destination::announce: hash: %s", _object->_hash.toHex().c_str());
|
||||
//TRACEF("Destination::announce: public key: %s", _object->_identity.get_public_key().toHex().c_str());
|
||||
//TRACEF("Destination::announce: name hash: %s", _object->_name_hash.toHex().c_str());
|
||||
//TRACEF("Destination::announce: random hash: %s", random_hash.toHex().c_str());
|
||||
//TRACEF("Destination::announce: app data: %s", new_app_data.toHex().c_str());
|
||||
//TRACEF("Destination::announce: app data text:%s", new_app_data.toString().c_str());
|
||||
TRACEF("[ANN-DIAG] dest_hash: %s", _object->_hash.toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] identity: %s", _object->_identity.hash().toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] pub_key(%d): %s", (int)_object->_identity.get_public_key().size(), _object->_identity.get_public_key().toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] name_hash: %s", _object->_name_hash.toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] random_hash: %s", random_hash.toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] app_data(%d):%s", (int)new_app_data.size(), new_app_data.toHex().c_str());
|
||||
signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash;
|
||||
if (new_app_data) {
|
||||
signed_data << new_app_data;
|
||||
}
|
||||
//TRACEF("Destination::announce: signed data: %s", signed_data.toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] signed_data(%d): %s", (int)signed_data.size(), signed_data.toHex().c_str());
|
||||
|
||||
Bytes signature(_object->_identity.sign(signed_data));
|
||||
//TRACEF("Destination::announce: signature: %s", signature.toHex().c_str());
|
||||
TRACEF("[ANN-DIAG] signature: %s", signature.toHex().c_str());
|
||||
|
||||
announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature;
|
||||
|
||||
if (new_app_data) {
|
||||
announce_data << new_app_data;
|
||||
}
|
||||
TRACEF("[ANN-DIAG] announce_data(%d): %s", (int)announce_data.size(), announce_data.toHex().c_str());
|
||||
|
||||
// CBA ACCUMULATES
|
||||
try {
|
||||
@@ -390,25 +406,38 @@ bool Destination::deregister_request_handler(const Bytes& path) {
|
||||
|
||||
void Destination::receive(const Packet& packet) {
|
||||
assert(_object);
|
||||
Serial.printf("[DEST-RX] receive: pkt_type=%d data=%d bytes dest=%s\n",
|
||||
(int)packet.packet_type(), (int)packet.data().size(),
|
||||
packet.destination_hash().toHex().substr(0, 12).c_str());
|
||||
if (packet.packet_type() == Type::Packet::LINKREQUEST) {
|
||||
Serial.println("[DEST-RX] → LINKREQUEST, entering incoming_link_request");
|
||||
Bytes plaintext(packet.data());
|
||||
incoming_link_request(plaintext, packet);
|
||||
Serial.println("[DEST-RX] ← LINKREQUEST done");
|
||||
}
|
||||
else {
|
||||
// CBA TODO Why isn't the Packet decrypting itself?
|
||||
Serial.printf("[DEST-RX] → decrypting %d bytes...\n", (int)packet.data().size());
|
||||
Bytes plaintext(decrypt(packet.data()));
|
||||
//TRACEF("Destination::receive: decrypted data: %s", plaintext.toHex().c_str());
|
||||
if (plaintext) {
|
||||
Serial.printf("[DEST-RX] decrypt OK, %d bytes plaintext\n", (int)plaintext.size());
|
||||
if (packet.packet_type() == Type::Packet::DATA) {
|
||||
if (_object->_callbacks._packet) {
|
||||
try {
|
||||
Serial.println("[DEST-RX] → calling packet callback");
|
||||
_object->_callbacks._packet(plaintext, packet);
|
||||
Serial.println("[DEST-RX] ← packet callback done");
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
DEBUGF("Error while executing receive callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
Serial.println("[DEST-RX] → proving packet");
|
||||
}
|
||||
else {
|
||||
Serial.printf("[DEST] DECRYPT FAILED for %d byte packet to %s\n",
|
||||
(int)packet.data().size(), packet.destination_hash().toHex().substr(0, 16).c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -823,8 +823,7 @@ bool Identity::validate(const Bytes& signature, const Bytes& message) const {
|
||||
if (_object->_pub) {
|
||||
try {
|
||||
TRACEF("Identity::validate: Attempting to verify signature: %s and message: %s", signature.toHex().c_str(), message.toHex().c_str());
|
||||
_object->_sig_pub->verify(signature, message);
|
||||
return true;
|
||||
return _object->_sig_pub->verify(signature, message);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
return false;
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
using namespace RNS;
|
||||
using namespace RNS::Type::Interface;
|
||||
|
||||
/*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY;
|
||||
/*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY | MODE_ROAMING;
|
||||
|
||||
void InterfaceImpl::handle_outgoing(const Bytes& data) {
|
||||
//TRACEF("InterfaceImpl.handle_outgoing: data: %s", data.toHex().c_str());
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
#include "AutoInterface.h"
|
||||
#include "AutoInterfacePeer.h"
|
||||
|
||||
#include "../Log.h"
|
||||
#include "../Transport.h"
|
||||
#include "../Utilities/OS.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
// Sockets layer — POSIX on native, lwIP on Arduino. lwIP intentionally
|
||||
// exposes a BSD-compatible API via <lwip/sockets.h> (socket/bind/recvfrom/
|
||||
// sendto/setsockopt/fcntl all work as macros), so the bodies below are
|
||||
// identical on both targets.
|
||||
#ifdef ARDUINO
|
||||
#include <lwip/opt.h>
|
||||
// Defense in depth: AutoInterface needs IPv6 + MLD enabled in lwIP so
|
||||
// IPV6_JOIN_GROUP works. espressif32@6.7.0's prebuilt SDK enables both
|
||||
// (LWIP_IPV6=1, LWIP_IPV6_MLD inherited from LWIP_IPV6); if a future
|
||||
// platform release flips that off, fail loudly at compile time so we
|
||||
// don't ship silent multicast breakage.
|
||||
#if !LWIP_IPV6
|
||||
#error "AutoInterface requires lwIP IPv6. CONFIG_LWIP_IPV6 must be enabled."
|
||||
#endif
|
||||
#if !LWIP_IPV6_MLD
|
||||
#error "AutoInterface requires lwIP MLD. CONFIG_LWIP_IPV6_MLD must be enabled."
|
||||
#endif
|
||||
#include <lwip/sockets.h>
|
||||
#include <lwip/inet.h>
|
||||
// errno on lwIP is provided via Arduino's stdlib; <cerrno> is safe to include.
|
||||
#include <cerrno>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace RNS {
|
||||
|
||||
AutoInterface::AutoInterface(const char* name,
|
||||
const char* group_id,
|
||||
char addr_type,
|
||||
char scope,
|
||||
uint16_t discovery_port,
|
||||
uint16_t data_port,
|
||||
uint8_t max_peers,
|
||||
uint8_t multicast_hops)
|
||||
: _addr_type(addr_type),
|
||||
_scope(scope),
|
||||
_discovery_port(discovery_port),
|
||||
_unicast_disco_port(discovery_port + 1),
|
||||
_data_port(data_port),
|
||||
_max_peers(max_peers),
|
||||
_multicast_hops(multicast_hops != 0
|
||||
? multicast_hops
|
||||
: (scope == SCOPE_LINK ? 1 : 32))
|
||||
{
|
||||
_name = name ? name : "AutoInterface";
|
||||
_group_id_bytes = Bytes(group_id);
|
||||
_HW_MTU = HW_MTU;
|
||||
_FIXED_MTU = FIXED_MTU;
|
||||
_bitrate = BITRATE_GUESS;
|
||||
_IN = true;
|
||||
_OUT = true;
|
||||
}
|
||||
|
||||
AutoInterface::~AutoInterface() {
|
||||
if (_online) {
|
||||
stop();
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Python / glibc / macOS produce lowercase canonical IPv6 strings;
|
||||
// lwIP's ip6addr_ntoa_r produces UPPERCASE. RFC 5952 mandates
|
||||
// lowercase, so normalize here so our SHA256 hashes wire-match
|
||||
// every other AutoInterface implementation regardless of platform.
|
||||
std::string canonicalize_ipv6(const std::string& addr_str) {
|
||||
struct in6_addr tmp;
|
||||
if (inet_pton(AF_INET6, addr_str.c_str(), &tmp) != 1) return addr_str;
|
||||
char buf[INET6_ADDRSTRLEN];
|
||||
if (inet_ntop(AF_INET6, &tmp, buf, sizeof(buf)) == nullptr) return addr_str;
|
||||
std::string out(buf);
|
||||
for (auto& c : out) {
|
||||
if (c >= 'A' && c <= 'F') c = static_cast<char>(c - 'A' + 'a');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::set_link_local(const std::string& addr_str, uint32_t scope_id) {
|
||||
notify_link_change(addr_str, scope_id);
|
||||
}
|
||||
|
||||
void AutoInterface::notify_link_change(const std::string& addr_str,
|
||||
uint32_t scope_id) {
|
||||
// Re-canonicalize so the stored form is the lowercase RFC 5952 form
|
||||
// regardless of whether the caller passed an expanded
|
||||
// "fe80:0000:..." form (Arduino IPv6Address::toString) or
|
||||
// uppercase from lwIP. Peers compute their expected self-token by
|
||||
// hashing what they read off recvfrom + inet_ntop, which on every
|
||||
// other implementation is lowercase canonical.
|
||||
const std::string canon = canonicalize_ipv6(addr_str);
|
||||
if (canon == _link_local_addr && scope_id == _scope_id) {
|
||||
return; // idempotent no-op
|
||||
}
|
||||
|
||||
struct in6_addr new_bin{};
|
||||
if (inet_pton(AF_INET6, canon.c_str(), &new_bin) != 1) {
|
||||
WARNINGF("AutoInterface::notify_link_change: invalid address '%s'",
|
||||
addr_str.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
// Remember the old link-local for self-echo suppression. Late
|
||||
// multicast loopbacks of our previous announces would otherwise
|
||||
// pass token validation (their token was hashed from our prior
|
||||
// address) and get added as a "peer" pointing back at us.
|
||||
if (!_link_local_addr.empty()) {
|
||||
_self_link_local_history.push_front(_self_link_local_bin);
|
||||
while (_self_link_local_history.size() > SELF_LL_HISTORY_MAX) {
|
||||
_self_link_local_history.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
std::memcpy(_self_link_local_bin.data(), &new_bin, 16);
|
||||
_link_local_addr = canon;
|
||||
_self_disco_token = compute_discovery_token(_group_id_bytes, _link_local_addr);
|
||||
|
||||
const uint32_t prev_scope_id = _scope_id;
|
||||
_scope_id = scope_id;
|
||||
|
||||
if (_online && _disco_sock >= 0 && prev_scope_id != scope_id) {
|
||||
// Leave the old multicast membership on the previous ifindex
|
||||
// and rejoin on the new one. Both calls are best-effort:
|
||||
// failure here is no worse than the start-time best-effort
|
||||
// join (see open_sockets()), and we don't want a transient
|
||||
// network blip to take the whole interface offline.
|
||||
struct ipv6_mreq leave{};
|
||||
std::memcpy(&leave.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||
leave.ipv6mr_interface = prev_scope_id;
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
|
||||
&leave, sizeof(leave));
|
||||
|
||||
const unsigned int idx = static_cast<unsigned int>(scope_id);
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
|
||||
&idx, sizeof(idx));
|
||||
|
||||
struct ipv6_mreq join{};
|
||||
std::memcpy(&join.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||
join.ipv6mr_interface = idx;
|
||||
if (::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
|
||||
&join, sizeof(join)) != 0) {
|
||||
WARNINGF("AutoInterface::notify_link_change: rejoin on "
|
||||
"scope=%u failed (errno=%d)", (unsigned)scope_id, errno);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool AutoInterface::start() {
|
||||
if (_online) return true;
|
||||
if (_link_local_addr.empty()) {
|
||||
WARNING("AutoInterface::start: no link-local address configured");
|
||||
return false;
|
||||
}
|
||||
if (_data_port == _unicast_disco_port || _data_port == _discovery_port) {
|
||||
WARNINGF("AutoInterface::start: data_port (%u) collides with "
|
||||
"discovery_port (%u) or unicast_disco_port (%u); "
|
||||
"pick data_port at least 2 away from discovery_port",
|
||||
(unsigned)_data_port, (unsigned)_discovery_port,
|
||||
(unsigned)_unicast_disco_port);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compute group hash + multicast address now (cheap; idempotent).
|
||||
_group_hash = compute_group_hash(_group_id_bytes);
|
||||
_mcast_addr_str = compute_multicast_address(_group_hash, _addr_type, _scope);
|
||||
struct in6_addr mc_tmp;
|
||||
if (inet_pton(AF_INET6, _mcast_addr_str.c_str(), &mc_tmp) != 1) {
|
||||
WARNING("AutoInterface::start: invalid multicast address");
|
||||
return false;
|
||||
}
|
||||
std::memcpy(_mcast_addr_bin.data(), &mc_tmp, 16);
|
||||
|
||||
if (!open_sockets()) {
|
||||
close_sockets();
|
||||
return false;
|
||||
}
|
||||
|
||||
_online = true;
|
||||
_final_init_done = false; // ignore any RX before peer_jobs first tick
|
||||
_next_announce_ms = 0;
|
||||
_next_peer_job_ms = PEER_JOB_INTERVAL_MS;
|
||||
_last_mcast_echo_ms = 0;
|
||||
_has_mcast_echo = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void AutoInterface::stop() {
|
||||
if (!_online) return;
|
||||
// Tear down all spawned peers — Transport must not retain stale refs.
|
||||
for (auto& kv : _peers) {
|
||||
Transport::deregister_interface(kv.second.wrapper);
|
||||
kv.second.peer_iface->stop();
|
||||
}
|
||||
_peers.clear();
|
||||
close_sockets();
|
||||
_online = false;
|
||||
_final_init_done = false;
|
||||
_has_mcast_echo = false;
|
||||
}
|
||||
|
||||
void AutoInterface::loop() {
|
||||
loop_at(static_cast<uint64_t>(Utilities::OS::ltime()));
|
||||
}
|
||||
|
||||
void AutoInterface::loop_at(uint64_t now_ms) {
|
||||
if (!_online) return;
|
||||
|
||||
// Drain RX (each capped to 4 packets / call to bound CPU).
|
||||
poll_multicast();
|
||||
poll_unicast_disco();
|
||||
poll_data();
|
||||
|
||||
if (now_ms >= _next_announce_ms) {
|
||||
announce_peer();
|
||||
_next_announce_ms = now_ms + ANNOUNCE_INTERVAL_MS;
|
||||
// First announce sent — RX may now process discovery packets.
|
||||
_final_init_done = true;
|
||||
}
|
||||
|
||||
if (now_ms >= _next_peer_job_ms) {
|
||||
peer_jobs(now_ms);
|
||||
_next_peer_job_ms = now_ms + PEER_JOB_INTERVAL_MS;
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::send_outgoing(const Bytes& /*data*/) {
|
||||
// No-op. Outbound goes through per-peer wrappers (matches Python).
|
||||
}
|
||||
|
||||
// --- Wire-format derivation ---
|
||||
//
|
||||
// Mirrors Python AutoInterface.py:
|
||||
// - group_hash = SHA256(group_id) (lines 202-203)
|
||||
// - mcast address = "ff{type}{scope}:0:{g[2:4]}:..." (lines 204-212)
|
||||
// each ":NN:" pair is uint16 = (g[2k]<<8)|g[2k+1],
|
||||
// printed with min-2 hex chars (Python "{:02x}")
|
||||
// - discovery token = SHA256(group_id || link_local_addr_str) (lines 491-501)
|
||||
// link_local_addr_str is canonical RFC 5952 (no scope suffix)
|
||||
|
||||
Bytes AutoInterface::compute_group_hash(const Bytes& group_id) {
|
||||
return Identity::full_hash(group_id);
|
||||
}
|
||||
|
||||
std::string AutoInterface::compute_multicast_address(const Bytes& group_hash,
|
||||
char addr_type,
|
||||
char scope) {
|
||||
if (group_hash.size() < 14) {
|
||||
return std::string();
|
||||
}
|
||||
const uint8_t* g = group_hash.data();
|
||||
char buf[64];
|
||||
std::snprintf(buf, sizeof(buf),
|
||||
"ff%c%c:0:%02x:%02x:%02x:%02x:%02x:%02x",
|
||||
addr_type, scope,
|
||||
(unsigned)((g[2] << 8) | g[3]),
|
||||
(unsigned)((g[4] << 8) | g[5]),
|
||||
(unsigned)((g[6] << 8) | g[7]),
|
||||
(unsigned)((g[8] << 8) | g[9]),
|
||||
(unsigned)((g[10] << 8) | g[11]),
|
||||
(unsigned)((g[12] << 8) | g[13]));
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
Bytes AutoInterface::compute_discovery_token(const Bytes& group_id,
|
||||
const std::string& link_local_addr) {
|
||||
Bytes material;
|
||||
material.append(group_id);
|
||||
material.append(link_local_addr);
|
||||
return Identity::full_hash(material);
|
||||
}
|
||||
|
||||
// --- Peer table semantics ---
|
||||
|
||||
bool AutoInterface::has_peer(const IPv6Addr& addr) const {
|
||||
return _peers.find(addr_key(addr)) != _peers.end();
|
||||
}
|
||||
|
||||
uint64_t AutoInterface::peer_last_heard_ms(const IPv6Addr& addr) const {
|
||||
auto it = _peers.find(addr_key(addr));
|
||||
return it == _peers.end() ? 0 : it->second.last_heard_ms;
|
||||
}
|
||||
|
||||
void AutoInterface::add_peer(const IPv6Addr& addr,
|
||||
uint32_t scope_id,
|
||||
uint64_t now_ms) {
|
||||
const std::string key = addr_key(addr);
|
||||
auto it = _peers.find(key);
|
||||
if (it != _peers.end()) {
|
||||
// Already known — just refresh the freshness timestamp.
|
||||
it->second.last_heard_ms = now_ms;
|
||||
return;
|
||||
}
|
||||
if (_peers.size() >= _max_peers) {
|
||||
WARNING("AutoInterface: peer cap reached, ignoring new peer");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the peer impl as a shared_ptr; alias it into a base
|
||||
// shared_ptr<InterfaceImpl> so the Interface wrapper shares the same
|
||||
// control block (no double-delete). The peer ctor already sets
|
||||
// HW_MTU / FIXED_MTU / bitrate / IN / OUT.
|
||||
auto peer_impl = std::make_shared<AutoInterfacePeer>(this, addr, scope_id);
|
||||
std::shared_ptr<InterfaceImpl> base = peer_impl;
|
||||
|
||||
PeerEntry entry;
|
||||
entry.addr = addr;
|
||||
entry.scope_id = scope_id;
|
||||
entry.last_heard_ms = now_ms;
|
||||
entry.last_outbound_ms = now_ms;
|
||||
entry.peer_iface = peer_impl;
|
||||
entry.wrapper = Interface(base);
|
||||
|
||||
auto inserted = _peers.emplace(key, std::move(entry));
|
||||
Interface& w = inserted.first->second.wrapper;
|
||||
w.mode(_mode);
|
||||
w.start(); // sets _online = true on the impl
|
||||
Transport::register_interface(w);
|
||||
}
|
||||
|
||||
void AutoInterface::refresh_peer(const std::string& key, uint64_t now_ms) {
|
||||
auto it = _peers.find(key);
|
||||
if (it != _peers.end()) {
|
||||
it->second.last_heard_ms = now_ms;
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::peer_jobs(uint64_t now_ms) {
|
||||
// Pass 1: collect timed-out peers (don't mutate map while iterating).
|
||||
std::vector<std::string> to_remove;
|
||||
to_remove.reserve(_peers.size());
|
||||
for (const auto& kv : _peers) {
|
||||
if (now_ms > kv.second.last_heard_ms + PEERING_TIMEOUT_MS) {
|
||||
to_remove.push_back(kv.first);
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: deregister + erase.
|
||||
for (const auto& key : to_remove) {
|
||||
auto it = _peers.find(key);
|
||||
if (it == _peers.end()) continue;
|
||||
Transport::deregister_interface(it->second.wrapper);
|
||||
it->second.peer_iface->stop();
|
||||
_peers.erase(it);
|
||||
}
|
||||
|
||||
// Pass 3: reverse-peering — periodically send a unicast token to each
|
||||
// peer so they see us even when our multicast announces are dropped
|
||||
// by a hostile AP. Mirrors Python AutoInterface lines 393-403.
|
||||
for (auto& kv : _peers) {
|
||||
if (now_ms > kv.second.last_outbound_ms + REVERSE_PEERING_INTERVAL_MS) {
|
||||
reverse_announce(kv.second.addr, kv.second.scope_id);
|
||||
kv.second.last_outbound_ms = now_ms;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Test-only entry points ---
|
||||
|
||||
void AutoInterface::test_inject_peer(const IPv6Addr& addr,
|
||||
uint32_t scope_id,
|
||||
uint64_t now_ms) {
|
||||
add_peer(addr, scope_id, now_ms);
|
||||
}
|
||||
|
||||
void AutoInterface::test_run_peer_jobs(uint64_t now_ms) {
|
||||
peer_jobs(now_ms);
|
||||
}
|
||||
|
||||
void AutoInterface::test_loop_at(uint64_t now_ms) {
|
||||
loop_at(now_ms);
|
||||
}
|
||||
|
||||
// --- Socket lifecycle ---
|
||||
//
|
||||
// Three non-blocking AF_INET6 / SOCK_DGRAM sockets:
|
||||
// _disco_sock — RX multicast on _discovery_port + TX announces
|
||||
// _unicast_sock — RX reverse-peering tokens on _unicast_disco_port
|
||||
// _data_sock — RX peer payloads + TX peer payloads on _data_port
|
||||
//
|
||||
// Multicast group join (IPV6_JOIN_GROUP) is best-effort: failure logs a
|
||||
// warning but does not fail start(). This lets us boot without LAN
|
||||
// connectivity (or on hosts where the chosen scope id has no link-local
|
||||
// IPv6) and recover later when the network comes up — Python AutoInterface
|
||||
// has the same robustness property.
|
||||
|
||||
namespace {
|
||||
// RAII helper to close a half-opened FD chain on early-return.
|
||||
void try_close(int& fd) {
|
||||
if (fd >= 0) {
|
||||
::close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
bool make_nonblocking(int fd) {
|
||||
int flags = ::fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0) return false;
|
||||
return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0;
|
||||
}
|
||||
|
||||
bool bind_any(int fd, uint16_t port) {
|
||||
sockaddr_in6 a{};
|
||||
a.sin6_family = AF_INET6;
|
||||
a.sin6_port = htons(port);
|
||||
a.sin6_addr = in6addr_any;
|
||||
return ::bind(fd, reinterpret_cast<sockaddr*>(&a), sizeof(a)) == 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool AutoInterface::open_sockets() {
|
||||
const int yes = 1;
|
||||
const int hops = static_cast<int>(_multicast_hops);
|
||||
const unsigned int ifindex = static_cast<unsigned int>(_scope_id);
|
||||
|
||||
// --- Multicast discovery socket (RX + TX announces) ---
|
||||
_disco_sock = ::socket(AF_INET6, SOCK_DGRAM, 0);
|
||||
if (_disco_sock < 0) {
|
||||
WARNING("AutoInterface: socket(disco) failed");
|
||||
return false;
|
||||
}
|
||||
::setsockopt(_disco_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
#ifdef SO_REUSEPORT
|
||||
::setsockopt(_disco_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
|
||||
#endif
|
||||
const int v6only = 1;
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
|
||||
// IPV6_MULTICAST_IF: outgoing multicast leaves on this interface
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
|
||||
&ifindex, sizeof(ifindex));
|
||||
// IPV6_MULTICAST_LOOP: receive our own multicast frames so we can detect
|
||||
// the multicast echo (matches Python AutoInterface lines 451-464).
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &yes, sizeof(yes));
|
||||
// IPV6_MULTICAST_HOPS — defaults to 1 for SCOPE_LINK (never leaks)
|
||||
// and 32 for wider scopes; user can override via the constructor.
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, sizeof(hops));
|
||||
if (!bind_any(_disco_sock, _discovery_port)) {
|
||||
WARNING("AutoInterface: bind(disco) failed");
|
||||
return false;
|
||||
}
|
||||
if (!make_nonblocking(_disco_sock)) {
|
||||
WARNING("AutoInterface: make_nonblocking(disco) failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
// IPV6_JOIN_GROUP: best-effort (see header note).
|
||||
struct ipv6_mreq mreq{};
|
||||
std::memcpy(&mreq.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||
mreq.ipv6mr_interface = ifindex;
|
||||
if (::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
|
||||
&mreq, sizeof(mreq)) != 0) {
|
||||
WARNINGF("AutoInterface: IPV6_JOIN_GROUP failed (errno=%d) — "
|
||||
"multicast RX may not work on this interface", errno);
|
||||
}
|
||||
|
||||
// --- Unicast discovery socket (port 29717) ---
|
||||
_unicast_sock = ::socket(AF_INET6, SOCK_DGRAM, 0);
|
||||
if (_unicast_sock < 0) return false;
|
||||
::setsockopt(_unicast_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
#ifdef SO_REUSEPORT
|
||||
::setsockopt(_unicast_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
|
||||
#endif
|
||||
::setsockopt(_unicast_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
|
||||
if (!bind_any(_unicast_sock, _unicast_disco_port)) {
|
||||
WARNING("AutoInterface: bind(unicast) failed");
|
||||
return false;
|
||||
}
|
||||
if (!make_nonblocking(_unicast_sock)) return false;
|
||||
|
||||
// --- Data socket (port 42671) ---
|
||||
_data_sock = ::socket(AF_INET6, SOCK_DGRAM, 0);
|
||||
if (_data_sock < 0) return false;
|
||||
::setsockopt(_data_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
#ifdef SO_REUSEPORT
|
||||
::setsockopt(_data_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
|
||||
#endif
|
||||
::setsockopt(_data_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
|
||||
if (!bind_any(_data_sock, _data_port)) {
|
||||
WARNING("AutoInterface: bind(data) failed");
|
||||
return false;
|
||||
}
|
||||
if (!make_nonblocking(_data_sock)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AutoInterface::close_sockets() {
|
||||
if (_disco_sock >= 0) {
|
||||
// Best-effort leave group before closing.
|
||||
struct ipv6_mreq mreq{};
|
||||
std::memcpy(&mreq.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||
mreq.ipv6mr_interface = static_cast<unsigned int>(_scope_id);
|
||||
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
|
||||
&mreq, sizeof(mreq));
|
||||
}
|
||||
try_close(_disco_sock);
|
||||
try_close(_unicast_sock);
|
||||
try_close(_data_sock);
|
||||
}
|
||||
|
||||
// --- TX / RX paths (BSD socket API; lwIP exposes the same signatures). ---
|
||||
|
||||
namespace {
|
||||
constexpr int kPollBudget = 4; // packets per poll() call
|
||||
|
||||
void make_dst_sockaddr(sockaddr_in6& dst,
|
||||
const AutoInterface::IPv6Addr& addr,
|
||||
uint32_t scope_id,
|
||||
uint16_t port) {
|
||||
std::memset(&dst, 0, sizeof(dst));
|
||||
dst.sin6_family = AF_INET6;
|
||||
dst.sin6_port = htons(port);
|
||||
dst.sin6_scope_id = scope_id;
|
||||
std::memcpy(&dst.sin6_addr, addr.data(), 16);
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::announce_peer() {
|
||||
if (_disco_sock < 0 || _self_disco_token.size() < 32) return;
|
||||
sockaddr_in6 dst;
|
||||
make_dst_sockaddr(dst, _mcast_addr_bin, _scope_id, _discovery_port);
|
||||
ssize_t n = ::sendto(_disco_sock,
|
||||
_self_disco_token.data(), _self_disco_token.size(),
|
||||
0, reinterpret_cast<sockaddr*>(&dst), sizeof(dst));
|
||||
if (n < 0 && errno != ENETUNREACH && errno != EHOSTUNREACH) {
|
||||
VERBOSEF("AutoInterface::announce_peer: sendto errno=%d", errno);
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::reverse_announce(const IPv6Addr& peer_addr,
|
||||
uint32_t peer_scope) {
|
||||
if (_unicast_sock < 0 || _self_disco_token.size() < 32) return;
|
||||
sockaddr_in6 dst;
|
||||
make_dst_sockaddr(dst, peer_addr, peer_scope, _unicast_disco_port);
|
||||
::sendto(_unicast_sock,
|
||||
_self_disco_token.data(), _self_disco_token.size(),
|
||||
0, reinterpret_cast<sockaddr*>(&dst), sizeof(dst));
|
||||
}
|
||||
|
||||
void AutoInterface::poll_multicast() {
|
||||
if (_disco_sock < 0) return;
|
||||
for (int i = 0; i < kPollBudget; ++i) {
|
||||
sockaddr_in6 src{};
|
||||
socklen_t sl = sizeof(src);
|
||||
ssize_t n = ::recvfrom(_disco_sock, _rx_buf, HW_MTU, 0,
|
||||
reinterpret_cast<sockaddr*>(&src), &sl);
|
||||
if (n <= 0) break;
|
||||
if (!_final_init_done) continue;
|
||||
|
||||
// Self-echo: confirms multicast loopback works (carrier). Also
|
||||
// suppress echoes of our previously-rotated link-locals so a
|
||||
// late loopback after notify_link_change() doesn't accidentally
|
||||
// peer us with our former self.
|
||||
bool self_echo = std::memcmp(&src.sin6_addr,
|
||||
_self_link_local_bin.data(), 16) == 0;
|
||||
if (!self_echo) {
|
||||
for (const auto& prev : _self_link_local_history) {
|
||||
if (std::memcmp(&src.sin6_addr, prev.data(), 16) == 0) {
|
||||
self_echo = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (self_echo) {
|
||||
_last_mcast_echo_ms = static_cast<uint64_t>(Utilities::OS::ltime());
|
||||
_has_mcast_echo = true;
|
||||
continue;
|
||||
}
|
||||
if (n < 32) continue;
|
||||
|
||||
char src_str[64];
|
||||
::inet_ntop(AF_INET6, &src.sin6_addr, src_str, sizeof(src_str));
|
||||
std::string canon = canonicalize_ipv6(src_str);
|
||||
Bytes expected = compute_discovery_token(_group_id_bytes, canon);
|
||||
if (expected.size() < 32) continue;
|
||||
if (std::memcmp(_rx_buf, expected.data(), 32) != 0) continue;
|
||||
|
||||
IPv6Addr addr;
|
||||
std::memcpy(addr.data(), &src.sin6_addr, 16);
|
||||
add_peer(addr, src.sin6_scope_id,
|
||||
static_cast<uint64_t>(Utilities::OS::ltime()));
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::poll_unicast_disco() {
|
||||
if (_unicast_sock < 0) return;
|
||||
for (int i = 0; i < kPollBudget; ++i) {
|
||||
sockaddr_in6 src{};
|
||||
socklen_t sl = sizeof(src);
|
||||
ssize_t n = ::recvfrom(_unicast_sock, _rx_buf, HW_MTU, 0,
|
||||
reinterpret_cast<sockaddr*>(&src), &sl);
|
||||
if (n <= 0) break;
|
||||
if (!_final_init_done) continue;
|
||||
if (n < 32) continue;
|
||||
|
||||
char src_str[64];
|
||||
::inet_ntop(AF_INET6, &src.sin6_addr, src_str, sizeof(src_str));
|
||||
std::string canon = canonicalize_ipv6(src_str);
|
||||
Bytes expected = compute_discovery_token(_group_id_bytes, canon);
|
||||
if (expected.size() < 32) continue;
|
||||
if (std::memcmp(_rx_buf, expected.data(), 32) != 0) continue;
|
||||
|
||||
IPv6Addr addr;
|
||||
std::memcpy(addr.data(), &src.sin6_addr, 16);
|
||||
add_peer(addr, src.sin6_scope_id,
|
||||
static_cast<uint64_t>(Utilities::OS::ltime()));
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::poll_data() {
|
||||
if (_data_sock < 0) return;
|
||||
for (int i = 0; i < kPollBudget; ++i) {
|
||||
sockaddr_in6 src{};
|
||||
socklen_t sl = sizeof(src);
|
||||
ssize_t n = ::recvfrom(_data_sock, _rx_buf, HW_MTU, 0,
|
||||
reinterpret_cast<sockaddr*>(&src), &sl);
|
||||
if (n <= 0) break;
|
||||
IPv6Addr addr;
|
||||
std::memcpy(addr.data(), &src.sin6_addr, 16);
|
||||
Bytes data(_rx_buf, static_cast<size_t>(n));
|
||||
route_inbound(data, addr);
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterface::route_inbound(const Bytes& data, const IPv6Addr& src) {
|
||||
auto it = _peers.find(addr_key(src));
|
||||
if (it == _peers.end()) return;
|
||||
|
||||
// MIF dedup ring — drops duplicates that arrive on multiple netifs
|
||||
// within MIF_DEDUP_TTL_MS. Single-NIC devices rarely hit this but
|
||||
// the cost is small and it matches Python's behaviour.
|
||||
Bytes h = Identity::full_hash(data);
|
||||
const uint64_t now = static_cast<uint64_t>(Utilities::OS::ltime());
|
||||
for (const auto& d : _mif_dedup) {
|
||||
if (d.hash == h && now < d.expires_ms) return;
|
||||
}
|
||||
_mif_dedup.push_back({h, now + MIF_DEDUP_TTL_MS});
|
||||
while (_mif_dedup.size() > RNS_AUTOIFACE_MIF_DEDUP_LEN) {
|
||||
_mif_dedup.pop_front();
|
||||
}
|
||||
|
||||
it->second.last_heard_ms = now;
|
||||
it->second.peer_iface->deliver_incoming(data);
|
||||
}
|
||||
|
||||
} // namespace RNS
|
||||
@@ -0,0 +1,254 @@
|
||||
#pragma once
|
||||
|
||||
#include "../Interface.h"
|
||||
#include "../Bytes.h"
|
||||
#include "../Identity.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
// MIF (multi-interface) dedup ring length. Override per device in
|
||||
// platformio.ini build_flags for memory-tight targets (e.g. Ratcom).
|
||||
#ifndef RNS_AUTOIFACE_MIF_DEDUP_LEN
|
||||
#define RNS_AUTOIFACE_MIF_DEDUP_LEN 48
|
||||
#endif
|
||||
|
||||
// Default cap on concurrent spawned peers. Each peer costs ~280 B plus
|
||||
// whatever Transport caches for its paths. Override per device.
|
||||
#ifndef RNS_AUTOIFACE_MAX_PEERS_DEFAULT
|
||||
#define RNS_AUTOIFACE_MAX_PEERS_DEFAULT 8
|
||||
#endif
|
||||
|
||||
namespace RNS {
|
||||
|
||||
class AutoInterfacePeer;
|
||||
|
||||
/*
|
||||
* Reticulum AutoInterface — IPv6 link-local multicast LAN auto-discovery.
|
||||
*
|
||||
* Wire-compatible with the Python reference implementation
|
||||
* (RNS/Interfaces/AutoInterface.py). Listens on a multicast group derived
|
||||
* from SHA256(group_id) and spawns a per-peer AutoInterfacePeer Interface
|
||||
* for each discovered node.
|
||||
*
|
||||
* Design notes:
|
||||
* - One parent AutoInterface holds the multicast/unicast/data sockets.
|
||||
* - One AutoInterfacePeer (registered with Transport) per peer.
|
||||
* - Single-threaded, cooperative: loop() polls non-blocking sockets.
|
||||
*
|
||||
* Limitations vs the Python reference:
|
||||
* - Single-NIC only. v1 does not enumerate system interfaces or take
|
||||
* `devices` / `ignored_devices`; the host injects exactly one
|
||||
* link-local address via set_link_local() / notify_link_change().
|
||||
* - IFAC keying not implemented. A Python AutoInterface configured
|
||||
* with `ifac_netname` / `ifac_netkey` is not interoperable with this
|
||||
* implementation.
|
||||
* - The host must call notify_link_change() on Wi-Fi reassociation
|
||||
* (or any event that rotates the link-local address or interface
|
||||
* index). Python's peer_jobs() polls for this every 4 s; the C++
|
||||
* port is event-driven to keep the MCU loop hot path empty.
|
||||
* - multicast_hops defaults to 1 for SCOPE_LINK and 32 for wider
|
||||
* scopes. Crossing routers also requires MLD/router config beyond
|
||||
* setting IPV6_MULTICAST_HOPS — same caveat as Python.
|
||||
*
|
||||
* Host integration recipe:
|
||||
* 1. Resolve the link-local: WiFi.linkLocalIPv6().toString() (Arduino)
|
||||
* or getifaddrs() (POSIX).
|
||||
* 2. Resolve the interface index: esp_netif_get_netif_impl_index(...)
|
||||
* (Arduino) or if_nametoindex(...) (POSIX).
|
||||
* 3. Construct AutoInterface, set_link_local(addr, scope_id), start().
|
||||
* 4. Register the parent with Transport::register_interface() — the
|
||||
* library only registers spawned per-peer wrappers, not the parent.
|
||||
* 5. Pump loop() from your main event loop (≤100 ms cadence).
|
||||
* 6. On Wi-Fi reassociation, call notify_link_change(new_addr,
|
||||
* new_scope_id) — no need to stop()/start().
|
||||
*/
|
||||
class AutoInterface : public InterfaceImpl {
|
||||
public:
|
||||
// Wire-compatible defaults — must match Python AutoInterface.py
|
||||
static constexpr uint16_t DEFAULT_DISCOVERY_PORT = 29716;
|
||||
static constexpr uint16_t DEFAULT_UNICAST_DISCO_PORT = 29717; // discovery + 1
|
||||
static constexpr uint16_t DEFAULT_DATA_PORT = 42671;
|
||||
static constexpr const char* DEFAULT_GROUP_ID = "reticulum";
|
||||
static constexpr uint16_t HW_MTU = 1196;
|
||||
static constexpr bool FIXED_MTU = true;
|
||||
static constexpr uint32_t BITRATE_GUESS = 10 * 1000 * 1000;
|
||||
|
||||
static constexpr uint32_t ANNOUNCE_INTERVAL_MS = 1600;
|
||||
static constexpr uint32_t PEER_JOB_INTERVAL_MS = 4000;
|
||||
static constexpr uint32_t PEERING_TIMEOUT_MS = 22000;
|
||||
static constexpr uint32_t MCAST_ECHO_TIMEOUT_MS = 6500;
|
||||
static constexpr uint32_t REVERSE_PEERING_INTERVAL_MS = 5200; // 1.6 * 3.25
|
||||
static constexpr uint32_t MIF_DEDUP_TTL_MS = 750;
|
||||
|
||||
static constexpr char SCOPE_LINK = '2';
|
||||
static constexpr char SCOPE_ADMIN = '4';
|
||||
static constexpr char SCOPE_SITE = '5';
|
||||
static constexpr char SCOPE_ORGANISATION = '8';
|
||||
static constexpr char SCOPE_GLOBAL = 'e';
|
||||
|
||||
static constexpr char MCAST_ADDR_TYPE_PERMANENT = '0';
|
||||
static constexpr char MCAST_ADDR_TYPE_TEMPORARY = '1';
|
||||
|
||||
using IPv6Addr = std::array<uint8_t, 16>;
|
||||
|
||||
// multicast_hops = 0 → auto: 1 for SCOPE_LINK, 32 otherwise. Larger
|
||||
// scopes (admin/site/org/global) also need router/MLD config to
|
||||
// actually forward; this only sets the IPV6_MULTICAST_HOPS sockopt.
|
||||
AutoInterface(const char* name = "AutoInterface",
|
||||
const char* group_id = DEFAULT_GROUP_ID,
|
||||
char addr_type = MCAST_ADDR_TYPE_TEMPORARY,
|
||||
char scope = SCOPE_LINK,
|
||||
uint16_t discovery_port = DEFAULT_DISCOVERY_PORT,
|
||||
uint16_t data_port = DEFAULT_DATA_PORT,
|
||||
uint8_t max_peers = RNS_AUTOIFACE_MAX_PEERS_DEFAULT,
|
||||
uint8_t multicast_hops = 0);
|
||||
virtual ~AutoInterface();
|
||||
|
||||
// InterfaceImpl overrides
|
||||
virtual bool start() override;
|
||||
virtual void stop() override;
|
||||
virtual void loop() override;
|
||||
virtual void send_outgoing(const Bytes& data) override; // no-op (mirrors Python)
|
||||
|
||||
// Diagnostics / UI surface
|
||||
size_t peer_count() const { return _peers.size(); }
|
||||
bool has_carrier() const { return _has_mcast_echo; }
|
||||
uint8_t multicast_hops() const { return _multicast_hops; }
|
||||
const std::string& multicast_address() const { return _mcast_addr_str; }
|
||||
const std::string& link_local_address() const { return _link_local_addr; }
|
||||
bool has_peer(const IPv6Addr& addr) const;
|
||||
uint64_t peer_last_heard_ms(const IPv6Addr& addr) const;
|
||||
|
||||
// Inject the local link-local address + interface scope id.
|
||||
// Production code resolves these from WiFi.linkLocalIPv6() +
|
||||
// esp_netif_get_netif_impl_index() (Arduino) or getifaddrs() +
|
||||
// if_nametoindex() (native). May be called any time — internally
|
||||
// dispatches to notify_link_change().
|
||||
void set_link_local(const std::string& addr_str, uint32_t scope_id);
|
||||
|
||||
// Notify the library that the host's link-local address and/or
|
||||
// interface scope id has changed (e.g. Wi-Fi reassociation, DHCPv6
|
||||
// PD reissue). Recomputes the announce token so peers continue to
|
||||
// validate us, rotates the previous link-local into the self-echo
|
||||
// filter so late multicast loopback echoes don't accidentally peer
|
||||
// us with our former self, and (if scope_id changed while online)
|
||||
// leaves the old IPV6 multicast group and rejoins on the new
|
||||
// interface index. Idempotent: a no-op if (addr, scope) match
|
||||
// the current values. Safe to call before start().
|
||||
void notify_link_change(const std::string& addr_str, uint32_t scope_id);
|
||||
|
||||
// Diagnostic FD accessors — returns -1 when closed.
|
||||
int discovery_socket_fd() const { return _disco_sock; }
|
||||
int unicast_socket_fd() const { return _unicast_sock; }
|
||||
int data_socket_fd() const { return _data_sock; }
|
||||
|
||||
// Test-only entry points (do not call from production code).
|
||||
// Allow driving the peer table without real sockets / real time.
|
||||
void test_inject_peer(const IPv6Addr& addr, uint32_t scope_id, uint64_t now_ms);
|
||||
void test_run_peer_jobs(uint64_t now_ms);
|
||||
void test_loop_at(uint64_t now_ms);
|
||||
size_t test_self_link_local_history_size() const {
|
||||
return _self_link_local_history.size();
|
||||
}
|
||||
const Bytes& test_self_disco_token() const { return _self_disco_token; }
|
||||
|
||||
// Drive a single iteration with an injected clock. Production code
|
||||
// uses the no-arg loop() which calls this with OS::ltime().
|
||||
void loop_at(uint64_t now_ms);
|
||||
|
||||
virtual std::string toString() const override {
|
||||
return "AutoInterface[" + _name + "]";
|
||||
}
|
||||
|
||||
// Wire-format derivation (pure, exposed for tests / external diagnostics).
|
||||
// All match the Python reference (RNS/Interfaces/AutoInterface.py).
|
||||
static Bytes compute_group_hash(const Bytes& group_id);
|
||||
static std::string compute_multicast_address(const Bytes& group_hash,
|
||||
char addr_type,
|
||||
char scope);
|
||||
static Bytes compute_discovery_token(const Bytes& group_id,
|
||||
const std::string& link_local_addr);
|
||||
|
||||
protected:
|
||||
friend class AutoInterfacePeer;
|
||||
|
||||
// Lifecycle helpers — implemented in commits 4+
|
||||
bool open_sockets();
|
||||
void close_sockets();
|
||||
void poll_multicast();
|
||||
void poll_unicast_disco();
|
||||
void poll_data();
|
||||
void announce_peer();
|
||||
void reverse_announce(const IPv6Addr& peer_addr, uint32_t scope_id);
|
||||
void peer_jobs(uint64_t now_ms);
|
||||
void add_peer(const IPv6Addr& addr, uint32_t scope_id, uint64_t now_ms);
|
||||
void refresh_peer(const std::string& key, uint64_t now_ms);
|
||||
void route_inbound(const Bytes& data, const IPv6Addr& src);
|
||||
|
||||
// Map key derivation
|
||||
static std::string addr_key(const IPv6Addr& addr) {
|
||||
return std::string(reinterpret_cast<const char*>(addr.data()), addr.size());
|
||||
}
|
||||
|
||||
// Configuration (immutable after start)
|
||||
Bytes _group_id_bytes;
|
||||
Bytes _group_hash;
|
||||
char _addr_type;
|
||||
char _scope;
|
||||
uint16_t _discovery_port;
|
||||
uint16_t _unicast_disco_port;
|
||||
uint16_t _data_port;
|
||||
uint8_t _max_peers;
|
||||
uint8_t _multicast_hops;
|
||||
std::string _mcast_addr_str;
|
||||
IPv6Addr _mcast_addr_bin{};
|
||||
|
||||
// Sockets — opaque int FDs; -1 when closed
|
||||
int _disco_sock = -1;
|
||||
int _unicast_sock = -1;
|
||||
int _data_sock = -1;
|
||||
|
||||
// Local link-local state
|
||||
std::string _link_local_addr;
|
||||
IPv6Addr _self_link_local_bin{};
|
||||
uint32_t _scope_id = 0;
|
||||
Bytes _self_disco_token;
|
||||
// Recently rotated link-local addresses kept for self-echo
|
||||
// suppression after notify_link_change(). Bounded at 4 — entries
|
||||
// age out implicitly via the 22 s peer timeout if anything slips
|
||||
// through.
|
||||
std::deque<IPv6Addr> _self_link_local_history;
|
||||
static constexpr size_t SELF_LL_HISTORY_MAX = 4;
|
||||
|
||||
// Peer table — keyed by 16-byte address (as std::string for cheap lookup)
|
||||
struct PeerEntry {
|
||||
IPv6Addr addr{};
|
||||
uint32_t scope_id = 0;
|
||||
uint64_t last_heard_ms = 0;
|
||||
uint64_t last_outbound_ms = 0;
|
||||
std::shared_ptr<AutoInterfacePeer> peer_iface;
|
||||
Interface wrapper{Type::NONE};
|
||||
};
|
||||
std::map<std::string, PeerEntry> _peers;
|
||||
|
||||
// Multi-interface dedup ring
|
||||
struct DedupEntry { Bytes hash; uint64_t expires_ms = 0; };
|
||||
std::deque<DedupEntry> _mif_dedup;
|
||||
|
||||
// Pacing / state
|
||||
uint64_t _next_announce_ms = 0;
|
||||
uint64_t _next_peer_job_ms = 0;
|
||||
uint64_t _last_mcast_echo_ms = 0;
|
||||
bool _has_mcast_echo = false;
|
||||
bool _final_init_done = false;
|
||||
|
||||
// RX scratch (single, reused across all three sockets — single-threaded).
|
||||
uint8_t _rx_buf[HW_MTU + 4]{};
|
||||
};
|
||||
|
||||
} // namespace RNS
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "AutoInterfacePeer.h"
|
||||
#include "AutoInterface.h"
|
||||
|
||||
#include "../Log.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#ifdef ARDUINO
|
||||
#include <lwip/sockets.h>
|
||||
#include <lwip/inet.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#endif
|
||||
|
||||
namespace RNS {
|
||||
|
||||
AutoInterfacePeer::AutoInterfacePeer(AutoInterface* parent,
|
||||
const AutoInterface::IPv6Addr& addr,
|
||||
uint32_t scope_id)
|
||||
: _parent(parent),
|
||||
_peer_addr(addr),
|
||||
_peer_scope(scope_id)
|
||||
{
|
||||
_HW_MTU = AutoInterface::HW_MTU;
|
||||
_FIXED_MTU = AutoInterface::FIXED_MTU;
|
||||
_bitrate = AutoInterface::BITRATE_GUESS;
|
||||
_IN = true;
|
||||
_OUT = true;
|
||||
}
|
||||
|
||||
AutoInterfacePeer::~AutoInterfacePeer() {}
|
||||
|
||||
bool AutoInterfacePeer::start() { _online = true; return true; }
|
||||
void AutoInterfacePeer::stop() { _online = false; }
|
||||
void AutoInterfacePeer::loop() {} // RX driven by parent's poll_data()
|
||||
|
||||
void AutoInterfacePeer::send_outgoing(const Bytes& data) {
|
||||
if (!_online || !_parent) return;
|
||||
const int fd = _parent->_data_sock;
|
||||
if (fd < 0) return;
|
||||
sockaddr_in6 dst{};
|
||||
dst.sin6_family = AF_INET6;
|
||||
dst.sin6_port = htons(_parent->_data_port);
|
||||
dst.sin6_scope_id = _peer_scope;
|
||||
std::memcpy(&dst.sin6_addr, _peer_addr.data(), 16);
|
||||
ssize_t n = sendto(fd, data.data(), data.size(), 0,
|
||||
reinterpret_cast<sockaddr*>(&dst), sizeof(dst));
|
||||
if (n > 0) {
|
||||
_txb += static_cast<size_t>(n);
|
||||
_parent->_txb += static_cast<size_t>(n);
|
||||
handle_outgoing(data);
|
||||
}
|
||||
}
|
||||
|
||||
void AutoInterfacePeer::deliver_incoming(const Bytes& data) {
|
||||
if (!_online) return;
|
||||
handle_incoming(data);
|
||||
}
|
||||
|
||||
std::string AutoInterfacePeer::toString() const {
|
||||
// Lowercase RFC 5952 canonical form via inet_ntop, lowercased to match
|
||||
// Python (lwIP emits uppercase). Display only — never used for hashing.
|
||||
char buf[INET6_ADDRSTRLEN];
|
||||
struct in6_addr a;
|
||||
std::memcpy(&a, _peer_addr.data(), 16);
|
||||
if (inet_ntop(AF_INET6, &a, buf, sizeof(buf)) == nullptr) {
|
||||
return "AutoInterfacePeer[invalid]";
|
||||
}
|
||||
std::string out(buf);
|
||||
for (auto& c : out) {
|
||||
if (c >= 'A' && c <= 'F') c = static_cast<char>(c - 'A' + 'a');
|
||||
}
|
||||
return std::string("AutoInterfacePeer[") + out + "]";
|
||||
}
|
||||
|
||||
} // namespace RNS
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include "../Interface.h"
|
||||
#include "../Bytes.h"
|
||||
#include "AutoInterface.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace RNS {
|
||||
|
||||
/*
|
||||
* Per-peer Interface spawned by AutoInterface for each discovered node.
|
||||
* Registered with Transport so per-path attached_interface routing works.
|
||||
* Sends outbound traffic via the parent's shared _data_sock.
|
||||
*/
|
||||
class AutoInterfacePeer : public InterfaceImpl {
|
||||
public:
|
||||
AutoInterfacePeer(AutoInterface* parent,
|
||||
const AutoInterface::IPv6Addr& addr,
|
||||
uint32_t scope_id);
|
||||
virtual ~AutoInterfacePeer();
|
||||
|
||||
virtual bool start() override;
|
||||
virtual void stop() override;
|
||||
virtual void loop() override;
|
||||
virtual void send_outgoing(const Bytes& data) override;
|
||||
|
||||
// Called by AutoInterface::route_inbound after dedup
|
||||
void deliver_incoming(const Bytes& data);
|
||||
|
||||
const AutoInterface::IPv6Addr& peer_addr() const { return _peer_addr; }
|
||||
uint32_t peer_scope() const { return _peer_scope; }
|
||||
|
||||
virtual std::string toString() const override;
|
||||
|
||||
protected:
|
||||
AutoInterface* _parent;
|
||||
AutoInterface::IPv6Addr _peer_addr{};
|
||||
uint32_t _peer_scope = 0;
|
||||
};
|
||||
|
||||
} // namespace RNS
|
||||
+92
-10
@@ -176,8 +176,10 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
|
||||
}
|
||||
|
||||
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
|
||||
Serial.printf("[LINK-VR] validate_request: data=%d bytes\n", (int)data.size());
|
||||
if (data.size() == ECPUBSIZE || data.size() == ECPUBSIZE + LINK_MTU_SIZE) {
|
||||
try {
|
||||
Serial.println("[LINK-VR] creating link object...");
|
||||
Link link({Type::NONE}, nullptr, nullptr, owner, data.left(ECPUBSIZE/2), data.mid(ECPUBSIZE/2, ECPUBSIZE/2));
|
||||
link.set_link_id(packet);
|
||||
|
||||
@@ -205,14 +207,21 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
|
||||
VERBOSEF("Validating link request %s", link.link_id().toHex().c_str());
|
||||
TRACEF("Link MTU configured to %d", link.mtu());
|
||||
TRACEF("Establishment timeout is %f for incoming link request %s", link.establishment_timeout(), link.link_id().toHex().c_str());
|
||||
Serial.printf("[LINK-VR] → handshake (ECDH)... heap=%d\n", (int)ESP.getFreeHeap());
|
||||
link.handshake();
|
||||
Serial.println("[LINK-VR] ← handshake done");
|
||||
link.attached_interface(packet.receiving_interface());
|
||||
Serial.println("[LINK-VR] → prove (Ed25519 sign + send)...");
|
||||
link.prove();
|
||||
Serial.println("[LINK-VR] ← prove done");
|
||||
link.request_time(OS::time());
|
||||
Transport::register_link(link);
|
||||
link.last_inbound(OS::time());
|
||||
link.start_watchdog();
|
||||
|
||||
Serial.printf("[LINK-DIAG] Link %s accepted, rx_iface=%s\n",
|
||||
link.link_id().toHex().substr(0, 16).c_str(),
|
||||
packet.receiving_interface().toString().c_str());
|
||||
DEBUGF("Incoming link request %s accepted", link.toString().c_str());
|
||||
return link;
|
||||
}
|
||||
@@ -277,7 +286,12 @@ void Link::prove() {
|
||||
assert(_object);
|
||||
DEBUGF("Link %s requesting proof", link_id().toHex().c_str());
|
||||
Bytes signalling_bytes = Link::signalling_bytes(_object->_mtu, _object->_mode);
|
||||
Bytes signed_data = _object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes + signalling_bytes;
|
||||
// Python validate_proof() reconstructs signed_data using the destination's
|
||||
// identity Ed25519 key, NOT the link's ephemeral Ed25519 key.
|
||||
// Reference: Python Link.py line 412:
|
||||
// peer_sig_pub_bytes = self.destination.identity.get_public_key()[ECPUBSIZE//2:ECPUBSIZE]
|
||||
const Bytes& owner_sig_pub = _object->_owner.identity().signingPublicKey();
|
||||
Bytes signed_data = _object->_link_id + _object->_pub_bytes + owner_sig_pub + signalling_bytes;
|
||||
const Bytes signature(_object->_owner.identity().sign(signed_data));
|
||||
|
||||
Bytes proof_data = signature + _object->_pub_bytes + signalling_bytes;
|
||||
@@ -285,18 +299,62 @@ void Link::prove() {
|
||||
// Diagnostic: dump proof components for cross-implementation debugging
|
||||
VERBOSEF("[LINK-PROOF] link_id: %s", _object->_link_id.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] pub_bytes: %s", _object->_pub_bytes.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] sig_pub: %s", _object->_sig_pub_bytes.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] sig_pub: %s (owner identity)", owner_sig_pub.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] signalling: %s (mtu=%d mode=%d)", signalling_bytes.toHex().c_str(), _object->_mtu, _object->_mode);
|
||||
VERBOSEF("[LINK-PROOF] signed_data: %s (%d bytes)", signed_data.toHex().c_str(), (int)signed_data.size());
|
||||
VERBOSEF("[LINK-PROOF] signature: %s", signature.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] proof_data: %d bytes", (int)proof_data.size());
|
||||
|
||||
// CBA LINK
|
||||
// CBA TODO: Determine which approach is better, passing liunk to packet or passing _link_destination
|
||||
// Cache proof data for retry if RTT doesn't arrive (LoRa packet loss recovery)
|
||||
_object->_cached_proof_data = proof_data;
|
||||
_object->_last_proof_send = OS::time();
|
||||
_object->_proof_retries = 0;
|
||||
|
||||
// Small random delay to reduce collision on half-duplex radio links.
|
||||
// Only apply for non-TCP interfaces (LoRa, etc.) where TX collision is real.
|
||||
if (_object->_attached_interface
|
||||
&& _object->_attached_interface.toString().find("TCP") == std::string::npos) {
|
||||
delay(random(50, 200));
|
||||
}
|
||||
|
||||
Packet proof(*this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
||||
proof.send();
|
||||
_object->_establishment_cost += proof.raw().size();
|
||||
had_outbound();
|
||||
Serial.printf("[LINK] Proof sent for %s, will retry if no RTT\n", link_id().toHex().substr(0, 16).c_str());
|
||||
}
|
||||
|
||||
void Link::retry_proof() {
|
||||
assert(_object);
|
||||
if (_object->_cached_proof_data.size() == 0) return;
|
||||
if (_object->_status != Type::Link::HANDSHAKE) return;
|
||||
|
||||
double now = OS::time();
|
||||
double interval = LinkData::PROOF_RETRY_INITIAL;
|
||||
for (int i = 0; i < _object->_proof_retries; i++) {
|
||||
interval *= LinkData::PROOF_RETRY_BACKOFF;
|
||||
}
|
||||
|
||||
if (now - _object->_last_proof_send >= interval) {
|
||||
if (_object->_proof_retries < LinkData::MAX_PROOF_RETRIES) {
|
||||
_object->_proof_retries++;
|
||||
_object->_last_proof_send = now;
|
||||
Serial.printf("[LINK] Retrying proof for %s (attempt %d/%d, interval %.0fs)\n",
|
||||
link_id().toHex().substr(0, 16).c_str(),
|
||||
_object->_proof_retries, LinkData::MAX_PROOF_RETRIES, interval);
|
||||
Serial.printf("[LINK-RETRY] creating packet... heap=%d\n", (int)ESP.getFreeHeap());
|
||||
Packet proof(*this, _object->_cached_proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
||||
Serial.println("[LINK-RETRY] → proof.send()...");
|
||||
proof.send();
|
||||
Serial.println("[LINK-RETRY] ← proof.send() done");
|
||||
had_outbound();
|
||||
Serial.println("[LINK-RETRY] complete");
|
||||
} else {
|
||||
Serial.printf("[LINK] Proof retries exhausted for %s, tearing down\n",
|
||||
link_id().toHex().substr(0, 16).c_str());
|
||||
teardown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Link::prove_packet(const Packet& packet) {
|
||||
@@ -513,6 +571,10 @@ void Link::update_mdu() {
|
||||
|
||||
void Link::rtt_packet(const Packet& packet) {
|
||||
assert(_object);
|
||||
Serial.printf("[LINK-DIAG] RTT packet received! link=%s (after %d proof retries)\n",
|
||||
link_id().toHex().substr(0, 16).c_str(), _object->_proof_retries);
|
||||
// Clear cached proof — handshake complete, no more retries needed
|
||||
_object->_cached_proof_data = Bytes();
|
||||
try {
|
||||
double measured_rtt = OS::time() - _object->_request_time;
|
||||
const Bytes plaintext(decrypt(packet.data()));
|
||||
@@ -1010,7 +1072,15 @@ void Link::receive(const Packet& packet) {
|
||||
_object->_watchdog_lock = true;
|
||||
if (_object->_status != Type::Link::CLOSED && !(_object->_initiator && packet.context() == Type::Packet::KEEPALIVE && packet.data() == "\xFF")) {
|
||||
if (packet.receiving_interface() != _object->_attached_interface) {
|
||||
ERROR("Link-associated packet received on unexpected interface! Someone might be trying to manipulate your communication!");
|
||||
ERRORF("Link packet on WRONG interface! rx=%s attached=%s ctx=0x%02X",
|
||||
packet.receiving_interface().toString().c_str(),
|
||||
_object->_attached_interface.toString().c_str(),
|
||||
(int)packet.context());
|
||||
Serial.printf("[LINK-DIAG] INTERFACE MISMATCH! rx=%s attached=%s link=%s ctx=0x%02X\n",
|
||||
packet.receiving_interface().toString().c_str(),
|
||||
_object->_attached_interface.toString().c_str(),
|
||||
link_id().toHex().substr(0, 16).c_str(),
|
||||
(int)packet.context());
|
||||
}
|
||||
else {
|
||||
_object->_last_inbound = OS::time();
|
||||
@@ -1024,27 +1094,31 @@ void Link::receive(const Packet& packet) {
|
||||
}
|
||||
|
||||
if (packet.packet_type() == Type::Packet::DATA) {
|
||||
VERBOSEF("[LINK-RX] context=0x%02X status=%d initiator=%d", (int)packet.context(), (int)_object->_status, _object->_initiator);
|
||||
Serial.printf("[LINK-RX] DATA ctx=0x%02X data=%d bytes heap=%d\n",
|
||||
(int)packet.context(), (int)packet.data().size(), (int)ESP.getFreeHeap());
|
||||
bool should_query = false;
|
||||
switch (packet.context()) {
|
||||
case Type::Packet::CONTEXT_NONE:
|
||||
{
|
||||
Serial.println("[LINK-RX] → link decrypt...");
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
Serial.printf("[LINK-RX] decrypt OK, %d bytes\n", (int)plaintext.size());
|
||||
if (_object->_callbacks._packet) {
|
||||
//z thread = threading.Thread(target=_object->_callbacks.packet, args=(plaintext, packet))
|
||||
//z thread.daemon = True
|
||||
//z thread.start()
|
||||
try {
|
||||
Serial.println("[LINK-RX] → packet callback...");
|
||||
_object->_callbacks._packet(plaintext, packet);
|
||||
Serial.println("[LINK-RX] ← packet callback done");
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Error while executing packet callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (_object->_destination.proof_strategy() == Type::Destination::PROVE_ALL) {
|
||||
Serial.println("[LINK-RX] → prove_packet...");
|
||||
const_cast<Packet&>(packet).prove();
|
||||
Serial.println("[LINK-RX] ← prove_packet done");
|
||||
should_query = true;
|
||||
}
|
||||
else if (_object->_destination.proof_strategy() == Type::Destination::PROVE_APP) {
|
||||
@@ -1065,6 +1139,7 @@ void Link::receive(const Packet& packet) {
|
||||
}
|
||||
case Type::Packet::LINKIDENTIFY:
|
||||
{
|
||||
Serial.printf("[LINK-RX] LINKIDENTIFY %d bytes\n", (int)packet.data().size());
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
if (!(_object->_initiator) && plaintext.size() == Type::Identity::KEYSIZE/8 + Type::Identity::SIGLENGTH/8) {
|
||||
@@ -1154,6 +1229,8 @@ void Link::receive(const Packet& packet) {
|
||||
}
|
||||
case Type::Packet::RESOURCE_ADV:
|
||||
{
|
||||
Serial.printf("[LINK-RX] RESOURCE_ADV %d bytes heap=%d\n",
|
||||
(int)packet.data().size(), (int)ESP.getFreeHeap());
|
||||
// Resource advertisement — decrypt and accept if strategy allows
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
@@ -1567,6 +1644,11 @@ void Link::destination(const Destination& destination) {
|
||||
_object->_destination = destination;
|
||||
}
|
||||
|
||||
const Interface& Link::attached_interface() const {
|
||||
assert(_object);
|
||||
return _object->_attached_interface;
|
||||
}
|
||||
|
||||
void Link::attached_interface(const Interface& interface) {
|
||||
assert(_object);
|
||||
_object->_attached_interface = interface;
|
||||
|
||||
@@ -174,6 +174,7 @@ namespace RNS {
|
||||
void set_link_id(const Packet& packet);
|
||||
void handshake();
|
||||
void prove();
|
||||
void retry_proof();
|
||||
void prove_packet(const Packet& packet);
|
||||
void validate_proof(const Packet& packet);
|
||||
void identify(const Identity& identity);
|
||||
|
||||
@@ -77,6 +77,14 @@ namespace RNS {
|
||||
float _expected_rate = 0.0;
|
||||
Type::Link::teardown_reason _teardown_reason = Type::Link::TEARDOWN_NONE;
|
||||
|
||||
// Link proof retry state (responder side: resend proof if RTT not received)
|
||||
Bytes _cached_proof_data;
|
||||
double _last_proof_send = 0.0;
|
||||
int _proof_retries = 0;
|
||||
static constexpr int MAX_PROOF_RETRIES = 3;
|
||||
static constexpr double PROOF_RETRY_INITIAL = 2.0; // seconds before first retry
|
||||
static constexpr double PROOF_RETRY_BACKOFF = 2.0; // multiplier per retry
|
||||
|
||||
Cryptography::Token::Ptr _token;
|
||||
|
||||
Cryptography::X25519PrivateKey::Ptr _prv;
|
||||
|
||||
@@ -2,6 +2,32 @@
|
||||
|
||||
#ifdef ARDUINO
|
||||
#include <Arduino.h>
|
||||
#else
|
||||
// Native-target shims: debug instrumentation in Transport/Destination/Link uses
|
||||
// Arduino's `Serial`, `millis()`, `delay()`, `random()`, and ESP32's
|
||||
// `ESP.getFreeHeap()`. Provide no-op stand-ins so the same code compiles
|
||||
// cleanly on the native unit-test target.
|
||||
#include <cstddef>
|
||||
namespace _rns_native_compat {
|
||||
struct SerialShim {
|
||||
template<class... A> void print(A&&...) {}
|
||||
template<class... A> void println(A&&...) {}
|
||||
template<class... A> void printf(A&&...) {}
|
||||
void flush() {}
|
||||
void begin(int) {}
|
||||
};
|
||||
struct ESPShim {
|
||||
size_t getFreeHeap() const { return 0; }
|
||||
size_t getFreePsram() const { return 0; }
|
||||
size_t getPsramSize() const { return 0; }
|
||||
};
|
||||
}
|
||||
inline _rns_native_compat::SerialShim Serial;
|
||||
inline _rns_native_compat::ESPShim ESP;
|
||||
inline unsigned long millis() { return 0; }
|
||||
inline void delay(unsigned long) {}
|
||||
inline long random(long min, long max) { return min; }
|
||||
inline long random(long max) { return 0; }
|
||||
#endif
|
||||
|
||||
#include <stdarg.h>
|
||||
|
||||
@@ -68,6 +68,11 @@ Packet::Packet(const Link& link, const Bytes& data, Type::Packet::types packet_t
|
||||
TRACE("Creating packet with link...");
|
||||
_object->_destination_link = link;
|
||||
_object->_MTU = link.mtu();
|
||||
// Route all link packets through the interface the link was established on.
|
||||
// This ensures TCP links stay on TCP, LoRa links stay on LoRa, etc.
|
||||
if (link.attached_interface()) {
|
||||
_object->_attached_interface = link.attached_interface();
|
||||
}
|
||||
// CBA HACK: Need to re-build packed flags since Link was assigned
|
||||
_object->_flags = get_packed_flags();
|
||||
MEMF("Packet link object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
@@ -376,6 +381,12 @@ TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
||||
_object->_raw.data()[2], _object->_raw.data()[3]);
|
||||
}
|
||||
|
||||
if (_object->_packet_type == ANNOUNCE) {
|
||||
TRACEF("[ANN-DIAG] PACKED: flags=0x%02x hops=%d ctx=0x%02x raw(%d): %s",
|
||||
_object->_flags, _object->_hops, _object->_context,
|
||||
(int)_object->_raw.size(), _object->_raw.toHex().c_str());
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
+17
-19
@@ -258,20 +258,16 @@ Bytes RNS::compute_expected_proof(const Bytes& data, const uint8_t resource_hash
|
||||
// OutboundResource
|
||||
// ============================================================
|
||||
|
||||
bool OutboundResource::init(const Bytes& plaintext, Link& link, bool auto_compress) {
|
||||
bool OutboundResource::init(const Bytes& plaintext, Link& link, bool /*auto_compress*/) {
|
||||
_data_size = plaintext.size();
|
||||
_flags.encrypted = true;
|
||||
|
||||
// Try bz2 compression (matches Python Resource.py:387-403)
|
||||
Bytes data_to_pack;
|
||||
if (auto_compress) {
|
||||
auto result = Compression::try_compress(plaintext);
|
||||
data_to_pack = result.data;
|
||||
_flags.compressed = result.compressed;
|
||||
} else {
|
||||
data_to_pack = plaintext;
|
||||
_flags.compressed = false;
|
||||
}
|
||||
// Compression is intentionally disabled on this build — see BZ2.cpp.
|
||||
// The auto_compress parameter is kept for API parity with Python Resource
|
||||
// but ignored: bz2 is too heavy for MCU targets, and we advertise
|
||||
// SF_COMPRESSION-absent in our LXMF announces so peers won't compress for us.
|
||||
Bytes data_to_pack = plaintext;
|
||||
_flags.compressed = false;
|
||||
|
||||
// Prepend 4-byte random_hash
|
||||
Bytes rh = Identity::get_random_hash();
|
||||
@@ -451,17 +447,19 @@ Bytes InboundResource::assemble(Link& link) {
|
||||
}
|
||||
Bytes payload(decrypted.data() + 4, decrypted.size() - 4);
|
||||
|
||||
// Decompress if compressed (matches Python Resource.py assemble())
|
||||
// bz2 decompression is intentionally not available on this build (see BZ2.cpp).
|
||||
// If a peer ships a compressed resource anyway — either an old Python LXMF that
|
||||
// pre-dates the SF_COMPRESSION advertisement, or any peer ignoring our empty
|
||||
// supported_functionality list — drop the resource cleanly rather than burning
|
||||
// hundreds of KB of MCU RAM trying to decode it.
|
||||
Bytes plaintext;
|
||||
if (_flags.compressed) {
|
||||
plaintext = Compression::bz2_decompress(payload, _data_size * 2 + 4096);
|
||||
if (plaintext.size() == 0) {
|
||||
_status = ResourceStatus::CORRUPT;
|
||||
return Bytes();
|
||||
}
|
||||
} else {
|
||||
plaintext = payload;
|
||||
WARNING("Resource: dropping compressed inbound payload (bz2 not supported on this build; "
|
||||
"peer ignored SF_COMPRESSION advertisement)");
|
||||
_status = ResourceStatus::CORRUPT;
|
||||
return Bytes();
|
||||
}
|
||||
plaintext = payload;
|
||||
|
||||
_status = ResourceStatus::COMPLETE;
|
||||
return plaintext;
|
||||
|
||||
+4
-3
@@ -97,8 +97,9 @@ class OutboundResource {
|
||||
public:
|
||||
OutboundResource() = default;
|
||||
|
||||
/// Initialize from raw data. Compresses, encrypts, chunks, computes hashmap.
|
||||
bool init(const Bytes& plaintext, Link& link, bool auto_compress = true);
|
||||
/// Initialize from raw data. Encrypts, chunks, computes hashmap.
|
||||
/// auto_compress is accepted for API parity but ignored — see Resource.cpp.
|
||||
bool init(const Bytes& plaintext, Link& link, bool auto_compress = false);
|
||||
|
||||
/// Get the advertisement to send.
|
||||
ResourceAdvertisement get_advertisement() const;
|
||||
@@ -198,7 +199,7 @@ public:
|
||||
Resource(Type::NoneConstructor none) {}
|
||||
Resource(const Resource& resource) : _object(resource._object) {}
|
||||
Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout = 0.0);
|
||||
Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = true,
|
||||
Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = false,
|
||||
Callbacks::concluded callback = nullptr, Callbacks::progress progress_callback = nullptr,
|
||||
double timeout = 0.0, int segment_index = 1, const Bytes& original_hash = {Type::NONE},
|
||||
const Bytes& request_id = {Type::NONE}, bool is_response = false);
|
||||
|
||||
+42
-15
@@ -314,6 +314,12 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
if (link.status() == Type::Link::CLOSED) {
|
||||
_active_links.erase(link);
|
||||
}
|
||||
// Watchdog: retry proof for links stuck in HANDSHAKE
|
||||
// (responder sent proof but RTT never arrived — packet lost on air)
|
||||
else if (link.status() == Type::Link::HANDSHAKE) {
|
||||
const_cast<Link&>(link).retry_proof();
|
||||
Serial.println("[TRANSPORT] retry_proof returned OK");
|
||||
}
|
||||
}
|
||||
|
||||
_links_last_checked = OS::time();
|
||||
@@ -460,11 +466,14 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
|
||||
if (OS::time() > (_tables_last_culled + _tables_cull_interval)) {
|
||||
unsigned long _tc0 = millis();
|
||||
|
||||
// Deferred culls: run here instead of per-packet to avoid
|
||||
// O(n log n) sorting on every inbound announce.
|
||||
Identity::deferred_cull_known_destinations();
|
||||
unsigned long _tc1 = millis();
|
||||
cull_announce_table();
|
||||
unsigned long _tc2 = millis();
|
||||
|
||||
// CBA Disabled following since we're calling immediately after adding to path table now
|
||||
// Cull the path table if it has reached its max size
|
||||
@@ -679,9 +688,18 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
ERRORF("jobs: failed to cull tunnel table: %s", e.what());
|
||||
}
|
||||
|
||||
//#ifndef NDEBUG
|
||||
dump_stats();
|
||||
//#endif
|
||||
unsigned long _tc3 = millis();
|
||||
|
||||
// dump_stats() takes 4+ seconds on ESP32 (heap introspection is slow)
|
||||
// Only run when verbose logging is enabled
|
||||
if (RNS::loglevel() >= RNS::LOG_VERBOSE) {
|
||||
dump_stats();
|
||||
}
|
||||
unsigned long _tc4 = millis();
|
||||
if ((_tc4 - _tc0) > 100) {
|
||||
Serial.printf("[JOBS-TIMING] cull_kd=%lums cull_at=%lums tables=%lums stats=%lums TOTAL=%lums\n",
|
||||
_tc1 - _tc0, _tc2 - _tc1, _tc3 - _tc2, _tc4 - _tc3, _tc4 - _tc0);
|
||||
}
|
||||
|
||||
_tables_last_culled = OS::time();
|
||||
}
|
||||
@@ -788,11 +806,10 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
|
||||
TRACEF("Transport::outbound: destination=%s hops=%d", packet.destination_hash().toHex().c_str(), packet.hops());
|
||||
|
||||
while (_jobs_running) {
|
||||
TRACE("Transport::outbound: sleeping...");
|
||||
OS::sleep(0.0005);
|
||||
}
|
||||
|
||||
// NOTE: The Python reference has `while jobs_running: sleep()` here,
|
||||
// but on single-threaded ESP32 (Arduino), jobs/inbound/outbound all run
|
||||
// on the same thread. Waiting for _jobs_running would deadlock when
|
||||
// outbound() is called from within jobs() (e.g. link proof retry).
|
||||
_jobs_locked = true;
|
||||
|
||||
bool sent = false;
|
||||
@@ -1139,7 +1156,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
_receipts.push_back(receipt);
|
||||
}
|
||||
|
||||
if (_transport_enabled) {
|
||||
if (Reticulum::transport_enabled()) {
|
||||
cache_packet(packet);
|
||||
}
|
||||
}
|
||||
@@ -1304,10 +1321,12 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
*/
|
||||
|
||||
while (_jobs_running) {
|
||||
TRACE("Transport::inbound: sleeping...");
|
||||
OS::sleep(0.0005);
|
||||
}
|
||||
Serial.printf("[TRANSPORT] inbound: %d bytes from %s, jobs_locked=%d jobs_running=%d\n",
|
||||
(int)raw.size(), interface ? interface.toString().c_str() : "NULL",
|
||||
(int)_jobs_locked, (int)_jobs_running);
|
||||
|
||||
// NOTE: _jobs_running wait removed — single-threaded ESP32 deadlocks
|
||||
// when inbound() is called from within jobs() (e.g. loopback packets).
|
||||
|
||||
if (!_identity) {
|
||||
WARNING("Transport::inbound: No identity!");
|
||||
@@ -1317,10 +1336,15 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
_jobs_locked = true;
|
||||
|
||||
Packet packet(RNS::Destination(RNS::Type::NONE), raw);
|
||||
Serial.printf("[TRANSPORT] unpacking %d bytes...\n", (int)raw.size());
|
||||
if (!packet.unpack()) {
|
||||
WARNING("Transport::inbound: Packet unpack failed!");
|
||||
_jobs_locked = false; // FIX: was missing, would deadlock jobs
|
||||
return;
|
||||
}
|
||||
Serial.printf("[TRANSPORT] unpacked: pt=%d dt=%d dest=%s\n",
|
||||
(int)packet.packet_type(), (int)packet.destination_type(),
|
||||
packet.destination_hash().toHex().substr(0, 12).c_str());
|
||||
#ifndef NDEBUG
|
||||
TRACEF("Transport::inbound: packet: %s", packet.debugString().c_str());
|
||||
#endif
|
||||
@@ -1398,7 +1422,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
|
||||
// Only cache packets on transport nodes (endpoints don't re-forward)
|
||||
if (_transport_enabled) {
|
||||
if (Reticulum::transport_enabled()) {
|
||||
cache_packet(packet);
|
||||
}
|
||||
|
||||
@@ -1503,6 +1527,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
if (packet.context() == Type::Packet::CACHE_REQUEST) {
|
||||
if (cache_request_packet(packet)) {
|
||||
TRACE("Transport::inbound: Cached packet");
|
||||
_jobs_locked = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1590,6 +1615,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
WARNINGF("Dropping link request packet. The contained exception was: %s", e.what());
|
||||
_jobs_locked = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1726,6 +1752,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
bool is_known = (bool)Identity::recall(packet.destination_hash());
|
||||
if (!is_known && ++_verify_count > 5) {
|
||||
DEBUG("Transport::inbound: announce rate-limited (>5 new verifies/sec)");
|
||||
_jobs_locked = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -2078,7 +2105,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
// Endpoints don't need cached packets — path table is persisted
|
||||
// separately via persist_data(). Caching here causes 0.5-2.3s
|
||||
// flash writes per announce that freeze endpoint devices.
|
||||
if (_transport_enabled) {
|
||||
if (Reticulum::transport_enabled()) {
|
||||
TRACEF("Caching packet %s", packet.get_hash().toHex().c_str());
|
||||
if (RNS::Transport::cache_packet(packet, true)) {
|
||||
packet.cached(true);
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
// Unit tests for AutoInterface wire-format derivation.
|
||||
//
|
||||
// Fixture values were captured from Python Reticulum
|
||||
// (RNS/Interfaces/AutoInterface.py) so any divergence here means we are no
|
||||
// longer wire-compatible with desktop Reticulum nodes.
|
||||
//
|
||||
// Source of fixture values:
|
||||
// group_hash: hashlib.sha256(b"reticulum").hexdigest()
|
||||
// mcast addr: Python AutoInterface lines 202-212 with the captured group hash
|
||||
// token: hashlib.sha256(group_id + link_local_addr.encode("utf-8")).hexdigest()
|
||||
|
||||
#include <unity.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "Interfaces/AutoInterface.h"
|
||||
#include "Bytes.h"
|
||||
#include "Log.h"
|
||||
|
||||
using RNS::AutoInterface;
|
||||
using RNS::Bytes;
|
||||
|
||||
// SHA256("reticulum")
|
||||
static const char* kGroupHashReticulumHex =
|
||||
"eac4d70bfb1c16e45e39485e31e1f5ccb18cedf878e0310d9a96100168f89f0d";
|
||||
|
||||
// Default group "reticulum", addr_type=temporary ('1'), scope=link ('2')
|
||||
static const char* kMcastDefaultLink =
|
||||
"ff12:0:d70b:fb1c:16e4:5e39:485e:31e1";
|
||||
|
||||
// Default group "reticulum", addr_type=permanent ('0'), scope=admin ('4')
|
||||
static const char* kMcastDefaultAdminPerm =
|
||||
"ff04:0:d70b:fb1c:16e4:5e39:485e:31e1";
|
||||
|
||||
// Custom group "testnet", addr_type=temporary ('1'), scope=link ('2')
|
||||
// Note: trailing group is "315" — only 3 hex chars (RFC 5952: leading zeros
|
||||
// suppressed). This is the format Python emits and that lwIP's inet_pton
|
||||
// accepts; do not pad to 4 chars.
|
||||
static const char* kMcastTestnetLink =
|
||||
"ff12:0:ce9f:2416:5207:33ba:cb37:315";
|
||||
|
||||
// SHA256("reticulum" + "fe80::abcd:1234")
|
||||
static const char* kTokenReticulumFe80AbcdHex =
|
||||
"eb45d091e4798b743d44f9242e245e90cb193ed1c39ac40563e2956e3759a6ca";
|
||||
|
||||
// SHA256("reticulum" + "fe80::1")
|
||||
static const char* kTokenReticulumFe80OneHex =
|
||||
"97b25576749ea936b0d8a8536ffaf442d157cf47d460dcf13c48b7bd18b6c163";
|
||||
|
||||
// SHA256("testnet" + "fe80::abcd:1234")
|
||||
static const char* kTokenTestnetFe80AbcdHex =
|
||||
"33c8aed6ebf08a5e3470d76a43cb090602e14952861877f25d72640aedcad0bf";
|
||||
|
||||
void test_group_hash_default() {
|
||||
Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum"));
|
||||
TEST_ASSERT_EQUAL_size_t(32, h.size());
|
||||
TEST_ASSERT_EQUAL_STRING(kGroupHashReticulumHex, h.toHex().c_str());
|
||||
}
|
||||
|
||||
void test_multicast_address_default_group_link_temp() {
|
||||
Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum"));
|
||||
std::string mcast = AutoInterface::compute_multicast_address(
|
||||
h,
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK);
|
||||
TEST_ASSERT_EQUAL_STRING(kMcastDefaultLink, mcast.c_str());
|
||||
}
|
||||
|
||||
void test_multicast_address_default_group_admin_permanent() {
|
||||
Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum"));
|
||||
std::string mcast = AutoInterface::compute_multicast_address(
|
||||
h,
|
||||
AutoInterface::MCAST_ADDR_TYPE_PERMANENT,
|
||||
AutoInterface::SCOPE_ADMIN);
|
||||
TEST_ASSERT_EQUAL_STRING(kMcastDefaultAdminPerm, mcast.c_str());
|
||||
}
|
||||
|
||||
void test_multicast_address_custom_group() {
|
||||
// Critical: tail group is "315" (3 hex chars). Python's "{:02x}" produces
|
||||
// 3 chars when the value exceeds 0xff but is < 0x1000. Make sure C++
|
||||
// snprintf behaves the same way.
|
||||
Bytes h = AutoInterface::compute_group_hash(Bytes("testnet"));
|
||||
std::string mcast = AutoInterface::compute_multicast_address(
|
||||
h,
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK);
|
||||
TEST_ASSERT_EQUAL_STRING(kMcastTestnetLink, mcast.c_str());
|
||||
}
|
||||
|
||||
void test_multicast_address_short_group_hash_returns_empty() {
|
||||
Bytes too_short(reinterpret_cast<const uint8_t*>("abcd"), 4);
|
||||
std::string mcast = AutoInterface::compute_multicast_address(
|
||||
too_short,
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK);
|
||||
TEST_ASSERT_TRUE(mcast.empty());
|
||||
}
|
||||
|
||||
void test_discovery_token_default_group() {
|
||||
Bytes token = AutoInterface::compute_discovery_token(
|
||||
Bytes("reticulum"), std::string("fe80::abcd:1234"));
|
||||
TEST_ASSERT_EQUAL_size_t(32, token.size());
|
||||
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80AbcdHex, token.toHex().c_str());
|
||||
}
|
||||
|
||||
void test_discovery_token_compressed_address() {
|
||||
// Validates that we accept the RFC 5952 short form "fe80::1" as-is.
|
||||
Bytes token = AutoInterface::compute_discovery_token(
|
||||
Bytes("reticulum"), std::string("fe80::1"));
|
||||
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80OneHex, token.toHex().c_str());
|
||||
}
|
||||
|
||||
void test_set_link_local_canonicalizes_expanded_form() {
|
||||
// Arduino-ESP32 IPv6Address::toString() returns the fully expanded form
|
||||
// "fe80:0000:0000:0000:0022:5d59:22e5:0924". Peers RX a packet from us
|
||||
// and compute SHA256(group_id || canonical_src_str), so our self-token
|
||||
// must be hashed against the canonical RFC 5952 form, not the expanded
|
||||
// form, or we will be silently rejected by every other implementation.
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||
ai.set_link_local("fe80:0000:0000:0000:0022:5d59:22e5:0924", 1);
|
||||
TEST_ASSERT_EQUAL_STRING("fe80::22:5d59:22e5:924",
|
||||
ai.link_local_address().c_str());
|
||||
}
|
||||
|
||||
void test_set_link_local_lowercases_uppercase_input() {
|
||||
// lwIP's ip6addr_ntoa_r emits UPPERCASE hex; Python / glibc / macOS
|
||||
// produce lowercase. Wire compat requires us to normalize to lowercase
|
||||
// (RFC 5952 canonical) before hashing, both on the self-token side and
|
||||
// the RX validation side.
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||
ai.set_link_local("FE80::3EDC:75FF:FE40:8000", 1);
|
||||
TEST_ASSERT_EQUAL_STRING("fe80::3edc:75ff:fe40:8000",
|
||||
ai.link_local_address().c_str());
|
||||
}
|
||||
|
||||
void test_discovery_token_custom_group() {
|
||||
Bytes token = AutoInterface::compute_discovery_token(
|
||||
Bytes("testnet"), std::string("fe80::abcd:1234"));
|
||||
TEST_ASSERT_EQUAL_STRING(kTokenTestnetFe80AbcdHex, token.toHex().c_str());
|
||||
|
||||
// Sanity: different from default-group token for the same address.
|
||||
Bytes other = AutoInterface::compute_discovery_token(
|
||||
Bytes("reticulum"), std::string("fe80::abcd:1234"));
|
||||
TEST_ASSERT_FALSE(token == other);
|
||||
}
|
||||
|
||||
// --- Peer-table semantics ---
|
||||
|
||||
static AutoInterface::IPv6Addr make_addr(uint8_t last) {
|
||||
// fe80::<last> — link-local with a unique tail byte
|
||||
AutoInterface::IPv6Addr a{};
|
||||
a[0] = 0xfe;
|
||||
a[1] = 0x80;
|
||||
a[15] = last;
|
||||
return a;
|
||||
}
|
||||
|
||||
void test_add_peer_registers_and_counts() {
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT,
|
||||
/*max_peers=*/4);
|
||||
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.peer_count());
|
||||
|
||||
auto a1 = make_addr(0x01);
|
||||
ai.test_inject_peer(a1, /*scope=*/1, /*now_ms=*/1000);
|
||||
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
TEST_ASSERT_TRUE(ai.has_peer(a1));
|
||||
TEST_ASSERT_EQUAL_UINT64(1000, ai.peer_last_heard_ms(a1));
|
||||
}
|
||||
|
||||
void test_add_peer_idempotent_refreshes_last_heard() {
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||
|
||||
auto a1 = make_addr(0x02);
|
||||
ai.test_inject_peer(a1, 1, 5000);
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
TEST_ASSERT_EQUAL_UINT64(5000, ai.peer_last_heard_ms(a1));
|
||||
|
||||
// Second add for the same address: count stays 1, last_heard advances.
|
||||
ai.test_inject_peer(a1, 1, 9999);
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
TEST_ASSERT_EQUAL_UINT64(9999, ai.peer_last_heard_ms(a1));
|
||||
}
|
||||
|
||||
void test_add_peer_respects_max_peers_cap() {
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT,
|
||||
/*max_peers=*/3);
|
||||
|
||||
for (uint8_t i = 1; i <= 5; ++i) {
|
||||
ai.test_inject_peer(make_addr(i), 1, 1000 + i);
|
||||
}
|
||||
|
||||
// Only first 3 should have been admitted.
|
||||
TEST_ASSERT_EQUAL_size_t(3, ai.peer_count());
|
||||
TEST_ASSERT_TRUE(ai.has_peer(make_addr(1)));
|
||||
TEST_ASSERT_TRUE(ai.has_peer(make_addr(2)));
|
||||
TEST_ASSERT_TRUE(ai.has_peer(make_addr(3)));
|
||||
TEST_ASSERT_FALSE(ai.has_peer(make_addr(4)));
|
||||
TEST_ASSERT_FALSE(ai.has_peer(make_addr(5)));
|
||||
}
|
||||
|
||||
void test_peer_jobs_evicts_timed_out_peers() {
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||
|
||||
auto fresh = make_addr(0x10); // injected near "now"
|
||||
auto stale = make_addr(0x11); // last_heard well in the past
|
||||
ai.test_inject_peer(stale, 1, /*now_ms=*/0);
|
||||
ai.test_inject_peer(fresh, 1, /*now_ms=*/30000);
|
||||
TEST_ASSERT_EQUAL_size_t(2, ai.peer_count());
|
||||
|
||||
// Run jobs at t = 25s. PEERING_TIMEOUT_MS = 22000.
|
||||
// stale: 25000 > 0 + 22000 → evict
|
||||
// fresh: 25000 > 30000 + 22000 → false → keep
|
||||
ai.test_run_peer_jobs(25000);
|
||||
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
TEST_ASSERT_FALSE(ai.has_peer(stale));
|
||||
TEST_ASSERT_TRUE(ai.has_peer(fresh));
|
||||
}
|
||||
|
||||
void test_peer_jobs_keeps_recent_peers() {
|
||||
AutoInterface ai("test_iface", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||
|
||||
auto a = make_addr(0x20);
|
||||
ai.test_inject_peer(a, 1, 10000);
|
||||
ai.test_run_peer_jobs(15000); // 15s < 22s timeout
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
}
|
||||
|
||||
// --- Socket lifecycle (native impl). Uses ephemeral high ports to avoid
|
||||
// colliding with any system AutoInterface listener on the host.
|
||||
|
||||
// Discovery and data must be ≥ 2 apart so the auto-derived
|
||||
// unicast_disco_port (= discovery + 1) doesn't collide with data.
|
||||
static const uint16_t kTestDiscoPort = 49716;
|
||||
static const uint16_t kTestDataPort = 49720;
|
||||
|
||||
void test_start_without_link_local_fails() {
|
||||
AutoInterface ai("test_lifecycle", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort, kTestDataPort, 4);
|
||||
|
||||
// No set_link_local() call — start() should refuse.
|
||||
TEST_ASSERT_FALSE(ai.start());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd());
|
||||
}
|
||||
|
||||
void test_notify_link_change_recomputes_token() {
|
||||
AutoInterface ai("nlc_token", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 42671, 4);
|
||||
|
||||
ai.set_link_local("fe80::abcd:1234", 1);
|
||||
Bytes t1 = ai.test_self_disco_token();
|
||||
TEST_ASSERT_EQUAL_size_t(32, t1.size());
|
||||
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80AbcdHex, t1.toHex().c_str());
|
||||
|
||||
ai.notify_link_change("fe80::1", 1);
|
||||
Bytes t2 = ai.test_self_disco_token();
|
||||
TEST_ASSERT_EQUAL_size_t(32, t2.size());
|
||||
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80OneHex, t2.toHex().c_str());
|
||||
TEST_ASSERT_TRUE(t1 != t2);
|
||||
}
|
||||
|
||||
void test_notify_link_change_remembers_old_for_self_echo() {
|
||||
AutoInterface ai("nlc_history", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 42671, 4);
|
||||
|
||||
// First call: no prior address, history stays empty.
|
||||
ai.set_link_local("fe80::abcd:1234", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||
|
||||
// Second call: prior address is rotated into history.
|
||||
ai.notify_link_change("fe80::1", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.test_self_link_local_history_size());
|
||||
|
||||
// Three more rotations — history caps at SELF_LL_HISTORY_MAX (4).
|
||||
ai.notify_link_change("fe80::2", 1);
|
||||
ai.notify_link_change("fe80::3", 1);
|
||||
ai.notify_link_change("fe80::4", 1);
|
||||
ai.notify_link_change("fe80::5", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(4, ai.test_self_link_local_history_size());
|
||||
}
|
||||
|
||||
void test_notify_link_change_idempotent() {
|
||||
AutoInterface ai("nlc_idem", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 42671, 4);
|
||||
|
||||
ai.set_link_local("fe80::abcd:1234", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||
|
||||
// Same args → no-op, history must not grow.
|
||||
ai.notify_link_change("fe80::abcd:1234", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||
|
||||
// Different canonical form of the same address (uppercase) → still no-op.
|
||||
ai.notify_link_change("FE80::ABCD:1234", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||
}
|
||||
|
||||
void test_notify_link_change_rejects_invalid_address() {
|
||||
AutoInterface ai("nlc_bad", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 42671, 4);
|
||||
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
Bytes before = ai.test_self_disco_token();
|
||||
|
||||
// Garbage input — must not mutate token or history.
|
||||
ai.notify_link_change("not-an-address", 2);
|
||||
TEST_ASSERT_TRUE(before == ai.test_self_disco_token());
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||
}
|
||||
|
||||
void test_constructor_default_hops_link_scope() {
|
||||
// SCOPE_LINK with hops=0 → auto-default 1 (link-local only).
|
||||
AutoInterface ai("hops_link", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 42671, 4);
|
||||
TEST_ASSERT_EQUAL_UINT8(1, ai.multicast_hops());
|
||||
}
|
||||
|
||||
void test_constructor_default_hops_admin_scope() {
|
||||
// SCOPE_ADMIN with hops=0 → auto-default 32 (cross-router-ready).
|
||||
AutoInterface ai("hops_admin", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_ADMIN,
|
||||
29716, 42671, 4);
|
||||
TEST_ASSERT_EQUAL_UINT8(32, ai.multicast_hops());
|
||||
}
|
||||
|
||||
void test_constructor_explicit_hops_overrides_default() {
|
||||
AutoInterface ai("hops_explicit", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 42671, 4, /*multicast_hops=*/16);
|
||||
TEST_ASSERT_EQUAL_UINT8(16, ai.multicast_hops());
|
||||
}
|
||||
|
||||
void test_start_rejects_colliding_data_port() {
|
||||
// data_port == unicast_disco_port (= discovery_port + 1). Without the
|
||||
// guard, both sockets bind via SO_REUSEPORT and silently steal each
|
||||
// other's packets.
|
||||
AutoInterface ai_collide_unicast("test_collide_unicast", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 29717, 4);
|
||||
ai_collide_unicast.set_link_local("fe80::1", 1);
|
||||
TEST_ASSERT_FALSE(ai_collide_unicast.start());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai_collide_unicast.discovery_socket_fd());
|
||||
|
||||
// data_port == discovery_port (the multicast socket itself).
|
||||
AutoInterface ai_collide_disco("test_collide_disco", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
29716, 29716, 4);
|
||||
ai_collide_disco.set_link_local("fe80::1", 1);
|
||||
TEST_ASSERT_FALSE(ai_collide_disco.start());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai_collide_disco.discovery_socket_fd());
|
||||
}
|
||||
|
||||
void test_start_opens_three_sockets() {
|
||||
AutoInterface ai("test_lifecycle", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort, kTestDataPort, 4);
|
||||
|
||||
// "fe80::1" + scope=1 (loopback / lo0 on most hosts). IPV6_JOIN_GROUP
|
||||
// may warn on some hosts but start() tolerates that — see open_sockets()
|
||||
// best-effort note.
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
TEST_ASSERT_TRUE(ai.start());
|
||||
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd());
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.unicast_socket_fd());
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.data_socket_fd());
|
||||
|
||||
// All three FDs must be distinct.
|
||||
TEST_ASSERT_NOT_EQUAL(ai.discovery_socket_fd(), ai.unicast_socket_fd());
|
||||
TEST_ASSERT_NOT_EQUAL(ai.discovery_socket_fd(), ai.data_socket_fd());
|
||||
TEST_ASSERT_NOT_EQUAL(ai.unicast_socket_fd(), ai.data_socket_fd());
|
||||
|
||||
// Multicast address must be populated.
|
||||
TEST_ASSERT_FALSE(ai.multicast_address().empty());
|
||||
|
||||
ai.stop();
|
||||
}
|
||||
|
||||
void test_stop_closes_sockets_and_clears_peers() {
|
||||
AutoInterface ai("test_lifecycle", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort + 10, kTestDataPort + 10, 4);
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
TEST_ASSERT_TRUE(ai.start());
|
||||
|
||||
ai.test_inject_peer(make_addr(0x42), 1, 1000);
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
|
||||
ai.stop();
|
||||
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd());
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.peer_count());
|
||||
}
|
||||
|
||||
void test_start_stop_start_is_idempotent() {
|
||||
AutoInterface ai("test_lifecycle", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort + 20, kTestDataPort + 20, 4);
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
|
||||
TEST_ASSERT_TRUE(ai.start());
|
||||
int fd1 = ai.discovery_socket_fd();
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, fd1);
|
||||
ai.stop();
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||
|
||||
// Restart on the same ports must succeed (REUSEADDR on disco_sock).
|
||||
TEST_ASSERT_TRUE(ai.start());
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd());
|
||||
ai.stop();
|
||||
}
|
||||
|
||||
void test_loop_at_does_not_crash_when_offline() {
|
||||
AutoInterface ai("test_loop_offline", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort + 30, kTestDataPort + 30, 4);
|
||||
// No start() — loop_at on an offline interface must early-return.
|
||||
ai.test_loop_at(0);
|
||||
ai.test_loop_at(99999);
|
||||
TEST_ASSERT_FALSE(ai.has_carrier());
|
||||
}
|
||||
|
||||
void test_loop_at_drives_announce_and_peer_jobs_scheduling() {
|
||||
AutoInterface ai("test_loop_sched", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort + 40, kTestDataPort + 40, 4);
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
TEST_ASSERT_TRUE(ai.start());
|
||||
|
||||
// Prime peer table — stale + fresh. Use t=0 / t=30000 so they end up on
|
||||
// opposite sides of PEERING_TIMEOUT_MS=22000 at t=25000.
|
||||
auto stale = make_addr(0x30);
|
||||
auto fresh = make_addr(0x31);
|
||||
ai.test_inject_peer(stale, 1, 0);
|
||||
ai.test_inject_peer(fresh, 1, 30000);
|
||||
TEST_ASSERT_EQUAL_size_t(2, ai.peer_count());
|
||||
|
||||
// First loop_at() at t=0 sends an announce (next_announce_ms starts at 0
|
||||
// after start()) and schedules peer_jobs for t=4000. Peer count should
|
||||
// not change at t=0.
|
||||
ai.test_loop_at(0);
|
||||
TEST_ASSERT_EQUAL_size_t(2, ai.peer_count());
|
||||
|
||||
// Advance to t=25000 — past PEERING_TIMEOUT for stale peer. loop_at
|
||||
// should fire peer_jobs (next_peer_job_ms=4000 < 25000) and evict.
|
||||
ai.test_loop_at(25000);
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||
TEST_ASSERT_TRUE(ai.has_peer(fresh));
|
||||
|
||||
ai.stop();
|
||||
}
|
||||
|
||||
// Loopback round-trip: announce + multicast RX. Skips silently if
|
||||
// IPV6_JOIN_GROUP isn't supported on the test host's loopback interface
|
||||
// (some Linux configurations). This is the closest we can get to a real
|
||||
// peering handshake without two physical machines.
|
||||
void test_loopback_announce_receives_self_echo() {
|
||||
AutoInterface ai("test_loopback", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kTestDiscoPort + 50, kTestDataPort + 50, 4);
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
if (!ai.start()) {
|
||||
TEST_IGNORE_MESSAGE("start() failed on this host's loopback");
|
||||
return;
|
||||
}
|
||||
|
||||
// First announce sets _final_init_done = true and sends to mcast.
|
||||
ai.test_loop_at(0);
|
||||
|
||||
// Give the kernel a moment to loop the multicast packet back.
|
||||
for (int i = 0; i < 20 && !ai.has_carrier(); ++i) {
|
||||
ai.test_loop_at(static_cast<uint64_t>(i + 1) * 10);
|
||||
struct timespec ts { 0, 5'000'000 }; // 5 ms
|
||||
nanosleep(&ts, nullptr);
|
||||
}
|
||||
|
||||
if (!ai.has_carrier()) {
|
||||
// Multicast loopback may be filtered out on some hosts (e.g. macOS
|
||||
// treats lo0's link-local strangely). Don't fail the suite — the
|
||||
// real validation is the Phase 2 E2E test against Python.
|
||||
TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback");
|
||||
} else {
|
||||
TEST_ASSERT_TRUE(ai.has_carrier());
|
||||
}
|
||||
|
||||
ai.stop();
|
||||
}
|
||||
|
||||
void setUp(void) {}
|
||||
void tearDown(void) {}
|
||||
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(test_group_hash_default);
|
||||
RUN_TEST(test_multicast_address_default_group_link_temp);
|
||||
RUN_TEST(test_multicast_address_default_group_admin_permanent);
|
||||
RUN_TEST(test_multicast_address_custom_group);
|
||||
RUN_TEST(test_multicast_address_short_group_hash_returns_empty);
|
||||
RUN_TEST(test_discovery_token_default_group);
|
||||
RUN_TEST(test_discovery_token_compressed_address);
|
||||
RUN_TEST(test_set_link_local_canonicalizes_expanded_form);
|
||||
RUN_TEST(test_set_link_local_lowercases_uppercase_input);
|
||||
RUN_TEST(test_discovery_token_custom_group);
|
||||
RUN_TEST(test_add_peer_registers_and_counts);
|
||||
RUN_TEST(test_add_peer_idempotent_refreshes_last_heard);
|
||||
RUN_TEST(test_add_peer_respects_max_peers_cap);
|
||||
RUN_TEST(test_peer_jobs_evicts_timed_out_peers);
|
||||
RUN_TEST(test_peer_jobs_keeps_recent_peers);
|
||||
RUN_TEST(test_notify_link_change_recomputes_token);
|
||||
RUN_TEST(test_notify_link_change_remembers_old_for_self_echo);
|
||||
RUN_TEST(test_notify_link_change_idempotent);
|
||||
RUN_TEST(test_notify_link_change_rejects_invalid_address);
|
||||
RUN_TEST(test_constructor_default_hops_link_scope);
|
||||
RUN_TEST(test_constructor_default_hops_admin_scope);
|
||||
RUN_TEST(test_constructor_explicit_hops_overrides_default);
|
||||
RUN_TEST(test_start_without_link_local_fails);
|
||||
RUN_TEST(test_start_rejects_colliding_data_port);
|
||||
RUN_TEST(test_start_opens_three_sockets);
|
||||
RUN_TEST(test_stop_closes_sockets_and_clears_peers);
|
||||
RUN_TEST(test_start_stop_start_is_idempotent);
|
||||
RUN_TEST(test_loop_at_does_not_crash_when_offline);
|
||||
RUN_TEST(test_loop_at_drives_announce_and_peer_jobs_scheduling);
|
||||
RUN_TEST(test_loopback_announce_receives_self_echo);
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
int main(void) { return runUnityTests(); }
|
||||
|
||||
#ifdef ARDUINO
|
||||
void setup() { delay(2000); runUnityTests(); }
|
||||
void loop() {}
|
||||
#endif
|
||||
|
||||
void app_main() { runUnityTests(); }
|
||||
@@ -0,0 +1,213 @@
|
||||
// AutoInterface loopback integration tests.
|
||||
//
|
||||
// These exercise the real socket/poll/setsockopt paths against the host's
|
||||
// loopback IPv6 multicast — the closest we can get to live LAN behavior
|
||||
// without two physical machines or root privileges.
|
||||
//
|
||||
// Limitations of single-host loopback testing:
|
||||
// * Two AutoInterface instances bound to the same fe80:: address can't
|
||||
// genuinely peer with each other: each treats the other's announce as
|
||||
// a self-echo (their src.sin6_addr matches each instance's own
|
||||
// _self_link_local_bin). True peering requires distinct link-local
|
||||
// identities, which on a single host requires root + `ip -6 addr add`.
|
||||
// * IPV6_JOIN_GROUP on lo0 may be filtered by some hosts (notably
|
||||
// macOS / older lwIP); those configurations TEST_IGNORE rather than
|
||||
// fail so CI on developer laptops doesn't flake.
|
||||
//
|
||||
// What IS verified end-to-end here:
|
||||
// 1. Two AutoInterface instances can coexist on the same host without
|
||||
// crashing, leaking sockets, or interfering with each other's
|
||||
// multicast traffic.
|
||||
// 2. has_carrier() becomes true after start() drives the multicast
|
||||
// loopback round-trip.
|
||||
// 3. Self-echo suppression keeps peer_count() at 0 after notify_link_
|
||||
// change(), even when the kernel delays a loopback of the announce
|
||||
// sent under the previous link-local.
|
||||
// 4. notify_link_change() while online survives the IPV6_LEAVE_GROUP /
|
||||
// IPV6_JOIN_GROUP rotation without breaking carrier.
|
||||
|
||||
#include <unity.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "Interfaces/AutoInterface.h"
|
||||
#include "Bytes.h"
|
||||
|
||||
using RNS::AutoInterface;
|
||||
using RNS::Bytes;
|
||||
|
||||
// Ports chosen well above the production defaults and the unit-test range
|
||||
// (49716+) so there is no overlap.
|
||||
static constexpr uint16_t kAlfaDisc = 49810;
|
||||
static constexpr uint16_t kAlfaData = 49814;
|
||||
static constexpr uint16_t kBravoDisc = 49820;
|
||||
static constexpr uint16_t kBravoData = 49824;
|
||||
|
||||
namespace {
|
||||
|
||||
// Drive loop_at() in 100ms simulated steps, sleeping a real 5ms between
|
||||
// each so the kernel actually delivers any pending multicast frames.
|
||||
void drive(AutoInterface& ai, uint64_t start_ms, uint64_t end_ms) {
|
||||
for (uint64_t t = start_ms; t <= end_ms; t += 100) {
|
||||
ai.test_loop_at(t);
|
||||
struct timespec ts { 0, 5'000'000 }; // 5 ms
|
||||
nanosleep(&ts, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
void drive_pair(AutoInterface& a, AutoInterface& b,
|
||||
uint64_t start_ms, uint64_t end_ms) {
|
||||
for (uint64_t t = start_ms; t <= end_ms; t += 100) {
|
||||
a.test_loop_at(t);
|
||||
b.test_loop_at(t);
|
||||
struct timespec ts { 0, 5'000'000 };
|
||||
nanosleep(&ts, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void test_two_instances_coexist_on_loopback() {
|
||||
AutoInterface alfa("alfa", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kAlfaDisc, kAlfaData, 4);
|
||||
AutoInterface bravo("bravo", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kBravoDisc, kBravoData, 4);
|
||||
|
||||
alfa.set_link_local("fe80::1", 1);
|
||||
bravo.set_link_local("fe80::1", 1);
|
||||
|
||||
if (!alfa.start() || !bravo.start()) {
|
||||
alfa.stop(); bravo.stop();
|
||||
TEST_IGNORE_MESSAGE("could not start two AutoInterface instances on loopback");
|
||||
return;
|
||||
}
|
||||
|
||||
drive_pair(alfa, bravo, 0, 3000);
|
||||
|
||||
if (!alfa.has_carrier() || !bravo.has_carrier()) {
|
||||
alfa.stop(); bravo.stop();
|
||||
TEST_IGNORE_MESSAGE("multicast loopback filtered on this host (lo0 IPV6 mcast)");
|
||||
return;
|
||||
}
|
||||
|
||||
// Both saw multicast carrier — kernel is routing between them.
|
||||
TEST_ASSERT_TRUE(alfa.has_carrier());
|
||||
TEST_ASSERT_TRUE(bravo.has_carrier());
|
||||
|
||||
// Both bound to fe80::1, so each correctly treats the other's
|
||||
// announce as self-echo. Documented limitation — round-trip peering
|
||||
// across a single loopback host without root is not achievable.
|
||||
TEST_ASSERT_EQUAL_size_t(0, alfa.peer_count());
|
||||
TEST_ASSERT_EQUAL_size_t(0, bravo.peer_count());
|
||||
|
||||
alfa.stop();
|
||||
bravo.stop();
|
||||
}
|
||||
|
||||
void test_notify_link_change_while_online_keeps_carrier() {
|
||||
AutoInterface ai("nlc_online", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kAlfaDisc + 100, kAlfaData + 100, 4);
|
||||
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
if (!ai.start()) {
|
||||
TEST_IGNORE_MESSAGE("start() failed on this host's loopback");
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 1: acquire carrier under the original address.
|
||||
drive(ai, 0, 2000);
|
||||
if (!ai.has_carrier()) {
|
||||
ai.stop();
|
||||
TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback");
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 2: rotate the link-local while online. Same scope_id so no
|
||||
// IPV6_LEAVE/JOIN cycle fires — only the token rotates and the old
|
||||
// address goes into the self-echo history.
|
||||
ai.notify_link_change("fe80::abcd:1234", 1);
|
||||
TEST_ASSERT_EQUAL_size_t(1, ai.test_self_link_local_history_size());
|
||||
|
||||
// Phase 3: keep driving. Any late loopback of the *previous*
|
||||
// announce's source address must be suppressed by the history-
|
||||
// backed self-echo filter — peer_count() must stay 0.
|
||||
drive(ai, 2000, 5000);
|
||||
TEST_ASSERT_EQUAL_size_t(0, ai.peer_count());
|
||||
|
||||
// Carrier should still be true (we kept getting echoes of our new
|
||||
// announces during phase 3). If multicast suddenly broke this would
|
||||
// surface here as a regression.
|
||||
TEST_ASSERT_TRUE(ai.has_carrier());
|
||||
|
||||
ai.stop();
|
||||
}
|
||||
|
||||
void test_notify_link_change_with_new_scope_rejoins_group() {
|
||||
// Same scope_id is the common case (Wi-Fi reassoc, new link-local
|
||||
// prefix on the same NIC). This test exercises the rarer scope_id
|
||||
// change (e.g. Wi-Fi disconnect, fall back to a different netif) so
|
||||
// the IPV6_LEAVE_GROUP / IPV6_JOIN_GROUP code path runs in a real
|
||||
// socket context. We can't observe the rejoin directly without
|
||||
// platform-specific introspection, so the assertion is "didn't
|
||||
// crash, sockets still open, carrier eventually reacquires."
|
||||
AutoInterface ai("nlc_scope", "reticulum",
|
||||
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||
AutoInterface::SCOPE_LINK,
|
||||
kAlfaDisc + 200, kAlfaData + 200, 4);
|
||||
|
||||
ai.set_link_local("fe80::1", 1);
|
||||
if (!ai.start()) {
|
||||
TEST_IGNORE_MESSAGE("start() failed on this host's loopback");
|
||||
return;
|
||||
}
|
||||
drive(ai, 0, 2000);
|
||||
if (!ai.has_carrier()) {
|
||||
ai.stop();
|
||||
TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback");
|
||||
return;
|
||||
}
|
||||
|
||||
// Rotate scope while online. scope_id=2 on most hosts won't match
|
||||
// any real interface — the rejoin will warn but must not break the
|
||||
// already-open sockets.
|
||||
ai.notify_link_change("fe80::abcd:1234", 2);
|
||||
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd());
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.unicast_socket_fd());
|
||||
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.data_socket_fd());
|
||||
|
||||
// Drive a few more cycles — this must not crash and must continue
|
||||
// processing the loop without leaking FDs.
|
||||
drive(ai, 2000, 3500);
|
||||
|
||||
ai.stop();
|
||||
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd());
|
||||
TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd());
|
||||
}
|
||||
|
||||
void setUp(void) {}
|
||||
void tearDown(void) {}
|
||||
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(test_two_instances_coexist_on_loopback);
|
||||
RUN_TEST(test_notify_link_change_while_online_keeps_carrier);
|
||||
RUN_TEST(test_notify_link_change_with_new_scope_rejoins_group);
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
int main(void) { return runUnityTests(); }
|
||||
|
||||
#ifdef ARDUINO
|
||||
void setup() { delay(2000); runUnityTests(); }
|
||||
void loop() {}
|
||||
#endif
|
||||
|
||||
void app_main() { runUnityTests(); }
|
||||
@@ -1,11 +1,13 @@
|
||||
#include <unity.h>
|
||||
|
||||
#include "Bytes.h"
|
||||
#include "Identity.h"
|
||||
#include "Utilities/Crc.h"
|
||||
#include "Cryptography/HMAC.h"
|
||||
#include "Cryptography/PKCS7.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
#include <stdint.h>
|
||||
@@ -192,6 +194,24 @@ void testByteCrc32() {
|
||||
}
|
||||
|
||||
|
||||
void testIdentityValidate() {
|
||||
RNS::Identity identity(true);
|
||||
RNS::Bytes message("the quick brown fox jumps over the lazy dog");
|
||||
|
||||
RNS::Bytes signature = identity.sign(message);
|
||||
TEST_ASSERT_TRUE(identity.validate(signature, message));
|
||||
|
||||
// A signature with a flipped byte must not validate.
|
||||
std::vector<uint8_t> tampered(signature.data(), signature.data() + signature.size());
|
||||
tampered[0] ^= 0xFF;
|
||||
RNS::Bytes bad_signature(tampered.data(), tampered.size());
|
||||
TEST_ASSERT_FALSE(identity.validate(bad_signature, message));
|
||||
|
||||
// A valid signature against a different message must not validate.
|
||||
RNS::Bytes other_message("the quick brown fox jumps over the lazy cat");
|
||||
TEST_ASSERT_FALSE(identity.validate(signature, other_message));
|
||||
}
|
||||
|
||||
void setUp(void) {
|
||||
// set stuff up here before each test
|
||||
}
|
||||
@@ -208,6 +228,7 @@ int runUnityTests(void) {
|
||||
RUN_TEST(testCrc32);
|
||||
RUN_TEST(testIncrementalCrc32);
|
||||
RUN_TEST(testByteCrc32);
|
||||
RUN_TEST(testIdentityValidate);
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
|
||||
@@ -226,6 +226,26 @@ void test_receipt_timeout_callback() {
|
||||
// Transport hashlist tests
|
||||
// ============================================================================
|
||||
|
||||
void test_discover_paths_for_matches_upstream_modes() {
|
||||
uint8_t discover_modes = RNS::Interface::DISCOVER_PATHS_FOR;
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(
|
||||
(discover_modes & RNS::Type::Interface::MODE_ACCESS_POINT) > 0,
|
||||
"Access point interfaces should discover unknown paths");
|
||||
TEST_ASSERT_TRUE_MESSAGE(
|
||||
(discover_modes & RNS::Type::Interface::MODE_GATEWAY) > 0,
|
||||
"Gateway interfaces should discover unknown paths");
|
||||
TEST_ASSERT_TRUE_MESSAGE(
|
||||
(discover_modes & RNS::Type::Interface::MODE_ROAMING) > 0,
|
||||
"Roaming interfaces should discover unknown paths");
|
||||
TEST_ASSERT_FALSE_MESSAGE(
|
||||
(discover_modes & RNS::Type::Interface::MODE_FULL) > 0,
|
||||
"Full interfaces should not discover paths on behalf of peers");
|
||||
TEST_ASSERT_FALSE_MESSAGE(
|
||||
(discover_modes & RNS::Type::Interface::MODE_BOUNDARY) > 0,
|
||||
"Boundary interfaces should not discover paths on behalf of peers");
|
||||
}
|
||||
|
||||
void test_hashlist_basic() {
|
||||
// Send enough packets that the hashlist should grow
|
||||
initRNS();
|
||||
@@ -580,6 +600,8 @@ void tearDown(void) {}
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
|
||||
RUN_TEST(test_discover_paths_for_matches_upstream_modes);
|
||||
|
||||
/*
|
||||
// Transport receipt lifecycle
|
||||
RUN_TEST(test_receipt_creation_and_culling);
|
||||
|
||||
Reference in new issue
Block a user