rns 1.6.1__0-py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. CRNS/__init__.py +292 -0
  2. RNS/Buffer.py +372 -0
  3. RNS/Channel.py +607 -0
  4. RNS/Cryptography/AES.py +111 -0
  5. RNS/Cryptography/Ed25519.py +70 -0
  6. RNS/Cryptography/HKDF.py +113 -0
  7. RNS/Cryptography/HMAC.py +188 -0
  8. RNS/Cryptography/Hashes.py +70 -0
  9. RNS/Cryptography/PKCS7.py +48 -0
  10. RNS/Cryptography/Provider.py +69 -0
  11. RNS/Cryptography/Proxies.py +120 -0
  12. RNS/Cryptography/SHA256.py +129 -0
  13. RNS/Cryptography/SHA512.py +129 -0
  14. RNS/Cryptography/Token.py +114 -0
  15. RNS/Cryptography/X25519.py +174 -0
  16. RNS/Cryptography/__init__.py +58 -0
  17. RNS/Cryptography/aes/__init__.py +2 -0
  18. RNS/Cryptography/aes/aes128.py +326 -0
  19. RNS/Cryptography/aes/aes256.py +236 -0
  20. RNS/Cryptography/pure25519/__init__.py +0 -0
  21. RNS/Cryptography/pure25519/_ed25519.py +58 -0
  22. RNS/Cryptography/pure25519/basic.py +368 -0
  23. RNS/Cryptography/pure25519/ed25519_oop.py +213 -0
  24. RNS/Cryptography/pure25519/eddsa.py +94 -0
  25. RNS/Destination.py +790 -0
  26. RNS/Discovery.py +1035 -0
  27. RNS/Identity.py +1339 -0
  28. RNS/Interfaces/AX25KISSInterface.py +409 -0
  29. RNS/Interfaces/Android/KISSInterface.py +448 -0
  30. RNS/Interfaces/Android/RNodeInterface.py +2008 -0
  31. RNS/Interfaces/Android/SerialInterface.py +289 -0
  32. RNS/Interfaces/Android/__init__.py +39 -0
  33. RNS/Interfaces/AutoInterface.py +711 -0
  34. RNS/Interfaces/BackboneInterface.py +1147 -0
  35. RNS/Interfaces/I2PInterface.py +972 -0
  36. RNS/Interfaces/Interface.py +517 -0
  37. RNS/Interfaces/KISSInterface.py +395 -0
  38. RNS/Interfaces/LocalInterface.py +491 -0
  39. RNS/Interfaces/PipeInterface.py +206 -0
  40. RNS/Interfaces/RNodeInterface.py +1583 -0
  41. RNS/Interfaces/RNodeMultiInterface.py +1164 -0
  42. RNS/Interfaces/SerialInterface.py +231 -0
  43. RNS/Interfaces/TCPInterface.py +723 -0
  44. RNS/Interfaces/UDPInterface.py +150 -0
  45. RNS/Interfaces/WeaveInterface.py +1096 -0
  46. RNS/Interfaces/__init__.py +42 -0
  47. RNS/Interfaces/util/HDLC.py +115 -0
  48. RNS/Interfaces/util/TransmitBuffer.py +171 -0
  49. RNS/Interfaces/util/__init__.py +9 -0
  50. RNS/Interfaces/util/netinfo.py +325 -0
  51. RNS/Link.py +1594 -0
  52. RNS/Packet.py +600 -0
  53. RNS/Resolver.py +34 -0
  54. RNS/Resource.py +1409 -0
  55. RNS/Reticulum.py +2741 -0
  56. RNS/Stamps.py +1093 -0
  57. RNS/Storage.py +851 -0
  58. RNS/Transport.py +5179 -0
  59. RNS/Utilities/__init__.py +39 -0
  60. RNS/Utilities/rncp.py +911 -0
  61. RNS/Utilities/rngit/__init__.py +41 -0
  62. RNS/Utilities/rngit/client.py +720 -0
  63. RNS/Utilities/rngit/commitsigs.py +324 -0
  64. RNS/Utilities/rngit/highlight.py +412 -0
  65. RNS/Utilities/rngit/main.py +40 -0
  66. RNS/Utilities/rngit/media.py +377 -0
  67. RNS/Utilities/rngit/pages.py +3074 -0
  68. RNS/Utilities/rngit/server.py +5120 -0
  69. RNS/Utilities/rngit/util.py +819 -0
  70. RNS/Utilities/rnid.py +1079 -0
  71. RNS/Utilities/rnir.py +72 -0
  72. RNS/Utilities/rnodeconf.py +4528 -0
  73. RNS/Utilities/rnpath.py +674 -0
  74. RNS/Utilities/rnpkg.py +78 -0
  75. RNS/Utilities/rnprobe.py +252 -0
  76. RNS/Utilities/rnsd.py +695 -0
  77. RNS/Utilities/rnsh/__init__.py +49 -0
  78. RNS/Utilities/rnsh/_version.py +1 -0
  79. RNS/Utilities/rnsh/args.py +94 -0
  80. RNS/Utilities/rnsh/exception.py +58 -0
  81. RNS/Utilities/rnsh/helpers.py +58 -0
  82. RNS/Utilities/rnsh/initiator.py +457 -0
  83. RNS/Utilities/rnsh/listener.py +234 -0
  84. RNS/Utilities/rnsh/loop.py +46 -0
  85. RNS/Utilities/rnsh/process.py +769 -0
  86. RNS/Utilities/rnsh/protocol.py +149 -0
  87. RNS/Utilities/rnsh/retry.py +196 -0
  88. RNS/Utilities/rnsh/rnsh.py +189 -0
  89. RNS/Utilities/rnsh/session.py +445 -0
  90. RNS/Utilities/rnstatus.py +1055 -0
  91. RNS/Utilities/rnx.py +742 -0
  92. RNS/__init__.py +694 -0
  93. RNS/_version.py +1 -0
  94. RNS/vendor/__init__.py +9 -0
  95. RNS/vendor/configobj.py +2474 -0
  96. RNS/vendor/i2plib/__init__.py +25 -0
  97. RNS/vendor/i2plib/__version__.py +8 -0
  98. RNS/vendor/i2plib/aiosam.py +239 -0
  99. RNS/vendor/i2plib/exceptions.py +41 -0
  100. RNS/vendor/i2plib/log.py +5 -0
  101. RNS/vendor/i2plib/sam.py +144 -0
  102. RNS/vendor/i2plib/tunnel.py +225 -0
  103. RNS/vendor/i2plib/utils.py +42 -0
  104. RNS/vendor/platformutils.py +76 -0
  105. RNS/vendor/umsgpack.py +1057 -0
  106. RNS/vendor/validate.py +537 -0
  107. rns-1.6.1.dist-info/METADATA +346 -0
  108. rns-1.6.1.dist-info/RECORD +111 -0
  109. rns-1.6.1.dist-info/WHEEL +5 -0
  110. rns-1.6.1.dist-info/entry_points.txt +15 -0
  111. rns-1.6.1.dist-info/top_level.txt +2 -0
