ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
networking.cpp
Go to the documentation of this file.
1#include <emscripten/bind.h>
2extern "C" {
6}
7#include "../common/opts.h"
8#include "byte_arrays.h"
9#include "client_bytes.h"
10#include <ascii-chat/common.h>
15#include <sodium.h>
16#include <array>
17#include <cstddef>
18#include <cstdint>
19#include <string>
20#include <optional>
21#include <vector>
22
24public:
25 static int errorAction(int code) {
26 return static_cast<int>(network_error_action(static_cast<asciichat_error_t>(code)));
27 }
28 explicit ClientSessionBinding(OptionsPatch options) {
29 transport_.reset(browser_transport_create());
30 if (transport_) {
31 result_ = browser_client_init(transport_.get());
32 if (!result_)
33 result_ = initial_options(options);
34 else
35 SET_ERRNO(ERROR_INIT, "Browser client initialization failed");
36 } else {
37 result_ = SET_ERRNO(ERROR_MEMORY, "Browser transport allocation failed");
38 }
39 if (result_ && transport_)
40 browser_client_cleanup(transport_.get());
41 if (!result_) {
42 owned_ = true;
43 }
44 }
50 bool valid() const {
51 return owned_;
52 }
53 emscripten::val protocolInfo() const {
54 emscripten::val info = emscripten::val::object();
55 info.set("protocolVersion", PROTOCOL_VERSION_MAJOR);
56 info.set("protocolMinorVersion", PROTOCOL_VERSION_MINOR);
57 info.set("protocolPatchVersion", PROTOCOL_VERSION_PATCH);
58 info.set("connectionStates", emscripten::val::array());
59 const char *states[] = {"disconnected", "connecting", "handshake", "connected", "error"};
60 for (unsigned index = 0; index < 5; ++index)
61 info["connectionStates"].set(index, states[index]);
62 info.set("cryptoModes", emscripten::val::object());
63 info["cryptoModes"].set("none", ACIP_CRYPTO_NONE);
64 info["cryptoModes"].set("auth", ACIP_CRYPTO_AUTH);
65 info["cryptoModes"].set("encrypt", ACIP_CRYPTO_ENCRYPT);
66 info.set("packetTypes", emscripten::val::object());
67 const std::pair<const char *, packet_type_t> packet_types[] = {
68 {"PROTOCOL_VERSION", PACKET_TYPE_PROTOCOL_VERSION},
69 {"CRYPTO_CLIENT_HELLO", PACKET_TYPE_CRYPTO_CLIENT_HELLO},
70 {"CRYPTO_CAPABILITIES", PACKET_TYPE_CRYPTO_CAPABILITIES},
71 {"CRYPTO_PARAMETERS", PACKET_TYPE_CRYPTO_PARAMETERS},
72 {"CRYPTO_KEY_EXCHANGE_INIT", PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT},
73 {"CRYPTO_KEY_EXCHANGE_RESP", PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP},
74 {"CRYPTO_AUTH_CHALLENGE", PACKET_TYPE_CRYPTO_AUTH_CHALLENGE},
75 {"CRYPTO_AUTH_RESPONSE", PACKET_TYPE_CRYPTO_AUTH_RESPONSE},
76 {"CRYPTO_AUTH_FAILED", PACKET_TYPE_CRYPTO_AUTH_FAILED},
77 {"CRYPTO_SERVER_AUTH_RESP", PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP},
78 {"CRYPTO_HANDSHAKE_COMPLETE", PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE},
79 {"CRYPTO_NO_ENCRYPTION", PACKET_TYPE_CRYPTO_NO_ENCRYPTION},
80 {"QUIC_READY", PACKET_TYPE_QUIC_READY},
81 {"QUIC_KEYFRAME_REQUEST", PACKET_TYPE_QUIC_KEYFRAME_REQUEST},
82 {"CRYPTO_EPOCH_MARKER", PACKET_TYPE_CRYPTO_EPOCH_MARKER},
83 {"CRYPTO_REKEY_NEEDED", PACKET_TYPE_CRYPTO_REKEY_NEEDED},
84 {"CRYPTO_EPOCH_ACK", PACKET_TYPE_CRYPTO_EPOCH_ACK},
85 {"ENCRYPTED", PACKET_TYPE_ENCRYPTED},
86 {"CRYPTO_REKEY_REQUEST", PACKET_TYPE_CRYPTO_REKEY_REQUEST},
87 {"CRYPTO_REKEY_RESPONSE", PACKET_TYPE_CRYPTO_REKEY_RESPONSE},
88 {"CRYPTO_REKEY_COMPLETE", PACKET_TYPE_CRYPTO_REKEY_COMPLETE},
89 {"SIZE_MESSAGE", PACKET_TYPE_SIZE_MESSAGE},
90 {"AUDIO_MESSAGE", PACKET_TYPE_AUDIO_MESSAGE},
91 {"TEXT_MESSAGE", PACKET_TYPE_TEXT_MESSAGE},
92 {"ERROR_MESSAGE", PACKET_TYPE_ERROR_MESSAGE},
93 {"REMOTE_LOG", PACKET_TYPE_REMOTE_LOG},
94 {"ASCII_FRAME", PACKET_TYPE_ASCII_FRAME},
95 {"IMAGE_FRAME", PACKET_TYPE_IMAGE_FRAME},
96 {"IMAGE_FRAME_H265", PACKET_TYPE_IMAGE_FRAME_H265},
97 {"IMAGE_FRAME_H264", PACKET_TYPE_IMAGE_FRAME_H264},
98 {"AUDIO_BATCH", PACKET_TYPE_AUDIO_BATCH},
99 {"AUDIO_OPUS_BATCH", PACKET_TYPE_AUDIO_OPUS_BATCH},
100 {"CLIENT_CAPABILITIES", PACKET_TYPE_CLIENT_CAPABILITIES},
101 {"PING", PACKET_TYPE_PING},
102 {"PONG", PACKET_TYPE_PONG},
103 {"CLIENT_JOIN", PACKET_TYPE_CLIENT_JOIN},
104 {"CLIENT_LEAVE", PACKET_TYPE_CLIENT_LEAVE},
105 {"STREAM_START", PACKET_TYPE_STREAM_START},
106 {"STREAM_STOP", PACKET_TYPE_STREAM_STOP},
107 {"CLEAR_CONSOLE", PACKET_TYPE_CLEAR_CONSOLE},
108 {"SERVER_STATE", PACKET_TYPE_SERVER_STATE},
109 {"ACIP_SESSION_CREATE", PACKET_TYPE_ACIP_SESSION_CREATE},
110 {"ACIP_SESSION_CREATED", PACKET_TYPE_ACIP_SESSION_CREATED},
111 {"ACIP_SESSION_LOOKUP", PACKET_TYPE_ACIP_SESSION_LOOKUP},
112 {"ACIP_SESSION_INFO", PACKET_TYPE_ACIP_SESSION_INFO},
113 {"ACIP_SESSION_JOIN", PACKET_TYPE_ACIP_SESSION_JOIN},
114 {"ACIP_SESSION_JOINED", PACKET_TYPE_ACIP_SESSION_JOINED},
115 {"ACIP_SESSION_LEAVE", PACKET_TYPE_ACIP_SESSION_LEAVE},
116 {"ACIP_SESSION_END", PACKET_TYPE_ACIP_SESSION_END},
117 {"ACIP_SESSION_RECONNECT", PACKET_TYPE_ACIP_SESSION_RECONNECT},
118 {"ACIP_WEBRTC_SDP", PACKET_TYPE_ACIP_WEBRTC_SDP},
119 {"ACIP_WEBRTC_ICE", PACKET_TYPE_ACIP_WEBRTC_ICE},
120 {"ACIP_STRING_RESERVE", PACKET_TYPE_ACIP_STRING_RESERVE},
121 {"ACIP_STRING_RESERVED", PACKET_TYPE_ACIP_STRING_RESERVED},
122 {"ACIP_STRING_RENEW", PACKET_TYPE_ACIP_STRING_RENEW},
123 {"ACIP_STRING_RELEASE", PACKET_TYPE_ACIP_STRING_RELEASE},
124 {"ACIP_PARTICIPANT_LIST", PACKET_TYPE_ACIP_PARTICIPANT_LIST},
125 {"ACIP_RING_COLLECT", PACKET_TYPE_ACIP_RING_COLLECT},
126 {"ACIP_NETWORK_QUALITY", PACKET_TYPE_ACIP_NETWORK_QUALITY},
127 {"ACIP_HOST_ANNOUNCEMENT", PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT},
128 {"ACIP_HOST_DESIGNATED", PACKET_TYPE_ACIP_HOST_DESIGNATED},
129 {"ACIP_SETTINGS_SYNC", PACKET_TYPE_ACIP_SETTINGS_SYNC},
130 {"ACIP_SETTINGS_ACK", PACKET_TYPE_ACIP_SETTINGS_ACK},
131 {"ACIP_HOST_LOST", PACKET_TYPE_ACIP_HOST_LOST},
132 {"ACIP_FUTURE_HOST_ELECTED", PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED},
133 {"ACIP_PARTICIPANT_JOINED", PACKET_TYPE_ACIP_PARTICIPANT_JOINED},
134 {"ACIP_PARTICIPANT_LEFT", PACKET_TYPE_ACIP_PARTICIPANT_LEFT},
135 {"ACIP_BANDWIDTH_TEST", PACKET_TYPE_ACIP_BANDWIDTH_TEST},
136 {"ACIP_BANDWIDTH_RESULT", PACKET_TYPE_ACIP_BANDWIDTH_RESULT},
137 {"ACIP_BROADCAST_ACK", PACKET_TYPE_ACIP_BROADCAST_ACK},
138 {"RING_MEMBERS", PACKET_TYPE_RING_MEMBERS},
139 {"STATS_COLLECTION_START", PACKET_TYPE_STATS_COLLECTION_START},
140 {"STATS_UPDATE", PACKET_TYPE_STATS_UPDATE},
141 {"RING_ELECTION_RESULT", PACKET_TYPE_RING_ELECTION_RESULT},
142 {"STATS_ACK", PACKET_TYPE_STATS_ACK},
143 {"ACIP_DISCOVERY_PING", PACKET_TYPE_ACIP_DISCOVERY_PING},
144 {"ACIP_ERROR", PACKET_TYPE_ACIP_ERROR},
145 };
146 for (const auto &[name, type] : packet_types)
147 info["packetTypes"].set(name, static_cast<unsigned>(type));
148 info.set("browserCapabilities", emscripten::val::object());
149 info["browserCapabilities"].set("datagrams", browser_capabilities_.datagrams);
150 info["browserCapabilities"].set("maxDatagramPayload", browser_capabilities_.max_datagram_payload);
151 return info;
152 }
153 emscripten::val packetTypes() const {
154 return protocolInfo()["packetTypes"];
155 }
156 int error() const {
157 return result_;
158 }
159 emscripten::val snapshot() const {
160 if (!owned_)
161 return result(SET_ERRNO(ERROR_INVALID_STATE, "Client session is not initialized"));
162 emscripten::val response = result(0);
163 response.set("ready", browser_client_ready(transport_.get()));
164 response.set("queuedBytes", browser_transport_queued_bytes(transport_.get()));
165 response.set("acceptedPackets", emscripten::val::global("BigInt")(std::to_string(browser_transport_accepted_packets(transport_.get()))));
166 response.set("droppedPackets", emscripten::val::global("BigInt")(std::to_string(browser_transport_dropped_packets(transport_.get()))));
167 response.set("droppedBytes", emscripten::val::global("BigInt")(std::to_string(browser_transport_dropped_bytes(transport_.get()))));
168 response.set("writable", browser_transport_writable(transport_.get(), 0));
169 return response;
170 }
171 void close() {
172 if (!owned_)
173 return;
174 browser_client_cleanup(transport_.get());
175 owned_ = false;
176 }
177 emscripten::val process(emscripten::val event) {
178 if (!owned_)
179 return result(SET_ERRNO(ERROR_INVALID_STATE, "Client session is not initialized"));
180 const std::string type = event["type"].as<std::string>();
181 if (type == "frame-validate") {
182 const ClientBytes encoded(event["encoded"]);
183 const ClientBytes contract(event["contract"]);
184 const unsigned width = event["width"].as<unsigned>();
185 const unsigned height = event["height"].as<unsigned>();
186 const unsigned checksum = event["checksum"].as<unsigned>();
187 const unsigned flags = event["flags"].as<unsigned>();
188 const unsigned original_size = event["originalSize"].as<unsigned>();
189 const size_t input_size = encoded["length"].as<size_t>();
190 const size_t metadata_size = contract["length"].as<size_t>();
191 const bool compressed = (flags & 2) != 0;
192 emscripten::val response = result(0);
193 if (!input_size || input_size > 16 * 1024 * 1024 || !original_size || original_size > 16 * 1024 * 1024 || metadata_size > 275 || (!compressed && input_size != original_size)) {
194 response.set("code", static_cast<int>(SET_ERRNO(ERROR_INVALID_PARAM, "Invalid encoded frame or metadata size")));
195 response.set("ok", false);
196 response.set("decodeFailed", false);
197 response.set("bytes", binding_copy_output(nullptr, 0));
198 return response;
199 }
200 auto input = binding_copy_input(encoded);
201 auto metadata = binding_copy_input(contract);
202 std::vector<uint8_t> decoded(compressed ? original_size : 0);
203 const uint8_t *text = compressed ? decoded.data() : input.data();
204 int code = compressed ? browser_client_decode_frame_data(input.data(), input.size(), decoded.data(), decoded.size()) : 0;
205 const bool decode_failed = code != 0;
206 if (!code)
207 code = browser_client_validate_frame(transport_.get(), reinterpret_cast<const char *>(text), original_size, width, height, checksum, flags, metadata.empty() ? nullptr : metadata.data(),
208 metadata.size());
209 response.set("code", code);
210 response.set("ok", code == 0);
211 response.set("decodeFailed", decode_failed);
212 response.set("bytes", binding_copy_output(text, code == 0 ? original_size : 0));
213 return response;
214 }
215 if (type == "settings-receive") {
216 auto input = binding_copy_input(event["payload"]);
217 const int code = browser_client_settings_receive(transport_.get(), input.data(), input.size());
218 emscripten::val response = result(code);
219 char *json = code == 0 ? browser_client_settings_values(transport_.get()) : nullptr;
220 response.set("json", json ? emscripten::val(std::string(json)) : emscripten::val::null());
221 if (json)
222 SAFE_FREE(json);
223 return response;
224 }
225 if (type == "settings-values") {
226 emscripten::val response = result(0);
227 char *json = browser_client_settings_values(transport_.get());
228 response.set("json", json ? emscripten::val(std::string(json)) : emscripten::val::null());
229 if (json)
230 SAFE_FREE(json);
231 return response;
232 }
233 if (type == "begin-handshake") {
234 const bool discovery = !event["discovery"].isUndefined() && event["discovery"].as<bool>();
235 const int code =
236 discovery ? static_cast<int>(browser_client_acds_handshake_begin(transport_.get(), event["mode"].as<uint8_t>())) : static_cast<int>(browser_client_handshake_begin(transport_.get()));
237 return code ? result(code) : drainOutputs();
238 }
239 if (type == "configure-crypto") {
240 auto pass = binding_copy_input(event["password"]);
241 auto secret = binding_copy_input(event["identity"]);
242 auto key = binding_copy_input(event["expected"]);
243 int code;
244 if ((secret.empty() || secret.size() == 64) && (key.empty() || key.size() == 32)) {
245 pass.push_back(0);
246 code = browser_client_configure_crypto_options(transport_.get(), pass.size() > 1 ? reinterpret_cast<char *>(pass.data()) : nullptr, secret.empty() ? nullptr : secret.data(),
247 key.empty() ? nullptr : key.data());
248 } else {
249 code = SET_ERRNO(ERROR_INVALID_PARAM, "Invalid client identity or verification key length");
250 }
251 if (!pass.empty())
252 sodium_memzero(pass.data(), pass.size());
253 if (!secret.empty())
254 sodium_memzero(secret.data(), secret.size());
255 if (!key.empty())
256 sodium_memzero(key.data(), key.size());
257 return result(code);
258 }
259 if (type == "transport-open") {
260 browser_client_reset_handshake(transport_.get());
262 return result(0);
263 }
264 if (type == "transport-connected") {
266 return result(0);
267 }
268 if (type == "transport-closed") {
269 browser_client_reset_handshake(transport_.get());
271 return result(0);
272 }
273 if (type == "snapshot")
274 return snapshot();
275 if (type == "drain-outputs")
276 return drainOutputs();
277 if (type == "state")
278 return result(0);
279 if (type == "generate-keypair") {
280 const int code = browser_client_generate_keypair(transport_.get());
281 emscripten::val response = result(code);
282 const uint8_t *key = browser_client_public_key_bytes(transport_.get());
283 if (!code && key) {
284 std::array<char, 65> hex{};
285 sodium_bin2hex(hex.data(), hex.size(), key, 32);
286 response.set("publicKey", std::string(hex.data()));
287 }
288 return response;
289 }
290 if (type == "send-packet") {
291 const unsigned packet_type = event["packetType"].as<unsigned>();
292 const unsigned client_id = event["clientId"].isUndefined() ? 0 : event["clientId"].as<unsigned>();
293 const bool encrypt = !event["encrypt"].isUndefined() && event["encrypt"].as<bool>();
294 auto input = binding_copy_input(event["payload"]);
295 if (input.size() > SIZE_MAX - sizeof(packet_header_t) - 512)
296 return result(SET_ERRNO(ERROR_INVALID_PARAM, "Browser client payload is too large"));
297 std::vector<uint8_t> output(input.size() + sizeof(packet_header_t) + 512);
298 size_t output_length = 0;
299 const int code =
300 browser_client_send_packet(transport_.get(), packet_type, client_id, encrypt, input.empty() ? nullptr : input.data(), input.size(), output.data(), output.size(), &output_length);
301 if (!input.empty())
302 sodium_memzero(input.data(), input.size());
303 auto response = result(code);
304 response.set("bytes", binding_copy_output(output.data(), code ? 0 : output_length));
305 return response;
306 }
307 if (type == "receive-transport-packet") {
308 if (event["packet"].isUndefined() || event["packet"].isNull())
309 return result(SET_ERRNO(ERROR_INVALID_PARAM, "Transport packet is required"));
310 auto input = binding_copy_input(event["packet"]);
311 if (input.size() > SIZE_MAX - 128)
312 return result(SET_ERRNO(ERROR_INVALID_PARAM, "Browser client packet is too large"));
313 std::vector<uint8_t> payload(input.size() + 128);
315 const bool discovery = !event["discovery"].isUndefined() && event["discovery"].as<bool>();
316 const int code = browser_client_receive_packet(transport_.get(), discovery, input.data(), input.size(), payload.data(), payload.size(), &packet);
317 if (!input.empty())
318 sodium_memzero(input.data(), input.size());
319 if (code)
320 return result(code);
321 if (packet.handshake || packet.consumed)
322 return drainOutputs();
323 const packet_type_t packet_type = static_cast<packet_type_t>(NET_TO_HOST_U16(packet.header.type));
324 auto response = result(0);
325 response.set("packet", emscripten::val::object());
326 response["packet"].set("type", static_cast<unsigned>(packet_type));
327 response["packet"].set("length", NET_TO_HOST_U32(packet.header.length));
328 response["packet"].set("client_id", NET_TO_HOST_U32(packet.header.client_id));
329 response["packet"].set("crc32", NET_TO_HOST_U32(packet.header.crc32));
330 response.set("encrypted", packet.encrypted);
331 response.set("kind", acip_is_media_packet(packet_type) ? "media"
332 : acip_is_control_packet(packet_type) ? "control"
333 : packet_is_handshake_type(packet_type) ? "crypto"
334 : acip_is_message_packet(packet_type) ? "message"
335 : "unknown");
336 response.set("payload", binding_copy_output(payload.data(), packet.payload_length));
337 if (!payload.empty())
338 sodium_memzero(payload.data(), payload.size());
339 return response;
340 }
341 if (type == "resolve-crypto-policy") {
342 const int mode = browser_client_resolve_crypto_policy(transport_.get(), event["wss"].as<bool>(), event["encryption"].as<int>());
343 emscripten::val response = result(mode < 0 ? SET_ERRNO(ERROR_INVALID_PARAM, "Invalid crypto policy") : 0);
344 response.set("mode", mode);
345 return response;
346 }
347 if (type == "configure-browser-capabilities") {
348 browser_capabilities_.datagrams = event["datagrams"].isUndefined() ? false : event["datagrams"].as<bool>();
349 const size_t max_datagram_payload = event["maxDatagramPayload"].isUndefined() ? 0 : event["maxDatagramPayload"].as<size_t>();
350 browser_capabilities_.max_datagram_payload = browser_capabilities_.datagrams ? max_datagram_payload : 0;
351 browser_transport_set_capabilities(transport_.get(), browser_capabilities_.datagrams, browser_capabilities_.max_datagram_payload);
352 emscripten::val response = result(0);
353 response.set("capabilities", emscripten::val::object());
354 response["capabilities"].set("datagrams", browser_capabilities_.datagrams);
355 response["capabilities"].set("maxDatagramPayload", browser_capabilities_.max_datagram_payload);
356 return response;
357 }
358 if (type == "set-server") {
359 const std::string host = event["host"].as<std::string>();
360 const int port = event["port"].as<int>();
361 if (host.empty() || port <= 0 || port > 65535)
362 return result(SET_ERRNO(ERROR_INVALID_PARAM, "Invalid client server address or port"));
363 return result(browser_client_set_server_address(transport_.get(), host.c_str(), port));
364 }
365 if (type == "quic-event") {
366 const std::string operation = event["operation"].as<std::string>();
367 if (operation == "init")
368 return result(browser_transport_security_init(transport_.get()));
369 if (operation == "state") {
370 emscripten::val response = result(0);
371 response.set("epoch", browser_transport_security_epoch(transport_.get()));
372 return response;
373 }
374 if (operation == "tick") {
375 const int code = browser_transport_security_tick(transport_.get());
376 emscripten::val response = drainOutputs();
377 if (code && response["code"].as<int>() == 0)
378 response.set("code", code);
379 return response;
380 }
381 if (operation != "seal" && operation != "open")
382 return result(SET_ERRNO(ERROR_INVALID_PARAM, "Unknown QUIC operation: %s", operation.c_str()));
383 if (event["packet"].isUndefined() || event["packet"].isNull() || event["flow"].isUndefined() || event["delivery"].isUndefined())
384 return result(SET_ERRNO(ERROR_INVALID_PARAM, "QUIC packet, flow, and delivery are required"));
385 auto input = binding_copy_input(event["packet"]);
386 const bool seal = operation == "seal";
387 std::vector<uint8_t> output(input.size() + (seal ? 94 : 0));
388 size_t length = 0;
389 uint64_t sequence = 0;
390 const int code = browser_transport_security_packet(transport_.get(), seal, event["flow"].as<unsigned>(), event["delivery"].as<unsigned>(), input.data(), input.size(), output.data(),
391 output.size(), &length, &sequence);
392 emscripten::val response = result(code);
393 response.set("bytes", binding_copy_output(output.data(), code ? 0 : length));
394 response.set("sequence", emscripten::val::global("BigInt")(std::to_string(sequence)));
395 if (!input.empty())
396 sodium_memzero(input.data(), input.size());
397 if (!output.empty())
398 sodium_memzero(output.data(), output.size());
399 return response;
400 }
401 return result(SET_ERRNO(ERROR_INVALID_PARAM, "Unknown browser client event: %s", type.c_str()));
402 }
403 emscripten::val drainOutputs() {
404 emscripten::val response = result(0);
405 int output_code = 0;
406 response.set("outputs", browser_outputs(&output_code));
407 if (!response["code"].as<int>() && output_code)
408 response.set("code", output_code);
409 response.set("epoch", browser_transport_security_epoch(transport_.get()));
410 response.set("queuedBytes", browser_transport_queued_bytes(transport_.get()));
411 response.set("acceptedPackets", emscripten::val::global("BigInt")(std::to_string(browser_transport_accepted_packets(transport_.get()))));
412 response.set("droppedPackets", emscripten::val::global("BigInt")(std::to_string(browser_transport_dropped_packets(transport_.get()))));
413 response.set("droppedBytes", emscripten::val::global("BigInt")(std::to_string(browser_transport_dropped_bytes(transport_.get()))));
414 response.set("writable", browser_transport_writable(transport_.get(), 0));
415 return response;
416 }
417 emscripten::val processBatch(emscripten::val events) {
418 if (!owned_) {
419 emscripten::val batch = emscripten::val::array();
420 batch.call<void>("push", result(SET_ERRNO(ERROR_INVALID_STATE, "Client session is not initialized")));
421 return batch;
422 }
423 const unsigned count = events["length"].as<unsigned>();
424 if (count > 256) {
425 emscripten::val batch = emscripten::val::array();
426 batch.call<void>("push", result(SET_ERRNO(ERROR_INVALID_PARAM, "Client event batch exceeds 256 events")));
427 return batch;
428 }
429 emscripten::val batch = emscripten::val::array();
430 for (unsigned index = 0; index < count; ++index)
431 batch.call<void>("push", process(events[index]));
432 return batch;
433 }
434
435private:
436 emscripten::val result(int code) const {
437 emscripten::val response = emscripten::val::object();
438 response.set("ok", code == 0);
439 response.set("code", code);
440 response.set("state", static_cast<int>(browser_transport_state(transport_.get())));
441 if (code) {
443 const bool has_context = errno_has(&context);
444 response.set("message", has_context && context.context_message[0] ? std::string(context.context_message) : std::string(asciichat_error_string(static_cast<asciichat_error_t>(code))));
445 response.set("retryable", network_error_action(static_cast<asciichat_error_t>(code)) == NETWORK_ERROR_RETRY);
446 }
447 return response;
448 }
449 emscripten::val browser_outputs(int *output_code) {
450 emscripten::val outputs = emscripten::val::array();
451 while (browser_transport_output_size(transport_.get())) {
452 const size_t length = browser_transport_output_size(transport_.get());
453 emscripten::val output = emscripten::val::object();
454 output.set("flow", static_cast<unsigned>(browser_transport_output_traffic(transport_.get())));
455 output.set("delivery", static_cast<unsigned>(browser_transport_output_delivery(transport_.get())));
456 output.set("packet", binding_copy_output(browser_transport_output_data(transport_.get()), length));
457 outputs.call<void>("push", output);
458 browser_transport_output_pop(transport_.get());
459 }
460 // Authenticated-but-unencrypted sessions complete the ACIP handshake but
461 // never create encrypted record/control traffic. Only ask the record
462 // layer for pending control packets when encryption is actually enabled;
463 // otherwise crypto_record_init() correctly rejects the request as not
464 // applicable and would turn a successful auth-only handshake into a
465 // spurious ERROR_INVALID_STATE result.
466 const crypto_context_t *crypto = browser_transport_base(transport_.get())->crypto_ctx;
467 if (crypto && crypto->encrypt_data) {
468 for (unsigned index = 0; index < 32; ++index) {
469 uint8_t data[256];
470 size_t length = 0;
471 uint32_t flow = 0;
472 const int code = browser_transport_security_output(transport_.get(), data, sizeof(data), &length, &flow);
473 if (code) {
474 if (output_code)
475 *output_code = code;
476 break;
477 }
478 if (!length)
479 break;
480 emscripten::val output = emscripten::val::object();
481 output.set("flow", flow);
482 output.set("packet", binding_copy_output(data, length));
483 outputs.call<void>("push", output);
484 }
485 }
486 return outputs;
487 }
488 std::unique_ptr<browser_transport_t, decltype(&browser_transport_destroy)> transport_{nullptr, &browser_transport_destroy};
489 struct {
490 // Only datagrams affect native ACIP transport policy. WebTransport and
491 // WebRTC selection, and HEVC encoder/decoder selection, belong to the
492 // browser adapters before they call into this session. These values are
493 // retained for protocol diagnostics and are not native policy inputs.
494 bool datagrams = false;
496 } browser_capabilities_;
497 bool owned_ = false;
498 int result_ = 0;
499};
500EMSCRIPTEN_BINDINGS(ascii_chat_network) {
501 emscripten::register_type<ClientBytes>("ClientBytes", "Uint8Array");
502 emscripten::class_<ClientSessionBinding>("ClientSessionBinding")
503 .constructor<OptionsPatch>()
504 .class_function("errorAction", &ClientSessionBinding::errorAction)
505 .function("valid", &ClientSessionBinding::valid)
506 .function("packetTypes", &ClientSessionBinding::packetTypes)
507 .function("protocolInfo", &ClientSessionBinding::protocolInfo)
508 .function("error", &ClientSessionBinding::error)
509 .function("close", &ClientSessionBinding::close)
510 .function("process", &ClientSessionBinding::process)
511 .function("processBatch", &ClientSessionBinding::processBatch);
512}
bool errno_has(asciichat_error_context_t *context)
#define SET_ERRNO(code,...)
browser_transport_t * browser_transport_create(void)
uint64_t browser_transport_dropped_packets(const browser_transport_t *browser)
acip_traffic_class_t browser_transport_output_traffic(const browser_transport_t *browser)
asciichat_error_t browser_transport_security_output(browser_transport_t *browser, uint8_t *output, size_t capacity, size_t *length, uint32_t *channel)
uint64_t browser_transport_dropped_bytes(const browser_transport_t *browser)
size_t browser_transport_output_size(browser_transport_t *browser)
asciichat_error_t browser_transport_security_init(browser_transport_t *browser)
acip_transport_t * browser_transport_base(browser_transport_t *browser)
bool browser_transport_writable(const browser_transport_t *browser, size_t additional_bytes)
asciichat_error_t browser_transport_security_packet(browser_transport_t *browser, bool seal, uint32_t channel, uint32_t delivery, const uint8_t *packet, size_t length, uint8_t *output, size_t capacity, size_t *out_length, uint64_t *sequence)
double browser_transport_security_epoch(browser_transport_t *browser)
size_t browser_transport_queued_bytes(const browser_transport_t *browser)
asciichat_error_t browser_transport_security_tick(browser_transport_t *browser)
const void * browser_transport_output_data(browser_transport_t *browser)
void browser_transport_set_state(browser_transport_t *browser, browser_transport_state_t state)
void browser_transport_set_capabilities(browser_transport_t *browser, bool datagrams, size_t max_datagram_payload)
uint64_t browser_transport_accepted_packets(const browser_transport_t *browser)
void browser_transport_output_pop(browser_transport_t *browser)
void browser_transport_destroy(browser_transport_t *browser)
acip_delivery_t browser_transport_output_delivery(const browser_transport_t *browser)
emscripten::val binding_copy_output(const void *data, size_t length)
Definition byte_arrays.h:18
std::vector< uint8_t > binding_copy_input(emscripten::val bytes)
Definition byte_arrays.h:6
emscripten::val snapshot() const
ClientSessionBinding(const ClientSessionBinding &)=delete
ClientSessionBinding(OptionsPatch options)
emscripten::val processBatch(emscripten::val events)
emscripten::val drainOutputs()
emscripten::val protocolInfo() const
emscripten::val packetTypes() const
emscripten::val process(emscripten::val event)
ClientSessionBinding & operator=(const ClientSessionBinding &)=delete
static int errorAction(int code)
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U16(val)
Definition endian.h:115
#define NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned int uint32_t
#define SAFE_FREE(ptr)
unsigned long long uint64_t
unsigned char uint8_t
struct crypto_context_t crypto_context_t
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_INIT
Definition error_codes.h:60
@ ERROR_INVALID_PARAM
#define ACIP_CRYPTO_NONE
No encryption, no authentication (plaintext only).
Definition packet.h:1161
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define ACIP_CRYPTO_ENCRYPT
Encryption only (no identity verification).
Definition packet.h:1162
#define ACIP_CRYPTO_AUTH
Authentication only (no payload encryption).
Definition packet.h:1163
@ PACKET_TYPE_CRYPTO_CLIENT_HELLO
Client -> Server: Expected server key fingerprint for multi-key selection (UNENCRYPTED).
Definition packet.h:328
@ PACKET_TYPE_ACIP_WEBRTC_ICE
WebRTC ICE candidate (bidirectional).
Definition packet.h:466
@ PACKET_TYPE_QUIC_READY
Internal authenticated readiness barrier for ACIP over QUIC.
Definition packet.h:356
@ PACKET_TYPE_AUDIO_OPUS_BATCH
Batched Opus-encoded audio frames.
Definition packet.h:412
@ PACKET_TYPE_ACIP_PARTICIPANT_JOINED
Participant joined notification (ACDS -> Existing Participants).
Definition packet.h:507
@ PACKET_TYPE_CLIENT_LEAVE
Clean disconnect notification.
Definition packet.h:427
@ PACKET_TYPE_ACIP_SESSION_INFO
Session info response (Discovery Server -> Client).
Definition packet.h:451
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_CRYPTO_AUTH_RESPONSE
Client -> Server: {HMAC[32]} (UNENCRYPTED).
Definition packet.h:346
@ PACKET_TYPE_TEXT_MESSAGE
Text message.
Definition packet.h:386
@ PACKET_TYPE_AUDIO_MESSAGE
Audio message.
Definition packet.h:384
@ PACKET_TYPE_PONG
Keepalive pong response.
Definition packet.h:423
@ PACKET_TYPE_ACIP_SESSION_RECONNECT
Reconnect to session (Client -> Discovery Server).
Definition packet.h:461
@ PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE
Server -> Client: "encryption ready" (UNENCRYPTED).
Definition packet.h:352
@ PACKET_TYPE_ACIP_PARTICIPANT_LIST
Participant list with ring order (ACDS -> Participants).
Definition packet.h:483
@ PACKET_TYPE_STREAM_START
Client requests to start sending video/audio.
Definition packet.h:429
@ PACKET_TYPE_ACIP_SETTINGS_SYNC
Settings sync (Initiator -> Host -> All Participants).
Definition packet.h:499
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT
Server -> Client: {server_pubkey[32]} (UNENCRYPTED).
Definition packet.h:340
@ PACKET_TYPE_ACIP_ERROR
Generic error response (Discovery Server -> Client).
Definition packet.h:547
@ PACKET_TYPE_CRYPTO_EPOCH_MARKER
Definition packet.h:359
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP
Client -> Server: {client_pubkey[32]} (UNENCRYPTED).
Definition packet.h:342
@ PACKET_TYPE_CRYPTO_REKEY_COMPLETE
Initiator -> Responder: Empty (encrypted with NEW key, but still handshake).
Definition packet.h:375
@ PACKET_TYPE_ACIP_NETWORK_QUALITY
NETWORK_QUALITY exchange (unified packet for all quality metrics).
Definition packet.h:493
@ PACKET_TYPE_SERVER_STATE
Server sends current state to clients.
Definition packet.h:435
@ PACKET_TYPE_ACIP_HOST_LOST
Host lost notification - lightweight (Participant -> ACDS).
Definition packet.h:503
@ PACKET_TYPE_ACIP_BROADCAST_ACK
Broadcast acknowledgment for reliable delivery.
Definition packet.h:522
@ PACKET_TYPE_ACIP_HOST_DESIGNATED
Host designated (ACDS -> All Participants).
Definition packet.h:497
@ PACKET_TYPE_ACIP_STRING_RESERVE
Reserve session string (Client -> Discovery Server).
Definition packet.h:469
@ PACKET_TYPE_CRYPTO_AUTH_FAILED
Server -> Client: "authentication failed" (UNENCRYPTED).
Definition packet.h:348
@ PACKET_TYPE_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ PACKET_TYPE_CRYPTO_REKEY_REQUEST
Initiator -> Responder: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).
Definition packet.h:371
@ PACKET_TYPE_SIZE_MESSAGE
Terminal size message.
Definition packet.h:382
@ PACKET_TYPE_REMOTE_LOG
Bidirectional remote logging packet.
Definition packet.h:390
@ PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP
Server -> Client: {HMAC[32]} server proves knowledge (UNENCRYPTED).
Definition packet.h:350
@ PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT
Host announcement (Participant -> ACDS, "I won negotiation").
Definition packet.h:495
@ PACKET_TYPE_PROTOCOL_VERSION
Protocol version and capabilities negotiation.
Definition packet.h:317
@ PACKET_TYPE_ACIP_SETTINGS_ACK
Settings acknowledgment (Participant -> Initiator).
Definition packet.h:501
@ PACKET_TYPE_ACIP_BANDWIDTH_TEST
Bandwidth test request (Client -> ACDS).
Definition packet.h:517
@ PACKET_TYPE_CLEAR_CONSOLE
Server tells client to clear console.
Definition packet.h:433
@ PACKET_TYPE_CRYPTO_EPOCH_ACK
Definition packet.h:361
@ PACKET_TYPE_CRYPTO_NO_ENCRYPTION
Client -> Server: "I want to proceed without encryption" (UNENCRYPTED).
Definition packet.h:354
@ PACKET_TYPE_ACIP_SESSION_CREATE
Create new session (Client -> Discovery Server).
Definition packet.h:445
@ PACKET_TYPE_STATS_UPDATE
Statistics update during collection phase (Participant -> Next Participant).
Definition packet.h:534
@ PACKET_TYPE_ACIP_STRING_RESERVED
String reserved response (Discovery Server -> Client).
Definition packet.h:471
@ PACKET_TYPE_IMAGE_FRAME_H265
H.265-encoded frame from client (HEVC/H.265 codec).
Definition packet.h:401
@ PACKET_TYPE_ACIP_DISCOVERY_PING
Discovery server ping (keepalive).
Definition packet.h:545
@ PACKET_TYPE_CRYPTO_AUTH_CHALLENGE
Server -> Client: {nonce[32]} (UNENCRYPTED).
Definition packet.h:344
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
@ PACKET_TYPE_CRYPTO_PARAMETERS
Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).
Definition packet.h:338
@ PACKET_TYPE_ACIP_SESSION_LOOKUP
Lookup session by string (Client -> Discovery Server).
Definition packet.h:449
@ PACKET_TYPE_CRYPTO_CAPABILITIES
Client -> Server: Supported crypto algorithms (UNENCRYPTED).
Definition packet.h:336
@ PACKET_TYPE_RING_ELECTION_RESULT
Final election result (Quorum Leader -> All Participants).
Definition packet.h:536
@ PACKET_TYPE_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457
@ PACKET_TYPE_ACIP_PARTICIPANT_LEFT
Participant left notification (ACDS -> Remaining Participants).
Definition packet.h:509
@ PACKET_TYPE_ACIP_WEBRTC_SDP
WebRTC SDP offer/answer (bidirectional).
Definition packet.h:464
@ PACKET_TYPE_ACIP_SESSION_JOIN
Join existing session (Client -> Discovery Server).
Definition packet.h:453
@ PACKET_TYPE_ACIP_SESSION_CREATED
Session created response (Discovery Server -> Client).
Definition packet.h:447
@ PACKET_TYPE_CRYPTO_REKEY_NEEDED
Definition packet.h:360
@ PACKET_TYPE_STATS_ACK
Acknowledgment of statistics update (Participant -> Sender).
Definition packet.h:538
@ PACKET_TYPE_ACIP_STRING_RELEASE
Release string reservation (Client -> Discovery Server).
Definition packet.h:475
@ PACKET_TYPE_CLIENT_JOIN
Client announces capability to send media.
Definition packet.h:425
@ PACKET_TYPE_CLIENT_CAPABILITIES
Client reports terminal capabilities.
Definition packet.h:419
@ PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED
Future host elected announcement (Quorum Leader -> ACDS -> All Participants).
Definition packet.h:505
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
@ PACKET_TYPE_ACIP_BANDWIDTH_RESULT
Bandwidth test results (ACDS -> Client).
Definition packet.h:519
@ PACKET_TYPE_ACIP_STRING_RENEW
Renew string reservation (Client -> Discovery Server).
Definition packet.h:473
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
@ PACKET_TYPE_RING_MEMBERS
Ring member list announcement (ACDS -> All Participants).
Definition packet.h:530
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
@ PACKET_TYPE_QUIC_KEYFRAME_REQUEST
Internal authenticated request for a QUIC encoded-video keyframe.
Definition packet.h:358
@ PACKET_TYPE_AUDIO_BATCH
Batched audio packets for efficiency.
Definition packet.h:410
@ PACKET_TYPE_CRYPTO_REKEY_RESPONSE
Responder -> Initiator: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).
Definition packet.h:373
@ PACKET_TYPE_ACIP_SESSION_JOINED
Session joined response (Discovery Server -> Client).
Definition packet.h:455
@ PACKET_TYPE_STATS_COLLECTION_START
Start statistics collection phase (Coordinator -> All Participants).
Definition packet.h:532
@ PACKET_TYPE_STREAM_STOP
Client stops sending media.
Definition packet.h:431
@ PACKET_TYPE_ACIP_RING_COLLECT
Ring collect request (Participant -> Next Participant).
Definition packet.h:485
@ PACKET_TYPE_ACIP_SESSION_END
End session (Host -> Discovery Server).
Definition packet.h:459
#define PROTOCOL_VERSION_MAJOR
Major protocol version number.
#define PROTOCOL_VERSION_MINOR
Minor protocol version number.
#define PROTOCOL_VERSION_PATCH
Patch protocol version number.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
struct browser_transport browser_transport_t
Network error handling utilities.
bool browser_client_ready(browser_transport_t *transport)
int browser_client_init(browser_transport_t *transport)
char * browser_client_settings_values(browser_transport_t *transport)
void browser_client_reset_handshake(browser_transport_t *transport)
asciichat_error_t browser_client_validate_frame(browser_transport_t *transport, const char *text, size_t length, uint32_t width, uint32_t height, uint32_t checksum, uint32_t flags, const void *metadata, size_t metadata_length)
asciichat_error_t browser_client_settings_receive(browser_transport_t *transport, const void *payload, size_t length)
asciichat_error_t browser_client_decode_frame_data(const void *encoded, size_t encoded_length, void *output, size_t output_length)
asciichat_error_t browser_client_handshake_begin(browser_transport_t *transport)
asciichat_error_t browser_client_acds_handshake_begin(browser_transport_t *transport, uint8_t mode)
int browser_client_resolve_crypto_policy(browser_transport_t *transport, bool secure, int encryption)
int browser_client_generate_keypair(browser_transport_t *transport)
int browser_client_set_server_address(browser_transport_t *transport, const char *server_host, int server_port)
asciichat_error_t browser_client_send_packet(browser_transport_t *transport, uint32_t type, uint32_t client_id, bool encrypt, const uint8_t *payload, size_t payload_length, uint8_t *output, size_t output_capacity, size_t *output_length)
int browser_client_configure_crypto_options(browser_transport_t *transport, const char *password, const uint8_t *identity_secret_key, const uint8_t *expected_server_public_key)
void browser_client_cleanup(browser_transport_t *transport)
asciichat_error_t browser_client_receive_packet(browser_transport_t *transport, bool discovery, const uint8_t *input, size_t input_length, uint8_t *payload, size_t payload_capacity, browser_client_packet_result_t *result)
const uint8_t * browser_client_public_key_bytes(browser_transport_t *transport)
network_error_action_t network_error_action(asciichat_error_t code)
ACIP protocol message structures and helpers.
EMSCRIPTEN_BINDINGS(ascii_chat_network)
int initial_options(OptionsPatch patch)
Definition opts.cpp:25
Protocol version, features, compression, and frame flag constants.
static bool size_t index
Definition queries.h:10
crypto_context_t * crypto_ctx
Optional encryption context.
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
uint32_t client_id
Client ID (0 = server, >0 = client identifier).
Definition packet.h:651
uint32_t length
Payload data length in bytes (0 for header-only packets).
Definition packet.h:647
uint16_t type
Packet type (packet_type_t enumeration).
Definition packet.h:645
uint32_t crc32
CRC32 checksum of payload data (0 if length == 0).
Definition packet.h:649