ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/network/browser/client.c
Go to the documentation of this file.
3
4/* Storage capacities in elements; text buffers include the terminating NUL. */
5#define WEB_CLIENT_CRYPTO_PASSWORD_BUFFER_SIZE 256
6
12#include <ascii-chat/common.h>
13#include <string.h>
18
22
27
28#include <stdlib.h>
29#include <string.h>
30#include <stdint.h>
31
32#include <options/options.h>
33#include <options/rcu.h>
35#include <ascii-chat/log/log.h>
49
50#include <ascii-chat/common.h>
51#include <ascii-chat/buffer.h>
54#include <sodium.h>
55
56// ============================================================================
57// WASM Transport Implementation
58// ============================================================================
59
60// ============================================================================
61// Global State
62// ============================================================================
63
77
79 return transport ? browser_transport_client_state(transport) : NULL;
80}
81
82asciichat_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,
83 size_t output_capacity, size_t *output_length) {
84 if (!transport || !output || !output_length || (payload_length && !payload) || type > UINT16_MAX || payload_length > SIZE_MAX - sizeof(packet_header_t) - 512)
85 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid browser client packet input");
86 *output_length = 0;
87 if (!encrypt)
88 return packet_encode((packet_type_t)type, payload, payload_length, client_id, output, output_capacity, output_length);
89 if (!browser_client_ready(transport))
90 return SET_ERRNO(ERROR_INVALID_STATE, "Cannot encrypt browser client packet before handshake completion");
91
92 asciichat_error_t error = packet_send_via_transport(browser_transport_base(transport), (packet_type_t)type, payload, payload_length, client_id);
93 if (error != ASCIICHAT_OK)
94 return error;
95 const size_t wire_length = browser_transport_output_size(transport);
96 if (wire_length > output_capacity) {
98 return SET_ERRNO(ERROR_NETWORK_SIZE, "Encrypted browser client packet output is too small");
99 }
100 memcpy(output, browser_transport_output_data(transport), wire_length);
101 *output_length = wire_length;
103 return ASCIICHAT_OK;
104}
105
106asciichat_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,
108 if (!transport || !input || !result || input_length < sizeof(packet_header_t))
109 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid browser client transport packet");
110 memset(result, 0, sizeof(*result));
111 packet_header_t header = {0};
112 asciichat_error_t error = packet_validate(input, input_length, 0, &header);
113 if (error != ASCIICHAT_OK)
114 return error;
115 const packet_type_t outer_type = (packet_type_t)NET_TO_HOST_U16(header.type);
116 const size_t header_size = sizeof(packet_header_t);
117 if (!browser_client_ready(transport) && (outer_type == PACKET_TYPE_PROTOCOL_VERSION || packet_is_handshake_type(outer_type))) {
118 result->handshake = true;
119 return discovery ? browser_client_acds_handshake_receive(transport, outer_type, input + header_size, input_length - header_size)
120 : browser_client_handshake_receive(transport, outer_type, input + header_size, input_length - header_size);
121 }
122 packet_envelope_t envelope = {0};
123 error = packet_parse_envelope(input, input_length, browser_transport_base(transport)->crypto_ctx, &envelope);
124 if (error != ASCIICHAT_OK)
125 return error;
126 result->encrypted = envelope.was_encrypted;
127 result->consumed = envelope.consumed;
128 if (envelope.consumed) {
129 packet_envelope_release(&envelope);
130 return ASCIICHAT_OK;
131 }
132 result->payload_length = envelope.len;
133 if (result->payload_length > payload_capacity || (result->payload_length && !payload)) {
134 packet_envelope_release(&envelope);
135 return SET_ERRNO(ERROR_INVALID_PARAM, "Browser client packet output is too small");
136 }
137 memcpy(&result->header, envelope.allocated_buffer, sizeof(result->header));
138 if (result->payload_length)
139 memcpy(payload, envelope.data, result->payload_length);
140 packet_envelope_release(&envelope);
141 return ASCIICHAT_OK;
142}
143
144asciichat_error_t browser_client_settings_receive(browser_transport_t *transport, const void *payload, size_t length) {
145 client_state_t *state = client_state(transport);
146 if (!state)
147 return SET_ERRNO(ERROR_INVALID_STATE, "Browser client transport is not initialized");
149 const char *json;
150 size_t json_length;
151 asciichat_error_t result = acip_settings_decode(payload, length, &header, &json, &json_length);
152 if (result != ASCIICHAT_OK)
153 return result;
154 options_t *current = SAFE_MALLOC(sizeof(*current), options_t *), *candidate = SAFE_MALLOC(sizeof(*candidate), options_t *);
155 state->remote_render_settings.caps.utf8_support = true;
157 result = options_prepare_json(current, json, json_length, candidate, true);
158 if (result == ASCIICHAT_OK)
159 result = acip_render_settings_prepare(&state->remote_render_settings, candidate);
160 if (result == ASCIICHAT_OK)
161 state->remote_render_settings.revision = header.revision;
162 SAFE_FREE(current);
163 SAFE_FREE(candidate);
164 return result;
165}
166
168 client_state_t *state = client_state(transport);
169 if (!state) {
170 SET_ERRNO(ERROR_INVALID_STATE, "Browser client transport is not initialized");
171 return NULL;
172 }
173 options_t *values = SAFE_MALLOC(sizeof(*values), options_t *);
175 char *json = options_values_json(values, true);
176 SAFE_FREE(values);
177 return json;
178}
179
180static int apply_client_crypto_options(browser_transport_t *transport) {
181 client_state_t *state = client_state(transport);
182 if (!state) {
183 SET_ERRNO(ERROR_INVALID_STATE, "Client transport is not initialized");
184 return -1;
185 }
187 if (ctx->state != CRYPTO_HANDSHAKE_INIT) {
188 SET_ERRNO(ERROR_INVALID_STATE, "Client handshake is not ready for crypto options");
189 return -1;
190 }
191
192 if (state->crypto_password[0] != '\0') {
194 if (result != CRYPTO_OK)
195 return -1;
196 ctx->crypto_ctx.has_password = true;
197 ctx->has_password = true;
198 SAFE_STRNCPY(ctx->password, state->crypto_password, sizeof(ctx->password) - 1);
199 }
200
201 if (state->has_client_identity_key) {
203 memcpy(ctx->client_private_key.key.ed25519, state->client_identity_key, sizeof(state->client_identity_key));
204 memcpy(ctx->client_private_key.public_key, state->client_identity_key + crypto_sign_SEEDBYTES, (size_t)crypto_sign_PUBLICKEYBYTES);
205 memcpy(ctx->client_public_key.key, state->client_identity_key + crypto_sign_SEEDBYTES, (size_t)crypto_sign_PUBLICKEYBYTES);
207 }
208
212 ctx->verify_server_key = true;
213 }
214 return 0;
215}
216
218int 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) {
219 client_state_t *state = client_state(transport);
220 if (!state || !state->initialized) {
221 SET_ERRNO(ERROR_INVALID_STATE, "Client is not initialized");
222 return -1;
223 }
224
225 sodium_memzero(state->crypto_password, sizeof(state->crypto_password));
226 sodium_memzero(state->client_identity_key, sizeof(state->client_identity_key));
227 sodium_memzero(state->expected_server_identity_key, sizeof(state->expected_server_identity_key));
228 state->has_client_identity_key = false;
230
231 if (password && password[0] != '\0') {
232 size_t length = strnlen(password, sizeof(state->crypto_password));
233 if (length < 8 || length >= sizeof(state->crypto_password)) {
234 SET_ERRNO(ERROR_INVALID_PARAM, "Client password must contain 8 to %zu bytes", sizeof(state->crypto_password) - 1);
235 return -1;
236 }
237 SAFE_STRNCPY(state->crypto_password, password, sizeof(state->crypto_password) - 1);
238 }
239
240 if (identity_secret_key) {
241 uint8_t derived_public_key[crypto_sign_PUBLICKEYBYTES];
242 if (crypto_sign_ed25519_sk_to_pk(derived_public_key, identity_secret_key) != 0 || sodium_memcmp(derived_public_key, identity_secret_key + crypto_sign_SEEDBYTES, crypto_sign_PUBLICKEYBYTES) != 0) {
243 sodium_memzero(derived_public_key, sizeof(derived_public_key));
244 SET_ERRNO(ERROR_INVALID_PARAM, "Client identity secret key is invalid");
245 return -1;
246 }
247 memcpy(state->client_identity_key, identity_secret_key, sizeof(state->client_identity_key));
248 sodium_memzero(derived_public_key, sizeof(derived_public_key));
249 state->has_client_identity_key = true;
250 }
251
252 if (expected_server_public_key) {
253 memcpy(state->expected_server_identity_key, expected_server_public_key, sizeof(state->expected_server_identity_key));
255 }
256 return 0;
257}
258
260int browser_client_parse_ssh_private_key(const char *key_path, uint8_t *secret_key_out) {
261 if (!key_path || !secret_key_out) {
262 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid SSH private key input or output");
263 return -1;
264 }
265#ifdef EMSCRIPTEN_BUILD
266 static const char wasm_key_prefix[] = "/tmp/ascii-chat-key-";
267 if (strncmp(key_path, wasm_key_prefix, sizeof(wasm_key_prefix) - 1) != 0) {
268 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid browser SSH private key path");
269 return -1;
270 }
271#endif
272 private_key_t key = {0};
273 asciichat_error_t result = parse_ssh_private_key(key_path, &key);
274 if (result != ASCIICHAT_OK || key.type != KEY_TYPE_ED25519 || key.use_ssh_agent || key.use_gpg_agent) {
275 sodium_memzero(&key, sizeof(key));
276 return -1;
277 }
278 memcpy(secret_key_out, key.key.ed25519, (size_t)crypto_sign_SECRETKEYBYTES);
279 sodium_memzero(&key, sizeof(key));
280 return 0;
281}
282
284int browser_client_parse_ssh_public_key(const char *key_line, uint8_t *public_key_out) {
285 if (!key_line || !public_key_out) {
286 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid SSH public key input or output");
287 return -1;
288 }
289 return parse_ssh_ed25519_line(key_line, public_key_out) == ASCIICHAT_OK ? 0 : -1;
290}
291
293int browser_client_parse_gpg_public_key(const char *armored_key, uint8_t *public_key_out) {
294 if (!armored_key || !public_key_out) {
295 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid OpenPGP public key input or output");
296 return -1;
297 }
298 return openpgp_parse_armored_pubkey(armored_key, public_key_out) == ASCIICHAT_OK ? 0 : -1;
299}
300
302int browser_client_parse_gpg_public_key_binary(const uint8_t *key_data, size_t key_data_len, uint8_t *public_key_out) {
303 if (!key_data || key_data_len == 0 || !public_key_out) {
304 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid binary OpenPGP public key input or output");
305 return -1;
306 }
307 return openpgp_parse_binary_pubkey(key_data, key_data_len, public_key_out) == ASCIICHAT_OK ? 0 : -1;
308}
309
311int browser_client_parse_gpg_private_key(const char *armored_key, uint8_t *secret_key_out) {
312 if (!armored_key || !secret_key_out) {
313 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid OpenPGP private key input or output");
314 return -1;
315 }
316 uint8_t public_key[crypto_sign_PUBLICKEYBYTES] = {0};
317 uint8_t seed[crypto_sign_SEEDBYTES] = {0};
318 uint8_t derived_public_key[crypto_sign_PUBLICKEYBYTES] = {0};
319 uint8_t secret_key[crypto_sign_SECRETKEYBYTES] = {0};
320 int result = -1;
321
322 if (openpgp_parse_armored_seckey(armored_key, public_key, seed) != ASCIICHAT_OK)
323 goto cleanup;
324 if (crypto_sign_seed_keypair(derived_public_key, secret_key, seed) != 0 || sodium_memcmp(derived_public_key, public_key, sizeof(public_key)) != 0) {
325 SET_ERRNO(ERROR_CRYPTO_KEY, "OpenPGP private key does not match its Ed25519 public key");
326 goto cleanup;
327 }
328
329 memcpy(secret_key_out, secret_key, sizeof(secret_key));
330 result = 0;
331
332cleanup:
333 sodium_memzero(public_key, sizeof(public_key));
334 sodium_memzero(seed, sizeof(seed));
335 sodium_memzero(derived_public_key, sizeof(derived_public_key));
336 sodium_memzero(secret_key, sizeof(secret_key));
337 return result;
338}
339
341int browser_client_parse_gpg_private_key_binary(const uint8_t *key_data, size_t key_data_len, uint8_t *secret_key_out) {
342 if (!key_data || key_data_len == 0 || !secret_key_out) {
343 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid binary OpenPGP private key input or output");
344 return -1;
345 }
346 uint8_t public_key[crypto_sign_PUBLICKEYBYTES] = {0};
347 uint8_t seed[crypto_sign_SEEDBYTES] = {0};
348 uint8_t derived_public_key[crypto_sign_PUBLICKEYBYTES] = {0};
349 uint8_t secret_key[crypto_sign_SECRETKEYBYTES] = {0};
350 int result = -1;
351
352 if (openpgp_parse_binary_seckey(key_data, key_data_len, public_key, seed) != ASCIICHAT_OK)
353 goto cleanup;
354 if (crypto_sign_seed_keypair(derived_public_key, secret_key, seed) != 0 || sodium_memcmp(derived_public_key, public_key, sizeof(public_key)) != 0) {
355 SET_ERRNO(ERROR_CRYPTO_KEY, "OpenPGP private key does not match its Ed25519 public key");
356 goto cleanup;
357 }
358
359 memcpy(secret_key_out, secret_key, sizeof(secret_key));
360 result = 0;
361
362cleanup:
363 sodium_memzero(public_key, sizeof(public_key));
364 sodium_memzero(seed, sizeof(seed));
365 sodium_memzero(derived_public_key, sizeof(derived_public_key));
366 sodium_memzero(secret_key, sizeof(secret_key));
367 return result;
368}
369
371int browser_client_get_crypto_error_message(char *output, size_t output_size) {
372 if (!output || output_size == 0) {
373 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid crypto error output buffer");
374 return -1;
375 }
376 asciichat_error_context_t context = {0};
377 if (!HAS_ERRNO(&context) || !context.context_message[0])
378 return -1;
379 safe_snprintf(output, output_size, "%s", context.context_message);
380 return 0;
381}
382
383// ============================================================================
384// Initialization
385// ============================================================================
386
392 if (!transport)
393 return SET_ERRNO(ERROR_INVALID_PARAM, "Cannot initialize client without a browser transport");
394 client_state_t *state = client_state(transport);
395 if (!state) {
396 state = SAFE_CALLOC(1, sizeof(*state), client_state_t *);
397 if (!state)
398 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate browser client state");
400 browser_transport_set_client_state(transport, state);
401 }
402 // The module, renderers, and allocator outlive individual connections.
403 if (state->initialized) {
405 return 0;
406 }
407 char *argv[] = {"client", NULL};
408 // Keep browser startup on the same shared initialization path as the CLI.
409 // options_init() relies on logging, timers, buffers, and platform state
410 // established by asciichat_shared_init(), so it must come second.
411 asciichat_error_t err = asciichat_shared_init(NULL, true, true);
412 if (err != ASCIICHAT_OK) {
413 return -1;
414 }
415
416 err = options_init(1, argv);
417 if (err != ASCIICHAT_OK)
418 return -1;
419 /* Browser options are patched immediately after this call, so initialize
420 * FFTW even when the default option is off and JavaScript enables it later. */
422 return -1;
423
424 // Honor the requested verbosity and let INFO use stdout (console.log).
425 log_init(NULL, GET_OPTION(log_level), false, false);
426 // Use debug-style format in WASM so browser console shows full log headers
428 log_info("WASM client initialized via logging system");
429
430 if (err != ASCIICHAT_OK) {
431 return -1;
432 }
433
434 // Initialize ANSI color code generation
436
438
439 state->initialized = true;
440
441 return 0;
442}
443
445 client_state_t *state = client_state(transport);
446 if (!state)
447 return;
449
450 // Clean up crypto handshake context
452 memset(&state->crypto_handshake_ctx, 0, sizeof(state->crypto_handshake_ctx));
453
454 state->handshake_complete = false;
456 sodium_memzero(state->crypto_password, sizeof(state->crypto_password));
457 sodium_memzero(state->client_identity_key, sizeof(state->client_identity_key));
458 sodium_memzero(state->expected_server_identity_key, sizeof(state->expected_server_identity_key));
459 state->has_client_identity_key = false;
461 state->initialized = false;
462 // Keep module-wide options and buffer domains alive while browser renderers
463 // still reference them. Connection cleanup only resets authentication state.
464 SAFE_FREE(state);
465 browser_transport_set_client_state(transport, NULL);
466}
467
468// ============================================================================
469// Cryptography API
470// ============================================================================
471
477 client_state_t *state = client_state(transport);
478 if (!state || !state->initialized) {
479 SET_ERRNO(ERROR_INVALID_STATE, "Client is not initialized");
480 return -1;
481 }
482
483 // A replacement handshake must not retain the previous connection's sequence state.
484 // Reset handshake context if previously used (reconnection / React Strict Mode remount)
487 memset(&state->crypto_handshake_ctx, 0, sizeof(state->crypto_handshake_ctx));
488 state->handshake_complete = false;
489 }
490
491 // Initialize crypto handshake context
492 asciichat_error_t result = crypto_handshake_init("wasm-client", &state->crypto_handshake_ctx, false /* is_server */);
493 if (result != ASCIICHAT_OK) {
494 return -1;
495 }
496 if (apply_client_crypto_options(transport) != 0) {
498 memset(&state->crypto_handshake_ctx, 0, sizeof(state->crypto_handshake_ctx));
499 return -1;
500 }
501
503 return 0;
504}
505
512int browser_client_set_server_address(browser_transport_t *transport, const char *server_host, int server_port) {
513 client_state_t *state = client_state(transport);
514 if (!state || !state->initialized) {
515 SET_ERRNO(ERROR_INVALID_STATE, "Client is not initialized");
516 return -1;
517 }
518
519 if (!server_host || !server_host[0] || server_port <= 0 || server_port > 65535) {
520 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid client server address or port");
521 return -1;
522 }
523
524 // Set server IP and port in handshake context
525 SAFE_STRNCPY(state->crypto_handshake_ctx.server_ip, server_host, sizeof(state->crypto_handshake_ctx.server_ip));
526 state->crypto_handshake_ctx.server_port = server_port;
527
528 return 0;
529}
530
532 client_state_t *state = client_state(transport);
533 if (!state || state->crypto_handshake_ctx.state == CRYPTO_HANDSHAKE_DISABLED) {
534 SET_ERRNO(ERROR_INVALID_STATE, "Client handshake is not initialized");
535 return NULL;
536 }
538}
539
540// ============================================================================
541// Packet Processing API
542// ============================================================================
543
553int browser_client_encrypt_packet(browser_transport_t *transport, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext, size_t ciphertext_size, size_t *out_len) {
554 client_state_t *state = client_state(transport);
555 if (!state || !state->handshake_complete) {
556 SET_ERRNO(ERROR_INVALID_STATE, "Client handshake is not complete");
557 return -1;
558 }
559
560 const size_t overhead = 32 + CRYPTO_NONCE_SIZE + CRYPTO_MAC_SIZE;
561 if (!plaintext || !ciphertext || !out_len || plaintext_len > SIZE_MAX - overhead || ciphertext_size < plaintext_len + overhead) {
562 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid client encryption buffers or lengths");
563 return -1;
564 }
565 uint8_t *wire = NULL;
566 size_t length = 0;
567 packet_header_t header;
568 if (plaintext_len < sizeof(header)) {
569 SET_ERRNO(ERROR_INVALID_PARAM, "Client plaintext packet is shorter than its header");
570 return -1;
571 }
572 memcpy(&header, plaintext, sizeof(header));
574 asciichat_error_t result = acip_security_seal(&state->crypto_handshake_ctx.crypto_ctx, channel, ACIP_DELIVERY_RELIABLE, plaintext, plaintext_len, &wire, &length);
575 if (result == ASCIICHAT_OK) {
576 *out_len = length - sizeof(packet_header_t);
577 memcpy(ciphertext, wire + sizeof(packet_header_t), *out_len);
578 }
579 buffer_release(wire);
580 return result == ASCIICHAT_OK ? 0 : -1;
581}
582
592int browser_client_decrypt_packet(browser_transport_t *transport, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext, size_t plaintext_size, size_t *out_len) {
593 client_state_t *state = client_state(transport);
594 if (!state || !state->handshake_complete) {
595 SET_ERRNO(ERROR_INVALID_STATE, "Client handshake is not complete");
596 return -1;
597 }
598
599 if (!ciphertext || !plaintext || !out_len || plaintext_size < ciphertext_len) {
600 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid client decryption buffers or lengths");
601 return -1;
602 }
603 *out_len = 0;
604 uint8_t *plain = NULL;
605 size_t length = 0;
606 uint64_t sequence;
607 bool consumed = false;
608 asciichat_error_t result =
609 acip_security_decrypt(&state->crypto_handshake_ctx.crypto_ctx, CRYPTO_RECORD_ANY_CHANNEL, ACIP_DELIVERY_RELIABLE, ciphertext, ciphertext_len, &plain, &length, &sequence, &consumed);
610 if (result == ASCIICHAT_OK && !consumed) {
611 memcpy(plaintext, plain, length);
612 *out_len = length;
613 }
614 buffer_release(plain);
615 return result == ASCIICHAT_OK ? 0 : -1;
616}
617
618// ============================================================================
619// Connection State API
620// ============================================================================
621
627 client_state_t *state = client_state(transport);
628 if (!state)
629 return SET_ERRNO(ERROR_INVALID_STATE, "Client transport is not initialized");
630 state->handshake_complete = false;
634 /* Discovery's unencrypted protocol has no version acknowledgement. */
635 if (result == ASCIICHAT_OK && mode == ACIP_CRYPTO_NONE) {
636 state->handshake_complete = true;
638 }
639 return result;
640}
641asciichat_error_t browser_client_acds_handshake_receive(browser_transport_t *transport, uint32_t type, const void *payload, size_t length) {
642 client_state_t *state = client_state(transport);
643 if (!state)
644 return SET_ERRNO(ERROR_INVALID_STATE, "Client transport is not initialized");
645 asciichat_error_t result = acds_handshake_receive(&state->crypto_handshake_ctx, browser_transport_base(transport), type, payload, length);
646 if (result != ASCIICHAT_OK) {
648 return result;
649 }
651 state->handshake_complete = true;
654 } else {
656 }
657 return ASCIICHAT_OK;
658}
659
661int browser_client_resolve_crypto_policy(browser_transport_t *transport, bool secure, int encryption) {
662 client_state_t *state = client_state(transport);
663 if (!state)
664 return SET_ERRNO(ERROR_INVALID_STATE, "Client transport is not initialized");
665 crypto_policy_t policy = {
666 .transport_secure = secure,
667 .encrypt = encryption == 1,
668 .no_encrypt = encryption == 0,
669 .has_password = state->crypto_password[0] != '\0',
670 .has_identity = state->has_client_identity_key,
671 .has_verification_key = state->has_expected_server_identity_key,
672 };
673 uint8_t mode;
674 if (crypto_policy_resolve(&policy, &mode) != ASCIICHAT_OK)
675 return -1;
676 state->crypto_mode = mode;
677 return mode;
678}
679
681 client_state_t *state = client_state(transport);
682 if (!state)
683 return SET_ERRNO(ERROR_INVALID_STATE, "Client transport is not initialized");
684 state->handshake_complete = false;
686 state->version_received = false;
689}
690
691asciichat_error_t browser_client_handshake_receive(browser_transport_t *transport, uint32_t type, const void *payload, size_t length) {
692 client_state_t *state = client_state(transport);
693 if (!state)
694 return SET_ERRNO(ERROR_INVALID_STATE, "Client transport is not initialized");
695 if (!state->version_received && type != PACKET_TYPE_PROTOCOL_VERSION)
696 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Expected server protocol version first");
697 if (type == PACKET_TYPE_PROTOCOL_VERSION) {
698 if (state->version_received)
699 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Duplicate server protocol version");
700 if (!payload || length != sizeof(protocol_version_packet_t))
701 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid server protocol version");
702 const protocol_version_packet_t *version = payload;
704 return SET_ERRNO(ERROR_CRYPTO, "Server rejected requested security policy");
705 state->version_received = true;
706 if (state->crypto_mode == ACIP_CRYPTO_NONE) {
707 state->handshake_complete = true;
709 return ASCIICHAT_OK;
710 }
720 if (result != ASCIICHAT_OK || !state->has_expected_server_identity_key)
721 return result;
723 }
724 if (type == PACKET_TYPE_CRYPTO_PARAMETERS) {
725 if (!payload || length != sizeof(crypto_parameters_packet_t) || (((const crypto_parameters_packet_t *)payload)->selected_cipher != CIPHER_ALGO_NONE) != ACIP_CRYPTO_HAS_ENCRYPT(state->crypto_mode))
726 return SET_ERRNO(ERROR_CRYPTO, "Server changed requested payload encryption");
727 }
728 return browser_client_acds_handshake_receive(transport, type, payload, length);
729}
730
732 client_state_t *state = client_state(transport);
733 return state && state->handshake_complete && browser_transport_state(transport) == BROWSER_TRANSPORT_CONNECTED;
734}
735
737 client_state_t *state = client_state(transport);
738 if (state) {
739 state->handshake_complete = false;
740 state->version_received = false;
741 }
742}
743
744/* Browser transport marshals framing, then invokes the SAME network content
745 * contract as native before any terminal parser or recording receives bytes. */
747 const void *metadata, size_t metadata_length) {
748 client_state_t *state = client_state(transport);
749 if (!state)
750 return SET_ERRNO(ERROR_INVALID_STATE, "Browser client transport is not initialized");
752 return SET_ERRNO(ERROR_INVALID_FRAME, "Unknown browser frame flags");
753 acip_render_settings_t settings;
754 uint32_t effects = 0;
755 bool contract = (flags & FRAME_FLAG_RENDER_CONTRACT) != 0;
756 if (contract) {
757 size_t consumed;
758 asciichat_error_t decoded = frame_render_contract_decode(metadata, metadata_length, &settings, &effects, &consumed);
759 if (decoded != ASCIICHAT_OK)
760 return decoded;
761 if (settings.revision && settings.revision == state->remote_render_settings.revision && state->remote_render_settings.palette[0] && state->remote_render_settings.caps.utf8_support &&
762 strcmp(settings.palette, state->remote_render_settings.palette) != 0)
763 return SET_ERRNO(ERROR_INVALID_FRAME, "Browser frame palette contradicts acknowledged revision");
764 if (consumed != metadata_length)
765 return SET_ERRNO(ERROR_INVALID_FRAME, "Trailing browser frame contract bytes");
766 } else if (metadata_length) {
767 return SET_ERRNO(ERROR_INVALID_FRAME, "Unexpected browser frame contract");
768 }
769 if (!text || !length || length > FRAME_RENDER_MAX_BYTES || asciichat_crc32(text, length) != checksum)
770 return SET_ERRNO(ERROR_INVALID_FRAME, "Browser frame length/checksum mismatch");
771 return session_frame_validate_contract(text, length, width, height, contract ? &settings : NULL, effects);
772}
773
774asciichat_error_t browser_client_decode_frame_data(const void *encoded, size_t encoded_length, void *output, size_t output_length) {
775 if (!encoded || !output || !encoded_length || encoded_length > FRAME_RENDER_MAX_BYTES || !output_length || output_length > FRAME_RENDER_MAX_BYTES)
776 return SET_ERRNO(ERROR_INVALID_FRAME, "Invalid browser frame decompression bounds");
777 return decompress_data_exact(encoded, encoded_length, output, output_length);
778}
asciichat_error_t acds_handshake_begin(acip_transport_t *transport, uint8_t mode)
asciichat_error_t acds_handshake_receive(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t type, const void *payload, size_t length)
ANSI escape sequence utilities and fast color code generation.
void errno_destroy(void)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
void browser_transport_set_client_state(browser_transport_t *browser, void *state)
size_t browser_transport_output_size(browser_transport_t *browser)
acip_transport_t * browser_transport_base(browser_transport_t *browser)
void * browser_transport_client_state(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_output_pop(browser_transport_t *browser)
#define buffer_release(data)
Definition buffer.h:99
📦 Network Packet Compression Utilities
Hardware-Accelerated CRC32 Checksum Computation.
asciichat_error_t crypto_handshake_init(const char *name, crypto_handshake_context_t *ctx, bool is_server)
Initialize named crypto handshake context.
void crypto_handshake_destroy(crypto_handshake_context_t *ctx)
Cleanup crypto handshake context with secure memory wiping.
#define HOST_TO_NET_U16(val)
Definition endian.h:100
#define NET_TO_HOST_U16(val)
Definition endian.h:115
asciichat_error_t audio_visualization_fft_init(void)
Definition fft.c:82
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
asciichat_error_t frame_render_contract_decode(const void *wire, size_t available, acip_render_settings_t *settings, uint32_t *effects, size_t *length)
asciichat_error_t session_frame_validate_contract(const char *text, size_t length, uint32_t width, uint32_t height, const acip_render_settings_t *settings, uint32_t effects)
void ansi_fast_init(void)
Definition ansi.c:226
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
asciichat_error_t asciichat_shared_init(const char *log_file, bool is_client, bool quiet_startup)
Initialize common subsystems shared by client and server.
Definition common.c:131
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
asciichat_error_t decompress_data_exact(const void *input, size_t input_size, void *output, size_t expected_size)
crypto_result_t
Cryptographic operation result codes.
crypto_result_t crypto_derive_password_key(crypto_context_t *ctx, const char *password)
Derive key from password using Argon2id.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_NETWORK_SIZE
Definition error_codes.h:81
@ ERROR_INVALID_FRAME
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
key_type_t type
Definition key_types.h:102
bool use_gpg_agent
Definition key_types.h:108
bool use_ssh_agent
Definition key_types.h:107
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:109
asciichat_error_t parse_ssh_private_key(const char *key_path, private_key_t *key_out)
Parse SSH Ed25519 private key from file.
Definition ssh_keys.c:967
key_type_t type
Definition key_types.h:77
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_ED25519
Definition key_types.h:58
void log_init(const char *filename, log_level_t level, bool force_stderr, bool use_mmap)
Initialize the logging system.
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
asciichat_error_t log_set_format(const char *format_str, bool console_only)
Set a custom log format string.
asciichat_error_t packet_validate(const void *packet, size_t length, size_t limit, packet_header_t *output)
Definition packet.c:81
#define AUTH_ALGO_ED25519
Ed25519 authentication (Edwards-curve signatures).
Definition packet.h:1140
asciichat_error_t packet_encode(packet_type_t type, const void *payload, size_t length, uint32_t client_id, void *output, size_t capacity, size_t *written)
Definition packet.c:63
#define ACIP_CRYPTO_NONE
No encryption, no authentication (plaintext only).
Definition packet.h:1157
#define ACIP_CRYPTO_HAS_AUTH(mode)
Check if crypto mode includes authentication.
Definition packet.h:1174
#define KEX_ALGO_X25519
X25519 key exchange (Curve25519).
Definition packet.h:1139
#define ACIP_CRYPTO_HAS_ENCRYPT(mode)
Check if crypto mode includes payload encryption.
Definition packet.h:1167
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define AUTH_ALGO_NONE
No authentication (plaintext mode).
Definition packet.h:1141
#define ACIP_CRYPTO_ENCRYPT
Encryption only (no identity verification).
Definition packet.h:1158
#define CIPHER_ALGO_NONE
No encryption (plaintext mode).
Definition packet.h:1143
#define CIPHER_ALGO_XSALSA20_POLY1305
XSalsa20-Poly1305 authenticated encryption.
Definition packet.h:1142
@ PACKET_TYPE_CRYPTO_CLIENT_HELLO
Client -> Server: Expected server key fingerprint for multi-key selection (UNENCRYPTED).
Definition packet.h:328
@ PACKET_TYPE_PROTOCOL_VERSION
Protocol version and capabilities negotiation.
Definition packet.h:317
@ PACKET_TYPE_CRYPTO_PARAMETERS
Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).
Definition packet.h:338
@ PACKET_TYPE_CRYPTO_CAPABILITIES
Client -> Server: Supported crypto algorithms (UNENCRYPTED).
Definition packet.h:336
#define GET_OPTION(field)
Definition options.h:1333
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments with unified mode detection.
Definition options.c:2291
#define OPT_LOG_TEMPLATE_DEFAULT_DEBUG
Default log format string - debug mode (verbose with thread name, file relative path,...
Definition options.h:373
#define PROTOCOL_VERSION_MAJOR
Major protocol version number.
#define FRAME_FLAG_RENDER_CONTRACT
Explicit versioned render contract precedes encoded ASCII text.
#define FRAME_FLAG_IS_COMPRESSED
Frame data is compressed.
#define asciichat_crc32(data, len)
Main CRC32 dispatcher macro - use this in application code.
Definition crc32.h:151
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Common declarations and data structures for cryptographic handshake.
Transport abstraction layer for ACIP protocol.
struct browser_transport browser_transport_t
asciichat_error_t acip_render_settings_prepare(acip_render_settings_t *candidate, const options_t *values)
asciichat_error_t acip_settings_decode(const void *payload, size_t length, acip_settings_header_t *header, const char **json, size_t *json_length)
void acip_render_settings_options(const acip_render_settings_t *state, options_t *values)
bool browser_client_ready(browser_transport_t *transport)
int browser_client_init(browser_transport_t *transport)
struct client_state client_state_t
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)
int browser_client_parse_ssh_private_key(const char *key_path, uint8_t *secret_key_out)
int browser_client_parse_gpg_private_key_binary(const uint8_t *key_data, size_t key_data_len, uint8_t *secret_key_out)
int browser_client_parse_gpg_public_key_binary(const uint8_t *key_data, size_t key_data_len, uint8_t *public_key_out)
int browser_client_parse_gpg_private_key(const char *armored_key, uint8_t *secret_key_out)
asciichat_error_t browser_client_settings_receive(browser_transport_t *transport, const void *payload, size_t length)
int browser_client_decrypt_packet(browser_transport_t *transport, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext, size_t plaintext_size, size_t *out_len)
int browser_client_parse_gpg_public_key(const char *armored_key, uint8_t *public_key_out)
asciichat_error_t browser_client_decode_frame_data(const void *encoded, size_t encoded_length, void *output, size_t output_length)
#define WEB_CLIENT_CRYPTO_PASSWORD_BUFFER_SIZE
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)
asciichat_error_t browser_client_acds_handshake_receive(browser_transport_t *transport, uint32_t type, const void *payload, size_t length)
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_parse_ssh_public_key(const char *key_line, uint8_t *public_key_out)
asciichat_error_t browser_client_handshake_receive(browser_transport_t *transport, uint32_t type, const void *payload, size_t length)
int browser_client_get_crypto_error_message(char *output, size_t output_size)
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)
int browser_client_encrypt_packet(browser_transport_t *transport, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext, size_t ciphertext_size, size_t *out_len)
const uint8_t * browser_client_public_key_bytes(browser_transport_t *transport)
📝 Logging API with multiple log levels and terminal output control
Magic number validation constants and macros.
asciichat_error_t acip_security_seal(crypto_context_t *crypto, acip_traffic_class_t flow, acip_delivery_t delivery, const void *packet, size_t length, uint8_t **output, size_t *written)
asciichat_error_t acip_security_decrypt(crypto_context_t *crypto, unsigned flow, unsigned delivery, const void *payload, size_t length, uint8_t **output, size_t *written, uint64_t *sequence, bool *consumed)
asciichat_error_t openpgp_parse_armored_seckey(const char *armored_text, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t ed25519_sk[ED25519_SEED_SIZE])
Definition openpgp.c:733
asciichat_error_t openpgp_parse_binary_pubkey(const uint8_t *data, size_t data_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:280
asciichat_error_t openpgp_parse_binary_seckey(const uint8_t *data, size_t data_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t ed25519_sk[ED25519_SEED_SIZE])
Definition openpgp.c:702
asciichat_error_t openpgp_parse_armored_pubkey(const char *armored_text, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:307
OpenPGP (RFC 4880) packet format parser.
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
asciichat_error_t packet_parse_envelope(const void *wire, size_t length, void *crypto_ctx, packet_envelope_t *out)
Parse one complete wire packet using the shared client receive path.
Definition packet.c:686
void packet_envelope_release(packet_envelope_t *envelope)
Definition packet.c:711
asciichat_error_t crypto_policy_resolve(const crypto_policy_t *policy, uint8_t *mode)
Definition policy.c:4
char * options_values_json(const options_t *values, bool remote_only)
Definition rcu.c:1001
asciichat_error_t options_prepare_json(const options_t *current, const char *json, size_t length, options_t *candidate, bool remote_only)
Definition rcu.c:977
#define CRYPTO_RECORD_ANY_CHANNEL
Definition record.h:15
#define FRAME_RENDER_MAX_BYTES
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
ACIP shared/bidirectional packet sending functions.
#define CRYPTO_NONCE_SIZE
Nonce size (XSalsa20).
Definition sizes.h:83
#define CRYPTO_MAC_SIZE
MAC size (Poly1305).
Definition sizes.h:89
asciichat_error_t parse_ssh_ed25519_line(const char *line, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition ssh_keys.c:165
🔤 String Manipulation and Shell Escaping Utilities
acip render settings keeps the values that move through the subsystem: caps, width,...
acip settings header keeps the values that move through the subsystem: schema, request,...
crypto_context_t * crypto_ctx
Optional encryption context.
uint8_t client_identity_key[crypto_sign_SECRETKEYBYTES]
crypto_handshake_context_t crypto_handshake_ctx
uint8_t expected_server_identity_key[crypto_sign_PUBLICKEYBYTES]
acip_render_settings_t remote_render_settings
Crypto capabilities packet structure (Packet Type 14).
Definition packet.h:1027
uint8_t preferred_auth
Preferred authentication algorithm (AUTH_ALGO_*).
Definition packet.h:1039
uint16_t supported_auth_algorithms
Supported authentication algorithms bitmask (AUTH_ALGO_*).
Definition packet.h:1031
uint16_t supported_kex_algorithms
Supported key exchange algorithms bitmask (KEX_ALGO_*).
Definition packet.h:1029
uint8_t preferred_cipher
Preferred cipher algorithm (CIPHER_ALGO_*).
Definition packet.h:1041
uint16_t supported_cipher_algorithms
Supported cipher algorithms bitmask (CIPHER_ALGO_*).
Definition packet.h:1033
uint8_t preferred_kex
Preferred key exchange algorithm (KEX_ALGO_*).
Definition packet.h:1037
uint8_t requires_verification
Server verification requirement flag (1=required, 0=optional).
Definition packet.h:1035
Cryptographic handshake context structure.
Crypto parameters packet structure (Packet Type 15).
Definition packet.h:1056
The useful part of crypto policy is in transport_secure, encrypt, no_encrypt, no_auth: together they ...
Definition policy.h:17
Packet envelope containing received packet data.
Definition packet.h:1204
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
Protocol version negotiation packet structure (Packet Type 1).
Definition packet.h:871
uint16_t protocol_version
Major protocol version (must match for compatibility).
Definition packet.h:873
uint8_t supports_encryption
Encryption & authentication mode bitmask (ACIP_CRYPTO_* constants: NONE, ENCRYPT, AUTH,...
Definition packet.h:879
acip_traffic_class_t acip_packet_traffic_class(uint16_t type)
Definition traffic.c:4
acip_traffic_class_t
Definition traffic.h:9
@ ACIP_DELIVERY_RELIABLE
Definition traffic.h:16
📊 String Formatting Utilities