librats 3.0.5.dev2__py3-none-win_amd64.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.
- librats-3.0.5.dev2.dist-info/METADATA +309 -0
- librats-3.0.5.dev2.dist-info/RECORD +21 -0
- librats-3.0.5.dev2.dist-info/WHEEL +5 -0
- librats-3.0.5.dev2.dist-info/licenses/LICENSE +21 -0
- librats-3.0.5.dev2.dist-info/top_level.txt +1 -0
- librats_py/__init__.py +48 -0
- librats_py/callbacks.py +52 -0
- librats_py/core.py +743 -0
- librats_py/ctypes_wrapper.py +274 -0
- librats_py/enums.py +181 -0
- librats_py/examples/__init__.py +3 -0
- librats_py/examples/basic_client.py +92 -0
- librats_py/examples/file_transfer.py +122 -0
- librats_py/examples/gossipsub_chat.py +125 -0
- librats_py/exceptions.py +85 -0
- librats_py/rats.dll +0 -0
- librats_py/tests/__init__.py +3 -0
- librats_py/tests/conftest.py +31 -0
- librats_py/tests/test_abi_layout.py +90 -0
- librats_py/tests/test_client.py +173 -0
- librats_py/tests/test_integration.py +181 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ctypes declarations for the librats C ABI (``src/librats/bindings/rats.h``).
|
|
3
|
+
|
|
4
|
+
Loads the shared library and declares every struct and function signature.
|
|
5
|
+
Library-owned strings (``rats_local_id``, ``rats_protocol``, the static names)
|
|
6
|
+
are ``const char*`` and declared ``c_char_p``: ctypes copies them, nothing is
|
|
7
|
+
freed. The arrays from ``rats_peer_ids`` / ``rats_observed_addresses`` are
|
|
8
|
+
caller-owned and released with ``rats_strings_free``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
from ctypes import (
|
|
14
|
+
CDLL, POINTER, Structure, c_char, c_char_p, c_double, c_int, c_int64, c_size_t,
|
|
15
|
+
c_uint16, c_uint32, c_uint64, c_void_p,
|
|
16
|
+
)
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
from .callbacks import (
|
|
20
|
+
PeerCallbackType, DisconnectCallbackType, DialFailedCallbackType, MessageCallbackType,
|
|
21
|
+
PathCallbackType, TopicCallbackType, JsonCallbackType,
|
|
22
|
+
FileOfferCallbackType, FileProgressCallbackType, FileCompleteCallbackType,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class LibratsNotFoundError(ImportError):
|
|
27
|
+
"""The librats shared library could not be found or loaded."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RatsConfig(Structure):
|
|
31
|
+
"""``rats_config_t``. Zero in every field is the library default."""
|
|
32
|
+
_fields_ = [
|
|
33
|
+
# identity
|
|
34
|
+
("protocol", c_char_p),
|
|
35
|
+
("data_dir", c_char_p),
|
|
36
|
+
("security", c_int),
|
|
37
|
+
# listening
|
|
38
|
+
("listen_port", c_uint16),
|
|
39
|
+
("bind_address", c_char_p),
|
|
40
|
+
("dial_only", c_int),
|
|
41
|
+
("max_peers", c_size_t),
|
|
42
|
+
# transports
|
|
43
|
+
("transports", c_uint32),
|
|
44
|
+
("preferred_transport", c_int),
|
|
45
|
+
("transport_fallback_ms", c_uint32),
|
|
46
|
+
# sending
|
|
47
|
+
("send_queue_limit", c_size_t),
|
|
48
|
+
("path_sample_ms", c_uint32),
|
|
49
|
+
# UDP transport
|
|
50
|
+
("congestion_control", c_int),
|
|
51
|
+
("udp_receive_window", c_size_t),
|
|
52
|
+
("udp_receive_budget", c_size_t),
|
|
53
|
+
("disable_udp_offload", c_int),
|
|
54
|
+
("udp_idle_timeout_ms", c_uint32),
|
|
55
|
+
# runtime
|
|
56
|
+
("reactor_threads", c_size_t),
|
|
57
|
+
("disable_network_monitor", c_int),
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RatsPeerInfo(Structure):
|
|
62
|
+
"""``rats_peer_info_t``."""
|
|
63
|
+
_fields_ = [
|
|
64
|
+
("transport", c_int),
|
|
65
|
+
("transports", c_uint32),
|
|
66
|
+
("direction", c_int),
|
|
67
|
+
("address", c_char * 64),
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class RatsPathStats(Structure):
|
|
72
|
+
"""``rats_path_stats_t``."""
|
|
73
|
+
_fields_ = [
|
|
74
|
+
("bandwidth_bps", c_uint64),
|
|
75
|
+
("app_limited", c_int),
|
|
76
|
+
("pacing_bps", c_uint64),
|
|
77
|
+
("srtt_us", c_uint32),
|
|
78
|
+
("min_rtt_us", c_uint32),
|
|
79
|
+
("queued_bytes", c_uint64),
|
|
80
|
+
("bytes_in_flight", c_uint64),
|
|
81
|
+
("loss", c_double),
|
|
82
|
+
("bytes_delivered", c_uint64),
|
|
83
|
+
("bytes_lost", c_uint64),
|
|
84
|
+
("live_sent", c_uint64),
|
|
85
|
+
("live_expired", c_uint64),
|
|
86
|
+
("live_repair_bytes", c_uint64),
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class RatsFileProgress(Structure):
|
|
91
|
+
"""``rats_file_progress_t``."""
|
|
92
|
+
_fields_ = [
|
|
93
|
+
("transfer_id", c_uint64),
|
|
94
|
+
("peer_id", c_char_p),
|
|
95
|
+
("direction", c_int),
|
|
96
|
+
("status", c_int),
|
|
97
|
+
("bytes_transferred", c_uint64),
|
|
98
|
+
("total_bytes", c_uint64),
|
|
99
|
+
("files_completed", c_uint32),
|
|
100
|
+
("total_files", c_uint32),
|
|
101
|
+
("rate_bytes_per_sec", c_double),
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class RatsBtConfig(Structure):
|
|
106
|
+
"""``rats_bt_config_t``. Zero in every field is the default."""
|
|
107
|
+
_fields_ = [
|
|
108
|
+
("listen_port", c_uint16),
|
|
109
|
+
("download_path", c_char_p),
|
|
110
|
+
("outgoing_encryption", c_int),
|
|
111
|
+
("incoming_encryption", c_int),
|
|
112
|
+
("disable_outgoing_utp", c_int),
|
|
113
|
+
("disable_incoming_utp", c_int),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# (name, restype, argtypes) of every function in rats.h.
|
|
118
|
+
_N = c_void_p # rats_t
|
|
119
|
+
_S = c_char_p # const char*
|
|
120
|
+
_E = c_int # rats_error_t and the other enums
|
|
121
|
+
_SIGNATURES = [
|
|
122
|
+
("rats_error_str", _S, [_E]),
|
|
123
|
+
("rats_close_reason_str", _S, [_E]),
|
|
124
|
+
# configuration and lifecycle
|
|
125
|
+
("rats_create", _N, [POINTER(RatsConfig)]),
|
|
126
|
+
("rats_destroy", None, [_N]),
|
|
127
|
+
("rats_start", _E, [_N]),
|
|
128
|
+
("rats_stop", None, [_N]),
|
|
129
|
+
# this node
|
|
130
|
+
("rats_local_id", _S, [_N]),
|
|
131
|
+
("rats_protocol", _S, [_N]),
|
|
132
|
+
("rats_listen_port", c_uint16, [_N]),
|
|
133
|
+
("rats_transports", c_uint32, [_N]),
|
|
134
|
+
("rats_nat_mapping", _E, [_N]),
|
|
135
|
+
("rats_observed_addresses", POINTER(c_char_p), [_N, POINTER(c_size_t)]),
|
|
136
|
+
# peers
|
|
137
|
+
("rats_connect", _E, [_N, _S, c_uint16]),
|
|
138
|
+
("rats_disconnect", _E, [_N, _S]),
|
|
139
|
+
("rats_peer_count", c_size_t, [_N]),
|
|
140
|
+
("rats_peer_ids", POINTER(c_char_p), [_N, POINTER(c_size_t)]),
|
|
141
|
+
("rats_peer_info", _E, [_N, _S, POINTER(RatsPeerInfo)]),
|
|
142
|
+
("rats_set_max_peers", None, [_N, c_size_t]),
|
|
143
|
+
("rats_max_peers", c_size_t, [_N]),
|
|
144
|
+
# messaging
|
|
145
|
+
("rats_send", _E, [_N, _S, _S, c_void_p, c_size_t, c_uint32]),
|
|
146
|
+
("rats_broadcast", _E, [_N, _S, c_void_p, c_size_t, c_uint32]),
|
|
147
|
+
("rats_peer_writable", c_int, [_N, _S]),
|
|
148
|
+
("rats_path_stats", _E, [_N, _S, POINTER(RatsPathStats)]),
|
|
149
|
+
# callbacks
|
|
150
|
+
("rats_on_peer_connected", _E, [_N, PeerCallbackType, c_void_p]),
|
|
151
|
+
("rats_on_peer_disconnected", _E, [_N, DisconnectCallbackType, c_void_p]),
|
|
152
|
+
("rats_on_dial_failed", _E, [_N, DialFailedCallbackType, c_void_p]),
|
|
153
|
+
("rats_on_peer_writable", _E, [_N, PeerCallbackType, c_void_p]),
|
|
154
|
+
("rats_on_peer_path", _E, [_N, PathCallbackType, c_void_p]),
|
|
155
|
+
("rats_on", _E, [_N, _S, MessageCallbackType, c_void_p]),
|
|
156
|
+
# discovery
|
|
157
|
+
("rats_enable_dht", _E, [_N, c_uint16, _S]),
|
|
158
|
+
("rats_dht_set_keys", _E, [_N, POINTER(c_char_p), c_size_t]),
|
|
159
|
+
("rats_enable_mdns", _E, [_N]),
|
|
160
|
+
("rats_enable_peer_exchange", _E, [_N]),
|
|
161
|
+
# NAT traversal
|
|
162
|
+
("rats_enable_port_mapping", _E, [_N, c_int, c_int]),
|
|
163
|
+
("rats_enable_hole_punch", _E, [_N, c_int]),
|
|
164
|
+
("rats_punch_peer", _E, [_N, _S]),
|
|
165
|
+
("rats_enable_relay", _E, [_N, c_int]),
|
|
166
|
+
("rats_connect_via_relay", _E, [_N, _S]),
|
|
167
|
+
# pub/sub
|
|
168
|
+
("rats_enable_pubsub", _E, [_N]),
|
|
169
|
+
("rats_subscribe", _E, [_N, _S, TopicCallbackType, c_void_p]),
|
|
170
|
+
("rats_unsubscribe", _E, [_N, _S]),
|
|
171
|
+
("rats_publish", _E, [_N, _S, c_void_p, c_size_t]),
|
|
172
|
+
# JSON messaging
|
|
173
|
+
("rats_enable_json", _E, [_N]),
|
|
174
|
+
("rats_on_json", _E, [_N, _S, JsonCallbackType, c_void_p]),
|
|
175
|
+
("rats_once_json", _E, [_N, _S, JsonCallbackType, c_void_p]),
|
|
176
|
+
("rats_off_json", _E, [_N, _S]),
|
|
177
|
+
("rats_send_json", _E, [_N, _S, _S, _S]),
|
|
178
|
+
("rats_broadcast_json", _E, [_N, _S, _S]),
|
|
179
|
+
# file transfer
|
|
180
|
+
("rats_enable_file_transfer", _E, [_N, _S]),
|
|
181
|
+
("rats_on_file_offer", _E, [_N, FileOfferCallbackType, c_void_p]),
|
|
182
|
+
("rats_on_file_progress", _E, [_N, FileProgressCallbackType, c_void_p]),
|
|
183
|
+
("rats_on_file_complete", _E, [_N, FileCompleteCallbackType, c_void_p]),
|
|
184
|
+
("rats_send_file", _E, [_N, _S, _S, POINTER(c_uint64)]),
|
|
185
|
+
("rats_send_directory", _E, [_N, _S, _S, POINTER(c_uint64)]),
|
|
186
|
+
("rats_accept_file", _E, [_N, _S, c_uint64, _S]),
|
|
187
|
+
("rats_reject_file", _E, [_N, _S, c_uint64]),
|
|
188
|
+
("rats_cancel_file", _E, [_N, _S, c_uint64]),
|
|
189
|
+
("rats_pause_file", _E, [_N, _S, c_uint64]),
|
|
190
|
+
("rats_resume_file", _E, [_N, _S, c_uint64]),
|
|
191
|
+
# ping
|
|
192
|
+
("rats_enable_ping", _E, [_N]),
|
|
193
|
+
("rats_peer_rtt_ms", c_int64, [_N, _S]),
|
|
194
|
+
# reconnection
|
|
195
|
+
("rats_enable_reconnect", _E, [_N]),
|
|
196
|
+
("rats_enable_reconnect_lost", _E, [_N, c_uint32]),
|
|
197
|
+
("rats_add_reconnect", _E, [_N, _S, c_uint16]),
|
|
198
|
+
("rats_remove_reconnect", _E, [_N, _S, c_uint16]),
|
|
199
|
+
# BitTorrent (RATS_ERR_NOT_ENABLED in builds without RATS_SEARCH_FEATURES)
|
|
200
|
+
("rats_enable_bittorrent", _E, [_N, POINTER(RatsBtConfig)]),
|
|
201
|
+
("rats_bt_add_magnet", _E, [_N, _S, _S]),
|
|
202
|
+
("rats_bt_add_torrent_file", _E, [_N, _S, _S]),
|
|
203
|
+
("rats_bt_remove_torrent", _E, [_N, _S]),
|
|
204
|
+
# process-wide
|
|
205
|
+
("rats_set_log_level", None, [_E]),
|
|
206
|
+
("rats_set_log_file", None, [_S]),
|
|
207
|
+
("rats_version_string", _S, []),
|
|
208
|
+
("rats_version", None, [POINTER(c_int)] * 4),
|
|
209
|
+
("rats_git_describe", _S, []),
|
|
210
|
+
("rats_abi", c_uint32, []),
|
|
211
|
+
("rats_strings_free", None, [POINTER(c_char_p), c_size_t]),
|
|
212
|
+
]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def find_librats_library() -> str:
|
|
216
|
+
"""Locate the librats shared library; returns a path or a bare name."""
|
|
217
|
+
system = platform.system().lower()
|
|
218
|
+
if system == 'windows':
|
|
219
|
+
names = ['rats.dll', 'librats.dll']
|
|
220
|
+
elif system == 'darwin':
|
|
221
|
+
names = ['librats.dylib']
|
|
222
|
+
else:
|
|
223
|
+
names = ['librats.so']
|
|
224
|
+
|
|
225
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
226
|
+
root = os.path.join(here, '..', '..')
|
|
227
|
+
search = [here, os.path.join(root, 'build', 'lib'), os.path.join(root, 'build', 'bin'),
|
|
228
|
+
os.path.join(root, 'build')]
|
|
229
|
+
env = os.environ.get('LIBRATS_LIBRARY_PATH')
|
|
230
|
+
if env:
|
|
231
|
+
search[:0] = env.split(os.pathsep)
|
|
232
|
+
|
|
233
|
+
for path in search:
|
|
234
|
+
for name in names:
|
|
235
|
+
candidate = os.path.join(path, name)
|
|
236
|
+
if os.path.isfile(candidate):
|
|
237
|
+
return os.path.abspath(candidate)
|
|
238
|
+
# Leave the rest to the OS loader (PATH, LD_LIBRARY_PATH, system dirs).
|
|
239
|
+
return names[0]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class LibratsCtypes:
|
|
243
|
+
"""The loaded library with every signature declared (``.lib``)."""
|
|
244
|
+
|
|
245
|
+
def __init__(self):
|
|
246
|
+
lib_path = find_librats_library()
|
|
247
|
+
# Since Python 3.8 Windows does not search PATH for a DLL's own
|
|
248
|
+
# dependencies; register the library's directory so ones shipped next to
|
|
249
|
+
# it resolve.
|
|
250
|
+
dll_dir = None
|
|
251
|
+
if os.name == 'nt' and os.path.isabs(lib_path):
|
|
252
|
+
dll_dir = os.add_dll_directory(os.path.dirname(lib_path))
|
|
253
|
+
try:
|
|
254
|
+
self.lib = CDLL(lib_path)
|
|
255
|
+
except OSError as e:
|
|
256
|
+
raise LibratsNotFoundError(f"cannot load the librats library ({lib_path}): {e}") from e
|
|
257
|
+
finally:
|
|
258
|
+
if dll_dir is not None:
|
|
259
|
+
dll_dir.close()
|
|
260
|
+
for name, restype, argtypes in _SIGNATURES:
|
|
261
|
+
fn = getattr(self.lib, name)
|
|
262
|
+
fn.restype = restype
|
|
263
|
+
fn.argtypes = argtypes
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
_librats: Optional[LibratsCtypes] = None
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def get_librats() -> LibratsCtypes:
|
|
270
|
+
"""The process-wide library instance, loaded on first use."""
|
|
271
|
+
global _librats
|
|
272
|
+
if _librats is None:
|
|
273
|
+
_librats = LibratsCtypes()
|
|
274
|
+
return _librats
|
librats_py/enums.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Enumerations, constants and value types of the librats Python bindings.
|
|
3
|
+
|
|
4
|
+
The enums mirror the C ABI (``src/librats/bindings/rats.h``) value for value.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import IntEnum, IntFlag
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RatsError(IntEnum):
|
|
12
|
+
"""``rats_error_t``. ``OK`` is 0; anything else is an error."""
|
|
13
|
+
OK = 0
|
|
14
|
+
INVALID_ARG = 1 # NULL or malformed argument (bad peer id, bad JSON, …)
|
|
15
|
+
NOT_STARTED = 2 # the call needs a started node
|
|
16
|
+
ALREADY_STARTED = 3 # only allowed before start()
|
|
17
|
+
NOT_ENABLED = 4 # the subsystem was not enabled
|
|
18
|
+
NO_SUCH_PEER = 5 # the peer is not connected
|
|
19
|
+
NOT_FOUND = 6 # no such transfer
|
|
20
|
+
DECLINED = 7 # nothing to do or nothing to try with
|
|
21
|
+
BIND = 8 # start() could not open its sockets
|
|
22
|
+
INTERNAL = 9
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Security(IntEnum):
|
|
26
|
+
"""``rats_security_t``."""
|
|
27
|
+
NOISE = 0 # Noise XX: encrypted and authenticated (default)
|
|
28
|
+
PLAINTEXT = 1 # no encryption; ids exchanged in the clear
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Transport(IntEnum):
|
|
32
|
+
"""``rats_transport_t`` — which wire a peer connection runs on.
|
|
33
|
+
|
|
34
|
+
UDP and TCP carry the same protocol under the same encrypted handshake.
|
|
35
|
+
RELAY is only ever reported (see :meth:`RatsNode.peer_info`), never chosen:
|
|
36
|
+
a relay is not something a dial can try.
|
|
37
|
+
"""
|
|
38
|
+
UDP = 0 # the library's own transport on one shared UDP socket
|
|
39
|
+
TCP = 1 # one kernel socket per peer
|
|
40
|
+
RELAY = 2 # carried through another peer's connection
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TransportMask(IntFlag):
|
|
44
|
+
"""Bitmask of transports (``RATS_TRANSPORT_MASK_*``)."""
|
|
45
|
+
NONE = 0
|
|
46
|
+
TCP = 0x1
|
|
47
|
+
UDP = 0x2
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Congestion(IntEnum):
|
|
51
|
+
"""``rats_congestion_t`` — congestion controller of every UDP connection.
|
|
52
|
+
|
|
53
|
+
TCP is the kernel's and ignores it.
|
|
54
|
+
"""
|
|
55
|
+
BBR = 0 # BBRv3 (default): holds its rate through loss that is not congestion
|
|
56
|
+
RENO = 1 # NewReno with HyStart++: backs off on every loss
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Direction(IntEnum):
|
|
60
|
+
"""``rats_direction_t`` — who opened a connection (or who sends a file)."""
|
|
61
|
+
OUTBOUND = 0 # we dialed it / we send
|
|
62
|
+
INBOUND = 1 # it dialed us / we receive
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class CloseReason(IntEnum):
|
|
66
|
+
"""``rats_close_reason_t`` — why a peer connection ended."""
|
|
67
|
+
LOCAL = 0 # we disconnected it
|
|
68
|
+
PEER_CLOSED = 1 # the peer closed cleanly
|
|
69
|
+
PEER_RESET = 2 # connection reset / socket error
|
|
70
|
+
CONNECT_FAILED = 3 # the dial never completed
|
|
71
|
+
HANDSHAKE_FAILED = 4 # secure handshake failed or timed out
|
|
72
|
+
PROTOCOL_ERROR = 5 # malformed frame or decryption failure
|
|
73
|
+
# We kept sending while the peer's queue was already past its limit — the one
|
|
74
|
+
# reason the application causes and can prevent (see RatsNode.peer_writable).
|
|
75
|
+
SLOW_CONSUMER = 6
|
|
76
|
+
SHUTDOWN = 7 # the node is stopping
|
|
77
|
+
DUPLICATE = 8 # replaced by another connection to the same peer
|
|
78
|
+
PEER_LIMIT = 9 # inbound refused: max_peers reached
|
|
79
|
+
IDLE_TIMEOUT = 10 # a UDP connection went silent
|
|
80
|
+
DIAL_SUPERSEDED = 11 # a dial racing over the other transport won
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class NatMapping(IntEnum):
|
|
84
|
+
"""``rats_nat_mapping_t`` — what the mesh has shown about this node's NAT."""
|
|
85
|
+
UNKNOWN = 0 # not enough independent observations yet
|
|
86
|
+
OPEN = 1 # no NAT in the path
|
|
87
|
+
ENDPOINT_INDEPENDENT = 2 # one external port for every peer: punchable
|
|
88
|
+
ENDPOINT_DEPENDENT = 3 # a new mapping per peer (symmetric): not punchable
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class LogLevel(IntEnum):
|
|
92
|
+
"""``rats_log_level_t``."""
|
|
93
|
+
DEBUG = 0
|
|
94
|
+
INFO = 1
|
|
95
|
+
WARN = 2
|
|
96
|
+
ERROR = 3
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class FileTransferStatus(IntEnum):
|
|
100
|
+
"""``rats_file_status_t``."""
|
|
101
|
+
PENDING = 0 # offered, not answered yet
|
|
102
|
+
ACTIVE = 1
|
|
103
|
+
PAUSED = 2
|
|
104
|
+
COMPLETED = 3
|
|
105
|
+
FAILED = 4
|
|
106
|
+
CANCELLED = 5
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class BtEncryption(IntEnum):
|
|
110
|
+
"""``rats_bt_encryption_t`` — BitTorrent MSE/PE policy."""
|
|
111
|
+
ENABLED = 0 # obfuscate first, fall back to plaintext (default)
|
|
112
|
+
FORCED = 1 # obfuscated connections only
|
|
113
|
+
DISABLED = 2 # plaintext only
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# ``transport_fallback_ms`` value that never races the second transport.
|
|
117
|
+
FALLBACK_NEVER = 0xFFFFFFFF
|
|
118
|
+
# Limits of a live message (``lifetime_ms`` > 0). A longer lifetime is cut to
|
|
119
|
+
# the maximum; a larger payload is refused.
|
|
120
|
+
LIVE_MAX_LIFETIME_MS = 30000
|
|
121
|
+
LIVE_MAX_PAYLOAD = 4 * 1024 * 1024
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class PeerInfo:
|
|
126
|
+
"""What the node knows about one connected peer (``rats_peer_info_t``)."""
|
|
127
|
+
transport: Transport # the wire this connection runs on
|
|
128
|
+
transports: TransportMask # what the peer says it accepts; NONE = it did not say
|
|
129
|
+
direction: Direction
|
|
130
|
+
address: str # where it can be dialed, "ip:port"; "" until known
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True)
|
|
134
|
+
class PathStats:
|
|
135
|
+
"""What the transport knows about the path to one peer (``rats_path_stats_t``).
|
|
136
|
+
|
|
137
|
+
For a sender that sizes its output to the path, such as a live encoder.
|
|
138
|
+
Rates are bits per second. A new message waits behind ``queued_bytes``;
|
|
139
|
+
``queued_bytes * 8 / bandwidth_bps`` is that wait in seconds. Over TCP the
|
|
140
|
+
path figures are the kernel's and exist on Linux only; elsewhere, and over a
|
|
141
|
+
relay, only ``queued_bytes`` and the live counters are filled.
|
|
142
|
+
"""
|
|
143
|
+
bandwidth_bps: int # the congestion controller's estimate; 0 = none yet
|
|
144
|
+
app_limited: bool # the sender was not filling the path: the estimate is a floor
|
|
145
|
+
pacing_bps: int # current release rate; 0 = unpaced
|
|
146
|
+
srtt_us: int # smoothed round trip
|
|
147
|
+
min_rtt_us: int # lowest round trip seen: the path without queues
|
|
148
|
+
queued_bytes: int # accepted for the peer, not yet sent
|
|
149
|
+
bytes_in_flight: int # sent, not yet acknowledged
|
|
150
|
+
loss: float # share of bytes lost over the last interval, 0..1
|
|
151
|
+
bytes_delivered: int # acknowledged since the connection opened
|
|
152
|
+
bytes_lost: int # declared lost since the connection opened
|
|
153
|
+
live_sent: int # live messages sent since the connection opened
|
|
154
|
+
live_expired: int # of those, dropped because their lifetime ran out
|
|
155
|
+
live_repair_bytes: int # forward-error-correction bytes sent with live messages
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass(frozen=True)
|
|
159
|
+
class FileProgress:
|
|
160
|
+
"""One progress report of a file transfer (``rats_file_progress_t``)."""
|
|
161
|
+
transfer_id: int
|
|
162
|
+
peer_id: str
|
|
163
|
+
direction: Direction # OUTBOUND = we send, INBOUND = we receive
|
|
164
|
+
status: FileTransferStatus
|
|
165
|
+
bytes_transferred: int
|
|
166
|
+
total_bytes: int
|
|
167
|
+
files_completed: int
|
|
168
|
+
total_files: int
|
|
169
|
+
rate_bytes_per_sec: float # recent, smoothed
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True)
|
|
173
|
+
class VersionInfo:
|
|
174
|
+
"""Library version components."""
|
|
175
|
+
major: int
|
|
176
|
+
minor: int
|
|
177
|
+
patch: int
|
|
178
|
+
build: int
|
|
179
|
+
|
|
180
|
+
def __str__(self) -> str:
|
|
181
|
+
return f"{self.major}.{self.minor}.{self.patch}.{self.build}"
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Basic node: peer events and raw-channel messaging.
|
|
4
|
+
|
|
5
|
+
Everything a node does beyond secure transport is opt-in, and every enable and
|
|
6
|
+
every callback goes in BEFORE start().
|
|
7
|
+
|
|
8
|
+
python basic_client.py <listen_port>
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from librats_py import RatsNode, RatsError, LogLevel, TransportMask, set_log_level
|
|
14
|
+
|
|
15
|
+
CHANNEL = "chat"
|
|
16
|
+
|
|
17
|
+
COMMANDS = """
|
|
18
|
+
commands:
|
|
19
|
+
connect <host> <port> dial a peer
|
|
20
|
+
send <peer_id> <msg> send on the 'chat' channel to one peer
|
|
21
|
+
broadcast <msg> send on 'chat' to every peer
|
|
22
|
+
peers list connected peers, with wire and address
|
|
23
|
+
quit exit
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main() -> None:
|
|
28
|
+
if len(sys.argv) != 2:
|
|
29
|
+
sys.exit("usage: python basic_client.py <listen_port>")
|
|
30
|
+
try:
|
|
31
|
+
listen_port = int(sys.argv[1])
|
|
32
|
+
except ValueError:
|
|
33
|
+
sys.exit("port must be a number")
|
|
34
|
+
|
|
35
|
+
set_log_level(LogLevel.INFO)
|
|
36
|
+
|
|
37
|
+
with RatsNode(listen_port) as node:
|
|
38
|
+
# All of this happens before start().
|
|
39
|
+
node.on_peer_connected(lambda peer: print(f"+ {peer}"))
|
|
40
|
+
node.on_peer_disconnected(lambda peer, why: print(f"- {peer} ({why.name})"))
|
|
41
|
+
node.on_dial_failed(lambda address: print(f"could not reach {address}"))
|
|
42
|
+
|
|
43
|
+
def on_chat(peer_id: str, data: bytes) -> None:
|
|
44
|
+
print(f"\n[{peer_id[:16]}…] {data.decode('utf-8', 'replace')}")
|
|
45
|
+
print("librats> ", end="", flush=True)
|
|
46
|
+
|
|
47
|
+
node.on(CHANNEL, on_chat)
|
|
48
|
+
|
|
49
|
+
node.start()
|
|
50
|
+
print(f"peer id {node.local_id}")
|
|
51
|
+
print(f"listening on {node.listen_port}")
|
|
52
|
+
running = [t for t in ("TCP", "UDP") if node.transports & TransportMask[t]]
|
|
53
|
+
print(f"transports {'+'.join(running) or 'none'}")
|
|
54
|
+
print(COMMANDS)
|
|
55
|
+
|
|
56
|
+
while True:
|
|
57
|
+
try:
|
|
58
|
+
parts = input("librats> ").strip().split()
|
|
59
|
+
except (EOFError, KeyboardInterrupt):
|
|
60
|
+
break
|
|
61
|
+
if not parts:
|
|
62
|
+
continue
|
|
63
|
+
cmd, *args = parts
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
if cmd in ("quit", "exit"):
|
|
67
|
+
break
|
|
68
|
+
elif cmd == "connect" and len(args) == 2:
|
|
69
|
+
node.connect(args[0], int(args[1]))
|
|
70
|
+
print(f"dialing {args[0]}:{args[1]}…")
|
|
71
|
+
elif cmd == "send" and len(args) >= 2:
|
|
72
|
+
node.send(args[0], CHANNEL, " ".join(args[1:]).encode())
|
|
73
|
+
elif cmd == "broadcast" and args:
|
|
74
|
+
node.broadcast(CHANNEL, " ".join(args).encode())
|
|
75
|
+
elif cmd == "peers":
|
|
76
|
+
for peer in node.peer_ids:
|
|
77
|
+
info = node.peer_info(peer)
|
|
78
|
+
if info:
|
|
79
|
+
print(f"{peer} {info.transport.name} {info.direction.name} "
|
|
80
|
+
f"{info.address or '?'}")
|
|
81
|
+
if not node.peer_count:
|
|
82
|
+
print("(none)")
|
|
83
|
+
else:
|
|
84
|
+
print(f"unknown command: {' '.join(parts)}")
|
|
85
|
+
except RatsError as exc:
|
|
86
|
+
print(f"error: {exc}")
|
|
87
|
+
|
|
88
|
+
print("\nstopped")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
main()
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
File transfer example using librats.
|
|
4
|
+
|
|
5
|
+
Demonstrates the push-model file-transfer subsystem: one peer offers a file,
|
|
6
|
+
the other accepts it. The file-transfer subsystem and its callbacks must be
|
|
7
|
+
enabled/registered before ``start()``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from librats_py import RatsNode, RatsError, LogLevel, FileProgress, set_log_level
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FileTransferExample:
|
|
17
|
+
def __init__(self, listen_port: int, download_dir: str):
|
|
18
|
+
self.listen_port = listen_port
|
|
19
|
+
self.download_dir = download_dir
|
|
20
|
+
os.makedirs(download_dir, exist_ok=True)
|
|
21
|
+
|
|
22
|
+
self.node = RatsNode(listen_port)
|
|
23
|
+
|
|
24
|
+
# Register callbacks + enable subsystem BEFORE start().
|
|
25
|
+
self.node.on_peer_connected(lambda pid: print(f"+ Peer connected: {pid}"))
|
|
26
|
+
self.node.on_peer_disconnected(
|
|
27
|
+
lambda pid, why: print(f"- Peer disconnected: {pid} ({why.name})"))
|
|
28
|
+
|
|
29
|
+
self.node.enable_file_transfer(temp_dir=download_dir)
|
|
30
|
+
self.node.on_file_offer(self.on_offer)
|
|
31
|
+
self.node.on_file_progress(self.on_progress)
|
|
32
|
+
self.node.on_file_complete(self.on_complete)
|
|
33
|
+
|
|
34
|
+
def on_offer(self, peer_id, transfer_id, name, size, is_directory):
|
|
35
|
+
kind = "directory" if is_directory else "file"
|
|
36
|
+
print(f"\nIncoming {kind} offer '{name}' ({size} bytes) "
|
|
37
|
+
f"from {peer_id[:16]}… (transfer {transfer_id})")
|
|
38
|
+
dest = os.path.join(self.download_dir, name)
|
|
39
|
+
# Auto-accept for the demo.
|
|
40
|
+
self.node.accept_file(peer_id, transfer_id, dest)
|
|
41
|
+
print(f"Accepted → {dest}")
|
|
42
|
+
|
|
43
|
+
def on_progress(self, p: FileProgress):
|
|
44
|
+
pct = (p.bytes_transferred * 100 // p.total_bytes) if p.total_bytes else 0
|
|
45
|
+
print(f" transfer {p.transfer_id} ({p.direction.name.lower()}): {pct}% "
|
|
46
|
+
f"({p.bytes_transferred}/{p.total_bytes}, {p.rate_bytes_per_sec / 1024:.0f} KiB/s) "
|
|
47
|
+
f"[{p.status.name}]")
|
|
48
|
+
|
|
49
|
+
def on_complete(self, peer_id, transfer_id, success, path):
|
|
50
|
+
state = "completed" if success else "failed"
|
|
51
|
+
print(f"\nTransfer {transfer_id} with {peer_id[:8]} {state}: {path}")
|
|
52
|
+
|
|
53
|
+
def start(self):
|
|
54
|
+
self.node.start()
|
|
55
|
+
print(f"File transfer client on port {self.listen_port}")
|
|
56
|
+
print(f"Local peer id: {self.node.local_id}")
|
|
57
|
+
|
|
58
|
+
def stop(self):
|
|
59
|
+
self.node.stop()
|
|
60
|
+
|
|
61
|
+
def run(self):
|
|
62
|
+
print("\nCommands:")
|
|
63
|
+
print(" connect <host> <port> - dial a peer")
|
|
64
|
+
print(" send <peer_id> <file_path> - offer a file")
|
|
65
|
+
print(" senddir <peer_id> <dir_path> - offer a directory")
|
|
66
|
+
print(" peers - list peers")
|
|
67
|
+
print(" quit - exit")
|
|
68
|
+
print()
|
|
69
|
+
while True:
|
|
70
|
+
try:
|
|
71
|
+
parts = input("file-transfer> ").strip().split()
|
|
72
|
+
except (EOFError, KeyboardInterrupt):
|
|
73
|
+
break
|
|
74
|
+
if not parts:
|
|
75
|
+
continue
|
|
76
|
+
cmd = parts[0].lower()
|
|
77
|
+
try:
|
|
78
|
+
if cmd in ("quit", "exit"):
|
|
79
|
+
break
|
|
80
|
+
elif cmd == "connect" and len(parts) == 3:
|
|
81
|
+
self.node.connect(parts[1], int(parts[2]))
|
|
82
|
+
print(f"Dialing {parts[1]}:{parts[2]}…")
|
|
83
|
+
elif cmd == "send" and len(parts) == 3:
|
|
84
|
+
if not os.path.exists(parts[2]):
|
|
85
|
+
print("File not found.")
|
|
86
|
+
continue
|
|
87
|
+
tid = self.node.send_file(parts[1], parts[2])
|
|
88
|
+
print(f"Offered file (transfer {tid})")
|
|
89
|
+
elif cmd == "senddir" and len(parts) == 3:
|
|
90
|
+
tid = self.node.send_directory(parts[1], parts[2])
|
|
91
|
+
print(f"Offered directory (transfer {tid})")
|
|
92
|
+
elif cmd == "peers":
|
|
93
|
+
for pid in self.node.peer_ids:
|
|
94
|
+
print(f" - {pid}")
|
|
95
|
+
else:
|
|
96
|
+
print("Unknown/invalid command.")
|
|
97
|
+
except RatsError as e:
|
|
98
|
+
print(f"Error: {e}")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main():
|
|
102
|
+
if len(sys.argv) < 2:
|
|
103
|
+
print("Usage: python file_transfer.py <listen_port> [download_dir]")
|
|
104
|
+
sys.exit(1)
|
|
105
|
+
try:
|
|
106
|
+
listen_port = int(sys.argv[1])
|
|
107
|
+
except ValueError:
|
|
108
|
+
print("Error: Port must be a number")
|
|
109
|
+
sys.exit(1)
|
|
110
|
+
download_dir = sys.argv[2] if len(sys.argv) > 2 else "./downloads"
|
|
111
|
+
|
|
112
|
+
set_log_level(LogLevel.INFO)
|
|
113
|
+
example = FileTransferExample(listen_port, download_dir)
|
|
114
|
+
try:
|
|
115
|
+
example.start()
|
|
116
|
+
example.run()
|
|
117
|
+
finally:
|
|
118
|
+
example.stop()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
main()
|