CRNS/__init__.py ADDED
@@ -0,0 +1,292 @@
1
+ compiling = False
2
+ noticed = False
3
+ notice_delay = 0.3
4
+ import os
5
+ import sys
6
+ import time
7
+ import threading
8
+ from importlib.util import find_spec
9
+ if find_spec("pyximport") and find_spec("cython"):
10
+ import json
11
+ import shutil
12
+ import subprocess
13
+ from importlib.abc import MetaPathFinder
14
+ from importlib.machinery import ExtensionFileLoader, SourceFileLoader
15
+ from importlib.machinery import EXTENSION_SUFFIXES
16
+ from importlib.util import spec_from_file_location
17
+ from distutils.extension import Extension
18
+ from pyximport import pyxbuild
19
+
20
+ COMPILE_DIRECTIVES = { "annotation_typing": False }
21
+
22
+ _WORKER_SCRIPT = r"""
23
+ import sys, os, json
24
+ from distutils.extension import Extension
25
+ from pyximport import pyxbuild
26
+ def main():
27
+ tasks_path = sys.argv[1]
28
+ with open(tasks_path, "r") as fh: tasks = json.load(fh)
29
+ results = []
30
+ for task in tasks:
31
+ try:
32
+ os.makedirs(task["scratch"], exist_ok=True)
33
+ extension = Extension(name=task["basename"], sources=[task["source"]])
34
+ extension.cython_directives = task["directives"]
35
+ so_path = pyxbuild.pyx_to_dll(task["source"], ext=extension, build_in_temp=True, pyxbuild_dir=task["scratch"])
36
+ os.makedirs(os.path.dirname(task["target"]), exist_ok=True)
37
+ os.replace(so_path, task["target"])
38
+ results.append({"fullname": task["fullname"], "ok": True, "error": None})
39
+ except Exception as e:
40
+ results.append({"fullname": task["fullname"], "ok": False,
41
+ "error": "{}: {}".format(type(e).__name__, e)})
42
+ with open(tasks_path + ".results", "w") as fh: json.dump(results, fh)
43
+ if __name__ == "__main__": main()
44
+ """
45
+
46
+ def _compile_jobs():
47
+ jobs = os.environ.get("CRNS_JOBS")
48
+ if jobs: return max(1, int(jobs))
49
+ return max(1, min(os.cpu_count() or 1, 16))
50
+
51
+ class _ImportFinder(MetaPathFinder):
52
+
53
+ def __init__(self):
54
+ self.build_dir = os.path.join(os.path.expanduser("~"), ".pyxbld")
55
+ self.mirror_root = os.path.join(self.build_dir, "rnslib")
56
+ self.source_root = self._find_source_root()
57
+ self.abi_suffix = EXTENSION_SUFFIXES[0]
58
+ self.unbuildable = {}
59
+ self.unbuildable_path = os.path.join(self.build_dir, "unbuildable.json")
60
+ self._verify_mirror_directives()
61
+ try:
62
+ with open(self.unbuildable_path, "r") as fh: self.unbuildable = json.load(fh)
63
+ except Exception: self.unbuildable = {}
64
+
65
+ def _verify_mirror_directives(self):
66
+ # If the compiler directives have changed since the mirror was
67
+ # built, the entire mirror is invalidated and rebuilt.
68
+ stamp_path = os.path.join(self.build_dir, "rnslib.stamp")
69
+ directives = json.dumps(COMPILE_DIRECTIVES, sort_keys=True)
70
+ stamp = directives + "\n" + self.abi_suffix
71
+ previous = None
72
+ try:
73
+ with open(stamp_path, "r") as fh: previous = fh.read()
74
+ except Exception: pass
75
+ if previous != stamp:
76
+ shutil.rmtree(self.mirror_root, ignore_errors=True)
77
+ os.makedirs(self.mirror_root, exist_ok=True)
78
+ try:
79
+ os.makedirs(self.build_dir, exist_ok=True)
80
+ with open(stamp_path, "w") as fh: fh.write(stamp)
81
+ except Exception: pass
82
+
83
+ def _save_unbuildable(self):
84
+ try:
85
+ os.makedirs(os.path.dirname(self.unbuildable_path), exist_ok=True)
86
+ with open(self.unbuildable_path, "w") as fh: json.dump(self.unbuildable, fh, indent=1)
87
+ except Exception: pass
88
+
89
+ def _mark_unbuildable(self, fullname, source):
90
+ try:
91
+ self.unbuildable[fullname] = int(os.path.getmtime(source))
92
+ self._save_unbuildable()
93
+ except Exception: pass
94
+
95
+ def _unmark_buildable(self, fullname):
96
+ if fullname in self.unbuildable:
97
+ del self.unbuildable[fullname]
98
+ self._save_unbuildable()
99
+
100
+ def _is_unbuildable(self, fullname, source):
101
+ if fullname not in self.unbuildable: return False
102
+ try:
103
+ if int(os.path.getmtime(source)) == self.unbuildable[fullname]: return True
104
+ except Exception: pass
105
+ self.unbuildable.pop(fullname, None)
106
+ return False
107
+
108
+ def _find_source_root(self):
109
+ here = os.path.dirname(os.path.abspath(__file__))
110
+ candidate = os.path.abspath(os.path.join(here, "..", "RNS", "__init__.py"))
111
+ if os.path.exists(candidate): return os.path.dirname(os.path.dirname(candidate))
112
+ for entry in [os.getcwd()] + list(sys.path):
113
+ if not entry: continue
114
+ candidate = os.path.join(entry, "RNS", "__init__.py")
115
+ if os.path.exists(candidate): return os.path.dirname(candidate)
116
+ raise RuntimeError("CRNS could not locate the RNS source tree")
117
+
118
+ def _all_source_modules(self):
119
+ rns_root = os.path.join(self.source_root, "RNS")
120
+ for root, dirs, files in os.walk(rns_root):
121
+ dirs[:] = [d for d in dirs if d not in ("__pycache__", "i2plib")]
122
+ rel = os.path.relpath(root, self.source_root).replace(os.sep, ".")
123
+ for fn in sorted(files):
124
+ if not fn.endswith(".py"): continue
125
+ if fn == "__init__.py": fullname = rel
126
+ else: fullname = rel + "." + fn[:-3]
127
+ yield fullname
128
+
129
+ def _mirror_target(self, fullname, is_package):
130
+ rel = fullname.split(".")
131
+ basename = rel[-1]
132
+ if is_package: return os.path.join(self.mirror_root, *rel, "__init__" + self.abi_suffix)
133
+ return os.path.join(self.mirror_root, *rel[:-1], basename + self.abi_suffix)
134
+
135
+ def _source(self, fullname):
136
+ rel = fullname.split(".")
137
+ package_source = os.path.join(self.source_root, *rel, "__init__.py")
138
+ if os.path.exists(package_source): return package_source, True
139
+ module_source = os.path.join(self.source_root, *rel) + ".py"
140
+ if os.path.exists(module_source): return module_source, False
141
+ return None, None
142
+
143
+ def _compile(self, fullname, source):
144
+ basename = fullname.rsplit(".", 1)[-1]
145
+ extension = Extension(name=basename, sources=[source])
146
+ extension.cython_directives = COMPILE_DIRECTIVES
147
+ so_path = pyxbuild.pyx_to_dll(source, ext=extension, build_in_temp=True, pyxbuild_dir=self.build_dir)
148
+ abi_suffix = os.path.basename(so_path)[len(basename):]
149
+ return so_path, abi_suffix
150
+
151
+ def _is_current(self, fullname, source, is_package):
152
+ target = self._mirror_target(fullname, is_package)
153
+ if not os.path.exists(target): return False
154
+ try: return os.path.getmtime(target) >= os.path.getmtime(source)
155
+ except Exception: return False
156
+
157
+ def _ensure_compiled(self, fullname, source, is_package):
158
+ target = self._mirror_target(fullname, is_package)
159
+ if os.path.exists(target) and os.path.getmtime(target) >= os.path.getmtime(source): return target
160
+ so_path, abi_suffix = self._compile(fullname, source)
161
+ os.makedirs(os.path.dirname(target), exist_ok=True)
162
+ os.replace(so_path, target)
163
+ return target
164
+
165
+ def precompile(self):
166
+ if not os.path.isdir(self.mirror_root):
167
+ os.makedirs(self.mirror_root, exist_ok=True)
168
+
169
+ pending = []
170
+ for fullname in self._all_source_modules():
171
+ source, is_package = self._source(fullname)
172
+ if source is None:
173
+ continue
174
+ if self._is_current(fullname, source, is_package):
175
+ self._unmark_buildable(fullname)
176
+ continue
177
+ if self._is_unbuildable(fullname, source):
178
+ continue
179
+
180
+ pending.append((fullname, source, is_package))
181
+
182
+ if not pending: return
183
+
184
+ jobs = min(_compile_jobs(), len(pending))
185
+ if jobs > 1:
186
+ # Round-robin assignment spreads the large modules evenly
187
+ # across workers.
188
+ chunks = [[] for _ in range(jobs)]
189
+ for i, item in enumerate(pending): chunks[i % jobs].append(item)
190
+
191
+ workers_dir = os.path.join(self.build_dir, "workers")
192
+ os.makedirs(workers_dir, exist_ok=True)
193
+ procs = []
194
+ for w in range(jobs):
195
+ tasks = []
196
+ for fullname, source, is_package in chunks[w]:
197
+ tasks.append({ "fullname": fullname,
198
+ "basename": fullname.rsplit(".", 1)[-1],
199
+ "source": source,
200
+ "target": self._mirror_target(fullname, is_package),
201
+ "scratch": os.path.join(workers_dir, "w{}".format(w)),
202
+ "directives": COMPILE_DIRECTIVES })
203
+ task_path = os.path.join(workers_dir, "tasks{}.json".format(w))
204
+ with open(task_path, "w") as fh: json.dump(tasks, fh)
205
+ procs.append((w, task_path, subprocess.Popen([sys.executable, "-c", _WORKER_SCRIPT, task_path],
206
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)))
207
+
208
+ for w, task_path, proc in procs:
209
+ stdout, stderr = proc.communicate()
210
+ if proc.returncode != 0:
211
+ for fullname, _, _ in chunks[w]:
212
+ source, _ = self._source(fullname)
213
+ self._mark_unbuildable(fullname, source)
214
+ print(f"CRNS: compile worker failed for {fullname}, using interpreted module", file=sys.stderr)
215
+ if stderr:
216
+ tail = stderr.decode(errors="replace").strip().splitlines()[-5:]
217
+ print("CRNS: worker output:\n" + "\n".join(tail), file=sys.stderr)
218
+ continue
219
+
220
+ results = {}
221
+ try:
222
+ with open(task_path + ".results", "r") as fh:
223
+ for entry in json.load(fh): results[entry["fullname"]] = entry
224
+ except Exception: results = {}
225
+
226
+ for fullname, _, _ in chunks[w]:
227
+ entry = results.get(fullname)
228
+ if entry is not None and entry.get("ok"): self._unmark_buildable(fullname)
229
+ else:
230
+ error = "" if entry is None else entry.get("error", "")
231
+ source, _ = self._source(fullname)
232
+ self._mark_unbuildable(fullname, source)
233
+ print(f"Could not compile {fullname}, using interpreted module: {error}", file=sys.stderr)
234
+ else:
235
+ for fullname, source, is_package in pending:
236
+ try:
237
+ self._ensure_compiled(fullname, source, is_package)
238
+ self._unmark_buildable(fullname)
239
+ except Exception as e:
240
+ self._mark_unbuildable(fullname, source)
241
+ print(f"Could not compile {fullname}, using interpreted module: {e}", file=sys.stderr)
242
+
243
+ def _spec(self, fullname, source, is_package, compile_attempted):
244
+ if fullname == "RNS.vendor.i2plib" or fullname.startswith("RNS.vendor.i2plib."):
245
+ rel = fullname.split(".")
246
+ locations = [os.path.join(self.source_root, *rel)] if is_package else None
247
+ return spec_from_file_location(fullname, source, loader=SourceFileLoader(fullname, source), submodule_search_locations=locations)
248
+
249
+ if compile_attempted:
250
+ try:
251
+ target = self._ensure_compiled(fullname, source, is_package)
252
+ self._unmark_buildable(fullname)
253
+ if is_package: locations = [os.path.dirname(target)]
254
+ else: locations = None
255
+ return spec_from_file_location(fullname, target, loader=ExtensionFileLoader(fullname, target),
256
+ submodule_search_locations=locations)
257
+ except Exception as e:
258
+ self._mark_unbuildable(fullname, source)
259
+ print(f"Could not compile {fullname}, using interpreted module: {e}", file=sys.stderr)
260
+
261
+ rel = fullname.split(".")
262
+ locations = [os.path.join(self.source_root, *rel)] if is_package else None
263
+ return spec_from_file_location(fullname, source,loader=SourceFileLoader(fullname, source),submodule_search_locations=locations)
264
+
265
+ def find_spec(self, fullname, path, target=None):
266
+ if not isinstance(fullname, str): return None
267
+ if not (fullname == "RNS" or fullname.startswith("RNS.")): return None
268
+
269
+ source, is_package = self._source(fullname)
270
+ if source is None: return None
271
+
272
+ return self._spec(fullname, source, is_package, compile_attempted=not self._is_unbuildable(fullname, source))
273
+
274
+ _importfinder = _ImportFinder()
275
+ sys.meta_path.insert(0, _importfinder)
276
+
277
+ def notice_job():
278
+ global noticed
279
+ started = time.time()
280
+ while compiling:
281
+ if time.time() > started+notice_delay and compiling:
282
+ noticed = True
283
+ print("Compiling RNS object code...")
284
+ sys.stdout.flush()
285
+ break
286
+ time.sleep(0.1)
287
+
288
+ compiling = True
289
+ threading.Thread(target=notice_job, daemon=True).start()
290
+ _importfinder.precompile()
291
+ import RNS; compiling = False
292
+ if noticed: print("Compilation done"); sys.stdout.flush()
RNS/Buffer.py ADDED
@@ -0,0 +1,372 @@
1
+ # Reticulum License
2
+ #
3
+ # Copyright (c) 2016-2026 Mark Qvist
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # - The Software shall not be used in any kind of system which includes amongst
13
+ # its functions the ability to purposefully do harm to human beings.
14
+ #
15
+ # - The Software shall not be used, directly or indirectly, in the creation of
16
+ # an artificial intelligence, machine learning or language model training
17
+ # dataset, including but not limited to any use that contributes to the
18
+ # training or development of such a model or algorithm.
19
+ #
20
+ # - The above copyright notice and this permission notice shall be included in
21
+ # all copies or substantial portions of the Software.
22
+ #
23
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ # SOFTWARE.
30
+
31
+ from __future__ import annotations
32
+ import bz2
33
+ import sys
34
+ import time
35
+ import threading
36
+ from threading import RLock
37
+ import struct
38
+ from RNS.Channel import Channel, MessageBase, SystemMessageTypes
39
+ import RNS
40
+ from io import RawIOBase, BufferedRWPair, BufferedReader, BufferedWriter
41
+ from typing import Callable
42
+ from contextlib import AbstractContextManager
43
+
44
+ class StreamDataMessage(MessageBase):
45
+ MSGTYPE = SystemMessageTypes.SMT_STREAM_DATA
46
+ """
47
+ Message type for ``Channel``. ``StreamDataMessage``
48
+ uses a system-reserved message type.
49
+ """
50
+
51
+ STREAM_ID_MAX = 0x3fff # 16383
52
+ """
53
+ The stream id is limited to 2 bytes - 2 bit
54
+ """
55
+
56
+ HEADER_LEN = 2 # 2 for stream data message header
57
+ OVERHEAD = HEADER_LEN + 6 # 6 for channel envelope
58
+ MAX_DATA_LEN = RNS.Link.MDU - OVERHEAD
59
+ """
60
+ When the Buffer package is imported, this value is
61
+ calculcated based on the value of OVERHEAD
62
+ """
63
+
64
+ def __init__(self, stream_id: int = None, data: bytes = None, eof: bool = False, compressed: bool = False):
65
+ """
66
+ This class is used to encapsulate binary stream
67
+ data to be sent over a ``Channel``.
68
+
69
+ :param stream_id: id of stream relative to receiver
70
+ :param data: binary data
71
+ :param eof: set to True if signalling End of File
72
+ """
73
+ super().__init__()
74
+ if stream_id is not None and stream_id > self.STREAM_ID_MAX:
75
+ raise ValueError("stream_id must be 0-16383")
76
+ self.stream_id = stream_id
77
+ self.compressed = compressed
78
+ self.data = data or bytes()
79
+ self.eof = eof
80
+
81
+ def pack(self) -> bytes:
82
+ if self.stream_id is None:
83
+ raise ValueError("stream_id")
84
+
85
+ header_val = (0x3fff & self.stream_id) | (0x8000 if self.eof else 0x0000) | (0x4000 if self.compressed > 0 else 0x0000)
86
+ return bytes(struct.pack(">H", header_val) + (self.data if self.data else bytes()))
87
+
88
+ def unpack(self, raw):
89
+ self.stream_id = struct.unpack(">H", raw[:2])[0]
90
+ self.eof = (0x8000 & self.stream_id) > 0
91
+ self.compressed = (0x4000 & self.stream_id) > 0
92
+ self.stream_id = self.stream_id & 0x3fff
93
+ self.data = raw[2:]
94
+
95
+ if self.compressed:
96
+ decompressor = bz2.BZ2Decompressor()
97
+ self.data = decompressor.decompress(self.data, max_length=RawChannelWriter.MAX_CHUNK_LEN)
98
+ if not decompressor.eof: raise IOError("Decompressed buffer chunk exceeds maximum legitimate size")
99
+
100
+
101
+ class RawChannelReader(RawIOBase, AbstractContextManager):
102
+ """
103
+ An implementation of RawIOBase that receives
104
+ binary stream data sent over a ``Channel``.
105
+
106
+ This class generally need not be instantiated directly.
107
+ Use :func:`RNS.Buffer.create_reader`,
108
+ :func:`RNS.Buffer.create_writer`, and
109
+ :func:`RNS.Buffer.create_bidirectional_buffer` functions
110
+ to create buffered streams with optional callbacks.
111
+
112
+ For additional information on the API of this
113
+ object, see the Python documentation for
114
+ ``RawIOBase``.
115
+ """
116
+ def __init__(self, stream_id: int, channel: Channel):
117
+ """
118
+ Create a raw channel reader.
119
+
120
+ :param stream_id: local stream id to receive at
121
+ :param channel: ``Channel`` object to receive from
122
+ """
123
+ self._stream_id = stream_id
124
+ self._channel = channel
125
+ self._lock = RLock()
126
+ self._buffer = bytearray()
127
+ self._eof = False
128
+ self._channel._register_message_type(StreamDataMessage, is_system_type=True)
129
+ self._channel.add_message_handler(self._handle_message)
130
+ self._listeners: [Callable[[int], None]] = []
131
+
132
+ def add_ready_callback(self, cb: Callable[[int], None]):
133
+ """
134
+ Add a function to be called when new data is available.
135
+ The function should have the signature ``(ready_bytes: int) -> None``
136
+
137
+ :param cb: function to call
138
+ """
139
+ with self._lock:
140
+ self._listeners.append(cb)
141
+
142
+ def remove_ready_callback(self, cb: Callable[[int], None]):
143
+ """
144
+ Remove a function added with :func:`RNS.RawChannelReader.add_ready_callback()`
145
+
146
+ :param cb: function to remove
147
+ """
148
+ with self._lock:
149
+ self._listeners.remove(cb)
150
+
151
+ def _handle_message(self, message: MessageBase):
152
+ if isinstance(message, StreamDataMessage):
153
+ if message.stream_id == self._stream_id:
154
+ with self._lock:
155
+ if message.data is not None:
156
+ self._buffer.extend(message.data)
157
+ if message.eof:
158
+ self._eof = True
159
+ for listener in self._listeners:
160
+ try:
161
+ threading.Thread(target=listener, name="Message Callback", args=[len(self._buffer)], daemon=True).start()
162
+ except Exception as ex:
163
+ RNS.log("Error calling RawChannelReader(" + str(self._stream_id) + ") callback: " + str(ex), RNS.LOG_ERROR)
164
+ return True
165
+ return False
166
+
167
+ def _read(self, __size: int) -> bytes | None:
168
+ with self._lock:
169
+ result = self._buffer[:__size]
170
+ self._buffer = self._buffer[__size:]
171
+ return result if len(result) > 0 or self._eof else None
172
+
173
+ def readinto(self, __buffer: bytearray) -> int | None:
174
+ ready = self._read(len(__buffer))
175
+ if ready is not None:
176
+ __buffer[:len(ready)] = ready
177
+ return len(ready) if ready is not None else None
178
+
179
+ def writable(self) -> bool:
180
+ return False
181
+
182
+ def seekable(self) -> bool:
183
+ return False
184
+
185
+ def readable(self) -> bool:
186
+ return True
187
+
188
+ def close(self):
189
+ with self._lock:
190
+ self._channel.remove_message_handler(self._handle_message)
191
+ self._listeners.clear()
192
+
193
+ def __enter__(self):
194
+ return self
195
+
196
+ def __exit__(self, exc_type, exc_val, exc_tb):
197
+ self.close()
198
+ return False
199
+
200
+
201
+ class RawChannelWriter(RawIOBase, AbstractContextManager):
202
+ """
203
+ An implementation of RawIOBase that receives
204
+ binary stream data sent over a channel.
205
+
206
+ This class generally need not be instantiated directly.
207
+ Use :func:`RNS.Buffer.create_reader`,
208
+ :func:`RNS.Buffer.create_writer`, and
209
+ :func:`RNS.Buffer.create_bidirectional_buffer` functions
210
+ to create buffered streams with optional callbacks.
211
+
212
+ For additional information on the API of this
213
+ object, see the Python documentation for
214
+ ``RawIOBase``.
215
+ """
216
+
217
+ MAX_CHUNK_LEN = 1024*16
218
+ COMPRESSION_TRIES = 4
219
+
220
+ def __init__(self, stream_id: int, channel: Channel):
221
+ """
222
+ Create a raw channel writer.
223
+
224
+ :param stream_id: remote stream id to sent do
225
+ :param channel: ``Channel`` object to send on
226
+ """
227
+ self._stream_id = stream_id
228
+ self._channel = channel
229
+ self._eof = False
230
+ self._mdu = channel.mdu - StreamDataMessage.HEADER_LEN
231
+
232
+ def write(self, __b: bytes) -> int | None:
233
+ try:
234
+ comp_tries = RawChannelWriter.COMPRESSION_TRIES
235
+ comp_try = 1
236
+ comp_success = False
237
+ chunk_len = len(__b)
238
+ if chunk_len > RawChannelWriter.MAX_CHUNK_LEN:
239
+ chunk_len = RawChannelWriter.MAX_CHUNK_LEN
240
+ __b = __b[:RawChannelWriter.MAX_CHUNK_LEN]
241
+ chunk_segment = None
242
+ while chunk_len > 32 and comp_try < comp_tries:
243
+ chunk_segment_length = int(chunk_len/comp_try)
244
+ compressed_chunk = bz2.compress(__b[:chunk_segment_length])
245
+ compressed_length = len(compressed_chunk)
246
+ if compressed_length < self._mdu and compressed_length < chunk_segment_length:
247
+ comp_success = True
248
+ break
249
+ else:
250
+ comp_try += 1
251
+
252
+ if comp_success:
253
+ chunk = compressed_chunk
254
+ processed_length = chunk_segment_length
255
+ else:
256
+ chunk = bytes(__b[:self._mdu])
257
+ processed_length = len(chunk)
258
+
259
+ message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success)
260
+
261
+ self._channel.send(message)
262
+ return processed_length
263
+
264
+ except RNS.Channel.ChannelException as cex:
265
+ if cex.type != RNS.Channel.CEType.ME_LINK_NOT_READY:
266
+ raise
267
+ return 0
268
+
269
+ def close(self):
270
+ try:
271
+ link_rtt = self._channel._outlet.link.rtt
272
+ timeout = time.time() + (link_rtt * len(self._channel._tx_ring) * 1)
273
+ except Exception as e:
274
+ timeout = time.time() + 15
275
+
276
+ while time.time() < timeout and not self._channel.is_ready_to_send():
277
+ time.sleep(0.05)
278
+
279
+ self._eof = True
280
+ self.write(bytes())
281
+
282
+ def __enter__(self):
283
+ return self
284
+
285
+ def __exit__(self, exc_type, exc_val, exc_tb):
286
+ self.close()
287
+ return False
288
+
289
+ def seekable(self) -> bool:
290
+ return False
291
+
292
+ def readable(self) -> bool:
293
+ return False
294
+
295
+ def writable(self) -> bool:
296
+ return True
297
+
298
+ class Buffer:
299
+ """
300
+ Static functions for creating buffered streams that send
301
+ and receive over a ``Channel``.
302
+
303
+ These functions use ``BufferedReader``, ``BufferedWriter``,
304
+ and ``BufferedRWPair`` to add buffering to
305
+ ``RawChannelReader`` and ``RawChannelWriter``.
306
+ """
307
+ @staticmethod
308
+ def create_reader(stream_id: int, channel: Channel,
309
+ ready_callback: Callable[[int], None] | None = None) -> BufferedReader:
310
+ """
311
+ Create a buffered reader that reads binary data sent
312
+ over a ``Channel``, with an optional callback when
313
+ new data is available.
314
+
315
+ Callback signature: ``(ready_bytes: int) -> None``
316
+
317
+ For more information on the reader-specific functions
318
+ of this object, see the Python documentation for
319
+ ``BufferedReader``
320
+
321
+ :param stream_id: the local stream id to receive from
322
+ :param channel: the channel to receive on
323
+ :param ready_callback: function to call when new data is available
324
+ :return: a BufferedReader object
325
+ """
326
+ reader = RawChannelReader(stream_id, channel)
327
+ if ready_callback:
328
+ reader.add_ready_callback(ready_callback)
329
+ return BufferedReader(reader)
330
+
331
+ @staticmethod
332
+ def create_writer(stream_id: int, channel: Channel) -> BufferedWriter:
333
+ """
334
+ Create a buffered writer that writes binary data over
335
+ a ``Channel``.
336
+
337
+ For more information on the writer-specific functions
338
+ of this object, see the Python documentation for
339
+ ``BufferedWriter``
340
+
341
+ :param stream_id: the remote stream id to send to
342
+ :param channel: the channel to send on
343
+ :return: a BufferedWriter object
344
+ """
345
+ writer = RawChannelWriter(stream_id, channel)
346
+ return BufferedWriter(writer)
347
+
348
+ @staticmethod
349
+ def create_bidirectional_buffer(receive_stream_id: int, send_stream_id: int, channel: Channel,
350
+ ready_callback: Callable[[int], None] | None = None) -> BufferedRWPair:
351
+ """
352
+ Create a buffered reader/writer pair that reads and
353
+ writes binary data over a ``Channel``, with an
354
+ optional callback when new data is available.
355
+
356
+ Callback signature: ``(ready_bytes: int) -> None``
357
+
358
+ For more information on the reader-specific functions
359
+ of this object, see the Python documentation for
360
+ ``BufferedRWPair``
361
+
362
+ :param receive_stream_id: the local stream id to receive at
363
+ :param send_stream_id: the remote stream id to send to
364
+ :param channel: the channel to send and receive on
365
+ :param ready_callback: function to call when new data is available
366
+ :return: a BufferedRWPair object
367
+ """
368
+ reader = RawChannelReader(receive_stream_id, channel)
369
+ if ready_callback:
370
+ reader.add_ready_callback(ready_callback)
371
+ writer = RawChannelWriter(send_stream_id, channel)
372
+ return BufferedRWPair(reader, writer)