mirror of
https://github.com/markqvist/Reticulum
synced 2026-11-27 23:00:28 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e32d4df754 | ||
|
|
561e2f23e1 | ||
|
|
b397870c97 | ||
|
|
6f6751d6b6 | ||
|
|
2aed542e61 | ||
|
|
091e021d0e | ||
|
|
fc69f323a8 | ||
|
|
6b2c5bcf0b | ||
|
|
3885d23293 | ||
|
|
b1aa527861 | ||
|
|
4c69b376b2 | ||
|
|
2b1b9589f1 | ||
|
|
378840a6bf | ||
|
|
7b8923b61f | ||
|
|
b3ef214e72 | ||
|
|
cab513fa31 | ||
|
|
60eb0509f2 | ||
|
|
42f6d64b9c | ||
|
|
6ba7cc8cb4 | ||
|
|
880db0a7b7 | ||
|
|
5f2f4438d0 | ||
|
|
7488336985 | ||
|
|
614e7bd834 | ||
|
|
386ef1f370 | ||
|
|
4ab0755d0a | ||
|
|
d478e380c9 | ||
|
|
05e6717d21 | ||
|
|
9ae3db169e | ||
|
|
68cda4a855 | ||
|
|
4b914fb9a4 | ||
|
|
bde5611a0d | ||
|
|
49073fcca5 | ||
|
|
6738db5437 | ||
|
|
49918c7e1d | ||
|
|
954567c581 | ||
|
|
77a1bb9b19 | ||
|
|
df80181006 | ||
|
|
0c0034f1ae | ||
|
|
2e9443ffe2 | ||
|
|
65222e0de8 | ||
|
|
db7daa4d94 | ||
|
|
c95bb551ab | ||
|
|
acecc1f490 | ||
|
|
39e3854dac | ||
|
|
6cd5be18ec | ||
|
|
0e2041c837 | ||
|
|
338173802d | ||
|
|
40a862acbd | ||
|
|
d825e39379 | ||
|
|
731a63b01b | ||
|
|
7c912d0936 | ||
|
|
503bd6c87b | ||
|
|
1a70bd3cd1 | ||
|
|
636012bbe5 | ||
|
|
e1b7bc316c | ||
|
|
1c488947bd | ||
|
|
1809461a07 | ||
|
|
01a78bee2a | ||
|
|
8c08b9ce09 | ||
|
|
efb8c8500d | ||
|
|
f366dd9cf2 | ||
|
|
0d15cfc134 | ||
|
|
e81532f541 | ||
|
|
d41afd2d81 | ||
|
|
7a1291d530 | ||
|
|
fc0f84f23e | ||
|
|
c2eac12ff5 | ||
|
|
e46496032c | ||
|
|
2d7f858a54 | ||
|
|
9ebcb55cb5 | ||
|
|
bbc1a0d06b | ||
|
|
31298e5eda | ||
|
|
e31c570d2b | ||
|
|
9b4947ef46 | ||
|
|
0d9bf5b862 | ||
|
|
c6f9ef1047 | ||
|
|
90ac62620d | ||
|
|
0c41027765 | ||
|
|
691211bf0d | ||
|
|
0ec51cce67 | ||
|
|
55755c6b3c | ||
|
|
72ba27d63c | ||
|
|
6c1182c2c2 | ||
|
|
ce81b339dc | ||
|
|
3db15dae44 | ||
|
|
38a73f9508 | ||
|
|
ebd9b862e9 | ||
|
|
4fc8e03d65 | ||
|
|
b48b96e616 | ||
|
|
529a9fd460 | ||
|
|
64fee86ebc | ||
|
|
e3f1a5e7cd | ||
|
|
0416c41956 | ||
|
|
4760103aa6 | ||
|
|
b2188ce9a7 | ||
|
|
4631d78bea | ||
|
|
0d16e2305e | ||
|
|
e5d37355b8 | ||
|
|
224124aac7 | ||
|
|
e29b839429 | ||
|
|
12c21d4e25 | ||
|
|
6a761a768c | ||
|
|
1ecf845cea | ||
|
|
a29a08716f | ||
|
|
e46b012e95 | ||
|
|
0f33d71966 | ||
|
|
00d57a22ee | ||
|
|
c25b56db9a | ||
|
|
a4b6129875 | ||
|
|
bce5f859da | ||
|
|
93526c17f5 | ||
|
|
6d4523c27e | ||
|
|
c4297d318f | ||
|
|
90e1dbb912 | ||
|
|
cbf50460c2 | ||
|
|
889c5ff55f | ||
|
|
566aa68fc0 | ||
|
|
3ca71527d9 | ||
|
|
5577e781fb | ||
|
|
7611fca6bf | ||
|
|
c10c465c02 | ||
|
|
9bc73819f6 | ||
|
|
bebf211b01 | ||
|
|
1af173e8a5 | ||
|
|
b051e76d00 | ||
|
|
4838875691 | ||
|
|
122f17fad6 | ||
|
|
be36abd857 | ||
|
|
fa4d4c6716 | ||
|
|
a5728be421 | ||
|
|
032b1aa3b2 | ||
|
|
fb7479a6f6 | ||
|
|
f81b267509 | ||
|
|
6527423526 | ||
|
|
d8bc20d4cb | ||
|
|
6c6238ce29 | ||
|
|
cbba3502b7 | ||
|
|
2b79db03c0 | ||
|
|
2c9edc43f1 | ||
|
|
ef9244f79f | ||
|
|
2d811dc398 | ||
|
|
e64d815033 | ||
|
|
bfade97051 | ||
|
|
3c4ef622cc | ||
|
|
3898d63689 | ||
|
|
ec8d43a548 | ||
|
|
5081255317 | ||
|
|
13a538168f | ||
|
|
a5ed0a4321 | ||
|
|
d93f9798ae | ||
|
|
88833f170b | ||
|
|
cd6911ed53 | ||
|
|
b95c51b96e | ||
|
|
3a36c367fe | ||
|
|
cf6010da59 | ||
|
|
bb2897445f | ||
|
|
406b141370 | ||
|
|
00b2f81a82 | ||
|
|
9adf045a31 | ||
|
|
de0f399a16 |
No files matched your search
+123
-6
@@ -1,12 +1,49 @@
|
|||||||
### 2026-07-10: RNS 1.3.8
|
### 2026-08-22: RNS 1.5.0
|
||||||
|
|
||||||
This release fixes various inconsistencies in link and hop-count related APIs.
|
This release significantly improves the core Transport handling of RNS, with a priority-based ingress queue backend, substantially improved efficiency of both data and management traffic handling, more efficient ingress/egress limiting, and a long list of other improvements and bugfixes.
|
||||||
|
|
||||||
**Changes**
|
**Changes**
|
||||||
- Fixed inconsistent link traffic stats calculation
|
- Added ability to include operator LXMF address in interface discovery information
|
||||||
- Fixed link hop-count metric only being available on initiator side
|
- Added prioritized inbound traffic processing to the transport core
|
||||||
- Fixed potential hop-count serialization error on transport
|
- Added configurable inbound queue lengths for data, announce, path request and ingress limited traffic
|
||||||
- Updated `WeaveInterface` to support latest Weave firmware
|
- Added early filtering for inbound traffic and improved filtering performance
|
||||||
|
- Added per-interface protocol violation tracking
|
||||||
|
- Added in-flight path requests tracking
|
||||||
|
- Added request and response batching for in-flight path requests
|
||||||
|
- Added ability to signal blackholed status in announce validation return to the API
|
||||||
|
- Added full link MDU utilization for `Channel` and `Buffer`
|
||||||
|
- Added inbound queue pressure and queue drop statistics to `rnstatus`
|
||||||
|
- Added detailed announce and path request traffic flow statistics per interface to `rnstatus`
|
||||||
|
- Added total announce and PR count/frequency stats per interface to `rnstatus`
|
||||||
|
- Added data flow speed and composition stats to `rnstatus`
|
||||||
|
- Added protocol violation stats to `rnstatus`
|
||||||
|
- Added active link statistics to `rnstatus`
|
||||||
|
- Added blocked IP listings to `rnstatus`
|
||||||
|
- Added medium bitrate based timeout calculation helpers and RPC functions, by **Zenith**
|
||||||
|
- Added extra timeout for discovery path requests when slow interfaces are online, by **Zenith**
|
||||||
|
- Added adaptive timeouts to `rncp`, `rnpath`, `rnprobe` and `rnx`, by **Zenith**
|
||||||
|
- Added adaptive timeout calculation to `rngit`, by **Zenith**
|
||||||
|
- Improved overall Transport inbound processing speed
|
||||||
|
- Improved path request handling significantly
|
||||||
|
- Improved path request ingress limiting and accounting
|
||||||
|
- Improved egress limiting responsiveness under high incoming path request load
|
||||||
|
- Improved transport background job processing
|
||||||
|
- Improved early rejection of packets with excessive hop counts
|
||||||
|
- Fixed `BackboneInterface` EPOLL receive starvation and ingress control timestamp handling, by **JRG**
|
||||||
|
- Fixed potential transport deadlock on receipts lock when callbacks sends packets, by **JRG**
|
||||||
|
- Fixed transport state handling edge cases in path request, announce queue and pending link processing, by **JRG**
|
||||||
|
- Fixed link watchdog not resetting on receive exceptions, by **JRG**
|
||||||
|
- Fixed `Resource` cancellation on multi-segment resources, by **JRG**
|
||||||
|
- Fixed `Resource` transfer part index alignment and rebinding, by **JRG**
|
||||||
|
- Fixed stale BLE device reference in `RNodeInterface`, by **JRG**
|
||||||
|
- Fixed ratchet cleaning retained preservation, by **JRG**
|
||||||
|
- Fixed invalid `rnstatus` statistics handling, by **JRG**
|
||||||
|
- Fixed various bugs in packet, link and interface handling, by **JRG**
|
||||||
|
- Fixed per-interface burst count inconsistencies in `rnstatus` output
|
||||||
|
- Fixed `rngit` file resource operations failing on Windows
|
||||||
|
- Fixed `rnodeconf` config summary incorrectly displaying WiFi mode
|
||||||
|
- Fixed speedtest example aborting transfers on stale link status
|
||||||
|
- Updated documentation, including manual sections on queue tuning and interface discovery options
|
||||||
|
|
||||||
**Verified Retrieval**
|
**Verified Retrieval**
|
||||||
You can retrieve and verify this release over Reticulum using the built-in `rngit release` utility. To retrieve only the installation `.whl` package, and the release manifest for future updates, you can use:
|
You can retrieve and verify this release over Reticulum using the built-in `rngit release` utility. To retrieve only the installation `.whl` package, and the release manifest for future updates, you can use:
|
||||||
@@ -36,6 +73,86 @@ rnid -i bc7291552be7a58f361522990465165c -V rns_*.rsm *.rsg
|
|||||||
|
|
||||||
The `rnid` utility will then verify the signatures, and display whether they are valid. If the signature cannot be verified, the release has been tampered with and should be discarded.
|
The `rnid` utility will then verify the signatures, and display whether they are valid. If the signature cannot be verified, the release has been tampered with and should be discarded.
|
||||||
|
|
||||||
|
### 2026-07-26: RNS 1.4.2
|
||||||
|
|
||||||
|
This maintenance release fixes bugs in blackholed identity filtering and recursive path request handling for RNode interfaces.
|
||||||
|
|
||||||
|
**Changes**
|
||||||
|
- Fixed a bug where recursive path requests would cause a division by zero error on uninitialized RNode interfaces.
|
||||||
|
- Fixed slow blackholed filtering for discovered interfaces on Android in some cases.
|
||||||
|
|
||||||
|
### 2026-07-24: RNS 1.4.1
|
||||||
|
|
||||||
|
This release significantly improves path convergence and stability with the new path re-balancing functionality. It also introduces interface gravity configuration, new API functionality and fixes a range of bugs and inefficiencies.
|
||||||
|
|
||||||
|
**Changes**
|
||||||
|
- Added dynamic path re-balancing
|
||||||
|
- Added `set_max_request_size` to `Destination` API
|
||||||
|
- Added `max_response_size` to request API
|
||||||
|
- Added interface gravity handling
|
||||||
|
- Added `autoconnect_interface_mode` option
|
||||||
|
- Added `autoconnect_announces_to_internal` option
|
||||||
|
- Added `autoconnect_interface_gravity` option
|
||||||
|
- Added `default_gravity` option
|
||||||
|
- Added `announces_to_internal` interface option
|
||||||
|
- Added `gravity` interface option
|
||||||
|
- Added gravity display and sorting option to `rnstatus`
|
||||||
|
- Added boundary -> boundary and boundary -> gateway path requests
|
||||||
|
- Fixed `I2PInterface` tasks getting garbage-collected prematurely, thanks to **welo**
|
||||||
|
- Fixed various minor bugs in `I2PInterface`
|
||||||
|
- Fixed ingress control burst active flag deadlocking until new announces arrived under burst timing patterns
|
||||||
|
- Fixed various memory inefficiencies
|
||||||
|
- Fixed loglevel `LOG_EXTREME` not being usable in some cases
|
||||||
|
- Fixed historical interface discoveries not being cleaned according to blackholed identities
|
||||||
|
|
||||||
|
### 2026-07-20: RNS 1.4.0
|
||||||
|
|
||||||
|
This release focuses on performance, stability and reliability improvements, particularly with resource-constrained systems in mind. It also fixes several bugs, reduces logging noise, and makes information about blocked `BackboneInterface` clients available in `ifstats`.
|
||||||
|
|
||||||
|
**Changes**
|
||||||
|
- Optimized transport data persistence to avoid CPU spikes on low-powered systems
|
||||||
|
- Optimized interface hashes calculation and access to reduce overall processing load
|
||||||
|
- Implemented known destinations cleaning as background priority to avoid lock contention and reduce load on CPU-constrained systems
|
||||||
|
- Deprecated known destination on-disk recombination on background data persist to alleviate lock contention on CPU-constrained systems
|
||||||
|
- Implemented caching of invalid discovery stamps to reduce CPU load on low-powered systems
|
||||||
|
- Implemented valid discovery announce caching and sequential validation lock to reduce processing load on CPU-constrained systems
|
||||||
|
- Fixed link stale teardown erroneously occurring due to missing keepalive from initiator side when destination continously sends packets but initiator stays silent
|
||||||
|
- Fixed race condition in link watchdog timing
|
||||||
|
- Fixed missing None-check in `BackboneInterface` fast-flap detection
|
||||||
|
- Fixed invalid exception log handler in `BackboneInterface`
|
||||||
|
- Increased default discovery stamp value to 16
|
||||||
|
- Added blocked IPs list to ifstats
|
||||||
|
- Improved backbone interface logging
|
||||||
|
- Reduced overall logging noise
|
||||||
|
|
||||||
|
### 2026-07-19: RNS 1.3.9
|
||||||
|
|
||||||
|
**Critical Security Update**: This release fixes a severe security flaw in `rnsh`. Due to the nature of the issue, I will not disclose any further details for the time being. Once operators have had time to update, I will provide a full report for transparency. If you use `rnsh`, update **right now**.
|
||||||
|
|
||||||
|
**Important**: The new version of `rnsh` changes default identity file locations, and these will now be sourced from `~/.rnsh/identity` (initiator) and `~/.rnsh/identity.default` (listener). Make sure you copy your old files to this directory, or specify a custom identity path using the command line arguments. The `--config` argument has also been renamed to `--rnsconfig`, and the `--config` argument will now specify the `rnsh` configuration directory instead of the RNS configuration directory, bringing the behavior into alignment with other RNS utilities.
|
||||||
|
|
||||||
|
Additionally, this release includes automated blocking of fast-flapping clients on `BackboneInterface` listeners (see the Interfaces chapter of the manual for details), and a number of improvements to resource handling. The logging system has also been improved, and path and destination information moved to a new `LOG_PATHING` loglevel, to decrease log noise.
|
||||||
|
|
||||||
|
**Changes**
|
||||||
|
- Fixed a critical security issue in `rnsh`
|
||||||
|
- Added automated blocking of fast-flapping clients to `BackboneInterface`
|
||||||
|
- Added new `LOG_PATHING` loglevel, improved logging
|
||||||
|
- Added ability to make internal-mode interfaces discoverable
|
||||||
|
- Added ability to get discoverable interface location from external script
|
||||||
|
- Added `RESOURCE_RCL` signal on resource receiver cancel
|
||||||
|
- Improved resource handling and reliability
|
||||||
|
- Updated `rnsh` config args to work similarly to other RNS utilities
|
||||||
|
|
||||||
|
### 2026-07-10: RNS 1.3.8
|
||||||
|
|
||||||
|
This release fixes various inconsistencies in link and hop-count related APIs.
|
||||||
|
|
||||||
|
**Changes**
|
||||||
|
- Fixed inconsistent link traffic stats calculation
|
||||||
|
- Fixed link hop-count metric only being available on initiator side
|
||||||
|
- Fixed potential hop-count serialization error on transport
|
||||||
|
- Updated `WeaveInterface` to support latest Weave firmware
|
||||||
|
|
||||||
### 2026-07-03: RNS 1.3.7
|
### 2026-07-03: RNS 1.3.7
|
||||||
|
|
||||||
This maintenance release improves announces propagation logic, and adds additional options for configuring announce propagation and interface behavior in transport mode.
|
This maintenance release improves announces propagation logic, and adds additional options for configuring announce propagation and interface behavior in transport mode.
|
||||||
|
|||||||
@@ -239,7 +239,7 @@ def link_established(link):
|
|||||||
RNS.log("Link established with server, sending...")
|
RNS.log("Link established with server, sending...")
|
||||||
rd = os.urandom(link.mdu)
|
rd = os.urandom(link.mdu)
|
||||||
started = time.time()
|
started = time.time()
|
||||||
while link.status == RNS.Link.ACTIVE and data_sent < data_cap*1.25:
|
while link.status != RNS.Link.CLOSED and data_sent < data_cap*1.25:
|
||||||
RNS.Packet(server_link, rd, create_receipt=False).send()
|
RNS.Packet(server_link, rd, create_receipt=False).send()
|
||||||
data_sent += len(rd)
|
data_sent += len(rd)
|
||||||
|
|
||||||
|
|||||||
+5
-4
@@ -53,7 +53,8 @@ class StreamDataMessage(MessageBase):
|
|||||||
The stream id is limited to 2 bytes - 2 bit
|
The stream id is limited to 2 bytes - 2 bit
|
||||||
"""
|
"""
|
||||||
|
|
||||||
OVERHEAD = 2 + 6 # 2 for stream data message header, 6 for channel envelope
|
HEADER_LEN = 2 # 2 for stream data message header
|
||||||
|
OVERHEAD = HEADER_LEN + 6 # 6 for channel envelope
|
||||||
MAX_DATA_LEN = RNS.Link.MDU - OVERHEAD
|
MAX_DATA_LEN = RNS.Link.MDU - OVERHEAD
|
||||||
"""
|
"""
|
||||||
When the Buffer package is imported, this value is
|
When the Buffer package is imported, this value is
|
||||||
@@ -226,7 +227,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
|
|||||||
self._stream_id = stream_id
|
self._stream_id = stream_id
|
||||||
self._channel = channel
|
self._channel = channel
|
||||||
self._eof = False
|
self._eof = False
|
||||||
self._mdu = channel.mdu - StreamDataMessage.OVERHEAD
|
self._mdu = channel.mdu - StreamDataMessage.HEADER_LEN
|
||||||
|
|
||||||
def write(self, __b: bytes) -> int | None:
|
def write(self, __b: bytes) -> int | None:
|
||||||
try:
|
try:
|
||||||
@@ -242,7 +243,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
|
|||||||
chunk_segment_length = int(chunk_len/comp_try)
|
chunk_segment_length = int(chunk_len/comp_try)
|
||||||
compressed_chunk = bz2.compress(__b[:chunk_segment_length])
|
compressed_chunk = bz2.compress(__b[:chunk_segment_length])
|
||||||
compressed_length = len(compressed_chunk)
|
compressed_length = len(compressed_chunk)
|
||||||
if compressed_length < StreamDataMessage.MAX_DATA_LEN and compressed_length < chunk_segment_length:
|
if compressed_length < self._mdu and compressed_length < chunk_segment_length:
|
||||||
comp_success = True
|
comp_success = True
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
@@ -252,7 +253,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
|
|||||||
chunk = compressed_chunk
|
chunk = compressed_chunk
|
||||||
processed_length = chunk_segment_length
|
processed_length = chunk_segment_length
|
||||||
else:
|
else:
|
||||||
chunk = bytes(__b[:StreamDataMessage.MAX_DATA_LEN])
|
chunk = bytes(__b[:self._mdu])
|
||||||
processed_length = len(chunk)
|
processed_length = len(chunk)
|
||||||
|
|
||||||
message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success)
|
message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success)
|
||||||
|
|||||||
+74
-205
@@ -45,63 +45,6 @@ TPacket = TypeVar("TPacket")
|
|||||||
class SystemMessageTypes(enum.IntEnum):
|
class SystemMessageTypes(enum.IntEnum):
|
||||||
SMT_STREAM_DATA = 0xff00
|
SMT_STREAM_DATA = 0xff00
|
||||||
|
|
||||||
class ChannelOutletBase(ABC, Generic[TPacket]):
|
|
||||||
"""
|
|
||||||
An abstract transport layer interface used by Channel.
|
|
||||||
|
|
||||||
DEPRECATED: This was created for testing; eventually
|
|
||||||
Channel will use Link or a LinkBase interface
|
|
||||||
directly.
|
|
||||||
"""
|
|
||||||
@abstractmethod
|
|
||||||
def send(self, raw: bytes) -> TPacket:
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def resend(self, packet: TPacket) -> TPacket:
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@property
|
|
||||||
@abstractmethod
|
|
||||||
def mdu(self):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@property
|
|
||||||
@abstractmethod
|
|
||||||
def rtt(self):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@property
|
|
||||||
@abstractmethod
|
|
||||||
def is_usable(self):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def get_packet_state(self, packet: TPacket) -> MessageState:
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def timed_out(self):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def __str__(self):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def set_packet_timeout_callback(self, packet: TPacket, callback: Callable[[TPacket], None] | None,
|
|
||||||
timeout: float | None = None):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def set_packet_delivered_callback(self, packet: TPacket, callback: Callable[[TPacket], None] | None):
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def get_packet_id(self, packet: TPacket) -> any:
|
|
||||||
raise NotImplemented()
|
|
||||||
|
|
||||||
|
|
||||||
class CEType(enum.IntEnum):
|
class CEType(enum.IntEnum):
|
||||||
"""
|
"""
|
||||||
ChannelException type codes
|
ChannelException type codes
|
||||||
@@ -113,7 +56,6 @@ class CEType(enum.IntEnum):
|
|||||||
ME_ALREADY_SENT = 4
|
ME_ALREADY_SENT = 4
|
||||||
ME_TOO_BIG = 5
|
ME_TOO_BIG = 5
|
||||||
|
|
||||||
|
|
||||||
class ChannelException(Exception):
|
class ChannelException(Exception):
|
||||||
"""
|
"""
|
||||||
An exception thrown by Channel, with a type code.
|
An exception thrown by Channel, with a type code.
|
||||||
@@ -122,7 +64,6 @@ class ChannelException(Exception):
|
|||||||
super().__init__(args)
|
super().__init__(args)
|
||||||
self.type = ce_type
|
self.type = ce_type
|
||||||
|
|
||||||
|
|
||||||
class MessageState(enum.IntEnum):
|
class MessageState(enum.IntEnum):
|
||||||
"""
|
"""
|
||||||
Set of possible states for a Message
|
Set of possible states for a Message
|
||||||
@@ -132,7 +73,6 @@ class MessageState(enum.IntEnum):
|
|||||||
MSGSTATE_DELIVERED = 2
|
MSGSTATE_DELIVERED = 2
|
||||||
MSGSTATE_FAILED = 3
|
MSGSTATE_FAILED = 3
|
||||||
|
|
||||||
|
|
||||||
class MessageBase(abc.ABC):
|
class MessageBase(abc.ABC):
|
||||||
"""
|
"""
|
||||||
Base type for any messages sent or received on a Channel.
|
Base type for any messages sent or received on a Channel.
|
||||||
@@ -170,7 +110,6 @@ class MessageBase(abc.ABC):
|
|||||||
|
|
||||||
MessageCallbackType = NewType("MessageCallbackType", Callable[[MessageBase], bool])
|
MessageCallbackType = NewType("MessageCallbackType", Callable[[MessageBase], bool])
|
||||||
|
|
||||||
|
|
||||||
class Envelope:
|
class Envelope:
|
||||||
"""
|
"""
|
||||||
Internal wrapper used to transport messages over a channel and
|
Internal wrapper used to transport messages over a channel and
|
||||||
@@ -180,8 +119,7 @@ class Envelope:
|
|||||||
msgtype, self.sequence, length = struct.unpack(">HHH", self.raw[:6])
|
msgtype, self.sequence, length = struct.unpack(">HHH", self.raw[:6])
|
||||||
raw = self.raw[6:]
|
raw = self.raw[6:]
|
||||||
ctor = message_factories.get(msgtype, None)
|
ctor = message_factories.get(msgtype, None)
|
||||||
if ctor is None:
|
if ctor is None: raise ChannelException(CEType.ME_NOT_REGISTERED, f"Unable to find constructor for Channel MSGTYPE {hex(msgtype)}")
|
||||||
raise ChannelException(CEType.ME_NOT_REGISTERED, f"Unable to find constructor for Channel MSGTYPE {hex(msgtype)}")
|
|
||||||
message = ctor()
|
message = ctor()
|
||||||
message.unpack(raw)
|
message.unpack(raw)
|
||||||
self.unpacked = True
|
self.unpacked = True
|
||||||
@@ -190,14 +128,13 @@ class Envelope:
|
|||||||
return message
|
return message
|
||||||
|
|
||||||
def pack(self) -> bytes:
|
def pack(self) -> bytes:
|
||||||
if self.message.__class__.MSGTYPE is None:
|
if self.message.__class__.MSGTYPE is None: raise ChannelException(CEType.ME_NO_MSG_TYPE, f"{self.message.__class__} lacks MSGTYPE")
|
||||||
raise ChannelException(CEType.ME_NO_MSG_TYPE, f"{self.message.__class__} lacks MSGTYPE")
|
|
||||||
data = self.message.pack()
|
data = self.message.pack()
|
||||||
self.raw = struct.pack(">HHH", self.message.MSGTYPE, self.sequence, len(data)) + data
|
self.raw = struct.pack(">HHH", self.message.MSGTYPE, self.sequence, len(data)) + data
|
||||||
self.packed = True
|
self.packed = True
|
||||||
return self.raw
|
return self.raw
|
||||||
|
|
||||||
def __init__(self, outlet: ChannelOutletBase, message: MessageBase = None, raw: bytes = None, sequence: int = None):
|
def __init__(self, outlet: LinkChannelOutlet, message: MessageBase = None, raw: bytes = None, sequence: int = None):
|
||||||
self.ts = time.time()
|
self.ts = time.time()
|
||||||
self.id = id(self)
|
self.id = id(self)
|
||||||
self.message = message
|
self.message = message
|
||||||
@@ -278,7 +215,7 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
SEQ_MAX = 0xFFFF
|
SEQ_MAX = 0xFFFF
|
||||||
SEQ_MODULUS = SEQ_MAX+1
|
SEQ_MODULUS = SEQ_MAX+1
|
||||||
|
|
||||||
def __init__(self, outlet: ChannelOutletBase):
|
def __init__(self, outlet: LinkChannelOutlet):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@param outlet:
|
@param outlet:
|
||||||
@@ -307,11 +244,9 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
self.window_min = Channel.WINDOW_MIN
|
self.window_min = Channel.WINDOW_MIN
|
||||||
self.window_flexibility = Channel.WINDOW_FLEXIBILITY
|
self.window_flexibility = Channel.WINDOW_FLEXIBILITY
|
||||||
|
|
||||||
def __enter__(self) -> Channel:
|
def __enter__(self) -> Channel: return self
|
||||||
return self
|
|
||||||
|
|
||||||
def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None,
|
def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None) -> bool | None:
|
||||||
__traceback: TracebackType | None) -> bool | None:
|
|
||||||
self._shutdown()
|
self._shutdown()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -327,20 +262,13 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
|
|
||||||
def _register_message_type(self, message_class: Type[MessageBase], *, is_system_type: bool = False):
|
def _register_message_type(self, message_class: Type[MessageBase], *, is_system_type: bool = False):
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if not issubclass(message_class, MessageBase):
|
if not issubclass(message_class, MessageBase): raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} is not a subclass of {MessageBase}.")
|
||||||
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
|
if message_class.MSGTYPE is None: raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} has invalid MSGTYPE class attribute.")
|
||||||
f"{message_class} is not a subclass of {MessageBase}.")
|
if message_class.MSGTYPE >= 0xf000 and not is_system_type: raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} has system-reserved message type.")
|
||||||
if message_class.MSGTYPE is None:
|
|
||||||
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
|
try: message_class()
|
||||||
f"{message_class} has invalid MSGTYPE class attribute.")
|
|
||||||
if message_class.MSGTYPE >= 0xf000 and not is_system_type:
|
|
||||||
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
|
|
||||||
f"{message_class} has system-reserved message type.")
|
|
||||||
try:
|
|
||||||
message_class()
|
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
|
raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} raised an exception when constructed with no arguments: {ex}")
|
||||||
f"{message_class} raised an exception when constructed with no arguments: {ex}")
|
|
||||||
|
|
||||||
self._message_factories[message_class.MSGTYPE] = message_class
|
self._message_factories[message_class.MSGTYPE] = message_class
|
||||||
|
|
||||||
@@ -384,8 +312,10 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
self._outlet.set_packet_timeout_callback(envelope.packet, None)
|
self._outlet.set_packet_timeout_callback(envelope.packet, None)
|
||||||
self._outlet.set_packet_delivered_callback(envelope.packet, None)
|
self._outlet.set_packet_delivered_callback(envelope.packet, None)
|
||||||
envelope.tracked = False
|
envelope.tracked = False
|
||||||
|
|
||||||
for envelope in self._rx_ring:
|
for envelope in self._rx_ring:
|
||||||
envelope.tracked = False
|
envelope.tracked = False
|
||||||
|
|
||||||
self._tx_ring.clear()
|
self._tx_ring.clear()
|
||||||
self._rx_ring.clear()
|
self._rx_ring.clear()
|
||||||
|
|
||||||
@@ -394,14 +324,12 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
i = 0
|
i = 0
|
||||||
|
|
||||||
for existing in ring:
|
for existing in ring:
|
||||||
|
|
||||||
if envelope.sequence == existing.sequence:
|
if envelope.sequence == existing.sequence:
|
||||||
RNS.log(f"Envelope: Emplacement of duplicate envelope with sequence "+str(envelope.sequence), RNS.LOG_EXTREME)
|
RNS.log(f"Envelope: Emplacement of duplicate envelope with sequence "+str(envelope.sequence), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if envelope.sequence < existing.sequence and not (self._next_rx_sequence - envelope.sequence) > (Channel.SEQ_MAX//2):
|
if envelope.sequence < existing.sequence and not (self._next_rx_sequence - envelope.sequence) > (Channel.SEQ_MAX//2):
|
||||||
ring.insert(i, envelope)
|
ring.insert(i, envelope)
|
||||||
|
|
||||||
envelope.tracked = True
|
envelope.tracked = True
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -417,10 +345,8 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
|
|
||||||
for cb in cbs:
|
for cb in cbs:
|
||||||
try:
|
try:
|
||||||
if cb(message):
|
if cb(message): return
|
||||||
return
|
except Exception as e: RNS.log(f"Channel {str(self)} experienced an error while running a message callback. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Channel "+str(self)+" experienced an error while running a message callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
def _receive(self, raw: bytes):
|
def _receive(self, raw: bytes):
|
||||||
try:
|
try:
|
||||||
@@ -432,16 +358,20 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
window_overflow = (self._next_rx_sequence+Channel.WINDOW_MAX) % Channel.SEQ_MODULUS
|
window_overflow = (self._next_rx_sequence+Channel.WINDOW_MAX) % Channel.SEQ_MODULUS
|
||||||
if window_overflow < self._next_rx_sequence:
|
if window_overflow < self._next_rx_sequence:
|
||||||
if envelope.sequence > window_overflow:
|
if envelope.sequence > window_overflow:
|
||||||
RNS.log("Invalid packet sequence ("+str(envelope.sequence)+") received on channel "+str(self), RNS.LOG_EXTREME)
|
RNS.log(f"Invalid packet sequence ({envelope.sequence}) received on channel {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
RNS.log("Invalid packet sequence ("+str(envelope.sequence)+") received on channel "+str(self), RNS.LOG_EXTREME)
|
RNS.log(f"Invalid packet sequence ({envelope.sequence}) received on channel {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
return
|
return
|
||||||
|
|
||||||
|
elif envelope.sequence > self._next_rx_sequence + self.WINDOW_MAX:
|
||||||
|
RNS.log(f"Invalid packet sequence ({envelope.sequence}) received on channel {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
return
|
||||||
|
|
||||||
is_new = self._emplace_envelope(envelope, self._rx_ring)
|
is_new = self._emplace_envelope(envelope, self._rx_ring)
|
||||||
|
|
||||||
if not is_new:
|
if not is_new:
|
||||||
RNS.log("Duplicate message received on channel "+str(self), RNS.LOG_EXTREME)
|
RNS.log("Duplicate message received on channel "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -457,10 +387,8 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
self._next_rx_sequence = (self._next_rx_sequence + 1) % Channel.SEQ_MODULUS
|
self._next_rx_sequence = (self._next_rx_sequence + 1) % Channel.SEQ_MODULUS
|
||||||
|
|
||||||
for e in contigous:
|
for e in contigous:
|
||||||
if not e.unpacked:
|
if not e.unpacked: m = e.unpack(self._message_factories)
|
||||||
m = e.unpack(self._message_factories)
|
else: m = e.message
|
||||||
else:
|
|
||||||
m = e.message
|
|
||||||
|
|
||||||
self._rx_ring.remove(e)
|
self._rx_ring.remove(e)
|
||||||
self._run_callbacks(m)
|
self._run_callbacks(m)
|
||||||
@@ -474,9 +402,7 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
|
|
||||||
:return: True if ready
|
:return: True if ready
|
||||||
"""
|
"""
|
||||||
if not self._outlet.is_usable:
|
if not self._outlet.is_usable: return False
|
||||||
return False
|
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
outstanding = 0
|
outstanding = 0
|
||||||
for envelope in self._tx_ring:
|
for envelope in self._tx_ring:
|
||||||
@@ -484,59 +410,38 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
if not envelope.packet or not self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED:
|
if not envelope.packet or not self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED:
|
||||||
outstanding += 1
|
outstanding += 1
|
||||||
|
|
||||||
if outstanding >= self.window:
|
if outstanding >= self.window: return False
|
||||||
return False
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _packet_tx_op(self, packet: TPacket, op: Callable[[TPacket], bool]):
|
def _packet_tx_op(self, packet: TPacket, op: Callable[[TPacket], bool]):
|
||||||
target_id = self._outlet.get_packet_id(packet)
|
target_id = self._outlet.get_packet_id(packet)
|
||||||
with self._lock:
|
with self._lock:
|
||||||
envelope = next(filter(lambda e: e.packet is not None
|
envelope = next(filter(lambda e: e.packet is not None and self._outlet.get_packet_id(e.packet) == target_id, self._tx_ring), None)
|
||||||
and self._outlet.get_packet_id(e.packet) == target_id,
|
|
||||||
self._tx_ring), None)
|
|
||||||
|
|
||||||
if envelope and op(envelope):
|
if envelope and op(envelope):
|
||||||
envelope.tracked = False
|
envelope.tracked = False
|
||||||
if envelope in self._tx_ring:
|
if envelope in self._tx_ring:
|
||||||
self._tx_ring.remove(envelope)
|
self._tx_ring.remove(envelope)
|
||||||
|
|
||||||
if self.window < self.window_max:
|
if self.window < self.window_max: self.window += 1
|
||||||
self.window += 1
|
|
||||||
|
|
||||||
# TODO: Remove at some point
|
|
||||||
# RNS.log("Increased "+str(self)+" window to "+str(self.window), RNS.LOG_DEBUG)
|
|
||||||
|
|
||||||
if self._outlet.rtt != 0:
|
if self._outlet.rtt != 0:
|
||||||
if self._outlet.rtt > Channel.RTT_FAST:
|
if self._outlet.rtt > Channel.RTT_FAST:
|
||||||
self.fast_rate_rounds = 0
|
self.fast_rate_rounds = 0
|
||||||
|
if self._outlet.rtt > Channel.RTT_MEDIUM: self.medium_rate_rounds = 0
|
||||||
if self._outlet.rtt > Channel.RTT_MEDIUM:
|
|
||||||
self.medium_rate_rounds = 0
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
self.medium_rate_rounds += 1
|
self.medium_rate_rounds += 1
|
||||||
if self.window_max < Channel.WINDOW_MAX_MEDIUM and self.medium_rate_rounds == Channel.FAST_RATE_THRESHOLD:
|
if self.window_max < Channel.WINDOW_MAX_MEDIUM and self.medium_rate_rounds == Channel.FAST_RATE_THRESHOLD:
|
||||||
self.window_max = Channel.WINDOW_MAX_MEDIUM
|
self.window_max = Channel.WINDOW_MAX_MEDIUM
|
||||||
self.window_min = Channel.WINDOW_MIN_LIMIT_MEDIUM
|
self.window_min = Channel.WINDOW_MIN_LIMIT_MEDIUM
|
||||||
# TODO: Remove at some point
|
|
||||||
# RNS.log("Increased "+str(self)+" max window to "+str(self.window_max), RNS.LOG_DEBUG)
|
|
||||||
# RNS.log("Increased "+str(self)+" min window to "+str(self.window_min), RNS.LOG_DEBUG)
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
self.fast_rate_rounds += 1
|
self.fast_rate_rounds += 1
|
||||||
if self.window_max < Channel.WINDOW_MAX_FAST and self.fast_rate_rounds == Channel.FAST_RATE_THRESHOLD:
|
if self.window_max < Channel.WINDOW_MAX_FAST and self.fast_rate_rounds == Channel.FAST_RATE_THRESHOLD:
|
||||||
self.window_max = Channel.WINDOW_MAX_FAST
|
self.window_max = Channel.WINDOW_MAX_FAST
|
||||||
self.window_min = Channel.WINDOW_MIN_LIMIT_FAST
|
self.window_min = Channel.WINDOW_MIN_LIMIT_FAST
|
||||||
# TODO: Remove at some point
|
|
||||||
# RNS.log("Increased "+str(self)+" max window to "+str(self.window_max), RNS.LOG_DEBUG)
|
|
||||||
# RNS.log("Increased "+str(self)+" min window to "+str(self.window_min), RNS.LOG_DEBUG)
|
|
||||||
|
|
||||||
|
else: RNS.log("Envelope not found in TX ring for "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
else:
|
if not envelope: RNS.log("Spurious message received on "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
RNS.log("Envelope not found in TX ring for "+str(self), RNS.LOG_EXTREME)
|
|
||||||
if not envelope:
|
|
||||||
RNS.log("Spurious message received on "+str(self), RNS.LOG_EXTREME)
|
|
||||||
|
|
||||||
def _packet_delivered(self, packet: TPacket):
|
def _packet_delivered(self, packet: TPacket):
|
||||||
self._packet_tx_op(packet, lambda env: True)
|
self._packet_tx_op(packet, lambda env: True)
|
||||||
@@ -545,29 +450,23 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
for envelope in self._tx_ring:
|
for envelope in self._tx_ring:
|
||||||
updated_timeout = self._get_packet_timeout_time(envelope.tries)
|
updated_timeout = self._get_packet_timeout_time(envelope.tries)
|
||||||
if envelope.packet and hasattr(envelope.packet, "receipt") and envelope.packet.receipt and envelope.packet.receipt.timeout:
|
if envelope.packet and hasattr(envelope.packet, "receipt") and envelope.packet.receipt and envelope.packet.receipt.timeout:
|
||||||
if updated_timeout > envelope.packet.receipt.timeout:
|
if updated_timeout > envelope.packet.receipt.timeout: envelope.packet.receipt.set_timeout(updated_timeout)
|
||||||
envelope.packet.receipt.set_timeout(updated_timeout)
|
|
||||||
|
|
||||||
def _get_packet_timeout_time(self, tries: int) -> float:
|
def _get_packet_timeout_time(self, tries: int) -> float:
|
||||||
to = pow(1.5, tries - 1) * max(self._outlet.rtt*2.5, 0.025) * (len(self._tx_ring)+1.5)
|
to = pow(1.5, tries - 1) * max(self._outlet.rtt*2.5, 0.025) * (len(self._tx_ring)+1.5)
|
||||||
return to
|
return to
|
||||||
|
|
||||||
def _packet_timeout(self, packet: TPacket):
|
def _packet_timeout(self, packet: TPacket):
|
||||||
if self._outlet.get_packet_state(packet) == MessageState.MSGSTATE_DELIVERED:
|
if self._outlet.get_packet_state(packet) == MessageState.MSGSTATE_DELIVERED: return
|
||||||
return
|
|
||||||
|
|
||||||
target_id = self._outlet.get_packet_id(packet)
|
target_id = self._outlet.get_packet_id(packet)
|
||||||
envelope_to_resend: Envelope | None = None
|
envelope_to_resend: Envelope | None = None
|
||||||
should_teardown = False
|
should_teardown = False
|
||||||
with self._lock:
|
with self._lock:
|
||||||
envelope = next(filter(
|
envelope = next(filter(lambda e: e.packet is not None and self._outlet.get_packet_id(e.packet) == target_id, self._tx_ring), None)
|
||||||
lambda e: e.packet is not None and self._outlet.get_packet_id(e.packet) == target_id,
|
if envelope is None: return
|
||||||
self._tx_ring), None)
|
|
||||||
if envelope is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
if envelope.tries >= self._max_tries:
|
if envelope.tries >= self._max_tries: should_teardown = True
|
||||||
should_teardown = True
|
|
||||||
else:
|
else:
|
||||||
envelope.tries += 1
|
envelope.tries += 1
|
||||||
envelope_to_resend = envelope
|
envelope_to_resend = envelope
|
||||||
@@ -587,14 +486,11 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
self._outlet.resend(envelope_to_resend.packet)
|
self._outlet.resend(envelope_to_resend.packet)
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._outlet.set_packet_delivered_callback(envelope_to_resend.packet, self._packet_delivered)
|
self._outlet.set_packet_delivered_callback(envelope_to_resend.packet, self._packet_delivered)
|
||||||
self._outlet.set_packet_timeout_callback(
|
self._outlet.set_packet_timeout_callback(envelope_to_resend.packet, self._packet_timeout, self._get_packet_timeout_time(envelope_to_resend.tries))
|
||||||
envelope_to_resend.packet, self._packet_timeout,
|
|
||||||
self._get_packet_timeout_time(envelope_to_resend.tries))
|
|
||||||
self._update_packet_timeouts()
|
self._update_packet_timeouts()
|
||||||
already_delivered = (self._outlet.get_packet_state(envelope_to_resend.packet) == MessageState.MSGSTATE_DELIVERED)
|
already_delivered = (self._outlet.get_packet_state(envelope_to_resend.packet) == MessageState.MSGSTATE_DELIVERED)
|
||||||
|
|
||||||
if already_delivered:
|
if already_delivered: self._packet_delivered(envelope_to_resend.packet)
|
||||||
self._packet_delivered(envelope_to_resend.packet)
|
|
||||||
|
|
||||||
def send(self, message: MessageBase) -> Envelope:
|
def send(self, message: MessageBase) -> Envelope:
|
||||||
"""
|
"""
|
||||||
@@ -605,24 +501,19 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
"""
|
"""
|
||||||
with self._send_lock:
|
with self._send_lock:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if not self.is_ready_to_send():
|
if not self.is_ready_to_send(): raise ChannelException(CEType.ME_LINK_NOT_READY, f"Link is not ready")
|
||||||
raise ChannelException(CEType.ME_LINK_NOT_READY, f"Link is not ready")
|
|
||||||
|
|
||||||
reserved_sequence = self._next_sequence
|
reserved_sequence = self._next_sequence
|
||||||
envelope = Envelope(self._outlet, message=message, sequence=reserved_sequence)
|
envelope = Envelope(self._outlet, message=message, sequence=reserved_sequence)
|
||||||
envelope.pack()
|
envelope.pack()
|
||||||
if len(envelope.raw) > self._outlet.mdu:
|
if len(envelope.raw) > self._outlet.mdu:
|
||||||
raise ChannelException(CEType.ME_TOO_BIG,
|
raise ChannelException(CEType.ME_TOO_BIG, f"Packed message too big for packet: {len(envelope.raw)} > {self._outlet.mdu}")
|
||||||
f"Packed message too big for packet: {len(envelope.raw)} > {self._outlet.mdu}")
|
|
||||||
self._next_sequence = (reserved_sequence + 1) % Channel.SEQ_MODULUS
|
self._next_sequence = (reserved_sequence + 1) % Channel.SEQ_MODULUS
|
||||||
|
|
||||||
envelope.packet = self._outlet.send(envelope.raw)
|
envelope.packet = self._outlet.send(envelope.raw)
|
||||||
|
|
||||||
if (envelope.packet is None
|
if envelope.packet is None or getattr(envelope.packet, "raw", None) is None or (hasattr(envelope.packet, "receipt") and envelope.packet.receipt is None):
|
||||||
or getattr(envelope.packet, "raw", None) is None
|
with self._lock: self._next_sequence = reserved_sequence
|
||||||
or (hasattr(envelope.packet, "receipt") and envelope.packet.receipt is None)):
|
|
||||||
with self._lock:
|
|
||||||
self._next_sequence = reserved_sequence
|
|
||||||
raise ChannelException(CEType.ME_LINK_NOT_READY, "Outlet did not transmit packet")
|
raise ChannelException(CEType.ME_LINK_NOT_READY, "Outlet did not transmit packet")
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -633,9 +524,8 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
self._update_packet_timeouts()
|
self._update_packet_timeouts()
|
||||||
already_delivered = (self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED)
|
already_delivered = (self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED)
|
||||||
|
|
||||||
# prevent _tx_ring envelope leak
|
# Prevent _tx_ring envelope leak
|
||||||
if already_delivered:
|
if already_delivered: self._packet_delivered(envelope.packet)
|
||||||
self._packet_delivered(envelope.packet)
|
|
||||||
|
|
||||||
return envelope
|
return envelope
|
||||||
|
|
||||||
@@ -650,14 +540,13 @@ class Channel(contextlib.AbstractContextManager):
|
|||||||
:return: number of bytes available
|
:return: number of bytes available
|
||||||
"""
|
"""
|
||||||
mdu = self._outlet.mdu - 6 # sizeof(msgtype) + sizeof(length) + sizeof(sequence)
|
mdu = self._outlet.mdu - 6 # sizeof(msgtype) + sizeof(length) + sizeof(sequence)
|
||||||
if mdu > 0xFFFF:
|
if mdu > 0xFFFF: mdu = 0xFFFF
|
||||||
mdu = 0xFFFF
|
|
||||||
return mdu
|
return mdu
|
||||||
|
|
||||||
|
|
||||||
class LinkChannelOutlet(ChannelOutletBase):
|
class LinkChannelOutlet(ABC, Generic[TPacket]):
|
||||||
"""
|
"""
|
||||||
An implementation of ChannelOutletBase for RNS.Link.
|
A channel outlet implementation for RNS.Link.
|
||||||
Allows Channel to send packets over an RNS Link with
|
Allows Channel to send packets over an RNS Link with
|
||||||
Packets.
|
Packets.
|
||||||
|
|
||||||
@@ -668,71 +557,51 @@ class LinkChannelOutlet(ChannelOutletBase):
|
|||||||
|
|
||||||
def send(self, raw: bytes) -> RNS.Packet:
|
def send(self, raw: bytes) -> RNS.Packet:
|
||||||
packet = RNS.Packet(self.link, raw, context=RNS.Packet.CHANNEL)
|
packet = RNS.Packet(self.link, raw, context=RNS.Packet.CHANNEL)
|
||||||
if self.link.status == RNS.Link.ACTIVE:
|
if self.link.status == RNS.Link.ACTIVE: packet.send()
|
||||||
packet.send()
|
|
||||||
return packet
|
return packet
|
||||||
|
|
||||||
def resend(self, packet: RNS.Packet) -> RNS.Packet:
|
def resend(self, packet: RNS.Packet) -> RNS.Packet:
|
||||||
receipt = packet.resend()
|
receipt = packet.resend()
|
||||||
if not receipt:
|
if not receipt: RNS.log("Failed to resend packet", RNS.LOG_ERROR)
|
||||||
RNS.log("Failed to resend packet", RNS.LOG_ERROR)
|
|
||||||
return packet
|
return packet
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def mdu(self):
|
def mdu(self): return self.link.mdu
|
||||||
return self.link.mdu
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def rtt(self):
|
def rtt(self): return self.link.rtt
|
||||||
return self.link.rtt
|
|
||||||
|
|
||||||
|
# TODO: Initial implementation had issues
|
||||||
|
# proxying this to link status. Should
|
||||||
|
# return False when link is not ACTIVE.
|
||||||
|
# Investigate what happened here.
|
||||||
@property
|
@property
|
||||||
def is_usable(self):
|
def is_usable(self): return True
|
||||||
return True # had issues looking at Link.status
|
|
||||||
|
|
||||||
def get_packet_state(self, packet: TPacket) -> MessageState:
|
def get_packet_state(self, packet: TPacket) -> MessageState:
|
||||||
if packet.receipt == None:
|
if packet.receipt == None:
|
||||||
return MessageState.MSGSTATE_FAILED
|
return MessageState.MSGSTATE_FAILED
|
||||||
|
|
||||||
status = packet.receipt.get_status()
|
status = packet.receipt.get_status()
|
||||||
if status == RNS.PacketReceipt.SENT:
|
if status == RNS.PacketReceipt.SENT: return MessageState.MSGSTATE_SENT
|
||||||
return MessageState.MSGSTATE_SENT
|
if status == RNS.PacketReceipt.DELIVERED: return MessageState.MSGSTATE_DELIVERED
|
||||||
if status == RNS.PacketReceipt.DELIVERED:
|
if status == RNS.PacketReceipt.FAILED: return MessageState.MSGSTATE_FAILED
|
||||||
return MessageState.MSGSTATE_DELIVERED
|
else: raise Exception(f"Unexpected receipt state: {status}")
|
||||||
if status == RNS.PacketReceipt.FAILED:
|
|
||||||
return MessageState.MSGSTATE_FAILED
|
|
||||||
else:
|
|
||||||
raise Exception(f"Unexpected receipt state: {status}")
|
|
||||||
|
|
||||||
def timed_out(self):
|
def set_packet_timeout_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None, timeout: float | None = None):
|
||||||
self.link.teardown()
|
if timeout and packet.receipt: packet.receipt.set_timeout(timeout)
|
||||||
|
def inner(receipt: RNS.PacketReceipt): callback(packet)
|
||||||
def __str__(self):
|
if packet and packet.receipt: packet.receipt.set_timeout_callback(inner if callback else None)
|
||||||
return f"{self.__class__.__name__}({self.link})"
|
|
||||||
|
|
||||||
def set_packet_timeout_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None,
|
|
||||||
timeout: float | None = None):
|
|
||||||
if timeout and packet.receipt:
|
|
||||||
packet.receipt.set_timeout(timeout)
|
|
||||||
|
|
||||||
def inner(receipt: RNS.PacketReceipt):
|
|
||||||
callback(packet)
|
|
||||||
|
|
||||||
if packet and packet.receipt:
|
|
||||||
packet.receipt.set_timeout_callback(inner if callback else None)
|
|
||||||
|
|
||||||
def set_packet_delivered_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None):
|
def set_packet_delivered_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None):
|
||||||
def inner(receipt: RNS.PacketReceipt):
|
def inner(receipt: RNS.PacketReceipt): callback(packet)
|
||||||
callback(packet)
|
if packet and packet.receipt: packet.receipt.set_delivery_callback(inner if callback else None)
|
||||||
|
|
||||||
if packet and packet.receipt:
|
|
||||||
packet.receipt.set_delivery_callback(inner if callback else None)
|
|
||||||
|
|
||||||
def get_packet_id(self, packet: RNS.Packet) -> any:
|
def get_packet_id(self, packet: RNS.Packet) -> any:
|
||||||
if (packet
|
if packet and getattr(packet, "raw", None) is not None and hasattr(packet, "get_hash") and callable(packet.get_hash):
|
||||||
and getattr(packet, "raw", None) is not None
|
|
||||||
and hasattr(packet, "get_hash")
|
|
||||||
and callable(packet.get_hash)):
|
|
||||||
return packet.get_hash()
|
return packet.get_hash()
|
||||||
else:
|
else: return None
|
||||||
return None
|
|
||||||
|
def timed_out(self): self.link.teardown()
|
||||||
|
|
||||||
|
def __str__(self): return f"{self.__class__.__name__}({self.link})"
|
||||||
@@ -180,4 +180,9 @@ def digest(key, msg, digest):
|
|||||||
outer.update(key.translate(trans_5C))
|
outer.update(key.translate(trans_5C))
|
||||||
inner.update(msg)
|
inner.update(msg)
|
||||||
outer.update(inner.digest())
|
outer.update(inner.digest())
|
||||||
return outer.digest()
|
return outer.digest()
|
||||||
|
|
||||||
|
def _cd_internal(a, b): return a == b
|
||||||
|
try: from hmac import compare_digest as _cd
|
||||||
|
except ImportError: _cd = _cd_internal
|
||||||
|
compare_digest = _cd
|
||||||
@@ -80,7 +80,7 @@ class Token():
|
|||||||
received_hmac = token[-32:]
|
received_hmac = token[-32:]
|
||||||
expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
|
expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
|
||||||
|
|
||||||
if received_hmac == expected_hmac: return True
|
if HMAC.compare_digest(received_hmac, expected_hmac): return True
|
||||||
else: return False
|
else: return False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+16
-5
@@ -155,6 +155,7 @@ class Destination:
|
|||||||
self.accept_link_requests = True
|
self.accept_link_requests = True
|
||||||
self.callbacks = Callbacks()
|
self.callbacks = Callbacks()
|
||||||
self.request_handlers = {}
|
self.request_handlers = {}
|
||||||
|
self.max_request_size = None
|
||||||
self.type = type
|
self.type = type
|
||||||
self.direction = direction
|
self.direction = direction
|
||||||
self.proof_strategy = Destination.PROVE_NONE
|
self.proof_strategy = Destination.PROVE_NONE
|
||||||
@@ -205,7 +206,7 @@ class Destination:
|
|||||||
def _clean_ratchets(self):
|
def _clean_ratchets(self):
|
||||||
if self.ratchets != None:
|
if self.ratchets != None:
|
||||||
if len (self.ratchets) > self.retained_ratchets:
|
if len (self.ratchets) > self.retained_ratchets:
|
||||||
self.ratchets = self.ratchets[:Destination.RATCHET_COUNT]
|
self.ratchets = self.ratchets[:self.retained_ratchets]
|
||||||
|
|
||||||
def _persist_ratchets(self):
|
def _persist_ratchets(self):
|
||||||
try:
|
try:
|
||||||
@@ -362,10 +363,20 @@ class Destination:
|
|||||||
|
|
||||||
:param proof_strategy: One of ``RNS.Destination.PROVE_NONE``, ``RNS.Destination.PROVE_ALL`` or ``RNS.Destination.PROVE_APP``. If ``RNS.Destination.PROVE_APP`` is set, the `proof_requested_callback` will be called to determine whether a proof should be sent or not.
|
:param proof_strategy: One of ``RNS.Destination.PROVE_NONE``, ``RNS.Destination.PROVE_ALL`` or ``RNS.Destination.PROVE_APP``. If ``RNS.Destination.PROVE_APP`` is set, the `proof_requested_callback` will be called to determine whether a proof should be sent or not.
|
||||||
"""
|
"""
|
||||||
if not proof_strategy in Destination.proof_strategies:
|
if not proof_strategy in Destination.proof_strategies: raise TypeError("Unsupported proof strategy")
|
||||||
raise TypeError("Unsupported proof strategy")
|
else: self.proof_strategy = proof_strategy
|
||||||
else:
|
|
||||||
self.proof_strategy = proof_strategy
|
def set_max_request_size(self, max_request_size):
|
||||||
|
"""
|
||||||
|
Sets the maximum accepted request size for registered request handlers.
|
||||||
|
|
||||||
|
:param max_request_size: The maximum accepted request size in bytes, as an integer.
|
||||||
|
:raises: ``TypeError`` or ``ValueError`` if any of the argument is invalid.
|
||||||
|
"""
|
||||||
|
try: max_request_size = int(max_request_size)
|
||||||
|
except: raise TypeError("Invalid maximum request size specified")
|
||||||
|
if max_request_size < 0: raise ValueError("Maximum request size cannot be negative")
|
||||||
|
self.max_request_size = max_request_size
|
||||||
|
|
||||||
def register_request_handler(self, path, response_generator = None, allow = ALLOW_NONE, allowed_list = None, auto_compress = True):
|
def register_request_handler(self, path, response_generator = None, allow = ALLOW_NONE, allowed_list = None, auto_compress = True):
|
||||||
"""
|
"""
|
||||||
|
|||||||
+125
-24
@@ -8,6 +8,7 @@ import ipaddress
|
|||||||
import subprocess
|
import subprocess
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
from .vendor import umsgpack as msgpack
|
from .vendor import umsgpack as msgpack
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
NAME = 0xFF
|
NAME = 0xFF
|
||||||
TRANSPORT_ID = 0xFE
|
TRANSPORT_ID = 0xFE
|
||||||
@@ -26,12 +27,13 @@ SPREADINGFACTOR = 0x0B
|
|||||||
CODINGRATE = 0x0C
|
CODINGRATE = 0x0C
|
||||||
MODULATION = 0x0D
|
MODULATION = 0x0D
|
||||||
CHANNEL = 0x0E
|
CHANNEL = 0x0E
|
||||||
|
OP_ADDR = 0xF0
|
||||||
|
|
||||||
APP_NAME = "rnstransport"
|
APP_NAME = "rnstransport"
|
||||||
|
|
||||||
class InterfaceAnnouncer():
|
class InterfaceAnnouncer():
|
||||||
JOB_INTERVAL = 60
|
JOB_INTERVAL = 60
|
||||||
DEFAULT_STAMP_VALUE = 14
|
DEFAULT_STAMP_VALUE = 16
|
||||||
WORKBLOCK_EXPAND_ROUNDS = 20
|
WORKBLOCK_EXPAND_ROUNDS = 20
|
||||||
|
|
||||||
DISCOVERABLE_INTERFACE_TYPES = ["BackboneInterface", "TCPServerInterface", "TCPClientInterface",
|
DISCOVERABLE_INTERFACE_TYPES = ["BackboneInterface", "TCPServerInterface", "TCPClientInterface",
|
||||||
@@ -99,6 +101,33 @@ class InterfaceAnnouncer():
|
|||||||
|
|
||||||
if not interface_type in self.DISCOVERABLE_INTERFACE_TYPES: return None
|
if not interface_type in self.DISCOVERABLE_INTERFACE_TYPES: return None
|
||||||
else:
|
else:
|
||||||
|
if not RNS.vendor.platformutils.is_windows() and interface.discovery_location:
|
||||||
|
try:
|
||||||
|
discovery_location = self.sanitize(interface.discovery_location)
|
||||||
|
exec_path = os.path.expanduser(discovery_location)
|
||||||
|
if os.path.isfile(exec_path) and os.access(exec_path, os.X_OK):
|
||||||
|
RNS.log(f"Evaluating discovery location from executable at {exec_path}", RNS.LOG_DEBUG)
|
||||||
|
exec_result = subprocess.run([exec_path], stdout=subprocess.PIPE)
|
||||||
|
exec_stdout = exec_result.stdout.decode("utf-8")
|
||||||
|
if exec_result.returncode != 0: raise ValueError("Non-zero exit code from subprocess")
|
||||||
|
discovery_location = self.sanitize(exec_stdout)
|
||||||
|
location_components = discovery_location.replace(" ", "").split(",")
|
||||||
|
if len(location_components) != 3: raise ValueError(f"Invalid location component count: {len(location_components)}")
|
||||||
|
dlat = float(location_components[0])
|
||||||
|
dlon = float(location_components[1])
|
||||||
|
dhgt = float(location_components[2])
|
||||||
|
if dlat < -90 or dlat > 90: raise ValueError(f"Invalid latitude: {dlat}")
|
||||||
|
if dlon < -180 or dlat > 180: raise ValueError(f"Invalid longitude: {dlon}")
|
||||||
|
if dhgt < -4000 or dhgt > 1e6: raise ValueError(f"Invalid height: {dhgt}")
|
||||||
|
interface.discovery_latitude = dlat
|
||||||
|
interface.discovery_longitude = dlon
|
||||||
|
interface.discovery_height = dhgt
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log(f"Error while getting discovery location from executable at {interface.reachable_on}: {e}", RNS.LOG_ERROR)
|
||||||
|
RNS.log(f"Aborting discovery announce", RNS.LOG_ERROR)
|
||||||
|
return None
|
||||||
|
|
||||||
flags = 0x00
|
flags = 0x00
|
||||||
info = {INTERFACE_TYPE: interface_type,
|
info = {INTERFACE_TYPE: interface_type,
|
||||||
TRANSPORT: RNS.Reticulum.transport_enabled(),
|
TRANSPORT: RNS.Reticulum.transport_enabled(),
|
||||||
@@ -108,11 +137,14 @@ class InterfaceAnnouncer():
|
|||||||
LONGITUDE: interface.discovery_longitude,
|
LONGITUDE: interface.discovery_longitude,
|
||||||
HEIGHT: interface.discovery_height}
|
HEIGHT: interface.discovery_height}
|
||||||
|
|
||||||
|
if interface.discovery_lxmf_address: info[OP_ADDR] = interface.discovery_lxmf_address
|
||||||
|
|
||||||
if interface_type == "TCPClientInterface" and not interface.kiss_framing:
|
if interface_type == "TCPClientInterface" and not interface.kiss_framing:
|
||||||
RNS.log(f"Invalid interface discovery configuration for {interface}, aborting discovery announce", RNS.LOG_ERROR)
|
RNS.log(f"Invalid interface discovery configuration for {interface}, aborting discovery announce", RNS.LOG_ERROR)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if interface_type in ["BackboneInterface", "TCPServerInterface"]:
|
if interface_type in ["BackboneInterface", "TCPServerInterface"]:
|
||||||
|
if not interface.reachable_on: return None
|
||||||
reachable_on = self.sanitize(interface.reachable_on)
|
reachable_on = self.sanitize(interface.reachable_on)
|
||||||
|
|
||||||
if not RNS.vendor.platformutils.is_windows():
|
if not RNS.vendor.platformutils.is_windows():
|
||||||
@@ -197,10 +229,14 @@ class InterfaceAnnounceHandler:
|
|||||||
RNS.log("You can install it with the command: pip install lxmf", RNS.LOG_CRITICAL)
|
RNS.log("You can install it with the command: pip install lxmf", RNS.LOG_CRITICAL)
|
||||||
RNS.panic()
|
RNS.panic()
|
||||||
|
|
||||||
self.aspect_filter = APP_NAME+".discovery.interface"
|
self.aspect_filter = APP_NAME+".discovery.interface"
|
||||||
self.required_value = required_value
|
self.required_value = required_value
|
||||||
self.callback = callback
|
self.callback = callback
|
||||||
self.stamper = LXStamper
|
self.stamper = LXStamper
|
||||||
|
self.valid_cache = {}
|
||||||
|
self.valid_cache_max = 2048
|
||||||
|
self.invalid_cache = deque(maxlen=2048)
|
||||||
|
self.validation_lock = threading.Lock()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def sanitize_name(name):
|
def sanitize_name(name):
|
||||||
@@ -223,21 +259,43 @@ class InterfaceAnnounceHandler:
|
|||||||
app_data = app_data[1:]
|
app_data = app_data[1:]
|
||||||
signed = flags & self.FLAG_SIGNED
|
signed = flags & self.FLAG_SIGNED
|
||||||
encrypted = flags & self.FLAG_ENCRYPTED
|
encrypted = flags & self.FLAG_ENCRYPTED
|
||||||
|
fullhash = RNS.Identity.full_hash(app_data)
|
||||||
|
|
||||||
if encrypted:
|
if fullhash in self.invalid_cache:
|
||||||
if not RNS.Transport.has_network_identity(): return
|
RNS.log(f"Ignored previously discovered interface with insufficient stamp value", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
app_data = RNS.Transport.network_identity.decrypt(app_data)
|
return
|
||||||
if not app_data: return
|
|
||||||
|
|
||||||
stamp = app_data[-self.stamper.STAMP_SIZE:]
|
if fullhash in self.valid_cache:
|
||||||
packed = app_data[:-self.stamper.STAMP_SIZE]
|
RNS.log(f"Discovery announce cache hit", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
infohash = RNS.Identity.full_hash(packed)
|
cache_entry = self.valid_cache[fullhash]
|
||||||
workblock = self.stamper.stamp_workblock(infohash, expand_rounds=InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS)
|
stamp = cache_entry["stamp"]
|
||||||
value = self.stamper.stamp_value(workblock, stamp)
|
packed = cache_entry["packed"]
|
||||||
valid = self.stamper.stamp_valid(stamp, self.required_value, workblock)
|
value = cache_entry["value"]
|
||||||
|
valid = cache_entry["valid"]
|
||||||
|
|
||||||
|
else:
|
||||||
|
if encrypted:
|
||||||
|
if not RNS.Transport.has_network_identity(): return
|
||||||
|
app_data = RNS.Transport.network_identity.decrypt(app_data)
|
||||||
|
if not app_data: return
|
||||||
|
|
||||||
|
if self.validation_lock.locked():
|
||||||
|
RNS.log(f"Dropping received interface discovery announce, already validating other discovery stamp", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
return
|
||||||
|
|
||||||
|
with self.validation_lock:
|
||||||
|
stamp = app_data[-self.stamper.STAMP_SIZE:]
|
||||||
|
packed = app_data[:-self.stamper.STAMP_SIZE]
|
||||||
|
infohash = RNS.Identity.full_hash(packed)
|
||||||
|
workblock = self.stamper.stamp_workblock(infohash, expand_rounds=InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS)
|
||||||
|
value = self.stamper.stamp_value(workblock, stamp)
|
||||||
|
valid = self.stamper.stamp_valid(stamp, self.required_value, workblock)
|
||||||
|
self.valid_cache[fullhash] = {"valid": valid, "value": value, "packed": packed, "stamp": stamp}
|
||||||
|
while len(self.valid_cache) > self.valid_cache_max: self.valid_cache.pop(next(iter(self.valid_cache)))
|
||||||
|
|
||||||
if not valid:
|
if not valid:
|
||||||
RNS.log(f"Ignored discovered interface with invalid stamp", RNS.LOG_DEBUG)
|
RNS.log(f"Ignored discovered interface with insufficient stamp value {value}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
self.invalid_cache.append(fullhash)
|
||||||
return
|
return
|
||||||
|
|
||||||
if value < self.required_value: RNS.log(f"Ignored discovered interface with stamp value {value}", RNS.LOG_DEBUG)
|
if value < self.required_value: RNS.log(f"Ignored discovered interface with stamp value {value}", RNS.LOG_DEBUG)
|
||||||
@@ -277,7 +335,7 @@ class InterfaceAnnounceHandler:
|
|||||||
if IFAC_NETKEY in unpacked: info["ifac_netkey"] = str(unpacked[IFAC_NETKEY])
|
if IFAC_NETKEY in unpacked: info["ifac_netkey"] = str(unpacked[IFAC_NETKEY])
|
||||||
|
|
||||||
if interface_type in ["BackboneInterface", "TCPServerInterface"]:
|
if interface_type in ["BackboneInterface", "TCPServerInterface"]:
|
||||||
backbone_support = not RNS.vendor.platformutils.is_windows()
|
backbone_support = not RNS.vendor.platformutils.is_windows() and not RNS.vendor.platformutils.is_darwin()
|
||||||
info["reachable_on"] = unpacked[REACHABLE_ON]
|
info["reachable_on"] = unpacked[REACHABLE_ON]
|
||||||
info["port"] = unpacked[PORT]
|
info["port"] = unpacked[PORT]
|
||||||
connection_interface = "BackboneInterface" if backbone_support else "TCPClientInterface"
|
connection_interface = "BackboneInterface" if backbone_support else "TCPClientInterface"
|
||||||
@@ -356,6 +414,11 @@ class InterfaceAnnounceHandler:
|
|||||||
discovery_hash_material = info["transport_id"]+info["name"]
|
discovery_hash_material = info["transport_id"]+info["name"]
|
||||||
info["discovery_hash"] = RNS.Identity.full_hash(discovery_hash_material.encode("utf-8"))
|
info["discovery_hash"] = RNS.Identity.full_hash(discovery_hash_material.encode("utf-8"))
|
||||||
|
|
||||||
|
if info and OP_ADDR in unpacked:
|
||||||
|
if type(unpacked[OP_ADDR]) not in [type(None), bytes]: raise ValueError("Invalid data in operator LXMF address field of announce")
|
||||||
|
if unpacked[OP_ADDR] and len(unpacked[OP_ADDR]) == RNS.Identity.TRUNCATED_HASHLENGTH//8:
|
||||||
|
info["operator_lxmf_address"] = RNS.hexrep(unpacked[OP_ADDR], delimit=False)
|
||||||
|
|
||||||
if self.callback and callable(self.callback): self.callback(info)
|
if self.callback and callable(self.callback): self.callback(info)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -376,6 +439,9 @@ class InterfaceDiscovery():
|
|||||||
AUTOCONNECT_TYPES = ["BackboneInterface", "TCPServerInterface"]
|
AUTOCONNECT_TYPES = ["BackboneInterface", "TCPServerInterface"]
|
||||||
DISCOVERABLE_TYPES = ["BackboneInterface", "TCPServerInterface", "I2PInterface", "RNodeInterface", "WeaveInterface", "KISSInterface"]
|
DISCOVERABLE_TYPES = ["BackboneInterface", "TCPServerInterface", "I2PInterface", "RNodeInterface", "WeaveInterface", "KISSInterface"]
|
||||||
|
|
||||||
|
AC_TRANSPORT_MODE = RNS.Interfaces.Interface.Interface.MODE_GATEWAY
|
||||||
|
AC_GRAVITY = 0
|
||||||
|
|
||||||
discovery_lock = Lock()
|
discovery_lock = Lock()
|
||||||
|
|
||||||
def __init__(self, required_value=InterfaceAnnouncer.DEFAULT_STAMP_VALUE, callback=None, discover_interfaces=True):
|
def __init__(self, required_value=InterfaceAnnouncer.DEFAULT_STAMP_VALUE, callback=None, discover_interfaces=True):
|
||||||
@@ -389,6 +455,8 @@ class InterfaceDiscovery():
|
|||||||
self.monitor_interval = self.MONITOR_INTERVAL
|
self.monitor_interval = self.MONITOR_INTERVAL
|
||||||
self.detach_threshold = self.DETACH_THRESHOLD
|
self.detach_threshold = self.DETACH_THRESHOLD
|
||||||
self.initial_autoconnect_ran = False
|
self.initial_autoconnect_ran = False
|
||||||
|
self.blackholed_updated = 0
|
||||||
|
self.__blackholed = {}
|
||||||
|
|
||||||
if not self.rns_instance: raise SystemError("Attempt to start interface discovery listener without an active RNS instance")
|
if not self.rns_instance: raise SystemError("Attempt to start interface discovery listener without an active RNS instance")
|
||||||
self.storagepath = os.path.join(RNS.Reticulum.storagepath, "discovery", "interfaces")
|
self.storagepath = os.path.join(RNS.Reticulum.storagepath, "discovery", "interfaces")
|
||||||
@@ -399,10 +467,18 @@ class InterfaceDiscovery():
|
|||||||
RNS.Transport.register_announce_handler(self.handler)
|
RNS.Transport.register_announce_handler(self.handler)
|
||||||
threading.Thread(target=self.connect_discovered, daemon=True).start()
|
threading.Thread(target=self.connect_discovered, daemon=True).start()
|
||||||
|
|
||||||
|
def __blackholed_identities(self):
|
||||||
|
st = time.time()
|
||||||
|
if not self.__blackholed or time.time() > self.blackholed_updated+60:
|
||||||
|
self.__blackholed = self.rns_instance.get_blackholed_identities()
|
||||||
|
self.blackholed_updated = time.time()
|
||||||
|
return self.__blackholed
|
||||||
|
|
||||||
def list_discovered_interfaces(self, only_available=False, only_transport=False):
|
def list_discovered_interfaces(self, only_available=False, only_transport=False):
|
||||||
now = time.time()
|
now = time.time()
|
||||||
discovered_interfaces = []
|
discovered_interfaces = []
|
||||||
discovery_sources = RNS.Reticulum.interface_discovery_sources()
|
discovery_sources = RNS.Reticulum.interface_discovery_sources()
|
||||||
|
blackholed_identities = self.__blackholed_identities()
|
||||||
for filename in os.listdir(self.storagepath):
|
for filename in os.listdir(self.storagepath):
|
||||||
try:
|
try:
|
||||||
with self.discovery_lock:
|
with self.discovery_lock:
|
||||||
@@ -410,13 +486,17 @@ class InterfaceDiscovery():
|
|||||||
with open(filepath, "rb") as f: info = msgpack.unpackb(f.read())
|
with open(filepath, "rb") as f: info = msgpack.unpackb(f.read())
|
||||||
|
|
||||||
should_remove = False
|
should_remove = False
|
||||||
heard_delta = now-info["last_heard"]
|
heard_delta = now-info["last_heard"]
|
||||||
info["name"] = InterfaceAnnounceHandler.sanitize_name(info["name"])
|
info["name"] = InterfaceAnnounceHandler.sanitize_name(info["name"])
|
||||||
|
|
||||||
if heard_delta > self.THRESHOLD_REMOVE: should_remove = True
|
if heard_delta > self.THRESHOLD_REMOVE: should_remove = True
|
||||||
|
elif not "transport_id" in info or not info["transport_id"]: should_remove = True
|
||||||
|
elif not "network_id" in info or not info["network_id"]: should_remove = True
|
||||||
elif discovery_sources and not "network_id" in info: should_remove = True
|
elif discovery_sources and not "network_id" in info: should_remove = True
|
||||||
elif discovery_sources and not bytes.fromhex(info["network_id"]) in discovery_sources: should_remove = True
|
elif discovery_sources and not bytes.fromhex(info["network_id"]) in discovery_sources: should_remove = True
|
||||||
elif not "type" in info or ("type" in info and not info["type"] in self.DISCOVERABLE_TYPES): should_remove = True
|
elif not "type" in info or ("type" in info and not info["type"] in self.DISCOVERABLE_TYPES): should_remove = True
|
||||||
|
elif bytes.fromhex(info["network_id"]) in blackholed_identities: should_remove = True
|
||||||
|
elif bytes.fromhex(info["transport_id"]) in blackholed_identities: should_remove = True
|
||||||
elif "reachable_on" in info:
|
elif "reachable_on" in info:
|
||||||
if not (is_ip_address(info["reachable_on"]) or is_hostname(info["reachable_on"])): should_remove = True
|
if not (is_ip_address(info["reachable_on"]) or is_hostname(info["reachable_on"])): should_remove = True
|
||||||
|
|
||||||
@@ -642,14 +722,22 @@ class InterfaceDiscovery():
|
|||||||
return
|
return
|
||||||
|
|
||||||
if interface_type == "I2PInterface":
|
if interface_type == "I2PInterface":
|
||||||
RNS.log(f"Auto-connecting discovered I2P interfaces is not yet implemented, aborting auto-connect", RNS.LOG_WARNING)
|
RNS.log(f"Auto-connecting discovered I2P interfaces is not yet implemented, aborting auto-connect", RNS.LOG_DEBUG)
|
||||||
RNS.log(f"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", RNS.LOG_WARNING)
|
RNS.log(f"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", RNS.LOG_DEBUG)
|
||||||
return
|
return
|
||||||
|
|
||||||
if is_ygg_ipv6(info["reachable_on"]):
|
if is_ygg_ipv6(info["reachable_on"]):
|
||||||
# TODO: Somehow detect if yggdrasil is enabled on the system
|
# TODO: Somehow detect if yggdrasil is enabled on the system
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if is_onion_address(info["reachable_on"]):
|
||||||
|
# TODO: Somehow detect if TOR is enabled on the system
|
||||||
|
return
|
||||||
|
|
||||||
|
if is_ip_address(info["reachable_on"]) and is_invalid_ip_address(info["reachable_on"]):
|
||||||
|
RNS.log(f"Not auto-connecting discovered interface with invalid IP address: {info['reachable_on']}", RNS.LOG_DEBUG)
|
||||||
|
return
|
||||||
|
|
||||||
interface_name = info["name"]
|
interface_name = info["name"]
|
||||||
config_entry = info["config_entry"]
|
config_entry = info["config_entry"]
|
||||||
interface_config = {}
|
interface_config = {}
|
||||||
@@ -668,12 +756,16 @@ class InterfaceDiscovery():
|
|||||||
RNS.log(f"Auto-connecting discovered {interface_type} {interface_name}")
|
RNS.log(f"Auto-connecting discovered {interface_type} {interface_name}")
|
||||||
interface.autoconnect_hash = endpoint_hash
|
interface.autoconnect_hash = endpoint_hash
|
||||||
interface.autoconnect_source = info["network_id"]
|
interface.autoconnect_source = info["network_id"]
|
||||||
mode = RNS.Interfaces.Interface.Interface.MODE_GATEWAY if RNS.Reticulum.transport_enabled() else None
|
if RNS.Reticulum.autoconnect_interface_mode(): mode = RNS.Reticulum.autoconnect_interface_mode()
|
||||||
|
else: mode = self.AC_TRANSPORT_MODE if RNS.Reticulum.transport_enabled() else None
|
||||||
|
internal_a = True if RNS.Reticulum.autoconnect_announces_to_internal() else None
|
||||||
|
gravity = RNS.Reticulum.autoconnect_interface_gravity() or self.AC_GRAVITY
|
||||||
ar_target = RNS.Reticulum.get_instance()._default_ar_target() if RNS.Reticulum.transport_enabled() else None
|
ar_target = RNS.Reticulum.get_instance()._default_ar_target() if RNS.Reticulum.transport_enabled() else None
|
||||||
ar_penalty = RNS.Reticulum.get_instance()._default_ar_penalty() if RNS.Reticulum.transport_enabled() else None
|
ar_penalty = RNS.Reticulum.get_instance()._default_ar_penalty() if RNS.Reticulum.transport_enabled() else None
|
||||||
ar_grace = RNS.Reticulum.get_instance()._default_ar_grace() if RNS.Reticulum.transport_enabled() else None
|
ar_grace = RNS.Reticulum.get_instance()._default_ar_grace() if RNS.Reticulum.transport_enabled() else None
|
||||||
RNS.Reticulum.get_instance()._add_interface(interface, mode=mode, ifac_netname=ifac_netname, ifac_netkey=ifac_netkey, configured_bitrate=5E6,
|
RNS.Reticulum.get_instance()._add_interface(interface, mode=mode, ifac_netname=ifac_netname, ifac_netkey=ifac_netkey, configured_bitrate=5E6,
|
||||||
announce_rate_target=ar_target, announce_rate_grace=ar_grace, announce_rate_penalty=ar_penalty)
|
announce_rate_target=ar_target, announce_rate_grace=ar_grace, announce_rate_penalty=ar_penalty,
|
||||||
|
announces_to_internal=internal_a, gravity=gravity)
|
||||||
self.monitor_interface(interface)
|
self.monitor_interface(interface)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -776,6 +868,15 @@ def is_ygg_ipv6(address_string):
|
|||||||
try: return ipaddress.ip_address(address_string) in ipaddress.IPv6Network("200::/7")
|
try: return ipaddress.ip_address(address_string) in ipaddress.IPv6Network("200::/7")
|
||||||
except: return False
|
except: return False
|
||||||
|
|
||||||
|
def is_onion_address(address_string):
|
||||||
|
try: return address_string.lower().endswith(".onion")
|
||||||
|
except: return False
|
||||||
|
|
||||||
|
INVALID_IP_ADDRESSES = ["127.0.0.1", "0.0.0.0"]
|
||||||
|
def is_invalid_ip_address(address_string):
|
||||||
|
if not address_string in INVALID_IP_ADDRESSES: return False
|
||||||
|
else: return True
|
||||||
|
|
||||||
def is_hostname(hostname):
|
def is_hostname(hostname):
|
||||||
if hostname[-1] == ".": hostname = hostname[:-1]
|
if hostname[-1] == ".": hostname = hostname[:-1]
|
||||||
if len(hostname) > 253: return False
|
if len(hostname) > 253: return False
|
||||||
|
|||||||
+16
-36
@@ -174,12 +174,9 @@ class Identity:
|
|||||||
else: return None
|
else: return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def save_known_destinations(background=False, recombine=True):
|
def save_known_destinations(background=False, recombine=False):
|
||||||
# TODO: Improve the storage method so we don't have to
|
if recombine: RNS.log(f"Recombining known destinations from disk cache on persist is deprecated, argument ignored", RNS.LOG_WARNING)
|
||||||
# deserialize and serialize the entire table on every
|
if RNS.Transport.owner.is_connected_to_shared_instance: return
|
||||||
# save, but the only changes. It might be possible to
|
|
||||||
# simply overwrite on exit now that every local client
|
|
||||||
# disconnect triggers a data persist.
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if hasattr(Identity, "saving_known_destinations"):
|
if hasattr(Identity, "saving_known_destinations"):
|
||||||
@@ -194,28 +191,9 @@ class Identity:
|
|||||||
|
|
||||||
Identity.saving_known_destinations = True
|
Identity.saving_known_destinations = True
|
||||||
save_start = time.time()
|
save_start = time.time()
|
||||||
|
RNS.log("Saving "+str(len(Identity.known_destinations))+" known destinations to storage...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
if recombine:
|
|
||||||
storage_known_destinations = {}
|
|
||||||
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
|
|
||||||
try:
|
|
||||||
with open(RNS.Reticulum.storagepath+"/known_destinations","rb") as file:
|
|
||||||
storage_known_destinations = umsgpack.load(file)
|
|
||||||
|
|
||||||
except: pass
|
|
||||||
|
|
||||||
try:
|
|
||||||
for destination_hash in storage_known_destinations:
|
|
||||||
if not destination_hash in Identity.known_destinations:
|
|
||||||
with Identity.known_destinations_lock:
|
|
||||||
Identity.known_destinations[destination_hash] = storage_known_destinations[destination_hash]
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Skipped recombining known destinations from disk, since an error occurred: "+str(e), RNS.LOG_WARNING)
|
|
||||||
|
|
||||||
RNS.log("Saving "+str(len(Identity.known_destinations))+" known destinations to storage...", RNS.LOG_VERBOSE)
|
|
||||||
temp_file = RNS.Reticulum.storagepath+f"/known_destinations.tmp.{time.time()}"
|
temp_file = RNS.Reticulum.storagepath+f"/known_destinations.tmp.{time.time()}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(temp_file,"wb") as file: umsgpack.dump(Identity.known_destinations.copy(), file)
|
with open(temp_file,"wb") as file: umsgpack.dump(Identity.known_destinations.copy(), file)
|
||||||
os.replace(temp_file, RNS.Reticulum.storagepath+f"/known_destinations")
|
os.replace(temp_file, RNS.Reticulum.storagepath+f"/known_destinations")
|
||||||
@@ -226,17 +204,13 @@ class Identity:
|
|||||||
except Exception as e: RNS.log(f"Could not clean up temporary file {temp_file}: {e}", RNS.LOG_WARNING)
|
except Exception as e: RNS.log(f"Could not clean up temporary file {temp_file}: {e}", RNS.LOG_WARNING)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
save_time = time.time() - save_start
|
RNS.log(f"Saved known destinations to storage in {RNS.prettyshorttime(time.time()-save_start)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
if save_time < 1: time_str = str(round(save_time*1000,2))+"ms"
|
|
||||||
else: time_str = str(round(save_time,2))+"s"
|
|
||||||
|
|
||||||
RNS.log("Saved known destinations to storage in "+time_str, RNS.LOG_VERBOSE)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("Error while saving known destinations to disk, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
RNS.log("Error while saving known destinations to disk, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
RNS.trace_exception(e)
|
RNS.trace_exception(e)
|
||||||
|
|
||||||
Identity.saving_known_destinations = False
|
finally: Identity.saving_known_destinations = False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def load_known_destinations():
|
def load_known_destinations():
|
||||||
@@ -308,7 +282,7 @@ class Identity:
|
|||||||
except Exception as e: RNS.log(f"Error while retaining identity {RNS.prettyhexrep(identity_hash)}: {e}", RNS.LOG_ERROR)
|
except Exception as e: RNS.log(f"Error while retaining identity {RNS.prettyhexrep(identity_hash)}: {e}", RNS.LOG_ERROR)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def clean_known_destinations():
|
def clean_known_destinations(background=False):
|
||||||
now = time.time()
|
now = time.time()
|
||||||
st = now
|
st = now
|
||||||
total = len(Identity.known_destinations)
|
total = len(Identity.known_destinations)
|
||||||
@@ -318,9 +292,13 @@ class Identity:
|
|||||||
never_used = 0
|
never_used = 0
|
||||||
ratchetdir = RNS.Reticulum.storagepath+"/ratchets"
|
ratchetdir = RNS.Reticulum.storagepath+"/ratchets"
|
||||||
|
|
||||||
|
RNS.log(f"Cleaning known destinations{' at background priority' if background else ''}...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
with Identity.known_destinations_lock: destination_hashes = list(Identity.known_destinations.keys())
|
with Identity.known_destinations_lock: destination_hashes = list(Identity.known_destinations.keys())
|
||||||
for destination_hash in destination_hashes:
|
for destination_hash in destination_hashes:
|
||||||
try:
|
try:
|
||||||
|
if background: time.sleep(0.001) # Low priority, yield thread
|
||||||
|
RNS.Transport.destinations_last_cleaned = time.time()
|
||||||
if RNS.Transport.has_path(destination_hash): has_path = True
|
if RNS.Transport.has_path(destination_hash): has_path = True
|
||||||
else:
|
else:
|
||||||
has_path = False
|
has_path = False
|
||||||
@@ -366,7 +344,8 @@ class Identity:
|
|||||||
if os.path.isfile(ratchet_path): os.unlink(ratchet_path)
|
if os.path.isfile(ratchet_path): os.unlink(ratchet_path)
|
||||||
except Exception as e: RNS.log(f"Could not clean stale ratchets for {RNS.prettyhexrep(destination_hash)}: {e}", RNS.LOG_WARNING)
|
except Exception as e: RNS.log(f"Could not clean stale ratchets for {RNS.prettyhexrep(destination_hash)}: {e}", RNS.LOG_WARNING)
|
||||||
|
|
||||||
# RNS.log(f"Total destinations: {total}, stale: {len(stale)}, removed: {removed}, no path: {no_path}, never used: {never_used}, with path: {total-no_path}, used: {total-never_used}, retained: {retained}. Completed in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_WARNING) # TODO: Remove
|
RNS.log(f"Cleaned known destinations in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
RNS.log(f"Total: {total}, stale: {len(stale)}, removed: {removed}, no path: {no_path}, never used: {never_used}, with path: {total-no_path}, used: {total-never_used}, retained: {retained}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
if not RNS.Transport.owner.is_connected_to_shared_instance: Identity.save_known_destinations(recombine=False)
|
if not RNS.Transport.owner.is_connected_to_shared_instance: Identity.save_known_destinations(recombine=False)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -529,7 +508,7 @@ class Identity:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def validate_announce(packet, only_validate_signature=False):
|
def validate_announce(packet, only_validate_signature=False, signal_blackholed=False):
|
||||||
try:
|
try:
|
||||||
if packet.packet_type == RNS.Packet.ANNOUNCE:
|
if packet.packet_type == RNS.Packet.ANNOUNCE:
|
||||||
keysize = Identity.KEYSIZE//8
|
keysize = Identity.KEYSIZE//8
|
||||||
@@ -574,7 +553,8 @@ class Identity:
|
|||||||
if len(RNS.Transport.blackholed_identities) > 0:
|
if len(RNS.Transport.blackholed_identities) > 0:
|
||||||
if announced_identity.hash in RNS.Transport.blackholed_identities:
|
if announced_identity.hash in RNS.Transport.blackholed_identities:
|
||||||
RNS.log(f"Invalidated and dropped announce from blackholed identity {RNS.prettyhexrep(announced_identity.hash)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
RNS.log(f"Invalidated and dropped announce from blackholed identity {RNS.prettyhexrep(announced_identity.hash)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
return False
|
if signal_blackholed: return "blackholed"
|
||||||
|
else: return False
|
||||||
|
|
||||||
if announced_identity.pub != None and announced_identity.validate(signature, signed_data):
|
if announced_identity.pub != None and announced_identity.validate(signature, signed_data):
|
||||||
if only_validate_signature:
|
if only_validate_signature:
|
||||||
|
|||||||
@@ -1742,7 +1742,7 @@ class BLEConnection(BluetoothDispatcher):
|
|||||||
ble_devices = self.find_target_devices()
|
ble_devices = self.find_target_devices()
|
||||||
|
|
||||||
if len(ble_devices) > 0: self.ble_device = ble_devices.pop()
|
if len(ble_devices) > 0: self.ble_device = ble_devices.pop()
|
||||||
else: self.ble_device == None
|
else: self.ble_device = None
|
||||||
|
|
||||||
if self.ble_device != None:
|
if self.ble_device != None:
|
||||||
if self.was_connected:
|
if self.was_connected:
|
||||||
|
|||||||
@@ -580,6 +580,7 @@ class AutoInterface(Interface):
|
|||||||
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
||||||
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
||||||
spawned_interface.mode = self.mode
|
spawned_interface.mode = self.mode
|
||||||
|
spawned_interface.gravity = self.gravity
|
||||||
spawned_interface.HW_MTU = self.HW_MTU
|
spawned_interface.HW_MTU = self.HW_MTU
|
||||||
spawned_interface.online = True
|
spawned_interface.online = True
|
||||||
RNS.Transport.add_interface(spawned_interface)
|
RNS.Transport.add_interface(spawned_interface)
|
||||||
|
|||||||
@@ -54,6 +54,13 @@ class BackboneInterface(Interface):
|
|||||||
DEFAULT_IFAC_SIZE = 16
|
DEFAULT_IFAC_SIZE = 16
|
||||||
AUTOCONFIGURE_MTU = True
|
AUTOCONFIGURE_MTU = True
|
||||||
|
|
||||||
|
BLOCK_FAST_FLAPPING = True
|
||||||
|
FAST_FLAP_THRESHOLD = 20
|
||||||
|
FAST_FLAP_GRACE = 5
|
||||||
|
FAST_FLAP_EXPIRY = 12*60*60
|
||||||
|
fast_flapping_lock = threading.Lock()
|
||||||
|
fast_flapping = {}
|
||||||
|
|
||||||
epoll = None
|
epoll = None
|
||||||
listener_filenos = {}
|
listener_filenos = {}
|
||||||
spawned_interface_filenos = {}
|
spawned_interface_filenos = {}
|
||||||
@@ -109,13 +116,17 @@ class BackboneInterface(Interface):
|
|||||||
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
c = Interface.get_config_obj(configuration)
|
c = Interface.get_config_obj(configuration)
|
||||||
name = c["name"]
|
name = c["name"]
|
||||||
device = c["device"] if "device" in c else None
|
device = c["device"] if "device" in c else None
|
||||||
port = int(c["port"]) if "port" in c else None
|
port = int(c["port"]) if "port" in c else None
|
||||||
bindip = c["listen_ip"] if "listen_ip" in c else None
|
bindip = c["listen_ip"] if "listen_ip" in c else None
|
||||||
bindport = int(c["listen_port"]) if "listen_port" in c else None
|
bindport = int(c["listen_port"]) if "listen_port" in c else None
|
||||||
prefer_ipv6 = c.as_bool("prefer_ipv6") if "prefer_ipv6" in c else False
|
prefer_ipv6 = c.as_bool("prefer_ipv6") if "prefer_ipv6" in c else False
|
||||||
|
flap_block = c.as_bool("block_fast_flapping") if "block_fast_flapping" in c else BackboneInterface.BLOCK_FAST_FLAPPING
|
||||||
|
flap_threshold = c.as_float("fast_flapping_threshold") if "fast_flapping_threshold" in c else BackboneInterface.FAST_FLAP_THRESHOLD
|
||||||
|
flap_grace = c.as_int("fast_flapping_grace") if "fast_flapping_grace" in c else BackboneInterface.FAST_FLAP_GRACE
|
||||||
|
flap_expiry = c.as_float("fast_flapping_block_time")*60 if "fast_flapping_block_time" in c else BackboneInterface.FAST_FLAP_EXPIRY
|
||||||
|
|
||||||
if port != None: bindport = port
|
if port != None: bindport = port
|
||||||
|
|
||||||
@@ -128,11 +139,13 @@ class BackboneInterface(Interface):
|
|||||||
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
|
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
|
||||||
self.spawned_interfaces = []
|
self.spawned_interfaces = []
|
||||||
self.supports_discovery = True
|
self.supports_discovery = True
|
||||||
|
self.block_fast_flapping = flap_block
|
||||||
|
self.fast_flap_threshold = flap_threshold
|
||||||
|
self.fast_flap_grace = flap_grace
|
||||||
|
self.fast_flap_expiry = flap_expiry
|
||||||
|
|
||||||
if bindport == None:
|
if bindport == None: raise SystemError(f"No TCP port configured for interface \"{name}\"")
|
||||||
raise SystemError(f"No TCP port configured for interface \"{name}\"")
|
else: self.bind_port = bindport
|
||||||
else:
|
|
||||||
self.bind_port = bindport
|
|
||||||
|
|
||||||
bind_address = None
|
bind_address = None
|
||||||
if device != None:
|
if device != None:
|
||||||
@@ -156,13 +169,34 @@ class BackboneInterface(Interface):
|
|||||||
else:
|
else:
|
||||||
raise SystemError("Insufficient parameters to create listener")
|
raise SystemError("Insufficient parameters to create listener")
|
||||||
|
|
||||||
|
__ic_burst_stats_throttle = 0.95
|
||||||
|
__last_ic_burst_count_check = 0
|
||||||
|
__last_ic_burst_count_state = 0
|
||||||
|
@property
|
||||||
|
def ic_burst_count(self):
|
||||||
|
if time.time() > self.__last_ic_burst_count_check + self.__ic_burst_stats_throttle:
|
||||||
|
self.__last_ic_burst_count_state = len([i.ic_burst_active for i in self.spawned_interfaces if i.ic_burst_active])
|
||||||
|
self.__last_ic_burst_count_check = time.time()
|
||||||
|
|
||||||
|
return self.__last_ic_burst_count_state
|
||||||
|
|
||||||
|
__last_ic_pr_burst_count_check = 0
|
||||||
|
__last_ic_pr_burst_count_state = 0
|
||||||
|
@property
|
||||||
|
def ic_pr_burst_count(self):
|
||||||
|
if time.time() > self.__last_ic_pr_burst_count_check + self.__ic_burst_stats_throttle:
|
||||||
|
self.__last_ic_pr_burst_count_state = len([i.ic_pr_burst_active for i in self.spawned_interfaces if i.ic_pr_burst_active])
|
||||||
|
self.__last_ic_pr_burst_count_check = time.time()
|
||||||
|
|
||||||
|
return self.__last_ic_pr_burst_count_state
|
||||||
|
|
||||||
__last_ic_burst_check = 0
|
__last_ic_burst_check = 0
|
||||||
__last_ic_burst_state = False
|
__last_ic_burst_state = False
|
||||||
@property
|
@property
|
||||||
def ic_burst_active(self):
|
def ic_burst_active(self):
|
||||||
if time.time() > self.__last_ic_burst_check + 2:
|
if time.time() > self.__last_ic_burst_check + self.__ic_burst_stats_throttle:
|
||||||
self.__last_ic_burst_state = any(i.ic_burst_active for i in self.spawned_interfaces)
|
self.__last_ic_burst_state = any(i.ic_burst_active for i in self.spawned_interfaces)
|
||||||
|
self.__last_ic_burst_check = time.time()
|
||||||
|
|
||||||
return self.__last_ic_burst_state
|
return self.__last_ic_burst_state
|
||||||
|
|
||||||
@@ -173,9 +207,10 @@ class BackboneInterface(Interface):
|
|||||||
__ic_burst_activated = 0
|
__ic_burst_activated = 0
|
||||||
@property
|
@property
|
||||||
def ic_burst_activated(self):
|
def ic_burst_activated(self):
|
||||||
if time.time() > self.__ic_burst_activated_check + 2:
|
if time.time() > self.__ic_burst_activated_check + self.__ic_burst_stats_throttle:
|
||||||
activated = [i.ic_burst_activated for i in self.spawned_interfaces if i.ic_burst_active]
|
activated = [i.ic_burst_activated for i in self.spawned_interfaces if i.ic_burst_active]
|
||||||
if activated: self.__ic_burst_activated = min(activated)
|
if activated: self.__ic_burst_activated = min(activated)
|
||||||
|
self.__ic_burst_activated_check = time.time()
|
||||||
|
|
||||||
return self.__ic_burst_activated
|
return self.__ic_burst_activated
|
||||||
|
|
||||||
@@ -187,8 +222,9 @@ class BackboneInterface(Interface):
|
|||||||
__last_ic_pr_burst_state = False
|
__last_ic_pr_burst_state = False
|
||||||
@property
|
@property
|
||||||
def ic_pr_burst_active(self):
|
def ic_pr_burst_active(self):
|
||||||
if time.time() > self.__last_ic_pr_burst_check + 2:
|
if time.time() > self.__last_ic_pr_burst_check + self.__ic_burst_stats_throttle:
|
||||||
self.__last_ic_pr_burst_state = any(i.ic_pr_burst_active for i in self.spawned_interfaces)
|
self.__last_ic_pr_burst_state = any(i.ic_pr_burst_active for i in self.spawned_interfaces)
|
||||||
|
self.__last_ic_pr_burst_check = time.time()
|
||||||
|
|
||||||
return self.__last_ic_pr_burst_state
|
return self.__last_ic_pr_burst_state
|
||||||
|
|
||||||
@@ -199,9 +235,10 @@ class BackboneInterface(Interface):
|
|||||||
__ic_pr_burst_activated = 0
|
__ic_pr_burst_activated = 0
|
||||||
@property
|
@property
|
||||||
def ic_pr_burst_activated(self):
|
def ic_pr_burst_activated(self):
|
||||||
if time.time() > self.__ic_pr_burst_activated_check + 2:
|
if time.time() > self.__ic_pr_burst_activated_check + self.__ic_burst_stats_throttle:
|
||||||
activated = [i.ic_pr_burst_activated for i in self.spawned_interfaces if i.ic_pr_burst_active]
|
activated = [i.ic_pr_burst_activated for i in self.spawned_interfaces if i.ic_pr_burst_active]
|
||||||
if activated: self.__ic_pr_burst_activated = min(activated)
|
if activated: self.__ic_pr_burst_activated = min(activated)
|
||||||
|
self.__ic_pr_burst_activated_check = time.time()
|
||||||
|
|
||||||
return self.__ic_pr_burst_activated
|
return self.__ic_pr_burst_activated
|
||||||
|
|
||||||
@@ -253,7 +290,7 @@ class BackboneInterface(Interface):
|
|||||||
|
|
||||||
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN)
|
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"An error occurred while registering EPOLL_IN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
|
RNS.log(f"An error occurred while registering EPOLLIN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def deregister_fileno(fileno):
|
def deregister_fileno(fileno):
|
||||||
@@ -263,7 +300,9 @@ class BackboneInterface(Interface):
|
|||||||
|
|
||||||
try: BackboneInterface.epoll.unregister(fileno)
|
try: BackboneInterface.epoll.unregister(fileno)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"An error occurred while deregistering file descriptor {fileno}: {e}", RNS.LOG_DEBUG)
|
if str(e).endswith("No such file or directory"): pass
|
||||||
|
elif str(e).endswith("Bad file descriptor"): pass
|
||||||
|
else: RNS.log(f"An error occurred while deregistering file descriptor {fileno}: {e}", RNS.LOG_DEBUG)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def deregister_listeners():
|
def deregister_listeners():
|
||||||
@@ -280,9 +319,11 @@ class BackboneInterface(Interface):
|
|||||||
if interface.socket:
|
if interface.socket:
|
||||||
fileno = interface.socket.fileno()
|
fileno = interface.socket.fileno()
|
||||||
if fileno in BackboneInterface.spawned_interface_filenos:
|
if fileno in BackboneInterface.spawned_interface_filenos:
|
||||||
try: BackboneInterface.epoll.modify(fileno, select.EPOLLOUT)
|
try: BackboneInterface.epoll.modify(fileno, select.EPOLLIN | select.EPOLLOUT)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"Error occurred on {interface} while modifying socket EPOLL state: {e}", RNS.LOG_WARNING)
|
if str(e).endswith("No such file or directory"): pass
|
||||||
|
elif str(e).endswith("Bad file descriptor"): pass
|
||||||
|
else: RNS.log(f"Error occurred on {interface} while modifying socket EPOLL state: {e}", RNS.LOG_WARNING)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -294,15 +335,15 @@ class BackboneInterface(Interface):
|
|||||||
BackboneInterface.ensure_epoll()
|
BackboneInterface.ensure_epoll()
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
events = BackboneInterface.epoll.poll(1)
|
|
||||||
for fileno, event in BackboneInterface.epoll.poll(1):
|
for fileno, event in BackboneInterface.epoll.poll(1):
|
||||||
if fileno in BackboneInterface.spawned_interface_filenos:
|
if fileno in BackboneInterface.spawned_interface_filenos:
|
||||||
spawned_interface = BackboneInterface.spawned_interface_filenos[fileno]
|
spawned_interface = BackboneInterface.spawned_interface_filenos[fileno]
|
||||||
client_socket = spawned_interface.socket
|
client_socket = spawned_interface.socket
|
||||||
if client_socket and fileno == client_socket.fileno() and (event & select.EPOLLIN):
|
socket_valid = client_socket and fileno == client_socket.fileno()
|
||||||
|
if socket_valid and (event & select.EPOLLIN):
|
||||||
try: received_bytes = client_socket.recv(spawned_interface.HW_MTU)
|
try: received_bytes = client_socket.recv(spawned_interface.HW_MTU)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"Error while reading from {spawned_interface}: {e}", RNS.LOG_DEBUG)
|
RNS.log(f"Error while reading from {spawned_interface}: {e}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
received_bytes = b""
|
received_bytes = b""
|
||||||
|
|
||||||
if len(received_bytes): spawned_interface.receive(received_bytes)
|
if len(received_bytes): spawned_interface.receive(received_bytes)
|
||||||
@@ -320,12 +361,19 @@ class BackboneInterface(Interface):
|
|||||||
except Exception as e: RNS.log(f"Error while removing spawned interface from {pif}: {e}", RNS.LOG_ERROR)
|
except Exception as e: RNS.log(f"Error while removing spawned interface from {pif}: {e}", RNS.LOG_ERROR)
|
||||||
|
|
||||||
spawned_interface.receive(received_bytes)
|
spawned_interface.receive(received_bytes)
|
||||||
|
|
||||||
elif client_socket and fileno == client_socket.fileno() and (event & select.EPOLLOUT):
|
socket_valid_after_read = socket_valid and fileno in BackboneInterface.spawned_interface_filenos
|
||||||
|
if socket_valid_after_read and (event & select.EPOLLOUT):
|
||||||
try: written = client_socket.send(spawned_interface.transmit_buffer)
|
try: written = client_socket.send(spawned_interface.transmit_buffer)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
written = 0
|
written = 0
|
||||||
if not spawned_interface.detached: RNS.log(f"Error while writing to {spawned_interface}: {e}", RNS.LOG_DEBUG)
|
if not spawned_interface.detached:
|
||||||
|
if RNS.sl(RNS.LOG_DEBUG):
|
||||||
|
if str(e).endswith("Connection timed out"): pass
|
||||||
|
elif str(e).endswith("Connection reset by peer"): pass
|
||||||
|
elif str(e).endswith("No route to host"): pass
|
||||||
|
elif str(e).endswith("Broken pipe"): pass
|
||||||
|
else: RNS.log(f"Error while writing to {spawned_interface}: {e}", RNS.LOG_DEBUG)
|
||||||
BackboneInterface.deregister_fileno(fileno)
|
BackboneInterface.deregister_fileno(fileno)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -352,7 +400,7 @@ class BackboneInterface(Interface):
|
|||||||
spawned_interface.txb += written
|
spawned_interface.txb += written
|
||||||
if spawned_interface.parent_interface: spawned_interface.parent_interface.txb += written
|
if spawned_interface.parent_interface: spawned_interface.parent_interface.txb += written
|
||||||
|
|
||||||
elif client_socket and fileno == client_socket.fileno() and event & (select.EPOLLHUP):
|
elif socket_valid_after_read and (event & select.EPOLLHUP):
|
||||||
BackboneInterface.deregister_fileno(fileno)
|
BackboneInterface.deregister_fileno(fileno)
|
||||||
try:
|
try:
|
||||||
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
|
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
|
||||||
@@ -379,7 +427,7 @@ class BackboneInterface(Interface):
|
|||||||
try: client_socket.close()
|
try: client_socket.close()
|
||||||
except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_WARNING)
|
except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_WARNING)
|
||||||
|
|
||||||
except:
|
except Exception as e:
|
||||||
RNS.log(f"Accepting socket failed for incoming connection: {e}", RNS.LOG_WARNING)
|
RNS.log(f"Accepting socket failed for incoming connection: {e}", RNS.LOG_WARNING)
|
||||||
try: client_socket.close()
|
try: client_socket.close()
|
||||||
except Exception as e: RNS.log(f"Error while closing socket for failed incoming socket accept: {e}", RNS.LOG_WARNING)
|
except Exception as e: RNS.log(f"Error while closing socket for failed incoming socket accept: {e}", RNS.LOG_WARNING)
|
||||||
@@ -399,8 +447,22 @@ class BackboneInterface(Interface):
|
|||||||
BackboneInterface.deregister_listeners()
|
BackboneInterface.deregister_listeners()
|
||||||
|
|
||||||
def incoming_connection(self, socket):
|
def incoming_connection(self, socket):
|
||||||
RNS.log("Accepting incoming connection", RNS.LOG_VERBOSE)
|
|
||||||
try:
|
try:
|
||||||
|
remote_ip = socket.getpeername()[0]
|
||||||
|
remote_port = str(socket.getpeername()[1])
|
||||||
|
if self.blocked_ip_count > 0:
|
||||||
|
with BackboneInterface.fast_flapping_lock:
|
||||||
|
if remote_ip in BackboneInterface.fast_flapping:
|
||||||
|
now = time.time()
|
||||||
|
ffe = BackboneInterface.fast_flapping[remote_ip]
|
||||||
|
started_flapping = ffe[0]
|
||||||
|
last_flap = ffe[1]
|
||||||
|
flaps = ffe[2]
|
||||||
|
if flaps > self.fast_flap_grace:
|
||||||
|
RNS.log(f"Ignoring incoming connection from fast-flapping IP {remote_ip}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
|
return False
|
||||||
|
|
||||||
|
RNS.log("Accepting incoming connection", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
spawned_configuration = {"name": "Client on "+self.name, "target_host": None, "target_port": None}
|
spawned_configuration = {"name": "Client on "+self.name, "target_host": None, "target_port": None}
|
||||||
spawned_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket)
|
spawned_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket)
|
||||||
spawned_interface.OUT = self.OUT
|
spawned_interface.OUT = self.OUT
|
||||||
@@ -421,8 +483,8 @@ class BackboneInterface(Interface):
|
|||||||
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
|
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
|
||||||
|
|
||||||
spawned_interface.socket = socket
|
spawned_interface.socket = socket
|
||||||
spawned_interface.target_ip = socket.getpeername()[0]
|
spawned_interface.target_ip = remote_ip
|
||||||
spawned_interface.target_port = str(socket.getpeername()[1])
|
spawned_interface.target_port = remote_port
|
||||||
spawned_interface.parent_interface = self
|
spawned_interface.parent_interface = self
|
||||||
spawned_interface.bitrate = self.bitrate
|
spawned_interface.bitrate = self.bitrate
|
||||||
spawned_interface.optimise_mtu()
|
spawned_interface.optimise_mtu()
|
||||||
@@ -432,18 +494,12 @@ class BackboneInterface(Interface):
|
|||||||
spawned_interface.ifac_netkey = self.ifac_netkey
|
spawned_interface.ifac_netkey = self.ifac_netkey
|
||||||
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
|
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
|
||||||
ifac_origin = b""
|
ifac_origin = b""
|
||||||
if spawned_interface.ifac_netname != None:
|
if spawned_interface.ifac_netname != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
|
||||||
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
|
if spawned_interface.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
|
||||||
if spawned_interface.ifac_netkey != None:
|
|
||||||
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
|
|
||||||
|
|
||||||
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
|
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
|
||||||
spawned_interface.ifac_key = RNS.Cryptography.hkdf(
|
spawned_interface.ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=ifac_origin_hash,
|
||||||
length=64,
|
salt=RNS.Reticulum.IFAC_SALT, context=None)
|
||||||
derive_from=ifac_origin_hash,
|
|
||||||
salt=RNS.Reticulum.IFAC_SALT,
|
|
||||||
context=None
|
|
||||||
)
|
|
||||||
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
|
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
|
||||||
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
|
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
|
||||||
|
|
||||||
@@ -451,13 +507,15 @@ class BackboneInterface(Interface):
|
|||||||
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
||||||
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
||||||
spawned_interface.mode = self.mode
|
spawned_interface.mode = self.mode
|
||||||
|
spawned_interface.gravity = self.gravity
|
||||||
spawned_interface.HW_MTU = self.HW_MTU
|
spawned_interface.HW_MTU = self.HW_MTU
|
||||||
spawned_interface.online = True
|
RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
|
|
||||||
RNS.Transport.add_interface(spawned_interface)
|
RNS.Transport.add_interface(spawned_interface)
|
||||||
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
|
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
|
||||||
self.spawned_interfaces.append(spawned_interface)
|
self.spawned_interfaces.append(spawned_interface)
|
||||||
BackboneInterface.add_client_socket(socket, spawned_interface)
|
BackboneInterface.add_client_socket(socket, spawned_interface)
|
||||||
|
spawned_interface.spawned_at = time.time()
|
||||||
|
spawned_interface.online = True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"An error occurred while accepting incoming connection on {self}: {e}", RNS.LOG_ERROR)
|
RNS.log(f"An error occurred while accepting incoming connection on {self}: {e}", RNS.LOG_ERROR)
|
||||||
@@ -465,17 +523,25 @@ class BackboneInterface(Interface):
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def received_announce(self, from_spawned=False):
|
def received_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ia_freq_deque.append(time.time())
|
||||||
|
self.arxb += size
|
||||||
|
|
||||||
def sent_announce(self, from_spawned=False):
|
def sent_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.oa_freq_deque.append(time.time())
|
||||||
|
self.atxb += size
|
||||||
|
|
||||||
def received_path_request(self, from_spawned=False):
|
def received_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ip_freq_deque.append(time.time())
|
||||||
|
self.prxb += size
|
||||||
|
|
||||||
def sent_path_request(self, from_spawned=False):
|
def sent_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.op_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.op_freq_deque.append(time.time())
|
||||||
|
self.ptxb += size
|
||||||
|
|
||||||
def process_outgoing(self, data):
|
def process_outgoing(self, data):
|
||||||
pass
|
pass
|
||||||
@@ -491,15 +557,43 @@ class BackboneInterface(Interface):
|
|||||||
if callable(listener_socket.shutdown):
|
if callable(listener_socket.shutdown):
|
||||||
try: listener_socket.shutdown(socket.SHUT_RDWR)
|
try: listener_socket.shutdown(socket.SHUT_RDWR)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if str(e).endswith("Transport endpoint is not connected"): pass
|
if str(e).endswith("Transport endpoint is not connected"): pass
|
||||||
|
elif str(e).endswith("Bad file descriptor"): pass
|
||||||
else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR)
|
else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
def __str__(self):
|
@property
|
||||||
if ":" in self.bind_ip:
|
def blocked_ip_list(self):
|
||||||
ip_str = f"[{self.bind_ip}]"
|
if not self.block_fast_flapping: return []
|
||||||
else:
|
else: return list(self.fast_flapping.keys())
|
||||||
ip_str = f"{self.bind_ip}"
|
|
||||||
|
|
||||||
|
@property
|
||||||
|
def blocked_ip_count(self):
|
||||||
|
if not self.block_fast_flapping: return 0
|
||||||
|
else:
|
||||||
|
count = 0
|
||||||
|
expired = []
|
||||||
|
now = time.time()
|
||||||
|
with BackboneInterface.fast_flapping_lock:
|
||||||
|
for remote_ip in BackboneInterface.fast_flapping:
|
||||||
|
ffe = BackboneInterface.fast_flapping[remote_ip]
|
||||||
|
started_flapping = ffe[0]
|
||||||
|
last_flap = ffe[1]
|
||||||
|
flaps = ffe[2]
|
||||||
|
if now - last_flap > self.fast_flap_expiry: expired.append(remote_ip)
|
||||||
|
elif flaps > self.fast_flap_grace: count += 1
|
||||||
|
|
||||||
|
for remote_ip in expired:
|
||||||
|
if remote_ip in BackboneInterface.fast_flapping:
|
||||||
|
try:
|
||||||
|
BackboneInterface.fast_flapping.pop(remote_ip)
|
||||||
|
RNS.log(f"Fast-flapping block expired for {remote_ip}", RNS.LOG_DEBUG)
|
||||||
|
except Exception as e: RNS.log(f"Error while expiring fast-flapping block for {remote_ip}: {e}", RNS.LOG_ERROR)
|
||||||
|
|
||||||
|
return count
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
if ":" in self.bind_ip: ip_str = f"[{self.bind_ip}]"
|
||||||
|
else: ip_str = f"{self.bind_ip}"
|
||||||
return "BackboneInterface["+self.name+"/"+ip_str+":"+str(self.bind_port)+"]"
|
return "BackboneInterface["+self.name+"/"+ip_str+":"+str(self.bind_port)+"]"
|
||||||
|
|
||||||
|
|
||||||
@@ -608,7 +702,8 @@ class BackboneClientInterface(Interface):
|
|||||||
try:
|
try:
|
||||||
if self.socket != None: self.socket.shutdown(socket.SHUT_RDWR)
|
if self.socket != None: self.socket.shutdown(socket.SHUT_RDWR)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if str(e).endswith("Transport endpoint is not connected"): pass
|
if str(e).endswith("Transport endpoint is not connected"): pass
|
||||||
|
elif str(e).endswith("Bad file descriptor"): pass
|
||||||
else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR)
|
else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -710,6 +805,14 @@ class BackboneClientInterface(Interface):
|
|||||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
self.teardown()
|
self.teardown()
|
||||||
|
|
||||||
|
def check_frame_len(self, frame_len):
|
||||||
|
if frame_len <= RNS.Reticulum.HEADER_MINSIZE: return False
|
||||||
|
elif frame_len > self.HW_MTU + (self.ifac_size or 0): return False
|
||||||
|
else: return True
|
||||||
|
|
||||||
|
def invalid_frame(self, frame_len):
|
||||||
|
RNS.log(f"Invalid HDLC frame of {RNS.prettysize(frame_len)} received on {self}, dropping frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
def receive(self, data_in):
|
def receive(self, data_in):
|
||||||
try:
|
try:
|
||||||
if len(data_in) > 0:
|
if len(data_in) > 0:
|
||||||
@@ -723,12 +826,18 @@ class BackboneClientInterface(Interface):
|
|||||||
frame = self.frame_buffer[frame_start+1:frame_end]
|
frame = self.frame_buffer[frame_start+1:frame_end]
|
||||||
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
|
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
|
||||||
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
|
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
|
||||||
if len(frame) > RNS.Reticulum.HEADER_MINSIZE:
|
frame_len = len(frame)
|
||||||
self.process_incoming(frame)
|
if frame_len != 0:
|
||||||
|
if self.check_frame_len(frame_len): self.process_incoming(frame)
|
||||||
|
else: self.invalid_frame(len(frame))
|
||||||
|
|
||||||
self.frame_buffer = self.frame_buffer[frame_end:]
|
self.frame_buffer = self.frame_buffer[frame_end:]
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
if len(self.frame_buffer) > self.HW_MTU*2: self.frame_buffer = b""
|
||||||
flags_remaining = False
|
flags_remaining = False
|
||||||
else:
|
else:
|
||||||
|
self.frame_buffer = b""
|
||||||
flags_remaining = False
|
flags_remaining = False
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -738,7 +847,7 @@ class BackboneClientInterface(Interface):
|
|||||||
def job(): self.reconnect()
|
def job(): self.reconnect()
|
||||||
threading.Thread(target=job, daemon=True).start()
|
threading.Thread(target=job, daemon=True).start()
|
||||||
else:
|
else:
|
||||||
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_DEBUG)
|
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
self.teardown()
|
self.teardown()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -755,11 +864,29 @@ class BackboneClientInterface(Interface):
|
|||||||
def teardown(self):
|
def teardown(self):
|
||||||
if self.initiator and not self.detached:
|
if self.initiator and not self.detached:
|
||||||
RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR)
|
RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR)
|
||||||
if RNS.Reticulum.panic_on_interface_error:
|
if RNS.Reticulum.panic_on_interface_error: RNS.panic()
|
||||||
RNS.panic()
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE)
|
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
|
||||||
|
if self.parent_interface and self.parent_interface.block_fast_flapping and hasattr(self, "spawned_at"):
|
||||||
|
connected_time = time.time() - self.spawned_at
|
||||||
|
if connected_time < self.parent_interface.fast_flap_threshold:
|
||||||
|
try:
|
||||||
|
now = time.time()
|
||||||
|
remote_id = f"{self.target_ip}"
|
||||||
|
with BackboneInterface.fast_flapping_lock:
|
||||||
|
if remote_id in BackboneInterface.fast_flapping: ffe = BackboneInterface.fast_flapping[remote_id]
|
||||||
|
else: ffe = [now, now, 0]
|
||||||
|
ffe[1] = now
|
||||||
|
ffe[2] += 1
|
||||||
|
with BackboneInterface.fast_flapping_lock: BackboneInterface.fast_flapping[remote_id] = ffe
|
||||||
|
|
||||||
|
dt = now-ffe[0]; fff = ffe[2]/dt if dt > 0 else None
|
||||||
|
freq_str = f" at {RNS.prettyfrequency(fff)}" if fff else ""
|
||||||
|
RNS.log(f"{self} is fast flapping{freq_str}, connection time was {RNS.prettytime(connected_time)}, {ffe[2]} fast flaps", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
if ffe[2] > self.parent_interface.fast_flap_grace: RNS.log(f"Ignoring further connections from {remote_id} due to fast-flapping", RNS.LOG_WARNING)
|
||||||
|
|
||||||
|
except Exception as e: RNS.log(f"Error while updating fast-flapping interface statistics: {e}", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.online = False
|
self.online = False
|
||||||
self.OUT = False
|
self.OUT = False
|
||||||
|
|||||||
+108
-232
@@ -88,8 +88,7 @@ class I2PController:
|
|||||||
self.ready = False
|
self.ready = False
|
||||||
|
|
||||||
self.storagepath = rns_storagepath+"/i2p"
|
self.storagepath = rns_storagepath+"/i2p"
|
||||||
if not os.path.isdir(self.storagepath):
|
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
|
||||||
os.makedirs(self.storagepath)
|
|
||||||
|
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
@@ -110,28 +109,22 @@ class I2PController:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.ready = False
|
self.ready = False
|
||||||
RNS.log("Exception on event loop for "+str(self)+": "+str(e), RNS.LOG_ERROR)
|
RNS.log("Exception on event loop for "+str(self)+": "+str(e), RNS.LOG_ERROR)
|
||||||
finally:
|
finally: self.loop.close()
|
||||||
self.loop.close()
|
|
||||||
|
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
for i2ptunnel in self.i2plib_tunnels:
|
for i2ptunnel in self.i2plib_tunnels:
|
||||||
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop):
|
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop): i2ptunnel.stop()
|
||||||
i2ptunnel.stop()
|
|
||||||
|
|
||||||
if hasattr(asyncio.Task, "all_tasks") and callable(asyncio.Task.all_tasks):
|
if hasattr(asyncio.Task, "all_tasks") and callable(asyncio.Task.all_tasks):
|
||||||
for task in asyncio.Task.all_tasks(loop=self.loop):
|
for task in asyncio.Task.all_tasks(loop=self.loop): task.cancel()
|
||||||
task.cancel()
|
|
||||||
|
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
|
|
||||||
self.loop.stop()
|
self.loop.stop()
|
||||||
|
|
||||||
|
|
||||||
def get_free_port(self):
|
def get_free_port(self):
|
||||||
return self.i2plib.utils.get_free_port()
|
return self.i2plib.utils.get_free_port()
|
||||||
|
|
||||||
|
|
||||||
def stop_tunnel(self, i2ptunnel):
|
def stop_tunnel(self, i2ptunnel):
|
||||||
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop):
|
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop):
|
||||||
i2ptunnel.stop()
|
i2ptunnel.stop()
|
||||||
@@ -159,10 +152,9 @@ class I2PController:
|
|||||||
tn = self.i2plib_tunnels[i2p_destination]
|
tn = self.i2plib_tunnels[i2p_destination]
|
||||||
if tn != None and hasattr(tn, "status"):
|
if tn != None and hasattr(tn, "status"):
|
||||||
|
|
||||||
RNS.log("Waiting for status from I2P control process", RNS.LOG_EXTREME)
|
RNS.log("Waiting for status from I2P control process", RNS.LOG_DEBUG)
|
||||||
while not tn.status["setup_ran"]:
|
while not tn.status["setup_ran"]: time.sleep(0.1)
|
||||||
time.sleep(0.1)
|
RNS.log("Got status from I2P control process", RNS.LOG_DEBUG)
|
||||||
RNS.log("Got status from I2P control process", RNS.LOG_EXTREME)
|
|
||||||
|
|
||||||
if tn.status["setup_failed"]:
|
if tn.status["setup_failed"]:
|
||||||
self.stop_tunnel(tn)
|
self.stop_tunnel(tn)
|
||||||
@@ -172,29 +164,19 @@ class I2PController:
|
|||||||
if owner.socket != None:
|
if owner.socket != None:
|
||||||
if hasattr(owner.socket, "close"):
|
if hasattr(owner.socket, "close"):
|
||||||
if callable(owner.socket.close):
|
if callable(owner.socket.close):
|
||||||
try:
|
try: owner.socket.shutdown(socket.SHUT_RDWR)
|
||||||
owner.socket.shutdown(socket.SHUT_RDWR)
|
except Exception as e: RNS.log("Error while shutting down socket for "+str(owner)+": "+str(e))
|
||||||
except Exception as e:
|
try: owner.socket.close()
|
||||||
RNS.log("Error while shutting down socket for "+str(owner)+": "+str(e))
|
except Exception as e: RNS.log("Error while closing socket for "+str(owner)+": "+str(e))
|
||||||
|
|
||||||
try:
|
|
||||||
owner.socket.close()
|
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while closing socket for "+str(owner)+": "+str(e))
|
|
||||||
self.client_tunnels[i2p_destination] = True
|
self.client_tunnels[i2p_destination] = True
|
||||||
owner.awaiting_i2p_tunnel = False
|
owner.awaiting_i2p_tunnel = False
|
||||||
|
|
||||||
RNS.log(str(owner)+" tunnel setup complete", RNS.LOG_VERBOSE)
|
RNS.log(str(owner)+" tunnel setup complete", RNS.LOG_VERBOSE)
|
||||||
|
|
||||||
else:
|
else: raise IOError("Got no status response from SAM API")
|
||||||
raise IOError("Got no status response from SAM API")
|
|
||||||
|
|
||||||
except ConnectionRefusedError as e:
|
|
||||||
raise e
|
|
||||||
|
|
||||||
except ConnectionAbortedError as e:
|
|
||||||
raise e
|
|
||||||
|
|
||||||
|
except ConnectionRefusedError as e: raise e
|
||||||
|
except ConnectionAbortedError as e: raise e
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("Unexpected error type from I2P SAM: "+str(e), RNS.LOG_ERROR)
|
RNS.log("Unexpected error type from I2P SAM: "+str(e), RNS.LOG_ERROR)
|
||||||
raise e
|
raise e
|
||||||
@@ -206,54 +188,33 @@ class I2PController:
|
|||||||
|
|
||||||
if i2ptunnel.status["setup_ran"] == False:
|
if i2ptunnel.status["setup_ran"] == False:
|
||||||
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
|
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
elif i2p_exception != None:
|
elif i2p_exception != None:
|
||||||
RNS.log("An error ocurred while setting up I2P tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
|
RNS.log("An error ocurred while setting up I2P tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
|
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer):
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest): RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR)
|
||||||
RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId): RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR)
|
||||||
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId): RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest):
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey): RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
|
||||||
RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR)
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound): RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound): RNS.log("The I2P daemon could not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId):
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError): RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
|
||||||
RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR)
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout): RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
|
else: RNS.log(f"Unspecified I2P daemon error: {i2p_exception}", RNS.LOG_ERROR)
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId):
|
|
||||||
RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey):
|
|
||||||
RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound):
|
|
||||||
RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound):
|
|
||||||
RNS.log("The I2P daemon mould not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError):
|
|
||||||
RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout):
|
|
||||||
RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
|
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
elif i2ptunnel.status["setup_failed"] == True:
|
elif i2ptunnel.status["setup_failed"] == True:
|
||||||
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
|
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
else:
|
else:
|
||||||
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
|
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -274,10 +235,8 @@ class I2PController:
|
|||||||
i2p_keyfile_nf = self.storagepath+"/"+RNS.hexrep(i2p_dest_hash_nf, delimit=False)+".i2p"
|
i2p_keyfile_nf = self.storagepath+"/"+RNS.hexrep(i2p_dest_hash_nf, delimit=False)+".i2p"
|
||||||
|
|
||||||
# Use old format if a key is already present
|
# Use old format if a key is already present
|
||||||
if os.path.isfile(i2p_keyfile_of):
|
if os.path.isfile(i2p_keyfile_of): i2p_keyfile = i2p_keyfile_of
|
||||||
i2p_keyfile = i2p_keyfile_of
|
else: i2p_keyfile = i2p_keyfile_nf
|
||||||
else:
|
|
||||||
i2p_keyfile = i2p_keyfile_nf
|
|
||||||
|
|
||||||
i2p_dest = None
|
i2p_dest = None
|
||||||
if not os.path.isfile(i2p_keyfile):
|
if not os.path.isfile(i2p_keyfile):
|
||||||
@@ -312,8 +271,7 @@ class I2PController:
|
|||||||
asyncio.run_coroutine_threadsafe(tunnel_up(), self.loop).result()
|
asyncio.run_coroutine_threadsafe(tunnel_up(), self.loop).result()
|
||||||
self.server_tunnels[i2p_b32] = True
|
self.server_tunnels[i2p_b32] = True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e: raise e
|
||||||
raise e
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
i2ptunnel = self.i2plib_tunnels[i2p_b32]
|
i2ptunnel = self.i2plib_tunnels[i2p_b32]
|
||||||
@@ -322,66 +280,45 @@ class I2PController:
|
|||||||
|
|
||||||
if i2ptunnel.status["setup_ran"] == False:
|
if i2ptunnel.status["setup_ran"] == False:
|
||||||
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
|
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
elif i2p_exception != None:
|
elif i2p_exception != None:
|
||||||
RNS.log("An error ocurred while setting up I2P tunnel", RNS.LOG_ERROR)
|
RNS.log("An error ocurred while setting up I2P tunnel", RNS.LOG_ERROR)
|
||||||
|
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer):
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest): RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR)
|
||||||
RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId): RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR)
|
||||||
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId): RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest):
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey): RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
|
||||||
RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR)
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound): RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound): RNS.log("The I2P daemon could not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId):
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError): RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
|
||||||
RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR)
|
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout): RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
|
||||||
|
else: RNS.log(f"Unspecified I2P daemon error: {i2p_exception}", RNS.LOG_ERROR)
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId):
|
|
||||||
RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey):
|
|
||||||
RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound):
|
|
||||||
RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound):
|
|
||||||
RNS.log("The I2P daemon mould not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError):
|
|
||||||
RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout):
|
|
||||||
RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
|
|
||||||
|
|
||||||
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
|
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
elif i2ptunnel.status["setup_failed"] == True:
|
elif i2ptunnel.status["setup_failed"] == True:
|
||||||
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
|
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
else:
|
else:
|
||||||
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
|
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.stop_tunnel(i2ptunnel)
|
self.stop_tunnel(i2ptunnel)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|
||||||
def get_loop(self):
|
def get_loop(self): return asyncio.get_event_loop()
|
||||||
return asyncio.get_event_loop()
|
|
||||||
|
|
||||||
|
|
||||||
class ThreadingI2PServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
|
class ThreadingI2PServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class I2PInterfacePeer(Interface):
|
class I2PInterfacePeer(Interface):
|
||||||
RECONNECT_WAIT = 15
|
RECONNECT_WAIT = 15
|
||||||
RECONNECT_MAX_TRIES = None
|
RECONNECT_MAX_TRIES = None
|
||||||
@@ -431,18 +368,11 @@ class I2PInterfacePeer(Interface):
|
|||||||
self.ifac_netkey = self.parent_interface.ifac_netkey
|
self.ifac_netkey = self.parent_interface.ifac_netkey
|
||||||
if self.ifac_netname != None or self.ifac_netkey != None:
|
if self.ifac_netname != None or self.ifac_netkey != None:
|
||||||
ifac_origin = b""
|
ifac_origin = b""
|
||||||
if self.ifac_netname != None:
|
if self.ifac_netname != None: ifac_origin += RNS.Identity.full_hash(self.ifac_netname.encode("utf-8"))
|
||||||
ifac_origin += RNS.Identity.full_hash(self.ifac_netname.encode("utf-8"))
|
if self.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(self.ifac_netkey.encode("utf-8"))
|
||||||
if self.ifac_netkey != None:
|
|
||||||
ifac_origin += RNS.Identity.full_hash(self.ifac_netkey.encode("utf-8"))
|
|
||||||
|
|
||||||
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
|
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
|
||||||
self.ifac_key = RNS.Cryptography.hkdf(
|
self.ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=ifac_origin_hash, salt=RNS.Reticulum.IFAC_SALT, context=None)
|
||||||
length=64,
|
|
||||||
derive_from=ifac_origin_hash,
|
|
||||||
salt=RNS.Reticulum.IFAC_SALT,
|
|
||||||
context=None
|
|
||||||
)
|
|
||||||
self.ifac_identity = RNS.Identity.from_bytes(self.ifac_key)
|
self.ifac_identity = RNS.Identity.from_bytes(self.ifac_key)
|
||||||
self.ifac_signature = self.ifac_identity.sign(RNS.Identity.full_hash(self.ifac_key))
|
self.ifac_signature = self.ifac_identity.sign(RNS.Identity.full_hash(self.ifac_key))
|
||||||
|
|
||||||
@@ -450,10 +380,8 @@ class I2PInterfacePeer(Interface):
|
|||||||
self.announce_rate_grace = None
|
self.announce_rate_grace = None
|
||||||
self.announce_rate_penalty = None
|
self.announce_rate_penalty = None
|
||||||
|
|
||||||
if max_reconnect_tries == None:
|
if max_reconnect_tries == None: self.max_reconnect_tries = I2PInterfacePeer.RECONNECT_MAX_TRIES
|
||||||
self.max_reconnect_tries = I2PInterfacePeer.RECONNECT_MAX_TRIES
|
else: self.max_reconnect_tries = max_reconnect_tries
|
||||||
else:
|
|
||||||
self.max_reconnect_tries = max_reconnect_tries
|
|
||||||
|
|
||||||
if connected_socket != None:
|
if connected_socket != None:
|
||||||
self.receives = True
|
self.receives = True
|
||||||
@@ -461,15 +389,12 @@ class I2PInterfacePeer(Interface):
|
|||||||
self.target_port = None
|
self.target_port = None
|
||||||
self.socket = connected_socket
|
self.socket = connected_socket
|
||||||
|
|
||||||
if platform.system() == "Linux":
|
if platform.system() == "Linux": self.set_timeouts_linux()
|
||||||
self.set_timeouts_linux()
|
elif platform.system() == "Darwin": self.set_timeouts_osx()
|
||||||
elif platform.system() == "Darwin":
|
|
||||||
self.set_timeouts_osx()
|
|
||||||
|
|
||||||
elif target_i2p_dest != None:
|
elif target_i2p_dest != None:
|
||||||
self.receives = True
|
self.receives = True
|
||||||
self.initiator = True
|
self.initiator = True
|
||||||
|
|
||||||
self.bind_ip = "127.0.0.1"
|
self.bind_ip = "127.0.0.1"
|
||||||
|
|
||||||
self.awaiting_i2p_tunnel = True
|
self.awaiting_i2p_tunnel = True
|
||||||
@@ -497,12 +422,10 @@ class I2PInterfacePeer(Interface):
|
|||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
def wait_job():
|
def wait_job():
|
||||||
while self.awaiting_i2p_tunnel:
|
while self.awaiting_i2p_tunnel: time.sleep(0.25)
|
||||||
time.sleep(0.25)
|
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
if not self.kiss_framing:
|
if not self.kiss_framing: self.wants_tunnel = True
|
||||||
self.wants_tunnel = True
|
|
||||||
|
|
||||||
if not self.connect(initial=True):
|
if not self.connect(initial=True):
|
||||||
thread = threading.Thread(target=self.reconnect)
|
thread = threading.Thread(target=self.reconnect)
|
||||||
@@ -517,7 +440,6 @@ class I2PInterfacePeer(Interface):
|
|||||||
thread.daemon = True
|
thread.daemon = True
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
|
|
||||||
def set_timeouts_linux(self):
|
def set_timeouts_linux(self):
|
||||||
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, int(I2PInterfacePeer.I2P_USER_TIMEOUT * 1000))
|
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, int(I2PInterfacePeer.I2P_USER_TIMEOUT * 1000))
|
||||||
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
||||||
@@ -526,10 +448,8 @@ class I2PInterfacePeer(Interface):
|
|||||||
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, int(I2PInterfacePeer.I2P_PROBES))
|
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, int(I2PInterfacePeer.I2P_PROBES))
|
||||||
|
|
||||||
def set_timeouts_osx(self):
|
def set_timeouts_osx(self):
|
||||||
if hasattr(socket, "TCP_KEEPALIVE"):
|
if hasattr(socket, "TCP_KEEPALIVE"): TCP_KEEPIDLE = socket.TCP_KEEPALIVE
|
||||||
TCP_KEEPIDLE = socket.TCP_KEEPALIVE
|
else: TCP_KEEPIDLE = 0x10
|
||||||
else:
|
|
||||||
TCP_KEEPIDLE = 0x10
|
|
||||||
|
|
||||||
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
||||||
self.socket.setsockopt(socket.IPPROTO_TCP, TCP_KEEPIDLE, int(I2PInterfacePeer.I2P_PROBE_AFTER))
|
self.socket.setsockopt(socket.IPPROTO_TCP, TCP_KEEPIDLE, int(I2PInterfacePeer.I2P_PROBE_AFTER))
|
||||||
@@ -537,16 +457,12 @@ class I2PInterfacePeer(Interface):
|
|||||||
def shutdown_socket(self, target_socket):
|
def shutdown_socket(self, target_socket):
|
||||||
if callable(target_socket.close):
|
if callable(target_socket.close):
|
||||||
try:
|
try:
|
||||||
if socket != None:
|
if socket != None: target_socket.shutdown(socket.SHUT_RDWR)
|
||||||
target_socket.shutdown(socket.SHUT_RDWR)
|
except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if socket != None:
|
if socket != None: target_socket.close()
|
||||||
target_socket.close()
|
except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
|
|
||||||
|
|
||||||
def detach(self):
|
def detach(self):
|
||||||
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
|
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
|
||||||
@@ -555,15 +471,11 @@ class I2PInterfacePeer(Interface):
|
|||||||
if callable(self.socket.close):
|
if callable(self.socket.close):
|
||||||
self.detached = True
|
self.detached = True
|
||||||
|
|
||||||
try:
|
try: self.socket.shutdown(socket.SHUT_RDWR)
|
||||||
self.socket.shutdown(socket.SHUT_RDWR)
|
except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
|
|
||||||
|
|
||||||
try:
|
try: self.socket.close()
|
||||||
self.socket.close()
|
except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
|
|
||||||
|
|
||||||
self.socket = None
|
self.socket = None
|
||||||
|
|
||||||
@@ -578,23 +490,17 @@ class I2PInterfacePeer(Interface):
|
|||||||
if not self.awaiting_i2p_tunnel:
|
if not self.awaiting_i2p_tunnel:
|
||||||
RNS.log("Initial connection for "+str(self)+" could not be established: "+str(e), RNS.LOG_ERROR)
|
RNS.log("Initial connection for "+str(self)+" could not be established: "+str(e), RNS.LOG_ERROR)
|
||||||
RNS.log("Leaving unconnected and retrying connection in "+str(I2PInterfacePeer.RECONNECT_WAIT)+" seconds.", RNS.LOG_ERROR)
|
RNS.log("Leaving unconnected and retrying connection in "+str(I2PInterfacePeer.RECONNECT_WAIT)+" seconds.", RNS.LOG_ERROR)
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
else: raise e
|
||||||
else:
|
|
||||||
raise e
|
|
||||||
|
|
||||||
if platform.system() == "Linux":
|
if platform.system() == "Linux": self.set_timeouts_linux()
|
||||||
self.set_timeouts_linux()
|
elif platform.system() == "Darwin": self.set_timeouts_osx()
|
||||||
elif platform.system() == "Darwin":
|
|
||||||
self.set_timeouts_osx()
|
|
||||||
|
|
||||||
self.online = True
|
self.online = True
|
||||||
self.writing = False
|
self.writing = False
|
||||||
self.never_connected = False
|
self.never_connected = False
|
||||||
|
|
||||||
if not self.kiss_framing and self.wants_tunnel:
|
if not self.kiss_framing and self.wants_tunnel: RNS.Transport.synthesize_tunnel(self)
|
||||||
RNS.Transport.synthesize_tunnel(self)
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -612,14 +518,10 @@ class I2PInterfacePeer(Interface):
|
|||||||
self.teardown()
|
self.teardown()
|
||||||
break
|
break
|
||||||
|
|
||||||
try:
|
try: self.connect()
|
||||||
self.connect()
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if not self.awaiting_i2p_tunnel:
|
if not self.awaiting_i2p_tunnel: RNS.log("Connection attempt for "+str(self)+" failed: "+str(e), RNS.LOG_DEBUG)
|
||||||
RNS.log("Connection attempt for "+str(self)+" failed: "+str(e), RNS.LOG_DEBUG)
|
else: RNS.log(str(self)+" still waiting for I2P tunnel to appear", RNS.LOG_VERBOSE)
|
||||||
else:
|
|
||||||
RNS.log(str(self)+" still waiting for I2P tunnel to appear", RNS.LOG_VERBOSE)
|
|
||||||
|
|
||||||
if not self.never_connected:
|
if not self.never_connected:
|
||||||
RNS.log(str(self)+" Re-established connection via I2P tunnel", RNS.LOG_INFO)
|
RNS.log(str(self)+" Re-established connection via I2P tunnel", RNS.LOG_INFO)
|
||||||
@@ -628,8 +530,7 @@ class I2PInterfacePeer(Interface):
|
|||||||
thread = threading.Thread(target=self.read_loop)
|
thread = threading.Thread(target=self.read_loop)
|
||||||
thread.daemon = True
|
thread.daemon = True
|
||||||
thread.start()
|
thread.start()
|
||||||
if not self.kiss_framing:
|
if not self.kiss_framing: RNS.Transport.synthesize_tunnel(self)
|
||||||
RNS.Transport.synthesize_tunnel(self)
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
RNS.log("Attempt to reconnect on a non-initiator I2P interface. This should not happen.", RNS.LOG_ERROR)
|
RNS.log("Attempt to reconnect on a non-initiator I2P interface. This should not happen.", RNS.LOG_ERROR)
|
||||||
@@ -639,29 +540,24 @@ class I2PInterfacePeer(Interface):
|
|||||||
self.rxb += len(data)
|
self.rxb += len(data)
|
||||||
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
|
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
|
||||||
self.parent_interface.rxb += len(data)
|
self.parent_interface.rxb += len(data)
|
||||||
|
|
||||||
self.owner.inbound(data, self)
|
self.owner.inbound(data, self)
|
||||||
|
|
||||||
def process_outgoing(self, data):
|
def process_outgoing(self, data):
|
||||||
if self.online:
|
if self.online:
|
||||||
while self.writing:
|
while self.writing: time.sleep(0.001)
|
||||||
time.sleep(0.001)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.writing = True
|
self.writing = True
|
||||||
|
|
||||||
if self.kiss_framing:
|
if self.kiss_framing: data = bytes([KISS.FEND])+bytes([KISS.CMD_DATA])+KISS.escape(data)+bytes([KISS.FEND])
|
||||||
data = bytes([KISS.FEND])+bytes([KISS.CMD_DATA])+KISS.escape(data)+bytes([KISS.FEND])
|
else: data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
|
||||||
else:
|
|
||||||
data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
|
|
||||||
|
|
||||||
self.socket.sendall(data)
|
self.socket.sendall(data)
|
||||||
self.writing = False
|
self.writing = False
|
||||||
self.txb += len(data)
|
self.txb += len(data)
|
||||||
self.last_write = time.time()
|
self.last_write = time.time()
|
||||||
|
|
||||||
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
|
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count: self.parent_interface.txb += len(data)
|
||||||
self.parent_interface.txb += len(data)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
|
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
|
||||||
@@ -670,8 +566,7 @@ class I2PInterfacePeer(Interface):
|
|||||||
|
|
||||||
|
|
||||||
def read_watchdog(self):
|
def read_watchdog(self):
|
||||||
while self.wd_reset:
|
while self.wd_reset: time.sleep(0.25)
|
||||||
time.sleep(0.25)
|
|
||||||
|
|
||||||
should_run = True
|
should_run = True
|
||||||
try:
|
try:
|
||||||
@@ -679,17 +574,13 @@ class I2PInterfacePeer(Interface):
|
|||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
if (time.time()-self.last_read > I2PInterfacePeer.I2P_PROBE_AFTER*2):
|
if (time.time()-self.last_read > I2PInterfacePeer.I2P_PROBE_AFTER*2):
|
||||||
if self.i2p_tunnel_state != I2PInterfacePeer.TUNNEL_STATE_STALE:
|
if self.i2p_tunnel_state != I2PInterfacePeer.TUNNEL_STATE_STALE: RNS.log("I2P tunnel became unresponsive", RNS.LOG_DEBUG)
|
||||||
RNS.log("I2P tunnel became unresponsive", RNS.LOG_DEBUG)
|
|
||||||
|
|
||||||
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_STALE
|
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_STALE
|
||||||
else:
|
else: self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_ACTIVE
|
||||||
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_ACTIVE
|
|
||||||
|
|
||||||
if (time.time()-self.last_write > I2PInterfacePeer.I2P_PROBE_AFTER*1):
|
if (time.time()-self.last_write > I2PInterfacePeer.I2P_PROBE_AFTER*1):
|
||||||
try:
|
try:
|
||||||
if self.socket != None:
|
if self.socket != None: self.socket.sendall(bytes([HDLC.FLAG, HDLC.FLAG]))
|
||||||
self.socket.sendall(bytes([HDLC.FLAG, HDLC.FLAG]))
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("An error ocurred while sending I2P keepalive. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
RNS.log("An error ocurred while sending I2P keepalive. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
self.shutdown_socket(self.socket)
|
self.shutdown_socket(self.socket)
|
||||||
@@ -698,22 +589,17 @@ class I2PInterfacePeer(Interface):
|
|||||||
if (time.time()-self.last_read > I2PInterfacePeer.I2P_READ_TIMEOUT):
|
if (time.time()-self.last_read > I2PInterfacePeer.I2P_READ_TIMEOUT):
|
||||||
RNS.log("I2P socket is unresponsive, restarting...", RNS.LOG_WARNING)
|
RNS.log("I2P socket is unresponsive, restarting...", RNS.LOG_WARNING)
|
||||||
if self.socket != None:
|
if self.socket != None:
|
||||||
try:
|
try: self.socket.shutdown(socket.SHUT_RDWR)
|
||||||
self.socket.shutdown(socket.SHUT_RDWR)
|
except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
|
|
||||||
|
|
||||||
try:
|
try: self.socket.close()
|
||||||
self.socket.close()
|
except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
|
||||||
except Exception as e:
|
|
||||||
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
|
|
||||||
|
|
||||||
should_run = False
|
should_run = False
|
||||||
|
|
||||||
self.wd_reset = False
|
self.wd_reset = False
|
||||||
|
|
||||||
finally:
|
finally: self.wd_reset = False
|
||||||
self.wd_reset = False
|
|
||||||
|
|
||||||
def read_loop(self):
|
def read_loop(self):
|
||||||
try:
|
try:
|
||||||
@@ -784,7 +670,6 @@ class I2PInterfacePeer(Interface):
|
|||||||
data_buffer = data_buffer+bytes([byte])
|
data_buffer = data_buffer+bytes([byte])
|
||||||
else:
|
else:
|
||||||
self.online = False
|
self.online = False
|
||||||
|
|
||||||
self.wd_reset = True
|
self.wd_reset = True
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
self.wd_reset = False
|
self.wd_reset = False
|
||||||
@@ -806,15 +691,12 @@ class I2PInterfacePeer(Interface):
|
|||||||
if self.initiator:
|
if self.initiator:
|
||||||
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
|
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
|
||||||
self.reconnect()
|
self.reconnect()
|
||||||
else:
|
else: self.teardown()
|
||||||
self.teardown()
|
|
||||||
|
|
||||||
def teardown(self):
|
def teardown(self):
|
||||||
if self.initiator and not self.detached:
|
if self.initiator and not self.detached:
|
||||||
RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR)
|
RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR)
|
||||||
if RNS.Reticulum.panic_on_interface_error:
|
if RNS.Reticulum.panic_on_interface_error: RNS.panic()
|
||||||
RNS.panic()
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE)
|
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE)
|
||||||
|
|
||||||
@@ -826,9 +708,7 @@ class I2PInterfacePeer(Interface):
|
|||||||
while self in self.parent_interface.spawned_interfaces:
|
while self in self.parent_interface.spawned_interfaces:
|
||||||
self.parent_interface.spawned_interfaces.remove(self)
|
self.parent_interface.spawned_interfaces.remove(self)
|
||||||
|
|
||||||
if not self.initiator:
|
if not self.initiator: RNS.Transport.remove_interface(self)
|
||||||
RNS.Transport.remove_interface(self)
|
|
||||||
|
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "I2PInterfacePeer["+str(self.name)+"]"
|
return "I2PInterfacePeer["+str(self.name)+"]"
|
||||||
@@ -839,8 +719,7 @@ class I2PInterface(Interface):
|
|||||||
DEFAULT_IFAC_SIZE = 16
|
DEFAULT_IFAC_SIZE = 16
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def clients(self):
|
def clients(self): return len(self.spawned_interfaces)
|
||||||
return len(self.spawned_interfaces)
|
|
||||||
|
|
||||||
def __init__(self, owner, configuration):
|
def __init__(self, owner, configuration):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
@@ -894,11 +773,9 @@ class I2PInterface(Interface):
|
|||||||
RNS.log("I2P controller did not become available in time, waiting for controller", RNS.LOG_VERBOSE)
|
RNS.log("I2P controller did not become available in time, waiting for controller", RNS.LOG_VERBOSE)
|
||||||
i2p_notready_warning = True
|
i2p_notready_warning = True
|
||||||
|
|
||||||
while not self.i2p.ready:
|
while not self.i2p.ready: time.sleep(0.25)
|
||||||
time.sleep(0.25)
|
|
||||||
|
|
||||||
if i2p_notready_warning == True:
|
if i2p_notready_warning == True: RNS.log("I2P controller ready, continuing setup", RNS.LOG_VERBOSE)
|
||||||
RNS.log("I2P controller ready, continuing setup", RNS.LOG_VERBOSE)
|
|
||||||
|
|
||||||
def handlerFactory(callback):
|
def handlerFactory(callback):
|
||||||
def createHandler(*args, **keys):
|
def createHandler(*args, **keys):
|
||||||
@@ -971,18 +848,11 @@ class I2PInterface(Interface):
|
|||||||
spawned_interface.ifac_netkey = self.ifac_netkey
|
spawned_interface.ifac_netkey = self.ifac_netkey
|
||||||
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
|
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
|
||||||
ifac_origin = b""
|
ifac_origin = b""
|
||||||
if spawned_interface.ifac_netname != None:
|
if spawned_interface.ifac_netname != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
|
||||||
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
|
if spawned_interface.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
|
||||||
if spawned_interface.ifac_netkey != None:
|
|
||||||
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
|
|
||||||
|
|
||||||
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
|
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
|
||||||
spawned_interface.ifac_key = RNS.Cryptography.hkdf(
|
spawned_interface.ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=ifac_origin_hash, salt=RNS.Reticulum.IFAC_SALT, context=None)
|
||||||
length=64,
|
|
||||||
derive_from=ifac_origin_hash,
|
|
||||||
salt=RNS.Reticulum.IFAC_SALT,
|
|
||||||
context=None
|
|
||||||
)
|
|
||||||
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
|
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
|
||||||
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
|
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
|
||||||
|
|
||||||
@@ -990,40 +860,46 @@ class I2PInterface(Interface):
|
|||||||
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
||||||
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
||||||
spawned_interface.mode = self.mode
|
spawned_interface.mode = self.mode
|
||||||
|
spawned_interface.gravity = self.gravity
|
||||||
spawned_interface.HW_MTU = self.HW_MTU
|
spawned_interface.HW_MTU = self.HW_MTU
|
||||||
RNS.log("Spawned new I2PInterface Peer: "+str(spawned_interface), RNS.LOG_VERBOSE)
|
RNS.log("Spawned new I2PInterface Peer: "+str(spawned_interface), RNS.LOG_VERBOSE)
|
||||||
RNS.Transport.add_interface(spawned_interface)
|
RNS.Transport.add_interface(spawned_interface)
|
||||||
while spawned_interface in self.spawned_interfaces:
|
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
|
||||||
self.spawned_interfaces.remove(spawned_interface)
|
|
||||||
self.spawned_interfaces.append(spawned_interface)
|
self.spawned_interfaces.append(spawned_interface)
|
||||||
spawned_interface.read_loop()
|
spawned_interface.read_loop()
|
||||||
|
|
||||||
def process_outgoing(self, data):
|
def process_outgoing(self, data):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def received_announce(self, from_spawned=False):
|
def received_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ia_freq_deque.append(time.time())
|
||||||
|
self.arxb += size
|
||||||
|
|
||||||
def sent_announce(self, from_spawned=False):
|
def sent_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.oa_freq_deque.append(time.time())
|
||||||
|
self.atxb += size
|
||||||
|
|
||||||
def received_path_request(self, from_spawned=False):
|
def received_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ip_freq_deque.append(time.time())
|
||||||
|
self.prxb += size
|
||||||
|
|
||||||
def sent_path_request(self, from_spawned=False):
|
def sent_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.op_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.op_freq_deque.append(time.time())
|
||||||
|
self.ptxb += size
|
||||||
|
|
||||||
def detach(self):
|
def detach(self):
|
||||||
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
|
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
|
||||||
self.i2p.stop()
|
self.i2p.stop()
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self): return "I2PInterface["+self.name+"]"
|
||||||
return "I2PInterface["+self.name+"]"
|
|
||||||
|
|
||||||
class I2PInterfaceHandler(socketserver.BaseRequestHandler):
|
class I2PInterfaceHandler(socketserver.BaseRequestHandler):
|
||||||
def __init__(self, callback, *args, **keys):
|
def __init__(self, callback, *args, **keys):
|
||||||
self.callback = callback
|
self.callback = callback
|
||||||
socketserver.BaseRequestHandler.__init__(self, *args, **keys)
|
socketserver.BaseRequestHandler.__init__(self, *args, **keys)
|
||||||
|
|
||||||
def handle(self):
|
def handle(self): self.callback(handler=self)
|
||||||
self.callback(handler=self)
|
|
||||||
+83
-31
@@ -52,7 +52,8 @@ class Interface:
|
|||||||
|
|
||||||
# Which interface modes a Transport Node should
|
# Which interface modes a Transport Node should
|
||||||
# actively discover paths for.
|
# actively discover paths for.
|
||||||
DISCOVER_PATHS_FOR = [MODE_ACCESS_POINT, MODE_GATEWAY, MODE_ROAMING, MODE_INTERNAL]
|
DISCOVER_PATHS_FOR = [MODE_ACCESS_POINT, MODE_GATEWAY, MODE_ROAMING, MODE_INTERNAL]
|
||||||
|
BOUNDARY_SEARCH_MODES = [MODE_BOUNDARY, MODE_GATEWAY]
|
||||||
|
|
||||||
# How many samples to use for announce
|
# How many samples to use for announce
|
||||||
# frequency calculations
|
# frequency calculations
|
||||||
@@ -70,9 +71,8 @@ class Interface:
|
|||||||
# to hold at any given time.
|
# to hold at any given time.
|
||||||
MAX_HELD_ANNOUNCES = 256
|
MAX_HELD_ANNOUNCES = 256
|
||||||
|
|
||||||
# How long a spawned interface will be
|
# Control parameters
|
||||||
# considered to be newly created. Two
|
DEFAULT_GRAVITY = 0
|
||||||
# hours by default.
|
|
||||||
IC_NEW_TIME = 2*60*60
|
IC_NEW_TIME = 2*60*60
|
||||||
IC_BURST_FREQ_NEW = 3
|
IC_BURST_FREQ_NEW = 3
|
||||||
IC_BURST_FREQ = 10
|
IC_BURST_FREQ = 10
|
||||||
@@ -82,7 +82,7 @@ class Interface:
|
|||||||
IC_BURST_PENALTY = 15
|
IC_BURST_PENALTY = 15
|
||||||
IC_HELD_RELEASE_INTERVAL = 5
|
IC_HELD_RELEASE_INTERVAL = 5
|
||||||
IC_DEQUE_MIN_SAMPLE = 2
|
IC_DEQUE_MIN_SAMPLE = 2
|
||||||
IC_BURST_MIN_SAMPLES = 6
|
EC_BURST_MIN_SAMPLES = 2
|
||||||
EC_PR_FREQ = 5
|
EC_PR_FREQ = 5
|
||||||
EGRESS_CONTROL = False
|
EGRESS_CONTROL = False
|
||||||
|
|
||||||
@@ -93,15 +93,26 @@ class Interface:
|
|||||||
|
|
||||||
AUTOCONFIGURE_MTU = False
|
AUTOCONFIGURE_MTU = False
|
||||||
FIXED_MTU = False
|
FIXED_MTU = False
|
||||||
|
DEFAULT_IFAC_SIZE = 16
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.rxb = 0
|
self.rxb = 0
|
||||||
self.txb = 0
|
self.txb = 0
|
||||||
|
self.arxb = 0
|
||||||
|
self.atxb = 0
|
||||||
|
self.arxc = 0
|
||||||
|
self.atxc = 0
|
||||||
|
self.prxb = 0
|
||||||
|
self.ptxb = 0
|
||||||
|
self.prxc = 0
|
||||||
|
self.ptxc = 0
|
||||||
|
self.gravity = 0
|
||||||
self.created = time.time()
|
self.created = time.time()
|
||||||
self.detached = False
|
self.detached = False
|
||||||
self.online = False
|
self.online = False
|
||||||
self.bitrate = 62500
|
self.bitrate = 62500
|
||||||
self.HW_MTU = None
|
self.HW_MTU = None
|
||||||
|
self.__hash = None
|
||||||
|
|
||||||
self.supports_discovery = False
|
self.supports_discovery = False
|
||||||
self.discoverable = False
|
self.discoverable = False
|
||||||
@@ -109,6 +120,7 @@ class Interface:
|
|||||||
self.bootstrap_only = False
|
self.bootstrap_only = False
|
||||||
self.recursive_prs = False
|
self.recursive_prs = False
|
||||||
self.announces_from_internal = True
|
self.announces_from_internal = True
|
||||||
|
self.announces_to_internal = None
|
||||||
self.parent_interface = None
|
self.parent_interface = None
|
||||||
self.spawned_interfaces = None
|
self.spawned_interfaces = None
|
||||||
self.tunnel_id = None
|
self.tunnel_id = None
|
||||||
@@ -117,8 +129,11 @@ class Interface:
|
|||||||
|
|
||||||
self.ic_burst_active = False
|
self.ic_burst_active = False
|
||||||
self.ic_burst_activated = 0
|
self.ic_burst_activated = 0
|
||||||
|
self.ic_burst_sustained = 0
|
||||||
self.ic_pr_burst_active = False
|
self.ic_pr_burst_active = False
|
||||||
self.ic_pr_burst_activated = 0
|
self.ic_pr_burst_activated = 0
|
||||||
|
self.ic_pr_burst_sustained = 0
|
||||||
|
self.ic_pr_burst_cooldown = 0
|
||||||
self.ic_held_release = 0
|
self.ic_held_release = 0
|
||||||
self.ic_max_held_announces = RNS.Reticulum.get_instance()._default_ic_max_held_announces()
|
self.ic_max_held_announces = RNS.Reticulum.get_instance()._default_ic_max_held_announces()
|
||||||
self.ic_burst_hold = RNS.Reticulum.get_instance()._default_ic_burst_hold()
|
self.ic_burst_hold = RNS.Reticulum.get_instance()._default_ic_burst_hold()
|
||||||
@@ -138,8 +153,13 @@ class Interface:
|
|||||||
self.ip_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
|
self.ip_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
|
||||||
self.op_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
|
self.op_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
|
||||||
|
|
||||||
|
self.protocol_violations = 0
|
||||||
|
self.ifac_violations = 0
|
||||||
|
self.packet_filter_hits = 0
|
||||||
|
|
||||||
def get_hash(self):
|
def get_hash(self):
|
||||||
return RNS.Identity.full_hash(str(self).encode("utf-8"))
|
if not self.__hash: self.__hash = RNS.Identity.full_hash(str(self).encode("utf-8"))
|
||||||
|
return self.__hash
|
||||||
|
|
||||||
# This is a generic function for determining when an interface
|
# This is a generic function for determining when an interface
|
||||||
# should activate ingress limiting. Since this can vary for
|
# should activate ingress limiting. Since this can vary for
|
||||||
@@ -151,8 +171,10 @@ class Interface:
|
|||||||
ia_freq = self.incoming_announce_frequency()
|
ia_freq = self.incoming_announce_frequency()
|
||||||
|
|
||||||
if self.ic_burst_active:
|
if self.ic_burst_active:
|
||||||
if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold:
|
if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold and time.time() > self.ic_burst_sustained+self.ic_burst_hold:
|
||||||
if len(self.ia_freq_deque) >= self.IC_BURST_MIN_SAMPLES: self.ic_burst_active = False
|
if len(self.ia_freq_deque) >= self.IC_DEQUE_MIN_SAMPLE: self.ic_burst_active = False
|
||||||
|
else:
|
||||||
|
if ia_freq >= freq_threshold: self.ic_burst_sustained = time.time()
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -160,6 +182,7 @@ class Interface:
|
|||||||
if ia_freq > freq_threshold:
|
if ia_freq > freq_threshold:
|
||||||
self.ic_burst_active = True
|
self.ic_burst_active = True
|
||||||
self.ic_burst_activated = time.time()
|
self.ic_burst_activated = time.time()
|
||||||
|
self.ic_burst_sustained = time.time()
|
||||||
self.ic_held_release = time.time() + self.ic_burst_penalty
|
self.ic_held_release = time.time() + self.ic_burst_penalty
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -173,8 +196,12 @@ class Interface:
|
|||||||
ip_freq = self.incoming_pr_frequency()
|
ip_freq = self.incoming_pr_frequency()
|
||||||
|
|
||||||
if self.ic_pr_burst_active:
|
if self.ic_pr_burst_active:
|
||||||
if ip_freq < freq_threshold and time.time() > self.ic_pr_burst_activated+self.ic_burst_hold:
|
if ip_freq < freq_threshold and time.time() > self.ic_pr_burst_activated+self.ic_burst_hold and time.time() > self.ic_pr_burst_sustained+self.ic_burst_hold:
|
||||||
self.ic_pr_burst_active = False
|
if self.ic_pr_burst_cooldown <= 0: self.ic_pr_burst_active = False
|
||||||
|
else: self.ic_pr_burst_cooldown -= 1
|
||||||
|
else:
|
||||||
|
self.ic_pr_burst_cooldown = 3
|
||||||
|
if ip_freq >= freq_threshold: self.ic_pr_burst_sustained = time.time()
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -182,6 +209,8 @@ class Interface:
|
|||||||
if ip_freq > freq_threshold:
|
if ip_freq > freq_threshold:
|
||||||
self.ic_pr_burst_active = True
|
self.ic_pr_burst_active = True
|
||||||
self.ic_pr_burst_activated = time.time()
|
self.ic_pr_burst_activated = time.time()
|
||||||
|
self.ic_pr_burst_sustained = time.time()
|
||||||
|
self.ic_pr_burst_cooldown = 3
|
||||||
return True
|
return True
|
||||||
|
|
||||||
else: return False
|
else: return False
|
||||||
@@ -191,10 +220,10 @@ class Interface:
|
|||||||
def should_egress_limit_pr(self):
|
def should_egress_limit_pr(self):
|
||||||
if self.egress_control:
|
if self.egress_control:
|
||||||
freq_threshold = self.ec_pr_freq
|
freq_threshold = self.ec_pr_freq
|
||||||
op_freq = self.outgoing_pr_frequency()
|
op_freq = self.outgoing_pr_frequency(preemptive=True)
|
||||||
|
|
||||||
if op_freq > freq_threshold:
|
if op_freq > freq_threshold:
|
||||||
if len(self.op_freq_deque) >= self.IC_BURST_MIN_SAMPLES: return True
|
if len(self.op_freq_deque) >= self.EC_BURST_MIN_SAMPLES: return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -212,7 +241,7 @@ class Interface:
|
|||||||
elif self.bitrate > 62_500: self.HW_MTU = 1024
|
elif self.bitrate > 62_500: self.HW_MTU = 1024
|
||||||
else: self.HW_MTU = None
|
else: self.HW_MTU = None
|
||||||
|
|
||||||
RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_DEBUG)
|
RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_PATHING)
|
||||||
|
|
||||||
def age(self):
|
def age(self):
|
||||||
return time.time()-self.created
|
return time.time()-self.created
|
||||||
@@ -243,32 +272,56 @@ class Interface:
|
|||||||
RNS.log("Releasing held announce packet "+str(selected_announce_packet)+" from "+str(self), RNS.LOG_EXTREME)
|
RNS.log("Releasing held announce packet "+str(selected_announce_packet)+" from "+str(self), RNS.LOG_EXTREME)
|
||||||
self.ic_held_release = time.time() + self.ic_held_release_interval
|
self.ic_held_release = time.time() + self.ic_held_release_interval
|
||||||
self.held_announces.pop(selected_announce_packet.destination_hash)
|
self.held_announces.pop(selected_announce_packet.destination_hash)
|
||||||
def release(): RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface)
|
def release(): RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface, tc=RNS.Transport.TC_INGRESS_LIMITED, ifac_handled=True)
|
||||||
threading.Thread(target=release, daemon=True).start()
|
threading.Thread(target=release, daemon=True).start()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("An error occurred while processing held announces for "+str(self), RNS.LOG_ERROR)
|
RNS.log("An error occurred while processing held announces for "+str(self), RNS.LOG_ERROR)
|
||||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
def received_announce(self, from_spawned=False):
|
def received_announce(self, size=0, from_spawned=False):
|
||||||
|
self.arxc += 1; self.arxb += size
|
||||||
self.ia_freq_deque.append(time.time())
|
self.ia_freq_deque.append(time.time())
|
||||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||||
self.parent_interface.received_announce(from_spawned=True)
|
self.parent_interface.received_announce(size=size, from_spawned=True)
|
||||||
|
|
||||||
def sent_announce(self, from_spawned=False):
|
def sent_announce(self, size=0, from_spawned=False):
|
||||||
|
self.atxc += 1; self.atxb += size
|
||||||
self.oa_freq_deque.append(time.time())
|
self.oa_freq_deque.append(time.time())
|
||||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||||
self.parent_interface.sent_announce(from_spawned=True)
|
self.parent_interface.sent_announce(size=size, from_spawned=True)
|
||||||
|
|
||||||
def received_path_request(self, from_spawned=False):
|
def received_path_request(self, size=0, from_spawned=False):
|
||||||
|
self.prxc += 1; self.prxb += size
|
||||||
self.ip_freq_deque.append(time.time())
|
self.ip_freq_deque.append(time.time())
|
||||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||||
self.parent_interface.received_path_request(from_spawned=True)
|
self.parent_interface.received_path_request(size=size, from_spawned=True)
|
||||||
|
|
||||||
def sent_path_request(self, from_spawned=False):
|
def sent_path_request(self, size=0, from_spawned=False):
|
||||||
|
self.ptxc += 1; self.ptxb += size
|
||||||
self.op_freq_deque.append(time.time())
|
self.op_freq_deque.append(time.time())
|
||||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||||
self.parent_interface.sent_path_request(from_spawned=True)
|
self.parent_interface.sent_path_request(size=size, from_spawned=True)
|
||||||
|
|
||||||
|
def protocol_violation(self, description=None):
|
||||||
|
self.protocol_violations += 1
|
||||||
|
RNS.log(f"Protocol violation on {self}: {description}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def ifac_violation(self, description=None):
|
||||||
|
self.ifac_violations += 1
|
||||||
|
RNS.log(f"IFAC violation on {self}: {description}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def packet_filter_hit(self):
|
||||||
|
self.packet_filter_hits += 1
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ic_burst_count(self): return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ic_pr_burst_count(self): return None
|
||||||
|
|
||||||
def incoming_announce_frequency(self):
|
def incoming_announce_frequency(self):
|
||||||
n = len(self.ia_freq_deque)
|
n = len(self.ia_freq_deque)
|
||||||
@@ -303,8 +356,8 @@ class Interface:
|
|||||||
hz = n / span
|
hz = n / span
|
||||||
return hz
|
return hz
|
||||||
|
|
||||||
def outgoing_pr_frequency(self):
|
def outgoing_pr_frequency(self, preemptive=False):
|
||||||
n = len(self.op_freq_deque)
|
n = len(self.op_freq_deque)+(1 if preemptive else 0)
|
||||||
if not len(self.op_freq_deque) > 1: return 0
|
if not len(self.op_freq_deque) > 1: return 0
|
||||||
else:
|
else:
|
||||||
oldest = self.op_freq_deque[0]
|
oldest = self.op_freq_deque[0]
|
||||||
@@ -337,12 +390,13 @@ class Interface:
|
|||||||
selected = entries[0]
|
selected = entries[0]
|
||||||
|
|
||||||
now = time.time()
|
now = time.time()
|
||||||
tx_time = (len(selected["raw"])*8) / self.bitrate
|
tx_size = len(selected["raw"])
|
||||||
|
tx_time = (tx_size*8) / self.bitrate
|
||||||
wait_time = (tx_time / self.announce_cap)
|
wait_time = (tx_time / self.announce_cap)
|
||||||
self.announce_allowed_at = now + wait_time
|
self.announce_allowed_at = now + wait_time
|
||||||
|
|
||||||
self.process_outgoing(selected["raw"])
|
RNS.Transport.transmit(self, selected["raw"])
|
||||||
self.sent_announce()
|
self.sent_announce(tx_size)
|
||||||
|
|
||||||
if selected in self.announce_queue:
|
if selected in self.announce_queue:
|
||||||
self.announce_queue.remove(selected)
|
self.announce_queue.remove(selected)
|
||||||
@@ -364,11 +418,9 @@ class Interface:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_config_obj(config_in):
|
def get_config_obj(config_in):
|
||||||
if type(config_in) == ConfigObj:
|
if type(config_in) == ConfigObj: return config_in
|
||||||
return config_in
|
|
||||||
else:
|
else:
|
||||||
try:
|
try: return ConfigObj(config_in)
|
||||||
return ConfigObj(config_in)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"Could not parse supplied configuration data. The contained exception was: {e}", RNS.LOG_ERROR)
|
RNS.log(f"Could not parse supplied configuration data. The contained exception was: {e}", RNS.LOG_ERROR)
|
||||||
raise SystemError("Invalid configuration data supplied")
|
raise SystemError("Invalid configuration data supplied")
|
||||||
@@ -70,6 +70,7 @@ class LocalClientInterface(Interface):
|
|||||||
self.epoll_backend = False
|
self.epoll_backend = False
|
||||||
self.HW_MTU = 262144
|
self.HW_MTU = 262144
|
||||||
self.online = False
|
self.online = False
|
||||||
|
self.ifac_size = self.DEFAULT_IFAC_SIZE
|
||||||
|
|
||||||
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
|
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
|
||||||
else: self.socket_path = None
|
else: self.socket_path = None
|
||||||
@@ -382,6 +383,7 @@ class LocalServerInterface(Interface):
|
|||||||
self.epoll_backend = False
|
self.epoll_backend = False
|
||||||
self.online = False
|
self.online = False
|
||||||
self.clients = 0
|
self.clients = 0
|
||||||
|
self.ifac_size = self.DEFAULT_IFAC_SIZE
|
||||||
|
|
||||||
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
|
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
|
||||||
else: self.socket_path = None
|
else: self.socket_path = None
|
||||||
@@ -481,17 +483,25 @@ class LocalServerInterface(Interface):
|
|||||||
def process_outgoing(self, data):
|
def process_outgoing(self, data):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def received_announce(self, from_spawned=False):
|
def received_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ia_freq_deque.append(time.time())
|
||||||
|
self.arxb += size
|
||||||
|
|
||||||
def sent_announce(self, from_spawned=False):
|
def sent_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.oa_freq_deque.append(time.time())
|
||||||
|
self.atxb += size
|
||||||
|
|
||||||
def received_path_request(self, from_spawned=False):
|
def received_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ip_freq_deque.append(time.time())
|
||||||
|
self.prxb += size
|
||||||
|
|
||||||
def sent_path_request(self, from_spawned=False):
|
def sent_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.op_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.op_freq_deque.append(time.time())
|
||||||
|
self.ptxb += size
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]"
|
if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]"
|
||||||
|
|||||||
@@ -543,17 +543,25 @@ class RNodeMultiInterface(Interface):
|
|||||||
if written != len(frame):
|
if written != len(frame):
|
||||||
raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data)))
|
raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data)))
|
||||||
|
|
||||||
def received_announce(self, from_spawned=False):
|
def received_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ia_freq_deque.append(time.time())
|
||||||
|
self.arxb += size
|
||||||
|
|
||||||
def sent_announce(self, from_spawned=False):
|
def sent_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.oa_freq_deque.append(time.time())
|
||||||
|
self.atxb += size
|
||||||
|
|
||||||
def received_path_request(self, from_spawned=False):
|
def received_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ip_freq_deque.append(time.time())
|
||||||
|
self.prxb += size
|
||||||
|
|
||||||
def sent_path_request(self, from_spawned=False):
|
def sent_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.op_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.op_freq_deque.append(time.time())
|
||||||
|
self.ptxb += size
|
||||||
|
|
||||||
def readLoop(self):
|
def readLoop(self):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -333,6 +333,13 @@ class TCPClientInterface(Interface):
|
|||||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
self.teardown()
|
self.teardown()
|
||||||
|
|
||||||
|
def check_frame_len(self, frame_len):
|
||||||
|
if frame_len <= RNS.Reticulum.HEADER_MINSIZE: return False
|
||||||
|
elif frame_len > self.HW_MTU + (self.ifac_size or 0): return False
|
||||||
|
else: return True
|
||||||
|
|
||||||
|
def invalid_frame(self, frame_len):
|
||||||
|
RNS.log(f"Invalid HDLC frame of {RNS.prettysize(frame_len)} received on {self}, dropping frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
def read_loop(self):
|
def read_loop(self):
|
||||||
try:
|
try:
|
||||||
@@ -389,12 +396,18 @@ class TCPClientInterface(Interface):
|
|||||||
frame = frame_buffer[frame_start+1:frame_end]
|
frame = frame_buffer[frame_start+1:frame_end]
|
||||||
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
|
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
|
||||||
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
|
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
|
||||||
if len(frame) > RNS.Reticulum.HEADER_MINSIZE:
|
frame_len = len(frame)
|
||||||
self.process_incoming(frame)
|
if frame_len != 0:
|
||||||
|
if self.check_frame_len(frame_len): self.process_incoming(frame)
|
||||||
|
else: self.invalid_frame(len(frame))
|
||||||
|
|
||||||
frame_buffer = frame_buffer[frame_end:]
|
frame_buffer = frame_buffer[frame_end:]
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
if len(frame_buffer) > self.HW_MTU*2: frame_buffer = b""
|
||||||
flags_remaining = False
|
flags_remaining = False
|
||||||
else:
|
else:
|
||||||
|
frame_buffer = b""
|
||||||
flags_remaining = False
|
flags_remaining = False
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -623,6 +636,7 @@ class TCPServerInterface(Interface):
|
|||||||
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
||||||
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
||||||
spawned_interface.mode = self.mode
|
spawned_interface.mode = self.mode
|
||||||
|
spawned_interface.gravity = self.gravity
|
||||||
spawned_interface.HW_MTU = self.HW_MTU
|
spawned_interface.HW_MTU = self.HW_MTU
|
||||||
spawned_interface.online = True
|
spawned_interface.online = True
|
||||||
RNS.log("Spawned new TCPClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
|
RNS.log("Spawned new TCPClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
|
||||||
@@ -632,17 +646,25 @@ class TCPServerInterface(Interface):
|
|||||||
self.spawned_interfaces.append(spawned_interface)
|
self.spawned_interfaces.append(spawned_interface)
|
||||||
spawned_interface.read_loop()
|
spawned_interface.read_loop()
|
||||||
|
|
||||||
def received_announce(self, from_spawned=False):
|
def received_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ia_freq_deque.append(time.time())
|
||||||
|
self.arxb += size
|
||||||
|
|
||||||
def sent_announce(self, from_spawned=False):
|
def sent_announce(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.oa_freq_deque.append(time.time())
|
||||||
|
self.atxb += size
|
||||||
|
|
||||||
def received_path_request(self, from_spawned=False):
|
def received_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.ip_freq_deque.append(time.time())
|
||||||
|
self.prxb += size
|
||||||
|
|
||||||
def sent_path_request(self, from_spawned=False):
|
def sent_path_request(self, size=0, from_spawned=False):
|
||||||
if from_spawned: self.op_freq_deque.append(time.time())
|
if from_spawned:
|
||||||
|
self.op_freq_deque.append(time.time())
|
||||||
|
self.ptxb += size
|
||||||
|
|
||||||
def process_outgoing(self, data):
|
def process_outgoing(self, data):
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -961,6 +961,7 @@ class WeaveInterface(Interface):
|
|||||||
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
spawned_interface.announce_rate_grace = self.announce_rate_grace
|
||||||
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
|
||||||
spawned_interface.mode = self.mode
|
spawned_interface.mode = self.mode
|
||||||
|
spawned_interface.gravity = self.gravity
|
||||||
spawned_interface.HW_MTU = self.HW_MTU
|
spawned_interface.HW_MTU = self.HW_MTU
|
||||||
spawned_interface._online = True
|
spawned_interface._online = True
|
||||||
RNS.Transport.add_interface(spawned_interface)
|
RNS.Transport.add_interface(spawned_interface)
|
||||||
|
|||||||
+125
-79
@@ -190,24 +190,22 @@ class Link:
|
|||||||
link.set_link_id(packet)
|
link.set_link_id(packet)
|
||||||
|
|
||||||
if len(data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE:
|
if len(data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE:
|
||||||
RNS.log("Link request includes MTU signalling", RNS.LOG_DEBUG) # TODO: Remove debug
|
RNS.log("Link request includes MTU signalling", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
try: link.mtu = Link.mtu_from_lr_packet(packet) or Reticulum.MTU
|
try: link.mtu = Link.mtu_from_lr_packet(packet) or RNS.Reticulum.MTU
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.trace_exception(e)
|
RNS.trace_exception(e)
|
||||||
link.mtu = RNS.Reticulum.MTU
|
link.mtu = RNS.Reticulum.MTU
|
||||||
|
|
||||||
link.mode = Link.mode_from_lr_packet(packet)
|
link.mode = Link.mode_from_lr_packet(packet)
|
||||||
|
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
# TODO: Remove debug
|
|
||||||
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG)
|
|
||||||
|
|
||||||
link.update_mdu()
|
link.update_mdu()
|
||||||
link.destination = packet.destination
|
link.destination = packet.destination
|
||||||
link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE
|
link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE
|
||||||
link.establishment_cost += len(packet.raw)
|
link.establishment_cost += len(packet.raw)
|
||||||
RNS.log(f"Validating link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_DEBUG)
|
RNS.log(f"Validating link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
RNS.log(f"Link MTU configured to {RNS.prettysize(link.mtu)}", RNS.LOG_EXTREME)
|
RNS.log(f"Link MTU configured to {RNS.prettysize(link.mtu)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
RNS.log(f"Establishment timeout is {RNS.prettytime(link.establishment_timeout)} for incoming link request "+RNS.prettyhexrep(link.link_id), RNS.LOG_EXTREME)
|
RNS.log(f"Establishment timeout is {RNS.prettytime(link.establishment_timeout)} for incoming link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||||
link.handshake()
|
link.handshake()
|
||||||
link.attached_interface = packet.receiving_interface
|
link.attached_interface = packet.receiving_interface
|
||||||
link.prove()
|
link.prove()
|
||||||
@@ -217,15 +215,15 @@ class Link:
|
|||||||
link.__update_phy_stats(packet, force_update=True)
|
link.__update_phy_stats(packet, force_update=True)
|
||||||
link.start_watchdog()
|
link.start_watchdog()
|
||||||
|
|
||||||
RNS.log("Incoming link request "+str(link)+" accepted on "+str(link.attached_interface), RNS.LOG_DEBUG)
|
RNS.log(f"Incoming link request {link} accepted on {link.attached_interface}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
return link
|
return link
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log(f"Validating link request failed: {e}", RNS.LOG_VERBOSE)
|
RNS.log(f"Validating link request failed: {e}", RNS.LOG_VERBOSE) if RNS.sl(RNS.LOG_VERBOSE) else None
|
||||||
return None
|
return None
|
||||||
|
|
||||||
else:
|
else:
|
||||||
RNS.log(f"Invalid link request payload size of {len(data)} bytes, dropping request", RNS.LOG_DEBUG)
|
RNS.log(f"Invalid link request payload size of {len(data)} bytes, dropping request", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -267,6 +265,7 @@ class Link:
|
|||||||
self.owner = owner
|
self.owner = owner
|
||||||
self.destination = destination
|
self.destination = destination
|
||||||
self.expected_hops = None
|
self.expected_hops = None
|
||||||
|
self.rebalanced = None
|
||||||
self.attached_interface = None
|
self.attached_interface = None
|
||||||
self.__remote_identity = None
|
self.__remote_identity = None
|
||||||
self.__track_phy_stats = False
|
self.__track_phy_stats = False
|
||||||
@@ -395,13 +394,13 @@ class Link:
|
|||||||
signalling_bytes = b""
|
signalling_bytes = b""
|
||||||
confirmed_mtu = None
|
confirmed_mtu = None
|
||||||
mode = Link.mode_from_lp_packet(packet)
|
mode = Link.mode_from_lp_packet(packet)
|
||||||
RNS.log(f"Validating link request proof with mode {Link.MODE_DESCRIPTIONS[mode]}", RNS.LOG_DEBUG) # TODO: Remove debug
|
RNS.log(f"Validating link request proof with mode {Link.MODE_DESCRIPTIONS[mode]}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
if mode != self.mode: raise TypeError(f"Invalid link mode {mode} in link request proof")
|
if mode != self.mode: raise TypeError(f"Invalid link mode {mode} in link request proof")
|
||||||
if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
|
if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
|
||||||
confirmed_mtu = Link.mtu_from_lp_packet(packet)
|
confirmed_mtu = Link.mtu_from_lp_packet(packet)
|
||||||
signalling_bytes = Link.signalling_bytes(confirmed_mtu, mode)
|
signalling_bytes = Link.signalling_bytes(confirmed_mtu, mode)
|
||||||
packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
|
packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
|
||||||
RNS.log(f"Destination confirmed link MTU of {RNS.prettysize(confirmed_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug
|
RNS.log(f"Destination confirmed link MTU of {RNS.prettysize(confirmed_mtu)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
if self.initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2:
|
if self.initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2:
|
||||||
peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
|
peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
|
||||||
@@ -426,7 +425,7 @@ class Link:
|
|||||||
self.activated_at = time.time()
|
self.activated_at = time.time()
|
||||||
self.last_proof = self.activated_at
|
self.last_proof = self.activated_at
|
||||||
RNS.Transport.activate_link(self)
|
RNS.Transport.activate_link(self)
|
||||||
RNS.log("Link "+str(self)+" established with "+str(self.destination)+", RTT is "+RNS.prettyshorttime(self.rtt), RNS.LOG_DEBUG)
|
RNS.log(f"Link {self} established with {self.destination}, RTT is {RNS.prettyshorttime(self.rtt)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0:
|
if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0:
|
||||||
self.establishment_rate = self.establishment_cost/self.rtt
|
self.establishment_rate = self.establishment_cost/self.rtt
|
||||||
@@ -444,7 +443,7 @@ class Link:
|
|||||||
thread.daemon = True
|
thread.daemon = True
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
else: RNS.log("Invalid link proof signature received by "+str(self)+". Ignoring.", RNS.LOG_DEBUG)
|
else: RNS.log(f"Invalid link proof signature received by {self}. Ignoring.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status = Link.CLOSED
|
self.status = Link.CLOSED
|
||||||
@@ -471,7 +470,8 @@ class Link:
|
|||||||
self.had_outbound()
|
self.had_outbound()
|
||||||
|
|
||||||
|
|
||||||
def request(self, path, data = None, response_callback = None, failed_callback = None, progress_callback = None, timeout = None):
|
def request(self, path, data=None, response_callback=None, failed_callback=None, progress_callback=None,
|
||||||
|
timeout=None, max_response_size=None):
|
||||||
"""
|
"""
|
||||||
Sends a request to the remote peer.
|
Sends a request to the remote peer.
|
||||||
|
|
||||||
@@ -479,6 +479,7 @@ class Link:
|
|||||||
:param response_callback: An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the :ref:`Request Example<example-request>` for more info.
|
:param response_callback: An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the :ref:`Request Example<example-request>` for more info.
|
||||||
:param failed_callback: An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the :ref:`Request Example<example-request>` for more info.
|
:param failed_callback: An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the :ref:`Request Example<example-request>` for more info.
|
||||||
:param progress_callback: An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property.
|
:param progress_callback: An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property.
|
||||||
|
:param max_response_size: An optional maximum accepted response size, in bytes as an integer.
|
||||||
:param timeout: An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT.
|
:param timeout: An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT.
|
||||||
:returns: A :ref:`RNS.RequestReceipt<api-requestreceipt>` instance if the request was sent, or *False* if it was not.
|
:returns: A :ref:`RNS.RequestReceipt<api-requestreceipt>` instance if the request was sent, or *False* if it was not.
|
||||||
"""
|
"""
|
||||||
@@ -496,18 +497,17 @@ class Link:
|
|||||||
if packet_receipt == False: return False
|
if packet_receipt == False: return False
|
||||||
else:
|
else:
|
||||||
packet_receipt.set_timeout(timeout)
|
packet_receipt.set_timeout(timeout)
|
||||||
return RequestReceipt(self, packet_receipt = packet_receipt, response_callback = response_callback,
|
return RequestReceipt(self, packet_receipt=packet_receipt, response_callback=response_callback,
|
||||||
failed_callback = failed_callback, progress_callback = progress_callback,
|
failed_callback=failed_callback, progress_callback=progress_callback, timeout=timeout,
|
||||||
timeout = timeout, request_size = len(packed_request))
|
request_size=len(packed_request), max_response_size=max_response_size)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
request_id = RNS.Identity.truncated_hash(packed_request)
|
request_id = RNS.Identity.truncated_hash(packed_request)
|
||||||
RNS.log("Sending request "+RNS.prettyhexrep(request_id)+" as resource.", RNS.LOG_DEBUG)
|
RNS.log("Sending request "+RNS.prettyhexrep(request_id)+" as resource.", RNS.LOG_DEBUG)
|
||||||
request_resource = RNS.Resource(packed_request, self, request_id = request_id, is_response = False, timeout = timeout)
|
request_resource = RNS.Resource(packed_request, self, request_id = request_id, is_response = False, timeout = timeout)
|
||||||
|
|
||||||
return RequestReceipt(self, resource = request_resource, response_callback = response_callback,
|
return RequestReceipt(self, resource=request_resource, response_callback=response_callback,
|
||||||
failed_callback = failed_callback, progress_callback = progress_callback,
|
failed_callback=failed_callback, progress_callback=progress_callback, timeout=timeout,
|
||||||
timeout = timeout, request_size = len(packed_request))
|
request_size=len(packed_request), max_response_size=max_response_size)
|
||||||
|
|
||||||
def update_mdu(self):
|
def update_mdu(self):
|
||||||
self.mdu = self.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
|
self.mdu = self.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
|
||||||
@@ -664,6 +664,7 @@ class Link:
|
|||||||
Closes the link and purges encryption keys. New keys will
|
Closes the link and purges encryption keys. New keys will
|
||||||
be used if a new link to the same destination is established.
|
be used if a new link to the same destination is established.
|
||||||
"""
|
"""
|
||||||
|
if self.status == Link.CLOSED: return
|
||||||
if self.status != Link.PENDING and self.status != Link.CLOSED: self.__teardown_packet()
|
if self.status != Link.PENDING and self.status != Link.CLOSED: self.__teardown_packet()
|
||||||
self.status = Link.CLOSED
|
self.status = Link.CLOSED
|
||||||
if self.initiator: self.teardown_reason = Link.INITIATOR_CLOSED
|
if self.initiator: self.teardown_reason = Link.INITIATOR_CLOSED
|
||||||
@@ -682,8 +683,8 @@ class Link:
|
|||||||
except Exception as e: pass
|
except Exception as e: pass
|
||||||
|
|
||||||
def link_closed(self):
|
def link_closed(self):
|
||||||
for resource in self.incoming_resources: resource.cancel()
|
for resource in self.incoming_resources.copy(): resource.cancel()
|
||||||
for resource in self.outgoing_resources: resource.cancel()
|
for resource in self.outgoing_resources.copy(): resource.cancel()
|
||||||
if self._channel: self._channel._shutdown()
|
if self._channel: self._channel._shutdown()
|
||||||
|
|
||||||
self.prv = None
|
self.prv = None
|
||||||
@@ -745,17 +746,17 @@ class Link:
|
|||||||
last_inbound = max(max(self.last_inbound, self.last_proof), activated_at)
|
last_inbound = max(max(self.last_inbound, self.last_proof), activated_at)
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|
||||||
if now >= last_inbound + self.keepalive:
|
if now >= last_inbound + self.keepalive or now >= self.last_outbound + self.keepalive:
|
||||||
if self.initiator and now >= self.last_keepalive + self.keepalive:
|
if self.initiator and now >= self.last_keepalive + self.keepalive:
|
||||||
self.send_keepalive()
|
self.send_keepalive()
|
||||||
|
|
||||||
if time.time() >= last_inbound + self.stale_time:
|
if now >= last_inbound + self.stale_time:
|
||||||
sleep_time = self.rtt * self.keepalive_timeout_factor + Link.STALE_GRACE
|
sleep_time = self.rtt * self.keepalive_timeout_factor + Link.STALE_GRACE
|
||||||
self.status = Link.STALE
|
self.status = Link.STALE
|
||||||
|
|
||||||
else: sleep_time = self.keepalive
|
else: sleep_time = self.keepalive
|
||||||
|
|
||||||
else: sleep_time = (last_inbound + self.keepalive) - time.time()
|
else: sleep_time = (last_inbound + self.keepalive) - now
|
||||||
|
|
||||||
elif self.status == Link.STALE:
|
elif self.status == Link.STALE:
|
||||||
sleep_time = 0.001
|
sleep_time = 0.001
|
||||||
@@ -765,9 +766,9 @@ class Link:
|
|||||||
self.link_closed()
|
self.link_closed()
|
||||||
|
|
||||||
|
|
||||||
if sleep_time == 0: RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_ERROR)
|
if sleep_time == 0: RNS.log(f"Link watchdog sleep time of 0 on {self}", RNS.LOG_ERROR)
|
||||||
if sleep_time == None or sleep_time < 0:
|
if sleep_time == None or sleep_time < 0:
|
||||||
RNS.log("Timing error! Tearing down link "+str(self)+" now.", RNS.LOG_ERROR)
|
RNS.log(f"Timing error, tearing down link {self} now", RNS.LOG_ERROR)
|
||||||
self.teardown()
|
self.teardown()
|
||||||
sleep_time = 0.1
|
sleep_time = 0.1
|
||||||
|
|
||||||
@@ -807,7 +808,7 @@ class Link:
|
|||||||
request_data = unpacked_request[2]
|
request_data = unpacked_request[2]
|
||||||
|
|
||||||
if path_hash in self.destination.request_handlers:
|
if path_hash in self.destination.request_handlers:
|
||||||
request_handler = self.destination.request_handlers[path_hash]
|
request_handler = self.destination.request_handlers[path_hash]
|
||||||
path = request_handler[0]
|
path = request_handler[0]
|
||||||
response_generator = request_handler[1]
|
response_generator = request_handler[1]
|
||||||
allow = request_handler[2]
|
allow = request_handler[2]
|
||||||
@@ -853,19 +854,26 @@ class Link:
|
|||||||
identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "<Unknown>"
|
identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "<Unknown>"
|
||||||
RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG)
|
RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG)
|
||||||
|
|
||||||
def handle_response(self, request_id, response_data, response_size, response_transfer_size, metadata=None, update_sizes=False):
|
def handle_response(self, request_id, response_data, response_size, response_transfer_size, metadata=None, update_sizes=False, check_size=False):
|
||||||
if self.status == Link.ACTIVE:
|
if self.status == Link.ACTIVE:
|
||||||
remove = None
|
remove = None
|
||||||
for pending_request in self.pending_requests:
|
for pending_request in self.pending_requests:
|
||||||
if pending_request.request_id == request_id:
|
if pending_request.request_id == request_id:
|
||||||
|
if not check_size or pending_request.max_response_size == None: size_ok = True
|
||||||
|
else: size_ok = response_size <= pending_request.max_response_size
|
||||||
|
|
||||||
remove = pending_request
|
remove = pending_request
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if update_sizes:
|
if update_sizes:
|
||||||
pending_request.response_size = response_size
|
pending_request.response_size = response_size
|
||||||
if pending_request.response_transfer_size == None: pending_request.response_transfer_size = 0
|
if pending_request.response_transfer_size == None: pending_request.response_transfer_size = 0
|
||||||
pending_request.response_transfer_size += response_transfer_size
|
pending_request.response_transfer_size += response_transfer_size
|
||||||
|
|
||||||
pending_request.response_received(response_data, metadata)
|
if size_ok: pending_request.response_received(response_data, metadata)
|
||||||
|
else:
|
||||||
|
RNS.log(f"Rejected response with excessive size {RNS.prettysize(response_size)} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
pending_request.response_rejected()
|
||||||
|
|
||||||
except Exception as e: RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
except Exception as e: RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
break
|
break
|
||||||
@@ -920,6 +928,13 @@ class Link:
|
|||||||
|
|
||||||
def receive(self, packet):
|
def receive(self, packet):
|
||||||
self.watchdog_lock = True
|
self.watchdog_lock = True
|
||||||
|
try: self.__receive(packet)
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log(f"Error on {self} while receiving packet: {e}", RNS.LOG_ERROR)
|
||||||
|
RNS.trace_exception(e)
|
||||||
|
finally: self.watchdog_lock = False
|
||||||
|
|
||||||
|
def __receive(self, packet):
|
||||||
if not self.status == Link.CLOSED and not (self.initiator and packet.context == RNS.Packet.KEEPALIVE and packet.data == bytes([0xFF])):
|
if not self.status == Link.CLOSED and not (self.initiator and packet.context == RNS.Packet.KEEPALIVE and packet.data == bytes([0xFF])):
|
||||||
if packet.receiving_interface != self.attached_interface:
|
if packet.receiving_interface != self.attached_interface:
|
||||||
RNS.log(f"Link-associated packet received on unexpected interface {packet.receiving_interface} instead of {self.attached_interface}! Someone might be trying to manipulate your communication!", RNS.LOG_ERROR)
|
RNS.log(f"Link-associated packet received on unexpected interface {packet.receiving_interface} instead of {self.attached_interface}! Someone might be trying to manipulate your communication!", RNS.LOG_ERROR)
|
||||||
@@ -968,10 +983,11 @@ class Link:
|
|||||||
self.teardown()
|
self.teardown()
|
||||||
|
|
||||||
else:
|
else:
|
||||||
self.__remote_identity = identity
|
if self.__remote_identity == None:
|
||||||
if self.callbacks.remote_identified != None:
|
self.__remote_identity = identity
|
||||||
try: self.callbacks.remote_identified(self, self.__remote_identity)
|
if self.callbacks.remote_identified != None:
|
||||||
except Exception as e: RNS.log(f"Error while executing remote identified callback from {self}. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
try: self.callbacks.remote_identified(self, self.__remote_identity)
|
||||||
|
except Exception as e: RNS.log(f"Error while executing remote identified callback from {self}. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
self.__update_phy_stats(packet, query_shared=True)
|
self.__update_phy_stats(packet, query_shared=True)
|
||||||
|
|
||||||
@@ -980,9 +996,13 @@ class Link:
|
|||||||
request_id = packet.getTruncatedHash()
|
request_id = packet.getTruncatedHash()
|
||||||
packed_request = self.decrypt(packet.data)
|
packed_request = self.decrypt(packet.data)
|
||||||
if packed_request != None:
|
if packed_request != None:
|
||||||
unpacked_request = umsgpack.unpackb(packed_request)
|
if self.destination.max_request_size == None: size_ok = True
|
||||||
def job(): self.handle_request(request_id, unpacked_request)
|
else: size_ok = len(packed_request) <= self.destination.max_request_size
|
||||||
threading.Thread(target=job, daemon=True).start()
|
if not size_ok: RNS.log(f"Ignored request with excessive size {RNS.prettysize(len(packed_request))} on {self.destination}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
else:
|
||||||
|
unpacked_request = umsgpack.unpackb(packed_request)
|
||||||
|
def job(): self.handle_request(request_id, unpacked_request)
|
||||||
|
threading.Thread(target=job, daemon=True).start()
|
||||||
self.__update_phy_stats(packet, query_shared=True)
|
self.__update_phy_stats(packet, query_shared=True)
|
||||||
except Exception as e: RNS.log("Error occurred while handling request. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
except Exception as e: RNS.log("Error occurred while handling request. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
@@ -994,7 +1014,7 @@ class Link:
|
|||||||
request_id = unpacked_response[0]
|
request_id = unpacked_response[0]
|
||||||
response_data = unpacked_response[1]
|
response_data = unpacked_response[1]
|
||||||
transfer_size = len(umsgpack.packb(response_data))-2
|
transfer_size = len(umsgpack.packb(response_data))-2
|
||||||
def job(): self.handle_response(request_id, response_data, transfer_size, transfer_size, update_sizes=True)
|
def job(): self.handle_response(request_id, response_data, transfer_size, transfer_size, update_sizes=True, check_size=True)
|
||||||
threading.Thread(target=job, daemon=True).start()
|
threading.Thread(target=job, daemon=True).start()
|
||||||
self.__update_phy_stats(packet, query_shared=True)
|
self.__update_phy_stats(packet, query_shared=True)
|
||||||
except Exception as e: RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
except Exception as e: RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
@@ -1012,36 +1032,51 @@ class Link:
|
|||||||
packet.plaintext = self.decrypt(packet.data)
|
packet.plaintext = self.decrypt(packet.data)
|
||||||
if packet.plaintext != None:
|
if packet.plaintext != None:
|
||||||
self.__update_phy_stats(packet, query_shared=True)
|
self.__update_phy_stats(packet, query_shared=True)
|
||||||
|
try:
|
||||||
if RNS.ResourceAdvertisement.is_request(packet):
|
if RNS.ResourceAdvertisement.is_request(packet):
|
||||||
RNS.Resource.accept(packet, callback=self.request_resource_concluded)
|
if self.destination.request_handlers:
|
||||||
elif RNS.ResourceAdvertisement.is_response(packet):
|
if self.destination.max_request_size == None: size_ok = True
|
||||||
request_id = RNS.ResourceAdvertisement.read_request_id(packet)
|
else: size_ok = RNS.ResourceAdvertisement.read_size(packet) <= self.destination.max_request_size
|
||||||
for pending_request in self.pending_requests:
|
if size_ok: RNS.Resource.accept(packet, callback=self.request_resource_concluded)
|
||||||
if pending_request.request_id == request_id:
|
else:
|
||||||
response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id)
|
RNS.Resource.reject(packet)
|
||||||
if response_resource != None:
|
RNS.log(f"Rejected request with excessive size {RNS.prettysize(RNS.ResourceAdvertisement.read_size(packet))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
if pending_request.response_size == None:
|
elif RNS.ResourceAdvertisement.is_response(packet):
|
||||||
pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet)
|
request_id = RNS.ResourceAdvertisement.read_request_id(packet)
|
||||||
if pending_request.response_transfer_size == None:
|
for pending_request in self.pending_requests:
|
||||||
pending_request.response_transfer_size = 0
|
if pending_request.request_id == request_id:
|
||||||
pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet)
|
if pending_request.max_response_size == None: size_ok = True
|
||||||
if pending_request.started_at == None:
|
else: size_ok = RNS.ResourceAdvertisement.read_size(packet) <= pending_request.max_response_size
|
||||||
pending_request.started_at = time.time()
|
if not size_ok:
|
||||||
pending_request.response_resource_progress(response_resource)
|
RNS.Resource.reject(packet)
|
||||||
|
pending_request.response_rejected()
|
||||||
elif self.resource_strategy == Link.ACCEPT_NONE: pass
|
RNS.log(f"Rejected response with excessive size {RNS.prettysize(RNS.ResourceAdvertisement.read_size(packet))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
elif self.resource_strategy == Link.ACCEPT_APP:
|
else:
|
||||||
if self.callbacks.resource != None:
|
response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id)
|
||||||
try:
|
if response_resource != None:
|
||||||
resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext)
|
if pending_request.response_size == None:
|
||||||
resource_advertisement.link = self
|
pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet)
|
||||||
if self.callbacks.resource(resource_advertisement): RNS.Resource.accept(packet, self.callbacks.resource_concluded)
|
if pending_request.response_transfer_size == None:
|
||||||
else: RNS.Resource.reject(packet)
|
pending_request.response_transfer_size = 0
|
||||||
except Exception as e:
|
pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet)
|
||||||
RNS.log("Error while executing resource accept callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
if pending_request.started_at == None:
|
||||||
elif self.resource_strategy == Link.ACCEPT_ALL:
|
pending_request.started_at = time.time()
|
||||||
RNS.Resource.accept(packet, self.callbacks.resource_concluded)
|
pending_request.response_resource_progress(response_resource)
|
||||||
|
elif self.resource_strategy == Link.ACCEPT_NONE: pass
|
||||||
|
elif self.resource_strategy == Link.ACCEPT_APP:
|
||||||
|
if self.callbacks.resource != None:
|
||||||
|
try:
|
||||||
|
resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext)
|
||||||
|
resource_advertisement.link = self
|
||||||
|
if self.callbacks.resource(resource_advertisement): RNS.Resource.accept(packet, self.callbacks.resource_concluded)
|
||||||
|
else: RNS.Resource.reject(packet)
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log("Error while executing resource accept callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
elif self.resource_strategy == Link.ACCEPT_ALL:
|
||||||
|
RNS.Resource.accept(packet, self.callbacks.resource_concluded)
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log(f"Invalid resource advertisement on {self}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
|
self.teardown()
|
||||||
|
|
||||||
elif packet.context == RNS.Packet.RESOURCE_REQ:
|
elif packet.context == RNS.Packet.RESOURCE_REQ:
|
||||||
plaintext = self.decrypt(packet.data)
|
plaintext = self.decrypt(packet.data)
|
||||||
@@ -1094,9 +1129,10 @@ class Link:
|
|||||||
|
|
||||||
elif packet.context == RNS.Packet.KEEPALIVE:
|
elif packet.context == RNS.Packet.KEEPALIVE:
|
||||||
if not self.initiator and packet.data == bytes([0xFF]):
|
if not self.initiator and packet.data == bytes([0xFF]):
|
||||||
keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE)
|
if time.time() >= self.last_outbound + self.keepalive:
|
||||||
keepalive_packet.send()
|
keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE)
|
||||||
self.had_outbound(is_keepalive = True)
|
keepalive_packet.send()
|
||||||
|
self.had_outbound(is_keepalive = True)
|
||||||
|
|
||||||
|
|
||||||
# TODO: find the most efficient way to allow multiple
|
# TODO: find the most efficient way to allow multiple
|
||||||
@@ -1127,8 +1163,6 @@ class Link:
|
|||||||
threading.Thread(target=job, daemon=True).start()
|
threading.Thread(target=job, daemon=True).start()
|
||||||
self.__update_phy_stats(packet, query_shared=True)
|
self.__update_phy_stats(packet, query_shared=True)
|
||||||
|
|
||||||
self.watchdog_lock = False
|
|
||||||
|
|
||||||
def encrypt(self, plaintext):
|
def encrypt(self, plaintext):
|
||||||
try:
|
try:
|
||||||
if not self.token:
|
if not self.token:
|
||||||
@@ -1287,7 +1321,9 @@ class RequestReceipt():
|
|||||||
RECEIVING = 0x03
|
RECEIVING = 0x03
|
||||||
READY = 0x04
|
READY = 0x04
|
||||||
|
|
||||||
def __init__(self, link, packet_receipt = None, resource = None, response_callback = None, failed_callback = None, progress_callback = None, timeout = None, request_size = None):
|
def __init__(self, link, packet_receipt=None, resource=None, response_callback=None, failed_callback=None,
|
||||||
|
progress_callback=None, timeout=None, request_size=None, max_response_size=None):
|
||||||
|
|
||||||
self.packet_receipt = packet_receipt
|
self.packet_receipt = packet_receipt
|
||||||
self.resource = resource
|
self.resource = resource
|
||||||
self.started_at = None
|
self.started_at = None
|
||||||
@@ -1314,6 +1350,7 @@ class RequestReceipt():
|
|||||||
self.progress = 0
|
self.progress = 0
|
||||||
self.concluded_at = None
|
self.concluded_at = None
|
||||||
self.response_concluded_at = None
|
self.response_concluded_at = None
|
||||||
|
self.max_response_size = max_response_size
|
||||||
|
|
||||||
if timeout != None:
|
if timeout != None:
|
||||||
self.timeout = timeout
|
self.timeout = timeout
|
||||||
@@ -1344,8 +1381,7 @@ class RequestReceipt():
|
|||||||
self.link.pending_requests.remove(self)
|
self.link.pending_requests.remove(self)
|
||||||
|
|
||||||
if self.callbacks.failed != None:
|
if self.callbacks.failed != None:
|
||||||
try:
|
try: self.callbacks.failed(self)
|
||||||
self.callbacks.failed(self)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("Error while executing request failed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
RNS.log("Error while executing request failed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
@@ -1368,6 +1404,16 @@ class RequestReceipt():
|
|||||||
try: self.callbacks.failed(self)
|
try: self.callbacks.failed(self)
|
||||||
except Exception as e: RNS.log("Error while executing request timed out callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
except Exception as e: RNS.log("Error while executing request timed out callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
|
def response_rejected(self):
|
||||||
|
if self in self.link.pending_requests and self.status == RequestReceipt.DELIVERED:
|
||||||
|
self.status = RequestReceipt.FAILED
|
||||||
|
self.concluded_at = time.time()
|
||||||
|
self.link.pending_requests.remove(self)
|
||||||
|
|
||||||
|
if self.callbacks.failed != None:
|
||||||
|
try: self.callbacks.failed(self)
|
||||||
|
except Exception as e: RNS.log("Error while executing request timed out callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
|
|
||||||
def response_resource_progress(self, resource):
|
def response_resource_progress(self, resource):
|
||||||
if resource != None:
|
if resource != None:
|
||||||
if not self.status == RequestReceipt.FAILED:
|
if not self.status == RequestReceipt.FAILED:
|
||||||
|
|||||||
+10
-5
@@ -117,7 +117,7 @@ class Packet:
|
|||||||
__slots__ = "hops", "header", "header_type", "packet_type", "transport_type", "context", "context_flag", "destination"
|
__slots__ = "hops", "header", "header_type", "packet_type", "transport_type", "context", "context_flag", "destination"
|
||||||
__slots__ += "transport_id", "data", "flags", "raw", "packed", "sent", "create_receipt", "receipt", "fromPacked", "MTU"
|
__slots__ += "transport_id", "data", "flags", "raw", "packed", "sent", "create_receipt", "receipt", "fromPacked", "MTU"
|
||||||
__slots__ += "sent_at", "packet_hash", "ratchet_id", "attached_interface", "receiving_interface", "rssi", "snr", "q"
|
__slots__ += "sent_at", "packet_hash", "ratchet_id", "attached_interface", "receiving_interface", "rssi", "snr", "q"
|
||||||
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr"
|
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr", "traffic_class"
|
||||||
|
|
||||||
def __init__(self, destination, data, packet_type = DATA, context = NONE, transport_type = RNS.Transport.BROADCAST,
|
def __init__(self, destination, data, packet_type = DATA, context = NONE, transport_type = RNS.Transport.BROADCAST,
|
||||||
header_type = HEADER_1, transport_id = None, attached_interface = None, create_receipt = True, context_flag=FLAG_UNSET):
|
header_type = HEADER_1, transport_id = None, attached_interface = None, create_receipt = True, context_flag=FLAG_UNSET):
|
||||||
@@ -159,6 +159,7 @@ class Packet:
|
|||||||
self.packet_hash = None
|
self.packet_hash = None
|
||||||
self.ratchet_id = None
|
self.ratchet_id = None
|
||||||
|
|
||||||
|
self.traffic_class = None
|
||||||
self.attached_interface = attached_interface
|
self.attached_interface = attached_interface
|
||||||
self.receiving_interface = None
|
self.receiving_interface = None
|
||||||
self.is_outbound_pr = False
|
self.is_outbound_pr = False
|
||||||
@@ -260,11 +261,14 @@ class Packet:
|
|||||||
self.destination_hash = self.raw[DST_LEN+2:2*DST_LEN+2]
|
self.destination_hash = self.raw[DST_LEN+2:2*DST_LEN+2]
|
||||||
self.context = ord(self.raw[2*DST_LEN+2:2*DST_LEN+3])
|
self.context = ord(self.raw[2*DST_LEN+2:2*DST_LEN+3])
|
||||||
self.data = self.raw[2*DST_LEN+3:]
|
self.data = self.raw[2*DST_LEN+3:]
|
||||||
|
if len(self.transport_id) != DST_LEN: raise ValueError("Malformed Transport ID field")
|
||||||
|
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
|
||||||
else:
|
else:
|
||||||
self.transport_id = None
|
self.transport_id = None
|
||||||
self.destination_hash = self.raw[2:DST_LEN+2]
|
self.destination_hash = self.raw[2:DST_LEN+2]
|
||||||
self.context = ord(self.raw[DST_LEN+2:DST_LEN+3])
|
self.context = ord(self.raw[DST_LEN+2:DST_LEN+3])
|
||||||
self.data = self.raw[DST_LEN+3:]
|
self.data = self.raw[DST_LEN+3:]
|
||||||
|
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
|
||||||
|
|
||||||
self.packed = False
|
self.packed = False
|
||||||
self.update_hash()
|
self.update_hash()
|
||||||
@@ -281,6 +285,7 @@ class Packet:
|
|||||||
:returns: A :ref:`RNS.PacketReceipt<api-packetreceipt>` instance if *create_receipt* was set to *True* when the packet was instantiated, if not returns *None*. If the packet could not be sent *False* is returned.
|
:returns: A :ref:`RNS.PacketReceipt<api-packetreceipt>` instance if *create_receipt* was set to *True* when the packet was instantiated, if not returns *None*. If the packet could not be sent *False* is returned.
|
||||||
"""
|
"""
|
||||||
if not self.sent:
|
if not self.sent:
|
||||||
|
if self.hops >= RNS.Transport.PATHFINDER_M: return False
|
||||||
if not self.packed: self.pack()
|
if not self.packed: self.pack()
|
||||||
if self.destination.type == RNS.Destination.LINK:
|
if self.destination.type == RNS.Destination.LINK:
|
||||||
if self.destination.status == RNS.Link.CLOSED:
|
if self.destination.status == RNS.Link.CLOSED:
|
||||||
@@ -296,7 +301,7 @@ class Packet:
|
|||||||
|
|
||||||
if RNS.Transport.outbound(self): return self.receipt
|
if RNS.Transport.outbound(self): return self.receipt
|
||||||
else:
|
else:
|
||||||
RNS.log("No interfaces could process the outbound packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
RNS.log(f"No interfaces could process the outbound {self.hops} hop, type {self.packet_type} packet for {self.destination}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
self.sent = False
|
self.sent = False
|
||||||
self.receipt = None
|
self.receipt = None
|
||||||
return False
|
return False
|
||||||
@@ -357,21 +362,21 @@ class Packet:
|
|||||||
:returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``.
|
:returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``.
|
||||||
"""
|
"""
|
||||||
if self.rssi != None: return self.rssi
|
if self.rssi != None: return self.rssi
|
||||||
else: return reticulum.get_packet_rssi(self.packet_hash)
|
else: return RNS.Reticulum.get_instance().get_packet_rssi(self.packet_hash)
|
||||||
|
|
||||||
def get_snr(self):
|
def get_snr(self):
|
||||||
"""
|
"""
|
||||||
:returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``.
|
:returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``.
|
||||||
"""
|
"""
|
||||||
if self.snr != None: return self.snr
|
if self.snr != None: return self.snr
|
||||||
else: return reticulum.get_packet_snr(self.packet_hash)
|
else: return RNS.Reticulum.get_instance().get_packet_snr(self.packet_hash)
|
||||||
|
|
||||||
def get_q(self):
|
def get_q(self):
|
||||||
"""
|
"""
|
||||||
:returns: The physical layer *Link Quality* if available, otherwise ``None``.
|
:returns: The physical layer *Link Quality* if available, otherwise ``None``.
|
||||||
"""
|
"""
|
||||||
if self.q != None: return self.q
|
if self.q != None: return self.q
|
||||||
else: return reticulum.get_packet_q(self.packet_hash)
|
else: return RNS.Reticulum.get_instance().get_packet_q(self.packet_hash)
|
||||||
|
|
||||||
class ProofDestination:
|
class ProofDestination:
|
||||||
def __init__(self, packet):
|
def __init__(self, packet):
|
||||||
|
|||||||
+91
-107
@@ -149,7 +149,7 @@ class Resource:
|
|||||||
COMPLETE = 0x06
|
COMPLETE = 0x06
|
||||||
FAILED = 0x07
|
FAILED = 0x07
|
||||||
CORRUPT = 0x08
|
CORRUPT = 0x08
|
||||||
REJECTED = 0x00
|
REJECTED = 0x09
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def reject(advertisement_packet):
|
def reject(advertisement_packet):
|
||||||
@@ -239,7 +239,7 @@ class Resource:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
RNS.log("Could not decode resource advertisement, dropping resource", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
RNS.log(f"Could not decode resource advertisement, dropping resource: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Create a resource for transmission to a remote destination
|
# Create a resource for transmission to a remote destination
|
||||||
@@ -314,30 +314,26 @@ class Resource:
|
|||||||
self.input_file = data
|
self.input_file = data
|
||||||
|
|
||||||
elif isinstance(data, bytes):
|
elif isinstance(data, bytes):
|
||||||
data_size = len(data)
|
data_size = len(data)
|
||||||
self.total_size = data_size + self.metadata_size
|
self.total_size = data_size + self.metadata_size
|
||||||
|
|
||||||
resource_data = data
|
resource_data = data
|
||||||
self.total_segments = 1
|
self.total_segments = 1
|
||||||
self.segment_index = 1
|
self.segment_index = 1
|
||||||
self.split = False
|
self.split = False
|
||||||
|
|
||||||
elif data == None:
|
elif data == None: pass
|
||||||
pass
|
|
||||||
|
|
||||||
else:
|
else: raise TypeError("Invalid data instance type passed to resource initialisation")
|
||||||
raise TypeError("Invalid data instance type passed to resource initialisation")
|
|
||||||
|
|
||||||
if resource_data:
|
if resource_data:
|
||||||
if self.has_metadata: data = self.metadata + resource_data
|
if self.has_metadata: data = self.metadata + resource_data
|
||||||
else: data = resource_data
|
else: data = resource_data
|
||||||
|
|
||||||
self.status = Resource.NONE
|
self.status = Resource.NONE
|
||||||
self.link = link
|
self.link = link
|
||||||
if self.link.mtu:
|
if self.link.mtu: self.sdu = self.link.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
|
||||||
self.sdu = self.link.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
|
else: self.sdu = link.mdu or Resource.SDU
|
||||||
else:
|
|
||||||
self.sdu = link.mdu or Resource.SDU
|
|
||||||
self.max_retries = Resource.MAX_RETRIES
|
self.max_retries = Resource.MAX_RETRIES
|
||||||
self.max_adv_retries = Resource.MAX_ADV_RETRIES
|
self.max_adv_retries = Resource.MAX_ADV_RETRIES
|
||||||
self.retries_left = self.max_retries
|
self.retries_left = self.max_retries
|
||||||
@@ -451,8 +447,8 @@ class Resource:
|
|||||||
self.hashmap = b""
|
self.hashmap = b""
|
||||||
collision_guard_list = []
|
collision_guard_list = []
|
||||||
for i in range(0,hashmap_entries):
|
for i in range(0,hashmap_entries):
|
||||||
data = self.data[i*self.sdu:(i+1)*self.sdu]
|
part_data = self.data[i*self.sdu:(i+1)*self.sdu]
|
||||||
map_hash = self.get_map_hash(data)
|
map_hash = self.get_map_hash(part_data)
|
||||||
|
|
||||||
if map_hash in collision_guard_list:
|
if map_hash in collision_guard_list:
|
||||||
RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
@@ -464,7 +460,7 @@ class Resource:
|
|||||||
if len(collision_guard_list) > ResourceAdvertisement.COLLISION_GUARD_SIZE:
|
if len(collision_guard_list) > ResourceAdvertisement.COLLISION_GUARD_SIZE:
|
||||||
collision_guard_list.pop(0)
|
collision_guard_list.pop(0)
|
||||||
|
|
||||||
part = RNS.Packet(link, data, context=RNS.Packet.RESOURCE)
|
part = RNS.Packet(link, part_data, context=RNS.Packet.RESOURCE)
|
||||||
part.pack()
|
part.pack()
|
||||||
part.map_hash = map_hash
|
part.map_hash = map_hash
|
||||||
|
|
||||||
@@ -482,12 +478,12 @@ class Resource:
|
|||||||
|
|
||||||
def hashmap_update_packet(self, plaintext):
|
def hashmap_update_packet(self, plaintext):
|
||||||
if not self.status == Resource.FAILED:
|
if not self.status == Resource.FAILED:
|
||||||
self.last_activity = time.time()
|
if self.waiting_for_hmu:
|
||||||
self.retries_left = self.max_retries
|
self.last_activity = time.time()
|
||||||
|
self.retries_left = self.max_retries
|
||||||
update = umsgpack.unpackb(plaintext[RNS.Identity.HASHLENGTH//8:])
|
|
||||||
self.hashmap_update(update[0], update[1])
|
|
||||||
|
|
||||||
|
update = umsgpack.unpackb(plaintext[RNS.Identity.HASHLENGTH//8:])
|
||||||
|
self.hashmap_update(update[0], update[1])
|
||||||
|
|
||||||
def hashmap_update(self, segment, hashmap):
|
def hashmap_update(self, segment, hashmap):
|
||||||
if not self.status == Resource.FAILED:
|
if not self.status == Resource.FAILED:
|
||||||
@@ -495,12 +491,16 @@ class Resource:
|
|||||||
seg_len = ResourceAdvertisement.HASHMAP_MAX_LEN
|
seg_len = ResourceAdvertisement.HASHMAP_MAX_LEN
|
||||||
hashes = len(hashmap)//Resource.MAPHASH_LEN
|
hashes = len(hashmap)//Resource.MAPHASH_LEN
|
||||||
for i in range(0,hashes):
|
for i in range(0,hashes):
|
||||||
if self.hashmap[i+segment*seg_len] == None:
|
if self.hashmap[i+segment*seg_len] == None: self.hashmap_height += 1
|
||||||
self.hashmap_height += 1
|
|
||||||
self.hashmap[i+segment*seg_len] = hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
|
self.hashmap[i+segment*seg_len] = hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
|
||||||
|
|
||||||
self.waiting_for_hmu = False
|
if hashes < 1:
|
||||||
self.request_next()
|
RNS.log("Invalid HMU received, cancelling transfer", RNS.LOG_ERROR)
|
||||||
|
self.cancel()
|
||||||
|
|
||||||
|
else:
|
||||||
|
self.waiting_for_hmu = False
|
||||||
|
self.request_next()
|
||||||
|
|
||||||
def get_map_hash(self, data):
|
def get_map_hash(self, data):
|
||||||
return RNS.Identity.full_hash(data+self.random_hash)[:Resource.MAPHASH_LEN]
|
return RNS.Identity.full_hash(data+self.random_hash)[:Resource.MAPHASH_LEN]
|
||||||
@@ -517,6 +517,14 @@ class Resource:
|
|||||||
prepare_thread = threading.Thread(target=self.__prepare_next_segment, daemon=True)
|
prepare_thread = threading.Thread(target=self.__prepare_next_segment, daemon=True)
|
||||||
prepare_thread.start()
|
prepare_thread.start()
|
||||||
|
|
||||||
|
def ensure_link(self):
|
||||||
|
if not self.link or self.link.status != RNS.Link.ACTIVE:
|
||||||
|
RNS.log(f"Invalid link state for {self}, aborting transfer", RNS.LOG_VERBOSE)
|
||||||
|
try: self.cancel()
|
||||||
|
except Exception as e: RNS.log(f"Error while cancelling resource on link-state abort: {e}", RNS.LOG_ERROR)
|
||||||
|
return False
|
||||||
|
else: return True
|
||||||
|
|
||||||
def __advertise_job(self):
|
def __advertise_job(self):
|
||||||
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
|
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
|
||||||
while not self.link.ready_for_new_resource():
|
while not self.link.ready_for_new_resource():
|
||||||
@@ -524,6 +532,7 @@ class Resource:
|
|||||||
sleep(0.25)
|
sleep(0.25)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if not self.ensure_link(): return
|
||||||
self.advertisement_packet.send()
|
self.advertisement_packet.send()
|
||||||
self.last_activity = time.time()
|
self.last_activity = time.time()
|
||||||
self.started_transferring = self.last_activity
|
self.started_transferring = self.last_activity
|
||||||
@@ -541,18 +550,13 @@ class Resource:
|
|||||||
self.watchdog_job()
|
self.watchdog_job()
|
||||||
|
|
||||||
def update_eifr(self):
|
def update_eifr(self):
|
||||||
if self.rtt == None:
|
if self.rtt == None: rtt = self.link.rtt
|
||||||
rtt = self.link.rtt
|
else: rtt = self.rtt
|
||||||
else:
|
|
||||||
rtt = self.rtt
|
|
||||||
|
|
||||||
if self.req_data_rtt_rate != 0:
|
if self.req_data_rtt_rate != 0: expected_inflight_rate = self.req_data_rtt_rate*8
|
||||||
expected_inflight_rate = self.req_data_rtt_rate*8
|
|
||||||
else:
|
else:
|
||||||
if self.previous_eifr != None:
|
if self.previous_eifr != None: expected_inflight_rate = self.previous_eifr
|
||||||
expected_inflight_rate = self.previous_eifr
|
else: expected_inflight_rate = self.link.establishment_cost*8 / rtt
|
||||||
else:
|
|
||||||
expected_inflight_rate = self.link.establishment_cost*8 / rtt
|
|
||||||
|
|
||||||
self.eifr = expected_inflight_rate
|
self.eifr = expected_inflight_rate
|
||||||
if self.link: self.link.expected_rate = self.eifr
|
if self.link: self.link.expected_rate = self.eifr
|
||||||
@@ -566,8 +570,7 @@ class Resource:
|
|||||||
this_job_id = self.__watchdog_job_id
|
this_job_id = self.__watchdog_job_id
|
||||||
|
|
||||||
while self.status < Resource.ASSEMBLING and this_job_id == self.__watchdog_job_id:
|
while self.status < Resource.ASSEMBLING and this_job_id == self.__watchdog_job_id:
|
||||||
while self.watchdog_lock:
|
while self.watchdog_lock: sleep(0.025)
|
||||||
sleep(0.025)
|
|
||||||
|
|
||||||
sleep_time = None
|
sleep_time = None
|
||||||
if self.status == Resource.ADVERTISED:
|
if self.status == Resource.ADVERTISED:
|
||||||
@@ -581,6 +584,7 @@ class Resource:
|
|||||||
try:
|
try:
|
||||||
RNS.log("No part requests received, retrying resource advertisement...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
RNS.log("No part requests received, retrying resource advertisement...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
self.retries_left -= 1
|
self.retries_left -= 1
|
||||||
|
if not self.ensure_link(): return
|
||||||
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
|
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
|
||||||
self.advertisement_packet.send()
|
self.advertisement_packet.send()
|
||||||
self.last_activity = time.time()
|
self.last_activity = time.time()
|
||||||
@@ -657,13 +661,13 @@ class Resource:
|
|||||||
self.last_part_sent = time.time()
|
self.last_part_sent = time.time()
|
||||||
sleep_time = 0.001
|
sleep_time = 0.001
|
||||||
|
|
||||||
elif self.status == Resource.REJECTED:
|
elif self.status >= Resource.ASSEMBLING:
|
||||||
sleep_time = 0.001
|
sleep_time = 0.001
|
||||||
|
|
||||||
if sleep_time == 0:
|
if sleep_time == 0:
|
||||||
RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||||
if sleep_time == None or sleep_time < 0:
|
if sleep_time == None or sleep_time < 0:
|
||||||
RNS.log("Timing error, cancelling resource transfer.", RNS.LOG_ERROR)
|
RNS.log(f"Timing error ({sleep_time}/{self.status}), cancelling resource transfer.", RNS.LOG_ERROR)
|
||||||
self.cancel()
|
self.cancel()
|
||||||
|
|
||||||
if sleep_time != None:
|
if sleep_time != None:
|
||||||
@@ -754,6 +758,7 @@ class Resource:
|
|||||||
try:
|
try:
|
||||||
proof = RNS.Identity.full_hash(self.data+self.hash)
|
proof = RNS.Identity.full_hash(self.data+self.hash)
|
||||||
proof_data = self.hash+proof
|
proof_data = self.hash+proof
|
||||||
|
if not self.ensure_link(): return
|
||||||
proof_packet = RNS.Packet(self.link, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.RESOURCE_PRF)
|
proof_packet = RNS.Packet(self.link, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.RESOURCE_PRF)
|
||||||
proof_packet.send()
|
proof_packet.send()
|
||||||
RNS.Transport.cache(proof_packet, force_cache=True)
|
RNS.Transport.cache(proof_packet, force_cache=True)
|
||||||
@@ -776,8 +781,8 @@ class Resource:
|
|||||||
advertise = False,
|
advertise = False,
|
||||||
auto_compress = self.auto_compress_option,
|
auto_compress = self.auto_compress_option,
|
||||||
sent_metadata_size = self.metadata_size)
|
sent_metadata_size = self.metadata_size)
|
||||||
if self.__progress_callback:
|
|
||||||
self.next_segment.progress_callback(self.__progress_callback)
|
if self.__progress_callback: self.next_segment.progress_callback(self.__progress_callback)
|
||||||
|
|
||||||
def validate_proof(self, proof_data):
|
def validate_proof(self, proof_data):
|
||||||
if not self.status == Resource.FAILED:
|
if not self.status == Resource.FAILED:
|
||||||
@@ -860,9 +865,9 @@ class Resource:
|
|||||||
part_data = packet.data
|
part_data = packet.data
|
||||||
part_hash = self.get_map_hash(part_data)
|
part_hash = self.get_map_hash(part_data)
|
||||||
|
|
||||||
consecutive_index = self.consecutive_completed_height if self.consecutive_completed_height >= 0 else 0
|
search_start = self.consecutive_completed_height+1
|
||||||
i = consecutive_index
|
i = search_start
|
||||||
for map_hash in self.hashmap[consecutive_index:consecutive_index+self.window]:
|
for map_hash in self.hashmap[search_start:search_start+self.window]:
|
||||||
if map_hash == part_hash:
|
if map_hash == part_hash:
|
||||||
if self.parts[i] == None:
|
if self.parts[i] == None:
|
||||||
|
|
||||||
@@ -873,9 +878,6 @@ class Resource:
|
|||||||
self.outstanding_parts -= 1
|
self.outstanding_parts -= 1
|
||||||
|
|
||||||
# Update consecutive completed pointer
|
# Update consecutive completed pointer
|
||||||
if i == self.consecutive_completed_height + 1:
|
|
||||||
self.consecutive_completed_height = i
|
|
||||||
|
|
||||||
cp = self.consecutive_completed_height + 1
|
cp = self.consecutive_completed_height + 1
|
||||||
while cp < len(self.parts) and self.parts[cp] != None:
|
while cp < len(self.parts) and self.parts[cp] != None:
|
||||||
self.consecutive_completed_height = cp
|
self.consecutive_completed_height = cp
|
||||||
@@ -966,6 +968,7 @@ class Resource:
|
|||||||
request_packet = RNS.Packet(self.link, request_data, context = RNS.Packet.RESOURCE_REQ)
|
request_packet = RNS.Packet(self.link, request_data, context = RNS.Packet.RESOURCE_REQ)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if not self.ensure_link(): return
|
||||||
request_packet.send()
|
request_packet.send()
|
||||||
self.last_activity = time.time()
|
self.last_activity = time.time()
|
||||||
self.req_sent = self.last_activity
|
self.req_sent = self.last_activity
|
||||||
@@ -1010,11 +1013,11 @@ class Resource:
|
|||||||
|
|
||||||
for part in requested_parts:
|
for part in requested_parts:
|
||||||
try:
|
try:
|
||||||
|
if not self.ensure_link(): return
|
||||||
if not part.sent:
|
if not part.sent:
|
||||||
part.send()
|
part.send()
|
||||||
self.sent_parts += 1
|
self.sent_parts += 1
|
||||||
else:
|
else: part.resend()
|
||||||
part.resend()
|
|
||||||
|
|
||||||
self.last_activity = time.time()
|
self.last_activity = time.time()
|
||||||
self.last_part_sent = self.last_activity
|
self.last_part_sent = self.last_activity
|
||||||
@@ -1032,8 +1035,7 @@ class Resource:
|
|||||||
search_end = self.receiver_min_consecutive_height+ResourceAdvertisement.COLLISION_GUARD_SIZE
|
search_end = self.receiver_min_consecutive_height+ResourceAdvertisement.COLLISION_GUARD_SIZE
|
||||||
for part in self.parts[search_start:search_end]:
|
for part in self.parts[search_start:search_end]:
|
||||||
part_index += 1
|
part_index += 1
|
||||||
if part.map_hash == last_map_hash:
|
if part.map_hash == last_map_hash: break
|
||||||
break
|
|
||||||
|
|
||||||
self.receiver_min_consecutive_height = max(part_index-1-Resource.WINDOW_MAX, 0)
|
self.receiver_min_consecutive_height = max(part_index-1-Resource.WINDOW_MAX, 0)
|
||||||
|
|
||||||
@@ -1041,10 +1043,8 @@ class Resource:
|
|||||||
RNS.log("Resource sequencing error, cancelling transfer!", RNS.LOG_ERROR)
|
RNS.log("Resource sequencing error, cancelling transfer!", RNS.LOG_ERROR)
|
||||||
self.cancel()
|
self.cancel()
|
||||||
return
|
return
|
||||||
else:
|
else: segment = part_index // ResourceAdvertisement.HASHMAP_MAX_LEN
|
||||||
segment = part_index // ResourceAdvertisement.HASHMAP_MAX_LEN
|
|
||||||
|
|
||||||
|
|
||||||
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
|
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
|
||||||
hashmap_end = min((segment+1)*ResourceAdvertisement.HASHMAP_MAX_LEN, len(self.parts))
|
hashmap_end = min((segment+1)*ResourceAdvertisement.HASHMAP_MAX_LEN, len(self.parts))
|
||||||
|
|
||||||
@@ -1052,10 +1052,16 @@ class Resource:
|
|||||||
for i in range(hashmap_start,hashmap_end):
|
for i in range(hashmap_start,hashmap_end):
|
||||||
hashmap += self.hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
|
hashmap += self.hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
|
||||||
|
|
||||||
|
if not hashmap:
|
||||||
|
RNS.log("Resource HMU error, cancelling transfer!", RNS.LOG_ERROR)
|
||||||
|
self.cancel()
|
||||||
|
return
|
||||||
|
|
||||||
hmu = self.hash+umsgpack.packb([segment, hashmap])
|
hmu = self.hash+umsgpack.packb([segment, hashmap])
|
||||||
hmu_packet = RNS.Packet(self.link, hmu, context = RNS.Packet.RESOURCE_HMU)
|
hmu_packet = RNS.Packet(self.link, hmu, context = RNS.Packet.RESOURCE_HMU)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if not self.ensure_link(): return
|
||||||
hmu_packet.send()
|
hmu_packet.send()
|
||||||
self.last_activity = time.time()
|
self.last_activity = time.time()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -1090,10 +1096,14 @@ class Resource:
|
|||||||
try:
|
try:
|
||||||
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_ICL)
|
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_ICL)
|
||||||
cancel_packet.send()
|
cancel_packet.send()
|
||||||
except Exception as e:
|
except Exception as e: RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
|
||||||
self.link.cancel_outgoing_resource(self)
|
self.link.cancel_outgoing_resource(self)
|
||||||
else:
|
else:
|
||||||
|
if self.link.status == RNS.Link.ACTIVE:
|
||||||
|
try:
|
||||||
|
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_RCL)
|
||||||
|
cancel_packet.send()
|
||||||
|
except Exception as e: RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||||
self.link.cancel_incoming_resource(self)
|
self.link.cancel_incoming_resource(self)
|
||||||
|
|
||||||
if self.callback != None:
|
if self.callback != None:
|
||||||
@@ -1241,40 +1251,30 @@ class ResourceAdvertisement:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def is_request(advertisement_packet):
|
def is_request(advertisement_packet):
|
||||||
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
||||||
if adv.q != None and adv.u:
|
if adv.q != None and adv.u: return True
|
||||||
return True
|
else: return False
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def is_response(advertisement_packet):
|
def is_response(advertisement_packet):
|
||||||
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
||||||
|
if adv.q != None and adv.p: return True
|
||||||
if adv.q != None and adv.p:
|
else: return False
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def read_request_id(advertisement_packet):
|
def read_request_id(advertisement_packet):
|
||||||
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
||||||
return adv.q
|
return adv.q
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def read_transfer_size(advertisement_packet):
|
def read_transfer_size(advertisement_packet):
|
||||||
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
||||||
return adv.t
|
return adv.t
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def read_size(advertisement_packet):
|
def read_size(advertisement_packet):
|
||||||
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
|
||||||
return adv.d
|
return adv.d
|
||||||
|
|
||||||
|
|
||||||
def __init__(self, resource=None, request_id=None, is_response=False):
|
def __init__(self, resource=None, request_id=None, is_response=False):
|
||||||
self.link = None
|
self.link = None
|
||||||
if resource != None:
|
if resource != None:
|
||||||
@@ -1306,29 +1306,14 @@ class ResourceAdvertisement:
|
|||||||
# Flags
|
# Flags
|
||||||
self.f = 0x00 | self.x << 5 | self.p << 4 | self.u << 3 | self.s << 2 | self.c << 1 | self.e
|
self.f = 0x00 | self.x << 5 | self.p << 4 | self.u << 3 | self.s << 2 | self.c << 1 | self.e
|
||||||
|
|
||||||
def get_transfer_size(self):
|
def get_transfer_size(self): return self.t
|
||||||
return self.t
|
def get_data_size(self): return self.d
|
||||||
|
def get_parts(self): return self.n
|
||||||
def get_data_size(self):
|
def get_segments(self): return self.l
|
||||||
return self.d
|
def get_hash(self): return self.h
|
||||||
|
def is_compressed(self): return self.c
|
||||||
def get_parts(self):
|
def has_metadata(self): return self.x
|
||||||
return self.n
|
def get_link(self): return self.link
|
||||||
|
|
||||||
def get_segments(self):
|
|
||||||
return self.l
|
|
||||||
|
|
||||||
def get_hash(self):
|
|
||||||
return self.h
|
|
||||||
|
|
||||||
def is_compressed(self):
|
|
||||||
return self.c
|
|
||||||
|
|
||||||
def has_metadata(self):
|
|
||||||
return self.x
|
|
||||||
|
|
||||||
def get_link(self):
|
|
||||||
return self.link
|
|
||||||
|
|
||||||
def pack(self, segment=0):
|
def pack(self, segment=0):
|
||||||
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
|
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
|
||||||
@@ -1338,23 +1323,20 @@ class ResourceAdvertisement:
|
|||||||
for i in range(hashmap_start,hashmap_end):
|
for i in range(hashmap_start,hashmap_end):
|
||||||
hashmap += self.m[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
|
hashmap += self.m[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
|
||||||
|
|
||||||
dictionary = {
|
dictionary = { "t": self.t, # Transfer size
|
||||||
"t": self.t, # Transfer size
|
"d": self.d, # Data size
|
||||||
"d": self.d, # Data size
|
"n": self.n, # Number of parts
|
||||||
"n": self.n, # Number of parts
|
"h": self.h, # Resource hash
|
||||||
"h": self.h, # Resource hash
|
"r": self.r, # Resource random hash
|
||||||
"r": self.r, # Resource random hash
|
"o": self.o, # Original hash
|
||||||
"o": self.o, # Original hash
|
"i": self.i, # Segment index
|
||||||
"i": self.i, # Segment index
|
"l": self.l, # Total segments
|
||||||
"l": self.l, # Total segments
|
"q": self.q, # Request ID
|
||||||
"q": self.q, # Request ID
|
"f": self.f, # Resource flags
|
||||||
"f": self.f, # Resource flags
|
"m": hashmap }
|
||||||
"m": hashmap
|
|
||||||
}
|
|
||||||
|
|
||||||
return umsgpack.packb(dictionary)
|
return umsgpack.packb(dictionary)
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def unpack(data):
|
def unpack(data):
|
||||||
dictionary = umsgpack.unpackb(data)
|
dictionary = umsgpack.unpackb(data)
|
||||||
@@ -1378,4 +1360,6 @@ class ResourceAdvertisement:
|
|||||||
adv.p = True if ((adv.f >> 4) & 0x01) == 0x01 else False
|
adv.p = True if ((adv.f >> 4) & 0x01) == 0x01 else False
|
||||||
adv.x = True if ((adv.f >> 5) & 0x01) == 0x01 else False
|
adv.x = True if ((adv.f >> 5) & 0x01) == 0x01 else False
|
||||||
|
|
||||||
|
if adv.t > Resource.MAX_EFFICIENT_SIZE*3: raise ValueError("Invalid transfer size")
|
||||||
|
|
||||||
return adv
|
return adv
|
||||||
+277
-31
@@ -140,6 +140,9 @@ class Reticulum:
|
|||||||
# TODO: Let Reticulum somehow continously build a map of per-hop
|
# TODO: Let Reticulum somehow continously build a map of per-hop
|
||||||
# latencies and use this map for global timeout calculation.
|
# latencies and use this map for global timeout calculation.
|
||||||
DEFAULT_PER_HOP_TIMEOUT = 6
|
DEFAULT_PER_HOP_TIMEOUT = 6
|
||||||
|
"""
|
||||||
|
The default per-hop timeout value used in various timeout calculations.
|
||||||
|
"""
|
||||||
|
|
||||||
# Length of truncated hashes in bits.
|
# Length of truncated hashes in bits.
|
||||||
TRUNCATED_HASHLENGTH = 128
|
TRUNCATED_HASHLENGTH = 128
|
||||||
@@ -207,7 +210,7 @@ class Reticulum:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_instance():
|
def get_instance():
|
||||||
"""
|
"""
|
||||||
Return the currently running Reticulum instance
|
Returns the currently running Reticulum instance.
|
||||||
"""
|
"""
|
||||||
return Reticulum.__instance
|
return Reticulum.__instance
|
||||||
|
|
||||||
@@ -261,11 +264,15 @@ class Reticulum:
|
|||||||
Reticulum.__discovery_enabled = False
|
Reticulum.__discovery_enabled = False
|
||||||
Reticulum.__discover_interfaces = False
|
Reticulum.__discover_interfaces = False
|
||||||
Reticulum.__autoconnect_discovered_interfaces = False
|
Reticulum.__autoconnect_discovered_interfaces = False
|
||||||
|
Reticulum.__autoconnect_interface_mode = None
|
||||||
|
Reticulum.__autoconnect_interface_gravity = None
|
||||||
|
Reticulum.__autoconnect_announces_to_internal = None
|
||||||
Reticulum.__required_discovery_value = None
|
Reticulum.__required_discovery_value = None
|
||||||
Reticulum.__publish_blackhole = False
|
Reticulum.__publish_blackhole = False
|
||||||
Reticulum.__blackhole_update_interval = RNS.Discovery.BlackholeUpdater.UPDATE_INTERVAL
|
Reticulum.__blackhole_update_interval = RNS.Discovery.BlackholeUpdater.UPDATE_INTERVAL
|
||||||
Reticulum.__blackhole_sources = []
|
Reticulum.__blackhole_sources = []
|
||||||
Reticulum.__interface_sources = []
|
Reticulum.__interface_sources = []
|
||||||
|
Reticulum.__default_gravity = None
|
||||||
Reticulum.__default_ar_target = None
|
Reticulum.__default_ar_target = None
|
||||||
Reticulum.__default_ar_penalty = None
|
Reticulum.__default_ar_penalty = None
|
||||||
Reticulum.__default_ar_grace = None
|
Reticulum.__default_ar_grace = None
|
||||||
@@ -280,6 +287,10 @@ class Reticulum:
|
|||||||
Reticulum.__ic_held_release_interval = None
|
Reticulum.__ic_held_release_interval = None
|
||||||
Reticulum.__ec_pr_freq = None
|
Reticulum.__ec_pr_freq = None
|
||||||
Reticulum.__egress_control = None
|
Reticulum.__egress_control = None
|
||||||
|
Reticulum.__inbound_data_queue_length = None
|
||||||
|
Reticulum.__inbound_announce_queue_length = None
|
||||||
|
Reticulum.__inbound_pr_queue_length = None
|
||||||
|
Reticulum.__inbound_il_queue_length = None
|
||||||
|
|
||||||
Reticulum.panic_on_interface_error = False
|
Reticulum.panic_on_interface_error = False
|
||||||
|
|
||||||
@@ -455,7 +466,7 @@ class Reticulum:
|
|||||||
RNS.loglevel = int(value)
|
RNS.loglevel = int(value)
|
||||||
if self.requested_verbosity != None: RNS.loglevel += self.requested_verbosity
|
if self.requested_verbosity != None: RNS.loglevel += self.requested_verbosity
|
||||||
if RNS.loglevel < 0: RNS.loglevel = 0
|
if RNS.loglevel < 0: RNS.loglevel = 0
|
||||||
if RNS.loglevel > 7: RNS.loglevel = 7
|
if RNS.loglevel > 8: RNS.loglevel = 8
|
||||||
elif option == "logtimestamps":
|
elif option == "logtimestamps":
|
||||||
value = self.config["logging"].as_bool(option)
|
value = self.config["logging"].as_bool(option)
|
||||||
RNS.logtimestamps = bool(value)
|
RNS.logtimestamps = bool(value)
|
||||||
@@ -532,7 +543,8 @@ class Reticulum:
|
|||||||
|
|
||||||
if option == "link_mtu_discovery":
|
if option == "link_mtu_discovery":
|
||||||
v = self.config["reticulum"].as_bool(option)
|
v = self.config["reticulum"].as_bool(option)
|
||||||
if v == True: Reticulum.__link_mtu_discovery = True
|
if v == True: Reticulum.__link_mtu_discovery = True
|
||||||
|
elif v == False: Reticulum.__link_mtu_discovery = False
|
||||||
|
|
||||||
if option == "enable_remote_management":
|
if option == "enable_remote_management":
|
||||||
v = self.config["reticulum"].as_bool(option)
|
v = self.config["reticulum"].as_bool(option)
|
||||||
@@ -566,6 +578,10 @@ class Reticulum:
|
|||||||
if v == True: Reticulum.__use_implicit_proof = True
|
if v == True: Reticulum.__use_implicit_proof = True
|
||||||
if v == False: Reticulum.__use_implicit_proof = False
|
if v == False: Reticulum.__use_implicit_proof = False
|
||||||
|
|
||||||
|
if option == "default_gravity":
|
||||||
|
v = self.config["reticulum"].as_int(option)
|
||||||
|
Reticulum.__default_gravity = v
|
||||||
|
|
||||||
if option == "discover_interfaces":
|
if option == "discover_interfaces":
|
||||||
v = self.config["reticulum"].as_bool(option)
|
v = self.config["reticulum"].as_bool(option)
|
||||||
if v == True: Reticulum.__discover_interfaces = True
|
if v == True: Reticulum.__discover_interfaces = True
|
||||||
@@ -603,11 +619,34 @@ class Reticulum:
|
|||||||
try: source_identity_hash = bytes.fromhex(hexhash)
|
try: source_identity_hash = bytes.fromhex(hexhash)
|
||||||
except Exception as e: raise ValueError(f"Invalid identity hash for interface discovery source: {hexhash}")
|
except Exception as e: raise ValueError(f"Invalid identity hash for interface discovery source: {hexhash}")
|
||||||
if not source_identity_hash in Reticulum.__interface_sources: Reticulum.__interface_sources.append(source_identity_hash)
|
if not source_identity_hash in Reticulum.__interface_sources: Reticulum.__interface_sources.append(source_identity_hash)
|
||||||
|
|
||||||
if option == "autoconnect_discovered_interfaces":
|
if option == "autoconnect_discovered_interfaces":
|
||||||
v = self.config["reticulum"].as_int(option)
|
v = self.config["reticulum"].as_int(option)
|
||||||
if v > 0: Reticulum.__autoconnect_discovered_interfaces = v
|
if v > 0: Reticulum.__autoconnect_discovered_interfaces = v
|
||||||
|
|
||||||
|
if option == "autoconnect_interface_mode":
|
||||||
|
v = None; dmode = str(self.config["reticulum"]["autoconnect_interface_mode"]).lower()
|
||||||
|
if dmode == "full": v = Interface.Interface.MODE_FULL
|
||||||
|
elif dmode == "access_point": v = Interface.Interface.MODE_ACCESS_POINT
|
||||||
|
elif dmode == "accesspoint": v = Interface.Interface.MODE_ACCESS_POINT
|
||||||
|
elif dmode == "ap": v = Interface.Interface.MODE_ACCESS_POINT
|
||||||
|
elif dmode == "pointtopoint": v = Interface.Interface.MODE_POINT_TO_POINT
|
||||||
|
elif dmode == "ptp": v = Interface.Interface.MODE_POINT_TO_POINT
|
||||||
|
elif dmode == "roaming": v = Interface.Interface.MODE_ROAMING
|
||||||
|
elif dmode == "boundary": v = Interface.Interface.MODE_BOUNDARY
|
||||||
|
elif dmode == "gateway": v = Interface.Interface.MODE_GATEWAY
|
||||||
|
elif dmode == "gw": v = Interface.Interface.MODE_GATEWAY
|
||||||
|
elif dmode == "internal": v = Interface.Interface.MODE_INTERNAL
|
||||||
|
if v != None: Reticulum.__autoconnect_interface_mode = v
|
||||||
|
|
||||||
|
if option == "autoconnect_interface_gravity":
|
||||||
|
v = self.config["reticulum"].as_int(option)
|
||||||
|
Reticulum.__autoconnect_interface_gravity = v
|
||||||
|
|
||||||
|
if option == "autoconnect_announces_to_internal":
|
||||||
|
v = self.config["reticulum"].as_bool(option)
|
||||||
|
if v > 0: Reticulum.__autoconnect_announces_to_internal = v
|
||||||
|
|
||||||
if option == "default_ar_target":
|
if option == "default_ar_target":
|
||||||
v = self.config["reticulum"].as_int(option)
|
v = self.config["reticulum"].as_int(option)
|
||||||
if v == 0: Reticulum.__default_ar_target = None
|
if v == 0: Reticulum.__default_ar_target = None
|
||||||
@@ -665,6 +704,22 @@ class Reticulum:
|
|||||||
v = self.config["reticulum"].as_float(option)
|
v = self.config["reticulum"].as_float(option)
|
||||||
if v >= 0: Reticulum.__ic_held_release_interval = v
|
if v >= 0: Reticulum.__ic_held_release_interval = v
|
||||||
|
|
||||||
|
if option == "qlen_in_data":
|
||||||
|
v = self.config["reticulum"].as_int(option)
|
||||||
|
if v > 0: Reticulum.__inbound_data_queue_length = v
|
||||||
|
|
||||||
|
if option == "qlen_in_announce":
|
||||||
|
v = self.config["reticulum"].as_int(option)
|
||||||
|
if v > 0: Reticulum.__inbound_announce_queue_length = v
|
||||||
|
|
||||||
|
if option == "qlen_in_pr":
|
||||||
|
v = self.config["reticulum"].as_int(option)
|
||||||
|
if v > 0: Reticulum.__inbound_pr_queue_length = v
|
||||||
|
|
||||||
|
if option == "qlen_in_il":
|
||||||
|
v = self.config["reticulum"].as_int(option)
|
||||||
|
if v > 0: Reticulum.__inbound_il_queue_length = v
|
||||||
|
|
||||||
|
|
||||||
if RNS.compiled: RNS.log("Reticulum running in compiled mode", RNS.LOG_DEBUG)
|
if RNS.compiled: RNS.log("Reticulum running in compiled mode", RNS.LOG_DEBUG)
|
||||||
else: RNS.log("Reticulum running in interpreted mode", RNS.LOG_DEBUG)
|
else: RNS.log("Reticulum running in interpreted mode", RNS.LOG_DEBUG)
|
||||||
@@ -737,6 +792,9 @@ class Reticulum:
|
|||||||
elif c["mode"] == "internal":
|
elif c["mode"] == "internal":
|
||||||
interface_mode = Interface.Interface.MODE_INTERNAL
|
interface_mode = Interface.Interface.MODE_INTERNAL
|
||||||
|
|
||||||
|
gravity = self._default_gravity()
|
||||||
|
if "gravity" in c: gravity = c.as_int("gravity")
|
||||||
|
|
||||||
ifac_size = None
|
ifac_size = None
|
||||||
if "ifac_size" in c:
|
if "ifac_size" in c:
|
||||||
if c.as_int("ifac_size") >= Reticulum.IFAC_MIN_SIZE*8: ifac_size = c.as_int("ifac_size")//8
|
if c.as_int("ifac_size") >= Reticulum.IFAC_MIN_SIZE*8: ifac_size = c.as_int("ifac_size")//8
|
||||||
@@ -811,6 +869,9 @@ class Reticulum:
|
|||||||
announces_from_internal = True
|
announces_from_internal = True
|
||||||
if "announces_from_internal" in c: announces_from_internal = c.as_bool("announces_from_internal")
|
if "announces_from_internal" in c: announces_from_internal = c.as_bool("announces_from_internal")
|
||||||
|
|
||||||
|
announces_to_internal = None
|
||||||
|
if "announces_to_internal" in c: announces_to_internal = c.as_bool("announces_to_internal")
|
||||||
|
|
||||||
ignore_config_warnings = False
|
ignore_config_warnings = False
|
||||||
if "ignore_config_warnings" in c: ignore_config_warnings = c.as_bool("ignore_config_warnings")
|
if "ignore_config_warnings" in c: ignore_config_warnings = c.as_bool("ignore_config_warnings")
|
||||||
|
|
||||||
@@ -823,12 +884,14 @@ class Reticulum:
|
|||||||
discovery_announce_interval = None
|
discovery_announce_interval = None
|
||||||
discovery_stamp_value = None
|
discovery_stamp_value = None
|
||||||
discovery_name = None
|
discovery_name = None
|
||||||
|
discovery_lxmf_address = None
|
||||||
discovery_encrypt = False
|
discovery_encrypt = False
|
||||||
reachable_on = None
|
reachable_on = None
|
||||||
publish_ifac = False
|
publish_ifac = False
|
||||||
latitude = None
|
latitude = None
|
||||||
longitude = None
|
longitude = None
|
||||||
height = None
|
height = None
|
||||||
|
discovery_location = None
|
||||||
discovery_frequency = None
|
discovery_frequency = None
|
||||||
discovery_bandwidth = None
|
discovery_bandwidth = None
|
||||||
discovery_modulation = None
|
discovery_modulation = None
|
||||||
@@ -846,21 +909,27 @@ class Reticulum:
|
|||||||
if "discovery_encrypt" in c: discovery_encrypt = c.as_bool("discovery_encrypt")
|
if "discovery_encrypt" in c: discovery_encrypt = c.as_bool("discovery_encrypt")
|
||||||
if "reachable_on" in c: reachable_on = c["reachable_on"]
|
if "reachable_on" in c: reachable_on = c["reachable_on"]
|
||||||
if "publish_ifac" in c: publish_ifac = c.as_bool("publish_ifac")
|
if "publish_ifac" in c: publish_ifac = c.as_bool("publish_ifac")
|
||||||
|
if "location_cmd" in c: discovery_location = c["location_cmd"]
|
||||||
if "latitude" in c: latitude = c.as_float("latitude")
|
if "latitude" in c: latitude = c.as_float("latitude")
|
||||||
if "longitude" in c: longitude = c.as_float("longitude")
|
if "longitude" in c: longitude = c.as_float("longitude")
|
||||||
if "height" in c: height = c.as_float("height")
|
if "height" in c: height = c.as_float("height")
|
||||||
if "discovery_frequency" in c: discovery_frequency = c.as_int("discovery_frequency")
|
if "discovery_frequency" in c: discovery_frequency = c.as_int("discovery_frequency")
|
||||||
if "discovery_bandwidth" in c: discovery_bandwidth = c.as_int("discovery_bandwidth")
|
if "discovery_bandwidth" in c: discovery_bandwidth = c.as_int("discovery_bandwidth")
|
||||||
if "discovery_modulation" in c: discovery_modulation = c.as_int("discovery_modulation")
|
if "discovery_modulation" in c: discovery_modulation = c.as_int("discovery_modulation")
|
||||||
|
if "discovery_lxmf_address" in c:
|
||||||
|
if len(c["discovery_lxmf_address"]) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2:
|
||||||
|
try: discovery_lxmf_address = bytes.fromhex(c["discovery_lxmf_address"])
|
||||||
|
except: RNS.log(f"Invalid interface discovery LXMF address: {c['discovery_lxmf_address']}", RNS.LOG_ERROR)
|
||||||
|
else: RNS.log(f"Invalid length for interface discovery LXMF address: {c['discovery_lxmf_address']}", RNS.LOG_ERROR)
|
||||||
|
|
||||||
if not interface_mode in [Interface.Interface.MODE_GATEWAY, Interface.Interface.MODE_ACCESS_POINT]:
|
if not interface_mode in [Interface.Interface.MODE_GATEWAY, Interface.Interface.MODE_ACCESS_POINT, Interface.Interface.MODE_INTERNAL]:
|
||||||
if not ignore_config_warnings:
|
if not ignore_config_warnings:
|
||||||
if c["type"] in ["RNodeInterface", "RNodeMultiInterface"]:
|
if c["type"] in ["RNodeInterface", "RNodeMultiInterface"]:
|
||||||
interface_mode = Interface.Interface.MODE_ACCESS_POINT
|
interface_mode = Interface.Interface.MODE_ACCESS_POINT
|
||||||
RNS.log(f"Discovery enabled on interface {name} without gateway or AP mode. Auto-configured to AP mode.", RNS.LOG_NOTICE)
|
RNS.log(f"Discovery enabled on interface {name} without gateway, internal or AP mode. Auto-configured to AP mode.", RNS.LOG_NOTICE)
|
||||||
else:
|
else:
|
||||||
interface_mode = Interface.Interface.MODE_GATEWAY
|
interface_mode = Interface.Interface.MODE_GATEWAY
|
||||||
RNS.log(f"Discovery enabled on interface {name} without gateway or AP mode. Auto-configured to gateway mode.", RNS.LOG_NOTICE)
|
RNS.log(f"Discovery enabled on interface {name} without gateway, internal or AP mode. Auto-configured to gateway mode.", RNS.LOG_NOTICE)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
def interface_post_init(interface):
|
def interface_post_init(interface):
|
||||||
@@ -869,6 +938,7 @@ class Reticulum:
|
|||||||
else: interface.OUT = True
|
else: interface.OUT = True
|
||||||
|
|
||||||
interface.mode = interface_mode
|
interface.mode = interface_mode
|
||||||
|
interface.gravity = gravity
|
||||||
interface.announce_cap = announce_cap
|
interface.announce_cap = announce_cap
|
||||||
interface.bootstrap_only = bootstrap_only
|
interface.bootstrap_only = bootstrap_only
|
||||||
if configured_bitrate: interface.bitrate = configured_bitrate
|
if configured_bitrate: interface.bitrate = configured_bitrate
|
||||||
@@ -882,8 +952,10 @@ class Reticulum:
|
|||||||
interface.discovery_publish_ifac = publish_ifac
|
interface.discovery_publish_ifac = publish_ifac
|
||||||
interface.reachable_on = reachable_on
|
interface.reachable_on = reachable_on
|
||||||
interface.discovery_name = discovery_name
|
interface.discovery_name = discovery_name
|
||||||
|
interface.discovery_lxmf_address = discovery_lxmf_address
|
||||||
interface.discovery_encrypt = discovery_encrypt
|
interface.discovery_encrypt = discovery_encrypt
|
||||||
interface.discovery_stamp_value = discovery_stamp_value
|
interface.discovery_stamp_value = discovery_stamp_value
|
||||||
|
interface.discovery_location = discovery_location
|
||||||
interface.discovery_latitude = latitude
|
interface.discovery_latitude = latitude
|
||||||
interface.discovery_longitude = longitude
|
interface.discovery_longitude = longitude
|
||||||
interface.discovery_height = height
|
interface.discovery_height = height
|
||||||
@@ -893,6 +965,7 @@ class Reticulum:
|
|||||||
|
|
||||||
interface.recursive_prs = recursive_prs
|
interface.recursive_prs = recursive_prs
|
||||||
interface.announces_from_internal = announces_from_internal
|
interface.announces_from_internal = announces_from_internal
|
||||||
|
interface.announces_to_internal = announces_to_internal
|
||||||
interface.announce_rate_target = announce_rate_target
|
interface.announce_rate_target = announce_rate_target
|
||||||
interface.announce_rate_grace = announce_rate_grace
|
interface.announce_rate_grace = announce_rate_grace
|
||||||
interface.announce_rate_penalty = announce_rate_penalty
|
interface.announce_rate_penalty = announce_rate_penalty
|
||||||
@@ -1047,15 +1120,17 @@ class Reticulum:
|
|||||||
RNS.trace_exception(e)
|
RNS.trace_exception(e)
|
||||||
RNS.panic()
|
RNS.panic()
|
||||||
|
|
||||||
def _add_interface(self, interface, mode = None, configured_bitrate=None, ifac_size=None, ifac_netname=None, ifac_netkey=None,
|
def _add_interface(self, interface, mode=None, gravity=None, configured_bitrate=None, ifac_size=None, ifac_netname=None, ifac_netkey=None,
|
||||||
announce_cap=None, announce_rate_target=None, announce_rate_grace=None, announce_rate_penalty=None,
|
announce_cap=None, announce_rate_target=None, announce_rate_grace=None, announce_rate_penalty=None,
|
||||||
bootstrap_only=False, recursive_prs=False, announces_from_internal=True):
|
bootstrap_only=False, recursive_prs=False, announces_from_internal=True, announces_to_internal=None):
|
||||||
|
|
||||||
if not self.is_connected_to_shared_instance:
|
if not self.is_connected_to_shared_instance:
|
||||||
if interface != None and issubclass(type(interface), RNS.Interfaces.Interface.Interface):
|
if interface != None and issubclass(type(interface), RNS.Interfaces.Interface.Interface):
|
||||||
|
|
||||||
if mode == None: mode = Interface.Interface.MODE_FULL
|
if mode == None: mode = Interface.Interface.MODE_FULL
|
||||||
|
if gravity == None: gravity = self._default_gravity()
|
||||||
interface.mode = mode
|
interface.mode = mode
|
||||||
|
interface.gravity = gravity
|
||||||
interface.OUT = True
|
interface.OUT = True
|
||||||
|
|
||||||
if configured_bitrate: interface.bitrate = configured_bitrate
|
if configured_bitrate: interface.bitrate = configured_bitrate
|
||||||
@@ -1067,6 +1142,7 @@ class Reticulum:
|
|||||||
|
|
||||||
interface.recursive_prs = recursive_prs
|
interface.recursive_prs = recursive_prs
|
||||||
interface.announces_from_internal = announces_from_internal
|
interface.announces_from_internal = announces_from_internal
|
||||||
|
interface.announces_to_internal = announces_to_internal
|
||||||
interface.announce_cap = announce_cap if announce_cap != None else Reticulum.ANNOUNCE_CAP/100.0
|
interface.announce_cap = announce_cap if announce_cap != None else Reticulum.ANNOUNCE_CAP/100.0
|
||||||
interface.announce_rate_target = announce_rate_target
|
interface.announce_rate_target = announce_rate_target
|
||||||
interface.announce_rate_grace = announce_rate_grace
|
interface.announce_rate_grace = announce_rate_grace
|
||||||
@@ -1094,6 +1170,9 @@ class Reticulum:
|
|||||||
RNS.Transport.add_interface(interface)
|
RNS.Transport.add_interface(interface)
|
||||||
interface.final_init()
|
interface.final_init()
|
||||||
|
|
||||||
|
def _default_gravity(self):
|
||||||
|
return self.__default_gravity or RNS.Interfaces.Interface.Interface.DEFAULT_GRAVITY
|
||||||
|
|
||||||
def _default_ar_target(self):
|
def _default_ar_target(self):
|
||||||
return self.__default_ar_target or RNS.Interfaces.Interface.Interface.DEFAULT_AR_TARGET
|
return self.__default_ar_target or RNS.Interfaces.Interface.Interface.DEFAULT_AR_TARGET
|
||||||
|
|
||||||
@@ -1202,17 +1281,20 @@ class Reticulum:
|
|||||||
mh = call["max_hops"]
|
mh = call["max_hops"]
|
||||||
self.rpc_return(conn, self.get_path_table(max_hops=mh))
|
self.rpc_return(conn, self.get_path_table(max_hops=mh))
|
||||||
|
|
||||||
if path == "interface_stats": self.rpc_return(conn, self.get_interface_stats())
|
if path == "interface_stats": self.rpc_return(conn, self.get_interface_stats())
|
||||||
if path == "rate_table": self.rpc_return(conn, self.get_rate_table())
|
if path == "rate_table": self.rpc_return(conn, self.get_rate_table())
|
||||||
if path == "next_hop_if_name": self.rpc_return(conn, self.get_next_hop_if_name(call["destination_hash"]))
|
if path == "next_hop_if_name": self.rpc_return(conn, self.get_next_hop_if_name(call["destination_hash"]))
|
||||||
if path == "next_hop": self.rpc_return(conn, self.get_next_hop(call["destination_hash"]))
|
if path == "next_hop": self.rpc_return(conn, self.get_next_hop(call["destination_hash"]))
|
||||||
if path == "first_hop_timeout": self.rpc_return(conn, self.get_first_hop_timeout(call["destination_hash"]))
|
if path == "first_hop_timeout": self.rpc_return(conn, self.get_first_hop_timeout(call["destination_hash"]))
|
||||||
if path == "link_count": self.rpc_return(conn, self.get_link_count())
|
if path == "lowest_interface_bitrate": self.rpc_return(conn, self.get_lowest_interface_bitrate())
|
||||||
if path == "packet_rssi": self.rpc_return(conn, self.get_packet_rssi(call["packet_hash"]))
|
if path == "medium_path_timeout": self.rpc_return(conn, self.get_medium_path_timeout())
|
||||||
if path == "packet_snr": self.rpc_return(conn, self.get_packet_snr(call["packet_hash"]))
|
if path == "link_count": self.rpc_return(conn, self.get_link_count())
|
||||||
if path == "packet_q": self.rpc_return(conn, self.get_packet_q(call["packet_hash"]))
|
if path == "active_link_count": self.rpc_return(conn, self.get_active_link_count())
|
||||||
if path == "blackholed_identities": self.rpc_return(conn, self.get_blackholed_identities())
|
if path == "packet_rssi": self.rpc_return(conn, self.get_packet_rssi(call["packet_hash"]))
|
||||||
if path == "is_blackholed": self.rpc_return(conn, self.is_blackholed(call["identity_hash"]))
|
if path == "packet_snr": self.rpc_return(conn, self.get_packet_snr(call["packet_hash"]))
|
||||||
|
if path == "packet_q": self.rpc_return(conn, self.get_packet_q(call["packet_hash"]))
|
||||||
|
if path == "blackholed_identities": self.rpc_return(conn, self.get_blackholed_identities())
|
||||||
|
if path == "is_blackholed": self.rpc_return(conn, self.is_blackholed(call["identity_hash"]))
|
||||||
|
|
||||||
if "drop" in call:
|
if "drop" in call:
|
||||||
path = call["drop"]
|
path = call["drop"]
|
||||||
@@ -1392,6 +1474,26 @@ class Reticulum:
|
|||||||
else: ifstats["txs"] = 0
|
else: ifstats["txs"] = 0
|
||||||
else: ifstats["txs"] = 0
|
else: ifstats["txs"] = 0
|
||||||
|
|
||||||
|
if hasattr(interface, "current_arx_speed"):
|
||||||
|
if interface.current_arx_speed != None: ifstats["arxs"] = interface.current_arx_speed
|
||||||
|
else: ifstats["arxs"] = 0
|
||||||
|
else: ifstats["arxs"] = 0
|
||||||
|
|
||||||
|
if hasattr(interface, "current_atx_speed"):
|
||||||
|
if interface.current_atx_speed != None: ifstats["atxs"] = interface.current_atx_speed
|
||||||
|
else: ifstats["atxs"] = 0
|
||||||
|
else: ifstats["atxs"] = 0
|
||||||
|
|
||||||
|
if hasattr(interface, "current_prx_speed"):
|
||||||
|
if interface.current_prx_speed != None: ifstats["prxs"] = interface.current_prx_speed
|
||||||
|
else: ifstats["prxs"] = 0
|
||||||
|
else: ifstats["prxs"] = 0
|
||||||
|
|
||||||
|
if hasattr(interface, "current_ptx_speed"):
|
||||||
|
if interface.current_ptx_speed != None: ifstats["ptxs"] = interface.current_ptx_speed
|
||||||
|
else: ifstats["ptxs"] = 0
|
||||||
|
else: ifstats["ptxs"] = 0
|
||||||
|
|
||||||
if hasattr(interface, "peers"):
|
if hasattr(interface, "peers"):
|
||||||
if interface.peers != None: ifstats["peers"] = len(interface.peers)
|
if interface.peers != None: ifstats["peers"] = len(interface.peers)
|
||||||
else: ifstats["peers"] = None
|
else: ifstats["peers"] = None
|
||||||
@@ -1412,12 +1514,26 @@ class Reticulum:
|
|||||||
if interface.announce_queue != None: ifstats["announce_queue"] = len(interface.announce_queue)
|
if interface.announce_queue != None: ifstats["announce_queue"] = len(interface.announce_queue)
|
||||||
else: ifstats["announce_queue"] = None
|
else: ifstats["announce_queue"] = None
|
||||||
|
|
||||||
|
if hasattr(interface, "blocked_ip_count"):
|
||||||
|
ifstats["blocked_ips"] = interface.blocked_ip_count
|
||||||
|
|
||||||
|
if hasattr(interface, "blocked_ip_list"):
|
||||||
|
ifstats["blocked_ip_list"] = interface.blocked_ip_list
|
||||||
|
|
||||||
ifstats["name"] = str(interface)
|
ifstats["name"] = str(interface)
|
||||||
ifstats["short_name"] = str(interface.name)
|
ifstats["short_name"] = str(interface.name)
|
||||||
ifstats["hash"] = interface.get_hash()
|
ifstats["hash"] = interface.get_hash()
|
||||||
ifstats["type"] = str(type(interface).__name__)
|
ifstats["type"] = str(type(interface).__name__)
|
||||||
ifstats["rxb"] = interface.rxb
|
ifstats["rxb"] = interface.rxb
|
||||||
ifstats["txb"] = interface.txb
|
ifstats["txb"] = interface.txb
|
||||||
|
ifstats["arxb"] = interface.arxb
|
||||||
|
ifstats["atxb"] = interface.atxb
|
||||||
|
ifstats["arxc"] = interface.arxc
|
||||||
|
ifstats["atxc"] = interface.atxc
|
||||||
|
ifstats["prxb"] = interface.prxb
|
||||||
|
ifstats["ptxb"] = interface.ptxb
|
||||||
|
ifstats["prxc"] = interface.prxc
|
||||||
|
ifstats["ptxc"] = interface.ptxc
|
||||||
ifstats["incoming_announce_frequency"] = interface.incoming_announce_frequency()
|
ifstats["incoming_announce_frequency"] = interface.incoming_announce_frequency()
|
||||||
ifstats["outgoing_announce_frequency"] = interface.outgoing_announce_frequency()
|
ifstats["outgoing_announce_frequency"] = interface.outgoing_announce_frequency()
|
||||||
ifstats["incoming_pr_frequency"] = interface.incoming_pr_frequency()
|
ifstats["incoming_pr_frequency"] = interface.incoming_pr_frequency()
|
||||||
@@ -1428,19 +1544,61 @@ class Reticulum:
|
|||||||
ifstats["held_announces"] = len(interface.held_announces)
|
ifstats["held_announces"] = len(interface.held_announces)
|
||||||
ifstats["burst_active"] = interface.ic_burst_active
|
ifstats["burst_active"] = interface.ic_burst_active
|
||||||
ifstats["burst_activated"] = interface.ic_burst_activated
|
ifstats["burst_activated"] = interface.ic_burst_activated
|
||||||
|
ifstats["burst_count"] = interface.ic_burst_count
|
||||||
ifstats["pr_burst_active"] = interface.ic_pr_burst_active
|
ifstats["pr_burst_active"] = interface.ic_pr_burst_active
|
||||||
ifstats["pr_burst_activated"] = interface.ic_pr_burst_activated
|
ifstats["pr_burst_activated"] = interface.ic_pr_burst_activated
|
||||||
|
ifstats["pr_burst_count"] = interface.ic_pr_burst_count
|
||||||
ifstats["status"] = interface.online
|
ifstats["status"] = interface.online
|
||||||
ifstats["mode"] = interface.mode
|
ifstats["mode"] = interface.mode
|
||||||
|
ifstats["gravity"] = interface.gravity
|
||||||
|
ifstats["announces_to_internal"] = interface.announces_to_internal
|
||||||
|
ifstats["protocol_violations"] = interface.protocol_violations
|
||||||
|
ifstats["ifac_violations"] = interface.ifac_violations
|
||||||
|
ifstats["packet_filter_hits"] = interface.packet_filter_hits
|
||||||
|
|
||||||
interfaces.append(ifstats)
|
interfaces.append(ifstats)
|
||||||
|
|
||||||
stats = {}
|
qsnapshot = RNS.Transport.inbound_queues.snapshot()
|
||||||
stats["interfaces"] = interfaces
|
dql = RNS.Transport.INBOUND_DA_QUEUE_LENGTH
|
||||||
stats["rxb"] = RNS.Transport.traffic_rxb
|
aql = RNS.Transport.INBOUND_AN_QUEUE_LENGTH
|
||||||
stats["txb"] = RNS.Transport.traffic_txb
|
pql = RNS.Transport.INBOUND_PR_QUEUE_LENGTH
|
||||||
stats["rxs"] = RNS.Transport.speed_rx
|
ilql = RNS.Transport.INBOUND_IL_QUEUE_LENGTH
|
||||||
stats["txs"] = RNS.Transport.speed_tx
|
tql = dql+aql+pql+ilql
|
||||||
|
|
||||||
|
stats = {}
|
||||||
|
stats["interfaces"] = interfaces
|
||||||
|
stats["rxb"] = RNS.Transport.traffic_rxb
|
||||||
|
stats["txb"] = RNS.Transport.traffic_txb
|
||||||
|
stats["rxs"] = RNS.Transport.speed_rx
|
||||||
|
stats["txs"] = RNS.Transport.speed_tx
|
||||||
|
stats["arxb"] = RNS.Transport.announce_rxb
|
||||||
|
stats["atxb"] = RNS.Transport.announce_txb
|
||||||
|
stats["arxs"] = RNS.Transport.announce_speed_rx
|
||||||
|
stats["atxs"] = RNS.Transport.announce_speed_tx
|
||||||
|
stats["arxf"] = RNS.Transport.announce_freq_rx
|
||||||
|
stats["atxf"] = RNS.Transport.announce_freq_tx
|
||||||
|
stats["prxb"] = RNS.Transport.pr_rxb
|
||||||
|
stats["ptxb"] = RNS.Transport.pr_txb
|
||||||
|
stats["prxs"] = RNS.Transport.pr_speed_rx
|
||||||
|
stats["ptxs"] = RNS.Transport.pr_speed_tx
|
||||||
|
stats["prxf"] = RNS.Transport.pr_freq_rx
|
||||||
|
stats["ptxf"] = RNS.Transport.pr_freq_tx
|
||||||
|
stats["rxqt"] = qsnapshot[0]
|
||||||
|
stats["rxqd"] = qsnapshot[1][0]
|
||||||
|
stats["rxqa"] = qsnapshot[1][1]
|
||||||
|
stats["rxqp"] = qsnapshot[1][2]
|
||||||
|
stats["rxqil"] = qsnapshot[1][3]
|
||||||
|
stats["rxqtd"] = qsnapshot[2][0]+qsnapshot[2][1]+qsnapshot[2][2]+qsnapshot[2][3]
|
||||||
|
stats["rxqdd"] = qsnapshot[2][0]
|
||||||
|
stats["rxqad"] = qsnapshot[2][1]
|
||||||
|
stats["rxqpd"] = qsnapshot[2][2]
|
||||||
|
stats["rxqild"] = qsnapshot[2][3]
|
||||||
|
stats["tqpressure"] = qsnapshot[0]/tql if qsnapshot[0] else 0
|
||||||
|
stats["dqpressure"] = qsnapshot[1][0]/dql if qsnapshot[1][0] else 0
|
||||||
|
stats["aqpressure"] = qsnapshot[1][1]/aql if qsnapshot[1][1] else 0
|
||||||
|
stats["pqpressure"] = qsnapshot[1][2]/pql if qsnapshot[1][2] else 0
|
||||||
|
stats["ilqpressure"] = qsnapshot[1][3]/ilql if qsnapshot[1][3] else 0
|
||||||
|
stats["txq"] = None
|
||||||
|
|
||||||
if Reticulum.transport_enabled():
|
if Reticulum.transport_enabled():
|
||||||
stats["transport_id"] = RNS.Transport.identity.hash
|
stats["transport_id"] = RNS.Transport.identity.hash
|
||||||
@@ -1546,6 +1704,16 @@ class Reticulum:
|
|||||||
return str(RNS.Transport.next_hop_interface(destination))
|
return str(RNS.Transport.next_hop_interface(destination))
|
||||||
|
|
||||||
def get_first_hop_timeout(self, destination):
|
def get_first_hop_timeout(self, destination):
|
||||||
|
"""
|
||||||
|
Returns a best-effort estimate of a reasonable minimum
|
||||||
|
*first-hop* timeout value for a given destination hash.
|
||||||
|
If a path is known, this calculation takes the next-hop
|
||||||
|
interface's bitrate into account. If no path is currently
|
||||||
|
known, returns ``DEFAULT_PER_HOP_TIMEOUT``.
|
||||||
|
|
||||||
|
:param destination: A destination hash, as *bytes*.
|
||||||
|
:returns: First-hop timeout, in seconds.
|
||||||
|
"""
|
||||||
if self.is_connected_to_shared_instance:
|
if self.is_connected_to_shared_instance:
|
||||||
try:
|
try:
|
||||||
rpc_connection = self.get_rpc_client()
|
rpc_connection = self.get_rpc_client()
|
||||||
@@ -1565,6 +1733,45 @@ class Reticulum:
|
|||||||
else:
|
else:
|
||||||
return RNS.Transport.first_hop_timeout(destination)
|
return RNS.Transport.first_hop_timeout(destination)
|
||||||
|
|
||||||
|
def get_lowest_interface_bitrate(self):
|
||||||
|
"""
|
||||||
|
Returns the bitrate of the slowest currently online
|
||||||
|
interface, or None if no online interface bitrate
|
||||||
|
|
||||||
|
:returns: Lowest online interface bitrate in bits per second, or ``None``.
|
||||||
|
"""
|
||||||
|
if self.is_connected_to_shared_instance:
|
||||||
|
try:
|
||||||
|
rpc_connection = self.get_rpc_client()
|
||||||
|
rpc_connection.send_bytes(mp.packb({"get": "lowest_interface_bitrate"}))
|
||||||
|
return mp.unpackb(rpc_connection.recv_bytes())
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log("An error occurred while getting lowest interface bitrate from shared instance: "+str(e), RNS.LOG_ERROR)
|
||||||
|
return None
|
||||||
|
|
||||||
|
else:
|
||||||
|
return RNS.Transport.lowest_interface_bitrate
|
||||||
|
|
||||||
|
def get_medium_path_timeout(self):
|
||||||
|
"""
|
||||||
|
Returns an estimate of a reasonable minimum path request timeout covering
|
||||||
|
a full round trip for an MTU on the slowest currently online interface
|
||||||
|
plus per hop grace
|
||||||
|
|
||||||
|
:returns: Timeout in seconds or 0 if it's unknown.
|
||||||
|
"""
|
||||||
|
if self.is_connected_to_shared_instance:
|
||||||
|
try:
|
||||||
|
rpc_connection = self.get_rpc_client()
|
||||||
|
rpc_connection.send_bytes(mp.packb({"get": "medium_path_timeout"}))
|
||||||
|
return mp.unpackb(rpc_connection.recv_bytes())
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log("An error occurred while getting medium path timeout from shared instance: "+str(e), RNS.LOG_ERROR)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
else:
|
||||||
|
return RNS.Transport.medium_path_timeout()
|
||||||
|
|
||||||
def get_next_hop(self, destination):
|
def get_next_hop(self, destination):
|
||||||
if self.is_connected_to_shared_instance:
|
if self.is_connected_to_shared_instance:
|
||||||
rpc_connection = self.get_rpc_client()
|
rpc_connection = self.get_rpc_client()
|
||||||
@@ -1584,7 +1791,17 @@ class Reticulum:
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return len(RNS.Transport.link_table)
|
return RNS.Transport.link_count()
|
||||||
|
|
||||||
|
def get_active_link_count(self):
|
||||||
|
if self.is_connected_to_shared_instance:
|
||||||
|
rpc_connection = self.get_rpc_client()
|
||||||
|
rpc_connection.send_bytes(mp.packb({"get": "active_link_count"}))
|
||||||
|
response = mp.unpackb(rpc_connection.recv_bytes())
|
||||||
|
return response
|
||||||
|
|
||||||
|
else:
|
||||||
|
return RNS.Transport.active_link_count()
|
||||||
|
|
||||||
def get_packet_rssi(self, packet_hash):
|
def get_packet_rssi(self, packet_hash):
|
||||||
if self.is_connected_to_shared_instance:
|
if self.is_connected_to_shared_instance:
|
||||||
@@ -1793,6 +2010,18 @@ class Reticulum:
|
|||||||
def should_autoconnect_discovered_interfaces():
|
def should_autoconnect_discovered_interfaces():
|
||||||
return Reticulum.__autoconnect_discovered_interfaces > 0
|
return Reticulum.__autoconnect_discovered_interfaces > 0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def autoconnect_interface_mode():
|
||||||
|
return Reticulum.__autoconnect_interface_mode
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def autoconnect_interface_gravity():
|
||||||
|
return Reticulum.__autoconnect_interface_gravity
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def autoconnect_announces_to_internal():
|
||||||
|
return Reticulum.__autoconnect_announces_to_internal
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def max_autoconnected_interfaces():
|
def max_autoconnected_interfaces():
|
||||||
return Reticulum.__autoconnect_discovered_interfaces
|
return Reticulum.__autoconnect_discovered_interfaces
|
||||||
@@ -1805,6 +2034,22 @@ class Reticulum:
|
|||||||
def local_hops_delta():
|
def local_hops_delta():
|
||||||
return Reticulum.__local_hops_delta
|
return Reticulum.__local_hops_delta
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def default_data_queue_length():
|
||||||
|
return Reticulum.__inbound_data_queue_length
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def default_announce_queue_length():
|
||||||
|
return Reticulum.__inbound_announce_queue_length
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def default_pr_queue_length():
|
||||||
|
return Reticulum.__inbound_pr_queue_length
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def default_il_queue_length():
|
||||||
|
return Reticulum.__inbound_il_queue_length
|
||||||
|
|
||||||
# Default configuration file:
|
# Default configuration file:
|
||||||
__default_rns_config__ = '''# This is the default Reticulum config file.
|
__default_rns_config__ = '''# This is the default Reticulum config file.
|
||||||
# You should probably edit it to include any additional,
|
# You should probably edit it to include any additional,
|
||||||
@@ -1892,7 +2137,7 @@ instance_name = default
|
|||||||
|
|
||||||
|
|
||||||
[logging]
|
[logging]
|
||||||
# Valid log levels are 0 through 7:
|
# Valid log levels are 0 through 8:
|
||||||
# 0: Log only critical information
|
# 0: Log only critical information
|
||||||
# 1: Log errors and lower log levels
|
# 1: Log errors and lower log levels
|
||||||
# 2: Log warnings and lower log levels
|
# 2: Log warnings and lower log levels
|
||||||
@@ -1900,7 +2145,8 @@ instance_name = default
|
|||||||
# 4: Log info and lower (this is the default)
|
# 4: Log info and lower (this is the default)
|
||||||
# 5: Verbose logging
|
# 5: Verbose logging
|
||||||
# 6: Debug logging
|
# 6: Debug logging
|
||||||
# 7: Extreme logging
|
# 7: Path logging
|
||||||
|
# 8: Extreme logging
|
||||||
|
|
||||||
loglevel = 4
|
loglevel = 4
|
||||||
|
|
||||||
|
|||||||
+1405
-933
File diff suppressed because it is too large.
Load diff
@@ -401,7 +401,7 @@ def fetch(configdir, identitypath = None, verbosity = 0, quietness = 0, destinat
|
|||||||
|
|
||||||
i = 0
|
i = 0
|
||||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||||
estab_timeout = time.time()+timeout
|
estab_timeout = time.time()+max(timeout, reticulum.get_medium_path_timeout())
|
||||||
while not RNS.Transport.has_path(destination_hash) and time.time() < estab_timeout:
|
while not RNS.Transport.has_path(destination_hash) and time.time() < estab_timeout:
|
||||||
if not silent:
|
if not silent:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
@@ -431,6 +431,7 @@ def fetch(configdir, identitypath = None, verbosity = 0, quietness = 0, destinat
|
|||||||
)
|
)
|
||||||
|
|
||||||
link = RNS.Link(listener_destination)
|
link = RNS.Link(listener_destination)
|
||||||
|
estab_timeout = max(estab_timeout, time.time()+link.establishment_timeout)
|
||||||
while link.status != RNS.Link.ACTIVE and time.time() < estab_timeout:
|
while link.status != RNS.Link.ACTIVE and time.time() < estab_timeout:
|
||||||
if not silent:
|
if not silent:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
@@ -656,7 +657,7 @@ def send(configdir, identitypath = None, verbosity = 0, quietness = 0, destinati
|
|||||||
|
|
||||||
i = 0
|
i = 0
|
||||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||||
estab_timeout = time.time()+timeout
|
estab_timeout = time.time()+max(timeout, reticulum.get_medium_path_timeout())
|
||||||
while not RNS.Transport.has_path(destination_hash) and time.time() < estab_timeout:
|
while not RNS.Transport.has_path(destination_hash) and time.time() < estab_timeout:
|
||||||
if not silent:
|
if not silent:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
@@ -686,6 +687,7 @@ def send(configdir, identitypath = None, verbosity = 0, quietness = 0, destinati
|
|||||||
)
|
)
|
||||||
|
|
||||||
link = RNS.Link(receiver_destination)
|
link = RNS.Link(receiver_destination)
|
||||||
|
estab_timeout = max(estab_timeout, time.time()+link.establishment_timeout)
|
||||||
while link.status != RNS.Link.ACTIVE and time.time() < estab_timeout:
|
while link.status != RNS.Link.ACTIVE and time.time() < estab_timeout:
|
||||||
if not silent:
|
if not silent:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
@@ -878,8 +880,8 @@ def main():
|
|||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("")
|
print("")
|
||||||
if resource != None:
|
if current_resource != None:
|
||||||
resource.cancel()
|
current_resource.cancel()
|
||||||
if link != None:
|
if link != None:
|
||||||
link.teardown()
|
link.teardown()
|
||||||
RNS.exit()
|
RNS.exit()
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import subprocess
|
|||||||
|
|
||||||
from RNS._version import __version__
|
from RNS._version import __version__
|
||||||
from RNS.Utilities.rngit import APP_NAME
|
from RNS.Utilities.rngit import APP_NAME
|
||||||
|
from RNS.Utilities.rngit.util import medium_path_timeout
|
||||||
|
|
||||||
from RNS.vendor.configobj import ConfigObj
|
from RNS.vendor.configobj import ConfigObj
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
@@ -223,7 +224,7 @@ class ReticulumGitClient():
|
|||||||
|
|
||||||
RNS.log(f"Requesting path to {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG)
|
RNS.log(f"Requesting path to {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG)
|
||||||
sys.stderr.write(f"Requesting path..."); sys.stderr.flush()
|
sys.stderr.write(f"Requesting path..."); sys.stderr.flush()
|
||||||
if not RNS.Transport.await_path(destination_hash, timeout=self.path_timeout):
|
if not RNS.Transport.await_path(destination_hash, timeout=medium_path_timeout(self.path_timeout)):
|
||||||
sys.stderr.write(f"\n"); sys.stderr.flush()
|
sys.stderr.write(f"\n"); sys.stderr.flush()
|
||||||
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
|
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
|
||||||
|
|
||||||
@@ -291,6 +292,8 @@ class ReticulumGitClient():
|
|||||||
|
|
||||||
if hasattr(self.request_response, "read") and callable(self.request_response.read):
|
if hasattr(self.request_response, "read") and callable(self.request_response.read):
|
||||||
response_path = self.request_response.name
|
response_path = self.request_response.name
|
||||||
|
try: self.request_response.close()
|
||||||
|
except Exception as e: RNS.log(f"Could not close resource file descriptor before retain: {e}", RNS.LOG_ERROR)
|
||||||
base_name = os.path.basename(response_path)
|
base_name = os.path.basename(response_path)
|
||||||
retained_path = os.path.join(self.tmp_dir.name, base_name)
|
retained_path = os.path.join(self.tmp_dir.name, base_name)
|
||||||
shutil.move(response_path, retained_path)
|
shutil.move(response_path, retained_path)
|
||||||
@@ -333,10 +336,10 @@ class ReticulumGitClient():
|
|||||||
try: self.connect_server()
|
try: self.connect_server()
|
||||||
except Exception as e: self.abort(str(e))
|
except Exception as e: self.abort(str(e))
|
||||||
|
|
||||||
timeout = self.link_timeout
|
timeout = max(self.link_timeout, self.link.establishment_timeout)
|
||||||
while not self.link_ready and not self.link_failed and timeout > 0:
|
while not self.link_ready and not self.link_failed and timeout > 0:
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
timeout -= 1
|
timeout -= 0.5
|
||||||
|
|
||||||
if not self.link_ready: self.abort("Failed to establish link")
|
if not self.link_ready: self.abort("Failed to establish link")
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ from datetime import datetime, timezone
|
|||||||
from RNS._version import __version__
|
from RNS._version import __version__
|
||||||
from RNS.Utilities.rngit import APP_NAME
|
from RNS.Utilities.rngit import APP_NAME
|
||||||
from RNS.Utilities.rngit.pages import NomadNetworkNode
|
from RNS.Utilities.rngit.pages import NomadNetworkNode
|
||||||
from RNS.Utilities.rngit.util import san_ref, san_refs, san_sha
|
from RNS.Utilities.rngit.util import san_ref, san_refs, san_sha, medium_path_timeout
|
||||||
from RNS.vendor.configobj import ConfigObj
|
from RNS.vendor.configobj import ConfigObj
|
||||||
from RNS.vendor import umsgpack as mp
|
from RNS.vendor import umsgpack as mp
|
||||||
from RNS.Utilities.rnid import create_rsg, validate_rsg, get_rsg_hash
|
from RNS.Utilities.rnid import create_rsg, validate_rsg, get_rsg_hash
|
||||||
@@ -465,7 +465,7 @@ class ReticulumGitClient():
|
|||||||
def connect_remote(self, remote):
|
def connect_remote(self, remote):
|
||||||
destination_hash = self.parse_remote_destination_url(remote)
|
destination_hash = self.parse_remote_destination_url(remote)
|
||||||
print(f"Requesting path... ", end="")
|
print(f"Requesting path... ", end="")
|
||||||
if not RNS.Transport.await_path(destination_hash, timeout=self.path_timeout):
|
if not RNS.Transport.await_path(destination_hash, timeout=medium_path_timeout(self.path_timeout)):
|
||||||
print(f"\n", end="")
|
print(f"\n", end="")
|
||||||
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
|
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
|
||||||
|
|
||||||
@@ -479,6 +479,7 @@ class ReticulumGitClient():
|
|||||||
self.link = RNS.Link(self.destination)
|
self.link = RNS.Link(self.destination)
|
||||||
self.link.set_link_established_callback(self.link_established)
|
self.link.set_link_established_callback(self.link_established)
|
||||||
self.link.set_link_closed_callback(self.link_closed)
|
self.link.set_link_closed_callback(self.link_closed)
|
||||||
|
self.link_timeout = max(self.link_timeout, self.link.establishment_timeout)
|
||||||
|
|
||||||
def link_established(self, link):
|
def link_established(self, link):
|
||||||
print(f"\rLink established ", end="")
|
print(f"\rLink established ", end="")
|
||||||
|
|||||||
@@ -814,3 +814,6 @@ class MarkdownToMicron:
|
|||||||
def convert_markdown_to_micron(text):
|
def convert_markdown_to_micron(text):
|
||||||
converter = MarkdownToMicron()
|
converter = MarkdownToMicron()
|
||||||
return converter.format_block(text)
|
return converter.format_block(text)
|
||||||
|
|
||||||
|
def medium_path_timeout(default_timeout):
|
||||||
|
return max(default_timeout, RNS.Reticulum.get_instance().get_medium_path_timeout())
|
||||||
@@ -3766,8 +3766,8 @@ def main():
|
|||||||
print("\nDevice configuration:")
|
print("\nDevice configuration:")
|
||||||
if ec_bt == 0x73: print(f" Bluetooth : Enabled")
|
if ec_bt == 0x73: print(f" Bluetooth : Enabled")
|
||||||
else: print(f" Bluetooth : Disabled")
|
else: print(f" Bluetooth : Disabled")
|
||||||
if ec_wifi == 0x01: print(f" WiFi : Enabled (Station)")
|
if ec_wifi == 0x01: print(f" WiFi : Enabled (Station)")
|
||||||
if ec_wifi == 0x02: print(f" WiFi : Enabled (AP)")
|
elif ec_wifi == 0x02: print(f" WiFi : Enabled (AP)")
|
||||||
else: print(f" WiFi : Disabled")
|
else: print(f" WiFi : Disabled")
|
||||||
if ec_wifi == 0x01 or ec_wifi == 0x02:
|
if ec_wifi == 0x01 or ec_wifi == 0x02:
|
||||||
if not ec_wchn: print(f" Channel : Unknown")
|
if not ec_wchn: print(f" Channel : Unknown")
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ remote_link = None
|
|||||||
output_rst_str = "\r \r"
|
output_rst_str = "\r \r"
|
||||||
def connect_remote(destination_hash, auth_identity, timeout, no_output = False, purpose="management"):
|
def connect_remote(destination_hash, auth_identity, timeout, no_output = False, purpose="management"):
|
||||||
global remote_link, reticulum
|
global remote_link, reticulum
|
||||||
|
timeout = max(timeout, reticulum.get_medium_path_timeout())
|
||||||
if not RNS.Transport.has_path(destination_hash):
|
if not RNS.Transport.has_path(destination_hash):
|
||||||
if not no_output:
|
if not no_output:
|
||||||
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested", end=" ")
|
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested", end=" ")
|
||||||
@@ -451,7 +452,7 @@ def program_setup(configdir, table, rates, drop, destination_hexhash, verbosity,
|
|||||||
|
|
||||||
i = 0
|
i = 0
|
||||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||||
limit = time.time()+timeout
|
limit = time.time()+max(timeout, reticulum.get_medium_path_timeout())
|
||||||
while not RNS.Transport.has_path(destination_hash) and time.time()<limit:
|
while not RNS.Transport.has_path(destination_hash) and time.time()<limit:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
print(("\b\b"+syms[i]+" "), end="")
|
print(("\b\b"+syms[i]+" "), end="")
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ def program_setup(configdir, destination_hexhash, size=None, full_name = None, v
|
|||||||
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested ", end=" ")
|
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested ", end=" ")
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
|
|
||||||
_timeout = time.time() + (timeout or DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash))
|
_timeout = time.time() + (timeout or max(DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash), reticulum.get_medium_path_timeout()))
|
||||||
i = 0
|
i = 0
|
||||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||||
while not RNS.Transport.has_path(destination_hash) and not time.time() > _timeout:
|
while not RNS.Transport.has_path(destination_hash) and not time.time() > _timeout:
|
||||||
@@ -131,7 +131,7 @@ def program_setup(configdir, destination_hexhash, size=None, full_name = None, v
|
|||||||
|
|
||||||
print("\rSent probe "+str(sent)+" ("+str(size)+" bytes) to "+RNS.prettyhexrep(destination_hash)+more+" ", end=" ")
|
print("\rSent probe "+str(sent)+" ("+str(size)+" bytes) to "+RNS.prettyhexrep(destination_hash)+more+" ", end=" ")
|
||||||
|
|
||||||
_timeout = time.time() + (timeout or DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash))
|
_timeout = time.time() + (timeout or max(DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash), reticulum.get_medium_path_timeout()))
|
||||||
i = 0
|
i = 0
|
||||||
while receipt.status == RNS.PacketReceipt.SENT and not time.time() > _timeout:
|
while receipt.status == RNS.PacketReceipt.SENT and not time.time() > _timeout:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
|||||||
+28
-2
@@ -173,6 +173,12 @@ instance_name = default
|
|||||||
# network_identity = ~/.reticulum/storage/identity/network
|
# network_identity = ~/.reticulum/storage/identity/network
|
||||||
|
|
||||||
|
|
||||||
|
# It is possible to configure the global default interface
|
||||||
|
# gravity. This value will be used if an interface does
|
||||||
|
# not have a specific gravity value in its configuration.
|
||||||
|
|
||||||
|
# default_gravity = 0
|
||||||
|
|
||||||
# You can configure whether Reticulum should discover
|
# You can configure whether Reticulum should discover
|
||||||
# available interfaces from other Transport Instances over
|
# available interfaces from other Transport Instances over
|
||||||
# the network. If this option is enabled, Reticulum will
|
# the network. If this option is enabled, Reticulum will
|
||||||
@@ -217,6 +223,25 @@ instance_name = default
|
|||||||
|
|
||||||
# panic_on_interface_error = no
|
# panic_on_interface_error = no
|
||||||
|
|
||||||
|
# You can specify which mode discovered interfaces should
|
||||||
|
# be created with when auto-connecting.
|
||||||
|
|
||||||
|
# autoconnect_interface_mode = gw
|
||||||
|
|
||||||
|
|
||||||
|
# It is possible to allow announces from auto-connected
|
||||||
|
# interfaces to propagate announces to internal-mode
|
||||||
|
# interfaces, even if the auto-connected interface's mode
|
||||||
|
# would normally not allow for this.
|
||||||
|
|
||||||
|
# autoconnect_announces_to_internal = yes
|
||||||
|
|
||||||
|
|
||||||
|
# You can configure the gravity for discovered interfaces
|
||||||
|
# that are auto-connected.
|
||||||
|
|
||||||
|
# autoconnect_interface_gravity = 0
|
||||||
|
|
||||||
|
|
||||||
# When Transport is enabled, it is possible to allow the
|
# When Transport is enabled, it is possible to allow the
|
||||||
# Transport Instance to respond to probe requests from
|
# Transport Instance to respond to probe requests from
|
||||||
@@ -265,7 +290,7 @@ instance_name = default
|
|||||||
|
|
||||||
|
|
||||||
[logging]
|
[logging]
|
||||||
# Valid log levels are 0 through 7:
|
# Valid log levels are 0 through 8:
|
||||||
# 0: Log only critical information
|
# 0: Log only critical information
|
||||||
# 1: Log errors and lower log levels
|
# 1: Log errors and lower log levels
|
||||||
# 2: Log warnings and lower log levels
|
# 2: Log warnings and lower log levels
|
||||||
@@ -273,7 +298,8 @@ instance_name = default
|
|||||||
# 4: Log info and lower (this is the default)
|
# 4: Log info and lower (this is the default)
|
||||||
# 5: Verbose logging
|
# 5: Verbose logging
|
||||||
# 6: Debug logging
|
# 6: Debug logging
|
||||||
# 7: Extreme logging
|
# 7: Path logging
|
||||||
|
# 8: Extreme logging
|
||||||
|
|
||||||
loglevel = 4
|
loglevel = 4
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,13 @@
|
|||||||
from ._version import __version__
|
from ._version import __version__
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import glob
|
||||||
module_abs_filename = os.path.abspath(__file__)
|
module_abs_filename = os.path.abspath(__file__)
|
||||||
module_dir = os.path.dirname(module_abs_filename)
|
module_dir = os.path.dirname(module_abs_filename)
|
||||||
|
|
||||||
|
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
|
||||||
|
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
|
||||||
|
modules = py_modules+pyc_modules
|
||||||
|
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
|
||||||
|
|
||||||
def _get_version(): return __version__
|
def _get_version(): return __version__
|
||||||
@@ -1 +1 @@
|
|||||||
__version__ = "0.2.0"
|
__version__ = "0.3.0"
|
||||||
@@ -44,7 +44,8 @@ def setup_argument_parser():
|
|||||||
parser = argparse.ArgumentParser(description="Reticulum Remote Shell Utility", epilog="When specifying a command to execute, separate rnsh\noptions from the command and its arguments with --\n\nFor example:\n rnsh -l -- /bin/bash --login\n rnsh <destination> -- ls -la /tmp", formatter_class=argparse.RawDescriptionHelpFormatter)
|
parser = argparse.ArgumentParser(description="Reticulum Remote Shell Utility", epilog="When specifying a command to execute, separate rnsh\noptions from the command and its arguments with --\n\nFor example:\n rnsh -l -- /bin/bash --login\n rnsh <destination> -- ls -la /tmp", formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
|
||||||
# Common options
|
# Common options
|
||||||
parser.add_argument("--config", "-c", action="store", default=None, help="path to alternative Reticulum config directory", type=str)
|
parser.add_argument("--config", "-c", action="store", default=None, help="path to config directory", type=str)
|
||||||
|
parser.add_argument("--rnsconfig", action="store", default=None, help="path to alternative Reticulum config directory", type=str)
|
||||||
parser.add_argument("--identity", "-i", action="store", default=None, help="path to identity file to use", type=str)
|
parser.add_argument("--identity", "-i", action="store", default=None, help="path to identity file to use", type=str)
|
||||||
parser.add_argument("-v", "--verbose", action="count", default=0, help="increase verbosity")
|
parser.add_argument("-v", "--verbose", action="count", default=0, help="increase verbosity")
|
||||||
parser.add_argument("-q", "--quiet", action="count", default=0, help="decrease verbosity")
|
parser.add_argument("-q", "--quiet", action="count", default=0, help="decrease verbosity")
|
||||||
|
|||||||
@@ -53,8 +53,6 @@ class permit(AbstractContextManager):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, *exceptions): self._exceptions = exceptions
|
def __init__(self, *exceptions): self._exceptions = exceptions
|
||||||
|
|
||||||
def __enter__(self): pass
|
def __enter__(self): pass
|
||||||
|
|
||||||
def __exit__(self, exctype, excinst, exctb):
|
def __exit__(self, exctype, excinst, exctb):
|
||||||
return exctype is not None and not issubclass(exctype, self._exceptions)
|
return exctype is not None and not issubclass(exctype, self._exceptions)
|
||||||
@@ -55,5 +55,4 @@ class SleepRate:
|
|||||||
return sleep_for if sleep_for > 0 else 0
|
return sleep_for if sleep_for > 0 else 0
|
||||||
|
|
||||||
async def sleep_async(self): await asyncio.sleep(self.next_sleep_time())
|
async def sleep_async(self): await asyncio.sleep(self.next_sleep_time())
|
||||||
|
|
||||||
def sleep_block(self): time.sleep(self.next_sleep_time())
|
def sleep_block(self): time.sleep(self.next_sleep_time())
|
||||||
@@ -35,7 +35,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import base64
|
|
||||||
import enum
|
import enum
|
||||||
import functools
|
import functools
|
||||||
import os
|
import os
|
||||||
@@ -53,10 +52,8 @@ import RNS.Utilities.rnsh.exception as exception
|
|||||||
import RNS.Utilities.rnsh.process as process
|
import RNS.Utilities.rnsh.process as process
|
||||||
import RNS.Utilities.rnsh.retry as retry
|
import RNS.Utilities.rnsh.retry as retry
|
||||||
import RNS.Utilities.rnsh.session as session
|
import RNS.Utilities.rnsh.session as session
|
||||||
import re
|
|
||||||
import contextlib
|
import contextlib
|
||||||
|
|
||||||
import pwd
|
|
||||||
import bz2
|
import bz2
|
||||||
import RNS.Utilities.rnsh.protocol as protocol
|
import RNS.Utilities.rnsh.protocol as protocol
|
||||||
import RNS.Utilities.rnsh.helpers as helpers
|
import RNS.Utilities.rnsh.helpers as helpers
|
||||||
@@ -71,7 +68,6 @@ _retry_timer: retry.RetryThread | None = None
|
|||||||
_destination: RNS.Destination | None = None
|
_destination: RNS.Destination | None = None
|
||||||
_loop: asyncio.AbstractEventLoop | None = None
|
_loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
|
||||||
|
|
||||||
async def _check_finished(timeout: float = 0):
|
async def _check_finished(timeout: float = 0):
|
||||||
return _finished is not None and await process.event_wait(_finished, timeout=timeout)
|
return _finished is not None and await process.event_wait(_finished, timeout=timeout)
|
||||||
|
|
||||||
@@ -92,13 +88,11 @@ async def _spin_tty(until=None, msg=None, timeout=None):
|
|||||||
print(("\b\b"+syms[i]+" "), end="")
|
print(("\b\b"+syms[i]+" "), end="")
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
i = (i+1)%len(syms)
|
i = (i+1)%len(syms)
|
||||||
|
|
||||||
print("\r"+" "*len(msg)+" \r", end="")
|
print("\r"+" "*len(msg)+" \r", end="")
|
||||||
|
|
||||||
if timeout != None and time.time() > timeout: return False
|
if timeout != None and time.time() > timeout: return False
|
||||||
else: return True
|
else: return True
|
||||||
|
|
||||||
|
|
||||||
async def _spin_pipe(until: callable = None, msg=None, timeout: float | None = None) -> bool:
|
async def _spin_pipe(until: callable = None, msg=None, timeout: float | None = None) -> bool:
|
||||||
if timeout is not None: timeout += time.time()
|
if timeout is not None: timeout += time.time()
|
||||||
|
|
||||||
@@ -133,18 +127,15 @@ def _client_message_handler(message: RNS.MessageBase): _pq.put(message)
|
|||||||
def compute_target_rns_loglevel(verbosity: int, quietness: int, base_level: int = RNS.LOG_INFO) -> int:
|
def compute_target_rns_loglevel(verbosity: int, quietness: int, base_level: int = RNS.LOG_INFO) -> int:
|
||||||
try:
|
try:
|
||||||
target = int(base_level) + int(verbosity) - int(quietness)
|
target = int(base_level) + int(verbosity) - int(quietness)
|
||||||
if target < RNS.LOG_CRITICAL: target = RNS.LOG_CRITICAL
|
if target < RNS.LOG_NONE: target = RNS.LOG_NONE
|
||||||
if target > RNS.LOG_DEBUG: target = RNS.LOG_DEBUG
|
if target > RNS.LOG_EXTREME: target = RNS.LOG_EXTREME
|
||||||
return target
|
return target
|
||||||
|
|
||||||
except Exception: return base_level
|
except Exception: return base_level
|
||||||
|
|
||||||
|
|
||||||
class RemoteExecutionError(Exception):
|
class RemoteExecutionError(Exception):
|
||||||
def __init__(self, msg): self.msg = msg
|
def __init__(self, msg): self.msg = msg
|
||||||
|
|
||||||
|
async def _initiate_link(configdir, rnsconfigdir, identitypath=None, logfile=None, verbosity=0, quietness=0, noid=False, destination=None,
|
||||||
async def _initiate_link(configdir, rnsconfigdir, identitypath=None, verbosity=0, quietness=0, noid=False, destination=None,
|
|
||||||
timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
|
timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
|
||||||
global _identity, _reticulum, _link, _destination, _remote_exec_grace
|
global _identity, _reticulum, _link, _destination, _remote_exec_grace
|
||||||
|
|
||||||
@@ -153,34 +144,28 @@ async def _initiate_link(configdir, rnsconfigdir, identitypath=None, verbosity=0
|
|||||||
raise RemoteExecutionError(
|
raise RemoteExecutionError(
|
||||||
"Allowed destination length is invalid, must be {hex} hexadecimal characters ({byte} bytes).".format(
|
"Allowed destination length is invalid, must be {hex} hexadecimal characters ({byte} bytes).".format(
|
||||||
hex=dest_len, byte=dest_len // 2))
|
hex=dest_len, byte=dest_len // 2))
|
||||||
try:
|
|
||||||
destination_hash = bytes.fromhex(destination)
|
try: destination_hash = bytes.fromhex(destination)
|
||||||
except Exception as e:
|
except Exception as e: raise RemoteExecutionError("Invalid destination entered. Check your input.")
|
||||||
raise RemoteExecutionError("Invalid destination entered. Check your input.")
|
|
||||||
|
|
||||||
if _reticulum is None:
|
if _reticulum is None:
|
||||||
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_ERROR)
|
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_INFO)
|
||||||
RNS.logfile = os.path.join(configdir, "logfile")
|
RNS.logfile = logfile
|
||||||
_reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel, logdest=RNS.LOG_FILE)
|
_reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel, logdest=RNS.LOG_FILE)
|
||||||
|
|
||||||
if _identity is None:
|
if _identity is None:
|
||||||
_identity = rnsh.prepare_identity(identitypath)
|
_identity = rnsh.prepare_identity(identity_path=identitypath, service_name=None, configdir=configdir)
|
||||||
|
|
||||||
if not RNS.Transport.has_path(destination_hash):
|
if not RNS.Transport.has_path(destination_hash):
|
||||||
RNS.Transport.request_path(destination_hash)
|
RNS.Transport.request_path(destination_hash)
|
||||||
RNS.log(f"Requesting path...", RNS.LOG_INFO)
|
RNS.log(f"Requesting path to {RNS.prettyhexrep(destination_hash)}", RNS.LOG_INFO)
|
||||||
if not await _spin(until=lambda: RNS.Transport.has_path(destination_hash), msg="Requesting path...",
|
if not await _spin(until=lambda: RNS.Transport.has_path(destination_hash), msg=f"Requesting path to {RNS.prettyhexrep(destination_hash)}",
|
||||||
timeout=timeout, quiet=quietness > 0):
|
timeout=timeout, quiet=quietness > 0):
|
||||||
raise RemoteExecutionError("Path not found")
|
raise RemoteExecutionError("Path not found")
|
||||||
|
|
||||||
if _destination is None:
|
if _destination is None:
|
||||||
listener_identity = RNS.Identity.recall(destination_hash)
|
listener_identity = RNS.Identity.recall(destination_hash)
|
||||||
_destination = RNS.Destination(
|
_destination = RNS.Destination(listener_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, rnsh.APP_NAME)
|
||||||
listener_identity,
|
|
||||||
RNS.Destination.OUT,
|
|
||||||
RNS.Destination.SINGLE,
|
|
||||||
rnsh.APP_NAME
|
|
||||||
)
|
|
||||||
|
|
||||||
if _link is None or _link.status == RNS.Link.PENDING:
|
if _link is None or _link.status == RNS.Link.PENDING:
|
||||||
RNS.log("No link", RNS.LOG_DEBUG)
|
RNS.log("No link", RNS.LOG_DEBUG)
|
||||||
@@ -189,33 +174,30 @@ async def _initiate_link(configdir, rnsconfigdir, identitypath=None, verbosity=0
|
|||||||
|
|
||||||
_link.set_link_closed_callback(_client_link_closed)
|
_link.set_link_closed_callback(_client_link_closed)
|
||||||
|
|
||||||
RNS.log(f"Establishing link...", RNS.LOG_VERBOSE)
|
RNS.log(f"Establishing link with {RNS.prettyhexrep(destination_hash)}", RNS.LOG_INFO)
|
||||||
if not await _spin(until=lambda: _link.status == RNS.Link.ACTIVE, msg="Establishing link...",
|
if not await _spin(until=lambda: _link.status == RNS.Link.ACTIVE, msg=f"Establishing link with {RNS.prettyhexrep(destination_hash)}",
|
||||||
timeout=timeout, quiet=quietness > 0):
|
timeout=timeout, quiet=quietness > 0):
|
||||||
raise RemoteExecutionError("Could not establish link with " + RNS.prettyhexrep(destination_hash))
|
raise RemoteExecutionError("Could not establish link with " + RNS.prettyhexrep(destination_hash))
|
||||||
|
|
||||||
RNS.log("Have link", RNS.LOG_DEBUG)
|
RNS.log(f"Link established with {RNS.prettyhexrep(destination_hash)}", RNS.LOG_INFO)
|
||||||
if not noid and not _link.did_identify:
|
if not noid and not _link.did_identify:
|
||||||
# Delay a tiny bit to allow listener to fully enter WAIT_IDENT state
|
# Delay a tiny bit to allow listener to fully enter WAIT_IDENT state
|
||||||
await asyncio.sleep(min(1, _link.rtt * 1.1 + 0.05))
|
await asyncio.sleep(min(1, _link.rtt * 1.1 + 0.05))
|
||||||
_link.identify(_identity)
|
_link.identify(_identity)
|
||||||
_link.did_identify = True
|
_link.did_identify = True
|
||||||
|
|
||||||
|
|
||||||
async def _handle_error(errmsg: RNS.MessageBase):
|
async def _handle_error(errmsg: RNS.MessageBase):
|
||||||
if isinstance(errmsg, protocol.ErrorMessage):
|
if isinstance(errmsg, protocol.ErrorMessage):
|
||||||
with contextlib.suppress(Exception):
|
with contextlib.suppress(Exception):
|
||||||
if _link and _link.status == RNS.Link.ACTIVE:
|
if _link and _link.status == RNS.Link.ACTIVE: _link.teardown()
|
||||||
_link.teardown()
|
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
raise RemoteExecutionError(f"Remote error: {errmsg.msg}")
|
raise RemoteExecutionError(f"Remote error: {errmsg.msg}")
|
||||||
|
|
||||||
|
async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, logfile:str, verbosity: int, quietness: int, noid: bool, destination: str,
|
||||||
async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosity: int, quietness: int, noid: bool, destination: str,
|
|
||||||
timeout: float, command: [str] | None = None):
|
timeout: float, command: [str] | None = None):
|
||||||
|
|
||||||
global _finished, _link
|
global _finished, _link
|
||||||
if timeout is None:
|
if timeout is None: timeout = RNS.Transport.PATH_REQUEST_TIMEOUT
|
||||||
timeout = RNS.Transport.PATH_REQUEST_TIMEOUT
|
|
||||||
with process.TTYRestorer(sys.stdin.fileno()) as ttyRestorer:
|
with process.TTYRestorer(sys.stdin.fileno()) as ttyRestorer:
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
state = InitiatorState.IS_INITIAL
|
state = InitiatorState.IS_INITIAL
|
||||||
@@ -225,33 +207,26 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
await _initiate_link(configdir=configdir,
|
await _initiate_link(configdir=configdir,
|
||||||
rnsconfigdir=rnsconfigdir,
|
rnsconfigdir=rnsconfigdir,
|
||||||
identitypath=identitypath,
|
identitypath=identitypath,
|
||||||
|
logfile=logfile,
|
||||||
verbosity=verbosity,
|
verbosity=verbosity,
|
||||||
quietness=quietness,
|
quietness=quietness,
|
||||||
noid=noid,
|
noid=noid,
|
||||||
destination=destination,
|
destination=destination,
|
||||||
timeout=timeout)
|
timeout=timeout)
|
||||||
|
|
||||||
if not _link or _link.status not in [RNS.Link.ACTIVE, RNS.Link.PENDING]:
|
if not _link or _link.status not in [RNS.Link.ACTIVE, RNS.Link.PENDING]: return 255
|
||||||
return 255
|
|
||||||
|
|
||||||
state = InitiatorState.IS_LINKED
|
state = InitiatorState.IS_LINKED
|
||||||
outlet = session.RNSOutlet(_link)
|
outlet = session.RNSOutlet(_link)
|
||||||
channel = _link.get_channel()
|
channel = _link.get_channel()
|
||||||
protocol.register_message_types(channel)
|
protocol.register_message_types(channel)
|
||||||
channel.add_message_handler(_client_message_handler)
|
channel.add_message_handler(_client_message_handler)
|
||||||
|
|
||||||
# Next step after linking and identifying: send version
|
|
||||||
# if not await _spin(lambda: messenger.is_outlet_ready(outlet), timeout=5, quiet=quietness > 0):
|
|
||||||
# print("Error bringing up link")
|
|
||||||
# return 253
|
|
||||||
|
|
||||||
channel.send(protocol.VersionInfoMessage())
|
channel.send(protocol.VersionInfoMessage())
|
||||||
try:
|
try:
|
||||||
vm = _pq.get(timeout=max(outlet.rtt * 20, 5))
|
vm = _pq.get(timeout=max(outlet.rtt * 20, 5))
|
||||||
await _handle_error(vm)
|
await _handle_error(vm)
|
||||||
if not isinstance(vm, protocol.VersionInfoMessage):
|
if not isinstance(vm, protocol.VersionInfoMessage): raise Exception("Invalid message received")
|
||||||
raise Exception("Invalid message received")
|
RNS.log(f"Connected server version info: sw {vm.sw_version}, proto {vm.protocol_version}", RNS.LOG_INFO)
|
||||||
RNS.log(f"Server version info: sw {vm.sw_version} prot {vm.protocol_version}", RNS.LOG_DEBUG)
|
|
||||||
state = InitiatorState.IS_RUNNING
|
state = InitiatorState.IS_RUNNING
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
print("Protocol error")
|
print("Protocol error")
|
||||||
@@ -283,10 +258,8 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
return None
|
return None
|
||||||
elif b == "L":
|
elif b == "L":
|
||||||
line_mode = not line_mode
|
line_mode = not line_mode
|
||||||
if line_mode:
|
if line_mode: os.write(1, "\n\rLine-interactive mode enabled\n\r".encode("utf-8"))
|
||||||
os.write(1, "\n\rLine-interactive mode enabled\n\r".encode("utf-8"))
|
else: os.write(1, "\n\rLine-interactive mode disabled\n\r".encode("utf-8"))
|
||||||
else:
|
|
||||||
os.write(1, "\n\rLine-interactive mode disabled\n\r".encode("utf-8"))
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return b
|
return b
|
||||||
@@ -329,8 +302,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
pre_esc = False
|
pre_esc = False
|
||||||
data.append(b)
|
data.append(b)
|
||||||
|
|
||||||
if not line_mode:
|
if not line_mode: data_buffer.extend(data)
|
||||||
data_buffer.extend(data)
|
|
||||||
else:
|
else:
|
||||||
line_buffer.extend(data)
|
line_buffer.extend(data)
|
||||||
if line_flush:
|
if line_flush:
|
||||||
@@ -344,8 +316,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
blind_write_count += len(data)
|
blind_write_count += len(data)
|
||||||
|
|
||||||
except EOFError:
|
except EOFError:
|
||||||
if os.isatty(0):
|
if os.isatty(0): data_buffer.extend(process.CTRL_D)
|
||||||
data_buffer.extend(process.CTRL_D)
|
|
||||||
stdin_eof = True
|
stdin_eof = True
|
||||||
process.tty_unset_reader_callbacks(sys.stdin.fileno())
|
process.tty_unset_reader_callbacks(sys.stdin.fileno())
|
||||||
|
|
||||||
@@ -398,7 +369,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
if message.stream_id == protocol.StreamDataMessage.STREAM_ID_STDOUT:
|
if message.stream_id == protocol.StreamDataMessage.STREAM_ID_STDOUT:
|
||||||
if message.data and len(message.data) > 0:
|
if message.data and len(message.data) > 0:
|
||||||
ttyRestorer.raw()
|
ttyRestorer.raw()
|
||||||
RNS.log(f"stdout: {message.data}", RNS.LOG_DEBUG)
|
# RNS.log(f"stdout: {message.data}", RNS.LOG_EXTREME)
|
||||||
os.write(1, message.data)
|
os.write(1, message.data)
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
if message.eof:
|
if message.eof:
|
||||||
@@ -406,7 +377,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
if message.stream_id == protocol.StreamDataMessage.STREAM_ID_STDERR:
|
if message.stream_id == protocol.StreamDataMessage.STREAM_ID_STDERR:
|
||||||
if message.data and len(message.data) > 0:
|
if message.data and len(message.data) > 0:
|
||||||
ttyRestorer.raw()
|
ttyRestorer.raw()
|
||||||
RNS.log(f"stdout: {message.data}", RNS.LOG_DEBUG)
|
# RNS.log(f"stdout: {message.data}", RNS.LOG_EXTREME)
|
||||||
os.write(2, message.data)
|
os.write(2, message.data)
|
||||||
sys.stderr.flush()
|
sys.stderr.flush()
|
||||||
if message.eof:
|
if message.eof:
|
||||||
@@ -420,8 +391,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
_link.teardown()
|
_link.teardown()
|
||||||
return 200
|
return 200
|
||||||
|
|
||||||
except queue.Empty:
|
except queue.Empty: processed = False
|
||||||
processed = False
|
|
||||||
|
|
||||||
if channel.is_ready_to_send():
|
if channel.is_ready_to_send():
|
||||||
def compress_adaptive(buf: bytes):
|
def compress_adaptive(buf: bytes):
|
||||||
@@ -435,7 +405,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
chunk_segment = None
|
chunk_segment = None
|
||||||
|
|
||||||
chunk_segment = None
|
chunk_segment = None
|
||||||
max_data_len = channel.mdu - protocol.StreamDataMessage.OVERHEAD
|
max_data_len = channel.mdu - protocol.StreamDataMessage.HEADER_LEN
|
||||||
while chunk_len > 32 and comp_try < comp_tries:
|
while chunk_len > 32 and comp_try < comp_tries:
|
||||||
chunk_segment_length = int(chunk_len/comp_try)
|
chunk_segment_length = int(chunk_len/comp_try)
|
||||||
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
|
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
|
||||||
@@ -443,8 +413,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
if compressed_length < max_data_len and compressed_length < chunk_segment_length:
|
if compressed_length < max_data_len and compressed_length < chunk_segment_length:
|
||||||
comp_success = True
|
comp_success = True
|
||||||
break
|
break
|
||||||
else:
|
else: comp_try += 1
|
||||||
comp_try += 1
|
|
||||||
|
|
||||||
if comp_success:
|
if comp_success:
|
||||||
diff = max_data_len - len(compressed_chunk)
|
diff = max_data_len - len(compressed_chunk)
|
||||||
@@ -473,6 +442,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
|
|||||||
r, c, h, v = process.tty_get_winsize(0)
|
r, c, h, v = process.tty_get_winsize(0)
|
||||||
channel.send(protocol.WindowSizeMessage(r, c, h, v))
|
channel.send(protocol.WindowSizeMessage(r, c, h, v))
|
||||||
processed = True
|
processed = True
|
||||||
|
|
||||||
except RemoteExecutionError as e:
|
except RemoteExecutionError as e:
|
||||||
print(e.msg)
|
print(e.msg)
|
||||||
return 255
|
return 255
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ import RNS.Utilities.rnsh.exception as exception
|
|||||||
import RNS.Utilities.rnsh.process as process
|
import RNS.Utilities.rnsh.process as process
|
||||||
import RNS.Utilities.rnsh.retry as retry
|
import RNS.Utilities.rnsh.retry as retry
|
||||||
import RNS.Utilities.rnsh.session as session
|
import RNS.Utilities.rnsh.session as session
|
||||||
import re
|
|
||||||
import contextlib
|
import contextlib
|
||||||
|
|
||||||
import pwd
|
import pwd
|
||||||
@@ -112,31 +111,38 @@ def _reload_allowed_file():
|
|||||||
def compute_target_rns_loglevel(verbosity: int, quietness: int, base_level: int = RNS.LOG_INFO) -> int:
|
def compute_target_rns_loglevel(verbosity: int, quietness: int, base_level: int = RNS.LOG_INFO) -> int:
|
||||||
try:
|
try:
|
||||||
target = int(base_level) + int(verbosity) - int(quietness)
|
target = int(base_level) + int(verbosity) - int(quietness)
|
||||||
if target < RNS.LOG_CRITICAL: target = RNS.LOG_CRITICAL
|
if target < RNS.LOG_NONE: target = RNS.LOG_NONE
|
||||||
if target > RNS.LOG_DEBUG: target = RNS.LOG_DEBUG
|
if target > RNS.LOG_EXTREME: target = RNS.LOG_EXTREME
|
||||||
return target
|
return target
|
||||||
|
|
||||||
except Exception: return base_level
|
except Exception: return base_level
|
||||||
|
|
||||||
async def listen(configdir, rnsconfigdir, command, identitypath=None, service_name=None, verbosity=0, quietness=0, allowed=None,
|
async def listen(configdir, rnsconfigdir, command, identitypath=None, logfile=None, service_name=None, verbosity=0, quietness=0,
|
||||||
allowed_file=None, disable_auth=None, announce_period=900, no_remote_command=True, remote_cmd_as_args=False,
|
allowed=None, allowed_file=None, disable_auth=None, announce_period=900, no_remote_command=True, remote_cmd_as_args=False,
|
||||||
loop: asyncio.AbstractEventLoop = None):
|
loop: asyncio.AbstractEventLoop = None):
|
||||||
global _identity, _allow_all, _allowed_identity_hashes, _allowed_file, _allowed_file_identity_hashes
|
global _identity, _allow_all, _allowed_identity_hashes, _allowed_file, _allowed_file_identity_hashes
|
||||||
global _reticulum, _cmd, _destination, _no_remote_command, _remote_cmd_as_args, _finished
|
global _reticulum, _cmd, _destination, _no_remote_command, _remote_cmd_as_args, _finished
|
||||||
|
|
||||||
if not loop: loop = asyncio.get_running_loop()
|
if not loop: loop = asyncio.get_running_loop()
|
||||||
if service_name is None or len(service_name) == 0:
|
if service_name is None or len(service_name) == 0: service_name = "default"
|
||||||
service_name = "default"
|
|
||||||
|
|
||||||
RNS.log(f"Using service name {service_name}", RNS.LOG_INFO)
|
RNS.log(f"Using service name {service_name}", RNS.LOG_INFO)
|
||||||
|
if logfile:
|
||||||
|
RNS.log(f"Logging to {logfile}", RNS.LOG_NOTICE)
|
||||||
|
logdest = RNS.LOG_FILE
|
||||||
|
RNS.logfile = logfile
|
||||||
|
else:
|
||||||
|
RNS.log(f"Logging to console", RNS.LOG_NOTICE)
|
||||||
|
logdest = RNS.LOG_STDOUT
|
||||||
|
|
||||||
# More -v should increase verbosity (higher RNS.loglevel); -q should decrease it
|
# More -v should increase verbosity (higher RNS.loglevel); -q should decrease it
|
||||||
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_INFO)
|
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_INFO)
|
||||||
_reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel)
|
_reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel)
|
||||||
_identity = rnsh.prepare_identity(identitypath, service_name)
|
_identity = rnsh.prepare_identity(identity_path=identitypath, service_name=service_name, configdir=configdir)
|
||||||
_destination = RNS.Destination(_identity, RNS.Destination.IN, RNS.Destination.SINGLE, rnsh.APP_NAME)
|
_destination = RNS.Destination(_identity, RNS.Destination.IN, RNS.Destination.SINGLE, rnsh.APP_NAME)
|
||||||
|
|
||||||
RNS.log(f"rnsh listening for commands on {RNS.prettyhexrep(_destination.hash)}", RNS.LOG_NOTICE)
|
RNS.log(f"rnsh listening for commands on {RNS.prettyhexrep(_destination.hash)}", RNS.LOG_NOTICE)
|
||||||
|
RNS.logdest = logdest
|
||||||
|
|
||||||
_cmd = command
|
_cmd = command
|
||||||
if _cmd is None or len(_cmd) == 0:
|
if _cmd is None or len(_cmd) == 0:
|
||||||
@@ -154,9 +160,8 @@ async def listen(configdir, rnsconfigdir, command, identitypath=None, service_na
|
|||||||
_no_remote_command = no_remote_command
|
_no_remote_command = no_remote_command
|
||||||
session.ListenerSession.allow_remote_command = not no_remote_command
|
session.ListenerSession.allow_remote_command = not no_remote_command
|
||||||
_remote_cmd_as_args = remote_cmd_as_args
|
_remote_cmd_as_args = remote_cmd_as_args
|
||||||
if (_cmd is None or len(_cmd) == 0 or _cmd[0] is None or len(_cmd[0]) == 0) \
|
if (_cmd is None or len(_cmd) == 0 or _cmd[0] is None or len(_cmd[0]) == 0) and (_no_remote_command or _remote_cmd_as_args):
|
||||||
and (_no_remote_command or _remote_cmd_as_args):
|
raise Exception(f"Unable to look up shell for {os.getlogin()}, cannot proceed with -A or -C and no <program>.")
|
||||||
raise Exception(f"Unable to look up shell for {os.getlogin}, cannot proceed with -A or -C and no <program>.")
|
|
||||||
|
|
||||||
session.ListenerSession.default_command = _cmd
|
session.ListenerSession.default_command = _cmd
|
||||||
session.ListenerSession.remote_cmd_as_args = _remote_cmd_as_args
|
session.ListenerSession.remote_cmd_as_args = _remote_cmd_as_args
|
||||||
|
|||||||
@@ -488,8 +488,6 @@ class CallbackSubprocess:
|
|||||||
self._stdin_is_pipe = stdin_is_pipe
|
self._stdin_is_pipe = stdin_is_pipe
|
||||||
self._stdout_is_pipe = stdout_is_pipe
|
self._stdout_is_pipe = stdout_is_pipe
|
||||||
self._stderr_is_pipe = stderr_is_pipe
|
self._stderr_is_pipe = stderr_is_pipe
|
||||||
self._at_line_start: bool = True
|
|
||||||
self._tty_line_buffer: bytearray = bytearray()
|
|
||||||
|
|
||||||
def _ensure_pipes_closed(self):
|
def _ensure_pipes_closed(self):
|
||||||
stdin = self._child_stdin
|
stdin = self._child_stdin
|
||||||
@@ -624,14 +622,6 @@ class CallbackSubprocess:
|
|||||||
"""
|
"""
|
||||||
RNS.log("start()", RNS.LOG_EXTREME)
|
RNS.log("start()", RNS.LOG_EXTREME)
|
||||||
|
|
||||||
# # Using the parent environment seems to do some weird stuff, at least on macOS
|
|
||||||
# parentenv = os.environ.copy()
|
|
||||||
# env = {"HOME": parentenv["HOME"],
|
|
||||||
# "PATH": parentenv["PATH"],
|
|
||||||
# "TERM": self._term if self._term is not None else parentenv.get("TERM", "xterm"),
|
|
||||||
# "LANG": parentenv.get("LANG"),
|
|
||||||
# "SHELL": self._command[0]}
|
|
||||||
|
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
for key in self._env:
|
for key in self._env:
|
||||||
env[key] = self._env[key]
|
env[key] = self._env[key]
|
||||||
@@ -639,12 +629,6 @@ class CallbackSubprocess:
|
|||||||
program = self._command[0]
|
program = self._command[0]
|
||||||
assert isinstance(program, str)
|
assert isinstance(program, str)
|
||||||
|
|
||||||
# match = re.search("^/bin/(.*sh)$", program)
|
|
||||||
# if match:
|
|
||||||
# self._command[0] = "-" + match.group(1)
|
|
||||||
# env["SHELL"] = program
|
|
||||||
# self._log.debug(f"set login shell {self._command}")
|
|
||||||
|
|
||||||
self._pid, \
|
self._pid, \
|
||||||
self._child_stdin, \
|
self._child_stdin, \
|
||||||
self._child_stdout, \
|
self._child_stdout, \
|
||||||
|
|||||||
@@ -88,8 +88,7 @@ class RetryThread(AbstractContextManager):
|
|||||||
self._thread = threading.Thread(name=name, target=self._thread_run, daemon=True)
|
self._thread = threading.Thread(name=name, target=self._thread_run, daemon=True)
|
||||||
self._thread.start()
|
self._thread.start()
|
||||||
|
|
||||||
def is_alive(self):
|
def is_alive(self): return self._thread.is_alive()
|
||||||
return self._thread.is_alive()
|
|
||||||
|
|
||||||
def close(self, loop: asyncio.AbstractEventLoop = None) -> asyncio.Future:
|
def close(self, loop: asyncio.AbstractEventLoop = None) -> asyncio.Future:
|
||||||
RNS.log("Stopping timer thread", RNS.LOG_DEBUG)
|
RNS.log("Stopping timer thread", RNS.LOG_DEBUG)
|
||||||
@@ -102,17 +101,12 @@ class RetryThread(AbstractContextManager):
|
|||||||
return self._finished
|
return self._finished
|
||||||
|
|
||||||
def wait(self, timeout: float = None):
|
def wait(self, timeout: float = None):
|
||||||
if timeout:
|
if timeout: timeout = timeout + time.time()
|
||||||
timeout = timeout + time.time()
|
|
||||||
|
|
||||||
while timeout is None or time.time() < timeout:
|
while timeout is None or time.time() < timeout:
|
||||||
with self._lock:
|
with self._lock: task_count = len(self._statuses)
|
||||||
task_count = len(self._statuses)
|
if task_count == 0: return
|
||||||
if task_count == 0:
|
|
||||||
return
|
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
|
||||||
def _thread_run(self):
|
def _thread_run(self):
|
||||||
while self._run and self._finished is None:
|
while self._run and self._finished is None:
|
||||||
time.sleep(self._loop_period)
|
time.sleep(self._loop_period)
|
||||||
|
|||||||
+41
-26
@@ -37,7 +37,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import base64
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import os
|
import os
|
||||||
@@ -57,43 +56,54 @@ loop: asyncio.AbstractEventLoop | None = None
|
|||||||
|
|
||||||
def _sanitize_service_name(service_name:str) -> str: return re.sub(r'\W+', '', service_name)
|
def _sanitize_service_name(service_name:str) -> str: return re.sub(r'\W+', '', service_name)
|
||||||
|
|
||||||
def prepare_identity(identity_path, service_name: str = None) -> tuple[RNS.Identity]:
|
def prepare_identity(identity_path=None, service_name=None, configdir=None):
|
||||||
service_name = _sanitize_service_name(service_name or "")
|
service_name = _sanitize_service_name(service_name or "")
|
||||||
if identity_path is None:
|
if not identity_path:
|
||||||
identity_path = RNS.Reticulum.identitypath + "/" + APP_NAME + \
|
identity_path = f"{configdir}/identity" + (f".{service_name}" if service_name and len(service_name) > 0 else "")
|
||||||
(f".{service_name}" if service_name and len(service_name) > 0 else "")
|
|
||||||
|
|
||||||
identity = None
|
identity = None
|
||||||
if os.path.isfile(identity_path):
|
if os.path.isfile(identity_path):
|
||||||
|
RNS.log(f"Loading identity from {identity_path}", RNS.LOG_VERBOSE)
|
||||||
identity = RNS.Identity.from_file(identity_path)
|
identity = RNS.Identity.from_file(identity_path)
|
||||||
|
|
||||||
if identity is None:
|
if identity is None:
|
||||||
RNS.log("No valid saved identity found, creating new...", RNS.LOG_INFO)
|
RNS.log(f"Creating identity {identity_path}", RNS.LOG_NOTICE)
|
||||||
identity = RNS.Identity()
|
identity = RNS.Identity()
|
||||||
identity.to_file(identity_path)
|
identity.to_file(identity_path)
|
||||||
|
|
||||||
return identity
|
return identity
|
||||||
|
|
||||||
|
|
||||||
def print_identity(configdir, identitypath, service_name, include_destination: bool):
|
def print_identity(configdir, rnsconfigdir, identitypath, service_name, include_destination: bool):
|
||||||
reticulum = RNS.Reticulum(configdir=configdir, loglevel=RNS.LOG_INFO)
|
reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=RNS.LOG_INFO)
|
||||||
if service_name and len(service_name) > 0:
|
if service_name and len(service_name) > 0: print(f"Using service name \"{service_name}\"")
|
||||||
print(f"Using service name \"{service_name}\"")
|
identity = prepare_identity(identity_path=identitypath, service_name=service_name, configdir=configdir)
|
||||||
identity = prepare_identity(identitypath, service_name)
|
|
||||||
destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME)
|
destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME)
|
||||||
print("Identity : " + str(identity))
|
print("Identity : " + str(identity))
|
||||||
if include_destination:
|
if include_destination: print("Listening on : " + RNS.prettyhexrep(destination.hash))
|
||||||
print("Listening on : " + RNS.prettyhexrep(destination.hash))
|
|
||||||
|
|
||||||
exit(0)
|
exit(0)
|
||||||
|
|
||||||
verbose_set = False
|
verbose_set = False
|
||||||
|
|
||||||
def ensure_config_directory():
|
def ensure_config_directory(configdir=None):
|
||||||
if os.path.isdir(os.path.expanduser("~/.config/rnsh")): return os.path.expanduser("~/.config/rnsh")
|
if configdir:
|
||||||
elif os.path.isdir(os.path.expanduser("~/.rnsh")): return os.path.expanduser("~/.rnsh")
|
if os.path.isdir(os.path.expanduser(configdir)): return os.path.expanduser(configdir)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
RNS.log(f"Creating configuration directory: {os.path.expanduser(configdir)}")
|
||||||
|
os.makedirs(os.path.expanduser(configdir))
|
||||||
|
return os.path.expanduser(configdir)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
RNS.log(f"Could not get or create rnsh configuration directory, aborting", RNS.LOG_CRITICAL)
|
||||||
|
os._exit(1)
|
||||||
|
|
||||||
|
elif os.path.isdir(os.path.expanduser("~/.config/rnsh")): return os.path.expanduser("~/.config/rnsh")
|
||||||
|
elif os.path.isdir(os.path.expanduser("~/.rnsh")): return os.path.expanduser("~/.rnsh")
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
|
RNS.log(f"Creating configuration directory: {os.path.expanduser('~/.rnsh')}")
|
||||||
os.makedirs(os.path.expanduser("~/.rnsh"))
|
os.makedirs(os.path.expanduser("~/.rnsh"))
|
||||||
return os.path.expanduser("~/.rnsh")
|
return os.path.expanduser("~/.rnsh")
|
||||||
|
|
||||||
@@ -105,26 +115,30 @@ def ensure_config_directory():
|
|||||||
async def _rnsh_cli_main():
|
async def _rnsh_cli_main():
|
||||||
global verbose_set
|
global verbose_set
|
||||||
args, parser = parse_arguments()
|
args, parser = parse_arguments()
|
||||||
verbose_set = args.verbose > 0
|
verbose_set = args.verbose > 0
|
||||||
|
configdir = ensure_config_directory(args.config)
|
||||||
|
|
||||||
configdir = ensure_config_directory()
|
if not configdir:
|
||||||
|
RNS.log(f"Could not resolve rnsh configuration directory", RNS.LOG_CRITICAL)
|
||||||
|
os._exit(1)
|
||||||
|
|
||||||
if args.print_identity:
|
if args.print_identity:
|
||||||
print_identity(args.config, args.identity, args.service, args.listen)
|
print_identity(configdir, args.rnsconfig, args.identity, args.service, args.listen)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
logfile = f"{configdir}/logfile"
|
||||||
|
|
||||||
if args.listen:
|
if args.listen:
|
||||||
allowed_file = None
|
allowed_file = None
|
||||||
dest_len = (RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2
|
dest_len = (RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2
|
||||||
if os.path.isfile(os.path.expanduser("~/.config/rnsh/allowed_identities")):
|
if os.path.isfile(os.path.expanduser(f"{configdir}/allowed_identities")):
|
||||||
allowed_file = os.path.expanduser("~/.config/rnsh/allowed_identities")
|
allowed_file = os.path.expanduser(f"{configdir}/allowed_identities")
|
||||||
elif os.path.isfile(os.path.expanduser("~/.rnsh/allowed_identities")):
|
|
||||||
allowed_file = os.path.expanduser("~/.rnsh/allowed_identities")
|
|
||||||
|
|
||||||
await listener.listen(configdir=configdir,
|
await listener.listen(configdir=configdir,
|
||||||
rnsconfigdir=args.config,
|
rnsconfigdir=args.rnsconfig,
|
||||||
command=args.command,
|
command=args.command,
|
||||||
identitypath=args.identity,
|
identitypath=args.identity,
|
||||||
|
logfile=logfile,
|
||||||
service_name=args.service,
|
service_name=args.service,
|
||||||
verbosity=args.verbose,
|
verbosity=args.verbose,
|
||||||
quietness=args.quiet,
|
quietness=args.quiet,
|
||||||
@@ -138,8 +152,9 @@ async def _rnsh_cli_main():
|
|||||||
|
|
||||||
if args.destination is not None:
|
if args.destination is not None:
|
||||||
return_code = await initiator.initiate(configdir=configdir,
|
return_code = await initiator.initiate(configdir=configdir,
|
||||||
rnsconfigdir=args.config,
|
rnsconfigdir=args.rnsconfig,
|
||||||
identitypath=args.identity,
|
identitypath=args.identity,
|
||||||
|
logfile=f"{logfile}.initiator",
|
||||||
verbosity=args.verbose,
|
verbosity=args.verbose,
|
||||||
quietness=args.quiet,
|
quietness=args.quiet,
|
||||||
noid=args.no_id,
|
noid=args.no_id,
|
||||||
@@ -147,6 +162,7 @@ async def _rnsh_cli_main():
|
|||||||
timeout=args.timeout,
|
timeout=args.timeout,
|
||||||
command=args.command
|
command=args.command
|
||||||
)
|
)
|
||||||
|
RNS.log(f"Sesssion with <{args.destination}> ended", RNS.LOG_INFO)
|
||||||
return return_code if args.mirror else 0
|
return return_code if args.mirror else 0
|
||||||
else:
|
else:
|
||||||
print("")
|
print("")
|
||||||
@@ -170,5 +186,4 @@ def main():
|
|||||||
if verbose_set and exc: raise exc
|
if verbose_set and exc: raise exc
|
||||||
sys.exit(return_code if return_code is not None else 255)
|
sys.exit(return_code if return_code is not None else 255)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__": main()
|
if __name__ == "__main__": main()
|
||||||
@@ -43,7 +43,6 @@ import RNS.Utilities.rnsh.protocol as protocol
|
|||||||
import enum
|
import enum
|
||||||
from typing import TypeVar, Generic, Callable, List
|
from typing import TypeVar, Generic, Callable, List
|
||||||
from abc import abstractmethod, ABC
|
from abc import abstractmethod, ABC
|
||||||
from multiprocessing import Manager
|
|
||||||
import os
|
import os
|
||||||
import bz2
|
import bz2
|
||||||
import RNS
|
import RNS
|
||||||
@@ -103,6 +102,8 @@ class ListenerSession:
|
|||||||
self.outlet.set_link_closed_callback(self._link_closed)
|
self.outlet.set_link_closed_callback(self._link_closed)
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
self.state: LSState = None
|
self.state: LSState = None
|
||||||
|
self.terminated = False
|
||||||
|
self.authenticated = False
|
||||||
self.remote_identity = None
|
self.remote_identity = None
|
||||||
self.term: str | None = None
|
self.term: str | None = None
|
||||||
self.stdin_is_pipe: bool = False
|
self.stdin_is_pipe: bool = False
|
||||||
@@ -122,8 +123,10 @@ class ListenerSession:
|
|||||||
self.return_code_sent = False
|
self.return_code_sent = False
|
||||||
self.process: process.CallbackSubprocess | None = None
|
self.process: process.CallbackSubprocess | None = None
|
||||||
|
|
||||||
if self.allow_all: self._set_state(LSState.LSSTATE_WAIT_VERS)
|
if not self.allow_all: self._set_state(LSState.LSSTATE_WAIT_IDENT)
|
||||||
else: self._set_state(LSState.LSSTATE_WAIT_IDENT)
|
else:
|
||||||
|
self._set_state(LSState.LSSTATE_WAIT_VERS)
|
||||||
|
self.authenticated = True
|
||||||
|
|
||||||
self.sessions.append(self)
|
self.sessions.append(self)
|
||||||
protocol.register_message_types(self.channel)
|
protocol.register_message_types(self.channel)
|
||||||
@@ -143,37 +146,31 @@ class ListenerSession:
|
|||||||
def _call(self, func: callable, delay: float = 0):
|
def _call(self, func: callable, delay: float = 0):
|
||||||
def call_inner():
|
def call_inner():
|
||||||
if delay == 0: func()
|
if delay == 0: func()
|
||||||
else: self.loop.call_later(delay, func)
|
else: self.loop.call_later(delay, func)
|
||||||
|
|
||||||
self.loop.call_soon_threadsafe(call_inner)
|
self.loop.call_soon_threadsafe(call_inner)
|
||||||
|
|
||||||
def send(self, message: RNS.MessageBase):
|
def send(self, message: RNS.MessageBase): self.channel.send(message)
|
||||||
self.channel.send(message)
|
def _protocol_error(self, name: str): self.terminate(f"Protocol error ({name})")
|
||||||
|
def _protocol_timeout_error(self, name: str): self.terminate(f"Protocol timeout error: {name}")
|
||||||
def _protocol_error(self, name: str):
|
|
||||||
self.terminate(f"Protocol error ({name})")
|
|
||||||
|
|
||||||
def _protocol_timeout_error(self, name: str):
|
|
||||||
self.terminate(f"Protocol timeout error: {name}")
|
|
||||||
|
|
||||||
def terminate(self, error: str = None):
|
def terminate(self, error: str = None):
|
||||||
|
self.terminated = True
|
||||||
|
self.state = LSState.LSSTATE_ERROR
|
||||||
with contextlib.suppress(Exception):
|
with contextlib.suppress(Exception):
|
||||||
RNS.log("Terminating session" + (f": {error}" if error else ""), RNS.LOG_DEBUG)
|
RNS.log("Terminating session" + (f": {error}" if error else ""), RNS.LOG_DEBUG)
|
||||||
if error and self.state != LSState.LSSTATE_TEARDOWN:
|
if error and self.state != LSState.LSSTATE_TEARDOWN:
|
||||||
with contextlib.suppress(Exception):
|
with contextlib.suppress(Exception):
|
||||||
self.send(protocol.ErrorMessage(error, True))
|
self.send(protocol.ErrorMessage(error, True))
|
||||||
|
|
||||||
self.state = LSState.LSSTATE_ERROR
|
|
||||||
self._terminate_process()
|
self._terminate_process()
|
||||||
self._call(self._prune, max(self.outlet.rtt * 3, process.CallbackSubprocess.PROCESS_PIPE_TIME+5))
|
self._call(self._prune, max(self.outlet.rtt * 3, process.CallbackSubprocess.PROCESS_PIPE_TIME+5))
|
||||||
|
|
||||||
def _prune(self):
|
def _prune(self):
|
||||||
self.state = LSState.LSSTATE_TEARDOWN
|
self.state = LSState.LSSTATE_TEARDOWN
|
||||||
RNS.log("Pruning session", RNS.LOG_DEBUG)
|
RNS.log("Pruning session", RNS.LOG_DEBUG)
|
||||||
with contextlib.suppress(ValueError):
|
with contextlib.suppress(ValueError): self.sessions.remove(self)
|
||||||
self.sessions.remove(self)
|
with contextlib.suppress(Exception): self.outlet.teardown()
|
||||||
with contextlib.suppress(Exception):
|
|
||||||
self.outlet.teardown()
|
|
||||||
|
|
||||||
def _check_protocol_timeout(self, fail_condition: Callable[[], bool], name: str):
|
def _check_protocol_timeout(self, fail_condition: Callable[[], bool], name: str):
|
||||||
timeout = True
|
timeout = True
|
||||||
@@ -183,7 +180,6 @@ class ListenerSession:
|
|||||||
|
|
||||||
def _link_closed(self, outlet: LSOutletBase):
|
def _link_closed(self, outlet: LSOutletBase):
|
||||||
outlet.unset_link_closed_callback()
|
outlet.unset_link_closed_callback()
|
||||||
|
|
||||||
if outlet != self.outlet:
|
if outlet != self.outlet:
|
||||||
RNS.log("Link closed received from incorrect outlet", RNS.LOG_DEBUG)
|
RNS.log("Link closed received from incorrect outlet", RNS.LOG_DEBUG)
|
||||||
return
|
return
|
||||||
@@ -196,15 +192,21 @@ class ListenerSession:
|
|||||||
RNS.log("Identity received from incorrect outlet", RNS.LOG_DEBUG)
|
RNS.log("Identity received from incorrect outlet", RNS.LOG_DEBUG)
|
||||||
return
|
return
|
||||||
|
|
||||||
RNS.log(f"initiator_identified {identity} on link {outlet}", RNS.LOG_INFO)
|
RNS.log(f"Initiator identified {identity} on link {outlet}", RNS.LOG_INFO)
|
||||||
if self.state not in [LSState.LSSTATE_WAIT_IDENT, LSState.LSSTATE_WAIT_VERS]:
|
if self.state not in [LSState.LSSTATE_WAIT_IDENT, LSState.LSSTATE_WAIT_VERS]:
|
||||||
self._protocol_error(LSState.LSSTATE_WAIT_IDENT.name)
|
self._protocol_error(LSState.LSSTATE_WAIT_IDENT.name)
|
||||||
|
return
|
||||||
|
|
||||||
if not self.allow_all and identity.hash not in self.allowed_identity_hashes and identity.hash not in self.allowed_file_identity_hashes:
|
if self.allow_all or identity.hash in self.allowed_identity_hashes or identity.hash in self.allowed_file_identity_hashes:
|
||||||
self.terminate("Identity is not allowed.")
|
RNS.log(f"Identity {identity} authenticated")
|
||||||
|
self.authenticated = True
|
||||||
|
self.remote_identity = identity
|
||||||
|
self._set_state(LSState.LSSTATE_WAIT_VERS)
|
||||||
|
|
||||||
self.remote_identity = identity
|
else:
|
||||||
self._set_state(LSState.LSSTATE_WAIT_VERS)
|
self.authenticated = False
|
||||||
|
self.terminate("Identity not allowed")
|
||||||
|
RNS.log(f"Identity {identity} not allowed")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def pump_all(cls) -> True:
|
async def pump_all(cls) -> True:
|
||||||
@@ -233,7 +235,7 @@ class ListenerSession:
|
|||||||
chunk_segment = None
|
chunk_segment = None
|
||||||
|
|
||||||
chunk_segment = None
|
chunk_segment = None
|
||||||
max_data_len = self.channel.mdu - protocol.StreamDataMessage.OVERHEAD
|
max_data_len = self.channel.mdu - protocol.StreamDataMessage.HEADER_LEN
|
||||||
while chunk_len > 32 and comp_try < comp_tries:
|
while chunk_len > 32 and comp_try < comp_tries:
|
||||||
chunk_segment_length = int(chunk_len/comp_try)
|
chunk_segment_length = int(chunk_len/comp_try)
|
||||||
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
|
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
|
||||||
@@ -241,8 +243,7 @@ class ListenerSession:
|
|||||||
if compressed_length < max_data_len and compressed_length < chunk_segment_length:
|
if compressed_length < max_data_len and compressed_length < chunk_segment_length:
|
||||||
comp_success = True
|
comp_success = True
|
||||||
break
|
break
|
||||||
else:
|
else: comp_try += 1
|
||||||
comp_try += 1
|
|
||||||
|
|
||||||
if comp_success:
|
if comp_success:
|
||||||
diff = max_data_len - len(compressed_chunk)
|
diff = max_data_len - len(compressed_chunk)
|
||||||
@@ -255,10 +256,8 @@ class ListenerSession:
|
|||||||
return comp_success, processed_length, chunk
|
return comp_success, processed_length, chunk
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if self.state != LSState.LSSTATE_RUNNING:
|
if self.state != LSState.LSSTATE_RUNNING: return False
|
||||||
return False
|
elif not self.channel.is_ready_to_send(): return False
|
||||||
elif not self.channel.is_ready_to_send():
|
|
||||||
return False
|
|
||||||
elif len(self.stderr_buf) > 0:
|
elif len(self.stderr_buf) > 0:
|
||||||
comp_success, processed_length, data = compress_adaptive(self.stderr_buf)
|
comp_success, processed_length, data = compress_adaptive(self.stderr_buf)
|
||||||
self.stderr_buf = self.stderr_buf[processed_length:]
|
self.stderr_buf = self.stderr_buf[processed_length:]
|
||||||
@@ -267,8 +266,7 @@ class ListenerSession:
|
|||||||
msg = protocol.StreamDataMessage(protocol.StreamDataMessage.STREAM_ID_STDERR,
|
msg = protocol.StreamDataMessage(protocol.StreamDataMessage.STREAM_ID_STDERR,
|
||||||
data, send_eof, comp_success)
|
data, send_eof, comp_success)
|
||||||
self.send(msg)
|
self.send(msg)
|
||||||
if send_eof:
|
if send_eof: self.stderr_eof_sent = True
|
||||||
self.stderr_eof_sent = True
|
|
||||||
return True
|
return True
|
||||||
elif len(self.stdout_buf) > 0:
|
elif len(self.stdout_buf) > 0:
|
||||||
comp_success, processed_length, data = compress_adaptive(self.stdout_buf)
|
comp_success, processed_length, data = compress_adaptive(self.stdout_buf)
|
||||||
@@ -278,8 +276,7 @@ class ListenerSession:
|
|||||||
msg = protocol.StreamDataMessage(protocol.StreamDataMessage.STREAM_ID_STDOUT,
|
msg = protocol.StreamDataMessage(protocol.StreamDataMessage.STREAM_ID_STDOUT,
|
||||||
data, send_eof, comp_success)
|
data, send_eof, comp_success)
|
||||||
self.send(msg)
|
self.send(msg)
|
||||||
if send_eof:
|
if send_eof: self.stdout_eof_sent = True
|
||||||
self.stdout_eof_sent = True
|
|
||||||
return True
|
return True
|
||||||
elif self.return_code is not None and not self.return_code_sent:
|
elif self.return_code is not None and not self.return_code_sent:
|
||||||
msg = protocol.CommandExitedMessage(self.return_code)
|
msg = protocol.CommandExitedMessage(self.return_code)
|
||||||
@@ -295,22 +292,33 @@ class ListenerSession:
|
|||||||
|
|
||||||
def _terminate_process(self):
|
def _terminate_process(self):
|
||||||
with contextlib.suppress(Exception):
|
with contextlib.suppress(Exception):
|
||||||
if self.process and self.process.running:
|
if self.process and self.process.running: self.process.terminate()
|
||||||
self.process.terminate()
|
|
||||||
|
|
||||||
def _start_cmd(self, cmdline: [str], pipe_stdin: bool, pipe_stdout: bool, pipe_stderr: bool, tcflags: [any],
|
def _start_cmd(self, cmdline: [str], pipe_stdin: bool, pipe_stdout: bool, pipe_stderr: bool, tcflags: [any],
|
||||||
term: str | None, rows: int, cols: int, hpix: int, vpix: int):
|
term: str | None, rows: int, cols: int, hpix: int, vpix: int):
|
||||||
|
|
||||||
self.cmdline = self.default_command
|
if self.terminated:
|
||||||
|
RNS.log(f"Attempt to start command on terminated session: {cmdline}", RNS.LOG_WARNING)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not self.authenticated:
|
||||||
|
RNS.log(f"Attempt to start command on unauthenticated session: {cmdline}", RNS.LOG_WARNING)
|
||||||
|
self.terminate("Invalid state")
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.state != LSState.LSSTATE_RUNNING:
|
||||||
|
RNS.log(f"Attempt to start command on session not in running state: {cmdline}", RNS.LOG_WARNING)
|
||||||
|
self.terminate("Invalid state")
|
||||||
|
return
|
||||||
|
|
||||||
|
self.cmdline = []
|
||||||
|
self.cmdline.extend(self.default_command)
|
||||||
if not self.allow_remote_command and cmdline and len(cmdline) > 0:
|
if not self.allow_remote_command and cmdline and len(cmdline) > 0:
|
||||||
self.terminate("Remote command line not allowed by listener")
|
self.terminate("Remote command line not allowed by listener")
|
||||||
return
|
return
|
||||||
|
|
||||||
if self.remote_cmd_as_args and cmdline and len(cmdline) > 0:
|
if self.remote_cmd_as_args and cmdline and len(cmdline) > 0: self.cmdline.extend(cmdline)
|
||||||
self.cmdline.extend(cmdline)
|
elif cmdline and len(cmdline) > 0: self.cmdline = cmdline
|
||||||
elif cmdline and len(cmdline) > 0:
|
|
||||||
self.cmdline = cmdline
|
|
||||||
|
|
||||||
|
|
||||||
self.stdin_is_pipe = pipe_stdin
|
self.stdin_is_pipe = pipe_stdin
|
||||||
self.stdout_is_pipe = pipe_stdout
|
self.stdout_is_pipe = pipe_stdout
|
||||||
@@ -318,13 +326,11 @@ class ListenerSession:
|
|||||||
self.tcflags = tcflags
|
self.tcflags = tcflags
|
||||||
self.term = term
|
self.term = term
|
||||||
|
|
||||||
def stdout(data: bytes):
|
def stdout(data: bytes): self.stdout_buf.extend(data)
|
||||||
self.stdout_buf.extend(data)
|
def stderr(data: bytes): self.stderr_buf.extend(data)
|
||||||
|
|
||||||
def stderr(data: bytes):
|
|
||||||
self.stderr_buf.extend(data)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
RNS.log(f"Remote {self.remote_identity} executing: {self.cmdline}", RNS.LOG_VERBOSE)
|
||||||
self.process = process.CallbackSubprocess(argv=self.cmdline,
|
self.process = process.CallbackSubprocess(argv=self.cmdline,
|
||||||
env={"TERM": self.term or os.environ.get("TERM") or "xterm",
|
env={"TERM": self.term or os.environ.get("TERM") or "xterm",
|
||||||
"RNS_REMOTE_IDENTITY": (RNS.prettyhexrep(self.remote_identity.hash)
|
"RNS_REMOTE_IDENTITY": (RNS.prettyhexrep(self.remote_identity.hash)
|
||||||
@@ -347,22 +353,28 @@ class ListenerSession:
|
|||||||
self.cols = cols
|
self.cols = cols
|
||||||
self.hpix = hpix
|
self.hpix = hpix
|
||||||
self.vpix = vpix
|
self.vpix = vpix
|
||||||
with contextlib.suppress(Exception):
|
with contextlib.suppress(Exception): self.process.set_winsize(rows, cols, hpix, vpix)
|
||||||
self.process.set_winsize(rows, cols, hpix, vpix)
|
|
||||||
|
|
||||||
def _received_stdin(self, data: bytes, eof: bool):
|
def _received_stdin(self, data: bytes, eof: bool):
|
||||||
if data and len(data) > 0:
|
if data and len(data) > 0: self.process.write(data)
|
||||||
self.process.write(data)
|
if eof: self.process.close_stdin()
|
||||||
if eof:
|
|
||||||
self.process.close_stdin()
|
|
||||||
|
|
||||||
def _handle_message(self, message: RNS.MessageBase):
|
def _handle_message(self, message: RNS.MessageBase):
|
||||||
|
if self.terminated:
|
||||||
|
RNS.log(f"Received packet, but session was terminated", RNS.LOG_ERROR)
|
||||||
|
return
|
||||||
|
if self.state > LSState.LSSTATE_RUNNING:
|
||||||
|
RNS.log(f"Received packet, but in state {self.state.name}", RNS.LOG_ERROR)
|
||||||
|
return
|
||||||
if self.state == LSState.LSSTATE_WAIT_IDENT:
|
if self.state == LSState.LSSTATE_WAIT_IDENT:
|
||||||
# Ignore any messages until the initiator has identified to avoid race conditions
|
# Ignore any messages until the initiator has identified to avoid race conditions
|
||||||
# between identity announcement and early protocol messages.
|
# between identity announcement and early protocol messages.
|
||||||
RNS.log("Ignoring message while waiting for identification", RNS.LOG_DEBUG)
|
RNS.log("Ignoring message while waiting for identification", RNS.LOG_DEBUG)
|
||||||
return
|
return
|
||||||
if self.state == LSState.LSSTATE_WAIT_VERS:
|
elif self.state == LSState.LSSTATE_WAIT_VERS:
|
||||||
|
if not self.authenticated:
|
||||||
|
self.terminate("Invalid state")
|
||||||
|
return
|
||||||
if not isinstance(message, protocol.VersionInfoMessage):
|
if not isinstance(message, protocol.VersionInfoMessage):
|
||||||
self._protocol_error(self.state.name)
|
self._protocol_error(self.state.name)
|
||||||
return
|
return
|
||||||
@@ -374,6 +386,9 @@ class ListenerSession:
|
|||||||
self._set_state(LSState.LSSTATE_WAIT_CMD)
|
self._set_state(LSState.LSSTATE_WAIT_CMD)
|
||||||
return
|
return
|
||||||
elif self.state == LSState.LSSTATE_WAIT_CMD:
|
elif self.state == LSState.LSSTATE_WAIT_CMD:
|
||||||
|
if not self.authenticated:
|
||||||
|
self.terminate("Invalid state")
|
||||||
|
return
|
||||||
if not isinstance(message, protocol.ExecuteCommandMesssage):
|
if not isinstance(message, protocol.ExecuteCommandMesssage):
|
||||||
return self._protocol_error(self.state.name)
|
return self._protocol_error(self.state.name)
|
||||||
RNS.log(f"Execute command message on link {self.outlet}: {message.cmdline}", RNS.LOG_VERBOSE)
|
RNS.log(f"Execute command message on link {self.outlet}: {message.cmdline}", RNS.LOG_VERBOSE)
|
||||||
@@ -382,6 +397,9 @@ class ListenerSession:
|
|||||||
message.tcflags, message.term, message.rows, message.cols, message.hpix, message.vpix)
|
message.tcflags, message.term, message.rows, message.cols, message.hpix, message.vpix)
|
||||||
return
|
return
|
||||||
elif self.state == LSState.LSSTATE_RUNNING:
|
elif self.state == LSState.LSSTATE_RUNNING:
|
||||||
|
if not self.authenticated:
|
||||||
|
self.terminate("Invalid state")
|
||||||
|
return
|
||||||
if isinstance(message, protocol.WindowSizeMessage):
|
if isinstance(message, protocol.WindowSizeMessage):
|
||||||
self._set_window_size(message.rows, message.cols, message.hpix, message.vpix)
|
self._set_window_size(message.rows, message.cols, message.hpix, message.vpix)
|
||||||
elif isinstance(message, protocol.StreamDataMessage):
|
elif isinstance(message, protocol.StreamDataMessage):
|
||||||
@@ -394,9 +412,6 @@ class ListenerSession:
|
|||||||
# echo noop only on listener--used for keepalive/connectivity check
|
# echo noop only on listener--used for keepalive/connectivity check
|
||||||
self.send(message)
|
self.send(message)
|
||||||
return
|
return
|
||||||
elif self.state in [LSState.LSSTATE_ERROR, LSState.LSSTATE_TEARDOWN]:
|
|
||||||
RNS.log(f"Received packet, but in state {self.state.name}", RNS.LOG_ERROR)
|
|
||||||
return
|
|
||||||
else:
|
else:
|
||||||
self._protocol_error("unexpected message")
|
self._protocol_error("unexpected message")
|
||||||
return
|
return
|
||||||
@@ -405,29 +420,20 @@ class ListenerSession:
|
|||||||
class RNSOutlet(LSOutletBase):
|
class RNSOutlet(LSOutletBase):
|
||||||
|
|
||||||
def set_initiator_identified_callback(self, cb: Callable[[LSOutletBase, _TIdentity], None]):
|
def set_initiator_identified_callback(self, cb: Callable[[LSOutletBase, _TIdentity], None]):
|
||||||
def inner_cb(link, identity: _TIdentity):
|
def inner_cb(link, identity: _TIdentity): cb(self, identity)
|
||||||
cb(self, identity)
|
|
||||||
|
|
||||||
self.link.set_remote_identified_callback(inner_cb)
|
self.link.set_remote_identified_callback(inner_cb)
|
||||||
|
|
||||||
def set_link_closed_callback(self, cb: Callable[[LSOutletBase], None]):
|
def set_link_closed_callback(self, cb: Callable[[LSOutletBase], None]):
|
||||||
def inner_cb(link):
|
def inner_cb(link): cb(self)
|
||||||
cb(self)
|
|
||||||
|
|
||||||
self.link.set_link_closed_callback(inner_cb)
|
self.link.set_link_closed_callback(inner_cb)
|
||||||
|
|
||||||
def unset_link_closed_callback(self):
|
def unset_link_closed_callback(self): self.link.set_link_closed_callback(None)
|
||||||
self.link.set_link_closed_callback(None)
|
def teardown(self): self.link.teardown()
|
||||||
|
|
||||||
def teardown(self):
|
|
||||||
self.link.teardown()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def rtt(self) -> float:
|
def rtt(self) -> float: return self.link.rtt
|
||||||
return self.link.rtt
|
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self): return f"Outlet on {self.link}"
|
||||||
return f"Outlet RNS Link {self.link}"
|
|
||||||
|
|
||||||
def __init__(self, link: RNS.Link):
|
def __init__(self, link: RNS.Link):
|
||||||
self.link = link
|
self.link = link
|
||||||
@@ -435,7 +441,5 @@ class RNSOutlet(LSOutletBase):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_outlet(link: RNS.Link):
|
def get_outlet(link: RNS.Link):
|
||||||
if hasattr(link, "lsoutlet"):
|
if hasattr(link, "lsoutlet"): return link.lsoutlet
|
||||||
return link.lsoutlet
|
|
||||||
|
|
||||||
return RNSOutlet(link)
|
return RNSOutlet(link)
|
||||||
+163
-23
@@ -152,9 +152,10 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
|
|||||||
|
|
||||||
return request_result
|
return request_result
|
||||||
|
|
||||||
def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=False, astats=False, pstats=False, lstats=False, sorting=None,
|
def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=False, astats=False, pstats=False, lstats=False,
|
||||||
sort_reverse=False, remote=None, management_identity=None, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT, must_exit=True,
|
sorting=None, sort_reverse=False, remote=None, management_identity=None, must_exit=True, rns_instance=None,
|
||||||
rns_instance=None, traffic_totals=False, discovered_interfaces=False, config_entries=False, burst_filter=False):
|
traffic_totals=False, discovered_interfaces=False, config_entries=False, burst_filter=False, blocked_ips=False,
|
||||||
|
queue_stats=False, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
|
||||||
|
|
||||||
if remote: require_shared = False
|
if remote: require_shared = False
|
||||||
else: require_shared = True
|
else: require_shared = True
|
||||||
@@ -172,6 +173,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
else: return
|
else: return
|
||||||
|
|
||||||
link_count = None
|
link_count = None
|
||||||
|
active_link_count = None
|
||||||
stats = None
|
stats = None
|
||||||
|
|
||||||
details = False
|
details = False
|
||||||
@@ -225,15 +227,18 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
location = f"{lat}, {lon}{height}"
|
location = f"{lat}, {lon}{height}"
|
||||||
else: location = "Unknown"
|
else: location = "Unknown"
|
||||||
|
|
||||||
|
lxmf_addr = None
|
||||||
transport_id = None
|
transport_id = None
|
||||||
network = None
|
network = None
|
||||||
|
if "operator_lxmf_address" in i: lxmf_addr = i['operator_lxmf_address']
|
||||||
if "transport_id" in i: transport_id = i["transport_id"]
|
if "transport_id" in i: transport_id = i["transport_id"]
|
||||||
if "transport_id" in i and "network_id" in i and i["transport_id"] != i["network_id"]:
|
if "transport_id" in i and "network_id" in i and i["transport_id"] != i["network_id"]:
|
||||||
network = i["network_id"]
|
network = i["network_id"]
|
||||||
|
|
||||||
if idx > 0: print("\n"+"="*32+"\n")
|
if idx > 0: print("\n"+"="*47+"\n")
|
||||||
if network: print(f"Network ID : {network}")
|
if network: print(f"Network ID : {network}")
|
||||||
if transport_id: print(f"Transport ID : {transport_id}")
|
if transport_id: print(f"Transport ID : {transport_id}")
|
||||||
|
if lxmf_addr: print(f"LXMF address : {lxmf_addr}")
|
||||||
|
|
||||||
print(f"Name : {name}")
|
print(f"Name : {name}")
|
||||||
print(f"Type : {if_type}")
|
print(f"Type : {if_type}")
|
||||||
@@ -258,8 +263,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
config_lines = i["config_entry"].split('\n')
|
config_lines = i["config_entry"].split('\n')
|
||||||
for line in config_lines: print(f" {line}")
|
for line in config_lines: print(f" {line}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e: pass
|
||||||
pass
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print(f"{'Name':<25} {'Type':<12} {'Status':<12} {'Last Heard':<12} {'Value':<8} {'Location':<15}")
|
print(f"{'Name':<25} {'Type':<12} {'Status':<12} {'Last Heard':<12} {'Value':<8} {'Location':<15}")
|
||||||
@@ -336,6 +340,8 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
if lstats:
|
if lstats:
|
||||||
try: link_count = reticulum.get_link_count()
|
try: link_count = reticulum.get_link_count()
|
||||||
except Exception as e: pass
|
except Exception as e: pass
|
||||||
|
try: active_link_count = reticulum.get_active_link_count()
|
||||||
|
except Exception as e: pass
|
||||||
|
|
||||||
try: stats = reticulum.get_interface_stats()
|
try: stats = reticulum.get_interface_stats()
|
||||||
except Exception as e: pass
|
except Exception as e: pass
|
||||||
@@ -379,14 +385,30 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
interfaces.sort(key=lambda i: i["incoming_announce_frequency"], reverse=not sort_reverse)
|
interfaces.sort(key=lambda i: i["incoming_announce_frequency"], reverse=not sort_reverse)
|
||||||
if sorting == "atx":
|
if sorting == "atx":
|
||||||
interfaces.sort(key=lambda i: i["outgoing_announce_frequency"], reverse=not sort_reverse)
|
interfaces.sort(key=lambda i: i["outgoing_announce_frequency"], reverse=not sort_reverse)
|
||||||
|
if sorting == "arxc":
|
||||||
|
interfaces.sort(key=lambda i: i["arxc"], reverse=not sort_reverse)
|
||||||
|
if sorting == "atxc":
|
||||||
|
interfaces.sort(key=lambda i: i["atxc"], reverse=not sort_reverse)
|
||||||
if sorting == "prx":
|
if sorting == "prx":
|
||||||
interfaces.sort(key=lambda i: i["incoming_pr_frequency"], reverse=not sort_reverse)
|
interfaces.sort(key=lambda i: i["incoming_pr_frequency"], reverse=not sort_reverse)
|
||||||
if sorting == "ptx":
|
if sorting == "ptx":
|
||||||
interfaces.sort(key=lambda i: i["outgoing_pr_frequency"], reverse=not sort_reverse)
|
interfaces.sort(key=lambda i: i["outgoing_pr_frequency"], reverse=not sort_reverse)
|
||||||
|
if sorting == "prxc":
|
||||||
|
interfaces.sort(key=lambda i: i["prxc"], reverse=not sort_reverse)
|
||||||
|
if sorting == "ptxc":
|
||||||
|
interfaces.sort(key=lambda i: i["ptxc"], reverse=not sort_reverse)
|
||||||
if sorting == "held":
|
if sorting == "held":
|
||||||
interfaces.sort(key=lambda i: i["held_announces"], reverse=not sort_reverse)
|
interfaces.sort(key=lambda i: i["held_announces"], reverse=not sort_reverse)
|
||||||
|
if sorting == "pvs":
|
||||||
|
interfaces.sort(key=lambda i: i["protocol_violations"], reverse=not sort_reverse)
|
||||||
|
if sorting == "ivs":
|
||||||
|
interfaces.sort(key=lambda i: i["ifac_violations"], reverse=not sort_reverse)
|
||||||
|
if sorting == "flt":
|
||||||
|
interfaces.sort(key=lambda i: i["packet_filter_hits"], reverse=not sort_reverse)
|
||||||
|
if sorting == "gravity" or sorting == "g":
|
||||||
|
interfaces.sort(key=lambda i: i["gravity"], reverse=not sort_reverse)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
for ifstat in interfaces:
|
for ifstat in interfaces:
|
||||||
name = ifstat["name"]
|
name = ifstat["name"]
|
||||||
|
|
||||||
@@ -418,6 +440,8 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
if ifstat["status"]: ss = "Up"
|
if ifstat["status"]: ss = "Up"
|
||||||
else: ss = "Down"
|
else: ss = "Down"
|
||||||
|
|
||||||
|
if "gravity" in ifstat and ifstat["gravity"]: ss += ", gravity "+str(ifstat["gravity"])
|
||||||
|
|
||||||
if ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_ACCESS_POINT: modestr = "Access Point"
|
if ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_ACCESS_POINT: modestr = "Access Point"
|
||||||
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_POINT_TO_POINT: modestr = "Point-to-Point"
|
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_POINT_TO_POINT: modestr = "Point-to-Point"
|
||||||
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_ROAMING: modestr = "Roaming"
|
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_ROAMING: modestr = "Roaming"
|
||||||
@@ -425,7 +449,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_GATEWAY: modestr = "Gateway"
|
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_GATEWAY: modestr = "Gateway"
|
||||||
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_INTERNAL: modestr = "Internal"
|
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_INTERNAL: modestr = "Internal"
|
||||||
else: modestr = "Full"
|
else: modestr = "Full"
|
||||||
|
if "announces_to_internal" in ifstat and ifstat["announces_to_internal"]: modestr += " (a>i)"
|
||||||
|
|
||||||
if ifstat["clients"] != None:
|
if ifstat["clients"] != None:
|
||||||
clients = ifstat["clients"]
|
clients = ifstat["clients"]
|
||||||
@@ -450,6 +474,12 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
clients_string = ""
|
clients_string = ""
|
||||||
else:
|
else:
|
||||||
clients_string = "Clients : "+str(clients)
|
clients_string = "Clients : "+str(clients)
|
||||||
|
if "blocked_ips" in ifstat:
|
||||||
|
p = ifstat["blocked_ips"] > 0
|
||||||
|
if p: clients_string += "\n Blocked : "+str(ifstat["blocked_ips"])+" IP"+"s" if p else ""
|
||||||
|
|
||||||
|
if blocked_ips and "blocked_ip_list" in ifstat and len(ifstat["blocked_ip_list"]) > 0:
|
||||||
|
for bip in ifstat["blocked_ip_list"]: clients_string += f"\n {bip}"
|
||||||
|
|
||||||
else:
|
else:
|
||||||
clients = None
|
clients = None
|
||||||
@@ -468,7 +498,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
print(" "+clients_string)
|
print(" "+clients_string)
|
||||||
|
|
||||||
if not (name.startswith("Shared Instance[") or name.startswith("TCPInterface[Client") or name.startswith("LocalInterface[")):
|
if not (name.startswith("Shared Instance[") or name.startswith("TCPInterface[Client") or name.startswith("LocalInterface[")):
|
||||||
print(" Mode : {mode}".format(mode=modestr))
|
print(f" Mode : {modestr}")
|
||||||
|
|
||||||
if "bitrate" in ifstat and ifstat["bitrate"] != None:
|
if "bitrate" in ifstat and ifstat["bitrate"] != None:
|
||||||
print(" Rate : {ss}".format(ss=speed_str(ifstat["bitrate"])))
|
print(" Rate : {ss}".format(ss=speed_str(ifstat["bitrate"])))
|
||||||
@@ -565,13 +595,17 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
|
|
||||||
burst_str = ""
|
burst_str = ""
|
||||||
if "burst_active" in ifstat and ifstat["burst_active"]:
|
if "burst_active" in ifstat and ifstat["burst_active"]:
|
||||||
|
if "burst_count" in ifstat and ifstat["burst_count"]: bcstr = f"on {ifstat['burst_count']} "
|
||||||
|
else: bcstr = ""
|
||||||
for_str = RNS.prettytime(time.time()-ifstat["burst_activated"])
|
for_str = RNS.prettytime(time.time()-ifstat["burst_activated"])
|
||||||
burst_str = f" burst for {for_str}"
|
burst_str = f" burst {bcstr}for {for_str}"
|
||||||
|
|
||||||
pburst_str = ""
|
pburst_str = ""
|
||||||
if "pr_burst_active" in ifstat and ifstat["pr_burst_active"]:
|
if "pr_burst_active" in ifstat and ifstat["pr_burst_active"]:
|
||||||
|
if "pr_burst_count" in ifstat and ifstat["pr_burst_count"]: prbcstr = f"on {ifstat['pr_burst_count']} "
|
||||||
|
else: prbcstr = ""
|
||||||
for_str = RNS.prettytime(time.time()-ifstat["pr_burst_activated"])
|
for_str = RNS.prettytime(time.time()-ifstat["pr_burst_activated"])
|
||||||
pburst_str = f"burst for {for_str}"
|
pburst_str = f"burst {prbcstr}for {for_str}"
|
||||||
|
|
||||||
rxb_str = "↓"+RNS.prettysize(ifstat["rxb"])
|
rxb_str = "↓"+RNS.prettysize(ifstat["rxb"])
|
||||||
txb_str = "↑"+RNS.prettysize(ifstat["txb"])
|
txb_str = "↑"+RNS.prettysize(ifstat["txb"])
|
||||||
@@ -586,8 +620,16 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
|
|
||||||
cspec = "c"
|
cspec = "c"
|
||||||
if clients == None and "peers" in ifstat and ifstat["peers"]: clients = ifstat["peers"]; cspec = "p"
|
if clients == None and "peers" in ifstat and ifstat["peers"]: clients = ifstat["peers"]; cspec = "p"
|
||||||
if clients != None and clients > 0: pc_str = f"{RNS.prettyfrequency(ifstat['outgoing_announce_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
if clients != None and clients > 0: pc_str = f" {RNS.prettyfrequency(ifstat['outgoing_announce_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
||||||
else: pc_str = ""
|
else: pc_str = ""
|
||||||
|
|
||||||
|
if "prxs" in ifstat and "rxs" in ifstat and "ptxs" in ifstat and "txs" in ifstat:
|
||||||
|
arxspct = min(100.0, (ifstat["arxs"] / ifstat["rxs"])*100.0) if ifstat["rxs"] and ifstat["arxs"] else 0.0
|
||||||
|
atxspct = min(100.0, (ifstat["atxs"] / ifstat["txs"])*100.0) if ifstat["txs"] and ifstat["atxs"] else 0.0
|
||||||
|
apctstr = f"(↓{int(arxspct)}% / ↑{int(atxspct)}% of flow)"
|
||||||
|
if pc_str: pc_str = f"{pc_str} {apctstr}"
|
||||||
|
else: pc_str = f"{apctstr}"
|
||||||
|
|
||||||
asr = True
|
asr = True
|
||||||
|
|
||||||
psr = False
|
psr = False
|
||||||
@@ -603,8 +645,16 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
ipf = RNS.prettyfrequency(ipn,d=1, lpf=True)+"↓"
|
ipf = RNS.prettyfrequency(ipn,d=1, lpf=True)+"↓"
|
||||||
cspec = "c"
|
cspec = "c"
|
||||||
if clients == None and "peers" in ifstat and ifstat["peers"]: clients = ifstat["peers"]; cspec = "p"
|
if clients == None and "peers" in ifstat and ifstat["peers"]: clients = ifstat["peers"]; cspec = "p"
|
||||||
if clients != None and clients > 0: rpc_str = f"{RNS.prettyfrequency(ifstat['outgoing_pr_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
if clients != None and clients > 0: rpc_str = f" {RNS.prettyfrequency(ifstat['outgoing_pr_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
||||||
else: rpc_str = ""
|
else: rpc_str = ""
|
||||||
|
|
||||||
|
if "prxs" in ifstat and "rxs" in ifstat and "ptxs" in ifstat and "txs" in ifstat:
|
||||||
|
prxspct = min(100.0, (ifstat["prxs"] / ifstat["rxs"])*100.0) if ifstat["rxs"] and ifstat["prxs"] else 0.0
|
||||||
|
ptxspct = min(100.0, (ifstat["ptxs"] / ifstat["txs"])*100.0) if ifstat["txs"] and ifstat["ptxs"] else 0.0
|
||||||
|
ppctstr = f"(↓{int(prxspct)}% / ↑{int(ptxspct)}% of flow)"
|
||||||
|
if rpc_str: rpc_str = f"{rpc_str} {ppctstr}"
|
||||||
|
else: rpc_str = f"{ppctstr}"
|
||||||
|
|
||||||
psr = True
|
psr = True
|
||||||
|
|
||||||
if not asr: iaf = ""; oaf = ""
|
if not asr: iaf = ""; oaf = ""
|
||||||
@@ -620,12 +670,30 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
rxb_str += (mlen-len(rxb_str))*" "
|
rxb_str += (mlen-len(rxb_str))*" "
|
||||||
txb_str += (mlen-len(txb_str))*" "
|
txb_str += (mlen-len(txb_str))*" "
|
||||||
|
|
||||||
|
if "protocol_violations" in ifstat and "ifac_violations" in ifstat:
|
||||||
|
pv = ifstat["protocol_violations"]; iv = ifstat["ifac_violations"]
|
||||||
|
if pv or iv:
|
||||||
|
pvstr = f"{pv} protocol{', ' if iv else ''}"
|
||||||
|
ivstr = f"{iv} IFAC" if iv else ""
|
||||||
|
print(f" Violatns. : {pvstr}{ivstr}")
|
||||||
|
|
||||||
|
if "packet_filter_hits" in ifstat and ifstat["packet_filter_hits"]:
|
||||||
|
print(f" Flt. Hits : {ifstat['packet_filter_hits']}")
|
||||||
|
|
||||||
if psr:
|
if psr:
|
||||||
print(f" Path Rqs. : {opf} {rpc_str}")
|
if ifstat["prxc"] and ifstat["ptxc"]:
|
||||||
|
print(f" Path Rqs. : {ifstat['prxc']}↓ {ifstat['ptxc']}↑ total")
|
||||||
|
print(f" {opf} {rpc_str}")
|
||||||
|
else:
|
||||||
|
print(f" Path Rqs. : {opf} {rpc_str}")
|
||||||
print(f" {ipf} {pburst_str}")
|
print(f" {ipf} {pburst_str}")
|
||||||
|
|
||||||
if asr:
|
if asr:
|
||||||
print(f" Announces : {oaf} {pc_str}")
|
if ifstat["arxc"] and ifstat["atxc"]:
|
||||||
|
print(f" Announces : {ifstat['arxc']}↓ {ifstat['atxc']}↑ total")
|
||||||
|
print(f" {oaf} {pc_str}")
|
||||||
|
else:
|
||||||
|
print(f" Announces : {oaf} {pc_str}")
|
||||||
print(f" {iaf} {art_str}{burst_str}")
|
print(f" {iaf} {art_str}{burst_str}")
|
||||||
|
|
||||||
rxstat = rxb_str
|
rxstat = rxb_str
|
||||||
@@ -644,19 +712,87 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
|||||||
else:
|
else:
|
||||||
lstr = f" {link_count} entr{ms} in link table"
|
lstr = f" {link_count} entr{ms} in link table"
|
||||||
|
|
||||||
|
if active_link_count: lstr = f"{lstr} ({active_link_count} active)"
|
||||||
|
|
||||||
if traffic_totals:
|
if traffic_totals:
|
||||||
rxb_str = "↓"+RNS.prettysize(stats["rxb"])
|
rxb_str = "↓"+RNS.prettysize(stats["rxb"])
|
||||||
txb_str = "↑"+RNS.prettysize(stats["txb"])
|
txb_str = "↑"+RNS.prettysize(stats["txb"])
|
||||||
strdiff = len(rxb_str)-len(txb_str)
|
strdiff = len(rxb_str)-len(txb_str)
|
||||||
if strdiff > 0:
|
if strdiff > 0: txb_str += " "*strdiff
|
||||||
txb_str += " "*strdiff
|
elif strdiff < 0: rxb_str += " "*-strdiff
|
||||||
elif strdiff < 0:
|
|
||||||
rxb_str += " "*-strdiff
|
|
||||||
|
|
||||||
rxstat = rxb_str+" "+RNS.prettyspeed(stats["rxs"])
|
rxstat = rxb_str+" "+RNS.prettyspeed(stats["rxs"])
|
||||||
txstat = txb_str+" "+RNS.prettyspeed(stats["txs"])
|
txstat = txb_str+" "+RNS.prettyspeed(stats["txs"])
|
||||||
|
|
||||||
|
if pstats or astats:
|
||||||
|
if "prxs" in stats and "ptxs" in stats and "arxs" in stats and "atxs" in stats:
|
||||||
|
parxs = stats["prxs"]+stats["arxs"]
|
||||||
|
patxs = stats["ptxs"]+stats["atxs"]
|
||||||
|
drxpct = 100.0-min(100.0, (parxs / stats["rxs"])*100.0) if stats["rxs"] else 100.0
|
||||||
|
dtxpct = 100.0-min(100.0, (patxs / stats["txs"])*100.0) if stats["txs"] else 100.0
|
||||||
|
drxs = stats["rxs"]*(drxpct/100.0)
|
||||||
|
dtxs = stats["txs"]*(dtxpct/100.0)
|
||||||
|
|
||||||
|
if stats["rxs"] > 0: rxstat = f"{rxstat}, {int(drxpct)}% data ({RNS.prettyspeed(drxs)})"
|
||||||
|
if stats["txs"] > 0: txstat = f"{txstat}, {int(dtxpct)}% data ({RNS.prettyspeed(dtxs)})"
|
||||||
|
|
||||||
print(f"\n Totals : {txstat}\n {rxstat}")
|
print(f"\n Totals : {txstat}\n {rxstat}")
|
||||||
|
|
||||||
|
if pstats:
|
||||||
|
if "prxb" in stats and "ptxb" in stats and "prxs" in stats and "ptxs" in stats:
|
||||||
|
prxb_str = "↓"+RNS.prettysize(stats["prxb"])
|
||||||
|
ptxb_str = "↑"+RNS.prettysize(stats["ptxb"])
|
||||||
|
strdiff = len(prxb_str)-len(ptxb_str)
|
||||||
|
if strdiff > 0: ptxb_str += " "*strdiff
|
||||||
|
elif strdiff < 0: prxb_str += " "*-strdiff
|
||||||
|
|
||||||
|
prxspct = min(100.0, (stats["prxs"] / stats["rxs"])*100.0) if stats["rxs"] and stats["prxs"] else 0.0
|
||||||
|
ptxspct = min(100.0, (stats["ptxs"] / stats["txs"])*100.0) if stats["txs"] and stats["ptxs"] else 0.0
|
||||||
|
|
||||||
|
prxfstr = RNS.prettyfrequency(stats["prxf"])
|
||||||
|
ptxfstr = RNS.prettyfrequency(stats["ptxf"])
|
||||||
|
|
||||||
|
prxstat = prxb_str+" "+RNS.prettyspeed(stats["prxs"])+f", {int(prxspct)}% of flow, {prxfstr}"
|
||||||
|
ptxstat = ptxb_str+" "+RNS.prettyspeed(stats["ptxs"])+f", {int(ptxspct)}% of flow, {ptxfstr}"
|
||||||
|
print(f"\n Path Rqs. : {ptxstat}\n {prxstat}")
|
||||||
|
|
||||||
|
if astats:
|
||||||
|
if "arxb" in stats and "atxb" in stats and "arxs" in stats and "atxs" in stats:
|
||||||
|
arxb_str = "↓"+RNS.prettysize(stats["arxb"])
|
||||||
|
atxb_str = "↑"+RNS.prettysize(stats["atxb"])
|
||||||
|
strdiff = len(arxb_str)-len(atxb_str)
|
||||||
|
if strdiff > 0: atxb_str += " "*strdiff
|
||||||
|
elif strdiff < 0: arxb_str += " "*-strdiff
|
||||||
|
|
||||||
|
arxspct = min(100.0, (stats["arxs"] / stats["rxs"])*100.0) if stats["rxs"] and stats["arxs"] else 0.0
|
||||||
|
atxspct = min(100.0, (stats["atxs"] / stats["txs"])*100.0) if stats["txs"] and stats["atxs"] else 0.0
|
||||||
|
|
||||||
|
arxfstr = RNS.prettyfrequency(stats["arxf"])
|
||||||
|
atxfstr = RNS.prettyfrequency(stats["atxf"])
|
||||||
|
|
||||||
|
arxstat = arxb_str+" "+RNS.prettyspeed(stats["arxs"])+f", {int(arxspct)}% of flow, {arxfstr}"
|
||||||
|
atxstat = atxb_str+" "+RNS.prettyspeed(stats["atxs"])+f", {int(atxspct)}% of flow, {atxfstr}"
|
||||||
|
print(f"\n Announces : {atxstat}\n {arxstat}")
|
||||||
|
|
||||||
|
|
||||||
|
if queue_stats:
|
||||||
|
tqdp = f", {stats['rxqtd']} dropped" if stats['rxqtd'] else ""
|
||||||
|
dqdp = f", {stats['rxqdd']} dropped" if stats['rxqdd'] else ""
|
||||||
|
aqdp = f", {stats['rxqad']} dropped" if stats['rxqad'] else ""
|
||||||
|
pqdp = f", {stats['rxqpd']} dropped" if stats['rxqpd'] else ""
|
||||||
|
ilqdp = f", {stats['rxqild']} dropped" if stats['rxqild'] else ""
|
||||||
|
tqpress = f"{round(stats['tqpressure']*100.0, 1)}% total, {stats['rxqt']} pkts{tqdp}"
|
||||||
|
dqpress = f"{round(stats['dqpressure']*100.0, 1)}% data, {stats['rxqd']} pkts{dqdp}"
|
||||||
|
aqpress = f"{round(stats['aqpressure']*100.0, 1)}% announce, {stats['rxqa']} pkts{aqdp}"
|
||||||
|
pqpress = f"{round(stats['pqpressure']*100.0, 1)}% path request, {stats['rxqp']} pkts{pqdp}"
|
||||||
|
ilpress = f"{round(stats['ilqpressure']*100.0, 1)}% ingress limiter, {stats['rxqil']} pkts{ilqdp}"
|
||||||
|
|
||||||
|
print(f"\n Qu. Pressure : {tqpress}")
|
||||||
|
print(f" {dqpress}")
|
||||||
|
print(f" {aqpress}")
|
||||||
|
print(f" {pqpress}")
|
||||||
|
print(f" {ilpress}")
|
||||||
|
|
||||||
if "transport_id" in stats and stats["transport_id"] != None:
|
if "transport_id" in stats and stats["transport_id"] != None:
|
||||||
print("\n Transport Instance "+RNS.prettyhexrep(stats["transport_id"])+" running")
|
print("\n Transport Instance "+RNS.prettyhexrep(stats["transport_id"])+" running")
|
||||||
if "network_id" in stats and stats["network_id"] != None:
|
if "network_id" in stats and stats["network_id"] != None:
|
||||||
@@ -692,8 +828,10 @@ def main(must_exit=True, rns_instance=None):
|
|||||||
parser.add_argument("-P", "--pr-stats", action="store_true", help="show path request stats", default=False)
|
parser.add_argument("-P", "--pr-stats", action="store_true", help="show path request stats", default=False)
|
||||||
parser.add_argument("-l", "--link-stats", action="store_true", help="show link stats", default=False)
|
parser.add_argument("-l", "--link-stats", action="store_true", help="show link stats", default=False)
|
||||||
parser.add_argument("-B", "--burst", action="store_true", help="only show interfaces with active bursts", default=False)
|
parser.add_argument("-B", "--burst", action="store_true", help="only show interfaces with active bursts", default=False)
|
||||||
|
parser.add_argument("-b", "--blocked-ips", action="store_true", help="show blocked IPs per interface", default=False)
|
||||||
parser.add_argument("-t", "--totals", action="store_true", help="display traffic totals", default=False)
|
parser.add_argument("-t", "--totals", action="store_true", help="display traffic totals", default=False)
|
||||||
parser.add_argument("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx, held]", default=None, type=str)
|
parser.add_argument("-q", "--queues", action="store_true", help="display queue stats", default=False)
|
||||||
|
parser.add_argument("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, announces, arx, atx, arxc, atxc, held, prx, ptx, prxc, ptxc, pvs, ivs, flt]", default=None, type=str)
|
||||||
parser.add_argument("-r", "--reverse", action="store_true", help="reverse sorting", default=False)
|
parser.add_argument("-r", "--reverse", action="store_true", help="reverse sorting", default=False)
|
||||||
parser.add_argument("-j", "--json", action="store_true", help="output in JSON format", default=False)
|
parser.add_argument("-j", "--json", action="store_true", help="output in JSON format", default=False)
|
||||||
parser.add_argument("-R", action="store", metavar="hash", help="transport identity hash of remote instance to get status from", default=None, type=str)
|
parser.add_argument("-R", action="store", metavar="hash", help="transport identity hash of remote instance to get status from", default=None, type=str)
|
||||||
@@ -730,7 +868,8 @@ def main(must_exit=True, rns_instance=None):
|
|||||||
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
|
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
|
||||||
astats=args.announce_stats, pstats=args.pr_stats, lstats=args.link_stats, sorting=args.sort, sort_reverse=args.reverse,
|
astats=args.announce_stats, pstats=args.pr_stats, lstats=args.link_stats, sorting=args.sort, sort_reverse=args.reverse,
|
||||||
remote=args.R, management_identity=args.i, remote_timeout=args.w, must_exit=False, rns_instance=reticulum,
|
remote=args.R, management_identity=args.i, remote_timeout=args.w, must_exit=False, rns_instance=reticulum,
|
||||||
traffic_totals=args.totals, discovered_interfaces=args.discovered, config_entries=args.D, burst_filter=args.burst)
|
traffic_totals=args.totals, discovered_interfaces=args.discovered, config_entries=args.D, burst_filter=args.burst,
|
||||||
|
blocked_ips=args.blocked_ips, queue_stats=args.queues)
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
sys.stdout = old_stdout
|
sys.stdout = old_stdout
|
||||||
@@ -747,7 +886,8 @@ def main(must_exit=True, rns_instance=None):
|
|||||||
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
|
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
|
||||||
astats=args.announce_stats, pstats=args.pr_stats, lstats=args.link_stats, sorting=args.sort, sort_reverse=args.reverse,
|
astats=args.announce_stats, pstats=args.pr_stats, lstats=args.link_stats, sorting=args.sort, sort_reverse=args.reverse,
|
||||||
remote=args.R, management_identity=args.i, remote_timeout=args.w, must_exit=must_exit, rns_instance=rns_instance,
|
remote=args.R, management_identity=args.i, remote_timeout=args.w, must_exit=must_exit, rns_instance=rns_instance,
|
||||||
traffic_totals=args.totals, discovered_interfaces=args.discovered, config_entries=args.D, burst_filter=args.burst)
|
traffic_totals=args.totals, discovered_interfaces=args.discovered, config_entries=args.D, burst_filter=args.burst,
|
||||||
|
blocked_ips=args.blocked_ips, queue_stats=args.queues)
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("")
|
print("")
|
||||||
|
|||||||
@@ -347,7 +347,7 @@ def execute(configdir, identitypath = None, verbosity = 0, quietness = 0, detail
|
|||||||
|
|
||||||
if not RNS.Transport.has_path(destination_hash):
|
if not RNS.Transport.has_path(destination_hash):
|
||||||
RNS.Transport.request_path(destination_hash)
|
RNS.Transport.request_path(destination_hash)
|
||||||
if not spin(until=lambda: RNS.Transport.has_path(destination_hash), msg="Path to "+RNS.prettyhexrep(destination_hash)+" requested", timeout=timeout):
|
if not spin(until=lambda: RNS.Transport.has_path(destination_hash), msg="Path to "+RNS.prettyhexrep(destination_hash)+" requested", timeout=max(timeout, reticulum.get_medium_path_timeout())):
|
||||||
print("Path not found")
|
print("Path not found")
|
||||||
exit(242)
|
exit(242)
|
||||||
|
|
||||||
@@ -365,7 +365,7 @@ def execute(configdir, identitypath = None, verbosity = 0, quietness = 0, detail
|
|||||||
link = RNS.Link(listener_destination)
|
link = RNS.Link(listener_destination)
|
||||||
link.did_identify = False
|
link.did_identify = False
|
||||||
|
|
||||||
if not spin(until=lambda: link.status == RNS.Link.ACTIVE, msg="Establishing link with "+RNS.prettyhexrep(destination_hash), timeout=timeout):
|
if not spin(until=lambda: link.status == RNS.Link.ACTIVE, msg="Establishing link with "+RNS.prettyhexrep(destination_hash), timeout=max(timeout, link.establishment_timeout)):
|
||||||
print("Could not establish link with "+RNS.prettyhexrep(destination_hash))
|
print("Could not establish link with "+RNS.prettyhexrep(destination_hash))
|
||||||
exit(243)
|
exit(243)
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -70,7 +70,8 @@ LOG_NOTICE = 3
|
|||||||
LOG_INFO = 4
|
LOG_INFO = 4
|
||||||
LOG_VERBOSE = 5
|
LOG_VERBOSE = 5
|
||||||
LOG_DEBUG = 6
|
LOG_DEBUG = 6
|
||||||
LOG_EXTREME = 7
|
LOG_PATHING = 7
|
||||||
|
LOG_EXTREME = 8
|
||||||
|
|
||||||
LOG_STDOUT = 0x91
|
LOG_STDOUT = 0x91
|
||||||
LOG_FILE = 0x92
|
LOG_FILE = 0x92
|
||||||
@@ -102,6 +103,7 @@ def loglevelname(level):
|
|||||||
if (level == LOG_INFO): return "[Info] "
|
if (level == LOG_INFO): return "[Info] "
|
||||||
if (level == LOG_VERBOSE): return "[Verbose] "
|
if (level == LOG_VERBOSE): return "[Verbose] "
|
||||||
if (level == LOG_DEBUG): return "[Debug] "
|
if (level == LOG_DEBUG): return "[Debug] "
|
||||||
|
if (level == LOG_PATHING): return "[Pathing] "
|
||||||
if (level == LOG_EXTREME): return "[Extra] "
|
if (level == LOG_EXTREME): return "[Extra] "
|
||||||
|
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
__version__ = "1.3.8"
|
__version__ = "1.5.0"
|
||||||
Vendored
+23
-42
@@ -6,14 +6,12 @@ from . import utils
|
|||||||
from .log import logger
|
from .log import logger
|
||||||
|
|
||||||
def parse_reply(data):
|
def parse_reply(data):
|
||||||
if not data:
|
if not data: raise ConnectionAbortedError("Empty response: SAM API went offline")
|
||||||
raise ConnectionAbortedError("Empty response: SAM API went offline")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
msg = sam.Message(data.decode().strip())
|
msg = sam.Message(data.decode().strip())
|
||||||
logger.debug("SAM reply: "+str(msg))
|
logger.debug("SAM reply: "+str(msg))
|
||||||
except:
|
except: raise ConnectionAbortedError("Invalid SAM response")
|
||||||
raise ConnectionAbortedError("Invalid SAM response")
|
|
||||||
|
|
||||||
return msg
|
return msg
|
||||||
|
|
||||||
@@ -28,8 +26,7 @@ async def get_sam_socket(sam_address=sam.DEFAULT_ADDRESS, loop=None):
|
|||||||
reader, writer = await asyncio.open_connection(*sam_address)
|
reader, writer = await asyncio.open_connection(*sam_address)
|
||||||
writer.write(sam.hello("3.1", "3.1"))
|
writer.write(sam.hello("3.1", "3.1"))
|
||||||
reply = parse_reply(await reader.readline())
|
reply = parse_reply(await reader.readline())
|
||||||
if reply.ok:
|
if reply.ok: return (reader, writer)
|
||||||
return (reader, writer)
|
|
||||||
else:
|
else:
|
||||||
writer.close()
|
writer.close()
|
||||||
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
|
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
|
||||||
@@ -49,10 +46,8 @@ async def dest_lookup(domain, sam_address=sam.DEFAULT_ADDRESS,
|
|||||||
writer.write(sam.naming_lookup(domain))
|
writer.write(sam.naming_lookup(domain))
|
||||||
reply = parse_reply(await reader.readline())
|
reply = parse_reply(await reader.readline())
|
||||||
writer.close()
|
writer.close()
|
||||||
if reply.ok:
|
if reply.ok: return sam.Destination(reply["VALUE"])
|
||||||
return sam.Destination(reply["VALUE"])
|
else: raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
|
||||||
else:
|
|
||||||
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
|
|
||||||
|
|
||||||
async def new_destination(sam_address=sam.DEFAULT_ADDRESS, loop=None,
|
async def new_destination(sam_address=sam.DEFAULT_ADDRESS, loop=None,
|
||||||
sig_type=sam.Destination.default_sig_type):
|
sig_type=sam.Destination.default_sig_type):
|
||||||
@@ -91,15 +86,10 @@ async def create_session(session_name, sam_address=sam.DEFAULT_ADDRESS,
|
|||||||
"""
|
"""
|
||||||
logger.debug("Creating session {}".format(session_name))
|
logger.debug("Creating session {}".format(session_name))
|
||||||
if destination:
|
if destination:
|
||||||
if type(destination) == sam.Destination:
|
if type(destination) == sam.Destination: destination = destination
|
||||||
destination = destination
|
else: destination = sam.Destination(destination, has_private_key=True)
|
||||||
else:
|
|
||||||
destination = sam.Destination(
|
|
||||||
destination, has_private_key=True)
|
|
||||||
|
|
||||||
dest_string = destination.private_key.base64
|
dest_string = destination.private_key.base64
|
||||||
else:
|
else: dest_string = sam.TRANSIENT_DESTINATION
|
||||||
dest_string = sam.TRANSIENT_DESTINATION
|
|
||||||
|
|
||||||
options = " ".join(["{}={}".format(k, v) for k, v in options.items()])
|
options = " ".join(["{}={}".format(k, v) for k, v in options.items()])
|
||||||
|
|
||||||
@@ -109,9 +99,7 @@ async def create_session(session_name, sam_address=sam.DEFAULT_ADDRESS,
|
|||||||
|
|
||||||
reply = parse_reply(await reader.readline())
|
reply = parse_reply(await reader.readline())
|
||||||
if reply.ok:
|
if reply.ok:
|
||||||
if not destination:
|
if not destination: destination = sam.Destination(reply["DESTINATION"], has_private_key=True)
|
||||||
destination = sam.Destination(
|
|
||||||
reply["DESTINATION"], has_private_key=True)
|
|
||||||
logger.debug(destination.base32)
|
logger.debug(destination.base32)
|
||||||
logger.debug("Session created {}".format(session_name))
|
logger.debug("Session created {}".format(session_name))
|
||||||
return (reader, writer)
|
return (reader, writer)
|
||||||
@@ -130,10 +118,8 @@ async def stream_connect(session_name, destination,
|
|||||||
:return: A (reader, writer) pair
|
:return: A (reader, writer) pair
|
||||||
"""
|
"""
|
||||||
logger.debug("Connecting stream {}".format(session_name))
|
logger.debug("Connecting stream {}".format(session_name))
|
||||||
if isinstance(destination, str) and not destination.endswith(".i2p"):
|
if isinstance(destination, str) and not destination.endswith(".i2p"): destination = sam.Destination(destination)
|
||||||
destination = sam.Destination(destination)
|
elif isinstance(destination, str): destination = await dest_lookup(destination, sam_address, loop)
|
||||||
elif isinstance(destination, str):
|
|
||||||
destination = await dest_lookup(destination, sam_address, loop)
|
|
||||||
|
|
||||||
reader, writer = await get_sam_socket(sam_address, loop)
|
reader, writer = await get_sam_socket(sam_address, loop)
|
||||||
writer.write(sam.stream_connect(session_name, destination.base64,
|
writer.write(sam.stream_connect(session_name, destination.base64,
|
||||||
@@ -158,8 +144,7 @@ async def stream_accept(session_name, sam_address=sam.DEFAULT_ADDRESS,
|
|||||||
reader, writer = await get_sam_socket(sam_address, loop)
|
reader, writer = await get_sam_socket(sam_address, loop)
|
||||||
writer.write(sam.stream_accept(session_name, silent="false"))
|
writer.write(sam.stream_accept(session_name, silent="false"))
|
||||||
reply = parse_reply(await reader.readline())
|
reply = parse_reply(await reader.readline())
|
||||||
if reply.ok:
|
if reply.ok: return (reader, writer)
|
||||||
return (reader, writer)
|
|
||||||
else:
|
else:
|
||||||
writer.close()
|
writer.close()
|
||||||
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
|
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
|
||||||
@@ -183,9 +168,9 @@ class Session:
|
|||||||
:return: :class:`Session` object
|
:return: :class:`Session` object
|
||||||
"""
|
"""
|
||||||
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS,
|
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS,
|
||||||
loop=None, style="STREAM",
|
loop=None, style="STREAM", signature_type=sam.Destination.default_sig_type,
|
||||||
signature_type=sam.Destination.default_sig_type,
|
destination=None, options={}):
|
||||||
destination=None, options={}):
|
|
||||||
self.session_name = session_name
|
self.session_name = session_name
|
||||||
self.sam_address = sam_address
|
self.sam_address = sam_address
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
@@ -195,10 +180,9 @@ class Session:
|
|||||||
self.options = options
|
self.options = options
|
||||||
|
|
||||||
async def __aenter__(self):
|
async def __aenter__(self):
|
||||||
self.reader, self.writer = await create_session(self.session_name,
|
self.reader, self.writer = await create_session(self.session_name, sam_address=self.sam_address, loop=self.loop,
|
||||||
sam_address=self.sam_address, loop=self.loop, style=self.style,
|
style=self.style, signature_type=self.signature_type,
|
||||||
signature_type=self.signature_type,
|
destination=self.destination, options=self.options)
|
||||||
destination=self.destination, options=self.options)
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
async def __aexit__(self, exc_type, exc, tb):
|
async def __aexit__(self, exc_type, exc, tb):
|
||||||
@@ -214,16 +198,15 @@ class StreamConnection:
|
|||||||
:param loop: (optional) Event loop instance
|
:param loop: (optional) Event loop instance
|
||||||
:return: :class:`StreamConnection` object
|
:return: :class:`StreamConnection` object
|
||||||
"""
|
"""
|
||||||
def __init__(self, session_name, destination,
|
def __init__(self, session_name, destination, sam_address=sam.DEFAULT_ADDRESS, loop=None):
|
||||||
sam_address=sam.DEFAULT_ADDRESS, loop=None):
|
|
||||||
self.session_name = session_name
|
self.session_name = session_name
|
||||||
self.sam_address = sam_address
|
self.sam_address = sam_address
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
self.destination = destination
|
self.destination = destination
|
||||||
|
|
||||||
async def __aenter__(self):
|
async def __aenter__(self):
|
||||||
self.reader, self.writer = await stream_connect(self.session_name,
|
self.reader, self.writer = await stream_connect(self.session_name, self.destination,
|
||||||
self.destination, sam_address=self.sam_address, loop=self.loop)
|
sam_address=self.sam_address, loop=self.loop)
|
||||||
self.read = self.reader.read
|
self.read = self.reader.read
|
||||||
self.write = self.writer.write
|
self.write = self.writer.write
|
||||||
return self
|
return self
|
||||||
@@ -240,15 +223,13 @@ class StreamAcceptor:
|
|||||||
:param loop: (optional) Event loop instance
|
:param loop: (optional) Event loop instance
|
||||||
:return: :class:`StreamAcceptor` object
|
:return: :class:`StreamAcceptor` object
|
||||||
"""
|
"""
|
||||||
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS,
|
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS, loop=None):
|
||||||
loop=None):
|
|
||||||
self.session_name = session_name
|
self.session_name = session_name
|
||||||
self.sam_address = sam_address
|
self.sam_address = sam_address
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
|
|
||||||
async def __aenter__(self):
|
async def __aenter__(self):
|
||||||
self.reader, self.writer = await stream_accept(self.session_name,
|
self.reader, self.writer = await stream_accept(self.session_name, sam_address=self.sam_address, loop=self.loop)
|
||||||
sam_address=self.sam_address, loop=self.loop)
|
|
||||||
self.read = self.reader.read
|
self.read = self.reader.read
|
||||||
self.write = self.writer.write
|
self.write = self.writer.write
|
||||||
return self
|
return self
|
||||||
|
|||||||
Vendored
+9
-12
@@ -30,15 +30,12 @@ class PeerNotFound(SAMException):
|
|||||||
class Timeout(SAMException):
|
class Timeout(SAMException):
|
||||||
"""The peer cannot be found on the network"""
|
"""The peer cannot be found on the network"""
|
||||||
|
|
||||||
SAM_EXCEPTIONS = {
|
SAM_EXCEPTIONS = { "CANT_REACH_PEER": CantReachPeer,
|
||||||
"CANT_REACH_PEER": CantReachPeer,
|
"DUPLICATED_DEST": DuplicatedDest,
|
||||||
"DUPLICATED_DEST": DuplicatedDest,
|
"DUPLICATED_ID": DuplicatedId,
|
||||||
"DUPLICATED_ID": DuplicatedId,
|
"I2P_ERROR": I2PError,
|
||||||
"I2P_ERROR": I2PError,
|
"INVALID_ID": InvalidId,
|
||||||
"INVALID_ID": InvalidId,
|
"INVALID_KEY": InvalidKey,
|
||||||
"INVALID_KEY": InvalidKey,
|
"KEY_NOT_FOUND": KeyNotFound,
|
||||||
"KEY_NOT_FOUND": KeyNotFound,
|
"PEER_NOT_FOUND": PeerNotFound,
|
||||||
"PEER_NOT_FOUND": PeerNotFound,
|
"TIMEOUT": Timeout }
|
||||||
"TIMEOUT": Timeout,
|
|
||||||
}
|
|
||||||
|
|
||||||
Vendored
+2
-5
@@ -3,7 +3,6 @@ from hashlib import sha256
|
|||||||
import struct
|
import struct
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
|
||||||
I2P_B64_CHARS = "-~"
|
I2P_B64_CHARS = "-~"
|
||||||
|
|
||||||
def i2p_b64encode(x):
|
def i2p_b64encode(x):
|
||||||
@@ -41,11 +40,9 @@ class Message(object):
|
|||||||
return self.opts[key]
|
return self.opts[key]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def ok(self):
|
def ok(self): return self["RESULT"] == "OK"
|
||||||
return self["RESULT"] == "OK"
|
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self): return self._reply_string
|
||||||
return self._reply_string
|
|
||||||
|
|
||||||
|
|
||||||
# SAM request messages
|
# SAM request messages
|
||||||
|
|||||||
Vendored
+58
-67
@@ -15,15 +15,13 @@ async def proxy_data(reader, writer):
|
|||||||
while True:
|
while True:
|
||||||
data = await reader.read(BUFFER_SIZE)
|
data = await reader.read(BUFFER_SIZE)
|
||||||
if not data:
|
if not data:
|
||||||
|
logger.debug('no more data')
|
||||||
break
|
break
|
||||||
writer.write(data)
|
writer.write(data)
|
||||||
except Exception as e:
|
except Exception as e: logger.debug('proxy_data_task exception {}'.format(e))
|
||||||
logger.debug('proxy_data_task exception {}'.format(e))
|
|
||||||
finally:
|
finally:
|
||||||
try:
|
try: writer.close()
|
||||||
writer.close()
|
except RuntimeError: pass
|
||||||
except RuntimeError:
|
|
||||||
pass
|
|
||||||
logger.debug('close connection')
|
logger.debug('close connection')
|
||||||
|
|
||||||
class I2PTunnel(object):
|
class I2PTunnel(object):
|
||||||
@@ -44,6 +42,7 @@ class I2PTunnel(object):
|
|||||||
|
|
||||||
def __init__(self, local_address, destination=None, session_name=None,
|
def __init__(self, local_address, destination=None, session_name=None,
|
||||||
options={}, loop=None, sam_address=sam.DEFAULT_ADDRESS):
|
options={}, loop=None, sam_address=sam.DEFAULT_ADDRESS):
|
||||||
|
|
||||||
self.local_address = local_address
|
self.local_address = local_address
|
||||||
self.destination = destination
|
self.destination = destination
|
||||||
self.session_name = session_name or utils.generate_session_id()
|
self.session_name = session_name or utils.generate_session_id()
|
||||||
@@ -53,16 +52,13 @@ class I2PTunnel(object):
|
|||||||
|
|
||||||
async def _pre_run(self):
|
async def _pre_run(self):
|
||||||
if not self.destination:
|
if not self.destination:
|
||||||
self.destination = await aiosam.new_destination(
|
self.destination = await aiosam.new_destination(sam_address=self.sam_address, loop=self.loop)
|
||||||
sam_address=self.sam_address, loop=self.loop)
|
|
||||||
_, self.session_writer = await aiosam.create_session(
|
|
||||||
self.session_name, style=self.style, options=self.options,
|
|
||||||
sam_address=self.sam_address,
|
|
||||||
loop=self.loop, destination=self.destination)
|
|
||||||
|
|
||||||
def stop(self):
|
_, self.session_writer = await aiosam.create_session(self.session_name, style=self.style, options=self.options,
|
||||||
"""Stop the tunnel"""
|
sam_address=self.sam_address,
|
||||||
self.session_writer.close()
|
loop=self.loop, destination=self.destination)
|
||||||
|
|
||||||
|
def stop(self): self.session_writer.close()
|
||||||
|
|
||||||
class ClientTunnel(I2PTunnel):
|
class ClientTunnel(I2PTunnel):
|
||||||
"""Client tunnel, a subclass of tunnel.I2PTunnel
|
"""Client tunnel, a subclass of tunnel.I2PTunnel
|
||||||
@@ -85,20 +81,25 @@ class ClientTunnel(I2PTunnel):
|
|||||||
"""A coroutine used to run the tunnel"""
|
"""A coroutine used to run the tunnel"""
|
||||||
await self._pre_run()
|
await self._pre_run()
|
||||||
|
|
||||||
self.status = { "setup_ran": False, "setup_failed": False, "exception": None, "connect_tasks": [] }
|
self.status = { "setup_ran": False, "setup_failed": False, "exception": None,
|
||||||
|
"connect_tasks": set(), "background_tasks": set() }
|
||||||
|
|
||||||
async def handle_client(client_reader, client_writer):
|
async def handle_client(client_reader, client_writer):
|
||||||
"""Handle local client connection"""
|
"""Handle local client connection"""
|
||||||
try:
|
try:
|
||||||
sc_task = aiosam.stream_connect(
|
sc_task = aiosam.stream_connect(self.session_name, self.remote_destination,
|
||||||
self.session_name, self.remote_destination,
|
sam_address=self.sam_address, loop=self.loop)
|
||||||
sam_address=self.sam_address, loop=self.loop)
|
|
||||||
self.status["connect_tasks"].append(sc_task)
|
self.status["connect_tasks"].add(sc_task)
|
||||||
|
|
||||||
remote_reader, remote_writer = await sc_task
|
remote_reader, remote_writer = await sc_task
|
||||||
asyncio.ensure_future(proxy_data(remote_reader, client_writer),
|
task = asyncio.ensure_future(proxy_data(remote_reader, client_writer), loop=self.loop)
|
||||||
loop=self.loop)
|
self.status["background_tasks"].add(task)
|
||||||
asyncio.ensure_future(proxy_data(client_reader, remote_writer),
|
task.add_done_callback(self.status["background_tasks"].discard)
|
||||||
loop=self.loop)
|
|
||||||
|
task = asyncio.ensure_future(proxy_data(client_reader, remote_writer), loop=self.loop)
|
||||||
|
self.status["background_tasks"].add(task)
|
||||||
|
task.add_done_callback(self.status["background_tasks"].discard)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status["setup_ran"] = True
|
self.status["setup_ran"] = True
|
||||||
@@ -135,14 +136,15 @@ class ServerTunnel(I2PTunnel):
|
|||||||
"""A coroutine used to run the tunnel"""
|
"""A coroutine used to run the tunnel"""
|
||||||
await self._pre_run()
|
await self._pre_run()
|
||||||
|
|
||||||
self.status = { "setup_ran": False, "setup_failed": False, "exception": None, "connect_tasks": [] }
|
self.status = { "setup_ran": False, "setup_failed": False, "exception": None,
|
||||||
|
"connect_tasks": set(), "background_tasks": set() }
|
||||||
|
|
||||||
async def handle_client(incoming, client_reader, client_writer):
|
async def handle_client(incoming, client_reader, client_writer):
|
||||||
try:
|
try:
|
||||||
# data and dest may come in one chunk
|
# data and dest may come in one chunk
|
||||||
dest, data = incoming.split(b"\n", 1)
|
dest, data = incoming.split(b"\n", 1)
|
||||||
remote_destination = sam.Destination(dest.decode())
|
remote_destination = sam.Destination(dest.decode())
|
||||||
logger.debug("{} client connected: {}.b32.i2p".format(
|
logger.debug("{} client connected: {}.b32.i2p".format(self.session_name, remote_destination.base32))
|
||||||
self.session_name, remote_destination.base32))
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status["exception"] = e
|
self.status["exception"] = e
|
||||||
@@ -150,21 +152,20 @@ class ServerTunnel(I2PTunnel):
|
|||||||
data = None
|
data = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sc_task = asyncio.wait_for(
|
sc_task = asyncio.wait_for(asyncio.open_connection(host=self.local_address[0], port=self.local_address[1]), timeout=5)
|
||||||
asyncio.open_connection(
|
self.status["connect_tasks"].add(sc_task)
|
||||||
host=self.local_address[0],
|
|
||||||
port=self.local_address[1]),
|
|
||||||
timeout=5)
|
|
||||||
self.status["connect_tasks"].append(sc_task)
|
|
||||||
|
|
||||||
remote_reader, remote_writer = await sc_task
|
remote_reader, remote_writer = await sc_task
|
||||||
if data: remote_writer.write(data)
|
if data: remote_writer.write(data)
|
||||||
asyncio.ensure_future(proxy_data(remote_reader, client_writer),
|
task = asyncio.ensure_future(proxy_data(remote_reader, client_writer), loop=self.loop)
|
||||||
loop=self.loop)
|
self.status["background_tasks"].add(task)
|
||||||
asyncio.ensure_future(proxy_data(client_reader, remote_writer),
|
task.add_done_callback(self.status["background_tasks"].discard)
|
||||||
loop=self.loop)
|
|
||||||
|
|
||||||
except ConnectionRefusedError:
|
task = asyncio.ensure_future(proxy_data(client_reader, remote_writer), loop=self.loop)
|
||||||
|
self.status["background_tasks"].add(task)
|
||||||
|
task.add_done_callback(self.status["background_tasks"].discard)
|
||||||
|
|
||||||
|
except ConnectionRefusedError as e:
|
||||||
client_writer.close()
|
client_writer.close()
|
||||||
self.status["exception"] = e
|
self.status["exception"] = e
|
||||||
self.status["setup_failed"] = True
|
self.status["setup_failed"] = True
|
||||||
@@ -172,14 +173,14 @@ class ServerTunnel(I2PTunnel):
|
|||||||
async def server_loop():
|
async def server_loop():
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
client_reader, client_writer = await aiosam.stream_accept(
|
client_reader, client_writer = await aiosam.stream_accept(self.session_name, sam_address=self.sam_address,
|
||||||
self.session_name, sam_address=self.sam_address,
|
loop=self.loop)
|
||||||
loop=self.loop)
|
|
||||||
incoming = await client_reader.read(BUFFER_SIZE)
|
incoming = await client_reader.read(BUFFER_SIZE)
|
||||||
asyncio.ensure_future(handle_client(
|
task = asyncio.ensure_future(handle_client(incoming, client_reader, client_writer), loop=self.loop)
|
||||||
incoming, client_reader, client_writer), loop=self.loop)
|
self.status["background_tasks"].add(task)
|
||||||
except asyncio.CancelledError:
|
task.add_done_callback(self.status["background_tasks"].discard)
|
||||||
pass
|
|
||||||
|
except asyncio.CancelledError: pass
|
||||||
|
|
||||||
self.server_loop = asyncio.ensure_future(server_loop(), loop=self.loop)
|
self.server_loop = asyncio.ensure_future(server_loop(), loop=self.loop)
|
||||||
self.status["setup_ran"] = True
|
self.status["setup_ran"] = True
|
||||||
@@ -191,16 +192,11 @@ class ServerTunnel(I2PTunnel):
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument('type', metavar="TYPE", choices=('server', 'client'),
|
parser.add_argument('type', metavar="TYPE", choices=('server', 'client'), help="Tunnel type (server or client)")
|
||||||
help="Tunnel type (server or client)")
|
parser.add_argument('address', metavar="ADDRESS", help="Local address (e.g. 127.0.0.1:8000)")
|
||||||
parser.add_argument('address', metavar="ADDRESS",
|
parser.add_argument('--debug', '-d', action='store_true', help='Debugging')
|
||||||
help="Local address (e.g. 127.0.0.1:8000)")
|
parser.add_argument('--key', '-k', default='', metavar='PRIVATE_KEY', help='Path to private key file')
|
||||||
parser.add_argument('--debug', '-d', action='store_true',
|
parser.add_argument('--destination', '-D', default='', metavar='DESTINATION', help='Remote destination')
|
||||||
help='Debugging')
|
|
||||||
parser.add_argument('--key', '-k', default='', metavar='PRIVATE_KEY',
|
|
||||||
help='Path to private key file')
|
|
||||||
parser.add_argument('--destination', '-D', default='',
|
|
||||||
metavar='DESTINATION', help='Remote destination')
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
SAM_ADDRESS = utils.get_sam_address()
|
SAM_ADDRESS = utils.get_sam_address()
|
||||||
@@ -209,26 +205,21 @@ if __name__ == '__main__':
|
|||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
loop.set_debug(args.debug)
|
loop.set_debug(args.debug)
|
||||||
|
|
||||||
if args.key:
|
if args.key: destination = sam.Destination(path=args.key, has_private_key=True)
|
||||||
destination = sam.Destination(path=args.key, has_private_key=True)
|
else: destination = None
|
||||||
else:
|
|
||||||
destination = None
|
|
||||||
|
|
||||||
local_address = utils.address_from_string(args.address)
|
local_address = utils.address_from_string(args.address)
|
||||||
|
|
||||||
if args.type == "client":
|
if args.type == "client":
|
||||||
tunnel = ClientTunnel(args.destination, local_address, loop=loop,
|
tunnel = ClientTunnel(args.destination, local_address, loop=loop, destination=destination, sam_address=SAM_ADDRESS)
|
||||||
destination=destination, sam_address=SAM_ADDRESS)
|
|
||||||
elif args.type == "server":
|
elif args.type == "server":
|
||||||
tunnel = ServerTunnel(local_address, loop=loop, destination=destination,
|
tunnel = ServerTunnel(local_address, loop=loop, destination=destination, sam_address=SAM_ADDRESS)
|
||||||
sam_address=SAM_ADDRESS)
|
|
||||||
|
|
||||||
asyncio.ensure_future(tunnel.run(), loop=loop)
|
asyncio.ensure_future(tunnel.run(), loop=loop)
|
||||||
|
|
||||||
try:
|
try: loop.run_forever()
|
||||||
loop.run_forever()
|
except KeyboardInterrupt: tunnel.stop()
|
||||||
except KeyboardInterrupt:
|
|
||||||
tunnel.stop()
|
|
||||||
finally:
|
finally:
|
||||||
loop.stop()
|
loop.stop()
|
||||||
loop.close()
|
loop.close()
|
||||||
Binary file not shown.
Binary file not shown.
@@ -1,4 +1,4 @@
|
|||||||
# Sphinx build info version 1
|
# Sphinx build info version 1
|
||||||
# This file records the configuration used when building these files. When it is not found, a full rebuild will be done.
|
# This file records the configuration used when building these files. When it is not found, a full rebuild will be done.
|
||||||
config: 5f1bb7356498498f06570848af4171af
|
config: e9bf292f6fd8e17bc5dda6fda8e6c07e
|
||||||
tags: 645f666f9bcd5a90fca523b33c5a78b7
|
tags: 645f666f9bcd5a90fca523b33c5a78b7
|
||||||
@@ -230,6 +230,51 @@ specify the target Yggdrasil IPv6 address and port, like so:
|
|||||||
target_host = 201:5d78:af73:5caf:a4de:a79f:3278:71e5
|
target_host = 201:5d78:af73:5caf:a4de:a79f:3278:71e5
|
||||||
target_port = 4343
|
target_port = 4343
|
||||||
|
|
||||||
|
Automated Blocking
|
||||||
|
------------------
|
||||||
|
Listener instances of ``BackboneInterface`` will automatically block fast-flapping clients,
|
||||||
|
that repeatedly connect for a short amount of time, and then disconnect. Such behavior usually
|
||||||
|
occurs from clients trying to spam the network with announces or path requests, by connecting, dumping
|
||||||
|
a massive amount of requests, and then disconnecting in an attempt to bypass rate limits.
|
||||||
|
|
||||||
|
While such bypass attempts only have very limited effect on the amount of spam actually dumped (ingress limits
|
||||||
|
trigger immediately once a client exceeds rate limits), the behavior is often seen anyways, and
|
||||||
|
causes log noise and needless interface rotation. The fast-flapping block ensures such clients
|
||||||
|
are never allocated an interface on the transport instance.
|
||||||
|
|
||||||
|
Another common cause can simply be clients using implementations that are broken, or automated
|
||||||
|
scanning tools attempting to connect to the instance.
|
||||||
|
|
||||||
|
.. code:: ini
|
||||||
|
|
||||||
|
[[Backbone Listener]]
|
||||||
|
type = BackboneInterface
|
||||||
|
enabled = yes
|
||||||
|
listen_on = 0.0.0.0
|
||||||
|
port = 4242
|
||||||
|
|
||||||
|
# Whether to enable blocking
|
||||||
|
block_fast_flapping = yes
|
||||||
|
|
||||||
|
# How long an IP address stays
|
||||||
|
# blocked, in minutes. Set to
|
||||||
|
# 12 hours by default.
|
||||||
|
fast_flapping_block_time = 720
|
||||||
|
|
||||||
|
# The minimum time, in seconds,
|
||||||
|
# an interface must stay connected
|
||||||
|
# to be considered not fast-flapping.
|
||||||
|
fast_flapping_threshold = 20
|
||||||
|
|
||||||
|
# Amount of fast flaps a remote
|
||||||
|
# IP can perform before having
|
||||||
|
# blocking triggered.
|
||||||
|
fast_flapping_grace = 5
|
||||||
|
|
||||||
|
The configuration options listed in the example above are the *default values*, and you do
|
||||||
|
not need to add them for automated blocking to work, but you can use them to change the
|
||||||
|
behavior from the defaults, if necessary.
|
||||||
|
|
||||||
.. _interfaces-tcps:
|
.. _interfaces-tcps:
|
||||||
|
|
||||||
TCP Server Interface
|
TCP Server Interface
|
||||||
@@ -953,6 +998,9 @@ When ``discoverable`` is enabled, a variety of additional options become availab
|
|||||||
``discovery_name``
|
``discovery_name``
|
||||||
A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
||||||
|
|
||||||
|
``discovery_lxmf_address``
|
||||||
|
An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.
|
||||||
|
|
||||||
``announce_interval``
|
``announce_interval``
|
||||||
The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
||||||
|
|
||||||
@@ -998,7 +1046,13 @@ On a real system, you should make the script robust enough to deal with intermit
|
|||||||
**Physical Location**
|
**Physical Location**
|
||||||
|
|
||||||
``latitude``, ``longitude``, ``height``
|
``latitude``, ``longitude``, ``height``
|
||||||
Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters.
|
Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters above mean sea level.
|
||||||
|
|
||||||
|
``location_cmd``
|
||||||
|
Optional path to executable or script that returns the physical coordinates for the interface. This can be used instead of manually setting ``latitude``, ``longitude`` and ``height``. Reticulum expects the script to output the location data to ``stdout`` on a single line, separated by commas, with values as floating point numbers in the format ``LAT, LON, HEIGHT``. Coordinates should be in decimal degrees, height in meters above mean sea level.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
The height value for interface discovery is specified in *height above mean sea level*! This is the geoid-corrected height value, and is distinct from GPS altitude. If you manually specify height, it will typically be set to what you find on a topographical map. If you are using a script to output the location data, make sure that you are using the geoid-corrected altitude, not height above the GPS ellipsoid. Most GPS systems will make both figures available.
|
||||||
|
|
||||||
**Radio Parameters**
|
**Radio Parameters**
|
||||||
|
|
||||||
@@ -1149,6 +1203,15 @@ These can be used to control various aspects of interface behaviour.
|
|||||||
expected to connect momentarily, use the network, and then
|
expected to connect momentarily, use the network, and then
|
||||||
disappear again.
|
disappear again.
|
||||||
|
|
||||||
|
- See the :ref:`Interface Modes<interfaces-modes>` section
|
||||||
|
below for a reference on additional modes.
|
||||||
|
|
||||||
|
* | The ``gravity`` option specifies the pathing affinity of an interface.
|
||||||
|
If not set specifically, and unless otherwise configured by
|
||||||
|
``default_gravity`` or ``autoconnect_interface_gravity``,
|
||||||
|
it defaults to ``0``. Positive values increase pathing affinity,
|
||||||
|
and negative values decrease it.
|
||||||
|
|
||||||
* | The ``outgoing`` option sets whether an interface is allowed
|
* | The ``outgoing`` option sets whether an interface is allowed
|
||||||
to transmit. Defaults to ``True``. If set to ``False`` or ``No``
|
to transmit. Defaults to ``True``. If set to ``False`` or ``No``
|
||||||
the interface will only receive data, and never transmit.
|
the interface will only receive data, and never transmit.
|
||||||
@@ -1223,6 +1286,11 @@ These can be used to control various aspects of interface behaviour.
|
|||||||
``internal`` mode interfaces may still be resolvable by means
|
``internal`` mode interfaces may still be resolvable by means
|
||||||
of path requests.
|
of path requests.
|
||||||
|
|
||||||
|
|
||||||
|
* | To allow an interface that would *otherwise not* propagate
|
||||||
|
announces to ``internal`` mode interfaces to do so, you can
|
||||||
|
configure the ``announces_to_internal`` option to ``True``.
|
||||||
|
|
||||||
.. _interfaces-modes:
|
.. _interfaces-modes:
|
||||||
|
|
||||||
Interface Modes
|
Interface Modes
|
||||||
@@ -1502,4 +1570,34 @@ but all the parameters are exposed for configuration if needed.
|
|||||||
|
|
||||||
All of the above settings can be configured both as instance-wide defaults
|
All of the above settings can be configured both as instance-wide defaults
|
||||||
under the ``[reticulum]`` section of the configuration file, or on a per-
|
under the ``[reticulum]`` section of the configuration file, or on a per-
|
||||||
interface basis under the relevant interface configuration section.
|
interface basis under the relevant interface configuration section.
|
||||||
|
|
||||||
|
|
||||||
|
Tuning Ingress Queues
|
||||||
|
=====================
|
||||||
|
|
||||||
|
Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:
|
||||||
|
|
||||||
|
1. Data and general traffic
|
||||||
|
|
||||||
|
2. Announces
|
||||||
|
|
||||||
|
3. Path requests
|
||||||
|
|
||||||
|
4. Ingress-limited traffic
|
||||||
|
|
||||||
|
You can tune the queue sizes from the defaults, for example if you're running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the ``[reticulum]`` section of the config
|
||||||
|
|
||||||
|
* | The ``qlen_in_data`` option sets the maximum size of the data
|
||||||
|
queue. Defaults to ``4096``.
|
||||||
|
|
||||||
|
* | The ``qlen_in_announce`` option sets the maximum size of the announce
|
||||||
|
queue. Defaults to ``256``.
|
||||||
|
|
||||||
|
* | The ``qlen_in_pr`` option sets the maximum size of the path request
|
||||||
|
queue. Defaults to ``256``.
|
||||||
|
|
||||||
|
* | The ``qlen_in_il`` option sets the maximum size of the ingress limiter
|
||||||
|
queue. Defaults to ``128``.
|
||||||
|
|
||||||
|
If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.
|
||||||
@@ -759,6 +759,8 @@ Or, represented in table form:
|
|||||||
✓ Will rebroadcast announce
|
✓ Will rebroadcast announce
|
||||||
✕ Will not rebroadcast announce
|
✕ Will not rebroadcast announce
|
||||||
|
|
||||||
|
For a visually intuitive overview of how announce propagation rules function in practice, you can take a look at the `Announce Propagation Simulator <https://rns.moscow/announce-sim.html>`_ hosted by `rns.moscow <https://rns.moscow/>`_.
|
||||||
|
|
||||||
|
|
||||||
.. _understanding-primitives:
|
.. _understanding-primitives:
|
||||||
|
|
||||||
|
|||||||
@@ -337,8 +337,8 @@ Filter output to only show some interfaces:
|
|||||||
|
|
||||||
.. code:: text
|
.. code:: text
|
||||||
|
|
||||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||||
|
|
||||||
Reticulum Network Stack Status
|
Reticulum Network Stack Status
|
||||||
@@ -352,10 +352,14 @@ Filter output to only show some interfaces:
|
|||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-a, --all show all interfaces
|
-a, --all show all interfaces
|
||||||
-A, --announce-stats show announce stats
|
-A, --announce-stats show announce stats
|
||||||
|
-P, --pr-stats show path request stats
|
||||||
-l, --link-stats show link stats
|
-l, --link-stats show link stats
|
||||||
|
-B, --burst only show interfaces with active bursts
|
||||||
|
-b, --blocked-ips show blocked IPs per interface
|
||||||
-t, --totals display traffic totals
|
-t, --totals display traffic totals
|
||||||
|
-q, --queues display queue stats
|
||||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||||
announces, arx, atx, held]
|
announces, arx, atx, prx, ptx, held]
|
||||||
-r, --reverse reverse sorting
|
-r, --reverse reverse sorting
|
||||||
-j, --json output in JSON format
|
-j, --json output in JSON format
|
||||||
-R hash transport identity hash of remote instance to get status from
|
-R hash transport identity hash of remote instance to get status from
|
||||||
@@ -1002,39 +1006,35 @@ available. These are only recognised immediately after a newline character:
|
|||||||
destination hexadecimal hash of the destination to connect to
|
destination hexadecimal hash of the destination to connect to
|
||||||
|
|
||||||
options:
|
options:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--config, -c CONFIG path to alternative Reticulum config directory
|
--config, -c PATH path to config directory
|
||||||
--identity, -i IDENTITY
|
--rnsconfig, -c PATH path to alternative Reticulum config directory
|
||||||
path to identity file to use
|
--identity, -i IDENTITY path to identity file to use
|
||||||
-v, --verbose increase verbosity
|
-v, --verbose increase verbosity
|
||||||
-q, --quiet decrease verbosity
|
-q, --quiet decrease verbosity
|
||||||
-p, --print-identity print identity and destination info and exit
|
-p, --print-identity print identity and destination info and exit
|
||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-l, --listen listen (server) mode; any command specified after --
|
-l, --listen listen (server) mode; any command specified after --
|
||||||
will be used as the default command when the initiator
|
will be used as the default command when the initiator
|
||||||
does not provide one or when remote command execution
|
does not provide one or when remote command execution
|
||||||
is disabled; if no command is specified, the default
|
is disabled; if no command is specified, the default
|
||||||
shell of the user running rnsh will be used
|
shell of the user running rnsh will be used
|
||||||
-s, --service SERVICE
|
-s, --service SERVICE service name for identity file if not the default
|
||||||
service name for identity file if not the default
|
-b, --announce PERIOD announce on startup and every PERIOD seconds; specify
|
||||||
-b, --announce PERIOD
|
0 to announce on startup only
|
||||||
announce on startup and every PERIOD seconds; specify
|
-a, --allowed HASH allow this identity to connect (may be specified
|
||||||
0 to announce on startup only
|
multiple times); allowed identities can also be
|
||||||
-a, --allowed HASH allow this identity to connect (may be specified
|
specified in ~/.rnsh/allowed_identities or
|
||||||
multiple times); allowed identities can also be
|
~/.config/rnsh/allowed_identities, one hash per line
|
||||||
specified in ~/.rnsh/allowed_identities or
|
-n, --no-auth disable authentication (allow any identity to connect)
|
||||||
~/.config/rnsh/allowed_identities, one hash per line
|
|
||||||
-n, --no-auth disable authentication (allow any identity to connect)
|
|
||||||
-A, --remote-command-as-args
|
-A, --remote-command-as-args
|
||||||
concatenate remote command to the argument list of the
|
concatenate remote command to the argument list of the
|
||||||
default program or shell
|
default program or shell
|
||||||
-C, --no-remote-command
|
-C, --no-remote-command disable executing command lines received from the
|
||||||
disable executing command lines received from the
|
remote initiator
|
||||||
remote initiator
|
-N, --no-id disable identity announcement on connect
|
||||||
-N, --no-id disable identity announcement on connect
|
-m, --mirror return with the exit code of the remote process
|
||||||
-m, --mirror return with the exit code of the remote process
|
-w, --timeout SECONDS connect and request timeout in seconds
|
||||||
-w, --timeout SECONDS
|
|
||||||
connect and request timeout in seconds
|
|
||||||
|
|
||||||
When specifying a command to execute, separate rnsh options from the command
|
When specifying a command to execute, separate rnsh options from the command
|
||||||
and its arguments with --. For example:
|
and its arguments with --. For example:
|
||||||
@@ -1224,6 +1224,12 @@ The configuration snippet below contains an example of setting these additional
|
|||||||
network_identity = ~/.reticulum/storage/identities/my_network
|
network_identity = ~/.reticulum/storage/identities/my_network
|
||||||
...
|
...
|
||||||
|
|
||||||
|
For more fine-grained control over how discovered interfaces are auto-connected, additional options are provided for configuraiton. These are not necessary to set in most cases, but can be useful in certain situations.
|
||||||
|
|
||||||
|
* The ``autoconnect_interface_mode`` options specifies which mode discovered interfaces should be created with when auto-connecting.
|
||||||
|
|
||||||
|
* The ``autoconnect_announces_to_internal`` option allows you to specify that auto-connected interfaces should propagate announces to ``internal`` mode interfaces, even if the auto-connected interface's mode would normally not allow for this.
|
||||||
|
|
||||||
Remote Management
|
Remote Management
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const DOCUMENTATION_OPTIONS = {
|
const DOCUMENTATION_OPTIONS = {
|
||||||
VERSION: '1.3.8',
|
VERSION: '1.5.0',
|
||||||
LANGUAGE: 'en',
|
LANGUAGE: 'en',
|
||||||
COLLAPSE_INDEX: false,
|
COLLAPSE_INDEX: false,
|
||||||
BUILDER: 'html',
|
BUILDER: 'html',
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Distributed Development - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Distributed Development - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -431,7 +431,7 @@
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Code Examples - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Code Examples - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -3648,7 +3648,7 @@
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>An Explanation of Reticulum for Human Beings - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>An Explanation of Reticulum for Human Beings - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -296,7 +296,7 @@
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="#"><link rel="search" title="Search" href="search.html">
|
<meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="#"><link rel="search" title="Search" href="search.html">
|
||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 --><title>Index - Reticulum Network Stack 1.3.8 documentation</title>
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 --><title>Index - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -178,7 +178,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -202,7 +202,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -365,10 +365,12 @@
|
|||||||
<li><a href="reference.html#RNS.Identity.decrypt">(RNS.Identity method)</a>
|
<li><a href="reference.html#RNS.Identity.decrypt">(RNS.Identity method)</a>
|
||||||
</li>
|
</li>
|
||||||
</ul></li>
|
</ul></li>
|
||||||
<li><a href="reference.html#RNS.Transport.deregister_announce_handler">deregister_announce_handler() (RNS.Transport static method)</a>
|
<li><a href="reference.html#RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT">DEFAULT_PER_HOP_TIMEOUT (RNS.Reticulum attribute)</a>
|
||||||
</li>
|
</li>
|
||||||
</ul></td>
|
</ul></td>
|
||||||
<td style="width: 33%; vertical-align: top;"><ul>
|
<td style="width: 33%; vertical-align: top;"><ul>
|
||||||
|
<li><a href="reference.html#RNS.Transport.deregister_announce_handler">deregister_announce_handler() (RNS.Transport static method)</a>
|
||||||
|
</li>
|
||||||
<li><a href="reference.html#RNS.Destination.deregister_request_handler">deregister_request_handler() (RNS.Destination method)</a>
|
<li><a href="reference.html#RNS.Destination.deregister_request_handler">deregister_request_handler() (RNS.Destination method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Destination">Destination (class in RNS)</a>
|
<li><a href="reference.html#RNS.Destination">Destination (class in RNS)</a>
|
||||||
@@ -434,12 +436,18 @@
|
|||||||
<li><a href="reference.html#RNS.Link.get_establishment_rate">get_establishment_rate() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.get_establishment_rate">get_establishment_rate() (RNS.Link method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Link.get_expected_rate">get_expected_rate() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.get_expected_rate">get_expected_rate() (RNS.Link method)</a>
|
||||||
|
</li>
|
||||||
|
<li><a href="reference.html#RNS.Reticulum.get_first_hop_timeout">get_first_hop_timeout() (RNS.Reticulum method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Resource.get_hash">get_hash() (RNS.Resource method)</a>
|
<li><a href="reference.html#RNS.Resource.get_hash">get_hash() (RNS.Resource method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Reticulum.get_instance">get_instance() (RNS.Reticulum static method)</a>
|
<li><a href="reference.html#RNS.Reticulum.get_instance">get_instance() (RNS.Reticulum static method)</a>
|
||||||
|
</li>
|
||||||
|
<li><a href="reference.html#RNS.Reticulum.get_lowest_interface_bitrate">get_lowest_interface_bitrate() (RNS.Reticulum method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Link.get_mdu">get_mdu() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.get_mdu">get_mdu() (RNS.Link method)</a>
|
||||||
|
</li>
|
||||||
|
<li><a href="reference.html#RNS.Reticulum.get_medium_path_timeout">get_medium_path_timeout() (RNS.Reticulum method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Link.get_mode">get_mode() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.get_mode">get_mode() (RNS.Link method)</a>
|
||||||
</li>
|
</li>
|
||||||
@@ -459,10 +467,10 @@
|
|||||||
<li><a href="reference.html#RNS.Resource.get_progress">(RNS.Resource method)</a>
|
<li><a href="reference.html#RNS.Resource.get_progress">(RNS.Resource method)</a>
|
||||||
</li>
|
</li>
|
||||||
</ul></li>
|
</ul></li>
|
||||||
<li><a href="reference.html#RNS.Identity.get_public_key">get_public_key() (RNS.Identity method)</a>
|
|
||||||
</li>
|
|
||||||
</ul></td>
|
</ul></td>
|
||||||
<td style="width: 33%; vertical-align: top;"><ul>
|
<td style="width: 33%; vertical-align: top;"><ul>
|
||||||
|
<li><a href="reference.html#RNS.Identity.get_public_key">get_public_key() (RNS.Identity method)</a>
|
||||||
|
</li>
|
||||||
<li><a href="reference.html#RNS.Link.get_q">get_q() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.get_q">get_q() (RNS.Link method)</a>
|
||||||
|
|
||||||
<ul>
|
<ul>
|
||||||
@@ -720,6 +728,8 @@
|
|||||||
<li><a href="reference.html#RNS.Link.set_link_closed_callback">set_link_closed_callback() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.set_link_closed_callback">set_link_closed_callback() (RNS.Link method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Destination.set_link_established_callback">set_link_established_callback() (RNS.Destination method)</a>
|
<li><a href="reference.html#RNS.Destination.set_link_established_callback">set_link_established_callback() (RNS.Destination method)</a>
|
||||||
|
</li>
|
||||||
|
<li><a href="reference.html#RNS.Destination.set_max_request_size">set_max_request_size() (RNS.Destination method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Destination.set_packet_callback">set_packet_callback() (RNS.Destination method)</a>
|
<li><a href="reference.html#RNS.Destination.set_packet_callback">set_packet_callback() (RNS.Destination method)</a>
|
||||||
|
|
||||||
@@ -732,11 +742,11 @@
|
|||||||
<li><a href="reference.html#RNS.Destination.set_proof_strategy">set_proof_strategy() (RNS.Destination method)</a>
|
<li><a href="reference.html#RNS.Destination.set_proof_strategy">set_proof_strategy() (RNS.Destination method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Destination.set_ratchet_interval">set_ratchet_interval() (RNS.Destination method)</a>
|
<li><a href="reference.html#RNS.Destination.set_ratchet_interval">set_ratchet_interval() (RNS.Destination method)</a>
|
||||||
</li>
|
|
||||||
<li><a href="reference.html#RNS.Link.set_remote_identified_callback">set_remote_identified_callback() (RNS.Link method)</a>
|
|
||||||
</li>
|
</li>
|
||||||
</ul></td>
|
</ul></td>
|
||||||
<td style="width: 33%; vertical-align: top;"><ul>
|
<td style="width: 33%; vertical-align: top;"><ul>
|
||||||
|
<li><a href="reference.html#RNS.Link.set_remote_identified_callback">set_remote_identified_callback() (RNS.Link method)</a>
|
||||||
|
</li>
|
||||||
<li><a href="reference.html#RNS.Link.set_resource_callback">set_resource_callback() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.set_resource_callback">set_resource_callback() (RNS.Link method)</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="reference.html#RNS.Link.set_resource_concluded_callback">set_resource_concluded_callback() (RNS.Link method)</a>
|
<li><a href="reference.html#RNS.Link.set_resource_concluded_callback">set_resource_concluded_callback() (RNS.Link method)</a>
|
||||||
@@ -846,7 +856,7 @@
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Getting Started Fast - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Getting Started Fast - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -776,7 +776,7 @@ section of this manual.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Git Over Reticulum - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Git Over Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -1594,7 +1594,7 @@ done
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Communications Hardware - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Communications Hardware - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -676,7 +676,7 @@ can be used with Reticulum. This includes virtual software modems such as
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="#"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="#"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -486,6 +486,7 @@ to participate in the development of Reticulum itself.</p>
|
|||||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#backbone-interface">Backbone Interface</a><ul>
|
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#backbone-interface">Backbone Interface</a><ul>
|
||||||
<li class="toctree-l3"><a class="reference internal" href="interfaces.html#listeners">Listeners</a></li>
|
<li class="toctree-l3"><a class="reference internal" href="interfaces.html#listeners">Listeners</a></li>
|
||||||
<li class="toctree-l3"><a class="reference internal" href="interfaces.html#connecting-remotes">Connecting Remotes</a></li>
|
<li class="toctree-l3"><a class="reference internal" href="interfaces.html#connecting-remotes">Connecting Remotes</a></li>
|
||||||
|
<li class="toctree-l3"><a class="reference internal" href="interfaces.html#automated-blocking">Automated Blocking</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#tcp-server-interface">TCP Server Interface</a></li>
|
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#tcp-server-interface">TCP Server Interface</a></li>
|
||||||
@@ -511,6 +512,7 @@ to participate in the development of Reticulum itself.</p>
|
|||||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#announce-rate-control">Announce Rate Control</a></li>
|
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#announce-rate-control">Announce Rate Control</a></li>
|
||||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#new-destination-rate-limiting">New Destination Rate Limiting</a></li>
|
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#new-destination-rate-limiting">New Destination Rate Limiting</a></li>
|
||||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#path-request-burst-control">Path Request Burst Control</a></li>
|
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#path-request-burst-control">Path Request Burst Control</a></li>
|
||||||
|
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#tuning-ingress-queues">Tuning Ingress Queues</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li class="toctree-l1"><a class="reference internal" href="networks.html">Building Networks</a><ul>
|
<li class="toctree-l1"><a class="reference internal" href="networks.html">Building Networks</a><ul>
|
||||||
@@ -719,7 +721,7 @@ to participate in the development of Reticulum itself.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
+110
-5
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Configuring Interfaces - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Configuring Interfaces - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -460,6 +460,47 @@ specify the target Yggdrasil IPv6 address and port, like so:</p>
|
|||||||
</pre></div>
|
</pre></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
<section id="automated-blocking">
|
||||||
|
<h3>Automated Blocking<a class="headerlink" href="#automated-blocking" title="Link to this heading">¶</a></h3>
|
||||||
|
<p>Listener instances of <code class="docutils literal notranslate"><span class="pre">BackboneInterface</span></code> will automatically block fast-flapping clients,
|
||||||
|
that repeatedly connect for a short amount of time, and then disconnect. Such behavior usually
|
||||||
|
occurs from clients trying to spam the network with announces or path requests, by connecting, dumping
|
||||||
|
a massive amount of requests, and then disconnecting in an attempt to bypass rate limits.</p>
|
||||||
|
<p>While such bypass attempts only have very limited effect on the amount of spam actually dumped (ingress limits
|
||||||
|
trigger immediately once a client exceeds rate limits), the behavior is often seen anyways, and
|
||||||
|
causes log noise and needless interface rotation. The fast-flapping block ensures such clients
|
||||||
|
are never allocated an interface on the transport instance.</p>
|
||||||
|
<p>Another common cause can simply be clients using implementations that are broken, or automated
|
||||||
|
scanning tools attempting to connect to the instance.</p>
|
||||||
|
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[[Backbone Listener]]</span>
|
||||||
|
<span class="w"> </span><span class="na">type</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">BackboneInterface</span>
|
||||||
|
<span class="w"> </span><span class="na">enabled</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">yes</span>
|
||||||
|
<span class="w"> </span><span class="na">listen_on</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">0.0.0.0</span>
|
||||||
|
<span class="w"> </span><span class="na">port</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">4242</span>
|
||||||
|
|
||||||
|
<span class="w"> </span><span class="c1"># Whether to enable blocking</span>
|
||||||
|
<span class="w"> </span><span class="na">block_fast_flapping</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">yes</span>
|
||||||
|
|
||||||
|
<span class="w"> </span><span class="c1"># How long an IP address stays</span>
|
||||||
|
<span class="w"> </span><span class="c1"># blocked, in minutes. Set to</span>
|
||||||
|
<span class="w"> </span><span class="c1"># 12 hours by default.</span>
|
||||||
|
<span class="w"> </span><span class="na">fast_flapping_block_time</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">720</span>
|
||||||
|
|
||||||
|
<span class="w"> </span><span class="c1"># The minimum time, in seconds,</span>
|
||||||
|
<span class="w"> </span><span class="c1"># an interface must stay connected</span>
|
||||||
|
<span class="w"> </span><span class="c1"># to be considered not fast-flapping.</span>
|
||||||
|
<span class="w"> </span><span class="na">fast_flapping_threshold</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">20</span>
|
||||||
|
|
||||||
|
<span class="w"> </span><span class="c1"># Amount of fast flaps a remote</span>
|
||||||
|
<span class="w"> </span><span class="c1"># IP can perform before having</span>
|
||||||
|
<span class="w"> </span><span class="c1"># blocking triggered.</span>
|
||||||
|
<span class="w"> </span><span class="na">fast_flapping_grace</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">5</span>
|
||||||
|
</pre></div>
|
||||||
|
</div>
|
||||||
|
<p>The configuration options listed in the example above are the <em>default values</em>, and you do
|
||||||
|
not need to add them for automated blocking to work, but you can use them to change the
|
||||||
|
behavior from the defaults, if necessary.</p>
|
||||||
|
</section>
|
||||||
</section>
|
</section>
|
||||||
<section id="tcp-server-interface">
|
<section id="tcp-server-interface">
|
||||||
<span id="interfaces-tcps"></span><h2>TCP Server Interface<a class="headerlink" href="#tcp-server-interface" title="Link to this heading">¶</a></h2>
|
<span id="interfaces-tcps"></span><h2>TCP Server Interface<a class="headerlink" href="#tcp-server-interface" title="Link to this heading">¶</a></h2>
|
||||||
@@ -1110,6 +1151,8 @@ relevant regulation for your location, and to make decisions accordingly.</p>
|
|||||||
<dl class="simple">
|
<dl class="simple">
|
||||||
<dt><code class="docutils literal notranslate"><span class="pre">discovery_name</span></code></dt><dd><p>A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.</p>
|
<dt><code class="docutils literal notranslate"><span class="pre">discovery_name</span></code></dt><dd><p>A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.</p>
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">discovery_lxmf_address</span></code></dt><dd><p>An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.</p>
|
||||||
|
</dd>
|
||||||
<dt><code class="docutils literal notranslate"><span class="pre">announce_interval</span></code></dt><dd><p>The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).</p>
|
<dt><code class="docutils literal notranslate"><span class="pre">announce_interval</span></code></dt><dd><p>The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).</p>
|
||||||
</dd>
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
@@ -1154,9 +1197,15 @@ curl<span class="w"> </span>-s<span class="w"> </span>ip.me
|
|||||||
</dl>
|
</dl>
|
||||||
<p><strong>Physical Location</strong></p>
|
<p><strong>Physical Location</strong></p>
|
||||||
<dl class="simple">
|
<dl class="simple">
|
||||||
<dt><code class="docutils literal notranslate"><span class="pre">latitude</span></code>, <code class="docutils literal notranslate"><span class="pre">longitude</span></code>, <code class="docutils literal notranslate"><span class="pre">height</span></code></dt><dd><p>Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters.</p>
|
<dt><code class="docutils literal notranslate"><span class="pre">latitude</span></code>, <code class="docutils literal notranslate"><span class="pre">longitude</span></code>, <code class="docutils literal notranslate"><span class="pre">height</span></code></dt><dd><p>Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters above mean sea level.</p>
|
||||||
|
</dd>
|
||||||
|
<dt><code class="docutils literal notranslate"><span class="pre">location_cmd</span></code></dt><dd><p>Optional path to executable or script that returns the physical coordinates for the interface. This can be used instead of manually setting <code class="docutils literal notranslate"><span class="pre">latitude</span></code>, <code class="docutils literal notranslate"><span class="pre">longitude</span></code> and <code class="docutils literal notranslate"><span class="pre">height</span></code>. Reticulum expects the script to output the location data to <code class="docutils literal notranslate"><span class="pre">stdout</span></code> on a single line, separated by commas, with values as floating point numbers in the format <code class="docutils literal notranslate"><span class="pre">LAT,</span> <span class="pre">LON,</span> <span class="pre">HEIGHT</span></code>. Coordinates should be in decimal degrees, height in meters above mean sea level.</p>
|
||||||
</dd>
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
|
<div class="admonition note">
|
||||||
|
<p class="admonition-title">Note</p>
|
||||||
|
<p>The height value for interface discovery is specified in <em>height above mean sea level</em>! This is the geoid-corrected height value, and is distinct from GPS altitude. If you manually specify height, it will typically be set to what you find on a topographical map. If you are using a script to output the location data, make sure that you are using the geoid-corrected altitude, not height above the GPS ellipsoid. Most GPS systems will make both figures available.</p>
|
||||||
|
</div>
|
||||||
<p><strong>Radio Parameters</strong></p>
|
<p><strong>Radio Parameters</strong></p>
|
||||||
<p>For physical radio interfaces like <code class="docutils literal notranslate"><span class="pre">RNodeInterface</span></code> or <code class="docutils literal notranslate"><span class="pre">KISSInterface</span></code>, the following optional parameters allow you to broadcast the operating frequency and characteristics, allowing clients to verify compatibility before connecting:</p>
|
<p>For physical radio interfaces like <code class="docutils literal notranslate"><span class="pre">RNodeInterface</span></code> or <code class="docutils literal notranslate"><span class="pre">KISSInterface</span></code>, the following optional parameters allow you to broadcast the operating frequency and characteristics, allowing clients to verify compatibility before connecting:</p>
|
||||||
<dl class="simple">
|
<dl class="simple">
|
||||||
@@ -1288,10 +1337,20 @@ someone is actually using them. An example of this could
|
|||||||
be a radio interface serving a wide area, where users are
|
be a radio interface serving a wide area, where users are
|
||||||
expected to connect momentarily, use the network, and then
|
expected to connect momentarily, use the network, and then
|
||||||
disappear again.</p></li>
|
disappear again.</p></li>
|
||||||
|
<li><p>See the <a class="reference internal" href="#interfaces-modes"><span class="std std-ref">Interface Modes</span></a> section
|
||||||
|
below for a reference on additional modes.</p></li>
|
||||||
</ul>
|
</ul>
|
||||||
</div></blockquote>
|
</div></blockquote>
|
||||||
</li>
|
</li>
|
||||||
<li><div class="line-block">
|
<li><div class="line-block">
|
||||||
|
<div class="line">The <code class="docutils literal notranslate"><span class="pre">gravity</span></code> option specifies the pathing affinity of an interface.
|
||||||
|
If not set specifically, and unless otherwise configured by
|
||||||
|
<code class="docutils literal notranslate"><span class="pre">default_gravity</span></code> or <code class="docutils literal notranslate"><span class="pre">autoconnect_interface_gravity</span></code>,
|
||||||
|
it defaults to <code class="docutils literal notranslate"><span class="pre">0</span></code>. Positive values increase pathing affinity,
|
||||||
|
and negative values decrease it.</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li><div class="line-block">
|
||||||
<div class="line">The <code class="docutils literal notranslate"><span class="pre">outgoing</span></code> option sets whether an interface is allowed
|
<div class="line">The <code class="docutils literal notranslate"><span class="pre">outgoing</span></code> option sets whether an interface is allowed
|
||||||
to transmit. Defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code>. If set to <code class="docutils literal notranslate"><span class="pre">False</span></code> or <code class="docutils literal notranslate"><span class="pre">No</span></code>
|
to transmit. Defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code>. If set to <code class="docutils literal notranslate"><span class="pre">False</span></code> or <code class="docutils literal notranslate"><span class="pre">No</span></code>
|
||||||
the interface will only receive data, and never transmit.</div>
|
the interface will only receive data, and never transmit.</div>
|
||||||
@@ -1379,6 +1438,12 @@ do not propagate out when received, paths to destinations on
|
|||||||
of path requests.</div>
|
of path requests.</div>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
|
<li><div class="line-block">
|
||||||
|
<div class="line">To allow an interface that would <em>otherwise not</em> propagate
|
||||||
|
announces to <code class="docutils literal notranslate"><span class="pre">internal</span></code> mode interfaces to do so, you can
|
||||||
|
configure the <code class="docutils literal notranslate"><span class="pre">announces_to_internal</span></code> option to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div></blockquote>
|
</div></blockquote>
|
||||||
</section>
|
</section>
|
||||||
@@ -1705,6 +1770,44 @@ per second on a given interface.</div>
|
|||||||
under the <code class="docutils literal notranslate"><span class="pre">[reticulum]</span></code> section of the configuration file, or on a per-
|
under the <code class="docutils literal notranslate"><span class="pre">[reticulum]</span></code> section of the configuration file, or on a per-
|
||||||
interface basis under the relevant interface configuration section.</p>
|
interface basis under the relevant interface configuration section.</p>
|
||||||
</section>
|
</section>
|
||||||
|
<section id="tuning-ingress-queues">
|
||||||
|
<h2>Tuning Ingress Queues<a class="headerlink" href="#tuning-ingress-queues" title="Link to this heading">¶</a></h2>
|
||||||
|
<p>Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:</p>
|
||||||
|
<blockquote>
|
||||||
|
<div><ol class="arabic simple">
|
||||||
|
<li><p>Data and general traffic</p></li>
|
||||||
|
<li><p>Announces</p></li>
|
||||||
|
<li><p>Path requests</p></li>
|
||||||
|
<li><p>Ingress-limited traffic</p></li>
|
||||||
|
</ol>
|
||||||
|
</div></blockquote>
|
||||||
|
<p>You can tune the queue sizes from the defaults, for example if you’re running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the <code class="docutils literal notranslate"><span class="pre">[reticulum]</span></code> section of the config</p>
|
||||||
|
<blockquote>
|
||||||
|
<div><ul>
|
||||||
|
<li><div class="line-block">
|
||||||
|
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_data</span></code> option sets the maximum size of the data
|
||||||
|
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">4096</span></code>.</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li><div class="line-block">
|
||||||
|
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_announce</span></code> option sets the maximum size of the announce
|
||||||
|
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">256</span></code>.</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li><div class="line-block">
|
||||||
|
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_pr</span></code> option sets the maximum size of the path request
|
||||||
|
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">256</span></code>.</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li><div class="line-block">
|
||||||
|
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_il</span></code> option sets the maximum size of the ingress limiter
|
||||||
|
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">128</span></code>.</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div></blockquote>
|
||||||
|
<p>If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.</p>
|
||||||
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
</article>
|
</article>
|
||||||
@@ -1767,6 +1870,7 @@ interface basis under the relevant interface configuration section.</p>
|
|||||||
<li><a class="reference internal" href="#backbone-interface">Backbone Interface</a><ul>
|
<li><a class="reference internal" href="#backbone-interface">Backbone Interface</a><ul>
|
||||||
<li><a class="reference internal" href="#listeners">Listeners</a></li>
|
<li><a class="reference internal" href="#listeners">Listeners</a></li>
|
||||||
<li><a class="reference internal" href="#connecting-remotes">Connecting Remotes</a></li>
|
<li><a class="reference internal" href="#connecting-remotes">Connecting Remotes</a></li>
|
||||||
|
<li><a class="reference internal" href="#automated-blocking">Automated Blocking</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li><a class="reference internal" href="#tcp-server-interface">TCP Server Interface</a></li>
|
<li><a class="reference internal" href="#tcp-server-interface">TCP Server Interface</a></li>
|
||||||
@@ -1792,6 +1896,7 @@ interface basis under the relevant interface configuration section.</p>
|
|||||||
<li><a class="reference internal" href="#announce-rate-control">Announce Rate Control</a></li>
|
<li><a class="reference internal" href="#announce-rate-control">Announce Rate Control</a></li>
|
||||||
<li><a class="reference internal" href="#new-destination-rate-limiting">New Destination Rate Limiting</a></li>
|
<li><a class="reference internal" href="#new-destination-rate-limiting">New Destination Rate Limiting</a></li>
|
||||||
<li><a class="reference internal" href="#path-request-burst-control">Path Request Burst Control</a></li>
|
<li><a class="reference internal" href="#path-request-burst-control">Path Request Burst Control</a></li>
|
||||||
|
<li><a class="reference internal" href="#tuning-ingress-queues">Tuning Ingress Queues</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -1803,7 +1908,7 @@ interface basis under the relevant interface configuration section.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Reticulum License - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Reticulum License - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -345,7 +345,7 @@ SOFTWARE.
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Building Networks - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Building Networks - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -664,7 +664,7 @@ differently than a mobile device roaming between radio cells.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
Binary file not shown.
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>API Reference - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>API Reference - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -335,10 +335,59 @@ alterations should be made on a per-interface basis instead.</p>
|
|||||||
to successfully establish links. Currently 5 bits per second.</p>
|
to successfully establish links. Currently 5 bits per second.</p>
|
||||||
</dd></dl>
|
</dd></dl>
|
||||||
|
|
||||||
|
<dl class="py attribute">
|
||||||
|
<dt class="sig sig-object py" id="RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT">
|
||||||
|
<span class="sig-name descname"><span class="pre">DEFAULT_PER_HOP_TIMEOUT</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">6</span></em><a class="headerlink" href="#RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT" title="Link to this definition">¶</a></dt>
|
||||||
|
<dd><p>The default per-hop timeout value used in various timeout calculations.</p>
|
||||||
|
</dd></dl>
|
||||||
|
|
||||||
<dl class="py method">
|
<dl class="py method">
|
||||||
<dt class="sig sig-object py" id="RNS.Reticulum.get_instance">
|
<dt class="sig sig-object py" id="RNS.Reticulum.get_instance">
|
||||||
<em class="property"><span class="k"><span class="pre">static</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">get_instance</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_instance" title="Link to this definition">¶</a></dt>
|
<em class="property"><span class="k"><span class="pre">static</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">get_instance</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_instance" title="Link to this definition">¶</a></dt>
|
||||||
<dd><p>Return the currently running Reticulum instance</p>
|
<dd><p>Returns the currently running Reticulum instance.</p>
|
||||||
|
</dd></dl>
|
||||||
|
|
||||||
|
<dl class="py method">
|
||||||
|
<dt class="sig sig-object py" id="RNS.Reticulum.get_first_hop_timeout">
|
||||||
|
<span class="sig-name descname"><span class="pre">get_first_hop_timeout</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">destination</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_first_hop_timeout" title="Link to this definition">¶</a></dt>
|
||||||
|
<dd><p>Returns a best-effort estimate of a reasonable minimum
|
||||||
|
<em>first-hop</em> timeout value for a given destination hash.
|
||||||
|
If a path is known, this calculation takes the next-hop
|
||||||
|
interface’s bitrate into account. If no path is currently
|
||||||
|
known, returns <code class="docutils literal notranslate"><span class="pre">DEFAULT_PER_HOP_TIMEOUT</span></code>.</p>
|
||||||
|
<dl class="field-list simple">
|
||||||
|
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
|
||||||
|
<dd class="field-odd"><p><strong>destination</strong> – A destination hash, as <em>bytes</em>.</p>
|
||||||
|
</dd>
|
||||||
|
<dt class="field-even">Returns<span class="colon">:</span></dt>
|
||||||
|
<dd class="field-even"><p>First-hop timeout, in seconds.</p>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd></dl>
|
||||||
|
|
||||||
|
<dl class="py method">
|
||||||
|
<dt class="sig sig-object py" id="RNS.Reticulum.get_lowest_interface_bitrate">
|
||||||
|
<span class="sig-name descname"><span class="pre">get_lowest_interface_bitrate</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_lowest_interface_bitrate" title="Link to this definition">¶</a></dt>
|
||||||
|
<dd><p>Returns the bitrate of the slowest currently online
|
||||||
|
interface, or None if no online interface bitrate</p>
|
||||||
|
<dl class="field-list simple">
|
||||||
|
<dt class="field-odd">Returns<span class="colon">:</span></dt>
|
||||||
|
<dd class="field-odd"><p>Lowest online interface bitrate in bits per second, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd></dl>
|
||||||
|
|
||||||
|
<dl class="py method">
|
||||||
|
<dt class="sig sig-object py" id="RNS.Reticulum.get_medium_path_timeout">
|
||||||
|
<span class="sig-name descname"><span class="pre">get_medium_path_timeout</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_medium_path_timeout" title="Link to this definition">¶</a></dt>
|
||||||
|
<dd><p>Returns an estimate of a reasonable minimum path request timeout covering
|
||||||
|
a full round trip for an MTU on the slowest currently online interface
|
||||||
|
plus per hop grace</p>
|
||||||
|
<dl class="field-list simple">
|
||||||
|
<dt class="field-odd">Returns<span class="colon">:</span></dt>
|
||||||
|
<dd class="field-odd"><p>Timeout in seconds or 0 if it’s unknown.</p>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
</dd></dl>
|
</dd></dl>
|
||||||
|
|
||||||
<dl class="py method">
|
<dl class="py method">
|
||||||
@@ -925,6 +974,20 @@ proofs should be returned for received packets.</p>
|
|||||||
</dl>
|
</dl>
|
||||||
</dd></dl>
|
</dd></dl>
|
||||||
|
|
||||||
|
<dl class="py method">
|
||||||
|
<dt class="sig sig-object py" id="RNS.Destination.set_max_request_size">
|
||||||
|
<span class="sig-name descname"><span class="pre">set_max_request_size</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">max_request_size</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Destination.set_max_request_size" title="Link to this definition">¶</a></dt>
|
||||||
|
<dd><p>Sets the maximum accepted request size for registered request handlers.</p>
|
||||||
|
<dl class="field-list simple">
|
||||||
|
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
|
||||||
|
<dd class="field-odd"><p><strong>max_request_size</strong> – The maximum accepted request size in bytes, as an integer.</p>
|
||||||
|
</dd>
|
||||||
|
<dt class="field-even">Raises<span class="colon">:</span></dt>
|
||||||
|
<dd class="field-even"><p><code class="docutils literal notranslate"><span class="pre">TypeError</span></code> or <code class="docutils literal notranslate"><span class="pre">ValueError</span></code> if any of the argument is invalid.</p>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</dd></dl>
|
||||||
|
|
||||||
<dl class="py method">
|
<dl class="py method">
|
||||||
<dt class="sig sig-object py" id="RNS.Destination.register_request_handler">
|
<dt class="sig sig-object py" id="RNS.Destination.register_request_handler">
|
||||||
<span class="sig-name descname"><span class="pre">register_request_handler</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">response_generator</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allow</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ALLOW_NONE</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allowed_list</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">auto_compress</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Destination.register_request_handler" title="Link to this definition">¶</a></dt>
|
<span class="sig-name descname"><span class="pre">register_request_handler</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">response_generator</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allow</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ALLOW_NONE</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allowed_list</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">auto_compress</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Destination.register_request_handler" title="Link to this definition">¶</a></dt>
|
||||||
@@ -1341,7 +1404,7 @@ thus preserved. This method can be used for authentication.</p>
|
|||||||
|
|
||||||
<dl class="py method">
|
<dl class="py method">
|
||||||
<dt class="sig sig-object py" id="RNS.Link.request">
|
<dt class="sig sig-object py" id="RNS.Link.request">
|
||||||
<span class="sig-name descname"><span class="pre">request</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">data</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">response_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">failed_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">progress_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Link.request" title="Link to this definition">¶</a></dt>
|
<span class="sig-name descname"><span class="pre">request</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">data</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">response_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">failed_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">progress_callback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">max_response_size</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Link.request" title="Link to this definition">¶</a></dt>
|
||||||
<dd><p>Sends a request to the remote peer.</p>
|
<dd><p>Sends a request to the remote peer.</p>
|
||||||
<dl class="field-list simple">
|
<dl class="field-list simple">
|
||||||
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
|
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
|
||||||
@@ -1350,6 +1413,7 @@ thus preserved. This method can be used for authentication.</p>
|
|||||||
<li><p><strong>response_callback</strong> – An optional function or method with the signature <em>response_callback(request_receipt)</em> to be called when a response is received. See the <a class="reference internal" href="examples.html#example-request"><span class="std std-ref">Request Example</span></a> for more info.</p></li>
|
<li><p><strong>response_callback</strong> – An optional function or method with the signature <em>response_callback(request_receipt)</em> to be called when a response is received. See the <a class="reference internal" href="examples.html#example-request"><span class="std std-ref">Request Example</span></a> for more info.</p></li>
|
||||||
<li><p><strong>failed_callback</strong> – An optional function or method with the signature <em>failed_callback(request_receipt)</em> to be called when a request fails. See the <a class="reference internal" href="examples.html#example-request"><span class="std std-ref">Request Example</span></a> for more info.</p></li>
|
<li><p><strong>failed_callback</strong> – An optional function or method with the signature <em>failed_callback(request_receipt)</em> to be called when a request fails. See the <a class="reference internal" href="examples.html#example-request"><span class="std std-ref">Request Example</span></a> for more info.</p></li>
|
||||||
<li><p><strong>progress_callback</strong> – An optional function or method with the signature <em>progress_callback(request_receipt)</em> to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the <em>request_receipt.progress</em> property.</p></li>
|
<li><p><strong>progress_callback</strong> – An optional function or method with the signature <em>progress_callback(request_receipt)</em> to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the <em>request_receipt.progress</em> property.</p></li>
|
||||||
|
<li><p><strong>max_response_size</strong> – An optional maximum accepted response size, in bytes as an integer.</p></li>
|
||||||
<li><p><strong>timeout</strong> – An optional timeout in seconds for the request. If <em>None</em> is supplied it will be calculated based on link RTT.</p></li>
|
<li><p><strong>timeout</strong> – An optional timeout in seconds for the request. If <em>None</em> is supplied it will be calculated based on link RTT.</p></li>
|
||||||
</ul>
|
</ul>
|
||||||
</dd>
|
</dd>
|
||||||
@@ -2322,7 +2386,11 @@ will announce it.</p>
|
|||||||
<li><a class="reference internal" href="#RNS.Reticulum.LINK_MTU_DISCOVERY"><code class="docutils literal notranslate"><span class="pre">LINK_MTU_DISCOVERY</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.LINK_MTU_DISCOVERY"><code class="docutils literal notranslate"><span class="pre">LINK_MTU_DISCOVERY</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Reticulum.ANNOUNCE_CAP"><code class="docutils literal notranslate"><span class="pre">ANNOUNCE_CAP</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.ANNOUNCE_CAP"><code class="docutils literal notranslate"><span class="pre">ANNOUNCE_CAP</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Reticulum.MINIMUM_BITRATE"><code class="docutils literal notranslate"><span class="pre">MINIMUM_BITRATE</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.MINIMUM_BITRATE"><code class="docutils literal notranslate"><span class="pre">MINIMUM_BITRATE</span></code></a></li>
|
||||||
|
<li><a class="reference internal" href="#RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT"><code class="docutils literal notranslate"><span class="pre">DEFAULT_PER_HOP_TIMEOUT</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Reticulum.get_instance"><code class="docutils literal notranslate"><span class="pre">get_instance()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.get_instance"><code class="docutils literal notranslate"><span class="pre">get_instance()</span></code></a></li>
|
||||||
|
<li><a class="reference internal" href="#RNS.Reticulum.get_first_hop_timeout"><code class="docutils literal notranslate"><span class="pre">get_first_hop_timeout()</span></code></a></li>
|
||||||
|
<li><a class="reference internal" href="#RNS.Reticulum.get_lowest_interface_bitrate"><code class="docutils literal notranslate"><span class="pre">get_lowest_interface_bitrate()</span></code></a></li>
|
||||||
|
<li><a class="reference internal" href="#RNS.Reticulum.get_medium_path_timeout"><code class="docutils literal notranslate"><span class="pre">get_medium_path_timeout()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Reticulum.should_use_implicit_proof"><code class="docutils literal notranslate"><span class="pre">should_use_implicit_proof()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.should_use_implicit_proof"><code class="docutils literal notranslate"><span class="pre">should_use_implicit_proof()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Reticulum.transport_enabled"><code class="docutils literal notranslate"><span class="pre">transport_enabled()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.transport_enabled"><code class="docutils literal notranslate"><span class="pre">transport_enabled()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Reticulum.link_mtu_discovery"><code class="docutils literal notranslate"><span class="pre">link_mtu_discovery()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Reticulum.link_mtu_discovery"><code class="docutils literal notranslate"><span class="pre">link_mtu_discovery()</span></code></a></li>
|
||||||
@@ -2373,6 +2441,7 @@ will announce it.</p>
|
|||||||
<li><a class="reference internal" href="#RNS.Destination.set_packet_callback"><code class="docutils literal notranslate"><span class="pre">set_packet_callback()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Destination.set_packet_callback"><code class="docutils literal notranslate"><span class="pre">set_packet_callback()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Destination.set_proof_requested_callback"><code class="docutils literal notranslate"><span class="pre">set_proof_requested_callback()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Destination.set_proof_requested_callback"><code class="docutils literal notranslate"><span class="pre">set_proof_requested_callback()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Destination.set_proof_strategy"><code class="docutils literal notranslate"><span class="pre">set_proof_strategy()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Destination.set_proof_strategy"><code class="docutils literal notranslate"><span class="pre">set_proof_strategy()</span></code></a></li>
|
||||||
|
<li><a class="reference internal" href="#RNS.Destination.set_max_request_size"><code class="docutils literal notranslate"><span class="pre">set_max_request_size()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Destination.register_request_handler"><code class="docutils literal notranslate"><span class="pre">register_request_handler()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Destination.register_request_handler"><code class="docutils literal notranslate"><span class="pre">register_request_handler()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Destination.deregister_request_handler"><code class="docutils literal notranslate"><span class="pre">deregister_request_handler()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Destination.deregister_request_handler"><code class="docutils literal notranslate"><span class="pre">deregister_request_handler()</span></code></a></li>
|
||||||
<li><a class="reference internal" href="#RNS.Destination.enable_ratchets"><code class="docutils literal notranslate"><span class="pre">enable_ratchets()</span></code></a></li>
|
<li><a class="reference internal" href="#RNS.Destination.enable_ratchets"><code class="docutils literal notranslate"><span class="pre">enable_ratchets()</span></code></a></li>
|
||||||
@@ -2519,7 +2588,7 @@ will announce it.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<meta name="robots" content="noindex" />
|
<meta name="robots" content="noindex" />
|
||||||
<title>Search - Reticulum Network Stack 1.3.8 documentation</title><link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<title>Search - Reticulum Network Stack 1.5.0 documentation</title><link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo-extensions.css?v=8dab3a3b" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo-extensions.css?v=8dab3a3b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="#" role="search">
|
</a><form class="sidebar-search-container" method="get" action="#" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -304,7 +304,7 @@
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
Search.setIndex({"alltitles":{"A Carrier-Grade Fallacy":[[16,"a-carrier-grade-fallacy"]],"API Reference":[[10,null]],"ARM64":[[3,"arm64"]],"AX.25 KISS Interface":[[7,"ax-25-kiss-interface"]],"Accessing Repository Pages":[[4,"accessing-repository-pages"]],"Adding Radio Interfaces":[[3,"adding-radio-interfaces"]],"An Explanation of Reticulum for Human Beings":[[2,null]],"Anchor In The Flow":[[16,"anchor-in-the-flow"]],"Android":[[3,"android"]],"Announce":[[1,"announce"]],"Announce Propagation Rules":[[13,"announce-propagation-rules"]],"Announce Rate Control":[[7,"announce-rate-control"]],"Announcing Presence":[[16,"announcing-presence"]],"Artifact-Centered Workflows":[[0,"artifact-centered-workflows"]],"Author Identity Binding":[[4,"author-identity-binding"]],"Auto Interface":[[7,"auto-interface"]],"Automated List Sourcing":[[14,"automated-list-sourcing"]],"Automatic Mirror Synchronization":[[4,"automatic-mirror-synchronization"]],"Backbone Interface":[[7,"backbone-interface"]],"Blackhole Management":[[14,"blackhole-management"]],"Bootstrapping Connectivity":[[3,"bootstrapping-connectivity"]],"Broadcast":[[1,"broadcast"]],"Buffer":[[1,"buffer"]],"Build Personal Infrastructure":[[3,"build-personal-infrastructure"]],"Building Networks":[[9,null]],"Channel":[[1,"channel"]],"Code Examples":[[1,null]],"Combining Hardware Types":[[5,"combining-hardware-types"]],"Command-Line Interaction":[[4,"command-line-interaction"]],"Commit Signing":[[4,"commit-signing"]],"Common Interface Options":[[7,"common-interface-options"]],"Communications Hardware":[[5,null]],"Composable Primitives":[[0,"composable-primitives"]],"Concepts & Overview":[[9,"concepts-overview"]],"Conceptual Overview":[[13,"conceptual-overview"]],"Configuration":[[4,"configuration"],[4,"id1"]],"Configuration & Data":[[14,"configuration-data"]],"Configuration Example":[[4,"configuration-example"]],"Configuration Methods":[[4,"configuration-methods"]],"Configuring Interfaces":[[7,null]],"Connect to the Distributed Backbone":[[3,"connect-to-the-distributed-backbone"]],"Connecting Remotes":[[7,"connecting-remotes"]],"Connecting Reticulum Instances Over the Internet":[[3,"connecting-reticulum-instances-over-the-internet"]],"Contributing to the Global Ret":[[3,"contributing-to-the-global-ret"]],"Cost Of A Byte":[[16,"cost-of-a-byte"]],"Creating Empty Repositories":[[4,"creating-empty-repositories"]],"Creating RNodes":[[5,"creating-rnodes"]],"Creating Signed Releases":[[4,"creating-signed-releases"]],"Creating a Network With Reticulum":[[3,"creating-a-network-with-reticulum"]],"Creating and Using Custom Interfaces":[[3,"creating-and-using-custom-interfaces"]],"Creating and Using a Network Identity":[[13,"creating-and-using-a-network-identity"]],"Creator Permissions":[[4,"creator-permissions"]],"Cryptographic Attribution":[[4,"cryptographic-attribution"]],"Cryptographic Primitives":[[13,"cryptographic-primitives"]],"Current Status":[[15,"current-status"]],"Current Usage":[[13,"current-usage"]],"Custom Interfaces":[[1,"custom-interfaces"],[7,"custom-interfaces"]],"Customizing Templates":[[4,"customizing-templates"]],"Death To The Address":[[16,"death-to-the-address"]],"Debian Bookworm":[[3,"debian-bookworm"]],"Decentralization Or Uncentralizability?":[[16,"decentralization-or-uncentralizability"]],"Design Patterns For Post-IP Systems":[[16,"design-patterns-for-post-ip-systems"]],"Destination Naming":[[13,"destination-naming"]],"Destinations":[[13,"destinations"]],"Destinations, Not Addresses":[[9,"destinations-not-addresses"]],"Develop a Program with Reticulum":[[3,"develop-a-program-with-reticulum"]],"Discoverable Interfaces":[[7,"discoverable-interfaces"]],"Discovering Interfaces":[[14,"discovering-interfaces"]],"Discovery Parameters":[[7,"discovery-parameters"]],"Distributed Development":[[0,null]],"Distribution Without Intermediaries":[[0,"distribution-without-intermediaries"]],"Donations":[[12,"donations"]],"Echo":[[1,"echo"]],"Emergent Patterns":[[16,"emergent-patterns"]],"Enabling Discovery":[[7,"enabling-discovery"]],"Enabling the Git Page Node":[[4,"enabling-the-git-page-node"]],"Encryption Is Not A Feature":[[16,"encryption-is-not-a-feature"]],"Ethernet-based Hardware":[[5,"ethernet-based-hardware"]],"Ethics Of The Tool":[[16,"ethics-of-the-tool"]],"Example Configuration":[[7,"example-configuration"]],"Fabric Of The Independent":[[16,"fabric-of-the-independent"]],"Fallacy Of The Cloud":[[16,"fallacy-of-the-cloud"]],"Filetransfer":[[1,"filetransfer"]],"Finding Your Way":[[3,"finding-your-way"]],"Fixed Serial Port Names":[[14,"fixed-serial-port-names"]],"Flow & Time":[[16,"flow-time"]],"Forking Repositories":[[4,"forking-repositories"]],"Formatting & Syntax Highlighting":[[4,"formatting-syntax-highlighting"]],"Future Implications":[[13,"future-implications"]],"Getting Further":[[13,"getting-further"]],"Getting Started Fast":[[3,null]],"Git Configuration Parameters":[[4,"git-configuration-parameters"]],"Git Over Reticulum":[[4,null]],"Goals":[[13,"goals"]],"Line truncated
|
Search.setIndex({"alltitles":{"A Carrier-Grade Fallacy":[[16,"a-carrier-grade-fallacy"]],"API Reference":[[10,null]],"ARM64":[[3,"arm64"]],"AX.25 KISS Interface":[[7,"ax-25-kiss-interface"]],"Accessing Repository Pages":[[4,"accessing-repository-pages"]],"Adding Radio Interfaces":[[3,"adding-radio-interfaces"]],"An Explanation of Reticulum for Human Beings":[[2,null]],"Anchor In The Flow":[[16,"anchor-in-the-flow"]],"Android":[[3,"android"]],"Announce":[[1,"announce"]],"Announce Propagation Rules":[[13,"announce-propagation-rules"]],"Announce Rate Control":[[7,"announce-rate-control"]],"Announcing Presence":[[16,"announcing-presence"]],"Artifact-Centered Workflows":[[0,"artifact-centered-workflows"]],"Author Identity Binding":[[4,"author-identity-binding"]],"Auto Interface":[[7,"auto-interface"]],"Automated Blocking":[[7,"automated-blocking"]],"Automated List Sourcing":[[14,"automated-list-sourcing"]],"Automatic Mirror Synchronization":[[4,"automatic-mirror-synchronization"]],"Backbone Interface":[[7,"backbone-interface"]],"Blackhole Management":[[14,"blackhole-management"]],"Bootstrapping Connectivity":[[3,"bootstrapping-connectivity"]],"Broadcast":[[1,"broadcast"]],"Buffer":[[1,"buffer"]],"Build Personal Infrastructure":[[3,"build-personal-infrastructure"]],"Building Networks":[[9,null]],"Channel":[[1,"channel"]],"Code Examples":[[1,null]],"Combining Hardware Types":[[5,"combining-hardware-types"]],"Command-Line Interaction":[[4,"command-line-interaction"]],"Commit Signing":[[4,"commit-signing"]],"Common Interface Options":[[7,"common-interface-options"]],"Communications Hardware":[[5,null]],"Composable Primitives":[[0,"composable-primitives"]],"Concepts & Overview":[[9,"concepts-overview"]],"Conceptual Overview":[[13,"conceptual-overview"]],"Configuration":[[4,"configuration"],[4,"id1"]],"Configuration & Data":[[14,"configuration-data"]],"Configuration Example":[[4,"configuration-example"]],"Configuration Methods":[[4,"configuration-methods"]],"Configuring Interfaces":[[7,null]],"Connect to the Distributed Backbone":[[3,"connect-to-the-distributed-backbone"]],"Connecting Remotes":[[7,"connecting-remotes"]],"Connecting Reticulum Instances Over the Internet":[[3,"connecting-reticulum-instances-over-the-internet"]],"Contributing to the Global Ret":[[3,"contributing-to-the-global-ret"]],"Cost Of A Byte":[[16,"cost-of-a-byte"]],"Creating Empty Repositories":[[4,"creating-empty-repositories"]],"Creating RNodes":[[5,"creating-rnodes"]],"Creating Signed Releases":[[4,"creating-signed-releases"]],"Creating a Network With Reticulum":[[3,"creating-a-network-with-reticulum"]],"Creating and Using Custom Interfaces":[[3,"creating-and-using-custom-interfaces"]],"Creating and Using a Network Identity":[[13,"creating-and-using-a-network-identity"]],"Creator Permissions":[[4,"creator-permissions"]],"Cryptographic Attribution":[[4,"cryptographic-attribution"]],"Cryptographic Primitives":[[13,"cryptographic-primitives"]],"Current Status":[[15,"current-status"]],"Current Usage":[[13,"current-usage"]],"Custom Interfaces":[[1,"custom-interfaces"],[7,"custom-interfaces"]],"Customizing Templates":[[4,"customizing-templates"]],"Death To The Address":[[16,"death-to-the-address"]],"Debian Bookworm":[[3,"debian-bookworm"]],"Decentralization Or Uncentralizability?":[[16,"decentralization-or-uncentralizability"]],"Design Patterns For Post-IP Systems":[[16,"design-patterns-for-post-ip-systems"]],"Destination Naming":[[13,"destination-naming"]],"Destinations":[[13,"destinations"]],"Destinations, Not Addresses":[[9,"destinations-not-addresses"]],"Develop a Program with Reticulum":[[3,"develop-a-program-with-reticulum"]],"Discoverable Interfaces":[[7,"discoverable-interfaces"]],"Discovering Interfaces":[[14,"discovering-interfaces"]],"Discovery Parameters":[[7,"discovery-parameters"]],"Distributed Development":[[0,null]],"Distribution Without Intermediaries":[[0,"distribution-without-intermediaries"]],"Donations":[[12,"donations"]],"Echo":[[1,"echo"]],"Emergent Patterns":[[16,"emergent-patterns"]],"Enabling Discovery":[[7,"enabling-discovery"]],"Enabling the Git Page Node":[[4,"enabling-the-git-page-node"]],"Encryption Is Not A Feature":[[16,"encryption-is-not-a-feature"]],"Ethernet-based Hardware":[[5,"ethernet-based-hardware"]],"Ethics Of The Tool":[[16,"ethics-of-the-tool"]],"Example Configuration":[[7,"example-configuration"]],"Fabric Of The Independent":[[16,"fabric-of-the-independent"]],"Fallacy Of The Cloud":[[16,"fallacy-of-the-cloud"]],"Filetransfer":[[1,"filetransfer"]],"Finding Your Way":[[3,"finding-your-way"]],"Fixed Serial Port Names":[[14,"fixed-serial-port-names"]],"Flow & Time":[[16,"flow-time"]],"Forking Repositories":[[4,"forking-repositories"]],"Formatting & Syntax Highlighting":[[4,"formatting-syntax-highlighting"]],"Future Implications":[[13,"future-implications"]],"Getting Further":[[13,"getting-further"]],"Getting Started Fast":[[3,null]],"Git Configuration Parameters":[[4,"git-configuration-parameters"]],"Git OveLine truncated
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Programs Using Reticulum - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Programs Using Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -513,7 +513,7 @@ plugin system for expandability.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Support Reticulum - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Support Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -383,7 +383,7 @@ circumstances, so we rely on old-fashioned human feedback.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Understanding Reticulum - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Understanding Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -973,6 +973,7 @@ but excluding any interface access codes.
|
|||||||
<img alt="_images/if_mode_graph_b.png" src="_images/if_mode_graph_b.png" />
|
<img alt="_images/if_mode_graph_b.png" src="_images/if_mode_graph_b.png" />
|
||||||
<p>Or, represented in table form:</p>
|
<p>Or, represented in table form:</p>
|
||||||
<img alt="_images/if_mode_graph_c.png" src="_images/if_mode_graph_c.png" />
|
<img alt="_images/if_mode_graph_c.png" src="_images/if_mode_graph_c.png" />
|
||||||
|
<p>For a visually intuitive overview of how announce propagation rules function in practice, you can take a look at the <a class="reference external" href="https://rns.moscow/announce-sim.html">Announce Propagation Simulator</a> hosted by <a class="reference external" href="https://rns.moscow/">rns.moscow</a>.</p>
|
||||||
</section>
|
</section>
|
||||||
<section id="cryptographic-primitives">
|
<section id="cryptographic-primitives">
|
||||||
<span id="understanding-primitives"></span><h3>Cryptographic Primitives<a class="headerlink" href="#cryptographic-primitives" title="Link to this heading">¶</a></h3>
|
<span id="understanding-primitives"></span><h3>Cryptographic Primitives<a class="headerlink" href="#cryptographic-primitives" title="Link to this heading">¶</a></h3>
|
||||||
@@ -1118,7 +1119,7 @@ those risks are acceptable to you.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
+44
-39
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Using Reticulum on Your System - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Using Reticulum on Your System - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -558,8 +558,8 @@ Reticulum Transport Instance <5245a8efe1788c6a1cd36144a270e13b> running
|
|||||||
</pre></div>
|
</pre></div>
|
||||||
</div>
|
</div>
|
||||||
<p><strong>All Command-Line Options</strong></p>
|
<p><strong>All Command-Line Options</strong></p>
|
||||||
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||||
|
|
||||||
Reticulum Network Stack Status
|
Reticulum Network Stack Status
|
||||||
@@ -573,10 +573,14 @@ options:
|
|||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-a, --all show all interfaces
|
-a, --all show all interfaces
|
||||||
-A, --announce-stats show announce stats
|
-A, --announce-stats show announce stats
|
||||||
|
-P, --pr-stats show path request stats
|
||||||
-l, --link-stats show link stats
|
-l, --link-stats show link stats
|
||||||
|
-B, --burst only show interfaces with active bursts
|
||||||
|
-b, --blocked-ips show blocked IPs per interface
|
||||||
-t, --totals display traffic totals
|
-t, --totals display traffic totals
|
||||||
|
-q, --queues display queue stats
|
||||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||||
announces, arx, atx, held]
|
announces, arx, atx, prx, ptx, held]
|
||||||
-r, --reverse reverse sorting
|
-r, --reverse reverse sorting
|
||||||
-j, --json output in JSON format
|
-j, --json output in JSON format
|
||||||
-R hash transport identity hash of remote instance to get status from
|
-R hash transport identity hash of remote instance to get status from
|
||||||
@@ -1106,39 +1110,35 @@ positional arguments:
|
|||||||
destination hexadecimal hash of the destination to connect to
|
destination hexadecimal hash of the destination to connect to
|
||||||
|
|
||||||
options:
|
options:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--config, -c CONFIG path to alternative Reticulum config directory
|
--config, -c PATH path to config directory
|
||||||
--identity, -i IDENTITY
|
--rnsconfig, -c PATH path to alternative Reticulum config directory
|
||||||
path to identity file to use
|
--identity, -i IDENTITY path to identity file to use
|
||||||
-v, --verbose increase verbosity
|
-v, --verbose increase verbosity
|
||||||
-q, --quiet decrease verbosity
|
-q, --quiet decrease verbosity
|
||||||
-p, --print-identity print identity and destination info and exit
|
-p, --print-identity print identity and destination info and exit
|
||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-l, --listen listen (server) mode; any command specified after --
|
-l, --listen listen (server) mode; any command specified after --
|
||||||
will be used as the default command when the initiator
|
will be used as the default command when the initiator
|
||||||
does not provide one or when remote command execution
|
does not provide one or when remote command execution
|
||||||
is disabled; if no command is specified, the default
|
is disabled; if no command is specified, the default
|
||||||
shell of the user running rnsh will be used
|
shell of the user running rnsh will be used
|
||||||
-s, --service SERVICE
|
-s, --service SERVICE service name for identity file if not the default
|
||||||
service name for identity file if not the default
|
-b, --announce PERIOD announce on startup and every PERIOD seconds; specify
|
||||||
-b, --announce PERIOD
|
0 to announce on startup only
|
||||||
announce on startup and every PERIOD seconds; specify
|
-a, --allowed HASH allow this identity to connect (may be specified
|
||||||
0 to announce on startup only
|
multiple times); allowed identities can also be
|
||||||
-a, --allowed HASH allow this identity to connect (may be specified
|
specified in ~/.rnsh/allowed_identities or
|
||||||
multiple times); allowed identities can also be
|
~/.config/rnsh/allowed_identities, one hash per line
|
||||||
specified in ~/.rnsh/allowed_identities or
|
-n, --no-auth disable authentication (allow any identity to connect)
|
||||||
~/.config/rnsh/allowed_identities, one hash per line
|
|
||||||
-n, --no-auth disable authentication (allow any identity to connect)
|
|
||||||
-A, --remote-command-as-args
|
-A, --remote-command-as-args
|
||||||
concatenate remote command to the argument list of the
|
concatenate remote command to the argument list of the
|
||||||
default program or shell
|
default program or shell
|
||||||
-C, --no-remote-command
|
-C, --no-remote-command disable executing command lines received from the
|
||||||
disable executing command lines received from the
|
remote initiator
|
||||||
remote initiator
|
-N, --no-id disable identity announcement on connect
|
||||||
-N, --no-id disable identity announcement on connect
|
-m, --mirror return with the exit code of the remote process
|
||||||
-m, --mirror return with the exit code of the remote process
|
-w, --timeout SECONDS connect and request timeout in seconds
|
||||||
-w, --timeout SECONDS
|
|
||||||
connect and request timeout in seconds
|
|
||||||
|
|
||||||
When specifying a command to execute, separate rnsh options from the command
|
When specifying a command to execute, separate rnsh options from the command
|
||||||
and its arguments with --. For example:
|
and its arguments with --. For example:
|
||||||
@@ -1307,6 +1307,11 @@ network_identity = ~/.reticulum/storage/identities/my_network
|
|||||||
...
|
...
|
||||||
</pre></div>
|
</pre></div>
|
||||||
</div>
|
</div>
|
||||||
|
<p>For more fine-grained control over how discovered interfaces are auto-connected, additional options are provided for configuraiton. These are not necessary to set in most cases, but can be useful in certain situations.</p>
|
||||||
|
<ul class="simple">
|
||||||
|
<li><p>The <code class="docutils literal notranslate"><span class="pre">autoconnect_interface_mode</span></code> options specifies which mode discovered interfaces should be created with when auto-connecting.</p></li>
|
||||||
|
<li><p>The <code class="docutils literal notranslate"><span class="pre">autoconnect_announces_to_internal</span></code> option allows you to specify that auto-connected interfaces should propagate announces to <code class="docutils literal notranslate"><span class="pre">internal</span></code> mode interfaces, even if the auto-connected interface’s mode would normally not allow for this.</p></li>
|
||||||
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
<section id="remote-management">
|
<section id="remote-management">
|
||||||
<h2>Remote Management<a class="headerlink" href="#remote-management" title="Link to this heading">¶</a></h2>
|
<h2>Remote Management<a class="headerlink" href="#remote-management" title="Link to this heading">¶</a></h2>
|
||||||
@@ -1639,7 +1644,7 @@ systemctl --user enable rnsd.service
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>What is Reticulum? - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>What is Reticulum? - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -505,7 +505,7 @@ network, and vice versa.</p>
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
|
||||||
|
|
||||||
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
|
||||||
<title>Zen of Reticulum - Reticulum Network Stack 1.3.8 documentation</title>
|
<title>Zen of Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
|
||||||
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
|
||||||
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
|
||||||
@@ -180,7 +180,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-center">
|
<div class="header-center">
|
||||||
<a href="index.html"><div class="brand">Reticulum Network Stack 1.3.8 documentation</div></a>
|
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="theme-toggle-container theme-toggle-header">
|
<div class="theme-toggle-container theme-toggle-header">
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="sidebar-brand-text">Reticulum Network Stack 1.3.8 documentation</span>
|
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
|
||||||
|
|
||||||
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
|
||||||
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
|
||||||
@@ -677,7 +677,7 @@ Imagine a messaging app. You write it once. It works on a laptop connected to fi
|
|||||||
|
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div><script src="_static/documentation_options.js?v=3cbadadc"></script>
|
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
|
||||||
<script src="_static/doctools.js?v=9bcbadda"></script>
|
<script src="_static/doctools.js?v=9bcbadda"></script>
|
||||||
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||||
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ to participate in the development of Reticulum itself.
|
|||||||
* [Backbone Interface](interfaces.md#backbone-interface)
|
* [Backbone Interface](interfaces.md#backbone-interface)
|
||||||
* [Listeners](interfaces.md#listeners)
|
* [Listeners](interfaces.md#listeners)
|
||||||
* [Connecting Remotes](interfaces.md#connecting-remotes)
|
* [Connecting Remotes](interfaces.md#connecting-remotes)
|
||||||
|
* [Automated Blocking](interfaces.md#automated-blocking)
|
||||||
* [TCP Server Interface](interfaces.md#tcp-server-interface)
|
* [TCP Server Interface](interfaces.md#tcp-server-interface)
|
||||||
* [TCP Client Interface](interfaces.md#tcp-client-interface)
|
* [TCP Client Interface](interfaces.md#tcp-client-interface)
|
||||||
* [UDP Interface](interfaces.md#udp-interface)
|
* [UDP Interface](interfaces.md#udp-interface)
|
||||||
@@ -182,6 +183,7 @@ to participate in the development of Reticulum itself.
|
|||||||
* [Announce Rate Control](interfaces.md#announce-rate-control)
|
* [Announce Rate Control](interfaces.md#announce-rate-control)
|
||||||
* [New Destination Rate Limiting](interfaces.md#new-destination-rate-limiting)
|
* [New Destination Rate Limiting](interfaces.md#new-destination-rate-limiting)
|
||||||
* [Path Request Burst Control](interfaces.md#path-request-burst-control)
|
* [Path Request Burst Control](interfaces.md#path-request-burst-control)
|
||||||
|
* [Tuning Ingress Queues](interfaces.md#tuning-ingress-queues)
|
||||||
* [Building Networks](networks.md)
|
* [Building Networks](networks.md)
|
||||||
* [Concepts & Overview](networks.md#concepts-overview)
|
* [Concepts & Overview](networks.md#concepts-overview)
|
||||||
* [Introductory Considerations](networks.md#introductory-considerations)
|
* [Introductory Considerations](networks.md#introductory-considerations)
|
||||||
|
|||||||
@@ -212,6 +212,51 @@ specify the target Yggdrasil IPv6 address and port, like so:
|
|||||||
target_port = 4343
|
target_port = 4343
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Automated Blocking
|
||||||
|
|
||||||
|
Listener instances of `BackboneInterface` will automatically block fast-flapping clients,
|
||||||
|
that repeatedly connect for a short amount of time, and then disconnect. Such behavior usually
|
||||||
|
occurs from clients trying to spam the network with announces or path requests, by connecting, dumping
|
||||||
|
a massive amount of requests, and then disconnecting in an attempt to bypass rate limits.
|
||||||
|
|
||||||
|
While such bypass attempts only have very limited effect on the amount of spam actually dumped (ingress limits
|
||||||
|
trigger immediately once a client exceeds rate limits), the behavior is often seen anyways, and
|
||||||
|
causes log noise and needless interface rotation. The fast-flapping block ensures such clients
|
||||||
|
are never allocated an interface on the transport instance.
|
||||||
|
|
||||||
|
Another common cause can simply be clients using implementations that are broken, or automated
|
||||||
|
scanning tools attempting to connect to the instance.
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[[Backbone Listener]]
|
||||||
|
type = BackboneInterface
|
||||||
|
enabled = yes
|
||||||
|
listen_on = 0.0.0.0
|
||||||
|
port = 4242
|
||||||
|
|
||||||
|
# Whether to enable blocking
|
||||||
|
block_fast_flapping = yes
|
||||||
|
|
||||||
|
# How long an IP address stays
|
||||||
|
# blocked, in minutes. Set to
|
||||||
|
# 12 hours by default.
|
||||||
|
fast_flapping_block_time = 720
|
||||||
|
|
||||||
|
# The minimum time, in seconds,
|
||||||
|
# an interface must stay connected
|
||||||
|
# to be considered not fast-flapping.
|
||||||
|
fast_flapping_threshold = 20
|
||||||
|
|
||||||
|
# Amount of fast flaps a remote
|
||||||
|
# IP can perform before having
|
||||||
|
# blocking triggered.
|
||||||
|
fast_flapping_grace = 5
|
||||||
|
```
|
||||||
|
|
||||||
|
The configuration options listed in the example above are the *default values*, and you do
|
||||||
|
not need to add them for automated blocking to work, but you can use them to change the
|
||||||
|
behavior from the defaults, if necessary.
|
||||||
|
|
||||||
## TCP Server Interface
|
## TCP Server Interface
|
||||||
|
|
||||||
The TCP Server interface is suitable for allowing other peers to connect over
|
The TCP Server interface is suitable for allowing other peers to connect over
|
||||||
@@ -894,6 +939,9 @@ When `discoverable` is enabled, a variety of additional options become available
|
|||||||
`discovery_name`
|
`discovery_name`
|
||||||
: A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
: A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
||||||
|
|
||||||
|
`discovery_lxmf_address`
|
||||||
|
: An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.
|
||||||
|
|
||||||
`announce_interval`
|
`announce_interval`
|
||||||
: The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
: The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
||||||
|
|
||||||
@@ -939,7 +987,13 @@ If you enable `discovery_encrypt` but do not configure a valid `network_identity
|
|||||||
**Physical Location**
|
**Physical Location**
|
||||||
|
|
||||||
`latitude`, `longitude`, `height`
|
`latitude`, `longitude`, `height`
|
||||||
: Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters.
|
: Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters above mean sea level.
|
||||||
|
|
||||||
|
`location_cmd`
|
||||||
|
: Optional path to executable or script that returns the physical coordinates for the interface. This can be used instead of manually setting `latitude`, `longitude` and `height`. Reticulum expects the script to output the location data to `stdout` on a single line, separated by commas, with values as floating point numbers in the format `LAT, LON, HEIGHT`. Coordinates should be in decimal degrees, height in meters above mean sea level.
|
||||||
|
|
||||||
|
#### NOTE
|
||||||
|
The height value for interface discovery is specified in *height above mean sea level*! This is the geoid-corrected height value, and is distinct from GPS altitude. If you manually specify height, it will typically be set to what you find on a topographical map. If you are using a script to output the location data, make sure that you are using the geoid-corrected altitude, not height above the GPS ellipsoid. Most GPS systems will make both figures available.
|
||||||
|
|
||||||
**Radio Parameters**
|
**Radio Parameters**
|
||||||
|
|
||||||
@@ -1080,6 +1134,14 @@ These can be used to control various aspects of interface behaviour.
|
|||||||
> > be a radio interface serving a wide area, where users are
|
> > be a radio interface serving a wide area, where users are
|
||||||
> > expected to connect momentarily, use the network, and then
|
> > expected to connect momentarily, use the network, and then
|
||||||
> > disappear again.
|
> > disappear again.
|
||||||
|
> > - See the [Interface Modes](#interfaces-modes) section
|
||||||
|
> > below for a reference on additional modes.
|
||||||
|
> * The `gravity` option specifies the pathing affinity of an interface.
|
||||||
|
> If not set specifically, and unless otherwise configured by
|
||||||
|
> `default_gravity` or `autoconnect_interface_gravity`,
|
||||||
|
> it defaults to `0`. Positive values increase pathing affinity,
|
||||||
|
> and negative values decrease it.
|
||||||
|
>
|
||||||
> * The `outgoing` option sets whether an interface is allowed
|
> * The `outgoing` option sets whether an interface is allowed
|
||||||
> to transmit. Defaults to `True`. If set to `False` or `No`
|
> to transmit. Defaults to `True`. If set to `False` or `No`
|
||||||
> the interface will only receive data, and never transmit.
|
> the interface will only receive data, and never transmit.
|
||||||
@@ -1150,6 +1212,10 @@ These can be used to control various aspects of interface behaviour.
|
|||||||
> `internal` mode interfaces may still be resolvable by means
|
> `internal` mode interfaces may still be resolvable by means
|
||||||
> of path requests.
|
> of path requests.
|
||||||
>
|
>
|
||||||
|
> * To allow an interface that would *otherwise not* propagate
|
||||||
|
> announces to `internal` mode interfaces to do so, you can
|
||||||
|
> configure the `announces_to_internal` option to `True`.
|
||||||
|
>
|
||||||
|
|
||||||
## Interface Modes
|
## Interface Modes
|
||||||
|
|
||||||
@@ -1421,4 +1487,30 @@ but all the parameters are exposed for configuration if needed.
|
|||||||
|
|
||||||
All of the above settings can be configured both as instance-wide defaults
|
All of the above settings can be configured both as instance-wide defaults
|
||||||
under the `[reticulum]` section of the configuration file, or on a per-
|
under the `[reticulum]` section of the configuration file, or on a per-
|
||||||
interface basis under the relevant interface configuration section.
|
interface basis under the relevant interface configuration section.
|
||||||
|
|
||||||
|
## Tuning Ingress Queues
|
||||||
|
|
||||||
|
Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:
|
||||||
|
|
||||||
|
> 1. Data and general traffic
|
||||||
|
> 2. Announces
|
||||||
|
> 3. Path requests
|
||||||
|
> 4. Ingress-limited traffic
|
||||||
|
|
||||||
|
You can tune the queue sizes from the defaults, for example if you’re running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the `[reticulum]` section of the config
|
||||||
|
|
||||||
|
> * The `qlen_in_data` option sets the maximum size of the data
|
||||||
|
> queue. Defaults to `4096`.
|
||||||
|
>
|
||||||
|
> * The `qlen_in_announce` option sets the maximum size of the announce
|
||||||
|
> queue. Defaults to `256`.
|
||||||
|
>
|
||||||
|
> * The `qlen_in_pr` option sets the maximum size of the path request
|
||||||
|
> queue. Defaults to `256`.
|
||||||
|
>
|
||||||
|
> * The `qlen_in_il` option sets the maximum size of the ingress limiter
|
||||||
|
> queue. Defaults to `128`.
|
||||||
|
>
|
||||||
|
|
||||||
|
If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.
|
||||||
@@ -69,9 +69,44 @@ alterations should be made on a per-interface basis instead.
|
|||||||
Minimum bitrate required across a medium for Reticulum to be able
|
Minimum bitrate required across a medium for Reticulum to be able
|
||||||
to successfully establish links. Currently 5 bits per second.
|
to successfully establish links. Currently 5 bits per second.
|
||||||
|
|
||||||
|
#### `DEFAULT_PER_HOP_TIMEOUT = 6`
|
||||||
|
|
||||||
|
The default per-hop timeout value used in various timeout calculations.
|
||||||
|
|
||||||
#### `static get_instance()`
|
#### `static get_instance()`
|
||||||
|
|
||||||
Return the currently running Reticulum instance
|
Returns the currently running Reticulum instance.
|
||||||
|
|
||||||
|
#### `get_first_hop_timeout(destination)`
|
||||||
|
|
||||||
|
Returns a best-effort estimate of a reasonable minimum
|
||||||
|
*first-hop* timeout value for a given destination hash.
|
||||||
|
If a path is known, this calculation takes the next-hop
|
||||||
|
interface’s bitrate into account. If no path is currently
|
||||||
|
known, returns `DEFAULT_PER_HOP_TIMEOUT`.
|
||||||
|
|
||||||
|
* **Parameters:**
|
||||||
|
**destination** – A destination hash, as *bytes*.
|
||||||
|
|
||||||
|
* **Returns:**
|
||||||
|
First-hop timeout, in seconds.
|
||||||
|
|
||||||
|
#### `get_lowest_interface_bitrate()`
|
||||||
|
|
||||||
|
Returns the bitrate of the slowest currently online
|
||||||
|
interface, or None if no online interface bitrate
|
||||||
|
|
||||||
|
* **Returns:**
|
||||||
|
Lowest online interface bitrate in bits per second, or `None`.
|
||||||
|
|
||||||
|
#### `get_medium_path_timeout()`
|
||||||
|
|
||||||
|
Returns an estimate of a reasonable minimum path request timeout covering
|
||||||
|
a full round trip for an MTU on the slowest currently online interface
|
||||||
|
plus per hop grace
|
||||||
|
|
||||||
|
* **Returns:**
|
||||||
|
Timeout in seconds or 0 if it’s unknown.
|
||||||
|
|
||||||
#### `static should_use_implicit_proof()`
|
#### `static should_use_implicit_proof()`
|
||||||
|
|
||||||
@@ -474,6 +509,16 @@ Sets the destinations proof strategy.
|
|||||||
* **Parameters:**
|
* **Parameters:**
|
||||||
**proof_strategy** – One of `RNS.Destination.PROVE_NONE`, `RNS.Destination.PROVE_ALL` or `RNS.Destination.PROVE_APP`. If `RNS.Destination.PROVE_APP` is set, the proof_requested_callback will be called to determine whether a proof should be sent or not.
|
**proof_strategy** – One of `RNS.Destination.PROVE_NONE`, `RNS.Destination.PROVE_ALL` or `RNS.Destination.PROVE_APP`. If `RNS.Destination.PROVE_APP` is set, the proof_requested_callback will be called to determine whether a proof should be sent or not.
|
||||||
|
|
||||||
|
#### `set_max_request_size(max_request_size)`
|
||||||
|
|
||||||
|
Sets the maximum accepted request size for registered request handlers.
|
||||||
|
|
||||||
|
* **Parameters:**
|
||||||
|
**max_request_size** – The maximum accepted request size in bytes, as an integer.
|
||||||
|
|
||||||
|
* **Raises:**
|
||||||
|
`TypeError` or `ValueError` if any of the argument is invalid.
|
||||||
|
|
||||||
#### `register_request_handler(path, response_generator=None, allow=ALLOW_NONE, allowed_list=None, auto_compress=True)`
|
#### `register_request_handler(path, response_generator=None, allow=ALLOW_NONE, allowed_list=None, auto_compress=True)`
|
||||||
|
|
||||||
Registers a request handler.
|
Registers a request handler.
|
||||||
@@ -757,7 +802,7 @@ thus preserved. This method can be used for authentication.
|
|||||||
* **Parameters:**
|
* **Parameters:**
|
||||||
**identity** – An RNS.Identity instance to identify as.
|
**identity** – An RNS.Identity instance to identify as.
|
||||||
|
|
||||||
#### `request(path, data=None, response_callback=None, failed_callback=None, progress_callback=None, timeout=None)`
|
#### `request(path, data=None, response_callback=None, failed_callback=None, progress_callback=None, timeout=None, max_response_size=None)`
|
||||||
|
|
||||||
Sends a request to the remote peer.
|
Sends a request to the remote peer.
|
||||||
|
|
||||||
@@ -766,6 +811,7 @@ Sends a request to the remote peer.
|
|||||||
* **response_callback** – An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the [Request Example](examples.md#example-request) for more info.
|
* **response_callback** – An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the [Request Example](examples.md#example-request) for more info.
|
||||||
* **failed_callback** – An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the [Request Example](examples.md#example-request) for more info.
|
* **failed_callback** – An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the [Request Example](examples.md#example-request) for more info.
|
||||||
* **progress_callback** – An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property.
|
* **progress_callback** – An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property.
|
||||||
|
* **max_response_size** – An optional maximum accepted response size, in bytes as an integer.
|
||||||
* **timeout** – An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT.
|
* **timeout** – An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT.
|
||||||
|
|
||||||
* **Returns:**
|
* **Returns:**
|
||||||
|
|||||||
@@ -682,6 +682,8 @@ Roaming ✓ ✕ ✕ ✕ ✓ ✓
|
|||||||
✓ Will rebroadcast announce
|
✓ Will rebroadcast announce
|
||||||
✕ Will not rebroadcast announce -->
|
✕ Will not rebroadcast announce -->
|
||||||
|
|
||||||
|
For a visually intuitive overview of how announce propagation rules function in practice, you can take a look at the [Announce Propagation Simulator](https://rns.moscow/announce-sim.html) hosted by [rns.moscow](https://rns.moscow/).
|
||||||
|
|
||||||
### Cryptographic Primitives
|
### Cryptographic Primitives
|
||||||
|
|
||||||
Reticulum uses a simple suite of efficient, strong and well-tested cryptographic primitives, with widely available implementations that can be used both on general-purpose CPUs and on microcontrollers.
|
Reticulum uses a simple suite of efficient, strong and well-tested cryptographic primitives, with widely available implementations that can be used both on general-purpose CPUs and on microcontrollers.
|
||||||
|
|||||||
+40
-35
@@ -318,8 +318,8 @@ Reticulum Transport Instance <5245a8efe1788c6a1cd36144a270e13b> running
|
|||||||
**All Command-Line Options**
|
**All Command-Line Options**
|
||||||
|
|
||||||
```text
|
```text
|
||||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||||
|
|
||||||
Reticulum Network Stack Status
|
Reticulum Network Stack Status
|
||||||
@@ -333,10 +333,14 @@ options:
|
|||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-a, --all show all interfaces
|
-a, --all show all interfaces
|
||||||
-A, --announce-stats show announce stats
|
-A, --announce-stats show announce stats
|
||||||
|
-P, --pr-stats show path request stats
|
||||||
-l, --link-stats show link stats
|
-l, --link-stats show link stats
|
||||||
|
-B, --burst only show interfaces with active bursts
|
||||||
|
-b, --blocked-ips show blocked IPs per interface
|
||||||
-t, --totals display traffic totals
|
-t, --totals display traffic totals
|
||||||
|
-q, --queues display queue stats
|
||||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||||
announces, arx, atx, held]
|
announces, arx, atx, prx, ptx, held]
|
||||||
-r, --reverse reverse sorting
|
-r, --reverse reverse sorting
|
||||||
-j, --json output in JSON format
|
-j, --json output in JSON format
|
||||||
-R hash transport identity hash of remote instance to get status from
|
-R hash transport identity hash of remote instance to get status from
|
||||||
@@ -965,39 +969,35 @@ positional arguments:
|
|||||||
destination hexadecimal hash of the destination to connect to
|
destination hexadecimal hash of the destination to connect to
|
||||||
|
|
||||||
options:
|
options:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--config, -c CONFIG path to alternative Reticulum config directory
|
--config, -c PATH path to config directory
|
||||||
--identity, -i IDENTITY
|
--rnsconfig, -c PATH path to alternative Reticulum config directory
|
||||||
path to identity file to use
|
--identity, -i IDENTITY path to identity file to use
|
||||||
-v, --verbose increase verbosity
|
-v, --verbose increase verbosity
|
||||||
-q, --quiet decrease verbosity
|
-q, --quiet decrease verbosity
|
||||||
-p, --print-identity print identity and destination info and exit
|
-p, --print-identity print identity and destination info and exit
|
||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-l, --listen listen (server) mode; any command specified after --
|
-l, --listen listen (server) mode; any command specified after --
|
||||||
will be used as the default command when the initiator
|
will be used as the default command when the initiator
|
||||||
does not provide one or when remote command execution
|
does not provide one or when remote command execution
|
||||||
is disabled; if no command is specified, the default
|
is disabled; if no command is specified, the default
|
||||||
shell of the user running rnsh will be used
|
shell of the user running rnsh will be used
|
||||||
-s, --service SERVICE
|
-s, --service SERVICE service name for identity file if not the default
|
||||||
service name for identity file if not the default
|
-b, --announce PERIOD announce on startup and every PERIOD seconds; specify
|
||||||
-b, --announce PERIOD
|
0 to announce on startup only
|
||||||
announce on startup and every PERIOD seconds; specify
|
-a, --allowed HASH allow this identity to connect (may be specified
|
||||||
0 to announce on startup only
|
multiple times); allowed identities can also be
|
||||||
-a, --allowed HASH allow this identity to connect (may be specified
|
specified in ~/.rnsh/allowed_identities or
|
||||||
multiple times); allowed identities can also be
|
~/.config/rnsh/allowed_identities, one hash per line
|
||||||
specified in ~/.rnsh/allowed_identities or
|
-n, --no-auth disable authentication (allow any identity to connect)
|
||||||
~/.config/rnsh/allowed_identities, one hash per line
|
|
||||||
-n, --no-auth disable authentication (allow any identity to connect)
|
|
||||||
-A, --remote-command-as-args
|
-A, --remote-command-as-args
|
||||||
concatenate remote command to the argument list of the
|
concatenate remote command to the argument list of the
|
||||||
default program or shell
|
default program or shell
|
||||||
-C, --no-remote-command
|
-C, --no-remote-command disable executing command lines received from the
|
||||||
disable executing command lines received from the
|
remote initiator
|
||||||
remote initiator
|
-N, --no-id disable identity announcement on connect
|
||||||
-N, --no-id disable identity announcement on connect
|
-m, --mirror return with the exit code of the remote process
|
||||||
-m, --mirror return with the exit code of the remote process
|
-w, --timeout SECONDS connect and request timeout in seconds
|
||||||
-w, --timeout SECONDS
|
|
||||||
connect and request timeout in seconds
|
|
||||||
|
|
||||||
When specifying a command to execute, separate rnsh options from the command
|
When specifying a command to execute, separate rnsh options from the command
|
||||||
and its arguments with --. For example:
|
and its arguments with --. For example:
|
||||||
@@ -1179,6 +1179,11 @@ network_identity = ~/.reticulum/storage/identities/my_network
|
|||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For more fine-grained control over how discovered interfaces are auto-connected, additional options are provided for configuraiton. These are not necessary to set in most cases, but can be useful in certain situations.
|
||||||
|
|
||||||
|
* The `autoconnect_interface_mode` options specifies which mode discovered interfaces should be created with when auto-connecting.
|
||||||
|
* The `autoconnect_announces_to_internal` option allows you to specify that auto-connected interfaces should propagate announces to `internal` mode interfaces, even if the auto-connected interface’s mode would normally not allow for this.
|
||||||
|
|
||||||
## Remote Management
|
## Remote Management
|
||||||
|
|
||||||
It is possible to allow remote management of Reticulum
|
It is possible to allow remote management of Reticulum
|
||||||
|
|||||||
+100
-2
@@ -230,6 +230,51 @@ specify the target Yggdrasil IPv6 address and port, like so:
|
|||||||
target_host = 201:5d78:af73:5caf:a4de:a79f:3278:71e5
|
target_host = 201:5d78:af73:5caf:a4de:a79f:3278:71e5
|
||||||
target_port = 4343
|
target_port = 4343
|
||||||
|
|
||||||
|
Automated Blocking
|
||||||
|
------------------
|
||||||
|
Listener instances of ``BackboneInterface`` will automatically block fast-flapping clients,
|
||||||
|
that repeatedly connect for a short amount of time, and then disconnect. Such behavior usually
|
||||||
|
occurs from clients trying to spam the network with announces or path requests, by connecting, dumping
|
||||||
|
a massive amount of requests, and then disconnecting in an attempt to bypass rate limits.
|
||||||
|
|
||||||
|
While such bypass attempts only have very limited effect on the amount of spam actually dumped (ingress limits
|
||||||
|
trigger immediately once a client exceeds rate limits), the behavior is often seen anyways, and
|
||||||
|
causes log noise and needless interface rotation. The fast-flapping block ensures such clients
|
||||||
|
are never allocated an interface on the transport instance.
|
||||||
|
|
||||||
|
Another common cause can simply be clients using implementations that are broken, or automated
|
||||||
|
scanning tools attempting to connect to the instance.
|
||||||
|
|
||||||
|
.. code:: ini
|
||||||
|
|
||||||
|
[[Backbone Listener]]
|
||||||
|
type = BackboneInterface
|
||||||
|
enabled = yes
|
||||||
|
listen_on = 0.0.0.0
|
||||||
|
port = 4242
|
||||||
|
|
||||||
|
# Whether to enable blocking
|
||||||
|
block_fast_flapping = yes
|
||||||
|
|
||||||
|
# How long an IP address stays
|
||||||
|
# blocked, in minutes. Set to
|
||||||
|
# 12 hours by default.
|
||||||
|
fast_flapping_block_time = 720
|
||||||
|
|
||||||
|
# The minimum time, in seconds,
|
||||||
|
# an interface must stay connected
|
||||||
|
# to be considered not fast-flapping.
|
||||||
|
fast_flapping_threshold = 20
|
||||||
|
|
||||||
|
# Amount of fast flaps a remote
|
||||||
|
# IP can perform before having
|
||||||
|
# blocking triggered.
|
||||||
|
fast_flapping_grace = 5
|
||||||
|
|
||||||
|
The configuration options listed in the example above are the *default values*, and you do
|
||||||
|
not need to add them for automated blocking to work, but you can use them to change the
|
||||||
|
behavior from the defaults, if necessary.
|
||||||
|
|
||||||
.. _interfaces-tcps:
|
.. _interfaces-tcps:
|
||||||
|
|
||||||
TCP Server Interface
|
TCP Server Interface
|
||||||
@@ -953,6 +998,9 @@ When ``discoverable`` is enabled, a variety of additional options become availab
|
|||||||
``discovery_name``
|
``discovery_name``
|
||||||
A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
||||||
|
|
||||||
|
``discovery_lxmf_address``
|
||||||
|
An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.
|
||||||
|
|
||||||
``announce_interval``
|
``announce_interval``
|
||||||
The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
||||||
|
|
||||||
@@ -998,7 +1046,13 @@ On a real system, you should make the script robust enough to deal with intermit
|
|||||||
**Physical Location**
|
**Physical Location**
|
||||||
|
|
||||||
``latitude``, ``longitude``, ``height``
|
``latitude``, ``longitude``, ``height``
|
||||||
Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters.
|
Optional physical coordinates for the interface. These are useful for mapping discovered interfaces geographically or for clients to automatically select the nearest access point. Coordinates should be in decimal degrees, height in meters above mean sea level.
|
||||||
|
|
||||||
|
``location_cmd``
|
||||||
|
Optional path to executable or script that returns the physical coordinates for the interface. This can be used instead of manually setting ``latitude``, ``longitude`` and ``height``. Reticulum expects the script to output the location data to ``stdout`` on a single line, separated by commas, with values as floating point numbers in the format ``LAT, LON, HEIGHT``. Coordinates should be in decimal degrees, height in meters above mean sea level.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
The height value for interface discovery is specified in *height above mean sea level*! This is the geoid-corrected height value, and is distinct from GPS altitude. If you manually specify height, it will typically be set to what you find on a topographical map. If you are using a script to output the location data, make sure that you are using the geoid-corrected altitude, not height above the GPS ellipsoid. Most GPS systems will make both figures available.
|
||||||
|
|
||||||
**Radio Parameters**
|
**Radio Parameters**
|
||||||
|
|
||||||
@@ -1149,6 +1203,15 @@ These can be used to control various aspects of interface behaviour.
|
|||||||
expected to connect momentarily, use the network, and then
|
expected to connect momentarily, use the network, and then
|
||||||
disappear again.
|
disappear again.
|
||||||
|
|
||||||
|
- See the :ref:`Interface Modes<interfaces-modes>` section
|
||||||
|
below for a reference on additional modes.
|
||||||
|
|
||||||
|
* | The ``gravity`` option specifies the pathing affinity of an interface.
|
||||||
|
If not set specifically, and unless otherwise configured by
|
||||||
|
``default_gravity`` or ``autoconnect_interface_gravity``,
|
||||||
|
it defaults to ``0``. Positive values increase pathing affinity,
|
||||||
|
and negative values decrease it.
|
||||||
|
|
||||||
* | The ``outgoing`` option sets whether an interface is allowed
|
* | The ``outgoing`` option sets whether an interface is allowed
|
||||||
to transmit. Defaults to ``True``. If set to ``False`` or ``No``
|
to transmit. Defaults to ``True``. If set to ``False`` or ``No``
|
||||||
the interface will only receive data, and never transmit.
|
the interface will only receive data, and never transmit.
|
||||||
@@ -1223,6 +1286,11 @@ These can be used to control various aspects of interface behaviour.
|
|||||||
``internal`` mode interfaces may still be resolvable by means
|
``internal`` mode interfaces may still be resolvable by means
|
||||||
of path requests.
|
of path requests.
|
||||||
|
|
||||||
|
|
||||||
|
* | To allow an interface that would *otherwise not* propagate
|
||||||
|
announces to ``internal`` mode interfaces to do so, you can
|
||||||
|
configure the ``announces_to_internal`` option to ``True``.
|
||||||
|
|
||||||
.. _interfaces-modes:
|
.. _interfaces-modes:
|
||||||
|
|
||||||
Interface Modes
|
Interface Modes
|
||||||
@@ -1502,4 +1570,34 @@ but all the parameters are exposed for configuration if needed.
|
|||||||
|
|
||||||
All of the above settings can be configured both as instance-wide defaults
|
All of the above settings can be configured both as instance-wide defaults
|
||||||
under the ``[reticulum]`` section of the configuration file, or on a per-
|
under the ``[reticulum]`` section of the configuration file, or on a per-
|
||||||
interface basis under the relevant interface configuration section.
|
interface basis under the relevant interface configuration section.
|
||||||
|
|
||||||
|
|
||||||
|
Tuning Ingress Queues
|
||||||
|
=====================
|
||||||
|
|
||||||
|
Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:
|
||||||
|
|
||||||
|
1. Data and general traffic
|
||||||
|
|
||||||
|
2. Announces
|
||||||
|
|
||||||
|
3. Path requests
|
||||||
|
|
||||||
|
4. Ingress-limited traffic
|
||||||
|
|
||||||
|
You can tune the queue sizes from the defaults, for example if you're running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the ``[reticulum]`` section of the config
|
||||||
|
|
||||||
|
* | The ``qlen_in_data`` option sets the maximum size of the data
|
||||||
|
queue. Defaults to ``4096``.
|
||||||
|
|
||||||
|
* | The ``qlen_in_announce`` option sets the maximum size of the announce
|
||||||
|
queue. Defaults to ``256``.
|
||||||
|
|
||||||
|
* | The ``qlen_in_pr`` option sets the maximum size of the path request
|
||||||
|
queue. Defaults to ``256``.
|
||||||
|
|
||||||
|
* | The ``qlen_in_il`` option sets the maximum size of the ingress limiter
|
||||||
|
queue. Defaults to ``128``.
|
||||||
|
|
||||||
|
If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.
|
||||||
@@ -759,6 +759,8 @@ Or, represented in table form:
|
|||||||
✓ Will rebroadcast announce
|
✓ Will rebroadcast announce
|
||||||
✕ Will not rebroadcast announce
|
✕ Will not rebroadcast announce
|
||||||
|
|
||||||
|
For a visually intuitive overview of how announce propagation rules function in practice, you can take a look at the `Announce Propagation Simulator <https://rns.moscow/announce-sim.html>`_ hosted by `rns.moscow <https://rns.moscow/>`_.
|
||||||
|
|
||||||
|
|
||||||
.. _understanding-primitives:
|
.. _understanding-primitives:
|
||||||
|
|
||||||
|
|||||||
+41
-35
@@ -337,8 +337,8 @@ Filter output to only show some interfaces:
|
|||||||
|
|
||||||
.. code:: text
|
.. code:: text
|
||||||
|
|
||||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||||
|
|
||||||
Reticulum Network Stack Status
|
Reticulum Network Stack Status
|
||||||
@@ -352,10 +352,14 @@ Filter output to only show some interfaces:
|
|||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-a, --all show all interfaces
|
-a, --all show all interfaces
|
||||||
-A, --announce-stats show announce stats
|
-A, --announce-stats show announce stats
|
||||||
|
-P, --pr-stats show path request stats
|
||||||
-l, --link-stats show link stats
|
-l, --link-stats show link stats
|
||||||
|
-B, --burst only show interfaces with active bursts
|
||||||
|
-b, --blocked-ips show blocked IPs per interface
|
||||||
-t, --totals display traffic totals
|
-t, --totals display traffic totals
|
||||||
|
-q, --queues display queue stats
|
||||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||||
announces, arx, atx, held]
|
announces, arx, atx, prx, ptx, held]
|
||||||
-r, --reverse reverse sorting
|
-r, --reverse reverse sorting
|
||||||
-j, --json output in JSON format
|
-j, --json output in JSON format
|
||||||
-R hash transport identity hash of remote instance to get status from
|
-R hash transport identity hash of remote instance to get status from
|
||||||
@@ -1002,39 +1006,35 @@ available. These are only recognised immediately after a newline character:
|
|||||||
destination hexadecimal hash of the destination to connect to
|
destination hexadecimal hash of the destination to connect to
|
||||||
|
|
||||||
options:
|
options:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
--config, -c CONFIG path to alternative Reticulum config directory
|
--config, -c PATH path to config directory
|
||||||
--identity, -i IDENTITY
|
--rnsconfig, -c PATH path to alternative Reticulum config directory
|
||||||
path to identity file to use
|
--identity, -i IDENTITY path to identity file to use
|
||||||
-v, --verbose increase verbosity
|
-v, --verbose increase verbosity
|
||||||
-q, --quiet decrease verbosity
|
-q, --quiet decrease verbosity
|
||||||
-p, --print-identity print identity and destination info and exit
|
-p, --print-identity print identity and destination info and exit
|
||||||
--version show program's version number and exit
|
--version show program's version number and exit
|
||||||
-l, --listen listen (server) mode; any command specified after --
|
-l, --listen listen (server) mode; any command specified after --
|
||||||
will be used as the default command when the initiator
|
will be used as the default command when the initiator
|
||||||
does not provide one or when remote command execution
|
does not provide one or when remote command execution
|
||||||
is disabled; if no command is specified, the default
|
is disabled; if no command is specified, the default
|
||||||
shell of the user running rnsh will be used
|
shell of the user running rnsh will be used
|
||||||
-s, --service SERVICE
|
-s, --service SERVICE service name for identity file if not the default
|
||||||
service name for identity file if not the default
|
-b, --announce PERIOD announce on startup and every PERIOD seconds; specify
|
||||||
-b, --announce PERIOD
|
0 to announce on startup only
|
||||||
announce on startup and every PERIOD seconds; specify
|
-a, --allowed HASH allow this identity to connect (may be specified
|
||||||
0 to announce on startup only
|
multiple times); allowed identities can also be
|
||||||
-a, --allowed HASH allow this identity to connect (may be specified
|
specified in ~/.rnsh/allowed_identities or
|
||||||
multiple times); allowed identities can also be
|
~/.config/rnsh/allowed_identities, one hash per line
|
||||||
specified in ~/.rnsh/allowed_identities or
|
-n, --no-auth disable authentication (allow any identity to connect)
|
||||||
~/.config/rnsh/allowed_identities, one hash per line
|
|
||||||
-n, --no-auth disable authentication (allow any identity to connect)
|
|
||||||
-A, --remote-command-as-args
|
-A, --remote-command-as-args
|
||||||
concatenate remote command to the argument list of the
|
concatenate remote command to the argument list of the
|
||||||
default program or shell
|
default program or shell
|
||||||
-C, --no-remote-command
|
-C, --no-remote-command disable executing command lines received from the
|
||||||
disable executing command lines received from the
|
remote initiator
|
||||||
remote initiator
|
-N, --no-id disable identity announcement on connect
|
||||||
-N, --no-id disable identity announcement on connect
|
-m, --mirror return with the exit code of the remote process
|
||||||
-m, --mirror return with the exit code of the remote process
|
-w, --timeout SECONDS connect and request timeout in seconds
|
||||||
-w, --timeout SECONDS
|
|
||||||
connect and request timeout in seconds
|
|
||||||
|
|
||||||
When specifying a command to execute, separate rnsh options from the command
|
When specifying a command to execute, separate rnsh options from the command
|
||||||
and its arguments with --. For example:
|
and its arguments with --. For example:
|
||||||
@@ -1224,6 +1224,12 @@ The configuration snippet below contains an example of setting these additional
|
|||||||
network_identity = ~/.reticulum/storage/identities/my_network
|
network_identity = ~/.reticulum/storage/identities/my_network
|
||||||
...
|
...
|
||||||
|
|
||||||
|
For more fine-grained control over how discovered interfaces are auto-connected, additional options are provided for configuraiton. These are not necessary to set in most cases, but can be useful in certain situations.
|
||||||
|
|
||||||
|
* The ``autoconnect_interface_mode`` options specifies which mode discovered interfaces should be created with when auto-connecting.
|
||||||
|
|
||||||
|
* The ``autoconnect_announces_to_internal`` option allows you to specify that auto-connected interfaces should propagate announces to ``internal`` mode interfaces, even if the auto-connected interface's mode would normally not allow for this.
|
||||||
|
|
||||||
Remote Management
|
Remote Management
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import threading
|
import threading
|
||||||
import RNS
|
import RNS
|
||||||
from RNS.Channel import MessageState, ChannelOutletBase, Channel, MessageBase
|
from RNS.Channel import MessageState, LinkChannelOutlet, Channel, MessageBase
|
||||||
import RNS.Buffer
|
import RNS.Buffer
|
||||||
from RNS.vendor import umsgpack
|
from RNS.vendor import umsgpack
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
@@ -71,7 +71,7 @@ class Packet:
|
|||||||
self.delivered_callback(self)
|
self.delivered_callback(self)
|
||||||
|
|
||||||
|
|
||||||
class ChannelOutletTest(ChannelOutletBase):
|
class ChannelOutletTest(LinkChannelOutlet):
|
||||||
def get_packet_state(self, packet: Packet) -> MessageState:
|
def get_packet_state(self, packet: Packet) -> MessageState:
|
||||||
return packet.state
|
return packet.state
|
||||||
|
|
||||||
@@ -93,7 +93,7 @@ class ChannelOutletTest(ChannelOutletBase):
|
|||||||
self._usable = True
|
self._usable = True
|
||||||
self.packets = []
|
self.packets = []
|
||||||
self.lock = threading.RLock()
|
self.lock = threading.RLock()
|
||||||
self.packet_callback: Callable[[ChannelOutletBase, bytes], None] | None = None
|
self.packet_callback: Callable[[LinkChannelOutlet, bytes], None] | None = None
|
||||||
|
|
||||||
def send(self, raw: bytes) -> Packet:
|
def send(self, raw: bytes) -> Packet:
|
||||||
with self.lock:
|
with self.lock:
|
||||||
|
|||||||
@@ -145,6 +145,34 @@ class TestIdentity(unittest.TestCase):
|
|||||||
print("Sign/validate 16KB chunks: "+self.size_str(b/t, "b")+"ps")
|
print("Sign/validate 16KB chunks: "+self.size_str(b/t, "b")+"ps")
|
||||||
|
|
||||||
|
|
||||||
|
def test_3_timings(self):
|
||||||
|
import random
|
||||||
|
random.seed(618736)
|
||||||
|
print("")
|
||||||
|
blobs = []
|
||||||
|
times = []
|
||||||
|
t = RNS.Cryptography.Token(key=random.randbytes(64))
|
||||||
|
for n in range(0, 1000): blobs.append(random.randbytes(64))
|
||||||
|
|
||||||
|
for a in blobs:
|
||||||
|
for b in blobs:
|
||||||
|
st = time.time()
|
||||||
|
res = t.verify_hmac(b)
|
||||||
|
d = time.time()-st
|
||||||
|
times.append(d)
|
||||||
|
|
||||||
|
import statistics
|
||||||
|
tmin = min(times)*1000000
|
||||||
|
tmax = max(times)*1000000
|
||||||
|
tmean = (sum(times)/len(times))*1000000
|
||||||
|
tmed = statistics.median(times)*1000000
|
||||||
|
tmdev = tmax - tmin
|
||||||
|
mpct = (tmax/tmed)*100
|
||||||
|
print(" HMAC timings:")
|
||||||
|
print(" µs min/avg/med/max/mdev: "+str(round(tmin, 3))+"/"+str(round(tmean, 3))+"/"+str(round(tmed, 3))+"/"+str(round(tmax, 3))+"/"+str(round(tmdev, 3)))
|
||||||
|
print(" Max deviation from median: "+str(round(mpct, 1))+"%")
|
||||||
|
print()
|
||||||
|
|
||||||
def test_2_encrypt(self):
|
def test_2_encrypt(self):
|
||||||
print("")
|
print("")
|
||||||
|
|
||||||
|
|||||||
+22
-25
@@ -13,7 +13,6 @@ import RNS
|
|||||||
import os
|
import os
|
||||||
from tests.channel import MessageTest
|
from tests.channel import MessageTest
|
||||||
from RNS.Channel import MessageBase
|
from RNS.Channel import MessageBase
|
||||||
from RNS.Buffer import StreamDataMessage
|
|
||||||
from RNS.Interfaces.LocalInterface import LocalClientInterface
|
from RNS.Interfaces.LocalInterface import LocalClientInterface
|
||||||
from math import ceil
|
from math import ceil
|
||||||
|
|
||||||
@@ -27,7 +26,9 @@ fixed_keys = [
|
|||||||
("08bb35f92b06a0832991165a0d9b4fd91af7b7765ce4572aa6222070b11b767092b61b0fd18b3a59cae6deb9db6d4bfb1c7fcfe076cfd66eea7ddd5f877543b9", "d13712efc45ef87674fb5ac26c37c912"),
|
("08bb35f92b06a0832991165a0d9b4fd91af7b7765ce4572aa6222070b11b767092b61b0fd18b3a59cae6deb9db6d4bfb1c7fcfe076cfd66eea7ddd5f877543b9", "d13712efc45ef87674fb5ac26c37c912"),
|
||||||
]
|
]
|
||||||
|
|
||||||
BUFFER_TEST_TARGET = 32000
|
BUFFER_TEST_TARGET = 256000
|
||||||
|
BUFFER_TEST_TARGET_SLOW = 1800
|
||||||
|
SLOW_TEST_MARKER = b"@SLOW_TEST_MARKER"
|
||||||
LINK_UP_WAIT = 0.050
|
LINK_UP_WAIT = 0.050
|
||||||
|
|
||||||
def targets_job(caller):
|
def targets_job(caller):
|
||||||
@@ -734,23 +735,16 @@ class TestLink(unittest.TestCase):
|
|||||||
# 1000))
|
# 1000))
|
||||||
|
|
||||||
if local_interface.bitrate < 1000:
|
if local_interface.bitrate < 1000:
|
||||||
target_bytes = 3000
|
target_bytes = BUFFER_TEST_TARGET_SLOW-len(SLOW_TEST_MARKER)
|
||||||
|
message = SLOW_TEST_MARKER
|
||||||
else:
|
else:
|
||||||
target_bytes = BUFFER_TEST_TARGET
|
target_bytes = BUFFER_TEST_TARGET
|
||||||
|
message = b""
|
||||||
|
|
||||||
random.seed(154889)
|
random.seed(154889)
|
||||||
message = random.randbytes(target_bytes)
|
message += random.randbytes(target_bytes)
|
||||||
buffer_read_target = len(message)
|
buffer_read_target = len(message)
|
||||||
|
expected_rx_message = message + " back at you".encode("utf-8")
|
||||||
# the return message will have an appendage string " back at you"
|
|
||||||
# for every StreamDataMessage that arrives. To verify, we need
|
|
||||||
# to insert that string every MAX_DATA_LEN and also at the end.
|
|
||||||
expected_rx_message = b""
|
|
||||||
for i in range(0, len(message)):
|
|
||||||
if i > 0 and (i % StreamDataMessage.MAX_DATA_LEN) == 0:
|
|
||||||
expected_rx_message += " back at you".encode("utf-8")
|
|
||||||
expected_rx_message += bytes([message[i]])
|
|
||||||
expected_rx_message += " back at you".encode("utf-8")
|
|
||||||
|
|
||||||
# since the segments will be received at max length for a
|
# since the segments will be received at max length for a
|
||||||
# StreamDataMessage, the appended text will end up in a
|
# StreamDataMessage, the appended text will end up in a
|
||||||
@@ -760,7 +754,7 @@ class TestLink(unittest.TestCase):
|
|||||||
buffer.write(message)
|
buffer.write(message)
|
||||||
buffer.flush()
|
buffer.flush()
|
||||||
|
|
||||||
timeout = time.time() + 4
|
timeout = time.time() + 2.5
|
||||||
while not time.time() > timeout:
|
while not time.time() > timeout:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
print(f"Received {len(received)} chunks so far")
|
print(f"Received {len(received)} chunks so far")
|
||||||
@@ -864,28 +858,31 @@ def targets(yp=False):
|
|||||||
|
|
||||||
response_data = []
|
response_data = []
|
||||||
def handle_buffer(ready_bytes: int):
|
def handle_buffer(ready_bytes: int):
|
||||||
global buffer_read_len, BUFFER_TEST_TARGET
|
global buffer_read_len, BUFFER_TEST_TARGET, BUFFER_TEST_TARGET_SLOW
|
||||||
data = buffer.read(ready_bytes)
|
data = buffer.read(ready_bytes)
|
||||||
buffer_read_len += len(data)
|
buffer_read_len += len(data)
|
||||||
response_data.append(data)
|
response_data.append(data)
|
||||||
|
|
||||||
|
if SLOW_TEST_MARKER in data:
|
||||||
|
BUFFER_TEST_TARGET = BUFFER_TEST_TARGET_SLOW
|
||||||
|
|
||||||
if data == "Hi there".encode("utf-8"):
|
if data == "Hi there".encode("utf-8"):
|
||||||
RNS.log("Sending response")
|
RNS.log("Sending response")
|
||||||
for data in response_data:
|
buffer.write(b"".join(response_data) + " back at you".encode("utf-8"))
|
||||||
buffer.write(data + " back at you".encode("utf-8"))
|
buffer.flush()
|
||||||
buffer.flush()
|
response_data.clear()
|
||||||
buffer_read_len = 0
|
buffer_read_len = 0
|
||||||
|
|
||||||
if buffer_read_len == BUFFER_TEST_TARGET:
|
if buffer_read_len == BUFFER_TEST_TARGET:
|
||||||
RNS.log("Sending response")
|
RNS.log("Sending response")
|
||||||
for data in response_data:
|
buffer.write(b"".join(response_data) + " back at you".encode("utf-8"))
|
||||||
buffer.write(data + " back at you".encode("utf-8"))
|
buffer.flush()
|
||||||
buffer.flush()
|
response_data.clear()
|
||||||
buffer_read_len = 0
|
buffer_read_len = 0
|
||||||
|
|
||||||
buffer = RNS.Buffer.create_bidirectional_buffer(0, 0, channel, handle_buffer)
|
buffer = RNS.Buffer.create_bidirectional_buffer(0, 0, channel, handle_buffer)
|
||||||
|
|
||||||
m_rns = RNS.Reticulum("./tests/rnsconfig", logdest=RNS.LOG_FILE, loglevel=RNS.LOG_EXTREME)
|
m_rns = RNS.Reticulum("./tests/rnsconfig", logdest=RNS.LOG_FILE)
|
||||||
id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0]))
|
id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0]))
|
||||||
d1 = RNS.Destination(id1, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "link", "establish")
|
d1 = RNS.Destination(id1, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "link", "establish")
|
||||||
d1.set_proof_strategy(RNS.Destination.PROVE_ALL)
|
d1.set_proof_strategy(RNS.Destination.PROVE_ALL)
|
||||||
|
|||||||
Reference in new issue
Block a user