Compare commits

...
596 Commits
Author SHA1 Message Date
Mark Qvist 0dbc9e90a3 Prepare release 2026-09-11 16:59:21 +02:00
Mark Qvist 9199cc9e4b Updated changelog 2026-09-11 16:57:52 +02:00
Mark Qvist 7785fd277a Updated version 2026-09-11 16:22:24 +02:00
Mark Qvist 851c18bc27 Improved RNode BLE reconnect reliability 2026-09-11 16:18:24 +02:00
Mark Qvist 996d822393 Fixed RNode BLE re-connection deadlock on desktop. Cleanup. 2026-09-11 12:49:05 +02:00
Mark Qvist 0c97853554 Fix RNode BLE device address acquisition on windows, by Nickie Deuxyeux 2026-09-11 11:49:24 +02:00
Mark Qvist fae64abf05 Prepare release 2026-09-10 22:00:14 +02:00
Mark Qvist 7330c20c6d Updated changelog 2026-09-10 21:58:03 +02:00
Mark Qvist e7a7c48c0a Added importable webp media file conversion helper 2026-09-10 19:37:24 +02:00
Mark Qvist f231fdcb4d Added immediate permissions change activation for rngit perms 2026-09-10 15:35:48 +02:00
Mark Qvist 87823c091f Cleanup 2026-09-10 13:48:59 +02:00
Mark Qvist 36a62e7b1a Cleanup, align with existing pattern of minimal information disclosure on insufficient permissions 2026-09-10 11:31:18 +02:00
Mark Qvist 859dc81805 Cleanup, in-method atomicity of group and repository name derivation to ensure no discrepancies between request data and method invocation parameters 2026-09-10 11:28:24 +02:00
Henri Bergius 409380a458 Allow admins to activate and complete work docs 2026-09-06 20:57:36 -11:00
Henri Bergius b0933d5c6f activate should work also with proposed work documents 2026-09-06 20:50:19 -11:00
Mark Qvist 0bb41bf948 Updated version 2026-09-06 17:39:53 +02:00
Mark Qvist 27910f25a1 Added rngit media conversion 2026-09-06 17:39:07 +02:00
Mark Qvist 602d52f178 Don't auto-compress media responses 2026-09-06 16:27:21 +02:00
Mark Qvist 7396e3994e Basic rngit media handling 2026-09-06 15:55:34 +02:00
Mark Qvist 8a82a50fc9 Updated readme 2026-09-06 15:37:36 +02:00
Mark Qvist 5c1141d1ce Updated readme 2026-09-06 15:34:34 +02:00
Mark Qvist 6b6dd73bc8 Updated readme 2026-09-06 15:20:45 +02:00
Mark Qvist 1a7e9e31a1 Fixed typo 2026-09-06 14:55:50 +02:00
Mark Qvist 2f29b56e96 Adjusted logging 2026-09-04 11:41:27 +02:00
Mark Qvist 3bc149e3d5 Added no_ident template support to rngit 2026-09-01 17:05:28 +02:00
Mark Qvist eb8414bee9 Killed a couple of allocs, canonical HDLC frame method 2026-09-01 14:45:54 +02:00
Mark Qvist ea98db4f53 Prepare release 2026-08-29 04:16:13 +02:00
Mark Qvist ad3c06636b Adjusted logging 2026-08-29 04:10:50 +02:00
Mark Qvist 9ce4502961 Updated changelog 2026-08-29 01:36:31 +02:00
Mark Qvist a3cd84111f Updated default config with null_ident blocking example 2026-08-29 01:31:05 +02:00
Mark Qvist d5b2fc5609 Updated changelog 2026-08-29 00:16:42 +02:00
Mark Qvist 83a30b187a Tuned dataplane control defaults 2026-08-28 23:57:31 +02:00
Mark Qvist 943771a3f9 Updated version 2026-08-28 23:41:20 +02:00
Mark Qvist 5b4117dadc Skip local shared instance interfaces in ingress/egress control 2026-08-28 23:41:00 +02:00
Mark Qvist 6bc0481cdf Always remember to flush 2026-08-28 23:33:32 +02:00
Mark Qvist 4eebf0b685 Guard empty keepalive frames 2026-08-28 21:47:24 +02:00
Mark Qvist 149e415109 Prepare release 2026-08-28 16:03:16 +02:00
Mark Qvist 53ed9c1ed3 Updated version 2026-08-28 15:28:48 +02:00
Mark Qvist ccc5468bcc Updated changelog 2026-08-28 15:21:02 +02:00
Mark Qvist c1d7c12b52 Fixed stream-based resource initialized transfer failing when total sized happened to not fall withing MAX_EFFICIENT_SIZE 2026-08-28 14:43:39 +02:00
Mark Qvist 9878b18377 Added transmit buffer, TX drops and stalled status output to rnstatus 2026-08-28 13:44:14 +02:00
Mark Qvist 6e8c976421 Worker spawn prep 2026-08-28 12:44:59 +02:00
Mark Qvist b28f5ebf7a Allow inbound queue utilization in drainer benchmarks 2026-08-28 11:11:42 +02:00
Mark Qvist 77c8256a1a Fixed invalid prefix stripping in rngit page server 2026-08-28 01:50:46 +02:00
Mark Qvist dc9cf0c2f4 Updated setup.py 2026-08-28 00:09:16 +02:00
Mark Qvist fa07c8c87c Updated setup.py 2026-08-27 23:56:19 +02:00
Mark Qvist b7fe01237d Updated setup.py 2026-08-27 23:38:29 +02:00
Mark Qvist 3543dc9802 Load module compilation status from buildinfo if available 2026-08-27 23:37:43 +02:00
Mark Qvist 5b04a88026 Updated makefile 2026-08-27 23:36:34 +02:00
Mark Qvist 5fdd661081 Updated makefile 2026-08-27 22:53:15 +02:00
Mark Qvist ae0191578f Updated Cython dev shim 2026-08-27 22:37:51 +02:00
Mark Qvist e714c559cc Updated tests init 2026-08-27 22:17:38 +02:00
Mark Qvist 75cbc73f64 Removed dead Python 2 code from umsgpack 2026-08-27 21:05:27 +02:00
Mark Qvist d32ba8c1a1 Fixed inconsistency against advertised return type 2026-08-27 21:04:40 +02:00
Mark Qvist ff3a72209e Avoid rebind of exception reference 2026-08-27 18:32:41 +02:00
Mark Qvist 803b548951 Allow loading compiled modules 2026-08-27 14:56:47 +02:00
Mark Qvist 67a45ac5e9 Fixed nav init order 2026-08-27 14:55:20 +02:00
Mark Qvist e71c01959f Fixed stray non-imported variable 2026-08-27 14:49:32 +02:00
Mark Qvist 0a1b9453b2 Fixed non-epoll backend keepalive 2026-08-27 14:47:05 +02:00
Mark Qvist 79cad39e78 Fixed missing import 2026-08-27 14:43:21 +02:00
Mark Qvist de0dac695b Fixed missing exception reference 2026-08-27 13:12:53 +02:00
Mark Qvist 281c47f3e0 Fixed invalid reference in exception description 2026-08-27 13:12:04 +02:00
Mark Qvist 99c428a9f5 Added dataplane egress control 2026-08-27 02:22:55 +02:00
Mark Qvist cb9071b478 Added HWM limit option to TransmitBuffer 2026-08-27 01:56:43 +02:00
Mark Qvist 10848b7cff Added egress control HWM limiter test 2026-08-27 01:55:28 +02:00
Mark Qvist 89e73db94a Wired coalescing transmit buffer and optimized HDLC deframer into Backbone and Local interfaces 2026-08-26 22:18:37 +02:00
Mark Qvist 0ec84c7491 Added coalescing transmit buffer 2026-08-26 21:58:51 +02:00
Mark Qvist ac9130f01f Added coalesced transmit test 2026-08-26 21:38:15 +02:00
Mark Qvist 54a919f045 Added optimized HDLC implementation 2026-08-26 20:59:38 +02:00
Mark Qvist bafc09d3a6 Cleanup 2026-08-26 14:26:34 +02:00
Mark Qvist 419956bada Over-optimization is the root of all evil 2026-08-26 13:25:14 +02:00
Mark Qvist 1a16fdb727 Fixed inbound queue high-water mark initialization order 2026-08-26 01:05:01 +02:00
Mark Qvist 3b7cfc0666 Cleanup 2026-08-26 00:15:44 +02:00
Mark Qvist de76b8939f Added dataplane ingress control 2026-08-25 23:30:59 +02:00
Mark Qvist d80245b62c Traffic class and violation handling 2026-08-25 14:02:08 +02:00
Mark Qvist dcbc7638d0 Fixed RSSI/SNR reporting regression 2026-08-25 13:22:46 +02:00
Mark Qvist 0536b972d7 Tuned QUEUED_ANNOUNCES. Logging. 2026-08-25 12:08:43 +02:00
Mark Qvist 47add6381d Increase queues for throughput tests 2026-08-25 11:14:38 +02:00
Mark Qvist be2ba7c2f3 Tuned auto MTU configurration 2026-08-25 11:08:01 +02:00
Mark Qvist dd204e11ce Added 32k throughput run 2026-08-25 11:07:38 +02:00
Mark Qvist be4ee32908 Tuned queuelen defaults 2026-08-25 10:58:08 +02:00
Mark Qvist 9f66b5a6a3 Merge branch 'optimize' 2026-08-25 02:51:54 +02:00
Mark Qvist d38a8de571 Fixed f-strings for old snakes 2026-08-25 02:18:23 +02:00
Mark Qvist dea0124c57 Reduced lock acquisition 2026-08-25 02:06:34 +02:00
Mark Qvist aba8d606dd Cleanup 2026-08-25 01:52:53 +02:00
Mark Qvist 8221f82dc0 Cleanup 2026-08-25 01:52:05 +02:00
Mark Qvist 38e9d1cdd4 Cleanup 2026-08-25 01:45:34 +02:00
Mark Qvist 17e980ff79 Cleanup 2026-08-25 01:44:50 +02:00
Mark Qvist f111709902 Updated througput benchmarker 2026-08-25 01:41:31 +02:00
Mark Qvist 2d2167140d FP cache experiment 2026-08-25 01:41:02 +02:00
Mark Qvist d044db2931 Cache announce signature validation 2026-08-24 22:12:04 +02:00
Mark Qvist 516cb106c1 Updated througput benchmarker 2026-08-24 21:54:11 +02:00
Mark Qvist 7e197542e5 Updated througput bench 2026-08-24 21:54:11 +02:00
Mark Qvist 77f7632584 Avoid extra epoll modifies when EPOLLOUT already set 2026-08-24 21:54:11 +02:00
Mark Qvist 5e013464da Added throughput benchmarker 2026-08-24 21:54:11 +02:00
Mark Qvist b9278ce352 Added throughput benchmarker 2026-08-24 20:42:57 +02:00
Mark Qvist d81421dad3 Avoid additional packet hashing under lock in inbound 2026-08-24 17:58:29 +02:00
Mark Qvist 629e4fde2d Added hash map lookups for pending and active links 2026-08-24 17:45:29 +02:00
Mark Qvist 7311dc8544 Reduced path table lock acquisitions in inbound processing 2026-08-24 17:03:48 +02:00
Mark Qvist 0e070aacf6 Ah well, of course. 2026-08-24 11:29:01 +02:00
Mark Qvist 39899651ee Merge adjustments 2026-08-24 10:56:26 +02:00
Mark Qvist 1034d78828 Merge adjustments 2026-08-24 10:52:47 +02:00
Mark Qvist 9c2f424aaa Merge branch 'live_profiling' into live_profiler_merge 2026-08-24 10:31:13 +02:00
K8 dca5b9639e Limit total profiler captures per tag, not per thread; handle reentrant profilers; make stats time windows be non-overlapping. 2026-08-23 22:39:32 -06:00
K8 40281f91da Decorator for profiling functions. 2026-08-23 21:53:33 -06:00
K8 cf5d6a796e Rework profilers for running indefinitely. 2026-08-23 21:53:33 -06:00
K8 9302415f9e Add live profiling results output to rnstatus. 2026-08-23 21:53:33 -06:00
K8 9da6664976 Move log writing to a dedicated thread. 2026-08-23 21:53:33 -06:00
K8 1694a17a75 Full and configurable logfile rotation. 2026-08-23 21:53:33 -06:00
Mark Qvist 3fdfe93ec7 Don't loop on attached interface packets 2026-08-24 01:26:24 +02:00
Mark Qvist a9538e9fd1 Loglevel 2026-08-24 00:53:35 +02:00
Mark Qvist 956d688e10 Check before cancel incoming 2026-08-24 00:14:54 +02:00
Mark Qvist 1c83e732ad Use optimized IFAC handlers 2026-08-23 23:54:45 +02:00
Mark Qvist 5da0870e2a Optimized HKDF 2026-08-23 23:54:17 +02:00
Mark Qvist 171868c6cb Added IFAC and HKDF tests to test runner 2026-08-23 23:49:59 +02:00
Mark Qvist cfddb9abe6 Added HKDF tests 2026-08-23 23:48:48 +02:00
Mark Qvist 929aba0282 Added IFAC tests 2026-08-23 23:47:34 +02:00
Mark Qvist 7347034f9a Optimized outbound IFAC handling 2026-08-23 22:27:53 +02:00
Mark Qvist aef9e5b416 Extract outbound IFAC handling 2026-08-23 22:05:36 +02:00
Mark Qvist e806ae5837 Optimized inbound IFAC handling 2026-08-23 21:57:22 +02:00
Mark Qvist 602085a1cd Extract inbound IFAC handler 2026-08-23 20:11:29 +02:00
Mark Qvist 84597f3186 Added MTU output to rnstatus 2026-08-23 18:01:24 +02:00
Mark Qvist 88c629e3ad Logging and MTU adjustments 2026-08-23 18:01:13 +02:00
Mark Qvist 2058596dd1 Check before cancel outgoing 2026-08-23 15:32:04 +02:00
Mark Qvist b123a756b0 Added transport implementation name and version to discovery information requirements 2026-08-23 11:56:27 +02:00
Mark Qvist bfab2964b6 Fixed rnstatus including not-yet-blocked IPs in blocked IP list output 2026-08-23 11:30:43 +02:00
Mark Qvist 1bad7f5807 Remove from previous hashlist under transport edge case handling 2026-08-23 11:14:47 +02:00
Mark Qvist 26e3ca4f2b Added shared medium hints to interfaces 2026-08-23 10:46:21 +02:00
Mark Qvist d25ea38c84 Added PPS stats to rnstatus. Don't count local shared instance in traffic totals. 2026-08-22 22:41:03 +02:00
Mark Qvist e32d4df754 Updated docs 2026-08-22 14:54:40 +02:00
Mark Qvist 561e2f23e1 Updated changelog 2026-08-22 14:51:49 +02:00
Mark Qvist b397870c97 Log levels 2026-08-22 13:18:01 +02:00
Mark Qvist 6f6751d6b6 Fixed PR egress limiter not preemptively considering potential outbound, and added late egress check to avoid state race under high incoming PR load 2026-08-22 12:23:37 +02:00
Mark Qvist 2aed542e61 Get path_entry directly in _outbound 2026-08-22 11:36:41 +02:00
Mark Qvist 091e021d0e Early return on excessive hop count packets 2026-08-22 11:09:39 +02:00
Mark Qvist fc69f323a8 Cleanup 2026-08-22 01:18:01 +02:00
Mark Qvist 6b2c5bcf0b Don't reprocess IFAC for held announces 2026-08-22 00:18:48 +02:00
Mark Qvist 3885d23293 Added protocol violations 2026-08-21 23:51:52 +02:00
Mark Qvist b1aa527861 Track in-flight path requests separately 2026-08-21 23:16:20 +02:00
Mark Qvist 4c69b376b2 Added adaptive timeouts to utilities, by Zenith 2026-08-21 22:20:00 +02:00
Mark Qvist 2b1b9589f1 Added medium bitrate based timeout calculation helpers and RPC functions and added dynamic timeout calculation to rngit, by Zenith 2026-08-21 22:16:10 +02:00
Mark Qvist 378840a6bf Added total announce/pr count stats per interface 2026-08-21 20:59:32 +02:00
Mark Qvist 7b8923b61f Added protocol violations 2026-08-21 20:35:52 +02:00
Mark Qvist b3ef214e72 Added total announce/pr frequency stats 2026-08-21 18:25:59 +02:00
Mark Qvist cab513fa31 Logging 2026-08-21 18:08:35 +02:00
Mark Qvist 60eb0509f2 Signal blackholed status in validate_announce 2026-08-21 17:40:12 +02:00
Mark Qvist 42f6d64b9c Implemented per-interface protocol violation tracking 2026-08-21 16:48:05 +02:00
Mark Qvist 6ba7cc8cb4 Added data flow speeds to rnstatus 2026-08-21 13:37:09 +02:00
Mark Qvist 880db0a7b7 Added active links stat to rnstatus 2026-08-21 13:23:30 +02:00
Mark Qvist 5f2f4438d0 Added detailed announce and path request traffic stats 2026-08-21 13:06:48 +02:00
Mark Qvist 7488336985 Use test runner config loglevel setting 2026-08-21 11:32:53 +02:00
Mark Qvist 614e7bd834 Improved path request handling, batch same-destination PRs when existing in-flight path request exists 2026-08-21 00:54:08 +02:00
Mark Qvist 386ef1f370 Transport jobs optimizations 2026-08-20 22:08:06 +02:00
Mark Qvist 4ab0755d0a Changed PR ingress accounting point 2026-08-20 17:16:01 +02:00
Mark Qvist d478e380c9 Use sets for discovery pr tags 2026-08-20 17:08:22 +02:00
Mark Qvist 05e6717d21 Fixed rngit file resource operations failing on Windows 2026-08-20 10:14:49 +02:00
Mark Qvist 9ae3db169e Fixed medium_timeout init 2026-08-20 08:38:09 +02:00
Mark Qvist 68cda4a855 Added discovery_lxmf_address to documentation 2026-08-19 21:15:30 +02:00
Mark Qvist 4b914fb9a4 Include extra timeout for discovery PRs when slow interfaces are online, thanks to Zenith 2026-08-19 21:07:50 +02:00
Mark Qvist bde5611a0d Fixed missing interface.bitrate validation in extra link proof timeout calculation, thanks to Zenith 2026-08-19 20:15:17 +02:00
Mark Qvist 49073fcca5 Fixed invalid interface basis for extra link proof timeout calculation, thanks to Zenith 2026-08-19 20:13:32 +02:00
Mark Qvist 6738db5437 Cleaned up deprecated logic block indent in relation to inbound processing refactor 2026-08-19 20:08:34 +02:00
Mark Qvist 49918c7e1d Updated docs 2026-08-19 19:57:17 +02:00
Mark Qvist 954567c581 Allow disabling link MTU discovery 2026-08-19 18:06:17 +02:00
Mark Qvist 77a1bb9b19 Consistency 2026-08-19 18:03:23 +02:00
Mark Qvist df80181006 Utilize full link MDU in RawChannelWriter 2026-08-19 17:57:14 +02:00
Mark Qvist 0c0034f1ae Tuned burst stats throttle 2026-08-19 16:44:29 +02:00
Mark Qvist 2e9443ffe2 Fixed typo 2026-08-19 15:49:09 +02:00
JRG 65222e0de8 Resource: align indexes in receive_part with request_next 2026-08-19 15:44:53 +02:00
Mark Qvist db7daa4d94 Method naming 2026-08-19 14:22:36 +02:00
JRG c95bb551ab Transport: handle exceptions in inbound() 2026-08-19 14:19:49 +02:00
Mark Qvist acecc1f490 Error logging 2026-08-19 13:39:53 +02:00
JRG 39e3854dac Link: reset watchdog if exception happens in receive 2026-08-19 13:38:18 +02:00
JRG 6cd5be18ec Transport: slice discovery_pr_tags to the end
Keep the last element.
2026-08-19 13:33:40 +02:00
JRG 0e2041c837 BackboneInterface: update timestamps in ic checks 2026-08-19 13:23:16 +02:00
JRG 338173802d Transport: fix destination_hash check in pending_discovery_prs 2026-08-19 13:07:55 +02:00
Mark Qvist 40a862acbd Break loop on existing entry in announce queue 2026-08-19 13:02:28 +02:00
JRG d825e39379 Transport: fix updating announce_queue 2026-08-19 12:59:41 +02:00
JRG 731a63b01b Transport: update interface_hashes_updated_at timestamp 2026-08-19 12:54:49 +02:00
JRG 7c912d0936 rnstatus: use proper stats 2026-08-19 12:53:15 +02:00
Mark Qvist 503bd6c87b Improved PR ingress limiter 2026-08-18 13:17:34 +02:00
Mark Qvist 1a70bd3cd1 Added queue drop stats 2026-08-18 12:34:18 +02:00
Mark Qvist 636012bbe5 Cleanup 2026-08-18 12:17:14 +02:00
Mark Qvist e1b7bc316c Fixed typo 2026-08-18 12:02:44 +02:00
Mark Qvist 1c488947bd Fixed typo 2026-08-18 12:00:42 +02:00
Mark Qvist 1809461a07 Early filtering note 2026-08-18 11:59:51 +02:00
Mark Qvist 01a78bee2a Fixed typo 2026-08-18 11:55:58 +02:00
Mark Qvist 8c08b9ce09 Added queue config to documentation 2026-08-18 11:45:34 +02:00
Mark Qvist efb8c8500d Made queue lengths configurable 2026-08-18 11:45:20 +02:00
Mark Qvist f366dd9cf2 Cleanup 2026-08-18 10:34:41 +02:00
Mark Qvist 0d15cfc134 Fixed f-string for old snakes 2026-08-17 21:52:53 +02:00
Mark Qvist e81532f541 Updated version 2026-08-17 21:40:57 +02:00
Mark Qvist d41afd2d81 Updated rnstatus docs 2026-08-17 21:40:14 +02:00
Mark Qvist 7a1291d530 Added inbound queue pressure statistics to rnstatus 2026-08-17 20:52:02 +02:00
Mark Qvist fc0f84f23e Added prioritized inbound traffic processing 2026-08-17 20:51:46 +02:00
Mark Qvist c2eac12ff5 Added burst count stat to interfaces 2026-08-17 20:47:30 +02:00
Mark Qvist e46496032c Contention comments 2026-08-17 01:37:22 +02:00
JRG 2d7f858a54 Transport: fix deadlock on receipts_lock when callback sends message
Deadlock on receipts_lock:

    inbound (Transport.py) <- holds receipts_lock
    validate_proof_packet (Packet.py)
    validate_link_proof (Packet.py)
    delivery_callback <- application callback, sends packet
    send (Packet.py)
    outbound (Transport.py)
    packet_sent (Transport.py) <- blocks on receipts_lock
2026-08-17 01:13:26 +02:00
Mark Qvist 9ebcb55cb5 Cleanup 2026-08-17 01:07:59 +02:00
JRG bbc1a0d06b BackboneInterface: fix epoll RX starvation
Speedtest.py fails when running on a shared instance with data_cap = 2*1024*1024*1024

Request both EPOLLIN | EPOLLOUT in tx_ready() and process both events in __job()

Not included:
Speedtest.py: change link.status == RNS.Link.ACTIVE to link.status != RNS.Link.CLOSED
2026-08-17 01:06:13 +02:00
Mark Qvist 31298e5eda Fixed speedtest TX abort on link stale status 2026-08-17 01:00:29 +02:00
JRG e31c570d2b Transport: fix rebind of expires variable 2026-08-17 00:51:33 +02:00
JRG 9b4947ef46 Destination: clean ratchets to retained_ratchets 2026-08-17 00:43:40 +02:00
JRG 0d9bf5b862 rncp: fix variable name 2026-08-17 00:41:14 +02:00
JRG c6f9ef1047 RNodeInterface: fix stale ble_device 2026-08-17 00:39:25 +02:00
JRG 90ac62620d Transport: fix pending_links items removal while being iterated 2026-08-17 00:38:28 +02:00
JRG 0c41027765 Resource: avoid rebind of data variable 2026-08-17 00:36:43 +02:00
JRG 691211bf0d BackboneInterface: remove unused poll 2026-08-17 00:34:16 +02:00
JRG 0ec51cce67 Link: fix constant name 2026-08-17 00:31:59 +02:00
JRG 55755c6b3c Transport: fix check for r_stat_snr 2026-08-17 00:30:38 +02:00
JRG 72ba27d63c Link: fix resource cancellation
Resource.cancel() -> Link.cancel_{incoming/outgoing}_resource()
changes the iterated list and every second resource is skipped.

Fix: iterate over copies of the two lists
2026-08-17 00:26:19 +02:00
JRG 6c1182c2c2 Packet: reticulum variable is not defined 2026-08-17 00:24:16 +02:00
Mark Qvist ce81b339dc This will have *zero* effect on any actual, real-world or otherwise just tangentially relevant physically viable situation, but at this point I am fed up with receiving a daily dose of overly verbose machine soup from yet another random LLM-bro who's playing security researcher, so there you have it, now ffs leave me in peace to do some *actual* work, and keep your tech-fantasy wanking to yourself, thank you very much. 2026-08-16 21:34:34 +02:00
Mark Qvist 3db15dae44 Updated identity test 2026-08-16 21:28:03 +02:00
Mark Qvist 38a73f9508 Added ability to include operator LXMF address in interface discovery info 2026-08-16 00:29:14 +02:00
Mark Qvist ebd9b862e9 Fixed rnodeconf config summary print 2026-08-14 11:21:04 +02:00
Mark Qvist 4fc8e03d65 Added blocked IP listing to rnstatus 2026-07-28 15:36:12 +02:00
Mark Qvist b48b96e616 Prepare release 2026-07-26 17:59:12 +02:00
Mark Qvist 529a9fd460 Cleaned up dead imports. Improved logging. 2026-07-26 17:41:27 +02:00
Mark Qvist 64fee86ebc Cleanup 2026-07-26 14:29:47 +02:00
Mark Qvist e3f1a5e7cd Updated version 2026-07-25 21:01:37 +02:00
Mark Qvist 0416c41956 Faster blackhole filtering for discovered interfaces on mobile / over RPC 2026-07-25 21:00:10 +02:00
Mark Qvist 4760103aa6 Ensure interface is online at time of recursive PR emission 2026-07-25 19:22:58 +02:00
Mark Qvist b2188ce9a7 Adjusted gravity update loglevel 2026-07-24 21:23:42 +02:00
Mark Qvist 4631d78bea Adjusted re-balance loglevel 2026-07-24 20:55:44 +02:00
Mark Qvist 0d16e2305e Updated documentation 2026-07-24 20:44:55 +02:00
Mark Qvist e5d37355b8 Updated changelog 2026-07-24 20:10:33 +02:00
Mark Qvist 224124aac7 Updated version 2026-07-24 19:47:53 +02:00
Mark Qvist e29b839429 Ensure historical interface discoveries are cleaned according to blackholed identities 2026-07-24 19:47:44 +02:00
Mark Qvist 12c21d4e25 Cleanup 2026-07-24 15:33:19 +02:00
Mark Qvist 6a761a768c Added max_response_size parameter to Link request API 2026-07-24 15:10:03 +02:00
Mark Qvist 1ecf845cea Added set_max_request_size to Destination API 2026-07-24 14:06:27 +02:00
Mark Qvist a29a08716f Cleaned up channel class logging and deprecated code 2026-07-24 13:12:29 +02:00
Mark Qvist e46b012e95 Allow loglevels above LOG_DEBUG, cleaned up logging 2026-07-24 12:23:12 +02:00
Mark Qvist 0f33d71966 Updated documentation 2026-07-24 02:44:09 +02:00
Mark Qvist 00d57a22ee Cleaned up I2P interface and control process code, fixed various i2plib bugs 2026-07-24 02:30:34 +02:00
Mark Qvist c25b56db9a Fixed discovered interfaces getting connected as BackboneInterface clients instead of TCPClientInterface on darwin 2026-07-24 02:29:51 +02:00
Mark Qvist a4b6129875 Fixed i2p tunnel handler futures getting garbage collected, thanks to **welo** 2026-07-24 02:28:26 +02:00
Mark Qvist bce5f859da Logging consistency 2026-07-23 19:05:45 +02:00
Mark Qvist 93526c17f5 Added rebalanced time to links 2026-07-23 17:52:45 +02:00
Mark Qvist 6d4523c27e Added rebalanced time to links 2026-07-23 17:14:48 +02:00
Mark Qvist c4297d318f Cleanup 2026-07-23 14:43:51 +02:00
Mark Qvist 90e1dbb912 Link request path re-balancing 2026-07-23 14:37:13 +02:00
Mark Qvist cbf50460c2 Cleaned up logging 2026-07-23 14:31:19 +02:00
Mark Qvist 889c5ff55f Added sort by gravity to rnstatus 2026-07-23 12:57:29 +02:00
Mark Qvist 566aa68fc0 Added gravity, default_gravity and autoconnect_interface_gravity options and updated documentation 2026-07-23 12:52:35 +02:00
Mark Qvist 3ca71527d9 Propagate gravity to spawned interfaces 2026-07-23 12:37:59 +02:00
Mark Qvist 5577e781fb Basic gravity processing for announces 2026-07-22 23:19:20 +02:00
Mark Qvist 7611fca6bf Fixed loglevel 8 not being respected 2026-07-22 23:11:38 +02:00
Mark Qvist c10c465c02 Interface gravity base property and configuration 2026-07-22 20:01:50 +02:00
Mark Qvist 9bc73819f6 Updated documentation 2026-07-22 19:50:49 +02:00
Mark Qvist bebf211b01 Added autoconnect_discovered_mode and autoconnect_announces_to_internal options 2026-07-22 19:45:21 +02:00
Mark Qvist 1af173e8a5 Added announces_to_internal interface option 2026-07-22 19:01:34 +02:00
Mark Qvist b051e76d00 Allow boundary -> boundary and boundary -> gateway path requests 2026-07-22 17:53:04 +02:00
Mark Qvist 4838875691 Fixed ingress control burst active flag deadlocking until new announces arrived under burst timing patterns 2026-07-22 17:51:23 +02:00
Mark Qvist 122f17fad6 Prepare release 2026-07-20 19:11:35 +02:00
Mark Qvist be36abd857 Increased default discovery stamp value to 16 2026-07-20 17:24:51 +02:00
Mark Qvist fa4d4c6716 Implemented valid discovery announce caching and sequential validation lock to reduce processing load on CPU-constrained systems 2026-07-20 17:21:41 +02:00
Mark Qvist a5728be421 Fixed missing None-check in BackboneInterface fast-flap detection. Fixed invalid exception log handler. Reduced logging noise. 2026-07-20 17:21:03 +02:00
Mark Qvist 032b1aa3b2 Updated version 2026-07-20 16:16:23 +02:00
Mark Qvist fb7479a6f6 Fixed race condition in link watchdog timing 2026-07-20 16:16:07 +02:00
Mark Qvist f81b267509 Added blocked IPs list to ifstats 2026-07-20 16:14:07 +02:00
Mark Qvist 6527423526 Run known destinations cleaning at background priority to avoid lock contention on CPU-constrained systems 2026-07-20 14:55:09 +02:00
Mark Qvist d8bc20d4cb Cleanup 2026-07-20 14:18:23 +02:00
Mark Qvist 6c6238ce29 Deprecated known destination on-disk recombination on background data persist to alleviate lock contention on CPU-constrained systems 2026-07-20 14:16:59 +02:00
Mark Qvist cbba3502b7 Optimized transport data persistence to avoid CPU spikes on low-powered systems 2026-07-20 13:55:53 +02:00
Mark Qvist 2b79db03c0 Added invalid discovery stamp cache 2026-07-20 12:57:49 +02:00
Mark Qvist 2c9edc43f1 Improved backbone interface logging 2026-07-20 12:52:40 +02:00
Mark Qvist ef9244f79f Store interface hashes instead of recomputing every time 2026-07-20 11:49:09 +02:00
Mark Qvist 2d811dc398 Updated logging 2026-07-19 21:54:33 +02:00
Mark Qvist e64d815033 Fixed link stale teardown due to missing keepalive from initiator side when destination continously sends packets 2026-07-19 21:37:59 +02:00
Mark Qvist bfade97051 Prepare release 2026-07-19 02:30:28 +02:00
Mark Qvist 3c4ef622cc Updated changelog 2026-07-19 02:29:09 +02:00
Mark Qvist 3898d63689 Block fast flapping configuration 2026-07-19 02:10:52 +02:00
Mark Qvist ec8d43a548 Updated rnsh config args to work similarly to other RNS utils 2026-07-19 00:57:27 +02:00
Mark Qvist 5081255317 Updated logging 2026-07-18 23:03:35 +02:00
Mark Qvist 13a538168f Cleanup 2026-07-18 21:30:46 +02:00
Mark Qvist a5ed0a4321 Improved HDLC handling 2026-07-18 21:26:57 +02:00
Mark Qvist d93f9798ae Cleanup 2026-07-18 19:23:02 +02:00
Mark Qvist 88833f170b Updated documentation 2026-07-18 16:46:04 +02:00
Mark Qvist cd6911ed53 Implemented automated fast-flapping client blocking on BackboneInterface 2026-07-18 16:45:42 +02:00
Mark Qvist b95c51b96e Added LOG_PATHING loglevel 2026-07-18 15:07:06 +02:00
Mark Qvist 3a36c367fe Improved resource handling 2026-07-18 02:46:06 +02:00
Mark Qvist cf6010da59 Enable discovery for internal-mode interfaces 2026-07-17 11:43:14 +02:00
Mark Qvist bb2897445f Added RESOURCE_RCL signal on resource receiver cancel. Improved link identify and resource safeguards. 2026-07-16 15:18:08 +02:00
Mark Qvist 406b141370 Updated version 2026-07-14 20:42:42 +02:00
Mark Qvist 00b2f81a82 Added ability to resolve discoverable interface location from external executable 2026-07-14 20:41:28 +02:00
Mark Qvist 9adf045a31 Added discovery location script info to docs 2026-07-14 20:40:45 +02:00
Mark Qvist de0f399a16 Prepare release 2026-07-10 12:42:56 +02:00
Mark Qvist dca2a92829 Prepare release 2026-07-10 12:40:39 +02:00
Mark Qvist b1b3ff7143 Updated version 2026-07-10 11:47:32 +02:00
Mark Qvist a0f0f31807 Cleanup 2026-07-10 01:15:57 +02:00
Mark Qvist 72db6e0ef2 Ensure link traffic stats consistency 2026-07-06 19:23:45 +02:00
Mark Qvist b70688883a Ensure link hops is available on both initiator and destination 2026-07-06 19:22:41 +02:00
Mark Qvist dd3ddb9d8a Added Weave event type 2026-07-06 19:21:45 +02:00
Mark Qvist 4ba1750c01 Updated changelog 2026-07-03 18:32:34 +02:00
Mark Qvist eacff56fe2 Cleanup 2026-07-03 18:25:44 +02:00
Mark Qvist 8768e163ae Updated changelog 2026-07-03 12:27:01 +02:00
Mark Qvist c0bc19d998 Cleanup 2026-06-27 21:59:34 +02:00
Mark Qvist c99ec922aa Cleanup 2026-06-26 11:59:33 +02:00
Mark Qvist 0a6f76e41b Updated documentation 2026-06-25 21:28:06 +02:00
Mark Qvist 156ce9cd34 Updated readme 2026-06-25 21:17:34 +02:00
Mark Qvist 176092ebf9 Cleanup 2026-06-25 20:57:40 +02:00
Mark Qvist 98817e3f9d Improved announce propagation logic 2026-06-25 19:53:06 +02:00
Mark Qvist 276b7bb92f Updated docs 2026-06-25 17:36:45 +02:00
Mark Qvist d1813e1ff0 Added announces_from_internal interface option 2026-06-25 15:33:48 +02:00
Mark Qvist 5355a9bb20 Updated readme 2026-06-25 15:33:25 +02:00
Mark Qvist 48d17a8616 Fixed typo 2026-06-19 23:55:50 +02:00
Mark Qvist 7e603f9606 Updated documentation 2026-06-19 20:13:16 +02:00
Mark Qvist ac6f0199f5 Updated documentation 2026-06-19 20:13:03 +02:00
Mark Qvist 71f6f721fd Added internal interface mode 2026-06-19 19:27:52 +02:00
Mark Qvist 51b7dc7cd4 Updated version 2026-06-19 10:16:25 +02:00
Mark Qvist 03ddb08248 Added recursive_prs interface option 2026-06-19 10:15:32 +02:00
Mark Qvist 422dc05549 Updated changelog 2026-06-07 15:21:20 +02:00
Mark Qvist 50c0a354c9 Cleanup 2026-06-01 00:34:49 +02:00
Mark Qvist e98487c1cf Prepare release 2026-06-01 00:27:36 +02:00
Mark Qvist 50e03a24e8 Updated version 2026-06-01 00:01:33 +02:00
Mark Qvist 0cc42568c7 Fixed UDP listener replacement deadlocking AutoInterface traffic when fast-roaming between physical interfaces or WiFi APs 2026-05-31 23:54:46 +02:00
Mark Qvist 41790ca707 Added release manifest 2026-05-31 11:39:27 +02:00
Mark Qvist 20b1bfd01e Prepare release 2026-05-29 09:29:40 +02:00
Mark Qvist 1be5e10abe Updated makefile 2026-05-29 09:29:19 +02:00
Mark Qvist 13a9ebed83 Updated version 2026-05-29 09:19:28 +02:00
Mark Qvist aee8c3be0c Fixed missing check for instance type configuration conflict 2026-05-29 09:01:21 +02:00
Mark Qvist ef8ccf67ed Cleaned up superfluous path state call 2026-05-29 08:21:32 +02:00
Mark Qvist 91d531b053 Fixed regression in inbound announce deduplication 2026-05-29 08:19:04 +02:00
Mark Qvist 0de169836e Improved cleanup of stale known destinations 2026-05-29 07:53:29 +02:00
Mark Qvist a2ef978208 Use msgpack for shared instance RPC 2026-05-29 07:30:41 +02:00
Mark Qvist 5b3bb050e7 Fixed typo 2026-05-29 00:22:50 +02:00
Mark Qvist 9b9efe5fac Added mailmap generation tip to git documentation 2026-05-29 00:04:05 +02:00
Mark Qvist 482d5ac4cb Updated docs 2026-05-28 23:36:51 +02:00
Mark Qvist 804a7ddbe1 Prepare release 2026-05-28 23:35:08 +02:00
Mark Qvist 739fdd387e Fixed known destinations persist regression on windows 2026-05-28 23:26:59 +02:00
Mark Qvist f3517d2e4b Prepare release 2026-05-28 17:55:40 +02:00
Mark Qvist c59f1e3dd6 Updated rngit documentation 2026-05-28 17:43:35 +02:00
Mark Qvist 2cf07099e3 Added local verify shorthand option to rngit release 2026-05-28 17:43:02 +02:00
Mark Qvist 0292465666 Added option to configure blackhole update interval 2026-05-28 17:12:21 +02:00
Victor Alexeev b4e15503c1 Added option to log without timestamps 2026-05-28 16:52:39 +02:00
Mark Qvist a5ca1ee41e Updated rngit docs 2026-05-28 02:27:24 +02:00
Mark Qvist f9c786fa28 Updated commit signing docs 2026-05-28 02:22:05 +02:00
Mark Qvist bcf35030bc Show signature status on commit page 2026-05-28 02:09:47 +02:00
Mark Qvist 237eada209 Added tag validation support 2026-05-28 00:17:22 +02:00
Mark Qvist afb984d3d4 Added rngit commit signing section to the manual 2026-05-27 23:42:37 +02:00
Mark Qvist 675a25c90e Added commit signing and validation to rngit 2026-05-27 21:42:31 +02:00
Mark Qvist f6d6314842 Added commit hash to generated release manifests 2026-05-27 15:39:27 +02:00
Mark Qvist 22ab5c29bd Cleanup of deprecated mandatory rsm note field 2026-05-27 13:35:26 +02:00
Mark Qvist 4931c6a54c Updated version 2026-05-26 23:31:26 +02:00
Mark Qvist d3fcc2a38c Extended blackhole functionality to immediately terminate links if remote identifies as a blackholed identity 2026-05-26 12:34:55 +02:00
Mark Qvist e9609b7f25 Only display first line in release lists 2026-05-25 17:36:32 +02:00
Mark Qvist 70cd51f0fa Adjusted logging 2026-05-25 13:48:34 +02:00
Mark Qvist fa7699a37d Improved markdown formatting of the manual 2026-05-23 09:53:38 +02:00
Mark Qvist 2c9b794182 Improved markdown formatting of gettingstartedfast chapter 2026-05-23 09:39:16 +02:00
Mark Qvist eae84ed8ba Improved markdown version of the manual 2026-05-23 09:26:38 +02:00
Mark Qvist 31539c5a0e Improved markdown formatting of understanding reticulum manual chapter 2026-05-23 09:21:56 +02:00
Mark Qvist abca32bca4 Improved markdown formatting of understanding reticulum manual chapter 2026-05-23 09:18:45 +02:00
Mark Qvist 1d7cfe7c20 Prepare release 2026-05-22 23:24:46 +02:00
Mark Qvist a516960e6f Prepare release 2026-05-22 23:23:53 +02:00
Mark Qvist 870bee16b1 Prepare release 2026-05-22 23:21:11 +02:00
Mark Qvist 3814102936 Changelog: Fixed regression in request response transfer size accumulator 2026-05-22 12:23:44 +02:00
Mark Qvist aaadff547d Updated documentation 2026-05-21 21:22:09 +02:00
Mark Qvist f0a3fadcd1 Fixed offline release validation command typo 2026-05-21 21:21:21 +02:00
Mark Qvist 7cbce84cbd Prepare release 2026-05-21 17:50:18 +02:00
Mark Qvist fe334c0d7c Updated changelog 2026-05-21 17:41:27 +02:00
Mark Qvist 33d5a8e2a8 Cleanup 2026-05-21 17:38:29 +02:00
Mark Qvist e80bf471ec Slight robustification 2026-05-21 17:31:20 +02:00
Mark Qvist 7dfdea2395 Raise descriptive error if hashlib.file_digest is not available. 2026-05-21 17:16:31 +02:00
Mark Qvist 74b61aebd2 Updated docs 2026-05-21 17:06:47 +02:00
Mark Qvist ce9071e2d3 Added ability to use wildcards in artifact fetch specifications 2026-05-21 17:06:04 +02:00
Mark Qvist d6cf59dcc8 Fix error message when no specified artifacts were available for fetch 2026-05-21 16:34:34 +02:00
Mark Qvist de61652d37 Updated changelog 2026-05-21 16:31:48 +02:00
Mark Qvist 6181f62d93 Return not found instead of remote error on missing document 2026-05-21 15:31:22 +02:00
Mark Qvist ed66b4873e Updated version 2026-05-21 15:17:33 +02:00
Mark Qvist 26869941a4 Merge branch 'patch_fix_channel_outlet_race' 2026-05-21 15:16:14 +02:00
Mark Qvist ee7b4e7ae5 Consistency 2026-05-21 15:16:09 +02:00
Mark Qvist 7866484453 Merge branch 'fix_kd_iter' 2026-05-21 15:01:37 +02:00
Mark Qvist 817b3b1a12 Consistency 2026-05-21 15:01:17 +02:00
Mark Qvist 17f6968467 Added blackhole methods to API docs 2026-05-21 13:19:06 +02:00
Mark Qvist a96a1d6692 Adjusted timeouts 2026-05-20 01:08:11 +02:00
Mark Qvist c1081fa9a4 Consistency 2026-05-20 01:07:54 +02:00
Mark Qvist dd3104094b Fixed check for existing link at shutdown 2026-05-20 00:32:08 +02:00
Mark Qvist dc68eea313 Fix commit message rendering 2026-05-19 21:35:45 +02:00
Jeremy O'Brien 794e437f6d Channel: prevent sequence holes and ghost envelopes when sending on a dying outlet
RNSChannelOutlet.send() can return a packet that never reached the wire
(link not ACTIVE, no capable interface, etc). The old Channel.send()
queued the envelope in _tx_ring before calling outlet.send(), then
tried to rewind _next_sequence and remove the envelope if the outlet
returned a failed packet. Two problems:

- Between queueing and outlet.send() returning, _tx_ring held an
envelope with packet.raw=None. Any worker thread iterating the
ring (timeout fire, proof callback) crashed in get_packet_id's
packet.get_hash() with a TypeError on None.raw.

- The rewind was only safe for a single-threaded sender: it checked
"is _next_sequence one past mine?" and skipped the rewind otherwise.
Under concurrent senders, the rewind silently failed, leaving a
hole in the on-wire sequence stream. The receiver's contiguous
seqnum rule then stalled the channel permanently with no error.

This fix serializes the reservation-and-transmit pair with a per-channel
_send_lock so the rewind is always correct, and defers queueing until
outlet.send() returns a real packet so _tx_ring never contains a
packet-less envelope. _packet_tx_op() and get_packet_id() now also
defensively skip/return-None for packet-less envelopes.

Also handle the small race where a proof arrives between outlet.send()
registering the receipt and us installing the delivery callback: after
registration, re-read the receipt status and synthesize the
_packet_delivered() call if it's already DELIVERED.
2026-05-19 14:52:59 -04:00
Jeremy O'Brien ebf544d335 rnsh: don't wait forever for rns operations when timeout isn't set 2026-05-19 07:46:50 -04:00
Jeremy O'Brien 939f30fef2 Don't iterate known_destinations directly; it can change during iteration 2026-05-19 07:46:50 -04:00
Mark Qvist 4549bbfdb9 Docs formatting 2026-05-19 11:41:09 +02:00
Mark Qvist 6c989eb38e Prepare release 2026-05-19 01:08:42 +02:00
Mark Qvist 137d73ad0d Updated version 2026-05-19 00:51:12 +02:00
Mark Qvist 58d4162f6d Updated rngit documentation 2026-05-19 00:48:14 +02:00
Mark Qvist 67625395fe Updated logging 2026-05-18 22:48:18 +02:00
Mark Qvist f62512381a Updated rngit documentation 2026-05-18 22:01:55 +02:00
Mark Qvist 888e3102de Added offline RSM release manifest verification 2026-05-18 17:55:10 +02:00
Mark Qvist f83435c697 Updated rngit documentation 2026-05-18 17:13:31 +02:00
Mark Qvist 5243d646f0 Improved known destination persist reliability 2026-05-18 14:57:17 +02:00
Mark Qvist bdb284ce5d Improved page node ref handling in commit links 2026-05-18 14:46:00 +02:00
Mark Qvist 1b34820601 Added ability to fetch new verified releases directly from RSM-embedded release manifest data. Added local release generation and signing with the --local option to rnid. 2026-05-18 13:49:01 +02:00
Mark Qvist 01010dd599 Added version getter to setup.py 2026-05-18 13:46:18 +02:00
Mark Qvist da32709f7c Updated makefile 2026-05-18 13:45:40 +02:00
Mark Qvist cdc6159a15 Added canonical release RSM structure validator to rnid 2026-05-18 13:32:54 +02:00
Mark Qvist eb2f7ae455 Implemented remote HEAD tracking for forks and mirrors in rngit 2026-05-18 12:39:22 +02:00
Mark Qvist a74f1bd89f Save manifest on release fetch 2026-05-18 11:52:46 +02:00
Jeremy O'Brien 603f709139 Don't iterate known_destinations directly; it can change during iteration 2026-05-18 00:10:25 -04:00
Mark Qvist 0dd063a32e Clear previous request progress 2026-05-18 03:37:52 +02:00
Mark Qvist 9885a70a88 Prepare release 2026-05-18 03:32:46 +02:00
Mark Qvist e4a85de089 Actually send manifest and rsgs 2026-05-18 03:31:40 +02:00
Mark Qvist ca0d2dffbe Prepare release 2026-05-18 03:06:16 +02:00
Mark Qvist 511d169c77 Cleanup 2026-05-18 03:03:30 +02:00
Mark Qvist 19bc8ef85c Cleanup 2026-05-18 03:00:52 +02:00
Mark Qvist 1e33d3eebb Updated version 2026-05-18 02:52:30 +02:00
Mark Qvist d18f434583 Implemented rsm-verified release fetching with embedded artifact signatures 2026-05-18 02:51:53 +02:00
Mark Qvist 64749b4d18 Cleanup. Prepared artifact fetch. 2026-05-18 01:24:15 +02:00
Mark Qvist 875d8ef7eb Updated changelog 2026-05-18 01:22:59 +02:00
Mark Qvist 20283f1536 Added automatic signing and release manifest generation to rnid release 2026-05-18 00:44:41 +02:00
Mark Qvist c4af328802 Dropped note meta field requirement from rsg structure 2026-05-18 00:10:22 +02:00
Mark Qvist a2193b9ffd Dropped note meta field requirement from rsg structure 2026-05-18 00:05:29 +02:00
Mark Qvist d2542fd49b Added blocked identities handling and push stats ignore to rngit 2026-05-17 23:26:19 +02:00
Mark Qvist 0333884877 Handle silly links 2026-05-17 23:09:21 +02:00
Mark Qvist 63947ed69a Oops 2026-05-17 23:07:44 +02:00
Mark Qvist d6d18ce29c Fixed micron tags escaping to where they shouldn't go and wreaking havoc on the rest of the pafe. Looking at you table cell truncator. 2026-05-17 23:01:36 +02:00
Mark Qvist 2ef58d8b59 Better table cell truncation method 2026-05-17 22:01:30 +02:00
Mark Qvist 15f2d1635e Added fork and mirror sync time to repo pages 2026-05-17 21:14:26 +02:00
Mark Qvist c83b71f49a Cleanup 2026-05-17 20:45:38 +02:00
Mark Qvist f0824fd71e Added RSM metadata embedding and spec validation to rnid 2026-05-17 20:29:40 +02:00
Mark Qvist 8dde60658f Added validate.py for spec validation 2026-05-17 20:27:16 +02:00
Mark Qvist 9437648ae5 Adjusted logging 2026-05-17 19:06:24 +02:00
Mark Qvist 71b19aca2c Added signed message from file creation to rnid. Added signed message metadata output option to rnid. 2026-05-17 18:29:44 +02:00
Mark Qvist 7d320f8cd5 Fixed missing working identity check on message signing op 2026-05-17 17:27:18 +02:00
Mark Qvist 340d0883a7 Updated docs 2026-05-17 17:24:44 +02:00
Mark Qvist 66096acc29 Added ability to render raw micron in markdown files 2026-05-17 17:22:25 +02:00
Mark Qvist e35100d865 Updated docs 2026-05-17 16:51:20 +02:00
Mark Qvist 128455ef01 Implemented remote permissions management in rngit 2026-05-17 16:49:44 +02:00
Mark Qvist 10156cc90e Updated rngit docs 2026-05-17 15:19:42 +02:00
Mark Qvist 4f5482f2ae Implemented identity and destination aliases in rngit 2026-05-17 15:09:00 +02:00
Mark Qvist 2b9fdae74b Fixed typo 2026-05-17 12:49:53 +02:00
Mark Qvist 7506caa0da Fixed f-string for old snakes 2026-05-17 12:25:21 +02:00
Mark Qvist b1f522277c Prepare release 2026-05-17 00:56:08 +02:00
Mark Qvist af6e0c9ecf Updated changelog 2026-05-17 00:47:15 +02:00
Mark Qvist 176567e3f1 Updated version 2026-05-17 00:39:15 +02:00
Mark Qvist 15cd4268ac Cleanup 2026-05-17 00:38:51 +02:00
Mark Qvist 9307db16c4 Allow disabling mirroring interval 2026-05-17 00:17:12 +02:00
Mark Qvist 0f29ab629a Updated rngit documentation 2026-05-17 00:07:16 +02:00
Mark Qvist b2a4ceb853 Updated default config 2026-05-16 23:37:45 +02:00
Mark Qvist 6c7f1d068b Implemented fork and mirror sync from upstreams 2026-05-16 23:02:45 +02:00
Mark Qvist b76beb602d Added scaffolding for periodic upstream mirror sync and manual fork/mirror sync 2026-05-16 22:06:16 +02:00
Mark Qvist 0c68f6491a Added fork and mirror indications to rngit page node 2026-05-16 21:14:02 +02:00
Mark Qvist 038981474a Added fork and mirroring support to rngit CLI and node 2026-05-16 20:21:01 +02:00
Mark Qvist df0b4a5165 Implemented rngit remote repo create 2026-05-16 17:35:00 +02:00
Mark Qvist db7359f56d Preparation for create, fork and mirror functionality. Refactored and expanded permissions system. Added group .allowed files. Prepared dynamic permissions resolution. Basic functional scaffolding for create/fork/mirror. 2026-05-16 16:16:10 +02:00
Mark Qvist 12e45b6483 Added work document proposals 2026-05-16 02:11:00 +02:00
Mark Qvist ba8fca6f87 Nicer stats page 2026-05-15 23:21:56 +02:00
Mark Qvist 9b99b72f61 Cleanup 2026-05-15 22:15:17 +02:00
Mark Qvist 03cfbc2eb6 Added half-block chart rendering 2026-05-15 22:09:27 +02:00
Mark Qvist c92872a81b Added download stats to rngit 2026-05-15 20:12:07 +02:00
Mark Qvist f3f4d9bca3 Cleanup 2026-05-15 17:32:10 +02:00
Mark Qvist e7a317f0a0 Use canonical Transport interface list add/removes. Improved announce cache cleaning. Adjusted logging. 2026-05-15 17:08:22 +02:00
Mark Qvist d5b64a4af3 Cleaned up log/print consistency for listener/initiator modes in rncp 2026-05-15 14:40:55 +02:00
Mark Qvist 5667a0bbac Better transfer completed feedback in rncp, thanks to neutral 2026-05-15 14:27:17 +02:00
Mark Qvist 7e46422c16 Auto-set latest release on creation 2026-05-15 00:58:17 +02:00
Mark Qvist 869a803149 Updated logging 2026-05-14 23:55:01 +02:00
Mark Qvist f744e4d9a3 Updated logging 2026-05-14 23:32:33 +02:00
Mark Qvist 1a7607cba3 Improved shared instance RPC error handling 2026-05-14 19:16:52 +02:00
Mark Qvist d881c111f6 Added latest release management to rngit 2026-05-14 14:13:42 +02:00
Mark Qvist bdac57ec0b Readme formatting 2026-05-14 12:02:54 +02:00
Mark Qvist c15f566cfa Updated readme 2026-05-14 11:58:05 +02:00
Mark Qvist bdc79b9097 Updated readme 2026-05-14 11:55:11 +02:00
Mark Qvist 102eccb77d Updated readme 2026-05-14 11:54:36 +02:00
Mark Qvist e8b236c7d8 Updated readme 2026-05-14 11:54:05 +02:00
Mark Qvist d69491eb80 Updated readme 2026-05-14 11:52:18 +02:00
Mark Qvist 256a4d0b92 Cleanup 2026-05-14 11:48:44 +02:00
Mark Qvist c5add012c1 Updated readme 2026-05-14 11:46:39 +02:00
Mark Qvist 6ecc8933b4 Updated readme 2026-05-14 11:44:07 +02:00
Mark Qvist 42b5661979 Updated readme 2026-05-14 11:35:30 +02:00
Mark Qvist 6333fb39bf Updated readme 2026-05-14 10:45:48 +02:00
Mark Qvist ea27a8b8a7 Updated readme 2026-05-14 10:43:57 +02:00
Mark Qvist 358f9c3b0c Updated readme 2026-05-14 10:42:33 +02:00
Mark Qvist cb3ef69072 Updated readme 2026-05-14 10:33:36 +02:00
Mark Qvist eee9354657 Updated readme 2026-05-14 10:26:21 +02:00
Mark Qvist ff86a1d7e6 Updated readme 2026-05-14 10:19:53 +02:00
Mark Qvist e49f31322c Redirect blob to tree page if target is a tree 2026-05-14 10:07:03 +02:00
Mark Qvist 95502e2c21 Prepare release 2026-05-14 01:56:30 +02:00
Mark Qvist 3dd4145e62 Updated changelog 2026-05-14 01:53:33 +02:00
Mark Qvist 1d7ddc3f8a Implemented rngit work document signing 2026-05-14 01:51:22 +02:00
Mark Qvist d731b4396c Repo page rendering 2026-05-14 00:32:22 +02:00
Mark Qvist c186a1f6b0 Updated version 2026-05-14 00:16:33 +02:00
Mark Qvist a049ec8b7b Updated changelog 2026-05-14 00:16:28 +02:00
Mark Qvist 4c93f6c7f4 Added local URL resolution to repo frontpage markdown readme renderer 2026-05-13 23:41:07 +02:00
Mark Qvist 35c7a89b19 Fixed typo 2026-05-13 22:58:50 +02:00
Mark Qvist c86b9c9703 Fixed missing none check in interface discovery sanitizer thanks to PAzter1101 2026-05-13 10:34:58 +02:00
Mark Qvist 64ebdd0ee3 Cleanup 2026-05-13 01:19:51 +02:00
Mark Qvist 9179b914d5 Added embedded message signing, validation and viewing to rnid 2026-05-13 01:14:41 +02:00
Mark Qvist eb5d46b20b Added file decryption for multiple file path inputs and shell expansions to rnid 2026-05-12 23:20:28 +02:00
Mark Qvist 54c36f515b Added file encryption for multiple file path inputs and shell expansions to rnid 2026-05-12 23:14:01 +02:00
Mark Qvist 5c5668a4fc Added signature creation for multiple file path inputs and shell expansions to rnid 2026-05-12 23:09:50 +02:00
Mark Qvist eeefb60c89 Added signature validation of multiple file path inputs and shell expansions to rnid 2026-05-12 23:00:06 +02:00
Mark Qvist 018df10a26 Fixed rngit remote helper hanging on startup if no client config had been created previously, and RNS loglevel was configured at debug or higher 2026-05-12 22:21:53 +02:00
Mark Qvist 93ead77435 Added workdoc downloads 2026-05-12 21:47:10 +02:00
Mark Qvist bd0e1ad0ca Better workdoc page handling 2026-05-12 21:05:15 +02:00
Mark Qvist d0ceeacb37 Allow setting title on workdoc edit 2026-05-12 15:04:02 +02:00
Mark Qvist 7d5fb6a13f Cleanup 2026-05-11 23:31:25 +02:00
Mark Qvist 855ef7bfd1 Base256 encoding 2026-05-11 23:22:13 +02:00
Mark Qvist 323890021a Better remote monitor loop 2026-05-11 00:20:02 +02:00
Mark Qvist e004e7592b Added lock to interface discovery 2026-05-10 00:29:48 +02:00
Mark Qvist 0ebec014e5 Improved release page 2026-05-10 00:26:55 +02:00
Mark Qvist 1b624cc0e2 Updated manual 2026-05-09 19:20:38 +02:00
Mark Qvist e8d161c0d5 Yes, that was indeed a bit overkill 2026-05-09 19:17:38 +02:00
Mark Qvist e5c7dd7ec7 Prepare release 2026-05-09 18:59:29 +02:00
Mark Qvist 7d6ed59e6e Added hex/b32/b64 output to rnid rsg signature generator 2026-05-09 18:34:28 +02:00
Mark Qvist 11e4e7953a Consistency 2026-05-09 15:11:33 +02:00
Mark Qvist a5b292ee81 Dreaming of a universe without escape characters 2026-05-09 14:58:43 +02:00
Mark Qvist d619bafb8d People use tabs, I guess 2026-05-09 13:51:55 +02:00
Mark Qvist 0119a589dc Improved transport jobs error handling 2026-05-09 13:32:32 +02:00
Mark Qvist b7346bed4d Fixed announce processing edge case where path was cleaned while waiting for announce rebroadcast 2026-05-09 13:29:31 +02:00
Mark Qvist fcea57cb8e Added burst filter to rnstatus 2026-05-09 13:28:49 +02:00
Mark Qvist 8d8af5e60a Improved git command timeout logging 2026-05-09 12:51:28 +02:00
Mark Qvist 1a732ac1c1 Adjusted logging 2026-05-09 12:35:39 +02:00
Mark Qvist f827d945be Implemented path request ingress burst control and egress limiting 2026-05-09 04:43:22 +02:00
Mark Qvist e03c4ee455 Added path request burst control to manual 2026-05-09 03:21:09 +02:00
Mark Qvist 35e7ccb773 Fixed invalid handling of corrupted discovery file 2026-05-09 02:52:01 +02:00
Mark Qvist a932a10492 Inherit egress and PR burst settings from parent interface 2026-05-09 02:27:31 +02:00
Mark Qvist c5108c3a19 Added path request frequency sorting to rnstatus 2026-05-09 01:45:04 +02:00
Mark Qvist 767782e425 Cleanup 2026-05-09 01:27:22 +02:00
Mark Qvist 60c440a3b6 Transport logic for path request ingress and egress control 2026-05-09 01:14:40 +02:00
Mark Qvist 6551a25877 Cleanup 2026-05-09 01:10:49 +02:00
Mark Qvist 70db2c5369 Updated log levels 2026-05-09 01:08:19 +02:00
Mark Qvist 8ed31d0dc8 Added path request frequency monitoring support to interfaces subsystem 2026-05-09 00:51:44 +02:00
Mark Qvist ef1ecb35e1 Fixed formatting 2026-05-09 00:50:19 +02:00
Mark Qvist 6768f10631 Improved discovery persist error handling 2026-05-09 00:26:42 +02:00
Mark Qvist fee6a53473 Added path request frequency display to rnstatus 2026-05-09 00:05:39 +02:00
Mark Qvist bbfa3b0aa0 Use validation functions canonically from util 2026-05-08 20:03:48 +02:00
Mark Qvist 325ae654ef Template rendering sequence 2026-05-08 18:24:30 +02:00
Mark Qvist 8655a4fb37 Cleaned up error messages 2026-05-08 18:18:28 +02:00
Mark Qvist b30d272ee6 Ensure non-corrupting stats writes 2026-05-08 17:37:32 +02:00
Mark Qvist cc90ac2853 Fixed workdoc limit 2026-05-08 17:27:56 +02:00
Mark Qvist 55473f39cb Improved rngit error logging 2026-05-08 17:25:46 +02:00
Mark Qvist 6d73881b07 Ensure error return consistency 2026-05-08 17:08:27 +02:00
Mark Qvist d107cd4b42 Cleanup 2026-05-08 17:00:49 +02:00
Mark Qvist 33247e21b2 Added AutoInterface per-peer announce rate display to rnstatus 2026-05-08 16:48:50 +02:00
Mark Qvist 6bdc769af3 Ensure SHA validation is canonical 2026-05-08 16:22:21 +02:00
Mark Qvist e923ccbf1b Improved ref name validation in rngit 2026-05-08 16:07:16 +02:00
Mark Qvist d402ee33a2 Formatting and cleanup 2026-05-08 12:00:39 +02:00
Mark Qvist d8d420745f Removed programs from docs using non-verified/LLM-generated implementations of Reticulum 2026-05-08 11:33:51 +02:00
Mark Qvist 524f2068cd Fixed regression in link close handling in rnstatus and rnpath remote management 2026-05-08 02:47:43 +02:00
Mark Qvist 5db089ff19 Updated version 2026-05-08 02:15:28 +02:00
Mark Qvist 08d6780c73 Tuned default IC params. Show burst status in rnstatus. 2026-05-08 01:13:49 +02:00
Mark Qvist ca3f0bba6d Cleanup 2026-05-08 00:28:02 +02:00
Mark Qvist 830327e4a2 IC default config 2026-05-08 00:26:01 +02:00
Mark Qvist f96409dfa9 IC config stuff 2026-05-08 00:11:18 +02:00
Mark Qvist 18e2da7d2b Updated manual 2026-05-07 21:08:24 +02:00
Mark Qvist dfd046afb6 Fixed f-string for old snakes 2026-05-07 20:59:44 +02:00
Mark Qvist 63d7f1e295 Fixed page formatting 2026-05-07 20:49:20 +02:00
Mark Qvist 9d076d6a19 Prepare release 2026-05-07 20:07:21 +02:00
Mark Qvist c6fa33a8aa Prepare release 2026-05-07 20:05:44 +02:00
Mark Qvist 37fa4392a5 Fixed signature validation display for offline rsg validation with hex-based required signer identity 2026-05-07 19:44:53 +02:00
Mark Qvist 90c88ade00 Fixed signature validation display for offline rsg validation with hex-based required signer identity 2026-05-07 19:32:55 +02:00
Mark Qvist bb08f63a9f Improved releases page rendering 2026-05-07 19:06:05 +02:00
Mark Qvist bdfad57d3f Added identity retain on use to rnid 2026-05-07 18:40:45 +02:00
Mark Qvist 7ceb2d2078 Added ability to retain identity data based on identity hash 2026-05-07 18:40:28 +02:00
Mark Qvist 304acdd0c1 Added ability to query network for raw identities to rnid 2026-05-07 18:15:31 +02:00
Mark Qvist 8b6609c588 Improved rnid options and control flow 2026-05-07 17:59:31 +02:00
Mark Qvist 8a1d3aedd4 Updated version 2026-05-07 17:23:07 +02:00
Mark Qvist d49f100edd Print help if no args 2026-05-07 17:23:01 +02:00
Mark Qvist 83d9ee1c5f Refactored rnid 2026-05-07 17:19:46 +02:00
Mark Qvist b527c59735 Cleanup 2026-05-07 15:50:07 +02:00
Mark Qvist 23498a7a0a Refactoring work for rnid 2026-05-07 15:46:17 +02:00
Mark Qvist ac2cf79451 Refactoring work for rnid 2026-05-07 15:31:14 +02:00
Mark Qvist 42b7426ed8 Refactoring work for rnid 2026-05-07 15:25:20 +02:00
Mark Qvist 928c02099b Refactoring work for rnid 2026-05-07 14:11:49 +02:00
Mark Qvist c0ae63e27a Fixed invalid processing order for inline markdown conversion 2026-05-07 02:18:11 +02:00
Mark Qvist 62532e1c54 Clean weird markdown output in API reference 2026-05-07 02:16:41 +02:00
Mark Qvist 3136b53277 Clean weird markdown output in API reference 2026-05-07 02:12:35 +02:00
Mark Qvist 9352cff870 Cleanup 2026-05-07 02:03:37 +02:00
Mark Qvist 9e5fd0f079 Cleanup 2026-05-07 02:01:42 +02:00
Mark Qvist 1d37ba4780 Updated readme 2026-05-07 01:36:53 +02:00
Mark Qvist 134c1fb6ac Updated readme 2026-05-07 01:35:43 +02:00
Mark Qvist 24df04f304 Cleanup 2026-05-07 01:31:18 +02:00
Mark Qvist 26595bb25a Added support for local URL scope mapping in markdown converter 2026-05-07 01:29:41 +02:00
Mark Qvist 5ee7dcf5a3 Cleanup 2026-05-07 00:44:11 +02:00
Mark Qvist 8b2ba9907f Added work document permissions control logic and CLI interaction to rngit. Added ability to create comments/updates on work documents from allowed identities. 2026-05-07 00:42:37 +02:00
Mark Qvist d1c59ef3b6 Prepare workdoc permissions management 2026-05-06 22:18:08 +02:00
Mark Qvist 2dd23b15a8 Added docs permissions resolver 2026-05-06 22:11:19 +02:00
Mark Qvist 93ad11f193 Consistency 2026-05-06 22:10:53 +02:00
Mark Qvist ec27d8bfde Added markdown manual build 2026-05-06 21:18:01 +02:00
Mark Qvist 4d6e164d62 Cleanup 2026-05-06 21:12:34 +02:00
Mark Qvist d82ffce504 Fixed markdown-to-micron formatting and syntax highlighting being weird in some cases 2026-05-06 21:11:49 +02:00
Mark Qvist 7ecd435911 Updated docs 2026-05-06 20:12:06 +02:00
Mark Qvist 49f56e7d0d Added markdown manual 2026-05-06 19:25:28 +02:00
Mark Qvist b8d6a14599 Display help if no operation 2026-05-06 19:12:26 +02:00
Mark Qvist 9c166936ad Added outbound announce frequency per client display to rnstatus 2026-05-06 19:06:16 +02:00
Mark Qvist 69db87cc24 Cleaned up f-strings for Android build compat 2026-05-06 18:59:17 +02:00
Mark Qvist 5d86232fbe Added detection of yggdrasil addresses to auto-connect handler 2026-05-06 04:57:20 +02:00
Mark Qvist 607e80bc82 Improved autoconnect logging 2026-05-06 04:46:23 +02:00
Mark Qvist f9625b2b88 Improved interface discovery data sanitization 2026-05-06 04:24:07 +02:00
Mark Qvist 3d8079c02b Added announce rate control defaults configuration options 2026-05-06 03:29:40 +02:00
Mark Qvist 5c05a7fa58 Updated docs 2026-05-06 03:25:21 +02:00
Mark Qvist 2fa959a560 Fixed time formatter 2026-05-06 01:49:19 +02:00
Mark Qvist c39494d9fa Improved logging performance 2026-05-06 01:03:43 +02:00
Mark Qvist a3cd1ea83d Improved shutdown handling 2026-05-05 23:42:00 +02:00
Mark Qvist d4ddf6bb13 Improved workdoc sorting 2026-05-05 21:19:16 +02:00
177 changed files with 33217 additions and 7674 deletions

No files matched your search

+1
View File
@@ -14,3 +14,4 @@ tests/rnsconfig/logfile*
*.data
*.result
.buildinfo.bak
docs/Reticulum Manual.*
+271 -5
View File
@@ -1,12 +1,278 @@
compiling = False
noticed = False
notice_delay = 0.3
import time
import os
import sys
import time
import threading
from importlib.util import find_spec
if find_spec("pyximport") and find_spec("cython"):
import pyximport; pyxloader = pyximport.install(pyimport=True, language_level=3)[1]
import json
import shutil
import subprocess
from importlib.abc import MetaPathFinder
from importlib.machinery import ExtensionFileLoader, SourceFileLoader
from importlib.machinery import EXTENSION_SUFFIXES
from importlib.util import spec_from_file_location
from distutils.extension import Extension
from pyximport import pyxbuild
COMPILE_DIRECTIVES = { "annotation_typing": False }
_WORKER_SCRIPT = r"""
import sys, os, json
from distutils.extension import Extension
from pyximport import pyxbuild
def main():
tasks_path = sys.argv[1]
with open(tasks_path, "r") as fh: tasks = json.load(fh)
results = []
for task in tasks:
try:
os.makedirs(task["scratch"], exist_ok=True)
extension = Extension(name=task["basename"], sources=[task["source"]])
extension.cython_directives = task["directives"]
so_path = pyxbuild.pyx_to_dll(task["source"], ext=extension, build_in_temp=True, pyxbuild_dir=task["scratch"])
os.makedirs(os.path.dirname(task["target"]), exist_ok=True)
os.replace(so_path, task["target"])
results.append({"fullname": task["fullname"], "ok": True, "error": None})
except Exception as e:
results.append({"fullname": task["fullname"], "ok": False,
"error": "{}: {}".format(type(e).__name__, e)})
with open(tasks_path + ".results", "w") as fh: json.dump(results, fh)
if __name__ == "__main__": main()
"""
def _compile_jobs():
jobs = os.environ.get("CRNS_JOBS")
if jobs: return max(1, int(jobs))
return max(1, min(os.cpu_count() or 1, 16))
class _ImportFinder(MetaPathFinder):
def __init__(self):
self.build_dir = os.path.join(os.path.expanduser("~"), ".pyxbld")
self.mirror_root = os.path.join(self.build_dir, "rnslib")
self.source_root = self._find_source_root()
self.abi_suffix = EXTENSION_SUFFIXES[0]
self.unbuildable = {}
self.unbuildable_path = os.path.join(self.build_dir, "unbuildable.json")
self._verify_mirror_directives()
try:
with open(self.unbuildable_path, "r") as fh: self.unbuildable = json.load(fh)
except Exception: self.unbuildable = {}
def _verify_mirror_directives(self):
# If the compiler directives have changed since the mirror was
# built, the entire mirror is invalidated and rebuilt.
stamp_path = os.path.join(self.build_dir, "rnslib.stamp")
directives = json.dumps(COMPILE_DIRECTIVES, sort_keys=True)
stamp = directives + "\n" + self.abi_suffix
previous = None
try:
with open(stamp_path, "r") as fh: previous = fh.read()
except Exception: pass
if previous != stamp:
shutil.rmtree(self.mirror_root, ignore_errors=True)
os.makedirs(self.mirror_root, exist_ok=True)
try:
os.makedirs(self.build_dir, exist_ok=True)
with open(stamp_path, "w") as fh: fh.write(stamp)
except Exception: pass
def _save_unbuildable(self):
try:
os.makedirs(os.path.dirname(self.unbuildable_path), exist_ok=True)
with open(self.unbuildable_path, "w") as fh: json.dump(self.unbuildable, fh, indent=1)
except Exception: pass
def _mark_unbuildable(self, fullname, source):
try:
self.unbuildable[fullname] = int(os.path.getmtime(source))
self._save_unbuildable()
except Exception: pass
def _unmark_buildable(self, fullname):
if fullname in self.unbuildable:
del self.unbuildable[fullname]
self._save_unbuildable()
def _is_unbuildable(self, fullname, source):
if fullname not in self.unbuildable: return False
try:
if int(os.path.getmtime(source)) == self.unbuildable[fullname]: return True
except Exception: pass
self.unbuildable.pop(fullname, None)
return False
def _find_source_root(self):
here = os.path.dirname(os.path.abspath(__file__))
candidate = os.path.abspath(os.path.join(here, "..", "RNS", "__init__.py"))
if os.path.exists(candidate): return os.path.dirname(os.path.dirname(candidate))
for entry in [os.getcwd()] + list(sys.path):
if not entry: continue
candidate = os.path.join(entry, "RNS", "__init__.py")
if os.path.exists(candidate): return os.path.dirname(candidate)
raise RuntimeError("CRNS could not locate the RNS source tree")
def _all_source_modules(self):
rns_root = os.path.join(self.source_root, "RNS")
for root, dirs, files in os.walk(rns_root):
dirs[:] = [d for d in dirs if d not in ("__pycache__", "i2plib")]
rel = os.path.relpath(root, self.source_root).replace(os.sep, ".")
for fn in sorted(files):
if not fn.endswith(".py"): continue
if fn == "__init__.py": fullname = rel
else: fullname = rel + "." + fn[:-3]
yield fullname
def _mirror_target(self, fullname, is_package):
rel = fullname.split(".")
basename = rel[-1]
if is_package: return os.path.join(self.mirror_root, *rel, "__init__" + self.abi_suffix)
return os.path.join(self.mirror_root, *rel[:-1], basename + self.abi_suffix)
def _source(self, fullname):
rel = fullname.split(".")
package_source = os.path.join(self.source_root, *rel, "__init__.py")
if os.path.exists(package_source): return package_source, True
module_source = os.path.join(self.source_root, *rel) + ".py"
if os.path.exists(module_source): return module_source, False
return None, None
def _compile(self, fullname, source):
basename = fullname.rsplit(".", 1)[-1]
extension = Extension(name=basename, sources=[source])
extension.cython_directives = COMPILE_DIRECTIVES
so_path = pyxbuild.pyx_to_dll(source, ext=extension, build_in_temp=True, pyxbuild_dir=self.build_dir)
abi_suffix = os.path.basename(so_path)[len(basename):]
return so_path, abi_suffix
def _is_current(self, fullname, source, is_package):
target = self._mirror_target(fullname, is_package)
if not os.path.exists(target): return False
try: return os.path.getmtime(target) >= os.path.getmtime(source)
except Exception: return False
def _ensure_compiled(self, fullname, source, is_package):
target = self._mirror_target(fullname, is_package)
if os.path.exists(target) and os.path.getmtime(target) >= os.path.getmtime(source): return target
so_path, abi_suffix = self._compile(fullname, source)
os.makedirs(os.path.dirname(target), exist_ok=True)
os.replace(so_path, target)
return target
def precompile(self):
if not os.path.isdir(self.mirror_root):
os.makedirs(self.mirror_root, exist_ok=True)
pending = []
for fullname in self._all_source_modules():
source, is_package = self._source(fullname)
if source is None:
continue
if self._is_current(fullname, source, is_package):
self._unmark_buildable(fullname)
continue
if self._is_unbuildable(fullname, source):
continue
pending.append((fullname, source, is_package))
if not pending: return
jobs = min(_compile_jobs(), len(pending))
if jobs > 1:
# Round-robin assignment spreads the large modules evenly
# across workers.
chunks = [[] for _ in range(jobs)]
for i, item in enumerate(pending): chunks[i % jobs].append(item)
workers_dir = os.path.join(self.build_dir, "workers")
os.makedirs(workers_dir, exist_ok=True)
procs = []
for w in range(jobs):
tasks = []
for fullname, source, is_package in chunks[w]:
tasks.append({ "fullname": fullname,
"basename": fullname.rsplit(".", 1)[-1],
"source": source,
"target": self._mirror_target(fullname, is_package),
"scratch": os.path.join(workers_dir, "w{}".format(w)),
"directives": COMPILE_DIRECTIVES })
task_path = os.path.join(workers_dir, "tasks{}.json".format(w))
with open(task_path, "w") as fh: json.dump(tasks, fh)
procs.append((w, task_path, subprocess.Popen([sys.executable, "-c", _WORKER_SCRIPT, task_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)))
for w, task_path, proc in procs:
stdout, stderr = proc.communicate()
if proc.returncode != 0:
for fullname, _, _ in chunks[w]:
source, _ = self._source(fullname)
self._mark_unbuildable(fullname, source)
print(f"CRNS: compile worker failed for {fullname}, using interpreted module", file=sys.stderr)
if stderr:
tail = stderr.decode(errors="replace").strip().splitlines()[-5:]
print("CRNS: worker output:\n" + "\n".join(tail), file=sys.stderr)
continue
results = {}
try:
with open(task_path + ".results", "r") as fh:
for entry in json.load(fh): results[entry["fullname"]] = entry
except Exception: results = {}
for fullname, _, _ in chunks[w]:
entry = results.get(fullname)
if entry is not None and entry.get("ok"): self._unmark_buildable(fullname)
else:
error = "" if entry is None else entry.get("error", "")
source, _ = self._source(fullname)
self._mark_unbuildable(fullname, source)
print(f"Could not compile {fullname}, using interpreted module: {error}", file=sys.stderr)
else:
for fullname, source, is_package in pending:
try:
self._ensure_compiled(fullname, source, is_package)
self._unmark_buildable(fullname)
except Exception as e:
self._mark_unbuildable(fullname, source)
print(f"Could not compile {fullname}, using interpreted module: {e}", file=sys.stderr)
def _spec(self, fullname, source, is_package, compile_attempted):
if fullname == "RNS.vendor.i2plib" or fullname.startswith("RNS.vendor.i2plib."):
rel = fullname.split(".")
locations = [os.path.join(self.source_root, *rel)] if is_package else None
return spec_from_file_location(fullname, source, loader=SourceFileLoader(fullname, source), submodule_search_locations=locations)
if compile_attempted:
try:
target = self._ensure_compiled(fullname, source, is_package)
self._unmark_buildable(fullname)
if is_package: locations = [os.path.dirname(target)]
else: locations = None
return spec_from_file_location(fullname, target, loader=ExtensionFileLoader(fullname, target),
submodule_search_locations=locations)
except Exception as e:
self._mark_unbuildable(fullname, source)
print(f"Could not compile {fullname}, using interpreted module: {e}", file=sys.stderr)
rel = fullname.split(".")
locations = [os.path.join(self.source_root, *rel)] if is_package else None
return spec_from_file_location(fullname, source,loader=SourceFileLoader(fullname, source),submodule_search_locations=locations)
def find_spec(self, fullname, path, target=None):
if not isinstance(fullname, str): return None
if not (fullname == "RNS" or fullname.startswith("RNS.")): return None
source, is_package = self._source(fullname)
if source is None: return None
return self._spec(fullname, source, is_package, compile_attempted=not self._is_unbuildable(fullname, source))
_importfinder = _ImportFinder()
sys.meta_path.insert(0, _importfinder)
def notice_job():
global noticed
@@ -14,13 +280,13 @@ def notice_job():
while compiling:
if time.time() > started+notice_delay and compiling:
noticed = True
print("Compiling RNS object code... ", end="")
print("Compiling RNS object code...")
sys.stdout.flush()
break
time.sleep(0.1)
compiling = True
threading.Thread(target=notice_job, daemon=True).start()
_importfinder.precompile()
import RNS; compiling = False
if noticed: print("Done."); sys.stdout.flush()
if noticed: print("Compilation done"); sys.stdout.flush()
+458 -1
View File
@@ -1,3 +1,460 @@
### 2026-09-11: RNS 1.5.4
This release improves RNode BLE connectivity reliability on desktop operating systems.
**Changes**
- Fixed RNode BLE device address acquisition on windows, by **Nickie Deuxyeux**
- Fixed RNode BLE re-connection deadlock on desktop
- Improved RNode BLE reconnect reliability
**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:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch "latest:rns-*.whl" --signer bc7291552be7a58f361522990465165c
```
To download all artifacts, including the documentation and source archive, you can use the following command:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch latest:all --signer bc7291552be7a58f361522990465165c
```
**Release Signatures**
Release artifacts include a signed `rsm` release manifest and `rsg` signature files that can be validated against the RNS release signing identity `<bc7291552be7a58f361522990465165c>` using `rngit` or `rnid`. To perform an offline verification of all release artifacts using a manifest:
```sh
rngit release rns_*.rsm verify --signer bc7291552be7a58f361522990465165c
```
To verify release artifacts using individual `rsg` files, while also verifying the manifest itself, download the `rsm` and `rsg` signatures, make sure they are in the same folder as the release artifact, and run `rnid` signature verification with the release identity as the required signer:
```sh
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.
### 2026-09-10: RNS 1.5.3
This maintenance release adds functionality to, and fixes bugs in `rngit`, and includes a few other optimizations and improvements.
**Changes**
- Added media request handler to `rngit`, for serving images to `nomadnet` clients
- Added media conversion handler to `rngit`, auto-converting images to webp
- Added importable helper method for using the `rngit` media converter in other programs
- Added a `no_ident` template to the `rngit` page node
- Added immediate activation of changed permissions with `rngit perms`
- Added optimized HDLC framer
- Fixed `rngit` repo admins not being able activate/complete workdocs from other users, by **Bergie**
- Fixed a typo, I'm positively certain this is the last one
### 2026-08-28: RNS 1.5.2
This maintenance release fixes a regression in resource transfers that was introduced in 1.5.1, an `I2PInterface` bug, and sets dataplane control parameters to default values that are actually sensible. If you installed `1.5.1`, it's update time again, baby.
**Changes**
- Tuned dataplane control parameters
- Added example for blocking unidentified page node peers to `rngit` default config
- Fixed regression in resource transfers causing some `rngit` file downloads to fail
- Fixed keepalive frames being passed to transport core on `I2PInterface`
### 2026-08-28: RNS 1.5.1
This release focuses on dataplane control, memory bounding and transport throughput, with adaptive ingress and egress control for interfaces, a new (and very efficient) zero-copy coalescing transmit buffer, an optimized HDLC deframer, and a range of other improvements to the inbound packet processing paths. It also introduces support for live profiling, and various new diagnostics output in `rnstatus`, along with a number of bug fixes and general improvements.
**Changes**
- Added adaptive dataplane egress control
- Added adaptive dataplane ingress control
- Added zero-copy coalescing transmit buffers to interfaces using the `BackboneInterface` backend
- Added early protocol violation checks for invalid frames
- Added transport implementation name and version to discovery information requirements
- Added full live profiling to the built-in `Profiler` primitive, by **K8**
- Added the `@RNS.Profiler.profile` decorator, by **K8**
- Added support for indefinitely running, reentrant profilers with bounded capture, by **K8**
- Added live profiling results output to `rnstatus`, by **K8**
- Added PPS statistics to `rnstatus`
- Added interface MTU display to `rnstatus`
- Added interface TX drop statistics to `rnstatus`
- Added interface TX buffer size output to `rnstatus`
- Added throughput benchmarker to the test suite
- Added support for natively compiled module builds, and the ability to load compiled modules when available
- Added module compilation status reporting from in-wheel build information
- Added parity tests for HDLC, IFAC and HKDF against the legacy implementations
- Added shared medium hints to interfaces
- Improved memory and CPU consumption under high traffic loads
- Improved traffic class handling
- Optimized HKDF to ~5.7x performance, if this worries you, **good**; then see the full parity and standard vector test suite and read the code
- Optimized inbound and outbound IFAC handling to ~90x performance on large frames
- Optimized inbound packet processing by reducing lock acquisitions and path table contention
- Optimized lookups for pending and active links using hash maps for lookup operations
- Optimized announce validation by caching signature validation results, significantly lowering announce storm CPU load
- Optimized the HDLC deframer
- Reduced redundant packet hashing in inbound processing
- Tuned default inbound queue lengths and announce queuing
- Tuned automatic interface MTU configuration
- Fixed `Resource` transfers failing when initialized from stream-based data sources that fell outside `MAX_EFFICIENT_SIZE`
- Fixed an invalid prefix stripping bug in the `rngit` page server (`.something` files not viewable)
- Fixed RSSI/SNR reporting regression
- Fixed keepalive handling on non-epoll backends
- Fixed a bug in `rngit` page navigation content initialization order
- Fixed the `rngit` page node not being able to serve in-tree downloads for large files
- Fixed `rnstatus` blocked IP listing including IPs that were actually not yet blocked
- Fixed `rnstatus` traffic totals counting the local shared instance inter-app transit in totals
- Fixed various minor bugs in `rnsh`, `rnir`, identity handling
- Fixed a latent bug in the AES module, where an exception would not resolve it's exception description correctly, and instead raise another exception.
- Removed dead Python 2 code from `umsgpack`
### 2026-08-22: RNS 1.5.0
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**
- Added ability to include operator LXMF address in interface discovery information
- Added prioritized inbound traffic processing to the transport core
- Added configurable inbound queue lengths for data, announce, path request and ingress limited traffic
- 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
### 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
This maintenance release improves announces propagation logic, and adds additional options for configuring announce propagation and interface behavior in transport mode.
**Changes**
- Added `internal` interface mode
- Added `recursive_prs` interface option
- Added `announces_from_internal` interface option
- Added new options to the manual
- Improved and cleaned up announce propagation logic
### 2026-07-03: RNS 1.3.6
This release contained a bug in the local instance transport handling, and was superseded by version `1.3.7`.
### 2026-06-01: RNS 1.3.5
This maintenance release contains an important fix for `AutoInterface` reliability when roaming between different physical networks.
**Changes**
- Fixed UDP listener replacement deadlocking inbound AutoInterface traffic when fast-roaming between physical interfaces or WiFi APs
- Fixed some paths never resolving when using other interfaces at the same time as a deadlocked AutoInterface
### 2026-05-29: RNS 1.3.4
This release fixes a regression that could cause sub-optimal path selection under conditions where the same announce was received within a very short timespan on different interfaces, as well as a few other bugs and inefficiencies.
**Changes**
- Fixed regression in inbound announce de-duplication
- Fixed missing check for shared instance type configuration conflict
- Fixed superfluous path state configuration on new announce from new destinations
- Improved cleanup of stale known destinations
- Improved shared instance RPC handling
### 2026-05-28: RNS 1.3.3
This release fixes a regression in persistence of known destination on Windows.
**Changes**
- Fixed regression in known destinations persist on Windows
### 2026-05-28: RNS 1.3.2
This release adds commit signing and validation support to the `rngit` system, as well as improvements to the blackhole functionality.
**Changes**
- Extended blackhole functionality to immediately terminate links from blackholed identities
- Added commit signing and validation to `rngit`
- Added commit hash inclusion in generated release manifest to `rngit`
- Added local `verify` operation shorthand to `rngit release`
- Added option to configure blackhole update interval
- Added configuration option to log without timestamps
### 2026-05-22: RNS 1.3.1
This maintenance release fixes a single bug.
**Changes**
- Fixed regression in request response transfer size accumulator
### 2026-05-21: RNS 1.3.0
This maintenance release fixes a number of bugs.
**Changes**
- Added ability to use wildcards and pattern matches in `rngit` artifact fetch targets
- Fixed channel outlet sequence holes and ghost envelopes on dying outlets by **neutral**
- Fixed known destination iteration races by **neutral**
- Fixed timeout deadlock in `rnsh` by **neutral**
- Fixed commit message rendering in `rngit`
- Fixed various minor bugs and output inconsistencies in `rngit`
- Adjusted timeouts for remote operations in `rngit`
- Updated documentation
### 2026-05-19: RNS 1.2.9
This release completes the operational functionality of the `rngit` system, which now has full release creation, fetch and verified update support using the `rngit release` command. Additionally, two chapters have been added to the manual should cover all the things that `rngit` is currently capable of.
**Changes**
- Added full `rngit` documentation to the manual
- Added offline `.rsm` release manifest verification
- Added the ability to fetch release updates directly from `.rsm` manifests
- Added canonical `.rsm` release structure validator to `rnid` for import
- Added `.rsm` manifest saving when using `rngit release fetch`
- Added remote `HEAD` tracking for forks and mirros to `rngit`
- Improved known destinations persist reliability
- Improved page node ref link handling in `rngit`
- Improved logging in various locations
### 2026-05-18: RNS 1.2.8
This release improves the `rngit` system with signed release manifest generation and automatic artifact signing. It also includes several additions to `rnid` and various minor fixes and improvements to the `rngit` system.
**Changes**
- Added signed release manifest generation to `rngit release`
- Added verified release fetching to `rngit release`
- Added automatic artifact signing to `rngit release`
- Added signed message creation from file to `rnid`
- Added signed message metadata output option to `rnid`
- Added `rsm` metadata embedding and spec validation to `rnid`
- Added identity and destination aliases to `rngit`
- Added blocked identities option to `rngit`
- Added ability to render raw micron in markdown files to `rngit`
- Added fork and mirror last sync time to repository page in `rngit`
- Better handling of silly links in `rngit`
- Fixed markdown table cell truncation not closing micron tags
- Fixed various minor bugs and inconsistencies in `rngit`
- Dropped `note` metadata field requirement from `rsg` structure
### 2026-05-17: RNS 1.2.7
This release significantly improves the `rngit` system with fork, mirroring and empty repository creation functionality, a new work document proposals feature, improvements to the transport core reliability and efficiency and various other tweaks and improvements.
**Changes**
- Added work document proposals functionality to `rngit`
- Added fork and mirroring support to `rngit`
- Added ability to create new repositories remotely to `rngit`
- Added latest release management to `rngit`
- Added download stats to `rngit`
- Improved shared instance RPC error handling
- Improved announce cache cleaning
- Improved `rngit` page node link handling
- Improved stats pages `rngit`
- Improved transfer completed feedback in `rncp`, thanks to **neutral**
- Improved interface transport insertion and removal
### 2026-05-14: RNS 1.2.6
This release adds further improvements to the `rnid` and `rngit` utilities, and includes several bugfixes and other improvements.
**Changes**
- Added embedded message signing, validation and viewing to `rnid`
- Added file encryption for multiple file path inputs and shell expansions to `rnid`
- Added file decryption for multiple file path inputs and shell expansions to `rnid`
- Added signature creation for multiple file path inputs and shell expansions to `rnid`
- Added signature validation of multiple file path inputs and shell expansions to `rnid`
- Added workdoc signing and validation to `rngit`
- Added ability to edit workdoc titles to `rngit`
- Added ability to download workdocs via the `nomadnet` interface to `rngit`
- Added local URL resolution to the `rngit` repository frontpage markdown readme renderer
- Improved `rnstatus` remote monitor loop
- Improved `rngit` workdoc page handling
- Improved `rngit` release page rendering
- Fixed missing none check in interface discovery sanitizer thanks to PAzter1101
- Fixed potential race condition in interface discovery
- Fixed `rngit` remote helper hanging on startup if no client config had been created previously, and RNS loglevel was configured at debug or higher
### 2026-05-09: RNS 1.2.5
This release brings substantial improvements to path request handling, and should significantly reduce overall network and local transport node processing loads. Path requests are now automatically ingress and egress limited per interface and sub-interface. Although the defaults are effective and sane, and should work right out of the box bring an end to practically all the PR and announce spam going on lately, the backend is fully configurable for both defaults and per interface, if you want to fiddle with the settings.
People who have written (ahem... *prompted into existence*) strange applications, that believed sending 25 random path requests every 10 seconds to try and punch holes through announce limiting, will now most likely find any potential users of such applications complaining that they are losing the ability to resolve paths alltogether, which is (entirely) by design, of course. Seriously, don't do crap like that.
You can read more about how the new ingress and egress controls work in the updated manual sections, in the Interfaces chapter.
For all node ops out there, I'd recomment updating to this at some sort of semi-expedient, but of course not un-leisurely pace, so peace and order on the networks can be restored.
**Changes**
- Added path request ingress and egress control with sane defaults for transport nodes
- Added full configurability of ingress and egress controls per interface and for instance-wide defaults
- Significantly improved transport logic for path request and announce handling
- Added path request frequency display to `rnstatus`
- Added AutoInterface per-peer announe rate display to `rnstatus`
- Added abilit to filter interfaces by burst state to `rnstatus`
- Added hex/base32/base64 ASCII-wrapped output to `rnid` signature generator
- Tuned default ingress control parameters
- Fixed regression in link close handling in `rnstatus` and `rnpath` remote management handling
- Fixed invalid handling of corrupted interface discovery files
- Fixed announce processing edge case handling if path was cleaned while waiting for rebroadcast
- Improved `rngit` error logging
- Improved transport background jobs error handling
- Fixed various edge-cases and inconsistencies in markdown rendering in `rngit`
- Ensured canonical validation functions in `rngit`
- Lots of other small fixes and stability improvements to `rngit`
### 2026-05-07: RNS 1.2.4
This release brings a complete rewrite and update to the `rnid` utility, which is now a lot more useful, and better at finding and saving identities. It also includes a bunch of other improvements, such as expanded `rngit` functionality, better transport performance and a few bugfixes. Enjoy!
Unless something really crazy happens, this will probably be the last release that is also published to GitHub, since everything can now run over Reticulum itself. Updates to `pip` will continue at least until `rnpkg` is complete, and RNS is completely self-hosting.
**Changes**
- Completely rewrote the `rnid` utility, **much** better now
- Added ability to query network for raw identities to `rnid`
- Added new, much more useful `rsg` file signature format
- Added auto-retain functionality for used identities to `rnid`
- Added outbound announce frequency per-client display to `rnstatus`
- Added announce rate control settings display to `rnstatus`
- Added announce rate control defaults configuration options
- Added saner default announce rate settings for transport nodes
- Added detection of Yggdrasil addresses to auto-connect handler
- Added work document permissions resolver to `rngit`
- Added ability to create updates and comments on `rngit` work documents
- Added work document permissions control logic and CLI interaction to `rngit`
- Added support for node-local URL-scoping in `rngit` markdown converter
- Added API functionality for retaining identity data
- Added the manual in markdown format
- Improved `rngit` releases page rendering
- Improved auto-connect logging
- Improved transport performance
- Improved logging performance
- Improved shutdown handling
- Improved workdoc sorting
- Fixed time formatting being unintuitive sometimes
- Fixed markdown-to-micron formatting and syntax highlighting being weird sometimes
**Release Hashes**
```
e821a0b6a18d6b3263bbcdde880d0388fb4dd0c07c7eb2f83cb0dbc30eda5965 rns-1.2.4-py3-none-any.whl
618e823cec0bd368f2f211431dfb78efef75e59132bad93d3101dacbe7deb7a6 rnspure-1.2.4-py3-none-any.whl
```
**Release Signatures**
Release artifacts include `rsg` signature files that can be validated against the RNS release signing identity `<bc7291552be7a58f361522990465165c>` using `rnid`. To verify files, download the `rsg` signatures, make sure they are in the same folder as the release artifact, and run `rnid` signature verification with the release identity as the required signer:
```sh
rnid -i bc7291552be7a58f361522990465165c -V rns-1.2.4-py3-none-any.whl
```
The `rnid` utility will then verify the signatures, and display whether it is valid. If the signature cannot be verified, the file has been tampered with and should be thrown very far away in a jiffy.
This is the first release using the new `rsg` signature format, and you will need this latest version of RNS to verify them. Ironic, I know, but that's how it is. Since release file hashes are now embbeded in the `rsg` signatures, this is the last release that will explicitly post the raw release hashes. Verifying with `rnid` is much more effective, since it ensures all data was signed by the release identity.
### 2026-05-05: RNS 1.2.3
This release adds Work Document and update/commenting support to `rngit`.
@@ -20,7 +477,7 @@ This release adds Work Document and update/commenting support to `rngit`.
Release artifacts include `rsg` signature files that can be validated against the RNS release signing identity `<bc7291552be7a58f361522990465165c>` using `rnid`:
```sh
rnid -i bc7291552be7a58f361522990465165c -V rns-1.2.2-py3-none-any.whl.rsg
rnid -i bc7291552be7a58f361522990465165c -V rns-1.2.3-py3-none-any.whl.rsg
```
### 2026-05-05: RNS 1.2.2
+1 -1
View File
@@ -239,7 +239,7 @@ def link_established(link):
RNS.log("Link established with server, sending...")
rd = os.urandom(link.mdu)
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()
data_sent += len(rd)
+37 -5
View File
@@ -21,12 +21,26 @@ clean:
@-rm -rf ./tests/__pycache__
@-rm -rf ./tests/rnsconfig/storage
@-rm -rf ./*.egg-info
@-rm -rf ./RNS/*.c
@-rm -rf ./RNS/Cryptography/*.c
@-rm -rf ./RNS/Cryptography/aes/*.c
@-rm -rf ./RNS/Cryptography/pure25519/*.c
@-rm -rf ./RNS/Interfaces/*.c
@-rm -rf ./RNS/Interfaces/util/*.c
@-rm -rf ./RNS/Interfaces/Android/*.c
@-rm -rf ./RNS/Utilities/*.c
@-rm -rf ./RNS/Utilities/rngit/*.c
@-rm -rf ./RNS/Utilities/rnsh/*.c
@-rm -rf ./RNS/vendor/*.c
@-rm -rf ./RNS/vendor/i2plib/*.c
@-rm -rf
@make -C docs clean
@echo Done
purge_docs:
@echo Purging documentation build...
@-rm -rf ./docs/manual
@-rm -rf ./docs/markdown
@-rm -rf ./docs/*.pdf
@-rm -rf ./docs/*.epub
@@ -49,28 +63,46 @@ build_wheel:
build_pure_wheel:
python3 setup.py bdist_wheel --pure
build_native:
python3 setup.py bdist_wheel --native
documentation:
make -C docs html
make -C docs html markdown
manual:
make -C docs latexpdf epub
distcollect:
mv docs/Reticulum\ Manual.* dist
build_spkg: remove_symlinks build_sdist create_symlinks
release: test remove_symlinks build_sdist build_wheel build_pure_wheel documentation manual create_symlinks
release: test remove_symlinks build_sdist build_wheel build_pure_wheel documentation manual distcollect create_symlinks
debug: remove_symlinks build_wheel build_pure_wheel create_symlinks
upload: upload-rns upload-rnspure
native: remove_symlinks build_native create_symlinks
upload-rns:
local: release sign
sign:
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum create $$(python setup.py --getversion):dist --name rns --local
upload:
@echo Ready to publish release over Reticulum
@read VOID
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum create $$(python setup.py --getversion):dist --name rns
upload-pip: upload-rns-pip upload-rnspure-pip
upload-rns-pip:
@echo Ready to publish rns release, hit enter to continue
@read VOID
@echo Uploading to PyPi...
twine upload dist/rns-*.whl dist/rns-*.tar.gz
@echo Release published
upload-rnspure:
upload-rnspure-pip:
@echo Ready to publish rnspure release, hit enter to continue
@read VOID
@echo Uploading to PyPi...
+7 -1
View File
@@ -39,7 +39,7 @@ userland, and can run on practically any system that runs Python 3.
## Read The Manual
The full documentation for Reticulum is available at [markqvist.github.io/Reticulum/manual/](https://markqvist.github.io/Reticulum/manual/).
You can also download the [Reticulum manual as a PDF](https://github.com/markqvist/Reticulum/raw/master/docs/Reticulum%20Manual.pdf) or [as an e-book in EPUB format](https://github.com/markqvist/Reticulum/raw/master/docs/Reticulum%20Manual.epub).
You can also download the [Reticulum manual as a PDF](https://github.com/markqvist/Reticulum/releases/latest/download/Reticulum.Manual.pdf) or [as an e-book in EPUB format](https://github.com/markqvist/Reticulum/releases/latest/download/Reticulum.Manual.epub).
For more info, see [reticulum.network](https://reticulum.network/) and [the FAQ section of the wiki](https://github.com/markqvist/Reticulum/wiki/Frequently-Asked-Questions).
@@ -85,6 +85,12 @@ The Reticulum Protocol is defined entirely and authoritatively by this reference
implementation, and its associated manual. It is maintained by Mark Qvist,
identified by the Reticulum Identity `<bc7291552be7a58f361522990465165c>`.
No second-order protocol specification derivatives currently do, or will ever exist. You can't get a better specification than one that is executable, functional, testable, deployed and operating 24/7 across the planet.
There is not, and never will be a separate, derived "formal spec", "RFC" or anything similar for Reticulum:
**The reference implementation *is* the final, authoritative specification.**
Compatibility with the Reticulum Protocol is defined as having full interoperability,
and sufficient functional parity with this reference implementation. Any specific protocol
implementation that achieves this is Reticulum. Any that does not is not Reticulum.
+81 -69
View File
@@ -1,24 +1,24 @@
>> Reticulum Network Stack
To understand the foundational philosophy and goals of this system, read the `!`[Zen of Reticulum`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=Zen+of+Reticulum.md]`!.
To understand the foundational philosophy and goals of this system, read the `_`!`[Zen of Reticulum`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=Zen+of+Reticulum.md]`!`_.
Reticulum is the cryptography-based networking stack for building local and wide-area networks with readily available hardware. It can operate even with very high latency and extremely low bandwidth. Reticulum allows you to build wide-area networks with off-the-shelf tools, and offers end-to-end encryption and connectivity, initiator anonymity, autoconfiguring cryptographically backed multi-hop transport, efficient addressing, unforgeable delivery acknowledgements and more.
The vision of Reticulum is to allow anyone to be their own network operator, and to make it cheap and easy to cover vast areas with a myriad of independent, inter-connectable and autonomous networks. Reticulum **is not** *one* network. It is **a tool** for building *thousands of networks*. Networks without kill-switches, surveillance, censorship and control. Networks that can freely interoperate, associate and disassociate with each other, and require no central oversight. Networks for human beings. *Networks for the people*.
`(RNS Logo`w=18`a=c`:/media/reticulum/reticulum/HEAD/docs/source/graphics/rns_logo_256.webp)
The vision of Reticulum is to allow anyone to be their own network operator, and to make it cheap and easy to cover vast areas with a myriad of independent, inter-connectable and autonomous networks. Reticulum `!is not`! `*one`* network. It is `!a tool`! for building `*thousands of networks`*. Networks without kill-switches, surveillance, censorship and control. Networks that can freely interoperate, associate and disassociate with each other, and require no central oversight. Networks for human beings. `*Networks for the people`*.
Reticulum is a complete networking stack, and does not rely on IP or higher layers, but it is possible to use IP as the underlying carrier for Reticulum. It is therefore trivial to tunnel Reticulum over the Internet or private IP networks.
Having no dependencies on traditional networking stacks frees up overhead that has been used to implement a networking stack built directly on cryptographic principles, allowing resilience and stable functionality, even in open and trustless networks.
No kernel modules or drivers are required. Reticulum runs completely in userland, and can run on practically any system that runs Python 3.
No kernel modules or drivers are required. Reticulum runs completely in userland, and can run on practically any system that runs Python.
>> Read The Manual
The full documentation for Reticulum is available at [markqvist.github.io/Reticulum/manual/](https://markqvist.github.io/Reticulum/manual/).
The full documentation for Reticulum is available on `_`!`[this node`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/index.md]`!`_.
You can also download the `!`[Reticulum manual as a PDF`:/file/download`g=reticulum|r=reticulum|ref=HEAD|path=docs%2FReticulum+Manual.pdf]`! or `!`[as an e-book in EPUB format`:/file/download`g=reticulum|r=reticulum|ref=HEAD|path=docs%2FReticulum+Manual.pdf]`!.
For more info, see [reticulum.network](https://reticulum.network/) and [the FAQ section of the wiki](https://github.com/markqvist/Reticulum/wiki/Frequently-Asked-Questions).
You can also download the `_`!`[Reticulum manual as a PDF`:/file/artifact`g=reticulum|r=reticulum|t=latest|a=Reticulum+Manual.pdf]`!`_ or `_`!`[as an e-book in EPUB format`:/file/artifact`g=reticulum|r=reticulum|t=latest|a=Reticulum+Manual.epub]`!`_.
>> Notable Features
@@ -60,6 +60,12 @@ For more info, see [reticulum.network](https://reticulum.network/) and [the FAQ
The Python code in this repository is the Reference Implementation of Reticulum. The Reticulum Protocol is defined entirely and authoritatively by this reference implementation, and its associated manual. It is maintained by Mark Qvist, identified by the Reticulum Identity `B333<bc7291552be7a58f361522990465165c>`b.
No second-order protocol specification derivatives currently do, or will ever exist. You can't get a better specification than one that is executable, functional, testable, deployed and operating 24/7 across the planet.
There is not, and never will be a separate, derived "formal spec", "RFC" or anything similar for Reticulum:
`!The reference implementation `*is`* the final, authoritative specification.`!
Compatibility with the Reticulum Protocol is defined as having full interoperability, and sufficient functional parity with this reference implementation. Any specific protocol implementation that achieves this is Reticulum. Any that does not is not Reticulum.
The reference implementation is licensed under the Reticulum License.
@@ -68,33 +74,31 @@ The Reticulum Protocol was dedicated to the Public Domain in 2016.
>> Examples of Reticulum Applications
If you want to quickly get an idea of what Reticulum can do, take a look at the [Programs Using Reticulum](https://reticulum.network/manual/software.html) section of the manual, or the following resources:
If you want to quickly get an idea of what Reticulum can do, take a look at the `_`!`[Programs Using Reticulum`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/software.md]`!`_ section of the manual, or the following resources:
• [LXMF](https://github.com/markqvist/lxmf) is a distributed, delay and disruption tolerant message transfer
protocol built on Reticulum
• `_`!`[LXMF`a8d24177d946de4f1f0a0fe1af9a1338:/page/repo.mu`g=reticulum|r=lxmf]`!`_ is a distributed, delay and disruption tolerant message transfer protocol built on Reticulum
• The [LXST](https://github.com/markqvist/lxst) protocol and framework provides real-time audio and signals
transport over Reticulum. It includes primitives and utilities for building voice-based applications and
hardware devices, such as the `B333rnphone`b program, that can be used to build hardware telephones.
• The `_`!`[LXST`a8d24177d946de4f1f0a0fe1af9a1338:/page/repo.mu`g=reticulum|r=lxst]`!`_ protocol and framework provides real-time audio and signals transport over Reticulum. It
includes primitives and utilities for building voice-based applications and hardware devices,
such as the `B333rnphone`b program, that can be used to build hardware telephones.
• For an off-grid, encrypted and resilient mesh communications platform, see [Nomad Network](https://github.com/markqvist/NomadNet)
• For an off-grid, encrypted and resilient mesh communications platform, see `_`!`[Nomad Network`a8d24177d946de4f1f0a0fe1af9a1338:/page/repo.mu`g=reticulum|r=nomadnet]`!`_.
• The Android, Linux, macOS and Windows app [Sideband](https://github.com/markqvist/Sideband) has a graphical
interface and many advanced features, such as file transfers, image and voice messages, real-time voice calls,
a distributed telemetry system, mapping capabilities and full plugin extensibility.
• The Android, Linux, macOS and Windows app `_`!`[Sideband`a8d24177d946de4f1f0a0fe1af9a1338:/page/repo.mu`g=reticulum|r=sideband]`!`_ has a graphical interface and many advanced
features, such as file transfers, image and voice messages, real-time voice calls, a distributed
telemetry system, mapping capabilities and full plugin extensibility.
• [MeshChatX](https://git.quad4.io/RNS-Things/MeshChatX) is a full-featured LXMF client with many built-in tools
and functionalities, that also supports image and voice messages, file transfers and voice calls. It also
includes a built-in page browser for browsing Nomad Network nodes.
• `_`!`[MeshChatX`c10d80b1a42fa958c37a6cc30dc04f53]`!`_ (`_`!`[source`5399f5a0212477618821e91e88ce053b:/page/repo.mu`g=quad4|r=MeshChatX]`_`!) is a full-featured LXMF client with many built-in tools and functionalities,
that also supports image and voice messages, file transfers and voice calls. It also includes a
built-in page browser for browsing Nomad Network nodes.
• You can use the included [rnsh](https://reticulum.network/manual/using.html#the-rnsh-utility) program to
establish remote shell sessions over Reticulum.
• You can use the included `_`!`[rnsh`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/using.md|anchor=the-rnsh-utility]`!`_ program to establish remote shell sessions over Reticulum.
>> Where can Reticulum be used?
Over practically any medium that can support at least a half-duplex channel with greater throughput than 5 bits per second, and an MTU of 500 bytes. Data radios, modems, LoRa radios, serial lines, AX.25 TNCs, amateur radio digital modes, WiFi and Ethernet devices, free-space optical links, and similar systems are all examples of the types of physical devices Reticulum can use.
An open-source LoRa-based interface called [RNode](https://markqvist.github.io/Reticulum/manual/hardware.html#rnode) has been designed specifically for use with Reticulum. It is possible to build yourself, or it can be purchased as a complete transceiver that just needs a USB connection to the host.
An open-source LoRa-based interface called `_`!`[RNode`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/hardware.md|anchor=rnode]`!`_ has been designed specifically for use with Reticulum. It is possible to build yourself, or it can be purchased as a complete transceiver that just needs a USB connection to the host.
Reticulum can also be encapsulated over existing IP networks, so there's nothing stopping you from using it over wired Ethernet, your local WiFi network or the Internet, where it'll work just as well. In fact, one of the strengths of Reticulum is how easily it allows you to connect different mediums into a self-configuring, resilient and encrypted mesh, using any available mixture of available infrastructure.
@@ -102,9 +106,9 @@ As an example, it's possible to set up a Raspberry Pi connected to both a LoRa r
>> How do I get started?
The best way to get started with the Reticulum Network Stack depends on what you want to do. For full details and examples, have a look at the [Getting Started Fast](https://markqvist.github.io/Reticulum/manual/gettingstartedfast.html) section of the [Reticulum Manual](https://markqvist.github.io/Reticulum/manual/).
The best way to get started with the Reticulum Network Stack depends on what you want to do. For full details and examples, have a look at the `_`!`[Getting Started Fast`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/gettingstartedfast.md]`!`_ section of the `_`!`[Reticulum Manual`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/index.md]`!`_.
To simply install Reticulum and related utilities on your system, the easiest way is via `B333pip`b. You can then start any program that uses Reticulum, or start Reticulum as a system service with [the rnsd utility](https://markqvist.github.io/Reticulum/manual/using.html#the-rnsd-utility).
To simply install Reticulum and related utilities on your system, the easiest way is via `B333pip`b. You can then start any program that uses Reticulum, or start Reticulum as a system service with `_`!`[the rnsd utility`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/using.md|anchor=the-rnsd-utility]`!`_.
`B333
`=
@@ -133,10 +137,11 @@ When first started, Reticulum will create a default configuration file, providin
If you have an old version of `B333pip`b on your system, you may need to upgrade it first with `B333pip install pip --upgrade`b. If you no not already have `B333pip`b installed, you can install it using the package manager of your system with `B333sudo apt install python3-pip`b or similar.
For more detailed examples on how to expand communication over many mediums such as packet radio or LoRa, serial ports, or over fast IP links and the Internet using the UDP and TCP interfaces, take a look at the [Supported Interfaces](https://markqvist.github.io/Reticulum/manual/interfaces.html) section of the [Reticulum Manual](https://markqvist.github.io/Reticulum/manual/).
For more detailed examples on how to expand communication over many mediums such as packet radio or LoRa, serial ports, or over fast IP links and the Internet using the UDP and TCP interfaces, take a look at the `_`!`[Supported Interfaces`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/interfaces.md]`!`_ section of the `_`!`[Reticulum Manual`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/index.md]`!`_.
>> Included Utilities
Reticulum includes a range of useful utilities for managing your networks, viewing status and information, and other tasks. You can read more about these programs in the [Included Utility Programs](https://markqvist.github.io/Reticulum/manual/using.html#included-utility-programs) section of the [Reticulum Manual](https://markqvist.github.io/Reticulum/manual/).
Reticulum includes a range of useful utilities for managing your networks, viewing status and information, and other tasks. You can read more about these programs in the `_`!`[Included Utility Programs`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/using.md|anchor=included-utility-programs]`!`_ section of the `_`!`[Reticulum Manual`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/index.md]`!`_.
• The system daemon `B333rnsd`b for running Reticulum as an always-available service
• An interface status utility called `B333rnstatus`b, that displays information about interfaces
@@ -149,16 +154,14 @@ Reticulum includes a range of useful utilities for managing your networks, viewi
• The `B333rngit`b program provides a full multi-repository Git node for serving repositories over Reticulum
• The included `B333git-remote-rns`b helper allows you to interact with Git repositories over Reticulum
All tools, including `B333rnx`b and `B333rncp`b, work reliably and well even over very low-bandwidth links like LoRa or Packet Radio. For full-featured remote shells over Reticulum, also have a look at the [rnsh](https://github.com/acehoss/rnsh) program.
>> Supported interface types and devices
Reticulum implements a range of generalised interface types that covers most of the communications hardware that Reticulum can run over. If your hardware is not supported, it's [simple to implement a custom interface module](https://markqvist.github.io/Reticulum/manual/interfaces.html#custom-interfaces).
Reticulum implements a range of generalised interface types that covers most of the communications hardware that Reticulum can run over. If your hardware is not supported, it's `_`!`[simple to implement a custom interface module`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/interfaces.md|anchor=custom-interfaces]`!`_.
Currently, the following built-in interfaces are supported:
• Any Ethernet device
• LoRa using [RNode](https://unsigned.io/rnode/)
• LoRa using `_`!`[RNode`a8d24177d946de4f1f0a0fe1af9a1338:/page/repo.mu`g=reticulum|r=rnode_firmware]`!`_
• Packet Radio TNCs (with or without AX.25)
• KISS-compatible hardware and software modems
• Any device with a serial port
@@ -168,64 +171,72 @@ Currently, the following built-in interfaces are supported:
• Custom hardware via stdio or pipes
>> Performance
Reticulum targets a *very* wide usable performance envelope, but prioritises functionality and performance on low-bandwidth mediums. The goal is to provide a dynamic performance envelope from 250 bits per second, to 1 gigabit per second on normal hardware.
Reticulum targets a `*very`* wide usable performance envelope, but prioritises functionality and performance on low-bandwidth mediums. The goal is to provide a dynamic performance envelope from 250 bits per second, to 1 gigabit per second on normal hardware.
Currently, the usable performance envelope is approximately 150 bits per second to 500 megabits per second, with physical mediums faster than that not being saturated. Performance beyond the current level is intended for future upgrades, but not highly prioritised at this point in time.
>> Current Status
All core protocol features are implemented and functioning, but additions will probably occur as real-world use is explored and understood. The API and wire-format can be considered stable.
>> Dependencies
The installation of the default `B333rns`b package requires only two external dependencies, listed below. Almost all systems and distributions have readily available packages for these dependencies, and when the `B333rns`b package is installed with `B333pip`b, they will be downloaded and installed as well.
• [PyCA/cryptography](https://github.com/pyca/cryptography)
• [pyserial](https://github.com/pyserial/pyserial)
• PyCA/cryptography
• pyserial
On more unusual systems, and in some rare cases, it might not be possible to install or even compile one or more of the above modules. In such situations, you can use the `B333rnspure`b package instead, which require no external dependencies for installation. Please note that the contents of the `B333rns`b and `B333rnspure`b packages are *identical*. The only difference is that the `B333rnspure`b package lists no dependencies required for installation.
On more unusual systems, and in some rare cases, it might not be possible to install or even compile one or more of the above modules. In such situations, you can use the `B333rnspure`b package instead, which require no external dependencies for installation. Please note that the contents of the `B333rns`b and `B333rnspure`b packages are `*identical`*. The only difference is that the `B333rnspure`b package lists no dependencies required for installation.
No matter how Reticulum is installed and started, it will load external dependencies only if they are *needed* and *available*. If for example you want to use Reticulum on a system that cannot support [pyserial](https://github.com/pyserial/pyserial), it is perfectly possible to do so using the `B333rnspure`b package, but Reticulum will not be able to use serial-based interfaces. All other available modules will still be loaded when needed.
No matter how Reticulum is installed and started, it will load external dependencies only if they are `*needed`* and `*available`*. If for example you want to use Reticulum on a system that cannot support `B333pyserial`b, it is perfectly possible to do so using the `B333rnspure`b package, but Reticulum will not be able to use serial-based interfaces. All other available modules will still be loaded when needed.
**Please Note!** If you use the `B333rnspure`b package to run Reticulum on systems that do not support [PyCA/cryptography](https://github.com/pyca/cryptography), it is important that you read and understand the [Cryptographic Primitives](#cryptographic-primitives) section of this document.
`!Please Note!`! If you use the `B333rnspure`b package to run Reticulum on systems that do not support PyCA/cryptography, it is important that you read and understand the `!Cryptographic Primitives`! section of this document.
>> Bootstrapping Connectivity
Reticulum is not a service you subscribe to, nor is it a single global network you "join". Reticulum provides functionality for discovering available public interfaces over the network itself, and the broader community has provided various directories of publicly available entrypoints to bootstrap connectivity.
To learn how to establish initial connectivity over Reticulum, read the [Bootstrapping Connectivity](https://reticulum.network/manual/gettingstartedfast.html#bootstrapping-connectivity) section of the manual.
To learn how to establish initial connectivity over Reticulum, read the `_`!`[Bootstrapping Connectivity`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/gettingstartedfast.md|anchor=bootstrapping-connectivity]`!`_ section of the manual.
If you already have a general idea of how this works, you can use community-run sites such as [directory.rns.recipes](https://directory.rns.recipes/) and [rmap.world](https://rmap.world) to find interface definitions for initial connectivity to the global distributed Reticulum backbone.
If you already have a general idea of how this works, you can use community-run sites such as `_`!`[rns.recipes`9ce92808be498e9e05590ff27cbfdfe4]`!`_ and `_`!`[rmap.world`a4a5e861626ce97c9aa544d9ecdf6d22]`!`_ to find interface definitions for initial connectivity to the global distributed Reticulum backbone.
>> Public Testnet
***Important!** Historically, a developer-targeted testnet was made available by the Reticulum project itself. As the amount of global Reticulum nodes and entrypoints have grown to a substantial quantity, this public testnet, including the Amsterdam Testnet entrypoint, has now been decommissioned. If your still have instances that relied on this entrypoint for connectivity, transition to using the distributed backbone instead. Reticulum now includes a full on-network interface discovery and connectivity bootstrapping system. Read the [Bootstrapping Connectivity](https://reticulum.network/manual/gettingstartedfast.html#bootstrapping-connectivity) section of the manual for pointers.*
`!`*Important!`! Historically, a developer-targeted testnet was made available by the Reticulum project itself. As the amount of global Reticulum nodes and entrypoints have grown to a substantial quantity, this public testnet, including the Amsterdam Testnet entrypoint, has now been decommissioned. If you still have instances that relied on this entrypoint for connectivity, transition to using the distributed backbone instead. Reticulum now includes a full on-network interface discovery and connectivity bootstrapping system. Read the `_`[Bootstrapping Connectivity`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/gettingstartedfast.md|anchor=bootstrapping-connectivity]`_ section of the manual for pointers.`*
>> Support Reticulum
For this to be possible, I need your help. Please support the continued development of open, free and private communications systems by donating via one of the following channels:
• Monero:
• `!Monero`!
84FpY1QbxHcgdseePYNmhTHcrgMX4nFfBYtz2GKYToqHVVhJp8Eaw1Z1EedRnKD19b3B8NiLCGVxzKV17UMmmeEsCrPyA5w
• Bitcoin
• `!Bitcoin`!
bc1pgqgu8h8xvj4jtafslq396v7ju7hkgymyrzyqft4llfslz5vp99psqfk3a6
• Ethereum
• `!Ethereum`!
0x91C421DdfB8a30a49A71d63447ddb54cEBe3465E
• Liberapay: https://liberapay.com/Reticulum/
• `!Liberapay`!
`[https://liberapay.com/Reticulum/]
• Ko-Fi: https://ko-fi.com/markqvist
• `!Ko-Fi`!
`[https://ko-fi.com/markqvist]
>> 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.
One of the primary considerations for choosing this particular set of primitives is that they can be implemented *safely* with relatively few pitfalls, on practically all current computing platforms.
One of the primary considerations for choosing this particular set of primitives is that they can be implemented `*safely`* with relatively few pitfalls, on practically all current computing platforms.
The primitives listed here **are authoritative**. Anything claiming to be Reticulum, but not using these exact primitives **is not** Reticulum, and possibly an intentionally compromised or weakened clone. The utilised primitives are:
The primitives listed here `!are authoritative`!. Anything `*claiming`* to be Reticulum, but not using these exact primitives `FTA35050`!is not`!`f Reticulum, and possibly an intentionally compromised or weakened clone. The utilised primitives are:
• Reticulum Identity Keys are 512-bit Curve25519 keysets
• A 256-bit Ed25519 key for signatures
• A 256-bit X22519 key for ECDH key exchanges
• HKDF for key derivation
• Encrypted tokens are based on the [Fernet spec](https://github.com/fernet/spec/)
• Encrypted tokens are based on the `_`!`[Fernet spec`https://github.com/fernet/spec/]`!`_
• Ephemeral keys derived from an ECDH key exchange on Curve25519
• HMAC using SHA256 for message authentication
• IVs must be generated through `B333os.urandom()`b or better
@@ -234,36 +245,37 @@ The primitives listed here **are authoritative**. Anything claiming to be Reticu
• SHA-256
• SHA-512
In the default installation configuration, the `B333X25519`b, `B333Ed25519`b, and `B333AES-256-CBC`b primitives are provided by [OpenSSL](https://www.openssl.org/) (via the [PyCA/cryptography](https://github.com/pyca/cryptography) package). The hashing functions `B333SHA-256`b and `B333SHA-512`b are provided by the standard Python [hashlib](https://docs.python.org/3/library/hashlib.html). The `B333HKDF`b, `B333HMAC`b, `B333Token`b primitives, and the `B333PKCS7`b padding function are always provided by the following internal implementations:
In the default installation configuration, the `B333X25519`b, `B333Ed25519`b, and `B333AES-256-CBC`b primitives are provided by `_`!`[OpenSSL`https://www.openssl.org/]`!`_ (via the `_`!`[PyCA/cryptography`https://github.com/pyca/cryptography]`!`_ package). The hashing functions `B333SHA-256`b and `B333SHA-512`b are provided by the standard Python `_`!`[hashlib`https://docs.python.org/3/library/hashlib.html]`!`_. The `B333HKDF`b, `B333HMAC`b, `B333Token`b primitives, and the `B333PKCS7`b padding function are always provided by the following internal implementations:
• [HKDF.py](RNS/Cryptography/HKDF.py)
• [HMAC.py](RNS/Cryptography/HMAC.py)
• [Token.py](RNS/Cryptography/Token.py)
• [PKCS7.py](RNS/Cryptography/PKCS7.py)
• `_`!`[HKDF.py`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=RNS/Cryptography/HKDF.py]`!`_
• `_`!`[HMAC.py`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=RNS/Cryptography/HMAC.py]`!`_
• `_`!`[Token.py`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=RNS/Cryptography/Token.py]`!`_
• `_`!`[PKCS7.py`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=RNS/Cryptography/PKCS7.py]`!`_
Reticulum also includes a complete implementation of all necessary primitives in pure Python. If OpenSSL and PyCA are not available on the system when Reticulum is started, Reticulum will instead use the internal pure-python primitives. A trivial consequence of this is performance, with the OpenSSL backend being *much* faster. The most important consequence however, is the potential loss of security by using primitives that has not seen the same amount of scrutiny, testing and review as those from OpenSSL.
Reticulum also includes a complete implementation of all necessary primitives in pure Python. If OpenSSL and PyCA are not available on the system when Reticulum is started, Reticulum will instead use the internal pure-python primitives. A trivial consequence of this is performance, with the OpenSSL backend being `*much`* faster. The most important consequence however, is the potential loss of security by using primitives that has not seen the same amount of scrutiny, testing and review as those from OpenSSL.
Please note that by default, installing Reticulum will **require** OpenSSL and PyCA to also be automatically installed if not already available. It is only possible to use the pure-python primitives if this requirement is specifically overridden by the user, for example by installing the `B333rnspure`b package instead of the normal `B333rns`b package, or by running directly from local source-code.
Please note that by default, installing Reticulum will `!require`! OpenSSL and PyCA to also be automatically installed if not already available. It is only possible to use the pure-python primitives if this requirement is specifically overridden by the user, for example by installing the `B333rnspure`b package instead of the normal `B333rns`b package, or by running directly from local source-code.
If you want to use the internal pure-python primitives, it is **highly advisable** that you have a good understanding of the risks that this pose, and make an informed decision on whether those risks are acceptable to you.
If you want to use the internal pure-python primitives, it is `!highly advisable`! that you have a good understanding of the risks that this pose, and make an informed decision on whether those risks are acceptable to you.
Reticulum is relatively young software, and should be considered as such. While it has been built with cryptography best-practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy or security breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
>> Acknowledgements & Credits
Reticulum can only exist because of the mountain of Open Source work it was built on top of, the contributions of everyone involved, and everyone that has supported the project through the years. To everyone who has helped, thank you so much.
A number of other modules and projects are either part of, or used by Reticulum. Sincere thanks to the authors and contributors of the following projects:
• [PyCA/cryptography](https://github.com/pyca/cryptography), *BSD License*
• [Pure-25519](https://github.com/warner/python-pure25519) by [Brian Warner](https://github.com/warner), *MIT License*
• [Pysha2](https://github.com/thomdixon/pysha2) by [Thom Dixon](https://github.com/thomdixon), *MIT License*
• [Python AES-128](https://github.com/orgurar/python-aes) by [Or Gur Arie](https://github.com/orgurar), *MIT License*
• [Python AES-256](https://github.com/boppreh/aes) by [BoppreH](https://github.com/boppreh), *MIT License*
• [Curve25519.py](https://gist.github.com/nickovs/cc3c22d15f239a2640c185035c06f8a3#file-curve25519-py) by [Nicko van Someren](https://gist.github.com/nickovs), *Public Domain*
• [I2Plib](https://github.com/l-n-s/i2plib) by [Viktor Villainov](https://github.com/l-n-s)
• [PySerial](https://github.com/pyserial/pyserial) by Chris Liechti, *BSD License*
• [Configobj](https://github.com/DiffSK/configobj) by Michael Foord, Nicola Larosa, Rob Dennis & Eli Courtwright, *BSD License*
• [ifaddr](https://github.com/pydron/ifaddr) by Stefan C. Mueller, *MIT License*
• [Umsgpack.py](https://github.com/vsergeev/u-msgpack-python) by [Ivan A. Sergeev](https://github.com/vsergeev)
• [rnsh](https://github.com/acehoss/rnsh) by [Aaron Heise](https://github.com/acehoss)
• [Python](https://www.python.org)
• `_`!`[PyCA/cryptography`https://github.com/pyca/cryptography]`!`_, `*BSD License`*
• `_`!`[Pure-25519`https://github.com/warner/python-pure25519]`!`_, by `_`!`[Brian Warner`https://github.com/warner]`!`_, `*MIT License`*
• `_`!`[Pysha2`https://github.com/thomdixon/pysha2]`!`_ by `_`!`[Thom Dixon`https://github.com/thomdixon]`!`_, `*MIT License`*
• `_`!`[Python AES-128`https://github.com/orgurar/python-aes]`!`_ by `_`!`[Or Gur Arie`https://github.com/orgurar]`!`_, `*MIT License`*
• `_`!`[Python AES-256`https://github.com/boppreh/aes]`!`_ by `_`!`[BoppreH`https://github.com/boppreh]`!`_, `*MIT License`*
• `_`!`[Curve25519.py`https://gist.github.com/nickovs/cc3c22d15f239a2640c185035c06f8a3]`!`_ by `_`!`[Nicko van Someren`https://gist.github.com/nickovs]`!`_, `*Public Domain`*
• `_`!`[I2Plib`https://github.com/l-n-s/i2plib]`!`_ by `_`!`[Viktor Villainov`https://github.com/l-n-s]`!`_
• `_`!`[PySerial`https://github.com/pyserial/pyserial]`!`_ by Chris Liechti, `*BSD License`*
• `_`!`[Configobj`https://github.com/DiffSK/configobj]`!`_ by Michael Foord, Nicola Larosa, Rob Dennis & Eli Courtwright, `*BSD License`*
• `_`!`[ifaddr`https://github.com/pydron/ifaddr]`!`_ by Stefan C. Mueller, `*MIT License`*
• `_`!`[Umsgpack.py`https://github.com/vsergeev/u-msgpack-python]`!`_ by `_`!`[Ivan A. Sergeev`https://github.com/vsergeev]`!`_
• `_`!`[rnsh`https://github.com/acehoss/rnsh]`!`_ by `_`!`[Aaron Heise`https://github.com/acehoss]`!`_
• `_`!`[Python`https://www.python.org]`!`_
+5 -4
View File
@@ -53,7 +53,8 @@ class StreamDataMessage(MessageBase):
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
"""
When the Buffer package is imported, this value is
@@ -226,7 +227,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
self._stream_id = stream_id
self._channel = channel
self._eof = False
self._mdu = channel.mdu - StreamDataMessage.OVERHEAD
self._mdu = channel.mdu - StreamDataMessage.HEADER_LEN
def write(self, __b: bytes) -> int | None:
try:
@@ -242,7 +243,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
chunk_segment_length = int(chunk_len/comp_try)
compressed_chunk = bz2.compress(__b[:chunk_segment_length])
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
break
else:
@@ -252,7 +253,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
chunk = compressed_chunk
processed_length = chunk_segment_length
else:
chunk = bytes(__b[:StreamDataMessage.MAX_DATA_LEN])
chunk = bytes(__b[:self._mdu])
processed_length = len(chunk)
message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success)
+129 -227
View File
@@ -45,63 +45,6 @@ TPacket = TypeVar("TPacket")
class SystemMessageTypes(enum.IntEnum):
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):
"""
ChannelException type codes
@@ -113,7 +56,6 @@ class CEType(enum.IntEnum):
ME_ALREADY_SENT = 4
ME_TOO_BIG = 5
class ChannelException(Exception):
"""
An exception thrown by Channel, with a type code.
@@ -122,7 +64,6 @@ class ChannelException(Exception):
super().__init__(args)
self.type = ce_type
class MessageState(enum.IntEnum):
"""
Set of possible states for a Message
@@ -132,7 +73,6 @@ class MessageState(enum.IntEnum):
MSGSTATE_DELIVERED = 2
MSGSTATE_FAILED = 3
class MessageBase(abc.ABC):
"""
Base type for any messages sent or received on a Channel.
@@ -144,7 +84,7 @@ class MessageBase(abc.ABC):
MSGTYPE = None
"""
Defines a unique identifier for a message class.
* Must be unique within all classes registered with a ``Channel``
* Must be less than ``0xf000``. Values greater than or equal to ``0xf000`` are reserved.
"""
@@ -170,7 +110,6 @@ class MessageBase(abc.ABC):
MessageCallbackType = NewType("MessageCallbackType", Callable[[MessageBase], bool])
class Envelope:
"""
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])
raw = self.raw[6:]
ctor = message_factories.get(msgtype, None)
if ctor is None:
raise ChannelException(CEType.ME_NOT_REGISTERED, f"Unable to find constructor for Channel MSGTYPE {hex(msgtype)}")
if ctor is None: raise ChannelException(CEType.ME_NOT_REGISTERED, f"Unable to find constructor for Channel MSGTYPE {hex(msgtype)}")
message = ctor()
message.unpack(raw)
self.unpacked = True
@@ -190,14 +128,13 @@ class Envelope:
return message
def pack(self) -> bytes:
if self.message.__class__.MSGTYPE is None:
raise ChannelException(CEType.ME_NO_MSG_TYPE, f"{self.message.__class__} lacks MSGTYPE")
if self.message.__class__.MSGTYPE is None: raise ChannelException(CEType.ME_NO_MSG_TYPE, f"{self.message.__class__} lacks MSGTYPE")
data = self.message.pack()
self.raw = struct.pack(">HHH", self.message.MSGTYPE, self.sequence, len(data)) + data
self.packed = True
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.id = id(self)
self.message = message
@@ -255,11 +192,11 @@ class Channel(contextlib.AbstractContextManager):
# The maximum window size for transfers on fast links
WINDOW_MAX_FAST = 48
# For calculating maps and guard segments, this
# must be set to the global maximum window.
WINDOW_MAX = WINDOW_MAX_FAST
# If the fast rate is sustained for this many request
# rounds, the fast link window size will be allowed.
FAST_RATE_THRESHOLD = 10
@@ -278,13 +215,14 @@ class Channel(contextlib.AbstractContextManager):
SEQ_MAX = 0xFFFF
SEQ_MODULUS = SEQ_MAX+1
def __init__(self, outlet: ChannelOutletBase):
def __init__(self, outlet: LinkChannelOutlet):
"""
@param outlet:
"""
self._outlet = outlet
self._lock = threading.RLock()
self._send_lock = threading.Lock()
self._tx_ring: collections.deque[Envelope] = collections.deque()
self._rx_ring: collections.deque[Envelope] = collections.deque()
self._message_callbacks: [MessageCallbackType] = []
@@ -306,11 +244,9 @@ class Channel(contextlib.AbstractContextManager):
self.window_min = Channel.WINDOW_MIN
self.window_flexibility = Channel.WINDOW_FLEXIBILITY
def __enter__(self) -> Channel:
return self
def __enter__(self) -> Channel: return self
def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None,
__traceback: TracebackType | None) -> bool | None:
def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None) -> bool | None:
self._shutdown()
return False
@@ -326,20 +262,13 @@ class Channel(contextlib.AbstractContextManager):
def _register_message_type(self, message_class: Type[MessageBase], *, is_system_type: bool = False):
with self._lock:
if not issubclass(message_class, MessageBase):
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
f"{message_class} is not a subclass of {MessageBase}.")
if message_class.MSGTYPE is None:
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
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()
if not issubclass(message_class, MessageBase): raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} is not a subclass of {MessageBase}.")
if message_class.MSGTYPE is None: raise ChannelException(CEType.ME_INVALID_MSG_TYPE, 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:
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
f"{message_class} raised an exception when constructed with no arguments: {ex}")
raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} raised an exception when constructed with no arguments: {ex}")
self._message_factories[message_class.MSGTYPE] = message_class
@@ -382,27 +311,30 @@ class Channel(contextlib.AbstractContextManager):
if envelope.packet is not None:
self._outlet.set_packet_timeout_callback(envelope.packet, None)
self._outlet.set_packet_delivered_callback(envelope.packet, None)
envelope.tracked = False
for envelope in self._rx_ring:
envelope.tracked = False
self._tx_ring.clear()
self._rx_ring.clear()
def _emplace_envelope(self, envelope: Envelope, ring: collections.deque[Envelope]) -> bool:
with self._lock:
i = 0
for existing in ring:
for existing in ring:
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
if envelope.sequence < existing.sequence and not (self._next_rx_sequence - envelope.sequence) > (Channel.SEQ_MAX//2):
ring.insert(i, envelope)
envelope.tracked = True
return True
i += 1
envelope.tracked = True
ring.append(envelope)
@@ -413,10 +345,8 @@ class Channel(contextlib.AbstractContextManager):
for cb in cbs:
try:
if cb(message):
return
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)
if cb(message): 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)
def _receive(self, raw: bytes):
try:
@@ -428,16 +358,20 @@ class Channel(contextlib.AbstractContextManager):
window_overflow = (self._next_rx_sequence+Channel.WINDOW_MAX) % Channel.SEQ_MODULUS
if window_overflow < self._next_rx_sequence:
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
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
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)
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
else:
with self._lock:
@@ -453,11 +387,9 @@ class Channel(contextlib.AbstractContextManager):
self._next_rx_sequence = (self._next_rx_sequence + 1) % Channel.SEQ_MODULUS
for e in contigous:
if not e.unpacked:
m = e.unpack(self._message_factories)
else:
m = e.message
if not e.unpacked: m = e.unpack(self._message_factories)
else: m = e.message
self._rx_ring.remove(e)
self._run_callbacks(m)
@@ -470,67 +402,46 @@ class Channel(contextlib.AbstractContextManager):
:return: True if ready
"""
if not self._outlet.is_usable:
return False
if not self._outlet.is_usable: return False
with self._lock:
outstanding = 0
for envelope in self._tx_ring:
if envelope.outlet == self._outlet:
if envelope.outlet == self._outlet:
if not envelope.packet or not self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED:
outstanding += 1
if outstanding >= self.window:
return False
if outstanding >= self.window: return False
return True
def _packet_tx_op(self, packet: TPacket, op: Callable[[TPacket], bool]):
target_id = self._outlet.get_packet_id(packet)
with self._lock:
envelope = next(filter(lambda e: self._outlet.get_packet_id(e.packet) == self._outlet.get_packet_id(packet),
self._tx_ring), 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)
if envelope and op(envelope):
envelope.tracked = False
if envelope in self._tx_ring:
self._tx_ring.remove(envelope)
if self.window < self.window_max:
self.window += 1
# TODO: Remove at some point
# RNS.log("Increased "+str(self)+" window to "+str(self.window), RNS.LOG_DEBUG)
if self.window < self.window_max: self.window += 1
if self._outlet.rtt != 0:
if self._outlet.rtt > Channel.RTT_FAST:
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:
self.medium_rate_rounds += 1
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_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:
self.fast_rate_rounds += 1
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_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 not envelope:
RNS.log("Spurious message received on "+str(self), RNS.LOG_EXTREME)
else: RNS.log("Envelope not found in TX ring for "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
if not envelope: RNS.log("Spurious message received on "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
def _packet_delivered(self, packet: TPacket):
self._packet_tx_op(packet, lambda env: True)
@@ -539,44 +450,47 @@ class Channel(contextlib.AbstractContextManager):
for envelope in self._tx_ring:
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 updated_timeout > envelope.packet.receipt.timeout:
envelope.packet.receipt.set_timeout(updated_timeout)
if updated_timeout > envelope.packet.receipt.timeout: envelope.packet.receipt.set_timeout(updated_timeout)
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)
return to
def _packet_timeout(self, packet: TPacket):
def retry_envelope(envelope: Envelope) -> bool:
if envelope.tries >= self._max_tries:
RNS.log("Retry count exceeded on "+str(self)+", tearing down Link.", RNS.LOG_ERROR)
self._shutdown() # start on separate thread?
self._outlet.timed_out()
return True
if self._outlet.get_packet_state(packet) == MessageState.MSGSTATE_DELIVERED: return
envelope.tries += 1
self._outlet.resend(envelope.packet)
self._outlet.set_packet_delivered_callback(envelope.packet, self._packet_delivered)
self._outlet.set_packet_timeout_callback(envelope.packet, self._packet_timeout, self._get_packet_timeout_time(envelope.tries))
self._update_packet_timeouts()
target_id = self._outlet.get_packet_id(packet)
envelope_to_resend: Envelope | None = None
should_teardown = False
with self._lock:
envelope = next(filter(lambda e: e.packet is not None and self._outlet.get_packet_id(e.packet) == target_id, self._tx_ring), None)
if envelope is None: return
if self.window > self.window_min:
self.window -= 1
# TODO: Remove at some point
# RNS.log("Decreased "+str(self)+" window to "+str(self.window), RNS.LOG_DEBUG)
if envelope.tries >= self._max_tries: should_teardown = True
else:
envelope.tries += 1
envelope_to_resend = envelope
if self.window_max > (self.window_min+self.window_flexibility):
self.window_max -= 1
# TODO: Remove at some point
# RNS.log("Decreased "+str(self)+" max window to "+str(self.window_max), RNS.LOG_DEBUG)
if self.window > self.window_min:
self.window -= 1
if self.window_max > (self.window_min+self.window_flexibility):
self.window_max -= 1
# TODO: Remove at some point
# RNS.log("Decreased "+str(self)+" window to "+str(self.window), RNS.LOG_EXTREME)
if should_teardown:
RNS.log("Retry count exceeded on "+str(self)+", tearing down Link.", RNS.LOG_ERROR)
self._shutdown()
self._outlet.timed_out()
return
return False
if envelope_to_resend is not None:
self._outlet.resend(envelope_to_resend.packet)
with self._lock:
self._outlet.set_packet_delivered_callback(envelope_to_resend.packet, self._packet_delivered)
self._outlet.set_packet_timeout_callback(envelope_to_resend.packet, self._packet_timeout, self._get_packet_timeout_time(envelope_to_resend.tries))
self._update_packet_timeouts()
already_delivered = (self._outlet.get_packet_state(envelope_to_resend.packet) == MessageState.MSGSTATE_DELIVERED)
if self._outlet.get_packet_state(packet) != MessageState.MSGSTATE_DELIVERED:
self._packet_tx_op(packet, retry_envelope)
if already_delivered: self._packet_delivered(envelope_to_resend.packet)
def send(self, message: MessageBase) -> Envelope:
"""
@@ -585,27 +499,33 @@ class Channel(contextlib.AbstractContextManager):
:param message: an instance of a ``MessageBase`` subclass
"""
envelope: Envelope | None = None
with self._lock:
if not self.is_ready_to_send():
raise ChannelException(CEType.ME_LINK_NOT_READY, f"Link is not ready")
envelope = Envelope(self._outlet, message=message, sequence=self._next_sequence)
self._next_sequence = (self._next_sequence + 1) % Channel.SEQ_MODULUS
self._emplace_envelope(envelope, self._tx_ring)
with self._send_lock:
with self._lock:
if not self.is_ready_to_send(): raise ChannelException(CEType.ME_LINK_NOT_READY, f"Link is not ready")
if envelope is None:
raise BlockingIOError()
reserved_sequence = self._next_sequence
envelope = Envelope(self._outlet, message=message, sequence=reserved_sequence)
envelope.pack()
if len(envelope.raw) > self._outlet.mdu:
raise ChannelException(CEType.ME_TOO_BIG, f"Packed message too big for packet: {len(envelope.raw)} > {self._outlet.mdu}")
self._next_sequence = (reserved_sequence + 1) % Channel.SEQ_MODULUS
envelope.pack()
if len(envelope.raw) > self._outlet.mdu:
raise ChannelException(CEType.ME_TOO_BIG, f"Packed message too big for packet: {len(envelope.raw)} > {self._outlet.mdu}")
envelope.packet = self._outlet.send(envelope.raw)
envelope.tries += 1
self._outlet.set_packet_delivered_callback(envelope.packet, self._packet_delivered)
self._outlet.set_packet_timeout_callback(envelope.packet, self._packet_timeout, self._get_packet_timeout_time(envelope.tries))
self._update_packet_timeouts()
envelope.packet = self._outlet.send(envelope.raw)
if envelope.packet is None or getattr(envelope.packet, "raw", None) is None 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")
with self._lock:
self._emplace_envelope(envelope, self._tx_ring)
envelope.tries += 1
self._outlet.set_packet_delivered_callback(envelope.packet, self._packet_delivered)
self._outlet.set_packet_timeout_callback(envelope.packet, self._packet_timeout, self._get_packet_timeout_time(envelope.tries))
self._update_packet_timeouts()
already_delivered = (self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED)
# Prevent _tx_ring envelope leak
if already_delivered: self._packet_delivered(envelope.packet)
return envelope
@@ -620,14 +540,13 @@ class Channel(contextlib.AbstractContextManager):
:return: number of bytes available
"""
mdu = self._outlet.mdu - 6 # sizeof(msgtype) + sizeof(length) + sizeof(sequence)
if mdu > 0xFFFF:
mdu = 0xFFFF
if mdu > 0xFFFF: mdu = 0xFFFF
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
Packets.
@@ -638,68 +557,51 @@ class LinkChannelOutlet(ChannelOutletBase):
def send(self, raw: bytes) -> RNS.Packet:
packet = RNS.Packet(self.link, raw, context=RNS.Packet.CHANNEL)
if self.link.status == RNS.Link.ACTIVE:
packet.send()
if self.link.status == RNS.Link.ACTIVE: packet.send()
return packet
def resend(self, packet: RNS.Packet) -> RNS.Packet:
receipt = packet.resend()
if not receipt:
RNS.log("Failed to resend packet", RNS.LOG_ERROR)
if not receipt: RNS.log("Failed to resend packet", RNS.LOG_ERROR)
return packet
@property
def mdu(self):
return self.link.mdu
def mdu(self): return self.link.mdu
@property
def rtt(self):
return self.link.rtt
def rtt(self): 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
def is_usable(self):
return True # had issues looking at Link.status
def is_usable(self): return True
def get_packet_state(self, packet: TPacket) -> MessageState:
if packet.receipt == None:
return MessageState.MSGSTATE_FAILED
status = packet.receipt.get_status()
if status == RNS.PacketReceipt.SENT:
return MessageState.MSGSTATE_SENT
if status == RNS.PacketReceipt.DELIVERED:
return MessageState.MSGSTATE_DELIVERED
if status == RNS.PacketReceipt.FAILED:
return MessageState.MSGSTATE_FAILED
else:
raise Exception(f"Unexpected receipt state: {status}")
if status == RNS.PacketReceipt.SENT: return MessageState.MSGSTATE_SENT
if status == RNS.PacketReceipt.DELIVERED: return MessageState.MSGSTATE_DELIVERED
if status == RNS.PacketReceipt.FAILED: return MessageState.MSGSTATE_FAILED
else: raise Exception(f"Unexpected receipt state: {status}")
def timed_out(self):
self.link.teardown()
def __str__(self):
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_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 inner(receipt: RNS.PacketReceipt):
callback(packet)
if packet and packet.receipt:
packet.receipt.set_delivery_callback(inner if callback else None)
def inner(receipt: RNS.PacketReceipt): callback(packet)
if packet and packet.receipt: packet.receipt.set_delivery_callback(inner if callback else None)
def get_packet_id(self, packet: RNS.Packet) -> any:
if packet and hasattr(packet, "get_hash") and callable(packet.get_hash):
if packet and getattr(packet, "raw", None) is not None and hasattr(packet, "get_hash") and callable(packet.get_hash):
return packet.get_hash()
else:
return None
else: return None
def timed_out(self): self.link.teardown()
def __str__(self): return f"{self.__class__.__name__}({self.link})"
+4 -4
View File
@@ -43,7 +43,7 @@ elif cp.PROVIDER == cp.PROVIDER_PYCA:
class AES_128_CBC:
@staticmethod
def encrypt(plaintext, key, iv):
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for AES_128_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key)
return cipher.encrypt(plaintext, iv)
@@ -60,7 +60,7 @@ class AES_128_CBC:
@staticmethod
def decrypt(ciphertext, key, iv):
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for AES_128_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key)
return cipher.decrypt(ciphertext, iv)
@@ -78,7 +78,7 @@ class AES_128_CBC:
class AES_256_CBC:
@staticmethod
def encrypt(plaintext, key, iv):
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for AES_256_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key)
return cipher.encrypt_cbc(plaintext, iv)
@@ -95,7 +95,7 @@ class AES_256_CBC:
@staticmethod
def decrypt(ciphertext, key, iv):
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for AES_256_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key)
return cipher.decrypt_cbc(ciphertext, iv)
-1
View File
@@ -35,7 +35,6 @@ class Ed25519PrivateKey:
def __init__(self, seed):
self.seed = seed
self.sk = ed25519.SigningKey(self.seed)
#self.vk = self.sk.get_verifying_key()
@classmethod
def generate(cls):
+51
View File
@@ -32,8 +32,59 @@ import hashlib
from math import ceil
from RNS.Cryptography import HMAC
# Precomputed byte-permutation tables used to key the inner
# and outer hashing states of the HMAC construction
trans_5C = bytes((x ^ 0x5C) for x in range(256))
trans_36 = bytes((x ^ 0x36) for x in range(256))
# Precomputed HKDF counter bytes
_counters = [bytes([(i + 1) % 0x100]) for i in range(0x100)]
def hkdf(length=None, derive_from=None, salt=None, context=None):
hash_len = 32
hash_block_size = 64
if length == None or length < 1: raise ValueError("Invalid output key length")
if derive_from == None or derive_from == "": raise ValueError("Cannot derive key from empty input material")
if salt == None or len(salt) == 0: salt = bytes([0] * hash_len)
if context == None: context = b""
pseudorandom_key = HMAC.new(salt, derive_from).digest()
# The pseudorandom key is always a 32-byte SHA-256 digest, so the
# HMAC key schedule below never needs the long-key hashing branch.
key = pseudorandom_key.ljust(hash_block_size, b"\x00")
# Precompute the keyed inner and outer hashing states of the
# HMAC construction once. Each expansion block then only requires
# two cheap hash-object copies instead of constructing a complete
# HMAC object per 32 bytes of output. This is possible since the
# PRK is **always** 32-byte SHA-256 HMAC output.
inner_state = hashlib.sha256(key.translate(trans_36))
outer_state = hashlib.sha256(key.translate(trans_5C))
# Expand
has_context = len(context) > 0
block = b""
derived = bytearray()
for i in range(ceil(length / hash_len)):
inner = inner_state.copy()
inner.update(block)
if has_context: inner.update(context)
inner.update(_counters[i & 0xFF])
outer = outer_state.copy()
outer.update(inner.digest())
block = outer.digest()
derived += block
return bytes(derived[:length])
def hkdf_legacy(length=None, derive_from=None, salt=None, context=None):
hash_len = 32
def hmac_sha256(key, data):
return HMAC.new(key, data).digest()
+6 -1
View File
@@ -180,4 +180,9 @@ def digest(key, msg, digest):
outer.update(key.translate(trans_5C))
inner.update(msg)
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
+6
View File
@@ -62,3 +62,9 @@ def sha512(data):
digest.update(data)
return digest.digest()
def file_sha256(file):
if not hashlib: raise SystemError("The hashlib module is not available on this system")
# TODO: Could implement fallback for old snakes here
if not hasattr(hashlib, "file_digest"): raise SystemError("The file_digest method is not available on this system. This functionality requires Python 3.11 or later.")
else: return hashlib.file_digest(file, "sha256").digest()
+1 -1
View File
@@ -80,7 +80,7 @@ class Token():
received_hmac = token[-32:]
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
+4 -2
View File
@@ -52,5 +52,7 @@ elif cp.PROVIDER == cp.PROVIDER_PYCA:
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+16 -5
View File
@@ -155,6 +155,7 @@ class Destination:
self.accept_link_requests = True
self.callbacks = Callbacks()
self.request_handlers = {}
self.max_request_size = None
self.type = type
self.direction = direction
self.proof_strategy = Destination.PROVE_NONE
@@ -205,7 +206,7 @@ class Destination:
def _clean_ratchets(self):
if self.ratchets != None:
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):
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.
"""
if not proof_strategy in Destination.proof_strategies:
raise TypeError("Unsupported proof strategy")
else:
self.proof_strategy = proof_strategy
if not proof_strategy in Destination.proof_strategies: raise TypeError("Unsupported 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):
"""
+228 -69
View File
@@ -6,10 +6,20 @@ import random
import threading
import ipaddress
import subprocess
from threading import Lock
from .vendor import umsgpack as msgpack
from collections import deque
# Discoverable interfaces must include a short,
# unique implementation-specific identifier and
# version tag in announced discovery information.
IMPLEMENTATION_NAME = "RNS"
from RNS._version import __version__ as RNS_VERSION
NAME = 0xFF
TRANSPORT_ID = 0xFE
TRANSPORT_IMPL = 0xFD
TRANSPORT_VERS = 0xFC
INTERFACE_TYPE = 0x00
TRANSPORT = 0x01
REACHABLE_ON = 0x02
@@ -25,12 +35,13 @@ SPREADINGFACTOR = 0x0B
CODINGRATE = 0x0C
MODULATION = 0x0D
CHANNEL = 0x0E
OP_ADDR = 0xF0
APP_NAME = "rnstransport"
class InterfaceAnnouncer():
JOB_INTERVAL = 60
DEFAULT_STAMP_VALUE = 14
DEFAULT_STAMP_VALUE = 16
WORKBLOCK_EXPAND_ROUNDS = 20
DISCOVERABLE_INTERFACE_TYPES = ["BackboneInterface", "TCPServerInterface", "TCPClientInterface",
@@ -86,6 +97,7 @@ class InterfaceAnnouncer():
RNS.trace_exception(e)
def sanitize(self, in_str):
if in_str == None: return None
sanitized = in_str.replace("\n", "")
sanitized = sanitized.replace("\r", "")
sanitized = sanitized.strip()
@@ -97,20 +109,52 @@ class InterfaceAnnouncer():
if not interface_type in self.DISCOVERABLE_INTERFACE_TYPES: return None
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
info = {INTERFACE_TYPE: interface_type,
TRANSPORT: RNS.Reticulum.transport_enabled(),
TRANSPORT_ID: RNS.Transport.identity.hash,
TRANSPORT_IMPL: IMPLEMENTATION_NAME,
TRANSPORT_VERS: RNS_VERSION,
NAME: self.sanitize(interface.discovery_name),
LATITUDE: interface.discovery_latitude,
LONGITUDE: interface.discovery_longitude,
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:
RNS.log(f"Invalid interface discovery configuration for {interface}, aborting discovery announce", RNS.LOG_ERROR)
return None
if interface_type in ["BackboneInterface", "TCPServerInterface"]:
if not interface.reachable_on: return None
reachable_on = self.sanitize(interface.reachable_on)
if not RNS.vendor.platformutils.is_windows():
@@ -195,10 +239,23 @@ class InterfaceAnnounceHandler:
RNS.log("You can install it with the command: pip install lxmf", RNS.LOG_CRITICAL)
RNS.panic()
self.aspect_filter = APP_NAME+".discovery.interface"
self.required_value = required_value
self.callback = callback
self.stamper = LXStamper
self.aspect_filter = APP_NAME+".discovery.interface"
self.required_value = required_value
self.callback = callback
self.stamper = LXStamper
self.valid_cache = {}
self.valid_cache_max = 2048
self.invalid_cache = deque(maxlen=2048)
self.validation_lock = threading.Lock()
@staticmethod
def sanitize_name(name):
if not name: return None
name = name.encode("ascii", "ignore").decode("ascii").strip()
for i in [5,3,2]: name = name.replace(" "*i, " ")
while len(name) and name[0] not in san_map: name = name[1:]
while len(name) and name[-1] not in san_map+")": name = name[:-1]
return name
def received_announce(self, destination_hash, announced_identity, app_data):
try:
@@ -212,21 +269,43 @@ class InterfaceAnnounceHandler:
app_data = app_data[1:]
signed = flags & self.FLAG_SIGNED
encrypted = flags & self.FLAG_ENCRYPTED
fullhash = RNS.Identity.full_hash(app_data)
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 fullhash in self.invalid_cache:
RNS.log(f"Ignored previously discovered interface with insufficient stamp value", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
return
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)
if fullhash in self.valid_cache:
RNS.log(f"Discovery announce cache hit", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
cache_entry = self.valid_cache[fullhash]
stamp = cache_entry["stamp"]
packed = cache_entry["packed"]
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:
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
if value < self.required_value: RNS.log(f"Ignored discovered interface with stamp value {value}", RNS.LOG_DEBUG)
@@ -234,10 +313,24 @@ class InterfaceAnnounceHandler:
info = None
unpacked = msgpack.unpackb(packed)
if INTERFACE_TYPE in unpacked:
interface_type = unpacked[INTERFACE_TYPE]
interface_type = unpacked[INTERFACE_TYPE]
name = self.sanitize_name(unpacked[NAME])
if type(unpacked[TRANSPORT]) != bool: raise ValueError("Invalid data in transport field of announce")
if type(unpacked[LATITUDE]) not in [type(None), float]: raise ValueError("Invalid data in latitude field of announce")
if type(unpacked[LONGITUDE]) not in [type(None), float]: raise ValueError("Invalid data in longitude field of announce")
if type(unpacked[HEIGHT]) not in [type(None), float]: raise ValueError("Invalid data in height field of announce")
if len(unpacked[TRANSPORT_ID]) != RNS.Identity.TRUNCATED_HASHLENGTH//8: raise ValueError("Invalid data in transport_id field of announce")
if not interface_type in InterfaceAnnouncer.DISCOVERABLE_INTERFACE_TYPES:
raise ValueError("Invalid interface type in announce data")
if REACHABLE_ON in unpacked:
if not (is_ip_address(unpacked[REACHABLE_ON]) or is_hostname(unpacked[REACHABLE_ON])):
raise ValueError("Invalid data in reachable_on field of announce")
info = {"type": interface_type,
"transport": unpacked[TRANSPORT],
"name": unpacked[NAME] or f"Discovered {interface_type}",
"name": name or f"Discovered {interface_type}",
"received": time.time(),
"stamp": stamp,
"value": value,
@@ -248,15 +341,11 @@ class InterfaceAnnounceHandler:
"longitude": unpacked[LONGITUDE],
"height": unpacked[HEIGHT]}
if REACHABLE_ON in unpacked:
if not (is_ip_address(unpacked[REACHABLE_ON]) or is_hostname(unpacked[REACHABLE_ON])):
raise ValueError("Invalid data in reachable_on field of announce")
if IFAC_NETNAME in unpacked: info["ifac_netname"] = unpacked[IFAC_NETNAME]
if IFAC_NETKEY in unpacked: info["ifac_netkey"] = unpacked[IFAC_NETKEY]
if IFAC_NETNAME in unpacked: info["ifac_netname"] = str(unpacked[IFAC_NETNAME])
if IFAC_NETKEY in unpacked: info["ifac_netkey"] = str(unpacked[IFAC_NETKEY])
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["port"] = unpacked[PORT]
connection_interface = "BackboneInterface" if backbone_support else "TCPClientInterface"
@@ -335,6 +424,11 @@ class InterfaceAnnounceHandler:
discovery_hash_material = info["transport_id"]+info["name"]
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)
except Exception as e:
@@ -355,6 +449,11 @@ class InterfaceDiscovery():
AUTOCONNECT_TYPES = ["BackboneInterface", "TCPServerInterface"]
DISCOVERABLE_TYPES = ["BackboneInterface", "TCPServerInterface", "I2PInterface", "RNodeInterface", "WeaveInterface", "KISSInterface"]
AC_TRANSPORT_MODE = RNS.Interfaces.Interface.Interface.MODE_GATEWAY
AC_GRAVITY = 0
discovery_lock = Lock()
def __init__(self, required_value=InterfaceAnnouncer.DEFAULT_STAMP_VALUE, callback=None, discover_interfaces=True):
if not required_value: required_value = InterfaceAnnouncer.DEFAULT_STAMP_VALUE
@@ -366,6 +465,8 @@ class InterfaceDiscovery():
self.monitor_interval = self.MONITOR_INTERVAL
self.detach_threshold = self.DETACH_THRESHOLD
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")
self.storagepath = os.path.join(RNS.Reticulum.storagepath, "discovery", "interfaces")
@@ -376,21 +477,36 @@ class InterfaceDiscovery():
RNS.Transport.register_announce_handler(self.handler)
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):
now = time.time()
discovered_interfaces = []
discovery_sources = RNS.Reticulum.interface_discovery_sources()
blackholed_identities = self.__blackholed_identities()
for filename in os.listdir(self.storagepath):
try:
filepath = os.path.join(self.storagepath, filename)
with open(filepath, "rb") as f: info = msgpack.unpackb(f.read())
with self.discovery_lock:
filepath = os.path.join(self.storagepath, filename)
with open(filepath, "rb") as f: info = msgpack.unpackb(f.read())
should_remove = False
heard_delta = now-info["last_heard"]
heard_delta = now-info["last_heard"]
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 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 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:
if not (is_ip_address(info["reachable_on"]) or is_hostname(info["reachable_on"])): should_remove = True
@@ -414,8 +530,8 @@ class InterfaceDiscovery():
if should_append: discovered_interfaces.append(info)
except Exception as e:
RNS.log(f"Error while loading discovered interface data: {e}", RNS.LOG_ERROR)
RNS.log(f"The interface data file {os.path.join(self.storagepath, filename)} may be corrupt", RNS.LOG_ERROR)
RNS.log(f"Error while loading discovered interface data: {e}", RNS.LOG_WARNING)
RNS.log(f"The interface data file {os.path.join(self.storagepath, filename)} may be corrupt", RNS.LOG_WARNING)
RNS.trace_exception(e)
discovered_interfaces.sort(key=lambda info: (info["status_code"], info["value"], info["last_heard"]), reverse=True)
@@ -433,41 +549,45 @@ class InterfaceDiscovery():
filename = RNS.hexrep(discovery_hash, delimit=False)
filepath = os.path.join(self.storagepath, filename)
RNS.log(f"Discovered {interface_type} {hops} hop{ms} away with stamp value {value}: {name}", RNS.LOG_DEBUG)
if not os.path.isfile(filepath):
try:
with open(filepath, "wb") as f:
info["discovered"] = info["received"]
info["last_heard"] = info["received"]
info["heard_count"] = 0
f.write(msgpack.packb(info))
except Exception as e:
RNS.log(f"Error while persisting discovered interface data: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return
with self.discovery_lock:
if not os.path.isfile(filepath):
try:
with open(filepath, "wb") as f:
info["discovered"] = info["received"]
info["last_heard"] = info["received"]
info["heard_count"] = 0
f.write(msgpack.packb(info))
except Exception as e:
RNS.log(f"Error while persisting discovered interface data: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return
else:
discovered = None
heard_count = None
try:
with open(filepath, "rb") as f:
last_info = msgpack.unpackb(f.read())
discovered = last_info["discovered"]
heard_count = last_info["heard_count"]
else:
discovered = None
heard_count = None
try:
try:
with open(filepath, "rb") as f:
last_info = msgpack.unpackb(f.read())
discovered = last_info["discovered"]
heard_count = last_info["heard_count"]
if discovered == None: discovered = info["discovered"]
if heard_count == None: heard_count = 0
except Exception as e: RNS.log(f"Error while reading existing data for discovered interface, re-creating data", RNS.LOG_ERROR)
with open(filepath, "wb") as f:
info["discovered"] = discovered
info["last_heard"] = info["received"]
info["heard_count"] = heard_count+1
f.write(msgpack.packb(info))
if discovered == None: discovered = info["received"]
if heard_count == None: heard_count = 0
except Exception as e:
RNS.log(f"Error while persisting discovered interface data: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return
with open(filepath, "wb") as f:
info["discovered"] = discovered
info["last_heard"] = info["received"]
info["heard_count"] = heard_count+1
f.write(msgpack.packb(info))
except Exception as e:
RNS.log(f"Error while persisting discovered interface data: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return
except Exception as e:
RNS.log(f"Error processing discovered interface data: {e}", RNS.LOG_ERROR)
@@ -489,7 +609,7 @@ class InterfaceDiscovery():
threading.Thread(target=self.__monitor_job, daemon=True).start()
def __monitor_job(self):
while self.monitoring_autoconnects:
while self.monitoring_autoconnects and RNS.Transport._should_run:
time.sleep(self.monitor_interval)
detached_interfaces = []
online_interfaces = 0
@@ -546,7 +666,7 @@ class InterfaceDiscovery():
def teardown_interface(self, interface):
interface.detach()
if interface in RNS.Transport.interfaces: RNS.Transport.interfaces.remove(interface)
RNS.Transport.remove_interface(interface)
if interface in self.monitored_interfaces: self.monitored_interfaces.remove(interface)
def autoconnect_count(self):
@@ -612,12 +732,23 @@ class InterfaceDiscovery():
return
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"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", 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_DEBUG)
return
if is_ygg_ipv6(info["reachable_on"]):
# TODO: Somehow detect if yggdrasil is enabled on the system
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"]
RNS.log(f"Auto-connecting discovered {interface_type} {interface_name}")
config_entry = info["config_entry"]
interface_config = {}
interface_config["name"] = f"{interface_name}"
@@ -632,9 +763,19 @@ class InterfaceDiscovery():
interface = BackboneInterface.BackboneClientInterface(RNS.Transport, interface_config)
if interface:
RNS.log(f"Auto-connecting discovered {interface_type} {interface_name}")
interface.autoconnect_hash = endpoint_hash
interface.autoconnect_source = info["network_id"]
RNS.Reticulum.get_instance()._add_interface(interface, ifac_netname=ifac_netname, ifac_netkey=ifac_netkey, configured_bitrate=5E6)
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_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
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,
announces_to_internal=internal_a, gravity=gravity)
self.monitor_interface(interface)
except Exception as e:
@@ -707,7 +848,7 @@ class BlackholeUpdater():
if identity_hash in self.last_updates: last_update = self.last_updates[identity_hash]
else: last_update = 0
if now > last_update+self.UPDATE_INTERVAL:
if now > last_update+RNS.Reticulum.blackhole_update_interval():
try:
destination_hash = RNS.Destination.hash_from_name_and_identity("rnstransport.info.blackhole", identity_hash)
RNS.log(f"Attempting blackhole list update from {RNS.prettyhexrep(identity_hash)}...", RNS.LOG_DEBUG)
@@ -733,6 +874,19 @@ def is_ip_address(address_string):
return True
except: return False
def is_ygg_ipv6(address_string):
try: return ipaddress.ip_address(address_string) in ipaddress.IPv6Network("200::/7")
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):
if hostname[-1] == ".": hostname = hostname[:-1]
if len(hostname) > 253: return False
@@ -740,3 +894,8 @@ def is_hostname(hostname):
if re.match(r"[0-9]+$", components[-1]): return False
allowed = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(label) for label in components)
san_map = ""
for i in range(48, 58): san_map += bytes([i]).decode("ascii")
for i in range(65, 91): san_map += bytes([i]).decode("ascii")
for i in range(97, 123): san_map += bytes([i]).decode("ascii")
+104 -70
View File
@@ -76,6 +76,7 @@ class Identity:
# Non-configurable constants
TOKEN_OVERHEAD = RNS.Cryptography.Token.TOKEN_OVERHEAD
AES128_BLOCKSIZE = 16 # In bytes
AES256_BLOCKSIZE = 16 # In bytes
HASHLENGTH = 256 # In bits
SIGLENGTH = KEYSIZE # In bits
@@ -126,13 +127,15 @@ class Identity:
:returns: An :ref:`RNS.Identity<api-identity>` instance that can be used to create an outgoing :ref:`RNS.Destination<api-destination>`, or *None* if the destination is unknown.
"""
if from_identity_hash:
for destination_hash in Identity.known_destinations:
if target_hash == Identity.truncated_hash(Identity.known_destinations[destination_hash][2]):
with Identity.known_destinations_lock: destination_hashes = list(Identity.known_destinations.keys())
for destination_hash in destination_hashes:
entry = Identity.known_destinations.get(destination_hash)
if not entry: continue
if target_hash == Identity.truncated_hash(entry[2]):
if not _no_use: RNS.Reticulum.get_instance()._used_destination_data(destination_hash)
identity_data = Identity.known_destinations[destination_hash]
identity = Identity(create_keys=False)
identity.load_public_key(identity_data[2])
identity.app_data = identity_data[3]
identity.load_public_key(entry[2])
identity.app_data = entry[3]
return identity
return None
@@ -171,12 +174,9 @@ class Identity:
else: return None
@staticmethod
def save_known_destinations(background=False, recombine=True):
# TODO: Improve the storage method so we don't have to
# deserialize and serialize the entire table on every
# save, but the only changes. It might be possible to
# simply overwrite on exit now that every local client
# disconnect triggers a data persist.
def save_known_destinations(background=False, recombine=False):
if recombine: RNS.log(f"Recombining known destinations from disk cache on persist is deprecated, argument ignored", RNS.LOG_WARNING)
if RNS.Transport.owner.is_connected_to_shared_instance: return
try:
if hasattr(Identity, "saving_known_destinations"):
@@ -191,40 +191,26 @@ class Identity:
Identity.saving_known_destinations = True
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
temp_file = RNS.Reticulum.storagepath+f"/known_destinations.tmp.{time.time()}"
try:
with open(temp_file,"wb") as file: umsgpack.dump(Identity.known_destinations.copy(), file)
os.replace(temp_file, RNS.Reticulum.storagepath+f"/known_destinations")
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)
except Exception as e:
RNS.log(f"Error while serializing and writing known destinations: {e}", RNS.LOG_ERROR)
try: os.unlink(temp_file)
except Exception as exc: RNS.log(f"Could not clean up temporary file {temp_file}: {exc}", RNS.LOG_WARNING)
raise e
RNS.log("Saving "+str(len(Identity.known_destinations))+" known destinations to storage...", RNS.LOG_VERBOSE)
with open(RNS.Reticulum.storagepath+"/known_destinations","wb") as file:
umsgpack.dump(Identity.known_destinations.copy(), file)
save_time = time.time() - save_start
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)
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
except Exception as e:
RNS.log("Error while saving known destinations to disk, the contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.trace_exception(e)
Identity.saving_known_destinations = False
finally: Identity.saving_known_destinations = False
@staticmethod
def load_known_destinations():
@@ -279,9 +265,24 @@ class Identity:
return True
return False
@staticmethod
def _retain_identity(identity_hash):
try:
retained = False
with Identity.known_destinations_lock: destination_hashes = list(Identity.known_destinations.keys())
for destination_hash in destination_hashes:
entry = Identity.known_destinations.get(destination_hash)
if not entry: continue
if identity_hash == Identity.truncated_hash(entry[2]):
if Identity._retain_destination_data(destination_hash): retained = True
return retained
except Exception as e: RNS.log(f"Error while retaining identity {RNS.prettyhexrep(identity_hash)}: {e}", RNS.LOG_ERROR)
@staticmethod
def clean_known_destinations():
def clean_known_destinations(background=False):
now = time.time()
st = now
total = len(Identity.known_destinations)
@@ -289,8 +290,15 @@ class Identity:
no_path = 0
retained = 0
never_used = 0
for destination_hash in Identity.known_destinations:
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())
for destination_hash in destination_hashes:
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
else:
has_path = False
@@ -321,7 +329,7 @@ class Identity:
if not was_used and now - last_announce > RNS.Transport.UNUSED_DESTINATION_LINGER: stale.append(destination_hash)
elif unused_for > RNS.Transport.DESTINATION_TIMEOUT*1.25: stale.append(destination_hash)
except Exception as e: RNS.log(f"Faulty entry for {RNS.prettyhexrep(destination_hash)} while cleaning known destinations: {e}", RNS.LOG_DEBUG)
except Exception as e: RNS.log(f"Faulty entry for {RNS.prettyhexrep(destination_hash)} while cleaning known destinations: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
removed = 0
for destination_hash in stale:
@@ -330,7 +338,14 @@ class Identity:
Identity.known_destinations.pop(destination_hash)
removed += 1
# 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
try:
hexhash = RNS.hexrep(destination_hash, delimit=False)
ratchet_path = f"{ratchetdir}/{hexhash}"
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)
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)
@staticmethod
@@ -400,7 +415,7 @@ class Identity:
ratchet_exists = False
if not ratchet_exists:
RNS.log(f"Remembering ratchet {RNS.prettyhexrep(Identity._get_ratchet_id(ratchet))} for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_EXTREME)
RNS.log(f"Remembering ratchet {RNS.prettyhexrep(Identity._get_ratchet_id(ratchet))} for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
Identity.known_ratchets[destination_hash] = ratchet
if not RNS.Transport.owner.is_connected_to_shared_instance:
def persist_job():
@@ -429,7 +444,7 @@ class Identity:
@staticmethod
def _clean_ratchets():
RNS.log("Cleaning ratchets...", RNS.LOG_DEBUG)
RNS.log("Cleaning ratchets...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
try:
count = 0
removed = 0
@@ -464,7 +479,7 @@ class Identity:
RNS.log(f"The contained exception was: {e}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"An error occurred while cleaning ratchets. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.log(f"Processed {count} ratchets in {RNS.prettytime(time.time()-now)}, not in use {not_known}, removed {removed}", RNS.LOG_DEBUG)
RNS.log(f"Processed {count} ratchets in {RNS.prettytime(time.time()-now)}, not in use {not_known}, removed {removed}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
@staticmethod
def get_ratchet(destination_hash):
@@ -489,11 +504,11 @@ class Identity:
if destination_hash in Identity.known_ratchets:
return Identity.known_ratchets[destination_hash]
else:
RNS.log(f"Could not load ratchet for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG)
RNS.log(f"Could not load ratchet for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None
@staticmethod
def validate_announce(packet, only_validate_signature=False):
def validate_announce(packet, only_validate_signature=False, signal_blackholed=False):
try:
if packet.packet_type == RNS.Packet.ANNOUNCE:
keysize = Identity.KEYSIZE//8
@@ -537,10 +552,12 @@ class Identity:
if len(RNS.Transport.blackholed_identities) > 0:
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)
return False
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
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 (packet.announce_signature_validated or announced_identity.validate(signature, signed_data)):
packet.announce_signature_validated = True
if only_validate_signature:
del announced_identity
return True
@@ -566,30 +583,27 @@ class Identity:
signal_str = " ["
if packet.rssi != None:
signal_str += "RSSI "+str(packet.rssi)+"dBm"
if packet.snr != None:
signal_str += ", "
if packet.snr != None:
signal_str += "SNR "+str(packet.snr)+"dB"
if packet.snr != None: signal_str += ", "
if packet.snr != None: signal_str += "SNR "+str(packet.snr)+"dB"
signal_str += "]"
else:
signal_str = ""
else: signal_str = ""
if hasattr(packet, "transport_id") and packet.transport_id != None:
RNS.log("Valid announce for "+RNS.prettyhexrep(destination_hash)+" "+str(packet.hops)+" hops away, received via "+RNS.prettyhexrep(packet.transport_id)+" on "+str(packet.receiving_interface)+signal_str, RNS.LOG_EXTREME)
RNS.log("Valid announce for "+RNS.prettyhexrep(destination_hash)+" "+str(packet.hops)+" hops away, received via "+RNS.prettyhexrep(packet.transport_id)+" on "+str(packet.receiving_interface)+signal_str, RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
else:
RNS.log("Valid announce for "+RNS.prettyhexrep(destination_hash)+" "+str(packet.hops)+" hops away, received on "+str(packet.receiving_interface)+signal_str, RNS.LOG_EXTREME)
RNS.log("Valid announce for "+RNS.prettyhexrep(destination_hash)+" "+str(packet.hops)+" hops away, received on "+str(packet.receiving_interface)+signal_str, RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
if ratchet:
Identity._remember_ratchet(destination_hash, ratchet)
if ratchet: Identity._remember_ratchet(destination_hash, ratchet)
return True
else:
RNS.log("Received invalid announce for "+RNS.prettyhexrep(destination_hash)+": Destination mismatch.", RNS.LOG_DEBUG)
RNS.log("Received invalid announce for "+RNS.prettyhexrep(destination_hash)+": Destination mismatch.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
else:
RNS.log("Received invalid announce for "+RNS.prettyhexrep(destination_hash)+": Invalid signature.", RNS.LOG_DEBUG)
RNS.log("Received invalid announce for "+RNS.prettyhexrep(destination_hash)+": Invalid signature.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
del announced_identity
return False
@@ -656,6 +670,22 @@ class Identity:
RNS.log("Error while saving identity to "+str(path), RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e))
def pub_to_file(self, path):
"""
Saves the public identity to a file.
:param path: The full path specifying where to save the identity.
:returns: True if the file was saved, otherwise False.
"""
try:
with open(path, "wb") as key_file:
key_file.write(self.get_public_key())
return True
return False
except Exception as e:
RNS.log("Error while saving identity to "+str(path), RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e))
def __init__(self,create_keys=True):
# Initialize keys to none
self.prv = None
@@ -695,13 +725,15 @@ class Identity:
"""
:returns: The private key as *bytes*
"""
return self.prv_bytes+self.sig_prv_bytes
if self.prv_bytes and self.sig_prv_bytes: return self.prv_bytes+self.sig_prv_bytes
else: return None
def get_public_key(self):
"""
:returns: The public key as *bytes*
"""
return self.pub_bytes+self.sig_pub_bytes
if self.pub_bytes and self.sig_pub_bytes: return self.pub_bytes+self.sig_pub_bytes
else: return None
def load_private_key(self, prv_bytes):
"""
@@ -727,9 +759,7 @@ class Identity:
return True
except Exception as e:
raise e
RNS.log("Failed to load identity key", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Failed to load identity key, the contained exception was: {e}", RNS.LOG_ERROR)
return False
def load_public_key(self, pub_bytes):
@@ -747,8 +777,12 @@ class Identity:
self.sig_pub = Ed25519PublicKey.from_public_bytes(self.sig_pub_bytes)
self.update_hashes()
return True
except Exception as e:
RNS.log("Error while loading public key, the contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while loading public key, the contained exception was: {e}", RNS.LOG_ERROR)
return False
def update_hashes(self):
self.hash = Identity.truncated_hash(self.get_public_key())
@@ -848,7 +882,7 @@ class Identity:
pass
if enforce_ratchets and plaintext == None:
RNS.log("Decryption with ratchet enforcement by "+RNS.prettyhexrep(self.hash)+" failed. Dropping packet.", RNS.LOG_DEBUG)
RNS.log("Decryption with ratchet enforcement by "+RNS.prettyhexrep(self.hash)+" failed. Dropping packet.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if ratchet_id_receiver:
ratchet_id_receiver.latest_ratchet_id = None
return None
@@ -861,14 +895,14 @@ class Identity:
ratchet_id_receiver.latest_ratchet_id = None
except Exception as e:
RNS.log("Decryption by "+RNS.prettyhexrep(self.hash)+" failed: "+str(e), RNS.LOG_DEBUG)
RNS.log("Decryption by "+RNS.prettyhexrep(self.hash)+" failed: "+str(e), RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if ratchet_id_receiver:
ratchet_id_receiver.latest_ratchet_id = None
return plaintext
else:
RNS.log("Decryption failed because the token size was invalid.", RNS.LOG_DEBUG)
RNS.log("Decryption failed because the token size was invalid.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None
else:
raise KeyError("Decryption failed because identity does not hold a private key")
+1
View File
@@ -128,6 +128,7 @@ class AX25KISSInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.flow_control_timeout = 5
self.flow_control_locked = time.time()
+1
View File
@@ -131,6 +131,7 @@ class KISSInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.flow_control_timeout = 5
self.flow_control_locked = time.time()
+5 -7
View File
@@ -282,12 +282,9 @@ class RNodeInterface(Interface):
if (port != None or device_serial != None) and (enable_bluetooth or disable_bluetooth or pairing_mode):
serial = None
bluetooth_state = None
if pairing_mode:
bluetooth_state = 0x01
elif enable_bluetooth:
bluetooth_state = 0x01
elif disable_bluetooth:
bluetooth_state = 0x00
if pairing_mode: bluetooth_state = 0x01
elif enable_bluetooth: bluetooth_state = 0x01
elif disable_bluetooth: bluetooth_state = 0x00
if port != None:
RNS.log("Opening serial port "+port+"...")
@@ -518,6 +515,7 @@ class RNodeInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.announce_rate_target = None
self.last_port_io = 0
@@ -1742,7 +1740,7 @@ class BLEConnection(BluetoothDispatcher):
ble_devices = self.find_target_devices()
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.was_connected:
@@ -95,6 +95,7 @@ class SerialInterface(Interface):
raise ValueError("No port specified for serial interface")
self.HW_MTU = 564
self.shared_medium = True
self.pyserial = serial
self.serial = None
+4 -2
View File
@@ -33,5 +33,7 @@ import glob
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+20 -6
View File
@@ -428,14 +428,22 @@ class AutoInterface(Interface):
if ifname in self.interface_servers:
RNS.log("Shutting down previous UDP listener for "+str(self)+" "+str(ifname), RNS.LOG_DEBUG)
previous_server = self.interface_servers[ifname]
def shutdown_server():
previous_server.shutdown()
def shutdown_server(): previous_server.shutdown()
threading.Thread(target=shutdown_server, daemon=True).start()
RNS.log("Starting new UDP listener for "+str(self)+" "+str(ifname), RNS.LOG_DEBUG)
udp_server = socketserver.UDPServer(listen_address, self.handler_factory(self.process_incoming))
self.interface_servers[ifname] = udp_server
retry_delay = 1.25
listener_started = False
while not listener_started:
try:
time.sleep(retry_delay)
udp_server = socketserver.UDPServer(listen_address, self.handler_factory(self.process_incoming))
self.interface_servers[ifname] = udp_server
listener_started = True
except Exception as e:
RNS.log(f"Could not start new UDP listener for {self} on {listen_address}: {e}", RNS.LOG_WARNING)
RNS.log(f"Retrying in {retry_delay} seconds", RNS.LOG_WARNING)
thread = threading.Thread(target=udp_server.serve_forever)
thread.daemon = True
@@ -539,6 +547,11 @@ class AutoInterface(Interface):
spawned_interface.ic_new_time = self.ic_new_time
spawned_interface.ic_burst_penalty = self.ic_burst_penalty
spawned_interface.ic_held_release_interval = self.ic_held_release_interval
spawned_interface.egress_control = self.egress_control
spawned_interface.ec_pr_freq = self.ec_pr_freq
spawned_interface.ic_pr_burst_freq_new = self.ic_pr_burst_freq_new
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
spawned_interface.parent_interface = self
spawned_interface.bitrate = self.bitrate
@@ -567,9 +580,10 @@ class AutoInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True
RNS.Transport.interfaces.append(spawned_interface)
RNS.Transport.add_interface(spawned_interface)
if addr in self.spawned_interfaces:
self.spawned_interfaces[addr].detach()
self.spawned_interfaces[addr].teardown()
@@ -661,7 +675,7 @@ class AutoInterfacePeer(Interface):
except Exception as e:
RNS.log(f"Could not remove {self} from parent interface on detach. The contained exception was: {e}", RNS.LOG_ERROR)
if self in RNS.Transport.interfaces: RNS.Transport.interfaces.remove(self)
RNS.Transport.remove_interface(self)
class AutoInterfaceHandler(socketserver.BaseRequestHandler):
def __init__(self, callback, *args, **keys):
+522 -119
View File
@@ -29,6 +29,8 @@
# SOFTWARE.
from RNS.Interfaces.Interface import Interface
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
import threading
import socket
import select
@@ -37,29 +39,47 @@ import sys
import os
import RNS
class HDLC():
FLAG = 0x7E
ESC = 0x7D
ESC_MASK = 0x20
@staticmethod
def escape(data):
data = data.replace(bytes([HDLC.ESC]), bytes([HDLC.ESC, HDLC.ESC^HDLC.ESC_MASK]))
data = data.replace(bytes([HDLC.FLAG]), bytes([HDLC.ESC, HDLC.FLAG^HDLC.ESC_MASK]))
return data
class BackboneInterface(Interface):
HW_MTU = 1048576
BITRATE_GUESS = 1_000_000_000
DEFAULT_IFAC_SIZE = 16
AUTOCONFIGURE_MTU = True
HW_MTU = 1048576
BITRATE_GUESS = 100_000_000
DEFAULT_IFAC_SIZE = 16
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 = {}
DP_IC_HIGH_WM_PCT = 90
DP_IC_MID_WM_PCT = 68
DP_IC_LOW_WM_PCT = 10
DP_IC_INTERVAL = 0.250
DP_IC_TRIGGER = 1.5
DP_IC_RCVBUF = 32768
DP_IC_IF_HEADROOM = 32
DP_IC_PENALTY = 1.5
DP_EC_INTERVAL = 1.0
DP_EC_MID_WM = 128*1024
DP_EC_HIGH_WM = 4*1024*1024
DP_EC_STALL_TICKS = 3
DP_EC_MAX_ETA = 10.0
DP_EC_RELEASE_ETA = 5.0 # Gate release hysterisis
DP_EC_DEAD_TIME = 12.0
epoll = None
listener_filenos = {}
spawned_interface_filenos = {}
epoll = None
_job_active = False
_job_lock = threading.Lock()
_job_active = False
_ic_job_active = False
_ec_job_active = False
_job_lock = threading.Lock()
_ec_job_lock = threading.Lock()
_ic_job_lock = threading.Lock()
_dp_ic_lock = threading.Lock()
_dp_ic_snapshot = 0
@staticmethod
def get_address_for_if(name, bind_port, prefer_ipv6=False):
@@ -109,13 +129,17 @@ class BackboneInterface(Interface):
super().__init__()
c = Interface.get_config_obj(configuration)
name = c["name"]
device = c["device"] if "device" 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
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
c = Interface.get_config_obj(configuration)
name = c["name"]
device = c["device"] if "device" 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
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
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
@@ -128,11 +152,13 @@ class BackboneInterface(Interface):
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.spawned_interfaces = []
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:
raise SystemError(f"No TCP port configured for interface \"{name}\"")
else:
self.bind_port = bindport
if bindport == None: raise SystemError(f"No TCP port configured for interface \"{name}\"")
else: self.bind_port = bindport
bind_address = None
if device != None:
@@ -156,9 +182,87 @@ class BackboneInterface(Interface):
else:
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_state = False
@property
def ic_burst_active(self):
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_check = time.time()
return self.__last_ic_burst_state
@ic_burst_active.setter
def ic_burst_active(self, value): pass
__ic_burst_activated_check = 0
__ic_burst_activated = 0
@property
def ic_burst_activated(self):
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]
if activated: self.__ic_burst_activated = min(activated)
self.__ic_burst_activated_check = time.time()
return self.__ic_burst_activated
@ic_burst_activated.setter
def ic_burst_activated(self, value): pass
__last_ic_pr_burst_check = 0
__last_ic_pr_burst_state = False
@property
def ic_pr_burst_active(self):
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_check = time.time()
return self.__last_ic_pr_burst_state
@ic_pr_burst_active.setter
def ic_pr_burst_active(self, value): pass
__ic_pr_burst_activated_check = 0
__ic_pr_burst_activated = 0
@property
def ic_pr_burst_activated(self):
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]
if activated: self.__ic_pr_burst_activated = min(activated)
self.__ic_pr_burst_activated_check = time.time()
return self.__ic_pr_burst_activated
@ic_pr_burst_activated.setter
def ic_pr_burst_activated(self, value): pass
@staticmethod
def start():
if not BackboneInterface._job_active: threading.Thread(target=BackboneInterface.__job, daemon=True).start()
if not BackboneInterface._job_active: threading.Thread(target=BackboneInterface.__job, daemon=True).start()
if not BackboneInterface._ic_job_active: threading.Thread(target=BackboneInterface.__dp_ic_job, daemon=True).start()
if not BackboneInterface._ec_job_active: threading.Thread(target=BackboneInterface.__dp_ec_job, daemon=True).start()
@staticmethod
def ensure_epoll():
@@ -196,22 +300,24 @@ class BackboneInterface(Interface):
@staticmethod
def register_in(fileno):
if fileno < 0:
RNS.log(f"Attempt to register invalid file descriptor {fileno}", RNS.LOG_ERROR)
RNS.log(f"Attempt to register invalid file descriptor {fileno}", RNS.LOG_WARNING)
return
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN)
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN | select.EPOLLHUP)
except Exception as e:
RNS.log(f"An error occurred while registering EPOLL_IN for file descriptor {fileno}: {e}", RNS.LOG_ERROR)
RNS.log(f"An error occurred while registering EPOLLIN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
@staticmethod
def deregister_fileno(fileno):
if fileno < 0:
RNS.log(f"Attempt to deregister invalid file descriptor {fileno}", RNS.LOG_ERROR)
RNS.log(f"Attempt to deregister invalid file descriptor {fileno}", RNS.LOG_DEBUG)
return
try: BackboneInterface.epoll.unregister(fileno)
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
def deregister_listeners():
@@ -228,11 +334,223 @@ class BackboneInterface(Interface):
if interface.socket:
fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos:
try: BackboneInterface.epoll.modify(fileno, select.EPOLLOUT)
try:
events = select.EPOLLOUT | select.EPOLLHUP
if not interface.dp_ingress_gated: events |= select.EPOLLIN
BackboneInterface.epoll.modify(fileno, events)
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
@staticmethod
def __throttle_ingress(interface, hold=None):
if interface.dp_ingress_gated: return False
try:
fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos:
interface.dp_ingress_gated = True
interface.dp_ingress_tcount += 1
events = select.EPOLLHUP
if interface.transmit_buffer.sendable > 0: events |= select.EPOLLOUT
BackboneInterface.epoll.modify(fileno, events)
if hold: interface.dp_ingress_hold = time.time() + hold
RNS.log(f"Ingress throttled on {interface}", RNS.LOG_NOTICE) if RNS.sl(RNS.LOG_NOTICE) else None
return True
except Exception as e: RNS.log(f"Error throttling {interface}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
@staticmethod
def __release_ingress(interface):
if not interface.dp_ingress_gated: return False
try:
fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos:
events = select.EPOLLIN | select.EPOLLHUP
if interface.transmit_buffer.sendable > 0: events |= select.EPOLLOUT
BackboneInterface.epoll.modify(fileno, events)
interface.dp_ingress_gated = False
RNS.log(f"Released ingress throttle on {interface}", RNS.LOG_NOTICE) if RNS.sl(RNS.LOG_NOTICE) else None
return True
except Exception as e: RNS.log(f"Error releasing throttle on {interface}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
@staticmethod
def _throttle_immediate(q_depth):
with BackboneInterface._dp_ic_lock:
st = time.time()
interfaces = list(BackboneInterface.spawned_interface_filenos.values())
producers = [iface for iface in interfaces if iface.dp_ingress_packets > 0]
if producers:
producers.sort(key=lambda p: p.dp_ingress_packets, reverse=True)
selected = producers[0]
now = time.time()
span = now - BackboneInterface._dp_ic_snapshot
total = sum(iface.dp_ingress_packets for iface in producers)
avail = sum(iface.dp_ingress_bytes for iface in interfaces) / span
share = selected.dp_ingress_packets / total
rate = selected.dp_ingress_packets / span
speed = selected.dp_ingress_bytes / span
data = selected.dp_ingress_bytes
pkts = selected.dp_ingress_packets
alloc = 1/((max(len(interfaces), BackboneInterface.DP_IC_IF_HEADROOM))*BackboneInterface.DP_IC_PENALTY)
hold = (avail/(avail*alloc))*span
if BackboneInterface.__throttle_ingress(selected, hold=hold):
taken = time.time()-st
if RNS.sl(RNS.LOG_DEBUG):
RNS.log(f"Throttled producer with {pkts} packets at {RNS.prettysize(rate, suffix='pps')} / {RNS.prettyspeed(speed*8)}, {round(share*100.0, 2)}% ingress share", RNS.LOG_DEBUG)
RNS.log(f"Available ingress budget {RNS.prettyspeed(avail*8)}, hard-allocated {round(alloc*100.0, 2)}% ({RNS.prettyspeed(avail*alloc*8)}), handled in {RNS.prettyshorttime(taken, compact=True, tight=True)}", RNS.LOG_DEBUG)
RNS.log(f"Holding for {RNS.prettyshorttime(hold, compact=True, tight=True)}, throttling handled in {RNS.prettyshorttime(taken, compact=True, tight=True)} at depth {q_depth}", RNS.LOG_DEBUG)
@staticmethod
def _dp_ec_evaluate(interface, now):
tb = interface.transmit_buffer
drained = tb._tx_sent - interface._dp_ec_prev_sent
interface._dp_ec_prev_sent = tb._tx_sent
sendable = tb.sendable
buffered = len(tb)
if buffered == 0 or sendable == 0:
interface._dp_ec_zero_ticks = 0
interface._dp_ec_last_drain = now
interface.tx_stalled = False
return False
if now - interface._dp_ec_last_drain >= BackboneInterface.DP_EC_DEAD_TIME:
RNS.log(f"No egress control drain progress for {RNS.prettyshorttime(BackboneInterface.DP_EC_DEAD_TIME, compact=True)} on {interface}, tearing down", RNS.LOG_NOTICE)
try:
if hasattr(interface, "socket") and interface.socket:
fileno = interface.socket.fileno()
BackboneInterface.deregister_fileno(fileno)
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
try: interface.socket.close()
except Exception as e: RNS.log(f"Egress control could not close socket for {interface}: {e}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"Egress control cleanup error for {interface}: {e}", RNS.LOG_ERROR)
interface.receive(b"")
return True
if drained > 0:
interface._dp_ec_last_drain = now
interface._dp_ec_zero_ticks = 0
drain_rate = drained / BackboneInterface.DP_EC_INTERVAL
clear_eta = buffered / drain_rate if drain_rate > 0 else float("inf")
if buffered > BackboneInterface.DP_EC_MID_WM and clear_eta > BackboneInterface.DP_EC_MAX_ETA:
if not interface.tx_stalled: RNS.log(f"Egress control drain ETA of {RNS.prettyshorttime(clear_eta, compact=True)} exceeds maximum on {interface}, gating outbound", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
interface.tx_stalled = True
elif clear_eta < BackboneInterface.DP_EC_RELEASE_ETA or buffered <= BackboneInterface.DP_EC_MID_WM:
if interface.tx_stalled: RNS.log(f"Egress control drain recovered on {interface}, resuming outbound", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
interface.tx_stalled = False
else:
# No drain progress on this tick
if buffered > BackboneInterface.DP_EC_MID_WM:
interface._dp_ec_zero_ticks += 1
if interface._dp_ec_zero_ticks >= BackboneInterface.DP_EC_STALL_TICKS:
if not interface.tx_stalled: RNS.log(f"No egress control drain progress on {interface}, gating outbound", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
interface.tx_stalled = True
else:
interface._dp_ec_zero_ticks = 0
interface.tx_stalled = False
return False
@staticmethod
def __dp_ec_job():
with BackboneInterface._ec_job_lock:
if BackboneInterface._ec_job_active: return
else:
BackboneInterface._ec_job_active = True
RNS.log(f"Started dataplane egress control", RNS.LOG_DEBUG)
try:
while True:
time.sleep(BackboneInterface.DP_EC_INTERVAL)
now = time.time()
try: interfaces = list(BackboneInterface.spawned_interface_filenos.values())
except RuntimeError as e:
RNS.log(f"Deferring egress control evaluation due to error: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
continue
for interface in interfaces:
if interface.detached: continue
if isinstance(interface, RNS.Interfaces.LocalInterface.LocalClientInterface): continue
BackboneInterface._dp_ec_evaluate(interface, now)
except Exception as e:
RNS.log(f"BackboneInterface egress control error: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
@staticmethod
def __dp_ic_job():
with BackboneInterface._ic_job_lock:
if BackboneInterface._ic_job_active: return
else:
BackboneInterface._ic_job_active = True
RNS.log(f"Started dataplane ingress control: High/mid/low water marks are {BackboneInterface.DP_IC_HIGH_WM}/{BackboneInterface.DP_IC_MID_WM}/{BackboneInterface.DP_IC_LOW_WM} packets", RNS.LOG_DEBUG)
try:
while True:
time.sleep(BackboneInterface.DP_IC_INTERVAL)
try:
if RNS.Transport.inbound_queues != None: q_depth = RNS.Transport.inbound_queues.qsize(RNS.Transport.TC_DATA)
else: continue
except Exception: continue
with BackboneInterface._dp_ic_lock:
st = time.time()
interfaces = list(BackboneInterface.spawned_interface_filenos.values())
if q_depth > BackboneInterface.DP_IC_MID_WM:
producers = [iface for iface in interfaces if iface.dp_ingress_packets > 0 and not isinstance(interface, RNS.Interfaces.LocalInterface.LocalClientInterface)]
if producers:
producers.sort(key=lambda p: p.dp_ingress_packets, reverse=True)
selected = producers[0]
now = time.time()
span = max(now - BackboneInterface._dp_ic_snapshot, 0.001)
total = sum(iface.dp_ingress_packets for iface in producers)
avail = sum(iface.dp_ingress_bytes for iface in interfaces) / span
mean = total / max(len(producers), 2)
share = selected.dp_ingress_packets / total
rate = selected.dp_ingress_packets / span
speed = selected.dp_ingress_bytes / span
data = selected.dp_ingress_bytes
pkts = selected.dp_ingress_packets
alloc = 1/((max(len(interfaces), BackboneInterface.DP_IC_IF_HEADROOM))*BackboneInterface.DP_IC_PENALTY)
hold = (avail/max(avail*alloc, 1))*span
if BackboneInterface.__throttle_ingress(selected, hold=hold):
taken = time.time()-st
if RNS.sl(RNS.LOG_DEBUG):
RNS.log(f"Throttled producer with {pkts} packets at {RNS.prettysize(rate, suffix='pps')} / {RNS.prettyspeed(speed*8)}, {round(share*100.0, 2)}% ingress share", RNS.LOG_DEBUG)
RNS.log(f"Available ingress budget {RNS.prettyspeed(avail*8)}, hard-allocated {round(alloc*100.0, 2)}% ({RNS.prettyspeed(avail*alloc*8)}), handled in {RNS.prettyshorttime(taken, compact=True, tight=True)}", RNS.LOG_DEBUG)
RNS.log(f"Holding for {RNS.prettyshorttime(hold, compact=True, tight=True)}, throttling handled in {RNS.prettyshorttime(taken, compact=True, tight=True)}", RNS.LOG_DEBUG)
elif q_depth < BackboneInterface.DP_IC_LOW_WM:
now = time.time()
for iface in interfaces:
if iface.dp_ingress_gated:
if iface.dp_ingress_hold and now < iface.dp_ingress_hold: continue
BackboneInterface.__release_ingress(iface)
break
BackboneInterface._dp_ic_snapshot = time.time()
for iface in interfaces:
iface.dp_ingress_bytes = 0
iface.dp_ingress_packets = 0
except Exception as e:
RNS.log(f"BackboneInterface ingress control error: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
@staticmethod
def __job():
with BackboneInterface._job_lock:
@@ -242,18 +560,21 @@ class BackboneInterface(Interface):
BackboneInterface.ensure_epoll()
try:
while True:
events = BackboneInterface.epoll.poll(1)
for fileno, event in BackboneInterface.epoll.poll(1):
if fileno in BackboneInterface.spawned_interface_filenos:
spawned_interface = BackboneInterface.spawned_interface_filenos[fileno]
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) and not spawned_interface.dp_ingress_gated:
if spawned_interface.dp_ingress_gated: continue
try: received_bytes = client_socket.recv(spawned_interface.HW_MTU)
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""
if len(received_bytes): spawned_interface.receive(received_bytes)
if len(received_bytes):
spawned_interface.dp_ingress_bytes += len(received_bytes)
spawned_interface.receive(received_bytes)
else:
BackboneInterface.deregister_fileno(fileno); client_socket.close()
try:
@@ -268,12 +589,19 @@ class BackboneInterface(Interface):
except Exception as e: RNS.log(f"Error while removing spawned interface from {pif}: {e}", RNS.LOG_ERROR)
spawned_interface.receive(received_bytes)
elif client_socket and fileno == client_socket.fileno() and (event & select.EPOLLOUT):
try: written = client_socket.send(spawned_interface.transmit_buffer)
socket_valid_after_read = socket_valid and fileno in BackboneInterface.spawned_interface_filenos
if socket_valid_after_read and (event & select.EPOLLOUT):
try: written = spawned_interface.transmit_buffer.drain_to(client_socket)
except Exception as e:
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)
try:
@@ -288,19 +616,20 @@ class BackboneInterface(Interface):
except Exception as e: RNS.log(f"Error while removing spawned interface from {pif}: {e}", RNS.LOG_ERROR)
try: client_socket.close()
except Exception as e: RNS.log(f"Error while closing socket for {spawned_interface}: {e}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"Error while closing socket for {spawned_interface}: {e}", RNS.LOG_WARNING)
spawned_interface.receive(b"")
spawned_interface.transmit_buffer = spawned_interface.transmit_buffer[written:]
try:
if len(spawned_interface.transmit_buffer) == 0: BackboneInterface.epoll.modify(fileno, select.EPOLLIN)
except Exception as e:
RNS.log(f"Error while setting EPOLLIN on {spawned_interface}: {e}", RNS.LOG_ERROR)
if spawned_interface.transmit_buffer.sendable == 0:
events = select.EPOLLHUP
if not spawned_interface.dp_ingress_gated: events |= select.EPOLLIN
BackboneInterface.epoll.modify(fileno, events)
except Exception as e: RNS.log(f"Error while setting EPOLLIN on {spawned_interface}: {e}", RNS.LOG_ERROR)
spawned_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)
try:
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
@@ -320,18 +649,25 @@ class BackboneInterface(Interface):
elif fileno in BackboneInterface.listener_filenos:
owner_interface, server_socket = BackboneInterface.listener_filenos[fileno]
if fileno == server_socket.fileno() and (event & select.EPOLLIN):
client_socket, address = server_socket.accept()
client_socket.setblocking(0)
if not owner_interface.incoming_connection(client_socket):
try:
client_socket, address = server_socket.accept()
client_socket.setblocking(0)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BackboneInterface.DP_IC_RCVBUF)
if not owner_interface.incoming_connection(client_socket):
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"Accepting socket failed for incoming connection: {e}", RNS.LOG_WARNING)
try: client_socket.close()
except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"Error while closing socket for failed incoming socket accept: {e}", RNS.LOG_WARNING)
elif fileno == server_socket.fileno() and (event & select.EPOLLHUP):
try: BackboneInterface.deregister_fileno(fileno)
except Exception as e: RNS.log(f"Error while deregistering listener file descriptor {fileno}: {e}", RNS.LOG_ERROR)
try: server_socket.close()
except Exception as e: RNS.log(f"Error while closing listener socket for {server_socket}: {e}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"Error while closing listener socket for {server_socket}: {e}", RNS.LOG_WARNING)
except Exception as e:
RNS.log(f"BackboneInterface error: {e}", RNS.LOG_ERROR)
@@ -341,8 +677,22 @@ class BackboneInterface(Interface):
BackboneInterface.deregister_listeners()
def incoming_connection(self, socket):
RNS.log("Accepting incoming connection", RNS.LOG_VERBOSE)
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_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket)
spawned_interface.OUT = self.OUT
@@ -356,10 +706,15 @@ class BackboneInterface(Interface):
spawned_interface.ic_new_time = self.ic_new_time
spawned_interface.ic_burst_penalty = self.ic_burst_penalty
spawned_interface.ic_held_release_interval = self.ic_held_release_interval
spawned_interface.egress_control = self.egress_control
spawned_interface.ec_pr_freq = self.ec_pr_freq
spawned_interface.ic_pr_burst_freq_new = self.ic_pr_burst_freq_new
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
spawned_interface.socket = socket
spawned_interface.target_ip = socket.getpeername()[0]
spawned_interface.target_port = str(socket.getpeername()[1])
spawned_interface.target_ip = remote_ip
spawned_interface.target_port = remote_port
spawned_interface.parent_interface = self
spawned_interface.bitrate = self.bitrate
spawned_interface.optimise_mtu()
@@ -369,18 +724,12 @@ class BackboneInterface(Interface):
spawned_interface.ifac_netkey = self.ifac_netkey
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
ifac_origin = b""
if spawned_interface.ifac_netname != None:
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_netname != None: 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"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
spawned_interface.ifac_key = RNS.Cryptography.hkdf(
length=64,
derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT,
context=None
)
spawned_interface.ifac_key = RNS.Cryptography.hkdf(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_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
@@ -388,13 +737,15 @@ class BackboneInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True
RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
RNS.Transport.interfaces.append(spawned_interface)
RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
RNS.Transport.add_interface(spawned_interface)
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.append(spawned_interface)
BackboneInterface.add_client_socket(socket, spawned_interface)
spawned_interface.spawned_at = time.time()
spawned_interface.online = True
except Exception as e:
RNS.log(f"An error occurred while accepting incoming connection on {self}: {e}", RNS.LOG_ERROR)
@@ -402,11 +753,25 @@ class BackboneInterface(Interface):
return True
def received_announce(self, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time())
def received_announce(self, size=0, from_spawned=False):
if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time())
def sent_announce(self, size=0, from_spawned=False):
if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def process_outgoing(self, data):
pass
@@ -422,15 +787,43 @@ class BackboneInterface(Interface):
if callable(listener_socket.shutdown):
try: listener_socket.shutdown(socket.SHUT_RDWR)
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)
def __str__(self):
if ":" in self.bind_ip:
ip_str = f"[{self.bind_ip}]"
else:
ip_str = f"{self.bind_ip}"
@property
def blocked_ip_list(self):
if not self.block_fast_flapping: return []
else: return [ip for ip in self.fast_flapping if self.fast_flapping[ip][2] > self.fast_flap_grace]
@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)+"]"
@@ -479,8 +872,10 @@ class BackboneClientInterface(Interface):
self.i2p_tunneled = i2p_tunneled
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.bitrate = BackboneClientInterface.BITRATE_GUESS
self.frame_buffer = b""
self.transmit_buffer = b""
self.transmit_buffer = TransmitBuffer()
self.receive_buffer = ReceiveBuffer(mtu=lambda: self.HW_MTU, min_frame_len=RNS.Reticulum.HEADER_MINSIZE,
max_frame_len=lambda: self.HW_MTU+(getattr(self, "ifac_size", None) or 0),
on_frame=self.process_incoming, on_invalid=self.invalid_frame)
if max_reconnect_tries == None:
self.max_reconnect_tries = BackboneClientInterface.RECONNECT_MAX_TRIES
@@ -539,7 +934,8 @@ class BackboneClientInterface(Interface):
try:
if self.socket != None: self.socket.shutdown(socket.SHUT_RDWR)
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)
try:
@@ -568,6 +964,7 @@ class BackboneClientInterface(Interface):
self.socket.settimeout(BackboneClientInterface.INITIAL_CONNECT_TIMEOUT)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.connect(target_address)
# TODO: Check missing setblocking(0)
self.socket.settimeout(None)
BackboneInterface.add_client_socket(self.socket, self)
@@ -578,8 +975,8 @@ class BackboneClientInterface(Interface):
except Exception as e:
if initial:
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(BackboneClientInterface.RECONNECT_WAIT)+" seconds.", RNS.LOG_ERROR)
RNS.log("Initial connection for "+str(self)+" could not be established: "+str(e), RNS.LOG_WARNING)
RNS.log("Leaving unconnected and retrying connection in "+str(BackboneClientInterface.RECONNECT_WAIT)+" seconds.", RNS.LOG_WARNING)
return False
else:
@@ -602,7 +999,7 @@ class BackboneClientInterface(Interface):
attempts += 1
if self.max_reconnect_tries != None and attempts > self.max_reconnect_tries:
RNS.log("Max reconnection attempts reached for "+str(self), RNS.LOG_ERROR)
RNS.log("Max reconnection attempts reached for "+str(self), RNS.LOG_WARNING)
self.teardown()
break
@@ -627,41 +1024,31 @@ class BackboneClientInterface(Interface):
self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.rxb += len(data)
self.dp_ingress_packets += 1
self.owner.inbound(data, self)
def process_outgoing(self, data):
if self.online and not self.detached:
try:
self.transmit_buffer += bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
BackboneInterface.tx_ready(self)
frame = HDLC.frame(data)
if self.tx_stalled or not self.transmit_buffer.append(frame, self.tx_hwm):
self.tx_drops += 1
self.tx_dropped_bytes += len(frame)
RNS.log(f"Egress control dropping outbound frame of {RNS.prettysize(len(frame))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
else: BackboneInterface.tx_ready(self)
except Exception as e:
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
self.teardown()
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):
try:
if len(data_in) > 0:
self.frame_buffer += data_in
flags_remaining = True
while flags_remaining:
frame_start = self.frame_buffer.find(HDLC.FLAG)
if frame_start != -1:
frame_end = self.frame_buffer.find(HDLC.FLAG, frame_start+1)
if frame_end != -1:
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.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > RNS.Reticulum.HEADER_MINSIZE:
self.process_incoming(frame)
self.frame_buffer = self.frame_buffer[frame_end:]
else:
flags_remaining = False
else:
flags_remaining = False
if len(data_in) > 0: self.receive_buffer.feed(data_in)
else:
self.online = False
if self.initiator and not self.detached:
@@ -669,7 +1056,7 @@ class BackboneClientInterface(Interface):
def job(): self.reconnect()
threading.Thread(target=job, daemon=True).start()
else:
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_VERBOSE)
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
self.teardown()
except Exception as e:
@@ -680,17 +1067,34 @@ class BackboneClientInterface(Interface):
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
def job(): self.reconnect()
threading.Thread(target=job, daemon=True).start()
else:
self.teardown()
else: self.teardown()
def teardown(self):
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)
if RNS.Reticulum.panic_on_interface_error:
RNS.panic()
if RNS.Reticulum.panic_on_interface_error: RNS.panic()
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.OUT = False
@@ -700,9 +1104,8 @@ class BackboneClientInterface(Interface):
while self in self.parent_interface.spawned_interfaces:
self.parent_interface.spawned_interfaces.remove(self)
if self in RNS.Transport.interfaces:
if not self.initiator:
RNS.Transport.interfaces.remove(self)
if not self.initiator:
RNS.Transport.remove_interface(self)
def __str__(self):
+118 -231
View File
@@ -88,8 +88,7 @@ class I2PController:
self.ready = False
self.storagepath = rns_storagepath+"/i2p"
if not os.path.isdir(self.storagepath):
os.makedirs(self.storagepath)
if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
def start(self):
@@ -110,28 +109,22 @@ class I2PController:
except Exception as e:
self.ready = False
RNS.log("Exception on event loop for "+str(self)+": "+str(e), RNS.LOG_ERROR)
finally:
self.loop.close()
finally: self.loop.close()
def stop(self):
for i2ptunnel in self.i2plib_tunnels:
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop):
i2ptunnel.stop()
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop): i2ptunnel.stop()
if hasattr(asyncio.Task, "all_tasks") and callable(asyncio.Task.all_tasks):
for task in asyncio.Task.all_tasks(loop=self.loop):
task.cancel()
for task in asyncio.Task.all_tasks(loop=self.loop): task.cancel()
time.sleep(0.2)
self.loop.stop()
def get_free_port(self):
return self.i2plib.utils.get_free_port()
def stop_tunnel(self, i2ptunnel):
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop):
i2ptunnel.stop()
@@ -159,10 +152,9 @@ class I2PController:
tn = self.i2plib_tunnels[i2p_destination]
if tn != None and hasattr(tn, "status"):
RNS.log("Waiting for status from I2P control process", RNS.LOG_EXTREME)
while not tn.status["setup_ran"]:
time.sleep(0.1)
RNS.log("Got 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"]: time.sleep(0.1)
RNS.log("Got status from I2P control process", RNS.LOG_DEBUG)
if tn.status["setup_failed"]:
self.stop_tunnel(tn)
@@ -172,29 +164,19 @@ class I2PController:
if owner.socket != None:
if hasattr(owner.socket, "close"):
if callable(owner.socket.close):
try:
owner.socket.shutdown(socket.SHUT_RDWR)
except Exception as e:
RNS.log("Error while shutting down socket for "+str(owner)+": "+str(e))
try: owner.socket.shutdown(socket.SHUT_RDWR)
except Exception as e: RNS.log("Error while shutting down 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))
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
owner.awaiting_i2p_tunnel = False
RNS.log(str(owner)+" tunnel setup complete", RNS.LOG_VERBOSE)
else:
raise IOError("Got no status response from SAM API")
except ConnectionRefusedError as e:
raise e
except ConnectionAbortedError as e:
raise e
else: raise IOError("Got no status response from SAM API")
except ConnectionRefusedError as e: raise e
except ConnectionAbortedError as e: raise e
except Exception as e:
RNS.log("Unexpected error type from I2P SAM: "+str(e), RNS.LOG_ERROR)
raise e
@@ -206,54 +188,33 @@ class I2PController:
if i2ptunnel.status["setup_ran"] == False:
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
elif i2p_exception != None:
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)
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)
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.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)
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
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)
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.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 could 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)
else: RNS.log(f"Unspecified I2P daemon error: {i2p_exception}", RNS.LOG_ERROR)
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
elif i2ptunnel.status["setup_failed"] == True:
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
else:
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
@@ -274,10 +235,8 @@ class I2PController:
i2p_keyfile_nf = self.storagepath+"/"+RNS.hexrep(i2p_dest_hash_nf, delimit=False)+".i2p"
# Use old format if a key is already present
if os.path.isfile(i2p_keyfile_of):
i2p_keyfile = i2p_keyfile_of
else:
i2p_keyfile = i2p_keyfile_nf
if os.path.isfile(i2p_keyfile_of): i2p_keyfile = i2p_keyfile_of
else: i2p_keyfile = i2p_keyfile_nf
i2p_dest = None
if not os.path.isfile(i2p_keyfile):
@@ -312,8 +271,7 @@ class I2PController:
asyncio.run_coroutine_threadsafe(tunnel_up(), self.loop).result()
self.server_tunnels[i2p_b32] = True
except Exception as e:
raise e
except Exception as e: raise e
else:
i2ptunnel = self.i2plib_tunnels[i2p_b32]
@@ -322,66 +280,45 @@ class I2PController:
if i2ptunnel.status["setup_ran"] == False:
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
elif i2p_exception != None:
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)
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)
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.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)
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
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)
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.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 could 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)
else: RNS.log(f"Unspecified I2P daemon error: {i2p_exception}", RNS.LOG_ERROR)
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
elif i2ptunnel.status["setup_failed"] == True:
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
else:
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel)
return False
time.sleep(5)
def get_loop(self):
return asyncio.get_event_loop()
def get_loop(self): return asyncio.get_event_loop()
class ThreadingI2PServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class I2PInterfacePeer(Interface):
RECONNECT_WAIT = 15
RECONNECT_MAX_TRIES = None
@@ -431,18 +368,11 @@ class I2PInterfacePeer(Interface):
self.ifac_netkey = self.parent_interface.ifac_netkey
if self.ifac_netname != None or self.ifac_netkey != None:
ifac_origin = b""
if self.ifac_netname != None:
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_netname != None: 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"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
self.ifac_key = RNS.Cryptography.hkdf(
length=64,
derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT,
context=None
)
self.ifac_key = RNS.Cryptography.hkdf(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_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_penalty = None
if max_reconnect_tries == None:
self.max_reconnect_tries = I2PInterfacePeer.RECONNECT_MAX_TRIES
else:
self.max_reconnect_tries = max_reconnect_tries
if max_reconnect_tries == None: self.max_reconnect_tries = I2PInterfacePeer.RECONNECT_MAX_TRIES
else: self.max_reconnect_tries = max_reconnect_tries
if connected_socket != None:
self.receives = True
@@ -461,15 +389,12 @@ class I2PInterfacePeer(Interface):
self.target_port = None
self.socket = connected_socket
if platform.system() == "Linux":
self.set_timeouts_linux()
elif platform.system() == "Darwin":
self.set_timeouts_osx()
if platform.system() == "Linux": self.set_timeouts_linux()
elif platform.system() == "Darwin": self.set_timeouts_osx()
elif target_i2p_dest != None:
self.receives = True
self.initiator = True
self.bind_ip = "127.0.0.1"
self.awaiting_i2p_tunnel = True
@@ -497,12 +422,10 @@ class I2PInterfacePeer(Interface):
thread.start()
def wait_job():
while self.awaiting_i2p_tunnel:
time.sleep(0.25)
while self.awaiting_i2p_tunnel: time.sleep(0.25)
time.sleep(2)
if not self.kiss_framing:
self.wants_tunnel = True
if not self.kiss_framing: self.wants_tunnel = True
if not self.connect(initial=True):
thread = threading.Thread(target=self.reconnect)
@@ -517,7 +440,6 @@ class I2PInterfacePeer(Interface):
thread.daemon = True
thread.start()
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.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))
def set_timeouts_osx(self):
if hasattr(socket, "TCP_KEEPALIVE"):
TCP_KEEPIDLE = socket.TCP_KEEPALIVE
else:
TCP_KEEPIDLE = 0x10
if hasattr(socket, "TCP_KEEPALIVE"): TCP_KEEPIDLE = socket.TCP_KEEPALIVE
else: TCP_KEEPIDLE = 0x10
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
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):
if callable(target_socket.close):
try:
if socket != None:
target_socket.shutdown(socket.SHUT_RDWR)
except Exception as e:
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
if socket != None: target_socket.shutdown(socket.SHUT_RDWR)
except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try:
if socket != None:
target_socket.close()
except Exception as e:
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
if socket != None: target_socket.close()
except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
def detach(self):
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
@@ -555,15 +471,11 @@ class I2PInterfacePeer(Interface):
if callable(self.socket.close):
self.detached = True
try:
self.socket.shutdown(socket.SHUT_RDWR)
except Exception as e:
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try: self.socket.shutdown(socket.SHUT_RDWR)
except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try:
self.socket.close()
except Exception as e:
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
try: self.socket.close()
except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
self.socket = None
@@ -578,23 +490,17 @@ class I2PInterfacePeer(Interface):
if not self.awaiting_i2p_tunnel:
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)
return False
else:
raise e
else: raise e
if platform.system() == "Linux":
self.set_timeouts_linux()
elif platform.system() == "Darwin":
self.set_timeouts_osx()
if platform.system() == "Linux": self.set_timeouts_linux()
elif platform.system() == "Darwin": self.set_timeouts_osx()
self.online = True
self.writing = False
self.never_connected = False
if not self.kiss_framing and self.wants_tunnel:
RNS.Transport.synthesize_tunnel(self)
if not self.kiss_framing and self.wants_tunnel: RNS.Transport.synthesize_tunnel(self)
return True
@@ -612,14 +518,10 @@ class I2PInterfacePeer(Interface):
self.teardown()
break
try:
self.connect()
try: self.connect()
except Exception as e:
if not self.awaiting_i2p_tunnel:
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)
if not self.awaiting_i2p_tunnel: 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)
if not self.never_connected:
RNS.log(str(self)+" Re-established connection via I2P tunnel", RNS.LOG_INFO)
@@ -628,40 +530,35 @@ class I2PInterfacePeer(Interface):
thread = threading.Thread(target=self.read_loop)
thread.daemon = True
thread.start()
if not self.kiss_framing:
RNS.Transport.synthesize_tunnel(self)
if not self.kiss_framing: RNS.Transport.synthesize_tunnel(self)
else:
RNS.log("Attempt to reconnect on a non-initiator I2P interface. This should not happen.", RNS.LOG_ERROR)
raise IOError("Attempt to reconnect on a non-initiator I2P interface")
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
self.parent_interface.rxb += len(data)
self.owner.inbound(data, self)
def process_outgoing(self, data):
if self.online:
while self.writing:
time.sleep(0.001)
while self.writing: time.sleep(0.001)
try:
self.writing = True
if self.kiss_framing:
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])
if self.kiss_framing: 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])
self.socket.sendall(data)
self.writing = False
self.txb += len(data)
self.last_write = time.time()
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
self.parent_interface.txb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count: self.parent_interface.txb += len(data)
except Exception as e:
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
@@ -670,8 +567,7 @@ class I2PInterfacePeer(Interface):
def read_watchdog(self):
while self.wd_reset:
time.sleep(0.25)
while self.wd_reset: time.sleep(0.25)
should_run = True
try:
@@ -679,17 +575,13 @@ class I2PInterfacePeer(Interface):
time.sleep(1)
if (time.time()-self.last_read > I2PInterfacePeer.I2P_PROBE_AFTER*2):
if self.i2p_tunnel_state != I2PInterfacePeer.TUNNEL_STATE_STALE:
RNS.log("I2P tunnel became unresponsive", RNS.LOG_DEBUG)
if self.i2p_tunnel_state != I2PInterfacePeer.TUNNEL_STATE_STALE: RNS.log("I2P tunnel became unresponsive", RNS.LOG_DEBUG)
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_STALE
else:
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_ACTIVE
else: self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_ACTIVE
if (time.time()-self.last_write > I2PInterfacePeer.I2P_PROBE_AFTER*1):
try:
if self.socket != None:
self.socket.sendall(bytes([HDLC.FLAG, HDLC.FLAG]))
if self.socket != None: self.socket.sendall(bytes([HDLC.FLAG, HDLC.FLAG]))
except Exception as e:
RNS.log("An error ocurred while sending I2P keepalive. The contained exception was: "+str(e), RNS.LOG_ERROR)
self.shutdown_socket(self.socket)
@@ -698,22 +590,17 @@ class I2PInterfacePeer(Interface):
if (time.time()-self.last_read > I2PInterfacePeer.I2P_READ_TIMEOUT):
RNS.log("I2P socket is unresponsive, restarting...", RNS.LOG_WARNING)
if self.socket != None:
try:
self.socket.shutdown(socket.SHUT_RDWR)
except Exception as e:
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try: self.socket.shutdown(socket.SHUT_RDWR)
except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try:
self.socket.close()
except Exception as e:
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
try: self.socket.close()
except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
should_run = False
self.wd_reset = False
finally:
self.wd_reset = False
finally: self.wd_reset = False
def read_loop(self):
try:
@@ -784,7 +671,6 @@ class I2PInterfacePeer(Interface):
data_buffer = data_buffer+bytes([byte])
else:
self.online = False
self.wd_reset = True
time.sleep(2)
self.wd_reset = False
@@ -806,15 +692,12 @@ class I2PInterfacePeer(Interface):
if self.initiator:
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
self.reconnect()
else:
self.teardown()
else: self.teardown()
def teardown(self):
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)
if RNS.Reticulum.panic_on_interface_error:
RNS.panic()
if RNS.Reticulum.panic_on_interface_error: RNS.panic()
else:
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE)
@@ -826,10 +709,7 @@ class I2PInterfacePeer(Interface):
while self in self.parent_interface.spawned_interfaces:
self.parent_interface.spawned_interfaces.remove(self)
if self in RNS.Transport.interfaces:
if not self.initiator:
RNS.Transport.interfaces.remove(self)
if not self.initiator: RNS.Transport.remove_interface(self)
def __str__(self):
return "I2PInterfacePeer["+str(self.name)+"]"
@@ -840,8 +720,7 @@ class I2PInterface(Interface):
DEFAULT_IFAC_SIZE = 16
@property
def clients(self):
return len(self.spawned_interfaces)
def clients(self): return len(self.spawned_interfaces)
def __init__(self, owner, configuration):
super().__init__()
@@ -895,11 +774,9 @@ class I2PInterface(Interface):
RNS.log("I2P controller did not become available in time, waiting for controller", RNS.LOG_VERBOSE)
i2p_notready_warning = True
while not self.i2p.ready:
time.sleep(0.25)
while not self.i2p.ready: time.sleep(0.25)
if i2p_notready_warning == True:
RNS.log("I2P controller ready, continuing setup", RNS.LOG_VERBOSE)
if i2p_notready_warning == True: RNS.log("I2P controller ready, continuing setup", RNS.LOG_VERBOSE)
def handlerFactory(callback):
def createHandler(*args, **keys):
@@ -940,7 +817,7 @@ class I2PInterface(Interface):
peer_interface.IN = True
peer_interface.parent_interface = self
peer_interface.parent_count = False
RNS.Transport.interfaces.append(peer_interface)
RNS.Transport.add_interface(peer_interface)
def incoming_connection(self, handler):
RNS.log("Accepting incoming I2P connection", RNS.LOG_VERBOSE)
@@ -957,6 +834,11 @@ class I2PInterface(Interface):
spawned_interface.ic_new_time = self.ic_new_time
spawned_interface.ic_burst_penalty = self.ic_burst_penalty
spawned_interface.ic_held_release_interval = self.ic_held_release_interval
spawned_interface.egress_control = self.egress_control
spawned_interface.ec_pr_freq = self.ec_pr_freq
spawned_interface.ic_pr_burst_freq_new = self.ic_pr_burst_freq_new
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
spawned_interface.parent_interface = self
spawned_interface.online = True
@@ -967,18 +849,11 @@ class I2PInterface(Interface):
spawned_interface.ifac_netkey = self.ifac_netkey
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
ifac_origin = b""
if spawned_interface.ifac_netname != None:
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_netname != None: 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"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
spawned_interface.ifac_key = RNS.Cryptography.hkdf(
length=64,
derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT,
context=None
)
spawned_interface.ifac_key = RNS.Cryptography.hkdf(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_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
@@ -986,34 +861,46 @@ class I2PInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU
RNS.log("Spawned new I2PInterface Peer: "+str(spawned_interface), RNS.LOG_VERBOSE)
RNS.Transport.interfaces.append(spawned_interface)
while spawned_interface in self.spawned_interfaces:
self.spawned_interfaces.remove(spawned_interface)
RNS.Transport.add_interface(spawned_interface)
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.append(spawned_interface)
spawned_interface.read_loop()
def process_outgoing(self, data):
pass
def received_announce(self, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time())
def received_announce(self, size=0, from_spawned=False):
if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time())
def sent_announce(self, size=0, from_spawned=False):
if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def detach(self):
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
self.i2p.stop()
def __str__(self):
return "I2PInterface["+self.name+"]"
def __str__(self): return "I2PInterface["+self.name+"]"
class I2PInterfaceHandler(socketserver.BaseRequestHandler):
def __init__(self, callback, *args, **keys):
self.callback = callback
socketserver.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self):
self.callback(handler=self)
def handle(self): self.callback(handler=self)
+227 -70
View File
@@ -48,69 +48,138 @@ class Interface:
MODE_ROAMING = 0x04
MODE_BOUNDARY = 0x05
MODE_GATEWAY = 0x06
MODE_INTERNAL = 0x07
# Which interface modes a Transport Node should
# actively discover paths for.
DISCOVER_PATHS_FOR = [MODE_ACCESS_POINT, MODE_GATEWAY, MODE_ROAMING]
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
# frequency calculations
IA_FREQ_SAMPLES = 128
OA_FREQ_SAMPLES = 128
IA_FREQ_SAMPLES = 48
OA_FREQ_SAMPLES = 48
IP_FREQ_SAMPLES = 48
OP_FREQ_SAMPLES = 48
AR_MINFREQ_HZ = 0.1
PR_MINFREQ_HZ = 0.1
AR_FREQ_DECAY = 1/AR_MINFREQ_HZ
PR_FREQ_DECAY = 1/PR_MINFREQ_HZ
# Maximum amount of ingress limited announces
# to hold at any given time.
MAX_HELD_ANNOUNCES = 256
# How long a spawned interface will be
# considered to be newly created. Two
# hours by default.
# Control parameters
DEFAULT_GRAVITY = 0
IC_NEW_TIME = 2*60*60
IC_BURST_FREQ_NEW = 6
IC_BURST_FREQ = 35
IC_BURST_HOLD = 1*60
IC_BURST_FREQ_NEW = 3
IC_BURST_FREQ = 10
IC_PR_BURST_FREQ_NEW = 3
IC_PR_BURST_FREQ = 8
IC_BURST_HOLD = 15
IC_BURST_PENALTY = 15
IC_HELD_RELEASE_INTERVAL = 2
IC_DEQUE_MIN_SAMPLE = 32
IC_HELD_RELEASE_INTERVAL = 5
IC_DEQUE_MIN_SAMPLE = 2
EC_BURST_MIN_SAMPLES = 2
EC_PR_FREQ = 5
EGRESS_CONTROL = False
# Default announce rate targets
DEFAULT_AR_TARGET = 3600
DEFAULT_AR_PENALTY = 0
DEFAULT_AR_GRACE = 5
AUTOCONFIGURE_MTU = False
FIXED_MTU = False
DEFAULT_IFAC_SIZE = 16
def __init__(self):
self.rxb = 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.detached = False
self.online = False
self.bitrate = 62500
self.HW_MTU = None
self.__hash = None
self.supports_discovery = False
self.discoverable = False
self.last_discovery_announce = 0
self.bootstrap_only = False
self.parent_interface = None
self.spawned_interfaces = None
self.tunnel_id = None
self.ingress_control = True
self.phy_keepalive = False
self.ic_max_held_announces = Interface.MAX_HELD_ANNOUNCES
self.ic_burst_hold = Interface.IC_BURST_HOLD
self.ic_burst_active = False
self.ic_burst_activated = 0
self.ic_held_release = 0
self.ic_burst_freq_new = Interface.IC_BURST_FREQ_NEW
self.ic_burst_freq = Interface.IC_BURST_FREQ
self.ic_new_time = Interface.IC_NEW_TIME
self.ic_burst_penalty = Interface.IC_BURST_PENALTY
self.ic_held_release_interval = Interface.IC_HELD_RELEASE_INTERVAL
self.held_announces = {}
self.supports_discovery = False
self.discoverable = False
self.last_discovery_announce = 0
self.bootstrap_only = False
self.recursive_prs = False
self.announces_from_internal = True
self.announces_to_internal = None
self.parent_interface = None
self.spawned_interfaces = None
self.tunnel_id = None
self.ingress_control = True
self.phy_keepalive = False
self.shared_medium = False
self.ic_burst_active = False
self.ic_burst_activated = 0
self.ic_burst_sustained = 0
self.ic_pr_burst_active = False
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_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_freq_new = RNS.Reticulum.get_instance()._default_ic_burst_freq_new()
self.ic_burst_freq = RNS.Reticulum.get_instance()._default_ic_burst_freq()
self.ic_pr_burst_freq_new = RNS.Reticulum.get_instance()._default_ic_pr_burst_freq_new()
self.ic_pr_burst_freq = RNS.Reticulum.get_instance()._default_ic_pr_burst_freq()
self.ic_new_time = RNS.Reticulum.get_instance()._default_ic_new_time()
self.ic_burst_penalty = RNS.Reticulum.get_instance()._default_ic_burst_penalty()
self.ic_held_release_interval = RNS.Reticulum.get_instance()._default_ic_held_release_interval()
self.ec_pr_freq = RNS.Reticulum.get_instance()._default_ec_pr_freq()
self.egress_control = RNS.Reticulum.get_instance()._default_egress_control()
self.held_announces = {}
self.transmit_buffer = None
self.ia_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
self.oa_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
self.ip_freq_deque = deque(maxlen=Interface.IA_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
self.dp_ingress_tcount = 0
self.dp_ingress_bytes = 0
self.dp_ingress_packets = 0
self.dp_ingress_hold = None
self.dp_ingress_gated = False
self.tx_hwm = 4*1024*1024
self.tx_stalled = False
self.tx_drops = 0
self.tx_dropped_bytes = 0
self._dp_ec_prev_sent = 0
self._dp_ec_zero_ticks = 0
self._dp_ec_last_drain = time.time()
self.reports_phy_stats = False
self.r_stat_rssi = None
self.r_stat_snr = None
self.r_stat_q = None
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
# should activate ingress limiting. Since this can vary for
@@ -122,8 +191,10 @@ class Interface:
ia_freq = self.incoming_announce_frequency()
if self.ic_burst_active:
if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold:
self.ic_burst_active = False
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_DEQUE_MIN_SAMPLE: self.ic_burst_active = False
else:
if ia_freq >= freq_threshold: self.ic_burst_sustained = time.time()
return True
@@ -131,6 +202,7 @@ class Interface:
if ia_freq > freq_threshold:
self.ic_burst_active = True
self.ic_burst_activated = time.time()
self.ic_burst_sustained = time.time()
self.ic_held_release = time.time() + self.ic_burst_penalty
return True
@@ -138,38 +210,66 @@ class Interface:
else: return False
def should_ingress_limit_pr(self):
if self.ingress_control:
freq_threshold = self.ic_pr_burst_freq_new if self.age() < self.ic_new_time else self.ic_pr_burst_freq
ip_freq = self.incoming_pr_frequency()
if self.ic_pr_burst_active:
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:
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
else:
if ip_freq > freq_threshold:
self.ic_pr_burst_active = True
self.ic_pr_burst_activated = time.time()
self.ic_pr_burst_sustained = time.time()
self.ic_pr_burst_cooldown = 3
return True
else: return False
else: return False
def should_egress_limit_pr(self):
if self.egress_control:
freq_threshold = self.ec_pr_freq
op_freq = self.outgoing_pr_frequency(preemptive=True)
if op_freq > freq_threshold:
if len(self.op_freq_deque) >= self.EC_BURST_MIN_SAMPLES: return True
return False
def optimise_mtu(self):
if self.AUTOCONFIGURE_MTU:
if self.bitrate >= 1_000_000_000:
self.HW_MTU = 524288
elif self.bitrate > 750_000_000:
self.HW_MTU = 262144
elif self.bitrate > 400_000_000:
self.HW_MTU = 131072
elif self.bitrate > 200_000_000:
self.HW_MTU = 65536
elif self.bitrate > 100_000_000:
self.HW_MTU = 32768
elif self.bitrate > 10_000_000:
self.HW_MTU = 16384
elif self.bitrate > 5_000_000:
self.HW_MTU = 8192
elif self.bitrate > 2_000_000:
self.HW_MTU = 4096
elif self.bitrate > 1_000_000:
self.HW_MTU = 2048
elif self.bitrate > 62_500:
self.HW_MTU = 1024
else:
self.HW_MTU = None
if self.bitrate >= 1_000_000_000: self.HW_MTU = 524288
elif self.bitrate >= 750_000_000: self.HW_MTU = 262144
elif self.bitrate >= 400_000_000: self.HW_MTU = 131072
elif self.bitrate >= 200_000_000: self.HW_MTU = 65536
elif self.bitrate >= 100_000_000: self.HW_MTU = 32768
elif self.bitrate >= 10_000_000: self.HW_MTU = 16384
elif self.bitrate >= 5_000_000: self.HW_MTU = 8192
elif self.bitrate >= 2_000_000: self.HW_MTU = 4096
elif self.bitrate >= 1_000_000: self.HW_MTU = 2048
elif self.bitrate >= 62_500: self.HW_MTU = 1024
else: self.HW_MTU = None
RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_DEBUG) # TODO: Remove debug
RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_EXTREME)
def age(self):
return time.time()-self.created
def hold_announce(self, announce_packet):
if announce_packet.destination_hash in self.held_announces:
if announce_packet.hops >= RNS.Transport.PATHFINDER_M-1:
return
elif announce_packet.destination_hash in self.held_announces:
self.held_announces[announce_packet.destination_hash] = announce_packet
elif not len(self.held_announces) >= self.ic_max_held_announces:
self.held_announces[announce_packet.destination_hash] = announce_packet
@@ -192,22 +292,56 @@ class Interface:
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.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()
except Exception as e:
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)
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())
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())
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, size=0, from_spawned=False):
self.prxc += 1; self.prxb += size
self.ip_freq_deque.append(time.time())
if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.received_path_request(size=size, from_spawned=True)
def sent_path_request(self, size=0, from_spawned=False):
self.ptxc += 1; self.ptxb += size
self.op_freq_deque.append(time.time())
if hasattr(self, "parent_interface") and self.parent_interface != None:
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):
n = len(self.ia_freq_deque)
@@ -215,6 +349,7 @@ class Interface:
else:
oldest = self.ia_freq_deque[0]
span = time.time() - oldest
if span > self.AR_FREQ_DECAY: self.ia_freq_deque.popleft()
if span <= 0: return 0
hz = n / span
return hz
@@ -225,6 +360,29 @@ class Interface:
else:
oldest = self.oa_freq_deque[0]
span = time.time() - oldest
if span > self.AR_FREQ_DECAY: self.oa_freq_deque.popleft()
if span <= 0: return 0
hz = n / span
return hz
def incoming_pr_frequency(self):
n = len(self.ip_freq_deque)
if not n > self.IC_DEQUE_MIN_SAMPLE: return 0
else:
oldest = self.ip_freq_deque[0]
span = time.time() - oldest
if span > self.PR_FREQ_DECAY: self.ip_freq_deque.popleft()
if span <= 0: return 0
hz = n / span
return hz
def outgoing_pr_frequency(self, preemptive=False):
n = len(self.op_freq_deque)+(1 if preemptive else 0)
if not len(self.op_freq_deque) > 1: return 0
else:
oldest = self.op_freq_deque[0]
span = time.time() - oldest
if span > self.PR_FREQ_DECAY: self.op_freq_deque.popleft()
if span <= 0: return 0
hz = n / span
return hz
@@ -252,12 +410,13 @@ class Interface:
selected = entries[0]
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)
self.announce_allowed_at = now + wait_time
self.process_outgoing(selected["raw"])
self.sent_announce()
RNS.Transport.transmit(self, selected["raw"])
self.sent_announce(tx_size)
if selected in self.announce_queue:
self.announce_queue.remove(selected)
@@ -279,11 +438,9 @@ class Interface:
@staticmethod
def get_config_obj(config_in):
if type(config_in) == ConfigObj:
return config_in
if type(config_in) == ConfigObj: return config_in
else:
try:
return ConfigObj(config_in)
try: return ConfigObj(config_in)
except Exception as e:
RNS.log(f"Could not parse supplied configuration data. The contained exception was: {e}", RNS.LOG_ERROR)
raise SystemError("Invalid configuration data supplied")
+2
View File
@@ -122,6 +122,7 @@ class KISSInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.flow_control_timeout = 5
self.flow_control_locked = time.time()
@@ -245,6 +246,7 @@ class KISSInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+45 -52
View File
@@ -30,6 +30,8 @@
from RNS.Interfaces.Interface import Interface
from RNS.Interfaces.BackboneInterface import BackboneInterface
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
import socketserver
import threading
import socket
@@ -39,17 +41,6 @@ import os
import RNS
from threading import Lock
class HDLC():
FLAG = 0x7E
ESC = 0x7D
ESC_MASK = 0x20
@staticmethod
def escape(data):
data = data.replace(bytes([HDLC.ESC]), bytes([HDLC.ESC, HDLC.ESC^HDLC.ESC_MASK]))
data = data.replace(bytes([HDLC.FLAG]), bytes([HDLC.ESC, HDLC.FLAG^HDLC.ESC_MASK]))
return data
class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def server_bind(self):
if RNS.vendor.platformutils.is_windows():
@@ -70,6 +61,7 @@ class LocalClientInterface(Interface):
self.epoll_backend = False
self.HW_MTU = 262144
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}"
else: self.socket_path = None
@@ -83,8 +75,9 @@ class LocalClientInterface(Interface):
self.detached = False
self.name = name
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.frame_buffer = b""
self.transmit_buffer = b""
self.transmit_buffer = TransmitBuffer()
self.receive_buffer = ReceiveBuffer(mtu=lambda: self.HW_MTU, min_frame_len=RNS.Reticulum.HEADER_MINSIZE,
max_frame_len=lambda: self.HW_MTU, on_frame=self.process_incoming)
if RNS.vendor.platformutils.use_epoll(): self.epoll_backend = True
@@ -194,15 +187,15 @@ class LocalClientInterface(Interface):
def send_keepalive(self):
if self.online:
RNS.log(f"Sending keepalive on {self}", RNS.LOG_DEBUG) # TODO: Remove
RNS.log(f"Sending keepalive on {self}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
try:
if self.epoll_backend:
self.transmit_buffer += bytes([HDLC.FLAG])+bytes([HDLC.FLAG])
self.transmit_buffer.append(bytes([HDLC.FLAG])+bytes([HDLC.FLAG]))
BackboneInterface.tx_ready(self)
else:
self.writing = True
data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
data = bytes([HDLC.FLAG])+bytes([HDLC.FLAG])
self.socket.sendall(data)
self.writing = False
@@ -219,28 +212,30 @@ class LocalClientInterface(Interface):
def process_outgoing(self, data):
if self.pause_on_client_sleep and time.time() > self.pause_timeout:
RNS.log(f"TX paused for LocalInterface client, dropping outbound packet", RNS.LOG_DEBUG) # TODO: Remove
RNS.log(f"TX paused for LocalInterface client, dropping outbound packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None # TODO: Remove
return
if self.online:
try:
if self.epoll_backend:
self.transmit_buffer += bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
BackboneInterface.tx_ready(self)
frame = HDLC.frame(data)
if self.tx_stalled or not self.transmit_buffer.append(frame, self.tx_hwm):
self.tx_drops += 1
self.tx_dropped_bytes += len(frame)
RNS.log(f"Egress control dropping outbound frame of {RNS.prettysize(len(frame))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
else: BackboneInterface.tx_ready(self)
else:
self.writing = True
if self._force_bitrate:
if not hasattr(self, "send_lock"):
self.send_lock = Lock()
if not hasattr(self, "send_lock"): self.send_lock = Lock()
with self.send_lock:
# RNS.log(f"Simulating latency of {RNS.prettytime(s)} for {len(data)} bytes", RNS.LOG_EXTREME)
s = len(data) / self.bitrate * 8
time.sleep(s)
data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
data = HDLC.frame(data)
self.socket.sendall(data)
self.writing = False
self.txb += len(data)
@@ -254,22 +249,7 @@ class LocalClientInterface(Interface):
self.teardown()
def handle_hdlc(self, data_in):
self.frame_buffer += data_in
flags_remaining = True
while flags_remaining:
frame_start = self.frame_buffer.find(HDLC.FLAG)
if frame_start != -1:
frame_end = self.frame_buffer.find(HDLC.FLAG, frame_start+1)
if frame_end != -1:
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.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > RNS.Reticulum.HEADER_MINSIZE: self.process_incoming(frame)
self.frame_buffer = self.frame_buffer[frame_end:]
else: flags_remaining = False
else: flags_remaining = False
self.receive_buffer.feed(data_in)
def receive(self, data_in):
try:
@@ -283,8 +263,7 @@ class LocalClientInterface(Interface):
# there's no other connectivity left to block anyway, it might be
# unnecessary.
self.reconnect()
else:
self.teardown(nowarning=True)
else: self.teardown(nowarning=True)
except Exception as e:
self.online = False
@@ -296,7 +275,7 @@ class LocalClientInterface(Interface):
def read_loop(self):
try:
self.frame_buffer = b""
self.receive_buffer.reset()
data_in = b""
while True:
data_in = self.socket.recv(4096)
@@ -347,8 +326,7 @@ class LocalClientInterface(Interface):
self.OUT = False
self.IN = False
if self in RNS.Transport.interfaces:
RNS.Transport.interfaces.remove(self)
RNS.Transport.remove_interface(self)
if self in RNS.Transport.local_client_interfaces:
RNS.Transport.local_client_interfaces.remove(self)
@@ -383,6 +361,7 @@ class LocalServerInterface(Interface):
self.epoll_backend = False
self.online = False
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}"
else: self.socket_path = None
@@ -430,6 +409,7 @@ class LocalServerInterface(Interface):
self.announce_rate_grace = None
self.announce_rate_penalty = None
self.HW_MTU = 262144
self.bitrate = 1000*1000*1000
self.online = True
@@ -458,7 +438,7 @@ class LocalServerInterface(Interface):
spawned_interface.socket_path = self.socket_path
if hasattr(self, "_force_bitrate"): spawned_interface._force_bitrate = self._force_bitrate
RNS.Transport.interfaces.append(spawned_interface)
RNS.Transport.add_interface(spawned_interface)
RNS.Transport.local_client_interfaces.append(spawned_interface)
BackboneInterface.add_client_socket(client_socket, spawned_interface)
self.clients += 1
@@ -474,7 +454,7 @@ class LocalServerInterface(Interface):
spawned_interface.parent_interface = self
spawned_interface.bitrate = self.bitrate
if hasattr(self, "_force_bitrate"): spawned_interface._force_bitrate = self._force_bitrate
RNS.Transport.interfaces.append(spawned_interface)
RNS.Transport.add_interface(spawned_interface)
RNS.Transport.local_client_interfaces.append(spawned_interface)
self.clients += 1
spawned_interface.read_loop()
@@ -482,11 +462,25 @@ class LocalServerInterface(Interface):
def process_outgoing(self, data):
pass
def received_announce(self, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time())
def received_announce(self, size=0, from_spawned=False):
if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time())
def sent_announce(self, size=0, from_spawned=False):
if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def __str__(self):
if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]"
@@ -497,5 +491,4 @@ class LocalInterfaceHandler(socketserver.BaseRequestHandler):
self.callback = callback
socketserver.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self):
self.callback(handler=self)
def handle(self): self.callback(handler=self)
+2
View File
@@ -84,6 +84,7 @@ class PipeInterface(Interface):
self.pipe_is_open = False
self.bitrate = PipeInterface.BITRATE_GUESS
self.respawn_delay = respawn_delay
self.shared_medium = True
try:
self.open_pipe()
@@ -119,6 +120,7 @@ class PipeInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+33 -12
View File
@@ -258,6 +258,7 @@ class RNodeInterface(Interface):
self.r_stat_tx = None
self.r_stat_rssi = None
self.r_stat_snr = None
self.r_stat_q = None
self.r_st_alock = None
self.r_lt_alock = None
self.r_random = None
@@ -278,6 +279,7 @@ class RNodeInterface(Interface):
self.r_noise_floor = None
self.r_interference = None
self.r_interference_l = None
self.reports_phy_stats = True
self.r_battery_state = RNodeInterface.BATTERY_STATE_UNKNOWN
self.r_battery_percent = 0
@@ -294,6 +296,7 @@ class RNodeInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.announce_rate_target = None
self.supports_discovery = True
@@ -383,6 +386,7 @@ class RNodeInterface(Interface):
RNS.log(f"Opening BLE connection for {self}...")
self.timeout = 1250
if self.ble != None and self.ble.running == False:
RNS.log(f"Cleaning up previous BLE connection for {self}...")
self.ble.close()
self.ble.cleanup()
self.ble = None
@@ -439,7 +443,11 @@ class RNodeInterface(Interface):
ble_detect_timeout = 5.0
detect_time = time.time()
while not self.detected and time.time() < detect_time + ble_detect_timeout: time.sleep(0.1)
if not self.detected: RNS.log(f"RNode detect timed out over BLE", RNS.LOG_ERROR)
if not self.detected:
RNS.log(f"RNode detect timed out over BLE", RNS.LOG_ERROR)
if self.ble:
self.ble.should_run = False
self.ble.must_disconnect = True
else:
sleep(0.2)
@@ -477,8 +485,7 @@ class RNodeInterface(Interface):
self.setLTALock()
self.setRadioState(KISS.RADIO_STATE_ON)
if self.use_ble:
time.sleep(2)
if self.use_ble: time.sleep(2)
def detect(self):
kiss_command = bytes([KISS.FEND, KISS.CMD_DETECT, KISS.DETECT_REQ, KISS.FEND, KISS.CMD_FW_VERSION, 0x00, KISS.FEND, KISS.CMD_PLATFORM, 0x00, KISS.FEND, KISS.CMD_MCU, 0x00, KISS.FEND])
@@ -684,10 +691,8 @@ class RNodeInterface(Interface):
RNS.log("Radio state mismatch", RNS.LOG_ERROR)
self.validcfg = False
if (self.validcfg):
return True
else:
return False
if (self.validcfg): return True
else: return False
def updateBitrate(self):
@@ -699,11 +704,9 @@ class RNodeInterface(Interface):
self.bitrate = 0
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
self.r_stat_rssi = None
self.r_stat_snr = None
def process_outgoing(self,data):
datalen = len(data)
@@ -1297,6 +1300,7 @@ class BLEConnection():
self.must_disconnect = False
self.connect_job_running = False
self.device_disappeared = False
self._windows_paired_addrs = None
import importlib.util
if BLEConnection.bleak == None:
@@ -1307,8 +1311,8 @@ class BLEConnection():
import asyncio
BLEConnection.asyncio = asyncio
else:
RNS.log("Using the RNode interface over BLE requires a the \"bleak\" module to be installed.", RNS.LOG_CRITICAL)
RNS.log("You can install one with the command: python3 -m pip install bleak", RNS.LOG_CRITICAL)
RNS.log("Using the RNode interface over BLE requires the \"bleak\" module to be installed.", RNS.LOG_CRITICAL)
RNS.log("You can install it with the command: python3 -m pip install bleak", RNS.LOG_CRITICAL)
RNS.panic()
self.should_run = True
@@ -1324,6 +1328,7 @@ class BLEConnection():
self.should_run = False
def connection_job(self):
self.running = True
while self.should_run:
if self.ble_device == None:
self.ble_device = self.find_target_device()
@@ -1350,6 +1355,7 @@ class BLEConnection():
self.owner.ble_receive(data)
self.connected = True
self.device_disappeared = False
self.ble_device = ble_client
self.last_client = ble_client
self.owner.port = str(f"ble://{ble_client.address}")
@@ -1384,6 +1390,9 @@ class BLEConnection():
def find_target_device(self):
RNS.log(f"Searching for attachable BLE device for {self.owner}...", RNS.LOG_EXTREME)
import platform
if RNS.vendor.platformutils.is_windows():
self._windows_paired_addrs = self._get_windows_paired_ble_addresses()
def device_filter(device: self.bleak.backends.device.BLEDevice, adv: self.bleak.backends.scanner.AdvertisementData):
if BLEConnection.UART_SERVICE_UUID.lower() in adv.service_uuids:
if self.device_bonded(device):
@@ -1415,6 +1424,9 @@ class BLEConnection():
def device_bonded(self, device):
try:
if self._windows_paired_addrs is not None:
return device.address is not None and device.address.lower() in self._windows_paired_addrs
if hasattr(device, "details"):
if "props" in device.details and "Bonded" in device.details["props"]:
if device.details["props"]["Bonded"] == True:
@@ -1425,6 +1437,15 @@ class BLEConnection():
return False
def _get_windows_paired_ble_addresses(self):
from winrt.windows.devices.bluetooth import BluetoothLEDevice
from winrt.windows.devices.enumeration import DeviceInformation
async def _query():
selector = BluetoothLEDevice.get_device_selector_from_pairing_state(True)
infos = await DeviceInformation.find_all_async_aqs_filter(selector)
return set(info.id.split("-")[-1].lower() for info in infos)
return self.asyncio.run(_query())
class TCPConnection():
TARGET_PORT = 7633
CONNECT_TIMEOUT = 5.0
+25 -9
View File
@@ -269,6 +269,7 @@ class RNodeMultiInterface(Interface):
self.r_stat_tx = None
self.r_stat_rssi = None
self.r_stat_snr = None
self.r_stat_q = None
self.r_st_alock = None
self.r_lt_alock = None
self.r_random = None
@@ -276,6 +277,8 @@ class RNodeMultiInterface(Interface):
self.packet_queue = []
self.interface_ready = False
self.announce_rate_target = None
self.reports_phy_stats = True
self.validcfg = True
if id_interval != None and id_callsign != None:
@@ -375,7 +378,7 @@ class RNodeMultiInterface(Interface):
interface.mode = self.mode
interface.HW_MTU = self.HW_MTU
interface.detected = True
RNS.Transport.interfaces.append(interface)
RNS.Transport.add_interface(interface)
RNS.log("Spawned new RNode subinterface: "+str(interface), RNS.LOG_VERBOSE)
self.clients += 1
@@ -543,11 +546,25 @@ class RNodeMultiInterface(Interface):
if written != len(frame):
raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data)))
def received_announce(self, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time())
def received_announce(self, size=0, from_spawned=False):
if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time())
def sent_announce(self, size=0, from_spawned=False):
if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def readLoop(self):
try:
@@ -903,8 +920,7 @@ class RNodeMultiInterface(Interface):
def teardown_subinterfaces(self):
for interface in self.subinterfaces:
if interface != 0:
if interface in RNS.Transport.interfaces:
RNS.Transport.interfaces.remove(interface)
RNS.Transport.remove_interface(interface)
self.subinterfaces[interface.index] = 0
def should_ingress_limit(self):
@@ -988,6 +1004,7 @@ class RNodeSubInterface(Interface):
self.r_premable_time_ms = None
self.packet_queue = []
self.shared_medium = True
self.interface_ready = False
self.parent_interface = parent_interface
self.announce_rate_target = None
@@ -1111,10 +1128,9 @@ class RNodeSubInterface(Interface):
self.bitrate = 0
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
self.r_stat_rssi = None
self.r_stat_snr = None
def process_outgoing(self,data):
if self.online:
+2
View File
@@ -83,6 +83,7 @@ class SerialInterface(Interface):
raise ValueError("No port specified for serial interface")
self.HW_MTU = 564
self.shared_medium = True
self.pyserial = serial
self.serial = None
@@ -142,6 +143,7 @@ class SerialInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+44 -11
View File
@@ -302,6 +302,7 @@ class TCPClientInterface(Interface):
raise IOError("Attempt to reconnect on a non-initiator TCP interface")
def process_incoming(self, data):
if not data: return
if self.online and not self.detached:
self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None:
@@ -333,6 +334,13 @@ class TCPClientInterface(Interface):
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
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):
try:
@@ -389,12 +397,18 @@ class TCPClientInterface(Interface):
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.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > RNS.Reticulum.HEADER_MINSIZE:
self.process_incoming(frame)
frame_len = len(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:]
else:
if len(frame_buffer) > self.HW_MTU*2: frame_buffer = b""
flags_remaining = False
else:
frame_buffer = b""
flags_remaining = False
else:
@@ -403,7 +417,7 @@ class TCPClientInterface(Interface):
RNS.log("The socket for "+str(self)+" was closed, attempting to reconnect...", RNS.LOG_WARNING)
self.reconnect()
else:
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_VERBOSE)
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_DEBUG)
self.teardown()
break
@@ -436,9 +450,8 @@ class TCPClientInterface(Interface):
while self in self.parent_interface.spawned_interfaces:
self.parent_interface.spawned_interfaces.remove(self)
if self in RNS.Transport.interfaces:
if not self.initiator:
RNS.Transport.interfaces.remove(self)
if not self.initiator:
RNS.Transport.remove_interface(self)
def __str__(self):
@@ -589,6 +602,11 @@ class TCPServerInterface(Interface):
spawned_interface.ic_burst_penalty = self.ic_burst_penalty
spawned_interface.ic_held_release_interval = self.ic_held_release_interval
spawned_interface.egress_control = self.egress_control
spawned_interface.ec_pr_freq = self.ec_pr_freq
spawned_interface.ic_pr_burst_freq_new = self.ic_pr_burst_freq_new
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
spawned_interface.target_ip = handler.client_address[0]
spawned_interface.target_port = str(handler.client_address[1])
spawned_interface.parent_interface = self
@@ -619,20 +637,35 @@ class TCPServerInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True
RNS.log("Spawned new TCPClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
RNS.Transport.interfaces.append(spawned_interface)
RNS.Transport.add_interface(spawned_interface)
while spawned_interface in self.spawned_interfaces:
self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.append(spawned_interface)
spawned_interface.read_loop()
def received_announce(self, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time())
def received_announce(self, size=0, from_spawned=False):
if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time())
def sent_announce(self, size=0, from_spawned=False):
if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, size=0, from_spawned=False):
if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def process_outgoing(self, data):
pass
+2
View File
@@ -78,6 +78,7 @@ class UDPInterface(Interface):
self.name = name
self.online = False
self.bitrate = UDPInterface.BITRATE_GUESS
self.shared_medium = True
if device != None:
if bindip == None:
@@ -114,6 +115,7 @@ class UDPInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+115 -133
View File
@@ -109,30 +109,30 @@ class WDCL():
self.switch_id = self.switch_identity.sig_pub_bytes[-4:]
self.switch_pub_bytes = self.switch_identity.sig_pub_bytes
self.rxb = 0
self.txb = 0
self.owner = owner
self.as_interface = as_interface
self.device = device
self.rxb = 0
self.txb = 0
self.owner = owner
self.as_interface = as_interface
self.device = device
self.device.connection = self
self.pyserial = serial
self.serial = None
self.port = port
self.speed = 3000000
self.databits = 8
self.parity = parity
self.stopbits = 1
self.timeout = 100
self.online = False
self.frame_buffer = b""
self.next_tx = 0
self.should_run = True
self.receiver = None
self.wdcl_connected = False
self.reconnecting = False
self.frame_queue = deque()
if not self.as_interface:
self.id = RNS.Identity.full_hash(port.hwid.encode("utf-8"))
self.pyserial = serial
self.serial = None
self.port = port
self.speed = 3000000
self.databits = 8
self.parity = parity
self.stopbits = 1
self.timeout = 100
self.online = False
self.frame_buffer = b""
self.next_tx = 0
self.should_run = True
self.receiver = None
self.wdcl_connected = False
self.reconnecting = False
self.frame_queue = deque()
if not self.as_interface: self.id = RNS.Identity.full_hash(port.hwid.encode("utf-8"))
if self.as_interface:
try:
@@ -168,19 +168,10 @@ class WDCL():
self.owner.wlog(f"Opening serial port {self.port.device}...")
target_port = self.port.device
self.serial = self.pyserial.Serial(
port = target_port,
baudrate = self.speed,
bytesize = self.databits,
parity = self.parity,
stopbits = self.stopbits,
xonxoff = False,
rtscts = False,
timeout = 0.250,
inter_byte_timeout = None,
write_timeout = None,
dsrdtr = False)
self.serial = self.pyserial.Serial(port = target_port, baudrate = self.speed,
bytesize = self.databits, parity = self.parity, stopbits = self.stopbits,
xonxoff = False, rtscts = False, timeout = 0.250, inter_byte_timeout = None,
write_timeout = None, dsrdtr = False)
else:
if self.port != None:
# Get device parameters
@@ -198,19 +189,9 @@ class WDCL():
from usbserial4a.cdcacmserial4a import CdcAcmSerial
proxy = CdcAcmSerial
self.serial = proxy(
self.port,
baudrate = self.speed,
bytesize = self.databits,
parity = self.parity,
stopbits = self.stopbits,
xonxoff = False,
rtscts = False,
timeout = None,
inter_byte_timeout = None,
# write_timeout = wtimeout,
dsrdtr = False,
)
self.serial = proxy(self.port, baudrate = self.speed, bytesize = self.databits,
parity = self.parity, stopbits = self.stopbits, xonxoff = False,
rtscts = False, timeout = None, inter_byte_timeout = None, dsrdtr = False)
if vid == 0x0403:
# Hardware parameters for FTDI devices @ 115200 baud
@@ -299,10 +280,9 @@ class WDCL():
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > WDCL.HEADER_MINSIZE: self.process_incoming(frame)
self.frame_buffer = self.frame_buffer[frame_end:]
else:
flags_remaining = False
else:
flags_remaining = False
else: flags_remaining = False
else: flags_remaining = False
except Exception as e:
self.online = False
@@ -359,6 +339,7 @@ class Evt():
ET_MSG = 0x0000
ET_SYSTEM_BOOT = 0x0001
ET_CORE_INIT = 0x0002
ET_BOARD_INIT = 0x0003
ET_DRV_UART_INIT = 0x1000
ET_DRV_USB_CDC_INIT = 0x1010
ET_DRV_USB_CDC_HOST_AVAIL = 0x1011
@@ -426,77 +407,78 @@ class Evt():
IF_TYPE_DMA = 0x10
event_descriptions = {
ET_SYSTEM_BOOT: "System boot",
ET_CORE_INIT: "Core initialization",
ET_DRV_UART_INIT: "UART driver initialization",
ET_DRV_USB_CDC_INIT: "USB CDC driver initialization",
ET_DRV_USB_CDC_HOST_AVAIL: "USB CDC host became available",
ET_DRV_USB_CDC_HOST_SUSPEND: "USB CDC host suspend",
ET_DRV_USB_CDC_HOST_RESUME: "USB CDC host resume",
ET_DRV_USB_CDC_CONNECTED: "USB CDC host connection",
ET_DRV_USB_CDC_READ_ERR: "USB CDC read error",
ET_DRV_USB_CDC_OVERFLOW: "USB CDC overflow occurred",
ET_DRV_USB_CDC_DROPPED: "USB CDC dropped bytes",
ET_DRV_USB_CDC_TX_TIMEOUT: "USB CDC TX flush timeout",
ET_DRV_I2C_INIT: "I2C driver initialization",
ET_DRV_NVS_INIT: "NVS driver initialization",
ET_DRV_CRYPTO_INIT: "Cryptography driver initialization",
ET_DRV_W80211_INIT: "W802.11 driver initialization",
ET_DRV_W80211_CHANNEL: "W802.11 channel configuration",
ET_DRV_W80211_POWER: "W802.11 TX power configuration",
ET_DRV_DISPLAY_INIT: "Display driver initialization",
ET_SYSTEM_BOOT: "System boot",
ET_CORE_INIT: "Core initialization",
ET_BOARD_INIT: "Board hardware initialization",
ET_DRV_UART_INIT: "UART driver initialization",
ET_DRV_USB_CDC_INIT: "USB CDC driver initialization",
ET_DRV_USB_CDC_HOST_AVAIL: "USB CDC host became available",
ET_DRV_USB_CDC_HOST_SUSPEND: "USB CDC host suspend",
ET_DRV_USB_CDC_HOST_RESUME: "USB CDC host resume",
ET_DRV_USB_CDC_CONNECTED: "USB CDC host connection",
ET_DRV_USB_CDC_READ_ERR: "USB CDC read error",
ET_DRV_USB_CDC_OVERFLOW: "USB CDC overflow occurred",
ET_DRV_USB_CDC_DROPPED: "USB CDC dropped bytes",
ET_DRV_USB_CDC_TX_TIMEOUT: "USB CDC TX flush timeout",
ET_DRV_I2C_INIT: "I2C driver initialization",
ET_DRV_NVS_INIT: "NVS driver initialization",
ET_DRV_CRYPTO_INIT: "Cryptography driver initialization",
ET_DRV_W80211_INIT: "W802.11 driver initialization",
ET_DRV_W80211_CHANNEL: "W802.11 channel configuration",
ET_DRV_W80211_POWER: "W802.11 TX power configuration",
ET_DRV_DISPLAY_INIT: "Display driver initialization",
ET_DRV_DISPLAY_BUS_AVAILABLE: "Display bus availability",
ET_DRV_DISPLAY_IO_CONFIGURED: "Display I/O configuration",
ET_DRV_DISPLAY_PANEL_CREATED: "Display panel allocation",
ET_DRV_DISPLAY_PANEL_RESET: "Display panel reset",
ET_DRV_DISPLAY_PANEL_INIT: "Display panel initialization",
ET_DRV_DISPLAY_PANEL_ENABLE: "Display panel activation",
ET_DRV_DISPLAY_PANEL_RESET: "Display panel reset",
ET_DRV_DISPLAY_PANEL_INIT: "Display panel initialization",
ET_DRV_DISPLAY_PANEL_ENABLE: "Display panel activation",
ET_DRV_DISPLAY_REMOTE_ENABLE: "Remote display output activation",
ET_KRN_LOGGER_INIT: "Logging service initialization",
ET_KRN_LOGGER_OUTPUT: "Logging service output activation",
ET_KRN_UI_INIT: "User interface service initialization",
ET_PROTO_WDCL_INIT: "WDCL protocol initialization",
ET_PROTO_WDCL_RUNNING: "WDCL protocol activation",
ET_PROTO_WDCL_CONNECTION: "WDCL host connection",
ET_PROTO_WDCL_HOST_ENDPOINT: "Weave host endpoint",
ET_PROTO_WEAVE_INIT: "Weave protocol initialization",
ET_PROTO_WEAVE_RUNNING: "Weave protocol activation",
ET_PROTO_WEAVE_EP_ALIVE: "Weave endpoint alive",
ET_PROTO_WEAVE_EP_TIMEOUT: "Weave endpoint disappeared",
ET_SRVCTL_REMOTE_DISPLAY: "Remote display service control event",
ET_INTERFACE_REGISTERED: "Interface registration",
ET_SYSERR_MEM_EXHAUSTED: "System memory exhausted",
ET_KRN_LOGGER_INIT: "Logging service initialization",
ET_KRN_LOGGER_OUTPUT: "Logging service output activation",
ET_KRN_UI_INIT: "User interface service initialization",
ET_PROTO_WDCL_INIT: "WDCL protocol initialization",
ET_PROTO_WDCL_RUNNING: "WDCL protocol activation",
ET_PROTO_WDCL_CONNECTION: "WDCL host connection",
ET_PROTO_WDCL_HOST_ENDPOINT: "Weave host endpoint",
ET_PROTO_WEAVE_INIT: "Weave protocol initialization",
ET_PROTO_WEAVE_RUNNING: "Weave protocol activation",
ET_PROTO_WEAVE_EP_ALIVE: "Weave endpoint alive",
ET_PROTO_WEAVE_EP_TIMEOUT: "Weave endpoint disappeared",
ET_SRVCTL_REMOTE_DISPLAY: "Remote display service control event",
ET_INTERFACE_REGISTERED: "Interface registration",
ET_SYSERR_MEM_EXHAUSTED: "System memory exhausted",
}
interface_types = {
IF_TYPE_USB: "usb",
IF_TYPE_UART: "uart",
IF_TYPE_W80211: "mw",
IF_TYPE_BLE: "ble",
IF_TYPE_LORA: "lora",
IF_TYPE_USB: "usb",
IF_TYPE_UART: "uart",
IF_TYPE_W80211: "mw",
IF_TYPE_BLE: "ble",
IF_TYPE_LORA: "lora",
IF_TYPE_ETHERNET: "eth",
IF_TYPE_WIFI: "wifi",
IF_TYPE_TCP: "tcp",
IF_TYPE_UDP: "udp",
IF_TYPE_IR: "ir",
IF_TYPE_AFSK: "afsk",
IF_TYPE_GPIO: "gpio",
IF_TYPE_SPI: "spi",
IF_TYPE_I2C: "i2c",
IF_TYPE_CAN: "can",
IF_TYPE_DMA: "dma",
IF_TYPE_WIFI: "wifi",
IF_TYPE_TCP: "tcp",
IF_TYPE_UDP: "udp",
IF_TYPE_IR: "ir",
IF_TYPE_AFSK: "afsk",
IF_TYPE_GPIO: "gpio",
IF_TYPE_SPI: "spi",
IF_TYPE_I2C: "i2c",
IF_TYPE_CAN: "can",
IF_TYPE_DMA: "dma",
}
channel_descriptions = {
1: "Channel 1 (2412 MHz)",
2: "Channel 2 (2417 MHz)",
3: "Channel 3 (2422 MHz)",
4: "Channel 4 (2427 MHz)",
5: "Channel 5 (2432 MHz)",
6: "Channel 6 (2437 MHz)",
7: "Channel 7 (2442 MHz)",
8: "Channel 8 (2447 MHz)",
9: "Channel 9 (2452 MHz)",
1: "Channel 1 (2412 MHz)",
2: "Channel 2 (2417 MHz)",
3: "Channel 3 (2422 MHz)",
4: "Channel 4 (2427 MHz)",
5: "Channel 5 (2432 MHz)",
6: "Channel 6 (2437 MHz)",
7: "Channel 7 (2442 MHz)",
8: "Channel 8 (2447 MHz)",
9: "Channel 9 (2452 MHz)",
10: "Channel 10 (2457 MHz)",
11: "Channel 11 (2462 MHz)",
12: "Channel 12 (2467 MHz)",
@@ -529,23 +511,23 @@ class Evt():
}
task_descriptions = {
"taskLVGL": "Driver: UI Renderer",
"ui_service": "Service: User Interface",
"TinyUSB": "Driver: USB",
"drv_w80211": "Driver: W802.11",
"system_stats": "System: Stats",
"core": "System: Core",
"protocol_wdcl": "Protocol: WDCL",
"taskLVGL": "Driver: UI Renderer",
"ui_service": "Service: User Interface",
"TinyUSB": "Driver: USB",
"drv_w80211": "Driver: W802.11",
"system_stats": "System: Stats",
"core": "System: Core",
"protocol_wdcl": "Protocol: WDCL",
"protocol_weave": "Protocol: Weave",
"tiT": "Protocol: TCP/IP",
"ipc0": "System: CPU 0 IPC",
"ipc1": "System: CPU 1 IPC",
"esp_timer": "Driver: Timers",
"Tmr Svc": "Service: Timers",
"kernel_logger": "Service: Logging",
"tiT": "Protocol: TCP/IP",
"ipc0": "System: CPU 0 IPC",
"ipc1": "System: CPU 1 IPC",
"esp_timer": "Driver: Timers",
"Tmr Svc": "Service: Timers",
"kernel_logger": "Service: Logging",
"remote_display": "Service: Remote Display",
"wifi": "System: WiFi Hardware",
"sys_evt": "System: Kernel Events",
"wifi": "System: WiFi Hardware",
"sys_evt": "System: Kernel Events",
}
@staticmethod
@@ -775,8 +757,8 @@ class WeaveDevice():
self.cpu_load = frame.data[0]
self.capture_stats_cpu()
elif frame.event == Evt.ET_STAT_MEMORY:
self.memory_free = int.from_bytes(frame.data[:4])
self.memory_total = int.from_bytes(frame.data[4:])
self.memory_free = int.from_bytes(frame.data[:4], "big")
self.memory_total = int.from_bytes(frame.data[4:], "big")
self.memory_used = self.memory_total-self.memory_free
self.memory_used_pct = round((self.memory_used/self.memory_total)*100, 2)
self.capture_stats_memory()
@@ -979,9 +961,10 @@ class WeaveInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU
spawned_interface._online = True
RNS.Transport.interfaces.append(spawned_interface)
RNS.Transport.add_interface(spawned_interface)
if endpoint_addr in self.spawned_interfaces:
self.spawned_interfaces[endpoint_addr].detach()
self.spawned_interfaces[endpoint_addr].teardown()
@@ -1097,5 +1080,4 @@ class WeaveInterfacePeer(Interface):
except Exception as e:
RNS.log(f"Could not remove {self} from parent interface on detach. The contained exception was: {e}", RNS.LOG_ERROR)
if self in RNS.Transport.interfaces:
RNS.Transport.interfaces.remove(self)
RNS.Transport.remove_interface(self)
+4 -2
View File
@@ -36,5 +36,7 @@ import RNS.Interfaces.util.netinfo as netinfo
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+115
View File
@@ -0,0 +1,115 @@
# Reticulum License
#
# Copyright (c) 2026 Mark Qvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# - The Software shall not be used in any kind of system which includes amongst
# its functions the ability to purposefully do harm to human beings.
#
# - The Software shall not be used, directly or indirectly, in the creation of
# an artificial intelligence, machine learning or language model training
# dataset, including but not limited to any use that contributes to the
# training or development of such a model or algorithm.
#
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class HDLC():
FLAG = 0x7E
ESC = 0x7D
ESC_MASK = 0x20
FLAG_B = bytes([FLAG])
ESC_B = bytes([ESC])
ESCPD_FLAG = bytes([ESC, FLAG ^ ESC_MASK])
ESCPD_ESC = bytes([ESC, ESC ^ ESC_MASK])
@staticmethod
def escape(data):
data = data.replace(HDLC.ESC_B, HDLC.ESCPD_ESC)
data = data.replace(HDLC.FLAG_B, HDLC.ESCPD_FLAG)
return data
@staticmethod
def unescape(frame):
frame = frame.replace(HDLC.ESCPD_FLAG, HDLC.FLAG_B)
frame = frame.replace(HDLC.ESCPD_ESC, HDLC.ESC_B)
return frame
@staticmethod
def frame(data):
esc = HDLC.escape(data)
frame = bytearray(len(esc)+2)
frame[0] = HDLC.FLAG
frame[1:-1] = esc
frame[-1] = HDLC.FLAG
return frame
class ReceiveBuffer():
def __init__(self, mtu, min_frame_len, max_frame_len=None, on_frame=None, on_invalid=None):
self._mtu = mtu
self._min_frame_len = min_frame_len
self._max_frame_len = max_frame_len
self._on_frame = on_frame
self._on_invalid = on_invalid
self._buf = bytearray()
self._off = 0
def mtu(self):
return self._mtu() if callable(self._mtu) else self._mtu
def max(self):
m = self._max_frame_len
return m() if callable(m) else m
def feed(self, data):
if not data: return
self._buf.extend(data)
buf = self._buf
while True:
frame_start = buf.find(HDLC.FLAG, self._off)
if frame_start == -1:
self.reset()
return
frame_end = buf.find(HDLC.FLAG, frame_start+1)
if frame_end == -1:
if len(buf)-self._off > self.mtu()*2: self.reset()
return
frame = HDLC.unescape(bytes(buf[frame_start+1:frame_end]))
frame_len = len(frame)
if frame_len > 0:
max_len = self.max()
if frame_len > self._min_frame_len and (max_len is None or frame_len <= max_len):
if self._on_frame is not None: self._on_frame(frame)
elif self._on_invalid is not None: self._on_invalid(frame_len)
self._off = frame_end
if self._off > 0 and self._off >= len(buf) // 2:
del buf[:self._off]
self._off = 0
# Drops any partial frames from the buffer and
# resets assembly offset
def reset(self):
self._buf.clear()
self._off = 0
# Buffered bytes currently unconsumed
def __len__(self): return len(self._buf)-self._off
+171
View File
@@ -0,0 +1,171 @@
# Reticulum License
#
# Copyright (c) 2026 Mark Qvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# - The Software shall not be used in any kind of system which includes amongst
# its functions the ability to purposefully do harm to human beings.
#
# - The Software shall not be used, directly or indirectly, in the creation of
# an artificial intelligence, machine learning or language model training
# dataset, including but not limited to any use that contributes to the
# training or development of such a model or algorithm.
#
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from collections import deque
import threading
# Zero-copy coalesced transmit buffer for arbitrary
# frame sizes. It's even almost 100% lock-free.
class TransmitBuffer:
COALESCE_TARGET = 65536
def __init__(self):
self._tail_lock = threading.Lock()
# Producer-owned state
self._cur = None
self._cur_frames = 0
# Consumer-owned state
self._head_offset = 0
# Shared chunk queue. Producer appends right, consumer
# pops from left. Appended chunks are immutable.
self._chunks = deque()
# Accounting counters
# Producer-owned
self._tx_total = 0 # Total bytes appended
self._tx_visible = 0 # Total bytes pushed to the chunk queue
self._tx_frames = 0 # Total frames appended
# Consumer-owned
self._tx_sent = 0 # Total bytes sent to the kernel
self._tx_frames_sent = 0 # Total frames fully sent
# Queue a finalized and complete on-wire frame.
# Executed by producer side only.
def append(self, frame, limit=None):
with self._tail_lock:
if limit is not None and (self._tx_total - self._tx_sent) + len(frame) > limit: return False
# Allocate separate chunks to frames
# larger than the coalescing target.
if len(frame) >= self.COALESCE_TARGET:
self._flush()
self._chunks.append((frame, 1))
self._tx_visible += len(frame)
self._tx_total += len(frame)
self._tx_frames += 1
else:
if self._cur is not None and len(self._cur) + len(frame) > self.COALESCE_TARGET: self._flush()
if self._cur is None:
self._cur = bytearray()
self._cur_frames = 0
self._cur.extend(frame)
self._cur_frames += 1
self._tx_total += len(frame)
self._tx_frames += 1
if not self._chunks:
# Queue is idle. Make the frame visible immediately so
# sparse traffic does not incur coalescing latency.
self._flush()
return True
def _flush(self):
if self._cur is not None and len(self._cur) > 0:
self._chunks.append((self._cur, self._cur_frames))
self._tx_visible += len(self._cur)
self._cur = None
self._cur_frames = 0
# Make producer-side coalescing tail visible to the consumer.
# Called by producer when it has finished producing a burst,
# and wants to make the remaining bytes transmittable. Safe to
# call after every append.
def flush(self):
with self._tail_lock: self._flush()
# Drain buffered frames to a socket. Called by consumer. If the
# chunk queue is drained completely, any potential producer-side
# coalescing tail is released under the tail lock, and drained in
# the same cycle. If you possess wizardry for doing this without
# the lock, I am all ears.
def drain_to(self, socket):
# TODO: At *some* point (no, not now), replace with a
# mechanism for send_msg to immediately drain all
# chunks directly to the kernel.
total = 0
whole = True
while whole:
if not self._chunks:
with self._tail_lock: self._flush()
if not self._chunks: break
chunk, _ = self._chunks[0]
remaining = len(chunk) - self._head_offset
if remaining <= 0:
self._pop_head()
continue
try: written = socket.send(memoryview(chunk)[self._head_offset:])
except BlockingIOError: break
except InterruptedError: continue
if written <= 0: break
total += written
self._head_offset += written
self._tx_sent += written
if self._head_offset >= len(chunk): self._pop_head()
else: whole = False
return total
def _pop_head(self):
chunk, frames = self._chunks.popleft()
self._tx_frames_sent += frames
self._head_offset = 0
# Total number of bytes currently buffered, including the
# producer's in-progress coalescing chunk.
def __len__(self): return self._tx_total-self._tx_sent
# The number of bytes actually ready to send, and will be
# visible to the consumer, that is, what can be drained.
@property
def sendable(self): return self._tx_visible-self._tx_sent
# The number of complete frames currently buffere, including
# ones contained in a potential in-progress coalescing chunk.
@property
def frames_buffered(self): return self._tx_frames-self._tx_frames_sent
# Number of chunks currently queued and visible to the consumer
@property
def chunks_buffered(self): return len(self._chunks)
def __repr__(self): return f"<TransmitBuffer buffered={len(self)} sendable={self.sendable} frames={self.frames_buffered} chunks={self.chunks_buffered}>"
+4 -2
View File
@@ -3,5 +3,7 @@ import glob
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+201 -231
View File
@@ -190,25 +190,22 @@ class Link:
link.set_link_id(packet)
if len(data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE:
RNS.log("Link request includes MTU signalling", RNS.LOG_DEBUG) # TODO: Remove debug
try:
link.mtu = Link.mtu_from_lr_packet(packet) or Reticulum.MTU
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 RNS.Reticulum.MTU
except Exception as e:
RNS.trace_exception(e)
link.mtu = RNS.Reticulum.MTU
link.mode = Link.mode_from_lr_packet(packet)
# TODO: Remove debug
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG)
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
link.update_mdu()
link.destination = packet.destination
link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE
link.establishment_cost += len(packet.raw)
RNS.log(f"Validating link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_DEBUG)
RNS.log(f"Link MTU configured to {RNS.prettysize(link.mtu)}", 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)
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) 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) if RNS.sl(RNS.LOG_EXTREME) else None
link.handshake()
link.attached_interface = packet.receiving_interface
link.prove()
@@ -218,15 +215,15 @@ class Link:
link.__update_phy_stats(packet, force_update=True)
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
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
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
@@ -268,6 +265,7 @@ class Link:
self.owner = owner
self.destination = destination
self.expected_hops = None
self.rebalanced = None
self.attached_interface = None
self.__remote_identity = None
self.__track_phy_stats = False
@@ -277,6 +275,7 @@ class Link:
self.initiator = False
self.prv = X25519PrivateKey.generate()
self.sig_prv = self.owner.identity.sig_prv
else:
self.initiator = True
self.expected_hops = RNS.Transport.hops_to(self.destination.hash)
@@ -296,14 +295,11 @@ class Link:
if peer_pub_bytes == None:
self.peer_pub = None
self.peer_pub_bytes = None
else:
self.load_peer(peer_pub_bytes, peer_sig_pub_bytes)
if established_callback != None:
self.set_link_established_callback(established_callback)
else: self.load_peer(peer_pub_bytes, peer_sig_pub_bytes)
if closed_callback != None:
self.set_link_closed_callback(closed_callback)
if established_callback != None: self.set_link_established_callback(established_callback)
if closed_callback != None: self.set_link_closed_callback(closed_callback)
if self.initiator:
signalling_bytes = b""
@@ -334,8 +330,7 @@ class Link:
self.peer_sig_pub_bytes = peer_sig_pub_bytes
self.peer_sig_pub = Ed25519PublicKey.from_public_bytes(self.peer_sig_pub_bytes)
if not hasattr(self.peer_pub, "curve"):
self.peer_pub.curve = Link.CURVE
if not hasattr(self.peer_pub, "curve"): self.peer_pub.curve = Link.CURVE
@staticmethod
def link_id_from_lr_packet(packet):
@@ -399,13 +394,13 @@ class Link:
signalling_bytes = b""
confirmed_mtu = None
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 len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
confirmed_mtu = Link.mtu_from_lp_packet(packet)
signalling_bytes = Link.signalling_bytes(confirmed_mtu, mode)
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:
peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
@@ -430,7 +425,7 @@ class Link:
self.activated_at = time.time()
self.last_proof = self.activated_at
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:
self.establishment_rate = self.establishment_cost/self.rtt
@@ -447,8 +442,8 @@ class Link:
thread = threading.Thread(target=self.callbacks.link_established, args=(self,))
thread.daemon = True
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:
self.status = Link.CLOSED
@@ -475,7 +470,8 @@ class Link:
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.
@@ -483,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 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 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.
:returns: A :ref:`RNS.RequestReceipt<api-requestreceipt>` instance if the request was sent, or *False* if it was not.
"""
@@ -497,35 +494,20 @@ class Link:
request_packet = RNS.Packet(self, packed_request, RNS.Packet.DATA, context = RNS.Packet.REQUEST)
packet_receipt = request_packet.send()
if packet_receipt == False:
return False
if packet_receipt == False: return False
else:
packet_receipt.set_timeout(timeout)
return RequestReceipt(
self,
packet_receipt = packet_receipt,
response_callback = response_callback,
failed_callback = failed_callback,
progress_callback = progress_callback,
timeout = timeout,
request_size = len(packed_request),
)
return RequestReceipt(self, packet_receipt=packet_receipt, response_callback=response_callback,
failed_callback=failed_callback, progress_callback=progress_callback, timeout=timeout,
request_size=len(packed_request), max_response_size=max_response_size)
else:
request_id = RNS.Identity.truncated_hash(packed_request)
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)
return RequestReceipt(
self,
resource = request_resource,
response_callback = response_callback,
failed_callback = failed_callback,
progress_callback = progress_callback,
timeout = timeout,
request_size = len(packed_request),
)
return RequestReceipt(self, resource=request_resource, response_callback=response_callback,
failed_callback=failed_callback, progress_callback=progress_callback, timeout=timeout,
request_size=len(packed_request), max_response_size=max_response_size)
def update_mdu(self):
self.mdu = self.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
@@ -540,6 +522,7 @@ class Link:
self.rtt = max(measured_rtt, rtt)
self.status = Link.ACTIVE
self.activated_at = time.time()
self.expected_hops = packet.hops
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
@@ -547,10 +530,8 @@ class Link:
self.__update_keepalive()
try:
if self.owner.callbacks.link_established != None:
self.owner.callbacks.link_established(self)
except Exception as e:
RNS.log("Error occurred in external link establishment callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
if self.owner.callbacks.link_established != None: self.owner.callbacks.link_established(self)
except Exception as e: RNS.log("Error occurred in external link establishment callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
except Exception as e:
RNS.log("Error occurred while processing RTT packet, tearing down link. The contained exception was: "+str(e), RNS.LOG_ERROR)
@@ -565,73 +546,57 @@ class Link:
:param track: Whether or not to keep track of physical layer statistics. Value must be ``True`` or ``False``.
"""
if track:
self.__track_phy_stats = True
else:
self.__track_phy_stats = False
if track: self.__track_phy_stats = True
else: self.__track_phy_stats = False
def get_rssi(self):
"""
:returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``. Physical layer statistics must be enabled on the link for this method to return a value.
"""
if self.__track_phy_stats:
return self.rssi
else:
return None
if self.__track_phy_stats: return self.rssi
else: return None
def get_snr(self):
"""
:returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``. Physical layer statistics must be enabled on the link for this method to return a value.
"""
if self.__track_phy_stats:
return self.snr
else:
return None
if self.__track_phy_stats: return self.snr
else: return None
def get_q(self):
"""
:returns: The physical layer *Link Quality* if available, otherwise ``None``. Physical layer statistics must be enabled on the link for this method to return a value.
"""
if self.__track_phy_stats:
return self.q
else:
return None
if self.__track_phy_stats: return self.q
else: return None
def get_establishment_rate(self):
"""
:returns: The data transfer rate at which the link establishment procedure ocurred, in bits per second.
"""
if self.establishment_rate != None:
return self.establishment_rate*8
else:
return None
if self.establishment_rate != None: return self.establishment_rate*8
else: return None
def get_mtu(self):
"""
:returns: The MTU of an established link.
"""
if self.status == Link.ACTIVE:
return self.mtu
else:
return None
if self.status == Link.ACTIVE: return self.mtu
else: return None
def get_mdu(self):
"""
:returns: The packet MDU of an established link.
"""
if self.status == Link.ACTIVE:
return self.mdu
else:
return None
if self.status == Link.ACTIVE: return self.mdu
else: return None
def get_expected_rate(self):
"""
:returns: The packet expected in-flight data rate of an established link.
:returns: The expected in-flight data rate of an established link.
"""
if self.status == Link.ACTIVE:
return self.expected_rate
else:
return None
if self.status == Link.ACTIVE: return self.expected_rate
else: return None
def get_mode(self):
"""
@@ -649,10 +614,8 @@ class Link:
"""
:returns: The time in seconds since this link was established.
"""
if self.activated_at:
return time.time() - self.activated_at
else:
return None
if self.activated_at: return time.time() - self.activated_at
else: return None
def no_inbound_for(self):
"""
@@ -701,6 +664,7 @@ class Link:
Closes the link and purges encryption keys. New keys will
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()
self.status = Link.CLOSED
if self.initiator: self.teardown_reason = Link.INITIATOR_CLOSED
@@ -712,18 +676,15 @@ class Link:
plaintext = self.decrypt(packet.data)
if plaintext == self.link_id:
self.status = Link.CLOSED
if self.initiator:
self.teardown_reason = Link.DESTINATION_CLOSED
else:
self.teardown_reason = Link.INITIATOR_CLOSED
if self.initiator: self.teardown_reason = Link.DESTINATION_CLOSED
else: self.teardown_reason = Link.INITIATOR_CLOSED
self.__update_phy_stats(packet)
self.link_closed()
except Exception as e:
pass
except Exception as e: pass
def link_closed(self):
for resource in self.incoming_resources: resource.cancel()
for resource in self.outgoing_resources: resource.cancel()
for resource in self.incoming_resources.copy(): resource.cancel()
for resource in self.outgoing_resources.copy(): resource.cancel()
if self._channel: self._channel._shutdown()
self.prv = None
@@ -752,9 +713,7 @@ class Link:
while not self.status == Link.CLOSED:
while (self.watchdog_lock):
rtt_wait = 0.025
if hasattr(self, "rtt") and self.rtt:
rtt_wait = self.rtt
if hasattr(self, "rtt") and self.rtt: rtt_wait = self.rtt
sleep(max(rtt_wait, 0.025))
if not self.status == Link.CLOSED:
@@ -779,28 +738,25 @@ class Link:
self.link_closed()
sleep_time = 0.001
if self.initiator:
RNS.log("Timeout waiting for link request proof", RNS.LOG_DEBUG)
else:
RNS.log("Timeout waiting for RTT packet from link initiator", RNS.LOG_DEBUG)
if self.initiator: RNS.log("Timeout waiting for link request proof", RNS.LOG_DEBUG)
else: RNS.log("Timeout waiting for RTT packet from link initiator", RNS.LOG_DEBUG)
elif self.status == Link.ACTIVE:
activated_at = self.activated_at if self.activated_at != None else 0
last_inbound = max(max(self.last_inbound, self.last_proof), activated_at)
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:
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
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:
sleep_time = 0.001
@@ -810,10 +766,9 @@ class Link:
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:
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()
sleep_time = 0.1
@@ -825,7 +780,6 @@ class Link:
self.snr = None
self.q = None
def __update_phy_stats(self, packet, query_shared = True, force_update = False):
if self.__track_phy_stats or force_update:
if query_shared:
@@ -834,12 +788,9 @@ class Link:
if packet.snr == None: packet.snr = reticulum.get_packet_snr(packet.packet_hash)
if packet.q == None: packet.q = reticulum.get_packet_q(packet.packet_hash)
if packet.rssi != None:
self.rssi = packet.rssi
if packet.snr != None:
self.snr = packet.snr
if packet.q != None:
self.q = packet.q
if packet.rssi != None: self.rssi = packet.rssi
if packet.snr != None: self.snr = packet.snr
if packet.q != None: self.q = packet.q
def __update_keepalive(self):
self.keepalive = max(min(self.rtt*(Link.KEEPALIVE_MAX/Link.KEEPALIVE_MAX_RTT), Link.KEEPALIVE_MAX), Link.KEEPALIVE_MIN)
@@ -857,7 +808,7 @@ class Link:
request_data = unpacked_request[2]
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]
response_generator = request_handler[1]
allow = request_handler[2]
@@ -903,21 +854,28 @@ class Link:
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)
def handle_response(self, request_id, response_data, response_size, response_transfer_size, metadata=None):
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:
remove = None
for pending_request in self.pending_requests:
if pending_request.request_id == request_id:
remove = pending_request
try:
pending_request.response_size = response_size
if pending_request.response_transfer_size == None:
pending_request.response_transfer_size = 0
pending_request.response_transfer_size += response_transfer_size
pending_request.response_received(response_data, metadata)
except Exception as e:
RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
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
try:
if update_sizes:
pending_request.response_size = response_size
if pending_request.response_transfer_size == None: pending_request.response_transfer_size = 0
pending_request.response_transfer_size += response_transfer_size
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)
break
if remove != None:
@@ -933,8 +891,8 @@ class Link:
def job(): self.handle_request(request_id, request_data)
threading.Thread(target=job, daemon=True).start()
else:
RNS.log("Incoming request resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG)
else: RNS.log("Incoming request resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG)
def response_resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE:
@@ -965,23 +923,27 @@ class Link:
:return: ``Channel`` object
"""
if self._channel is None:
self._channel = Channel(LinkChannelOutlet(self))
if self._channel is None: self._channel = Channel(LinkChannelOutlet(self))
return self._channel
def receive(self, packet):
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 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)
else:
self.last_inbound = time.time()
if packet.context != RNS.Packet.KEEPALIVE:
self.last_data = self.last_inbound
if packet.context != RNS.Packet.KEEPALIVE: self.last_data = self.last_inbound
self.rx += 1
self.rxbytes += len(packet.data)
if self.status == Link.STALE:
self.status = Link.ACTIVE
if self.status == Link.STALE: self.status = Link.ACTIVE
if packet.packet_type == RNS.Packet.DATA:
should_query = False
@@ -1002,10 +964,8 @@ class Link:
elif self.destination.proof_strategy == RNS.Destination.PROVE_APP:
if self.destination.callbacks.proof_requested:
try:
if self.destination.callbacks.proof_requested(packet):
packet.prove()
except Exception as e:
RNS.log("Error while executing proof request callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
if self.destination.callbacks.proof_requested(packet): packet.prove()
except Exception as e: RNS.log("Error while executing proof request callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
elif packet.context == RNS.Packet.LINKIDENTIFY:
plaintext = self.decrypt(packet.data)
@@ -1018,12 +978,16 @@ class Link:
identity.load_public_key(public_key)
if identity.validate(signature, signed_data):
self.__remote_identity = identity
if self.callbacks.remote_identified != None:
try:
self.callbacks.remote_identified(self, self.__remote_identity)
except Exception as e:
RNS.log("Error while executing remote identified callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
if RNS.Reticulum.get_instance().is_blackholed(identity.hash):
RNS.log(f"Terminating incoming link from blackholed identity {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.teardown()
else:
if self.__remote_identity == None:
self.__remote_identity = identity
if self.callbacks.remote_identified != None:
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)
@@ -1032,12 +996,15 @@ class Link:
request_id = packet.getTruncatedHash()
packed_request = self.decrypt(packet.data)
if packed_request != None:
unpacked_request = umsgpack.unpackb(packed_request)
def job(): self.handle_request(request_id, unpacked_request)
threading.Thread(target=job, daemon=True).start()
if self.destination.max_request_size == None: size_ok = True
else: size_ok = len(packed_request) <= self.destination.max_request_size
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)
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)
elif packet.context == RNS.Packet.RESPONSE:
try:
@@ -1047,11 +1014,10 @@ class Link:
request_id = unpacked_response[0]
response_data = unpacked_response[1]
transfer_size = len(umsgpack.packb(response_data))-2
def job(): self.handle_response(request_id, response_data, transfer_size, transfer_size)
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()
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)
elif packet.context == RNS.Packet.LRRTT:
if not self.initiator:
@@ -1066,36 +1032,51 @@ class Link:
packet.plaintext = self.decrypt(packet.data)
if packet.plaintext != None:
self.__update_phy_stats(packet, query_shared=True)
if RNS.ResourceAdvertisement.is_request(packet):
RNS.Resource.accept(packet, callback=self.request_resource_concluded)
elif RNS.ResourceAdvertisement.is_response(packet):
request_id = RNS.ResourceAdvertisement.read_request_id(packet)
for pending_request in self.pending_requests:
if pending_request.request_id == request_id:
response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id)
if response_resource != None:
if pending_request.response_size == None:
pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet)
if pending_request.response_transfer_size == None:
pending_request.response_transfer_size = 0
pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet)
if pending_request.started_at == None:
pending_request.started_at = time.time()
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)
try:
if RNS.ResourceAdvertisement.is_request(packet):
if self.destination.request_handlers:
if self.destination.max_request_size == None: size_ok = True
else: size_ok = RNS.ResourceAdvertisement.read_size(packet) <= self.destination.max_request_size
if size_ok: RNS.Resource.accept(packet, callback=self.request_resource_concluded)
else:
RNS.Resource.reject(packet)
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
elif RNS.ResourceAdvertisement.is_response(packet):
request_id = RNS.ResourceAdvertisement.read_request_id(packet)
for pending_request in self.pending_requests:
if pending_request.request_id == request_id:
if pending_request.max_response_size == None: size_ok = True
else: size_ok = RNS.ResourceAdvertisement.read_size(packet) <= pending_request.max_response_size
if not size_ok:
RNS.Resource.reject(packet)
pending_request.response_rejected()
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
else:
response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id)
if response_resource != None:
if pending_request.response_size == None:
pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet)
if pending_request.response_transfer_size == None:
pending_request.response_transfer_size = 0
pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet)
if pending_request.started_at == None:
pending_request.started_at = time.time()
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:
plaintext = self.decrypt(packet.data)
@@ -1148,9 +1129,10 @@ class Link:
elif packet.context == RNS.Packet.KEEPALIVE:
if not self.initiator and packet.data == bytes([0xFF]):
keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE)
keepalive_packet.send()
self.had_outbound(is_keepalive = True)
if time.time() >= self.last_outbound + self.keepalive:
keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE)
keepalive_packet.send()
self.had_outbound(is_keepalive = True)
# TODO: find the most efficient way to allow multiple
@@ -1181,9 +1163,6 @@ class Link:
threading.Thread(target=job, daemon=True).start()
self.__update_phy_stats(packet, query_shared=True)
self.watchdog_lock = False
def encrypt(self, plaintext):
try:
if not self.token:
@@ -1198,7 +1177,6 @@ class Link:
RNS.log("Encryption on link "+str(self)+" failed. The contained exception was: "+str(e), RNS.LOG_ERROR)
raise e
def decrypt(self, ciphertext):
try:
if not self.token: self.token = Token(self.derived_key)
@@ -1208,7 +1186,6 @@ class Link:
RNS.log("Decryption failed on link "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
return None
def sign(self, message):
return self.sig_prv.sign(message)
@@ -1216,8 +1193,7 @@ class Link:
try:
self.peer_sig_pub.verify(signature, message)
return True
except Exception as e:
return False
except Exception as e: return False
def set_link_established_callback(self, callback):
self.callbacks.link_established = callback
@@ -1345,7 +1321,9 @@ class RequestReceipt():
RECEIVING = 0x03
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.resource = resource
self.started_at = None
@@ -1372,6 +1350,7 @@ class RequestReceipt():
self.progress = 0
self.concluded_at = None
self.response_concluded_at = None
self.max_response_size = max_response_size
if timeout != None:
self.timeout = timeout
@@ -1385,7 +1364,6 @@ class RequestReceipt():
self.link.pending_requests.append(self)
def request_resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE:
RNS.log("Request "+RNS.prettyhexrep(self.request_id)+" successfully sent as resource.", RNS.LOG_DEBUG)
@@ -1403,12 +1381,10 @@ class RequestReceipt():
self.link.pending_requests.remove(self)
if self.callbacks.failed != None:
try:
self.callbacks.failed(self)
try: self.callbacks.failed(self)
except Exception as e:
RNS.log("Error while executing request failed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
def __response_timeout_job(self):
while self.status == RequestReceipt.DELIVERED:
now = time.time()
@@ -1418,7 +1394,6 @@ class RequestReceipt():
time.sleep(0.1)
def request_timed_out(self, packet_receipt):
if self in self.link.pending_requests and self.status == RequestReceipt.DELIVERED:
self.status = RequestReceipt.FAILED
@@ -1427,9 +1402,17 @@ class RequestReceipt():
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)
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):
if resource != None:
@@ -1446,13 +1429,10 @@ class RequestReceipt():
self.progress = resource.get_progress()
if self.callbacks.progress != None:
try:
self.callbacks.progress(self)
except Exception as e:
RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
else:
resource.cancel()
try: self.callbacks.progress(self)
except Exception as e: RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
else: resource.cancel()
def response_received(self, response, metadata=None):
if not self.status == RequestReceipt.FAILED:
@@ -1471,13 +1451,11 @@ class RequestReceipt():
if self.callbacks.progress != None:
try: self.callbacks.progress(self)
except Exception as e:
RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
except Exception as e: RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
if self.callbacks.response != None:
try: self.callbacks.response(self)
except Exception as e:
RNS.log("Error while executing response received callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
except Exception as e: RNS.log("Error while executing response received callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
def get_request_id(self):
"""
@@ -1501,31 +1479,23 @@ class RequestReceipt():
"""
:returns: The response as *bytes* if it is ready, otherwise *None*.
"""
if self.status == RequestReceipt.READY:
return self.response
else:
return None
if self.status == RequestReceipt.READY: return self.response
else: return None
def get_response_time(self):
"""
:returns: The response time of the request in seconds.
"""
if self.status == RequestReceipt.READY:
return self.response_concluded_at - self.started_at
else:
return None
if self.status == RequestReceipt.READY: return self.response_concluded_at - self.started_at
else: return None
def concluded(self):
"""
:returns: True if the associated request has concluded (successfully or with a failure), otherwise False.
"""
if self.status == RequestReceipt.READY:
return True
elif self.status == RequestReceipt.FAILED:
return True
else:
return False
if self.status == RequestReceipt.READY: return True
elif self.status == RequestReceipt.FAILED: return True
else: return False
class RequestReceiptCallbacks:
+68 -79
View File
@@ -117,7 +117,8 @@ class Packet:
__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__ += "sent_at", "packet_hash", "ratchet_id", "attached_interface", "receiving_interface", "rssi", "snr", "q"
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash"
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr"
__slots__ += "traffic_class", "announce_signature_validated"
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):
@@ -159,8 +160,11 @@ class Packet:
self.packet_hash = None
self.ratchet_id = None
self.traffic_class = None
self.announce_signature_validated = None
self.attached_interface = attached_interface
self.receiving_interface = None
self.is_outbound_pr = False
self.rssi = None
self.snr = None
self.q = None
@@ -243,6 +247,9 @@ class Packet:
self.flags = self.raw[0]
self.hops = self.raw[1]
if self.hops >= RNS.Transport.PATHFINDER_M:
raise ValueError(f"Invalid hop count {self.hops}")
self.header_type = (self.flags & 0b01000000) >> 6
self.context_flag = (self.flags & 0b00100000) >> 5
self.transport_type = (self.flags & 0b00010000) >> 4
@@ -256,18 +263,23 @@ class Packet:
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.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:
self.transport_id = None
self.destination_hash = self.raw[2:DST_LEN+2]
self.context = ord(self.raw[DST_LEN+2:DST_LEN+3])
self.data = self.raw[DST_LEN+3:]
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
if len(self.data) == 0: raise ValueError("Zero-length data field")
self.packed = False
self.update_hash()
return True
except Exception as e:
RNS.log("Received malformed packet, dropping it. The contained exception was: "+str(e), RNS.LOG_EXTREME)
RNS.log(f"Received malformed packet, dropping it. The contained exception was: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
def send(self):
@@ -277,9 +289,11 @@ 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.
"""
if not self.sent:
if self.hops >= RNS.Transport.PATHFINDER_M: return False
if not self.packed: self.pack()
if self.destination.type == RNS.Destination.LINK:
if self.destination.status == RNS.Link.CLOSED:
RNS.log("Attempt to transmit over a closed link, dropping packet", RNS.LOG_DEBUG)
RNS.log("Attempt to transmit over a closed link, dropping packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.sent = False
self.receipt = None
return False
@@ -287,13 +301,13 @@ class Packet:
else:
self.destination.last_outbound = time.time()
self.destination.tx += 1
self.destination.txbytes += len(self.data)
if not self.packed: self.pack()
self.destination.txbytes += len(self.ciphertext)
if RNS.Transport.outbound(self): return self.receipt
else:
RNS.log("No interfaces could process the outbound packet", RNS.LOG_DEBUG)
if not self.attached_interface:
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.receipt = None
return False
@@ -312,51 +326,44 @@ class Packet:
# encrypted destinations
self.pack()
if RNS.Transport.outbound(self):
return self.receipt
if RNS.Transport.outbound(self): return self.receipt
else:
RNS.log("Re-send failed. No interfaces could process the outbound packet", RNS.LOG_WARNING)
self.sent = False
self.receipt = None
return False
else:
raise IOError("Packet was not sent yet")
else: raise IOError("Packet was not sent yet")
def prove(self, destination=None):
if self.fromPacked and hasattr(self, "destination") and self.destination:
if self.destination.identity and self.destination.identity.prv:
self.destination.identity.prove(self, destination)
elif self.fromPacked and hasattr(self, "link") and self.link:
self.link.prove_packet(self)
else:
RNS.log("Could not prove packet associated with neither a destination nor a link", RNS.LOG_ERROR)
elif self.fromPacked and hasattr(self, "link") and self.link: self.link.prove_packet(self)
else: RNS.log("Could not prove packet associated with neither a destination nor a link", RNS.LOG_ERROR)
# Generates a special destination that allows Reticulum
# to direct the proof back to the proved packet's sender
def generate_proof_destination(self):
return ProofDestination(self)
def generate_proof_destination(self): return ProofDestination(self)
def validate_proof_packet(self, proof_packet):
return self.receipt.validate_proof_packet(proof_packet)
def validate_proof_packet(self, proof_packet): return self.receipt.validate_proof_packet(proof_packet)
def validate_proof(self, proof):
return self.receipt.validate_proof(proof)
def validate_proof(self, proof): return self.receipt.validate_proof(proof)
def update_hash(self):
self.packet_hash = self.get_hash()
def update_hash(self): self.packet_hash = self.get_hash()
def get_hash(self):
return RNS.Identity.full_hash(self.get_hashable_part())
def get_hash(self): return RNS.Identity.full_hash(self.get_hashable_part())
def getTruncatedHash(self):
return RNS.Identity.truncated_hash(self.get_hashable_part())
def getTruncatedHash(self): return RNS.Identity.truncated_hash(self.get_hashable_part())
@property
def truncated_packet_hash(self):
return self.packet_hash[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8]
def get_hashable_part(self):
hashable_part = bytes([self.raw[0] & 0b00001111])
if self.header_type == Packet.HEADER_2:
hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
else:
hashable_part += self.raw[2:]
if self.header_type == Packet.HEADER_2: hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
else: hashable_part += self.raw[2:]
return hashable_part
@@ -364,36 +371,29 @@ class Packet:
"""
:returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``.
"""
if self.rssi != None:
return self.rssi
else:
return reticulum.get_packet_rssi(self.packet_hash)
if self.rssi != None: return self.rssi
else: return RNS.Reticulum.get_instance().get_packet_rssi(self.packet_hash)
def get_snr(self):
"""
:returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``.
"""
if self.snr != None:
return self.snr
else:
return reticulum.get_packet_snr(self.packet_hash)
if self.snr != None: return self.snr
else: return RNS.Reticulum.get_instance().get_packet_snr(self.packet_hash)
def get_q(self):
"""
:returns: The physical layer *Link Quality* if available, otherwise ``None``.
"""
if self.q != None:
return self.q
else:
return reticulum.get_packet_q(self.packet_hash)
if self.q != None: return self.q
else: return RNS.Reticulum.get_instance().get_packet_q(self.packet_hash)
class ProofDestination:
def __init__(self, packet):
self.hash = packet.get_hash()[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8];
self.hash = packet.truncated_packet_hash;
self.type = RNS.Destination.SINGLE
def encrypt(self, plaintext):
return plaintext
def encrypt(self, plaintext): return plaintext
class PacketReceipt:
@@ -415,8 +415,8 @@ class PacketReceipt:
# Creates a new packet receipt from a sent packet
def __init__(self, packet):
self.hash = packet.get_hash()
self.truncated_hash = packet.getTruncatedHash()
self.hash = packet.packet_hash
self.truncated_hash = packet.truncated_packet_hash
self.sent = True
self.sent_at = time.time()
self.proved = False
@@ -462,18 +462,17 @@ class PacketReceipt:
link.last_proof = self.concluded_at
if self.callbacks.delivery != None:
try:
self.callbacks.delivery(self)
try: self.callbacks.delivery(self)
except Exception as e:
RNS.log("An error occurred while evaluating external delivery callback for "+str(link), RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.trace_exception(e)
return True
else:
return False
else:
return False
else: return False
else: return False
elif len(proof) == PacketReceipt.IMPL_LENGTH:
pass
# TODO: Why is this disabled?
@@ -490,8 +489,7 @@ class PacketReceipt:
# else:
# RNS.log("invalid")
# return False
else:
return False
else: return False
# Validate a raw proof
def validate_proof(self, proof, proof_packet=None):
@@ -508,24 +506,20 @@ class PacketReceipt:
self.proof_packet = proof_packet
if self.callbacks.delivery != None:
try:
self.callbacks.delivery(self)
try: self.callbacks.delivery(self)
except Exception as e:
RNS.log("Error while executing proof validated callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
return True
else:
return False
else:
return False
else: return False
else: return False
elif len(proof) == PacketReceipt.IMPL_LENGTH:
# This is an implicit proof
if not hasattr(self.destination, "identity"):
return False
if self.destination.identity == None:
return False
if not hasattr(self.destination, "identity"): return False
if self.destination.identity == None: return False
signature = proof[:RNS.Identity.SIGLENGTH//8]
proof_valid = self.destination.identity.validate(signature, self.hash)
@@ -536,16 +530,13 @@ class PacketReceipt:
self.proof_packet = proof_packet
if self.callbacks.delivery != None:
try:
self.callbacks.delivery(self)
except Exception as e:
RNS.log("Error while executing proof validated callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
try: self.callbacks.delivery(self)
except Exception as e: RNS.log("Error while executing proof validated callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
return True
else:
return False
else:
return False
else: return False
else: return False
def get_rtt(self):
"""
@@ -558,10 +549,8 @@ class PacketReceipt:
def check_timeout(self):
if self.status == PacketReceipt.SENT and self.is_timed_out():
if self.timeout == -1:
self.status = PacketReceipt.CULLED
else:
self.status = PacketReceipt.FAILED
if self.timeout == -1: self.status = PacketReceipt.CULLED
else: self.status = PacketReceipt.FAILED
self.concluded_at = time.time()
+1 -2
View File
@@ -31,5 +31,4 @@
class Resolver:
@staticmethod
def resolve_identity(full_name):
pass
def resolve_identity(full_name): pass
+149 -154
View File
@@ -30,6 +30,7 @@
import RNS
import os
import io
import bz2
import math
import time
@@ -149,7 +150,7 @@ class Resource:
COMPLETE = 0x06
FAILED = 0x07
CORRUPT = 0x08
REJECTED = 0x00
REJECTED = 0x09
@staticmethod
def reject(advertisement_packet):
@@ -223,7 +224,7 @@ class Resource:
if not resource.link.has_incoming_resource(resource):
resource.link.register_incoming_resource(resource)
RNS.log(f"Accepting resource advertisement for {RNS.prettyhexrep(resource.hash)}. Transfer size is {RNS.prettysize(resource.size)} in {resource.total_parts} parts.", RNS.LOG_DEBUG)
RNS.log(f"Accepting resource advertisement for {RNS.prettyhexrep(resource.hash)}. Transfer size is {RNS.prettysize(resource.size)} in {resource.total_parts} parts.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if resource.link.callbacks.resource_started != None:
try:
resource.link.callbacks.resource_started(resource)
@@ -235,11 +236,11 @@ class Resource:
return resource
else:
RNS.log("Ignoring resource advertisement for "+RNS.prettyhexrep(resource.hash)+", resource already transferring", RNS.LOG_DEBUG)
RNS.log("Ignoring resource advertisement for "+RNS.prettyhexrep(resource.hash)+", resource already transferring", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None
except Exception as e:
RNS.log("Could not decode resource advertisement, dropping resource", RNS.LOG_DEBUG)
RNS.log(f"Could not decode resource advertisement, dropping resource: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None
# Create a resource for transmission to a remote destination
@@ -280,6 +281,19 @@ class Resource:
if hasattr(data, "read"):
if data_size == None: data_size = os.stat(data.name).st_size
if data_size == 0:
if isinstance(data, io.BufferedReader):
RNS.log(f"Attempting to proxy stream data...", RNS.LOG_DEBUG)
stream_proxy = tempfile.TemporaryFile()
stream_proxy.write(data.read())
stream_proxy.flush(); stream_proxy.seek(0)
data_size = os.stat(stream_proxy.name).st_size
if data_size: RNS.log(f"Stream proxy succeeded, final data size is {RNS.prettysize(data_size)}", RNS.LOG_DEBUG)
else: RNS.log(f"Resource initialisation received an invalid readable input, or stream data that could not be proxied, the transfer will likely fail.", RNS.LOG_WARNING)
data = stream_proxy
else: RNS.log(f"Got zero-sized readable at resource initialisation, the transfer will likely.", RNS.LOG_WARNING)
self.total_size = data_size + self.metadata_size
if self.total_size <= Resource.MAX_EFFICIENT_SIZE:
@@ -290,12 +304,6 @@ class Resource:
data.close()
else:
# self.total_segments = ((data_size-1)//Resource.MAX_EFFICIENT_SIZE)+1
# self.segment_index = segment_index
# self.split = True
# seek_index = segment_index-1
# seek_position = seek_index*Resource.MAX_EFFICIENT_SIZE
self.total_segments = ((self.total_size-1)//Resource.MAX_EFFICIENT_SIZE)+1
self.segment_index = segment_index
self.split = True
@@ -314,30 +322,26 @@ class Resource:
self.input_file = data
elif isinstance(data, bytes):
data_size = len(data)
data_size = len(data)
self.total_size = data_size + self.metadata_size
resource_data = data
resource_data = data
self.total_segments = 1
self.segment_index = 1
self.split = False
elif data == None:
pass
elif data == None: pass
else:
raise TypeError("Invalid data instance type passed to resource initialisation")
else: raise TypeError("Invalid data instance type passed to resource initialisation")
if resource_data:
if self.has_metadata: data = self.metadata + resource_data
else: data = resource_data
self.status = Resource.NONE
self.link = link
if self.link.mtu:
self.sdu = self.link.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
else:
self.sdu = link.mdu or Resource.SDU
self.link = link
if self.link.mtu: self.sdu = self.link.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
else: self.sdu = link.mdu or Resource.SDU
self.max_retries = Resource.MAX_RETRIES
self.max_adv_retries = Resource.MAX_ADV_RETRIES
self.retries_left = self.max_retries
@@ -376,10 +380,8 @@ class Resource:
self.req_hashlist = []
self.receiver_min_consecutive_height = 0
if timeout != None:
self.timeout = timeout
else:
self.timeout = self.link.rtt * self.link.traffic_timeout_factor
if timeout != None: self.timeout = timeout
else: self.timeout = self.link.rtt * self.link.traffic_timeout_factor
if data != None:
self.initiator = True
@@ -388,18 +390,21 @@ class Resource:
compression_began = time.time()
if self.auto_compress and data_size <= self.auto_compress_limit:
RNS.log("Compressing resource data...", RNS.LOG_EXTREME)
self.compressed_data = bz2.compress(self.uncompressed_data)
RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_EXTREME)
else:
self.compressed_data = self.uncompressed_data
RNS.log("Compressing resource data...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
try:
self.compressed_data = bz2.compress(self.uncompressed_data)
RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
except Exception as e:
RNS.log(f"Could not auto-compress resource data, falling back to uncompressed transfer: {e}", RNS.LOG_DEBUG)
self.compressed_data = self.uncompressed_data
else: self.compressed_data = self.uncompressed_data
self.uncompressed_size = len(self.uncompressed_data)
self.compressed_size = len(self.compressed_data)
if (self.compressed_size < self.uncompressed_size and auto_compress):
saved_bytes = len(self.uncompressed_data) - len(self.compressed_data)
RNS.log("Compression saved "+str(saved_bytes)+" bytes, sending compressed", RNS.LOG_EXTREME)
RNS.log("Compression saved "+str(saved_bytes)+" bytes, sending compressed", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.data = b""
self.data += RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE]
@@ -415,7 +420,7 @@ class Resource:
self.compressed = False
self.compressed_data = None
if self.auto_compress and data_size <= self.auto_compress_limit:
RNS.log("Compression did not decrease size, sending uncompressed", RNS.LOG_EXTREME)
RNS.log("Compression did not decrease size, sending uncompressed", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
self.compressed_data = None
self.uncompressed_data = None
@@ -435,7 +440,7 @@ class Resource:
hashmap_ok = False
while not hashmap_ok:
hashmap_computation_began = time.time()
RNS.log("Starting resource hashmap computation with "+str(hashmap_entries)+" entries...", RNS.LOG_EXTREME)
RNS.log("Starting resource hashmap computation with "+str(hashmap_entries)+" entries...", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
self.random_hash = RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE]
self.hash = RNS.Identity.full_hash(data+self.random_hash)
@@ -451,11 +456,11 @@ class Resource:
self.hashmap = b""
collision_guard_list = []
for i in range(0,hashmap_entries):
data = self.data[i*self.sdu:(i+1)*self.sdu]
map_hash = self.get_map_hash(data)
part_data = self.data[i*self.sdu:(i+1)*self.sdu]
map_hash = self.get_map_hash(part_data)
if map_hash in collision_guard_list:
RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG)
RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
hashmap_ok = False
break
else:
@@ -464,14 +469,14 @@ class Resource:
if len(collision_guard_list) > ResourceAdvertisement.COLLISION_GUARD_SIZE:
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.map_hash = map_hash
self.hashmap += part.map_hash
self.parts.append(part)
RNS.log("Hashmap computation concluded in "+str(round(time.time()-hashmap_computation_began, 3))+" seconds", RNS.LOG_EXTREME)
RNS.log("Hashmap computation concluded in "+str(round(time.time()-hashmap_computation_began, 3))+" seconds", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
self.data = None
if advertise:
@@ -482,12 +487,12 @@ class Resource:
def hashmap_update_packet(self, plaintext):
if not self.status == Resource.FAILED:
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])
if self.waiting_for_hmu:
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])
def hashmap_update(self, segment, hashmap):
if not self.status == Resource.FAILED:
@@ -495,12 +500,16 @@ class Resource:
seg_len = ResourceAdvertisement.HASHMAP_MAX_LEN
hashes = len(hashmap)//Resource.MAPHASH_LEN
for i in range(0,hashes):
if self.hashmap[i+segment*seg_len] == None:
self.hashmap_height += 1
if self.hashmap[i+segment*seg_len] == None: self.hashmap_height += 1
self.hashmap[i+segment*seg_len] = hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
self.waiting_for_hmu = False
self.request_next()
if hashes < 1:
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):
return RNS.Identity.full_hash(data+self.random_hash)[:Resource.MAPHASH_LEN]
@@ -517,6 +526,14 @@ class Resource:
prepare_thread = threading.Thread(target=self.__prepare_next_segment, daemon=True)
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):
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
while not self.link.ready_for_new_resource():
@@ -524,6 +541,7 @@ class Resource:
sleep(0.25)
try:
if not self.ensure_link(): return
self.advertisement_packet.send()
self.last_activity = time.time()
self.started_transferring = self.last_activity
@@ -532,7 +550,7 @@ class Resource:
self.status = Resource.ADVERTISED
self.retries_left = self.max_adv_retries
self.link.register_outgoing_resource(self)
RNS.log("Sent resource advertisement for "+RNS.prettyhexrep(self.hash), RNS.LOG_EXTREME)
RNS.log("Sent resource advertisement for "+RNS.prettyhexrep(self.hash), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
except Exception as e:
RNS.log("Could not advertise resource, the contained exception was: "+str(e), RNS.LOG_ERROR)
self.cancel()
@@ -541,18 +559,13 @@ class Resource:
self.watchdog_job()
def update_eifr(self):
if self.rtt == None:
rtt = self.link.rtt
else:
rtt = self.rtt
if self.rtt == None: rtt = self.link.rtt
else: rtt = self.rtt
if self.req_data_rtt_rate != 0:
expected_inflight_rate = self.req_data_rtt_rate*8
if self.req_data_rtt_rate != 0: expected_inflight_rate = self.req_data_rtt_rate*8
else:
if self.previous_eifr != None:
expected_inflight_rate = self.previous_eifr
else:
expected_inflight_rate = self.link.establishment_cost*8 / rtt
if self.previous_eifr != None: expected_inflight_rate = self.previous_eifr
else: expected_inflight_rate = self.link.establishment_cost*8 / rtt
self.eifr = expected_inflight_rate
if self.link: self.link.expected_rate = self.eifr
@@ -566,28 +579,28 @@ class Resource:
this_job_id = self.__watchdog_job_id
while self.status < Resource.ASSEMBLING and this_job_id == self.__watchdog_job_id:
while self.watchdog_lock:
sleep(0.025)
while self.watchdog_lock: sleep(0.025)
sleep_time = None
if self.status == Resource.ADVERTISED:
sleep_time = (self.adv_sent+self.timeout+Resource.PROCESSING_GRACE)-time.time()
if sleep_time < 0:
if self.retries_left <= 0:
RNS.log("Resource transfer timeout after sending advertisement", RNS.LOG_DEBUG)
RNS.log("Resource transfer timeout after sending advertisement", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
sleep_time = 0.001
else:
try:
RNS.log("No part requests received, retrying resource advertisement...", RNS.LOG_DEBUG)
RNS.log("No part requests received, retrying resource advertisement...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
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.send()
self.last_activity = time.time()
self.adv_sent = self.last_activity
sleep_time = 0.001
except Exception as e:
RNS.log("Could not resend advertisement packet, cancelling resource. The contained exception was: "+str(e), RNS.LOG_VERBOSE)
RNS.log("Could not resend advertisement packet, cancelling resource. The contained exception was: "+str(e), RNS.LOG_VERBOSE) if RNS.sl(RNS.LOG_VERBOSE) else None
self.cancel()
@@ -612,7 +625,7 @@ class Resource:
if sleep_time < 0:
if self.retries_left > 0:
ms = "" if self.outstanding_parts == 1 else "s"
RNS.log(f"Timed out waiting for {self.outstanding_parts} part{ms}, requesting retry on {self}", RNS.LOG_DEBUG)
RNS.log(f"Timed out waiting for {self.outstanding_parts} part{ms}, requesting retry on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if self.window > self.window_min:
self.window -= 1
if self.window_max > self.window_min:
@@ -632,7 +645,7 @@ class Resource:
max_wait = self.rtt * self.timeout_factor * self.max_retries + self.sender_grace_time + max_extra_wait
sleep_time = self.last_activity + max_wait - time.time()
if sleep_time < 0:
RNS.log("Resource timed out waiting for part requests", RNS.LOG_DEBUG)
RNS.log("Resource timed out waiting for part requests", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
sleep_time = 0.001
@@ -644,11 +657,11 @@ class Resource:
sleep_time = self.last_part_sent + (self.rtt*self.timeout_factor+self.sender_grace_time) - time.time()
if sleep_time < 0:
if self.retries_left <= 0:
RNS.log("Resource timed out waiting for proof", RNS.LOG_DEBUG)
RNS.log("Resource timed out waiting for proof", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
sleep_time = 0.001
else:
RNS.log("All parts sent, but no resource proof received, querying network cache...", RNS.LOG_DEBUG)
RNS.log("All parts sent, but no resource proof received, querying network cache...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.retries_left -= 1
expected_data = self.hash + self.expected_proof
expected_proof_packet = RNS.Packet(self.link, expected_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.RESOURCE_PRF)
@@ -657,13 +670,13 @@ class Resource:
self.last_part_sent = time.time()
sleep_time = 0.001
elif self.status == Resource.REJECTED:
elif self.status >= Resource.ASSEMBLING:
sleep_time = 0.001
if sleep_time == 0:
RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_DEBUG)
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:
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()
if sleep_time != None:
@@ -746,7 +759,7 @@ class Resource:
except Exception as e:
RNS.log(f"Error while cleaning up resource files, the contained exception was: {e}", RNS.LOG_ERROR)
else:
RNS.log("Resource segment "+str(self.segment_index)+" of "+str(self.total_segments)+" received, waiting for next segment to be announced", RNS.LOG_DEBUG)
RNS.log("Resource segment "+str(self.segment_index)+" of "+str(self.total_segments)+" received, waiting for next segment to be announced", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
def prove(self):
@@ -754,17 +767,18 @@ class Resource:
try:
proof = RNS.Identity.full_hash(self.data+self.hash)
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.send()
RNS.Transport.cache(proof_packet, force_cache=True)
except Exception as e:
RNS.log("Could not send proof packet, cancelling resource", RNS.LOG_DEBUG)
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
RNS.log("Could not send proof packet, cancelling resource", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
def __prepare_next_segment(self):
# Prepare the next segment for advertisement
RNS.log(f"Preparing segment {self.segment_index+1} of {self.total_segments} for resource {self}", RNS.LOG_DEBUG)
RNS.log(f"Preparing segment {self.segment_index+1} of {self.total_segments} for resource {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.preparing_next_segment = True
self.next_segment = Resource(self.input_file, self.link,
callback = self.callback,
@@ -776,8 +790,8 @@ class Resource:
advertise = False,
auto_compress = self.auto_compress_option,
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):
if not self.status == Resource.FAILED:
@@ -860,9 +874,9 @@ class Resource:
part_data = packet.data
part_hash = self.get_map_hash(part_data)
consecutive_index = self.consecutive_completed_height if self.consecutive_completed_height >= 0 else 0
i = consecutive_index
for map_hash in self.hashmap[consecutive_index:consecutive_index+self.window]:
search_start = self.consecutive_completed_height+1
i = search_start
for map_hash in self.hashmap[search_start:search_start+self.window]:
if map_hash == part_hash:
if self.parts[i] == None:
@@ -873,9 +887,6 @@ class Resource:
self.outstanding_parts -= 1
# Update consecutive completed pointer
if i == self.consecutive_completed_height + 1:
self.consecutive_completed_height = i
cp = self.consecutive_completed_height + 1
while cp < len(self.parts) and self.parts[cp] != None:
self.consecutive_completed_height = cp
@@ -966,6 +977,7 @@ class Resource:
request_packet = RNS.Packet(self.link, request_data, context = RNS.Packet.RESOURCE_REQ)
try:
if not self.ensure_link(): return
request_packet.send()
self.last_activity = time.time()
self.req_sent = self.last_activity
@@ -974,8 +986,8 @@ class Resource:
self.req_resp = None
except Exception as e:
RNS.log("Could not send resource request packet, cancelling resource", RNS.LOG_DEBUG)
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
RNS.log("Could not send resource request packet, cancelling resource", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
# Called on outgoing resource to make it send more data
@@ -1010,18 +1022,18 @@ class Resource:
for part in requested_parts:
try:
if not self.ensure_link(): return
if not part.sent:
part.send()
self.sent_parts += 1
else:
part.resend()
else: part.resend()
self.last_activity = time.time()
self.last_part_sent = self.last_activity
except Exception as e:
RNS.log("Resource could not send parts, cancelling transfer!", RNS.LOG_DEBUG)
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
RNS.log("Resource could not send parts, cancelling transfer!", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
if wants_more_hashmap:
@@ -1032,8 +1044,7 @@ class Resource:
search_end = self.receiver_min_consecutive_height+ResourceAdvertisement.COLLISION_GUARD_SIZE
for part in self.parts[search_start:search_end]:
part_index += 1
if part.map_hash == last_map_hash:
break
if part.map_hash == last_map_hash: break
self.receiver_min_consecutive_height = max(part_index-1-Resource.WINDOW_MAX, 0)
@@ -1041,10 +1052,8 @@ class Resource:
RNS.log("Resource sequencing error, cancelling transfer!", RNS.LOG_ERROR)
self.cancel()
return
else:
segment = part_index // ResourceAdvertisement.HASHMAP_MAX_LEN
else: segment = part_index // ResourceAdvertisement.HASHMAP_MAX_LEN
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
hashmap_end = min((segment+1)*ResourceAdvertisement.HASHMAP_MAX_LEN, len(self.parts))
@@ -1052,15 +1061,21 @@ class Resource:
for i in range(hashmap_start,hashmap_end):
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_packet = RNS.Packet(self.link, hmu, context = RNS.Packet.RESOURCE_HMU)
try:
if not self.ensure_link(): return
hmu_packet.send()
self.last_activity = time.time()
except Exception as e:
RNS.log("Could not send resource HMU packet, cancelling resource", RNS.LOG_DEBUG)
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
RNS.log("Could not send resource HMU packet, cancelling resource", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.cancel()
if self.sent_parts == len(self.parts):
@@ -1079,7 +1094,7 @@ class Resource:
if self.next_segment: self.next_segment.cancel()
if self.status == Resource.CORRUPT:
self.link.cancel_incoming_resource(self)
if self in self.link.incoming_resources: self.link.cancel_incoming_resource(self)
self.reject(self.advertisement_packet)
self.link.teardown()
@@ -1090,11 +1105,15 @@ class Resource:
try:
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_ICL)
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_outgoing_resource(self)
except Exception as e: RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
if self in self.link.outgoing_resources: self.link.cancel_outgoing_resource(self)
else:
self.link.cancel_incoming_resource(self)
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)
if self in self.link.incoming_resources: self.link.cancel_incoming_resource(self)
if self.callback != None:
try:
@@ -1107,7 +1126,7 @@ class Resource:
if self.status < Resource.COMPLETE:
if self.initiator:
self.status = Resource.REJECTED
self.link.cancel_outgoing_resource(self)
if self in self.link.outgoing_resources: self.link.cancel_outgoing_resource(self)
if self.callback != None:
try:
self.link.resource_concluded(self)
@@ -1228,7 +1247,9 @@ class Resource:
return self.compressed
def __str__(self):
return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">"
if hasattr(self, "hash") and self.hash and hasattr(self, "link") and self.link:
return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">"
else: return "<initializing_resource/unknown>"
class ResourceAdvertisement:
@@ -1241,40 +1262,30 @@ class ResourceAdvertisement:
@staticmethod
def is_request(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
if adv.q != None and adv.u:
return True
else:
return False
if adv.q != None and adv.u: return True
else: return False
@staticmethod
def is_response(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
if adv.q != None and adv.p:
return True
else:
return False
if adv.q != None and adv.p: return True
else: return False
@staticmethod
def read_request_id(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
return adv.q
@staticmethod
def read_transfer_size(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
return adv.t
@staticmethod
def read_size(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
return adv.d
def __init__(self, resource=None, request_id=None, is_response=False):
self.link = None
if resource != None:
@@ -1306,29 +1317,14 @@ class ResourceAdvertisement:
# Flags
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):
return self.t
def get_data_size(self):
return self.d
def get_parts(self):
return self.n
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 get_transfer_size(self): return self.t
def get_data_size(self): return self.d
def get_parts(self): return self.n
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):
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
@@ -1338,23 +1334,20 @@ class ResourceAdvertisement:
for i in range(hashmap_start,hashmap_end):
hashmap += self.m[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
dictionary = {
"t": self.t, # Transfer size
"d": self.d, # Data size
"n": self.n, # Number of parts
"h": self.h, # Resource hash
"r": self.r, # Resource random hash
"o": self.o, # Original hash
"i": self.i, # Segment index
"l": self.l, # Total segments
"q": self.q, # Request ID
"f": self.f, # Resource flags
"m": hashmap
}
dictionary = { "t": self.t, # Transfer size
"d": self.d, # Data size
"n": self.n, # Number of parts
"h": self.h, # Resource hash
"r": self.r, # Resource random hash
"o": self.o, # Original hash
"i": self.i, # Segment index
"l": self.l, # Total segments
"q": self.q, # Request ID
"f": self.f, # Resource flags
"m": hashmap }
return umsgpack.packb(dictionary)
@staticmethod
def unpack(data):
dictionary = umsgpack.unpackb(data)
@@ -1378,4 +1371,6 @@ class ResourceAdvertisement:
adv.p = True if ((adv.f >> 4) & 0x01) == 0x01 else False
adv.x = True if ((adv.f >> 5) & 0x01) == 0x01 else False
return adv
if adv.t > Resource.MAX_EFFICIENT_SIZE*3: raise ValueError("Invalid transfer size")
return adv
+725 -284
View File
File diff suppressed because it is too large. Load diff
+1818 -1139
View File
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -33,5 +33,7 @@ import glob
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+14 -11
View File
@@ -163,11 +163,11 @@ def listen(configdir, identitypath = None, verbosity = 0, quietness = 0, allowed
except Exception as e:
raise ValueError("Invalid destination entered. Check your input.")
except Exception as e:
print(str(e))
RNS.log(f"Could not apply allowed identity: {e}", RNS.LOG_ERROR)
RNS.exit(1)
if len(allowed_identity_hashes) < 1 and not disable_auth:
print("Warning: No allowed identities configured, rncp will not accept any files!")
RNS.log("No allowed identities configured, rncp will not accept any files!", RNS.LOG_WARNING)
def fetch_request(path, data, request_id, link_id, remote_identity, requested_at):
global allow_fetch, fetch_jail, fetch_auto_compress
@@ -217,7 +217,7 @@ def listen(configdir, identitypath = None, verbosity = 0, quietness = 0, allowed
else:
destination.register_request_handler("fetch_file", response_generator=fetch_request, allow=RNS.Destination.ALLOW_LIST, allowed_list=allowed_identity_hashes)
print("rncp listening on "+RNS.prettyhexrep(destination.hash))
RNS.log("rncp listening on "+RNS.prettyhexrep(destination.hash), RNS.LOG_INFO)
if announce >= 0:
def job():
@@ -271,15 +271,15 @@ def receive_resource_started(resource):
else:
id_str = ""
print("Starting resource transfer "+RNS.prettyhexrep(resource.hash)+id_str)
RNS.log("Starting resource transfer "+RNS.prettyhexrep(resource.hash)+id_str, RNS.LOG_INFO)
def receive_resource_concluded(resource):
global save_path, allow_overwrite_on_receive
if resource.status == RNS.Resource.COMPLETE:
print(str(resource)+" completed")
RNS.log(f"Incoming resource {resource} completed", RNS.LOG_INFO)
if resource.metadata == None:
print("Invalid data received, ignoring resource")
RNS.log("Invalid data received, ignoring resource", RNS.LOG_WARNING)
return
else:
@@ -306,13 +306,14 @@ def receive_resource_concluded(resource):
full_save_path = saved_filename+"."+str(counter)
shutil.move(resource.data.name, full_save_path)
RNS.log("Saved received file to "+full_save_path, RNS.LOG_NOTICE)
except Exception as e:
RNS.log(f"An error occurred while saving received resource: {e}", RNS.LOG_ERROR)
return
else:
print("Resource failed")
RNS.log("Resource failed", RNS.LOG_INFO)
resource_done = False
current_resource = None
@@ -400,7 +401,7 @@ def fetch(configdir, identitypath = None, verbosity = 0, quietness = 0, destinat
i = 0
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:
if not silent:
time.sleep(0.1)
@@ -430,6 +431,7 @@ def fetch(configdir, identitypath = None, verbosity = 0, quietness = 0, destinat
)
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:
if not silent:
time.sleep(0.1)
@@ -655,7 +657,7 @@ def send(configdir, identitypath = None, verbosity = 0, quietness = 0, destinati
i = 0
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:
if not silent:
time.sleep(0.1)
@@ -685,6 +687,7 @@ def send(configdir, identitypath = None, verbosity = 0, quietness = 0, destinati
)
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:
if not silent:
time.sleep(0.1)
@@ -877,8 +880,8 @@ def main():
except KeyboardInterrupt:
print("")
if resource != None:
resource.cancel()
if current_resource != None:
current_resource.cancel()
if link != None:
link.teardown()
RNS.exit()
+4 -2
View File
@@ -35,5 +35,7 @@ import glob
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+53 -9
View File
@@ -40,6 +40,7 @@ import subprocess
from RNS._version import __version__
from RNS.Utilities.rngit import APP_NAME
from RNS.Utilities.rngit.util import medium_path_timeout
from RNS.vendor.configobj import ConfigObj
from tempfile import TemporaryDirectory
@@ -101,6 +102,7 @@ class ReticulumGitClient():
self.config = None
self.ready = False
self.destination_aliases = {}
self.remote_identity = None
self.destination = None
self.link = None
@@ -138,12 +140,6 @@ class ReticulumGitClient():
self.configpath = self.configdir+"/client_config"
self.identitypath = self.configdir+"/client_identity"
RNS.logfile = self.logfile
try: self.reticulum = RNS.Reticulum(configdir=rnsconfigdir, logdest=RNS.LOG_FILE)
except Exception as e:
print(f"Failed to initialize Reticulum: {e}", file=sys.stderr)
return
if os.path.isfile(self.configpath):
try: self.config = ConfigObj(self.configpath)
except Exception as e:
@@ -152,6 +148,12 @@ class ReticulumGitClient():
else: self.__create_default_config()
RNS.logfile = self.logfile
try: self.reticulum = RNS.Reticulum(configdir=rnsconfigdir, logdest=RNS.LOG_FILE)
except Exception as e:
print(f"Failed to initialize Reticulum: {e}", file=sys.stderr)
return
self.__apply_config()
self.ready = True
@@ -170,6 +172,18 @@ class ReticulumGitClient():
section = self.config["client"]
if "ref_batch_size" in section: self.ref_batch_size = max(0, min(1024, section.as_int("ref_batch_size")))
if "aliases" in self.config:
section = self.config["aliases"]
for alias in section:
alias_hexhash = section[alias]
len_ok = len(alias_hexhash) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2
try: alias_hash = bytes.fromhex(alias_hexhash)
except: alias_hash = None
alias_exists = alias in self.destination_aliases
if not len_ok or not alias_hash: continue
if alias_exists: continue
self.destination_aliases[alias] = RNS.hexrep(alias_hash, delimit=False)
if not os.path.isfile(self.identitypath):
identity = RNS.Identity()
identity.to_file(self.identitypath)
@@ -185,6 +199,19 @@ class ReticulumGitClient():
else: self.identity = identity
self.destination_hexhash = self.__resolve_destination_alias(self.destination_hexhash)
def __resolve_destination_alias(self, alias):
def resolve(alias):
len_match = len(alias) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2
try: hash_bytes = bytes.fromhex(alias)
except: hash_bytes = None
if len_match and hash_bytes: return alias
else: return self.destination_aliases[alias] if alias in self.destination_aliases else alias
resolved = resolve(alias)
return resolved
def abort(self, reason=None, code=255):
if not reason: reason = "Unknown reason"
print(f"git-remote-rns failed: {reason}", file=sys.stderr)
@@ -197,7 +224,7 @@ class ReticulumGitClient():
RNS.log(f"Requesting path to {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG)
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()
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
@@ -265,6 +292,8 @@ class ReticulumGitClient():
if hasattr(self.request_response, "read") and callable(self.request_response.read):
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)
retained_path = os.path.join(self.tmp_dir.name, base_name)
shutil.move(response_path, retained_path)
@@ -307,10 +336,10 @@ class ReticulumGitClient():
try: self.connect_server()
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:
time.sleep(0.5)
timeout -= 1
timeout -= 0.5
if not self.link_ready: self.abort("Failed to establish link")
@@ -656,6 +685,21 @@ __default_rngit_config__ = '''# This is the default rngit client config file.
ref_batch_size = 25
[aliases]
# You can define aliases for commonly used destination
# hashes in this section. Each line must be in the format
# aliased_name = DESTINATION_HASH
#
# These hashes are used for resolving remote destinations.
# For rngit node permissions and identity resolution,
# aliases must be defined in ~/.rngit/config.
# my_node = 063d38912bffc850af4a1b8a270a9d85
# bobs_node = 714981d03e41deda0e4468cb274414cc
[logging]
# Valid log levels are 0 through 7:
# 0: Log only critical information
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env python3
# Reticulum License
#
# Copyright (c) 2016-2026 Mark Qvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# - The Software shall not be used in any kind of system which includes amongst
# its functions the ability to purposefully do harm to human beings.
#
# - The Software shall not be used, directly or indirectly, in the creation of
# an artificial intelligence, machine learning or language model training
# dataset, including but not limited to any use that contributes to the
# training or development of such a model or algorithm.
#
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import sys
import RNS
import struct
import base64
import argparse
from RNS.Utilities.rnid import validate_rsg, create_rsg, extract_signed_rsg_data
SSHSIG_MAGIC = b"SSHSIG"
SSHSIG_VERSION = 1
NAMESPACE_GIT = b"git"
RESERVED_EMPTY = b""
HASH_ALGORITHM = b"sha256"
def ssh_string(data): return struct.pack(">I", len(data)) + data
def read_ssh_string(data, offset):
if offset + 4 > len(data): raise ValueError("Not enough data for string length")
length = struct.unpack(">I", data[offset:offset+4])[0]
if offset + 4 + length > len(data): raise ValueError("Not enough data for string content")
return data[offset+4:offset+4+length], offset + 4 + length
def create_ssh_signature(public_key_wire, namespace, reserved, hash_algorithm, signature_data):
# SSHSIG (6 bytes) || version (uint32) || pubkey (ssh-string) || namespace (ssh-string) ||
# reserved (ssh-string) || hash_algorithm (ssh-string) || signature (ssh-string)
sig_blob = SSHSIG_MAGIC
sig_blob += struct.pack(">I", SSHSIG_VERSION)
sig_blob += ssh_string(public_key_wire)
sig_blob += ssh_string(namespace)
sig_blob += ssh_string(reserved)
sig_blob += ssh_string(hash_algorithm)
sig_blob += ssh_string(signature_data)
return sig_blob
def parse_ssh_signature(sig_data):
offset = 0
if not sig_data.startswith(SSHSIG_MAGIC): raise ValueError("Invalid SSH signature: missing SSHSIG magic")
offset += len(SSHSIG_MAGIC)
if offset + 4 > len(sig_data): raise ValueError("Invalid SSH signature: truncated")
version = struct.unpack(">I", sig_data[offset:offset+4])[0]
if version != SSHSIG_VERSION: raise ValueError(f"Unsupported SSH signature version: {version}")
offset += 4
public_key, offset = read_ssh_string(sig_data, offset)
namespace, offset = read_ssh_string(sig_data, offset)
reserved, offset = read_ssh_string(sig_data, offset)
hash_algorithm, offset = read_ssh_string(sig_data, offset)
signature_data, offset = read_ssh_string(sig_data, offset)
return { "version": version,
"public_key": public_key,
"namespace": namespace,
"reserved": reserved,
"hash_algorithm": hash_algorithm,
"signature_data": signature_data }
def armor_ssh_signature(sig_blob):
b64_data = base64.b64encode(sig_blob).decode('ascii')
lines = [b64_data[i:i+70] for i in range(0, len(b64_data), 70)]
result = "-----BEGIN SSH SIGNATURE-----\n"
result += "\n".join(lines) + "\n"
result += "-----END SSH SIGNATURE-----\n"
return result
def unarmor_ssh_signature(armored_data):
lines = armored_data.strip().split('\n')
b64_data = ""
in_sig = False
for line in lines:
if 'BEGIN SSH SIGNATURE' in line: in_sig = True; continue
if 'END SSH SIGNATURE' in line: break
if in_sig: b64_data += line.strip()
if not b64_data: raise ValueError("No signature data found in armored input")
return base64.b64decode(b64_data)
def get_pubkey_wire_format(identity):
return ssh_string(b"ssh-ed25519")+ssh_string(identity.sig_pub_bytes)
def sign(args):
keyfile = args.keyfile
if not keyfile or not os.path.isfile(keyfile):
print(f"Identity file not found: {keyfile}", file=sys.stderr)
return 1
try:
identity = RNS.Identity.from_file(keyfile)
if not identity or not identity.get_private_key():
print("Error: Could not load identity or identity has no private key", file=sys.stderr)
return 1
except Exception as e:
print(f"Error loading identity: {e}", file=sys.stderr)
return 1
if args.file and os.path.isfile(args.file):
with open(args.file, 'rb') as f: message = f.read()
sig_file = args.file + ".sig"
else:
message = sys.stdin.buffer.read()
sig_file = None
try: rsg = create_rsg(identity, message)
except Exception as e:
print(f"Error creating signature: {e}", file=sys.stderr)
return 1
try: ssh_pubkey = get_pubkey_wire_format(identity)
except Exception as e:
print(f"Error converting public key: {e}", file=sys.stderr)
return 1
try:
ssh_sig = create_ssh_signature(public_key_wire=ssh_pubkey, namespace=NAMESPACE_GIT, reserved=RESERVED_EMPTY,
hash_algorithm=HASH_ALGORITHM, signature_data=rsg)
except Exception as e:
print(f"Error creating SSH signature: {e}", file=sys.stderr)
return 1
try: armored = armor_ssh_signature(ssh_sig)
except Exception as e:
print(f"Error armoring signature: {e}", file=sys.stderr)
return 1
if sig_file:
try:
with open(sig_file, 'w') as f: f.write(armored)
except Exception as e:
print(f"Error writing signature file: {e}", file=sys.stderr)
return 1
else: print(armored, end="")
return 0
def find_principals(args):
sigfile = args.sigfile
if not sigfile or not os.path.isfile(sigfile): print("Error: Signature file not found", file=sys.stderr); return 1
try:
with open(sigfile, 'r') as f: armored_sig = f.read()
except Exception as e: print(f"Error reading signature file: {e}", file=sys.stderr); return 1
try: ssh_sig = parse_ssh_signature(unarmor_ssh_signature(armored_sig))
except Exception as e: print(f"Error parsing SSH signature: {e}", file=sys.stderr); return 1
if ssh_sig["namespace"] != NAMESPACE_GIT:
print(f"Error: Namespace mismatch: {ssh_sig['namespace']}", file=sys.stderr)
return 1
rsg = ssh_sig["signature_data"]
try: identity_hash = extract_signed_rsg_data(rsg)["meta"]["signer"]
except Exception as e: print(f"Could not determine signer identity: {e}", file=sys.stderr); return 1
print(RNS.hexrep(identity_hash, delimit=False))
return 0
def check_novalidate(args):
sigfile = args.sigfile
if not sigfile or not os.path.isfile(sigfile): return 1
try:
with open(sigfile, 'r') as f: armored_sig = f.read()
ssh_sig = parse_ssh_signature(unarmor_ssh_signature(armored_sig))
if ssh_sig["namespace"] != NAMESPACE_GIT: return 1
rsg = ssh_sig["signature_data"]
signed_data = extract_signed_rsg_data(rsg)
if not signed_data: return 1
else: return 0
except Exception: return 1
def extract_commit_author(message):
message_lines = message.splitlines()
author = ""
AUTHOR_TARGET = b"author "
for line in message_lines:
if not line.strip(b""): break
elif line.startswith(AUTHOR_TARGET):
try:
spos = line.find(b"<"); epos = line.find(b">")
if spos > len(AUTHOR_TARGET) and epos > spos and epos < len(line)-1:
author = line[spos+1:epos].decode("utf-8")
break
except Exception as e: print(f"Error while determining author from signed commit"); return 1
return author
def extract_commit_committer(message):
message_lines = message.splitlines()
committer = ""
COMMITTER_TARGET = b"committer "
for line in message_lines:
if not line.strip(b""): break
elif line.startswith(COMMITTER_TARGET):
try:
spos = line.find(b"<"); epos = line.find(b">")
if spos > len(COMMITTER_TARGET) and epos > spos and epos < len(line)-1:
committer = line[spos+1:epos].decode("utf-8")
break
except Exception as e: print(f"Error while determining committer from signed commit"); return 1
return committer
def extract_commit_tagger(message):
message_lines = message.splitlines()
tagger = ""
is_tag = False
for line in message_lines:
TAG_TARGET = b"tag "
TAGGER_TARGET = b"tagger "
if not line.strip(b""): break
elif line.startswith(TAG_TARGET): is_tag = True
elif line.startswith(TAGGER_TARGET) and is_tag:
try:
spos = line.find(b"<"); epos = line.find(b">")
if spos > len(TAGGER_TARGET) and epos > spos and epos < len(line)-1:
tagger = line[spos+1:epos].decode("utf-8")
break
except Exception as e: print(f"Error while determining tagger from signed commit"); return 1
return tagger, is_tag
def verify(args):
sigfile = args.sigfile
principal = args.principal
if not sigfile or not os.path.isfile(sigfile): print("Error: Signature file not found", file=sys.stderr); return 1
message = sys.stdin.buffer.read()
try:
with open(sigfile, 'r') as f: armored_sig = f.read()
raw_sig = unarmor_ssh_signature(armored_sig)
ssh_sig = parse_ssh_signature(raw_sig)
except Exception as e: print(f"Error parsing signature: {e}", file=sys.stderr); return 1
author = extract_commit_author(message)
committer = extract_commit_committer(message)
tagger, is_tag = extract_commit_tagger(message)
if ssh_sig["namespace"] != NAMESPACE_GIT: print(f"Invalid commit signature namespace", file=sys.stderr); return 1
rsg = ssh_sig["signature_data"]
valid, signed_data, signing_identity = validate_rsg(rsg, message)
if not valid: print(f"Invalid signature", file=sys.stderr); return 1
if is_tag: author = tagger
signer_hash = RNS.hexrep(signing_identity.hash, delimit=False)
if not author == signer_hash: print(f"Commit not signed by author <{author}>"); return 1
if principal:
if principal != signer_hash: print(f"Principal mismatch", file=sys.stderr); return 1
print(f"Good \"git\" signature for commit, signed with Reticulum Identity key <{signer_hash}>")
return 0
def main():
parser = argparse.ArgumentParser(description="Git commit signer and validator")
parser.add_argument("-Y", dest="op", required=True, choices=["sign", "find-principals", "check-novalidate", "verify"], help="Operation to perform")
parser.add_argument("-n", dest="namespace", default="git", help="Namespace")
parser.add_argument("-f", dest="keyfile", help="Key file (for signing) or allowed signers file (for verification)")
parser.add_argument("-I", dest="principal", help="Principal identity (for verification)")
parser.add_argument("-s", dest="sigfile", help="Signature file")
parser.add_argument("file", nargs="?", help="File to sign (for signing)")
parser.add_argument("-O", dest="ssh_options", action="append", default=[], help="SSH options (for git compatibility, ignored)")
args, unknown = parser.parse_known_args()
for arg in unknown:
if arg.startswith('-O'): continue # TODO: Add options for time validation
else:
print(f"Error: Unknown argument: {arg}", file=sys.stderr)
sys.exit(1)
if args.op == "sign": return sign(args)
elif args.op == "find-principals": return find_principals(args)
elif args.op == "check-novalidate": return check_novalidate(args)
elif args.op == "verify": return verify(args)
else:
print(f"Error: Unknown operation: {args.op}", file=sys.stderr)
return 1
if __name__ == "__main__": sys.exit(main())
+35 -12
View File
@@ -165,15 +165,15 @@ class SyntaxHighlighter:
except Exception as e:
RNS.log(f"Pygments highlighting failed, falling back: {e}", RNS.LOG_WARNING)
return self._plain_text(content)
return self._plain_text(content).replace("\\", "\\\\")
# TODO: Implement Python tokenize fallback for .py files.
# For now, route to plain text
if filename and filename.endswith(".py"):
return self._plain_text(content)
return self._plain_text(content).replace("\\", "\\\\")
# Universal fallback
return self._plain_text(content)
return self._plain_text(content).replace("\\", "\\\\")
def _highlight_pygments(self, content, filename=None, language=None):
from pygments.lexers import get_lexer_for_filename, guess_lexer, get_lexer_by_name
@@ -218,8 +218,10 @@ class MicronFormatter:
output_parts = []
prev_was_dot = False
last_ended_with_break = True
for ttype, value in tokensource:
is_dot = (str(ttype) == "Token.Operator" and value == ".")
ends_with_break = value.endswith("\n")
# If previous token was a dot and this is a Name, treat as attribute/function call
# TODO: Improve this if we can check next token as parantheses or something.
@@ -241,19 +243,39 @@ class MicronFormatter:
else: ilb = ""
if escaped.endswith("\n"): tlb = "\n"; escaped = escaped[:-1]
else: tlb = ""
output_parts.append(f"{ilb}`FT{color}{escaped}`f{tlb}")
if len(escaped): output = f"{ilb}`FT{color}{escaped}`f{tlb}"
else: output = f"{ilb}{tlb}"
output_parts.append(output)
else: output_parts.append(self._escape_value(value))
else:
escaped = self._escape_value(value)
if "\n" in escaped:
parts = []
splitl = escaped.splitlines()
if len(splitl) > 1:
for line in splitl:
if line.startswith("-"): l = f"\\{line}"
elif line.startswith(">"): l = f"\\{line}"
elif line.startswith("<"): l = f"\\{line}"
else: l = line
parts.append(l)
trmpart = "\n" if escaped.endswith("\n") else ""
escaped = "\n".join(parts)+trmpart
elif last_ended_with_break:
if escaped.startswith("-"): escaped = f"\\{escaped}"
elif escaped.startswith(">"): escaped = f"\\{escaped}"
elif escaped.startswith("<"): escaped = f"\\{escaped}"
output_parts.append(escaped)
prev_was_dot = is_dot
last_ended_with_break = ends_with_break
output = "".join(output_parts)
final_output = ""
for line in output.splitlines():
if line.startswith(">"): line = f"`>{line}"
final_output += f"{line}\n"
outfile.write(final_output)
outfile.write(output)
def _get_color_key_for_token(self, ttype):
token_parts = []
@@ -279,7 +301,8 @@ class MicronFormatter:
return None
@staticmethod
def _escape_value(value: str) -> str: return value.replace("`", "\\`")
def _escape_value(value):
return value.replace("\\", "\\\\").replace("`", "\\`")
# Required by Pygments formatter API, returns None for Micron
def get_style_defs(self, arg=None): return None
+239
View File
@@ -0,0 +1,239 @@
# Reticulum License
#
# Copyright (c) 2016-2026 Mark Qvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# - The Software shall not be used in any kind of system which includes amongst
# its functions the ability to purposefully do harm to human beings.
#
# - The Software shall not be used, directly or indirectly, in the creation of
# an artificial intelligence, machine learning or language model training
# dataset, including but not limited to any use that contributes to the
# training or development of such a model or algorithm.
#
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import time
import shutil
import subprocess
import tempfile
import RNS
CONVERSION_TIMEOUT = 8
# WebP encoding backends, in preference order. All supported
# encoder families handle the common still formats (PNG, JPEG,
# TIFF, BMP, GIF, WebP).
#
# Environment overrides:
# RNGIT_MEDIA_BACKEND force a specific backend
BACKENDS = ( ("magick", ["magick", "-", "webp:-"]),
("convert", ["convert", "-", "webp:-"]),
("gm", ["gm", "convert", "-", "webp:-"]),
("ffmpeg", ["ffmpeg", "-y", "-loglevel", "error", "-i", "-", "-f", "webp", "pipe:1"]),
("avconv", ["avconv", "-y", "-loglevel", "error", "-i", "-", "-f", "webp", "pipe:1"]) )
_ENV_BACKEND = os.environ.get("RNGIT_MEDIA_BACKEND")
_winner = None
_no_backend_logged = False
def available_backends():
out = []
for name, argv in BACKENDS: out.append((name, shutil.which(argv[0]) is not None))
return out
def _selected_backend():
global _winner
if _ENV_BACKEND:
for name, argv in BACKENDS:
if name == _ENV_BACKEND and shutil.which(argv[0]) is not None:
return (name, argv)
return None
order = list(BACKENDS)
if _winner is not None: order.sort(key=lambda backend: backend[0] != _winner)
for name, argv in order:
if shutil.which(argv[0]) is not None:
_winner = name
return (name, argv)
return None
def _terminate(proc):
try: proc.kill()
except Exception: pass
try: proc.wait()
except Exception: pass
def _stderr_tail(proc, limit=1024):
try:
data = proc.stderr.read(limit)
return data.decode("utf-8", "replace").strip()
except Exception: return ""
def _webp_info(data):
if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP": return None
fourcc = data[12:16]
if fourcc == b"VP8X":
width = int.from_bytes(data[24:27], "little") + 1
height = int.from_bytes(data[27:30], "little") + 1
elif fourcc == b"VP8 ":
width = int.from_bytes(data[26:28], "little") & 0x3FFF
height = int.from_bytes(data[28:30], "little") & 0x3FFF
elif fourcc == b"VP8L":
bits = int.from_bytes(data[21:25], "little")
width = (bits & 0x3FFF) + 1
height = ((bits >> 14) & 0x3FFF) + 1
else: return None
if width > 0 and height > 0: return (width, height)
return None
def _valid_webp(path):
try:
with open(path, "rb") as fh: return _webp_info(fh.read(30)) is not None
except Exception: return False
def _unlink_output(path):
try: os.unlink(path)
except Exception: pass
def _configured_backend(quality=None, max_dimension=None):
global _no_backend_logged
backend = _selected_backend()
if backend is None:
if not _no_backend_logged:
_no_backend_logged = True
RNS.log("No WebP encoding backend available for media conversion. You can Install ImageMagick or ffmpeg to enable image conversion.", RNS.LOG_WARNING)
return None
backend_name, encoder_argv = backend
_no_backend_logged = False
quality_arg = None
dimension_arg = None
if quality is not None:
try: quality_arg = max(1, min(100, int(quality)))
except (ValueError, TypeError): pass
if max_dimension is not None:
try: dimension_arg = int(max_dimension)
except (ValueError, TypeError): pass
if dimension_arg is not None and dimension_arg < 1: dimension_arg = None
encoder_argv = list(encoder_argv)
if backend_name in ("magick", "convert", "gm"):
options = []
if quality_arg is not None: options += ["-quality", str(quality_arg)]
if dimension_arg is not None: options += ["-resize", f"{dimension_arg}x{dimension_arg}>"]
encoder_argv = encoder_argv[:-1] + options + encoder_argv[-1:]
elif backend_name in ("ffmpeg", "avconv"):
options = []
if quality_arg is not None: options += ["-quality", str(quality_arg)]
if dimension_arg is not None: options += ["-vf", f"scale='min(iw,{dimension_arg})':'min(ih,{dimension_arg})':force_original_aspect_ratio=decrease"]
try: format_index = encoder_argv.index("-f")
except ValueError: format_index = len(encoder_argv)
encoder_argv = encoder_argv[:format_index] + options + encoder_argv[format_index:]
return backend_name, encoder_argv
def _await(backend_name, encoder_proc, input_proc=None, timeout=None):
if timeout is None: timeout = CONVERSION_TIMEOUT
deadline = time.time() + timeout
try:
encoder_proc.wait(timeout=max(0.0, deadline - time.time()))
if input_proc is not None: input_proc.wait(timeout=max(0.0, deadline - time.time()))
except subprocess.TimeoutExpired:
_terminate(input_proc)
_terminate(encoder_proc)
RNS.log(f"Media conversion via {backend_name} timed out after {timeout} seconds", RNS.LOG_WARNING)
return False
if encoder_proc.returncode != 0:
detail = ""
encoder_tail = _stderr_tail(encoder_proc)
input_tail = _stderr_tail(input_proc) if input_proc is not None else ""
if encoder_tail: detail += f" Encoder: {encoder_tail}"
if input_tail: detail += f" Input: {input_tail}"
RNS.log(f"Media conversion via {backend_name} failed.{detail}", RNS.LOG_WARNING)
return False
return True
def convert_to_webp(input_argv, output_path, cwd=None, timeout=None, quality=None, max_dimension=None):
configured = _configured_backend(quality=quality, max_dimension=max_dimension)
if configured is None: return False
backend_name, encoder_argv = configured
try:
with open(output_path, "wb") as output_fh:
input_proc = subprocess.Popen(input_argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
encoder_proc = subprocess.Popen(encoder_argv, stdin=input_proc.stdout, stdout=output_fh, stderr=subprocess.PIPE)
# The parent must not retain a copy of the input pipe's write
# end, or the input process would never see EOF.
input_proc.stdout.close()
if not _await(backend_name, encoder_proc, input_proc=input_proc, timeout=timeout): return False
if not _valid_webp(output_path):
RNS.log(f"Media conversion via {backend_name} produced invalid WebP output", RNS.LOG_WARNING)
return False
RNS.log(f"Media converted to WebP with {backend_name}", RNS.LOG_DEBUG)
return True
except Exception as e:
RNS.log(f"Error during media conversion: {e}", RNS.LOG_WARNING)
return False
def convert_file_to_webp(source_path, quality=85, max_dimension=None, timeout=None):
configured = _configured_backend(quality=quality, max_dimension=max_dimension)
if configured is None: return False
backend_name, encoder_argv = configured
tmp_path = None
success = False
try:
if not os.path.isfile(source_path):
RNS.log(f"Cannot convert media: source file does not exist: {source_path}", RNS.LOG_WARNING)
return False
fd, tmp_path = tempfile.mkstemp(prefix="rns_media_", suffix=".webp")
os.close(fd)
with open(source_path, "rb") as input_fh, open(tmp_path, "wb") as output_fh:
encoder_proc = subprocess.Popen(encoder_argv, stdin=input_fh, stdout=output_fh, stderr=subprocess.PIPE)
if not _await(backend_name, encoder_proc, timeout=timeout): return False
if not _valid_webp(tmp_path):
RNS.log(f"Invalid media conversion output from {backend_name}", RNS.LOG_WARNING)
return False
success = True
RNS.log(f"Media converted to WebP with {backend_name}", RNS.LOG_DEBUG)
return tmp_path
except Exception as e:
RNS.log(f"Error during media conversion: {e}", RNS.LOG_WARNING)
return False
finally:
if not success and tmp_path is not None: _unlink_output(tmp_path)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+154 -34
View File
@@ -31,6 +31,51 @@
import re
import RNS
# Validate ref names according to https://git-scm.com/docs/git-check-ref-format
# This may be a bit overkill, since git validates names as well, but why not.
def san_ref(ref):
if ref.startswith("-"): return None
if ref.startswith("/"): return None
if ref.endswith("/"): return None
if ref.endswith("."): return None
if " " in ref: return None
if not "/" in ref: return None
if ".." in ref: return None
if "/." in ref: return None
if "//" in ref: return None
if "\\" in ref: return None
for comp in ref.split("/"):
if comp.endswith(".lock"): return None
if not all(ord(c) >= 40 for c in ref): return None # Any control character
if "\x7f" in ref: return None # ASCII DEL (177)
if "~" in ref: return None
if "^" in ref: return None
if ":" in ref: return None
if "?" in ref: return None
if "*" in ref: return None
if "[" in ref: return None
if "@{" in ref: return None
if "@" == ref: return None
return ref
def san_refs(refs):
if not type(refs) == list: return None
for ref in refs:
if not san_ref(ref): return None
return refs
# Git SHA format validation
def san_sha(sha):
if len(sha) < 40: return None
try: bytes.fromhex(sha)
except: return None
return sha
class MarkdownToMicron:
BOLD = "`!"
BOLD_END = "`!"
@@ -82,10 +127,16 @@ class MarkdownToMicron:
TABLE_MIN_COL_WIDTH = 3
def __init__(self, max_width=100, syntax_highlighter=None):
def __init__(self, max_width=100, syntax_highlighter=None, url_scope=None):
self.max_width = max_width
self.local_url_scope = url_scope or ":/page/"
self.__local_url_scope = self.local_url_scope
self.syntax_highlighter = syntax_highlighter
self.wcwidth = None
self.bold_links = True
self.underline_links = True
self.link_color = None
try:
import wcwidth
@@ -93,6 +144,9 @@ class MarkdownToMicron:
except: RNS.log(f"The wcwidth module is unavailable, display width calculations for some glyphs will be incorrect", RNS.LOG_WARNING)
def set_url_scope(self, url_scope): self.local_url_scope = url_scope
def restore_url_scope(self, url_scope): self.local_url_scope = self.__local_url_scope
def display_width(self, text):
if not self.wcwidth: return len(text)
else:
@@ -101,7 +155,8 @@ class MarkdownToMicron:
w = self.wcwidth.wcswidth(text)
return w if w is not None and w >= 0 else len(text)
def format_block(self, text):
def format_block(self, text, url_scope=None):
# text = text.replace("\\", "\\\\") # Now handled in format_line instead
lines = text.split('\n')
result_lines = []
in_code_block = False
@@ -153,19 +208,21 @@ class MarkdownToMicron:
code_content = '\n'.join(code_buffer)
if self.syntax_highlighter and code_block_lang:
try:
highlighted = self.syntax_highlighter.highlight(code_content, language=code_block_lang)
result_lines.append(f"{self.CODE_BG}{self.CODE_FG}")
result_lines.append(highlighted)
result_lines.append(self.CODE_RESET)
if code_block_lang.lower() == "rawmu": result_lines.append(code_content)
else:
try:
highlighted = self.syntax_highlighter.highlight(code_content, language=code_block_lang)
result_lines.append(f"{self.CODE_BG}{self.CODE_FG}")
result_lines.append(highlighted)
result_lines.append(self.CODE_RESET)
except Exception:
# Fallback to plain literal block on any error
result_lines.append(f"{self.CODE_BG}{self.CODE_FG}")
result_lines.append(self.LITERAL_START)
result_lines.append(self._escape_literals(code_content))
result_lines.append(self.LITERAL_END)
result_lines.append(self.CODE_RESET)
except Exception:
# Fallback to plain literal block on any error
result_lines.append(f"{self.CODE_BG}{self.CODE_FG}")
result_lines.append(self.LITERAL_START)
result_lines.append(self._escape_literals(code_content))
result_lines.append(self.LITERAL_END)
result_lines.append(self.CODE_RESET)
else:
result_lines.append(f"{self.CODE_BG}{self.CODE_FG}")
result_lines.append(self.LITERAL_START)
@@ -177,7 +234,7 @@ class MarkdownToMicron:
for line in lines:
is_fence, lang_hint = self._detect_code_fence(line)
if is_fence:
# Flush any pending structures before code fence
flush_quote_buffer()
@@ -246,6 +303,11 @@ class MarkdownToMicron:
def format_line(self, line, mode="normal"):
if mode == "codeblock": return self._escape_literals(line)
line = line.replace("\\", "\\\\")
if line.startswith("-") and not line.startswith("---") and not line.startswith("- "): line = f"\\{line}"
if line.startswith("<"): line = f"\\{line}"
# if line.startswith(">"): line = f"\\{line}" # Now handled by blockquotes
if self.HORIZONTAL_RULE_RE.match(line): return self._format_horizontal_rule()
@@ -270,28 +332,38 @@ class MarkdownToMicron:
links.append((match.group(1), match.group(2)))
return f"\x00LINK{len(links)-1}\x00"
text = self.INLINE_CODE_RE.sub(extract_code, text)
text = self.LINK_RE.sub(extract_link, text)
text = self.INLINE_CODE_RE.sub(extract_code, text)
text = self.BOLD_RE.sub(self._bold_sub, text)
text = self.ITALIC_RE.sub(self._italic_sub, text)
def restore_link(match):
idx = int(match.group(1))
text, url = links[idx]
anchor_components = url.split("#")
url = anchor_components[0]
anchor = anchor_components[1] if len(anchor_components) > 1 else ""
if not ":/" in url:
url = f"{self.local_url_scope}{url}"
if anchor: url = f"{url}|anchor={anchor}"
undl = "`_" if self.underline_links else ""
bold = "`!" if self.bold_links else ""
text = text.replace('`', '')
return f"`!`[{text}`{url}]`!"
link = f"{undl}{bold}`[{text}`{url}]{bold}{undl}"
if self.link_color and len(self.link_color) == 3: link = f"`F{self.link_color}{link}`f"
if self.link_color and len(self.link_color) == 6: link = f"`FT{self.link_color}{link}`f"
return link
text = re.sub(r'\x00LINK(\d+)\x00', restore_link, text)
def restore_code(match):
idx = int(match.group(1))
content = code_blocks[idx]
# Disabled for now
# highlighted = self._highlight_inline_code(content)
# if highlighted: return highlighted
# Use plain inline code formatting
content = content.replace('`', '\\`')
return f"{self.CODE_BG_INLINE}{self.CODE_FG}{content}{self.CODE_RESET}"
@@ -614,19 +686,64 @@ class MarkdownToMicron:
return " " * left + text + " " * right
else:
return text + " " * padding
def _truncate_cell(self, text, width):
if self._visible_width(text) <= width: return text
stripped = text
stripped = re.sub(r'`[FB][0-9a-fA-F]{3}', '', stripped)
stripped = re.sub(r'`[!*_]', '', stripped)
stripped = re.sub(r'`f`b', '', stripped)
if len(stripped) <= width - 1: return text
truncated = stripped[:width - 1] + "…"
return truncated
truncation_point = len(text)
while truncation_point > 0 and self._visible_width(text[0:truncation_point]) >= width:
truncation_point -= 1
truncated = text[:truncation_point]
# Yes, this is convoluted, but if someone else has
# a better idea on how to handle unclosed micron
# tags in the truncated cells, I'm all ears.
active_tags = set()
fg_active = False
bg_active = False
i = 0
while i < len(truncated):
if truncated[i] == '`':
if i + 1 < len(truncated):
tag_char = truncated[i + 1]
if tag_char in '!*_=':
if tag_char in active_tags: active_tags.remove(tag_char)
else: active_tags.add(tag_char)
i += 2
continue
elif tag_char == 'f':
fg_active = False
i += 2
continue
elif tag_char == 'b':
bg_active = False
i += 2
continue
elif tag_char == 'F':
fg_active = True
if i + 2 < len(truncated) and truncated[i + 2] == 'T': i += 8
else: i += 5
continue
elif tag_char == 'B':
bg_active = True
if i + 2 < len(truncated) and truncated[i + 2] == 'T': i += 8
else: i += 5
continue
i += 1
closers = []
if fg_active: closers.append('`f')
if bg_active: closers.append('`b')
for fmt in active_tags: closers.append(f'`{fmt}')
return truncated + ''.join(closers) + "…"
def _wrap_text(self, text, width):
if not text: return [""]
@@ -697,3 +814,6 @@ class MarkdownToMicron:
def convert_markdown_to_micron(text):
converter = MarkdownToMicron()
return converter.format_block(text)
def medium_path_timeout(default_timeout):
return max(default_timeout, RNS.Reticulum.get_instance().get_medium_path_timeout())
+1021 -554
View File
File diff suppressed because it is too large. Load diff
+2 -9
View File
@@ -55,19 +55,12 @@ def main():
parser.add_argument("--config", action="store", default=None, help="path to alternative Reticulum config directory", type=str)
parser.add_argument('-v', '--verbose', action='count', default=0)
parser.add_argument('-q', '--quiet', action='count', default=0)
parser.add_argument("--exampleconfig", action='store_true', default=False, help="print verbose configuration example to stdout and exit")
parser.add_argument("--version", action="version", version="rnir {version}".format(version=__version__))
args = parser.parse_args()
if args.exampleconfig:
print(__example_rns_config__)
exit()
if args.config:
configarg = args.config
else:
configarg = None
if args.config: configarg = args.config
else: configarg = None
program_setup(configdir = configarg, verbosity=args.verbose, quietness=args.quiet)
+2 -2
View File
@@ -3766,8 +3766,8 @@ def main():
print("\nDevice configuration:")
if ec_bt == 0x73: print(f" Bluetooth : Enabled")
else: print(f" Bluetooth : Disabled")
if ec_wifi == 0x01: print(f" WiFi : Enabled (Station)")
if ec_wifi == 0x02: print(f" WiFi : Enabled (AP)")
if ec_wifi == 0x01: print(f" WiFi : Enabled (Station)")
elif ec_wifi == 0x02: print(f" WiFi : Enabled (AP)")
else: print(f" WiFi : Disabled")
if ec_wifi == 0x01 or ec_wifi == 0x02:
if not ec_wchn: print(f" Channel : Unknown")
+6 -5
View File
@@ -42,6 +42,7 @@ remote_link = None
output_rst_str = "\r \r"
def connect_remote(destination_hash, auth_identity, timeout, no_output = False, purpose="management"):
global remote_link, reticulum
timeout = max(timeout, reticulum.get_medium_path_timeout())
if not RNS.Transport.has_path(destination_hash):
if not no_output:
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested", end=" ")
@@ -59,7 +60,8 @@ def connect_remote(destination_hash, auth_identity, timeout, no_output = False,
remote_identity = RNS.Identity.recall(destination_hash)
def remote_link_closed(link):
if link.teardown_reason == RNS.Link.TIMEOUT:
if link.teardown_reason == RNS.Link.INITIATOR_CLOSED: return
elif link.teardown_reason == RNS.Link.TIMEOUT:
if not no_output:
print(output_rst_str, end="")
print("The link timed out, exiting now")
@@ -450,7 +452,7 @@ def program_setup(configdir, table, rates, drop, destination_hexhash, verbosity,
i = 0
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:
time.sleep(0.1)
print(("\b\b"+syms[i]+" "), end="")
@@ -536,9 +538,8 @@ def pretty_date(time=False):
if day_diff == 0:
if second_diff < 10: return str(second_diff) + " seconds"
if second_diff < 60: return str(second_diff) + " seconds"
if second_diff < 120: return "1 minute"
if second_diff < 3600: return str(int(second_diff / 60)) + " minutes"
if second_diff < 7200: return "an hour"
if second_diff < 70: return "1 minute"
if second_diff < 7200: return str(int(second_diff / 60)) + " minutes"
if second_diff < 86400: return str(int(second_diff / 3600)) + " hours"
if day_diff == 1: return "1 day"
if day_diff < 7: return str(day_diff) + " days"
+2 -2
View File
@@ -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=" ")
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
syms = "⢄⢂⢁⡁⡈⡐⡠"
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=" ")
_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
while receipt.status == RNS.PacketReceipt.SENT and not time.time() > _timeout:
time.sleep(0.1)
+55 -8
View File
@@ -100,7 +100,7 @@ __example_rns_config__ = '''# This is an example Reticulum config file.
# always-on. This directive is optional and can be removed
# for brevity.
enable_transport = No
enable_transport = no
# By default, the first program to launch the Reticulum
@@ -112,7 +112,7 @@ enable_transport = No
# user, and should generally be turned on. This directive
# is optional and can be removed for brevity.
share_instance = Yes
share_instance = yes
# If you want to run multiple *different* shared instances
@@ -173,12 +173,18 @@ instance_name = default
# 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
# available interfaces from other Transport Instances over
# the network. If this option is enabled, Reticulum will
# collect interface information discovered from the network.
# discover_interfaces = No
# discover_interfaces = no
# If you only want to discover interfaces from specific
@@ -215,7 +221,26 @@ instance_name = default
# an optional directive, and can be left out for brevity.
# This behaviour is disabled by 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
@@ -226,14 +251,15 @@ instance_name = default
# Transport Instance, and printed to the log at startup.
# Optional, and disabled by default.
# respond_to_probes = No
# respond_to_probes = no
# You can publish your local list of blackholed identities
# for other transport instances to use for automatic,
# network-wide blackhole management.
# publish_blackhole = No
# publish_blackhole = no
# List of remote transport identities from which to auto-
# matically source lists of blackholed identities.
@@ -249,8 +275,22 @@ instance_name = default
# blackhole_sources = 521c87a83afb8f29e4455e77930b973b
# You can set the interval in minutes at which remote
# blackhole sources are updated. Defaults to one hour.
# blackhole_update_interval = 60
# When not running as a transport node, it is possible to
# force the use of the same, static transport identity
# for every instance start. Defaults to using a new identity
# at every instance start, if transport is disabled.
# static_transport_identity = no
[logging]
# Valid log levels are 0 through 7:
# Valid log levels are 0 through 8:
# 0: Log only critical information
# 1: Log errors and lower log levels
# 2: Log warnings and lower log levels
@@ -258,10 +298,17 @@ instance_name = default
# 4: Log info and lower (this is the default)
# 5: Verbose logging
# 6: Debug logging
# 7: Extreme logging
# 7: Path logging
# 8: Extreme logging
loglevel = 4
# You can disable timestamp inclusion in logs. Useful if
# you want to use an external logging tool that provides
# its own timestamps or custom formatting.
# logtimestamps = no
# The interfaces section defines the physical and virtual
# interfaces Reticulum will use to communicate on. This
+8
View File
@@ -35,7 +35,15 @@
from ._version import __version__
import os
import glob
module_abs_filename = os.path.abspath(__file__)
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")
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
def _get_version(): return __version__
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.0"
__version__ = "0.3.0"
+2 -1
View File
@@ -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)
# 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("-v", "--verbose", action="count", default=0, help="increase verbosity")
parser.add_argument("-q", "--quiet", action="count", default=0, help="decrease verbosity")
-2
View File
@@ -53,8 +53,6 @@ class permit(AbstractContextManager):
"""
def __init__(self, *exceptions): self._exceptions = exceptions
def __enter__(self): pass
def __exit__(self, exctype, excinst, exctb):
return exctype is not None and not issubclass(exctype, self._exceptions)
-1
View File
@@ -55,5 +55,4 @@ class SleepRate:
return sleep_for if sleep_for > 0 else 0
async def sleep_async(self): await asyncio.sleep(self.next_sleep_time())
def sleep_block(self): time.sleep(self.next_sleep_time())
+33 -61
View File
@@ -35,7 +35,6 @@
from __future__ import annotations
import asyncio
import base64
import enum
import functools
import os
@@ -53,10 +52,8 @@ import RNS.Utilities.rnsh.exception as exception
import RNS.Utilities.rnsh.process as process
import RNS.Utilities.rnsh.retry as retry
import RNS.Utilities.rnsh.session as session
import re
import contextlib
import pwd
import bz2
import RNS.Utilities.rnsh.protocol as protocol
import RNS.Utilities.rnsh.helpers as helpers
@@ -71,7 +68,6 @@ _retry_timer: retry.RetryThread | None = None
_destination: RNS.Destination | None = None
_loop: asyncio.AbstractEventLoop | None = None
async def _check_finished(timeout: float = 0):
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="")
sys.stdout.flush()
i = (i+1)%len(syms)
print("\r"+" "*len(msg)+" \r", end="")
if timeout != None and time.time() > timeout: return False
else: return True
async def _spin_pipe(until: callable = None, msg=None, timeout: float | None = None) -> bool:
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:
try:
target = int(base_level) + int(verbosity) - int(quietness)
if target < RNS.LOG_CRITICAL: target = RNS.LOG_CRITICAL
if target > RNS.LOG_DEBUG: target = RNS.LOG_DEBUG
if target < RNS.LOG_NONE: target = RNS.LOG_NONE
if target > RNS.LOG_EXTREME: target = RNS.LOG_EXTREME
return target
except Exception: return base_level
class RemoteExecutionError(Exception):
def __init__(self, msg): self.msg = msg
async def _initiate_link(configdir, rnsconfigdir, identitypath=None, verbosity=0, quietness=0, noid=False, destination=None,
async def _initiate_link(configdir, rnsconfigdir, identitypath=None, logfile=None, verbosity=0, quietness=0, noid=False, destination=None,
timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
global _identity, _reticulum, _link, _destination, _remote_exec_grace
@@ -153,34 +144,28 @@ async def _initiate_link(configdir, rnsconfigdir, identitypath=None, verbosity=0
raise RemoteExecutionError(
"Allowed destination length is invalid, must be {hex} hexadecimal characters ({byte} bytes).".format(
hex=dest_len, byte=dest_len // 2))
try:
destination_hash = bytes.fromhex(destination)
except Exception as e:
raise RemoteExecutionError("Invalid destination entered. Check your input.")
try: destination_hash = bytes.fromhex(destination)
except Exception as e: raise RemoteExecutionError("Invalid destination entered. Check your input.")
if _reticulum is None:
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_ERROR)
RNS.logfile = os.path.join(configdir, "logfile")
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_INFO)
RNS.logfile = logfile
_reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel, logdest=RNS.LOG_FILE)
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):
RNS.Transport.request_path(destination_hash)
RNS.log(f"Requesting path...", RNS.LOG_INFO)
if not await _spin(until=lambda: RNS.Transport.has_path(destination_hash), msg="Requesting path...",
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=f"Requesting path to {RNS.prettyhexrep(destination_hash)}",
timeout=timeout, quiet=quietness > 0):
raise RemoteExecutionError("Path not found")
if _destination is None:
listener_identity = RNS.Identity.recall(destination_hash)
_destination = RNS.Destination(
listener_identity,
RNS.Destination.OUT,
RNS.Destination.SINGLE,
rnsh.APP_NAME
)
_destination = RNS.Destination(listener_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, rnsh.APP_NAME)
if _link is None or _link.status == RNS.Link.PENDING:
RNS.log("No link", RNS.LOG_DEBUG)
@@ -189,31 +174,30 @@ async def _initiate_link(configdir, rnsconfigdir, identitypath=None, verbosity=0
_link.set_link_closed_callback(_client_link_closed)
RNS.log(f"Establishing link...", RNS.LOG_VERBOSE)
if not await _spin(until=lambda: _link.status == RNS.Link.ACTIVE, msg="Establishing link...",
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=f"Establishing link with {RNS.prettyhexrep(destination_hash)}",
timeout=timeout, quiet=quietness > 0):
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:
# Delay a tiny bit to allow listener to fully enter WAIT_IDENT state
await asyncio.sleep(min(1, _link.rtt * 1.1 + 0.05))
_link.identify(_identity)
_link.did_identify = True
async def _handle_error(errmsg: RNS.MessageBase):
if isinstance(errmsg, protocol.ErrorMessage):
with contextlib.suppress(Exception):
if _link and _link.status == RNS.Link.ACTIVE:
_link.teardown()
if _link and _link.status == RNS.Link.ACTIVE: _link.teardown()
await asyncio.sleep(0.1)
raise RemoteExecutionError(f"Remote error: {errmsg.msg}")
async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosity: int, quietness: int, noid: bool, destination: str,
async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, logfile:str, verbosity: int, quietness: int, noid: bool, destination: str,
timeout: float, command: [str] | None = None):
global _finished, _link
if timeout is None: timeout = RNS.Transport.PATH_REQUEST_TIMEOUT
with process.TTYRestorer(sys.stdin.fileno()) as ttyRestorer:
loop = asyncio.get_running_loop()
state = InitiatorState.IS_INITIAL
@@ -223,33 +207,26 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
await _initiate_link(configdir=configdir,
rnsconfigdir=rnsconfigdir,
identitypath=identitypath,
logfile=logfile,
verbosity=verbosity,
quietness=quietness,
noid=noid,
destination=destination,
timeout=timeout)
if not _link or _link.status not in [RNS.Link.ACTIVE, RNS.Link.PENDING]:
return 255
if not _link or _link.status not in [RNS.Link.ACTIVE, RNS.Link.PENDING]: return 255
state = InitiatorState.IS_LINKED
outlet = session.RNSOutlet(_link)
channel = _link.get_channel()
protocol.register_message_types(channel)
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())
try:
vm = _pq.get(timeout=max(outlet.rtt * 20, 5))
await _handle_error(vm)
if not isinstance(vm, protocol.VersionInfoMessage):
raise Exception("Invalid message received")
RNS.log(f"Server version info: sw {vm.sw_version} prot {vm.protocol_version}", RNS.LOG_DEBUG)
if not isinstance(vm, protocol.VersionInfoMessage): raise Exception("Invalid message received")
RNS.log(f"Connected server version info: sw {vm.sw_version}, proto {vm.protocol_version}", RNS.LOG_INFO)
state = InitiatorState.IS_RUNNING
except queue.Empty:
print("Protocol error")
@@ -281,10 +258,8 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
return None
elif b == "L":
line_mode = not line_mode
if line_mode:
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"))
if line_mode: 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"))
return None
return b
@@ -327,8 +302,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
pre_esc = False
data.append(b)
if not line_mode:
data_buffer.extend(data)
if not line_mode: data_buffer.extend(data)
else:
line_buffer.extend(data)
if line_flush:
@@ -342,8 +316,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
blind_write_count += len(data)
except EOFError:
if os.isatty(0):
data_buffer.extend(process.CTRL_D)
if os.isatty(0): data_buffer.extend(process.CTRL_D)
stdin_eof = True
process.tty_unset_reader_callbacks(sys.stdin.fileno())
@@ -396,7 +369,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
if message.stream_id == protocol.StreamDataMessage.STREAM_ID_STDOUT:
if message.data and len(message.data) > 0:
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)
sys.stdout.flush()
if message.eof:
@@ -404,7 +377,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
if message.stream_id == protocol.StreamDataMessage.STREAM_ID_STDERR:
if message.data and len(message.data) > 0:
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)
sys.stderr.flush()
if message.eof:
@@ -418,8 +391,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
_link.teardown()
return 200
except queue.Empty:
processed = False
except queue.Empty: processed = False
if channel.is_ready_to_send():
def compress_adaptive(buf: bytes):
@@ -433,7 +405,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
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:
chunk_segment_length = int(chunk_len/comp_try)
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
@@ -441,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:
comp_success = True
break
else:
comp_try += 1
else: comp_try += 1
if comp_success:
diff = max_data_len - len(compressed_chunk)
@@ -471,6 +442,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, verbosit
r, c, h, v = process.tty_get_winsize(0)
channel.send(protocol.WindowSizeMessage(r, c, h, v))
processed = True
except RemoteExecutionError as e:
print(e.msg)
return 255
+16 -11
View File
@@ -50,7 +50,6 @@ import RNS.Utilities.rnsh.exception as exception
import RNS.Utilities.rnsh.process as process
import RNS.Utilities.rnsh.retry as retry
import RNS.Utilities.rnsh.session as session
import re
import contextlib
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:
try:
target = int(base_level) + int(verbosity) - int(quietness)
if target < RNS.LOG_CRITICAL: target = RNS.LOG_CRITICAL
if target > RNS.LOG_DEBUG: target = RNS.LOG_DEBUG
if target < RNS.LOG_NONE: target = RNS.LOG_NONE
if target > RNS.LOG_EXTREME: target = RNS.LOG_EXTREME
return target
except Exception: return base_level
async def listen(configdir, rnsconfigdir, command, identitypath=None, service_name=None, verbosity=0, quietness=0, allowed=None,
allowed_file=None, disable_auth=None, announce_period=900, no_remote_command=True, remote_cmd_as_args=False,
async def listen(configdir, rnsconfigdir, command, identitypath=None, logfile=None, service_name=None, verbosity=0, quietness=0,
allowed=None, allowed_file=None, disable_auth=None, announce_period=900, no_remote_command=True, remote_cmd_as_args=False,
loop: asyncio.AbstractEventLoop = None):
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
if not loop: loop = asyncio.get_running_loop()
if service_name is None or len(service_name) == 0:
service_name = "default"
if service_name is None or len(service_name) == 0: service_name = "default"
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
targetloglevel = compute_target_rns_loglevel(verbosity, quietness, RNS.LOG_INFO)
_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)
RNS.log(f"rnsh listening for commands on {RNS.prettyhexrep(_destination.hash)}", RNS.LOG_NOTICE)
RNS.logdest = logdest
_cmd = command
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
session.ListenerSession.allow_remote_command = not no_remote_command
_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) \
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>.")
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):
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.remote_cmd_as_args = _remote_cmd_as_args
-16
View File
@@ -488,8 +488,6 @@ class CallbackSubprocess:
self._stdin_is_pipe = stdin_is_pipe
self._stdout_is_pipe = stdout_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):
stdin = self._child_stdin
@@ -624,14 +622,6 @@ class CallbackSubprocess:
"""
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()
for key in self._env:
env[key] = self._env[key]
@@ -639,12 +629,6 @@ class CallbackSubprocess:
program = self._command[0]
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._child_stdin, \
self._child_stdout, \
+5 -10
View File
@@ -32,6 +32,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import RNS
import asyncio
import threading
import time
@@ -88,8 +89,7 @@ class RetryThread(AbstractContextManager):
self._thread = threading.Thread(name=name, target=self._thread_run, daemon=True)
self._thread.start()
def is_alive(self):
return self._thread.is_alive()
def is_alive(self): return self._thread.is_alive()
def close(self, loop: asyncio.AbstractEventLoop = None) -> asyncio.Future:
RNS.log("Stopping timer thread", RNS.LOG_DEBUG)
@@ -102,17 +102,12 @@ class RetryThread(AbstractContextManager):
return self._finished
def wait(self, timeout: float = None):
if timeout:
timeout = timeout + time.time()
if timeout: timeout = timeout + time.time()
while timeout is None or time.time() < timeout:
with self._lock:
task_count = len(self._statuses)
if task_count == 0:
return
with self._lock: task_count = len(self._statuses)
if task_count == 0: return
time.sleep(0.1)
def _thread_run(self):
while self._run and self._finished is None:
time.sleep(self._loop_period)
+41 -26
View File
@@ -37,7 +37,6 @@
from __future__ import annotations
import asyncio
import base64
import re
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 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 "")
if identity_path is None:
identity_path = RNS.Reticulum.identitypath + "/" + APP_NAME + \
(f".{service_name}" if service_name and len(service_name) > 0 else "")
if not identity_path:
identity_path = f"{configdir}/identity" + (f".{service_name}" if service_name and len(service_name) > 0 else "")
identity = None
if os.path.isfile(identity_path):
RNS.log(f"Loading identity from {identity_path}", RNS.LOG_VERBOSE)
identity = RNS.Identity.from_file(identity_path)
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.to_file(identity_path)
return identity
def print_identity(configdir, identitypath, service_name, include_destination: bool):
reticulum = RNS.Reticulum(configdir=configdir, loglevel=RNS.LOG_INFO)
if service_name and len(service_name) > 0:
print(f"Using service name \"{service_name}\"")
identity = prepare_identity(identitypath, service_name)
def print_identity(configdir, rnsconfigdir, identitypath, service_name, include_destination: bool):
reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=RNS.LOG_INFO)
if service_name and len(service_name) > 0: print(f"Using service name \"{service_name}\"")
identity = prepare_identity(identity_path=identitypath, service_name=service_name, configdir=configdir)
destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME)
print("Identity : " + str(identity))
if include_destination:
print("Listening on : " + RNS.prettyhexrep(destination.hash))
if include_destination: print("Listening on : " + RNS.prettyhexrep(destination.hash))
exit(0)
verbose_set = False
def ensure_config_directory():
if 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")
def ensure_config_directory(configdir=None):
if configdir:
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:
try:
RNS.log(f"Creating configuration directory: {os.path.expanduser('~/.rnsh')}")
os.makedirs(os.path.expanduser("~/.rnsh"))
return os.path.expanduser("~/.rnsh")
@@ -105,26 +115,30 @@ def ensure_config_directory():
async def _rnsh_cli_main():
global verbose_set
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:
print_identity(args.config, args.identity, args.service, args.listen)
print_identity(configdir, args.rnsconfig, args.identity, args.service, args.listen)
return 0
logfile = f"{configdir}/logfile"
if args.listen:
allowed_file = None
dest_len = (RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2
if os.path.isfile(os.path.expanduser("~/.config/rnsh/allowed_identities")):
allowed_file = os.path.expanduser("~/.config/rnsh/allowed_identities")
elif os.path.isfile(os.path.expanduser("~/.rnsh/allowed_identities")):
allowed_file = os.path.expanduser("~/.rnsh/allowed_identities")
if os.path.isfile(os.path.expanduser(f"{configdir}/allowed_identities")):
allowed_file = os.path.expanduser(f"{configdir}/allowed_identities")
await listener.listen(configdir=configdir,
rnsconfigdir=args.config,
rnsconfigdir=args.rnsconfig,
command=args.command,
identitypath=args.identity,
logfile=logfile,
service_name=args.service,
verbosity=args.verbose,
quietness=args.quiet,
@@ -138,8 +152,9 @@ async def _rnsh_cli_main():
if args.destination is not None:
return_code = await initiator.initiate(configdir=configdir,
rnsconfigdir=args.config,
rnsconfigdir=args.rnsconfig,
identitypath=args.identity,
logfile=f"{logfile}.initiator",
verbosity=args.verbose,
quietness=args.quiet,
noid=args.no_id,
@@ -147,6 +162,7 @@ async def _rnsh_cli_main():
timeout=args.timeout,
command=args.command
)
RNS.log(f"Sesssion with <{args.destination}> ended", RNS.LOG_INFO)
return return_code if args.mirror else 0
else:
print("")
@@ -170,5 +186,4 @@ def main():
if verbose_set and exc: raise exc
sys.exit(return_code if return_code is not None else 255)
if __name__ == "__main__": main()
+79 -75
View File
@@ -43,7 +43,6 @@ import RNS.Utilities.rnsh.protocol as protocol
import enum
from typing import TypeVar, Generic, Callable, List
from abc import abstractmethod, ABC
from multiprocessing import Manager
import os
import bz2
import RNS
@@ -103,6 +102,8 @@ class ListenerSession:
self.outlet.set_link_closed_callback(self._link_closed)
self.loop = loop
self.state: LSState = None
self.terminated = False
self.authenticated = False
self.remote_identity = None
self.term: str | None = None
self.stdin_is_pipe: bool = False
@@ -122,8 +123,10 @@ class ListenerSession:
self.return_code_sent = False
self.process: process.CallbackSubprocess | None = None
if self.allow_all: self._set_state(LSState.LSSTATE_WAIT_VERS)
else: self._set_state(LSState.LSSTATE_WAIT_IDENT)
if not self.allow_all: self._set_state(LSState.LSSTATE_WAIT_IDENT)
else:
self._set_state(LSState.LSSTATE_WAIT_VERS)
self.authenticated = True
self.sessions.append(self)
protocol.register_message_types(self.channel)
@@ -143,37 +146,31 @@ class ListenerSession:
def _call(self, func: callable, delay: float = 0):
def call_inner():
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)
def send(self, message: RNS.MessageBase):
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 send(self, message: RNS.MessageBase): 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 terminate(self, error: str = None):
self.terminated = True
self.state = LSState.LSSTATE_ERROR
with contextlib.suppress(Exception):
RNS.log("Terminating session" + (f": {error}" if error else ""), RNS.LOG_DEBUG)
if error and self.state != LSState.LSSTATE_TEARDOWN:
with contextlib.suppress(Exception):
self.send(protocol.ErrorMessage(error, True))
self.state = LSState.LSSTATE_ERROR
self._terminate_process()
self._call(self._prune, max(self.outlet.rtt * 3, process.CallbackSubprocess.PROCESS_PIPE_TIME+5))
def _prune(self):
self.state = LSState.LSSTATE_TEARDOWN
RNS.log("Pruning session", RNS.LOG_DEBUG)
with contextlib.suppress(ValueError):
self.sessions.remove(self)
with contextlib.suppress(Exception):
self.outlet.teardown()
with contextlib.suppress(ValueError): self.sessions.remove(self)
with contextlib.suppress(Exception): self.outlet.teardown()
def _check_protocol_timeout(self, fail_condition: Callable[[], bool], name: str):
timeout = True
@@ -183,7 +180,6 @@ class ListenerSession:
def _link_closed(self, outlet: LSOutletBase):
outlet.unset_link_closed_callback()
if outlet != self.outlet:
RNS.log("Link closed received from incorrect outlet", RNS.LOG_DEBUG)
return
@@ -196,15 +192,21 @@ class ListenerSession:
RNS.log("Identity received from incorrect outlet", RNS.LOG_DEBUG)
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]:
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:
self.terminate("Identity is not allowed.")
if self.allow_all or identity.hash in self.allowed_identity_hashes or identity.hash in self.allowed_file_identity_hashes:
RNS.log(f"Identity {identity} authenticated")
self.authenticated = True
self.remote_identity = identity
self._set_state(LSState.LSSTATE_WAIT_VERS)
self.remote_identity = identity
self._set_state(LSState.LSSTATE_WAIT_VERS)
else:
self.authenticated = False
self.terminate("Identity not allowed")
RNS.log(f"Identity {identity} not allowed")
@classmethod
async def pump_all(cls) -> True:
@@ -233,7 +235,7 @@ class ListenerSession:
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:
chunk_segment_length = int(chunk_len/comp_try)
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:
comp_success = True
break
else:
comp_try += 1
else: comp_try += 1
if comp_success:
diff = max_data_len - len(compressed_chunk)
@@ -255,10 +256,8 @@ class ListenerSession:
return comp_success, processed_length, chunk
try:
if self.state != LSState.LSSTATE_RUNNING:
return False
elif not self.channel.is_ready_to_send():
return False
if self.state != LSState.LSSTATE_RUNNING: return False
elif not self.channel.is_ready_to_send(): return False
elif len(self.stderr_buf) > 0:
comp_success, processed_length, data = compress_adaptive(self.stderr_buf)
self.stderr_buf = self.stderr_buf[processed_length:]
@@ -267,8 +266,7 @@ class ListenerSession:
msg = protocol.StreamDataMessage(protocol.StreamDataMessage.STREAM_ID_STDERR,
data, send_eof, comp_success)
self.send(msg)
if send_eof:
self.stderr_eof_sent = True
if send_eof: self.stderr_eof_sent = True
return True
elif len(self.stdout_buf) > 0:
comp_success, processed_length, data = compress_adaptive(self.stdout_buf)
@@ -278,8 +276,7 @@ class ListenerSession:
msg = protocol.StreamDataMessage(protocol.StreamDataMessage.STREAM_ID_STDOUT,
data, send_eof, comp_success)
self.send(msg)
if send_eof:
self.stdout_eof_sent = True
if send_eof: self.stdout_eof_sent = True
return True
elif self.return_code is not None and not self.return_code_sent:
msg = protocol.CommandExitedMessage(self.return_code)
@@ -295,22 +292,33 @@ class ListenerSession:
def _terminate_process(self):
with contextlib.suppress(Exception):
if self.process and self.process.running:
self.process.terminate()
if self.process and self.process.running: self.process.terminate()
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):
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:
self.terminate("Remote command line not allowed by listener")
return
if self.remote_cmd_as_args and cmdline and len(cmdline) > 0:
self.cmdline.extend(cmdline)
elif cmdline and len(cmdline) > 0:
self.cmdline = cmdline
if self.remote_cmd_as_args and cmdline and len(cmdline) > 0: self.cmdline.extend(cmdline)
elif cmdline and len(cmdline) > 0: self.cmdline = cmdline
self.stdin_is_pipe = pipe_stdin
self.stdout_is_pipe = pipe_stdout
@@ -318,13 +326,11 @@ class ListenerSession:
self.tcflags = tcflags
self.term = term
def stdout(data: bytes):
self.stdout_buf.extend(data)
def stderr(data: bytes):
self.stderr_buf.extend(data)
def stdout(data: bytes): self.stdout_buf.extend(data)
def stderr(data: bytes): self.stderr_buf.extend(data)
try:
RNS.log(f"Remote {self.remote_identity} executing: {self.cmdline}", RNS.LOG_VERBOSE)
self.process = process.CallbackSubprocess(argv=self.cmdline,
env={"TERM": self.term or os.environ.get("TERM") or "xterm",
"RNS_REMOTE_IDENTITY": (RNS.prettyhexrep(self.remote_identity.hash)
@@ -347,22 +353,28 @@ class ListenerSession:
self.cols = cols
self.hpix = hpix
self.vpix = vpix
with contextlib.suppress(Exception):
self.process.set_winsize(rows, cols, hpix, vpix)
with contextlib.suppress(Exception): self.process.set_winsize(rows, cols, hpix, vpix)
def _received_stdin(self, data: bytes, eof: bool):
if data and len(data) > 0:
self.process.write(data)
if eof:
self.process.close_stdin()
if data and len(data) > 0: self.process.write(data)
if eof: self.process.close_stdin()
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:
# Ignore any messages until the initiator has identified to avoid race conditions
# between identity announcement and early protocol messages.
RNS.log("Ignoring message while waiting for identification", RNS.LOG_DEBUG)
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):
self._protocol_error(self.state.name)
return
@@ -374,6 +386,9 @@ class ListenerSession:
self._set_state(LSState.LSSTATE_WAIT_CMD)
return
elif self.state == LSState.LSSTATE_WAIT_CMD:
if not self.authenticated:
self.terminate("Invalid state")
return
if not isinstance(message, protocol.ExecuteCommandMesssage):
return self._protocol_error(self.state.name)
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)
return
elif self.state == LSState.LSSTATE_RUNNING:
if not self.authenticated:
self.terminate("Invalid state")
return
if isinstance(message, protocol.WindowSizeMessage):
self._set_window_size(message.rows, message.cols, message.hpix, message.vpix)
elif isinstance(message, protocol.StreamDataMessage):
@@ -394,9 +412,6 @@ class ListenerSession:
# echo noop only on listener--used for keepalive/connectivity check
self.send(message)
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:
self._protocol_error("unexpected message")
return
@@ -405,29 +420,20 @@ class ListenerSession:
class RNSOutlet(LSOutletBase):
def set_initiator_identified_callback(self, cb: Callable[[LSOutletBase, _TIdentity], None]):
def inner_cb(link, identity: _TIdentity):
cb(self, identity)
def inner_cb(link, identity: _TIdentity): cb(self, identity)
self.link.set_remote_identified_callback(inner_cb)
def set_link_closed_callback(self, cb: Callable[[LSOutletBase], None]):
def inner_cb(link):
cb(self)
def inner_cb(link): cb(self)
self.link.set_link_closed_callback(inner_cb)
def unset_link_closed_callback(self):
self.link.set_link_closed_callback(None)
def teardown(self):
self.link.teardown()
def unset_link_closed_callback(self): self.link.set_link_closed_callback(None)
def teardown(self): self.link.teardown()
@property
def rtt(self) -> float:
return self.link.rtt
def rtt(self) -> float: return self.link.rtt
def __str__(self):
return f"Outlet RNS Link {self.link}"
def __str__(self): return f"Outlet on {self.link}"
def __init__(self, link: RNS.Link):
self.link = link
@@ -435,7 +441,5 @@ class RNSOutlet(LSOutletBase):
@staticmethod
def get_outlet(link: RNS.Link):
if hasattr(link, "lsoutlet"):
return link.lsoutlet
if hasattr(link, "lsoutlet"): return link.lsoutlet
return RNSOutlet(link)
+322 -84
View File
@@ -60,9 +60,13 @@ def size_str(num, suffix='B'):
request_result = None
request_concluded = False
def get_remote_status(destination_hash, include_lstats, identity, no_output=False, timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
global request_result, request_concluded
first_remote_req = True
remote_destination = None
remote_link = None
def get_remote_status(destination_hash, include_lstats, include_profiling, identity, no_output=False, timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
global request_result, request_concluded, first_remote_req, remote_destination, remote_link
link_count = None
profiling_results = None
if not RNS.Transport.has_path(destination_hash):
if not no_output:
@@ -81,7 +85,8 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
remote_identity = RNS.Identity.recall(destination_hash)
def remote_link_closed(link):
if link.teardown_reason == RNS.Link.TIMEOUT:
if link.teardown_reason == RNS.Link.INITIATOR_CLOSED: return
elif link.teardown_reason == RNS.Link.TIMEOUT:
if not no_output:
print("\r \r", end="")
print("The link timed out, exiting now")
@@ -107,44 +112,54 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
response = request_receipt.response
if isinstance(response, list):
status = response[0]
if len(response) > 1:
link_count = response[1]
else:
link_count = None
if len(response) > 1: link_count = response[1]
else: link_count = None
request_result = (status, link_count)
if len(response) > 2: profiling_results = response[2]
else: profiling_results = None
request_result = (status, link_count, profiling_results)
request_concluded = True
def remote_link_established(link):
if not no_output:
global first_remote_req
if not no_output and first_remote_req:
print("\r \r", end="")
print("Sending request...", end=" ")
sys.stdout.flush()
link.identify(identity)
link.request("/status", data = [include_lstats], response_callback = got_response, failed_callback = request_failed)
link.request("/status", data = [include_lstats, include_profiling], response_callback = got_response, failed_callback = request_failed)
first_remote_req = False
if not no_output:
if not remote_link and not no_output:
print("\r \r", end="")
print("Establishing link with remote transport instance...", end=" ")
sys.stdout.flush()
remote_destination = RNS.Destination(remote_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "rnstransport", "remote", "management")
link = RNS.Link(remote_destination)
link.set_link_established_callback(remote_link_established)
link.set_link_closed_callback(remote_link_closed)
if not remote_destination:
remote_destination = RNS.Destination(remote_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "rnstransport", "remote", "management")
if remote_link and remote_link.status == RNS.Link.ACTIVE:
request_concluded = False
remote_link.request("/status", data = [include_lstats], response_callback = got_response, failed_callback = request_failed)
while not request_concluded:
time.sleep(0.1)
else:
remote_link = RNS.Link(remote_destination)
remote_link.set_link_established_callback(remote_link_established)
remote_link.set_link_closed_callback(remote_link_closed)
while not request_concluded: time.sleep(0.1)
if request_result != None:
print("\r \r", end="")
return request_result
def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=False, astats=False, lstats=False, sorting=None, sort_reverse=False,
remote=None, management_identity=None, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT, must_exit=True, rns_instance=None,
traffic_totals=False, discovered_interfaces=False, config_entries=False):
def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=False, astats=False, pstats=False, lstats=False,
sorting=None, sort_reverse=False, remote=None, management_identity=None, must_exit=True, rns_instance=None,
traffic_totals=False, discovered_interfaces=False, config_entries=False, burst_filter=False, blocked_ips=False,
queue_stats=False, pps=False, profiling=False, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
if remote: require_shared = False
else: require_shared = True
@@ -162,7 +177,9 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
else: return
link_count = None
active_link_count = None
stats = None
profiling_results = None
details = False
if config_entries:
@@ -215,15 +232,18 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
location = f"{lat}, {lon}{height}"
else: location = "Unknown"
lxmf_addr = 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 and "network_id" in i and i["transport_id"] != 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 transport_id: print(f"Transport ID : {transport_id}")
if lxmf_addr: print(f"LXMF address : {lxmf_addr}")
print(f"Name : {name}")
print(f"Type : {if_type}")
@@ -248,8 +268,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
config_lines = i["config_entry"].split('\n')
for line in config_lines: print(f" {line}")
except Exception as e:
pass
except Exception as e: pass
else:
print(f"{'Name':<25} {'Type':<12} {'Status':<12} {'Last Heard':<12} {'Value':<8} {'Location':<15}")
@@ -300,28 +319,22 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
if remote:
try:
if management_identity is None:
raise ValueError("Remote management requires an identity file. Use -i to specify the path to a management identity.")
if management_identity is None: raise ValueError("Remote management requires an identity file. Use -i to specify the path to a management identity.")
dest_len = (RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2
if len(remote) != dest_len:
raise ValueError("Destination length is invalid, must be {hex} hexadecimal characters ({byte} bytes).".format(hex=dest_len, byte=dest_len//2))
if len(remote) != dest_len: raise ValueError("Destination length is invalid, must be {hex} hexadecimal characters ({byte} bytes).".format(hex=dest_len, byte=dest_len//2))
try:
identity_hash = bytes.fromhex(remote)
destination_hash = RNS.Destination.hash_from_name_and_identity("rnstransport.remote.management", identity_hash)
except Exception as e:
raise ValueError("Invalid destination entered. Check your input.")
except Exception as e: raise ValueError("Invalid destination entered. Check your input.")
identity = RNS.Identity.from_file(os.path.expanduser(management_identity))
if identity == None:
raise ValueError("Could not load management identity from "+str(management_identity))
if identity == None: raise ValueError("Could not load management identity from "+str(management_identity))
try:
remote_status = get_remote_status(destination_hash, lstats, identity, no_output=json, timeout=remote_timeout)
if remote_status != None:
stats, link_count = remote_status
except Exception as e:
raise e
remote_status = get_remote_status(destination_hash, lstats, profiling, identity, no_output=json, timeout=remote_timeout)
if remote_status != None: stats, link_count, profiling_results = remote_status
except Exception as e: raise e
except Exception as e:
print(str(e))
@@ -332,6 +345,12 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
if lstats:
try: link_count = reticulum.get_link_count()
except Exception as e: pass
try: active_link_count = reticulum.get_active_link_count()
except Exception as e: pass
if profiling:
try: profiling_results = reticulum.get_profiling_results()
except Exception as e: pass
try: stats = reticulum.get_interface_stats()
except Exception as e: pass
@@ -357,28 +376,31 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
interfaces = stats["interfaces"]
if sorting != None and isinstance(sorting, str):
sorting = sorting.lower()
if sorting == "rate" or sorting == "bitrate":
interfaces.sort(key=lambda i: i["bitrate"], reverse=not sort_reverse)
if sorting == "rx":
interfaces.sort(key=lambda i: i["rxb"], reverse=not sort_reverse)
if sorting == "tx":
interfaces.sort(key=lambda i: i["txb"], reverse=not sort_reverse)
if sorting == "rxs":
interfaces.sort(key=lambda i: i["rxs"], reverse=not sort_reverse)
if sorting == "txs":
interfaces.sort(key=lambda i: i["txs"], reverse=not sort_reverse)
if sorting == "traffic":
interfaces.sort(key=lambda i: i["rxb"]+i["txb"], reverse=not sort_reverse)
if sorting == "announces" or sorting == "announce":
interfaces.sort(key=lambda i: i["incoming_announce_frequency"]+i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "arx":
interfaces.sort(key=lambda i: i["incoming_announce_frequency"], reverse=not sort_reverse)
if sorting == "atx":
interfaces.sort(key=lambda i: i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "held":
interfaces.sort(key=lambda i: i["held_announces"], reverse=not sort_reverse)
if sorting == "rate" or sorting == "bitrate": interfaces.sort(key=lambda i: i["bitrate"], reverse=not sort_reverse)
if sorting == "rx": interfaces.sort(key=lambda i: i["rxb"], reverse=not sort_reverse)
if sorting == "tx": interfaces.sort(key=lambda i: i["txb"], reverse=not sort_reverse)
if sorting == "rxs": interfaces.sort(key=lambda i: i["rxs"], reverse=not sort_reverse)
if sorting == "txs": interfaces.sort(key=lambda i: i["txs"], reverse=not sort_reverse)
if sorting == "traffic": interfaces.sort(key=lambda i: i["rxb"]+i["txb"], reverse=not sort_reverse)
if sorting == "anns" or sorting == "announces": interfaces.sort(key=lambda i: i["incoming_announce_frequency"]+i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "arx": interfaces.sort(key=lambda i: i["incoming_announce_frequency"], reverse=not sort_reverse)
if sorting == "atx": 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": interfaces.sort(key=lambda i: i["incoming_pr_frequency"], reverse=not sort_reverse)
if sorting == "ptx": 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": 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)
if sorting == "txdrp": interfaces.sort(key=lambda i: i["txdrp"], reverse=not sort_reverse)
if sorting == "txdrb": interfaces.sort(key=lambda i: i["txdrb"], reverse=not sort_reverse)
if sorting == "txbuf": interfaces.sort(key=lambda i: i["txbuffered"], reverse=not sort_reverse)
for ifstat in interfaces:
name = ifstat["name"]
@@ -393,19 +415,33 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
):
if not (name.startswith("I2PInterface[") and ("i2p_connectable" in ifstat and ifstat["i2p_connectable"] == False)):
if name_filter == None or name_filter.lower() in name.lower():
if name_filter == None and burst_filter == None: show_if = True
elif not burst_filter:
if not name_filter or name_filter.lower() in name.lower(): show_if = True
else: show_if = False
elif burst_filter:
burst_act = True if ("burst_active" in ifstat and "pr_burst_active" in ifstat) and (ifstat["burst_active"] or ifstat["pr_burst_active"]) else False
nfilt = name_filter.lower() in name.lower() if name_filter else False
if burst_act or nfilt: show_if = True
else: show_if = False
else: show_if = True
if show_if:
print("")
if ifstat["status"]: ss = "Up"
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"
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_BOUNDARY: modestr = "Boundary"
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_GATEWAY: modestr = "Gateway"
elif ifstat["mode"] == RNS.Interfaces.Interface.Interface.MODE_INTERNAL: modestr = "Internal"
else: modestr = "Full"
if "announces_to_internal" in ifstat and ifstat["announces_to_internal"]: modestr += " (a>i)"
if ifstat["clients"] != None:
clients = ifstat["clients"]
@@ -430,6 +466,12 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
clients_string = ""
else:
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:
clients = None
@@ -448,10 +490,13 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
print(" "+clients_string)
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 ifstat["txdrp"]:
print(f" TX Drops : {ifstat['txdrp']} ({RNS.prettysize(ifstat['txdrb'])})")
if "bitrate" in ifstat and ifstat["bitrate"] != None:
print(" Rate : {ss}".format(ss=speed_str(ifstat["bitrate"])))
print(f" Rate : {speed_str(ifstat['bitrate'])}, MTU {ifstat['mtu']}")
if "noise_floor" in ifstat:
if not "interference" in ifstat: nstr = ""
@@ -533,24 +578,129 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
print(" Held : {np} announce".format(np=aqn))
else:
print(" Held : {np} announces".format(np=aqn))
if astats and "incoming_announce_frequency" in ifstat and ifstat["incoming_announce_frequency"] != None:
print(" Announces : {iaf}↑".format(iaf=RNS.prettyfrequency(ifstat["outgoing_announce_frequency"])))
print(" {iaf}↓".format(iaf=RNS.prettyfrequency(ifstat["incoming_announce_frequency"])))
art = None; arp = None; arg = None
if astats and "announce_rate_target" in ifstat: art = ifstat["announce_rate_target"]
if astats and "announce_rate_penalty" in ifstat: arp = ifstat["announce_rate_penalty"]
if astats and "announce_rate_grace" in ifstat: arg = ifstat["announce_rate_grace"]
if art and arp != None and arg: art_str = f"(t:{RNS.prettytime(art)}/p:{RNS.prettytime(arp)}/g:{arg})"
elif art and arp != None: art_str = f"(t:{RNS.prettytime(art)}/p:{RNS.prettytime(arp)})"
elif art: art_str = f"(t:{RNS.prettytime(art)})"
else: art_str = ""
burst_str = ""
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"])
burst_str = f" burst {bcstr}for {for_str}"
pburst_str = ""
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"])
pburst_str = f"burst {prbcstr}for {for_str}"
rxb_str = "↓"+RNS.prettysize(ifstat["rxb"])
txb_str = "↑"+RNS.prettysize(ifstat["txb"])
strdiff = len(rxb_str)-len(txb_str)
if strdiff > 0:
txb_str += " "*strdiff
elif strdiff < 0:
rxb_str += " "*-strdiff
asr = False
if astats and "incoming_announce_frequency" in ifstat and ifstat["incoming_announce_frequency"] != None:
oan = ifstat["outgoing_announce_frequency"]
ian = ifstat["incoming_announce_frequency"]
if name.startswith("Shared Instance[") and clients and clients > 0: oan = oan-(oan/clients) # Sub rnstatus own part
oaf = RNS.prettyfrequency(oan, d=1, lpf=True)
iaf = RNS.prettyfrequency(ian, d=1, lpf=True)
cspec = "c"
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}"
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
psr = False
if pstats and "incoming_pr_frequency" in ifstat and ifstat["incoming_pr_frequency"] != None:
opn = ifstat["outgoing_pr_frequency"]
ipn = ifstat["incoming_pr_frequency"]
if name.startswith("Shared Instance[") and clients and clients > 0: opn = opn-(opn/clients) # Sub rnstatus own part
if astats:
opf = "↑"+RNS.prettyfrequency(opn, d=1, lpf=True)
ipf = "↓"+RNS.prettyfrequency(ipn, d=1, lpf=True)
else:
opf = RNS.prettyfrequency(opn,d=1, lpf=True)+"↑"
ipf = RNS.prettyfrequency(ipn,d=1, lpf=True)+"↓"
cspec = "c"
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}"
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
if not asr: iaf = ""; oaf = ""
if not psr: ipf = ""; opf = ""
amlen = max(len(iaf), len(oaf))
iaf += (amlen-len(iaf))*" "+"↓"
oaf += (amlen-len(oaf))*" "+"↑"
mlen = max(max(len(iaf), len(oaf), len(rxb_str), len(txb_str), len(ipf), len(opf)), 10)
iaf += (mlen-len(iaf))*" "
oaf += (mlen-len(oaf))*" "
ipf += (mlen-len(ipf))*" "
opf += (mlen-len(opf))*" "
rxb_str += (mlen-len(rxb_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 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}")
if asr:
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}")
rxstat = rxb_str
txstat = txb_str
if "rxs" in ifstat and "txs" in ifstat:
rxstat += " "+RNS.prettyspeed(ifstat["rxs"])
txstat += " "+RNS.prettyspeed(ifstat["txs"])
if ifstat["txbuffered"]:
if ifstat["txstalled"]: stlstr = ", stalled"
else: stlstr = ""
txstat += f" ({RNS.prettysize(ifstat['txbuffered'])} waiting{stlstr})"
print(f" Traffic : {txstat}\n {rxstat}")
@@ -562,19 +712,96 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
else:
lstr = f" {link_count} entr{ms} in link table"
if active_link_count: lstr = f"{lstr} ({active_link_count} active)"
if traffic_totals:
rxb_str = "↓"+RNS.prettysize(stats["rxb"])
txb_str = "↑"+RNS.prettysize(stats["txb"])
strdiff = len(rxb_str)-len(txb_str)
if strdiff > 0:
txb_str += " "*strdiff
elif strdiff < 0:
rxb_str += " "*-strdiff
if strdiff > 0: txb_str += " "*strdiff
elif strdiff < 0: rxb_str += " "*-strdiff
rxstat = rxb_str+" "+RNS.prettyspeed(stats["rxs"])
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)})"
if pps:
rpps = RNS.prettysize(stats['rxpps'], suffix="pps")
tpps = RNS.prettysize(stats['txpps'], suffix="pps")
rxstat = f"{rxstat}, {rpps}"
txstat = f"{txstat}, {tpps}"
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 profiling_results:
print(f"\n Profiling :\n{RNS.Profiler.format_results(profiling_results)}")
if "transport_id" in stats and stats["transport_id"] != None:
print("\n Transport Instance "+RNS.prettyhexrep(stats["transport_id"])+" running")
if "network_id" in stats and stats["network_id"] != None:
@@ -607,9 +834,15 @@ def main(must_exit=True, rns_instance=None):
parser.add_argument("-a", "--all", action="store_true", help="show all interfaces", default=False)
parser.add_argument("-A", "--announce-stats", action="store_true", help="show announce 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("-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("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, announces, arx, atx, held]", default=None, type=str)
parser.add_argument("-p", "--pps", action="store_true", help="display packets per second in totals", default=False)
parser.add_argument("-q", "--queues", action="store_true", help="display queue stats", default=False)
parser.add_argument("-z", "--profiling", action="store_true", help="display live profiling results", default=False)
parser.add_argument("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, anns, arx, atx, arxc, atxc, held, prx, ptx, prxc, ptxc, pvs, ivs, flt, txdrp, txdrb, txbuf]", default=None, type=str)
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("-R", action="store", metavar="hash", help="transport identity hash of remote instance to get status from", default=None, type=str)
@@ -637,15 +870,17 @@ def main(must_exit=True, rns_instance=None):
exit(1)
while True:
st = time.time()
buffer = io.StringIO()
old_stdout = sys.stdout
sys.stdout = buffer
try:
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
astats=args.announce_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, traffic_totals=args.totals,
discovered_interfaces=args.discovered, config_entries=args.D)
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,
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, pps=args.pps, profiling=args.profiling)
finally:
sys.stdout = old_stdout
@@ -653,14 +888,17 @@ def main(must_exit=True, rns_instance=None):
output = buffer.getvalue()
print("\033[H\033[2J", end="")
print(output, end="", flush=True)
time.sleep(args.monitor_interval)
td = time.time()-st
sleeptime = max(args.monitor_interval-td, 0.2)
time.sleep(sleeptime)
else:
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
astats=args.announce_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, traffic_totals=args.totals,
discovered_interfaces=args.discovered, config_entries=args.D)
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,
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, pps=args.pps, profiling=args.profiling)
except KeyboardInterrupt:
print("")
+2 -2
View File
@@ -347,7 +347,7 @@ def execute(configdir, identitypath = None, verbosity = 0, quietness = 0, detail
if not RNS.Transport.has_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")
exit(242)
@@ -365,7 +365,7 @@ def execute(configdir, identitypath = None, verbosity = 0, quietness = 0, detail
link = RNS.Link(listener_destination)
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))
exit(243)
+288 -178
View File
@@ -35,32 +35,25 @@ import time
import datetime
import random
import threading
import math
import bisect
from ._version import __version__
from .Reticulum import Reticulum
from .Identity import Identity
from .Link import Link, RequestReceipt
from .Channel import MessageBase
from .Buffer import Buffer, RawChannelReader, RawChannelWriter
from .Transport import Transport
from .Discovery import InterfaceAnnouncer
from .Destination import Destination
from .Packet import Packet
from .Packet import PacketReceipt
from .Resolver import Resolver
from .Resource import Resource, ResourceAdvertisement
from .Cryptography import HKDF
from .Cryptography import Hashes
from collections import deque
from functools import partial, wraps
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
import importlib.util
if importlib.util.find_spec("cython"): import cython; compiled = cython.compiled
else: compiled = False
try: from ._buildinfo import compiled
except ImportError:
if importlib.util.find_spec("cython"): import cython; compiled = cython.compiled
else: compiled = False
LOG_NONE = -1
LOG_CRITICAL = 0
@@ -70,7 +63,8 @@ LOG_NOTICE = 3
LOG_INFO = 4
LOG_VERBOSE = 5
LOG_DEBUG = 6
LOG_EXTREME = 7
LOG_PATHING = 7
LOG_EXTREME = 8
LOG_STDOUT = 0x91
LOG_FILE = 0x92
@@ -82,6 +76,7 @@ loglevel = LOG_NOTICE
logfile = None
logdest = LOG_STDOUT
logcall = None
logtimestamps = True
logtimefmt = "%Y-%m-%d %H:%M:%S"
logtimefmt_p = "%H:%M:%S.%f"
compact_log_fmt = False
@@ -94,22 +89,15 @@ _always_override_destination = False
logging_lock = threading.Lock()
def loglevelname(level):
if (level == LOG_CRITICAL):
return "[Critical]"
if (level == LOG_ERROR):
return "[Error] "
if (level == LOG_WARNING):
return "[Warning] "
if (level == LOG_NOTICE):
return "[Notice] "
if (level == LOG_INFO):
return "[Info] "
if (level == LOG_VERBOSE):
return "[Verbose] "
if (level == LOG_DEBUG):
return "[Debug] "
if (level == LOG_EXTREME):
return "[Extra] "
if (level == LOG_CRITICAL): return "[Critical]"
if (level == LOG_ERROR): return "[Error] "
if (level == LOG_WARNING): return "[Warning] "
if (level == LOG_NOTICE): return "[Notice] "
if (level == LOG_INFO): return "[Info] "
if (level == LOG_VERBOSE): return "[Verbose] "
if (level == LOG_DEBUG): return "[Debug] "
if (level == LOG_PATHING): return "[Pathing] "
if (level == LOG_EXTREME): return "[Extra] "
return "Unknown"
@@ -127,18 +115,16 @@ def timestamp_str(time_s):
def precise_timestamp_str(time_s):
return datetime.datetime.now().strftime(logtimefmt_p)[:-3]
def sl(level=3): return loglevel >= level
def log(msg, level=3, _override_destination = False, pt=False):
if loglevel == LOG_NONE: return
global _always_override_destination, compact_log_fmt
msg = str(msg)
if loglevel >= level:
if pt:
logstring = "["+precise_timestamp_str(time.time())+"] "+loglevelname(level)+" "+msg
if pt: logstring = "["+precise_timestamp_str(time.time())+"] "+loglevelname(level)+" "+msg
else:
if not compact_log_fmt:
logstring = "["+timestamp_str(time.time())+"] "+loglevelname(level)+" "+msg
else:
logstring = "["+timestamp_str(time.time())+"] "+msg
if not compact_log_fmt: logstring = ("["+timestamp_str(time.time())+"] " if logtimestamps else "")+loglevelname(level)+" "+msg
else: logstring = ("["+timestamp_str(time.time())+"] " if logtimestamps else "")+msg
with logging_lock:
if (logdest == LOG_STDOUT or _always_override_destination or _override_destination):
@@ -168,7 +154,6 @@ def log(msg, level=3, _override_destination = False, pt=False):
log("Exception occurred while calling external log handler: "+str(e), LOG_CRITICAL)
log("Dumping future log events to console!", LOG_CRITICAL)
log(msg, level)
def rand():
result = instance_random.random()
@@ -181,14 +166,11 @@ def trace_exception(e):
log(exception_info, LOG_ERROR)
def hexrep(data, delimit=True):
try:
iter(data)
except TypeError:
data = [data]
try: iter(data)
except TypeError: data = [data]
delimiter = ":"
if not delimit:
delimiter = ""
if not delimit: delimiter = ""
hexrep = delimiter.join("{:02x}".format(c) for c in data)
return hexrep
@@ -197,11 +179,6 @@ def prettyhexrep(data):
hexrep = "<"+delimiter.join("{:02x}".format(c) for c in data)+">"
return hexrep
def prettyb256rep(data):
delimiter = ""
b256rep = "<"+delimiter.join(b256_rep(c) for c in data)+">"
return b256rep
def prettyspeed(num, suffix="b"):
return prettysize(num/8, suffix=suffix)+"ps"
@@ -216,23 +193,24 @@ def prettysize(num, suffix='B'):
for unit in units:
if abs(num) < 1000.0:
if unit == "":
return "%.0f %s%s" % (num, unit, suffix)
else:
return "%.2f %s%s" % (num, unit, suffix)
if unit == "": return "%.0f %s%s" % (num, unit, suffix)
else: return "%.2f %s%s" % (num, unit, suffix)
num /= 1000.0
return "%.2f%s%s" % (num, last_unit, suffix)
def prettyfrequency(hz, suffix="Hz"):
def prettyfrequency(hz, suffix="Hz", d=2, lpf=False):
if hz == 0: return "0 Hz"
num = hz*1e6
units = ["µ", "m", "", "K","M","G","T","P","E","Z"]
if not lpf: num = hz*1e6
else: num = hz
if not lpf: units = ["µ", "m", "", "K","M","G","T","P","E","Z"]
else: units = ["", "K","M","G","T","P","E","Z"]
last_unit = "Y"
for unit in units:
if abs(num) < 1000.0:
return "%.2f %s%s" % (num, unit, suffix)
if d == 2: return "%.2f %s%s" % (num, unit, suffix)
else: return "%s %s%s" % (str(round(num,d)), unit, suffix)
num /= 1000.0
return "%.2f%s%s" % (num, last_unit, suffix)
@@ -247,8 +225,7 @@ def prettydistance(m, suffix="m"):
if unit == "m": divisor = 10
if unit == "c": divisor = 100
if abs(num) < divisor:
return "%.2f %s%s" % (num, unit, suffix)
if abs(num) < divisor: return "%.2f %s%s" % (num, unit, suffix)
num /= divisor
return "%.2f %s%s" % (num, last_unit, suffix)
@@ -265,10 +242,8 @@ def prettytime(time, verbose=False, compact=False):
time %= 3600
minutes = int(time // 60)
time %= 60
if compact:
seconds = int(time)
else:
seconds = round(time, 2)
if compact: seconds = int(time)
else: seconds = round(time, 2)
ss = "" if seconds == 1 else "s"
sm = "" if minutes == 1 else "s"
@@ -297,24 +272,18 @@ def prettytime(time, verbose=False, compact=False):
tstr = ""
for c in components:
i += 1
if i == 1:
pass
elif i < len(components):
tstr += ", "
elif i == len(components):
tstr += " and "
if i == 1: pass
elif i < len(components): tstr += ", "
elif i == len(components): tstr += " and "
tstr += c
if tstr == "":
return "0s"
if tstr == "": return "0s"
else:
if not neg:
return tstr
else:
return f"-{tstr}"
if not neg: return tstr
else: return f"-{tstr}"
def prettyshorttime(time, verbose=False, compact=False):
def prettyshorttime(time, verbose=False, compact=False, tight=False):
neg = False
time = time*1e6
if time < 0:
@@ -324,10 +293,8 @@ def prettyshorttime(time, verbose=False, compact=False):
seconds = int(time // 1e6); time %= 1e6
milliseconds = int(time // 1e3); time %= 1e3
if compact:
microseconds = int(time)
else:
microseconds = round(time, 2)
if compact: microseconds = int(time)
else: microseconds = round(time, 2)
ss = "" if seconds == 1 else "s"
sms = "" if milliseconds == 1 else "s"
@@ -351,22 +318,16 @@ def prettyshorttime(time, verbose=False, compact=False):
tstr = ""
for c in components:
i += 1
if i == 1:
pass
elif i < len(components):
tstr += ", "
elif i == len(components):
tstr += " and "
if i == 1: pass
elif i < len(components): tstr += ", " if not tight else " "
elif i == len(components): tstr += " and " if not tight else " "
tstr += c
if tstr == "":
return "0us"
if tstr == "": return "0us"
else:
if not neg:
return tstr
else:
return f"-{tstr}"
if not neg: return tstr
else: return f"-{tstr}"
def phyparams():
print("Required Physical Layer MTU : "+str(Reticulum.MTU)+" bytes")
@@ -377,8 +338,7 @@ def phyparams():
print("Link Public Key Size : "+str(Link.ECPUBSIZE*8)+" bits")
print("Link Private Key Size : "+str(Link.KEYSIZE*8)+" bits")
def panic():
os._exit(255)
def panic(): os._exit(255)
exit_called = False
def exit(code=0):
@@ -388,33 +348,67 @@ def exit(code=0):
Reticulum.exit_handler()
os._exit(code)
def _detach_stdout():
sys.stdout = open(os.devnull, "w")
sys.stderr = open(os.devnull, "w")
class Profiler:
_ran = False
profilers = {}
tags = {}
# Samples per tag
MAX_CAPTURES = 10000
@staticmethod
def get_profiler(tag=None, super_tag=None):
if tag in Profiler.profilers:
return Profiler.profilers[tag]
def get_profiler(tag=None, super_tag=None, max_captures=None):
if tag in Profiler.profilers: return Profiler.profilers[tag]
else:
profiler = Profiler(tag, super_tag)
if max_captures is None: max_captures = Profiler.MAX_CAPTURES
profiler = Profiler(tag, super_tag, max_captures)
Profiler.profilers[tag] = profiler
return profiler
def __init__(self, tag=None, super_tag=None):
@staticmethod
def profile(func=None, *, tag=None, max_captures=None):
"""
Decorator to profile a function. With no arguments, it can be
used as `@RNS.Profiler.profile`, in which case it will use the
qualified name of the function as the profiler tag. It can
also be used as `@RNS.Profiler.profile(tag="prof_tag")` to use
a specific profiler tag.
:param tag: Either a profiler tag as passed to `Profiler.get_profiler(...)` or a `Profiler` object.
:param max_captures: Maximum samples to capture for the specified profiler tag.
"""
if func is None:
return partial(Profiler.profile, tag=tag, max_captures=max_captures)
tag = func.__qualname__ if tag is None else tag
if isinstance(tag, Profiler): profiler = tag
else: profiler = Profiler.get_profiler(tag=tag, max_captures=max_captures)
@wraps(func)
def wrapper(*args, **kwargs):
with profiler:
return func(*args, **kwargs)
return wrapper
def __init__(self, tag=None, super_tag=None, max_captures=None):
self.paused = False
self.pause_time = 0
self.pause_started = None
self.tag = tag
self.super_tag = super_tag
self.max_captures = max_captures if max_captures is not None else Profiler.MAX_CAPTURES
if self.super_tag in Profiler.profilers:
self.super_profiler = Profiler.profilers[self.super_tag]
self.pause_super = self.super_profiler.pause
self.resume_super = self.super_profiler.resume
else:
def noop(self=None):
pass
def noop(self=None): pass
self.super_profiler = None
self.pause_super = noop
self.resume_super = noop
@@ -424,12 +418,18 @@ class Profiler:
tag = self.tag
super_tag = self.super_tag
thread_ident = threading.get_ident()
if not tag in Profiler.tags:
Profiler.tags[tag] = {"threads": {}, "super": super_tag}
if not tag in Profiler.tags: Profiler.tags[tag] = {"threads": {}, "super": super_tag, "captures": deque(maxlen=self.max_captures)}
if not thread_ident in Profiler.tags[tag]["threads"]:
Profiler.tags[tag]["threads"][thread_ident] = {"current_start": None, "captures": []}
Profiler.tags[tag]["threads"][thread_ident] = {"running": deque()}
Profiler.tags[tag]["threads"][thread_ident]["current_start"] = time.perf_counter()
# The tag deque stores a shared reference to the capture, and the end
# time isn't updated until the context manager exits. This leaves the
# deque sorted by start time, except for cases where the thread is
# preemted between getting the current time and appending. We also store
# a stack of start times per thread to support reentrancy.
capture = {"start": time.perf_counter(), "end": None, "thread_ident": thread_ident}
Profiler.tags[tag]["captures"].append(capture)
Profiler.tags[tag]["threads"][thread_ident]["running"].append(capture)
self.resume_super()
def __exit__(self, exc_type, exc_value, traceback):
@@ -439,14 +439,15 @@ class Profiler:
end = time.perf_counter() - self.pause_time
self.pause_time = 0
thread_ident = threading.get_ident()
if tag in Profiler.tags and thread_ident in Profiler.tags[tag]["threads"]:
if Profiler.tags[tag]["threads"][thread_ident]["current_start"] != None:
begin = Profiler.tags[tag]["threads"][thread_ident]["current_start"]
Profiler.tags[tag]["threads"][thread_ident]["current_start"] = None
Profiler.tags[tag]["threads"][thread_ident]["captures"].append(end-begin)
try:
if tag in Profiler.tags and thread_ident in Profiler.tags[tag]["threads"]:
try: capture = Profiler.tags[tag]["threads"][thread_ident]["running"].pop()
except IndexError as e: return
capture["end"] = end
if not Profiler._ran:
Profiler._ran = True
self.resume_super()
finally:
self.resume_super()
def pause(self, pause_started=None):
if not self.paused:
@@ -461,92 +462,162 @@ class Profiler:
self.resume_super()
@staticmethod
def ran():
return Profiler._ran
def ran(): return Profiler._ran
@staticmethod
def results():
from statistics import mean, median, stdev
def find_window_start(captures, start_time, hi=None):
hi = len(captures) if hi is None else hi
idx = bisect.bisect_left(captures, start_time, hi=hi, key=lambda c: c["start"])
return idx if len(captures) - idx > 1 else None
# Fast one-pass calculation of summary statistics
def calc_stats(captures, start=0, end=None, key=lambda c: c, threads_key=None):
if end is None: end = len(captures)
while start > 0 and start < len(captures) and start < end and key(captures[start]) is None: start += 1
while end > 0 and end <= len(captures) and start < end and key(captures[end-1]) is None: end -= 1
count = end - start
if count <= 0: return None
elif count == 1:
capture = key(captures[start])
return { "count": 1,
"mean": capture,
"median": capture,
"min": capture,
"max": capture,
"stdev": None,
"sum": capture,
"threads": 1 if threads_key else None}
# Median is approximate if there are any incomplete captures in the
# middle of the range.
med_even = count % 2 == 0
med_idx = start + (count // 2 if med_even else (count - 1) // 2)
while key(captures[med_idx]) is None and med_idx < end: med_idx += 1
if med_idx == end: c_median = None
elif med_even: c_median = key(captures[med_idx])
else:
med_idx2 = med_idx + 1
while key(captures[med_idx2]) is None and med_idx2 < end: med_idx2 += 1
if med_idx2 == end: c_median = None
else:
med_cap1 = key(captures[med_idx])
med_cap2 = key(captures[med_idx+1])
if med_cap1 is None or med_cap2 is None: c_median = None
else: c_median = (med_cap1 + med_cap2) / 2
c_count = 0; c_sum = 0; c_min = key(captures[start]); c_max = key(captures[start]); ck = 0; ck2 = 0
uniq_threads = set()
for idx in range(start, end):
c = key(captures[idx])
if c is None: continue
else: c_count += 1
c_sum += c
if c < c_min: c_min = c
if c > c_max: c_max = c
ck += c - c_median
ck2 += (c - c_median) ** 2
if threads_key: uniq_threads.add(threads_key(captures[idx]))
c_mean = c_sum / c_count if c_count > 0 else None
c_std = math.sqrt((ck2 - (ck ** 2)/c_count) / (c_count - 1)) if c_count > 1 else None
return { "count": c_count,
"mean": c_mean,
"median": c_median,
"min": c_min,
"max": c_max,
"stdev": c_std,
"sum": c_sum,
"threads": len(uniq_threads) if threads_key else None }
def stats_key(capture):
end = capture["end"]
if end is None: return None
else: return end - capture["start"]
results = {}
for tag in Profiler.tags:
tag_captures = []
now = time.perf_counter()
for tag in sorted(Profiler.tags):
tag_entry = Profiler.tags[tag]
for thread_ident in tag_entry["threads"]:
thread_entry = tag_entry["threads"][thread_ident]
thread_captures = thread_entry["captures"]
sample_count = len(thread_captures)
if sample_count > 1:
thread_results = {
"count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": stdev(thread_captures)
}
elif sample_count == 1:
thread_results = {
"count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": None
}
tag_captures = sorted(tag_entry["captures"], key=lambda c: c["start"])
tag_captures.extend(thread_captures)
if len(tag_captures):
captures_1m = None; captures_5m = None; captures_30m = None; captures_60m = None
stats_1m = None; stats_5m = None; stats_30m = None; stats_60m = None
sample_count = len(tag_captures)
if sample_count > 1:
tag_results = {
"name": tag,
"super": tag_entry["super"],
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": stdev(tag_captures)
}
elif sample_count == 1:
tag_results = {
"name": tag,
"super": tag_entry["super"],
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": None
}
captures_1m = find_window_start(tag_captures, now - 1*60)
if captures_1m: captures_5m = find_window_start(tag_captures, now - 5*60, hi=captures_1m)
if captures_5m: captures_30m = find_window_start(tag_captures, now - 30*60, hi=captures_5m)
if captures_30m: captures_60m = find_window_start(tag_captures, now - 60*60, hi=captures_30m)
results[tag] = tag_results
stats_all = calc_stats(tag_captures, 0, None, key=stats_key, threads_key=lambda c: c["thread_ident"])
if captures_1m: stats_1m = calc_stats(tag_captures, captures_1m, None, key=stats_key)
if captures_5m: stats_5m = calc_stats(tag_captures, captures_5m, captures_1m, key=stats_key)
if captures_30m: stats_30m = calc_stats(tag_captures, captures_30m, captures_5m, key=stats_key)
if captures_60m: stats_60m = calc_stats(tag_captures, captures_60m, captures_30m, key=stats_key)
if stats_all["count"]:
results[tag] = { "name": tag,
"super": tag_entry["super"],
"stats_all": stats_all,
"stats_1m": stats_1m,
"stats_5m": stats_5m,
"stats_30m": stats_30m,
"stats_60m": stats_60m }
# Yield to avoid bogging down the instance
time.sleep(0.001)
return results
@staticmethod
def format_results(results):
def pst(time):
if time is not None: return prettyshorttime(time, tight=True)
else: return "-----"
def print_results_recursive(tag, results, level=0):
print_tag_results(tag, level+1)
results_str = print_tag_results(tag, level+1) + "\n"
for tag_name in results:
sub_tag = results[tag_name]
if sub_tag["super"] == tag["name"]:
print_results_recursive(sub_tag, results, level=level+1)
results_str += print_results_recursive(sub_tag, results, level=level+1)
return results_str
def print_tag_results(tag, level):
ind = " "*level
name = tag["name"]; count = tag["count"]
mean = tag["mean"]; median = tag["median"]; stdev = tag["stdev"]
print( f"{ind}{name}")
print( f"{ind} Samples : {count}")
if stdev != None:
print(f"{ind} Mean : {prettyshorttime(mean)}")
print(f"{ind} Median : {prettyshorttime(median)}")
print(f"{ind} St.dev. : {prettyshorttime(stdev)}")
print( f"{ind} Total : {prettyshorttime(mean*count)}")
print("")
name = tag["name"]
stats_all = tag["stats_all"]; stats_1m = tag["stats_1m"]; stats_5m = tag["stats_5m"]; stats_30m = tag["stats_30m"]; stats_60m = tag["stats_60m"]
results_str = f" {ind}{name}\n"
results_str += f" {ind} Samples : {stats_all['count']} from {stats_all['threads']} thread{'s' if stats_all['threads'] > 1 else ''}\n"
if stats_all != None:
results_str += f" {ind} {'Mean':^15} | {'Median':^15} | {'Min':^15} | {'Max':^15} | {'St. dev':^15} | {'Total':^15}\n"
results_str += f" {ind} Stats : ({pst(stats_all['mean']):^15} | {pst(stats_all['median']):^15} | {pst(stats_all['min']):^15} | {pst(stats_all['max']):^15} | {pst(stats_all['stdev']):^15} | {pst(stats_all['sum']):^15})\n"
if stats_1m != None:
results_str += f" {ind} 0-1m : ({pst(stats_1m['mean']):^15} | {pst(stats_1m['median']):^15} | {pst(stats_1m['min']):^15} | {pst(stats_1m['max']):^15} | {pst(stats_1m['stdev']):^15} | {pst(stats_1m['sum']):^15})\n"
if stats_5m != None:
results_str += f" {ind} 1-5m : ({pst(stats_5m['mean']):^15} | {pst(stats_5m['median']):^15} | {pst(stats_5m['min']):^15} | {pst(stats_5m['max']):^15} | {pst(stats_5m['stdev']):^15} | {pst(stats_5m['sum']):^15})\n"
if stats_30m != None:
results_str += f" {ind} 5-30m : ({pst(stats_30m['mean']):^15} | {pst(stats_30m['median']):^15} | {pst(stats_30m['min']):^15} | {pst(stats_30m['max']):^15} | {pst(stats_30m['stdev']):^15} | {pst(stats_30m['sum']):^15})\n"
if stats_60m != None:
results_str += f" {ind} 30-60m : ({pst(stats_60m['mean']):^15} | {pst(stats_60m['median']):^15} | {pst(stats_60m['min']):^15} | {pst(stats_60m['max']):^15} | {pst(stats_60m['stdev']):^15} | {pst(stats_60m['sum']):^15})\n"
return results_str
print("\nProfiler results:\n")
results_str = ""
for tag_name in results:
tag = results[tag_name]
if tag["super"] == None:
print_results_recursive(tag, results)
results_str += print_results_recursive(tag, results)
return results_str
profile = Profiler.get_profiler
# The base-256 table is likely to change. Currently, it is just
# experimental, so don't count on it too much just yet.
b256 = [
# 0 1 2 3 4 5 6 7 8 9 A B C D F F
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p", # 0x0 Latin & numerals
@@ -567,4 +638,43 @@ b256 = [
"𐌳","𐌸","𐌾","𐐀","𐐁","𐐂","𐐆","𐐇","𐐈","𐐉","𐐊","𐐋","𐐌","𐐍","𐐎","𐐏", # 0xF Gothic & Deseret
]
def b256_rep(input_byte): return b256[int(input_byte)]
def b256rep(data): return "".join(bytes_to_b256(data))
def prettyb256rep(data): return f"<{b256rep(data)}>"
def b256_to_byte(point):
if not type(point) == str or not len(point) == 1: raise TypeError("Invalid input data for base256 byte decode")
try: return b256.index(point)
except Exception as e: raise ValueError(f"Could not decode base256 byte: {e}")
def b256_to_bytes(b256rep):
if not type(b256rep) == str: raise TypeError("Invalid input data for base256 decode")
try: return bytes([b256.index(c) for c in b256rep])
except Exception as e: raise ValueError(f"Could not decode base256: {e}")
def byte_to_b256(input_byte):
if type(input_byte) == bytes and not len(input_byte) == 1: TypeError("Invalid input data for base256 byte encode")
if type(input_byte) == bytes and len(input_byte) == 1: input_byte = ord(input_byte)
if not type(input_byte) == int: raise TypeError("Invalid input data for base256 byte encode")
try: return b256[int(input_byte)]
except Exception as e: raise TypeError(f"Could not encode byte to base256: {e}")
def bytes_to_b256(data):
if not type(data) == bytes: raise TypeError("Invalid input data for base256 encode")
try: return [byte_to_b256(c) for c in data]
except Exception as e: raise TypeError(f"Could not encode to base256: {e}")
from .Reticulum import Reticulum
from .Identity import Identity
from .Link import Link, RequestReceipt
from .Channel import MessageBase
from .Buffer import Buffer, RawChannelReader, RawChannelWriter
from .Transport import Transport
from .Discovery import InterfaceAnnouncer
from .Destination import Destination
from .Packet import Packet
from .Packet import PacketReceipt
from .Resolver import Resolver
from .Resource import Resource, ResourceAdvertisement
from .Cryptography import HKDF
from .Cryptography import Hashes
+1 -1
View File
@@ -1 +1 @@
__version__ = "1.2.3"
__version__ = "1.5.4"
+4 -2
View File
@@ -3,5 +3,7 @@ import glob
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"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+23 -42
View File
@@ -6,14 +6,12 @@ from . import utils
from .log import logger
def parse_reply(data):
if not data:
raise ConnectionAbortedError("Empty response: SAM API went offline")
if not data: raise ConnectionAbortedError("Empty response: SAM API went offline")
try:
msg = sam.Message(data.decode().strip())
logger.debug("SAM reply: "+str(msg))
except:
raise ConnectionAbortedError("Invalid SAM response")
except: raise ConnectionAbortedError("Invalid SAM response")
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)
writer.write(sam.hello("3.1", "3.1"))
reply = parse_reply(await reader.readline())
if reply.ok:
return (reader, writer)
if reply.ok: return (reader, writer)
else:
writer.close()
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))
reply = parse_reply(await reader.readline())
writer.close()
if reply.ok:
return sam.Destination(reply["VALUE"])
else:
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
if reply.ok: return sam.Destination(reply["VALUE"])
else: raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
async def new_destination(sam_address=sam.DEFAULT_ADDRESS, loop=None,
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))
if destination:
if type(destination) == sam.Destination:
destination = destination
else:
destination = sam.Destination(
destination, has_private_key=True)
if type(destination) == sam.Destination: destination = destination
else: destination = sam.Destination(destination, has_private_key=True)
dest_string = destination.private_key.base64
else:
dest_string = sam.TRANSIENT_DESTINATION
else: dest_string = sam.TRANSIENT_DESTINATION
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())
if reply.ok:
if not destination:
destination = sam.Destination(
reply["DESTINATION"], has_private_key=True)
if not destination: destination = sam.Destination(reply["DESTINATION"], has_private_key=True)
logger.debug(destination.base32)
logger.debug("Session created {}".format(session_name))
return (reader, writer)
@@ -130,10 +118,8 @@ async def stream_connect(session_name, destination,
:return: A (reader, writer) pair
"""
logger.debug("Connecting stream {}".format(session_name))
if isinstance(destination, str) and not destination.endswith(".i2p"):
destination = sam.Destination(destination)
elif isinstance(destination, str):
destination = await dest_lookup(destination, sam_address, loop)
if isinstance(destination, str) and not destination.endswith(".i2p"): destination = sam.Destination(destination)
elif isinstance(destination, str): destination = await dest_lookup(destination, sam_address, loop)
reader, writer = await get_sam_socket(sam_address, loop)
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)
writer.write(sam.stream_accept(session_name, silent="false"))
reply = parse_reply(await reader.readline())
if reply.ok:
return (reader, writer)
if reply.ok: return (reader, writer)
else:
writer.close()
raise exceptions.SAM_EXCEPTIONS[reply["RESULT"]]()
@@ -183,9 +168,9 @@ class Session:
:return: :class:`Session` object
"""
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS,
loop=None, style="STREAM",
signature_type=sam.Destination.default_sig_type,
destination=None, options={}):
loop=None, style="STREAM", signature_type=sam.Destination.default_sig_type,
destination=None, options={}):
self.session_name = session_name
self.sam_address = sam_address
self.loop = loop
@@ -195,10 +180,9 @@ class Session:
self.options = options
async def __aenter__(self):
self.reader, self.writer = await create_session(self.session_name,
sam_address=self.sam_address, loop=self.loop, style=self.style,
signature_type=self.signature_type,
destination=self.destination, options=self.options)
self.reader, self.writer = await create_session(self.session_name, sam_address=self.sam_address, loop=self.loop,
style=self.style, signature_type=self.signature_type,
destination=self.destination, options=self.options)
return self
async def __aexit__(self, exc_type, exc, tb):
@@ -214,16 +198,15 @@ class StreamConnection:
:param loop: (optional) Event loop instance
:return: :class:`StreamConnection` object
"""
def __init__(self, session_name, destination,
sam_address=sam.DEFAULT_ADDRESS, loop=None):
def __init__(self, session_name, destination, sam_address=sam.DEFAULT_ADDRESS, loop=None):
self.session_name = session_name
self.sam_address = sam_address
self.loop = loop
self.destination = destination
async def __aenter__(self):
self.reader, self.writer = await stream_connect(self.session_name,
self.destination, sam_address=self.sam_address, loop=self.loop)
self.reader, self.writer = await stream_connect(self.session_name, self.destination,
sam_address=self.sam_address, loop=self.loop)
self.read = self.reader.read
self.write = self.writer.write
return self
@@ -240,15 +223,13 @@ class StreamAcceptor:
:param loop: (optional) Event loop instance
:return: :class:`StreamAcceptor` object
"""
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS,
loop=None):
def __init__(self, session_name, sam_address=sam.DEFAULT_ADDRESS, loop=None):
self.session_name = session_name
self.sam_address = sam_address
self.loop = loop
async def __aenter__(self):
self.reader, self.writer = await stream_accept(self.session_name,
sam_address=self.sam_address, loop=self.loop)
self.reader, self.writer = await stream_accept(self.session_name, sam_address=self.sam_address, loop=self.loop)
self.read = self.reader.read
self.write = self.writer.write
return self
+9 -12
View File
@@ -30,15 +30,12 @@ class PeerNotFound(SAMException):
class Timeout(SAMException):
"""The peer cannot be found on the network"""
SAM_EXCEPTIONS = {
"CANT_REACH_PEER": CantReachPeer,
"DUPLICATED_DEST": DuplicatedDest,
"DUPLICATED_ID": DuplicatedId,
"I2P_ERROR": I2PError,
"INVALID_ID": InvalidId,
"INVALID_KEY": InvalidKey,
"KEY_NOT_FOUND": KeyNotFound,
"PEER_NOT_FOUND": PeerNotFound,
"TIMEOUT": Timeout,
}
SAM_EXCEPTIONS = { "CANT_REACH_PEER": CantReachPeer,
"DUPLICATED_DEST": DuplicatedDest,
"DUPLICATED_ID": DuplicatedId,
"I2P_ERROR": I2PError,
"INVALID_ID": InvalidId,
"INVALID_KEY": InvalidKey,
"KEY_NOT_FOUND": KeyNotFound,
"PEER_NOT_FOUND": PeerNotFound,
"TIMEOUT": Timeout }
+2 -5
View File
@@ -3,7 +3,6 @@ from hashlib import sha256
import struct
import re
I2P_B64_CHARS = "-~"
def i2p_b64encode(x):
@@ -41,11 +40,9 @@ class Message(object):
return self.opts[key]
@property
def ok(self):
return self["RESULT"] == "OK"
def ok(self): return self["RESULT"] == "OK"
def __repr__(self):
return self._reply_string
def __repr__(self): return self._reply_string
# SAM request messages
+58 -67
View File
@@ -15,15 +15,13 @@ async def proxy_data(reader, writer):
while True:
data = await reader.read(BUFFER_SIZE)
if not data:
logger.debug('no more data')
break
writer.write(data)
except Exception as e:
logger.debug('proxy_data_task exception {}'.format(e))
except Exception as e: logger.debug('proxy_data_task exception {}'.format(e))
finally:
try:
writer.close()
except RuntimeError:
pass
try: writer.close()
except RuntimeError: pass
logger.debug('close connection')
class I2PTunnel(object):
@@ -44,6 +42,7 @@ class I2PTunnel(object):
def __init__(self, local_address, destination=None, session_name=None,
options={}, loop=None, sam_address=sam.DEFAULT_ADDRESS):
self.local_address = local_address
self.destination = destination
self.session_name = session_name or utils.generate_session_id()
@@ -53,16 +52,13 @@ class I2PTunnel(object):
async def _pre_run(self):
if not self.destination:
self.destination = await aiosam.new_destination(
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)
self.destination = await aiosam.new_destination(sam_address=self.sam_address, loop=self.loop)
def stop(self):
"""Stop the tunnel"""
self.session_writer.close()
_, 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.close()
class ClientTunnel(I2PTunnel):
"""Client tunnel, a subclass of tunnel.I2PTunnel
@@ -85,20 +81,25 @@ class ClientTunnel(I2PTunnel):
"""A coroutine used to run the tunnel"""
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):
"""Handle local client connection"""
try:
sc_task = aiosam.stream_connect(
self.session_name, self.remote_destination,
sam_address=self.sam_address, loop=self.loop)
self.status["connect_tasks"].append(sc_task)
sc_task = aiosam.stream_connect(self.session_name, self.remote_destination,
sam_address=self.sam_address, loop=self.loop)
self.status["connect_tasks"].add(sc_task)
remote_reader, remote_writer = await sc_task
asyncio.ensure_future(proxy_data(remote_reader, client_writer),
loop=self.loop)
asyncio.ensure_future(proxy_data(client_reader, remote_writer),
loop=self.loop)
task = asyncio.ensure_future(proxy_data(remote_reader, client_writer), loop=self.loop)
self.status["background_tasks"].add(task)
task.add_done_callback(self.status["background_tasks"].discard)
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:
self.status["setup_ran"] = True
@@ -135,14 +136,15 @@ class ServerTunnel(I2PTunnel):
"""A coroutine used to run the tunnel"""
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):
try:
# data and dest may come in one chunk
dest, data = incoming.split(b"\n", 1)
remote_destination = sam.Destination(dest.decode())
logger.debug("{} client connected: {}.b32.i2p".format(
self.session_name, remote_destination.base32))
logger.debug("{} client connected: {}.b32.i2p".format(self.session_name, remote_destination.base32))
except Exception as e:
self.status["exception"] = e
@@ -150,21 +152,20 @@ class ServerTunnel(I2PTunnel):
data = None
try:
sc_task = asyncio.wait_for(
asyncio.open_connection(
host=self.local_address[0],
port=self.local_address[1]),
timeout=5)
self.status["connect_tasks"].append(sc_task)
sc_task = asyncio.wait_for(asyncio.open_connection(host=self.local_address[0], port=self.local_address[1]), timeout=5)
self.status["connect_tasks"].add(sc_task)
remote_reader, remote_writer = await sc_task
if data: remote_writer.write(data)
asyncio.ensure_future(proxy_data(remote_reader, client_writer),
loop=self.loop)
asyncio.ensure_future(proxy_data(client_reader, remote_writer),
loop=self.loop)
task = asyncio.ensure_future(proxy_data(remote_reader, client_writer), loop=self.loop)
self.status["background_tasks"].add(task)
task.add_done_callback(self.status["background_tasks"].discard)
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()
self.status["exception"] = e
self.status["setup_failed"] = True
@@ -172,14 +173,14 @@ class ServerTunnel(I2PTunnel):
async def server_loop():
try:
while True:
client_reader, client_writer = await aiosam.stream_accept(
self.session_name, sam_address=self.sam_address,
loop=self.loop)
client_reader, client_writer = await aiosam.stream_accept(self.session_name, sam_address=self.sam_address,
loop=self.loop)
incoming = await client_reader.read(BUFFER_SIZE)
asyncio.ensure_future(handle_client(
incoming, client_reader, client_writer), loop=self.loop)
except asyncio.CancelledError:
pass
task = asyncio.ensure_future(handle_client(incoming, client_reader, client_writer), loop=self.loop)
self.status["background_tasks"].add(task)
task.add_done_callback(self.status["background_tasks"].discard)
except asyncio.CancelledError: pass
self.server_loop = asyncio.ensure_future(server_loop(), loop=self.loop)
self.status["setup_ran"] = True
@@ -191,16 +192,11 @@ class ServerTunnel(I2PTunnel):
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('type', metavar="TYPE", choices=('server', '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('--debug', '-d', action='store_true',
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')
parser.add_argument('type', metavar="TYPE", choices=('server', '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('--debug', '-d', action='store_true', 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()
SAM_ADDRESS = utils.get_sam_address()
@@ -209,26 +205,21 @@ if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.set_debug(args.debug)
if args.key:
destination = sam.Destination(path=args.key, has_private_key=True)
else:
destination = None
if args.key: destination = sam.Destination(path=args.key, has_private_key=True)
else: destination = None
local_address = utils.address_from_string(args.address)
if args.type == "client":
tunnel = ClientTunnel(args.destination, local_address, loop=loop,
destination=destination, sam_address=SAM_ADDRESS)
tunnel = ClientTunnel(args.destination, local_address, loop=loop, destination=destination, sam_address=SAM_ADDRESS)
elif args.type == "server":
tunnel = ServerTunnel(local_address, loop=loop, destination=destination,
sam_address=SAM_ADDRESS)
tunnel = ServerTunnel(local_address, loop=loop, destination=destination, sam_address=SAM_ADDRESS)
asyncio.ensure_future(tunnel.run(), loop=loop)
try:
loop.run_forever()
except KeyboardInterrupt:
tunnel.stop()
try: loop.run_forever()
except KeyboardInterrupt: tunnel.stop()
finally:
loop.stop()
loop.close()
+16 -217
View File
@@ -2,7 +2,7 @@
# https://github.com/vsergeev/u-msgpack-python
#
# u-msgpack-python is a lightweight MessagePack serializer and deserializer
# module, compatible with both Python 2 and 3, as well CPython and PyPy
# module, compatible with Python 3, as well CPython and PyPy
# implementations of Python. u-msgpack-python is fully compliant with the
# latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
# particular, it supports the new binary, UTF-8 string, and application ext
@@ -35,7 +35,7 @@ u-msgpack-python v2.7.1 - v at sergeev.io
https://github.com/vsergeev/u-msgpack-python
u-msgpack-python is a lightweight MessagePack serializer and deserializer
module, compatible with both Python 2 and 3, as well CPython and PyPy
module, compatible with Python 3, as well CPython and PyPy
implementations of Python. u-msgpack-python is fully compliant with the
latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
particular, it supports the new binary, UTF-8 string, and application ext
@@ -49,10 +49,7 @@ import datetime
import sys
import io
if sys.version_info[0:2] >= (3, 3):
from collections.abc import Hashable
else:
from collections import Hashable
from collections.abc import Hashable
__version__ = "2.7.1"
"Module version string"
@@ -104,8 +101,6 @@ class Ext(object):
# Check data is type bytes or str
elif sys.version_info[0] == 3 and not isinstance(data, bytes):
raise TypeError("ext data is not type \'bytes\'")
elif sys.version_info[0] == 2 and not isinstance(data, str):
raise TypeError("ext data is not type \'str\'")
self.type = type
self.data = data
@@ -129,7 +124,7 @@ class Ext(object):
"""
s = "Ext Object (Type: {:d}, Data: ".format(self.type)
s += " ".join(["0x{:02}".format(ord(self.data[i:i + 1]))
for i in xrange(min(len(self.data), 8))])
for i in range(min(len(self.data), 8))])
if len(self.data) > 8:
s += " ..."
s += ")"
@@ -452,94 +447,6 @@ def _pack_map(obj, fp, options):
########################################
# Pack for Python 2, with 'unicode' type, 'str' type, and 'long' type
def _pack2(obj, fp, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
fp: a .write()-supporting file-like object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
into an Ext object
force_float_precision (str): "single" to force packing floats as
IEEE-754 single-precision floats,
"double" to force packing floats as
IEEE-754 double-precision floats.
Returns:
None.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> f = open('test.bin', 'wb')
>>> umsgpack.pack({u"compact": True, u"schema": 0}, f)
>>>
"""
global compatibility
ext_handlers = options.get("ext_handlers")
if obj is None:
_pack_nil(obj, fp, options)
elif ext_handlers and obj.__class__ in ext_handlers:
_pack_ext(ext_handlers[obj.__class__](obj), fp, options)
elif obj.__class__ in _ext_class_to_type:
try:
_pack_ext(Ext(_ext_class_to_type[obj.__class__], obj.packb()), fp, options)
except AttributeError:
raise NotImplementedError("Ext serializable class {:s} is missing implementation of packb()".format(repr(obj.__class__)))
elif isinstance(obj, bool):
_pack_boolean(obj, fp, options)
elif isinstance(obj, (int, long)):
_pack_integer(obj, fp, options)
elif isinstance(obj, float):
_pack_float(obj, fp, options)
elif compatibility and isinstance(obj, unicode):
_pack_oldspec_raw(bytes(obj), fp, options)
elif compatibility and isinstance(obj, bytes):
_pack_oldspec_raw(obj, fp, options)
elif isinstance(obj, unicode):
_pack_string(obj, fp, options)
elif isinstance(obj, str):
_pack_binary(obj, fp, options)
elif isinstance(obj, (list, tuple)):
_pack_array(obj, fp, options)
elif isinstance(obj, dict):
_pack_map(obj, fp, options)
elif isinstance(obj, datetime.datetime):
_pack_ext_timestamp(obj, fp, options)
elif isinstance(obj, Ext):
_pack_ext(obj, fp, options)
elif ext_handlers:
# Linear search for superclass
t = next((t for t in ext_handlers.keys() if isinstance(obj, t)), None)
if t:
_pack_ext(ext_handlers[t](obj), fp, options)
else:
raise UnsupportedTypeException(
"unsupported type: {:s}".format(str(type(obj))))
elif _ext_class_to_type:
# Linear search for superclass
t = next((t for t in _ext_class_to_type if isinstance(obj, t)), None)
if t:
try:
_pack_ext(Ext(_ext_class_to_type[t], obj.packb()), fp, options)
except AttributeError:
raise NotImplementedError("Ext serializable class {:s} is missing implementation of packb()".format(repr(t)))
else:
raise UnsupportedTypeException("unsupported type: {:s}".format(str(type(obj))))
else:
raise UnsupportedTypeException("unsupported type: {:s}".format(str(type(obj))))
# Pack for Python 3, with unicode 'str' type, 'bytes' type, and no 'long' type
def _pack3(obj, fp, **options):
"""
@@ -627,40 +534,6 @@ def _pack3(obj, fp, **options):
raise UnsupportedTypeException(
"unsupported type: {:s}".format(str(type(obj))))
def _packb2(obj, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
into an Ext object
force_float_precision (str): "single" to force packing floats as
IEEE-754 single-precision floats,
"double" to force packing floats as
IEEE-754 double-precision floats.
Returns:
A 'str' containing serialized MessagePack bytes.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> umsgpack.packb({u"compact": True, u"schema": 0})
'\x82\xa7compact\xc3\xa6schema\x00'
>>>
"""
fp = io.BytesIO()
_pack2(obj, fp, **options)
return fp.getvalue()
def _packb3(obj, **options):
"""
Serialize a Python object into MessagePack bytes.
@@ -885,9 +758,9 @@ def _unpack_array(code, fp, options):
raise Exception("logic error, not array: 0x{:02x}".format(ord(code)))
if options.get('use_tuple'):
return tuple((_unpack(fp, options) for i in xrange(length)))
return tuple((_unpack(fp, options) for i in range(length)))
return [_unpack(fp, options) for i in xrange(length)]
return [_unpack(fp, options) for i in range(length)]
def _deep_list_to_tuple(obj):
@@ -907,7 +780,7 @@ def _unpack_map(code, fp, options):
raise Exception("logic error, not map: 0x{:02x}".format(ord(code)))
d = {} if not options.get('use_ordered_dict') else collections.OrderedDict()
for _ in xrange(length):
for _ in range(length):
# Unpack key
k = _unpack(fp, options)
@@ -938,53 +811,6 @@ def _unpack(fp, options):
########################################
def _unpack2(fp, **options):
"""
Deserialize MessagePack bytes into a Python object.
Args:
fp: a .read()-supporting file-like object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext
type to a callable that unpacks an instance of
Ext into an object
use_ordered_dict (bool): unpack maps into OrderedDict, instead of
unordered dict (default False)
use_tuple (bool): unpacks arrays into tuples, instead of lists (default
False)
allow_invalid_utf8 (bool): unpack invalid strings into instances of
InvalidString, for access to the bytes
(default False)
Returns:
A Python object.
Raises:
InsufficientDataException(UnpackException):
Insufficient data to unpack the serialized object.
InvalidStringException(UnpackException):
Invalid UTF-8 string encountered during unpacking.
UnsupportedTimestampException(UnpackException):
Unsupported timestamp format encountered during unpacking.
ReservedCodeException(UnpackException):
Reserved code encountered during unpacking.
UnhashableKeyException(UnpackException):
Unhashable key encountered during map unpacking.
The serialized map cannot be deserialized into a Python dictionary.
DuplicateKeyException(UnpackException):
Duplicate key encountered during map unpacking.
Example:
>>> f = open('test.bin', 'rb')
>>> umsgpack.unpackb(f)
{u'compact': True, u'schema': 0}
>>>
"""
return _unpack(fp, options)
def _unpack3(fp, **options):
"""
Deserialize MessagePack bytes into a Python object.
@@ -1149,27 +975,11 @@ def __init():
global _utc_tzinfo
global _float_precision
global _unpack_dispatch_table
global xrange
# Compatibility mode for handling strings/bytes with the old specification
compatibility = False
if sys.version_info[0] == 3:
_utc_tzinfo = datetime.timezone.utc
else:
class UTC(datetime.tzinfo):
ZERO = datetime.timedelta(0)
def utcoffset(self, dt):
return UTC.ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return UTC.ZERO
_utc_tzinfo = UTC()
_utc_tzinfo = datetime.timezone.utc
# Calculate an aware epoch datetime
_epoch = datetime.datetime(1970, 1, 1, tzinfo=_utc_tzinfo)
@@ -1181,25 +991,14 @@ def __init():
_float_precision = "single"
# Map packb and unpackb to the appropriate version
if sys.version_info[0] == 3:
pack = _pack3
packb = _packb3
dump = _pack3
dumps = _packb3
unpack = _unpack3
unpackb = _unpackb3
load = _unpack3
loads = _unpackb3
xrange = range
else:
pack = _pack2
packb = _packb2
dump = _pack2
dumps = _packb2
unpack = _unpack2
unpackb = _unpackb2
load = _unpack2
loads = _unpackb2
pack = _pack3
packb = _packb3
dump = _pack3
dumps = _packb3
unpack = _unpack3
unpackb = _unpackb3
load = _unpack3
loads = _unpackb3
# Build a dispatch table for fast lookup of unpacking function
+537
View File
@@ -0,0 +1,537 @@
# validate.py
# -*- coding: utf-8 -*-
# pylint: disable=
#
# A Validator object.
#
# Copyright (C) 2005-2014:
# (name) : (email)
# Michael Foord: fuzzyman AT voidspace DOT org DOT uk
# Mark Andrews: mark AT la-la DOT com
# Nicola Larosa: nico AT tekNico DOT net
# Rob Dennis: rdennis AT gmail DOT com
# Eli Courtwright: eli AT courtwright DOT org
# This software is licensed under the terms of the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
# ConfigObj 5 - main repository for documentation and issue tracking:
# https://github.com/DiffSK/configobj
import re
import sys
from pprint import pprint
__version__ = '1.0.1'
__all__ = (
'dottedQuadToNum',
'numToDottedQuad',
'ValidateError',
'VdtUnknownCheckError',
'VdtParamError',
'VdtTypeError',
'VdtValueError',
'VdtValueTooSmallError',
'VdtValueTooBigError',
'VdtValueTooShortError',
'VdtValueTooLongError',
'VdtMissingValue',
'Validator',
'is_integer',
'is_float',
'is_boolean',
'is_list',
'is_tuple',
'is_ip_addr',
'is_string',
'is_int_list',
'is_bool_list',
'is_float_list',
'is_string_list',
'is_ip_addr_list',
'is_mixed_list',
'is_option',
)
_list_arg = re.compile(r'''
(?:
([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*list\(
(
(?:
\s*
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s\)][^,\)]*?) # unquoted
)
\s*,\s*
)*
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s\)][^,\)]*?) # unquoted
)? # last one
)
\)
)
''', re.VERBOSE | re.DOTALL) # two groups
_list_members = re.compile(r'''
(
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s=][^,=]*?) # unquoted
)
(?:
(?:\s*,\s*)|(?:\s*$) # comma
)
''', re.VERBOSE | re.DOTALL) # one group
_paramstring = r'''
(?:
(
(?:
[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*list\(
(?:
\s*
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s\)][^,\)]*?) # unquoted
)
\s*,\s*
)*
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s\)][^,\)]*?) # unquoted
)? # last one
\)
)|
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s=][^,=]*?)| # unquoted
(?: # keyword argument
[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*
(?:
(?:".*?")| # double quotes
(?:'.*?')| # single quotes
(?:[^'",\s=][^,=]*?) # unquoted
)
)
)
)
(?:
(?:\s*,\s*)|(?:\s*$) # comma
)
)
'''
_matchstring = '^%s*' % _paramstring
def dottedQuadToNum(ip):
# import here to avoid it when ip_addr values are not used
import socket, struct
try:
return struct.unpack('!L',
socket.inet_aton(ip.strip()))[0]
except socket.error:
raise ValueError('Not a good dotted-quad IP: %s' % ip)
return
def numToDottedQuad(num):
# import here to avoid it when ip_addr values are not used
import socket, struct
# no need to intercept here, 4294967295L is fine
if num > int(4294967295) or num < 0:
raise ValueError('Not a good numeric IP: %s' % num)
try:
return socket.inet_ntoa(
struct.pack('!L', int(num)))
except (socket.error, struct.error, OverflowError):
raise ValueError('Not a good numeric IP: %s' % num)
class ValidateError(Exception):
"""
This error indicates that the check failed.
It can be the base class for more specific errors.
"""
class VdtMissingValue(ValidateError):
"""No value was supplied to a check that needed one."""
class VdtUnknownCheckError(ValidateError):
def __init__(self, value):
ValidateError.__init__(self, 'the check "{}" is unknown.'.format(value))
class VdtParamError(SyntaxError):
NOT_GIVEN = object()
def __init__(self, name_or_msg, value=NOT_GIVEN):
if value is self.NOT_GIVEN:
SyntaxError.__init__(self, name_or_msg)
else:
SyntaxError.__init__(self, 'passed an incorrect value "{}" for parameter "{}".'.format(value, name_or_msg))
class VdtTypeError(ValidateError):
def __init__(self, value):
ValidateError.__init__(self, 'the value "{}" is of the wrong type.'.format(value))
class VdtValueError(ValidateError):
def __init__(self, value):
ValidateError.__init__(self, 'the value "{}" is unacceptable.'.format(value))
class VdtValueTooSmallError(VdtValueError):
def __init__(self, value):
ValidateError.__init__(self, 'the value "{}" is too small.'.format(value))
class VdtValueTooBigError(VdtValueError):
def __init__(self, value):
ValidateError.__init__(self, 'the value "{}" is too big.'.format(value))
class VdtValueTooShortError(VdtValueError):
def __init__(self, value):
ValidateError.__init__(
self,
'the value "{}" is too short.'.format(value))
class VdtValueTooLongError(VdtValueError):
def __init__(self, value):
ValidateError.__init__(self, 'the value "{}" is too long.'.format(value))
class Validator(object):
# this regex does the initial parsing of the checks
_func_re = re.compile(r'([^\(\)]+?)\((.*)\)', re.DOTALL)
# this regex takes apart keyword arguments
_key_arg = re.compile(r'^([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.*)$', re.DOTALL)
# this regex finds keyword=list(....) type values
_list_arg = _list_arg
# this regex takes individual values out of lists - in one pass
_list_members = _list_members
# These regexes check a set of arguments for validity
# and then pull the members out
_paramfinder = re.compile(_paramstring, re.VERBOSE | re.DOTALL)
_matchfinder = re.compile(_matchstring, re.VERBOSE | re.DOTALL)
def __init__(self, functions=None):
self.functions = {
'': self._pass,
'integer': is_integer,
'float': is_float,
'boolean': is_boolean,
'ip_addr': is_ip_addr,
'string': is_string,
'list': is_list,
'tuple': is_tuple,
'int_list': is_int_list,
'float_list': is_float_list,
'bool_list': is_bool_list,
'ip_addr_list': is_ip_addr_list,
'string_list': is_string_list,
'mixed_list': is_mixed_list,
'pass': self._pass,
'option': is_option,
'force_list': force_list,
}
if functions is not None:
self.functions.update(functions)
# tekNico: for use by ConfigObj
self.baseErrorClass = ValidateError
self._cache = {}
def check(self, check, value, missing=False):
fun_name, fun_args, fun_kwargs, default = self._parse_with_caching(check)
if missing:
if default is None:
# no information needed here - to be handled by caller
raise VdtMissingValue()
value = self._handle_none(default)
if value is None:
return None
return self._check_value(value, fun_name, fun_args, fun_kwargs)
def _handle_none(self, value):
if value == 'None':
return None
elif value in ("'None'", '"None"'):
# Special case a quoted None
value = self._unquote(value)
return value
def _parse_with_caching(self, check):
if check in self._cache:
fun_name, fun_args, fun_kwargs, default = self._cache[check]
# We call list and dict below to work with *copies* of the data
# rather than the original (which are mutable of course)
fun_args = list(fun_args)
fun_kwargs = dict(fun_kwargs)
else:
fun_name, fun_args, fun_kwargs, default = self._parse_check(check)
fun_kwargs = {str(key): value for (key, value) in list(fun_kwargs.items())}
self._cache[check] = fun_name, list(fun_args), dict(fun_kwargs), default
return fun_name, fun_args, fun_kwargs, default
def _check_value(self, value, fun_name, fun_args, fun_kwargs):
try:
fun = self.functions[fun_name]
except KeyError:
raise VdtUnknownCheckError(fun_name)
else:
return fun(value, *fun_args, **fun_kwargs)
def _parse_check(self, check):
fun_match = self._func_re.match(check)
if fun_match:
fun_name = fun_match.group(1)
arg_string = fun_match.group(2)
arg_match = self._matchfinder.match(arg_string)
if arg_match is None:
# Bad syntax
raise VdtParamError('Bad syntax in check "%s".' % check)
fun_args = []
fun_kwargs = {}
# pull out args of group 2
for arg in self._paramfinder.findall(arg_string):
# args may need whitespace removing (before removing quotes)
arg = arg.strip()
listmatch = self._list_arg.match(arg)
if listmatch:
key, val = self._list_handle(listmatch)
fun_kwargs[key] = val
continue
keymatch = self._key_arg.match(arg)
if keymatch:
val = keymatch.group(2)
if not val in ("'None'", '"None"'):
# Special case a quoted None
val = self._unquote(val)
fun_kwargs[keymatch.group(1)] = val
continue
fun_args.append(self._unquote(arg))
else:
# allows for function names without (args)
return check, (), {}, None
# Default must be deleted if the value is specified too,
# otherwise the check function will get a spurious "default" keyword arg
default = fun_kwargs.pop('default', None)
return fun_name, fun_args, fun_kwargs, default
def _unquote(self, val):
if (len(val) >= 2) and (val[0] in ("'", '"')) and (val[0] == val[-1]):
val = val[1:-1]
return val
def _list_handle(self, listmatch):
out = []
name = listmatch.group(1)
args = listmatch.group(2)
for arg in self._list_members.findall(args):
out.append(self._unquote(arg))
return name, out
def _pass(self, value):
return value
def get_default_value(self, check):
fun_name, fun_args, fun_kwargs, default = self._parse_with_caching(check)
if default is None:
raise KeyError('Check "%s" has no default value.' % check)
value = self._handle_none(default)
if value is None:
return value
return self._check_value(value, fun_name, fun_args, fun_kwargs)
def _is_num_param(names, values, to_float=False):
fun = to_float and float or int
out_params = []
for (name, val) in zip(names, values):
if val is None:
out_params.append(val)
elif isinstance(val, (int, float, str)):
try:
out_params.append(fun(val))
except ValueError:
raise VdtParamError(name, val)
else:
raise VdtParamError(name, val)
return out_params
# built in checks
# you can override these by setting the appropriate name
# in Validator.functions
# note: if the params are specified wrongly in your input string,
# you will also raise errors.
def is_integer(value, min=None, max=None):
(min_val, max_val) = _is_num_param( # pylint: disable=unbalanced-tuple-unpacking
('min', 'max'), (min, max))
if not isinstance(value, (int, str)):
raise VdtTypeError(value)
if isinstance(value, str):
# if it's a string - does it represent an integer ?
try:
value = int(value)
except ValueError:
raise VdtTypeError(value)
if (min_val is not None) and (value < min_val):
raise VdtValueTooSmallError(value)
if (max_val is not None) and (value > max_val):
raise VdtValueTooBigError(value)
return value
def is_float(value, min=None, max=None):
(min_val, max_val) = _is_num_param(
('min', 'max'), (min, max), to_float=True)
if not isinstance(value, (int, float, str)):
raise VdtTypeError(value)
if not isinstance(value, float):
# if it's a string - does it represent a float ?
try:
value = float(value)
except ValueError:
raise VdtTypeError(value)
if (min_val is not None) and (value < min_val):
raise VdtValueTooSmallError(value)
if (max_val is not None) and (value > max_val):
raise VdtValueTooBigError(value)
return value
bool_dict = {
True: True, 'on': True, '1': True, 'true': True, 'yes': True,
False: False, 'off': False, '0': False, 'false': False, 'no': False,
}
def is_boolean(value):
if isinstance(value, str):
try:
return bool_dict[value.lower()]
except KeyError:
raise VdtTypeError(value)
# we do an equality test rather than an identity test
# this ensures Python 2.2 compatibility
# and allows 0 and 1 to represent True and False
if value == False:
return False
elif value == True:
return True
else:
raise VdtTypeError(value)
def is_ip_addr(value):
if not isinstance(value, str):
raise VdtTypeError(value)
value = value.strip()
try:
dottedQuadToNum(value)
except ValueError:
raise VdtValueError(value)
return value
def is_list(value, min=None, max=None):
(min_len, max_len) = _is_num_param( # pylint: disable=unbalanced-tuple-unpacking
('min', 'max'), (min, max))
if isinstance(value, str):
raise VdtTypeError(value)
try:
num_members = len(value)
except TypeError:
raise VdtTypeError(value)
if min_len is not None and num_members < min_len:
raise VdtValueTooShortError(value)
if max_len is not None and num_members > max_len:
raise VdtValueTooLongError(value)
return list(value)
def is_tuple(value, min=None, max=None):
return tuple(is_list(value, min, max))
def is_string(value, min=None, max=None):
if not isinstance(value, str):
raise VdtTypeError(value)
(min_len, max_len) = _is_num_param(
('min', 'max'), (min, max))
try:
num_members = len(value)
except TypeError:
raise VdtTypeError(value)
if min_len is not None and num_members < min_len:
raise VdtValueTooShortError(value)
if max_len is not None and num_members > max_len:
raise VdtValueTooLongError(value)
return value
def is_int_list(value, min=None, max=None):
return [is_integer(mem) for mem in is_list(value, min, max)]
def is_bool_list(value, min=None, max=None):
return [is_boolean(mem) for mem in is_list(value, min, max)]
def is_float_list(value, min=None, max=None):
return [is_float(mem) for mem in is_list(value, min, max)]
def is_string_list(value, min=None, max=None):
if isinstance(value, str):
raise VdtTypeError(value)
return [is_string(mem) for mem in is_list(value, min, max)]
def is_ip_addr_list(value, min=None, max=None):
return [is_ip_addr(mem) for mem in is_list(value, min, max)]
def force_list(value, min=None, max=None):
if not isinstance(value, (list, tuple)):
value = [value]
return is_list(value, min, max)
fun_dict = {
int: is_integer,
'int': is_integer,
'integer': is_integer,
float: is_float,
'float': is_float,
'ip_addr': is_ip_addr,
str: is_string,
'str': is_string,
'string': is_string,
bool: is_boolean,
'bool': is_boolean,
'boolean': is_boolean,
}
def is_mixed_list(value, *args):
try: length = len(value)
except TypeError: raise VdtTypeError(value)
if length < len(args): raise VdtValueTooShortError(value)
elif length > len(args): raise VdtValueTooLongError(value)
try: return [fun_dict[arg](val) for arg, val in zip(args, value)]
except KeyError as cause: raise VdtParamError('mixed_list', cause)
def is_option(value, *options):
if not isinstance(value, str): raise VdtTypeError(value)
if not value in options: raise VdtValueError(value)
return value
+68
View File
@@ -0,0 +1,68 @@
Recently, and mostly from people who I've never seen before, the opinions about how this project should be run has started flooding in again. In a recent forum thread of such opinions, specifically about:
- The decision to no longer mirror release notes on GitHub.
- Some people feeling there were too many "barriers to entry" to joining RNS development.
- The project not really being "open source" because random strangers couldn't just "contribute".
Joakim posted some very relevant observations about how Reticulum operates, along with the following quote:
> The modern industrial system has a built-in tendency to grow; it cannot really work unless it is growing. The word “stability” has been struck from its dictionary and replaced by “stagnation”. Its continuous growth pursues no particular aims or objectives: it is growth for the sake of growing. No one even enquires after its final shape. There is none; there is no “saturation point”.
That E. F. Schumacher quote perfectly illustrates the ontological schism that makes it so tiresome to deal with stuff like this.
There is, in this day and age, between different people, widely different base conceptual integrations of what "open source" means. For many people, "open source" has become synonymous **not** with skilled people working together in a coordinated and careful way on complex engineering challenges, but a sort of growth- and attention-focused "free-for-all" *behavioral* codex that must be followed above all else; a *social* modus operandi of fake inclusivity where everyone "should have their voice heard", and adherence to that specific process is weighed much higher than the final results.
I do not subscribe to, and consequently do not operate the Reticulum project under *any* versions of that idea.
**Here's the statistical, boring reality:**
- Around 90% of pull requests and "recommendations" I received when people could just submit stuff via GitHub would
have *severely* broken things, introduced bugs or security issues, created roadblocks for future work, or otherwise
damaged the software. Usually just for the sake of satisfying a random newcomers "idea" or personal preference.
- Similarly, around 90% "bug reports" were actually people asking for help, because of having failed to read even the
most basic parts of the documentation.
- The people with the least amount of understanding, skill and effort invested tend to be loudest and most vocal. When
all you have is "opinions", those are iterated upon ad infinitum, apparently.
Can you imagine how much time that wasted? Can you imagine what we could have accomplished with that time instead?
The only thing that this creates is *noise* and confusion. Clogging up the mental and physical workspaces, of people who are actually investing time and effort on the project with stuff like that is objectively just taking time that could have been used on development, and replacing it with *nothing*.
I was receiving *actual* bug reports, pull requests, proper technical investigations and patches via methods outside GitHub and "public" internet-based channels *way* before GitHub interaction and similar was closed down. That was were almost *all* of the real contributions were coming from, anyway. Apparently, and not unsurprisingly, the people who has invested the time and effort to understand Reticulum also prefer to collaborate in this way. Since leaving the GitHub madhouse behind, the signal-to-noise ratio has **significantly** increased.
Managing a public "issue" tracker with global read/write access is a futile and useless endeavor. Consider this:
- User A reports a "bug" that is really just a failure of understanding.
- User B sees this and seconds is, proposing a "fix" that in continued failure of understanding would actually break functionality X.
- User C joins the bandwagon and asks why this hasn't already been implemented like that? It's obvious!
The sensible response here from the developer is closing the issue with "No. Go RTFM". Today, though, this usually results in hurt feelings, animosity towards the developer and in some cases (as experienced and documented in the case of RNS), months of perfidious personal vendetta against the developer for being so brazen as to suggest the user was wrong and wasting people's time.
When this pattern repeats, over and over, the only sensible, measured and constructive course of action is to shrug your shoulders and say:
*"This system is fundamentally broken. It ain't working. I can give up here, or I can go build something better that has a chance of working."*
So, now it's your turn. Go look at the diffs for the last six months. What does it look like I have been doing?
But I will be damned straight with you all, and say that part of that solution is **absolutely** to erect barriers to entry. You can fucking bet your arse on that. I don't want opinionated man-babies running around in my living-room at 3am. I don't want to clean up the floor after a wannabe "dev-ops stars" with LLMs and a peripheral case of influencitis has puked all over the office.
- If you want to join the fun of changing core networking code that thousands of people rely on for communication
daily, you better know what the fuck you're doing.
- I'm not here to provide validation and hugs to random strangers. I'm here to make sure the reference implementation
of Reticulum works.
- If you cannot figure out how to submit a patch or valid bug investigation over RNS, you cannot expect I will take
you seriously. At all.
If someone can't handle that, they should find their entertainment elsewhere.
I've said it before: I've provided the information and code required to make Reticulum *work*, and build networked systems, protocols and applications on top of it. That information is deep, complex, and requires you to read hundreds of pages, and put in weeks of efforts to get the *full* picture. A lot less is required to get started, but it *will* still be a steep learning experience.
This is a full networking stack, based on some pretty complex principles, for crying out loud. It's **not** a `hello_world` designed to make you feel good about yourself. It turns almost everything you know about networked systems on its head. That's **challenging** for *anyone*. Climb the mountain, and it will be satisfying in the end. Refuse to climb... Well, what do you think will happen?
As for barriers to entry of *using* RNS and related programs, utilities and clients, it's not my task to teach every single user how to do X, Y and Z. The information *is* out there. If it wasn't organized optimally for your way of learning, you can choose to "raise your concerns" about it, discuss "the fact of it" on a forum or chatroom, or: *You can choose to remedy that, and help others along*.
I sure know what *I* would have done.
+7
View File
@@ -35,3 +35,10 @@ help:
cp -r build/epub/ReticulumNetworkStack.epub ./Reticulum\ Manual.epub; \
echo "EPUB Manual Generated"; \
fi
@if [ $@ = "markdown" ]; then \
rm -rf markdown; \
cp -r build/markdown ./; \
./clean_md.py ./markdown \
echo "Markdown Manual Generated"; \
fi
Binary file not shown.
Binary file not shown.
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
import os
import sys
import re
from pathlib import Path
LINE_START_PATTERNS = [
r'<a\s+', # HTML anchor tags: <a id="..."></a>
r'\\\\newpage', # LaTeX newpage commands
]
LINE_ANY_PATTERNS = [
# r'<br/>',
# r'<div[^>]*>',
# r'</div>',
]
def compile_patterns():
start_patterns = [re.compile(p) for p in LINE_START_PATTERNS]
any_patterns = [re.compile(p) for p in LINE_ANY_PATTERNS]
return start_patterns, any_patterns
def should_remove_line(line, start_patterns, any_patterns):
stripped = line.strip()
for pattern in start_patterns:
if pattern.match(stripped):
return True
for pattern in any_patterns:
if pattern.search(stripped):
return True
return False
def clean_markdown_content(content, start_patterns, any_patterns, api_ref=False):
content = content.replace("**\n : ", "**\n ")
content = content.replace("\n* **", "\n\n* **")
content = content.replace("\n\n\n", "\n\n")
lines = content.split('\n')
result = []
skip_next_empty = False
for i, line in enumerate(lines):
if should_remove_line(line, start_patterns, any_patterns):
skip_next_empty = True
continue
if skip_next_empty:
if line.strip() == '': continue
else: skip_next_empty = False
if api_ref:
if line.startswith("### ") or line.startswith("#### "):
line = line.replace("*", "")
line = line.replace("\\_", "_")
if line.startswith("### "): line = line.replace("### ", "### `")
if line.startswith("#### "): line = line.replace("#### ", "#### `")
line = f"{line}`"
line = line.replace("<br/>", "")
result.append(line)
# Remove trailing empty lines from end of file
while result and result[-1].strip() == '':
result.pop()
return '\n'.join(result)
def process_file(filepath, start_patterns, any_patterns):
try:
with open(filepath, 'r', encoding='utf-8') as f:
original_content = f.read()
api_ref = str(filepath) == "markdown/reference.md"
cleaned_content = clean_markdown_content(original_content, start_patterns, any_patterns, api_ref=api_ref)
if cleaned_content != original_content:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(cleaned_content)
return True
return False
except Exception as e:
print(f"Error processing {filepath}: {e}", file=sys.stderr)
return False
def find_markdown_files(directory):
md_files = []
for root, _, files in os.walk(directory):
for filename in files:
if filename.endswith('.md'): md_files.append(Path(root) / filename)
return md_files
def main():
if len(sys.argv) < 2:
print("Usage: python clean_markdown.py <directory_path>", file=sys.stderr)
sys.exit(1)
directory = sys.argv[1]
if not os.path.isdir(directory):
print(f"Error: '{directory}' is not a valid directory", file=sys.stderr)
sys.exit(1)
start_patterns, any_patterns = compile_patterns()
md_files = find_markdown_files(directory)
if not md_files:
print(f"No markdown files found in '{directory}'")
return
modified_count = 0
for filepath in md_files:
if process_file(filepath, start_patterns, any_patterns):
print(f"Cleaned: {filepath}")
modified_count += 1
print(f"\nProcessed {len(md_files)} file(s), modified {modified_count}")
if __name__ == '__main__':
main()
+1 -1
View File
@@ -1,4 +1,4 @@
# 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.
config: ea8ffef16f1cae34d273c7bce7123529
config: a1cad1964a279ae382ed4c4412f7de41
tags: 645f666f9bcd5a90fca523b33c5a78b7
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

+148
View File
@@ -0,0 +1,148 @@
.. _distributed-development:
***********************
Distributed Development
***********************
This chapter of the manual provides the conceptual basis for understanding *why* ``rngit`` exists, what it aims to achieve, and the kinds of spaces it seeks to reestablish. For the practical details of operating the system, refer to the :ref:`Git Over Reticulum<git-main>` chapter.
The Original Architecture
=========================
When Torvalds created Git in 2005, he designed a tool that reflected a specific philosophy of collaboration. Every copy of a repository would be a complete, sovereign instance. There was no central server, no single point of failure, no gatekeeper. Developers would be able to work independently, exchange patches directly, and maintain their own branches indefinitely. This concept was - and is - both beautiful and revolutionary. It's execution is peer-to-peer not as a marketing term, but in the most foundational sense: As fundamental, structural reality.
Such a design emerged from necessity. The Linux kernel development process operated across geographical boundaries, time zones, and organizational affiliations. Contributors did not "log in" to a shared server to do their work; they maintained their own trees, and the flow of code between these trees was negotiated through patches, reviews, and merge decisions. The architecture of Git mirrored the social architecture of the community: Autonomous, competent, and fundamentally distributed in its technical operation.
*The result of that work is, in the most direct sense, what makes it possible for you to read this today.*
There's something very important to take note of here: With Git, developers could collaborate effectively and perfectly well without any central server being present, without platform-mediated visibility into each other's work, and without a centralized authority validating their contributions. They needed *only* a protocol for exchanging differences and a mechanism for verification of authorship. Everything else - social organization, quality control, release management - was handled by careful *human judgment* operating on top of the technical substrate.
What Git provided was not a development environment, but a **language for versioning**. It specified how to represent history, how to compute differences, how to merge divergent branches. It did not specify who could participate, how they should communicate, or what workflows they should follow. These were left to the competence and discretion of the creators using the system.
The Platform Interregnum
========================
What followed represents a very familiar pattern: Tools designed to distribute power were re-centralized by platforms that offered convenience in exchange for control. GitHub, GitLab, and similar services reintroduced the centralization that Git had eliminated architecturally. The activity feed replaced durable artifacts with ephemeral notifications. The social graph and open interaction became as important as the code itself, if not more.
This re-centralization was not technical, as such. It was **ontological**. When every developer pushes to the same server, when every merge is in theory controllable by a platform, when every issue is tracked in a database controlled by a corporation, the nature of collaboration changes. The platform, and its social dynamics, becomes the ground of reality. The platform mediates not just the technical exchange of information and the programmatics, but the social recognition and codices of contribution, the future archival prospects of the work, and the very identity of the project itself.
The consequences extend beyond individual inconvenience. Centralized platforms create single points of failure for entire ecosystem. When a platform changes its terms of service, suspends accounts, removes repositories or ceases operation, entire project histories and community relationships can be disrupted or destroyed. The extractive economics of platform capitalism mean that value created by open-source communities is captured by corporations, while communities remain dependent on infrastructure they do not control. And the surveillance inherent in platform operation means that every action - every commit, every comment, every page view - is logged, analyzed, and potentially monetized or weaponized.
More insidiously, platforms have completely reshaped the culture of development itself. They have created what we could call the **Teahouse Developer**: A participant who treats engineering projects as social venues for opinion-sharing rather than sites of disciplined and careful production. These personages have no actual stakes in the projects they act as leeches upon, and only a very base consciousness of the damage they are incurring in order to feed their attention and external validation dependencies.
When platforms optimize for engagement, when growth is the only metric, when every user with an opinion must have their voice heard, when a random social process is elevated to higher importance than results, the signal-to-noise ratio collapses catastrophically. Competent engineers find themselves drowning in feedback from the incompetent, managing the emotional needs and dysregulations of drive-by commentators rather than solving technical problems.
The platform model is predicated on **unsaturable expansion**. Like almost any industrial system, it cannot function without growth. It pursues no particular aims; it is growth for the sake of growing. There is no saturation point, no concept of "enough". Every barrier to entry must be put down to the very lowest common denominator, every voice must be amplified, every interaction must be converted into content that feeds the machine. This is fundamentally incompatible with the nature of social beings itself. It is also incompatible with serious engineering, which requires focus, discernment, and the right of people who know better to say "no".
Restoration
===========
The ``rngit`` system represents a return to Git's original architectural principles, fortified with cryptographic networking capabilities that were not available in 2005. The ``rngit`` system *is* Git - but running over Reticulum. Welcome back to a world where your work is your own, but where everyone can still reach you - if you want them to.
Just as Git eliminated the need for a central version control server, ``rngit`` eliminates the need for a central hosting platform, "servers" or any kinds of middle-men between the people actually doing the work. By operating over Reticulum, it eliminates the visibility of development activity to platform operators, network observers, state actors and other malicious third-parties.
In this model, the repository node is a **sovereign entity**. It is reachable from anywhere in the Reticulum network but owned, operated, and controlled by the developer or community that runs it. It is an actual home for creative output, not an extraction mechanism to which dues are paid. The node operator decides who may contribute, what standards must be met, and which voices are worth listening to. This is not exclusion; it is **discernment**. It is the necessary exercise of judgment that separates engineering from theatrics.
I did not create this in a fit of nostalgia. I created it because it is a necessary response to the failures of the centralized model. Git's technical architecture was - and *is* - correct. It was the social and economic superstructure built atop it that introduced fragility, exploitation, and environments toxic to actual creativity. By returning to first principles - distributed version control on distributed infrastructure - we recover not just a technical capability, but a mode of collaboration that respects the autonomy of individual developers and the sovereignty of actual communities.
Protocols Over Platforms
========================
The distinction between platforms and protocols is fundamental to understanding the architecture of sovereignty in networked systems. A platform is a service you access; a protocol is a grammar you speak; actions you live. A platform requires permission to enter, a protocol requires only *comprehension* to employ. A platform can change its rules, suspend your account, or cease operation entirely, a protocol persists as long as there are participants who *understand* and *use* it. A protocol is an *idea*, a platform is a machine that turns its users into products.
Platforms operate on a client-server model that inherently creates power asymmetry. Even when platforms are built atop open-source software, the operational instance remains a black box of corporate control. You *may* be able to download *some* of your data, but you cannot download the connections to the people that are the true value-base of the platform, or take them with you if you want to leave.
Protocols, by contrast, are agreements. They specify how systems should communicate, but not who may communicate or on what terms. Email is a protocol; Gmail is a platform. HTTP is a protocol; Facebook is a platform. Git is a protocol; GitHub is a platform. The protocol persists regardless of any particular implementation's success or failure.
The power of protocols lies in their **permissionlessness**. Anyone can implement a protocol without approval. Anyone can extend it, fork it, or use it for purposes unforeseen by its creators. This creates resilience: protocols cannot be easily censored, monopolized, or shut down because they exist as shared understanding rather than centralized infrastructure.
Reticulum is a protocol in this strict sense. It specifies how packets should be formatted, how paths should be discovered, how encryption should be applied. The ``rngit`` system extends this protocol approach to development workflows. It is not an external platform that hosts your repositories; it is a protocol for exchanging repository data, release artifacts, and work documents over Reticulum's encrypted transport. But with a few commands and an old computer, it creates your own infrastructure for hosting repositories, or sharing them with who you choose. *That* is how tools should function, in case we had forgotten.
Unlike platforms, which extract value by creating dependency, there is no entity that can grant or deny you the privilege of running ``rngit``. Your Reticulum identity is not endowed by any platform; it is generated locally and certified by its own cryptographic properties. Your repositories are hosted on nodes you control or nodes operated by communities you trust. Your relationships with other developers are peer-to-peer connections established through cryptographic addressing, not social graph connections managed by recommendation algorithms.
On a platform, exit means abandonment: you lose your history, your relationships, your visibility. With protocols, exit is just migration. When you change your infrastructure, your identity and your work travel with you. There are no middlemen between you and your collaborators. If push comes to shove, you can write your entire life's work and connections to an SD card, swim across the lake, and set up camp on the other side.
Sovereignty Through Infrastructure
==================================
The concept of sovereignty - supreme authority within a territory - has traditionally been applied to nation-states. But in an age where creative work is conducted through digital infrastructure, sovereignty is essential for individuals and communities. **Creative sovereignty** means having supreme authority over the artifacts you produce, the processes by which you produce them, and the terms under which they are distributed. It means not merely legal ownership of copyright, but operational control of the infrastructure that mediates creation, collaboration, and dissemination.
Centralized development platforms strip away most layers of sovereignty. When you host code on a corporate platform, you retain *some* legal ownership of copyright, but you surrender complete operational control. The platform decides what content is acceptable, who can access it, and how it is presented. They can delete your repository, suspend your account, or change the visibility of your work without consent. In reality, legal ownership becomes meaningless as operational control is ceded.
Running your own ``rngit`` node restores this sovereignty. You control the hardware, the network configuration, the backup strategies, and the access permissions. You decide what constitutes acceptable use, who may contribute, and how contributions are evaluated. Taking this responsibility on yourself is an assertion that your creative work is not a product to be harvested by platform economics, but an autonomous activity to be conducted on your own terms.
This sovereignty and responsibility extends to the entry barriers you establish. The ``rngit`` system allows you to configure access controls that filter participants based on cryptographic identity and demonstrated competence. If, for example, someone cannot navigate a command line, or use Reticulum to submit a patch, they most likely lack the required competence to modify your code. In a world that apparently labels this as "exclusion", I would simply refer to it as a minimally acceptable level of quality control.
Such a stance protects projects from the noise that so often overwhelms and completely dilutes platform-based development, where every user with an opinion believes themselves entitled to attention and access to the decision process.
Artifact-Centered Workflows
===========================
Contemporary platform-based development has shifted focus from durable artifacts to ephemeral *activity*. It does not matter what constitutes this activity, as long as it's there. The primary interface is not the repository itself, not the produced artifacts, but the activity feed: *Notifications* of commits, comments, pull requests, and social interactions. Work is measured by velocity, throughput, and the constant stream of updates. This activity-centric model creates constant urgency, discourages discernment, encourages reactive rather than reflective work patterns, and produces vast quantities of ephemeral and useless communication that obscures actual project state and productivity.
The ``rngit`` system enables a return to **artifact-centered workflows**, where the focus is on durable, attributable, versioned outputs rather than the stream of notifications surrounding them. The fundamental unit of work is the commit - signed, immutable records of change. The fundamental unit of production is the signed artifact - a self-verifying package of functionality. The fundamental unit of discussion is the work document - a structured, threaded conversation attached to repositories.
Artifacts can persist independently of any platform's continued operation. A commit signed with your Reticulum identity is attributable to you regardless of where it is stored. A release signed with your private key is verifiable as authentic regardless of which network it traverses, and can be verified offline on any system running Reticulum. The work exists as **cryptographic fact**, distributed over the planet, not as database entries in a corporate cloud.
Such a shift has real psychological consequences. When work is measured in artifacts rather than activity, the pace changes. There is no need for constant visibility, no pressure to perform busyness. Developers can work deeply, reflectively, and submit complete solutions rather than incremental updates designed to maintain presence in an activity feed. The work becomes **substantial**, in the physical sense of the word, rather than performative.
Composable Primitives
=====================
The ``rngit`` system is not a monolithic application prescribing a specific workflow; it is a collection of **composable primitives** that can be arranged to support diverse creative processes. Understanding these primitives as separate, orthogonal capabilities enables users to construct workflows suited to their specific needs and to recombine these primitives in ways unforeseen by the system's designers.
The core primitives include:
* **Repository Hosting**: Bare Git repositories served over Reticulum links, accessible via standard Git commands through the ``rns://`` URL scheme.
* **Identity-Based Access Control**: Fine-grained permissions managed through cryptographically verifiable identity hashes, configurable at the group, repository, or document level.
* **Release Distribution**: Cryptographically signed release artifacts with embedded provenance information, verifiable offline and distributable through any Reticulum or physical path.
* **Work Document Tracking**: Structured, threaded work management attached to repositories, with precise permission controls, and the ability to contain updates or discussions.
* **Forking and Mirroring**: Automated replication of repositories from any accessible Git URL, with metadata tracking upstream relationships for synchronization.
* **Nomad Network Integration**: Page node functionality for browsing repository contents, commit history, and release information through the Nomad Network protocol.
These primitives can be composed into workflows ranging from single-developer projects to complex multi-organizational collaborations. A solo developer might use only repository hosting and release distribution. A research group might add work document tracking for structured peer review. A software distribution network might combine mirroring with cryptographic release verification to create resilient update channels.
The entire system is incredibly light-weight, and can host hundreds of repositories on a Raspberry Pi.
Composability is essential because **creative work is diverse**. Software development, academic research, technical writing, hardware design, music production and data analysis all have different requirements for collaboration, review, and distribution. A platform prescribes a single workflow and forces all users to conform. A protocol provides primitives and allows users to construct workflows appropriate to their domain.
With ``rngit``, you can re-build the system into anything you can imagine. Everything can be modified, extended and hooked into. Adding functionality or automation is never further away than a shell script, a cron-job, or a Python modification of the source.
Distribution Without Intermediaries
===================================
Creating software is only part of the work. Then comes actually getting it to the people needing to use it. Centralized platforms handle distribution through their own infrastructure: Content delivery networks, central package registries, and download servers accessed through platform-controlled interfaces. This convenience masks a fundamental dependency: Your ability to distribute depends on the platform's continued operation, their policies regarding your content, and their technical infrastructure's reach.
The ``rngit`` release system enables distribution strategies **decoupled from any single infrastructure provider**. Releases are cryptographically signed using Ed25519 signatures and packaged in signed release manifests (``.rsm`` files). These manifests contain embedded signatures for each artifact. The manifest provides full verifiability of all release information, and contains embedded release artifact lists, per-file ``.rsg`` signatures, origin information, and the creator's Reticulum Identity. It can also be used to fetch verified updates of the software package over the network, and can always be verified completely offline.
Because releases are self-verifying, they can traverse any network or physical path that Reticulum can establish. A release can travel over LoRa radio, be carried on USB drives through areas without internet connectivity, disseminated over a mirror network, or be distributed through store-and-forward mechanisms on intermittent infrastructure. Recipients can verify authenticity regardless of how they obtained the files. This is particularly valuable in low-connectivity environments where Reticulum may be the only available communication channel.
The ``rngit release`` command provides tools for creating, publishing, fetching, and verifying releases. When fetching a release using an ``.rsm`` manifest, the system validates the manifest signature against the required Reticulum Identity, extracts the origin node and repository path, connects to the origin over Reticulum, retrieves the latest release manifest, and verifies each downloaded artifact against the signatures embedded in the manifest. If any verification fails, the fetch aborts, preventing installation of corrupted or tampered files.
This cryptographic verification replaces the trust model of platform distribution. Instead of trusting that a platform has not been compromised, users verify that artifacts match the signatures created by the developer's identity. It doesn't matter *how* they obtained the artifacts, they can **always** be verified. This security model shifts from **institutional trust** (just believe in the goodness of the platform) to **cryptographic proof** (verify the signatures).
Long Archive
============
Software development is often conceived as an activity of the present only: Solving today's problems, meeting current deadlines, responding to immediate feedback. But the artifacts produced - code, documentation, releases - have lifespans extending *far* beyond their creation. They may be used for decades, studied by future developers, depended upon by systems not yet imagined, or preserved as historical records of technological development.
The ``rngit`` system is designed with this **extended timeframe** in mind, supporting the creation of archives that are durable, portable, and intelligible across generational timescales. Git repositories are always internally complete; they contain full history and can be migrated to new infrastructure without loss of information. Everything that ``rngit`` adds on top of this is stored in normal files in standard formats right next to the Git repository folders, not an esoteric database-cluster two thousand kilometers away. Because releases are cryptographically signed, they remain verifiable as authentic regardless of when or where they are retrieved. Because the system operates over Reticulum, it can function over communication mediums that may outlast the internet as we know it.
This long-term perspective influences technical decisions. The use of well-established cryptographic primitives ensures that signatures will remain verifiable for centuries. The use of standard formats ensures that repositories will remain readable by future tools. The protocol-based architecture ensures that the system can evolve without losing compatibility with existing data.
For critical infrastructure, this archival durability is not optional; it is essential. Communication systems, cryptographic libraries, and safety-critical code must remain available and verifiable for the lifespans of the systems that depend on them. The ``rngit`` system provides the tools to create such archives: distributed across multiple nodes, cryptographically verified, and independent of any corporate or governmental infrastructure, which as history has shown repeatedly, does *not* persist.
Start Of The Road
=================
Distributed development and production over Reticulum is a *different mode of existence* for creative work. It restores the autonomy originally created by Git. It provides local sovereignty over production infrastructure, composability of workflow, and durability of artifact. It lets you filter participation through competence and cryptography rather than incentives of platform operators, raising the quality and enjoyment of work, and protecting the focus of real engineering and creative expression.
This is not a system for everyone, and that is the point. It requires investment - in understanding Reticulum, in configuring infrastructure, in establishing workflows. It requires accepting responsibility for your own tools rather than delegating them to platform operators. It requires the discipline to maintain your own node, manage your own backups, and nurture your own community.
But for those who make this investment, the returns are substantial. You gain **immunity from platform failure**; your work persists regardless of corporate decisions or service outages. You gain **shelter from surveillance**; your development activity is visible only to those that *you* choose to involve. You gain **control over process**; you decide how work is conducted, reviewed, and released, unmediated by terms of service, algorithmic feeds and thousands of uninformed and irrelevant opinions.
Most importantly, though, you regain the **dignity of craft**. Development becomes an activity conducted among peers, equals among equals, mediated by skill and cryptographic proof rather than corporate permission, producing artifacts that stand as independent testimony to competence, functionality or beauty rather than as content feeding engagement metrics. The *work* becomes the point. The artifacts become durable. And the network becomes *one* of the tools you wield in this endeavor.
+11 -28
View File
@@ -4,18 +4,14 @@
Code Examples
*************
A number of examples are included in the source distribution of Reticulum.
You can use these examples to learn how to write your own programs.
A number of examples are included in the source distribution of Reticulum. You can use these examples to learn how to write your own programs.
.. _example-minimal:
Minimal
=======
The *Minimal* example demonstrates the bare-minimum setup required to connect to
a Reticulum network from your program. In about five lines of code, you will
have the Reticulum Network Stack initialised, and ready to pass traffic in your
program.
The *Minimal* example demonstrates the bare-minimum setup required to connect to a Reticulum network from your program. In about five lines of code, you will have the Reticulum Network Stack initialised, and ready to pass traffic in your program.
.. literalinclude:: ../../Examples/Minimal.py
@@ -26,9 +22,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Announce
========
The *Announce* example builds upon the previous example by exploring how to
announce a destination on the network, and how to let your program receive
notifications about announces from relevant destinations.
The *Announce* example builds upon the previous example by exploring how to announce a destination on the network, and how to let your program receive notifications about announces from relevant destinations.
.. literalinclude:: ../../Examples/Announce.py
@@ -38,8 +32,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Broadcast
=========
The *Broadcast* example explores how to transmit plaintext broadcast messages
over the network.
The *Broadcast* example explores how to transmit plaintext broadcast messages over the network.
.. literalinclude:: ../../Examples/Broadcast.py
@@ -50,8 +43,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Echo
====
The *Echo* example demonstrates communication between two destinations using
the Packet interface.
The *Echo* example demonstrates communication between two destinations using the Packet interface.
.. literalinclude:: ../../Examples/Echo.py
@@ -62,8 +54,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Link
====
The *Link* example explores establishing an encrypted link to a remote
destination, and passing traffic back and forth over the link.
The *Link* example explores establishing an encrypted link to a remote destination, and passing traffic back and forth over the link.
.. literalinclude:: ../../Examples/Link.py
@@ -74,8 +65,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Identification
==============
The *Identify* example explores identifying an intiator of a link, once
the link has been established.
The *Identify* example explores identifying an intiator of a link, once the link has been established.
.. literalinclude:: ../../Examples/Identify.py
@@ -97,8 +87,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Channel
=======
The *Channel* example explores using a ``Channel`` to send structured
data between peers of a ``Link``.
The *Channel* example explores using a ``Channel`` to send structured data between peers of a ``Link``.
.. literalinclude:: ../../Examples/Channel.py
@@ -107,8 +96,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Buffer
======
The *Buffer* example explores using buffered readers and writers to send
binary data between peers of a ``Link``.
The *Buffer* example explores using buffered readers and writers to send binary data between peers of a ``Link``.
.. literalinclude:: ../../Examples/Buffer.py
@@ -119,9 +107,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Filetransfer
============
The *Filetransfer* example implements a basic file-server program that
allow clients to connect and download files. The program uses the Resource
interface to efficiently pass files of any size over a Reticulum :ref:`Link<api-link>`.
The *Filetransfer* example implements a basic file-server program that allow clients to connect and download files. The program uses the Resource interface to efficiently pass files of any size over a Reticulum :ref:`Link<api-link>`.
.. literalinclude:: ../../Examples/Filetransfer.py
@@ -132,10 +118,7 @@ This example can also be found at `<https://github.com/markqvist/Reticulum/blob/
Custom Interfaces
=================
The *ExampleInterface* demonstrates creating custom interfaces for Reticulum.
Any number of custom interfaces can be loaded and utilised by Reticulum, and
will be fully on-par with natively included interfaces, including all supported
:ref:`interface modes<interfaces-modes>` and :ref:`common configuration options<interfaces-options>`.
The *ExampleInterface* demonstrates creating custom interfaces for Reticulum. Any number of custom interfaces can be loaded and utilised by Reticulum, and will be fully on-par with natively included interfaces, including all supported :ref:`interface modes<interfaces-modes>` and :ref:`common configuration options<interfaces-options>`.
.. literalinclude:: ../../Examples/ExampleInterface.py
+99 -293
View File
@@ -2,51 +2,38 @@
Getting Started Fast
********************
The best way to get started with the Reticulum Network Stack depends on what
you want to do. This guide will outline sensible starting paths for different
scenarios.
The best way to get started with the Reticulum Network Stack depends on what you want to do. This guide will outline sensible starting paths for different scenarios.
Standalone Reticulum Installation
=================================
If you simply want to install Reticulum and related utilities on a system,
the easiest way is via the ``pip`` package manager:
If you simply want to install Reticulum and related utilities on a system, the easiest way is via the ``pip`` package manager:
.. code:: shell
pip install rns
If you do not already have pip installed, you can install it using the package manager
of your system with a command like ``sudo apt install python3-pip``,
``sudo pamac install python-pip`` or similar.
If you do not already have pip installed, you can install it using the package manager of your system with a command like ``sudo apt install python3-pip``, ``sudo pamac install python-pip`` or similar.
You can also dowload the Reticulum release wheels from GitHub, or other release channels,
and install them offline using ``pip``:
You can also dowload the Reticulum release wheels from GitHub, or other release channels, and install them offline using ``pip``:
.. code:: shell
pip install ./rns-1.1.2-py3-none-any.whl
On platforms that limit user package installation via ``pip``, you may need to manually
allow this using the ``--break-system-packages`` command line flag when installing. This
will not actually break any packages, unless you have installed Reticulum directly via
your operating system's package manager.
On platforms that limit user package installation via ``pip``, you may need to manually allow this using the ``--break-system-packages`` command line flag when installing. This will not actually break any packages, unless you have installed Reticulum directly via your operating system's package manager.
.. code:: shell
pip install rns --break-system-packages
For more detailed installation instructions, please see the
:ref:`Platform-Specific Install Notes<install-guides>` section.
For more detailed installation instructions, please see the :ref:`Platform-Specific Install Notes<install-guides>` section.
After installation is complete, it might be helpful to refer to the
:ref:`Using Reticulum on Your System<using-main>` chapter.
After installation is complete, it might be helpful to refer to the :ref:`Using Reticulum on Your System<using-main>` chapter.
Resolving Dependency & Installation Issues
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
On some platforms, there may not be binary packages available for all dependencies, and
``pip`` installation may fail with an error message. In these cases, the issue can usually
be resolved by installing the development essentials packages for your platform:
On some platforms, there may not be binary packages available for all dependencies, and ``pip`` installation may fail with an error message. In these cases, the issue can usually be resolved by installing the development essentials packages for your platform:
.. code:: shell
@@ -59,69 +46,38 @@ be resolved by installing the development essentials packages for your platform:
# Fedora
sudo dnf groupinstall "Development Tools" "Development Libraries"
With the base development packages installed, ``pip`` should be able to compile any missing
dependencies from source, and complete installation even on platforms that don't have pre-
compiled packages available.
With the base development packages installed, ``pip`` should be able to compile any missing dependencies from source, and complete installation even on platforms that don't have pre-compiled packages available.
Try Using a Reticulum-based Program
=============================================
===================================
If you simply want to try using a program built with Reticulum, a :ref:`range of different
programs <software-main>` exist that allow basic communication and a various other useful functions,
even over extremely low-bandwidth Reticulum networks.
If you simply want to try using a program built with Reticulum, a :ref:`range of different programs <software-main>` exist that allow basic communication and a various other useful functions, even over extremely low-bandwidth Reticulum networks.
Using the Included Utilities
=============================================
Reticulum comes with a range of included utilities that make it easier to
manage your network, check connectivity and make Reticulum available to other
programs on your system.
============================
Reticulum comes with a range of included utilities that make it easier to manage your network, check connectivity and make Reticulum available to other programs on your system.
You can use ``rnsd`` to run Reticulum as a background or foreground service,
and the ``rnstatus``, ``rnpath`` and ``rnprobe`` utilities to view and query
network status and connectivity.
You can use ``rnsd`` to run Reticulum as a background or foreground service, and the ``rnstatus``, ``rnpath`` and ``rnprobe`` utilities to view and query network status and connectivity.
To learn more about these utility programs, have a look at the
:ref:`Using Reticulum on Your System<using-main>` chapter of this manual.
To learn more about these utility programs, have a look at the :ref:`Using Reticulum on Your System<using-main>` chapter of this manual.
Creating a Network With Reticulum
=============================================
To create a network, you will need to specify one or more *interfaces* for
Reticulum to use. This is done in the Reticulum configuration file, which by
default is located at ``~/.reticulum/config``. You can get an example
configuration file with all options via ``rnsd --exampleconfig``.
=================================
To create a network, you will need to specify one or more *interfaces* for Reticulum to use. This is done in the Reticulum configuration file, which by default is located at ``~/.reticulum/config``. You can get an example configuration file with all options via ``rnsd --exampleconfig``.
When Reticulum is started for the first time, it will create a default
configuration file, with one active interface. This default interface uses
your existing Ethernet and WiFi networks (if any), and only allows you to
communicate with other Reticulum peers within your local broadcast domains.
When Reticulum is started for the first time, it will create a default configuration file, with one active interface. This default interface uses your existing Ethernet and WiFi networks (if any), and only allows you to communicate with other Reticulum peers within your local broadcast domains.
To communicate further, you will have to add one or more interfaces. The default
configuration includes a number of examples, ranging from using TCP over the
internet, to LoRa and Packet Radio interfaces.
To communicate further, you will have to add one or more interfaces. The default configuration includes a number of examples, ranging from using TCP over the internet, to LoRa and Packet Radio interfaces.
With Reticulum, you only need to configure what interfaces you want to communicate
over. There is no need to configure address spaces, subnets, routing tables,
or other things you might be used to from other network types.
With Reticulum, you only need to configure what interfaces you want to communicate over. There is no need to configure address spaces, subnets, routing tables, or other things you might be used to from other network types.
Once Reticulum knows which interfaces it should use, it will automatically
discover topography and configure transport of data to any destinations it
knows about.
Once Reticulum knows which interfaces it should use, it will automatically discover topography and configure transport of data to any destinations it knows about.
In situations where you already have an established WiFi or Ethernet network, and
many devices that want to utilise the same external Reticulum network paths (for example over
LoRa), it will often be sufficient to let one system act as a Reticulum gateway, by
adding any external interfaces to the configuration of this system, and then enabling transport on it. Any
other device on your local WiFi will then be able to connect to this wider Reticulum
network just using the default (:ref:`AutoInterface<interfaces-auto>`) configuration.
In situations where you already have an established WiFi or Ethernet network, and many devices that want to utilise the same external Reticulum network paths (for example over LoRa), it will often be sufficient to let one system act as a Reticulum gateway, by adding any external interfaces to the configuration of this system, and then enabling transport on it. Any other device on your local WiFi will then be able to connect to this wider Reticulum network just using the default (:ref:`AutoInterface<interfaces-auto>`) configuration.
Possibly, the examples in the config file are enough to get you started. If
you want more information, you can read the :ref:`Building Networks<networks-main>`
and :ref:`Interfaces<interfaces-main>` chapters of this manual, but most importantly,
start with reading the next section, :ref:`Bootstrapping Connectivity<bootstrapping-connectivity>`,
as this provides the most essential understanding of how to ensure reliable
connectivity with a minimum of maintenance.
Possibly, the examples in the config file are enough to get you started. If you want more information, you can read the :ref:`Building Networks<networks-main>` and :ref:`Interfaces<interfaces-main>` chapters of this manual, but most importantly, start with reading the next section, :ref:`Bootstrapping Connectivity<bootstrapping-connectivity>`, as this provides the most essential understanding of how to ensure reliable connectivity with a minimum of maintenance.
.. _bootstrapping-connectivity:
@@ -216,20 +172,13 @@ As a good starting point, you can find interface definitions for connecting your
Hosting Public Entrypoints
==========================
If you want to help build a strong global interconnection backbone, you can host a public (or private) entry-point to a Reticulum network over the
Internet. This section offers some helpful pointers. Once you have set up your public entrypoint, it is a great idea to :ref:`make it discoverable over Reticulum<interfaces-discoverable>`.
If you want to help build a strong global interconnection backbone, you can host a public (or private) entry-point to a Reticulum network over the Internet. This section offers some helpful pointers. Once you have set up your public entrypoint, it is a great idea to :ref:`make it discoverable over Reticulum<interfaces-discoverable>`.
You will need a machine, physical or virtual with a public IP address, that can be reached by other devices on the Internet.
The most efficient and performant way to host a connectable entry-point supporting many
users is to use the ``BackboneInterface``. This interface type is fully compatible with
the ``TCPClientInterface`` and ``TCPServerInterface`` types, but much faster and uses
less system resources, allowing your device to handle thousands of connections even on
small systems.
The most efficient and performant way to host a connectable entry-point supporting many users is to use the ``BackboneInterface``. This interface type is fully compatible with the ``TCPClientInterface`` and ``TCPServerInterface`` types, but much faster and uses less system resources, allowing your device to handle thousands of connections even on small systems.
It is also important to set your connectable interface to ``gateway`` mode, since this
will greatly improve network convergence time and path resolution for anyone connecting
to your entry-point.
It is also important to set your connectable interface to ``gateway`` mode, since this will greatly improve network convergence time and path resolution for anyone connecting to your entry-point.
.. code:: ini
@@ -244,15 +193,14 @@ to your entry-point.
listen_on = 0.0.0.0
port = 4242
# On publicly available interfaces, it can be
# a good idea to configure sensible announce
# On publicly available interfaces, it is
# essential to configure sensible announce
# rate targets.
announce_rate_target = 3600
announce_rate_penalty = 3600
announce_rate_grace = 12
announce_rate_grace = 6
If instead you want to make a private entry-point from the Internet, you can use the
:ref:`IFAC name and passphrase options<interfaces-options>` to secure your interface with a network name and passphrase.
If instead you want to make a private entry-point from the Internet, you can use the :ref:`IFAC name and passphrase options<interfaces-options>` to secure your interface with a network name and passphrase.
.. code:: ini
@@ -268,132 +216,79 @@ If instead you want to make a private entry-point from the Internet, you can use
network_name = private_ret
passphrase = 2owjajquafIanPecAc
If you are hosting an entry-point on an operating system that does not support
``BackboneInterface``, you can use ``TCPServerInterface`` instead, although it will
not be as performant.
If you are hosting an entry-point on an operating system that does not support ``BackboneInterface``, you can use ``TCPServerInterface`` instead, although it will not be as performant.
Connecting Reticulum Instances Over the Internet
================================================
Reticulum currently offers three interfaces suitable for connecting instances over the Internet: :ref:`Backbone<interfaces-backbone>`, :ref:`TCP<interfaces-tcps>`
and :ref:`I2P<interfaces-i2p>`. Each interface offers a different set of features, and Reticulum
users should carefully choose the interface which best suites their needs.
Reticulum currently offers three interfaces suitable for connecting instances over the Internet: :ref:`Backbone<interfaces-backbone>`, :ref:`TCP<interfaces-tcps>` and :ref:`I2P<interfaces-i2p>`. Each interface offers a different set of features, and Reticulum users should carefully choose the interface which best suites their needs.
The ``TCPServerInterface`` allows users to host an instance accessible over TCP/IP. This
method is generally faster, lower latency, and more energy efficient than using ``I2PInterface``,
however it also leaks more data about the server host.
The ``TCPServerInterface`` allows users to host an instance accessible over TCP/IP. This method is generally faster, lower latency, and more energy efficient than using ``I2PInterface``, however it also leaks more data about the server host.
The ``BackboneInterface`` is a very fast and efficient interface type available on POSIX operating
systems, designed to handle thousands of connections simultaneously with low memory, processing
and I/O overhead. It is fully compatible with the TCP-based interface types.
The ``BackboneInterface`` is a very fast and efficient interface type available on POSIX operating systems, designed to handle thousands of connections simultaneously with low memory, processing and I/O overhead. It is fully compatible with the TCP-based interface types.
TCP connections reveal the IP address of both your instance and the server to anyone who can
inspect the connection. Someone could use this information to determine your location or identity. Adversaries
inspecting your packets may be able to record packet metadata like time of transmission and packet size.
Even though Reticulum encrypts traffic, TCP does not, so an adversary may be able to use
packet inspection to learn that a system is running Reticulum, and what other IP addresses connect to it.
Hosting a publicly reachable instance over TCP also requires a publicly reachable IP address,
which most Internet connections don't offer anymore.
TCP connections reveal the IP address of both your instance and the server to anyone who can inspect the connection. Someone could use this information to determine your location or identity. Adversaries inspecting your packets may be able to record packet metadata like time of transmission and packet size. Even though Reticulum encrypts traffic, TCP does not, so an adversary may be able to use packet inspection to learn that a system is running Reticulum, and what other IP addresses connect to it. Hosting a publicly reachable instance over TCP also requires a publicly reachable IP address, which most Internet connections don't offer anymore.
The ``I2PInterface`` routes messages through the `Invisible Internet Protocol
(I2P) <https://geti2p.net/en/>`_. To use this interface, users must also run an I2P daemon in
parallel to ``rnsd``. For always-on I2P nodes it is recommended to use `i2pd <https://i2pd.website/>`_.
The ``I2PInterface`` routes messages through the `Invisible Internet Protocol (I2P) <https://geti2p.net/en/>`_. To use this interface, users must also run an I2P daemon in parallel to ``rnsd``. For always-on I2P nodes it is recommended to use `i2pd <https://i2pd.website/>`_.
By default, I2P will encrypt and mix all traffic sent over the Internet, and
hide both the sender and receiver Reticulum instance IP addresses. Running an I2P node
will also relay other I2P user's encrypted packets, which will use extra
bandwidth and compute power, but also makes timing attacks and other forms of
deep-packet-inspection much more difficult.
By default, I2P will encrypt and mix all traffic sent over the Internet, and hide both the sender and receiver Reticulum instance IP addresses. Running an I2P node will also relay other I2P user's encrypted packets, which will use extra bandwidth and compute power, but also makes timing attacks and other forms of deep-packet-inspection much more difficult.
I2P also allows users to host globally available Reticulum instances from non-public IP's and behind firewalls and NAT.
In general it is recommended to use an I2P node if you want to host a publicly accessible
instance, while preserving anonymity. If you care more about performance, and a slightly
easier setup, use TCP.
In general it is recommended to use an I2P node if you want to host a publicly accessible instance, while preserving anonymity. If you care more about performance, and a slightly easier setup, use TCP.
Adding Radio Interfaces
=======================
Once you have Reticulum installed and working, you can add radio interfaces with
any compatible hardware you have available. Reticulum supports a wide range of radio
hardware, and if you already have any available, it is very likely that it will
work with Reticulum. For information on how to configure this, see the
:ref:`Interfaces<interfaces-main>` section of this manual.
Once you have Reticulum installed and working, you can add radio interfaces with any compatible hardware you have available. Reticulum supports a wide range of radio hardware, and if you already have any available, it is very likely that it will work with Reticulum. For information on how to configure this, see the :ref:`Interfaces<interfaces-main>` section of this manual.
If you do not already have transceiver hardware available, you can easily and
cheaply build an :ref:`RNode<rnode-main>`, which is a general-purpose long-range
digital radio transceiver, that integrates easily with Reticulum.
If you do not already have transceiver hardware available, you can easily and cheaply build an :ref:`RNode<rnode-main>`, which is a general-purpose long-range digital radio transceiver, that integrates easily with Reticulum.
To build one yourself requires installing a custom firmware on a supported LoRa
development board with an auto-install script or web-based flasher.
Please see the :ref:`Communications Hardware<hardware-main>` chapter for a guide.
If you prefer purchasing a ready-made unit, you can refer to the
:ref:`list of suppliers<rnode-suppliers>`.
To build one yourself requires installing a custom firmware on a supported LoRa development board with an auto-install script or web-based flasher. Please see the :ref:`Communications Hardware<hardware-main>` chapter for a guide. If you prefer purchasing a ready-made unit, you can refer to the :ref:`list of suppliers<rnode-suppliers>`.
Other radio-based hardware interfaces are being developed and made available by
the broader Reticulum community. You can find more information on such topics
over Reticulum-based information sharing systems.
Other radio-based hardware interfaces are being developed and made available by the broader Reticulum community. You can find more information on such topics over Reticulum-based information sharing systems.
If you have communications hardware that is not already supported by any of the
:ref:`existing interface types<interfaces-main>`, it is easy to write (and potentially
publish) a :ref:`custom interface module<interfaces-custom>` that makes it compatible with Reticulum.
If you have communications hardware that is not already supported by any of the :ref:`existing interface types<interfaces-main>`, it is easy to write (and potentially publish) a :ref:`custom interface module<interfaces-custom>` that makes it compatible with Reticulum.
Creating and Using Custom Interfaces
====================================
While Reticulum includes a flexible and broad range of built-in interfaces, these
will not cover every conceivable type of communications hardware that Reticulum
can potentially use to communicate.
While Reticulum includes a flexible and broad range of built-in interfaces, these will not cover every conceivable type of communications hardware that Reticulum can potentially use to communicate.
It is therefore possible to easily write your own interface modules, that can be
loaded at run-time and used on-par with any of the built-in interface types.
It is therefore possible to easily write your own interface modules, that can be loaded at run-time and used on-par with any of the built-in interface types.
For more information on this subject, and code examples to build on, please see
the :ref:`Configuring Interfaces<interfaces-main>` chapter.
For more information on this subject, and code examples to build on, please see the :ref:`Configuring Interfaces<interfaces-main>` chapter.
Develop a Program with Reticulum
===========================================
If you want to develop programs that use Reticulum, the easiest way to get
started is to install the latest release of Reticulum via pip:
================================
If you want to develop programs that use Reticulum, the easiest way to get started is to install the latest release of Reticulum via pip:
.. code::
pip install rns
The above command will install Reticulum and dependencies, and you will be
ready to import and use RNS in your own programs. The next step will most
likely be to look at some :ref:`Example Programs<examples-main>`.
The above command will install Reticulum and dependencies, and you will be ready to import and use RNS in your own programs. The next step will most likely be to look at some :ref:`Example Programs<examples-main>`.
The entire Reticulum API is documented in the :ref:`API Reference<api-main>`
chapter of this manual. Before diving in, it's probably a good idea to read
this manual in full, but at least start with the :ref:`Understanding Reticulum<understanding-main>` chapter.
The entire Reticulum API is documented in the :ref:`API Reference<api-main>` chapter of this manual. Before diving in, it's probably a good idea to read this manual in full, but at least start with the :ref:`Understanding Reticulum<understanding-main>` chapter.
.. _install-guides:
Platform-Specific Install Notes
==============================================
===============================
Some platforms require a slightly different installation procedure, or have
various quirks that are worth being aware of. These are listed here.
Some platforms require a slightly different installation procedure, or have various quirks that are worth being aware of. These are listed here.
Android
^^^^^^^^^^^^^^^^^^^^^^^^
Reticulum can be used on Android in different ways. The easiest way to get
started is using an app like `Sideband <https://unsigned.io/sideband>`_.
^^^^^^^
Reticulum can be used on Android in different ways. The easiest way to get started is using an app like `Sideband <https://unsigned.io/sideband>`_.
For more control and features, you can use Reticulum and related programs via
the `Termux app <https://termux.com/>`_, at the time of writing available on
`F-droid <https://f-droid.org>`_.
For more control and features, you can use Reticulum and related programs via the `Termux app <https://termux.com/>`_, at the time of writing available on `F-droid <https://f-droid.org>`_.
Termux is a terminal emulator and Linux environment for Android based devices,
which includes the ability to use many different programs and libraries,
including Reticulum.
Termux is a terminal emulator and Linux environment for Android based devices, which includes the ability to use many different programs and libraries, including Reticulum.
To use Reticulum within the Termux environment, you will need to install
``python`` and the ``python-cryptography`` library using ``pkg``, the package-manager
build into Termux. After that, you can use ``pip`` to install Reticulum.
To use Reticulum within the Termux environment, you will need to install ``python`` and the ``python-cryptography`` library using ``pkg``, the package-manager build into Termux. After that, you can use ``pip`` to install Reticulum.
From within Termux, execute the following:
@@ -412,9 +307,7 @@ From within Termux, execute the following:
# Install Reticulum
pip install rns
If for some reason the ``python-cryptography`` package is not available for
your platform via the Termux package manager, you can attempt to build it
locally on your device using the following command:
If for some reason the ``python-cryptography`` package is not available for your platform via the Termux package manager, you can attempt to build it locally on your device using the following command:
.. code:: shell
@@ -441,16 +334,12 @@ locally on your device using the following command:
# Reticulum and any related software
pip install rns
It is also possible to include Reticulum in apps compiled and distributed as
Android APKs. A detailed tutorial and example source code will be included
here at a later point. Until then you can use the `Sideband source code <https://github.com/markqvist/sideband>`_ as an example and starting point.
It is also possible to include Reticulum in apps compiled and distributed as Android APKs. A detailed tutorial and example source code will be included here at a later point. Until then you can use the `Sideband source code <https://github.com/markqvist/sideband>`_ as an example and starting point.
ARM64
^^^^^^^^^^^^^^^^^^^^^^^^
On some architectures, including ARM64, not all dependencies have precompiled
binaries. On such systems, you may need to install ``python3-dev`` (or similar) before
installing Reticulum or programs that depend on Reticulum.
^^^^^
On some architectures, including ARM64, not all dependencies have precompiled binaries. On such systems, you may need to install ``python3-dev`` (or similar) before installing Reticulum or programs that depend on Reticulum.
.. code:: shell
@@ -466,12 +355,8 @@ on your system locally.
Debian Bookworm
^^^^^^^^^^^^^^^^^^^^^^^^
On versions of Debian released after April 2023, it is no longer possible by default
to use ``pip`` to install packages onto your system. Unfortunately, you will need to
use the replacement ``pipx`` command instead, which places installed packages in an
isolated environment. This should not negatively affect Reticulum, but will not work
for including and using Reticulum in your own scripts and programs.
^^^^^^^^^^^^^^^
On versions of Debian released after April 2023, it is no longer possible by default to use ``pip`` to install packages onto your system. Unfortunately, you will need to use the replacement ``pipx`` command instead, which places installed packages in an isolated environment. This should not negatively affect Reticulum, but will not work for including and using Reticulum in your own scripts and programs.
.. code:: shell
@@ -484,42 +369,30 @@ for including and using Reticulum in your own scripts and programs.
# Install Reticulum
pipx install rns
Alternatively, you can restore normal behaviour to ``pip`` by creating or editing
the configuration file located at ``~/.config/pip/pip.conf``, and adding the
following section:
Alternatively, you can restore normal behaviour to ``pip`` by creating or editing the configuration file located at ``~/.config/pip/pip.conf``, and adding the following section:
.. code:: ini
[global]
break-system-packages = true
For a one-shot installation of Reticulum, without globally enabling the ``break-system-packages``
option, you can use the following command:
For a one-shot installation of Reticulum, without globally enabling the ``break-system-packages`` option, you can use the following command:
.. code:: shell
pip install rns --break-system-packages
.. note::
The ``--break-system-packages`` directive is a somewhat misleading choice
of words. Setting it will of course not break any system packages, but will simply
allow installing ``pip`` packages user- and system-wide. While this *could* in rare
cases lead to version conflicts, it does not generally pose any problems, especially
not in the case of installing Reticulum.
The ``--break-system-packages`` directive is a somewhat misleading choice of words. Setting it will of course not break any system packages, but will simply allow installing ``pip`` packages user- and system-wide. While this *could* in rare cases lead to version conflicts, it does not generally pose any problems, especially not in the case of installing Reticulum.
MacOS
^^^^^^^^^^^^^^^^^^^^^^^^^
To install Reticulum on macOS, you will need to have Python and the ``pip`` package
manager installed.
^^^^^
To install Reticulum on macOS, you will need to have Python and the ``pip`` package manager installed.
Systems running macOS can vary quite widely in whether or not Python is pre-installed,
and if it is, which version is installed, and whether the ``pip`` package manager is
also installed and set up. If in doubt, you can `download and install <https://www.python.org/downloads/>`_
Python manually.
Systems running macOS can vary quite widely in whether or not Python is pre-installed, and if it is, which version is installed, and whether the ``pip`` package manager is also installed and set up. If in doubt, you can `download and install <https://www.python.org/downloads/>`_ Python manually.
When Python and ``pip`` is available on your system, simply open a terminal window
and use one of the following commands:
When Python and ``pip`` is available on your system, simply open a terminal window and use one of the following commands:
.. code:: shell
@@ -531,16 +404,9 @@ and use one of the following commands:
pip3 install rns --break-system-packages
.. note::
The ``--break-system-packages`` directive is a somewhat misleading choice
of words. Setting it will of course not break any system packages, but will simply
allow installing ``pip`` packages user- and system-wide. While this *could* in rare
cases lead to version conflicts, it does not generally pose any problems, especially
not in the case of installing Reticulum.
The ``--break-system-packages`` directive is a somewhat misleading choice of words. Setting it will of course not break any system packages, but will simply allow installing ``pip`` packages user- and system-wide. While this *could* in rare cases lead to version conflicts, it does not generally pose any problems, especially not in the case of installing Reticulum.
Additionally, some version combinations of macOS and Python require you to
manually add your installed ``pip`` packages directory to your `PATH` environment
variable, before you can use installed commands in your terminal. Usually, adding
the following line to your shell init script (for example ``~/.zshrc``) will be enough:
Additionally, some version combinations of macOS and Python require you to manually add your installed ``pip`` packages directory to your `PATH` environment variable, before you can use installed commands in your terminal. Usually, adding the following line to your shell init script (for example ``~/.zshrc``) will be enough:
.. code:: shell
@@ -550,20 +416,13 @@ Adjust Python version and shell init script location according to your system.
OpenWRT
^^^^^^^^^^^^^^^^^^^^^^^^^
On OpenWRT systems with sufficient storage and memory, you can install
Reticulum and related utilities using the `opkg` package manager and `pip`.
^^^^^^^
On OpenWRT systems with sufficient storage and memory, you can install Reticulum and related utilities using the `opkg` package manager and `pip`.
.. note::
At the time of releasing this manual, work is underway to create pre-built Reticulum packages for OpenWRT, with full configuration, service and ``uci`` integration. Please see the `feed-reticulum <https://github.com/gretel/feed-reticulum>`_ and `reticulum-openwrt <https://github.com/gretel/reticulum-openwrt>`_ repositories for more information.
At the time of releasing this manual, work is underway to create pre-built
Reticulum packages for OpenWRT, with full configuration, service
and ``uci`` integration. Please see the `feed-reticulum <https://github.com/gretel/feed-reticulum>`_
and `reticulum-openwrt <https://github.com/gretel/reticulum-openwrt>`_
repositories for more information.
To install Reticulum on OpenWRT, first log into a command line session, and
then use the following instructions:
To install Reticulum on OpenWRT, first log into a command line session, and then use the following instructions:
.. code:: shell
@@ -577,30 +436,15 @@ then use the following instructions:
rnsd -vvv
.. note::
The above instructions have been verified and tested on OpenWRT 21.02 only.
It is likely that other versions may require slightly altered installation
commands or package names. You will also need enough free space in your
overlay FS, and enough free RAM to actually run Reticulum and any related
programs and utilities.
The above instructions have been verified and tested on OpenWRT 21.02 only. It is likely that other versions may require slightly altered installation commands or package names. You will also need enough free space in your overlay FS, and enough free RAM to actually run Reticulum and any related programs and utilities.
Depending on your device configuration, you may need to adjust firewall rules
for Reticulum connectivity to and from your device to work. Until proper
packaging is ready, you will also need to manually create a service or startup
script to automatically laucnh Reticulum at boot time.
Depending on your device configuration, you may need to adjust firewall rules for Reticulum connectivity to and from your device to work. Until proper packaging is ready, you will also need to manually create a service or startup script to automatically laucnh Reticulum at boot time.
Please also note that the `AutoInterface` requires link-local IPv6 addresses
to be enabled for any Ethernet and WiFi devices you intend to use. If ``ip a``
shows an address starting with ``fe80::`` for the device in question,
``AutoInterface`` should work for that device.
Please also note that the `AutoInterface` requires link-local IPv6 addresses to be enabled for any Ethernet and WiFi devices you intend to use. If ``ip a`` shows an address starting with ``fe80::`` for the device in question, ``AutoInterface`` should work for that device.
Raspberry Pi
^^^^^^^^^^^^^^^^^^^^^^^^^
It is currently recommended to use a 64-bit version of the Raspberry Pi OS
if you want to run Reticulum on Raspberry Pi computers, since 32-bit versions
don't always have packages available for some dependencies. If Python and the
`pip` package manager is not already installed, do that first, and then
install Reticulum using `pip`.
^^^^^^^^^^^^
It is currently recommended to use a 64-bit version of the Raspberry Pi OS if you want to run Reticulum on Raspberry Pi computers, since 32-bit versions don't always have packages available for some dependencies. If Python and the `pip` package manager is not already installed, do that first, and then install Reticulum using `pip`.
.. code:: shell
@@ -611,22 +455,14 @@ install Reticulum using `pip`.
pip install rns --break-system-packages
.. note::
The ``--break-system-packages`` directive is a somewhat misleading choice
of words. Setting it will of course not break any system packages, but will simply
allow installing ``pip`` packages user- and system-wide. While this *could* in rare
cases lead to version conflicts, it does not generally pose any problems, especially
not in the case of installing Reticulum.
The ``--break-system-packages`` directive is a somewhat misleading choice of words. Setting it will of course not break any system packages, but will simply allow installing ``pip`` packages user- and system-wide. While this *could* in rare cases lead to version conflicts, it does not generally pose any problems, especially not in the case of installing Reticulum.
While it is possible to install and run Reticulum on 32-bit Rasperry Pi OSes,
it will require manually configuring and installing required build dependencies,
and is not detailed in this manual.
While it is possible to install and run Reticulum on 32-bit Rasperry Pi OSes, it will require manually configuring and installing required build dependencies, and is not detailed in this manual.
RISC-V
^^^^^^^^^^^^^^^^^^^^^^^^
On some architectures, including RISC-V, not all dependencies have precompiled
binaries. On such systems, you may need to install ``python3-dev`` (or similar) before
installing Reticulum or programs that depend on Reticulum.
^^^^^^
On some architectures, including RISC-V, not all dependencies have precompiled binaries. On such systems, you may need to install ``python3-dev`` (or similar) before installing Reticulum or programs that depend on Reticulum.
.. code:: shell
@@ -637,17 +473,12 @@ installing Reticulum or programs that depend on Reticulum.
# Install Reticulum
python3 -m pip install rns
With these packages installed, ``pip`` will be able to build any missing dependencies
on your system locally.
With these packages installed, ``pip`` will be able to build any missing dependencies on your system locally.
Ubuntu Lunar
^^^^^^^^^^^^^^^^^^^^^^^^
On versions of Ubuntu released after April 2023, it is no longer possible by default
to use ``pip`` to install packages onto your system. Unfortunately, you will need to
use the replacement ``pipx`` command instead, which places installed packages in an
isolated environment. This should not negatively affect Reticulum, but will not work
for including and using Reticulum in your own scripts and programs.
^^^^^^^^^^^^
On versions of Ubuntu released after April 2023, it is no longer possible by default to use ``pip`` to install packages onto your system. Unfortunately, you will need to use the replacement ``pipx`` command instead, which places installed packages in an isolated environment. This should not negatively affect Reticulum, but will not work for including and using Reticulum in your own scripts and programs.
.. code:: shell
@@ -660,42 +491,29 @@ for including and using Reticulum in your own scripts and programs.
# Install Reticulum
pipx install rns
Alternatively, you can restore normal behaviour to ``pip`` by creating or editing
the configuration file located at ``~/.config/pip/pip.conf``, and adding the
following section:
Alternatively, you can restore normal behaviour to ``pip`` by creating or editing the configuration file located at ``~/.config/pip/pip.conf``, and adding the following section:
.. code:: text
[global]
break-system-packages = true
For a one-shot installation of Reticulum, without globally enabling the ``break-system-packages``
option, you can use the following command:
For a one-shot installation of Reticulum, without globally enabling the ``break-system-packages`` option, you can use the following command:
.. code:: text
pip install rns --break-system-packages
.. note::
The ``--break-system-packages`` directive is a somewhat misleading choice
of words. Setting it will of course not break any system packages, but will simply
allow installing ``pip`` packages user- and system-wide. While this *could* in rare
cases lead to version conflicts, it does not generally pose any problems, especially
not in the case of installing Reticulum.
The ``--break-system-packages`` directive is a somewhat misleading choice of words. Setting it will of course not break any system packages, but will simply allow installing ``pip`` packages user- and system-wide. While this *could* in rare cases lead to version conflicts, it does not generally pose any problems, especially not in the case of installing Reticulum.
Windows
^^^^^^^^^^^^^^^^^^^^^^^^^
On Windows operating systems, the easiest way to install Reticulum is by using the
``pip`` package manager from the command line (either the command prompt or Windows
Powershell).
^^^^^^^
On Windows operating systems, the easiest way to install Reticulum is by using the ``pip`` package manager from the command line (either the command prompt or Windows Powershell).
If you don't already have Python installed, `download and install Python <https://www.python.org/downloads/>`_.
At the time of publication of this manual, the recommended version is `Python 3.12.7 <https://www.python.org/downloads/release/python-3127>`_.
If you don't already have Python installed, `download and install Python <https://www.python.org/downloads/>`_. At the time of publication of this manual, the recommended version is `Python 3.12.7 <https://www.python.org/downloads/release/python-3127>`_.
**Important!** When asked by the installer, make sure to add the Python program to
your PATH environment variables. If you don't do this, you will not be able to
use the ``pip`` installer, or run the included Reticulum utility programs (such as
``rnsd`` and ``rnstatus``) from the command line.
**Important!** When asked by the installer, make sure to add the Python program to your PATH environment variables. If you don't do this, you will not be able to use the ``pip`` installer, or run the included Reticulum utility programs (such as ``rnsd`` and ``rnstatus``) from the command line.
After installing Python, open the command prompt or Windows Powershell, and type:
@@ -703,11 +521,10 @@ After installing Python, open the command prompt or Windows Powershell, and type
pip install rns
You can now use Reticulum and all included utility programs directly from your
preferred command line interface.
You can now use Reticulum and all included utility programs directly from your preferred command line interface.
Pure-Python Reticulum
==============================================
=====================
.. warning::
If you use the ``rnspure`` package to run Reticulum on systems that
@@ -715,17 +532,6 @@ Pure-Python Reticulum
important that you read and understand the :ref:`Cryptographic Primitives <understanding-primitives>`
section of this manual.
In some rare cases, and on more obscure system types, it is not possible to
install one or more dependencies. In such situations,
you can use the ``rnspure`` package instead of the ``rns`` package, or use ``pip``
with the ``--no-dependencies`` command-line option. The ``rnspure``
package requires no external dependencies for installation. Please note that the
actual contents of the ``rns`` and ``rnspure`` packages are *completely identical*.
The only difference is that the ``rnspure`` package lists no dependencies required
for installation.
In some rare cases, and on more obscure system types, it is not possible to install one or more dependencies. In such situations, you can use the ``rnspure`` package instead of the ``rns`` package, or use ``pip`` with the ``--no-dependencies`` command-line option. The ``rnspure`` package requires no external dependencies for installation. Please note that the actual contents of the ``rns`` and ``rnspure`` packages are *completely identical*. The only difference is that the ``rnspure`` package lists no dependencies required for installation.
No matter how Reticulum is installed and started, it will load external dependencies
only if they are *needed* and *available*. If for example you want to use Reticulum
on a system that cannot support ``pyserial``, it is perfectly possible to do so using
the `rnspure` package, but Reticulum will not be able to use serial-based interfaces.
All other available modules will still be loaded when needed.
No matter how Reticulum is installed and started, it will load external dependencies only if they are *needed* and *available*. If for example you want to use Reticulum on a system that cannot support ``pyserial``, it is perfectly possible to do so using the `rnspure` package, but Reticulum will not be able to use serial-based interfaces. All other available modules will still be loaded when needed.
File diff suppressed because it is too large. Load diff
+1
View File
@@ -27,6 +27,7 @@ to participate in the development of Reticulum itself.
hardware
interfaces
networks
distributed
git
support
examples
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more