ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
Shared Packet Parsing Utilities

📡 Shared protocol parsing utilities for server and client packet handlers More...

Macros

#define PACKET_MAX_FRAME_SIZE   (256 * 1024 * 1024)
 Maximum frame size (256MB) - prevents memory exhaustion attacks.
#define PACKET_MAX_DIMENSION   32768
 Maximum frame dimension (32768x32768) - prevents overflow.

Frame Decoding Functions

Unified frame data decoding for both compressed and uncompressed formats

char * packet_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)
 Decode frame data (malloc version for client handlers).
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_decode_frame_data_workspace (buffer_workspace_t *workspace, const void *data, size_t length, bool compressed, uint32_t original_size, uint32_t compressed_size)

Frame Dimension Validation

Validation helpers for frame dimensions with overflow checking

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.

Opus Audio Batch Parsing

Helpers for parsing Opus audio batch packets

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.

Detailed Description

📡 Shared protocol parsing utilities for server and client packet handlers

This module provides reusable utilities for parsing and validating protocol packets, used by both server (src/server/protocol.c) and client (src/client/protocol.c) handlers.

CORE RESPONSIBILITIES:

  1. Frame data decoding (handles compressed and uncompressed formats)
  2. Network byte order conversions and validation
  3. Audio batch header parsing and validation
  4. Frame dimension validation with overflow checking
  5. Generic packet payload validation helpers

DESIGN PRINCIPLES:

  • Minimal dependencies on protocol-specific types
  • Clear error codes and messages
  • No assumptions about error handling (caller decides)
  • Support for both server and client usage patterns
  • Overflow-safe integer arithmetic throughout

USAGE PATTERNS:

Server handlers use these for incoming client packets:

// Decode compressed/uncompressed frame data
frame_buffer_t *decoded = packet_decode_frame_data(
frame_data_ptr, frame_data_len, is_compressed,
expected_size, compressed_size);
// Validate audio batch header
result = packet_parse_audio_batch_header(data, len, &batch);
struct frame_buffer frame_buffer_t
Opaque frame buffer handle.
Parsed audio batch packet header information.

Client handlers use these for incoming server packets:

// Same frame decoding for server->client frames
frame_data, frame_data_len, is_compressed,
original_size, 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).

INTEGRATION POINTS:

  • src/server/protocol.c: IMAGE_FRAME, AUDIO_BATCH, AUDIO_OPUS_BATCH packet handling
  • src/client/protocol.c: ASCII_FRAME, AUDIO_BATCH, AUDIO_OPUS_BATCH packet handling
  • lib/network/packet.h: Low-level packet structure definitions
  • lib/network/av.h: Audio/video packet serialization
  • lib/util/validation.h: High-level packet validation macros

OVERFLOW SAFETY:

All integer calculations use safe_size_mul() and overflow checking to prevent buffer overflows from malicious or malformed packets.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025

Macro Definition Documentation

◆ PACKET_MAX_DIMENSION

#define PACKET_MAX_DIMENSION   32768

#include <lib/network/packet/parsing.c>

Maximum frame dimension (32768x32768) - prevents overflow.

Definition at line 39 of file network/packet/parsing.c.

Referenced by packet_validate_frame_dimensions().

◆ PACKET_MAX_FRAME_SIZE

#define PACKET_MAX_FRAME_SIZE   (256 * 1024 * 1024)

#include <lib/network/packet/parsing.c>

Maximum frame size (256MB) - prevents memory exhaustion attacks.

Definition at line 33 of file network/packet/parsing.c.

Referenced by packet_decode_frame_data_workspace(), and packet_validate_frame_dimensions().

Function Documentation

◆ packet_decode_frame_data_buffer()

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 )

#include <include/ascii-chat/network/packet/parsing.h>

Decode frame data (fixed buffer version for server handlers).

Decodes frame data into a pre-allocated fixed-size buffer. Used when buffer allocation is managed separately (e.g., ring buffers).

