ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
packet.c
Go to the documentation of this file.
1
6
11#include <ascii-chat/common.h>
12#include <recast/defer.h>
15#include <libplatform/socket.h>
16#include <libplatform/thread.h>
17#include <ascii-chat/buffer.h>
24#include <ascii-chat/source_root.h>
26#include <options/options.h>
27#include <options/rcu.h> // For RCU-based options access
28#include <stdint.h>
29#include <errno.h>
30#include <stdbool.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34
35// Network timeout constants are defined in packet_types.h
36
38 if (!version)
39 return;
40 memset(version, 0, sizeof(*version));
44 version->supports_encryption = supports_encryption;
45}
46
47asciichat_error_t packet_header_build(packet_header_t *header, packet_type_t type, const socket_buffer_t *payload, size_t count, uint32_t client_id) {
48 if (!header || (!payload && count) || count > SOCKET_IOV_MAX)
49 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet header arguments");
50 size_t length = 0;
51 uint32_t crc = 0;
52 for (size_t i = 0; i < count; ++i) {
53 if ((!payload[i].data && payload[i].len) || payload[i].len > MAX_PACKET_SIZE - length)
54 return SET_ERRNO(ERROR_NETWORK_SIZE, "Invalid packet payload size");
55 length += payload[i].len;
56 crc = asciichat_crc32_update(crc, payload[i].data, payload[i].len);
57 }
58 *header = (packet_header_t){
59 .magic = HOST_TO_NET_U64(PACKET_MAGIC), .type = HOST_TO_NET_U16(type), .length = HOST_TO_NET_U32((uint32_t)length), .crc32 = HOST_TO_NET_U32(crc), .client_id = HOST_TO_NET_U32(client_id)};
60 return ASCIICHAT_OK;
61}
62
63asciichat_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) {
64 if (!output || !written)
65 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing packet output");
66 *written = 0;
67 if (capacity < sizeof(packet_header_t) || length > capacity - sizeof(packet_header_t))
68 return SET_ERRNO(ERROR_NETWORK_SIZE, "Packet output is too small");
69 socket_buffer_t slice = {payload, length};
70 packet_header_t header;
71 asciichat_error_t result = packet_header_build(&header, type, &slice, 1, client_id);
72 if (result != ASCIICHAT_OK)
73 return result;
74 if (length)
75 memmove((uint8_t *)output + sizeof(header), payload, length);
76 memcpy(output, &header, sizeof(header));
77 *written = sizeof(header) + length;
78 return ASCIICHAT_OK;
79}
80
81asciichat_error_t packet_validate(const void *packet, size_t length, size_t limit, packet_header_t *output) {
82 if (!packet || length < sizeof(packet_header_t))
83 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Incomplete packet header");
84 packet_header_t header;
85 memcpy(&header, packet, sizeof(header));
86 size_t payload = length - sizeof(header);
87 if (NET_TO_HOST_U64(header.magic) != PACKET_MAGIC || NET_TO_HOST_U32(header.length) != payload || payload > (limit ? limit : MAX_PACKET_SIZE))
88 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid packet framing or size");
89 if (asciichat_crc32((const uint8_t *)packet + sizeof(header), payload) != NET_TO_HOST_U32(header.crc32))
90 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Packet CRC mismatch");
91 if (output)
92 *output = header;
93 return ASCIICHAT_OK;
94}
95
96/* ============================================================================
97 * Packet Protocol Implementation
98 * ============================================================================
99 * This module handles packet verification, CRC validation, and protocol
100 * compliance checking for all network packets.
101 */
102
103// Use network_network_is_test_environment() from network.h
104
111uint64_t packet_send_timeout_ns(size_t packet_size) {
112 uint64_t base_timeout = SEND_TIMEOUT * NS_PER_SEC_INT;
113
114 // For large packets, increase timeout proportionally
115 if (packet_size > LARGE_PACKET_THRESHOLD) {
116 // Add extra timeout per MB above the threshold
117 uint64_t extra_timeout = (uint64_t)(((double)packet_size - LARGE_PACKET_THRESHOLD) / 1000000.0 * LARGE_PACKET_EXTRA_TIMEOUT_PER_MB) + NS_PER_MS_INT;
118 uint64_t total_timeout = base_timeout + extra_timeout;
119
120 // Ensure client timeout is longer than server's RECV_TIMEOUT (30s) to prevent deadlock
121 // Add 10 seconds buffer to account for server processing delays
122 if (total_timeout < MIN_CLIENT_TIMEOUT) {
123 total_timeout = MIN_CLIENT_TIMEOUT;
124 }
125
126 // Cap at maximum timeout
127 return (total_timeout > MAX_CLIENT_TIMEOUT) ? MAX_CLIENT_TIMEOUT : total_timeout;
128 }
129
130 return base_timeout;
131}
132
141static asciichat_error_t packet_validate_header(const packet_header_t *header, uint16_t *pkt_type, uint32_t *pkt_len, uint32_t *expected_crc) {
142 if (!header || !pkt_type || !pkt_len || !expected_crc) {
143 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: header=%p, pkt_type=%p, pkt_len=%p, expected_crc=%p", header, pkt_type, pkt_len, expected_crc);
144 }
145
146 // First validate packet length BEFORE converting from network byte order
147 // This prevents potential integer overflow issues
148 uint32_t pkt_len_network = header->length;
149 if (pkt_len_network == 0xFFFFFFFF) {
150 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid packet length in network byte order: 0xFFFFFFFF");
151 }
152
153 // Convert from network byte order using safe helpers
154 uint64_t magic = endian_unpack_u64(header->magic);
155 uint16_t type = endian_unpack_u16(header->type);
156 uint32_t len = endian_unpack_u32(pkt_len_network);
157 uint32_t crc = endian_unpack_u32(header->crc32);
158
159 // Validate magic
160 if (magic != PACKET_MAGIC) {
161 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid packet magic: 0x%x (expected 0x%x)", magic, PACKET_MAGIC);
162 }
163
164 // Validate packet size with bounds checking
165 if (len > MAX_PACKET_SIZE) {
166 return SET_ERRNO(ERROR_NETWORK_SIZE, "Packet too large: %u > %d", len, MAX_PACKET_SIZE);
167 }
168
169 // Validate packet type and size constraints
170 switch (type) {
172 // Protocol version packet has fixed size
173 if (len != sizeof(protocol_version_packet_t)) {
174 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid protocol version packet size: %u, expected %zu", len, sizeof(protocol_version_packet_t));
175 }
176 break;
178 // ASCII frame contains header + frame data
179 if (len < sizeof(ascii_frame_packet_t)) {
180 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid ASCII frame packet size: %u, minimum %zu", len, sizeof(ascii_frame_packet_t));
181 }
182 break;
184 // Image frame contains header + pixel data
185 if (len < sizeof(image_frame_packet_t)) {
186 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid image frame packet size: %u, minimum %zu", len, sizeof(image_frame_packet_t));
187 }
188 break;
190 // Batch must have at least header + some samples
191 if (len < sizeof(audio_batch_packet_t) + sizeof(float)) {
192 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid audio batch packet size: %u", len);
193 }
194 break;
195 case PACKET_TYPE_PING:
196 case PACKET_TYPE_PONG:
197 if (len != 0) { // Ping/pong are just header packets and no payload.
198 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid ping/pong packet size: %u", len);
199 }
200 break;
202 // Client capabilities packet can be empty or contain capability data
203 if (len > 1024) { // Reasonable limit for capability data
204 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid client capabilities packet size: %u", len);
205 }
206 break;
208 if (len != sizeof(client_info_packet_t)) {
209 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid client join packet size: %u, expected %zu", len, sizeof(client_info_packet_t));
210 }
211 break;
213 // Client leave packet can be empty or contain reason
214 if (len > 256) {
215 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid client leave packet size: %u", len);
216 }
217 break;
220 if (len != sizeof(uint32_t)) {
221 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid stream control packet size: %u, expected %zu", len, sizeof(uint32_t));
222 }
223 break;
225 // Size message format: "SIZE:width,height"
226 if (len == 0 || len > 32) { // Reasonable size for "SIZE:1234,5678"
227 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid size message packet size: %u", len);
228 }
229 break;
231 // Audio message format: "AUDIO:num_samples"
232 if (len == 0 || len > 32) { // Reasonable size for "AUDIO:1234"
233 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid audio message packet size: %u", len);
234 }
235 break;
237 // Text message can be empty or contain message
238 if (len > 1024) { // Reasonable limit for text messages
239 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid text message packet size: %u", len);
240 }
241 break;
243 if (len < sizeof(error_packet_t)) {
244 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid error packet size: %u (minimum %zu)", len, sizeof(error_packet_t));
245 }
246 if (len > sizeof(error_packet_t) + MAX_ERROR_MESSAGE_LENGTH) {
247 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Error packet message too large: %u (max %zu)", len, sizeof(error_packet_t) + (size_t)MAX_ERROR_MESSAGE_LENGTH);
248 }
249 break;
250 // All crypto handshake packet types - validate using session parameters
263 // Crypto packets are validated by the crypto handshake context
264 // This is just a basic sanity check for extremely large packets
265 if (len > 65536) { // 64KB should be enough for even large post-quantum crypto packets
266 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Crypto packet too large: %u bytes (max 65536)", len);
267 }
268 // Note: Proper size validation is done in crypto_handshake_validate_packet_size()
269 // which uses the session's crypto parameters for accurate validation
270 break;
271 // ACIP protocol packets (Discovery Service)
294 // ACIP packets - basic size validation
295 // Discovery service packets can vary in size (variable-length strings, etc.)
296 if (len > 65536) { // 64KB max for discovery packets
297 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "ACIP packet too large: %u bytes (max 65536)", len);
298 }
299 break;
300 default:
301 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Unknown packet type: %u", type);
302 }
303
304 // Return parsed values
305 *pkt_type = type;
306 *pkt_len = len;
307 *expected_crc = crc;
308
309 return ASCIICHAT_OK;
310}
311
319static asciichat_error_t packet_validate_crc32(const void *data, size_t len, uint32_t expected_crc) {
320 if (!data && len > 0) {
321 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: data=%p but len=%zu", data, len);
322 }
323
324 if (len == 0) {
325 // Empty packets should have CRC32 of 0
326 if (expected_crc != 0) {
327 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid CRC32 for empty packet: 0x%x (expected 0)", expected_crc);
328 }
329 return 0;
330 }
331
332 uint32_t calculated_crc = asciichat_crc32(data, len);
333 if (calculated_crc != expected_crc) {
334 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "CRC32 mismatch: calculated 0x%x, expected 0x%x", calculated_crc, expected_crc);
335 }
336
337 return ASCIICHAT_OK;
338}
339
348asciichat_error_t packet_send(socket_t sockfd, packet_type_t type, const void *data, size_t len) {
349 if (sockfd == INVALID_SOCKET_VALUE) {
350 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket descriptor");
351 }
352
353 if (len > MAX_PACKET_SIZE) {
354 return SET_ERRNO(ERROR_NETWORK_SIZE, "Packet too large: %zu > %d", len, MAX_PACKET_SIZE);
355 }
356
357 if (len && !data)
358 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing packet payload");
359 packet_header_t header = {.magic = HOST_TO_NET_U64(PACKET_MAGIC),
360 .type = HOST_TO_NET_U16((uint16_t)type),
361 .length = HOST_TO_NET_U32((uint32_t)len),
362 .crc32 = HOST_TO_NET_U32(len > 0 ? asciichat_crc32(data, len) : 0),
363 .client_id = HOST_TO_NET_U32(0)}; // Always initialize client_id to 0 in network byte order
364
365 // Calculate timeout based on packet size (in nanoseconds)
366 uint64_t timeout = packet_send_timeout_ns(len);
367
368 socket_buffer_t slices[] = {{&header, sizeof(header)}, {data, len}};
369 asciichat_error_t result = socket_sendv_all(sockfd, slices, 2, timeout);
370 if (result != ASCIICHAT_OK)
371 return result;
372
373#ifdef DEBUG_NETWORK
374 log_debug_every(US_PER_SEC_INT, "Sent packet type=%d, len=%zu, errno=%d (%s)", type, len, errno, SAFE_STRERROR(errno));
375#endif
376
377 return 0;
378}
379
388asciichat_error_t packet_receive(socket_t sockfd, packet_type_t *type, void **data, size_t *len) {
389 if (sockfd == INVALID_SOCKET_VALUE) {
390 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket descriptor");
391 }
392 if (!type || !data || !len) {
393 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: type=%p, data=%p, len=%p", type, data, len);
394 }
395
396 // Read packet header into memory from network socket
397 packet_header_t header;
398 uint64_t header_timeout_ns = RECV_TIMEOUT * NS_PER_SEC_INT;
399 ssize_t received = recv_with_timeout(sockfd, &header, sizeof(header), header_timeout_ns);
400 if (received < 0) {
401 // Error context is already set by recv_with_timeout
402 return ERROR_NETWORK;
403 }
404 if ((size_t)received != sizeof(header)) {
405 if (received == 0) {
406 log_warn("Connection closed while reading packet header");
407 return SET_ERRNO(ERROR_NETWORK, "Connection closed by peer while reading packet header");
408 }
409
410 return SET_ERRNO(ERROR_NETWORK, "Partial packet header received: %zd/%zu bytes", received, sizeof(header));
411 }
412
413 // Validate packet header
414 uint16_t pkt_type;
415 uint32_t pkt_len;
416 uint32_t expected_crc;
417 if (packet_validate_header(&header, &pkt_type, &pkt_len, &expected_crc) != ASCIICHAT_OK) {
418 // Error context is already set by packet_validate_header
420 }
421
422 // Allocate buffer for payload
423 void *payload = NULL;
424 defer_named(release_payload, buffer_release(payload));
425 if (pkt_len > 0) {
426 payload = buffer_alloc(packet_is_handshake_type(pkt_type) || pkt_type == PACKET_TYPE_ERROR_MESSAGE ? buffer_control_domain() : NULL, pkt_len);
427 if (!payload)
428 return SET_ERRNO(ERROR_MEMORY, "Packet payload exceeds buffer budget");
429
430 // Use adaptive timeout for large packets
431 uint64_t recv_timeout = packet_send_timeout_ns(pkt_len);
432 received = recv_with_timeout(sockfd, payload, pkt_len, recv_timeout);
433 if (received < 0) {
434 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to receive packet payload");
435 }
436 if (received != (ssize_t)pkt_len) {
437 return SET_ERRNO(ERROR_NETWORK, "Partial packet payload received: %zd/%u bytes", received, pkt_len);
438 }
439
440 // Validate CRC32
441 if (packet_validate_crc32(payload, pkt_len, expected_crc) != ASCIICHAT_OK) {
442 // Error context is already set by packet_validate_crc32
444 }
445 }
446
447 // Return results
448 *type = (packet_type_t)pkt_type;
449 *data = payload;
450 defer_cancel(release_payload);
451 *len = pkt_len;
452
453 return ASCIICHAT_OK;
454}
455
456/* ============================================================================
457 * High-Level Secure Packet Functions
458 * ============================================================================
459 * These functions handle encryption and compression for secure communication.
460 */
461
471asciichat_error_t send_packet_secure(socket_t sockfd, packet_type_t type, const void *data, size_t len, crypto_context_t *crypto_ctx) {
472 if (sockfd == INVALID_SOCKET_VALUE)
473 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet socket");
474 if (len > MAX_PACKET_SIZE) {
475 return SET_ERRNO(ERROR_NETWORK_SIZE, "Packet too large: %zu > %d", len, MAX_PACKET_SIZE);
476 }
477
478 if (!data && len > 0) {
479 return SET_ERRNO(ERROR_INVALID_PARAM, "Packet payload is NULL with nonzero length");
480 }
481
482 // Handshake packets are ALWAYS sent unencrypted
483 if (packet_is_initial_handshake_type(type)) {
484 return packet_send(sockfd, type, data, len);
485 }
486
487 // Apply compression if beneficial for large packets
488 const void *final_data = data;
489 size_t final_len = len;
490 void *compressed_data = NULL;
491
492 // Skip compression for pre-compressed data (Opus audio) or if --no-compress flag is set
493 bool should_skip_compression = packet_is_precompressed(type) || GET_OPTION(no_compress);
494 if (!should_skip_compression && len > COMPRESSION_MIN_SIZE && should_compress(len, len)) {
495 void *temp_compressed = NULL;
496 size_t compressed_size = 0;
497
498 // Use configured compression level from options (default: 1 for fastest compression)
499 int compression_level = (GET_OPTION(compression_level) > 0) ? GET_OPTION(compression_level) : 1;
500 asciichat_error_t compress_result = compress_data(data, len, &temp_compressed, &compressed_size, compression_level);
501 if (compress_result == ASCIICHAT_OK) {
502 double ratio = (double)compressed_size / (double)len;
503 if (ratio < COMPRESSION_RATIO_THRESHOLD) {
504 final_data = temp_compressed;
505 final_len = compressed_size;
506 compressed_data = temp_compressed;
507 log_debug_every(US_PER_SEC_INT, "Compressed packet: %zu -> %zu bytes (%.1f%%)", len, compressed_size, ratio * 100.0);
508 } else {
509 buffer_release(temp_compressed);
510 }
511 }
512 }
513
514 // If no crypto context or crypto not ready, send unencrypted
515 bool ready = crypto_ctx ? crypto_is_ready(crypto_ctx) : false;
516 if (!crypto_ctx || !ready || !crypto_ctx->encrypt_data) {
517 log_warn_every(LOG_RATE_FAST, "CRYPTO_DEBUG: Sending packet type %d UNENCRYPTED (crypto_ctx=%p, ready=%d)", type, (void *)crypto_ctx, ready);
518 asciichat_error_t result = packet_send(sockfd, type, final_data, final_len);
519 if (compressed_data) {
520 buffer_release(compressed_data);
521 }
522 if (result != ASCIICHAT_OK) {
523 SET_ERRNO(ERROR_NETWORK, "Failed to send packet: %s", asciichat_error_string(result));
524 }
525 return result;
526 }
527
528 socket_buffer_t payload = {final_data, final_len};
529 packet_header_t header;
530 asciichat_error_t result = packet_header_build(&header, type, &payload, 1, 0);
531 socket_buffer_t slices[] = {{&header, sizeof(header)}, payload};
533 if (result == ASCIICHAT_OK)
534 result = acip_packet_plan(crypto_ctx, slices, 2, &plan);
535 uint8_t *ciphertext = NULL;
536 if (result == ASCIICHAT_OK) {
537 ciphertext = buffer_alloc(plan.domain, plan.ciphertext_capacity);
538 if (!ciphertext)
539 result = SET_ERRNO(ERROR_MEMORY, "Cannot allocate packet ciphertext");
540 }
541 if (result == ASCIICHAT_OK) {
542 packet_header_t outer;
543 size_t length = 0;
544 result = acip_packet_encrypt(crypto_ctx, &plan, plan.domain, ciphertext, plan.ciphertext_capacity, &outer, &length);
545 if (result == ASCIICHAT_OK) {
546 socket_buffer_t wire[] = {{&outer, sizeof(outer)}, {ciphertext, length}};
547 result = socket_sendv_all(sockfd, wire, 2, packet_send_timeout_ns(sizeof(outer) + length));
548 }
549 }
550 buffer_release(ciphertext);
551 buffer_release(compressed_data);
552 return result;
553}
554
563packet_recv_result_t receive_packet_secure(socket_t sockfd, void *crypto_ctx, bool enforce_encryption, packet_envelope_t *envelope) {
564 return receive_packet_secure_with_timeout(sockfd, crypto_ctx, enforce_encryption, envelope, RECV_TIMEOUT * NS_PER_SEC_INT);
565}
566
567/* ============================================================================
568 * Basic Packet Functions (Non-Secure)
569 * ============================================================================
570 * These are the basic packet send/receive functions without encryption.
571 */
572
581int send_packet(socket_t sockfd, packet_type_t type, const void *data, size_t len) {
582 asciichat_error_t result = packet_send(sockfd, type, data, len);
583 return result == ASCIICHAT_OK ? 0 : -1;
584}
585
594int receive_packet(socket_t sockfd, packet_type_t *type, void **data, size_t *len) {
595 asciichat_error_t result = packet_receive(sockfd, type, data, len);
596 return result == ASCIICHAT_OK ? 0 : -1;
597}
598
599/* ============================================================================
600 * Protocol Message Functions
601 * ============================================================================
602 * These functions send specific protocol messages.
603 */
604
611 return send_packet(sockfd, PACKET_TYPE_PING, NULL, 0);
612}
613
620 return send_packet(sockfd, PACKET_TYPE_PONG, NULL, 0);
621}
622
640 if (!envelope) {
641 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid envelope");
642 }
643
644 // Only decrypt if this is an encrypted packet
645 if (envelope->type != PACKET_TYPE_ENCRYPTED) {
646 return ASCIICHAT_OK; // Not encrypted, nothing to do
647 }
648
649 if (!crypto_ctx) {
650 return SET_ERRNO(ERROR_CRYPTO, "Received encrypted packet but no crypto context");
651 }
652
653 uint8_t *plaintext = NULL;
654 size_t plaintext_length = 0;
655 bool consumed = false;
656 asciichat_error_t result = acip_security_decrypt(crypto_ctx, CRYPTO_RECORD_ANY_CHANNEL, CRYPTO_RECORD_RELIABLE, envelope->data, envelope->len, &plaintext, &plaintext_length, NULL, &consumed);
657 if (result != ASCIICHAT_OK)
658 return result;
659 if (!plaintext || plaintext_length < sizeof(packet_header_t)) {
660 buffer_release(plaintext);
661 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Decrypted packet is smaller than its header");
662 }
663
664 packet_header_t header;
665 memcpy(&header, plaintext, sizeof(header));
666 // Keep the decrypted buffer separate from the received ciphertext buffer.
667 // Transport implementations may share or recycle their receive allocation;
668 // overwriting it here makes the lifetime and capacity metadata ambiguous.
669 // The envelope owns one plaintext allocation after this point.
670 void *received_buffer = envelope->allocated_buffer;
671 if (received_buffer && received_buffer != plaintext) {
672 if (buffer_is_unique(received_buffer))
673 sodium_memzero(received_buffer, buffer_capacity(received_buffer));
674 buffer_release(received_buffer);
675 }
676 envelope->type = NET_TO_HOST_U16(header.type);
677 envelope->data = plaintext + sizeof(header);
678 envelope->len = plaintext_length - sizeof(header);
679 envelope->allocated_buffer = plaintext;
680 envelope->allocated_size = buffer_capacity(plaintext);
681 envelope->was_encrypted = true;
682 envelope->consumed = consumed;
683 return ASCIICHAT_OK;
684}
685
686asciichat_error_t packet_parse_envelope(const void *wire, size_t length, void *crypto_ctx, packet_envelope_t *out) {
687 if (!wire || !out || length < sizeof(packet_header_t) || length - sizeof(packet_header_t) > MAX_PACKET_SIZE)
688 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet envelope input");
689 *out = (packet_envelope_t){0};
690 packet_header_t wire_header;
691 asciichat_error_t result = packet_validate(wire, length, 0, &wire_header);
692 if (result != ASCIICHAT_OK)
693 return result;
694 void *owned = buffer_alloc(NULL, length);
695 if (!owned)
696 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate packet envelope");
697 memcpy(owned, wire, length);
698 packet_header_t header = wire_header;
699 out->type = NET_TO_HOST_U16(header.type);
700 out->data = (uint8_t *)owned + sizeof(header);
701 out->len = length - sizeof(header);
702 out->allocated_buffer = owned;
703 out->allocated_size = length;
704 result = packet_decrypt_envelope(out, crypto_ctx);
705 if (result != ASCIICHAT_OK) {
707 }
708 return result;
709}
710
712 if (!envelope)
713 return;
714 if (envelope->allocated_buffer) {
715 if (buffer_is_unique(envelope->allocated_buffer))
716 sodium_memzero(envelope->allocated_buffer, buffer_capacity(envelope->allocated_buffer));
717 buffer_release(envelope->allocated_buffer);
718 }
719 *envelope = (packet_envelope_t){0};
720}
721
722size_t packet_format_error_stack(char *buffer, size_t size) {
723 if (!buffer || size == 0)
724 return 0;
725 buffer[0] = '\0';
727 size_t frame_count = errno_snapshot(thread_current_id(), frames, ASCIICHAT_ERRNO_MAX_DEPTH).copied;
728 size_t offset = 0;
729 for (size_t i = 0; i < frame_count && offset < size - 1; ++i) {
730 const asciichat_error_context_t *frame = &frames[i];
731 const char *file = extract_project_relative_path(frame->file, ASCIICHAT_OWNED_SOURCE_DIRS);
732#ifdef NDEBUG
733 int written = snprintf(buffer + offset, size - offset, "%s%s (%s:%d in %s())", i ? "\n" : "", frame->context_message, file, frame->line, frame->function ? frame->function : "<unknown>");
734#else
735 int written = snprintf(buffer + offset, size - offset, "%s%s (%s:%d in %s())\tfull-path=%s", i ? "\n" : "", frame->context_message, file, frame->line,
736 frame->function ? frame->function : "<unknown>", frame->file ? frame->file : "");
737#endif
738 if (written < 0)
739 break;
740 size_t available = size - offset;
741 offset += (size_t)written < available ? (size_t)written : available - 1;
742 }
743 return offset;
744}
745
746asciichat_error_t packet_send_error(socket_t sockfd, const crypto_context_t *crypto_ctx, asciichat_error_t error_code, const char *message) {
747 if (sockfd == INVALID_SOCKET_VALUE) {
748 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket descriptor");
749 }
750
751 error_code = network_error_public_code(error_code);
752 // This packet is valid before peer authentication, so use only the public
753 // error description rather than contextual errno data.
754 (void)message;
755 message = asciichat_error_string(error_code);
756
757 size_t message_len = strnlen(message, MAX_ERROR_MESSAGE_LENGTH);
758 if (message_len == MAX_ERROR_MESSAGE_LENGTH) {
759 log_warn("Error message truncated to %zu bytes", (size_t)MAX_ERROR_MESSAGE_LENGTH);
760 }
761
762 size_t payload_len = sizeof(error_packet_t) + message_len;
763 uint8_t *payload = SAFE_MALLOC(payload_len, uint8_t *);
764 if (!payload) {
765 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate %zu bytes for error packet", payload_len);
766 }
767
768 error_packet_t *packet = (error_packet_t *)payload;
769 packet->error_code = HOST_TO_NET_U32((uint32_t)error_code);
770 packet->message_length = HOST_TO_NET_U32((uint32_t)message_len);
771
772 if (message_len > 0) {
773 memcpy(payload + sizeof(error_packet_t), message, message_len);
774 }
775
776 bool encryption_ready = crypto_ctx && crypto_ctx->encrypt_data && crypto_is_ready(crypto_ctx);
777 asciichat_error_t send_result;
778
779 if (encryption_ready) {
780 send_result = send_packet_secure(sockfd, PACKET_TYPE_ERROR_MESSAGE, payload, payload_len, (crypto_context_t *)crypto_ctx);
781 } else {
782 send_result = packet_send(sockfd, PACKET_TYPE_ERROR_MESSAGE, payload, payload_len);
783 }
784 SAFE_FREE(payload);
785
786 if (send_result != ASCIICHAT_OK) {
787 return SET_ERRNO(ERROR_NETWORK, "Failed to send error packet: %s", asciichat_error_string(send_result));
788 }
789
790 return ASCIICHAT_OK;
791}
792
793asciichat_error_t packet_parse_error_message(const void *data, size_t len, asciichat_error_t *out_error_code, char *message_buffer, size_t message_buffer_size, size_t *out_message_length) {
794 if (!data || len < sizeof(error_packet_t) || !out_error_code || !message_buffer || message_buffer_size == 0) {
795 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: data=%p len=%zu out_error_code=%p message_buffer=%p buffer_size=%zu", data, len, out_error_code, message_buffer, message_buffer_size);
796 }
797
798 const error_packet_t *packet = (const error_packet_t *)data;
799 uint32_t raw_error_code = NET_TO_HOST_U32(packet->error_code);
800 uint32_t raw_message_length = NET_TO_HOST_U32(packet->message_length);
801
802 if (raw_message_length > MAX_ERROR_MESSAGE_LENGTH) {
803 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Error message length too large: %u", raw_message_length);
804 }
805
806 size_t total_required = sizeof(error_packet_t) + (size_t)raw_message_length;
807 if (total_required > len) {
808 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Error packet truncated: expected %zu bytes, have %zu", total_required, len);
809 }
810
811 const uint8_t *message_bytes = (const uint8_t *)data + sizeof(error_packet_t);
812 size_t copy_len = raw_message_length;
813 if (copy_len >= message_buffer_size) {
814 copy_len = message_buffer_size - 1;
815 }
816
817 if (copy_len > 0) {
818 memcpy(message_buffer, message_bytes, copy_len);
819 }
820 message_buffer[copy_len] = '\0';
821
822 if (out_message_length) {
823 *out_message_length = raw_message_length;
824 }
825
826 *out_error_code = (asciichat_error_t)raw_error_code;
827 return ASCIICHAT_OK;
828}
829
830asciichat_error_t packet_send_remote_log(socket_t sockfd, const crypto_context_t *crypto_ctx, log_level_t level, remote_log_direction_t direction, uint16_t flags, const char *message) {
831 if (sockfd == INVALID_SOCKET_VALUE) {
832 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket descriptor");
833 }
834
835 if (level < LOG_DEV || level > LOG_FATAL) {
836 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid log level: %d", level);
837 }
838
839 const char *safe_message = message ? message : "";
840 bool truncated = false;
841 size_t message_len = strnlen(safe_message, MAX_REMOTE_LOG_MESSAGE_LENGTH);
842 if (message_len == MAX_REMOTE_LOG_MESSAGE_LENGTH && safe_message[message_len] != '\0') {
843 truncated = true;
844 }
845
846 size_t payload_len = sizeof(remote_log_packet_t) + message_len;
847 uint8_t *payload = SAFE_MALLOC(payload_len, uint8_t *);
848 if (!payload) {
849 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate %zu bytes for remote log packet", payload_len);
850 }
851
852 remote_log_packet_t *packet = (remote_log_packet_t *)payload;
853 packet->log_level = (uint8_t)level;
854 packet->direction = (uint8_t)direction;
855 uint16_t final_flags = flags;
856 if (truncated) {
857 final_flags |= REMOTE_LOG_FLAG_TRUNCATED;
858 }
859 packet->flags = HOST_TO_NET_U16(final_flags);
860 packet->message_length = HOST_TO_NET_U32((uint32_t)message_len);
861
862 if (message_len > 0) {
863 memcpy(payload + sizeof(remote_log_packet_t), safe_message, message_len);
864 }
865
866 bool encryption_ready = crypto_ctx && crypto_ctx->encrypt_data && crypto_is_ready(crypto_ctx);
867 asciichat_error_t send_result;
868
869 if (encryption_ready) {
870 int secure_result = send_packet_secure(sockfd, PACKET_TYPE_REMOTE_LOG, payload, payload_len, (crypto_context_t *)crypto_ctx);
871 send_result = secure_result == 0 ? ASCIICHAT_OK : ERROR_NETWORK;
872 } else {
873 send_result = packet_send(sockfd, PACKET_TYPE_REMOTE_LOG, payload, payload_len);
874 }
875
876 SAFE_FREE(payload);
877
878 if (send_result != ASCIICHAT_OK) {
879 return SET_ERRNO(ERROR_NETWORK, "Failed to send remote log packet: %d", send_result);
880 }
881
882 return ASCIICHAT_OK;
883}
884
885asciichat_error_t packet_parse_remote_log(const void *data, size_t len, log_level_t *out_level, remote_log_direction_t *out_direction, uint16_t *out_flags, char *message_buffer,
886 size_t message_buffer_size, size_t *out_message_length) {
887 if (!data || len < sizeof(remote_log_packet_t) || !out_level || !out_direction || !out_flags || !message_buffer || message_buffer_size == 0) {
888 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: data=%p len=%zu out_level=%p out_direction=%p out_flags=%p buffer=%p size=%zu", data, len, out_level, out_direction, out_flags,
889 message_buffer, message_buffer_size);
890 }
891
892 const remote_log_packet_t *packet = (const remote_log_packet_t *)data;
893 uint8_t raw_level = packet->log_level;
894 if (raw_level > LOG_FATAL) {
895 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid remote log level: %u", raw_level);
896 }
897 *out_level = (log_level_t)raw_level;
898
899 uint8_t raw_direction = packet->direction;
900 if (raw_direction > REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER) {
901 raw_direction = REMOTE_LOG_DIRECTION_UNKNOWN;
902 }
903 *out_direction = (remote_log_direction_t)raw_direction;
904
905 uint16_t raw_flags = NET_TO_HOST_U16(packet->flags);
906 *out_flags = raw_flags;
907
908 uint32_t raw_message_length = NET_TO_HOST_U32(packet->message_length);
909 if (raw_message_length > MAX_REMOTE_LOG_MESSAGE_LENGTH) {
910 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Remote log message length too large: %u", raw_message_length);
911 }
912
913 size_t total_required = sizeof(remote_log_packet_t) + (size_t)raw_message_length;
914 if (total_required > len) {
915 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Remote log packet truncated: expected %zu bytes, have %zu", total_required, len);
916 }
917
918 const uint8_t *message_bytes = (const uint8_t *)data + sizeof(remote_log_packet_t);
919 size_t copy_len = raw_message_length;
920 if (copy_len >= message_buffer_size) {
921 copy_len = message_buffer_size - 1;
922 }
923
924 if (copy_len > 0) {
925 memcpy(message_buffer, message_bytes, copy_len);
926 }
927 message_buffer[copy_len] = '\0';
928
929 if (out_message_length) {
930 *out_message_length = raw_message_length;
931 }
932
933 return ASCIICHAT_OK;
934}
935
943 if (!version) {
944 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: version=%p", version);
945 return -1;
946 }
947 return send_packet(sockfd, PACKET_TYPE_PROTOCOL_VERSION, version, sizeof(*version));
948}
949
957 if (!caps) {
958 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: caps=%p", caps);
959 return -1;
960 }
961 return send_packet(sockfd, PACKET_TYPE_CRYPTO_CAPABILITIES, caps, sizeof(*caps));
962}
963
971 if (!params) {
972 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: params=%p", params);
973 return -1;
974 }
975
976 // Create a copy and convert uint16_t fields to network byte order
977 crypto_parameters_packet_t net_params = *params;
978 log_debug("NETWORK_DEBUG: Before htons: kex=%u, auth=%u, sig=%u, secret=%u", params->kex_public_key_size, params->auth_public_key_size, params->signature_size, params->shared_secret_size);
981 net_params.signature_size = HOST_TO_NET_U16(params->signature_size);
983 log_debug("NETWORK_DEBUG: After htons: kex=%u, auth=%u, sig=%u, secret=%u", net_params.kex_public_key_size, net_params.auth_public_key_size, net_params.signature_size,
984 net_params.shared_secret_size);
985
986 return send_packet(sockfd, PACKET_TYPE_CRYPTO_PARAMETERS, &net_params, sizeof(net_params));
987}
988
989// =============================================================================
990// Audio Batch Packet Sending
991// =============================================================================
992// These functions were moved from lib/network/av.c during refactoring.
993// They provide socket-level audio packet sending with encryption support.
994// For transport-agnostic sending, use acip_send_audio_batch() instead.
995// =============================================================================
996
997asciichat_error_t av_send_audio_opus_batch(socket_t sockfd, const uint8_t *opus_data, size_t opus_size, const uint16_t *frame_sizes, int sample_rate, int frame_duration, int frame_count,
998 crypto_context_t *crypto_ctx) {
999 if (!opus_data || opus_size == 0 || !frame_sizes || sample_rate <= 0 || frame_duration <= 0 || frame_count <= 0) {
1001 "Invalid Opus batch parameters: opus_data=%p, opus_size=%zu, frame_sizes=%p, sample_rate=%d, "
1002 "frame_duration=%d, frame_count=%d",
1003 (const void *)opus_data, opus_size, (const void *)frame_sizes, sample_rate, frame_duration, frame_count);
1004 }
1005
1006 // Validate frame_count to prevent integer overflow in size calculations
1007 // Max reasonable frames per batch: ~1 second of 10ms frames = 100 frames
1008 if (frame_count > 1000) {
1009 return SET_ERRNO(ERROR_INVALID_PARAM, "Too many Opus frames: %d (max 1000)", frame_count);
1010 }
1011
1012 // Allocate buffer for header + frame sizes + encoded data
1013 size_t header_size = 16; // sample_rate (4), frame_duration (4), frame_count (4), reserved (4)
1014 size_t frame_sizes_bytes = (size_t)frame_count * sizeof(uint16_t);
1015 size_t total_size = header_size + frame_sizes_bytes + opus_size;
1016 void *packet_data = buffer_alloc(NULL, total_size);
1017 if (!packet_data) {
1018 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate buffer for Opus batch packet: %zu bytes", total_size);
1019 }
1020
1021 // Write header (network byte order for cross-platform compatibility)
1022 uint8_t *buf = (uint8_t *)packet_data;
1023 uint32_t sr = HOST_TO_NET_U32((uint32_t)sample_rate);
1024 uint32_t fd = HOST_TO_NET_U32((uint32_t)frame_duration);
1025 uint32_t fc = HOST_TO_NET_U32((uint32_t)frame_count);
1026 memcpy(buf, &sr, 4);
1027 memcpy(buf + 4, &fd, 4);
1028 memcpy(buf + 8, &fc, 4);
1029 memset(buf + 12, 0, 4); // Reserved
1030
1031 // Write frame sizes array (convert each to network byte order)
1032 uint16_t *frame_sizes_out = (uint16_t *)(buf + header_size);
1033 for (int i = 0; i < frame_count; i++) {
1034 frame_sizes_out[i] = HOST_TO_NET_U16(frame_sizes[i]);
1035 }
1036
1037 // Copy Opus data
1038 memcpy(buf + header_size + frame_sizes_bytes, opus_data, opus_size);
1039
1040 // Send packet (with encryption support)
1041 asciichat_error_t result = send_packet_secure(sockfd, PACKET_TYPE_AUDIO_OPUS_BATCH, packet_data, total_size, crypto_ctx);
1042
1043 // Clean up
1044 buffer_release(packet_data);
1045
1046 return result;
1047}
1048
1050 if (!image_data || width == 0 || height == 0) {
1051 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: image_data=%p, width=%u, height=%u", image_data, width, height);
1052 }
1053
1054 // Validate dimensions to prevent integer overflow
1055 // Max reasonable dimensions: 4K (3840x2160) = ~25MB per frame
1056 if (width > 4096 || height > 4096) {
1057 return SET_ERRNO(ERROR_INVALID_PARAM, "Image dimensions too large: %ux%u (max 4096x4096)", width, height);
1058 }
1059
1060 // Create image frame packet
1061 image_frame_packet_t packet;
1062 packet.width = HOST_TO_NET_U32(width);
1063 packet.height = HOST_TO_NET_U32(height);
1064 packet.pixel_format = HOST_TO_NET_U32(format);
1065 packet.compressed_size = 0;
1066 packet.checksum = 0;
1067 packet.timestamp = 0; // Will be set by receiver
1068
1069 // Calculate total packet size
1070 // Cast to size_t before multiplication to prevent integer overflow
1071 // Use overflow-checked multiplication
1072 size_t width_times_height;
1073 if (checked_size_mul((size_t)width, (size_t)height, &width_times_height) != ASCIICHAT_OK) {
1074 return SET_ERRNO(ERROR_BUFFER_OVERFLOW, "Image dimensions too large: %d x %d", width, height);
1075 }
1076
1077 size_t frame_size;
1078 if (checked_size_mul(width_times_height, 3u, &frame_size) != ASCIICHAT_OK) {
1079 return SET_ERRNO(ERROR_BUFFER_OVERFLOW, "Frame size overflow for RGB format");
1080 }
1081
1082 size_t total_size;
1083 if (checked_size_add(sizeof(image_frame_packet_t), frame_size, &total_size) != ASCIICHAT_OK) {
1084 return SET_ERRNO(ERROR_BUFFER_OVERFLOW, "Total packet size overflow");
1085 }
1086
1087 // Allocate buffer for complete packet
1088 void *packet_data = buffer_alloc(NULL, total_size);
1089 if (!packet_data) {
1090 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate buffer for image frame packet: %zu bytes", total_size);
1091 }
1092
1093 // Copy packet header and image data
1094 memcpy(packet_data, &packet, sizeof(image_frame_packet_t));
1095 memcpy((char *)packet_data + sizeof(image_frame_packet_t), image_data, frame_size);
1096
1097 // Send packet
1098 asciichat_error_t result = packet_send(sockfd, PACKET_TYPE_IMAGE_FRAME, packet_data, total_size);
1099
1100 // Clean up
1101 buffer_release(packet_data);
1102
1103 return result;
1104}
1105
1106packet_recv_result_t receive_packet_secure_with_timeout(socket_t sockfd, void *crypto_ctx, bool enforce_encryption, packet_envelope_t *envelope, uint64_t timeout_ns) {
1107 if (!envelope) {
1108 SET_ERRNO(ERROR_INVALID_PARAM, "Missing packet envelope");
1109 return PACKET_RECV_ERROR;
1110 }
1111 *envelope = (packet_envelope_t){0};
1112 packet_header_t header;
1113 ssize_t received = recv_with_timeout(sockfd, &header, sizeof(header), timeout_ns);
1114 if (!received)
1115 return PACKET_RECV_EOF;
1116 if (received != (ssize_t)sizeof(header))
1117 return PACKET_RECV_ERROR;
1118 size_t payload_length = NET_TO_HOST_U32(header.length);
1119 if (NET_TO_HOST_U64(header.magic) != PACKET_MAGIC || payload_length > MAX_PACKET_SIZE) {
1120 SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid packet header");
1121 return PACKET_RECV_ERROR;
1122 }
1123 size_t length = sizeof(header) + payload_length;
1124 uint8_t *packet = buffer_alloc(NULL, length);
1125 if (!packet) {
1126 SET_ERRNO(ERROR_MEMORY, "Cannot allocate received packet");
1127 return PACKET_RECV_ERROR;
1128 }
1129 memcpy(packet, &header, sizeof(header));
1130 if (payload_length && recv_with_timeout(sockfd, packet + sizeof(header), payload_length, MAX(timeout_ns, packet_send_timeout_ns(payload_length))) != (ssize_t)payload_length) {
1131 buffer_release(packet);
1132 // The header has already been consumed, so even an idle payload timeout
1133 // leaves the byte stream out of sync and must close the connection.
1134 SET_ERRNO(ERROR_NETWORK, "Incomplete packet payload after receiving header");
1135 return PACKET_RECV_ERROR;
1136 }
1137 asciichat_error_t result = packet_validate(packet, length, MAX_PACKET_SIZE, NULL);
1138 packet_type_t type = NET_TO_HOST_U16(header.type);
1139 if (result == ASCIICHAT_OK && enforce_encryption && type != PACKET_TYPE_ENCRYPTED && !packet_is_initial_handshake_type(type))
1140 result = SET_ERRNO(ERROR_CRYPTO, "Unencrypted packet in encrypted session");
1141 if (result != ASCIICHAT_OK) {
1142 buffer_release(packet);
1143 return PACKET_RECV_ERROR;
1144 }
1145 *envelope = (packet_envelope_t){.type = type, .data = packet, .len = length, .allocated_buffer = packet, .allocated_size = length};
1146 if (type == PACKET_TYPE_ENCRYPTED) {
1147 envelope->data = packet + sizeof(header);
1148 envelope->len = payload_length;
1149 result = packet_decrypt_envelope(envelope, crypto_ctx);
1150 if (result != ASCIICHAT_OK) {
1151 buffer_release(envelope->allocated_buffer);
1152 *envelope = (packet_envelope_t){0};
1153 return PACKET_RECV_ERROR;
1154 }
1155 }
1156 return PACKET_RECV_SUCCESS;
1157}
asciichat_errno_snapshot_t errno_snapshot(uint64_t id, asciichat_error_context_t *out, size_t capacity)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
#define ASCIICHAT_ERRNO_MAX_DEPTH
size_t buffer_capacity(const void *data)
Definition buffer.c:278
bool buffer_is_unique(const void *data)
Definition buffer.c:315
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
buffer_domain_t * buffer_control_domain(void)
Definition buffer.c:432
#define buffer_release(data)
Definition buffer.h:99
📦 Network Packet Compression Utilities
Hardware-Accelerated CRC32 Checksum Computation.
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U16(val)
Definition endian.h:100
#define NET_TO_HOST_U64(val)
Definition endian.h:232
#define HOST_TO_NET_U32(val)
Definition endian.h:70
#define HOST_TO_NET_U64(val)
Definition endian.h:217
#define NET_TO_HOST_U16(val)
Definition endian.h:115
#define NET_TO_HOST_U32(val)
Definition endian.h:85
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_STRERROR(errnum)
unsigned long long uint64_t
unsigned char uint8_t
#define COMPRESSION_MIN_SIZE
Minimum packet size to attempt compression (1KB).
Definition compression.h:66
bool should_compress(size_t original_size, size_t compressed_size)
Determine if compression should be used for given data sizes.
asciichat_error_t compress_data(const void *input, size_t input_size, void **output, size_t *output_size, int compression_level)
Compress data using zstd with configurable compression level.
Definition compression.c:29
#define COMPRESSION_RATIO_THRESHOLD
Compression ratio threshold - only use if <80% original size.
Definition compression.h:63
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:76
@ 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_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_BUFFER_OVERFLOW
#define LOG_RATE_FAST
Log rate limit: 1 second (1,000,000 microseconds).
Definition log_rates.h:30
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
enum remote_log_direction remote_log_direction_t
Remote log packet direction enumeration.
log_level_t
Logging levels enumeration.
Definition types.h:33
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
@ REMOTE_LOG_DIRECTION_UNKNOWN
Definition network/log.h:20
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:20
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_SEC_INT
Definition time.h:177
asciichat_error_t send_packet_secure(socket_t sockfd, packet_type_t type, const void *data, size_t len, crypto_context_t *crypto_ctx)
Send a packet with encryption and compression support.
Definition packet.c:471
asciichat_error_t packet_validate(const void *packet, size_t length, size_t limit, packet_header_t *output)
Definition packet.c:81
#define LARGE_PACKET_THRESHOLD
Large packet size threshold (100KB).
Definition packet.h:134
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
ssize_t recv_with_timeout(socket_t sockfd, void *buf, size_t len, uint64_t timeout_ns)
Receive data with timeout.
asciichat_error_t send_image_frame_packet(socket_t sockfd, const void *image_data, uint16_t width, uint16_t height, uint8_t format)
Send image frame packet.
Definition packet.c:1049
void protocol_version_packet_init(protocol_version_packet_t *version, uint8_t supports_encryption)
Initialize a protocol version packet with the current wire version.
Definition packet.c:37
int send_protocol_version_packet(socket_t sockfd, const protocol_version_packet_t *version)
Send protocol version packet.
Definition packet.c:942
#define MAX_CLIENT_TIMEOUT
Maximum client timeout in nanoseconds (60 seconds).
Definition packet.h:214
int send_pong_packet(socket_t sockfd)
Send a pong packet.
Definition packet.c:619
#define LARGE_PACKET_EXTRA_TIMEOUT_PER_MB
Extra timeout per MB for large packets (0.8 seconds per MB).
Definition packet.h:194
asciichat_error_t packet_receive(socket_t sockfd, packet_type_t *type, void **data, size_t *len)
Receive a packet with proper header validation and CRC32 checking.
Definition packet.c:388
int receive_packet(socket_t sockfd, packet_type_t *type, void **data, size_t *len)
Receive a basic packet without encryption.
Definition packet.c:594
asciichat_error_t packet_decrypt_envelope(packet_envelope_t *envelope, void *crypto_ctx)
Send a clear console packet.
Definition packet.c:639
asciichat_error_t av_send_audio_opus_batch(socket_t sockfd, const uint8_t *opus_data, size_t opus_size, const uint16_t *frame_sizes, int sample_rate, int frame_duration, int frame_count, crypto_context_t *crypto_ctx)
Send Opus-encoded audio batch packet with encryption support.
Definition packet.c:997
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define MAX_PACKET_SIZE
Maximum packet size (5MB).
Definition packet.h:144
int send_packet(socket_t sockfd, packet_type_t type, const void *data, size_t len)
Send a basic packet without encryption.
Definition packet.c:581
#define MAX_REMOTE_LOG_MESSAGE_LENGTH
Maximum remote log message length (512 bytes).
Definition packet.h:163
asciichat_error_t packet_send(socket_t sockfd, packet_type_t type, const void *data, size_t len)
Send a packet with proper header and CRC32.
Definition packet.c:348
packet_recv_result_t receive_packet_secure(socket_t sockfd, void *crypto_ctx, bool enforce_encryption, packet_envelope_t *envelope)
Receive a packet with decryption and decompression support.
Definition packet.c:563
#define RECV_TIMEOUT
Receive timeout in seconds (1 second).
Definition network.h:133
int send_crypto_capabilities_packet(socket_t sockfd, const crypto_capabilities_packet_t *caps)
Send crypto capabilities packet.
Definition packet.c:956
int send_ping_packet(socket_t sockfd)
Send a ping packet.
Definition packet.c:610
#define PACKET_MAGIC
Packet magic number (alias for MAGIC_PACKET_VALID).
Definition packet.h:284
#define REMOTE_LOG_FLAG_TRUNCATED
Remote log packet flag definitions.
Definition packet.h:787
asciichat_error_t packet_header_build(packet_header_t *header, packet_type_t type, const socket_buffer_t *payload, size_t count, uint32_t client_id)
Definition packet.c:47
#define MAX_ERROR_MESSAGE_LENGTH
Maximum error message length (512 bytes).
Definition packet.h:153
#define MIN_CLIENT_TIMEOUT
Minimum client timeout in nanoseconds (10 seconds).
Definition packet.h:204
int send_crypto_parameters_packet(socket_t sockfd, const crypto_parameters_packet_t *params)
Send crypto parameters packet.
Definition packet.c:970
packet_recv_result_t
packet envelope is intentionally a small, concrete record. Fields such as type, data,...
Definition packet.h:1231
#define SEND_TIMEOUT
Send timeout in seconds (5 seconds).
Definition network.h:117
@ 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_AUDIO_OPUS_BATCH
Batched Opus-encoded audio frames.
Definition packet.h:412
@ 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_STREAM_START
Client requests to start sending video/audio.
Definition packet.h:429
@ 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_KEY_EXCHANGE_RESP
Client -> Server: {client_pubkey[32]} (UNENCRYPTED).
Definition packet.h:342
@ PACKET_TYPE_ACIP_NETWORK_QUALITY
NETWORK_QUALITY exchange (unified packet for all quality metrics).
Definition packet.h:493
@ PACKET_TYPE_ACIP_HOST_LOST
Host lost notification - lightweight (Participant -> ACDS).
Definition packet.h:503
@ 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_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_BANDWIDTH_TEST
Bandwidth test request (Client -> ACDS).
Definition packet.h:517
@ 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_ACIP_STRING_RESERVED
String reserved response (Discovery Server -> Client).
Definition packet.h:471
@ 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_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457
@ 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_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_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_PING
Keepalive ping packet.
Definition packet.h:421
@ PACKET_TYPE_AUDIO_BATCH
Batched audio packets for efficiency.
Definition packet.h:410
@ PACKET_TYPE_ACIP_SESSION_JOINED
Session joined response (Discovery Server -> Client).
Definition packet.h:455
@ PACKET_TYPE_STREAM_STOP
Client stops sending media.
Definition packet.h:431
@ PACKET_TYPE_ACIP_SESSION_END
End session (Host -> Discovery Server).
Definition packet.h:459
@ PACKET_RECV_ERROR
Network error occurred.
Definition packet.h:1237
@ PACKET_RECV_EOF
Connection closed (EOF).
Definition packet.h:1235
@ PACKET_RECV_SUCCESS
Packet received successfully.
Definition packet.h:1233
#define GET_OPTION(field)
Definition options.h:1333
#define PROTOCOL_VERSION_MAJOR
Major protocol version number.
#define PROTOCOL_VERSION_MINOR
Minor protocol version number.
#define PROTOCOL_VERSION_PATCH
Patch protocol version number.
#define asciichat_crc32(data, len)
Main CRC32 dispatcher macro - use this in application code.
Definition crc32.h:151
const char * extract_project_relative_path(const char *file, const char *const *owned_dirs)
Extract a path relative to the source root embedded by CMake.
Definition path.c:132
uint32_t asciichat_crc32_update(uint32_t previous, const void *data, size_t len)
Compute CRC32 checksum with hardware acceleration (if available).
Definition crc32.c:81
int socket_t
🔊 Audio Capture and Playback Interface for ascii-chat
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Network error handling utilities.
asciichat_error_t network_error_public_code(asciichat_error_t code)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:749
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)
🌐 Core network I/O operations with timeout support
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
✅ Safe Integer Arithmetic and Overflow Detection
asciichat_error_t packet_parse_remote_log(const void *data, size_t len, log_level_t *out_level, remote_log_direction_t *out_direction, uint16_t *out_flags, char *message_buffer, size_t message_buffer_size, size_t *out_message_length)
Parse a remote log packet payload into components.
Definition packet.c:885
asciichat_error_t packet_send_error(socket_t sockfd, const crypto_context_t *crypto_ctx, asciichat_error_t error_code, const char *message)
Send an error packet with optional encryption context.
Definition packet.c:746
asciichat_error_t packet_send_remote_log(socket_t sockfd, const crypto_context_t *crypto_ctx, log_level_t level, remote_log_direction_t direction, uint16_t flags, const char *message)
Send a remote log packet with optional encryption context.
Definition packet.c:830
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
size_t packet_format_error_stack(char *buffer, size_t size)
Format the current thread's error stack for transport to a peer.
Definition packet.c:722
asciichat_error_t packet_parse_error_message(const void *data, size_t len, asciichat_error_t *out_error_code, char *message_buffer, size_t message_buffer_size, size_t *out_message_length)
Parse an error packet payload into components.
Definition packet.c:793
void packet_envelope_release(packet_envelope_t *envelope)
Definition packet.c:711
packet_recv_result_t receive_packet_secure_with_timeout(socket_t sockfd, void *crypto_ctx, bool enforce_encryption, packet_envelope_t *envelope, uint64_t timeout_ns)
Definition packet.c:1106
uint64_t packet_send_timeout_ns(size_t packet_size)
Definition packet.c:111
#define MAX(a, b)
Definition param.h:10
📂 Path Manipulation Utilities
asciichat_error_t acip_packet_plan(crypto_context_t *crypto, const socket_buffer_t *buffers, size_t count, acip_packet_plan_t *plan)
Definition prepare.c:9
asciichat_error_t acip_packet_encrypt(crypto_context_t *crypto, const acip_packet_plan_t *plan, buffer_domain_t *domain, void *ciphertext, size_t capacity, packet_header_t *header, size_t *length)
The useful part of acip packet plan is in buffers, count, plaintext_size, ciphertext_capacity: togeth...
Definition prepare.c:53
Protocol version, features, compression, and frame flag constants.
static bool size_t gotel_query_t * out
Definition queries.h:8
#define CRYPTO_RECORD_RELIABLE
Definition record.h:13
#define CRYPTO_RECORD_ANY_CHANNEL
Definition record.h:15
🔤 String Manipulation and Shell Escaping Utilities
size_t ciphertext_capacity
Definition prepare.h:24
buffer_domain_t * domain
Borrowed control reserve for handshake/error traffic; NULL otherwise.
Definition prepare.h:29
The wire metadata for one rendered ASCII frame. width and height describe the terminal grid,...
Definition packet.h:916
The metadata prefix for a batch of encoded audio samples. batch_count, total_samples,...
Definition packet.h:979
Client information packet structure.
Definition packet.h:703
Crypto capabilities packet structure (Packet Type 14).
Definition packet.h:1027
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.
Crypto parameters packet structure (Packet Type 15).
Definition packet.h:1056
uint16_t auth_public_key_size
Authentication public key size in bytes (e.g., 32 for Ed25519, 1952 for Dilithium3).
Definition packet.h:1068
uint16_t signature_size
Signature size in bytes (e.g., 64 for Ed25519, 3309 for Dilithium3).
Definition packet.h:1070
uint16_t shared_secret_size
Shared secret size in bytes (e.g., 32 for X25519).
Definition packet.h:1072
uint16_t kex_public_key_size
Key exchange public key size in bytes (e.g., 32 for X25519, 1568 for Kyber1024).
Definition packet.h:1066
Error packet structure carrying error code and textual description.
Definition packet.h:778
uint32_t message_length
Length of message payload in bytes (0-512).
Definition packet.h:782
uint32_t error_code
Error code from asciichat_error_t enumeration.
Definition packet.h:780
Describes one compressed image sent through ACIP. width, height, and pixel_format tell the decoder ho...
Definition packet.h:948
uint32_t pixel_format
Pixel format enum (1=RGB24, 2=RGBA32, 3=BGR24, 4=BGRA32).
Definition packet.h:954
uint32_t timestamp
Timestamp when frame was captured (milliseconds since epoch).
Definition packet.h:960
uint32_t compressed_size
Compressed data size (0 = not compressed, >0 = compressed).
Definition packet.h:956
uint32_t checksum
CRC32 checksum of pixel data.
Definition packet.h:958
uint32_t height
Image height in pixels.
Definition packet.h:952
uint32_t width
Image width in pixels.
Definition packet.h:950
Packet envelope containing received packet data.
Definition packet.h:1204
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
Protocol version negotiation packet structure (Packet Type 1).
Definition packet.h:871
uint16_t protocol_patch
Patch protocol revision.
Definition packet.h:877
uint16_t protocol_revision
Minor protocol revision (server can be newer).
Definition packet.h:875
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
Remote log packet structure carrying log level and message text.
Definition packet.h:792
uint16_t flags
Additional flags (REMOTE_LOG_FLAG_*).
Definition packet.h:798
uint32_t message_length
Message payload length in bytes (0-512).
Definition packet.h:800
uint8_t log_level
Log level associated with the message (log_level_t cast to uint8_t).
Definition packet.h:794
uint8_t direction
Direction hint so receivers can annotate origin.
Definition packet.h:796
#define LOG_FATAL
Definition types.h:47