ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
network/packet/parsing.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define NETWORK_PACKET_PARSING_SIZE_BUFFER_SIZE 32
4#define NETWORK_PACKET_PARSING_HEX_BUFFER_SIZE 256
5
7#include <recast/defer.h>
20
27#include <string.h>
28
33#define PACKET_MAX_FRAME_SIZE (256 * 1024 * 1024)
34
39#define PACKET_MAX_DIMENSION 32768
40
41static char *decode_frame_data_malloc(const char *frame_data_ptr, size_t frame_data_len, bool is_compressed, uint32_t original_size, uint32_t compressed_size) {
42 // Validate size before allocation to prevent excessive memory usage
43 if (original_size > PACKET_MAX_FRAME_SIZE) {
45 format_bytes_pretty(original_size, size_str, sizeof(size_str));
46 SET_ERRNO(ERROR_NETWORK_SIZE, "Frame size exceeds maximum: %s (max %d MB)", size_str, PACKET_MAX_FRAME_SIZE / (1024 * 1024));
47 return NULL;
48 }
49
50 // Allocate buffer with extra byte for null terminator
51 SAFE_MALLOC_DEFER_FREE(frame_data, original_size + 1, char *);
52 if (!frame_data) {
53 SET_ERRNO(ERROR_MEMORY, "Failed to allocate %u bytes for frame decode", original_size);
54 return NULL;
55 }
56
57 if (is_compressed) {
58 // Validate compressed frame size
59 if (frame_data_len != compressed_size) {
60 SET_ERRNO(ERROR_NETWORK_SIZE, "Compressed frame size mismatch: expected %u, got %zu", compressed_size, frame_data_len);
61 return NULL;
62 }
63
64 // Decompress using compression API
65 asciichat_error_t decompress_result = decompress_data_exact(frame_data_ptr, frame_data_len, frame_data, original_size);
66
67 if (decompress_result != ASCIICHAT_OK) {
68 SET_ERRNO(ERROR_COMPRESSION, "Decompression failed for expected size %u: %s", original_size, asciichat_error_string(decompress_result));
69 return NULL;
70 }
71
72 log_debug_every(US_PER_SEC_INT, "Decompressed frame: %zu -> %u bytes", frame_data_len, original_size);
73 } else {
74 // Uncompressed frame - validate size
75 if (frame_data_len != original_size) {
76 log_error("Uncompressed frame size mismatch: expected %u, got %zu", original_size, frame_data_len);
77 return NULL;
78 }
79
80 // Only copy the actual amount of data we received
81 size_t copy_size = (frame_data_len > original_size) ? original_size : frame_data_len;
82 memcpy(frame_data, frame_data_ptr, copy_size);
83 }
84
85 // Null-terminate the frame data
86 frame_data[original_size] = '\0';
87 char *result = frame_data;
88 frame_data = NULL;
89 return result;
90}
91
92char *packet_decode_frame_data_malloc(const char *data, size_t length, bool compressed, uint32_t original_size, uint32_t compressed_size) {
93 uint64_t started = time_get_ns();
94 char *result = decode_frame_data_malloc(data, length, compressed, original_size, compressed_size);
97 return result;
98}
99
100asciichat_error_t packet_decode_frame_data_buffer(const char *frame_data_ptr, size_t frame_data_len, bool is_compressed, void *output_buffer, size_t output_size, uint32_t original_size,
101 uint32_t compressed_size) {
102 if (!frame_data_ptr || !output_buffer) {
103 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL pointer in frame decode");
104 }
105
106 if (output_size < original_size) {
107 return SET_ERRNO(ERROR_BUFFER_FULL, "Output buffer too small: %zu < %u", output_size, original_size);
108 }
109
110 if (is_compressed) {
111 // Validate compressed frame size
112 if (frame_data_len != compressed_size) {
113 return SET_ERRNO(ERROR_NETWORK_SIZE, "Compressed frame size mismatch: expected %u, got %zu", compressed_size, frame_data_len);
114 }
115
116 // Decompress using compression API
117 asciichat_error_t decompress_result = decompress_data_exact(frame_data_ptr, frame_data_len, output_buffer, original_size);
118
119 if (decompress_result != ASCIICHAT_OK) {
120 return SET_ERRNO(ERROR_COMPRESSION, "Decompression failed for expected size %u: %s", original_size, asciichat_error_string(decompress_result));
121 }
122
123 log_debug_every(US_PER_SEC_INT, "Decompressed frame to buffer: %zu -> %u bytes", frame_data_len, original_size);
124 } else {
125 // Uncompressed frame - validate size
126 if (frame_data_len != original_size) {
127 return SET_ERRNO(ERROR_NETWORK_SIZE, "Uncompressed frame size mismatch: expected %u, got %zu", original_size, frame_data_len);
128 }
129
130 // Copy data to output buffer
131 memcpy(output_buffer, frame_data_ptr, original_size);
132 }
133
134 return ASCIICHAT_OK;
135}
136
137asciichat_error_t packet_decode_frame_data_workspace(buffer_workspace_t *workspace, const void *data, size_t length, bool compressed, uint32_t original_size, uint32_t compressed_size) {
138 if (!workspace || original_size > PACKET_MAX_FRAME_SIZE)
139 return SET_ERRNO(ERROR_NETWORK_SIZE, "Invalid decoded ASCII workspace size: %u", original_size);
140 uint64_t started = time_get_ns();
141 asciichat_error_t result = buffer_workspace_reserve(workspace, NULL, (size_t)original_size + 1);
142 if (result == ASCIICHAT_OK)
143 result = packet_decode_frame_data_buffer(data, length, compressed, workspace->data, buffer_capacity(workspace->data), original_size, compressed_size);
144 if (result == ASCIICHAT_OK) {
145 ((char *)workspace->data)[original_size] = '\0';
146 workspace->length = original_size;
147 }
150 return result;
151}
152
154 if (!out_rgb_size) {
155 return SET_ERRNO(ERROR_INVALID_PARAM, "out_rgb_size pointer is NULL");
156 }
157
158 // Check dimensions are non-zero
159 if (width == 0 || height == 0) {
160 return SET_ERRNO(ERROR_INVALID_STATE, "Frame dimensions cannot be zero: %ux%u", width, height);
161 }
162
163 // Check dimensions are within reasonable bounds
165 return SET_ERRNO(ERROR_INVALID_STATE, "Frame dimensions exceed maximum: %ux%u (max %u)", width, height, PACKET_MAX_DIMENSION);
166 }
167
168 // Calculate RGB buffer size with overflow checking (width * height * 3 bytes per pixel)
169 size_t pixel_count = 0;
170 if (safe_size_mul(width, height, &pixel_count) != 0) {
171 return SET_ERRNO(ERROR_MEMORY, "Frame dimension multiplication overflow: %u * %u", width, height);
172 }
173
174 size_t rgb_size = 0;
175 if (safe_size_mul(pixel_count, 3, &rgb_size) != 0) {
176 return SET_ERRNO(ERROR_MEMORY, "RGB buffer size overflow: %zu * 3", pixel_count);
177 }
178
179 // Validate final buffer size against maximum
180 if (rgb_size > PACKET_MAX_FRAME_SIZE) {
182 format_bytes_pretty(rgb_size, size_str, sizeof(size_str));
183 return SET_ERRNO(ERROR_MEMORY, "Frame buffer size exceeds maximum: %s (max %d MB)", size_str, PACKET_MAX_FRAME_SIZE / (1024 * 1024));
184 }
185
186 *out_rgb_size = rgb_size;
187 return ASCIICHAT_OK;
188}
189
190// NOTE: packet_parse_audio_batch_header has been moved to lib/audio/audio.c as audio_parse_batch_header
191// This module now provides a wrapper inline function in packet_parsing.h for backwards compatibility
192// See lib/audio/audio.h for the canonical implementation
193
194asciichat_error_t packet_parse_opus_batch(const void *packet_data, size_t packet_len, const uint8_t **out_opus_data, size_t *out_opus_size, const uint16_t **out_frame_sizes, int *out_sample_rate,
195 int *out_frame_duration, int *out_frame_count) {
196 if (!packet_data || !out_opus_data || !out_opus_size || !out_frame_sizes || !out_sample_rate || !out_frame_duration || !out_frame_count) {
197 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter in Opus batch parsing");
198 }
199
200 // Verify minimum packet size (16-byte header: sample_rate + frame_duration + frame_count + reserved)
201 const size_t header_size = 16;
202 if (packet_len < header_size) {
203 // DEBUG: Log first few bytes of corrupted packet to understand what's happening
205 size_t bytes_to_show = (packet_len < 32) ? packet_len : 32;
206 for (size_t i = 0; i < bytes_to_show; i++) {
207 snprintf(hex_buf + i * 2, 3, "%02x", ((uint8_t *)packet_data)[i]);
208 }
209 hex_buf[bytes_to_show * 2] = '\0';
210 log_error("★ OPUS_BATCH_RCV_DEBUG: packet_len=%zu, expected_min=%zu, first_bytes=%s", packet_len, header_size, hex_buf);
211 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Opus batch packet too small: %zu < %zu", packet_len, header_size);
212 }
213
214 // Parse header (convert from network byte order)
215 const uint8_t *buf = (const uint8_t *)packet_data;
216 uint32_t sr, fd, fc;
217 memcpy(&sr, buf, 4);
218 memcpy(&fd, buf + 4, 4);
219 memcpy(&fc, buf + 8, 4);
220 *out_sample_rate = (int)NET_TO_HOST_U32(sr);
221 *out_frame_duration = (int)NET_TO_HOST_U32(fd);
222 int frame_count = (int)NET_TO_HOST_U32(fc);
223 *out_frame_count = frame_count;
224
225 // Validate frame count to prevent overflow
226 if (frame_count < 0 || frame_count > 1000) {
227 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid Opus frame count: %d (must be 0-1000)", frame_count);
228 }
229
230 // Extract frame sizes array (after 16-byte header)
231 size_t frame_sizes_bytes = (size_t)frame_count * sizeof(uint16_t);
232 if (packet_len < header_size + frame_sizes_bytes) {
233 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Opus batch packet too small for frame sizes: %zu < %zu", packet_len, header_size + frame_sizes_bytes);
234 }
235 // NOTE: Frame sizes are in network byte order - caller must use NET_TO_HOST_U16() when reading
236 *out_frame_sizes = (const uint16_t *)(buf + header_size);
237
238 // Extract Opus data (after header + frame sizes)
239 *out_opus_data = buf + header_size + frame_sizes_bytes;
240 *out_opus_size = packet_len - header_size - frame_sizes_bytes;
241
242 return ASCIICHAT_OK;
243}
#define SET_ERRNO(code,...)
size_t buffer_capacity(const void *data)
Definition buffer.c:300
asciichat_error_t buffer_workspace_reserve(buffer_workspace_t *workspace, buffer_domain_t *domain, size_t capacity)
Definition buffer.c:376
🔢 Byte-Level Access and Arithmetic Utilities
📦 Network Packet Compression Utilities
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define safe_size_mul
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)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_COMPRESSION
@ ERROR_BUFFER_FULL
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:81
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_NETWORK_SIZE
Definition error_codes.h:83
@ ERROR_INVALID_PARAM
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define US_PER_SEC_INT
Definition time.h:177
asciichat_error_t packet_parse_opus_batch(const void *packet_data, size_t packet_len, const uint8_t **out_opus_data, size_t *out_opus_size, const uint16_t **out_frame_sizes, int *out_sample_rate, int *out_frame_duration, int *out_frame_count)
Parse Opus audio batch packet header and extract frame data.
#define PACKET_MAX_DIMENSION
Maximum frame dimension (32768x32768) - prevents overflow.
asciichat_error_t packet_decode_frame_data_buffer(const char *frame_data_ptr, size_t frame_data_len, bool is_compressed, void *output_buffer, size_t output_size, uint32_t original_size, uint32_t compressed_size)
Decode frame data (fixed buffer version for server handlers).
asciichat_error_t packet_validate_frame_dimensions(uint32_t width, uint32_t height, size_t *out_rgb_size)
Validate frame dimensions and calculate RGB buffer size.
asciichat_error_t packet_decode_frame_data_workspace(buffer_workspace_t *workspace, const void *data, size_t length, bool compressed, uint32_t original_size, uint32_t compressed_size)
char * packet_decode_frame_data_malloc(const char *data, size_t length, bool compressed, uint32_t original_size, uint32_t compressed_size)
Decode frame data (malloc version for client handlers).
#define PACKET_MAX_FRAME_SIZE
Maximum frame size (256MB) - prevents memory exhaustion attacks.
void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity)
Format byte count into human-readable string.
Definition util/format.c:12
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define NETWORK_PACKET_PARSING_SIZE_BUFFER_SIZE
#define NETWORK_PACKET_PARSING_HEX_BUFFER_SIZE
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
🔤 String Manipulation and Shell Escaping Utilities
Owns the temporary storage used by buffer workspace. The data pointers and size or cursor fields desc...
Definition buffer.h:122
⏱️ High-precision timing utilities using sokol_time.h and uthash
📊 String Formatting Utilities