byond-wire 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wirewraith
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 above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include README.md PROTOCOL.md LICENSE cli.py test_byond_wire.py
2
+ include tests/text-vectors.tsv
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: byond-wire
3
+ Version: 0.1.0
4
+ Summary: Small standard-library BYOND Topic client
5
+ Author: Wirewraith
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Wirewraith/byond-wire
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # BYOND Wire
14
+
15
+ Small, standard-library BYOND Topic client. MIT licensed.
16
+
17
+ Library calls return decoded text, numbers, or null. Raw calls preserve text bytes.
18
+ See [PROTOCOL.md](PROTOCOL.md) for encoding and wire details.
19
+
20
+
21
+ Requires Python 3.9 or later. Install the library and CLI with `python3 -m pip install byond-wire`.
22
+ Ports must be integers from `1` to `65535` (booleans are rejected).
23
+ Timeouts are positive numbers up to `2147483647` seconds;
24
+ invalid values raise `ValueError` before DNS or socket creation.
25
+
26
+ ```sh
27
+ python3 cli.py 127.0.0.1 4999 status
28
+ ```
29
+
30
+ Import the installed module, or copy `byond_wire.py` onto your Python import path:
31
+
32
+ ```python
33
+ from byond_wire import topic, topic_raw
34
+
35
+ response = topic("127.0.0.1", 4999, "status", timeout=5)
36
+ # str, float, or None; failures raise exceptions, including TimeoutError.
37
+ raw = topic_raw("127.0.0.1", 4999, "status") # bytes, float, or None
38
+ ```
39
+
40
+ Run regression tests with `python3 -m unittest discover -s python`.
@@ -0,0 +1,265 @@
1
+ # BYOND Topic protocol: tested implementation reference
2
+
3
+ ## Scope and evidence
4
+
5
+ Verified on **2026-11-04** against the real server at **127.0.0.1:4999**
6
+ specified in [README.md](README.md). It identified itself as Goonstation
7
+ Development, BYOND **516.1688**, through the `?type=version` query.
8
+
9
+ Additional character-encoding tests were performed on **2026-11-09** using an
10
+ isolated Windows Dream Daemon **516.1688** on port **5101**. These are described
11
+ under [Text encoding](#text-encoding); they did not modify the Goonstation server.
12
+
13
+ This reference covers TCP Topic exchanges on those builds. Query names and
14
+ payload fields belong to the tested Goonstation application, not BYOND itself.
15
+
16
+ ## Transport and exchange
17
+
18
+ - Open a TCP connection, send one request, read the complete response, then close.
19
+ - No handshake, login, HTTP request, or TLS was needed on the tested endpoint.
20
+ - Sending the request at once or splitting header/body by 50 ms both worked.
21
+ - Batch small binary requests before writing to TCP. On **2026-11-16**, syscall traces against `goondev.goonhub.com:26900` showed Bash's line-buffered `printf` splitting `?who` into writes of 4 and 10 bytes: its body length `00 0a` contains a newline. Disabling Nagle's algorithm removed the extra latency; `?status` was already a single 17-byte write. The Bash client now stages the request in its existing temporary file and sends it with `cat`. TCP may still segment a complete write.
22
+ - Reading a response one byte at a time worked. Loop until the declared length is complete; a socket read need not return an entire frame.
23
+ - Keep binary data in byte buffers and queries out of executable shell source.
24
+
25
+ ## Request layout
26
+
27
+ Offsets are zero-based. Hexadecimal values below denote actual bytes, not text
28
+ containing escape sequences.
29
+
30
+ | Offset | Size | Bytes / interpretation |
31
+ | --- | --- | --- |
32
+ | 0 | 2 | `00 83`, Topic frame signature |
33
+ | 2 | 2 | Unsigned big-endian body length `L` |
34
+ | 4 | 5 | `00 00 00 00 00`, the tested request prefix |
35
+ | 9 | `N` | Query bytes, including the leading `?` when supplied |
36
+ | `9 + N` | 1 | `00`, query terminator |
37
+
38
+ For this tested construction:
39
+
40
+ ```text
41
+ L = number_of_query_bytes + 6
42
+ request = 00 83 || uint16_be(L) || 00 00 00 00 00 || query_bytes || 00
43
+ total_request_bytes = 4 + L
44
+ ```
45
+
46
+ `L` excludes the four-byte frame header. Count the bytes actually sent, after
47
+ encoding the query. For example, a probe containing UTF-8 `café` had 31 body
48
+ bytes; counting text characters instead produced the incorrect length 30.
49
+ Both variants returned null for the unknown query. This establishes the byte-count
50
+ discrepancy; Unicode handling was checked separately under [Text encoding](#text-encoding).
51
+
52
+ The two-byte request length was checked beyond 255: the query consisting of
53
+ `?protocol_reference=` followed by 280 ASCII `x` bytes produced `L = 306`
54
+ (`01 32`) and received a complete null reply. Swapping the two length bytes to
55
+ `32 01` produced no response within the test's one-second receive timeout.
56
+ Maximum accepted request size was not established.
57
+
58
+ ### Exact request vectors
59
+
60
+ ```text
61
+ ?status, L = 13:
62
+ 00 83 00 0d 00 00 00 00 00 3f 73 74 61 74 75 73 00
63
+
64
+ ?ping, L = 11:
65
+ 00 83 00 0b 00 00 00 00 00 3f 70 69 6e 67 00
66
+
67
+ ?who, L = 10:
68
+ 00 83 00 0a 00 00 00 00 00 3f 77 68 6f 00
69
+
70
+ ?playing, L = 14:
71
+ 00 83 00 0e 00 00 00 00 00 3f 70 6c 61 79 69 6e 67 00
72
+ ```
73
+
74
+ ### Query interpretation observed on this server
75
+
76
+ | Query bytes | Observed result |
77
+ | --- | --- |
78
+ | `?status` | Status text |
79
+ | `status` | Status text; one leading `?` was optional in this test |
80
+ | `??status` | Null |
81
+ | `?%73tatus` | Null; percent-encoding the initial `s` did not select `status` |
82
+ | `?status&protocol_reference=1` | Null; adding a parameter changed the result |
83
+
84
+ Clients add one `?` if absent and preserve it if already present. Do not assume a
85
+ Topic query is always interpreted as an HTTP query string or that arbitrary
86
+ parameters can be appended to a working topic.
87
+
88
+ The five-zero-byte prefix is a verified working construction, not a claim that
89
+ all five bytes are mandatory padding: a separate four-zero-prefix `?status`
90
+ request also returned status. A six-zero-prefix variant returned null. These
91
+ probes did not establish the meanings of individual prefix bytes; use the
92
+ five-zero construction for implementations based on this reference.
93
+
94
+ ## Response layout
95
+
96
+ | Offset | Size | Bytes / interpretation |
97
+ | --- | --- | --- |
98
+ | 0 | 2 | `00 83`, Topic frame signature |
99
+ | 2 | 2 | Unsigned big-endian body length `L` |
100
+ | 4 | 1 | Response type tag |
101
+ | 5 | `L - 1` | Type-specific payload |
102
+
103
+ Read the four-byte header, then exactly `L` body bytes. The type tag is included
104
+ in `L`; the header is excluded. A captured status response began `00 83 01 19`:
105
+ its body contained **281 bytes**, and the full frame contained **285 bytes**.
106
+ This also verifies that response lengths can exceed one byte.
107
+
108
+ ### Observed response types
109
+
110
+ | Tag | Tested interpretation | Observed body length |
111
+ | --- | --- | --- |
112
+ | `00` | Null result, no payload | 1 |
113
+ | `06` | Text bytes followed by one `00` terminator | Text byte count + 2 |
114
+ | `2a` | Little-endian IEEE-754 binary32 numeric payload | 5 |
115
+
116
+ For text, remove the type tag and final NUL only. The text byte count is
117
+ `L - 2`. Empty text and null are distinct observed results. The captured text
118
+ responses contained ASCII bytes. The later controlled tests below establish
119
+ UTF-8 for normal text on the tested build, with an important formatting exception.
120
+
121
+ For numbers, decode the four payload bytes explicitly as little-endian float32,
122
+ independently of the host machine's byte order. Zero and one were verified:
123
+
124
+ ```text
125
+ ?ping with zero players:
126
+ 00 83 00 05 2a 00 00 00 00
127
+ ^ four-byte numeric payload: 0.0
128
+
129
+ ?ping after the user connected a player:
130
+ 00 83 00 05 2a 00 00 80 3f
131
+ ^ four-byte numeric payload: 1.0
132
+ ```
133
+
134
+ The latter payload decoded as little-endian float32 `1.0`; interpreting it as
135
+ big-endian float32 gave approximately `4.600603e-41`. Negative, fractional, and
136
+ special floating-point values were not exercised.
137
+
138
+ Exact empty-text and null vectors:
139
+
140
+ ```text
141
+ ?who with zero players: empty text
142
+ 00 83 00 02 06 00
143
+
144
+ ?playing: null
145
+ 00 83 00 01 00
146
+ ```
147
+
148
+ `?protocol_reference_unknown` also returned the null vector. A null reply is a
149
+ received, complete Topic response, not proof of a transport failure or a
150
+ specific application error.
151
+
152
+ ## Text encoding
153
+
154
+ - Normal text is UTF-8 on the tested modern build. Raw BYOND formatting codes can make the complete payload invalid as strict UTF-8.
155
+ - BYOND switched its internal string representation to UTF-8 in version 513: [release notes](https://www.byond.com/docs/notes/513.html), [feature announcement](https://www.byond.com/forum/post/2580951).
156
+ - The reference project's [protocol notes](https://github.com/NGGJamie/byond-topics/blob/master/documentation/protocol.txt) specify ASCII requests. Its [Python example](https://github.com/NGGJamie/byond-topics/blob/master/python3/example.py) sends Latin-1 and returns raw response bytes; it does not establish the response encoding.
157
+
158
+ ### Controlled wire tests
159
+
160
+ - Tested **2026-11-09** with Windows Dream Maker/Dream Daemon **516.1688**, using an isolated world on port **5101**. The Goonstation server on port **4999** was not modified.
161
+ - Returned `café|€|Ж|漢|🙂` using Unicode escapes and `ascii2text()`. Both produced UTF-8; UTF-8 query echo preserved the same bytes.
162
+ - `list2params()` percent-escaped UTF-8: `é` became `%c3%a9`, consistent with the [DM reference](https://www.byond.com/docs/ref/info.html#/{proc}/list2params).
163
+ - `\proper café` returned `ff 15 63 61 66 c3 a9`; `\improper café` returned `ff 16 63 61 66 c3 a9`. These are text payload bytes, excluding the type tag and final NUL.
164
+ - BYOND's developer [identifies `0xff` as the format-code marker](https://www.byond.com/forum/post/1768158). It is distinct from Unicode `ÿ`, which returned `c3 bf`.
165
+ - Legacy query probes on this Windows build: `e9` became `c3 a9`; `80` became `e2 82 ac`; isolated `ff` survived unchanged. The first two results are consistent with Windows-1252 conversion. Other versions and locales remain untested.
166
+ - The macro inventory covers **101 cases**: standalone controls; expanded articles; pronouns for all four genders; ordinals/plurals at several numbers; icons/references; Roman numerals; escaped punctuation/whitespace; all three Unicode escape forms; and legacy styles/colors.
167
+ - [Source world](tests/text-macros.dme); [captured payloads and synthetic edge cases](tests/text-vectors.tsv), **434 vectors total**. Offline tests consume exact bytes. Live comparisons normalize dynamic object/resource reference numbers only.
168
+ - Reproduce with `python3 tests/capture-text.py`. It compiles temporary files, checks a unique per-run identity, validates all 101 cases, and shuts down its own world.
169
+ - Runtime discovery: native `DreamMaker`/`DreamDaemon` commands or the standard Windows installation under WSL. Overrides: `--compiler`, `--daemon`, `--port` (default `5101`).
170
+
171
+ ### Decoder rules
172
+
173
+ - Remove only the **18 tested two-byte markers** below. Preserve ordinary UTF-8, NUL, newlines, BOM, HTML entities, and markup.
174
+ - Validate each UTF-8 run separately. Reject `c3 ff 15 a9`; removing a marker must not join broken character fragments.
175
+ - Reject unknown marker codes, trailing `ff`, invalid continuation bytes, overlong encodings, surrogates, truncated sequences, and code points beyond U+10FFFF.
176
+ - Shell filters fail with status `1` and empty stdout. Other implementations return or raise decoding errors.
177
+ - Keep raw responses when formatting metadata is required. UTF-8 decoding with marker removal is intentionally lossy for that metadata.
178
+ - Coverage is specific to the tested version and forms; undocumented and future controls are errors until mapped and tested.
179
+
180
+ | Bytes | DM forms | Removed metadata |
181
+ | --- | --- | --- |
182
+ | `ff 06` | `\a`, `\an` without an embedded expression | Article modifier |
183
+ | `ff 07` | `\A`, `\An` without an embedded expression | Article modifier |
184
+ | `ff 08` | `\the` without an embedded expression | Article modifier |
185
+ | `ff 09` | `\The` without an embedded expression | Article modifier |
186
+ | `ff 12` | `\...` | Newline suppression |
187
+ | `ff 15` | `\proper` | Proper-name flag |
188
+ | `ff 16` | `\improper` | Improper-name flag |
189
+ | `ff 17` | `\bold`, `\b` | Style |
190
+ | `ff 18` | `\italic`, `\i` | Style |
191
+ | `ff 19` | `\underline`, `\u` without hexadecimal digits | Style |
192
+ | `ff 1f` | `\red` | Color |
193
+ | `ff 20` | `\green` | Color |
194
+ | `ff 21` | `\blue` | Color |
195
+ | `ff 22` | `\black` | Color |
196
+ | `ff 23` | `\white` | Color |
197
+ | `ff 24` | `\yellow` | Color |
198
+ | `ff 25` | `\cyan` | Color |
199
+ | `ff 26` | `\magenta` | Color |
200
+
201
+ - Expanded articles, pronouns, ordinals, plurals, and Roman numerals were ordinary UTF-8 before transmission. `\icon` became an HTML `IMG` tag; `\ref` became an ASCII reference. The decoder preserves those results.
202
+ - Compiler acceptance alone does not prove a control exists: `\navy`, `\teal`, and `\normal` became newline/tab escapes followed by literal letters. Those bytes are preserved.
203
+
204
+ ## Application payloads observed
205
+
206
+ `?status` returned an ASCII parameter string. A captured response body was
207
+ `06`, followed by the following text, followed by `00`:
208
+
209
+ ```text
210
+ version=Goonstation+13+%28r1%29&host=Wirewraith&gamestate=7&respawn=0&enter=1&round_id=0&ai=1&mode=extended&round_duration=517&shuttle_online=0&shuttle_direction=1&shuttle_location=0&shuttle_timer=360&station_name=Developer+Lounge+%26+Co&map_name=DevTest&map_id=DEVTEST&players=0
211
+ ```
212
+
213
+ For this payload, parsing pairs on `&` and applying form-style decoding produced
214
+ `version = Goonstation 13 (r1)` and
215
+ `station_name = Developer Lounge & Co`. Preserve the raw text at the protocol
216
+ layer; parameter parsing belongs to the caller handling this query.
217
+
218
+ Other verified queries:
219
+
220
+ | Query | Observed text / value |
221
+ | --- | --- |
222
+ | `?ping` | Numeric `0.0`, later `1.0` after a player connected |
223
+ | `?who` | Empty text while there were no players |
224
+ | `?admins` | Text `admins=0` |
225
+ | `?mentors` | Text `mentors=0` |
226
+ | `?type=version` | Text containing `major=516&minor=1688` and server metadata |
227
+ | `?playing` | Null |
228
+
229
+ ## Malformed-request observations
230
+
231
+ These are individual observations, not a general error-message specification.
232
+ In particular, null also occurred for unknown, correctly framed topics.
233
+
234
+ | Change to the canonical `?status` request | Observed result |
235
+ | --- | --- |
236
+ | Declare length 12 but transmit the original 13-byte body | Null |
237
+ | Declare length 14 but transmit the original 13-byte body | No response within the one-second receive timeout |
238
+ | Remove the final NUL and set length to the resulting 12-byte body | Null |
239
+ | Change the five-zero prefix to six zeros and update the length | Null |
240
+
241
+ Earlier live tests sent the original Bash script's backslash-containing arguments
242
+ `status&review=hello\nworld` and `status&review=hello\cworld`. Its `echo -ne`
243
+ converted the former's `5c 6e` into `0a`, and truncated the latter at `\c`.
244
+ The packets declared 33 body bytes but transmitted 32 and 25 respectively.
245
+ Both received this non-Topic response:
246
+
247
+ ```text
248
+ 08 08 28 68 69 74 20 65 6e 74 65 72 20 74 6f 20 63
249
+ 6f 6e 74 69 6e 75 65 2e 29 ff fc 01 ff fd 1f 0d 0a
250
+ ```
251
+
252
+ That capture is not a `00 83` frame. Its readable portion is
253
+ `(hit enter to continue.)`. Do not interpret its third and fourth bytes as a
254
+ Topic length. That original script returned zero with empty output for both exchanges. Current
255
+ clients send queries literally and reject non-Topic responses.
256
+
257
+ ## Limits of this reference
258
+
259
+ The tests establish a working Topic client exchange with this server/build.
260
+ They do not establish other BYOND protocols, authentication, file transfer,
261
+ connection reuse, pipelining, maximum accepted sizes, every Unicode/codepage edge case,
262
+ embedded-NUL semantics, every prefix field's meaning, all error layouts, or
263
+ all numeric values. No universal meaning is assigned to a null application
264
+ result. New implementations should test any additional behavior against a real
265
+ server before extending this reference.
@@ -0,0 +1,28 @@
1
+ # BYOND Wire
2
+
3
+ Small, standard-library BYOND Topic client. MIT licensed.
4
+
5
+ Library calls return decoded text, numbers, or null. Raw calls preserve text bytes.
6
+ See [PROTOCOL.md](PROTOCOL.md) for encoding and wire details.
7
+
8
+
9
+ Requires Python 3.9 or later. Install the library and CLI with `python3 -m pip install byond-wire`.
10
+ Ports must be integers from `1` to `65535` (booleans are rejected).
11
+ Timeouts are positive numbers up to `2147483647` seconds;
12
+ invalid values raise `ValueError` before DNS or socket creation.
13
+
14
+ ```sh
15
+ python3 cli.py 127.0.0.1 4999 status
16
+ ```
17
+
18
+ Import the installed module, or copy `byond_wire.py` onto your Python import path:
19
+
20
+ ```python
21
+ from byond_wire import topic, topic_raw
22
+
23
+ response = topic("127.0.0.1", 4999, "status", timeout=5)
24
+ # str, float, or None; failures raise exceptions, including TimeoutError.
25
+ raw = topic_raw("127.0.0.1", 4999, "status") # bytes, float, or None
26
+ ```
27
+
28
+ Run regression tests with `python3 -m unittest discover -s python`.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: byond-wire
3
+ Version: 0.1.0
4
+ Summary: Small standard-library BYOND Topic client
5
+ Author: Wirewraith
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Wirewraith/byond-wire
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # BYOND Wire
14
+
15
+ Small, standard-library BYOND Topic client. MIT licensed.
16
+
17
+ Library calls return decoded text, numbers, or null. Raw calls preserve text bytes.
18
+ See [PROTOCOL.md](PROTOCOL.md) for encoding and wire details.
19
+
20
+
21
+ Requires Python 3.9 or later. Install the library and CLI with `python3 -m pip install byond-wire`.
22
+ Ports must be integers from `1` to `65535` (booleans are rejected).
23
+ Timeouts are positive numbers up to `2147483647` seconds;
24
+ invalid values raise `ValueError` before DNS or socket creation.
25
+
26
+ ```sh
27
+ python3 cli.py 127.0.0.1 4999 status
28
+ ```
29
+
30
+ Import the installed module, or copy `byond_wire.py` onto your Python import path:
31
+
32
+ ```python
33
+ from byond_wire import topic, topic_raw
34
+
35
+ response = topic("127.0.0.1", 4999, "status", timeout=5)
36
+ # str, float, or None; failures raise exceptions, including TimeoutError.
37
+ raw = topic_raw("127.0.0.1", 4999, "status") # bytes, float, or None
38
+ ```
39
+
40
+ Run regression tests with `python3 -m unittest discover -s python`.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ PROTOCOL.md
4
+ README.md
5
+ byond_wire.py
6
+ cli.py
7
+ pyproject.toml
8
+ test_byond_wire.py
9
+ byond_wire.egg-info/PKG-INFO
10
+ byond_wire.egg-info/SOURCES.txt
11
+ byond_wire.egg-info/dependency_links.txt
12
+ byond_wire.egg-info/entry_points.txt
13
+ byond_wire.egg-info/top_level.txt
14
+ tests/text-vectors.tsv
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ byond-wire = byond_wire:main
@@ -0,0 +1 @@
1
+ byond_wire
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env python3
2
+ """Standard library only. Exit: 0 value, 1 error, 2 null, 124 network timeout."""
3
+ import socket
4
+ import struct
5
+ import sys
6
+ import time
7
+
8
+
9
+ def decode_text(data):
10
+ """Remove tested BYOND markers and strictly decode the UTF-8 runs."""
11
+ if b'\xff' not in data:
12
+ return data.decode('utf-8')
13
+ parts = data.split(b'\xff')
14
+ text = [parts[0].decode('utf-8')]
15
+ for part in parts[1:]:
16
+ if not part or part[0] not in b'\x06\x07\x08\x09\x12\x15\x16\x17\x18\x19\x1f\x20\x21\x22\x23\x24\x25\x26':
17
+ raise ValueError('Unknown or truncated BYOND text marker')
18
+ text.append(part[1:].decode('utf-8'))
19
+ return ''.join(text)
20
+
21
+
22
+ def remaining(deadline):
23
+ seconds = deadline - time.monotonic()
24
+ if seconds <= 0:
25
+ raise TimeoutError('Topic request timed out')
26
+ return seconds
27
+
28
+
29
+ def read_exact(sock, count, deadline):
30
+ chunks = []
31
+ while count:
32
+ sock.settimeout(remaining(deadline))
33
+ chunk = sock.recv(count)
34
+ if not chunk:
35
+ raise EOFError('Incomplete Topic response')
36
+ chunks.append(chunk)
37
+ count -= len(chunk)
38
+ return b''.join(chunks)
39
+
40
+
41
+ def connect(host, port, deadline):
42
+ remaining(deadline)
43
+ error = None
44
+ for family, kind, protocol, _, address in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
45
+ seconds = remaining(deadline)
46
+ sock = None
47
+ try:
48
+ sock = socket.socket(family, kind, protocol)
49
+ sock.settimeout(seconds)
50
+ sock.connect(address)
51
+ return sock
52
+ except BaseException as failure:
53
+ if sock is not None:
54
+ sock.close()
55
+ if not isinstance(failure, OSError):
56
+ raise
57
+ error = failure
58
+ raise error or OSError('Address resolved to no endpoints')
59
+
60
+
61
+ def topic(host, port, query, timeout=5):
62
+ value = topic_raw(host, port, query, timeout)
63
+ return decode_text(value) if isinstance(value, bytes) else value
64
+
65
+
66
+ def topic_raw(host, port, query, timeout=5):
67
+ if not host or type(port) is not int or not 1 <= port <= 65535:
68
+ raise ValueError('Invalid address or port')
69
+ if not isinstance(timeout, (int, float)) or not 0 < timeout <= 2147483647:
70
+ raise ValueError('Timeout must be positive and at most 2147483647 seconds')
71
+ if not query.startswith('?'):
72
+ query = '?' + query
73
+ query_bytes = query.encode('utf-8')
74
+ if b'\0' in query_bytes:
75
+ raise ValueError('Query contains NUL')
76
+ length = len(query_bytes) + 6
77
+ if length > 65535:
78
+ raise ValueError('Query exceeds two-byte frame length')
79
+ request = struct.pack('>HH5x', 0x83, length) + query_bytes + b'\0'
80
+ deadline = time.monotonic() + timeout
81
+ try:
82
+ with connect(host, port, deadline) as sock:
83
+ sock.settimeout(remaining(deadline))
84
+ sock.sendall(request)
85
+ header = read_exact(sock, 4, deadline)
86
+ if header[:2] != b'\0\x83':
87
+ raise ValueError('Non-Topic response')
88
+ length = struct.unpack('>H', header[2:])[0]
89
+ if length == 0:
90
+ raise ValueError('Empty Topic body')
91
+ body = read_exact(sock, length, deadline)
92
+ except socket.timeout as error:
93
+ raise TimeoutError('Topic request timed out') from error
94
+ if body == b'\0':
95
+ return None
96
+ if body[:1] == b'\x06' and len(body) >= 2 and body.endswith(b'\0'):
97
+ return body[1:-1]
98
+ if body[:1] == b'\x2a' and len(body) == 5:
99
+ return struct.unpack('<f', body[1:])[0]
100
+ raise ValueError('Invalid Topic response')
101
+
102
+
103
+ def main():
104
+ try:
105
+ if len(sys.argv) != 4:
106
+ raise ValueError(f'Usage: {sys.argv[0]} <address> <port> <message>')
107
+ result = topic_raw(sys.argv[1], int(sys.argv[2]), sys.argv[3])
108
+ if result is None:
109
+ return 2
110
+ if isinstance(result, bytes):
111
+ sys.stdout.buffer.write(result)
112
+ else:
113
+ sys.stdout.buffer.write(format(result, '.9g').encode('ascii'))
114
+ sys.stdout.buffer.flush()
115
+ return 0
116
+ except TimeoutError:
117
+ print('Topic request timed out', file=sys.stderr)
118
+ return 124
119
+ except (OSError, ValueError, EOFError) as error:
120
+ print(error, file=sys.stderr)
121
+ return 1
122
+
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env python3
2
+ """Command-line wrapper for byond_wire."""
3
+ from byond_wire import main, topic
4
+
5
+ if __name__ == '__main__':
6
+ raise SystemExit(main())
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "byond-wire"
7
+ version = "0.1.0"
8
+ description = "Small standard-library BYOND Topic client"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Wirewraith"}]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/Wirewraith/byond-wire"
17
+
18
+ [project.scripts]
19
+ byond-wire = "byond_wire:main"
20
+
21
+ [tool.setuptools]
22
+ py-modules = ["byond_wire"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+