Parameters
frame_data_ptrPointer to frame data (compressed or uncompressed)
frame_data_lenActual size of frame_data_ptr buffer
is_compressedTrue if data is zstd-compressed
output_bufferPre-allocated output buffer
output_sizeSize of output_buffer in bytes
original_sizeExpected decompressed/uncompressed size
compressed_sizeExpected compressed size (if is_compressed=true)
Returns
ASCIICHAT_OK on success, error code on failure Errors set asciichat_errno with context message
Note
Used by server handlers for client->server IMAGE_FRAME packets
See also
packet_decode_frame_data_malloc() For malloc version

Definition at line 100 of file network/packet/parsing.c.

101 {
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}
#define SET_ERRNO(code,...)
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_COMPRESSION
@ ERROR_BUFFER_FULL
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_NETWORK_SIZE
Definition error_codes.h:83
@ ERROR_INVALID_PARAM
#define US_PER_SEC_INT
Definition time.h:177
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719

References ASCIICHAT_OK, decompress_data_exact(), ERROR_BUFFER_FULL, ERROR_COMPRESSION, ERROR_INVALID_PARAM, ERROR_NETWORK_SIZE, log_debug_every, SET_ERRNO, and US_PER_SEC_INT.

Referenced by packet_decode_frame_data_workspace().

◆ packet_decode_frame_data_malloc()

char * packet_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 )

#include <include/ascii-chat/network/packet/parsing.h>

Decode frame data (malloc version for client handlers).

Handles both compressed (zstd) and uncompressed frame formats. Allocates buffer using SAFE_MALLOC that caller must free. Validates sizes to prevent memory exhaustion attacks.

Frame formats supported:

  • Uncompressed: Raw pixel/text data at expected_size bytes
  • Compressed: zstd-compressed data, decompresses to expected_size bytes

SIZE VALIDATION:

  • Validates original_size <= 100MB (prevents excessive allocation)
  • Validates expected_size == uncompressed size
  • Validates compressed_size <= frame_data_len (if compressed)

ERROR HANDLING:

  • Returns NULL on allocation failure
  • Returns NULL on decompression failure
  • Returns NULL on size validation failure
  • Sets asciichat_errno for detailed error reporting
Parameters
frame_data_ptrPointer to frame data (compressed or uncompressed)
frame_data_lenActual size of frame_data_ptr buffer
is_compressedTrue if data is zstd-compressed, false if raw
original_sizeExpected decompressed/uncompressed size in bytes
compressed_sizeExpected compressed size (validated only if is_compressed=true)
Returns
Allocated buffer with decoded data (caller must SAFE_FREE), or NULL on error
Note
Caller is responsible for freeing returned buffer with SAFE_FREE()
Added null terminator to decoded data (buffer is original_size + 1)
Used by client handlers for server->client frame packets
See also
packet_decode_frame_data_buffer() For fixed-size Owned Buffers variant

Definition at line 92 of file network/packet/parsing.c.

92 {
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}
unsigned long long uint64_t
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)
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88

References stats_counter_add(), STATS_COUNTER_FRAMES_DECODED, STATS_COUNTER_FRAMES_DROPPED, STATS_DURATION_DECODE, stats_duration_record(), and stats_runtime_scope().

◆ packet_decode_frame_data_workspace()

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 )

#include <include/ascii-chat/network/packet/parsing.h>

Decode into caller-owned reusable storage, including a trailing NUL.

Definition at line 137 of file network/packet/parsing.c.

137 {
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}
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
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).
#define PACKET_MAX_FRAME_SIZE
Maximum frame size (256MB) - prevents memory exhaustion attacks.

References ASCIICHAT_OK, buffer_capacity(), buffer_workspace_reserve(), buffer_workspace_t::data, ERROR_NETWORK_SIZE, buffer_workspace_t::length, packet_decode_frame_data_buffer(), PACKET_MAX_FRAME_SIZE, SET_ERRNO, stats_counter_add(), STATS_COUNTER_FRAMES_DECODED, STATS_COUNTER_FRAMES_DROPPED, STATS_DURATION_DECODE, stats_duration_record(), and stats_runtime_scope().

