Compare commits

..
385 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
Jeremy O'Brien 603f709139 Don't iterate known_destinations directly; it can change during iteration 2026-05-18 00:10:25 -04:00
156 changed files with 12028 additions and 6645 deletions

No files matched your search

+1
View File
@@ -14,3 +14,4 @@ tests/rnsconfig/logfile*
*.data *.data
*.result *.result
.buildinfo.bak .buildinfo.bak
docs/Reticulum Manual.*
+271 -5
View File
@@ -1,12 +1,278 @@
compiling = False compiling = False
noticed = False noticed = False
notice_delay = 0.3 notice_delay = 0.3
import time import os
import sys import sys
import time
import threading import threading
from importlib.util import find_spec from importlib.util import find_spec
if find_spec("pyximport") and find_spec("cython"): 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(): def notice_job():
global noticed global noticed
@@ -14,13 +280,13 @@ def notice_job():
while compiling: while compiling:
if time.time() > started+notice_delay and compiling: if time.time() > started+notice_delay and compiling:
noticed = True noticed = True
print("Compiling RNS object code... ", end="") print("Compiling RNS object code...")
sys.stdout.flush() sys.stdout.flush()
break break
time.sleep(0.1) time.sleep(0.1)
compiling = True compiling = True
threading.Thread(target=notice_job, daemon=True).start() threading.Thread(target=notice_job, daemon=True).start()
_importfinder.precompile()
import RNS; compiling = False import RNS; compiling = False
if noticed: print("Done."); sys.stdout.flush() if noticed: print("Compilation done"); sys.stdout.flush()
+308 -58
View File
@@ -1,3 +1,311 @@
### 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 ### 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. 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.
@@ -13,28 +321,6 @@ This release completes the operational functionality of the `rngit` system, whic
- Improved page node ref link handling in `rngit` - Improved page node ref link handling in `rngit`
- Improved logging in various locations - Improved logging in various locations
**Verified Retrieval**
You can retrieve and verify this release over Reticulum using the built-in `rngit release` utility. To download all artifacts, and the release manifest for future updates, you can use the following command:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch latest:all --signer bc7291552be7a58f361522990465165c
```
To retrieve only the `.whl` package for installation, you can use:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch latest:rns-1.2.8-py3-none-any.whl --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 `rnid`. To verify files, 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 manifest.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-05-18: RNS 1.2.8 ### 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. 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.
@@ -55,15 +341,6 @@ This release improves the `rngit` system with signed release manifest generation
- Fixed various minor bugs and inconsistencies in `rngit` - Fixed various minor bugs and inconsistencies in `rngit`
- Dropped `note` metadata field requirement from `rsg` structure - Dropped `note` metadata field requirement from `rsg` structure
**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 `rnid`. To verify files, 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 manifest.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-05-17: RNS 1.2.7 ### 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. 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.
@@ -81,15 +358,6 @@ This release significantly improves the `rngit` system with fork, mirroring and
- Improved transfer completed feedback in `rncp`, thanks to **neutral** - Improved transfer completed feedback in `rncp`, thanks to **neutral**
- Improved interface transport insertion and removal - Improved interface transport insertion and removal
**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*.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.
### 2026-05-14: RNS 1.2.6 ### 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. This release adds further improvements to the `rnid` and `rngit` utilities, and includes several bugfixes and other improvements.
@@ -111,15 +379,6 @@ This release adds further improvements to the `rnid` and `rngit` utilities, and
- Fixed potential race condition in interface discovery - 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 - Fixed `rngit` remote helper hanging on startup if no client config had been created previously, and RNS loglevel was configured at debug or higher
**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*.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.
### 2026-05-09: RNS 1.2.5 ### 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. 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.
@@ -148,15 +407,6 @@ For all node ops out there, I'd recomment updating to this at some sort of semi-
- Ensured canonical validation functions in `rngit` - Ensured canonical validation functions in `rngit`
- Lots of other small fixes and stability improvements to `rngit` - Lots of other small fixes and stability improvements to `rngit`
**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.5-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.
### 2026-05-07: RNS 1.2.4 ### 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! 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!
+1 -1
View File
@@ -239,7 +239,7 @@ def link_established(link):
RNS.log("Link established with server, sending...") RNS.log("Link established with server, sending...")
rd = os.urandom(link.mdu) rd = os.urandom(link.mdu)
started = time.time() started = time.time()
while link.status == RNS.Link.ACTIVE and data_sent < data_cap*1.25: while link.status != RNS.Link.CLOSED and data_sent < data_cap*1.25:
RNS.Packet(server_link, rd, create_receipt=False).send() RNS.Packet(server_link, rd, create_receipt=False).send()
data_sent += len(rd) data_sent += len(rd)
+19 -1
View File
@@ -21,6 +21,19 @@ clean:
@-rm -rf ./tests/__pycache__ @-rm -rf ./tests/__pycache__
@-rm -rf ./tests/rnsconfig/storage @-rm -rf ./tests/rnsconfig/storage
@-rm -rf ./*.egg-info @-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 @make -C docs clean
@echo Done @echo Done
@@ -50,6 +63,9 @@ build_wheel:
build_pure_wheel: build_pure_wheel:
python3 setup.py bdist_wheel --pure python3 setup.py bdist_wheel --pure
build_native:
python3 setup.py bdist_wheel --native
documentation: documentation:
make -C docs html markdown make -C docs html markdown
@@ -57,7 +73,7 @@ manual:
make -C docs latexpdf epub make -C docs latexpdf epub
distcollect: distcollect:
cp docs/Reticulum\ Manual.* dist mv docs/Reticulum\ Manual.* dist
build_spkg: remove_symlinks build_sdist create_symlinks build_spkg: remove_symlinks build_sdist create_symlinks
@@ -65,6 +81,8 @@ release: test remove_symlinks build_sdist build_wheel build_pure_wheel documenta
debug: remove_symlinks build_wheel build_pure_wheel create_symlinks debug: remove_symlinks build_wheel build_pure_wheel create_symlinks
native: remove_symlinks build_native create_symlinks
local: release sign local: release sign
sign: sign:
+7 -1
View File
@@ -39,7 +39,7 @@ userland, and can run on practically any system that runs Python 3.
## Read The Manual ## 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 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). 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, implementation, and its associated manual. It is maintained by Mark Qvist,
identified by the Reticulum Identity `<bc7291552be7a58f361522990465165c>`. 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, Compatibility with the Reticulum Protocol is defined as having full interoperability,
and sufficient functional parity with this reference implementation. Any specific protocol and sufficient functional parity with this reference implementation. Any specific protocol
implementation that achieves this is Reticulum. Any that does not is not Reticulum. implementation that achieves this is Reticulum. Any that does not is not Reticulum.
+9 -1
View File
@@ -4,6 +4,8 @@ To understand the foundational philosophy and goals of this system, read the `_`
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. 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.
`(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`*. 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. 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.
@@ -16,7 +18,7 @@ No kernel modules or drivers are required. Reticulum runs completely in userland
The full documentation for Reticulum is available on `_`!`[this node`:/page/blob.mu`g=reticulum|r=reticulum|ref=HEAD|path=docs/markdown/index.md]`!`_. 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]`!`_. 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 >> Notable Features
@@ -58,6 +60,12 @@ You can also download the `_`!`[Reticulum manual as a PDF`:/file/download`g=reti
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. 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. 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. The reference implementation is licensed under the Reticulum License.
+5 -4
View File
@@ -53,7 +53,8 @@ class StreamDataMessage(MessageBase):
The stream id is limited to 2 bytes - 2 bit The stream id is limited to 2 bytes - 2 bit
""" """
OVERHEAD = 2 + 6 # 2 for stream data message header, 6 for channel envelope HEADER_LEN = 2 # 2 for stream data message header
OVERHEAD = HEADER_LEN + 6 # 6 for channel envelope
MAX_DATA_LEN = RNS.Link.MDU - OVERHEAD MAX_DATA_LEN = RNS.Link.MDU - OVERHEAD
""" """
When the Buffer package is imported, this value is When the Buffer package is imported, this value is
@@ -226,7 +227,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
self._stream_id = stream_id self._stream_id = stream_id
self._channel = channel self._channel = channel
self._eof = False self._eof = False
self._mdu = channel.mdu - StreamDataMessage.OVERHEAD self._mdu = channel.mdu - StreamDataMessage.HEADER_LEN
def write(self, __b: bytes) -> int | None: def write(self, __b: bytes) -> int | None:
try: try:
@@ -242,7 +243,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
chunk_segment_length = int(chunk_len/comp_try) chunk_segment_length = int(chunk_len/comp_try)
compressed_chunk = bz2.compress(__b[:chunk_segment_length]) compressed_chunk = bz2.compress(__b[:chunk_segment_length])
compressed_length = len(compressed_chunk) compressed_length = len(compressed_chunk)
if compressed_length < StreamDataMessage.MAX_DATA_LEN and compressed_length < chunk_segment_length: if compressed_length < self._mdu and compressed_length < chunk_segment_length:
comp_success = True comp_success = True
break break
else: else:
@@ -252,7 +253,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
chunk = compressed_chunk chunk = compressed_chunk
processed_length = chunk_segment_length processed_length = chunk_segment_length
else: else:
chunk = bytes(__b[:StreamDataMessage.MAX_DATA_LEN]) chunk = bytes(__b[:self._mdu])
processed_length = len(chunk) processed_length = len(chunk)
message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success) message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success)
+118 -216
View File
@@ -45,63 +45,6 @@ TPacket = TypeVar("TPacket")
class SystemMessageTypes(enum.IntEnum): class SystemMessageTypes(enum.IntEnum):
SMT_STREAM_DATA = 0xff00 SMT_STREAM_DATA = 0xff00
class ChannelOutletBase(ABC, Generic[TPacket]):
"""
An abstract transport layer interface used by Channel.
DEPRECATED: This was created for testing; eventually
Channel will use Link or a LinkBase interface
directly.
"""
@abstractmethod
def send(self, raw: bytes) -> TPacket:
raise NotImplemented()
@abstractmethod
def resend(self, packet: TPacket) -> TPacket:
raise NotImplemented()
@property
@abstractmethod
def mdu(self):
raise NotImplemented()
@property
@abstractmethod
def rtt(self):
raise NotImplemented()
@property
@abstractmethod
def is_usable(self):
raise NotImplemented()
@abstractmethod
def get_packet_state(self, packet: TPacket) -> MessageState:
raise NotImplemented()
@abstractmethod
def timed_out(self):
raise NotImplemented()
@abstractmethod
def __str__(self):
raise NotImplemented()
@abstractmethod
def set_packet_timeout_callback(self, packet: TPacket, callback: Callable[[TPacket], None] | None,
timeout: float | None = None):
raise NotImplemented()
@abstractmethod
def set_packet_delivered_callback(self, packet: TPacket, callback: Callable[[TPacket], None] | None):
raise NotImplemented()
@abstractmethod
def get_packet_id(self, packet: TPacket) -> any:
raise NotImplemented()
class CEType(enum.IntEnum): class CEType(enum.IntEnum):
""" """
ChannelException type codes ChannelException type codes
@@ -113,7 +56,6 @@ class CEType(enum.IntEnum):
ME_ALREADY_SENT = 4 ME_ALREADY_SENT = 4
ME_TOO_BIG = 5 ME_TOO_BIG = 5
class ChannelException(Exception): class ChannelException(Exception):
""" """
An exception thrown by Channel, with a type code. An exception thrown by Channel, with a type code.
@@ -122,7 +64,6 @@ class ChannelException(Exception):
super().__init__(args) super().__init__(args)
self.type = ce_type self.type = ce_type
class MessageState(enum.IntEnum): class MessageState(enum.IntEnum):
""" """
Set of possible states for a Message Set of possible states for a Message
@@ -132,7 +73,6 @@ class MessageState(enum.IntEnum):
MSGSTATE_DELIVERED = 2 MSGSTATE_DELIVERED = 2
MSGSTATE_FAILED = 3 MSGSTATE_FAILED = 3
class MessageBase(abc.ABC): class MessageBase(abc.ABC):
""" """
Base type for any messages sent or received on a Channel. Base type for any messages sent or received on a Channel.
@@ -170,7 +110,6 @@ class MessageBase(abc.ABC):
MessageCallbackType = NewType("MessageCallbackType", Callable[[MessageBase], bool]) MessageCallbackType = NewType("MessageCallbackType", Callable[[MessageBase], bool])
class Envelope: class Envelope:
""" """
Internal wrapper used to transport messages over a channel and Internal wrapper used to transport messages over a channel and
@@ -180,8 +119,7 @@ class Envelope:
msgtype, self.sequence, length = struct.unpack(">HHH", self.raw[:6]) msgtype, self.sequence, length = struct.unpack(">HHH", self.raw[:6])
raw = self.raw[6:] raw = self.raw[6:]
ctor = message_factories.get(msgtype, None) ctor = message_factories.get(msgtype, None)
if ctor is None: if ctor is None: raise ChannelException(CEType.ME_NOT_REGISTERED, f"Unable to find constructor for Channel MSGTYPE {hex(msgtype)}")
raise ChannelException(CEType.ME_NOT_REGISTERED, f"Unable to find constructor for Channel MSGTYPE {hex(msgtype)}")
message = ctor() message = ctor()
message.unpack(raw) message.unpack(raw)
self.unpacked = True self.unpacked = True
@@ -190,14 +128,13 @@ class Envelope:
return message return message
def pack(self) -> bytes: def pack(self) -> bytes:
if self.message.__class__.MSGTYPE is None: if self.message.__class__.MSGTYPE is None: raise ChannelException(CEType.ME_NO_MSG_TYPE, f"{self.message.__class__} lacks MSGTYPE")
raise ChannelException(CEType.ME_NO_MSG_TYPE, f"{self.message.__class__} lacks MSGTYPE")
data = self.message.pack() data = self.message.pack()
self.raw = struct.pack(">HHH", self.message.MSGTYPE, self.sequence, len(data)) + data self.raw = struct.pack(">HHH", self.message.MSGTYPE, self.sequence, len(data)) + data
self.packed = True self.packed = True
return self.raw return self.raw
def __init__(self, outlet: ChannelOutletBase, message: MessageBase = None, raw: bytes = None, sequence: int = None): def __init__(self, outlet: LinkChannelOutlet, message: MessageBase = None, raw: bytes = None, sequence: int = None):
self.ts = time.time() self.ts = time.time()
self.id = id(self) self.id = id(self)
self.message = message self.message = message
@@ -278,13 +215,14 @@ class Channel(contextlib.AbstractContextManager):
SEQ_MAX = 0xFFFF SEQ_MAX = 0xFFFF
SEQ_MODULUS = SEQ_MAX+1 SEQ_MODULUS = SEQ_MAX+1
def __init__(self, outlet: ChannelOutletBase): def __init__(self, outlet: LinkChannelOutlet):
""" """
@param outlet: @param outlet:
""" """
self._outlet = outlet self._outlet = outlet
self._lock = threading.RLock() self._lock = threading.RLock()
self._send_lock = threading.Lock()
self._tx_ring: collections.deque[Envelope] = collections.deque() self._tx_ring: collections.deque[Envelope] = collections.deque()
self._rx_ring: collections.deque[Envelope] = collections.deque() self._rx_ring: collections.deque[Envelope] = collections.deque()
self._message_callbacks: [MessageCallbackType] = [] self._message_callbacks: [MessageCallbackType] = []
@@ -306,11 +244,9 @@ class Channel(contextlib.AbstractContextManager):
self.window_min = Channel.WINDOW_MIN self.window_min = Channel.WINDOW_MIN
self.window_flexibility = Channel.WINDOW_FLEXIBILITY self.window_flexibility = Channel.WINDOW_FLEXIBILITY
def __enter__(self) -> Channel: def __enter__(self) -> Channel: return self
return self
def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None) -> bool | None:
__traceback: TracebackType | None) -> bool | None:
self._shutdown() self._shutdown()
return False return False
@@ -326,20 +262,13 @@ class Channel(contextlib.AbstractContextManager):
def _register_message_type(self, message_class: Type[MessageBase], *, is_system_type: bool = False): def _register_message_type(self, message_class: Type[MessageBase], *, is_system_type: bool = False):
with self._lock: with self._lock:
if not issubclass(message_class, MessageBase): if not issubclass(message_class, MessageBase): raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} is not a subclass of {MessageBase}.")
raise ChannelException(CEType.ME_INVALID_MSG_TYPE, if message_class.MSGTYPE is None: raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} has invalid MSGTYPE class attribute.")
f"{message_class} is not a subclass of {MessageBase}.") if message_class.MSGTYPE >= 0xf000 and not is_system_type: raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} has system-reserved message type.")
if message_class.MSGTYPE is None:
raise ChannelException(CEType.ME_INVALID_MSG_TYPE, try: message_class()
f"{message_class} has invalid MSGTYPE class attribute.")
if message_class.MSGTYPE >= 0xf000 and not is_system_type:
raise ChannelException(CEType.ME_INVALID_MSG_TYPE,
f"{message_class} has system-reserved message type.")
try:
message_class()
except Exception as ex: except Exception as ex:
raise ChannelException(CEType.ME_INVALID_MSG_TYPE, raise ChannelException(CEType.ME_INVALID_MSG_TYPE, f"{message_class} raised an exception when constructed with no arguments: {ex}")
f"{message_class} raised an exception when constructed with no arguments: {ex}")
self._message_factories[message_class.MSGTYPE] = message_class self._message_factories[message_class.MSGTYPE] = message_class
@@ -382,6 +311,11 @@ class Channel(contextlib.AbstractContextManager):
if envelope.packet is not None: if envelope.packet is not None:
self._outlet.set_packet_timeout_callback(envelope.packet, None) self._outlet.set_packet_timeout_callback(envelope.packet, None)
self._outlet.set_packet_delivered_callback(envelope.packet, None) self._outlet.set_packet_delivered_callback(envelope.packet, None)
envelope.tracked = False
for envelope in self._rx_ring:
envelope.tracked = False
self._tx_ring.clear() self._tx_ring.clear()
self._rx_ring.clear() self._rx_ring.clear()
@@ -390,14 +324,12 @@ class Channel(contextlib.AbstractContextManager):
i = 0 i = 0
for existing in ring: for existing in ring:
if envelope.sequence == existing.sequence: if envelope.sequence == existing.sequence:
RNS.log(f"Envelope: Emplacement of duplicate envelope with sequence "+str(envelope.sequence), RNS.LOG_EXTREME) RNS.log(f"Envelope: Emplacement of duplicate envelope with sequence "+str(envelope.sequence), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return False return False
if envelope.sequence < existing.sequence and not (self._next_rx_sequence - envelope.sequence) > (Channel.SEQ_MAX//2): if envelope.sequence < existing.sequence and not (self._next_rx_sequence - envelope.sequence) > (Channel.SEQ_MAX//2):
ring.insert(i, envelope) ring.insert(i, envelope)
envelope.tracked = True envelope.tracked = True
return True return True
@@ -413,10 +345,8 @@ class Channel(contextlib.AbstractContextManager):
for cb in cbs: for cb in cbs:
try: try:
if cb(message): if cb(message): return
return except Exception as e: RNS.log(f"Channel {str(self)} experienced an error while running a message callback. The contained exception was: {e}", RNS.LOG_ERROR)
except Exception as e:
RNS.log("Channel "+str(self)+" experienced an error while running a message callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
def _receive(self, raw: bytes): def _receive(self, raw: bytes):
try: try:
@@ -428,16 +358,20 @@ class Channel(contextlib.AbstractContextManager):
window_overflow = (self._next_rx_sequence+Channel.WINDOW_MAX) % Channel.SEQ_MODULUS window_overflow = (self._next_rx_sequence+Channel.WINDOW_MAX) % Channel.SEQ_MODULUS
if window_overflow < self._next_rx_sequence: if window_overflow < self._next_rx_sequence:
if envelope.sequence > window_overflow: if envelope.sequence > window_overflow:
RNS.log("Invalid packet sequence ("+str(envelope.sequence)+") received on channel "+str(self), RNS.LOG_EXTREME) RNS.log(f"Invalid packet sequence ({envelope.sequence}) received on channel {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return return
else: else:
RNS.log("Invalid packet sequence ("+str(envelope.sequence)+") received on channel "+str(self), RNS.LOG_EXTREME) RNS.log(f"Invalid packet sequence ({envelope.sequence}) received on channel {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return return
elif envelope.sequence > self._next_rx_sequence + self.WINDOW_MAX:
RNS.log(f"Invalid packet sequence ({envelope.sequence}) received on channel {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return
is_new = self._emplace_envelope(envelope, self._rx_ring) is_new = self._emplace_envelope(envelope, self._rx_ring)
if not is_new: if not is_new:
RNS.log("Duplicate message received on channel "+str(self), RNS.LOG_EXTREME) RNS.log("Duplicate message received on channel "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return return
else: else:
with self._lock: with self._lock:
@@ -453,10 +387,8 @@ class Channel(contextlib.AbstractContextManager):
self._next_rx_sequence = (self._next_rx_sequence + 1) % Channel.SEQ_MODULUS self._next_rx_sequence = (self._next_rx_sequence + 1) % Channel.SEQ_MODULUS
for e in contigous: for e in contigous:
if not e.unpacked: if not e.unpacked: m = e.unpack(self._message_factories)
m = e.unpack(self._message_factories) else: m = e.message
else:
m = e.message
self._rx_ring.remove(e) self._rx_ring.remove(e)
self._run_callbacks(m) self._run_callbacks(m)
@@ -470,9 +402,7 @@ class Channel(contextlib.AbstractContextManager):
:return: True if ready :return: True if ready
""" """
if not self._outlet.is_usable: if not self._outlet.is_usable: return False
return False
with self._lock: with self._lock:
outstanding = 0 outstanding = 0
for envelope in self._tx_ring: for envelope in self._tx_ring:
@@ -480,57 +410,38 @@ class Channel(contextlib.AbstractContextManager):
if not envelope.packet or not self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED: if not envelope.packet or not self._outlet.get_packet_state(envelope.packet) == MessageState.MSGSTATE_DELIVERED:
outstanding += 1 outstanding += 1
if outstanding >= self.window: if outstanding >= self.window: return False
return False
return True return True
def _packet_tx_op(self, packet: TPacket, op: Callable[[TPacket], bool]): def _packet_tx_op(self, packet: TPacket, op: Callable[[TPacket], bool]):
target_id = self._outlet.get_packet_id(packet)
with self._lock: with self._lock:
envelope = next(filter(lambda e: self._outlet.get_packet_id(e.packet) == self._outlet.get_packet_id(packet), envelope = next(filter(lambda e: e.packet is not None and self._outlet.get_packet_id(e.packet) == target_id, self._tx_ring), None)
self._tx_ring), None)
if envelope and op(envelope): if envelope and op(envelope):
envelope.tracked = False envelope.tracked = False
if envelope in self._tx_ring: if envelope in self._tx_ring:
self._tx_ring.remove(envelope) self._tx_ring.remove(envelope)
if self.window < self.window_max: if self.window < self.window_max: self.window += 1
self.window += 1
# TODO: Remove at some point
# RNS.log("Increased "+str(self)+" window to "+str(self.window), RNS.LOG_DEBUG)
if self._outlet.rtt != 0: if self._outlet.rtt != 0:
if self._outlet.rtt > Channel.RTT_FAST: if self._outlet.rtt > Channel.RTT_FAST:
self.fast_rate_rounds = 0 self.fast_rate_rounds = 0
if self._outlet.rtt > Channel.RTT_MEDIUM: self.medium_rate_rounds = 0
if self._outlet.rtt > Channel.RTT_MEDIUM:
self.medium_rate_rounds = 0
else: else:
self.medium_rate_rounds += 1 self.medium_rate_rounds += 1
if self.window_max < Channel.WINDOW_MAX_MEDIUM and self.medium_rate_rounds == Channel.FAST_RATE_THRESHOLD: if self.window_max < Channel.WINDOW_MAX_MEDIUM and self.medium_rate_rounds == Channel.FAST_RATE_THRESHOLD:
self.window_max = Channel.WINDOW_MAX_MEDIUM self.window_max = Channel.WINDOW_MAX_MEDIUM
self.window_min = Channel.WINDOW_MIN_LIMIT_MEDIUM self.window_min = Channel.WINDOW_MIN_LIMIT_MEDIUM
# TODO: Remove at some point
# RNS.log("Increased "+str(self)+" max window to "+str(self.window_max), RNS.LOG_DEBUG)
# RNS.log("Increased "+str(self)+" min window to "+str(self.window_min), RNS.LOG_DEBUG)
else: else:
self.fast_rate_rounds += 1 self.fast_rate_rounds += 1
if self.window_max < Channel.WINDOW_MAX_FAST and self.fast_rate_rounds == Channel.FAST_RATE_THRESHOLD: if self.window_max < Channel.WINDOW_MAX_FAST and self.fast_rate_rounds == Channel.FAST_RATE_THRESHOLD:
self.window_max = Channel.WINDOW_MAX_FAST self.window_max = Channel.WINDOW_MAX_FAST
self.window_min = Channel.WINDOW_MIN_LIMIT_FAST self.window_min = Channel.WINDOW_MIN_LIMIT_FAST
# TODO: Remove at some point
# RNS.log("Increased "+str(self)+" max window to "+str(self.window_max), RNS.LOG_DEBUG)
# RNS.log("Increased "+str(self)+" min window to "+str(self.window_min), RNS.LOG_DEBUG)
else: RNS.log("Envelope not found in TX ring for "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
else: if not envelope: RNS.log("Spurious message received on "+str(self), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
RNS.log("Envelope not found in TX ring for "+str(self), RNS.LOG_EXTREME)
if not envelope:
RNS.log("Spurious message received on "+str(self), RNS.LOG_EXTREME)
def _packet_delivered(self, packet: TPacket): def _packet_delivered(self, packet: TPacket):
self._packet_tx_op(packet, lambda env: True) self._packet_tx_op(packet, lambda env: True)
@@ -539,44 +450,47 @@ class Channel(contextlib.AbstractContextManager):
for envelope in self._tx_ring: for envelope in self._tx_ring:
updated_timeout = self._get_packet_timeout_time(envelope.tries) updated_timeout = self._get_packet_timeout_time(envelope.tries)
if envelope.packet and hasattr(envelope.packet, "receipt") and envelope.packet.receipt and envelope.packet.receipt.timeout: if envelope.packet and hasattr(envelope.packet, "receipt") and envelope.packet.receipt and envelope.packet.receipt.timeout:
if updated_timeout > envelope.packet.receipt.timeout: if updated_timeout > envelope.packet.receipt.timeout: envelope.packet.receipt.set_timeout(updated_timeout)
envelope.packet.receipt.set_timeout(updated_timeout)
def _get_packet_timeout_time(self, tries: int) -> float: def _get_packet_timeout_time(self, tries: int) -> float:
to = pow(1.5, tries - 1) * max(self._outlet.rtt*2.5, 0.025) * (len(self._tx_ring)+1.5) to = pow(1.5, tries - 1) * max(self._outlet.rtt*2.5, 0.025) * (len(self._tx_ring)+1.5)
return to return to
def _packet_timeout(self, packet: TPacket): def _packet_timeout(self, packet: TPacket):
def retry_envelope(envelope: Envelope) -> bool: if self._outlet.get_packet_state(packet) == MessageState.MSGSTATE_DELIVERED: return
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
envelope.tries += 1 target_id = self._outlet.get_packet_id(packet)
self._outlet.resend(envelope.packet) envelope_to_resend: Envelope | None = None
self._outlet.set_packet_delivered_callback(envelope.packet, self._packet_delivered) should_teardown = False
self._outlet.set_packet_timeout_callback(envelope.packet, self._packet_timeout, self._get_packet_timeout_time(envelope.tries)) with self._lock:
self._update_packet_timeouts() 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: if envelope.tries >= self._max_tries: should_teardown = True
self.window -= 1 else:
# TODO: Remove at some point envelope.tries += 1
# RNS.log("Decreased "+str(self)+" window to "+str(self.window), RNS.LOG_DEBUG) envelope_to_resend = envelope
if self.window_max > (self.window_min+self.window_flexibility): if self.window > self.window_min:
self.window_max -= 1 self.window -= 1
# TODO: Remove at some point if self.window_max > (self.window_min+self.window_flexibility):
# RNS.log("Decreased "+str(self)+" max window to "+str(self.window_max), RNS.LOG_DEBUG) self.window_max -= 1
# TODO: Remove at some point if should_teardown:
# RNS.log("Decreased "+str(self)+" window to "+str(self.window), RNS.LOG_EXTREME) 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: if already_delivered: self._packet_delivered(envelope_to_resend.packet)
self._packet_tx_op(packet, retry_envelope)
def send(self, message: MessageBase) -> Envelope: def send(self, message: MessageBase) -> Envelope:
""" """
@@ -585,27 +499,33 @@ class Channel(contextlib.AbstractContextManager):
:param message: an instance of a ``MessageBase`` subclass :param message: an instance of a ``MessageBase`` subclass
""" """
envelope: Envelope | None = None with self._send_lock:
with self._lock: with self._lock:
if not self.is_ready_to_send(): if not self.is_ready_to_send(): raise ChannelException(CEType.ME_LINK_NOT_READY, f"Link is not ready")
raise ChannelException(CEType.ME_LINK_NOT_READY, f"Link is not ready")
envelope = Envelope(self._outlet, message=message, sequence=self._next_sequence) reserved_sequence = self._next_sequence
self._next_sequence = (self._next_sequence + 1) % Channel.SEQ_MODULUS envelope = Envelope(self._outlet, message=message, sequence=reserved_sequence)
self._emplace_envelope(envelope, self._tx_ring) 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
if envelope is None: envelope.packet = self._outlet.send(envelope.raw)
raise BlockingIOError()
envelope.pack() if envelope.packet is None or getattr(envelope.packet, "raw", None) is None or (hasattr(envelope.packet, "receipt") and envelope.packet.receipt is None):
if len(envelope.raw) > self._outlet.mdu: with self._lock: self._next_sequence = reserved_sequence
raise ChannelException(CEType.ME_TOO_BIG, f"Packed message too big for packet: {len(envelope.raw)} > {self._outlet.mdu}") raise ChannelException(CEType.ME_LINK_NOT_READY, "Outlet did not transmit packet")
envelope.packet = self._outlet.send(envelope.raw) with self._lock:
envelope.tries += 1 self._emplace_envelope(envelope, self._tx_ring)
self._outlet.set_packet_delivered_callback(envelope.packet, self._packet_delivered) envelope.tries += 1
self._outlet.set_packet_timeout_callback(envelope.packet, self._packet_timeout, self._get_packet_timeout_time(envelope.tries)) self._outlet.set_packet_delivered_callback(envelope.packet, self._packet_delivered)
self._update_packet_timeouts() 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 return envelope
@@ -620,14 +540,13 @@ class Channel(contextlib.AbstractContextManager):
:return: number of bytes available :return: number of bytes available
""" """
mdu = self._outlet.mdu - 6 # sizeof(msgtype) + sizeof(length) + sizeof(sequence) mdu = self._outlet.mdu - 6 # sizeof(msgtype) + sizeof(length) + sizeof(sequence)
if mdu > 0xFFFF: if mdu > 0xFFFF: mdu = 0xFFFF
mdu = 0xFFFF
return mdu return mdu
class LinkChannelOutlet(ChannelOutletBase): class LinkChannelOutlet(ABC, Generic[TPacket]):
""" """
An implementation of ChannelOutletBase for RNS.Link. A channel outlet implementation for RNS.Link.
Allows Channel to send packets over an RNS Link with Allows Channel to send packets over an RNS Link with
Packets. Packets.
@@ -638,68 +557,51 @@ class LinkChannelOutlet(ChannelOutletBase):
def send(self, raw: bytes) -> RNS.Packet: def send(self, raw: bytes) -> RNS.Packet:
packet = RNS.Packet(self.link, raw, context=RNS.Packet.CHANNEL) packet = RNS.Packet(self.link, raw, context=RNS.Packet.CHANNEL)
if self.link.status == RNS.Link.ACTIVE: if self.link.status == RNS.Link.ACTIVE: packet.send()
packet.send()
return packet return packet
def resend(self, packet: RNS.Packet) -> RNS.Packet: def resend(self, packet: RNS.Packet) -> RNS.Packet:
receipt = packet.resend() receipt = packet.resend()
if not receipt: if not receipt: RNS.log("Failed to resend packet", RNS.LOG_ERROR)
RNS.log("Failed to resend packet", RNS.LOG_ERROR)
return packet return packet
@property @property
def mdu(self): def mdu(self): return self.link.mdu
return self.link.mdu
@property @property
def rtt(self): def rtt(self): return self.link.rtt
return self.link.rtt
# TODO: Initial implementation had issues
# proxying this to link status. Should
# return False when link is not ACTIVE.
# Investigate what happened here.
@property @property
def is_usable(self): def is_usable(self): return True
return True # had issues looking at Link.status
def get_packet_state(self, packet: TPacket) -> MessageState: def get_packet_state(self, packet: TPacket) -> MessageState:
if packet.receipt == None: if packet.receipt == None:
return MessageState.MSGSTATE_FAILED return MessageState.MSGSTATE_FAILED
status = packet.receipt.get_status() status = packet.receipt.get_status()
if status == RNS.PacketReceipt.SENT: if status == RNS.PacketReceipt.SENT: return MessageState.MSGSTATE_SENT
return MessageState.MSGSTATE_SENT if status == RNS.PacketReceipt.DELIVERED: return MessageState.MSGSTATE_DELIVERED
if status == RNS.PacketReceipt.DELIVERED: if status == RNS.PacketReceipt.FAILED: return MessageState.MSGSTATE_FAILED
return MessageState.MSGSTATE_DELIVERED else: raise Exception(f"Unexpected receipt state: {status}")
if status == RNS.PacketReceipt.FAILED:
return MessageState.MSGSTATE_FAILED
else:
raise Exception(f"Unexpected receipt state: {status}")
def timed_out(self): def set_packet_timeout_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None, timeout: float | None = None):
self.link.teardown() if timeout and packet.receipt: packet.receipt.set_timeout(timeout)
def inner(receipt: RNS.PacketReceipt): callback(packet)
def __str__(self): if packet and packet.receipt: packet.receipt.set_timeout_callback(inner if callback else None)
return f"{self.__class__.__name__}({self.link})"
def set_packet_timeout_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None,
timeout: float | None = None):
if timeout and packet.receipt:
packet.receipt.set_timeout(timeout)
def inner(receipt: RNS.PacketReceipt):
callback(packet)
if packet and packet.receipt:
packet.receipt.set_timeout_callback(inner if callback else None)
def set_packet_delivered_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None): def set_packet_delivered_callback(self, packet: RNS.Packet, callback: Callable[[RNS.Packet], None] | None):
def inner(receipt: RNS.PacketReceipt): def inner(receipt: RNS.PacketReceipt): callback(packet)
callback(packet) if packet and packet.receipt: packet.receipt.set_delivery_callback(inner if callback else None)
if packet and packet.receipt:
packet.receipt.set_delivery_callback(inner if callback else None)
def get_packet_id(self, packet: RNS.Packet) -> any: def get_packet_id(self, packet: RNS.Packet) -> any:
if packet 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() return packet.get_hash()
else: else: return None
return None
def timed_out(self): self.link.teardown()
def __str__(self): return f"{self.__class__.__name__}({self.link})"
+4 -4
View File
@@ -43,7 +43,7 @@ elif cp.PROVIDER == cp.PROVIDER_PYCA:
class AES_128_CBC: class AES_128_CBC:
@staticmethod @staticmethod
def encrypt(plaintext, key, iv): 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: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key) cipher = AES128(key)
return cipher.encrypt(plaintext, iv) return cipher.encrypt(plaintext, iv)
@@ -60,7 +60,7 @@ class AES_128_CBC:
@staticmethod @staticmethod
def decrypt(ciphertext, key, iv): 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: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key) cipher = AES128(key)
return cipher.decrypt(ciphertext, iv) return cipher.decrypt(ciphertext, iv)
@@ -78,7 +78,7 @@ class AES_128_CBC:
class AES_256_CBC: class AES_256_CBC:
@staticmethod @staticmethod
def encrypt(plaintext, key, iv): 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: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key) cipher = AES256(key)
return cipher.encrypt_cbc(plaintext, iv) return cipher.encrypt_cbc(plaintext, iv)
@@ -95,7 +95,7 @@ class AES_256_CBC:
@staticmethod @staticmethod
def decrypt(ciphertext, key, iv): 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: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key) cipher = AES256(key)
return cipher.decrypt_cbc(ciphertext, iv) return cipher.decrypt_cbc(ciphertext, iv)
+51
View File
@@ -32,8 +32,59 @@ import hashlib
from math import ceil from math import ceil
from RNS.Cryptography import HMAC 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): def hkdf(length=None, derive_from=None, salt=None, context=None):
hash_len = 32 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): def hmac_sha256(key, data):
return HMAC.new(key, data).digest() return HMAC.new(key, data).digest()
+5
View File
@@ -181,3 +181,8 @@ def digest(key, msg, digest):
inner.update(msg) inner.update(msg)
outer.update(inner.digest()) outer.update(inner.digest())
return outer.digest() return outer.digest()
def _cd_internal(a, b): return a == b
try: from hmac import compare_digest as _cd
except ImportError: _cd = _cd_internal
compare_digest = _cd
+2
View File
@@ -65,4 +65,6 @@ def sha512(data):
def file_sha256(file): def file_sha256(file):
if not hashlib: raise SystemError("The hashlib module is not available on this system") 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() else: return hashlib.file_digest(file, "sha256").digest()
+1 -1
View File
@@ -80,7 +80,7 @@ class Token():
received_hmac = token[-32:] received_hmac = token[-32:]
expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest() expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
if received_hmac == expected_hmac: return True if HMAC.compare_digest(received_hmac, expected_hmac): return True
else: return False else: return False
+4 -2
View File
@@ -52,5 +52,7 @@ elif cp.PROVIDER == cp.PROVIDER_PYCA:
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py") py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc") pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
__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"))])) 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.accept_link_requests = True
self.callbacks = Callbacks() self.callbacks = Callbacks()
self.request_handlers = {} self.request_handlers = {}
self.max_request_size = None
self.type = type self.type = type
self.direction = direction self.direction = direction
self.proof_strategy = Destination.PROVE_NONE self.proof_strategy = Destination.PROVE_NONE
@@ -205,7 +206,7 @@ class Destination:
def _clean_ratchets(self): def _clean_ratchets(self):
if self.ratchets != None: if self.ratchets != None:
if len (self.ratchets) > self.retained_ratchets: if len (self.ratchets) > self.retained_ratchets:
self.ratchets = self.ratchets[:Destination.RATCHET_COUNT] self.ratchets = self.ratchets[:self.retained_ratchets]
def _persist_ratchets(self): def _persist_ratchets(self):
try: try:
@@ -362,10 +363,20 @@ class Destination:
:param proof_strategy: One of ``RNS.Destination.PROVE_NONE``, ``RNS.Destination.PROVE_ALL`` or ``RNS.Destination.PROVE_APP``. If ``RNS.Destination.PROVE_APP`` is set, the `proof_requested_callback` will be called to determine whether a proof should be sent or not. :param proof_strategy: One of ``RNS.Destination.PROVE_NONE``, ``RNS.Destination.PROVE_ALL`` or ``RNS.Destination.PROVE_APP``. If ``RNS.Destination.PROVE_APP`` is set, the `proof_requested_callback` will be called to determine whether a proof should be sent or not.
""" """
if not proof_strategy in Destination.proof_strategies: if not proof_strategy in Destination.proof_strategies: raise TypeError("Unsupported proof strategy")
raise TypeError("Unsupported proof strategy") else: self.proof_strategy = proof_strategy
else:
self.proof_strategy = proof_strategy def set_max_request_size(self, max_request_size):
"""
Sets the maximum accepted request size for registered request handlers.
:param max_request_size: The maximum accepted request size in bytes, as an integer.
:raises: ``TypeError`` or ``ValueError`` if any of the argument is invalid.
"""
try: max_request_size = int(max_request_size)
except: raise TypeError("Invalid maximum request size specified")
if max_request_size < 0: raise ValueError("Maximum request size cannot be negative")
self.max_request_size = max_request_size
def register_request_handler(self, path, response_generator = None, allow = ALLOW_NONE, allowed_list = None, auto_compress = True): def register_request_handler(self, path, response_generator = None, allow = ALLOW_NONE, allowed_list = None, auto_compress = True):
""" """
+136 -25
View File
@@ -8,9 +8,18 @@ import ipaddress
import subprocess import subprocess
from threading import Lock from threading import Lock
from .vendor import umsgpack as msgpack from .vendor import umsgpack as msgpack
from collections import deque
# 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 NAME = 0xFF
TRANSPORT_ID = 0xFE TRANSPORT_ID = 0xFE
TRANSPORT_IMPL = 0xFD
TRANSPORT_VERS = 0xFC
INTERFACE_TYPE = 0x00 INTERFACE_TYPE = 0x00
TRANSPORT = 0x01 TRANSPORT = 0x01
REACHABLE_ON = 0x02 REACHABLE_ON = 0x02
@@ -26,12 +35,13 @@ SPREADINGFACTOR = 0x0B
CODINGRATE = 0x0C CODINGRATE = 0x0C
MODULATION = 0x0D MODULATION = 0x0D
CHANNEL = 0x0E CHANNEL = 0x0E
OP_ADDR = 0xF0
APP_NAME = "rnstransport" APP_NAME = "rnstransport"
class InterfaceAnnouncer(): class InterfaceAnnouncer():
JOB_INTERVAL = 60 JOB_INTERVAL = 60
DEFAULT_STAMP_VALUE = 14 DEFAULT_STAMP_VALUE = 16
WORKBLOCK_EXPAND_ROUNDS = 20 WORKBLOCK_EXPAND_ROUNDS = 20
DISCOVERABLE_INTERFACE_TYPES = ["BackboneInterface", "TCPServerInterface", "TCPClientInterface", DISCOVERABLE_INTERFACE_TYPES = ["BackboneInterface", "TCPServerInterface", "TCPClientInterface",
@@ -99,20 +109,52 @@ class InterfaceAnnouncer():
if not interface_type in self.DISCOVERABLE_INTERFACE_TYPES: return None if not interface_type in self.DISCOVERABLE_INTERFACE_TYPES: return None
else: else:
if not RNS.vendor.platformutils.is_windows() and interface.discovery_location:
try:
discovery_location = self.sanitize(interface.discovery_location)
exec_path = os.path.expanduser(discovery_location)
if os.path.isfile(exec_path) and os.access(exec_path, os.X_OK):
RNS.log(f"Evaluating discovery location from executable at {exec_path}", RNS.LOG_DEBUG)
exec_result = subprocess.run([exec_path], stdout=subprocess.PIPE)
exec_stdout = exec_result.stdout.decode("utf-8")
if exec_result.returncode != 0: raise ValueError("Non-zero exit code from subprocess")
discovery_location = self.sanitize(exec_stdout)
location_components = discovery_location.replace(" ", "").split(",")
if len(location_components) != 3: raise ValueError(f"Invalid location component count: {len(location_components)}")
dlat = float(location_components[0])
dlon = float(location_components[1])
dhgt = float(location_components[2])
if dlat < -90 or dlat > 90: raise ValueError(f"Invalid latitude: {dlat}")
if dlon < -180 or dlat > 180: raise ValueError(f"Invalid longitude: {dlon}")
if dhgt < -4000 or dhgt > 1e6: raise ValueError(f"Invalid height: {dhgt}")
interface.discovery_latitude = dlat
interface.discovery_longitude = dlon
interface.discovery_height = dhgt
except Exception as e:
RNS.log(f"Error while getting discovery location from executable at {interface.reachable_on}: {e}", RNS.LOG_ERROR)
RNS.log(f"Aborting discovery announce", RNS.LOG_ERROR)
return None
flags = 0x00 flags = 0x00
info = {INTERFACE_TYPE: interface_type, info = {INTERFACE_TYPE: interface_type,
TRANSPORT: RNS.Reticulum.transport_enabled(), TRANSPORT: RNS.Reticulum.transport_enabled(),
TRANSPORT_ID: RNS.Transport.identity.hash, TRANSPORT_ID: RNS.Transport.identity.hash,
TRANSPORT_IMPL: IMPLEMENTATION_NAME,
TRANSPORT_VERS: RNS_VERSION,
NAME: self.sanitize(interface.discovery_name), NAME: self.sanitize(interface.discovery_name),
LATITUDE: interface.discovery_latitude, LATITUDE: interface.discovery_latitude,
LONGITUDE: interface.discovery_longitude, LONGITUDE: interface.discovery_longitude,
HEIGHT: interface.discovery_height} HEIGHT: interface.discovery_height}
if interface.discovery_lxmf_address: info[OP_ADDR] = interface.discovery_lxmf_address
if interface_type == "TCPClientInterface" and not interface.kiss_framing: if interface_type == "TCPClientInterface" and not interface.kiss_framing:
RNS.log(f"Invalid interface discovery configuration for {interface}, aborting discovery announce", RNS.LOG_ERROR) RNS.log(f"Invalid interface discovery configuration for {interface}, aborting discovery announce", RNS.LOG_ERROR)
return None return None
if interface_type in ["BackboneInterface", "TCPServerInterface"]: if interface_type in ["BackboneInterface", "TCPServerInterface"]:
if not interface.reachable_on: return None
reachable_on = self.sanitize(interface.reachable_on) reachable_on = self.sanitize(interface.reachable_on)
if not RNS.vendor.platformutils.is_windows(): if not RNS.vendor.platformutils.is_windows():
@@ -197,10 +239,14 @@ class InterfaceAnnounceHandler:
RNS.log("You can install it with the command: pip install lxmf", RNS.LOG_CRITICAL) RNS.log("You can install it with the command: pip install lxmf", RNS.LOG_CRITICAL)
RNS.panic() RNS.panic()
self.aspect_filter = APP_NAME+".discovery.interface" self.aspect_filter = APP_NAME+".discovery.interface"
self.required_value = required_value self.required_value = required_value
self.callback = callback self.callback = callback
self.stamper = LXStamper self.stamper = LXStamper
self.valid_cache = {}
self.valid_cache_max = 2048
self.invalid_cache = deque(maxlen=2048)
self.validation_lock = threading.Lock()
@staticmethod @staticmethod
def sanitize_name(name): def sanitize_name(name):
@@ -223,21 +269,43 @@ class InterfaceAnnounceHandler:
app_data = app_data[1:] app_data = app_data[1:]
signed = flags & self.FLAG_SIGNED signed = flags & self.FLAG_SIGNED
encrypted = flags & self.FLAG_ENCRYPTED encrypted = flags & self.FLAG_ENCRYPTED
fullhash = RNS.Identity.full_hash(app_data)
if encrypted: if fullhash in self.invalid_cache:
if not RNS.Transport.has_network_identity(): return RNS.log(f"Ignored previously discovered interface with insufficient stamp value", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
app_data = RNS.Transport.network_identity.decrypt(app_data) return
if not app_data: return
stamp = app_data[-self.stamper.STAMP_SIZE:] if fullhash in self.valid_cache:
packed = app_data[:-self.stamper.STAMP_SIZE] RNS.log(f"Discovery announce cache hit", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
infohash = RNS.Identity.full_hash(packed) cache_entry = self.valid_cache[fullhash]
workblock = self.stamper.stamp_workblock(infohash, expand_rounds=InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS) stamp = cache_entry["stamp"]
value = self.stamper.stamp_value(workblock, stamp) packed = cache_entry["packed"]
valid = self.stamper.stamp_valid(stamp, self.required_value, workblock) value = cache_entry["value"]
valid = cache_entry["valid"]
else:
if encrypted:
if not RNS.Transport.has_network_identity(): return
app_data = RNS.Transport.network_identity.decrypt(app_data)
if not app_data: return
if self.validation_lock.locked():
RNS.log(f"Dropping received interface discovery announce, already validating other discovery stamp", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return
with self.validation_lock:
stamp = app_data[-self.stamper.STAMP_SIZE:]
packed = app_data[:-self.stamper.STAMP_SIZE]
infohash = RNS.Identity.full_hash(packed)
workblock = self.stamper.stamp_workblock(infohash, expand_rounds=InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS)
value = self.stamper.stamp_value(workblock, stamp)
valid = self.stamper.stamp_valid(stamp, self.required_value, workblock)
self.valid_cache[fullhash] = {"valid": valid, "value": value, "packed": packed, "stamp": stamp}
while len(self.valid_cache) > self.valid_cache_max: self.valid_cache.pop(next(iter(self.valid_cache)))
if not valid: if not valid:
RNS.log(f"Ignored discovered interface with invalid stamp", RNS.LOG_DEBUG) RNS.log(f"Ignored discovered interface with insufficient stamp value {value}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.invalid_cache.append(fullhash)
return return
if value < self.required_value: RNS.log(f"Ignored discovered interface with stamp value {value}", RNS.LOG_DEBUG) if value < self.required_value: RNS.log(f"Ignored discovered interface with stamp value {value}", RNS.LOG_DEBUG)
@@ -277,7 +345,7 @@ class InterfaceAnnounceHandler:
if IFAC_NETKEY in unpacked: info["ifac_netkey"] = str(unpacked[IFAC_NETKEY]) if IFAC_NETKEY in unpacked: info["ifac_netkey"] = str(unpacked[IFAC_NETKEY])
if interface_type in ["BackboneInterface", "TCPServerInterface"]: if interface_type in ["BackboneInterface", "TCPServerInterface"]:
backbone_support = not RNS.vendor.platformutils.is_windows() backbone_support = not RNS.vendor.platformutils.is_windows() and not RNS.vendor.platformutils.is_darwin()
info["reachable_on"] = unpacked[REACHABLE_ON] info["reachable_on"] = unpacked[REACHABLE_ON]
info["port"] = unpacked[PORT] info["port"] = unpacked[PORT]
connection_interface = "BackboneInterface" if backbone_support else "TCPClientInterface" connection_interface = "BackboneInterface" if backbone_support else "TCPClientInterface"
@@ -356,6 +424,11 @@ class InterfaceAnnounceHandler:
discovery_hash_material = info["transport_id"]+info["name"] discovery_hash_material = info["transport_id"]+info["name"]
info["discovery_hash"] = RNS.Identity.full_hash(discovery_hash_material.encode("utf-8")) info["discovery_hash"] = RNS.Identity.full_hash(discovery_hash_material.encode("utf-8"))
if info and OP_ADDR in unpacked:
if type(unpacked[OP_ADDR]) not in [type(None), bytes]: raise ValueError("Invalid data in operator LXMF address field of announce")
if unpacked[OP_ADDR] and len(unpacked[OP_ADDR]) == RNS.Identity.TRUNCATED_HASHLENGTH//8:
info["operator_lxmf_address"] = RNS.hexrep(unpacked[OP_ADDR], delimit=False)
if self.callback and callable(self.callback): self.callback(info) if self.callback and callable(self.callback): self.callback(info)
except Exception as e: except Exception as e:
@@ -376,6 +449,9 @@ class InterfaceDiscovery():
AUTOCONNECT_TYPES = ["BackboneInterface", "TCPServerInterface"] AUTOCONNECT_TYPES = ["BackboneInterface", "TCPServerInterface"]
DISCOVERABLE_TYPES = ["BackboneInterface", "TCPServerInterface", "I2PInterface", "RNodeInterface", "WeaveInterface", "KISSInterface"] DISCOVERABLE_TYPES = ["BackboneInterface", "TCPServerInterface", "I2PInterface", "RNodeInterface", "WeaveInterface", "KISSInterface"]
AC_TRANSPORT_MODE = RNS.Interfaces.Interface.Interface.MODE_GATEWAY
AC_GRAVITY = 0
discovery_lock = Lock() discovery_lock = Lock()
def __init__(self, required_value=InterfaceAnnouncer.DEFAULT_STAMP_VALUE, callback=None, discover_interfaces=True): def __init__(self, required_value=InterfaceAnnouncer.DEFAULT_STAMP_VALUE, callback=None, discover_interfaces=True):
@@ -389,6 +465,8 @@ class InterfaceDiscovery():
self.monitor_interval = self.MONITOR_INTERVAL self.monitor_interval = self.MONITOR_INTERVAL
self.detach_threshold = self.DETACH_THRESHOLD self.detach_threshold = self.DETACH_THRESHOLD
self.initial_autoconnect_ran = False self.initial_autoconnect_ran = False
self.blackholed_updated = 0
self.__blackholed = {}
if not self.rns_instance: raise SystemError("Attempt to start interface discovery listener without an active RNS instance") if not self.rns_instance: raise SystemError("Attempt to start interface discovery listener without an active RNS instance")
self.storagepath = os.path.join(RNS.Reticulum.storagepath, "discovery", "interfaces") self.storagepath = os.path.join(RNS.Reticulum.storagepath, "discovery", "interfaces")
@@ -399,10 +477,18 @@ class InterfaceDiscovery():
RNS.Transport.register_announce_handler(self.handler) RNS.Transport.register_announce_handler(self.handler)
threading.Thread(target=self.connect_discovered, daemon=True).start() threading.Thread(target=self.connect_discovered, daemon=True).start()
def __blackholed_identities(self):
st = time.time()
if not self.__blackholed or time.time() > self.blackholed_updated+60:
self.__blackholed = self.rns_instance.get_blackholed_identities()
self.blackholed_updated = time.time()
return self.__blackholed
def list_discovered_interfaces(self, only_available=False, only_transport=False): def list_discovered_interfaces(self, only_available=False, only_transport=False):
now = time.time() now = time.time()
discovered_interfaces = [] discovered_interfaces = []
discovery_sources = RNS.Reticulum.interface_discovery_sources() discovery_sources = RNS.Reticulum.interface_discovery_sources()
blackholed_identities = self.__blackholed_identities()
for filename in os.listdir(self.storagepath): for filename in os.listdir(self.storagepath):
try: try:
with self.discovery_lock: with self.discovery_lock:
@@ -410,13 +496,17 @@ class InterfaceDiscovery():
with open(filepath, "rb") as f: info = msgpack.unpackb(f.read()) with open(filepath, "rb") as f: info = msgpack.unpackb(f.read())
should_remove = False should_remove = False
heard_delta = now-info["last_heard"] heard_delta = now-info["last_heard"]
info["name"] = InterfaceAnnounceHandler.sanitize_name(info["name"]) info["name"] = InterfaceAnnounceHandler.sanitize_name(info["name"])
if heard_delta > self.THRESHOLD_REMOVE: should_remove = True if heard_delta > self.THRESHOLD_REMOVE: should_remove = True
elif not "transport_id" in info or not info["transport_id"]: should_remove = True
elif not "network_id" in info or not info["network_id"]: should_remove = True
elif discovery_sources and not "network_id" in info: should_remove = True elif discovery_sources and not "network_id" in info: should_remove = True
elif discovery_sources and not bytes.fromhex(info["network_id"]) in discovery_sources: should_remove = True elif discovery_sources and not bytes.fromhex(info["network_id"]) in discovery_sources: should_remove = True
elif not "type" in info or ("type" in info and not info["type"] in self.DISCOVERABLE_TYPES): should_remove = True elif not "type" in info or ("type" in info and not info["type"] in self.DISCOVERABLE_TYPES): should_remove = True
elif bytes.fromhex(info["network_id"]) in blackholed_identities: should_remove = True
elif bytes.fromhex(info["transport_id"]) in blackholed_identities: should_remove = True
elif "reachable_on" in info: elif "reachable_on" in info:
if not (is_ip_address(info["reachable_on"]) or is_hostname(info["reachable_on"])): should_remove = True if not (is_ip_address(info["reachable_on"]) or is_hostname(info["reachable_on"])): should_remove = True
@@ -642,14 +732,22 @@ class InterfaceDiscovery():
return return
if interface_type == "I2PInterface": if interface_type == "I2PInterface":
RNS.log(f"Auto-connecting discovered I2P interfaces is not yet implemented, aborting auto-connect", RNS.LOG_WARNING) RNS.log(f"Auto-connecting discovered I2P interfaces is not yet implemented, aborting auto-connect", RNS.LOG_DEBUG)
RNS.log(f"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", RNS.LOG_WARNING) RNS.log(f"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", RNS.LOG_DEBUG)
return return
if is_ygg_ipv6(info["reachable_on"]): if is_ygg_ipv6(info["reachable_on"]):
# TODO: Somehow detect if yggdrasil is enabled on the system # TODO: Somehow detect if yggdrasil is enabled on the system
return return
if is_onion_address(info["reachable_on"]):
# TODO: Somehow detect if TOR is enabled on the system
return
if is_ip_address(info["reachable_on"]) and is_invalid_ip_address(info["reachable_on"]):
RNS.log(f"Not auto-connecting discovered interface with invalid IP address: {info['reachable_on']}", RNS.LOG_DEBUG)
return
interface_name = info["name"] interface_name = info["name"]
config_entry = info["config_entry"] config_entry = info["config_entry"]
interface_config = {} interface_config = {}
@@ -668,12 +766,16 @@ class InterfaceDiscovery():
RNS.log(f"Auto-connecting discovered {interface_type} {interface_name}") RNS.log(f"Auto-connecting discovered {interface_type} {interface_name}")
interface.autoconnect_hash = endpoint_hash interface.autoconnect_hash = endpoint_hash
interface.autoconnect_source = info["network_id"] interface.autoconnect_source = info["network_id"]
mode = RNS.Interfaces.Interface.Interface.MODE_GATEWAY if RNS.Reticulum.transport_enabled() else None if RNS.Reticulum.autoconnect_interface_mode(): mode = RNS.Reticulum.autoconnect_interface_mode()
else: mode = self.AC_TRANSPORT_MODE if RNS.Reticulum.transport_enabled() else None
internal_a = True if RNS.Reticulum.autoconnect_announces_to_internal() else None
gravity = RNS.Reticulum.autoconnect_interface_gravity() or self.AC_GRAVITY
ar_target = RNS.Reticulum.get_instance()._default_ar_target() if RNS.Reticulum.transport_enabled() else None ar_target = RNS.Reticulum.get_instance()._default_ar_target() if RNS.Reticulum.transport_enabled() else None
ar_penalty = RNS.Reticulum.get_instance()._default_ar_penalty() if RNS.Reticulum.transport_enabled() else None ar_penalty = RNS.Reticulum.get_instance()._default_ar_penalty() if RNS.Reticulum.transport_enabled() else None
ar_grace = RNS.Reticulum.get_instance()._default_ar_grace() if RNS.Reticulum.transport_enabled() else None ar_grace = RNS.Reticulum.get_instance()._default_ar_grace() if RNS.Reticulum.transport_enabled() else None
RNS.Reticulum.get_instance()._add_interface(interface, mode=mode, ifac_netname=ifac_netname, ifac_netkey=ifac_netkey, configured_bitrate=5E6, RNS.Reticulum.get_instance()._add_interface(interface, mode=mode, ifac_netname=ifac_netname, ifac_netkey=ifac_netkey, configured_bitrate=5E6,
announce_rate_target=ar_target, announce_rate_grace=ar_grace, announce_rate_penalty=ar_penalty) announce_rate_target=ar_target, announce_rate_grace=ar_grace, announce_rate_penalty=ar_penalty,
announces_to_internal=internal_a, gravity=gravity)
self.monitor_interface(interface) self.monitor_interface(interface)
except Exception as e: except Exception as e:
@@ -746,7 +848,7 @@ class BlackholeUpdater():
if identity_hash in self.last_updates: last_update = self.last_updates[identity_hash] if identity_hash in self.last_updates: last_update = self.last_updates[identity_hash]
else: last_update = 0 else: last_update = 0
if now > last_update+self.UPDATE_INTERVAL: if now > last_update+RNS.Reticulum.blackhole_update_interval():
try: try:
destination_hash = RNS.Destination.hash_from_name_and_identity("rnstransport.info.blackhole", identity_hash) 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) RNS.log(f"Attempting blackhole list update from {RNS.prettyhexrep(identity_hash)}...", RNS.LOG_DEBUG)
@@ -776,6 +878,15 @@ def is_ygg_ipv6(address_string):
try: return ipaddress.ip_address(address_string) in ipaddress.IPv6Network("200::/7") try: return ipaddress.ip_address(address_string) in ipaddress.IPv6Network("200::/7")
except: return False except: return False
def is_onion_address(address_string):
try: return address_string.lower().endswith(".onion")
except: return False
INVALID_IP_ADDRESSES = ["127.0.0.1", "0.0.0.0"]
def is_invalid_ip_address(address_string):
if not address_string in INVALID_IP_ADDRESSES: return False
else: return True
def is_hostname(hostname): def is_hostname(hostname):
if hostname[-1] == ".": hostname = hostname[:-1] if hostname[-1] == ".": hostname = hostname[:-1]
if len(hostname) > 253: return False if len(hostname) > 253: return False
+53 -59
View File
@@ -127,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. :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: if from_identity_hash:
for destination_hash in Identity.known_destinations: with Identity.known_destinations_lock: destination_hashes = list(Identity.known_destinations.keys())
if target_hash == Identity.truncated_hash(Identity.known_destinations[destination_hash][2]): 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) 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 = Identity(create_keys=False)
identity.load_public_key(identity_data[2]) identity.load_public_key(entry[2])
identity.app_data = identity_data[3] identity.app_data = entry[3]
return identity return identity
return None return None
@@ -172,12 +174,9 @@ class Identity:
else: return None else: return None
@staticmethod @staticmethod
def save_known_destinations(background=False, recombine=True): def save_known_destinations(background=False, recombine=False):
# TODO: Improve the storage method so we don't have to if recombine: RNS.log(f"Recombining known destinations from disk cache on persist is deprecated, argument ignored", RNS.LOG_WARNING)
# deserialize and serialize the entire table on every if RNS.Transport.owner.is_connected_to_shared_instance: return
# save, but the only changes. It might be possible to
# simply overwrite on exit now that every local client
# disconnect triggers a data persist.
try: try:
if hasattr(Identity, "saving_known_destinations"): if hasattr(Identity, "saving_known_destinations"):
@@ -192,49 +191,26 @@ class Identity:
Identity.saving_known_destinations = True Identity.saving_known_destinations = True
save_start = time.time() save_start = time.time()
RNS.log("Saving "+str(len(Identity.known_destinations))+" known destinations to storage...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if recombine:
storage_known_destinations = {}
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
try:
with open(RNS.Reticulum.storagepath+"/known_destinations","rb") as file:
storage_known_destinations = umsgpack.load(file)
except: pass
try:
for destination_hash in storage_known_destinations:
if not destination_hash in Identity.known_destinations:
with Identity.known_destinations_lock:
Identity.known_destinations[destination_hash] = storage_known_destinations[destination_hash]
except Exception as e:
RNS.log("Skipped recombining known destinations from disk, since an error occurred: "+str(e), RNS.LOG_WARNING)
RNS.log("Saving "+str(len(Identity.known_destinations))+" known destinations to storage...", RNS.LOG_VERBOSE)
temp_file = RNS.Reticulum.storagepath+f"/known_destinations.tmp.{time.time()}" temp_file = RNS.Reticulum.storagepath+f"/known_destinations.tmp.{time.time()}"
try: try:
with open(temp_file,"wb") as file: umsgpack.dump(Identity.known_destinations.copy(), file) with open(temp_file,"wb") as file: umsgpack.dump(Identity.known_destinations.copy(), file)
os.rename(temp_file, RNS.Reticulum.storagepath+f"/known_destinations") os.replace(temp_file, RNS.Reticulum.storagepath+f"/known_destinations")
except Exception as e: except Exception as e:
RNS.log(f"Error while serializing and writing known destinations: {e}", RNS.LOG_ERROR) RNS.log(f"Error while serializing and writing known destinations: {e}", RNS.LOG_ERROR)
try: os.unlink(temp_file) try: os.unlink(temp_file)
except Exception as e: RNS.log(f"Could not clean up temporary file {temp_file}: {e}", RNS.LOG_WARNING) except Exception as exc: RNS.log(f"Could not clean up temporary file {temp_file}: {exc}", RNS.LOG_WARNING)
raise e raise e
save_time = time.time() - save_start RNS.log(f"Saved known destinations to storage in {RNS.prettyshorttime(time.time()-save_start)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if save_time < 1: time_str = str(round(save_time*1000,2))+"ms"
else: time_str = str(round(save_time,2))+"s"
RNS.log("Saved known destinations to storage in "+time_str, RNS.LOG_VERBOSE)
except Exception as e: except Exception as e:
RNS.log("Error while saving known destinations to disk, the contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error while saving known destinations to disk, the contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.trace_exception(e) RNS.trace_exception(e)
Identity.saving_known_destinations = False finally: Identity.saving_known_destinations = False
@staticmethod @staticmethod
def load_known_destinations(): def load_known_destinations():
@@ -294,8 +270,11 @@ class Identity:
def _retain_identity(identity_hash): def _retain_identity(identity_hash):
try: try:
retained = False retained = False
for destination_hash in Identity.known_destinations: with Identity.known_destinations_lock: destination_hashes = list(Identity.known_destinations.keys())
if identity_hash == Identity.truncated_hash(Identity.known_destinations[destination_hash][2]): 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 if Identity._retain_destination_data(destination_hash): retained = True
return retained return retained
@@ -303,7 +282,7 @@ class Identity:
except Exception as e: RNS.log(f"Error while retaining identity {RNS.prettyhexrep(identity_hash)}: {e}", RNS.LOG_ERROR) except Exception as e: RNS.log(f"Error while retaining identity {RNS.prettyhexrep(identity_hash)}: {e}", RNS.LOG_ERROR)
@staticmethod @staticmethod
def clean_known_destinations(): def clean_known_destinations(background=False):
now = time.time() now = time.time()
st = now st = now
total = len(Identity.known_destinations) total = len(Identity.known_destinations)
@@ -311,8 +290,15 @@ class Identity:
no_path = 0 no_path = 0
retained = 0 retained = 0
never_used = 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: try:
if background: time.sleep(0.001) # Low priority, yield thread
RNS.Transport.destinations_last_cleaned = time.time()
if RNS.Transport.has_path(destination_hash): has_path = True if RNS.Transport.has_path(destination_hash): has_path = True
else: else:
has_path = False has_path = False
@@ -352,7 +338,14 @@ class Identity:
Identity.known_destinations.pop(destination_hash) Identity.known_destinations.pop(destination_hash)
removed += 1 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) if not RNS.Transport.owner.is_connected_to_shared_instance: Identity.save_known_destinations(recombine=False)
@staticmethod @staticmethod
@@ -515,7 +508,7 @@ class Identity:
return None return None
@staticmethod @staticmethod
def validate_announce(packet, only_validate_signature=False): def validate_announce(packet, only_validate_signature=False, signal_blackholed=False):
try: try:
if packet.packet_type == RNS.Packet.ANNOUNCE: if packet.packet_type == RNS.Packet.ANNOUNCE:
keysize = Identity.KEYSIZE//8 keysize = Identity.KEYSIZE//8
@@ -560,9 +553,11 @@ class Identity:
if len(RNS.Transport.blackholed_identities) > 0: if len(RNS.Transport.blackholed_identities) > 0:
if announced_identity.hash in RNS.Transport.blackholed_identities: if announced_identity.hash in RNS.Transport.blackholed_identities:
RNS.log(f"Invalidated and dropped announce from blackholed identity {RNS.prettyhexrep(announced_identity.hash)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None RNS.log(f"Invalidated and dropped announce from blackholed identity {RNS.prettyhexrep(announced_identity.hash)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return False if signal_blackholed: return "blackholed"
else: return False
if announced_identity.pub != None and announced_identity.validate(signature, signed_data): if announced_identity.pub != None and (packet.announce_signature_validated or announced_identity.validate(signature, signed_data)):
packet.announce_signature_validated = True
if only_validate_signature: if only_validate_signature:
del announced_identity del announced_identity
return True return True
@@ -588,21 +583,18 @@ class Identity:
signal_str = " [" signal_str = " ["
if packet.rssi != None: if packet.rssi != None:
signal_str += "RSSI "+str(packet.rssi)+"dBm" signal_str += "RSSI "+str(packet.rssi)+"dBm"
if packet.snr != None: if packet.snr != None: signal_str += ", "
signal_str += ", " if packet.snr != None: signal_str += "SNR "+str(packet.snr)+"dB"
if packet.snr != None:
signal_str += "SNR "+str(packet.snr)+"dB"
signal_str += "]" signal_str += "]"
else:
signal_str = "" else: signal_str = ""
if hasattr(packet, "transport_id") and packet.transport_id != None: 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) if RNS.sl(RNS.LOG_EXTREME) else 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) if RNS.sl(RNS.LOG_EXTREME) else None
else: 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) if RNS.sl(RNS.LOG_EXTREME) else None 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: if ratchet: Identity._remember_ratchet(destination_hash, ratchet)
Identity._remember_ratchet(destination_hash, ratchet)
return True return True
@@ -767,9 +759,7 @@ class Identity:
return True return True
except Exception as e: except Exception as e:
raise e RNS.log(f"Failed to load identity key, the contained exception was: {e}", RNS.LOG_ERROR)
RNS.log("Failed to load identity key", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
return False return False
def load_public_key(self, pub_bytes): def load_public_key(self, pub_bytes):
@@ -787,8 +777,12 @@ class Identity:
self.sig_pub = Ed25519PublicKey.from_public_bytes(self.sig_pub_bytes) self.sig_pub = Ed25519PublicKey.from_public_bytes(self.sig_pub_bytes)
self.update_hashes() self.update_hashes()
return True
except Exception as e: 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): def update_hashes(self):
self.hash = Identity.truncated_hash(self.get_public_key()) self.hash = Identity.truncated_hash(self.get_public_key())
+1
View File
@@ -128,6 +128,7 @@ class AX25KISSInterface(Interface):
self.packet_queue = [] self.packet_queue = []
self.flow_control = flow_control self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False self.interface_ready = False
self.flow_control_timeout = 5 self.flow_control_timeout = 5
self.flow_control_locked = time.time() self.flow_control_locked = time.time()
+1
View File
@@ -131,6 +131,7 @@ class KISSInterface(Interface):
self.packet_queue = [] self.packet_queue = []
self.flow_control = flow_control self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False self.interface_ready = False
self.flow_control_timeout = 5 self.flow_control_timeout = 5
self.flow_control_locked = time.time() 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): if (port != None or device_serial != None) and (enable_bluetooth or disable_bluetooth or pairing_mode):
serial = None serial = None
bluetooth_state = None bluetooth_state = None
if pairing_mode: if pairing_mode: bluetooth_state = 0x01
bluetooth_state = 0x01 elif enable_bluetooth: bluetooth_state = 0x01
elif enable_bluetooth: elif disable_bluetooth: bluetooth_state = 0x00
bluetooth_state = 0x01
elif disable_bluetooth:
bluetooth_state = 0x00
if port != None: if port != None:
RNS.log("Opening serial port "+port+"...") RNS.log("Opening serial port "+port+"...")
@@ -518,6 +515,7 @@ class RNodeInterface(Interface):
self.packet_queue = [] self.packet_queue = []
self.flow_control = flow_control self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False self.interface_ready = False
self.announce_rate_target = None self.announce_rate_target = None
self.last_port_io = 0 self.last_port_io = 0
@@ -1742,7 +1740,7 @@ class BLEConnection(BluetoothDispatcher):
ble_devices = self.find_target_devices() ble_devices = self.find_target_devices()
if len(ble_devices) > 0: self.ble_device = ble_devices.pop() if len(ble_devices) > 0: self.ble_device = ble_devices.pop()
else: self.ble_device == None else: self.ble_device = None
if self.ble_device != None: if self.ble_device != None:
if self.was_connected: if self.was_connected:
@@ -95,6 +95,7 @@ class SerialInterface(Interface):
raise ValueError("No port specified for serial interface") raise ValueError("No port specified for serial interface")
self.HW_MTU = 564 self.HW_MTU = 564
self.shared_medium = True
self.pyserial = serial self.pyserial = serial
self.serial = None self.serial = None
+4 -2
View File
@@ -33,5 +33,7 @@ import glob
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py") py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc") pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
__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"))])) 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__"]))
+13 -4
View File
@@ -428,14 +428,22 @@ class AutoInterface(Interface):
if ifname in self.interface_servers: if ifname in self.interface_servers:
RNS.log("Shutting down previous UDP listener for "+str(self)+" "+str(ifname), RNS.LOG_DEBUG) RNS.log("Shutting down previous UDP listener for "+str(self)+" "+str(ifname), RNS.LOG_DEBUG)
previous_server = self.interface_servers[ifname] previous_server = self.interface_servers[ifname]
def shutdown_server(): def shutdown_server(): previous_server.shutdown()
previous_server.shutdown()
threading.Thread(target=shutdown_server, daemon=True).start() threading.Thread(target=shutdown_server, daemon=True).start()
RNS.log("Starting new UDP listener for "+str(self)+" "+str(ifname), RNS.LOG_DEBUG) 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)) retry_delay = 1.25
self.interface_servers[ifname] = udp_server 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 = threading.Thread(target=udp_server.serve_forever)
thread.daemon = True thread.daemon = True
@@ -572,6 +580,7 @@ class AutoInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True spawned_interface.online = True
RNS.Transport.add_interface(spawned_interface) RNS.Transport.add_interface(spawned_interface)
+446 -111
View File
@@ -29,6 +29,8 @@
# SOFTWARE. # SOFTWARE.
from RNS.Interfaces.Interface import Interface from RNS.Interfaces.Interface import Interface
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
import threading import threading
import socket import socket
import select import select
@@ -37,29 +39,47 @@ import sys
import os import os
import RNS 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): class BackboneInterface(Interface):
HW_MTU = 1048576 HW_MTU = 1048576
BITRATE_GUESS = 1_000_000_000 BITRATE_GUESS = 100_000_000
DEFAULT_IFAC_SIZE = 16 DEFAULT_IFAC_SIZE = 16
AUTOCONFIGURE_MTU = True AUTOCONFIGURE_MTU = True
BLOCK_FAST_FLAPPING = True
FAST_FLAP_THRESHOLD = 20
FAST_FLAP_GRACE = 5
FAST_FLAP_EXPIRY = 12*60*60
fast_flapping_lock = threading.Lock()
fast_flapping = {}
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 epoll = None
listener_filenos = {} listener_filenos = {}
spawned_interface_filenos = {} spawned_interface_filenos = {}
epoll = None
_job_active = False _job_active = False
_job_lock = threading.Lock() _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 @staticmethod
def get_address_for_if(name, bind_port, prefer_ipv6=False): def get_address_for_if(name, bind_port, prefer_ipv6=False):
@@ -109,13 +129,17 @@ class BackboneInterface(Interface):
super().__init__() super().__init__()
c = Interface.get_config_obj(configuration) c = Interface.get_config_obj(configuration)
name = c["name"] name = c["name"]
device = c["device"] if "device" in c else None device = c["device"] if "device" in c else None
port = int(c["port"]) if "port" in c else None port = int(c["port"]) if "port" in c else None
bindip = c["listen_ip"] if "listen_ip" in c else None bindip = c["listen_ip"] if "listen_ip" in c else None
bindport = int(c["listen_port"]) if "listen_port" in c else None bindport = int(c["listen_port"]) if "listen_port" in c else None
prefer_ipv6 = c.as_bool("prefer_ipv6") if "prefer_ipv6" in c else False prefer_ipv6 = c.as_bool("prefer_ipv6") if "prefer_ipv6" in c else False
flap_block = c.as_bool("block_fast_flapping") if "block_fast_flapping" in c else BackboneInterface.BLOCK_FAST_FLAPPING
flap_threshold = c.as_float("fast_flapping_threshold") if "fast_flapping_threshold" in c else BackboneInterface.FAST_FLAP_THRESHOLD
flap_grace = c.as_int("fast_flapping_grace") if "fast_flapping_grace" in c else BackboneInterface.FAST_FLAP_GRACE
flap_expiry = c.as_float("fast_flapping_block_time")*60 if "fast_flapping_block_time" in c else BackboneInterface.FAST_FLAP_EXPIRY
if port != None: bindport = port if port != None: bindport = port
@@ -128,11 +152,13 @@ class BackboneInterface(Interface):
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.spawned_interfaces = [] self.spawned_interfaces = []
self.supports_discovery = True self.supports_discovery = True
self.block_fast_flapping = flap_block
self.fast_flap_threshold = flap_threshold
self.fast_flap_grace = flap_grace
self.fast_flap_expiry = flap_expiry
if bindport == None: if bindport == None: raise SystemError(f"No TCP port configured for interface \"{name}\"")
raise SystemError(f"No TCP port configured for interface \"{name}\"") else: self.bind_port = bindport
else:
self.bind_port = bindport
bind_address = None bind_address = None
if device != None: if device != None:
@@ -156,13 +182,34 @@ class BackboneInterface(Interface):
else: else:
raise SystemError("Insufficient parameters to create listener") raise SystemError("Insufficient parameters to create listener")
__ic_burst_stats_throttle = 0.95
__last_ic_burst_count_check = 0
__last_ic_burst_count_state = 0
@property
def ic_burst_count(self):
if time.time() > self.__last_ic_burst_count_check + self.__ic_burst_stats_throttle:
self.__last_ic_burst_count_state = len([i.ic_burst_active for i in self.spawned_interfaces if i.ic_burst_active])
self.__last_ic_burst_count_check = time.time()
return self.__last_ic_burst_count_state
__last_ic_pr_burst_count_check = 0
__last_ic_pr_burst_count_state = 0
@property
def ic_pr_burst_count(self):
if time.time() > self.__last_ic_pr_burst_count_check + self.__ic_burst_stats_throttle:
self.__last_ic_pr_burst_count_state = len([i.ic_pr_burst_active for i in self.spawned_interfaces if i.ic_pr_burst_active])
self.__last_ic_pr_burst_count_check = time.time()
return self.__last_ic_pr_burst_count_state
__last_ic_burst_check = 0 __last_ic_burst_check = 0
__last_ic_burst_state = False __last_ic_burst_state = False
@property @property
def ic_burst_active(self): def ic_burst_active(self):
if time.time() > self.__last_ic_burst_check + 2: if time.time() > self.__last_ic_burst_check + self.__ic_burst_stats_throttle:
self.__last_ic_burst_state = any(i.ic_burst_active for i in self.spawned_interfaces) self.__last_ic_burst_state = any(i.ic_burst_active for i in self.spawned_interfaces)
self.__last_ic_burst_check = time.time()
return self.__last_ic_burst_state return self.__last_ic_burst_state
@@ -173,9 +220,10 @@ class BackboneInterface(Interface):
__ic_burst_activated = 0 __ic_burst_activated = 0
@property @property
def ic_burst_activated(self): def ic_burst_activated(self):
if time.time() > self.__ic_burst_activated_check + 2: if time.time() > self.__ic_burst_activated_check + self.__ic_burst_stats_throttle:
activated = [i.ic_burst_activated for i in self.spawned_interfaces if i.ic_burst_active] activated = [i.ic_burst_activated for i in self.spawned_interfaces if i.ic_burst_active]
if activated: self.__ic_burst_activated = min(activated) if activated: self.__ic_burst_activated = min(activated)
self.__ic_burst_activated_check = time.time()
return self.__ic_burst_activated return self.__ic_burst_activated
@@ -187,8 +235,9 @@ class BackboneInterface(Interface):
__last_ic_pr_burst_state = False __last_ic_pr_burst_state = False
@property @property
def ic_pr_burst_active(self): def ic_pr_burst_active(self):
if time.time() > self.__last_ic_pr_burst_check + 2: if time.time() > self.__last_ic_pr_burst_check + self.__ic_burst_stats_throttle:
self.__last_ic_pr_burst_state = any(i.ic_pr_burst_active for i in self.spawned_interfaces) self.__last_ic_pr_burst_state = any(i.ic_pr_burst_active for i in self.spawned_interfaces)
self.__last_ic_pr_burst_check = time.time()
return self.__last_ic_pr_burst_state return self.__last_ic_pr_burst_state
@@ -199,9 +248,10 @@ class BackboneInterface(Interface):
__ic_pr_burst_activated = 0 __ic_pr_burst_activated = 0
@property @property
def ic_pr_burst_activated(self): def ic_pr_burst_activated(self):
if time.time() > self.__ic_pr_burst_activated_check + 2: if time.time() > self.__ic_pr_burst_activated_check + self.__ic_burst_stats_throttle:
activated = [i.ic_pr_burst_activated for i in self.spawned_interfaces if i.ic_pr_burst_active] activated = [i.ic_pr_burst_activated for i in self.spawned_interfaces if i.ic_pr_burst_active]
if activated: self.__ic_pr_burst_activated = min(activated) if activated: self.__ic_pr_burst_activated = min(activated)
self.__ic_pr_burst_activated_check = time.time()
return self.__ic_pr_burst_activated return self.__ic_pr_burst_activated
@@ -210,7 +260,9 @@ class BackboneInterface(Interface):
@staticmethod @staticmethod
def start(): 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 @staticmethod
def ensure_epoll(): def ensure_epoll():
@@ -251,9 +303,9 @@ class BackboneInterface(Interface):
RNS.log(f"Attempt to register invalid file descriptor {fileno}", RNS.LOG_WARNING) RNS.log(f"Attempt to register invalid file descriptor {fileno}", RNS.LOG_WARNING)
return return
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN) try: BackboneInterface.epoll.register(fileno, select.EPOLLIN | select.EPOLLHUP)
except Exception as e: except Exception as e:
RNS.log(f"An error occurred while registering EPOLL_IN for file descriptor {fileno}: {e}", RNS.LOG_WARNING) RNS.log(f"An error occurred while registering EPOLLIN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
@staticmethod @staticmethod
def deregister_fileno(fileno): def deregister_fileno(fileno):
@@ -263,7 +315,9 @@ class BackboneInterface(Interface):
try: BackboneInterface.epoll.unregister(fileno) try: BackboneInterface.epoll.unregister(fileno)
except Exception as e: except Exception as e:
RNS.log(f"An error occurred while deregistering file descriptor {fileno}: {e}", RNS.LOG_DEBUG) if str(e).endswith("No such file or directory"): pass
elif str(e).endswith("Bad file descriptor"): pass
else: RNS.log(f"An error occurred while deregistering file descriptor {fileno}: {e}", RNS.LOG_DEBUG)
@staticmethod @staticmethod
def deregister_listeners(): def deregister_listeners():
@@ -280,11 +334,223 @@ class BackboneInterface(Interface):
if interface.socket: if interface.socket:
fileno = interface.socket.fileno() fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos: if fileno in BackboneInterface.spawned_interface_filenos:
try: BackboneInterface.epoll.modify(fileno, select.EPOLLOUT) try:
events = select.EPOLLOUT | select.EPOLLHUP
if not interface.dp_ingress_gated: events |= select.EPOLLIN
BackboneInterface.epoll.modify(fileno, events)
except Exception as e: except Exception as e:
RNS.log(f"Error occurred on {interface} while modifying socket EPOLL state: {e}", RNS.LOG_WARNING) if str(e).endswith("No such file or directory"): pass
elif str(e).endswith("Bad file descriptor"): pass
else: RNS.log(f"Error occurred on {interface} while modifying socket EPOLL state: {e}", RNS.LOG_WARNING)
raise e raise e
@staticmethod
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 @staticmethod
def __job(): def __job():
with BackboneInterface._job_lock: with BackboneInterface._job_lock:
@@ -294,18 +560,21 @@ class BackboneInterface(Interface):
BackboneInterface.ensure_epoll() BackboneInterface.ensure_epoll()
try: try:
while True: while True:
events = BackboneInterface.epoll.poll(1)
for fileno, event in BackboneInterface.epoll.poll(1): for fileno, event in BackboneInterface.epoll.poll(1):
if fileno in BackboneInterface.spawned_interface_filenos: if fileno in BackboneInterface.spawned_interface_filenos:
spawned_interface = BackboneInterface.spawned_interface_filenos[fileno] spawned_interface = BackboneInterface.spawned_interface_filenos[fileno]
client_socket = spawned_interface.socket client_socket = spawned_interface.socket
if client_socket and fileno == client_socket.fileno() and (event & select.EPOLLIN): socket_valid = client_socket and fileno == client_socket.fileno()
if socket_valid and (event & select.EPOLLIN) and not spawned_interface.dp_ingress_gated:
if spawned_interface.dp_ingress_gated: continue
try: received_bytes = client_socket.recv(spawned_interface.HW_MTU) try: received_bytes = client_socket.recv(spawned_interface.HW_MTU)
except Exception as e: except Exception as e:
RNS.log(f"Error while reading from {spawned_interface}: {e}", RNS.LOG_DEBUG) RNS.log(f"Error while reading from {spawned_interface}: {e}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
received_bytes = b"" received_bytes = b""
if len(received_bytes): spawned_interface.receive(received_bytes) if len(received_bytes):
spawned_interface.dp_ingress_bytes += len(received_bytes)
spawned_interface.receive(received_bytes)
else: else:
BackboneInterface.deregister_fileno(fileno); client_socket.close() BackboneInterface.deregister_fileno(fileno); client_socket.close()
try: try:
@@ -321,11 +590,18 @@ class BackboneInterface(Interface):
spawned_interface.receive(received_bytes) spawned_interface.receive(received_bytes)
elif client_socket and fileno == client_socket.fileno() and (event & select.EPOLLOUT): socket_valid_after_read = socket_valid and fileno in BackboneInterface.spawned_interface_filenos
try: written = client_socket.send(spawned_interface.transmit_buffer) if socket_valid_after_read and (event & select.EPOLLOUT):
try: written = spawned_interface.transmit_buffer.drain_to(client_socket)
except Exception as e: except Exception as e:
written = 0 written = 0
if not spawned_interface.detached: RNS.log(f"Error while writing to {spawned_interface}: {e}", RNS.LOG_DEBUG) if not spawned_interface.detached:
if RNS.sl(RNS.LOG_DEBUG):
if str(e).endswith("Connection timed out"): pass
elif str(e).endswith("Connection reset by peer"): pass
elif str(e).endswith("No route to host"): pass
elif str(e).endswith("Broken pipe"): pass
else: RNS.log(f"Error while writing to {spawned_interface}: {e}", RNS.LOG_DEBUG)
BackboneInterface.deregister_fileno(fileno) BackboneInterface.deregister_fileno(fileno)
try: try:
@@ -343,16 +619,17 @@ class BackboneInterface(Interface):
except Exception as e: RNS.log(f"Error while closing socket for {spawned_interface}: {e}", RNS.LOG_WARNING) except Exception as e: RNS.log(f"Error while closing socket for {spawned_interface}: {e}", RNS.LOG_WARNING)
spawned_interface.receive(b"") spawned_interface.receive(b"")
spawned_interface.transmit_buffer = spawned_interface.transmit_buffer[written:]
try: try:
if len(spawned_interface.transmit_buffer) == 0: BackboneInterface.epoll.modify(fileno, select.EPOLLIN) if spawned_interface.transmit_buffer.sendable == 0:
except Exception as e: events = select.EPOLLHUP
RNS.log(f"Error while setting EPOLLIN on {spawned_interface}: {e}", RNS.LOG_ERROR) 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 spawned_interface.txb += written
if spawned_interface.parent_interface: spawned_interface.parent_interface.txb += written if spawned_interface.parent_interface: spawned_interface.parent_interface.txb += written
elif client_socket and fileno == client_socket.fileno() and event & (select.EPOLLHUP): elif socket_valid_after_read and (event & select.EPOLLHUP):
BackboneInterface.deregister_fileno(fileno) BackboneInterface.deregister_fileno(fileno)
try: try:
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno) if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
@@ -375,11 +652,12 @@ class BackboneInterface(Interface):
try: try:
client_socket, address = server_socket.accept() client_socket, address = server_socket.accept()
client_socket.setblocking(0) 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): if not owner_interface.incoming_connection(client_socket):
try: client_socket.close() try: client_socket.close()
except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_WARNING) except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_WARNING)
except: except Exception as e:
RNS.log(f"Accepting socket failed for incoming connection: {e}", RNS.LOG_WARNING) RNS.log(f"Accepting socket failed for incoming connection: {e}", RNS.LOG_WARNING)
try: client_socket.close() try: client_socket.close()
except Exception as e: RNS.log(f"Error while closing socket for failed incoming socket accept: {e}", RNS.LOG_WARNING) except Exception as e: RNS.log(f"Error while closing socket for failed incoming socket accept: {e}", RNS.LOG_WARNING)
@@ -399,8 +677,22 @@ class BackboneInterface(Interface):
BackboneInterface.deregister_listeners() BackboneInterface.deregister_listeners()
def incoming_connection(self, socket): def incoming_connection(self, socket):
RNS.log("Accepting incoming connection", RNS.LOG_VERBOSE)
try: try:
remote_ip = socket.getpeername()[0]
remote_port = str(socket.getpeername()[1])
if self.blocked_ip_count > 0:
with BackboneInterface.fast_flapping_lock:
if remote_ip in BackboneInterface.fast_flapping:
now = time.time()
ffe = BackboneInterface.fast_flapping[remote_ip]
started_flapping = ffe[0]
last_flap = ffe[1]
flaps = ffe[2]
if flaps > self.fast_flap_grace:
RNS.log(f"Ignoring incoming connection from fast-flapping IP {remote_ip}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
return False
RNS.log("Accepting incoming connection", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
spawned_configuration = {"name": "Client on "+self.name, "target_host": None, "target_port": None} spawned_configuration = {"name": "Client on "+self.name, "target_host": None, "target_port": None}
spawned_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket) spawned_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket)
spawned_interface.OUT = self.OUT spawned_interface.OUT = self.OUT
@@ -421,8 +713,8 @@ class BackboneInterface(Interface):
spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq spawned_interface.ic_pr_burst_freq = self.ic_pr_burst_freq
spawned_interface.socket = socket spawned_interface.socket = socket
spawned_interface.target_ip = socket.getpeername()[0] spawned_interface.target_ip = remote_ip
spawned_interface.target_port = str(socket.getpeername()[1]) spawned_interface.target_port = remote_port
spawned_interface.parent_interface = self spawned_interface.parent_interface = self
spawned_interface.bitrate = self.bitrate spawned_interface.bitrate = self.bitrate
spawned_interface.optimise_mtu() spawned_interface.optimise_mtu()
@@ -432,18 +724,12 @@ class BackboneInterface(Interface):
spawned_interface.ifac_netkey = self.ifac_netkey spawned_interface.ifac_netkey = self.ifac_netkey
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None: if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
ifac_origin = b"" ifac_origin = b""
if spawned_interface.ifac_netname != None: if spawned_interface.ifac_netname != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8")) if spawned_interface.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
if spawned_interface.ifac_netkey != None:
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin) ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
spawned_interface.ifac_key = RNS.Cryptography.hkdf( spawned_interface.ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=ifac_origin_hash,
length=64, salt=RNS.Reticulum.IFAC_SALT, context=None)
derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT,
context=None
)
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key) spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key)) spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
@@ -451,13 +737,15 @@ class BackboneInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
RNS.Transport.add_interface(spawned_interface) RNS.Transport.add_interface(spawned_interface)
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface) while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.append(spawned_interface) self.spawned_interfaces.append(spawned_interface)
BackboneInterface.add_client_socket(socket, spawned_interface) BackboneInterface.add_client_socket(socket, spawned_interface)
spawned_interface.spawned_at = time.time()
spawned_interface.online = True
except Exception as e: except Exception as e:
RNS.log(f"An error occurred while accepting incoming connection on {self}: {e}", RNS.LOG_ERROR) RNS.log(f"An error occurred while accepting incoming connection on {self}: {e}", RNS.LOG_ERROR)
@@ -465,17 +753,25 @@ class BackboneInterface(Interface):
return True return True
def received_announce(self, from_spawned=False): def received_announce(self, size=0, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time()) if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False): def sent_announce(self, size=0, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time()) if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, from_spawned=False): def received_path_request(self, size=0, from_spawned=False):
if from_spawned: self.ip_freq_deque.append(time.time()) if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, from_spawned=False): def sent_path_request(self, size=0, from_spawned=False):
if from_spawned: self.op_freq_deque.append(time.time()) if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def process_outgoing(self, data): def process_outgoing(self, data):
pass pass
@@ -491,15 +787,43 @@ class BackboneInterface(Interface):
if callable(listener_socket.shutdown): if callable(listener_socket.shutdown):
try: listener_socket.shutdown(socket.SHUT_RDWR) try: listener_socket.shutdown(socket.SHUT_RDWR)
except Exception as e: except Exception as e:
if str(e).endswith("Transport endpoint is not connected"): pass if str(e).endswith("Transport endpoint is not connected"): pass
elif str(e).endswith("Bad file descriptor"): pass
else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR) else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR)
def __str__(self): @property
if ":" in self.bind_ip: def blocked_ip_list(self):
ip_str = f"[{self.bind_ip}]" if not self.block_fast_flapping: return []
else: else: return [ip for ip in self.fast_flapping if self.fast_flapping[ip][2] > self.fast_flap_grace]
ip_str = f"{self.bind_ip}"
@property
def blocked_ip_count(self):
if not self.block_fast_flapping: return 0
else:
count = 0
expired = []
now = time.time()
with BackboneInterface.fast_flapping_lock:
for remote_ip in BackboneInterface.fast_flapping:
ffe = BackboneInterface.fast_flapping[remote_ip]
started_flapping = ffe[0]
last_flap = ffe[1]
flaps = ffe[2]
if now - last_flap > self.fast_flap_expiry: expired.append(remote_ip)
elif flaps > self.fast_flap_grace: count += 1
for remote_ip in expired:
if remote_ip in BackboneInterface.fast_flapping:
try:
BackboneInterface.fast_flapping.pop(remote_ip)
RNS.log(f"Fast-flapping block expired for {remote_ip}", RNS.LOG_DEBUG)
except Exception as e: RNS.log(f"Error while expiring fast-flapping block for {remote_ip}: {e}", RNS.LOG_ERROR)
return count
def __str__(self):
if ":" in self.bind_ip: ip_str = f"[{self.bind_ip}]"
else: ip_str = f"{self.bind_ip}"
return "BackboneInterface["+self.name+"/"+ip_str+":"+str(self.bind_port)+"]" return "BackboneInterface["+self.name+"/"+ip_str+":"+str(self.bind_port)+"]"
@@ -548,8 +872,10 @@ class BackboneClientInterface(Interface):
self.i2p_tunneled = i2p_tunneled self.i2p_tunneled = i2p_tunneled
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.bitrate = BackboneClientInterface.BITRATE_GUESS self.bitrate = BackboneClientInterface.BITRATE_GUESS
self.frame_buffer = b"" self.transmit_buffer = TransmitBuffer()
self.transmit_buffer = b"" 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: if max_reconnect_tries == None:
self.max_reconnect_tries = BackboneClientInterface.RECONNECT_MAX_TRIES self.max_reconnect_tries = BackboneClientInterface.RECONNECT_MAX_TRIES
@@ -608,7 +934,8 @@ class BackboneClientInterface(Interface):
try: try:
if self.socket != None: self.socket.shutdown(socket.SHUT_RDWR) if self.socket != None: self.socket.shutdown(socket.SHUT_RDWR)
except Exception as e: except Exception as e:
if str(e).endswith("Transport endpoint is not connected"): pass if str(e).endswith("Transport endpoint is not connected"): pass
elif str(e).endswith("Bad file descriptor"): pass
else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR) else: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e), RNS.LOG_ERROR)
try: try:
@@ -637,6 +964,7 @@ class BackboneClientInterface(Interface):
self.socket.settimeout(BackboneClientInterface.INITIAL_CONNECT_TIMEOUT) self.socket.settimeout(BackboneClientInterface.INITIAL_CONNECT_TIMEOUT)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.connect(target_address) self.socket.connect(target_address)
# TODO: Check missing setblocking(0)
self.socket.settimeout(None) self.socket.settimeout(None)
BackboneInterface.add_client_socket(self.socket, self) BackboneInterface.add_client_socket(self.socket, self)
@@ -697,40 +1025,30 @@ class BackboneClientInterface(Interface):
if hasattr(self, "parent_interface") and self.parent_interface != None: if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.rxb += len(data) self.parent_interface.rxb += len(data)
self.dp_ingress_packets += 1
self.owner.inbound(data, self) self.owner.inbound(data, self)
def process_outgoing(self, data): def process_outgoing(self, data):
if self.online and not self.detached: if self.online and not self.detached:
try: try:
self.transmit_buffer += bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG]) frame = HDLC.frame(data)
BackboneInterface.tx_ready(self) 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: except Exception as e:
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR) RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
self.teardown() self.teardown()
def invalid_frame(self, frame_len):
RNS.log(f"Invalid HDLC frame of {RNS.prettysize(frame_len)} received on {self}, dropping frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
def receive(self, data_in): def receive(self, data_in):
try: try:
if len(data_in) > 0: if len(data_in) > 0: self.receive_buffer.feed(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
else: else:
self.online = False self.online = False
if self.initiator and not self.detached: if self.initiator and not self.detached:
@@ -738,7 +1056,7 @@ class BackboneClientInterface(Interface):
def job(): self.reconnect() def job(): self.reconnect()
threading.Thread(target=job, daemon=True).start() threading.Thread(target=job, daemon=True).start()
else: else:
RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_DEBUG) RNS.log("The socket for remote client "+str(self)+" was closed.", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
self.teardown() self.teardown()
except Exception as e: except Exception as e:
@@ -749,17 +1067,34 @@ class BackboneClientInterface(Interface):
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING) RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
def job(): self.reconnect() def job(): self.reconnect()
threading.Thread(target=job, daemon=True).start() threading.Thread(target=job, daemon=True).start()
else: else: self.teardown()
self.teardown()
def teardown(self): def teardown(self):
if self.initiator and not self.detached: if self.initiator and not self.detached:
RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR) RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR)
if RNS.Reticulum.panic_on_interface_error: if RNS.Reticulum.panic_on_interface_error: RNS.panic()
RNS.panic()
else: else:
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE) RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
if self.parent_interface and self.parent_interface.block_fast_flapping and hasattr(self, "spawned_at"):
connected_time = time.time() - self.spawned_at
if connected_time < self.parent_interface.fast_flap_threshold:
try:
now = time.time()
remote_id = f"{self.target_ip}"
with BackboneInterface.fast_flapping_lock:
if remote_id in BackboneInterface.fast_flapping: ffe = BackboneInterface.fast_flapping[remote_id]
else: ffe = [now, now, 0]
ffe[1] = now
ffe[2] += 1
with BackboneInterface.fast_flapping_lock: BackboneInterface.fast_flapping[remote_id] = ffe
dt = now-ffe[0]; fff = ffe[2]/dt if dt > 0 else None
freq_str = f" at {RNS.prettyfrequency(fff)}" if fff else ""
RNS.log(f"{self} is fast flapping{freq_str}, connection time was {RNS.prettytime(connected_time)}, {ffe[2]} fast flaps", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if ffe[2] > self.parent_interface.fast_flap_grace: RNS.log(f"Ignoring further connections from {remote_id} due to fast-flapping", RNS.LOG_WARNING)
except Exception as e: RNS.log(f"Error while updating fast-flapping interface statistics: {e}", RNS.LOG_ERROR)
self.online = False self.online = False
self.OUT = False self.OUT = False
+109 -232
View File
@@ -88,8 +88,7 @@ class I2PController:
self.ready = False self.ready = False
self.storagepath = rns_storagepath+"/i2p" self.storagepath = rns_storagepath+"/i2p"
if not os.path.isdir(self.storagepath): if not os.path.isdir(self.storagepath): os.makedirs(self.storagepath)
os.makedirs(self.storagepath)
def start(self): def start(self):
@@ -110,28 +109,22 @@ class I2PController:
except Exception as e: except Exception as e:
self.ready = False self.ready = False
RNS.log("Exception on event loop for "+str(self)+": "+str(e), RNS.LOG_ERROR) RNS.log("Exception on event loop for "+str(self)+": "+str(e), RNS.LOG_ERROR)
finally: finally: self.loop.close()
self.loop.close()
def stop(self): def stop(self):
for i2ptunnel in self.i2plib_tunnels: for i2ptunnel in self.i2plib_tunnels:
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop): if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop): i2ptunnel.stop()
i2ptunnel.stop()
if hasattr(asyncio.Task, "all_tasks") and callable(asyncio.Task.all_tasks): if hasattr(asyncio.Task, "all_tasks") and callable(asyncio.Task.all_tasks):
for task in asyncio.Task.all_tasks(loop=self.loop): for task in asyncio.Task.all_tasks(loop=self.loop): task.cancel()
task.cancel()
time.sleep(0.2) time.sleep(0.2)
self.loop.stop() self.loop.stop()
def get_free_port(self): def get_free_port(self):
return self.i2plib.utils.get_free_port() return self.i2plib.utils.get_free_port()
def stop_tunnel(self, i2ptunnel): def stop_tunnel(self, i2ptunnel):
if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop): if hasattr(i2ptunnel, "stop") and callable(i2ptunnel.stop):
i2ptunnel.stop() i2ptunnel.stop()
@@ -159,10 +152,9 @@ class I2PController:
tn = self.i2plib_tunnels[i2p_destination] tn = self.i2plib_tunnels[i2p_destination]
if tn != None and hasattr(tn, "status"): if tn != None and hasattr(tn, "status"):
RNS.log("Waiting for status from I2P control process", RNS.LOG_EXTREME) RNS.log("Waiting for status from I2P control process", RNS.LOG_DEBUG)
while not tn.status["setup_ran"]: while not tn.status["setup_ran"]: time.sleep(0.1)
time.sleep(0.1) RNS.log("Got status from I2P control process", RNS.LOG_DEBUG)
RNS.log("Got status from I2P control process", RNS.LOG_EXTREME)
if tn.status["setup_failed"]: if tn.status["setup_failed"]:
self.stop_tunnel(tn) self.stop_tunnel(tn)
@@ -172,29 +164,19 @@ class I2PController:
if owner.socket != None: if owner.socket != None:
if hasattr(owner.socket, "close"): if hasattr(owner.socket, "close"):
if callable(owner.socket.close): if callable(owner.socket.close):
try: try: owner.socket.shutdown(socket.SHUT_RDWR)
owner.socket.shutdown(socket.SHUT_RDWR) except Exception as e: RNS.log("Error while shutting down socket for "+str(owner)+": "+str(e))
except Exception as e: try: owner.socket.close()
RNS.log("Error while shutting down socket for "+str(owner)+": "+str(e)) except Exception as e: RNS.log("Error while closing socket for "+str(owner)+": "+str(e))
try:
owner.socket.close()
except Exception as e:
RNS.log("Error while closing socket for "+str(owner)+": "+str(e))
self.client_tunnels[i2p_destination] = True self.client_tunnels[i2p_destination] = True
owner.awaiting_i2p_tunnel = False owner.awaiting_i2p_tunnel = False
RNS.log(str(owner)+" tunnel setup complete", RNS.LOG_VERBOSE) RNS.log(str(owner)+" tunnel setup complete", RNS.LOG_VERBOSE)
else: else: raise IOError("Got no status response from SAM API")
raise IOError("Got no status response from SAM API")
except ConnectionRefusedError as e:
raise e
except ConnectionAbortedError as e:
raise e
except ConnectionRefusedError as e: raise e
except ConnectionAbortedError as e: raise e
except Exception as e: except Exception as e:
RNS.log("Unexpected error type from I2P SAM: "+str(e), RNS.LOG_ERROR) RNS.log("Unexpected error type from I2P SAM: "+str(e), RNS.LOG_ERROR)
raise e raise e
@@ -206,54 +188,33 @@ class I2PController:
if i2ptunnel.status["setup_ran"] == False: if i2ptunnel.status["setup_ran"] == False:
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR) RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
elif i2p_exception != None: elif i2p_exception != None:
RNS.log("An error ocurred while setting up I2P tunnel to "+str(i2p_destination), RNS.LOG_ERROR) RNS.log("An error ocurred while setting up I2P tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest): RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR)
RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR) elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId): RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId): RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest): elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey): RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR) elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound): RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound): RNS.log("The I2P daemon could not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId): elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError): RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR) elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout): RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
else: RNS.log(f"Unspecified I2P daemon error: {i2p_exception}", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId):
RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey):
RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound):
RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound):
RNS.log("The I2P daemon mould not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError):
RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout):
RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR) RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
elif i2ptunnel.status["setup_failed"] == True: elif i2ptunnel.status["setup_failed"] == True:
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR) RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
else: else:
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR) RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
@@ -274,10 +235,8 @@ class I2PController:
i2p_keyfile_nf = self.storagepath+"/"+RNS.hexrep(i2p_dest_hash_nf, delimit=False)+".i2p" i2p_keyfile_nf = self.storagepath+"/"+RNS.hexrep(i2p_dest_hash_nf, delimit=False)+".i2p"
# Use old format if a key is already present # Use old format if a key is already present
if os.path.isfile(i2p_keyfile_of): if os.path.isfile(i2p_keyfile_of): i2p_keyfile = i2p_keyfile_of
i2p_keyfile = i2p_keyfile_of else: i2p_keyfile = i2p_keyfile_nf
else:
i2p_keyfile = i2p_keyfile_nf
i2p_dest = None i2p_dest = None
if not os.path.isfile(i2p_keyfile): if not os.path.isfile(i2p_keyfile):
@@ -312,8 +271,7 @@ class I2PController:
asyncio.run_coroutine_threadsafe(tunnel_up(), self.loop).result() asyncio.run_coroutine_threadsafe(tunnel_up(), self.loop).result()
self.server_tunnels[i2p_b32] = True self.server_tunnels[i2p_b32] = True
except Exception as e: except Exception as e: raise e
raise e
else: else:
i2ptunnel = self.i2plib_tunnels[i2p_b32] i2ptunnel = self.i2plib_tunnels[i2p_b32]
@@ -322,66 +280,45 @@ class I2PController:
if i2ptunnel.status["setup_ran"] == False: if i2ptunnel.status["setup_ran"] == False:
RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR) RNS.log(str(self)+" I2P tunnel setup did not complete", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
elif i2p_exception != None: elif i2p_exception != None:
RNS.log("An error ocurred while setting up I2P tunnel", RNS.LOG_ERROR) RNS.log("An error ocurred while setting up I2P tunnel", RNS.LOG_ERROR)
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR)
if isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.CantReachPeer): elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest): RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR)
RNS.log("The I2P daemon can't reach peer "+str(i2p_destination), RNS.LOG_ERROR) elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId): RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId): RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedDest): elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey): RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
RNS.log("The I2P daemon reported that the destination is already in use", RNS.LOG_ERROR) elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound): RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound): RNS.log("The I2P daemon could not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.DuplicatedId): elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError): RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
RNS.log("The I2P daemon reported that the ID is arleady in use", RNS.LOG_ERROR) elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout): RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
else: RNS.log(f"Unspecified I2P daemon error: {i2p_exception}", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidId):
RNS.log("The I2P daemon reported that the stream session ID doesn't exist", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.InvalidKey):
RNS.log("The I2P daemon reported that the key for "+str(i2p_destination)+" is invalid", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.KeyNotFound):
RNS.log("The I2P daemon could not find the key for "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.PeerNotFound):
RNS.log("The I2P daemon mould not find the peer "+str(i2p_destination), RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.I2PError):
RNS.log("The I2P daemon experienced an unspecified error", RNS.LOG_ERROR)
elif isinstance(i2p_exception, RNS.vendor.i2plib.exceptions.Timeout):
RNS.log("I2P daemon timed out while setting up client tunnel to "+str(i2p_destination), RNS.LOG_ERROR)
RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR) RNS.log("Resetting I2P tunnel and retrying later", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
elif i2ptunnel.status["setup_failed"] == True: elif i2ptunnel.status["setup_failed"] == True:
RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR) RNS.log(str(self)+" Unspecified I2P tunnel setup error, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
else: else:
RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR) RNS.log(str(self)+" Got no status from SAM API, resetting I2P tunnel", RNS.LOG_ERROR)
self.stop_tunnel(i2ptunnel) self.stop_tunnel(i2ptunnel)
return False return False
time.sleep(5) time.sleep(5)
def get_loop(self): def get_loop(self): return asyncio.get_event_loop()
return asyncio.get_event_loop()
class ThreadingI2PServer(socketserver.ThreadingMixIn, socketserver.TCPServer): class ThreadingI2PServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass pass
class I2PInterfacePeer(Interface): class I2PInterfacePeer(Interface):
RECONNECT_WAIT = 15 RECONNECT_WAIT = 15
RECONNECT_MAX_TRIES = None RECONNECT_MAX_TRIES = None
@@ -431,18 +368,11 @@ class I2PInterfacePeer(Interface):
self.ifac_netkey = self.parent_interface.ifac_netkey self.ifac_netkey = self.parent_interface.ifac_netkey
if self.ifac_netname != None or self.ifac_netkey != None: if self.ifac_netname != None or self.ifac_netkey != None:
ifac_origin = b"" ifac_origin = b""
if self.ifac_netname != None: if self.ifac_netname != None: ifac_origin += RNS.Identity.full_hash(self.ifac_netname.encode("utf-8"))
ifac_origin += RNS.Identity.full_hash(self.ifac_netname.encode("utf-8")) if self.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(self.ifac_netkey.encode("utf-8"))
if self.ifac_netkey != None:
ifac_origin += RNS.Identity.full_hash(self.ifac_netkey.encode("utf-8"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin) ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
self.ifac_key = RNS.Cryptography.hkdf( self.ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=ifac_origin_hash, salt=RNS.Reticulum.IFAC_SALT, context=None)
length=64,
derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT,
context=None
)
self.ifac_identity = RNS.Identity.from_bytes(self.ifac_key) self.ifac_identity = RNS.Identity.from_bytes(self.ifac_key)
self.ifac_signature = self.ifac_identity.sign(RNS.Identity.full_hash(self.ifac_key)) self.ifac_signature = self.ifac_identity.sign(RNS.Identity.full_hash(self.ifac_key))
@@ -450,10 +380,8 @@ class I2PInterfacePeer(Interface):
self.announce_rate_grace = None self.announce_rate_grace = None
self.announce_rate_penalty = None self.announce_rate_penalty = None
if max_reconnect_tries == None: if max_reconnect_tries == None: self.max_reconnect_tries = I2PInterfacePeer.RECONNECT_MAX_TRIES
self.max_reconnect_tries = I2PInterfacePeer.RECONNECT_MAX_TRIES else: self.max_reconnect_tries = max_reconnect_tries
else:
self.max_reconnect_tries = max_reconnect_tries
if connected_socket != None: if connected_socket != None:
self.receives = True self.receives = True
@@ -461,15 +389,12 @@ class I2PInterfacePeer(Interface):
self.target_port = None self.target_port = None
self.socket = connected_socket self.socket = connected_socket
if platform.system() == "Linux": if platform.system() == "Linux": self.set_timeouts_linux()
self.set_timeouts_linux() elif platform.system() == "Darwin": self.set_timeouts_osx()
elif platform.system() == "Darwin":
self.set_timeouts_osx()
elif target_i2p_dest != None: elif target_i2p_dest != None:
self.receives = True self.receives = True
self.initiator = True self.initiator = True
self.bind_ip = "127.0.0.1" self.bind_ip = "127.0.0.1"
self.awaiting_i2p_tunnel = True self.awaiting_i2p_tunnel = True
@@ -497,12 +422,10 @@ class I2PInterfacePeer(Interface):
thread.start() thread.start()
def wait_job(): def wait_job():
while self.awaiting_i2p_tunnel: while self.awaiting_i2p_tunnel: time.sleep(0.25)
time.sleep(0.25)
time.sleep(2) time.sleep(2)
if not self.kiss_framing: if not self.kiss_framing: self.wants_tunnel = True
self.wants_tunnel = True
if not self.connect(initial=True): if not self.connect(initial=True):
thread = threading.Thread(target=self.reconnect) thread = threading.Thread(target=self.reconnect)
@@ -517,7 +440,6 @@ class I2PInterfacePeer(Interface):
thread.daemon = True thread.daemon = True
thread.start() thread.start()
def set_timeouts_linux(self): def set_timeouts_linux(self):
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, int(I2PInterfacePeer.I2P_USER_TIMEOUT * 1000)) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, int(I2PInterfacePeer.I2P_USER_TIMEOUT * 1000))
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
@@ -526,10 +448,8 @@ class I2PInterfacePeer(Interface):
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, int(I2PInterfacePeer.I2P_PROBES)) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, int(I2PInterfacePeer.I2P_PROBES))
def set_timeouts_osx(self): def set_timeouts_osx(self):
if hasattr(socket, "TCP_KEEPALIVE"): if hasattr(socket, "TCP_KEEPALIVE"): TCP_KEEPIDLE = socket.TCP_KEEPALIVE
TCP_KEEPIDLE = socket.TCP_KEEPALIVE else: TCP_KEEPIDLE = 0x10
else:
TCP_KEEPIDLE = 0x10
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.socket.setsockopt(socket.IPPROTO_TCP, TCP_KEEPIDLE, int(I2PInterfacePeer.I2P_PROBE_AFTER)) self.socket.setsockopt(socket.IPPROTO_TCP, TCP_KEEPIDLE, int(I2PInterfacePeer.I2P_PROBE_AFTER))
@@ -537,16 +457,12 @@ class I2PInterfacePeer(Interface):
def shutdown_socket(self, target_socket): def shutdown_socket(self, target_socket):
if callable(target_socket.close): if callable(target_socket.close):
try: try:
if socket != None: if socket != None: target_socket.shutdown(socket.SHUT_RDWR)
target_socket.shutdown(socket.SHUT_RDWR) except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
except Exception as e:
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try: try:
if socket != None: if socket != None: target_socket.close()
target_socket.close() except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
except Exception as e:
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
def detach(self): def detach(self):
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG) RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
@@ -555,15 +471,11 @@ class I2PInterfacePeer(Interface):
if callable(self.socket.close): if callable(self.socket.close):
self.detached = True self.detached = True
try: try: self.socket.shutdown(socket.SHUT_RDWR)
self.socket.shutdown(socket.SHUT_RDWR) except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
except Exception as e:
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try: try: self.socket.close()
self.socket.close() except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
except Exception as e:
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
self.socket = None self.socket = None
@@ -578,23 +490,17 @@ class I2PInterfacePeer(Interface):
if not self.awaiting_i2p_tunnel: if not self.awaiting_i2p_tunnel:
RNS.log("Initial connection for "+str(self)+" could not be established: "+str(e), RNS.LOG_ERROR) RNS.log("Initial connection for "+str(self)+" could not be established: "+str(e), RNS.LOG_ERROR)
RNS.log("Leaving unconnected and retrying connection in "+str(I2PInterfacePeer.RECONNECT_WAIT)+" seconds.", RNS.LOG_ERROR) RNS.log("Leaving unconnected and retrying connection in "+str(I2PInterfacePeer.RECONNECT_WAIT)+" seconds.", RNS.LOG_ERROR)
return False return False
else: raise e
else: if platform.system() == "Linux": self.set_timeouts_linux()
raise e 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.online = True
self.writing = False self.writing = False
self.never_connected = False self.never_connected = False
if not self.kiss_framing and self.wants_tunnel: if not self.kiss_framing and self.wants_tunnel: RNS.Transport.synthesize_tunnel(self)
RNS.Transport.synthesize_tunnel(self)
return True return True
@@ -612,14 +518,10 @@ class I2PInterfacePeer(Interface):
self.teardown() self.teardown()
break break
try: try: self.connect()
self.connect()
except Exception as e: except Exception as e:
if not self.awaiting_i2p_tunnel: if not self.awaiting_i2p_tunnel: RNS.log("Connection attempt for "+str(self)+" failed: "+str(e), RNS.LOG_DEBUG)
RNS.log("Connection attempt for "+str(self)+" failed: "+str(e), RNS.LOG_DEBUG) else: RNS.log(str(self)+" still waiting for I2P tunnel to appear", RNS.LOG_VERBOSE)
else:
RNS.log(str(self)+" still waiting for I2P tunnel to appear", RNS.LOG_VERBOSE)
if not self.never_connected: if not self.never_connected:
RNS.log(str(self)+" Re-established connection via I2P tunnel", RNS.LOG_INFO) RNS.log(str(self)+" Re-established connection via I2P tunnel", RNS.LOG_INFO)
@@ -628,40 +530,35 @@ class I2PInterfacePeer(Interface):
thread = threading.Thread(target=self.read_loop) thread = threading.Thread(target=self.read_loop)
thread.daemon = True thread.daemon = True
thread.start() thread.start()
if not self.kiss_framing: if not self.kiss_framing: RNS.Transport.synthesize_tunnel(self)
RNS.Transport.synthesize_tunnel(self)
else: else:
RNS.log("Attempt to reconnect on a non-initiator I2P interface. This should not happen.", RNS.LOG_ERROR) RNS.log("Attempt to reconnect on a non-initiator I2P interface. This should not happen.", RNS.LOG_ERROR)
raise IOError("Attempt to reconnect on a non-initiator I2P interface") raise IOError("Attempt to reconnect on a non-initiator I2P interface")
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count: if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
self.parent_interface.rxb += len(data) self.parent_interface.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
def process_outgoing(self, data): def process_outgoing(self, data):
if self.online: if self.online:
while self.writing: while self.writing: time.sleep(0.001)
time.sleep(0.001)
try: try:
self.writing = True self.writing = True
if self.kiss_framing: if self.kiss_framing: data = bytes([KISS.FEND])+bytes([KISS.CMD_DATA])+KISS.escape(data)+bytes([KISS.FEND])
data = bytes([KISS.FEND])+bytes([KISS.CMD_DATA])+KISS.escape(data)+bytes([KISS.FEND]) else: data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
else:
data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
self.socket.sendall(data) self.socket.sendall(data)
self.writing = False self.writing = False
self.txb += len(data) self.txb += len(data)
self.last_write = time.time() self.last_write = time.time()
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count: if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count: self.parent_interface.txb += len(data)
self.parent_interface.txb += len(data)
except Exception as e: except Exception as e:
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR) RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
@@ -670,8 +567,7 @@ class I2PInterfacePeer(Interface):
def read_watchdog(self): def read_watchdog(self):
while self.wd_reset: while self.wd_reset: time.sleep(0.25)
time.sleep(0.25)
should_run = True should_run = True
try: try:
@@ -679,17 +575,13 @@ class I2PInterfacePeer(Interface):
time.sleep(1) time.sleep(1)
if (time.time()-self.last_read > I2PInterfacePeer.I2P_PROBE_AFTER*2): if (time.time()-self.last_read > I2PInterfacePeer.I2P_PROBE_AFTER*2):
if self.i2p_tunnel_state != I2PInterfacePeer.TUNNEL_STATE_STALE: if self.i2p_tunnel_state != I2PInterfacePeer.TUNNEL_STATE_STALE: RNS.log("I2P tunnel became unresponsive", RNS.LOG_DEBUG)
RNS.log("I2P tunnel became unresponsive", RNS.LOG_DEBUG)
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_STALE self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_STALE
else: else: self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_ACTIVE
self.i2p_tunnel_state = I2PInterfacePeer.TUNNEL_STATE_ACTIVE
if (time.time()-self.last_write > I2PInterfacePeer.I2P_PROBE_AFTER*1): if (time.time()-self.last_write > I2PInterfacePeer.I2P_PROBE_AFTER*1):
try: try:
if self.socket != None: if self.socket != None: self.socket.sendall(bytes([HDLC.FLAG, HDLC.FLAG]))
self.socket.sendall(bytes([HDLC.FLAG, HDLC.FLAG]))
except Exception as e: except Exception as e:
RNS.log("An error ocurred while sending I2P keepalive. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("An error ocurred while sending I2P keepalive. The contained exception was: "+str(e), RNS.LOG_ERROR)
self.shutdown_socket(self.socket) self.shutdown_socket(self.socket)
@@ -698,22 +590,17 @@ class I2PInterfacePeer(Interface):
if (time.time()-self.last_read > I2PInterfacePeer.I2P_READ_TIMEOUT): if (time.time()-self.last_read > I2PInterfacePeer.I2P_READ_TIMEOUT):
RNS.log("I2P socket is unresponsive, restarting...", RNS.LOG_WARNING) RNS.log("I2P socket is unresponsive, restarting...", RNS.LOG_WARNING)
if self.socket != None: if self.socket != None:
try: try: self.socket.shutdown(socket.SHUT_RDWR)
self.socket.shutdown(socket.SHUT_RDWR) except Exception as e: RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
except Exception as e:
RNS.log("Error while shutting down socket for "+str(self)+": "+str(e))
try: try: self.socket.close()
self.socket.close() except Exception as e: RNS.log("Error while closing socket for "+str(self)+": "+str(e))
except Exception as e:
RNS.log("Error while closing socket for "+str(self)+": "+str(e))
should_run = False should_run = False
self.wd_reset = False self.wd_reset = False
finally: finally: self.wd_reset = False
self.wd_reset = False
def read_loop(self): def read_loop(self):
try: try:
@@ -784,7 +671,6 @@ class I2PInterfacePeer(Interface):
data_buffer = data_buffer+bytes([byte]) data_buffer = data_buffer+bytes([byte])
else: else:
self.online = False self.online = False
self.wd_reset = True self.wd_reset = True
time.sleep(2) time.sleep(2)
self.wd_reset = False self.wd_reset = False
@@ -806,15 +692,12 @@ class I2PInterfacePeer(Interface):
if self.initiator: if self.initiator:
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING) RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
self.reconnect() self.reconnect()
else: else: self.teardown()
self.teardown()
def teardown(self): def teardown(self):
if self.initiator and not self.detached: if self.initiator and not self.detached:
RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR) RNS.log("The interface "+str(self)+" experienced an unrecoverable error and is being torn down. Restart Reticulum to attempt to open this interface again.", RNS.LOG_ERROR)
if RNS.Reticulum.panic_on_interface_error: if RNS.Reticulum.panic_on_interface_error: RNS.panic()
RNS.panic()
else: else:
RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE) RNS.log("The interface "+str(self)+" is being torn down.", RNS.LOG_VERBOSE)
@@ -826,9 +709,7 @@ class I2PInterfacePeer(Interface):
while self in self.parent_interface.spawned_interfaces: while self in self.parent_interface.spawned_interfaces:
self.parent_interface.spawned_interfaces.remove(self) self.parent_interface.spawned_interfaces.remove(self)
if not self.initiator: if not self.initiator: RNS.Transport.remove_interface(self)
RNS.Transport.remove_interface(self)
def __str__(self): def __str__(self):
return "I2PInterfacePeer["+str(self.name)+"]" return "I2PInterfacePeer["+str(self.name)+"]"
@@ -839,8 +720,7 @@ class I2PInterface(Interface):
DEFAULT_IFAC_SIZE = 16 DEFAULT_IFAC_SIZE = 16
@property @property
def clients(self): def clients(self): return len(self.spawned_interfaces)
return len(self.spawned_interfaces)
def __init__(self, owner, configuration): def __init__(self, owner, configuration):
super().__init__() super().__init__()
@@ -894,11 +774,9 @@ class I2PInterface(Interface):
RNS.log("I2P controller did not become available in time, waiting for controller", RNS.LOG_VERBOSE) RNS.log("I2P controller did not become available in time, waiting for controller", RNS.LOG_VERBOSE)
i2p_notready_warning = True i2p_notready_warning = True
while not self.i2p.ready: while not self.i2p.ready: time.sleep(0.25)
time.sleep(0.25)
if i2p_notready_warning == True: if i2p_notready_warning == True: RNS.log("I2P controller ready, continuing setup", RNS.LOG_VERBOSE)
RNS.log("I2P controller ready, continuing setup", RNS.LOG_VERBOSE)
def handlerFactory(callback): def handlerFactory(callback):
def createHandler(*args, **keys): def createHandler(*args, **keys):
@@ -971,18 +849,11 @@ class I2PInterface(Interface):
spawned_interface.ifac_netkey = self.ifac_netkey spawned_interface.ifac_netkey = self.ifac_netkey
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None: if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
ifac_origin = b"" ifac_origin = b""
if spawned_interface.ifac_netname != None: if spawned_interface.ifac_netname != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8")) if spawned_interface.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
if spawned_interface.ifac_netkey != None:
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin) ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
spawned_interface.ifac_key = RNS.Cryptography.hkdf( spawned_interface.ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=ifac_origin_hash, salt=RNS.Reticulum.IFAC_SALT, context=None)
length=64,
derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT,
context=None
)
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key) spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key)) spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
@@ -990,40 +861,46 @@ class I2PInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU spawned_interface.HW_MTU = self.HW_MTU
RNS.log("Spawned new I2PInterface Peer: "+str(spawned_interface), RNS.LOG_VERBOSE) RNS.log("Spawned new I2PInterface Peer: "+str(spawned_interface), RNS.LOG_VERBOSE)
RNS.Transport.add_interface(spawned_interface) RNS.Transport.add_interface(spawned_interface)
while spawned_interface in self.spawned_interfaces: while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.append(spawned_interface) self.spawned_interfaces.append(spawned_interface)
spawned_interface.read_loop() spawned_interface.read_loop()
def process_outgoing(self, data): def process_outgoing(self, data):
pass pass
def received_announce(self, from_spawned=False): def received_announce(self, size=0, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time()) if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False): def sent_announce(self, size=0, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time()) if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, from_spawned=False): def received_path_request(self, size=0, from_spawned=False):
if from_spawned: self.ip_freq_deque.append(time.time()) if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, from_spawned=False): def sent_path_request(self, size=0, from_spawned=False):
if from_spawned: self.op_freq_deque.append(time.time()) if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def detach(self): def detach(self):
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG) RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
self.i2p.stop() self.i2p.stop()
def __str__(self): def __str__(self): return "I2PInterface["+self.name+"]"
return "I2PInterface["+self.name+"]"
class I2PInterfaceHandler(socketserver.BaseRequestHandler): class I2PInterfaceHandler(socketserver.BaseRequestHandler):
def __init__(self, callback, *args, **keys): def __init__(self, callback, *args, **keys):
self.callback = callback self.callback = callback
socketserver.BaseRequestHandler.__init__(self, *args, **keys) socketserver.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self): def handle(self): self.callback(handler=self)
self.callback(handler=self)
+120 -54
View File
@@ -48,10 +48,12 @@ class Interface:
MODE_ROAMING = 0x04 MODE_ROAMING = 0x04
MODE_BOUNDARY = 0x05 MODE_BOUNDARY = 0x05
MODE_GATEWAY = 0x06 MODE_GATEWAY = 0x06
MODE_INTERNAL = 0x07
# Which interface modes a Transport Node should # Which interface modes a Transport Node should
# actively discover paths for. # actively discover paths for.
DISCOVER_PATHS_FOR = [MODE_ACCESS_POINT, MODE_GATEWAY, MODE_ROAMING] DISCOVER_PATHS_FOR = [MODE_ACCESS_POINT, MODE_GATEWAY, MODE_ROAMING, MODE_INTERNAL]
BOUNDARY_SEARCH_MODES = [MODE_BOUNDARY, MODE_GATEWAY]
# How many samples to use for announce # How many samples to use for announce
# frequency calculations # frequency calculations
@@ -69,9 +71,8 @@ class Interface:
# to hold at any given time. # to hold at any given time.
MAX_HELD_ANNOUNCES = 256 MAX_HELD_ANNOUNCES = 256
# How long a spawned interface will be # Control parameters
# considered to be newly created. Two DEFAULT_GRAVITY = 0
# hours by default.
IC_NEW_TIME = 2*60*60 IC_NEW_TIME = 2*60*60
IC_BURST_FREQ_NEW = 3 IC_BURST_FREQ_NEW = 3
IC_BURST_FREQ = 10 IC_BURST_FREQ = 10
@@ -81,7 +82,7 @@ class Interface:
IC_BURST_PENALTY = 15 IC_BURST_PENALTY = 15
IC_HELD_RELEASE_INTERVAL = 5 IC_HELD_RELEASE_INTERVAL = 5
IC_DEQUE_MIN_SAMPLE = 2 IC_DEQUE_MIN_SAMPLE = 2
IC_BURST_MIN_SAMPLES = 6 EC_BURST_MIN_SAMPLES = 2
EC_PR_FREQ = 5 EC_PR_FREQ = 5
EGRESS_CONTROL = False EGRESS_CONTROL = False
@@ -92,30 +93,48 @@ class Interface:
AUTOCONFIGURE_MTU = False AUTOCONFIGURE_MTU = False
FIXED_MTU = False FIXED_MTU = False
DEFAULT_IFAC_SIZE = 16
def __init__(self): def __init__(self):
self.rxb = 0 self.rxb = 0
self.txb = 0 self.txb = 0
self.arxb = 0
self.atxb = 0
self.arxc = 0
self.atxc = 0
self.prxb = 0
self.ptxb = 0
self.prxc = 0
self.ptxc = 0
self.gravity = 0
self.created = time.time() self.created = time.time()
self.detached = False self.detached = False
self.online = False self.online = False
self.bitrate = 62500 self.bitrate = 62500
self.HW_MTU = None self.HW_MTU = None
self.__hash = None
self.supports_discovery = False self.supports_discovery = False
self.discoverable = False self.discoverable = False
self.last_discovery_announce = 0 self.last_discovery_announce = 0
self.bootstrap_only = False self.bootstrap_only = False
self.recursive_prs = False
self.announces_from_internal = True
self.announces_to_internal = None
self.parent_interface = None self.parent_interface = None
self.spawned_interfaces = None self.spawned_interfaces = None
self.tunnel_id = None self.tunnel_id = None
self.ingress_control = True self.ingress_control = True
self.phy_keepalive = False self.phy_keepalive = False
self.shared_medium = False
self.ic_burst_active = False self.ic_burst_active = False
self.ic_burst_activated = 0 self.ic_burst_activated = 0
self.ic_burst_sustained = 0
self.ic_pr_burst_active = False self.ic_pr_burst_active = False
self.ic_pr_burst_activated = 0 self.ic_pr_burst_activated = 0
self.ic_pr_burst_sustained = 0
self.ic_pr_burst_cooldown = 0
self.ic_held_release = 0 self.ic_held_release = 0
self.ic_max_held_announces = RNS.Reticulum.get_instance()._default_ic_max_held_announces() self.ic_max_held_announces = RNS.Reticulum.get_instance()._default_ic_max_held_announces()
self.ic_burst_hold = RNS.Reticulum.get_instance()._default_ic_burst_hold() self.ic_burst_hold = RNS.Reticulum.get_instance()._default_ic_burst_hold()
@@ -129,14 +148,38 @@ class Interface:
self.ec_pr_freq = RNS.Reticulum.get_instance()._default_ec_pr_freq() self.ec_pr_freq = RNS.Reticulum.get_instance()._default_ec_pr_freq()
self.egress_control = RNS.Reticulum.get_instance()._default_egress_control() self.egress_control = RNS.Reticulum.get_instance()._default_egress_control()
self.held_announces = {} self.held_announces = {}
self.transmit_buffer = None
self.ia_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES) self.ia_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
self.oa_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES) self.oa_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
self.ip_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES) self.ip_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
self.op_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES) self.op_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
self.protocol_violations = 0
self.ifac_violations = 0
self.packet_filter_hits = 0
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): def get_hash(self):
return RNS.Identity.full_hash(str(self).encode("utf-8")) if not self.__hash: self.__hash = RNS.Identity.full_hash(str(self).encode("utf-8"))
return self.__hash
# This is a generic function for determining when an interface # This is a generic function for determining when an interface
# should activate ingress limiting. Since this can vary for # should activate ingress limiting. Since this can vary for
@@ -148,8 +191,10 @@ class Interface:
ia_freq = self.incoming_announce_frequency() ia_freq = self.incoming_announce_frequency()
if self.ic_burst_active: if self.ic_burst_active:
if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold: if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold and time.time() > self.ic_burst_sustained+self.ic_burst_hold:
if len(self.ia_freq_deque) >= self.IC_BURST_MIN_SAMPLES: self.ic_burst_active = False if len(self.ia_freq_deque) >= self.IC_DEQUE_MIN_SAMPLE: self.ic_burst_active = False
else:
if ia_freq >= freq_threshold: self.ic_burst_sustained = time.time()
return True return True
@@ -157,6 +202,7 @@ class Interface:
if ia_freq > freq_threshold: if ia_freq > freq_threshold:
self.ic_burst_active = True self.ic_burst_active = True
self.ic_burst_activated = time.time() self.ic_burst_activated = time.time()
self.ic_burst_sustained = time.time()
self.ic_held_release = time.time() + self.ic_burst_penalty self.ic_held_release = time.time() + self.ic_burst_penalty
return True return True
@@ -170,8 +216,12 @@ class Interface:
ip_freq = self.incoming_pr_frequency() ip_freq = self.incoming_pr_frequency()
if self.ic_pr_burst_active: if self.ic_pr_burst_active:
if ip_freq < freq_threshold and time.time() > self.ic_pr_burst_activated+self.ic_burst_hold: if ip_freq < freq_threshold and time.time() > self.ic_pr_burst_activated+self.ic_burst_hold and time.time() > self.ic_pr_burst_sustained+self.ic_burst_hold:
self.ic_pr_burst_active = False if self.ic_pr_burst_cooldown <= 0: self.ic_pr_burst_active = False
else: self.ic_pr_burst_cooldown -= 1
else:
self.ic_pr_burst_cooldown = 3
if ip_freq >= freq_threshold: self.ic_pr_burst_sustained = time.time()
return True return True
@@ -179,6 +229,8 @@ class Interface:
if ip_freq > freq_threshold: if ip_freq > freq_threshold:
self.ic_pr_burst_active = True self.ic_pr_burst_active = True
self.ic_pr_burst_activated = time.time() self.ic_pr_burst_activated = time.time()
self.ic_pr_burst_sustained = time.time()
self.ic_pr_burst_cooldown = 3
return True return True
else: return False else: return False
@@ -188,45 +240,36 @@ class Interface:
def should_egress_limit_pr(self): def should_egress_limit_pr(self):
if self.egress_control: if self.egress_control:
freq_threshold = self.ec_pr_freq freq_threshold = self.ec_pr_freq
op_freq = self.outgoing_pr_frequency() op_freq = self.outgoing_pr_frequency(preemptive=True)
if op_freq > freq_threshold: if op_freq > freq_threshold:
if len(self.op_freq_deque) >= self.IC_BURST_MIN_SAMPLES: return True if len(self.op_freq_deque) >= self.EC_BURST_MIN_SAMPLES: return True
return False return False
def optimise_mtu(self): def optimise_mtu(self):
if self.AUTOCONFIGURE_MTU: if self.AUTOCONFIGURE_MTU:
if self.bitrate >= 1_000_000_000: if self.bitrate >= 1_000_000_000: self.HW_MTU = 524288
self.HW_MTU = 524288 elif self.bitrate >= 750_000_000: self.HW_MTU = 262144
elif self.bitrate > 750_000_000: elif self.bitrate >= 400_000_000: self.HW_MTU = 131072
self.HW_MTU = 262144 elif self.bitrate >= 200_000_000: self.HW_MTU = 65536
elif self.bitrate > 400_000_000: elif self.bitrate >= 100_000_000: self.HW_MTU = 32768
self.HW_MTU = 131072 elif self.bitrate >= 10_000_000: self.HW_MTU = 16384
elif self.bitrate > 200_000_000: elif self.bitrate >= 5_000_000: self.HW_MTU = 8192
self.HW_MTU = 65536 elif self.bitrate >= 2_000_000: self.HW_MTU = 4096
elif self.bitrate > 100_000_000: elif self.bitrate >= 1_000_000: self.HW_MTU = 2048
self.HW_MTU = 32768 elif self.bitrate >= 62_500: self.HW_MTU = 1024
elif self.bitrate > 10_000_000: else: self.HW_MTU = None
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) RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_EXTREME)
def age(self): def age(self):
return time.time()-self.created return time.time()-self.created
def hold_announce(self, announce_packet): 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 self.held_announces[announce_packet.destination_hash] = announce_packet
elif not len(self.held_announces) >= self.ic_max_held_announces: elif not len(self.held_announces) >= self.ic_max_held_announces:
self.held_announces[announce_packet.destination_hash] = announce_packet self.held_announces[announce_packet.destination_hash] = announce_packet
@@ -249,32 +292,56 @@ class Interface:
RNS.log("Releasing held announce packet "+str(selected_announce_packet)+" from "+str(self), RNS.LOG_EXTREME) RNS.log("Releasing held announce packet "+str(selected_announce_packet)+" from "+str(self), RNS.LOG_EXTREME)
self.ic_held_release = time.time() + self.ic_held_release_interval self.ic_held_release = time.time() + self.ic_held_release_interval
self.held_announces.pop(selected_announce_packet.destination_hash) self.held_announces.pop(selected_announce_packet.destination_hash)
def release(): RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface) def release(): RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface, tc=RNS.Transport.TC_INGRESS_LIMITED, ifac_handled=True)
threading.Thread(target=release, daemon=True).start() threading.Thread(target=release, daemon=True).start()
except Exception as e: except Exception as e:
RNS.log("An error occurred while processing held announces for "+str(self), RNS.LOG_ERROR) RNS.log("An error occurred while processing held announces for "+str(self), RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
def received_announce(self, from_spawned=False): def received_announce(self, size=0, from_spawned=False):
self.arxc += 1; self.arxb += size
self.ia_freq_deque.append(time.time()) self.ia_freq_deque.append(time.time())
if hasattr(self, "parent_interface") and self.parent_interface != None: if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.received_announce(from_spawned=True) self.parent_interface.received_announce(size=size, from_spawned=True)
def sent_announce(self, from_spawned=False): def sent_announce(self, size=0, from_spawned=False):
self.atxc += 1; self.atxb += size
self.oa_freq_deque.append(time.time()) self.oa_freq_deque.append(time.time())
if hasattr(self, "parent_interface") and self.parent_interface != None: if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.sent_announce(from_spawned=True) self.parent_interface.sent_announce(size=size, from_spawned=True)
def received_path_request(self, from_spawned=False): def received_path_request(self, size=0, from_spawned=False):
self.prxc += 1; self.prxb += size
self.ip_freq_deque.append(time.time()) self.ip_freq_deque.append(time.time())
if hasattr(self, "parent_interface") and self.parent_interface != None: if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.received_path_request(from_spawned=True) self.parent_interface.received_path_request(size=size, from_spawned=True)
def sent_path_request(self, from_spawned=False): def sent_path_request(self, size=0, from_spawned=False):
self.ptxc += 1; self.ptxb += size
self.op_freq_deque.append(time.time()) self.op_freq_deque.append(time.time())
if hasattr(self, "parent_interface") and self.parent_interface != None: if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.sent_path_request(from_spawned=True) self.parent_interface.sent_path_request(size=size, from_spawned=True)
def protocol_violation(self, description=None):
self.protocol_violations += 1
RNS.log(f"Protocol violation on {self}: {description}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None
def ifac_violation(self, description=None):
self.ifac_violations += 1
RNS.log(f"IFAC violation on {self}: {description}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None
def packet_filter_hit(self):
self.packet_filter_hits += 1
return None
@property
def ic_burst_count(self): return None
@property
def ic_pr_burst_count(self): return None
def incoming_announce_frequency(self): def incoming_announce_frequency(self):
n = len(self.ia_freq_deque) n = len(self.ia_freq_deque)
@@ -309,8 +376,8 @@ class Interface:
hz = n / span hz = n / span
return hz return hz
def outgoing_pr_frequency(self): def outgoing_pr_frequency(self, preemptive=False):
n = len(self.op_freq_deque) n = len(self.op_freq_deque)+(1 if preemptive else 0)
if not len(self.op_freq_deque) > 1: return 0 if not len(self.op_freq_deque) > 1: return 0
else: else:
oldest = self.op_freq_deque[0] oldest = self.op_freq_deque[0]
@@ -343,12 +410,13 @@ class Interface:
selected = entries[0] selected = entries[0]
now = time.time() now = time.time()
tx_time = (len(selected["raw"])*8) / self.bitrate tx_size = len(selected["raw"])
tx_time = (tx_size*8) / self.bitrate
wait_time = (tx_time / self.announce_cap) wait_time = (tx_time / self.announce_cap)
self.announce_allowed_at = now + wait_time self.announce_allowed_at = now + wait_time
self.process_outgoing(selected["raw"]) RNS.Transport.transmit(self, selected["raw"])
self.sent_announce() self.sent_announce(tx_size)
if selected in self.announce_queue: if selected in self.announce_queue:
self.announce_queue.remove(selected) self.announce_queue.remove(selected)
@@ -370,11 +438,9 @@ class Interface:
@staticmethod @staticmethod
def get_config_obj(config_in): def get_config_obj(config_in):
if type(config_in) == ConfigObj: if type(config_in) == ConfigObj: return config_in
return config_in
else: else:
try: try: return ConfigObj(config_in)
return ConfigObj(config_in)
except Exception as e: except Exception as e:
RNS.log(f"Could not parse supplied configuration data. The contained exception was: {e}", RNS.LOG_ERROR) RNS.log(f"Could not parse supplied configuration data. The contained exception was: {e}", RNS.LOG_ERROR)
raise SystemError("Invalid configuration data supplied") raise SystemError("Invalid configuration data supplied")
+2
View File
@@ -122,6 +122,7 @@ class KISSInterface(Interface):
self.packet_queue = [] self.packet_queue = []
self.flow_control = flow_control self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False self.interface_ready = False
self.flow_control_timeout = 5 self.flow_control_timeout = 5
self.flow_control_locked = time.time() self.flow_control_locked = time.time()
@@ -245,6 +246,7 @@ class KISSInterface(Interface):
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
+40 -52
View File
@@ -30,6 +30,8 @@
from RNS.Interfaces.Interface import Interface from RNS.Interfaces.Interface import Interface
from RNS.Interfaces.BackboneInterface import BackboneInterface from RNS.Interfaces.BackboneInterface import BackboneInterface
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
import socketserver import socketserver
import threading import threading
import socket import socket
@@ -39,17 +41,6 @@ import os
import RNS import RNS
from threading import Lock 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): class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def server_bind(self): def server_bind(self):
if RNS.vendor.platformutils.is_windows(): if RNS.vendor.platformutils.is_windows():
@@ -70,6 +61,7 @@ class LocalClientInterface(Interface):
self.epoll_backend = False self.epoll_backend = False
self.HW_MTU = 262144 self.HW_MTU = 262144
self.online = False self.online = False
self.ifac_size = self.DEFAULT_IFAC_SIZE
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}" if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
else: self.socket_path = None else: self.socket_path = None
@@ -83,8 +75,9 @@ class LocalClientInterface(Interface):
self.detached = False self.detached = False
self.name = name self.name = name
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.frame_buffer = b"" self.transmit_buffer = TransmitBuffer()
self.transmit_buffer = b"" 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 if RNS.vendor.platformutils.use_epoll(): self.epoll_backend = True
@@ -194,15 +187,15 @@ class LocalClientInterface(Interface):
def send_keepalive(self): def send_keepalive(self):
if self.online: 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: try:
if self.epoll_backend: 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) BackboneInterface.tx_ready(self)
else: else:
self.writing = True 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.socket.sendall(data)
self.writing = False self.writing = False
@@ -219,28 +212,30 @@ class LocalClientInterface(Interface):
def process_outgoing(self, data): def process_outgoing(self, data):
if self.pause_on_client_sleep and time.time() > self.pause_timeout: 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 return
if self.online: if self.online:
try: try:
if self.epoll_backend: if self.epoll_backend:
self.transmit_buffer += bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG]) frame = HDLC.frame(data)
BackboneInterface.tx_ready(self) 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: else:
self.writing = True self.writing = True
if self._force_bitrate: if self._force_bitrate:
if not hasattr(self, "send_lock"): if not hasattr(self, "send_lock"): self.send_lock = Lock()
self.send_lock = Lock()
with self.send_lock: with self.send_lock:
# RNS.log(f"Simulating latency of {RNS.prettytime(s)} for {len(data)} bytes", RNS.LOG_EXTREME) # RNS.log(f"Simulating latency of {RNS.prettytime(s)} for {len(data)} bytes", RNS.LOG_EXTREME)
s = len(data) / self.bitrate * 8 s = len(data) / self.bitrate * 8
time.sleep(s) time.sleep(s)
data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG]) data = HDLC.frame(data)
self.socket.sendall(data) self.socket.sendall(data)
self.writing = False self.writing = False
self.txb += len(data) self.txb += len(data)
@@ -254,22 +249,7 @@ class LocalClientInterface(Interface):
self.teardown() self.teardown()
def handle_hdlc(self, data_in): def handle_hdlc(self, data_in):
self.frame_buffer += data_in self.receive_buffer.feed(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
def receive(self, data_in): def receive(self, data_in):
try: try:
@@ -283,8 +263,7 @@ class LocalClientInterface(Interface):
# there's no other connectivity left to block anyway, it might be # there's no other connectivity left to block anyway, it might be
# unnecessary. # unnecessary.
self.reconnect() self.reconnect()
else: else: self.teardown(nowarning=True)
self.teardown(nowarning=True)
except Exception as e: except Exception as e:
self.online = False self.online = False
@@ -296,7 +275,7 @@ class LocalClientInterface(Interface):
def read_loop(self): def read_loop(self):
try: try:
self.frame_buffer = b"" self.receive_buffer.reset()
data_in = b"" data_in = b""
while True: while True:
data_in = self.socket.recv(4096) data_in = self.socket.recv(4096)
@@ -382,6 +361,7 @@ class LocalServerInterface(Interface):
self.epoll_backend = False self.epoll_backend = False
self.online = False self.online = False
self.clients = 0 self.clients = 0
self.ifac_size = self.DEFAULT_IFAC_SIZE
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}" if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
else: self.socket_path = None else: self.socket_path = None
@@ -429,6 +409,7 @@ class LocalServerInterface(Interface):
self.announce_rate_grace = None self.announce_rate_grace = None
self.announce_rate_penalty = None self.announce_rate_penalty = None
self.HW_MTU = 262144
self.bitrate = 1000*1000*1000 self.bitrate = 1000*1000*1000
self.online = True self.online = True
@@ -481,17 +462,25 @@ class LocalServerInterface(Interface):
def process_outgoing(self, data): def process_outgoing(self, data):
pass pass
def received_announce(self, from_spawned=False): def received_announce(self, size=0, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time()) if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False): def sent_announce(self, size=0, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time()) if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, from_spawned=False): def received_path_request(self, size=0, from_spawned=False):
if from_spawned: self.ip_freq_deque.append(time.time()) if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, from_spawned=False): def sent_path_request(self, size=0, from_spawned=False):
if from_spawned: self.op_freq_deque.append(time.time()) if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def __str__(self): def __str__(self):
if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]" if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]"
@@ -502,5 +491,4 @@ class LocalInterfaceHandler(socketserver.BaseRequestHandler):
self.callback = callback self.callback = callback
socketserver.BaseRequestHandler.__init__(self, *args, **keys) socketserver.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self): def handle(self): self.callback(handler=self)
self.callback(handler=self)
+2
View File
@@ -84,6 +84,7 @@ class PipeInterface(Interface):
self.pipe_is_open = False self.pipe_is_open = False
self.bitrate = PipeInterface.BITRATE_GUESS self.bitrate = PipeInterface.BITRATE_GUESS
self.respawn_delay = respawn_delay self.respawn_delay = respawn_delay
self.shared_medium = True
try: try:
self.open_pipe() self.open_pipe()
@@ -119,6 +120,7 @@ class PipeInterface(Interface):
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
+33 -12
View File
@@ -258,6 +258,7 @@ class RNodeInterface(Interface):
self.r_stat_tx = None self.r_stat_tx = None
self.r_stat_rssi = None self.r_stat_rssi = None
self.r_stat_snr = None self.r_stat_snr = None
self.r_stat_q = None
self.r_st_alock = None self.r_st_alock = None
self.r_lt_alock = None self.r_lt_alock = None
self.r_random = None self.r_random = None
@@ -278,6 +279,7 @@ class RNodeInterface(Interface):
self.r_noise_floor = None self.r_noise_floor = None
self.r_interference = None self.r_interference = None
self.r_interference_l = None self.r_interference_l = None
self.reports_phy_stats = True
self.r_battery_state = RNodeInterface.BATTERY_STATE_UNKNOWN self.r_battery_state = RNodeInterface.BATTERY_STATE_UNKNOWN
self.r_battery_percent = 0 self.r_battery_percent = 0
@@ -294,6 +296,7 @@ class RNodeInterface(Interface):
self.packet_queue = [] self.packet_queue = []
self.flow_control = flow_control self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False self.interface_ready = False
self.announce_rate_target = None self.announce_rate_target = None
self.supports_discovery = True self.supports_discovery = True
@@ -383,6 +386,7 @@ class RNodeInterface(Interface):
RNS.log(f"Opening BLE connection for {self}...") RNS.log(f"Opening BLE connection for {self}...")
self.timeout = 1250 self.timeout = 1250
if self.ble != None and self.ble.running == False: if self.ble != None and self.ble.running == False:
RNS.log(f"Cleaning up previous BLE connection for {self}...")
self.ble.close() self.ble.close()
self.ble.cleanup() self.ble.cleanup()
self.ble = None self.ble = None
@@ -439,7 +443,11 @@ class RNodeInterface(Interface):
ble_detect_timeout = 5.0 ble_detect_timeout = 5.0
detect_time = time.time() detect_time = time.time()
while not self.detected and time.time() < detect_time + ble_detect_timeout: time.sleep(0.1) 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: else:
sleep(0.2) sleep(0.2)
@@ -477,8 +485,7 @@ class RNodeInterface(Interface):
self.setLTALock() self.setLTALock()
self.setRadioState(KISS.RADIO_STATE_ON) self.setRadioState(KISS.RADIO_STATE_ON)
if self.use_ble: if self.use_ble: time.sleep(2)
time.sleep(2)
def detect(self): 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]) 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) RNS.log("Radio state mismatch", RNS.LOG_ERROR)
self.validcfg = False self.validcfg = False
if (self.validcfg): if (self.validcfg): return True
return True else: return False
else:
return False
def updateBitrate(self): def updateBitrate(self):
@@ -699,11 +704,9 @@ class RNodeInterface(Interface):
self.bitrate = 0 self.bitrate = 0
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
self.r_stat_rssi = None
self.r_stat_snr = None
def process_outgoing(self,data): def process_outgoing(self,data):
datalen = len(data) datalen = len(data)
@@ -1297,6 +1300,7 @@ class BLEConnection():
self.must_disconnect = False self.must_disconnect = False
self.connect_job_running = False self.connect_job_running = False
self.device_disappeared = False self.device_disappeared = False
self._windows_paired_addrs = None
import importlib.util import importlib.util
if BLEConnection.bleak == None: if BLEConnection.bleak == None:
@@ -1307,8 +1311,8 @@ class BLEConnection():
import asyncio import asyncio
BLEConnection.asyncio = asyncio BLEConnection.asyncio = asyncio
else: else:
RNS.log("Using the RNode interface over BLE requires a the \"bleak\" module to be installed.", 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 one with the command: python3 -m pip install bleak", RNS.LOG_CRITICAL) RNS.log("You can install it with the command: python3 -m pip install bleak", RNS.LOG_CRITICAL)
RNS.panic() RNS.panic()
self.should_run = True self.should_run = True
@@ -1324,6 +1328,7 @@ class BLEConnection():
self.should_run = False self.should_run = False
def connection_job(self): def connection_job(self):
self.running = True
while self.should_run: while self.should_run:
if self.ble_device == None: if self.ble_device == None:
self.ble_device = self.find_target_device() self.ble_device = self.find_target_device()
@@ -1350,6 +1355,7 @@ class BLEConnection():
self.owner.ble_receive(data) self.owner.ble_receive(data)
self.connected = True self.connected = True
self.device_disappeared = False
self.ble_device = ble_client self.ble_device = ble_client
self.last_client = ble_client self.last_client = ble_client
self.owner.port = str(f"ble://{ble_client.address}") self.owner.port = str(f"ble://{ble_client.address}")
@@ -1384,6 +1390,9 @@ class BLEConnection():
def find_target_device(self): def find_target_device(self):
RNS.log(f"Searching for attachable BLE device for {self.owner}...", RNS.LOG_EXTREME) 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): 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 BLEConnection.UART_SERVICE_UUID.lower() in adv.service_uuids:
if self.device_bonded(device): if self.device_bonded(device):
@@ -1415,6 +1424,9 @@ class BLEConnection():
def device_bonded(self, device): def device_bonded(self, device):
try: 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 hasattr(device, "details"):
if "props" in device.details and "Bonded" in device.details["props"]: if "props" in device.details and "Bonded" in device.details["props"]:
if device.details["props"]["Bonded"] == True: if device.details["props"]["Bonded"] == True:
@@ -1425,6 +1437,15 @@ class BLEConnection():
return False 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(): class TCPConnection():
TARGET_PORT = 7633 TARGET_PORT = 7633
CONNECT_TIMEOUT = 5.0 CONNECT_TIMEOUT = 5.0
+21 -10
View File
@@ -269,6 +269,7 @@ class RNodeMultiInterface(Interface):
self.r_stat_tx = None self.r_stat_tx = None
self.r_stat_rssi = None self.r_stat_rssi = None
self.r_stat_snr = None self.r_stat_snr = None
self.r_stat_q = None
self.r_st_alock = None self.r_st_alock = None
self.r_lt_alock = None self.r_lt_alock = None
self.r_random = None self.r_random = None
@@ -276,6 +277,8 @@ class RNodeMultiInterface(Interface):
self.packet_queue = [] self.packet_queue = []
self.interface_ready = False self.interface_ready = False
self.announce_rate_target = None self.announce_rate_target = None
self.reports_phy_stats = True
self.validcfg = True self.validcfg = True
if id_interval != None and id_callsign != None: if id_interval != None and id_callsign != None:
@@ -543,17 +546,25 @@ class RNodeMultiInterface(Interface):
if written != len(frame): if written != len(frame):
raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data))) raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data)))
def received_announce(self, from_spawned=False): def received_announce(self, size=0, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time()) if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False): def sent_announce(self, size=0, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time()) if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, from_spawned=False): def received_path_request(self, size=0, from_spawned=False):
if from_spawned: self.ip_freq_deque.append(time.time()) if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, from_spawned=False): def sent_path_request(self, size=0, from_spawned=False):
if from_spawned: self.op_freq_deque.append(time.time()) if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def readLoop(self): def readLoop(self):
try: try:
@@ -993,6 +1004,7 @@ class RNodeSubInterface(Interface):
self.r_premable_time_ms = None self.r_premable_time_ms = None
self.packet_queue = [] self.packet_queue = []
self.shared_medium = True
self.interface_ready = False self.interface_ready = False
self.parent_interface = parent_interface self.parent_interface = parent_interface
self.announce_rate_target = None self.announce_rate_target = None
@@ -1116,10 +1128,9 @@ class RNodeSubInterface(Interface):
self.bitrate = 0 self.bitrate = 0
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
self.r_stat_rssi = None
self.r_stat_snr = None
def process_outgoing(self,data): def process_outgoing(self,data):
if self.online: if self.online:
+2
View File
@@ -83,6 +83,7 @@ class SerialInterface(Interface):
raise ValueError("No port specified for serial interface") raise ValueError("No port specified for serial interface")
self.HW_MTU = 564 self.HW_MTU = 564
self.shared_medium = True
self.pyserial = serial self.pyserial = serial
self.serial = None self.serial = None
@@ -142,6 +143,7 @@ class SerialInterface(Interface):
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
+33 -10
View File
@@ -302,6 +302,7 @@ class TCPClientInterface(Interface):
raise IOError("Attempt to reconnect on a non-initiator TCP interface") raise IOError("Attempt to reconnect on a non-initiator TCP interface")
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
if self.online and not self.detached: if self.online and not self.detached:
self.rxb += len(data) self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None: 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) RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
self.teardown() self.teardown()
def check_frame_len(self, frame_len):
if frame_len <= RNS.Reticulum.HEADER_MINSIZE: return False
elif frame_len > self.HW_MTU + (self.ifac_size or 0): return False
else: return True
def invalid_frame(self, frame_len):
RNS.log(f"Invalid HDLC frame of {RNS.prettysize(frame_len)} received on {self}, dropping frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
def read_loop(self): def read_loop(self):
try: try:
@@ -389,12 +397,18 @@ class TCPClientInterface(Interface):
frame = frame_buffer[frame_start+1:frame_end] frame = frame_buffer[frame_start+1:frame_end]
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG])) frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC])) frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > RNS.Reticulum.HEADER_MINSIZE: frame_len = len(frame)
self.process_incoming(frame) if frame_len != 0:
if self.check_frame_len(frame_len): self.process_incoming(frame)
else: self.invalid_frame(len(frame))
frame_buffer = frame_buffer[frame_end:] frame_buffer = frame_buffer[frame_end:]
else: else:
if len(frame_buffer) > self.HW_MTU*2: frame_buffer = b""
flags_remaining = False flags_remaining = False
else: else:
frame_buffer = b""
flags_remaining = False flags_remaining = False
else: else:
@@ -623,6 +637,7 @@ class TCPServerInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True spawned_interface.online = True
RNS.log("Spawned new TCPClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE) RNS.log("Spawned new TCPClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
@@ -632,17 +647,25 @@ class TCPServerInterface(Interface):
self.spawned_interfaces.append(spawned_interface) self.spawned_interfaces.append(spawned_interface)
spawned_interface.read_loop() spawned_interface.read_loop()
def received_announce(self, from_spawned=False): def received_announce(self, size=0, from_spawned=False):
if from_spawned: self.ia_freq_deque.append(time.time()) if from_spawned:
self.ia_freq_deque.append(time.time())
self.arxb += size
def sent_announce(self, from_spawned=False): def sent_announce(self, size=0, from_spawned=False):
if from_spawned: self.oa_freq_deque.append(time.time()) if from_spawned:
self.oa_freq_deque.append(time.time())
self.atxb += size
def received_path_request(self, from_spawned=False): def received_path_request(self, size=0, from_spawned=False):
if from_spawned: self.ip_freq_deque.append(time.time()) if from_spawned:
self.ip_freq_deque.append(time.time())
self.prxb += size
def sent_path_request(self, from_spawned=False): def sent_path_request(self, size=0, from_spawned=False):
if from_spawned: self.op_freq_deque.append(time.time()) if from_spawned:
self.op_freq_deque.append(time.time())
self.ptxb += size
def process_outgoing(self, data): def process_outgoing(self, data):
pass pass
+2
View File
@@ -78,6 +78,7 @@ class UDPInterface(Interface):
self.name = name self.name = name
self.online = False self.online = False
self.bitrate = UDPInterface.BITRATE_GUESS self.bitrate = UDPInterface.BITRATE_GUESS
self.shared_medium = True
if device != None: if device != None:
if bindip == None: if bindip == None:
@@ -114,6 +115,7 @@ class UDPInterface(Interface):
def process_incoming(self, data): def process_incoming(self, data):
if not data: return
self.rxb += len(data) self.rxb += len(data)
self.owner.inbound(data, self) self.owner.inbound(data, self)
+113 -130
View File
@@ -109,30 +109,30 @@ class WDCL():
self.switch_id = self.switch_identity.sig_pub_bytes[-4:] self.switch_id = self.switch_identity.sig_pub_bytes[-4:]
self.switch_pub_bytes = self.switch_identity.sig_pub_bytes self.switch_pub_bytes = self.switch_identity.sig_pub_bytes
self.rxb = 0 self.rxb = 0
self.txb = 0 self.txb = 0
self.owner = owner self.owner = owner
self.as_interface = as_interface self.as_interface = as_interface
self.device = device self.device = device
self.device.connection = self self.device.connection = self
self.pyserial = serial self.pyserial = serial
self.serial = None self.serial = None
self.port = port self.port = port
self.speed = 3000000 self.speed = 3000000
self.databits = 8 self.databits = 8
self.parity = parity self.parity = parity
self.stopbits = 1 self.stopbits = 1
self.timeout = 100 self.timeout = 100
self.online = False self.online = False
self.frame_buffer = b"" self.frame_buffer = b""
self.next_tx = 0 self.next_tx = 0
self.should_run = True self.should_run = True
self.receiver = None self.receiver = None
self.wdcl_connected = False self.wdcl_connected = False
self.reconnecting = False self.reconnecting = False
self.frame_queue = deque() self.frame_queue = deque()
if not self.as_interface:
self.id = RNS.Identity.full_hash(port.hwid.encode("utf-8")) if not self.as_interface: self.id = RNS.Identity.full_hash(port.hwid.encode("utf-8"))
if self.as_interface: if self.as_interface:
try: try:
@@ -168,19 +168,10 @@ class WDCL():
self.owner.wlog(f"Opening serial port {self.port.device}...") self.owner.wlog(f"Opening serial port {self.port.device}...")
target_port = self.port.device target_port = self.port.device
self.serial = self.pyserial.Serial( self.serial = self.pyserial.Serial(port = target_port, baudrate = self.speed,
port = target_port, bytesize = self.databits, parity = self.parity, stopbits = self.stopbits,
baudrate = self.speed, xonxoff = False, rtscts = False, timeout = 0.250, inter_byte_timeout = None,
bytesize = self.databits, write_timeout = None, dsrdtr = False)
parity = self.parity,
stopbits = self.stopbits,
xonxoff = False,
rtscts = False,
timeout = 0.250,
inter_byte_timeout = None,
write_timeout = None,
dsrdtr = False)
else: else:
if self.port != None: if self.port != None:
# Get device parameters # Get device parameters
@@ -198,19 +189,9 @@ class WDCL():
from usbserial4a.cdcacmserial4a import CdcAcmSerial from usbserial4a.cdcacmserial4a import CdcAcmSerial
proxy = CdcAcmSerial proxy = CdcAcmSerial
self.serial = proxy( self.serial = proxy(self.port, baudrate = self.speed, bytesize = self.databits,
self.port, parity = self.parity, stopbits = self.stopbits, xonxoff = False,
baudrate = self.speed, rtscts = False, timeout = None, inter_byte_timeout = None, dsrdtr = False)
bytesize = self.databits,
parity = self.parity,
stopbits = self.stopbits,
xonxoff = False,
rtscts = False,
timeout = None,
inter_byte_timeout = None,
# write_timeout = wtimeout,
dsrdtr = False,
)
if vid == 0x0403: if vid == 0x0403:
# Hardware parameters for FTDI devices @ 115200 baud # 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])) frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > WDCL.HEADER_MINSIZE: self.process_incoming(frame) if len(frame) > WDCL.HEADER_MINSIZE: self.process_incoming(frame)
self.frame_buffer = self.frame_buffer[frame_end:] self.frame_buffer = self.frame_buffer[frame_end:]
else:
flags_remaining = False else: flags_remaining = False
else: else: flags_remaining = False
flags_remaining = False
except Exception as e: except Exception as e:
self.online = False self.online = False
@@ -359,6 +339,7 @@ class Evt():
ET_MSG = 0x0000 ET_MSG = 0x0000
ET_SYSTEM_BOOT = 0x0001 ET_SYSTEM_BOOT = 0x0001
ET_CORE_INIT = 0x0002 ET_CORE_INIT = 0x0002
ET_BOARD_INIT = 0x0003
ET_DRV_UART_INIT = 0x1000 ET_DRV_UART_INIT = 0x1000
ET_DRV_USB_CDC_INIT = 0x1010 ET_DRV_USB_CDC_INIT = 0x1010
ET_DRV_USB_CDC_HOST_AVAIL = 0x1011 ET_DRV_USB_CDC_HOST_AVAIL = 0x1011
@@ -426,77 +407,78 @@ class Evt():
IF_TYPE_DMA = 0x10 IF_TYPE_DMA = 0x10
event_descriptions = { event_descriptions = {
ET_SYSTEM_BOOT: "System boot", ET_SYSTEM_BOOT: "System boot",
ET_CORE_INIT: "Core initialization", ET_CORE_INIT: "Core initialization",
ET_DRV_UART_INIT: "UART driver initialization", ET_BOARD_INIT: "Board hardware initialization",
ET_DRV_USB_CDC_INIT: "USB CDC driver initialization", ET_DRV_UART_INIT: "UART driver initialization",
ET_DRV_USB_CDC_HOST_AVAIL: "USB CDC host became available", ET_DRV_USB_CDC_INIT: "USB CDC driver initialization",
ET_DRV_USB_CDC_HOST_SUSPEND: "USB CDC host suspend", ET_DRV_USB_CDC_HOST_AVAIL: "USB CDC host became available",
ET_DRV_USB_CDC_HOST_RESUME: "USB CDC host resume", ET_DRV_USB_CDC_HOST_SUSPEND: "USB CDC host suspend",
ET_DRV_USB_CDC_CONNECTED: "USB CDC host connection", ET_DRV_USB_CDC_HOST_RESUME: "USB CDC host resume",
ET_DRV_USB_CDC_READ_ERR: "USB CDC read error", ET_DRV_USB_CDC_CONNECTED: "USB CDC host connection",
ET_DRV_USB_CDC_OVERFLOW: "USB CDC overflow occurred", ET_DRV_USB_CDC_READ_ERR: "USB CDC read error",
ET_DRV_USB_CDC_DROPPED: "USB CDC dropped bytes", ET_DRV_USB_CDC_OVERFLOW: "USB CDC overflow occurred",
ET_DRV_USB_CDC_TX_TIMEOUT: "USB CDC TX flush timeout", ET_DRV_USB_CDC_DROPPED: "USB CDC dropped bytes",
ET_DRV_I2C_INIT: "I2C driver initialization", ET_DRV_USB_CDC_TX_TIMEOUT: "USB CDC TX flush timeout",
ET_DRV_NVS_INIT: "NVS driver initialization", ET_DRV_I2C_INIT: "I2C driver initialization",
ET_DRV_CRYPTO_INIT: "Cryptography driver initialization", ET_DRV_NVS_INIT: "NVS driver initialization",
ET_DRV_W80211_INIT: "W802.11 driver initialization", ET_DRV_CRYPTO_INIT: "Cryptography driver initialization",
ET_DRV_W80211_CHANNEL: "W802.11 channel configuration", ET_DRV_W80211_INIT: "W802.11 driver initialization",
ET_DRV_W80211_POWER: "W802.11 TX power configuration", ET_DRV_W80211_CHANNEL: "W802.11 channel configuration",
ET_DRV_DISPLAY_INIT: "Display driver initialization", 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_BUS_AVAILABLE: "Display bus availability",
ET_DRV_DISPLAY_IO_CONFIGURED: "Display I/O configuration", ET_DRV_DISPLAY_IO_CONFIGURED: "Display I/O configuration",
ET_DRV_DISPLAY_PANEL_CREATED: "Display panel allocation", ET_DRV_DISPLAY_PANEL_CREATED: "Display panel allocation",
ET_DRV_DISPLAY_PANEL_RESET: "Display panel reset", ET_DRV_DISPLAY_PANEL_RESET: "Display panel reset",
ET_DRV_DISPLAY_PANEL_INIT: "Display panel initialization", ET_DRV_DISPLAY_PANEL_INIT: "Display panel initialization",
ET_DRV_DISPLAY_PANEL_ENABLE: "Display panel activation", ET_DRV_DISPLAY_PANEL_ENABLE: "Display panel activation",
ET_DRV_DISPLAY_REMOTE_ENABLE: "Remote display output activation", ET_DRV_DISPLAY_REMOTE_ENABLE: "Remote display output activation",
ET_KRN_LOGGER_INIT: "Logging service initialization", ET_KRN_LOGGER_INIT: "Logging service initialization",
ET_KRN_LOGGER_OUTPUT: "Logging service output activation", ET_KRN_LOGGER_OUTPUT: "Logging service output activation",
ET_KRN_UI_INIT: "User interface service initialization", ET_KRN_UI_INIT: "User interface service initialization",
ET_PROTO_WDCL_INIT: "WDCL protocol initialization", ET_PROTO_WDCL_INIT: "WDCL protocol initialization",
ET_PROTO_WDCL_RUNNING: "WDCL protocol activation", ET_PROTO_WDCL_RUNNING: "WDCL protocol activation",
ET_PROTO_WDCL_CONNECTION: "WDCL host connection", ET_PROTO_WDCL_CONNECTION: "WDCL host connection",
ET_PROTO_WDCL_HOST_ENDPOINT: "Weave host endpoint", ET_PROTO_WDCL_HOST_ENDPOINT: "Weave host endpoint",
ET_PROTO_WEAVE_INIT: "Weave protocol initialization", ET_PROTO_WEAVE_INIT: "Weave protocol initialization",
ET_PROTO_WEAVE_RUNNING: "Weave protocol activation", ET_PROTO_WEAVE_RUNNING: "Weave protocol activation",
ET_PROTO_WEAVE_EP_ALIVE: "Weave endpoint alive", ET_PROTO_WEAVE_EP_ALIVE: "Weave endpoint alive",
ET_PROTO_WEAVE_EP_TIMEOUT: "Weave endpoint disappeared", ET_PROTO_WEAVE_EP_TIMEOUT: "Weave endpoint disappeared",
ET_SRVCTL_REMOTE_DISPLAY: "Remote display service control event", ET_SRVCTL_REMOTE_DISPLAY: "Remote display service control event",
ET_INTERFACE_REGISTERED: "Interface registration", ET_INTERFACE_REGISTERED: "Interface registration",
ET_SYSERR_MEM_EXHAUSTED: "System memory exhausted", ET_SYSERR_MEM_EXHAUSTED: "System memory exhausted",
} }
interface_types = { interface_types = {
IF_TYPE_USB: "usb", IF_TYPE_USB: "usb",
IF_TYPE_UART: "uart", IF_TYPE_UART: "uart",
IF_TYPE_W80211: "mw", IF_TYPE_W80211: "mw",
IF_TYPE_BLE: "ble", IF_TYPE_BLE: "ble",
IF_TYPE_LORA: "lora", IF_TYPE_LORA: "lora",
IF_TYPE_ETHERNET: "eth", IF_TYPE_ETHERNET: "eth",
IF_TYPE_WIFI: "wifi", IF_TYPE_WIFI: "wifi",
IF_TYPE_TCP: "tcp", IF_TYPE_TCP: "tcp",
IF_TYPE_UDP: "udp", IF_TYPE_UDP: "udp",
IF_TYPE_IR: "ir", IF_TYPE_IR: "ir",
IF_TYPE_AFSK: "afsk", IF_TYPE_AFSK: "afsk",
IF_TYPE_GPIO: "gpio", IF_TYPE_GPIO: "gpio",
IF_TYPE_SPI: "spi", IF_TYPE_SPI: "spi",
IF_TYPE_I2C: "i2c", IF_TYPE_I2C: "i2c",
IF_TYPE_CAN: "can", IF_TYPE_CAN: "can",
IF_TYPE_DMA: "dma", IF_TYPE_DMA: "dma",
} }
channel_descriptions = { channel_descriptions = {
1: "Channel 1 (2412 MHz)", 1: "Channel 1 (2412 MHz)",
2: "Channel 2 (2417 MHz)", 2: "Channel 2 (2417 MHz)",
3: "Channel 3 (2422 MHz)", 3: "Channel 3 (2422 MHz)",
4: "Channel 4 (2427 MHz)", 4: "Channel 4 (2427 MHz)",
5: "Channel 5 (2432 MHz)", 5: "Channel 5 (2432 MHz)",
6: "Channel 6 (2437 MHz)", 6: "Channel 6 (2437 MHz)",
7: "Channel 7 (2442 MHz)", 7: "Channel 7 (2442 MHz)",
8: "Channel 8 (2447 MHz)", 8: "Channel 8 (2447 MHz)",
9: "Channel 9 (2452 MHz)", 9: "Channel 9 (2452 MHz)",
10: "Channel 10 (2457 MHz)", 10: "Channel 10 (2457 MHz)",
11: "Channel 11 (2462 MHz)", 11: "Channel 11 (2462 MHz)",
12: "Channel 12 (2467 MHz)", 12: "Channel 12 (2467 MHz)",
@@ -529,23 +511,23 @@ class Evt():
} }
task_descriptions = { task_descriptions = {
"taskLVGL": "Driver: UI Renderer", "taskLVGL": "Driver: UI Renderer",
"ui_service": "Service: User Interface", "ui_service": "Service: User Interface",
"TinyUSB": "Driver: USB", "TinyUSB": "Driver: USB",
"drv_w80211": "Driver: W802.11", "drv_w80211": "Driver: W802.11",
"system_stats": "System: Stats", "system_stats": "System: Stats",
"core": "System: Core", "core": "System: Core",
"protocol_wdcl": "Protocol: WDCL", "protocol_wdcl": "Protocol: WDCL",
"protocol_weave": "Protocol: Weave", "protocol_weave": "Protocol: Weave",
"tiT": "Protocol: TCP/IP", "tiT": "Protocol: TCP/IP",
"ipc0": "System: CPU 0 IPC", "ipc0": "System: CPU 0 IPC",
"ipc1": "System: CPU 1 IPC", "ipc1": "System: CPU 1 IPC",
"esp_timer": "Driver: Timers", "esp_timer": "Driver: Timers",
"Tmr Svc": "Service: Timers", "Tmr Svc": "Service: Timers",
"kernel_logger": "Service: Logging", "kernel_logger": "Service: Logging",
"remote_display": "Service: Remote Display", "remote_display": "Service: Remote Display",
"wifi": "System: WiFi Hardware", "wifi": "System: WiFi Hardware",
"sys_evt": "System: Kernel Events", "sys_evt": "System: Kernel Events",
} }
@staticmethod @staticmethod
@@ -775,8 +757,8 @@ class WeaveDevice():
self.cpu_load = frame.data[0] self.cpu_load = frame.data[0]
self.capture_stats_cpu() self.capture_stats_cpu()
elif frame.event == Evt.ET_STAT_MEMORY: elif frame.event == Evt.ET_STAT_MEMORY:
self.memory_free = 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:]) self.memory_total = int.from_bytes(frame.data[4:], "big")
self.memory_used = self.memory_total-self.memory_free self.memory_used = self.memory_total-self.memory_free
self.memory_used_pct = round((self.memory_used/self.memory_total)*100, 2) self.memory_used_pct = round((self.memory_used/self.memory_total)*100, 2)
self.capture_stats_memory() self.capture_stats_memory()
@@ -979,6 +961,7 @@ class WeaveInterface(Interface):
spawned_interface.announce_rate_grace = self.announce_rate_grace spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode spawned_interface.mode = self.mode
spawned_interface.gravity = self.gravity
spawned_interface.HW_MTU = self.HW_MTU spawned_interface.HW_MTU = self.HW_MTU
spawned_interface._online = True spawned_interface._online = True
RNS.Transport.add_interface(spawned_interface) RNS.Transport.add_interface(spawned_interface)
+4 -2
View File
@@ -36,5 +36,7 @@ import RNS.Interfaces.util.netinfo as netinfo
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py") py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc") pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
__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"))])) 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") py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc") pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
__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"))])) 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__"]))
+200 -230
View File
@@ -190,25 +190,22 @@ class Link:
link.set_link_id(packet) link.set_link_id(packet)
if len(data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE: if len(data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE:
RNS.log("Link request includes MTU signalling", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log("Link request includes MTU signalling", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
try: try: link.mtu = Link.mtu_from_lr_packet(packet) or RNS.Reticulum.MTU
link.mtu = Link.mtu_from_lr_packet(packet) or Reticulum.MTU
except Exception as e: except Exception as e:
RNS.trace_exception(e) RNS.trace_exception(e)
link.mtu = RNS.Reticulum.MTU link.mtu = RNS.Reticulum.MTU
link.mode = Link.mode_from_lr_packet(packet) link.mode = Link.mode_from_lr_packet(packet)
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
# TODO: Remove debug
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG)
link.update_mdu() link.update_mdu()
link.destination = packet.destination link.destination = packet.destination
link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE
link.establishment_cost += len(packet.raw) link.establishment_cost += len(packet.raw)
RNS.log(f"Validating link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_DEBUG) RNS.log(f"Validating link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
RNS.log(f"Link MTU configured to {RNS.prettysize(link.mtu)}", RNS.LOG_EXTREME) RNS.log(f"Link MTU configured to {RNS.prettysize(link.mtu)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
RNS.log(f"Establishment timeout is {RNS.prettytime(link.establishment_timeout)} for incoming link request "+RNS.prettyhexrep(link.link_id), RNS.LOG_EXTREME) RNS.log(f"Establishment timeout is {RNS.prettytime(link.establishment_timeout)} for incoming link request {RNS.prettyhexrep(link.link_id)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
link.handshake() link.handshake()
link.attached_interface = packet.receiving_interface link.attached_interface = packet.receiving_interface
link.prove() link.prove()
@@ -218,15 +215,15 @@ class Link:
link.__update_phy_stats(packet, force_update=True) link.__update_phy_stats(packet, force_update=True)
link.start_watchdog() link.start_watchdog()
RNS.log("Incoming link request "+str(link)+" accepted on "+str(link.attached_interface), RNS.LOG_DEBUG) RNS.log(f"Incoming link request {link} accepted on {link.attached_interface}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return link return link
except Exception as e: except Exception as e:
RNS.log(f"Validating link request failed: {e}", RNS.LOG_VERBOSE) RNS.log(f"Validating link request failed: {e}", RNS.LOG_VERBOSE) if RNS.sl(RNS.LOG_VERBOSE) else None
return None return None
else: else:
RNS.log(f"Invalid link request payload size of {len(data)} bytes, dropping request", RNS.LOG_DEBUG) RNS.log(f"Invalid link request payload size of {len(data)} bytes, dropping request", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None return None
@@ -268,6 +265,7 @@ class Link:
self.owner = owner self.owner = owner
self.destination = destination self.destination = destination
self.expected_hops = None self.expected_hops = None
self.rebalanced = None
self.attached_interface = None self.attached_interface = None
self.__remote_identity = None self.__remote_identity = None
self.__track_phy_stats = False self.__track_phy_stats = False
@@ -277,6 +275,7 @@ class Link:
self.initiator = False self.initiator = False
self.prv = X25519PrivateKey.generate() self.prv = X25519PrivateKey.generate()
self.sig_prv = self.owner.identity.sig_prv self.sig_prv = self.owner.identity.sig_prv
else: else:
self.initiator = True self.initiator = True
self.expected_hops = RNS.Transport.hops_to(self.destination.hash) self.expected_hops = RNS.Transport.hops_to(self.destination.hash)
@@ -296,14 +295,11 @@ class Link:
if peer_pub_bytes == None: if peer_pub_bytes == None:
self.peer_pub = None self.peer_pub = None
self.peer_pub_bytes = None self.peer_pub_bytes = None
else:
self.load_peer(peer_pub_bytes, peer_sig_pub_bytes)
if established_callback != None: else: self.load_peer(peer_pub_bytes, peer_sig_pub_bytes)
self.set_link_established_callback(established_callback)
if closed_callback != None: if established_callback != None: self.set_link_established_callback(established_callback)
self.set_link_closed_callback(closed_callback) if closed_callback != None: self.set_link_closed_callback(closed_callback)
if self.initiator: if self.initiator:
signalling_bytes = b"" signalling_bytes = b""
@@ -334,8 +330,7 @@ class Link:
self.peer_sig_pub_bytes = peer_sig_pub_bytes self.peer_sig_pub_bytes = peer_sig_pub_bytes
self.peer_sig_pub = Ed25519PublicKey.from_public_bytes(self.peer_sig_pub_bytes) self.peer_sig_pub = Ed25519PublicKey.from_public_bytes(self.peer_sig_pub_bytes)
if not hasattr(self.peer_pub, "curve"): if not hasattr(self.peer_pub, "curve"): self.peer_pub.curve = Link.CURVE
self.peer_pub.curve = Link.CURVE
@staticmethod @staticmethod
def link_id_from_lr_packet(packet): def link_id_from_lr_packet(packet):
@@ -399,13 +394,13 @@ class Link:
signalling_bytes = b"" signalling_bytes = b""
confirmed_mtu = None confirmed_mtu = None
mode = Link.mode_from_lp_packet(packet) mode = Link.mode_from_lp_packet(packet)
RNS.log(f"Validating link request proof with mode {Link.MODE_DESCRIPTIONS[mode]}", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Validating link request proof with mode {Link.MODE_DESCRIPTIONS[mode]}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if mode != self.mode: raise TypeError(f"Invalid link mode {mode} in link request proof") if mode != self.mode: raise TypeError(f"Invalid link mode {mode} in link request proof")
if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE: if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
confirmed_mtu = Link.mtu_from_lp_packet(packet) confirmed_mtu = Link.mtu_from_lp_packet(packet)
signalling_bytes = Link.signalling_bytes(confirmed_mtu, mode) signalling_bytes = Link.signalling_bytes(confirmed_mtu, mode)
packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2] packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
RNS.log(f"Destination confirmed link MTU of {RNS.prettysize(confirmed_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Destination confirmed link MTU of {RNS.prettysize(confirmed_mtu)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if self.initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2: if self.initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2:
peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2] peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
@@ -430,7 +425,7 @@ class Link:
self.activated_at = time.time() self.activated_at = time.time()
self.last_proof = self.activated_at self.last_proof = self.activated_at
RNS.Transport.activate_link(self) RNS.Transport.activate_link(self)
RNS.log("Link "+str(self)+" established with "+str(self.destination)+", RTT is "+RNS.prettyshorttime(self.rtt), RNS.LOG_DEBUG) RNS.log(f"Link {self} established with {self.destination}, RTT is {RNS.prettyshorttime(self.rtt)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0: if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0:
self.establishment_rate = self.establishment_cost/self.rtt self.establishment_rate = self.establishment_cost/self.rtt
@@ -447,8 +442,8 @@ class Link:
thread = threading.Thread(target=self.callbacks.link_established, args=(self,)) thread = threading.Thread(target=self.callbacks.link_established, args=(self,))
thread.daemon = True thread.daemon = True
thread.start() thread.start()
else:
RNS.log("Invalid link proof signature received by "+str(self)+". Ignoring.", RNS.LOG_DEBUG) else: RNS.log(f"Invalid link proof signature received by {self}. Ignoring.", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
except Exception as e: except Exception as e:
self.status = Link.CLOSED self.status = Link.CLOSED
@@ -475,7 +470,8 @@ class Link:
self.had_outbound() self.had_outbound()
def request(self, path, data = None, response_callback = None, failed_callback = None, progress_callback = None, timeout = None): def request(self, path, data=None, response_callback=None, failed_callback=None, progress_callback=None,
timeout=None, max_response_size=None):
""" """
Sends a request to the remote peer. Sends a request to the remote peer.
@@ -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 response_callback: An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the :ref:`Request Example<example-request>` for more info.
:param failed_callback: An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the :ref:`Request Example<example-request>` for more info. :param failed_callback: An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the :ref:`Request Example<example-request>` for more info.
:param progress_callback: An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property. :param progress_callback: An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property.
:param max_response_size: An optional maximum accepted response size, in bytes as an integer.
:param timeout: An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT. :param timeout: An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT.
:returns: A :ref:`RNS.RequestReceipt<api-requestreceipt>` instance if the request was sent, or *False* if it was not. :returns: A :ref:`RNS.RequestReceipt<api-requestreceipt>` instance if the request was sent, or *False* if it was not.
""" """
@@ -497,35 +494,20 @@ class Link:
request_packet = RNS.Packet(self, packed_request, RNS.Packet.DATA, context = RNS.Packet.REQUEST) request_packet = RNS.Packet(self, packed_request, RNS.Packet.DATA, context = RNS.Packet.REQUEST)
packet_receipt = request_packet.send() packet_receipt = request_packet.send()
if packet_receipt == False: if packet_receipt == False: return False
return False
else: else:
packet_receipt.set_timeout(timeout) packet_receipt.set_timeout(timeout)
return RequestReceipt( return RequestReceipt(self, packet_receipt=packet_receipt, response_callback=response_callback,
self, failed_callback=failed_callback, progress_callback=progress_callback, timeout=timeout,
packet_receipt = packet_receipt, request_size=len(packed_request), max_response_size=max_response_size)
response_callback = response_callback,
failed_callback = failed_callback,
progress_callback = progress_callback,
timeout = timeout,
request_size = len(packed_request),
)
else: else:
request_id = RNS.Identity.truncated_hash(packed_request) request_id = RNS.Identity.truncated_hash(packed_request)
RNS.log("Sending request "+RNS.prettyhexrep(request_id)+" as resource.", RNS.LOG_DEBUG) RNS.log("Sending request "+RNS.prettyhexrep(request_id)+" as resource.", RNS.LOG_DEBUG)
request_resource = RNS.Resource(packed_request, self, request_id = request_id, is_response = False, timeout = timeout) request_resource = RNS.Resource(packed_request, self, request_id = request_id, is_response = False, timeout = timeout)
return RequestReceipt( return RequestReceipt(self, resource=request_resource, response_callback=response_callback,
self, failed_callback=failed_callback, progress_callback=progress_callback, timeout=timeout,
resource = request_resource, request_size=len(packed_request), max_response_size=max_response_size)
response_callback = response_callback,
failed_callback = failed_callback,
progress_callback = progress_callback,
timeout = timeout,
request_size = len(packed_request),
)
def update_mdu(self): def update_mdu(self):
self.mdu = self.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE self.mdu = self.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
@@ -540,6 +522,7 @@ class Link:
self.rtt = max(measured_rtt, rtt) self.rtt = max(measured_rtt, rtt)
self.status = Link.ACTIVE self.status = Link.ACTIVE
self.activated_at = time.time() 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: if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0:
self.establishment_rate = self.establishment_cost/self.rtt self.establishment_rate = self.establishment_cost/self.rtt
@@ -547,10 +530,8 @@ class Link:
self.__update_keepalive() self.__update_keepalive()
try: try:
if self.owner.callbacks.link_established != None: if self.owner.callbacks.link_established != None: self.owner.callbacks.link_established(self)
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 in external link establishment callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
except Exception as e: except Exception as e:
RNS.log("Error occurred while processing RTT packet, tearing down link. The contained exception was: "+str(e), RNS.LOG_ERROR) 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``. :param track: Whether or not to keep track of physical layer statistics. Value must be ``True`` or ``False``.
""" """
if track: if track: self.__track_phy_stats = True
self.__track_phy_stats = True else: self.__track_phy_stats = False
else:
self.__track_phy_stats = False
def get_rssi(self): 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. :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: if self.__track_phy_stats: return self.rssi
return self.rssi else: return None
else:
return None
def get_snr(self): 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. :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: if self.__track_phy_stats: return self.snr
return self.snr else: return None
else:
return None
def get_q(self): 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. :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: if self.__track_phy_stats: return self.q
return self.q else: return None
else:
return None
def get_establishment_rate(self): def get_establishment_rate(self):
""" """
:returns: The data transfer rate at which the link establishment procedure ocurred, in bits per second. :returns: The data transfer rate at which the link establishment procedure ocurred, in bits per second.
""" """
if self.establishment_rate != None: if self.establishment_rate != None: return self.establishment_rate*8
return self.establishment_rate*8 else: return None
else:
return None
def get_mtu(self): def get_mtu(self):
""" """
:returns: The MTU of an established link. :returns: The MTU of an established link.
""" """
if self.status == Link.ACTIVE: if self.status == Link.ACTIVE: return self.mtu
return self.mtu else: return None
else:
return None
def get_mdu(self): def get_mdu(self):
""" """
:returns: The packet MDU of an established link. :returns: The packet MDU of an established link.
""" """
if self.status == Link.ACTIVE: if self.status == Link.ACTIVE: return self.mdu
return self.mdu else: return None
else:
return None
def get_expected_rate(self): 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: if self.status == Link.ACTIVE: return self.expected_rate
return self.expected_rate else: return None
else:
return None
def get_mode(self): def get_mode(self):
""" """
@@ -649,10 +614,8 @@ class Link:
""" """
:returns: The time in seconds since this link was established. :returns: The time in seconds since this link was established.
""" """
if self.activated_at: if self.activated_at: return time.time() - self.activated_at
return time.time() - self.activated_at else: return None
else:
return None
def no_inbound_for(self): def no_inbound_for(self):
""" """
@@ -701,6 +664,7 @@ class Link:
Closes the link and purges encryption keys. New keys will Closes the link and purges encryption keys. New keys will
be used if a new link to the same destination is established. be used if a new link to the same destination is established.
""" """
if self.status == Link.CLOSED: return
if self.status != Link.PENDING and self.status != Link.CLOSED: self.__teardown_packet() if self.status != Link.PENDING and self.status != Link.CLOSED: self.__teardown_packet()
self.status = Link.CLOSED self.status = Link.CLOSED
if self.initiator: self.teardown_reason = Link.INITIATOR_CLOSED if self.initiator: self.teardown_reason = Link.INITIATOR_CLOSED
@@ -712,18 +676,15 @@ class Link:
plaintext = self.decrypt(packet.data) plaintext = self.decrypt(packet.data)
if plaintext == self.link_id: if plaintext == self.link_id:
self.status = Link.CLOSED self.status = Link.CLOSED
if self.initiator: if self.initiator: self.teardown_reason = Link.DESTINATION_CLOSED
self.teardown_reason = Link.DESTINATION_CLOSED else: self.teardown_reason = Link.INITIATOR_CLOSED
else:
self.teardown_reason = Link.INITIATOR_CLOSED
self.__update_phy_stats(packet) self.__update_phy_stats(packet)
self.link_closed() self.link_closed()
except Exception as e: except Exception as e: pass
pass
def link_closed(self): def link_closed(self):
for resource in self.incoming_resources: resource.cancel() for resource in self.incoming_resources.copy(): resource.cancel()
for resource in self.outgoing_resources: resource.cancel() for resource in self.outgoing_resources.copy(): resource.cancel()
if self._channel: self._channel._shutdown() if self._channel: self._channel._shutdown()
self.prv = None self.prv = None
@@ -752,9 +713,7 @@ class Link:
while not self.status == Link.CLOSED: while not self.status == Link.CLOSED:
while (self.watchdog_lock): while (self.watchdog_lock):
rtt_wait = 0.025 rtt_wait = 0.025
if hasattr(self, "rtt") and self.rtt: if hasattr(self, "rtt") and self.rtt: rtt_wait = self.rtt
rtt_wait = self.rtt
sleep(max(rtt_wait, 0.025)) sleep(max(rtt_wait, 0.025))
if not self.status == Link.CLOSED: if not self.status == Link.CLOSED:
@@ -779,28 +738,25 @@ class Link:
self.link_closed() self.link_closed()
sleep_time = 0.001 sleep_time = 0.001
if self.initiator: if self.initiator: RNS.log("Timeout waiting for link request proof", RNS.LOG_DEBUG)
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)
else:
RNS.log("Timeout waiting for RTT packet from link initiator", RNS.LOG_DEBUG)
elif self.status == Link.ACTIVE: elif self.status == Link.ACTIVE:
activated_at = self.activated_at if self.activated_at != None else 0 activated_at = self.activated_at if self.activated_at != None else 0
last_inbound = max(max(self.last_inbound, self.last_proof), activated_at) last_inbound = max(max(self.last_inbound, self.last_proof), activated_at)
now = time.time() now = time.time()
if now >= last_inbound + self.keepalive: if now >= last_inbound + self.keepalive or now >= self.last_outbound + self.keepalive:
if self.initiator and now >= self.last_keepalive + self.keepalive: if self.initiator and now >= self.last_keepalive + self.keepalive:
self.send_keepalive() self.send_keepalive()
if time.time() >= last_inbound + self.stale_time: if now >= last_inbound + self.stale_time:
sleep_time = self.rtt * self.keepalive_timeout_factor + Link.STALE_GRACE sleep_time = self.rtt * self.keepalive_timeout_factor + Link.STALE_GRACE
self.status = Link.STALE self.status = Link.STALE
else:
sleep_time = self.keepalive
else: else: sleep_time = self.keepalive
sleep_time = (last_inbound + self.keepalive) - time.time()
else: sleep_time = (last_inbound + self.keepalive) - now
elif self.status == Link.STALE: elif self.status == Link.STALE:
sleep_time = 0.001 sleep_time = 0.001
@@ -810,10 +766,9 @@ class Link:
self.link_closed() self.link_closed()
if sleep_time == 0: if sleep_time == 0: RNS.log(f"Link watchdog sleep time of 0 on {self}", RNS.LOG_ERROR)
RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_ERROR)
if sleep_time == None or sleep_time < 0: if sleep_time == None or sleep_time < 0:
RNS.log("Timing error! Tearing down link "+str(self)+" now.", RNS.LOG_ERROR) RNS.log(f"Timing error, tearing down link {self} now", RNS.LOG_ERROR)
self.teardown() self.teardown()
sleep_time = 0.1 sleep_time = 0.1
@@ -825,7 +780,6 @@ class Link:
self.snr = None self.snr = None
self.q = None self.q = None
def __update_phy_stats(self, packet, query_shared = True, force_update = False): def __update_phy_stats(self, packet, query_shared = True, force_update = False):
if self.__track_phy_stats or force_update: if self.__track_phy_stats or force_update:
if query_shared: if query_shared:
@@ -834,12 +788,9 @@ class Link:
if packet.snr == None: packet.snr = reticulum.get_packet_snr(packet.packet_hash) 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.q == None: packet.q = reticulum.get_packet_q(packet.packet_hash)
if packet.rssi != None: if packet.rssi != None: self.rssi = packet.rssi
self.rssi = packet.rssi if packet.snr != None: self.snr = packet.snr
if packet.snr != None: if packet.q != None: self.q = packet.q
self.snr = packet.snr
if packet.q != None:
self.q = packet.q
def __update_keepalive(self): def __update_keepalive(self):
self.keepalive = max(min(self.rtt*(Link.KEEPALIVE_MAX/Link.KEEPALIVE_MAX_RTT), Link.KEEPALIVE_MAX), Link.KEEPALIVE_MIN) 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] request_data = unpacked_request[2]
if path_hash in self.destination.request_handlers: if path_hash in self.destination.request_handlers:
request_handler = self.destination.request_handlers[path_hash] request_handler = self.destination.request_handlers[path_hash]
path = request_handler[0] path = request_handler[0]
response_generator = request_handler[1] response_generator = request_handler[1]
allow = request_handler[2] allow = request_handler[2]
@@ -903,21 +854,28 @@ class Link:
identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "<Unknown>" identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "<Unknown>"
RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG) RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG)
def handle_response(self, request_id, response_data, response_size, response_transfer_size, metadata=None): def handle_response(self, request_id, response_data, response_size, response_transfer_size, metadata=None, update_sizes=False, check_size=False):
if self.status == Link.ACTIVE: if self.status == Link.ACTIVE:
remove = None remove = None
for pending_request in self.pending_requests: for pending_request in self.pending_requests:
if pending_request.request_id == request_id: if pending_request.request_id == request_id:
remove = pending_request if not check_size or pending_request.max_response_size == None: size_ok = True
try: else: size_ok = response_size <= pending_request.max_response_size
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)
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 break
if remove != None: if remove != None:
@@ -933,8 +891,8 @@ class Link:
def job(): self.handle_request(request_id, request_data) def job(): self.handle_request(request_id, request_data)
threading.Thread(target=job, daemon=True).start() 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): def response_resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
@@ -965,23 +923,27 @@ class Link:
:return: ``Channel`` object :return: ``Channel`` object
""" """
if self._channel is None: if self._channel is None: self._channel = Channel(LinkChannelOutlet(self))
self._channel = Channel(LinkChannelOutlet(self))
return self._channel return self._channel
def receive(self, packet): def receive(self, packet):
self.watchdog_lock = True self.watchdog_lock = True
try: self.__receive(packet)
except Exception as e:
RNS.log(f"Error on {self} while receiving packet: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
finally: self.watchdog_lock = False
def __receive(self, packet):
if not self.status == Link.CLOSED and not (self.initiator and packet.context == RNS.Packet.KEEPALIVE and packet.data == bytes([0xFF])): if not self.status == Link.CLOSED and not (self.initiator and packet.context == RNS.Packet.KEEPALIVE and packet.data == bytes([0xFF])):
if packet.receiving_interface != self.attached_interface: if packet.receiving_interface != self.attached_interface:
RNS.log(f"Link-associated packet received on unexpected interface {packet.receiving_interface} instead of {self.attached_interface}! Someone might be trying to manipulate your communication!", RNS.LOG_ERROR) RNS.log(f"Link-associated packet received on unexpected interface {packet.receiving_interface} instead of {self.attached_interface}! Someone might be trying to manipulate your communication!", RNS.LOG_ERROR)
else: else:
self.last_inbound = time.time() self.last_inbound = time.time()
if packet.context != RNS.Packet.KEEPALIVE: if packet.context != RNS.Packet.KEEPALIVE: self.last_data = self.last_inbound
self.last_data = self.last_inbound
self.rx += 1 self.rx += 1
self.rxbytes += len(packet.data) self.rxbytes += len(packet.data)
if self.status == Link.STALE: if self.status == Link.STALE: self.status = Link.ACTIVE
self.status = Link.ACTIVE
if packet.packet_type == RNS.Packet.DATA: if packet.packet_type == RNS.Packet.DATA:
should_query = False should_query = False
@@ -1002,10 +964,8 @@ class Link:
elif self.destination.proof_strategy == RNS.Destination.PROVE_APP: elif self.destination.proof_strategy == RNS.Destination.PROVE_APP:
if self.destination.callbacks.proof_requested: if self.destination.callbacks.proof_requested:
try: try:
if self.destination.callbacks.proof_requested(packet): if self.destination.callbacks.proof_requested(packet): packet.prove()
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)
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: elif packet.context == RNS.Packet.LINKIDENTIFY:
plaintext = self.decrypt(packet.data) plaintext = self.decrypt(packet.data)
@@ -1018,12 +978,16 @@ class Link:
identity.load_public_key(public_key) identity.load_public_key(public_key)
if identity.validate(signature, signed_data): if identity.validate(signature, signed_data):
self.__remote_identity = identity if RNS.Reticulum.get_instance().is_blackholed(identity.hash):
if self.callbacks.remote_identified != None: RNS.log(f"Terminating incoming link from blackholed identity {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
try: self.teardown()
self.callbacks.remote_identified(self, self.__remote_identity)
except Exception as e: else:
RNS.log("Error while executing remote identified callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) 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) self.__update_phy_stats(packet, query_shared=True)
@@ -1032,12 +996,15 @@ class Link:
request_id = packet.getTruncatedHash() request_id = packet.getTruncatedHash()
packed_request = self.decrypt(packet.data) packed_request = self.decrypt(packet.data)
if packed_request != None: if packed_request != None:
unpacked_request = umsgpack.unpackb(packed_request) if self.destination.max_request_size == None: size_ok = True
def job(): self.handle_request(request_id, unpacked_request) else: size_ok = len(packed_request) <= self.destination.max_request_size
threading.Thread(target=job, daemon=True).start() if not size_ok: RNS.log(f"Ignored request with excessive size {RNS.prettysize(len(packed_request))} on {self.destination}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
else:
unpacked_request = umsgpack.unpackb(packed_request)
def job(): self.handle_request(request_id, unpacked_request)
threading.Thread(target=job, daemon=True).start()
self.__update_phy_stats(packet, query_shared=True) self.__update_phy_stats(packet, query_shared=True)
except Exception as e: except Exception as e: RNS.log("Error occurred while handling request. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log("Error occurred while handling request. The contained exception was: "+str(e), RNS.LOG_ERROR)
elif packet.context == RNS.Packet.RESPONSE: elif packet.context == RNS.Packet.RESPONSE:
try: try:
@@ -1047,11 +1014,10 @@ class Link:
request_id = unpacked_response[0] request_id = unpacked_response[0]
response_data = unpacked_response[1] response_data = unpacked_response[1]
transfer_size = len(umsgpack.packb(response_data))-2 transfer_size = len(umsgpack.packb(response_data))-2
def job(): self.handle_response(request_id, response_data, transfer_size, transfer_size) def job(): self.handle_response(request_id, response_data, transfer_size, transfer_size, update_sizes=True, check_size=True)
threading.Thread(target=job, daemon=True).start() threading.Thread(target=job, daemon=True).start()
self.__update_phy_stats(packet, query_shared=True) self.__update_phy_stats(packet, query_shared=True)
except Exception as e: except Exception as e: RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
elif packet.context == RNS.Packet.LRRTT: elif packet.context == RNS.Packet.LRRTT:
if not self.initiator: if not self.initiator:
@@ -1066,36 +1032,51 @@ class Link:
packet.plaintext = self.decrypt(packet.data) packet.plaintext = self.decrypt(packet.data)
if packet.plaintext != None: if packet.plaintext != None:
self.__update_phy_stats(packet, query_shared=True) self.__update_phy_stats(packet, query_shared=True)
try:
if RNS.ResourceAdvertisement.is_request(packet): if RNS.ResourceAdvertisement.is_request(packet):
RNS.Resource.accept(packet, callback=self.request_resource_concluded) if self.destination.request_handlers:
elif RNS.ResourceAdvertisement.is_response(packet): if self.destination.max_request_size == None: size_ok = True
request_id = RNS.ResourceAdvertisement.read_request_id(packet) else: size_ok = RNS.ResourceAdvertisement.read_size(packet) <= self.destination.max_request_size
for pending_request in self.pending_requests: if size_ok: RNS.Resource.accept(packet, callback=self.request_resource_concluded)
if pending_request.request_id == request_id: else:
response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id) RNS.Resource.reject(packet)
if response_resource != None: RNS.log(f"Rejected request with excessive size {RNS.prettysize(RNS.ResourceAdvertisement.read_size(packet))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if pending_request.response_size == None: elif RNS.ResourceAdvertisement.is_response(packet):
pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet) request_id = RNS.ResourceAdvertisement.read_request_id(packet)
if pending_request.response_transfer_size == None: for pending_request in self.pending_requests:
pending_request.response_transfer_size = 0 if pending_request.request_id == request_id:
pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet) if pending_request.max_response_size == None: size_ok = True
if pending_request.started_at == None: else: size_ok = RNS.ResourceAdvertisement.read_size(packet) <= pending_request.max_response_size
pending_request.started_at = time.time() if not size_ok:
pending_request.response_resource_progress(response_resource) RNS.Resource.reject(packet)
pending_request.response_rejected()
elif self.resource_strategy == Link.ACCEPT_NONE: pass RNS.log(f"Rejected response with excessive size {RNS.prettysize(RNS.ResourceAdvertisement.read_size(packet))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
elif self.resource_strategy == Link.ACCEPT_APP: else:
if self.callbacks.resource != None: response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id)
try: if response_resource != None:
resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext) if pending_request.response_size == None:
resource_advertisement.link = self pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet)
if self.callbacks.resource(resource_advertisement): RNS.Resource.accept(packet, self.callbacks.resource_concluded) if pending_request.response_transfer_size == None:
else: RNS.Resource.reject(packet) pending_request.response_transfer_size = 0
except Exception as e: pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet)
RNS.log("Error while executing resource accept callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) if pending_request.started_at == None:
elif self.resource_strategy == Link.ACCEPT_ALL: pending_request.started_at = time.time()
RNS.Resource.accept(packet, self.callbacks.resource_concluded) pending_request.response_resource_progress(response_resource)
elif self.resource_strategy == Link.ACCEPT_NONE: pass
elif self.resource_strategy == Link.ACCEPT_APP:
if self.callbacks.resource != None:
try:
resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext)
resource_advertisement.link = self
if self.callbacks.resource(resource_advertisement): RNS.Resource.accept(packet, self.callbacks.resource_concluded)
else: RNS.Resource.reject(packet)
except Exception as e:
RNS.log("Error while executing resource accept callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
elif self.resource_strategy == Link.ACCEPT_ALL:
RNS.Resource.accept(packet, self.callbacks.resource_concluded)
except Exception as e:
RNS.log(f"Invalid resource advertisement on {self}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.teardown()
elif packet.context == RNS.Packet.RESOURCE_REQ: elif packet.context == RNS.Packet.RESOURCE_REQ:
plaintext = self.decrypt(packet.data) plaintext = self.decrypt(packet.data)
@@ -1148,9 +1129,10 @@ class Link:
elif packet.context == RNS.Packet.KEEPALIVE: elif packet.context == RNS.Packet.KEEPALIVE:
if not self.initiator and packet.data == bytes([0xFF]): if not self.initiator and packet.data == bytes([0xFF]):
keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE) if time.time() >= self.last_outbound + self.keepalive:
keepalive_packet.send() keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE)
self.had_outbound(is_keepalive = True) keepalive_packet.send()
self.had_outbound(is_keepalive = True)
# TODO: find the most efficient way to allow multiple # TODO: find the most efficient way to allow multiple
@@ -1181,9 +1163,6 @@ class Link:
threading.Thread(target=job, daemon=True).start() threading.Thread(target=job, daemon=True).start()
self.__update_phy_stats(packet, query_shared=True) self.__update_phy_stats(packet, query_shared=True)
self.watchdog_lock = False
def encrypt(self, plaintext): def encrypt(self, plaintext):
try: try:
if not self.token: if not self.token:
@@ -1198,7 +1177,6 @@ class Link:
RNS.log("Encryption on link "+str(self)+" failed. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Encryption on link "+str(self)+" failed. The contained exception was: "+str(e), RNS.LOG_ERROR)
raise e raise e
def decrypt(self, ciphertext): def decrypt(self, ciphertext):
try: try:
if not self.token: self.token = Token(self.derived_key) 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) RNS.log("Decryption failed on link "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
return None return None
def sign(self, message): def sign(self, message):
return self.sig_prv.sign(message) return self.sig_prv.sign(message)
@@ -1216,8 +1193,7 @@ class Link:
try: try:
self.peer_sig_pub.verify(signature, message) self.peer_sig_pub.verify(signature, message)
return True return True
except Exception as e: except Exception as e: return False
return False
def set_link_established_callback(self, callback): def set_link_established_callback(self, callback):
self.callbacks.link_established = callback self.callbacks.link_established = callback
@@ -1345,7 +1321,9 @@ class RequestReceipt():
RECEIVING = 0x03 RECEIVING = 0x03
READY = 0x04 READY = 0x04
def __init__(self, link, packet_receipt = None, resource = None, response_callback = None, failed_callback = None, progress_callback = None, timeout = None, request_size = None): def __init__(self, link, packet_receipt=None, resource=None, response_callback=None, failed_callback=None,
progress_callback=None, timeout=None, request_size=None, max_response_size=None):
self.packet_receipt = packet_receipt self.packet_receipt = packet_receipt
self.resource = resource self.resource = resource
self.started_at = None self.started_at = None
@@ -1372,6 +1350,7 @@ class RequestReceipt():
self.progress = 0 self.progress = 0
self.concluded_at = None self.concluded_at = None
self.response_concluded_at = None self.response_concluded_at = None
self.max_response_size = max_response_size
if timeout != None: if timeout != None:
self.timeout = timeout self.timeout = timeout
@@ -1385,7 +1364,6 @@ class RequestReceipt():
self.link.pending_requests.append(self) self.link.pending_requests.append(self)
def request_resource_concluded(self, resource): def request_resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
RNS.log("Request "+RNS.prettyhexrep(self.request_id)+" successfully sent as resource.", RNS.LOG_DEBUG) 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) self.link.pending_requests.remove(self)
if self.callbacks.failed != None: if self.callbacks.failed != None:
try: try: self.callbacks.failed(self)
self.callbacks.failed(self)
except Exception as e: except Exception as e:
RNS.log("Error while executing request failed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error while executing request failed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
def __response_timeout_job(self): def __response_timeout_job(self):
while self.status == RequestReceipt.DELIVERED: while self.status == RequestReceipt.DELIVERED:
now = time.time() now = time.time()
@@ -1418,7 +1394,6 @@ class RequestReceipt():
time.sleep(0.1) time.sleep(0.1)
def request_timed_out(self, packet_receipt): def request_timed_out(self, packet_receipt):
if self in self.link.pending_requests and self.status == RequestReceipt.DELIVERED: if self in self.link.pending_requests and self.status == RequestReceipt.DELIVERED:
self.status = RequestReceipt.FAILED self.status = RequestReceipt.FAILED
@@ -1427,9 +1402,17 @@ class RequestReceipt():
if self.callbacks.failed != None: if self.callbacks.failed != None:
try: self.callbacks.failed(self) try: self.callbacks.failed(self)
except Exception as e: 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)
RNS.log("Error while executing request timed out callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
def response_rejected(self):
if self in self.link.pending_requests and self.status == RequestReceipt.DELIVERED:
self.status = RequestReceipt.FAILED
self.concluded_at = time.time()
self.link.pending_requests.remove(self)
if self.callbacks.failed != None:
try: self.callbacks.failed(self)
except Exception as e: RNS.log("Error while executing request timed out callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
def response_resource_progress(self, resource): def response_resource_progress(self, resource):
if resource != None: if resource != None:
@@ -1446,13 +1429,10 @@ class RequestReceipt():
self.progress = resource.get_progress() self.progress = resource.get_progress()
if self.callbacks.progress != None: if self.callbacks.progress != None:
try: try: self.callbacks.progress(self)
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)
else:
resource.cancel()
else: resource.cancel()
def response_received(self, response, metadata=None): def response_received(self, response, metadata=None):
if not self.status == RequestReceipt.FAILED: if not self.status == RequestReceipt.FAILED:
@@ -1471,13 +1451,11 @@ class RequestReceipt():
if self.callbacks.progress != None: if self.callbacks.progress != None:
try: self.callbacks.progress(self) try: self.callbacks.progress(self)
except Exception as e: except Exception as e: RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
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: if self.callbacks.response != None:
try: self.callbacks.response(self) try: self.callbacks.response(self)
except Exception as e: except Exception as e: RNS.log("Error while executing response received callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
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): def get_request_id(self):
""" """
@@ -1501,31 +1479,23 @@ class RequestReceipt():
""" """
:returns: The response as *bytes* if it is ready, otherwise *None*. :returns: The response as *bytes* if it is ready, otherwise *None*.
""" """
if self.status == RequestReceipt.READY: if self.status == RequestReceipt.READY: return self.response
return self.response else: return None
else:
return None
def get_response_time(self): def get_response_time(self):
""" """
:returns: The response time of the request in seconds. :returns: The response time of the request in seconds.
""" """
if self.status == RequestReceipt.READY: if self.status == RequestReceipt.READY: return self.response_concluded_at - self.started_at
return self.response_concluded_at - self.started_at else: return None
else:
return None
def concluded(self): def concluded(self):
""" """
:returns: True if the associated request has concluded (successfully or with a failure), otherwise False. :returns: True if the associated request has concluded (successfully or with a failure), otherwise False.
""" """
if self.status == RequestReceipt.READY: if self.status == RequestReceipt.READY: return True
return True elif self.status == RequestReceipt.FAILED: return True
elif self.status == RequestReceipt.FAILED: else: return False
return True
else:
return False
class RequestReceiptCallbacks: class RequestReceiptCallbacks:
+65 -77
View File
@@ -118,6 +118,7 @@ class Packet:
__slots__ += "transport_id", "data", "flags", "raw", "packed", "sent", "create_receipt", "receipt", "fromPacked", "MTU" __slots__ += "transport_id", "data", "flags", "raw", "packed", "sent", "create_receipt", "receipt", "fromPacked", "MTU"
__slots__ += "sent_at", "packet_hash", "ratchet_id", "attached_interface", "receiving_interface", "rssi", "snr", "q" __slots__ += "sent_at", "packet_hash", "ratchet_id", "attached_interface", "receiving_interface", "rssi", "snr", "q"
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr" __slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr"
__slots__ += "traffic_class", "announce_signature_validated"
def __init__(self, destination, data, packet_type = DATA, context = NONE, transport_type = RNS.Transport.BROADCAST, def __init__(self, destination, data, packet_type = DATA, context = NONE, transport_type = RNS.Transport.BROADCAST,
header_type = HEADER_1, transport_id = None, attached_interface = None, create_receipt = True, context_flag=FLAG_UNSET): header_type = HEADER_1, transport_id = None, attached_interface = None, create_receipt = True, context_flag=FLAG_UNSET):
@@ -159,6 +160,8 @@ class Packet:
self.packet_hash = None self.packet_hash = None
self.ratchet_id = None self.ratchet_id = None
self.traffic_class = None
self.announce_signature_validated = None
self.attached_interface = attached_interface self.attached_interface = attached_interface
self.receiving_interface = None self.receiving_interface = None
self.is_outbound_pr = False self.is_outbound_pr = False
@@ -244,6 +247,9 @@ class Packet:
self.flags = self.raw[0] self.flags = self.raw[0]
self.hops = self.raw[1] 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.header_type = (self.flags & 0b01000000) >> 6
self.context_flag = (self.flags & 0b00100000) >> 5 self.context_flag = (self.flags & 0b00100000) >> 5
self.transport_type = (self.flags & 0b00010000) >> 4 self.transport_type = (self.flags & 0b00010000) >> 4
@@ -257,18 +263,23 @@ class Packet:
self.destination_hash = self.raw[DST_LEN+2:2*DST_LEN+2] self.destination_hash = self.raw[DST_LEN+2:2*DST_LEN+2]
self.context = ord(self.raw[2*DST_LEN+2:2*DST_LEN+3]) self.context = ord(self.raw[2*DST_LEN+2:2*DST_LEN+3])
self.data = self.raw[2*DST_LEN+3:] self.data = self.raw[2*DST_LEN+3:]
if len(self.transport_id) != DST_LEN: raise ValueError("Malformed Transport ID field")
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
else: else:
self.transport_id = None self.transport_id = None
self.destination_hash = self.raw[2:DST_LEN+2] self.destination_hash = self.raw[2:DST_LEN+2]
self.context = ord(self.raw[DST_LEN+2:DST_LEN+3]) self.context = ord(self.raw[DST_LEN+2:DST_LEN+3])
self.data = self.raw[DST_LEN+3:] self.data = self.raw[DST_LEN+3:]
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
if len(self.data) == 0: raise ValueError("Zero-length data field")
self.packed = False self.packed = False
self.update_hash() self.update_hash()
return True return True
except Exception as e: except Exception as e:
RNS.log("Received malformed packet, dropping it. The contained exception was: "+str(e), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None 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 return False
def send(self): def send(self):
@@ -278,6 +289,8 @@ class Packet:
:returns: A :ref:`RNS.PacketReceipt<api-packetreceipt>` instance if *create_receipt* was set to *True* when the packet was instantiated, if not returns *None*. If the packet could not be sent *False* is returned. :returns: A :ref:`RNS.PacketReceipt<api-packetreceipt>` instance if *create_receipt* was set to *True* when the packet was instantiated, if not returns *None*. If the packet could not be sent *False* is returned.
""" """
if not self.sent: if not self.sent:
if self.hops >= RNS.Transport.PATHFINDER_M: return False
if not self.packed: self.pack()
if self.destination.type == RNS.Destination.LINK: if self.destination.type == RNS.Destination.LINK:
if self.destination.status == RNS.Link.CLOSED: if self.destination.status == RNS.Link.CLOSED:
RNS.log("Attempt to transmit over a closed link, dropping packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None RNS.log("Attempt to transmit over a closed link, dropping packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
@@ -288,13 +301,13 @@ class Packet:
else: else:
self.destination.last_outbound = time.time() self.destination.last_outbound = time.time()
self.destination.tx += 1 self.destination.tx += 1
self.destination.txbytes += len(self.data) self.destination.txbytes += len(self.ciphertext)
if not self.packed: self.pack()
if RNS.Transport.outbound(self): return self.receipt if RNS.Transport.outbound(self): return self.receipt
else: else:
RNS.log("No interfaces could process the outbound packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None 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.sent = False
self.receipt = None self.receipt = None
return False return False
@@ -313,51 +326,44 @@ class Packet:
# encrypted destinations # encrypted destinations
self.pack() self.pack()
if RNS.Transport.outbound(self): if RNS.Transport.outbound(self): return self.receipt
return self.receipt
else: else:
RNS.log("Re-send failed. No interfaces could process the outbound packet", RNS.LOG_WARNING) RNS.log("Re-send failed. No interfaces could process the outbound packet", RNS.LOG_WARNING)
self.sent = False self.sent = False
self.receipt = None self.receipt = None
return False return False
else:
raise IOError("Packet was not sent yet") else: raise IOError("Packet was not sent yet")
def prove(self, destination=None): def prove(self, destination=None):
if self.fromPacked and hasattr(self, "destination") and self.destination: if self.fromPacked and hasattr(self, "destination") and self.destination:
if self.destination.identity and self.destination.identity.prv: if self.destination.identity and self.destination.identity.prv:
self.destination.identity.prove(self, destination) self.destination.identity.prove(self, destination)
elif self.fromPacked and hasattr(self, "link") and self.link: elif self.fromPacked and hasattr(self, "link") and self.link: self.link.prove_packet(self)
self.link.prove_packet(self) else: RNS.log("Could not prove packet associated with neither a destination nor a link", RNS.LOG_ERROR)
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 # Generates a special destination that allows Reticulum
# to direct the proof back to the proved packet's sender # to direct the proof back to the proved packet's sender
def generate_proof_destination(self): def generate_proof_destination(self): return ProofDestination(self)
return ProofDestination(self)
def validate_proof_packet(self, proof_packet): def validate_proof_packet(self, proof_packet): return self.receipt.validate_proof_packet(proof_packet)
return self.receipt.validate_proof_packet(proof_packet)
def validate_proof(self, proof): def validate_proof(self, proof): return self.receipt.validate_proof(proof)
return self.receipt.validate_proof(proof)
def update_hash(self): def update_hash(self): self.packet_hash = self.get_hash()
self.packet_hash = self.get_hash()
def get_hash(self): def get_hash(self): return RNS.Identity.full_hash(self.get_hashable_part())
return RNS.Identity.full_hash(self.get_hashable_part())
def getTruncatedHash(self): def getTruncatedHash(self): return RNS.Identity.truncated_hash(self.get_hashable_part())
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): def get_hashable_part(self):
hashable_part = bytes([self.raw[0] & 0b00001111]) hashable_part = bytes([self.raw[0] & 0b00001111])
if self.header_type == Packet.HEADER_2: if self.header_type == Packet.HEADER_2: hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:] else: hashable_part += self.raw[2:]
else:
hashable_part += self.raw[2:]
return hashable_part return hashable_part
@@ -365,36 +371,29 @@ class Packet:
""" """
:returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``. :returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``.
""" """
if self.rssi != None: if self.rssi != None: return self.rssi
return self.rssi else: return RNS.Reticulum.get_instance().get_packet_rssi(self.packet_hash)
else:
return reticulum.get_packet_rssi(self.packet_hash)
def get_snr(self): def get_snr(self):
""" """
:returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``. :returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``.
""" """
if self.snr != None: if self.snr != None: return self.snr
return self.snr else: return RNS.Reticulum.get_instance().get_packet_snr(self.packet_hash)
else:
return reticulum.get_packet_snr(self.packet_hash)
def get_q(self): def get_q(self):
""" """
:returns: The physical layer *Link Quality* if available, otherwise ``None``. :returns: The physical layer *Link Quality* if available, otherwise ``None``.
""" """
if self.q != None: if self.q != None: return self.q
return self.q else: return RNS.Reticulum.get_instance().get_packet_q(self.packet_hash)
else:
return reticulum.get_packet_q(self.packet_hash)
class ProofDestination: class ProofDestination:
def __init__(self, packet): 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 self.type = RNS.Destination.SINGLE
def encrypt(self, plaintext): def encrypt(self, plaintext): return plaintext
return plaintext
class PacketReceipt: class PacketReceipt:
@@ -416,8 +415,8 @@ class PacketReceipt:
# Creates a new packet receipt from a sent packet # Creates a new packet receipt from a sent packet
def __init__(self, packet): def __init__(self, packet):
self.hash = packet.get_hash() self.hash = packet.packet_hash
self.truncated_hash = packet.getTruncatedHash() self.truncated_hash = packet.truncated_packet_hash
self.sent = True self.sent = True
self.sent_at = time.time() self.sent_at = time.time()
self.proved = False self.proved = False
@@ -463,18 +462,17 @@ class PacketReceipt:
link.last_proof = self.concluded_at link.last_proof = self.concluded_at
if self.callbacks.delivery != None: if self.callbacks.delivery != None:
try: try: self.callbacks.delivery(self)
self.callbacks.delivery(self)
except Exception as e: except Exception as e:
RNS.log("An error occurred while evaluating external delivery callback for "+str(link), RNS.LOG_ERROR) 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.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.trace_exception(e) RNS.trace_exception(e)
return True return True
else:
return False else: return False
else: else: return False
return False
elif len(proof) == PacketReceipt.IMPL_LENGTH: elif len(proof) == PacketReceipt.IMPL_LENGTH:
pass pass
# TODO: Why is this disabled? # TODO: Why is this disabled?
@@ -491,8 +489,7 @@ class PacketReceipt:
# else: # else:
# RNS.log("invalid") # RNS.log("invalid")
# return False # return False
else: else: return False
return False
# Validate a raw proof # Validate a raw proof
def validate_proof(self, proof, proof_packet=None): def validate_proof(self, proof, proof_packet=None):
@@ -509,24 +506,20 @@ class PacketReceipt:
self.proof_packet = proof_packet self.proof_packet = proof_packet
if self.callbacks.delivery != None: if self.callbacks.delivery != None:
try: try: self.callbacks.delivery(self)
self.callbacks.delivery(self)
except Exception as e: except Exception as e:
RNS.log("Error while executing proof validated callback. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error while executing proof validated callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
return True return True
else:
return False else: return False
else: else: return False
return False
elif len(proof) == PacketReceipt.IMPL_LENGTH: elif len(proof) == PacketReceipt.IMPL_LENGTH:
# This is an implicit proof # This is an implicit proof
if not hasattr(self.destination, "identity"): if not hasattr(self.destination, "identity"): return False
return False if self.destination.identity == None: return False
if self.destination.identity == None:
return False
signature = proof[:RNS.Identity.SIGLENGTH//8] signature = proof[:RNS.Identity.SIGLENGTH//8]
proof_valid = self.destination.identity.validate(signature, self.hash) proof_valid = self.destination.identity.validate(signature, self.hash)
@@ -537,16 +530,13 @@ class PacketReceipt:
self.proof_packet = proof_packet self.proof_packet = proof_packet
if self.callbacks.delivery != None: if self.callbacks.delivery != None:
try: try: self.callbacks.delivery(self)
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)
except Exception as e:
RNS.log("Error while executing proof validated callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
return True return True
else:
return False else: return False
else: else: return False
return False
def get_rtt(self): def get_rtt(self):
""" """
@@ -559,10 +549,8 @@ class PacketReceipt:
def check_timeout(self): def check_timeout(self):
if self.status == PacketReceipt.SENT and self.is_timed_out(): if self.status == PacketReceipt.SENT and self.is_timed_out():
if self.timeout == -1: if self.timeout == -1: self.status = PacketReceipt.CULLED
self.status = PacketReceipt.CULLED else: self.status = PacketReceipt.FAILED
else:
self.status = PacketReceipt.FAILED
self.concluded_at = time.time() self.concluded_at = time.time()
+1 -2
View File
@@ -31,5 +31,4 @@
class Resolver: class Resolver:
@staticmethod @staticmethod
def resolve_identity(full_name): def resolve_identity(full_name): pass
pass
+123 -128
View File
@@ -30,6 +30,7 @@
import RNS import RNS
import os import os
import io
import bz2 import bz2
import math import math
import time import time
@@ -149,7 +150,7 @@ class Resource:
COMPLETE = 0x06 COMPLETE = 0x06
FAILED = 0x07 FAILED = 0x07
CORRUPT = 0x08 CORRUPT = 0x08
REJECTED = 0x00 REJECTED = 0x09
@staticmethod @staticmethod
def reject(advertisement_packet): def reject(advertisement_packet):
@@ -239,7 +240,7 @@ class Resource:
return None return None
except Exception as e: except Exception as e:
RNS.log("Could not decode resource advertisement, dropping resource", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None RNS.log(f"Could not decode resource advertisement, dropping resource: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return None return None
# Create a resource for transmission to a remote destination # Create a resource for transmission to a remote destination
@@ -280,6 +281,19 @@ class Resource:
if hasattr(data, "read"): if hasattr(data, "read"):
if data_size == None: data_size = os.stat(data.name).st_size 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 self.total_size = data_size + self.metadata_size
if self.total_size <= Resource.MAX_EFFICIENT_SIZE: if self.total_size <= Resource.MAX_EFFICIENT_SIZE:
@@ -290,12 +304,6 @@ class Resource:
data.close() data.close()
else: 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.total_segments = ((self.total_size-1)//Resource.MAX_EFFICIENT_SIZE)+1
self.segment_index = segment_index self.segment_index = segment_index
self.split = True self.split = True
@@ -314,30 +322,26 @@ class Resource:
self.input_file = data self.input_file = data
elif isinstance(data, bytes): elif isinstance(data, bytes):
data_size = len(data) data_size = len(data)
self.total_size = data_size + self.metadata_size self.total_size = data_size + self.metadata_size
resource_data = data resource_data = data
self.total_segments = 1 self.total_segments = 1
self.segment_index = 1 self.segment_index = 1
self.split = False self.split = False
elif data == None: elif data == None: pass
pass
else: else: raise TypeError("Invalid data instance type passed to resource initialisation")
raise TypeError("Invalid data instance type passed to resource initialisation")
if resource_data: if resource_data:
if self.has_metadata: data = self.metadata + resource_data if self.has_metadata: data = self.metadata + resource_data
else: data = resource_data else: data = resource_data
self.status = Resource.NONE self.status = Resource.NONE
self.link = link self.link = link
if self.link.mtu: if self.link.mtu: self.sdu = self.link.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE
self.sdu = self.link.mtu - RNS.Reticulum.HEADER_MAXSIZE - RNS.Reticulum.IFAC_MIN_SIZE else: self.sdu = link.mdu or Resource.SDU
else:
self.sdu = link.mdu or Resource.SDU
self.max_retries = Resource.MAX_RETRIES self.max_retries = Resource.MAX_RETRIES
self.max_adv_retries = Resource.MAX_ADV_RETRIES self.max_adv_retries = Resource.MAX_ADV_RETRIES
self.retries_left = self.max_retries self.retries_left = self.max_retries
@@ -376,10 +380,8 @@ class Resource:
self.req_hashlist = [] self.req_hashlist = []
self.receiver_min_consecutive_height = 0 self.receiver_min_consecutive_height = 0
if timeout != None: if timeout != None: self.timeout = timeout
self.timeout = timeout else: self.timeout = self.link.rtt * self.link.traffic_timeout_factor
else:
self.timeout = self.link.rtt * self.link.traffic_timeout_factor
if data != None: if data != None:
self.initiator = True self.initiator = True
@@ -388,18 +390,21 @@ class Resource:
compression_began = time.time() compression_began = time.time()
if self.auto_compress and data_size <= self.auto_compress_limit: if self.auto_compress and data_size <= self.auto_compress_limit:
RNS.log("Compressing resource data...", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None RNS.log("Compressing resource data...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.compressed_data = bz2.compress(self.uncompressed_data) try:
RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None self.compressed_data = bz2.compress(self.uncompressed_data)
else: RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.compressed_data = self.uncompressed_data 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.uncompressed_size = len(self.uncompressed_data)
self.compressed_size = len(self.compressed_data) self.compressed_size = len(self.compressed_data)
if (self.compressed_size < self.uncompressed_size and auto_compress): if (self.compressed_size < self.uncompressed_size and auto_compress):
saved_bytes = len(self.uncompressed_data) - len(self.compressed_data) saved_bytes = len(self.uncompressed_data) - len(self.compressed_data)
RNS.log("Compression saved "+str(saved_bytes)+" bytes, sending compressed", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None 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 = b""
self.data += RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE] self.data += RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE]
@@ -451,8 +456,8 @@ class Resource:
self.hashmap = b"" self.hashmap = b""
collision_guard_list = [] collision_guard_list = []
for i in range(0,hashmap_entries): for i in range(0,hashmap_entries):
data = self.data[i*self.sdu:(i+1)*self.sdu] part_data = self.data[i*self.sdu:(i+1)*self.sdu]
map_hash = self.get_map_hash(data) map_hash = self.get_map_hash(part_data)
if map_hash in collision_guard_list: if map_hash in collision_guard_list:
RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
@@ -464,7 +469,7 @@ class Resource:
if len(collision_guard_list) > ResourceAdvertisement.COLLISION_GUARD_SIZE: if len(collision_guard_list) > ResourceAdvertisement.COLLISION_GUARD_SIZE:
collision_guard_list.pop(0) collision_guard_list.pop(0)
part = RNS.Packet(link, data, context=RNS.Packet.RESOURCE) part = RNS.Packet(link, part_data, context=RNS.Packet.RESOURCE)
part.pack() part.pack()
part.map_hash = map_hash part.map_hash = map_hash
@@ -482,12 +487,12 @@ class Resource:
def hashmap_update_packet(self, plaintext): def hashmap_update_packet(self, plaintext):
if not self.status == Resource.FAILED: if not self.status == Resource.FAILED:
self.last_activity = time.time() if self.waiting_for_hmu:
self.retries_left = self.max_retries self.last_activity = time.time()
self.retries_left = self.max_retries
update = umsgpack.unpackb(plaintext[RNS.Identity.HASHLENGTH//8:])
self.hashmap_update(update[0], update[1])
update = umsgpack.unpackb(plaintext[RNS.Identity.HASHLENGTH//8:])
self.hashmap_update(update[0], update[1])
def hashmap_update(self, segment, hashmap): def hashmap_update(self, segment, hashmap):
if not self.status == Resource.FAILED: if not self.status == Resource.FAILED:
@@ -495,12 +500,16 @@ class Resource:
seg_len = ResourceAdvertisement.HASHMAP_MAX_LEN seg_len = ResourceAdvertisement.HASHMAP_MAX_LEN
hashes = len(hashmap)//Resource.MAPHASH_LEN hashes = len(hashmap)//Resource.MAPHASH_LEN
for i in range(0,hashes): for i in range(0,hashes):
if self.hashmap[i+segment*seg_len] == None: if self.hashmap[i+segment*seg_len] == None: self.hashmap_height += 1
self.hashmap_height += 1
self.hashmap[i+segment*seg_len] = hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN] self.hashmap[i+segment*seg_len] = hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
self.waiting_for_hmu = False if hashes < 1:
self.request_next() RNS.log("Invalid HMU received, cancelling transfer", RNS.LOG_ERROR)
self.cancel()
else:
self.waiting_for_hmu = False
self.request_next()
def get_map_hash(self, data): def get_map_hash(self, data):
return RNS.Identity.full_hash(data+self.random_hash)[:Resource.MAPHASH_LEN] return RNS.Identity.full_hash(data+self.random_hash)[:Resource.MAPHASH_LEN]
@@ -517,6 +526,14 @@ class Resource:
prepare_thread = threading.Thread(target=self.__prepare_next_segment, daemon=True) prepare_thread = threading.Thread(target=self.__prepare_next_segment, daemon=True)
prepare_thread.start() prepare_thread.start()
def ensure_link(self):
if not self.link or self.link.status != RNS.Link.ACTIVE:
RNS.log(f"Invalid link state for {self}, aborting transfer", RNS.LOG_VERBOSE)
try: self.cancel()
except Exception as e: RNS.log(f"Error while cancelling resource on link-state abort: {e}", RNS.LOG_ERROR)
return False
else: return True
def __advertise_job(self): def __advertise_job(self):
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV) self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
while not self.link.ready_for_new_resource(): while not self.link.ready_for_new_resource():
@@ -524,6 +541,7 @@ class Resource:
sleep(0.25) sleep(0.25)
try: try:
if not self.ensure_link(): return
self.advertisement_packet.send() self.advertisement_packet.send()
self.last_activity = time.time() self.last_activity = time.time()
self.started_transferring = self.last_activity self.started_transferring = self.last_activity
@@ -541,18 +559,13 @@ class Resource:
self.watchdog_job() self.watchdog_job()
def update_eifr(self): def update_eifr(self):
if self.rtt == None: if self.rtt == None: rtt = self.link.rtt
rtt = self.link.rtt else: rtt = self.rtt
else:
rtt = self.rtt
if self.req_data_rtt_rate != 0: if self.req_data_rtt_rate != 0: expected_inflight_rate = self.req_data_rtt_rate*8
expected_inflight_rate = self.req_data_rtt_rate*8
else: else:
if self.previous_eifr != None: if self.previous_eifr != None: expected_inflight_rate = self.previous_eifr
expected_inflight_rate = self.previous_eifr else: expected_inflight_rate = self.link.establishment_cost*8 / rtt
else:
expected_inflight_rate = self.link.establishment_cost*8 / rtt
self.eifr = expected_inflight_rate self.eifr = expected_inflight_rate
if self.link: self.link.expected_rate = self.eifr if self.link: self.link.expected_rate = self.eifr
@@ -566,8 +579,7 @@ class Resource:
this_job_id = self.__watchdog_job_id this_job_id = self.__watchdog_job_id
while self.status < Resource.ASSEMBLING and this_job_id == self.__watchdog_job_id: while self.status < Resource.ASSEMBLING and this_job_id == self.__watchdog_job_id:
while self.watchdog_lock: while self.watchdog_lock: sleep(0.025)
sleep(0.025)
sleep_time = None sleep_time = None
if self.status == Resource.ADVERTISED: if self.status == Resource.ADVERTISED:
@@ -581,6 +593,7 @@ class Resource:
try: try:
RNS.log("No part requests received, retrying resource advertisement...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None RNS.log("No part requests received, retrying resource advertisement...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.retries_left -= 1 self.retries_left -= 1
if not self.ensure_link(): return
self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV) self.advertisement_packet = RNS.Packet(self.link, ResourceAdvertisement(self).pack(), context=RNS.Packet.RESOURCE_ADV)
self.advertisement_packet.send() self.advertisement_packet.send()
self.last_activity = time.time() self.last_activity = time.time()
@@ -657,13 +670,13 @@ class Resource:
self.last_part_sent = time.time() self.last_part_sent = time.time()
sleep_time = 0.001 sleep_time = 0.001
elif self.status == Resource.REJECTED: elif self.status >= Resource.ASSEMBLING:
sleep_time = 0.001 sleep_time = 0.001
if sleep_time == 0: if sleep_time == 0:
RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
if sleep_time == None or sleep_time < 0: if sleep_time == None or sleep_time < 0:
RNS.log("Timing error, cancelling resource transfer.", RNS.LOG_ERROR) RNS.log(f"Timing error ({sleep_time}/{self.status}), cancelling resource transfer.", RNS.LOG_ERROR)
self.cancel() self.cancel()
if sleep_time != None: if sleep_time != None:
@@ -754,6 +767,7 @@ class Resource:
try: try:
proof = RNS.Identity.full_hash(self.data+self.hash) proof = RNS.Identity.full_hash(self.data+self.hash)
proof_data = self.hash+proof proof_data = self.hash+proof
if not self.ensure_link(): return
proof_packet = RNS.Packet(self.link, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.RESOURCE_PRF) proof_packet = RNS.Packet(self.link, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.RESOURCE_PRF)
proof_packet.send() proof_packet.send()
RNS.Transport.cache(proof_packet, force_cache=True) RNS.Transport.cache(proof_packet, force_cache=True)
@@ -776,8 +790,8 @@ class Resource:
advertise = False, advertise = False,
auto_compress = self.auto_compress_option, auto_compress = self.auto_compress_option,
sent_metadata_size = self.metadata_size) sent_metadata_size = self.metadata_size)
if self.__progress_callback:
self.next_segment.progress_callback(self.__progress_callback) if self.__progress_callback: self.next_segment.progress_callback(self.__progress_callback)
def validate_proof(self, proof_data): def validate_proof(self, proof_data):
if not self.status == Resource.FAILED: if not self.status == Resource.FAILED:
@@ -860,9 +874,9 @@ class Resource:
part_data = packet.data part_data = packet.data
part_hash = self.get_map_hash(part_data) part_hash = self.get_map_hash(part_data)
consecutive_index = self.consecutive_completed_height if self.consecutive_completed_height >= 0 else 0 search_start = self.consecutive_completed_height+1
i = consecutive_index i = search_start
for map_hash in self.hashmap[consecutive_index:consecutive_index+self.window]: for map_hash in self.hashmap[search_start:search_start+self.window]:
if map_hash == part_hash: if map_hash == part_hash:
if self.parts[i] == None: if self.parts[i] == None:
@@ -873,9 +887,6 @@ class Resource:
self.outstanding_parts -= 1 self.outstanding_parts -= 1
# Update consecutive completed pointer # Update consecutive completed pointer
if i == self.consecutive_completed_height + 1:
self.consecutive_completed_height = i
cp = self.consecutive_completed_height + 1 cp = self.consecutive_completed_height + 1
while cp < len(self.parts) and self.parts[cp] != None: while cp < len(self.parts) and self.parts[cp] != None:
self.consecutive_completed_height = cp self.consecutive_completed_height = cp
@@ -966,6 +977,7 @@ class Resource:
request_packet = RNS.Packet(self.link, request_data, context = RNS.Packet.RESOURCE_REQ) request_packet = RNS.Packet(self.link, request_data, context = RNS.Packet.RESOURCE_REQ)
try: try:
if not self.ensure_link(): return
request_packet.send() request_packet.send()
self.last_activity = time.time() self.last_activity = time.time()
self.req_sent = self.last_activity self.req_sent = self.last_activity
@@ -1010,11 +1022,11 @@ class Resource:
for part in requested_parts: for part in requested_parts:
try: try:
if not self.ensure_link(): return
if not part.sent: if not part.sent:
part.send() part.send()
self.sent_parts += 1 self.sent_parts += 1
else: else: part.resend()
part.resend()
self.last_activity = time.time() self.last_activity = time.time()
self.last_part_sent = self.last_activity self.last_part_sent = self.last_activity
@@ -1032,8 +1044,7 @@ class Resource:
search_end = self.receiver_min_consecutive_height+ResourceAdvertisement.COLLISION_GUARD_SIZE search_end = self.receiver_min_consecutive_height+ResourceAdvertisement.COLLISION_GUARD_SIZE
for part in self.parts[search_start:search_end]: for part in self.parts[search_start:search_end]:
part_index += 1 part_index += 1
if part.map_hash == last_map_hash: if part.map_hash == last_map_hash: break
break
self.receiver_min_consecutive_height = max(part_index-1-Resource.WINDOW_MAX, 0) self.receiver_min_consecutive_height = max(part_index-1-Resource.WINDOW_MAX, 0)
@@ -1041,9 +1052,7 @@ class Resource:
RNS.log("Resource sequencing error, cancelling transfer!", RNS.LOG_ERROR) RNS.log("Resource sequencing error, cancelling transfer!", RNS.LOG_ERROR)
self.cancel() self.cancel()
return return
else: else: segment = part_index // ResourceAdvertisement.HASHMAP_MAX_LEN
segment = part_index // ResourceAdvertisement.HASHMAP_MAX_LEN
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
hashmap_end = min((segment+1)*ResourceAdvertisement.HASHMAP_MAX_LEN, len(self.parts)) hashmap_end = min((segment+1)*ResourceAdvertisement.HASHMAP_MAX_LEN, len(self.parts))
@@ -1052,10 +1061,16 @@ class Resource:
for i in range(hashmap_start,hashmap_end): for i in range(hashmap_start,hashmap_end):
hashmap += self.hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN] hashmap += self.hashmap[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
if not hashmap:
RNS.log("Resource HMU error, cancelling transfer!", RNS.LOG_ERROR)
self.cancel()
return
hmu = self.hash+umsgpack.packb([segment, hashmap]) hmu = self.hash+umsgpack.packb([segment, hashmap])
hmu_packet = RNS.Packet(self.link, hmu, context = RNS.Packet.RESOURCE_HMU) hmu_packet = RNS.Packet(self.link, hmu, context = RNS.Packet.RESOURCE_HMU)
try: try:
if not self.ensure_link(): return
hmu_packet.send() hmu_packet.send()
self.last_activity = time.time() self.last_activity = time.time()
except Exception as e: except Exception as e:
@@ -1079,7 +1094,7 @@ class Resource:
if self.next_segment: self.next_segment.cancel() if self.next_segment: self.next_segment.cancel()
if self.status == Resource.CORRUPT: 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.reject(self.advertisement_packet)
self.link.teardown() self.link.teardown()
@@ -1090,11 +1105,15 @@ class Resource:
try: try:
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_ICL) cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_ICL)
cancel_packet.send() cancel_packet.send()
except Exception as e: except Exception as e: RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR) if self in self.link.outgoing_resources: self.link.cancel_outgoing_resource(self)
self.link.cancel_outgoing_resource(self)
else: 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: if self.callback != None:
try: try:
@@ -1107,7 +1126,7 @@ class Resource:
if self.status < Resource.COMPLETE: if self.status < Resource.COMPLETE:
if self.initiator: if self.initiator:
self.status = Resource.REJECTED 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: if self.callback != None:
try: try:
self.link.resource_concluded(self) self.link.resource_concluded(self)
@@ -1228,7 +1247,9 @@ class Resource:
return self.compressed return self.compressed
def __str__(self): 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: class ResourceAdvertisement:
@@ -1241,40 +1262,30 @@ class ResourceAdvertisement:
@staticmethod @staticmethod
def is_request(advertisement_packet): def is_request(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext) adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
if adv.q != None and adv.u: if adv.q != None and adv.u: return True
return True else: return False
else:
return False
@staticmethod @staticmethod
def is_response(advertisement_packet): def is_response(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext) adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
if adv.q != None and adv.p: return True
if adv.q != None and adv.p: else: return False
return True
else:
return False
@staticmethod @staticmethod
def read_request_id(advertisement_packet): def read_request_id(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext) adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
return adv.q return adv.q
@staticmethod @staticmethod
def read_transfer_size(advertisement_packet): def read_transfer_size(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext) adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
return adv.t return adv.t
@staticmethod @staticmethod
def read_size(advertisement_packet): def read_size(advertisement_packet):
adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext) adv = ResourceAdvertisement.unpack(advertisement_packet.plaintext)
return adv.d return adv.d
def __init__(self, resource=None, request_id=None, is_response=False): def __init__(self, resource=None, request_id=None, is_response=False):
self.link = None self.link = None
if resource != None: if resource != None:
@@ -1306,29 +1317,14 @@ class ResourceAdvertisement:
# Flags # Flags
self.f = 0x00 | self.x << 5 | self.p << 4 | self.u << 3 | self.s << 2 | self.c << 1 | self.e self.f = 0x00 | self.x << 5 | self.p << 4 | self.u << 3 | self.s << 2 | self.c << 1 | self.e
def get_transfer_size(self): def get_transfer_size(self): return self.t
return self.t def get_data_size(self): return self.d
def get_parts(self): return self.n
def get_data_size(self): def get_segments(self): return self.l
return self.d def get_hash(self): return self.h
def is_compressed(self): return self.c
def get_parts(self): def has_metadata(self): return self.x
return self.n def get_link(self): return self.link
def get_segments(self):
return self.l
def get_hash(self):
return self.h
def is_compressed(self):
return self.c
def has_metadata(self):
return self.x
def get_link(self):
return self.link
def pack(self, segment=0): def pack(self, segment=0):
hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN hashmap_start = segment*ResourceAdvertisement.HASHMAP_MAX_LEN
@@ -1338,23 +1334,20 @@ class ResourceAdvertisement:
for i in range(hashmap_start,hashmap_end): for i in range(hashmap_start,hashmap_end):
hashmap += self.m[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN] hashmap += self.m[i*Resource.MAPHASH_LEN:(i+1)*Resource.MAPHASH_LEN]
dictionary = { dictionary = { "t": self.t, # Transfer size
"t": self.t, # Transfer size "d": self.d, # Data size
"d": self.d, # Data size "n