◆ packet_parse_opus_batch()

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 )

#include <include/ascii-chat/network/packet/parsing.h>

Parse Opus audio batch packet header and extract frame data.

Parses PACKET_TYPE_AUDIO_OPUS_BATCH packet and extracts metadata and Opus data. The Opus data and frame_sizes pointers point into the packet_data buffer (NOT copied), so packet_data must remain valid while using these outputs.

Packet format:

  • Offset 0-3: sample_rate (uint32_t, network byte order)
  • Offset 4-7: frame_duration (uint32_t, network byte order)
  • Offset 8-11: frame_count (uint32_t, network byte order)
  • Offset 12-15: reserved (4 bytes, zeroed)
  • Offset 16+: frame_sizes array (uint16_t[], network byte order)
  • After sizes: Opus-encoded data (concatenated frames)
Parameters
packet_dataPacket payload data
packet_lenPacket payload length
out_opus_dataOutput: Pointer to Opus-encoded data within packet (NOT copied)
out_opus_sizeOutput: Size of Opus-encoded data
out_frame_sizesOutput: Pointer to frame sizes array within packet (NOT copied)
out_sample_rateOutput: Sample rate in Hz
out_frame_durationOutput: Frame duration in milliseconds
out_frame_countOutput: Number of frames in batch
Returns
ASCIICHAT_OK on success, error code on failure:
  • ERROR_INVALID_PARAM: NULL pointers
  • ERROR_NETWORK_PROTOCOL: Packet too small or malformed
Note
out_opus_data and out_frame_sizes point into packet_data - do not free separately
Frame sizes in out_frame_sizes are in NETWORK byte order - use NET_TO_HOST_U16() when reading
Warning
packet_data must remain valid while using out_opus_data and out_frame_sizes

Definition at line 194 of file network/packet/parsing.c.

195 {
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 NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned short uint16_t
unsigned int uint32_t
unsigned char uint8_t
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:81
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define NETWORK_PACKET_PARSING_HEX_BUFFER_SIZE

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK_PROTOCOL, log_error, NET_TO_HOST_U32, NETWORK_PACKET_PARSING_HEX_BUFFER_SIZE, and SET_ERRNO.

Referenced by handle_audio_opus_batch_packet().

◆ packet_validate_frame_dimensions()

asciichat_error_t packet_validate_frame_dimensions ( uint32_t width,
uint32_t height,
size_t * out_rgb_size )

#include <include/ascii-chat/network/packet/parsing.h>

Validate frame dimensions and calculate RGB buffer size.

Performs comprehensive validation of frame dimensions:

  1. Checks width and height are non-zero and reasonable (< 32768)
  2. Calculates RGB buffer size (width * height * 3) with overflow checking
  3. Validates result size doesn't exceed max image size (256MB)

OVERFLOW PROTECTION:

  • Uses safe_size_mul() for dimension multiplication
  • Checks for integer overflow at each step
  • Returns error instead of wrapping around
Parameters
widthFrame width in pixels
heightFrame height in pixels
out_rgb_sizeOutput parameter: calculated RGB size (width*height*3)
Returns
ASCIICHAT_OK on success, error code on failure:
  • ERROR_INVALID_STATE: width or height is zero
  • ERROR_INVALID_STATE: dimensions exceed max (32768)
  • ERROR_MEMORY: Calculated size exceeds max (256MB)
  • ERROR_MEMORY: Integer overflow in multiplication
Note
Critical for preventing integer overflow attacks
Used by both server and client frame handlers

Definition at line 153 of file network/packet/parsing.c.

153 {
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}
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
#define safe_size_mul
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
#define PACKET_MAX_DIMENSION
Maximum frame dimension (32768x32768) - prevents overflow.
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
#define NETWORK_PACKET_PARSING_SIZE_BUFFER_SIZE

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, format_bytes_pretty(), height, NETWORK_PACKET_PARSING_SIZE_BUFFER_SIZE, PACKET_MAX_DIMENSION, PACKET_MAX_FRAME_SIZE, safe_size_mul, SET_ERRNO, and width.