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 Module

🌐 Core network I/O operations with timeout support More...

Files

file  frame_validator.c
 Frame validation implementation for IMAGE_FRAME packets.
file  client.c
 πŸŒ HTTPS client with BearSSL for fetching public keys from GitHub/GitLab with CA validation
file  network.c
 πŸŒ Cross-platform socket I/O with timeout management and connection handling
file  callback_timing.c
 WebSocket callback timing instrumentation implementation.
file  server.c
 WebSocket server implementation.
file  protocol.h
 Server packet processing and protocol implementation.
file  protocol.h
 ascii-chat Binary Network Protocol (complete system including ACIP discovery service)
file  dns.h
 πŸŒ DNS resolution utilities
file  frame_validator.h
 Frame validation utilities for IMAGE_FRAME packets.
file  client.h
 Simple HTTPS client for fetching public keys from GitHub/GitLab.
file  network.h
 πŸŒ Core network I/O operations with timeout support
file  parallel_connect.h
 Parallel IPv4/IPv6 connection with race-to-connect semantics.
file  tailscale.h
 Tailscale host identity helpers.
file  update_checker.h
 πŸ”„ Update checker for GitHub releases with DNS connectivity test and cache
file  callback_timing.h
 WebSocket callback timing instrumentation.
file  internal.h
 Internal WebSocket implementation types shared between transport.c and server.c.
file  server.h
 WebSocket server for accepting browser client connections.

Data Structures

struct  packet_header_t
 Fixed prefix shared by every ACIP packet on the wire. More...
struct  size_packet_t
 Terminal size update packet. More...
struct  client_info_packet_t
 Client information packet structure. More...
struct  stream_header_t
 Stream header packet structure. More...
struct  client_list_packet_t
 Snapshot of the clients currently known to the server. More...
struct  server_state_packet_t
 Server state packet structure. More...
struct  error_packet_t
 Error packet structure carrying error code and textual description. More...
struct  remote_log_packet_t
 Remote log packet structure carrying log level and message text. More...
struct  auth_failure_packet_t
 Authentication failure packet structure. More...
struct  protocol_version_packet_t
 Protocol version negotiation packet structure (Packet Type 1). More...
struct  ascii_frame_packet_t
 The wire metadata for one rendered ASCII frame. width and height describe the terminal grid, original_size and compressed_size bound the encoded text, and checksum detects corruption; flags carry frame-specific options. The variable text follows this fixed prefix and is owned by the packet storage until decoding completes. More...
struct  image_frame_packet_t
 Describes one compressed image sent through ACIP. width, height, and pixel_format tell the decoder how to interpret the payload; compressed_size bounds the following bytes, and checksum plus timestamp support validation and frame ordering. The packet header is fixed-size, but the image bytes are variable-length and owned by the packet buffer. More...
struct  audio_batch_packet_t
 The metadata prefix for a batch of encoded audio samples. batch_count, total_samples, sample_rate, and channels let the receiver allocate or route the batch correctly before it touches the encoded payload. The header is serialized with the packet; the audio bytes remain in the enclosing packet buffer. More...
struct  crypto_capabilities_packet_t
 Crypto capabilities packet structure (Packet Type 14). More...
struct  crypto_parameters_packet_t
 Crypto parameters packet structure (Packet Type 15). More...
struct  terminal_capabilities_packet_t
 Terminal capabilities packet structure (Packet Type 5). More...
struct  packet_envelope_t
 Packet envelope containing received packet data. More...
struct  update_check_result_t
 update check result keeps the values that move through the subsystem: update_available, last_check_time, dismissed_until, check_succeeded. Some members are pointers into caller- or subsystem-owned memory, so lifetime follows the API that populated them rather than the struct copy itself. More...

Macros

#define NETWORK_PACKET_TERM_TYPE_BUFFER_SIZE   32
#define NETWORK_PACKET_COLORTERM_BUFFER_SIZE   32
#define NETWORK_PACKET_PALETTE_CUSTOM_BUFFER_SIZE   64
#define ACIP_OPUS_BATCH_HEADER_SIZE   16
#define REMOTE_LOG_FLAG_TRUNCATED   0x0001U
 Remote log packet flag definitions.
#define NETWORK_UPDATE_CHECKER_LATEST_VERSION_BUFFER_SIZE   64
#define NETWORK_UPDATE_CHECKER_LATEST_SHA_BUFFER_SIZE   41
#define NETWORK_UPDATE_CHECKER_CURRENT_VERSION_BUFFER_SIZE   64
#define NETWORK_UPDATE_CHECKER_CURRENT_SHA_BUFFER_SIZE   41
#define NETWORK_UPDATE_CHECKER_RELEASE_URL_BUFFER_SIZE   512

Enumerations

enum  packet_type_t {
  PACKET_TYPE_PROTOCOL_VERSION = 1 , PACKET_TYPE_CRYPTO_CLIENT_HELLO = 1000 , PACKET_TYPE_CRYPTO_CAPABILITIES = 1100 , PACKET_TYPE_CRYPTO_PARAMETERS = 1101 ,
  PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT = 1102 , PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP = 1103 , PACKET_TYPE_CRYPTO_AUTH_CHALLENGE = 1104 , PACKET_TYPE_CRYPTO_AUTH_RESPONSE = 1105 ,
  PACKET_TYPE_CRYPTO_AUTH_FAILED = 1106 , PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP = 1107 , PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE = 1108 , PACKET_TYPE_CRYPTO_NO_ENCRYPTION = 1109 ,
  PACKET_TYPE_QUIC_READY = 1110 , PACKET_TYPE_QUIC_KEYFRAME_REQUEST = 1111 , PACKET_TYPE_CRYPTO_EPOCH_MARKER = 1112 , PACKET_TYPE_CRYPTO_REKEY_NEEDED = 1113 ,
  PACKET_TYPE_CRYPTO_EPOCH_ACK = 1114 , PACKET_TYPE_ENCRYPTED = 1200 , PACKET_TYPE_CRYPTO_REKEY_REQUEST = 1201 , PACKET_TYPE_CRYPTO_REKEY_RESPONSE = 1202 ,
  PACKET_TYPE_CRYPTO_REKEY_COMPLETE = 1203 , PACKET_TYPE_SIZE_MESSAGE = 2000 , PACKET_TYPE_AUDIO_MESSAGE = 2001 , PACKET_TYPE_TEXT_MESSAGE = 2002 ,
  PACKET_TYPE_ERROR_MESSAGE = 2003 , PACKET_TYPE_REMOTE_LOG = 2004 , PACKET_TYPE_ASCII_FRAME = 3000 , PACKET_TYPE_IMAGE_FRAME = 3001 ,
  PACKET_TYPE_IMAGE_FRAME_H265 = 3002 , PACKET_TYPE_IMAGE_FRAME_H264 = 3003 , PACKET_TYPE_AUDIO_BATCH = 4000 , PACKET_TYPE_AUDIO_OPUS_BATCH = 4001 ,
  PACKET_TYPE_CLIENT_CAPABILITIES = 5000 , PACKET_TYPE_PING = 5001 , PACKET_TYPE_PONG = 5002 , PACKET_TYPE_CLIENT_JOIN = 5003 ,
  PACKET_TYPE_CLIENT_LEAVE = 5004 , PACKET_TYPE_STREAM_START = 5005 , PACKET_TYPE_STREAM_STOP = 5006 , PACKET_TYPE_CLEAR_CONSOLE = 5007 ,
  PACKET_TYPE_SERVER_STATE = 5008 , PACKET_TYPE_ACIP_SESSION_CREATE = 6000 , PACKET_TYPE_ACIP_SESSION_CREATED = 6001 , PACKET_TYPE_ACIP_SESSION_LOOKUP = 6002 ,
  PACKET_TYPE_ACIP_SESSION_INFO = 6003 , PACKET_TYPE_ACIP_SESSION_JOIN = 6004 , PACKET_TYPE_ACIP_SESSION_JOINED = 6005 , PACKET_TYPE_ACIP_SESSION_LEAVE = 6006 ,
  PACKET_TYPE_ACIP_SESSION_END = 6007 , PACKET_TYPE_ACIP_SESSION_RECONNECT = 6008 , PACKET_TYPE_ACIP_WEBRTC_SDP = 6009 , PACKET_TYPE_ACIP_WEBRTC_ICE = 6010 ,
  PACKET_TYPE_ACIP_STRING_RESERVE = 6020 , PACKET_TYPE_ACIP_STRING_RESERVED = 6021 , PACKET_TYPE_ACIP_STRING_RENEW = 6022 , PACKET_TYPE_ACIP_STRING_RELEASE = 6023 ,
  PACKET_TYPE_ACIP_PARTICIPANT_LIST = 6050 , PACKET_TYPE_ACIP_RING_COLLECT = 6051 , PACKET_TYPE_ACIP_NETWORK_QUALITY = 6060 , PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT = 6061 ,
  PACKET_TYPE_ACIP_HOST_DESIGNATED = 6062 , PACKET_TYPE_ACIP_SETTINGS_SYNC = 6063 , PACKET_TYPE_ACIP_SETTINGS_ACK = 6064 , PACKET_TYPE_ACIP_HOST_LOST = 6065 ,
  PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED = 6066 , PACKET_TYPE_ACIP_PARTICIPANT_JOINED = 6067 , PACKET_TYPE_ACIP_PARTICIPANT_LEFT = 6068 , PACKET_TYPE_ACIP_BANDWIDTH_TEST = 6070 ,
  PACKET_TYPE_ACIP_BANDWIDTH_RESULT = 6071 , PACKET_TYPE_ACIP_BROADCAST_ACK = 6075 , PACKET_TYPE_RING_MEMBERS = 6100 , PACKET_TYPE_STATS_COLLECTION_START = 6101 ,
  PACKET_TYPE_STATS_UPDATE = 6102 , PACKET_TYPE_RING_ELECTION_RESULT = 6103 , PACKET_TYPE_STATS_ACK = 6104 , PACKET_TYPE_ACIP_DISCOVERY_PING = 6190 ,
  PACKET_TYPE_ACIP_ERROR = 6199
}
 Network protocol packet type enumeration. More...
enum  auth_failure_reason_t {
  AUTH_FAIL_PASSWORD_REQUIRED = 0x01 , AUTH_FAIL_PASSWORD_INCORRECT = 0x02 , AUTH_FAIL_CLIENT_KEY_REQUIRED = 0x04 , AUTH_FAIL_CLIENT_KEY_REJECTED = 0x08 ,
  AUTH_FAIL_SIGNATURE_INVALID = 0x10
}
 Authentication failure reason flags. More...
enum  packet_recv_result_t { PACKET_RECV_SUCCESS = 0 , PACKET_RECV_EOF = -1 , PACKET_RECV_ERROR = -2 , PACKET_RECV_SECURITY_VIOLATION = -3 }
 packet envelope is intentionally a small, concrete record. Fields such as type, data, len, was_encrypted give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystemβ€”not independently managed. More...
enum  install_method_t {
  INSTALL_METHOD_HOMEBREW , INSTALL_METHOD_SCOOP , INSTALL_METHOD_ARCH_AUR , INSTALL_METHOD_INSTALLER ,
  INSTALL_METHOD_GITHUB , INSTALL_METHOD_UNKNOWN
}
 Installation method for suggesting upgrade command. More...

Functions

bool dns_test_connectivity (const char *hostname)
 Test DNS connectivity by resolving a hostname.
asciichat_error_t frame_validate_legacy (size_t len, size_t expected_rgb_size)
 Validate legacy frame format.
asciichat_error_t frame_validate_new (void *data, size_t len, bool *out_compressed, uint32_t *out_data_size)
 Validate new frame format with optional compression.
asciichat_error_t frame_check_size_overflow (size_t header_size, size_t data_size)
 Check for overflow when adding header to data.
void frame_extract_dimensions (const void *data, uint32_t *width, uint32_t *height)
 Extract width and height from frame header.
void frame_extract_new_header (const void *data, uint32_t *compressed, uint32_t *data_size)
 Extract compressed flag and data size from new format header.
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)
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)
asciichat_error_t packet_validate (const void *packet, size_t length, size_t limit, packet_header_t *header)
void protocol_version_packet_init (protocol_version_packet_t *version, uint8_t supports_encryption)
 Initialize a protocol version packet with the current wire version.
asciichat_error_t update_check_perform (update_check_result_t *result)
 Check for updates from GitHub releases API.
asciichat_error_t update_check_load_cache (update_check_result_t *result)
 Load cached update check result.
asciichat_error_t update_check_save_cache (const update_check_result_t *result)
 Save update check result to cache.
void update_check_dismiss_for_a_week (update_check_result_t *result)
bool update_check_is_dismissed (const update_check_result_t *result)
bool update_check_is_cache_fresh (const update_check_result_t *result)
 Check if cache is fresh (< 7 days old).
bool update_check_try_fresh_cache (update_check_result_t *result)
install_method_t update_check_detect_install_method (void)
 Detect installation method.
void update_check_get_upgrade_suggestion (install_method_t method, const char *latest_version, char *buffer, size_t buffer_size)
 Get upgrade suggestion string.
const char * update_check_get_aur_helper (void)
void update_check_format_notification (const update_check_result_t *result, char *buffer, size_t buffer_size)
 Format update notification message.
asciichat_error_t update_check_startup (update_check_result_t *result)
 Perform startup update check with caching.

HTTPS Client

char * https_get (const char *hostname, const char *path)
 Perform HTTPS GET request.

Socket I/O Operations

ssize_t send_with_timeout (socket_t sockfd, const void *data, size_t len, uint64_t timeout_ns)
 Send data with timeout using chunked transmission.
ssize_t recv_with_timeout (socket_t sockfd, void *buf, size_t len, uint64_t timeout_ns)
 Receive data with timeout.
int accept_with_timeout (socket_t listenfd, struct sockaddr *addr, socklen_t *addrlen, uint64_t timeout_ns)
 Accept connection with timeout.
bool connect_with_timeout (socket_t sockfd, const struct sockaddr *addr, socklen_t addrlen, int timeout_seconds)
 Connect to server with timeout.

Socket Configuration Functions

asciichat_error_t set_socket_timeout (socket_t sockfd, uint64_t timeout_ns)
 Set socket timeout for send/receive operations.
asciichat_error_t set_socket_keepalive (socket_t sockfd)
 Enable TCP keepalive on socket.
asciichat_error_t set_socket_nonblocking (socket_t sockfd)
 Set socket to non-blocking mode.
asciichat_error_t socket_configure_buffers (socket_t sockfd)
 Configure socket buffers and TCP_NODELAY for optimal performance.

Error Reporting Functions

const char * network_error_string ()
 Get human-readable error string for network errors.

Basic Packet I/O Functions

asciichat_error_t packet_send (socket_t sockfd, packet_type_t type, const void *data, size_t len)
 Send a packet with header and CRC32 checksum.
asciichat_error_t packet_receive (socket_t sockfd, packet_type_t *type, void **data, size_t *len)
 Receive a packet with header validation and CRC32 checking.

Secure Packet I/O Functions

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.
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.
asciichat_error_t packet_decrypt_envelope (packet_envelope_t *envelope, void *crypto_ctx)
 Decrypt a PACKET_TYPE_ENCRYPTED envelope and extract inner packet.
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)
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.
void packet_envelope_release (packet_envelope_t *envelope)

Legacy Packet I/O Functions

These functions provide basic packet I/O without encryption support. Use send_packet_secure() and receive_packet_secure() for encryption support.

int send_packet (socket_t sockfd, packet_type_t type, const void *data, size_t len)
 Send a basic packet without encryption.
int receive_packet (socket_t sockfd, packet_type_t *type, void **data, size_t *len)
 Receive a basic packet without encryption.

Protocol Packet Functions

Convenience functions for sending specific protocol packets. These functions construct the appropriate packet structure and send it over the socket.

int send_ping_packet (socket_t sockfd)
 Send a ping packet (keepalive).
int send_pong_packet (socket_t sockfd)
 Send a pong packet (keepalive response).
int send_protocol_version_packet (socket_t sockfd, const protocol_version_packet_t *version)
 Send protocol version negotiation packet.
int send_crypto_capabilities_packet (socket_t sockfd, const crypto_capabilities_packet_t *caps)
 Send crypto capabilities packet.
int send_crypto_parameters_packet (socket_t sockfd, const crypto_parameters_packet_t *params)
 Send crypto parameters packet.
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.
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.
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.
size_t packet_format_error_stack (char *buffer, size_t size)
 Format the current thread's error stack for transport to a peer.
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.
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.
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.

Network Timeout Constants

Timeout values tuned for real-time video streaming. All timeouts are specified in seconds.

#define CONNECT_TIMEOUT   3
 Connection timeout in seconds (3 seconds).
#define SEND_TIMEOUT   1
 Send timeout in seconds (5 seconds).
#define RECV_TIMEOUT   1
 Receive timeout in seconds (1 second).
#define ACCEPT_TIMEOUT   1
 Accept timeout in seconds (1 second).

Test Environment Detection

#define network_is_test_environment()
 Check if we're in a test environment.

Socket Keepalive Settings

Keepalive settings to detect dead connections. TCP keepalive probes are sent when connection is idle to detect broken connections.

#define KEEPALIVE_IDLE   60
 Keepalive idle time in seconds (60 seconds).
#define KEEPALIVE_INTERVAL   10
 Keepalive interval in seconds (10 seconds).
#define KEEPALIVE_COUNT   8
 Keepalive probe count (8 probes).

Network Protocol Constants

Announces the key-exchange, authentication, and cipher algorithms an endpoint is willing to use. The supported-algorithm fields are capability bitmasks or lists, while the preferred values guide selection; the receiver uses this packet to build the later crypto-parameters message rather than keeping it as session state.

Fixed prefix shared by every ACIP packet on the wire

The first ACIP negotiation packet exchanged by two peers. Its protocol version and revision fields establish wire compatibility, while the encryption, compression, and feature flags tell the receiver which later packet paths are safe to use. It is assembled for transmission and parsed into host-sized values on receipt.

Terminal size update packet

When code needs to work with server state packet, it keeps connected_client_count, active_client_count here instead of scattering it across globals. Initialization establishes the handles and sizes; teardown must release any allocation, lock, thread, or callback context recorded in those fields.

For stream header, this is the live record that ties client_id, stream_type, timestamp together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.

The ACIP packet sent when a terminal announces what it can render. capabilities and color_level describe feature support, while width, height, and render_mode let the peer choose a compatible output format. The packed fields are serialized directly; do not treat this as a long-lived heap object.

#define LARGE_PACKET_THRESHOLD   (100 * 1024)
 Large packet size threshold (100KB).
#define MAX_PACKET_SIZE   ((size_t)5 * 1024 * 1024)
 Maximum packet size (5MB).
#define MAX_ERROR_MESSAGE_LENGTH   4096
 Maximum error message length (512 bytes).
#define MAX_REMOTE_LOG_MESSAGE_LENGTH   512
 Maximum remote log message length (512 bytes).

Timeout Configuration Constants

Timeout constants for handling packets of different sizes. Large packets require extended timeouts for successful transmission.

#define BASE_SEND_TIMEOUT   (5LL * NS_PER_SEC_INT)
 Base send timeout in nanoseconds (5 seconds).
#define LARGE_PACKET_EXTRA_TIMEOUT_PER_MB   (800LL * NS_PER_MS_INT)
 Extra timeout per MB for large packets (0.8 seconds per MB).
#define MIN_CLIENT_TIMEOUT   (10LL * NS_PER_SEC_INT)
 Minimum client timeout in nanoseconds (10 seconds).
#define MAX_CLIENT_TIMEOUT   (60LL * NS_PER_SEC_INT)
 Maximum client timeout in nanoseconds (60 seconds).

Audio Batching Constants

Audio batching configuration for efficient audio transmission. Batched audio reduces packet overhead and improves bandwidth usage.

#define AUDIO_BATCH_COUNT   32
 Number of audio chunks per batch (4 chunks).
#define AUDIO_BATCH_SAMPLES   (AUDIO_SAMPLES_PER_PACKET * AUDIO_BATCH_COUNT)
 Total samples in audio batch (8192 samples).
#define AUDIO_BATCH_MS   186
 Audio batch duration in milliseconds (~186ms).
#define AUDIO_SAMPLES_PER_PACKET   256
 Samples per audio packet (256 samples).

Protocol Constants

#define PACKET_MAGIC   MAGIC_PACKET_VALID
 Packet magic number (alias for MAGIC_PACKET_VALID).

Multi-User Protocol Constants

#define ASCIICHAT_DEFAULT_DISPLAY_NAME   "AsciiChatter"
 Default display name for clients without a custom name.

Protocol Negotiation Constants

#define FEATURE_RLE_ENCODING   0x01
 Feature flags for protocol_version_packet_t.
#define FEATURE_DELTA_FRAMES   0x02
 Delta frame encoding (future).
#define PROTOCOL_FEATURE_RECOVERABLE_ERRORS   0x04
#define PROTOCOL_FEATURE_IDENTITY_SET   0x08

Client Capability Flags

Bitmask flags for client capabilities in multi-user protocol.

#define CLIENT_CAP_VIDEO   0x01
 Client can send/receive video.
#define CLIENT_CAP_AUDIO   0x02
 Client can send/receive audio.
#define CLIENT_CAP_COLOR   0x04
 Client supports color rendering.
#define CLIENT_CAP_STRETCH   0x08
 Client can stretch frames to fill terminal.

Stream Type Flags

Bitmask flags for stream types in multi-user protocol.

#define STREAM_TYPE_VIDEO   0x01
 Video stream.
#define STREAM_TYPE_AUDIO   0x02
 Audio stream.

Crypto Algorithm Constants

Algorithm identifiers for key exchange, authentication, and encryption. Used in crypto handshake packet negotiation.

#define KEX_ALGO_X25519   0x01
 X25519 key exchange (Curve25519).
#define AUTH_ALGO_ED25519   0x01
 Ed25519 authentication (Edwards-curve signatures).
#define AUTH_ALGO_NONE   0x00
 No authentication (plaintext mode).
#define CIPHER_ALGO_XSALSA20_POLY1305   0x01
 XSalsa20-Poly1305 authenticated encryption.
#define CIPHER_ALGO_NONE   0x00
 No encryption (plaintext mode).

Crypto Mode Bitmasks

2-bit bitmask for encryption and authentication modes

These constants define all valid combinations of encryption and authentication in the crypto protocol. The supports_encryption field in protocol_version_packet_t uses these values to negotiate capabilities:

  • Bit 0 (0x01): ACIP_CRYPTO_ENCRYPT - payload encryption enabled
  • Bit 1 (0x02): ACIP_CRYPTO_AUTH - identity authentication enabled
#define ACIP_CRYPTO_NONE   0x00
 No encryption, no authentication (plaintext only).
#define ACIP_CRYPTO_ENCRYPT   0x01
 Encryption only (no identity verification).
#define ACIP_CRYPTO_AUTH   0x02
 Authentication only (no payload encryption).
#define ACIP_CRYPTO_FULL   0x03
 Full crypto: encryption + authentication.
#define ACIP_CRYPTO_HAS_ENCRYPT(mode)
 Check if crypto mode includes payload encryption.
#define ACIP_CRYPTO_HAS_AUTH(mode)
 Check if crypto mode includes authentication.

Detailed Description

🌐 Core network I/O operations with timeout support

Provides DNS resolution and connectivity testing utilities.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

This module provides basic HTTPS GET functionality using BearSSL for TLS. It's designed specifically for fetching SSH/GPG public keys from GitHub and GitLab.

Note
TLS library: Uses BearSSL for TLS connections. BearSSL is a minimal TLS implementation with system CA certificate support.
Security: Uses system CA certificates for trust validation (20-year longevity). Validates server certificates against system trust store.
Key fetching: Fetches keys from GitHub/GitLab endpoints:
Key fetching functions: fetch_github_ssh_keys, fetch_gitlab_ssh_keys, fetch_github_gpg_keys, and fetch_gitlab_gpg_keys are in crypto/keys/https_keys.h. They properly belong in the keys module.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This module provides fundamental network I/O operations including socket management, timeout handling, and basic send/receive operations. All operations support configurable timeouts to prevent indefinite blocking, critical for real-time video streaming applications.

CORE RESPONSIBILITIES:

  1. Socket I/O operations with timeout support
  2. Connection management (connect, accept) with timeouts
  3. Socket configuration (keepalive, non-blocking, timeouts)
  4. Chunked transmission for large data transfers
  5. Error reporting and diagnostics

ARCHITECTURAL OVERVIEW:

TIMEOUT SYSTEM:

  • All I/O operations support configurable timeouts
  • Timeouts are tuned for real-time video streaming requirements
  • Chunked transmission prevents large data from blocking indefinitely
  • Platform-specific timeout implementation (select/poll/epoll)

SOCKET CONFIGURATION:

  • Keepalive settings to detect dead connections
  • Non-blocking mode support for asynchronous I/O
  • Socket-level timeout configuration
  • Platform abstraction for cross-platform compatibility

ERROR HANDLING:

  • Comprehensive error reporting with human-readable messages
  • Platform-specific error code translation
  • Network error string utilities

INTEGRATION WITH OTHER MODULES:

  • platform/socket.h: Uses platform socket abstraction
  • Used by packet.h for packet transmission
  • Used by av.h for media packet sending
  • Used by handshake.c for crypto handshake operations

PERFORMANCE CHARACTERISTICS:

  • Chunked transmission enables progressive sending of large frames
  • Timeout handling prevents indefinite blocking
  • Keepalive settings detect dead connections efficiently
  • Platform-specific optimizations where available
Note
Timeout values are tuned for real-time video streaming. Adjust CONNECT_TIMEOUT, SEND_TIMEOUT, and RECV_TIMEOUT if needed for different network conditions.
Chunked transmission is used automatically for large data to prevent timeouts and enable progress tracking.
Warning
Timeout values that are too short may cause false positives on slow networks. Values that are too long may delay error detection unnecessarily.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025
Version
2.0 (Post-Modularization)

This module provides comprehensive packet protocol implementation including packet verification, CRC validation, protocol compliance checking, encryption support, and compression integration. It serves as the core network protocol layer for ascii-chat's communication system.

CORE RESPONSIBILITIES:

  1. Packet header validation and CRC32 checksum verification
  2. Secure packet transmission with encryption support
  3. Secure packet reception with decryption and validation
  4. Protocol compliance checking and error handling
  5. Integration with cryptographic and compression subsystems

ARCHITECTURAL OVERVIEW:

PACKET STRUCTURE:

  • Header: Magic number, type, length, CRC32, client ID
  • Payload: Variable-length data (may be encrypted/compressed)
  • Validation: CRC32 checksum for integrity verification

ENCRYPTION INTEGRATION:

  • Automatic encryption/decryption when crypto context provided
  • Handshake packets always sent unencrypted (plaintext)
  • Session packets encrypted after handshake completion
  • Encryption policy enforcement (require/optional encryption)

COMPRESSION INTEGRATION:

  • Automatic compression for large packets (frames, audio)
  • Compression threshold-based decision making
  • Decompression on receive path

PROTOCOL VALIDATION:

  • Magic number validation to detect corruption
  • CRC32 checksum verification for integrity
  • Packet size validation to prevent attacks
  • Type validation for protocol compliance

INTEGRATION WITH OTHER MODULES:

PERFORMANCE CHARACTERISTICS:

  • Zero-copy operation when possible
  • Automatic memory management for packet buffers
  • Efficient CRC32 validation (hardware-accelerated when available)
  • Compression reduces bandwidth for large frames
Note
All packet functions handle encryption automatically when crypto context is provided. Plaintext packets are used for handshake.
Compression is automatically applied to large packets (frames, audio batches) based on size thresholds.
Warning
Packet buffers are allocated by receive functions and must be freed by caller using the allocated_buffer pointer.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025
Version
2.0 (Post-Modularization)

Provides automatic and manual update checking against GitHub releases API.

  • Checks once per week automatically at startup
  • Manual check via –check-update flag
  • DNS connectivity test before attempting HTTP request
  • Compares semantic versions to detect updates
  • Caches results in ~/.config/ascii-chat/last_update_check
  • Detects installation method (Homebrew, Arch AUR, GitHub)
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

Packet Queues

Queues own their nodes and payload references. Use packet_queue_push_copy() for a borrowed view, packet_queue_push_take() to move a buffer without copying, or packet_queue_push_shared() for immutable fan-out. Successful take clears the caller pointer; rejection preserves it. All operations return contextual asciichat_error_t errors.

Every queue has both a packet-count limit and a byte limit. The default overflow policy rejects new packets. DROP_OLDEST must be explicitly selected for independently discardable media such as raw frames or audio blocks. Do not select it for dependency-bearing encoded video without recovery logic.

One queue mutex protects admission, list mutation, accounting and reclamation. Nodes use the shared buffer API; there is no independent node allocator. Dequeue transfers the existing node without another allocation. Release with packet_queue_free_packet(). Dequeued packets can outlive their queue.

Stop rejects new admissions and hides queued data from consumers. Clear and destroy still drain stopped queues. Join queue users before destruction. Queued storage is released automatically; already dequeued packets remain owned by their consumers.

Macro Definition Documentation

◆ ACCEPT_TIMEOUT

#define ACCEPT_TIMEOUT   1

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

Accept timeout in seconds (1 second).

Maximum time to wait for incoming connections. Balanced between responsiveness and CPU usage. Status screen updates independently in its own thread at target FPS.

Definition at line 148 of file network.h.

◆ ACIP_CRYPTO_AUTH

#define ACIP_CRYPTO_AUTH   0x02

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

Authentication only (no payload encryption).

Definition at line 1163 of file packet.h.

Referenced by crypto_policy_resolve(), network_connection_establish(), and ClientSessionBinding::protocolInfo().

◆ ACIP_CRYPTO_ENCRYPT

#define ACIP_CRYPTO_ENCRYPT   0x01

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

Encryption only (no identity verification).

Definition at line 1162 of file packet.h.

Referenced by browser_client_init(), client_connection_create(), crypto_policy_resolve(), and ClientSessionBinding::protocolInfo().

◆ ACIP_CRYPTO_FULL

#define ACIP_CRYPTO_FULL   0x03

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

Full crypto: encryption + authentication.

Definition at line 1164 of file packet.h.

Referenced by acip_security_receive(), acip_security_start(), crypto_policy_check_mode(), and network_client_negotiate().

◆ ACIP_CRYPTO_HAS_AUTH

#define ACIP_CRYPTO_HAS_AUTH ( mode)

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

Value:
(((mode) & ACIP_CRYPTO_AUTH) != 0)
#define ACIP_CRYPTO_AUTH
Authentication only (no payload encryption).
Definition packet.h:1163

Check if crypto mode includes authentication.

Parameters
modeCrypto mode bitmask (ACIP_CRYPTO_*)
Returns
true if authentication is enabled, false otherwise

Definition at line 1178 of file packet.h.

Referenced by acip_security_receive(), browser_client_handshake_receive(), browser_session_receive(), client_handshake_receive(), and crypto_policy_check_mode().

◆ ACIP_CRYPTO_HAS_ENCRYPT

#define ACIP_CRYPTO_HAS_ENCRYPT ( mode)

◆ ACIP_CRYPTO_NONE

◆ ACIP_OPUS_BATCH_HEADER_SIZE

#define ACIP_OPUS_BATCH_HEADER_SIZE   16

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

Definition at line 81 of file packet.h.

Referenced by acip_send_audio_opus_batch().

◆ ASCIICHAT_DEFAULT_DISPLAY_NAME

#define ASCIICHAT_DEFAULT_DISPLAY_NAME   "AsciiChatter"

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

Default display name for clients without a custom name.

Used when a client connects without specifying a display name.

Definition at line 675 of file packet.h.

◆ AUDIO_BATCH_COUNT

#define AUDIO_BATCH_COUNT   32

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

Number of audio chunks per batch (4 chunks).

Number of audio chunks aggregated into a single batch packet for efficiency.

Definition at line 235 of file packet.h.

◆ AUDIO_BATCH_MS

#define AUDIO_BATCH_MS   186

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

Audio batch duration in milliseconds (~186ms).

Approximate duration of audio batch at 44.1kHz sample rate.

Definition at line 254 of file packet.h.

◆ AUDIO_BATCH_SAMPLES

#define AUDIO_BATCH_SAMPLES   (AUDIO_SAMPLES_PER_PACKET * AUDIO_BATCH_COUNT)

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

Total samples in audio batch (8192 samples).

Total audio samples across all chunks in a batch. At 44.1kHz, this equals ~185.8ms of audio.

Definition at line 245 of file packet.h.

Referenced by handle_audio_batch_packet().

◆ AUDIO_SAMPLES_PER_PACKET

#define AUDIO_SAMPLES_PER_PACKET   256

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

Samples per audio packet (256 samples).

Number of audio samples in a single audio packet. Smaller packets provide lower latency at the cost of increased packet overhead.

Definition at line 264 of file packet.h.

Referenced by handle_audio_packet().

◆ AUTH_ALGO_ED25519

#define AUTH_ALGO_ED25519   0x01

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

Ed25519 authentication (Edwards-curve signatures).

Definition at line 1144 of file packet.h.

Referenced by browser_client_handshake_receive(), browser_session_receive(), client_handshake_receive(), and crypto_handshake_server_send_parameters().

◆ AUTH_ALGO_NONE

#define AUTH_ALGO_NONE   0x00

◆ BASE_SEND_TIMEOUT

#define BASE_SEND_TIMEOUT   (5LL * NS_PER_SEC_INT)

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

Base send timeout in nanoseconds (5 seconds).

Default timeout for sending packets. Used as base value for calculating timeouts for large packets.

Definition at line 184 of file packet.h.

◆ CIPHER_ALGO_NONE

◆ CIPHER_ALGO_XSALSA20_POLY1305

#define CIPHER_ALGO_XSALSA20_POLY1305   0x01

◆ CLIENT_CAP_AUDIO

#define CLIENT_CAP_AUDIO   0x02

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

Client can send/receive audio.

Definition at line 1003 of file packet.h.

Referenced by handle_client_join_packet().

◆ CLIENT_CAP_COLOR

#define CLIENT_CAP_COLOR   0x04

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

Client supports color rendering.

Definition at line 1004 of file packet.h.

Referenced by handle_client_join_packet().

◆ CLIENT_CAP_STRETCH

#define CLIENT_CAP_STRETCH   0x08

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

Client can stretch frames to fill terminal.

Definition at line 1005 of file packet.h.

Referenced by handle_client_join_packet().

◆ CLIENT_CAP_VIDEO

#define CLIENT_CAP_VIDEO   0x01

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

Client can send/receive video.

Definition at line 1002 of file packet.h.

Referenced by handle_client_join_packet().

◆ CONNECT_TIMEOUT

#define CONNECT_TIMEOUT   3

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

Connection timeout in seconds (3 seconds).

Maximum time to wait for connection establishment. Reduced from default for faster connection attempts and quicker failure detection.

Definition at line 103 of file network.h.

◆ FEATURE_DELTA_FRAMES

#define FEATURE_DELTA_FRAMES   0x02

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

Delta frame encoding (future).

Definition at line 854 of file packet.h.

◆ FEATURE_RLE_ENCODING

#define FEATURE_RLE_ENCODING   0x01

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

Feature flags for protocol_version_packet_t.

Bitmask values for optional protocol features. Used in protocol negotiation to enable advanced capabilities.

Run-length encoding support

Definition at line 853 of file packet.h.

◆ KEEPALIVE_COUNT

#define KEEPALIVE_COUNT   8

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

Keepalive probe count (8 probes).

Number of keepalive probes to send before considering connection dead.

Definition at line 207 of file network.h.

Referenced by set_socket_keepalive().

◆ KEEPALIVE_IDLE

#define KEEPALIVE_IDLE   60

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

Keepalive idle time in seconds (60 seconds).

Time to wait before sending first keepalive probe after connection becomes idle.

Definition at line 189 of file network.h.

Referenced by set_socket_keepalive().

◆ KEEPALIVE_INTERVAL

#define KEEPALIVE_INTERVAL   10

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

Keepalive interval in seconds (10 seconds).

Interval between subsequent keepalive probes.

Definition at line 198 of file network.h.

Referenced by set_socket_keepalive().

◆ KEX_ALGO_X25519

#define KEX_ALGO_X25519   0x01

◆ LARGE_PACKET_EXTRA_TIMEOUT_PER_MB

#define LARGE_PACKET_EXTRA_TIMEOUT_PER_MB   (800LL * NS_PER_MS_INT)

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

Extra timeout per MB for large packets (0.8 seconds per MB).

Additional timeout added per MB for large packets to prevent premature timeout failures.

Definition at line 194 of file packet.h.

Referenced by packet_send_timeout_ns().

◆ LARGE_PACKET_THRESHOLD

#define LARGE_PACKET_THRESHOLD   (100 * 1024)

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

Large packet size threshold (100KB).

Packets larger than this threshold are considered "large" and may receive extended timeouts or compression treatment.

Definition at line 134 of file packet.h.

Referenced by packet_send_timeout_ns().

◆ MAX_CLIENT_TIMEOUT

#define MAX_CLIENT_TIMEOUT   (60LL * NS_PER_SEC_INT)

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

Maximum client timeout in nanoseconds (60 seconds).

Maximum timeout value for client operations. Prevents excessively long waits for dead connections.

Definition at line 214 of file packet.h.

Referenced by packet_send_timeout_ns().

◆ MAX_ERROR_MESSAGE_LENGTH

#define MAX_ERROR_MESSAGE_LENGTH   4096

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

Maximum error message length (512 bytes).

Error packets include a message payload. This defines the maximum number of bytes allowed in the message portion to prevent excessive allocations and potential abuse.

Definition at line 153 of file packet.h.

Referenced by acip_send_error(), network_error_decode(), packet_parse_error_message(), and packet_send_error().

◆ MAX_PACKET_SIZE

#define MAX_PACKET_SIZE   ((size_t)5 * 1024 * 1024)

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

Maximum packet size (5MB).

Absolute maximum size for any packet. Packets larger than this are rejected to prevent memory exhaustion attacks.

Definition at line 144 of file packet.h.

Referenced by acip_send_audio_batch(), acip_send_audio_opus_batch(), packet_decoder_feed(), packet_header_build(), packet_parse_envelope(), packet_send(), packet_validate(), receive_packet_secure_with_timeout(), and send_packet_secure().

◆ MAX_REMOTE_LOG_MESSAGE_LENGTH

#define MAX_REMOTE_LOG_MESSAGE_LENGTH   512

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

Maximum remote log message length (512 bytes).

Remote logging packets mirror the error packet structure but are intended for diagnostic log forwarding between client and server. Limiting the payload size keeps allocations predictable and prevents log flooding over the network.

Definition at line 163 of file packet.h.

Referenced by handle_remote_log_packet_from_client(), packet_parse_remote_log(), and packet_send_remote_log().

◆ MIN_CLIENT_TIMEOUT

#define MIN_CLIENT_TIMEOUT   (10LL * NS_PER_SEC_INT)

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

Minimum client timeout in nanoseconds (10 seconds).

Minimum timeout value for client operations. Set to server timeout plus buffer for reliable operation.

Definition at line 204 of file packet.h.

Referenced by packet_send_timeout_ns().

◆ network_is_test_environment

#define network_is_test_environment ( )

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

Value:
((int)is_test_environment())

Check if we're in a test environment.

Compatibility macro that calls is_test_environment() from tests/test_env.h. Used to adjust timeouts for faster test execution.

Returns
1 if test environment, 0 otherwise

Definition at line 168 of file network.h.

Referenced by send_with_timeout().

◆ NETWORK_PACKET_COLORTERM_BUFFER_SIZE

#define NETWORK_PACKET_COLORTERM_BUFFER_SIZE   32

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

Definition at line 77 of file packet.h.

◆ NETWORK_PACKET_PALETTE_CUSTOM_BUFFER_SIZE

#define NETWORK_PACKET_PALETTE_CUSTOM_BUFFER_SIZE   64

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

Definition at line 78 of file packet.h.

◆ NETWORK_PACKET_TERM_TYPE_BUFFER_SIZE

#define NETWORK_PACKET_TERM_TYPE_BUFFER_SIZE   32

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

Definition at line 76 of file packet.h.

◆ NETWORK_UPDATE_CHECKER_CURRENT_SHA_BUFFER_SIZE

#define NETWORK_UPDATE_CHECKER_CURRENT_SHA_BUFFER_SIZE   41

#include <include/ascii-chat/network/update_checker.h>

Definition at line 27 of file update_checker.h.

◆ NETWORK_UPDATE_CHECKER_CURRENT_VERSION_BUFFER_SIZE

#define NETWORK_UPDATE_CHECKER_CURRENT_VERSION_BUFFER_SIZE   64

#include <include/ascii-chat/network/update_checker.h>

Definition at line 26 of file update_checker.h.

◆ NETWORK_UPDATE_CHECKER_LATEST_SHA_BUFFER_SIZE

#define NETWORK_UPDATE_CHECKER_LATEST_SHA_BUFFER_SIZE   41

#include <include/ascii-chat/network/update_checker.h>

Definition at line 25 of file update_checker.h.

◆ NETWORK_UPDATE_CHECKER_LATEST_VERSION_BUFFER_SIZE

#define NETWORK_UPDATE_CHECKER_LATEST_VERSION_BUFFER_SIZE   64

#include <include/ascii-chat/network/update_checker.h>

Definition at line 24 of file update_checker.h.

◆ NETWORK_UPDATE_CHECKER_RELEASE_URL_BUFFER_SIZE

#define NETWORK_UPDATE_CHECKER_RELEASE_URL_BUFFER_SIZE   512

#include <include/ascii-chat/network/update_checker.h>

Definition at line 28 of file update_checker.h.

Referenced by update_check_perform().

◆ PACKET_MAGIC

#define PACKET_MAGIC   MAGIC_PACKET_VALID

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

Packet magic number (alias for MAGIC_PACKET_VALID).

Magic number used in packet headers for packet validation. Defined once in util/magic.h (0xA5C11C4A1 = "ASCIICHAT" in hex) and imported here for use in packet validation.

See also
MAGIC_PACKET_VALID

Definition at line 284 of file packet.h.

Referenced by acds_receive_packet(), packet_decoder_feed(), packet_header_build(), packet_queue_validate_packet(), packet_send(), packet_validate(), and receive_packet_secure_with_timeout().

◆ PROTOCOL_FEATURE_IDENTITY_SET

#define PROTOCOL_FEATURE_IDENTITY_SET   0x08

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

CLIENT_HELLO accepts a bounded set of pinned Ed25519 keys

Definition at line 856 of file packet.h.

◆ PROTOCOL_FEATURE_RECOVERABLE_ERRORS

#define PROTOCOL_FEATURE_RECOVERABLE_ERRORS   0x04

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

Peer accepts nonfatal audio error notifications

Definition at line 855 of file packet.h.

Referenced by handle_protocol_version_packet().

◆ RECV_TIMEOUT

#define RECV_TIMEOUT   1

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

Receive timeout in seconds (1 second).

Reduced to 1 second to allow snapshot mode to check elapsed time frequently and exit cleanly when snapshot_delay expires. With the longer 30-second timeout, clients in snapshot mode would block waiting for data and miss their snapshot window. The 1-second timeout balances responsiveness with network latency tolerance.

Definition at line 133 of file network.h.

Referenced by packet_receive(), and receive_packet_secure().

◆ REMOTE_LOG_FLAG_TRUNCATED

#define REMOTE_LOG_FLAG_TRUNCATED   0x0001U

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

Remote log packet flag definitions.

Message payload was truncated to fit the maximum length

Definition at line 787 of file packet.h.

Referenced by handle_remote_log_packet_from_client(), and packet_send_remote_log().

◆ SEND_TIMEOUT

#define SEND_TIMEOUT   1

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

Send timeout in seconds (5 seconds).

Maximum time to wait for data transmission. Video frames need timely delivery to maintain real-time performance.

Definition at line 116 of file network.h.

Referenced by packet_send_timeout_ns().

◆ STREAM_TYPE_AUDIO

#define STREAM_TYPE_AUDIO   0x02

◆ STREAM_TYPE_VIDEO

#define STREAM_TYPE_VIDEO   0x01

Enumeration Type Documentation

◆ auth_failure_reason_t

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

Authentication failure reason flags.

Bitmask enumeration for authentication failure reasons. Multiple flags can be combined to indicate multiple failure causes.

Enumerator
AUTH_FAIL_PASSWORD_REQUIRED 

Server requires password but client didn't provide one.

AUTH_FAIL_PASSWORD_INCORRECT 

Password verification failed (incorrect password).

AUTH_FAIL_CLIENT_KEY_REQUIRED 

Server requires client key but client didn't provide one.

AUTH_FAIL_CLIENT_KEY_REJECTED 

Client key not in whitelist (access denied).

AUTH_FAIL_SIGNATURE_INVALID 

Client signature verification failed (invalid signature).

Definition at line 812 of file packet.h.

812 {
auth_failure_reason_t
Authentication failure reason flags.
Definition packet.h:812
@ AUTH_FAIL_PASSWORD_INCORRECT
Password verification failed (incorrect password).
Definition packet.h:816
@ AUTH_FAIL_PASSWORD_REQUIRED
Server requires password but client didn't provide one.
Definition packet.h:814
@ AUTH_FAIL_CLIENT_KEY_REQUIRED
Server requires client key but client didn't provide one.
Definition packet.h:818
@ AUTH_FAIL_CLIENT_KEY_REJECTED
Client key not in whitelist (access denied).
Definition packet.h:820
@ AUTH_FAIL_SIGNATURE_INVALID
Client signature verification failed (invalid signature).
Definition packet.h:822

◆ install_method_t

#include <include/ascii-chat/network/update_checker.h>

Installation method for suggesting upgrade command.

Enumerator
INSTALL_METHOD_HOMEBREW 

Installed via Homebrew.

INSTALL_METHOD_SCOOP 

Installed via Scoop.

INSTALL_METHOD_ARCH_AUR 

Installed via Arch AUR (paru/yay).

INSTALL_METHOD_INSTALLER 

Installed by ascii-chat.com installer.

INSTALL_METHOD_GITHUB 

Manual install from GitHub releases.

INSTALL_METHOD_UNKNOWN 

Unknown installation method.

Definition at line 73 of file update_checker.h.

73 {
install_method_t
Installation method for suggesting upgrade command.
@ INSTALL_METHOD_ARCH_AUR
Installed via Arch AUR (paru/yay).
@ INSTALL_METHOD_UNKNOWN
Unknown installation method.
@ INSTALL_METHOD_GITHUB
Manual install from GitHub releases.
@ INSTALL_METHOD_INSTALLER
Installed by ascii-chat.com installer.
@ INSTALL_METHOD_SCOOP
Installed via Scoop.
@ INSTALL_METHOD_HOMEBREW
Installed via Homebrew.

◆ packet_recv_result_t

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

packet envelope is intentionally a small, concrete record. Fields such as type, data, len, was_encrypted give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystemβ€”not independently managed.

Packet reception result codes

Result codes for packet reception operations. Negative values indicate errors, zero indicates success.

Enumerator
PACKET_RECV_SUCCESS 

Packet received successfully.

PACKET_RECV_EOF 

Connection closed (EOF).

PACKET_RECV_ERROR 

Network error occurred.

PACKET_RECV_SECURITY_VIOLATION 

Encryption policy violation (e.g., unencrypted packet when encryption required).

Definition at line 1235 of file packet.h.

1235 {
1239 PACKET_RECV_EOF = -1,
1241 PACKET_RECV_ERROR = -2,
packet_recv_result_t
packet envelope is intentionally a small, concrete record. Fields such as type, data,...
Definition packet.h:1235
@ PACKET_RECV_ERROR
Network error occurred.
Definition packet.h:1241
@ PACKET_RECV_EOF
Connection closed (EOF).
Definition packet.h:1239
@ PACKET_RECV_SECURITY_VIOLATION
Encryption policy violation (e.g., unencrypted packet when encryption required).
Definition packet.h:1243
@ PACKET_RECV_SUCCESS
Packet received successfully.
Definition packet.h:1237

◆ packet_type_t

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

Network protocol packet type enumeration.

Defines all packet types used in the ascii-chat network protocol. Packet types are organized by priority: protocol negotiation, then all cryptographic operations, then media, control, audio, and messages.

PACKET CATEGORIES (with expansion room):

  • 1: Protocol negotiation
  • 2-1001: Cryptographic operations (1000 space reserved)
    • 2: Client hello (expansion room: 3-101)
    • 102-201: Handshake/exchange (expansion room: 113-201)
    • 202-301: Rekeying (expansion room: 205-301)
  • 1002-2001: Message packets (1000 space reserved)
  • 2002-3001: Media frame packets (1000 space reserved)
  • 3002-4001: Audio packets (1000 space reserved)
  • 4002-5001: Control/state packets (1000 space reserved)
  • 6001+: Discovery/ACIP protocol
Note
Crypto handshake packets (2-12) and rekey packets (14-16) are ALWAYS sent unencrypted. Use packet_is_handshake_type() to check.
PACKET_TYPE_ENCRYPTED (13) is used for encrypted session packets after handshake completion.
Enumerator
PACKET_TYPE_PROTOCOL_VERSION 

Protocol version and capabilities negotiation.

PACKET_TYPE_CRYPTO_CLIENT_HELLO 

Client -> Server: Expected server key fingerprint for multi-key selection (UNENCRYPTED).

PACKET_TYPE_CRYPTO_CAPABILITIES 

Client -> Server: Supported crypto algorithms (UNENCRYPTED).

PACKET_TYPE_CRYPTO_PARAMETERS 

Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).

PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT 

Server -> Client: {server_pubkey[32]} (UNENCRYPTED).

PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP 

Client -> Server: {client_pubkey[32]} (UNENCRYPTED).

PACKET_TYPE_CRYPTO_AUTH_CHALLENGE 

Server -> Client: {nonce[32]} (UNENCRYPTED).

PACKET_TYPE_CRYPTO_AUTH_RESPONSE 

Client -> Server: {HMAC[32]} (UNENCRYPTED).

PACKET_TYPE_CRYPTO_AUTH_FAILED 

Server -> Client: "authentication failed" (UNENCRYPTED).

PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP 

Server -> Client: {HMAC[32]} server proves knowledge (UNENCRYPTED).

PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE 

Server -> Client: "encryption ready" (UNENCRYPTED).

PACKET_TYPE_CRYPTO_NO_ENCRYPTION 

Client -> Server: "I want to proceed without encryption" (UNENCRYPTED).

PACKET_TYPE_QUIC_READY 

Internal authenticated readiness barrier for ACIP over QUIC.

PACKET_TYPE_QUIC_KEYFRAME_REQUEST 

Internal authenticated request for a QUIC encoded-video keyframe.

PACKET_TYPE_CRYPTO_EPOCH_MARKER 
PACKET_TYPE_CRYPTO_REKEY_NEEDED 
PACKET_TYPE_CRYPTO_EPOCH_ACK 
PACKET_TYPE_ENCRYPTED 

Encrypted packet (after handshake completion).

PACKET_TYPE_CRYPTO_REKEY_REQUEST 

Initiator -> Responder: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).

PACKET_TYPE_CRYPTO_REKEY_RESPONSE 

Responder -> Initiator: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).

PACKET_TYPE_CRYPTO_REKEY_COMPLETE 

Initiator -> Responder: Empty (encrypted with NEW key, but still handshake).

PACKET_TYPE_SIZE_MESSAGE 

Terminal size message.

PACKET_TYPE_AUDIO_MESSAGE 

Audio message.

PACKET_TYPE_TEXT_MESSAGE 

Text message.

PACKET_TYPE_ERROR_MESSAGE 

Error packet with asciichat_error_t code and human-readable message.

PACKET_TYPE_REMOTE_LOG 

Bidirectional remote logging packet.

PACKET_TYPE_ASCII_FRAME 

Complete ASCII frame with all metadata.

PACKET_TYPE_IMAGE_FRAME 

Complete RGB image with dimensions.

PACKET_TYPE_IMAGE_FRAME_H265 

H.265-encoded frame from client (HEVC/H.265 codec).

PACKET_TYPE_IMAGE_FRAME_H264 

H.264 Annex B access unit: flags:u8, width:u16be, height:u16be, data.

PACKET_TYPE_AUDIO_BATCH 

Batched audio packets for efficiency.

PACKET_TYPE_AUDIO_OPUS_BATCH 

Batched Opus-encoded audio frames.

PACKET_TYPE_CLIENT_CAPABILITIES 

Client reports terminal capabilities.

PACKET_TYPE_PING 

Keepalive ping packet.

PACKET_TYPE_PONG 

Keepalive pong response.

PACKET_TYPE_CLIENT_JOIN 

Client announces capability to send media.

PACKET_TYPE_CLIENT_LEAVE 

Clean disconnect notification.

PACKET_TYPE_STREAM_START 

Client requests to start sending video/audio.

PACKET_TYPE_STREAM_STOP 

Client stops sending media.

PACKET_TYPE_CLEAR_CONSOLE 

Server tells client to clear console.

PACKET_TYPE_SERVER_STATE 

Server sends current state to clients.

PACKET_TYPE_ACIP_SESSION_CREATE 

Create new session (Client -> Discovery Server).

PACKET_TYPE_ACIP_SESSION_CREATED 

Session created response (Discovery Server -> Client).

PACKET_TYPE_ACIP_SESSION_LOOKUP 

Lookup session by string (Client -> Discovery Server).

PACKET_TYPE_ACIP_SESSION_INFO 

Session info response (Discovery Server -> Client).

PACKET_TYPE_ACIP_SESSION_JOIN 

Join existing session (Client -> Discovery Server).

PACKET_TYPE_ACIP_SESSION_JOINED 

Session joined response (Discovery Server -> Client).

PACKET_TYPE_ACIP_SESSION_LEAVE 

Leave session (Client -> Discovery Server).

PACKET_TYPE_ACIP_SESSION_END 

End session (Host -> Discovery Server).

PACKET_TYPE_ACIP_SESSION_RECONNECT 

Reconnect to session (Client -> Discovery Server).

PACKET_TYPE_ACIP_WEBRTC_SDP 

WebRTC SDP offer/answer (bidirectional).

PACKET_TYPE_ACIP_WEBRTC_ICE 

WebRTC ICE candidate (bidirectional).

PACKET_TYPE_ACIP_STRING_RESERVE 

Reserve session string (Client -> Discovery Server).

PACKET_TYPE_ACIP_STRING_RESERVED 

String reserved response (Discovery Server -> Client).

PACKET_TYPE_ACIP_STRING_RENEW 

Renew string reservation (Client -> Discovery Server).

PACKET_TYPE_ACIP_STRING_RELEASE 

Release string reservation (Client -> Discovery Server).

PACKET_TYPE_ACIP_PARTICIPANT_LIST 

Participant list with ring order (ACDS -> Participants).

PACKET_TYPE_ACIP_RING_COLLECT 

Ring collect request (Participant -> Next Participant).

PACKET_TYPE_ACIP_NETWORK_QUALITY 

NETWORK_QUALITY exchange (unified packet for all quality metrics).

PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT 

Host announcement (Participant -> ACDS, "I won negotiation").

PACKET_TYPE_ACIP_HOST_DESIGNATED 

Host designated (ACDS -> All Participants).

PACKET_TYPE_ACIP_SETTINGS_SYNC 

Settings sync (Initiator -> Host -> All Participants).

PACKET_TYPE_ACIP_SETTINGS_ACK 

Settings acknowledgment (Participant -> Initiator).

PACKET_TYPE_ACIP_HOST_LOST 

Host lost notification - lightweight (Participant -> ACDS).

PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED 

Future host elected announcement (Quorum Leader -> ACDS -> All Participants).

PACKET_TYPE_ACIP_PARTICIPANT_JOINED 

Participant joined notification (ACDS -> Existing Participants).

PACKET_TYPE_ACIP_PARTICIPANT_LEFT 

Participant left notification (ACDS -> Remaining Participants).

PACKET_TYPE_ACIP_BANDWIDTH_TEST 

Bandwidth test request (Client -> ACDS).

PACKET_TYPE_ACIP_BANDWIDTH_RESULT 

Bandwidth test results (ACDS -> Client).

PACKET_TYPE_ACIP_BROADCAST_ACK 

Broadcast acknowledgment for reliable delivery.

PACKET_TYPE_RING_MEMBERS 

Ring member list announcement (ACDS -> All Participants).

PACKET_TYPE_STATS_COLLECTION_START 

Start statistics collection phase (Coordinator -> All Participants).

PACKET_TYPE_STATS_UPDATE 

Statistics update during collection phase (Participant -> Next Participant).

PACKET_TYPE_RING_ELECTION_RESULT 

Final election result (Quorum Leader -> All Participants).

PACKET_TYPE_STATS_ACK 

Acknowledgment of statistics update (Participant -> Sender).

PACKET_TYPE_ACIP_DISCOVERY_PING 

Discovery server ping (keepalive).

PACKET_TYPE_ACIP_ERROR 

Generic error response (Discovery Server -> Client).

Definition at line 315 of file packet.h.

315 {
318
319 // ============================================================================
320 // Cryptographic Operations (Types 1000-1999)
321 // ============================================================================
322
323 // ============================================================================
324 // Cryptographic Client Hello (Types 1000-1099)
325 // ============================================================================
326
329
330 // ============================================================================
331 // Cryptographic Handshake (Types 1100-1199)
332 // ============================================================================
333 // ALWAYS UNENCRYPTED (except ENCRYPTED which wraps encrypted data)
334
362
363 // ============================================================================
364 // Cryptographic Rekeying (Types 1200-1299)
365 // ============================================================================
366 // ALWAYS UNENCRYPTED during rekey phase
367
376
377 // ============================================================================
378 // Message Packets (Types 2000-2999)
379 // ============================================================================
380
391
392 // ============================================================================
393 // Media Frames (Types 3000-3999)
394 // ============================================================================
395
404
405 // ============================================================================
406 // Audio Packets (Types 4000-4999)
407 // ============================================================================
408
413
414 // ============================================================================
415 // Control/State Packets (Types 5000-5999)
416 // ============================================================================
417
421 PACKET_TYPE_PING = 5001,
423 PACKET_TYPE_PONG = 5002,
436
437 // ============================================================================
438 // Discovery Service Protocol (ACDS) (Types 6000+)
439 // ============================================================================
440 // ACIP packets use range 6000+ for discovery mode operations
441 // See network/acip/protocol.h for protocol overview and utility functions
442 // See network/acip/acds.h for ACDS message structures and detailed documentation
443
462
467
476
477 // ============================================================================
478 // Ring Consensus Protocol (6050-6051)
479 // ============================================================================
480 // Used for proactive future host election every 5 minutes
481
486
487 // ============================================================================
488 // Host Negotiation & Migration Protocol (6060-6069)
489 // ============================================================================
490 // Used by discovery mode for dynamic host selection and failover
491
510
511 // ============================================================================
512 // Bandwidth Testing (6070-6071)
513 // ============================================================================
514 // Used for measuring network bandwidth during NAT quality detection
515
520
523
524 // ============================================================================
525 // Ring Consensus Protocol (6100-6104)
526 // ============================================================================
527 // Used for collecting statistics and coordinating ring-based consensus
528
539
540 // ============================================================================
541 // Discovery Service Keepalive (6190-6199)
542 // ============================================================================
543
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
@ PACKET_TYPE_CRYPTO_CLIENT_HELLO
Client -> Server: Expected server key fingerprint for multi-key selection (UNENCRYPTED).
Definition packet.h:328
@ PACKET_TYPE_ACIP_WEBRTC_ICE
WebRTC ICE candidate (bidirectional).
Definition packet.h:466
@ PACKET_TYPE_QUIC_READY
Internal authenticated readiness barrier for ACIP over QUIC.
Definition packet.h:356
@ PACKET_TYPE_AUDIO_OPUS_BATCH
Batched Opus-encoded audio frames.
Definition packet.h:412
@ PACKET_TYPE_ACIP_PARTICIPANT_JOINED
Participant joined notification (ACDS -> Existing Participants).
Definition packet.h:507
@ PACKET_TYPE_CLIENT_LEAVE
Clean disconnect notification.
Definition packet.h:427
@ PACKET_TYPE_ACIP_SESSION_INFO
Session info response (Discovery Server -> Client).
Definition packet.h:451
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_CRYPTO_AUTH_RESPONSE
Client -> Server: {HMAC[32]} (UNENCRYPTED).
Definition packet.h:346
@ PACKET_TYPE_TEXT_MESSAGE
Text message.
Definition packet.h:386
@ PACKET_TYPE_AUDIO_MESSAGE
Audio message.
Definition packet.h:384
@ PACKET_TYPE_PONG
Keepalive pong response.
Definition packet.h:423
@ PACKET_TYPE_ACIP_SESSION_RECONNECT
Reconnect to session (Client -> Discovery Server).
Definition packet.h:461
@ PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE
Server -> Client: "encryption ready" (UNENCRYPTED).
Definition packet.h:352
@ PACKET_TYPE_ACIP_PARTICIPANT_LIST
Participant list with ring order (ACDS -> Participants).
Definition packet.h:483
@ PACKET_TYPE_STREAM_START
Client requests to start sending video/audio.
Definition packet.h:429
@ PACKET_TYPE_ACIP_SETTINGS_SYNC
Settings sync (Initiator -> Host -> All Participants).
Definition packet.h:499
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT
Server -> Client: {server_pubkey[32]} (UNENCRYPTED).
Definition packet.h:340
@ PACKET_TYPE_ACIP_ERROR
Generic error response (Discovery Server -> Client).
Definition packet.h:547
@ PACKET_TYPE_CRYPTO_EPOCH_MARKER
Definition packet.h:359
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP
Client -> Server: {client_pubkey[32]} (UNENCRYPTED).
Definition packet.h:342
@ PACKET_TYPE_CRYPTO_REKEY_COMPLETE
Initiator -> Responder: Empty (encrypted with NEW key, but still handshake).
Definition packet.h:375
@ PACKET_TYPE_ACIP_NETWORK_QUALITY
NETWORK_QUALITY exchange (unified packet for all quality metrics).
Definition packet.h:493
@ PACKET_TYPE_SERVER_STATE
Server sends current state to clients.
Definition packet.h:435
@ PACKET_TYPE_ACIP_HOST_LOST
Host lost notification - lightweight (Participant -> ACDS).
Definition packet.h:503
@ PACKET_TYPE_ACIP_BROADCAST_ACK
Broadcast acknowledgment for reliable delivery.
Definition packet.h:522
@ PACKET_TYPE_ACIP_HOST_DESIGNATED
Host designated (ACDS -> All Participants).
Definition packet.h:497
@ PACKET_TYPE_ACIP_STRING_RESERVE
Reserve session string (Client -> Discovery Server).
Definition packet.h:469
@ PACKET_TYPE_CRYPTO_AUTH_FAILED
Server -> Client: "authentication failed" (UNENCRYPTED).
Definition packet.h:348
@ PACKET_TYPE_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ PACKET_TYPE_CRYPTO_REKEY_REQUEST
Initiator -> Responder: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).
Definition packet.h:371
@ PACKET_TYPE_SIZE_MESSAGE
Terminal size message.
Definition packet.h:382
@ PACKET_TYPE_REMOTE_LOG
Bidirectional remote logging packet.
Definition packet.h:390
@ PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP
Server -> Client: {HMAC[32]} server proves knowledge (UNENCRYPTED).
Definition packet.h:350
@ PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT
Host announcement (Participant -> ACDS, "I won negotiation").
Definition packet.h:495
@ PACKET_TYPE_PROTOCOL_VERSION
Protocol version and capabilities negotiation.
Definition packet.h:317
@ PACKET_TYPE_ACIP_SETTINGS_ACK
Settings acknowledgment (Participant -> Initiator).
Definition packet.h:501
@ PACKET_TYPE_ACIP_BANDWIDTH_TEST
Bandwidth test request (Client -> ACDS).
Definition packet.h:517
@ PACKET_TYPE_CLEAR_CONSOLE
Server tells client to clear console.
Definition packet.h:433
@ PACKET_TYPE_CRYPTO_EPOCH_ACK
Definition packet.h:361
@ PACKET_TYPE_CRYPTO_NO_ENCRYPTION
Client -> Server: "I want to proceed without encryption" (UNENCRYPTED).
Definition packet.h:354
@ PACKET_TYPE_ACIP_SESSION_CREATE
Create new session (Client -> Discovery Server).
Definition packet.h:445
@ PACKET_TYPE_STATS_UPDATE
Statistics update during collection phase (Participant -> Next Participant).
Definition packet.h:534
@ PACKET_TYPE_ACIP_STRING_RESERVED
String reserved response (Discovery Server -> Client).
Definition packet.h:471
@ PACKET_TYPE_IMAGE_FRAME_H265
H.265-encoded frame from client (HEVC/H.265 codec).
Definition packet.h:401
@ PACKET_TYPE_ACIP_DISCOVERY_PING
Discovery server ping (keepalive).
Definition packet.h:545
@ PACKET_TYPE_CRYPTO_AUTH_CHALLENGE
Server -> Client: {nonce[32]} (UNENCRYPTED).
Definition packet.h:344
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
@ PACKET_TYPE_CRYPTO_PARAMETERS
Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).
Definition packet.h:338
@ PACKET_TYPE_ACIP_SESSION_LOOKUP
Lookup session by string (Client -> Discovery Server).
Definition packet.h:449
@ PACKET_TYPE_CRYPTO_CAPABILITIES
Client -> Server: Supported crypto algorithms (UNENCRYPTED).
Definition packet.h:336
@ PACKET_TYPE_RING_ELECTION_RESULT
Final election result (Quorum Leader -> All Participants).
Definition packet.h:536
@ PACKET_TYPE_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457
@ PACKET_TYPE_ACIP_PARTICIPANT_LEFT
Participant left notification (ACDS -> Remaining Participants).
Definition packet.h:509
@ PACKET_TYPE_ACIP_WEBRTC_SDP
WebRTC SDP offer/answer (bidirectional).
Definition packet.h:464
@ PACKET_TYPE_ACIP_SESSION_JOIN
Join existing session (Client -> Discovery Server).
Definition packet.h:453
@ PACKET_TYPE_ACIP_SESSION_CREATED
Session created response (Discovery Server -> Client).
Definition packet.h:447
@ PACKET_TYPE_CRYPTO_REKEY_NEEDED
Definition packet.h:360
@ PACKET_TYPE_STATS_ACK
Acknowledgment of statistics update (Participant -> Sender).
Definition packet.h:538
@ PACKET_TYPE_ACIP_STRING_RELEASE
Release string reservation (Client -> Discovery Server).
Definition packet.h:475
@ PACKET_TYPE_CLIENT_JOIN
Client announces capability to send media.
Definition packet.h:425
@ PACKET_TYPE_CLIENT_CAPABILITIES
Client reports terminal capabilities.
Definition packet.h:419
@ PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED
Future host elected announcement (Quorum Leader -> ACDS -> All Participants).
Definition packet.h:505
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
@ PACKET_TYPE_ACIP_BANDWIDTH_RESULT
Bandwidth test results (ACDS -> Client).
Definition packet.h:519
@ PACKET_TYPE_ACIP_STRING_RENEW
Renew string reservation (Client -> Discovery Server).
Definition packet.h:473
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
@ PACKET_TYPE_RING_MEMBERS
Ring member list announcement (ACDS -> All Participants).
Definition packet.h:530
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
@ PACKET_TYPE_QUIC_KEYFRAME_REQUEST
Internal authenticated request for a QUIC encoded-video keyframe.
Definition packet.h:358
@ PACKET_TYPE_AUDIO_BATCH
Batched audio packets for efficiency.
Definition packet.h:410
@ PACKET_TYPE_CRYPTO_REKEY_RESPONSE
Responder -> Initiator: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).
Definition packet.h:373
@ PACKET_TYPE_ACIP_SESSION_JOINED
Session joined response (Discovery Server -> Client).
Definition packet.h:455
@ PACKET_TYPE_STATS_COLLECTION_START
Start statistics collection phase (Coordinator -> All Participants).
Definition packet.h:532
@ PACKET_TYPE_STREAM_STOP
Client stops sending media.
Definition packet.h:431
@ PACKET_TYPE_ACIP_RING_COLLECT
Ring collect request (Participant -> Next Participant).
Definition packet.h:485
@ PACKET_TYPE_ACIP_SESSION_END
End session (Host -> Discovery Server).
Definition packet.h:459

Function Documentation

◆ accept_with_timeout()

int accept_with_timeout ( socket_t listenfd,
struct sockaddr * addr,
socklen_t * addrlen,
uint64_t timeout_ns )

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

Accept connection with timeout.

Parameters
listenfdListening socket file descriptor
addrOutput: Client address structure (can be NULL)
addrlenInput/output: Length of address structure
timeout_nsTimeout in nanoseconds
Returns
Client socket file descriptor on success, -1 on error

Accepts incoming connection with timeout support. Waits up to timeout_ns for incoming connection.

Note
If addr is NULL, client address information is not returned.
addrlen must point to initialized value containing size of addr buffer. On return, contains actual size of address.
Parameters
listenfdListening socket
addrClient address structure
addrlenLength of address structure
timeout_secondsTimeout in seconds
Returns
Client socket, or -1 on error

Definition at line 310 of file lib/network/network.c.

311 {
312 // Set up poll for accept timeout (in nanoseconds)
313 struct pollfd pfd;
314 pfd.fd = listenfd;
315 pfd.events = POLLIN;
316 pfd.revents = 0;
317
318 int result = socket_poll(&pfd, 1, (int64_t)timeout_ns);
319
320 if (result <= 0) {
321 if (result == 0) {
322 // Timeout is expected behavior for server waiting for connections
324 __func__, ETIMEDOUT);
325 return -1;
326 }
327
328 if (network_handle_select_error(result)) {
329 return -1; // Don't retry for accept
330 }
331 return -1;
332 }
333
334 // Check if socket is ready
335 if (!(pfd.revents & POLLIN)) {
337 __func__, ETIMEDOUT);
338 return -1;
339 }
340
341 // Check if socket is still valid before attempting accept
342 if (listenfd == INVALID_SOCKET_VALUE) {
343 SET_ERRNO(ERROR_NETWORK, "listening socket is closed");
344 return -1;
345 }
346
347 socket_t accept_result = socket_accept(listenfd, addr, addrlen, "connection");
348
349 if (accept_result == INVALID_SOCKET_VALUE) {
350 // Check if this is a socket closed error (common during shutdown)
351 int error_code = socket_get_last_error();
352
353 if (socket_is_invalid_socket_error(error_code)) {
354 // During shutdown, don't log this as an error since it's expected
355 // behavior
356 SET_ERRNO(ERROR_NETWORK, "Network operation failed");
357 } else {
358 SET_ERRNO_SYS(ERROR_NETWORK_BIND, "accept failed: %s",
360 }
361 return -1;
362 }
363
364 return (int)accept_result;
365}
asciichat_error_t errno_set_with_system_error(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno)
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
@ ERROR_NETWORK_BIND
Definition error_codes.h:78
@ ERROR_NETWORK
Definition error_codes.h:77
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:80
int socket_t
int socket_poll(struct pollfd *, nfds_t, int64_t)
int socket_get_last_error(void)
const char * socket_get_error_string(void)
bool socket_is_invalid_socket_error(int)

References errno_set_with_system_error(), ERROR_NETWORK, ERROR_NETWORK_BIND, ERROR_NETWORK_TIMEOUT, SET_ERRNO, SET_ERRNO_SYS, socket_get_error_string(), socket_get_last_error(), socket_is_invalid_socket_error(), and socket_poll().

◆ av_send_audio_opus_batch()

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 )

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

Send Opus-encoded audio batch packet with encryption support.

Parameters
sockfdSocket file descriptor
opus_dataOpus-encoded audio data buffer
opus_sizeSize of Opus-encoded data in bytes
frame_sizesArray of frame sizes (one per Opus frame)
sample_rateSample rate in Hz (e.g., 48000)
frame_durationFrame duration in milliseconds (e.g., 20)
frame_countNumber of Opus frames in batch
crypto_ctxCryptographic context for encryption (NULL for plaintext)
Returns
ASCIICHAT_OK on success, error code on failure

Sends PACKET_TYPE_AUDIO_OPUS_BATCH with multiple Opus-encoded frames. Opus provides better compression than raw audio (30-100 bytes per 20ms frame).

Note
Opus packets are NOT compressed again (already compressed by Opus codec).
Encryption is applied automatically when crypto_ctx is provided.

Definition at line 997 of file packet.c.

998 {
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}
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:294
#define buffer_release(data)
Definition buffer.h:108
#define HOST_TO_NET_U16(val)
Definition endian.h:100
#define HOST_TO_NET_U32(val)
Definition endian.h:70
unsigned short uint16_t
unsigned int uint32_t
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_INVALID_PARAM
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

References buffer_alloc(), buffer_release, ERROR_INVALID_PARAM, ERROR_MEMORY, HOST_TO_NET_U16, HOST_TO_NET_U32, PACKET_TYPE_AUDIO_OPUS_BATCH, send_packet_secure(), and SET_ERRNO.

◆ connect_with_timeout()

bool connect_with_timeout ( socket_t sockfd,
const struct sockaddr * addr,
socklen_t addrlen,
int timeout_seconds )

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

Connect to server with timeout.

Parameters
sockfdSocket file descriptor
addrServer address structure
addrlenAddress structure length
timeout_secondsTimeout in seconds
Returns
true on success, false on failure

Establishes connection to server with timeout support. Waits up to timeout_seconds for connection to complete.

Note
Uses platform-specific connection timeout mechanism (select/poll).
Returns false on timeout or connection failure. Use network_error_string() to get human-readable error description.

Connect to server with timeout.

Parameters
sockfdSocket file descriptor
addrAddress to connect to
addrlenAddress length
timeout_secondsTimeout in seconds
Returns
true on success, false on failure

Definition at line 510 of file lib/network/network.c.

511 {
512 if (sockfd == INVALID_SOCKET_VALUE) {
513 errno = EBADF;
514 return false;
515 }
516
517 // Set socket to non-blocking for timeout control
518 if (set_socket_nonblocking(sockfd) != ASCIICHAT_OK) {
519 return false;
520 }
521
522 // Attempt connection
523 int result = connect(sockfd, addr, addrlen);
524
525 if (result == 0) {
526 // Connected immediately
527 if (socket_set_blocking(sockfd) != 0) {
528 return false;
529 }
530 return true;
531 }
532
533 // Check if connection is in progress (expected for non-blocking sockets)
534 int error = socket_get_last_error();
535 if (!socket_is_in_progress_error(error) &&
537 log_warn("TCP connection could not start (socket error %d)", error);
538 return false;
539 }
540
541 // Use select to wait for connection with timeout
542 fd_set write_fds;
543 struct timeval timeout;
544
545 socket_fd_zero(&write_fds);
546 socket_fd_set(sockfd, &write_fds);
547
548 timeout.tv_sec = timeout_seconds;
549 timeout.tv_usec = 0;
550
551 result = socket_select(sockfd, NULL, &write_fds, NULL, &timeout);
552
553 if (result <= 0) {
554 log_warn("TCP connection wait failed (result %d, socket error %d)", result,
555 result == 0 ? 0 : socket_get_last_error());
556 return false; // Timeout or error
557 }
558
559 if (!socket_fd_isset(sockfd, &write_fds)) {
560 return false; // Socket not ready
561 }
562
563 // Check if connection was successful
564 int error_code = 0;
565 socklen_t error_len = sizeof(error_code);
566
567 if (socket_getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error_code,
568 &error_len) != 0) {
569 return false;
570 }
571
572 if (error_code != 0) {
573 log_warn("TCP connection failed (socket error %d)", error_code);
574 return false;
575 }
576
577 // Connection successful - restore blocking mode
578 if (socket_set_blocking(sockfd) != 0) {
579 log_warn("Failed to restore socket to blocking mode after connect");
580 // Continue anyway - non-blocking mode works but may cause issues with
581 // send/recv
582 }
583
584 return true;
585}
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
asciichat_error_t set_socket_nonblocking(socket_t sockfd)
Set socket non-blocking.
bool socket_is_would_block_error(int)

References ASCIICHAT_OK, log_warn, set_socket_nonblocking(), socket_get_last_error(), and socket_is_would_block_error().

◆ dns_test_connectivity()

bool dns_test_connectivity ( const char * hostname)

#include <include/ascii-chat/network/dns.h>

Test DNS connectivity by resolving a hostname.

Attempts to resolve the given hostname to verify DNS connectivity. Uses a short timeout to avoid blocking.

Parameters
hostnameHostname to resolve (e.g., "api.github.com")
Returns
true if DNS resolution succeeds, false otherwise
Note
Logs warnings on failure
IPv4 resolution only (AF_INET)

Definition at line 13 of file dns.c.

13 {
14 ASCII_OTEL_SCOPE(DNS_TEST_CONNECTIVITY);
15 if (!hostname) {
16 log_warn("NULL hostname provided to DNS connectivity test");
17 return false;
18 }
19
20 char ascii_hostname[HOSTNAME_BUFFER_SIZE];
21 asciichat_error_t normalized =
22 hostname_to_ascii(hostname, ascii_hostname, sizeof(ascii_hostname));
23 if (normalized != ASCIICHAT_OK)
24 return false;
25 hostname = ascii_hostname;
26
27 struct addrinfo hints, *result = NULL;
28 memset(&hints, 0, sizeof(hints));
29 /* Connectivity is not IPv4-specific. Restricting this probe to AF_INET
30 * reports a false DNS failure on IPv6-only or IPv6-preferred networks even
31 * though the HTTP client can connect successfully. */
32 hints.ai_family = AF_UNSPEC;
33 hints.ai_socktype = SOCK_STREAM;
34
35 log_debug("Testing DNS connectivity to %s...", hostname);
36 log_debug("β˜… ABOUT TO CALL getaddrinfo for %s", hostname);
37
38 /* Resolve the same service used by the update request. Passing a NULL
39 * service is rejected by some Windows resolver configurations even though
40 * hostname resolution itself is healthy. */
41 int ret = getaddrinfo(hostname, "443", &hints, &result);
42 log_debug("β˜… getaddrinfo returned %d", ret);
43 if (ret != 0) {
44 log_warn("DNS resolution failed for %s: %s", hostname, gai_strerror(ret));
45 return false;
46 }
47
48 if (result) {
49 freeaddrinfo(result);
50 }
51
52 log_debug("DNS connectivity test succeeded for %s", hostname);
53 return true;
54}
#define HOSTNAME_BUFFER_SIZE
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity)
Definition url.c:109
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, HOSTNAME_BUFFER_SIZE, hostname_to_ascii(), log_debug, and log_warn.

◆ frame_check_size_overflow()

asciichat_error_t frame_check_size_overflow ( size_t header_size,
size_t data_size )

#include <include/ascii-chat/network/frame_validator.h>

Check for overflow when adding header to data.

Parameters
header_sizeHeader size in bytes
data_sizeData size in bytes
Returns
ASCIICHAT_OK if safe, ERROR_BUFFER_OVERFLOW if would overflow

Definition at line 18 of file network/frame_validator.c.

19 {
20 if (data_size > SIZE_MAX - header_size) {
22 format_bytes_pretty(data_size, size_str, sizeof(size_str));
23 SET_ERRNO(ERROR_BUFFER_OVERFLOW, "Frame size overflow: %s", size_str);
25 }
26 return ASCIICHAT_OK;
27}
@ ERROR_BUFFER_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_FRAME_VALIDATOR_SIZE_BUFFER_SIZE

References ASCIICHAT_OK, ERROR_BUFFER_OVERFLOW, format_bytes_pretty(), NETWORK_FRAME_VALIDATOR_SIZE_BUFFER_SIZE, and SET_ERRNO.

Referenced by frame_validate_legacy(), frame_validate_new(), and handle_image_frame_packet().

◆ frame_extract_dimensions()

void frame_extract_dimensions ( const void * data,
uint32_t * width,
uint32_t * height )

#include <include/ascii-chat/network/frame_validator.h>

Extract width and height from frame header.

Parameters
dataPacket data (must be at least 8 bytes)
widthOutput: frame width
heightOutput: frame height

Definition at line 100 of file network/frame_validator.c.

101 {
102 uint32_t width_net, height_net;
103 memcpy(&width_net, data, FRAME_HEADER_FIELD_SIZE);
104 memcpy(&height_net, (char *)data + FRAME_HEADER_FIELD_SIZE,
106 *width = NET_TO_HOST_U32(width_net);
107 *height = NET_TO_HOST_U32(height_net);
108}
#define NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
#define FRAME_HEADER_FIELD_SIZE
Size of each header field (uint32_t = 4 bytes).

References FRAME_HEADER_FIELD_SIZE, height, NET_TO_HOST_U32, and width.

◆ frame_extract_new_header()

void frame_extract_new_header ( const void * data,
uint32_t * compressed,
uint32_t * data_size )

#include <include/ascii-chat/network/frame_validator.h>

Extract compressed flag and data size from new format header.

Parameters
dataPacket data (must be at least 16 bytes)
compressedOutput: whether data is compressed
data_sizeOutput: size of data field

Definition at line 110 of file network/frame_validator.c.

111 {
112 uint32_t compressed_net, size_net;
113 memcpy(&compressed_net, (char *)data + FRAME_HEADER_FIELD_SIZE * 2,
115 memcpy(&size_net, (char *)data + FRAME_HEADER_FIELD_SIZE * 3,
117 *compressed = NET_TO_HOST_U32(compressed_net);
118 *data_size = NET_TO_HOST_U32(size_net);
119}

References FRAME_HEADER_FIELD_SIZE, and NET_TO_HOST_U32.

Referenced by frame_validate_new().

◆ frame_validate_legacy()

asciichat_error_t frame_validate_legacy ( size_t len,
size_t expected_rgb_size )

#include <include/ascii-chat/network/frame_validator.h>

Validate legacy frame format.

Parameters
lenTotal packet length
expected_rgb_sizeExpected RGB data size (width * height * 3)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 29 of file network/frame_validator.c.

29 {
30 // Check minimum header size
31 if (len < FRAME_HEADER_SIZE_LEGACY) {
32 SET_ERRNO(ERROR_INVALID_FRAME, "Legacy frame header too small: %zu bytes",
33 len);
35 }
36
37 // Check for overflow
40 if (err != ASCIICHAT_OK) {
41 return err;
42 }
43
44 size_t expected_total = FRAME_HEADER_SIZE_LEGACY + expected_rgb_size;
45 if (len != expected_total) {
47 "Legacy frame length mismatch: expected %zu got %zu",
48 expected_total, len);
50 }
51
52 return ASCIICHAT_OK;
53}
@ ERROR_INVALID_FRAME
asciichat_error_t frame_check_size_overflow(size_t header_size, size_t data_size)
Check for overflow when adding header to data.
#define FRAME_HEADER_SIZE_LEGACY
Legacy frame header size (width:4 + height:4).

References ASCIICHAT_OK, ERROR_INVALID_FRAME, frame_check_size_overflow(), FRAME_HEADER_SIZE_LEGACY, and SET_ERRNO.

Referenced by handle_image_frame_packet().

◆ frame_validate_new()

asciichat_error_t frame_validate_new ( void * data,
size_t len,
bool * out_compressed,
uint32_t * out_data_size )

#include <include/ascii-chat/network/frame_validator.h>

Validate new frame format with optional compression.

Parameters
dataPacket data
lenTotal packet length
out_compressedOutput: whether data is compressed (optional)
out_data_sizeOutput: size of compressed/uncompressed data (optional)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 55 of file network/frame_validator.c.

57 {
58 // Check minimum new format header size
59 if (len < FRAME_HEADER_SIZE_NEW) {
60 SET_ERRNO(ERROR_INVALID_FRAME, "New frame header too small: %zu bytes",
61 len);
63 }
64
65 uint32_t compressed_flag, data_size;
66 frame_extract_new_header(data, &compressed_flag, &data_size);
67
68 size_t data_size_sz = (size_t)data_size;
69
70 // Check data size against maximum
71 if (data_size_sz > IMAGE_MAX_PIXELS_SIZE) {
73 format_bytes_pretty(data_size_sz, size_str, sizeof(size_str));
74 SET_ERRNO(ERROR_INVALID_FRAME, "Frame data too large: %s", size_str);
76 }
77
78 // Check for overflow
81 if (err != ASCIICHAT_OK) {
82 return err;
83 }
84
85 size_t expected_total = FRAME_HEADER_SIZE_NEW + data_size_sz;
86 if (len != expected_total) {
88 "New frame length mismatch: expected %zu got %zu", expected_total,
89 len);
91 }
92
93 if (out_compressed)
94 *out_compressed = (compressed_flag != 0);
95 if (out_data_size)
96 *out_data_size = data_size;
97 return ASCIICHAT_OK;
98}
void frame_extract_new_header(const void *data, uint32_t *compressed, uint32_t *data_size)
Extract compressed flag and data size from new format header.
#define IMAGE_MAX_PIXELS_SIZE
Maximum pixel data size in bytes.
#define FRAME_HEADER_SIZE_NEW
New frame header size (width:4 + height:4 + compressed:4 + size:4).

References ASCIICHAT_OK, ERROR_INVALID_FRAME, format_bytes_pretty(), frame_check_size_overflow(), frame_extract_new_header(), FRAME_HEADER_SIZE_NEW, IMAGE_MAX_PIXELS_SIZE, NETWORK_FRAME_VALIDATOR_SIZE_BUFFER_SIZE, and SET_ERRNO.

◆ https_get()

char * https_get ( const char * hostname,
const char * path )

#include <include/ascii-chat/network/http/client/client.h>

Perform HTTPS GET request.

Parameters
hostnameServer hostname (e.g., "github.com", must not be NULL)
pathResource path (e.g., "/username.keys", must not be NULL)
Returns
Allocated string containing response body (caller must free), or NULL on error

Makes a secure HTTPS connection to the specified hostname and fetches the resource at the given path. Uses system CA certificates for validation.

Note
TLS connection: Uses BearSSL for TLS connections. Validates server certificate against system CA certificates.
Memory management: Returns allocated string that caller must free. Use SAFE_FREE() to free the returned string.
Error handling: Returns NULL on error (network error, TLS error, etc.). Error messages are logged via logging system.
Hostname format: Hostname should be domain name only (no "https://" prefix). Example: "github.com", not "https://github.com".
Path format: Path should start with "/" for absolute paths. Example: "/username.keys", not "username.keys".
Response body: Returns complete response body as null-terminated string. Response may contain multiple keys (one per line for SSH keys).
Warning
Network dependency: Requires network connectivity and valid hostname. May fail if network is unavailable or hostname is unreachable.
Memory leak: Caller must free returned string using SAFE_FREE(). Function allocates memory that must be freed.
Certificate validation: Uses system CA certificates for validation. May fail if system CA certificates are missing or outdated.

Definition at line 179 of file lib/network/http/client/client.c.

179 {
180 ASCII_OTEL_SCOPE(HTTP);
181 ascii_otel_http(&otel_scope, hostname, path);
182 char *body = NULL;
183 if (!hostname || !path) {
184 log_error("Invalid arguments");
185 return NULL;
186 }
187
188 char ascii_hostname[HOSTNAME_BUFFER_SIZE];
189 asciichat_error_t normalized = hostname_to_ascii(hostname, ascii_hostname, sizeof(ascii_hostname));
190 if (normalized != ASCIICHAT_OK)
191 return NULL;
192 hostname = ascii_hostname;
193
194 log_info("HTTPS GET https://%s%s", hostname, path);
195
196 // Load system CA certificates
197 char *pem_data = NULL;
198 size_t pem_size = 0;
199 if (platform_load_system_ca_certs(&pem_data, &pem_size) != 0) {
200 log_error("Failed to load system CA certificates");
201 return NULL;
202 }
203
204 // Parse PEM certificates into BearSSL trust anchors
206 defer(free_http_anchors(&anchors));
207 size_t num_anchors = read_trust_anchors_from_memory(&anchors, (unsigned char *)pem_data, pem_size);
208 /* libplatform allocates the certificate bundle with the regular C
209 * allocator; it must not cross into ascii-chat's optional mimalloc path. */
210 free(pem_data);
211 pem_data = NULL;
212
213 if (num_anchors == 0) {
214 log_error("No trust anchors loaded");
215 return NULL;
216 }
217 log_info("Loaded %zu trust anchors", num_anchors);
218
219 // Resolve hostname using getaddrinfo (modern, non-deprecated API)
220 struct addrinfo hints, *result;
221 memset(&hints, 0, sizeof(hints));
222 hints.ai_family = AF_INET; // IPv4
223 hints.ai_socktype = SOCK_STREAM;
224 hints.ai_protocol = IPPROTO_TCP;
225
226 int dns_result;
227 {
228 ASCII_OTEL_SCOPE_AS(dns_scope, DNS_RESOLVE);
229 if (dns_scope.retained)
230 gotel_attr_string(&dns_scope.scope, "dns.question.name", hostname);
231 dns_result = getaddrinfo(hostname, "443", &hints, &result);
232 if (dns_result && dns_scope.retained)
233 gotel_error(&dns_scope.scope, "dns.error", "DNS lookup failed");
234 }
235 if (dns_result != 0) {
236 log_error("Failed to resolve hostname: %s", hostname);
237 return NULL;
238 }
239
240 defer(if (result) freeaddrinfo(result));
241
242 // Create TCP socket
243 socket_t sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
244 if (sock == INVALID_SOCKET_VALUE) {
245 log_error("Failed to create socket");
246 return NULL;
247 }
248
249 defer(if (sock != INVALID_SOCKET_VALUE) socket_close(sock));
250
251 // Set socket timeouts to avoid blocking indefinitely on stalled connections.
252 // Windows expects a DWORD timeout in milliseconds, while POSIX expects a
253 // struct timeval. Passing timeval to Winsock makes the timeout effectively
254 // a few milliseconds and commonly aborts the TLS handshake.
255#ifdef _WIN32
256 DWORD timeout_ms = 5000;
257 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout_ms, sizeof(timeout_ms));
258 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout_ms, sizeof(timeout_ms));
259#else
260 struct timeval timeout = {.tv_sec = 5, .tv_usec = 0};
261 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));
262 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout, sizeof(timeout));
263#endif
264
265 // Connect to server
266 if (connect(sock, result->ai_addr, (int)result->ai_addrlen) != 0) {
267 log_error("Failed to connect to %s:443", hostname);
268 return NULL;
269 }
270
271 freeaddrinfo(result);
272 result = NULL;
273
274 log_info("Connected to %s:443", hostname);
275
276 // Initialize BearSSL X.509 minimal validator
277 br_x509_minimal_context xc;
278 br_x509_minimal_init(&xc, &br_sha256_vtable, anchors.buf, anchors.ptr);
279
280 // Initialize BearSSL client context
281 br_ssl_client_context sc;
282 br_ssl_client_init_full(&sc, &xc, anchors.buf, anchors.ptr);
283
284 // Set I/O buffer
285 const size_t iobuf_size = BR_SSL_BUFSIZE_BIDI;
286 SAFE_MALLOC_DEFER_FREE(iobuf, iobuf_size, unsigned char *);
287 br_ssl_engine_set_buffer(&sc.eng, iobuf, BR_SSL_BUFSIZE_BIDI, 1);
288
289 // Initialize I/O context
290 br_sslio_context ioc;
291 br_sslio_init(&ioc, &sc.eng, sock_read, &sock, sock_write, &sock);
292
293 // Start TLS handshake
294 br_ssl_client_reset(&sc, hostname, 0);
295
296 log_info("Starting TLS handshake with %s", hostname);
297
298 // Build HTTP request
299 char request[BUFFER_SIZE_LARGE];
300 int request_len = safe_snprintf(request, sizeof(request),
301 "GET %s HTTP/1.1\r\n"
302 "Host: %s\r\n"
303 "Connection: close\r\n"
304 "User-Agent: ascii-chat/" ASCII_CHAT_VERSION_STRING "\r\n"
305 "\r\n",
306 path, hostname);
307
308 // Send HTTP request over TLS
309 if (br_sslio_write_all(&ioc, request, (size_t)request_len) != 0) {
310 log_error("Failed to send HTTP request");
311 return NULL;
312 }
313
314 br_sslio_flush(&ioc);
315 log_info("Sent HTTP request");
316
317 // Read HTTP response
318 size_t response_capacity = 8192;
319 size_t response_len = 0;
320 SAFE_MALLOC_DEFER_FREE(response_buf, response_capacity, char *);
321
322 while (1) {
323 // Ensure we have space to read
324 if (response_len + 1024 > response_capacity) {
325 response_capacity *= 2;
326 if (response_capacity > HTTPS_MAX_RESPONSE_SIZE) {
327 log_error("Response exceeds maximum size (%d bytes)", HTTPS_MAX_RESPONSE_SIZE);
328 return NULL;
329 }
330 response_buf = SAFE_REALLOC(response_buf, response_capacity, char *);
331 }
332
333 // Read data (reserve 1 byte for null terminator)
334 int n = br_sslio_read(&ioc, response_buf + response_len, response_capacity - response_len - 1);
335 if (n < 0) {
336 // Check for TLS errors
337 int err = br_ssl_engine_last_error(&sc.eng);
338 if (err != BR_ERR_OK) {
339 log_error("TLS error: %d", err);
340 return NULL;
341 }
342 // EOF or connection closed
343 break;
344 }
345 if (n == 0) {
346 break; // EOF
347 }
348
349 response_len += (size_t)n;
350 }
351
352 response_buf[response_len] = '\0';
353 log_info("Received %zu bytes", response_len);
354
355 // Close connection
356 br_sslio_close(&ioc);
357 socket_close(sock);
358 sock = INVALID_SOCKET_VALUE;
359
360 // Parse HTTP response
361 int code = parse_http_status(response_buf, response_len);
362 if (code >= 0 && otel_scope.retained)
363 gotel_http_attributes(&otel_scope.scope, "GET", code);
364 if (code != 200) {
365 if (code < 0)
366 SET_ERRNO(ERROR_NETWORK, "Invalid HTTP response: %s", response_buf);
367 else
368 SET_ERRNO(ERROR_NETWORK, "HTTP request failed: %.50s", response_buf);
369 return NULL;
370 }
371
372 body = extract_http_body(response_buf, response_len);
373 if (body)
374 ascii_otel_http_status(&otel_scope, 200);
375
376 return body;
377}
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define SAFE_REALLOC(ptr, size, cast)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
br_x509_trust_anchor * buf
Definition pem.h:89
#define ANCHOR_LIST_INIT
Initializer for anchor_list.
Definition pem.h:103
size_t read_trust_anchors_from_memory(anchor_list *dst, const unsigned char *pem_data, size_t pem_len)
Read trust anchors from PEM-encoded data in memory.
Definition pem.c:469
size_t ptr
Definition pem.h:90
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define HTTPS_MAX_RESPONSE_SIZE
int socket_close(socket_t)
void ascii_otel_http(ascii_otel_scope_t *s, const char *hostname, const char *path)
Definition otel.c:974
void ascii_otel_http_status(ascii_otel_scope_t *s, int status)
Definition otel.c:993
#define ASCII_OTEL_SCOPE_AS(variable, id)
Definition otel.h:106
Vector type for trust anchors.
Definition pem.h:87

References ANCHOR_LIST_INIT, ascii_otel_http(), ascii_otel_http_status(), ASCII_OTEL_SCOPE, ASCII_OTEL_SCOPE_AS, ASCIICHAT_OK, anchor_list::buf, BUFFER_SIZE_LARGE, ERROR_NETWORK, HOSTNAME_BUFFER_SIZE, hostname_to_ascii(), HTTPS_MAX_RESPONSE_SIZE, log_error, log_info, anchor_list::ptr, read_trust_anchors_from_memory(), SAFE_MALLOC_DEFER_FREE, SAFE_REALLOC, SET_ERRNO, and socket_close().

Referenced by parse_public_key(), and update_check_perform().

◆ network_error_string()

const char * network_error_string ( )

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

Get human-readable error string for network errors.

Returns
Error string describing last network error

Returns a human-readable description of the last network error. Useful for error logging and user-facing error messages.

Note
Error string is thread-local - each thread has its own error state.
Parameters
error_codeError code
Returns
Error string

Definition at line 500 of file lib/network/network.c.

500{ return socket_get_error_string(); }

References socket_get_error_string().

Referenced by socket_configure_buffers().

◆ packet_decrypt_envelope()

asciichat_error_t packet_decrypt_envelope ( packet_envelope_t * envelope,
void * crypto_ctx )

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

Decrypt a PACKET_TYPE_ENCRYPTED envelope and extract inner packet.

If the envelope contains PACKET_TYPE_ENCRYPTED, decrypts the payload and updates the envelope with the inner packet (type, data, length). Used by both TCP and non-socket (WebRTC) transports to handle encryption uniformly.

Parameters
envelopePacket envelope to decrypt (will be modified if encrypted)
crypto_ctxCrypto context for decryption (required if envelope is encrypted)
Returns
ASCIICHAT_OK on success, error code otherwise
Note
Updates envelope->type, envelope->data, envelope->len, and envelope->allocated_buffer to point to decrypted plaintext
Caller must free the updated envelope->allocated_buffer

Decrypt a PACKET_TYPE_ENCRYPTED envelope and extract inner packet.

Parameters
sockfdSocket file descriptor
Returns
0 on success, -1 on error

Decrypt a PACKET_TYPE_ENCRYPTED envelope and extract inner packet

Shared decryption logic for both TCP (receive_packet_secure) and non-socket (WebRTC) transports. Decrypts PACKET_TYPE_ENCRYPTED envelopes and updates the envelope with the inner packet type and data.

Parameters
envelopePacket envelope to decrypt (will be modified if encrypted)
crypto_ctxCrypto context for decryption (required if envelope is encrypted)
Returns
ASCIICHAT_OK on success, error code otherwise

Definition at line 639 of file packet.c.

639 {
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}
size_t buffer_capacity(const void *data)
Definition buffer.c:300
bool buffer_is_unique(const void *data)
Definition buffer.c:335
#define NET_TO_HOST_U16(val)
Definition endian.h:115
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:81
@ ERROR_CRYPTO
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)
#define CRYPTO_RECORD_RELIABLE
Definition record.h:13
#define CRYPTO_RECORD_ANY_CHANNEL
Definition record.h:15
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641

References acip_security_decrypt(), ASCIICHAT_OK, buffer_capacity(), buffer_is_unique(), buffer_release, CRYPTO_RECORD_ANY_CHANNEL, CRYPTO_RECORD_RELIABLE, ERROR_CRYPTO, ERROR_INVALID_PARAM, ERROR_NETWORK_PROTOCOL, NET_TO_HOST_U16, PACKET_TYPE_ENCRYPTED, and SET_ERRNO.

Referenced by acds_receive_packet(), packet_parse_envelope(), packet_receive_via_transport(), and receive_packet_secure_with_timeout().

◆ packet_encode()

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 )

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

Definition at line 63 of file packet.c.

63 {
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}
@ ERROR_NETWORK_SIZE
Definition error_codes.h:83
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

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK_SIZE, packet_header_build(), and SET_ERRNO.

Referenced by acip_security_rekey_encode(), and browser_client_send_packet().

◆ packet_envelope_release()

void packet_envelope_release ( packet_envelope_t * envelope)

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

Wipe and release an envelope allocation, then clear the envelope.

Definition at line 711 of file packet.c.

711 {
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}
Packet envelope containing received packet data.
Definition packet.h:1208

References buffer_capacity(), buffer_is_unique(), and buffer_release.

Referenced by acip_client_receive_and_dispatch(), acip_client_session_process_wire(), browser_client_receive_packet(), and packet_parse_envelope().

◆ packet_format_error_stack()

size_t packet_format_error_stack ( char * buffer,
size_t size )

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

Format the current thread's error stack for transport to a peer.

Parameters
bufferDestination buffer
sizeDestination buffer size
Returns
Number of bytes written, excluding the null terminator

Definition at line 722 of file packet.c.

722 {
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}
asciichat_errno_snapshot_t errno_snapshot(uint64_t id, asciichat_error_context_t *out, size_t capacity)
#define ASCIICHAT_ERRNO_MAX_DEPTH
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:137

References ASCIICHAT_ERRNO_MAX_DEPTH, asciichat_error_context_t::context_message, asciichat_errno_snapshot_t::copied, errno_snapshot(), extract_project_relative_path(), asciichat_error_context_t::file, asciichat_error_context_t::function, and asciichat_error_context_t::line.

◆ packet_header_build()

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 )

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

Shared ACIP wire codec. Headers are returned in network byte order.

Definition at line 47 of file packet.c.

47 {
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}
#define HOST_TO_NET_U64(val)
Definition endian.h:209
#define MAX_PACKET_SIZE
Maximum packet size (5MB).
Definition packet.h:144
#define PACKET_MAGIC
Packet magic number (alias for MAGIC_PACKET_VALID).
Definition packet.h:284
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:84

References asciichat_crc32_update(), ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK_SIZE, HOST_TO_NET_U16, HOST_TO_NET_U32, HOST_TO_NET_U64, MAX_PACKET_SIZE, PACKET_MAGIC, and SET_ERRNO.

Referenced by acip_packet_encrypt(), packet_encode(), packet_send_via_transportv(), and send_packet_secure().

◆ packet_parse_envelope()

asciichat_error_t packet_parse_envelope ( const void * wire,
size_t length,
void * crypto_ctx,
packet_envelope_t * out )

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

Parse one complete wire packet using the shared client receive path.

Copies the wire packet into an owned buffer, validates it, and decrypts an encrypted envelope through the shared ACIP security implementation. The caller owns out->allocated_buffer and must release it with buffer_release.

Definition at line 686 of file packet.c.

686 {
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}
asciichat_error_t packet_validate(const void *packet, size_t length, size_t limit, packet_header_t *output)
Definition packet.c:81
asciichat_error_t packet_decrypt_envelope(packet_envelope_t *envelope, void *crypto_ctx)
Send a clear console packet.
Definition packet.c:639
void packet_envelope_release(packet_envelope_t *envelope)
Definition packet.c:711
static bool size_t gotel_query_t * out
Definition queries.h:10

References ASCIICHAT_OK, buffer_alloc(), ERROR_INVALID_PARAM, ERROR_MEMORY, MAX_PACKET_SIZE, NET_TO_HOST_U16, out, packet_decrypt_envelope(), packet_envelope_release(), packet_validate(), and SET_ERRNO.

Referenced by acip_client_session_process_wire(), and browser_client_receive_packet().

◆ packet_parse_error_message()

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 )

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

Parse an error packet payload into components.

Parameters
dataPacket payload buffer
lenPayload length in bytes
out_error_codeOutput pointer for asciichat_error_t value (must not be NULL)
message_bufferDestination buffer for message string (must not be NULL)
message_buffer_sizeSize of destination buffer in bytes (must be > 0)
out_message_lengthOptional output for message length reported by sender
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 793 of file packet.c.

793 {
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}
#define MAX_ERROR_MESSAGE_LENGTH
Maximum error message length (512 bytes).
Definition packet.h:153
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

References ASCIICHAT_OK, error_packet_t::error_code, ERROR_INVALID_PARAM, ERROR_NETWORK_PROTOCOL, MAX_ERROR_MESSAGE_LENGTH, error_packet_t::message_length, NET_TO_HOST_U32, and SET_ERRNO.

Referenced by network_error_decode().

◆ packet_parse_remote_log()

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 )

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

Parse a remote log packet payload into components.

Parameters
dataPacket payload buffer
lenPayload length in bytes
out_levelOutput pointer for log level (must not be NULL)
out_directionOutput pointer for direction (must not be NULL)
out_flagsOutput pointer for flags (must not be NULL)
message_bufferDestination buffer for message string (must not be NULL)
message_buffer_sizeSize of destination buffer in bytes (must be > 0)
out_message_lengthOptional output for message length reported by sender
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 885 of file packet.c.

886 {
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}
enum remote_log_direction remote_log_direction_t
Remote log packet direction enumeration.
log_level_t
Logging levels enumeration.
Definition log/types.h:33
@ REMOTE_LOG_DIRECTION_UNKNOWN
Definition network/log.h:21
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:23
#define MAX_REMOTE_LOG_MESSAGE_LENGTH
Maximum remote log message length (512 bytes).
Definition packet.h:163
#define LOG_FATAL
Definition log/types.h:47
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

References ASCIICHAT_OK, remote_log_packet_t::direction, ERROR_INVALID_PARAM, ERROR_NETWORK_PROTOCOL, remote_log_packet_t::flags, LOG_FATAL, remote_log_packet_t::log_level, MAX_REMOTE_LOG_MESSAGE_LENGTH, remote_log_packet_t::message_length, NET_TO_HOST_U16, NET_TO_HOST_U32, REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER, REMOTE_LOG_DIRECTION_UNKNOWN, and SET_ERRNO.

Referenced by handle_remote_log_packet_from_client().

◆ packet_receive()

asciichat_error_t packet_receive ( socket_t sockfd,
packet_type_t * type,
void ** data,
size_t * len )

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

Receive a packet with header validation and CRC32 checking.

Parameters
sockfdSocket file descriptor
typeOutput: Packet type
dataOutput: Packet payload data (allocated by function, freed by caller)
lenOutput: Payload data length in bytes
Returns
ASCIICHAT_OK on success, error code on failure

Receives a complete packet, validates header, and verifies CRC32 checksum. Allocates buffer for payload data which must be freed by caller.

Note
Allocates buffer for payload data - caller must free when done.
Validates magic number and CRC32 checksum before returning data.
Warning
Allocated data buffer must be freed by caller to prevent memory leaks.

Receive a packet with header validation and CRC32 checking.

Parameters
sockfdSocket file descriptor
typeOutput: packet type
dataOutput: packet data (allocated by caller, freed by caller)
lenOutput: data length
Returns
0 on success, -1 on error

Definition at line 388 of file packet.c.

388 {
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 = 0;
415 uint32_t pkt_len = 0;
416 uint32_t expected_crc = 0;
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}
buffer_domain_t * buffer_control_domain(void)
Definition buffer.c:465
unsigned long long uint64_t
#define NS_PER_SEC_INT
Definition time.h:173
ssize_t recv_with_timeout(socket_t sockfd, void *buf, size_t len, uint64_t timeout_ns)
Receive data with timeout.
#define RECV_TIMEOUT
Receive timeout in seconds (1 second).
Definition network.h:133
uint64_t packet_send_timeout_ns(size_t packet_size)
Definition packet.c:111

References ASCIICHAT_OK, buffer_alloc(), buffer_control_domain(), buffer_release, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, ERROR_NETWORK_PROTOCOL, log_warn, NS_PER_SEC_INT, packet_send_timeout_ns(), PACKET_TYPE_ERROR_MESSAGE, RECV_TIMEOUT, recv_with_timeout(), SET_ERRNO, and SET_ERRNO_SYS.

Referenced by receive_packet().

◆ packet_send()

asciichat_error_t packet_send ( socket_t sockfd,
packet_type_t type,
const void * data,
size_t len )

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

Send a packet with header and CRC32 checksum.

Parameters
sockfdSocket file descriptor
typePacket type (from packet_types.h)
dataPacket payload data (can be NULL for header-only packets)
lenPayload data length in bytes
Returns
ASCIICHAT_OK on success, error code on failure

Sends a complete packet with header (magic, type, length, CRC32) and optional payload. CRC32 is computed automatically and included in header.

Note
Packet header is constructed with all required fields including magic number, type, length, CRC32, and client ID.
CRC32 is computed over payload data (or zero if data is NULL).

Send a packet with header and CRC32 checksum.

Parameters
sockfdSocket file descriptor
typePacket type
dataPacket data
lenData length
Returns
0 on success, -1 on error

Definition at line 348 of file packet.c.

348 {
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}
#define SAFE_STRERROR(errnum)
#define US_PER_SEC_INT
Definition time.h:177
#define asciichat_crc32(data, len)
Main CRC32 dispatcher macro - use this in application code.
Definition crc32.h:153
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719

References asciichat_crc32, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK_SIZE, HOST_TO_NET_U16, HOST_TO_NET_U32, HOST_TO_NET_U64, log_debug_every, MAX_PACKET_SIZE, PACKET_MAGIC, packet_send_timeout_ns(), SAFE_STRERROR, SET_ERRNO, and US_PER_SEC_INT.

Referenced by packet_send_error(), packet_send_remote_log(), send_image_frame_packet(), send_packet(), and send_packet_secure().

◆ packet_send_error()

asciichat_error_t packet_send_error ( socket_t sockfd,
const crypto_context_t * crypto_ctx,
asciichat_error_t error_code,
const char * message )

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

Send an error packet with optional encryption context.

Parameters
sockfdSocket file descriptor
crypto_ctxCrypto context for encryption (NULL or not ready sends plaintext)
error_codeError code from asciichat_error_t enumeration
messageLegacy argument; fixed public text is sent for the allowlisted error code
Returns
ASCIICHAT_OK on success, error code otherwise

When the crypto context is ready, the packet is encrypted automatically. During the handshake (or when encryption is disabled), the packet is sent in plaintext so protocol errors can be delivered before encryption is active.

Definition at line 746 of file packet.c.

746 {
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}
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
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
asciichat_error_t network_error_public_code(asciichat_error_t code)
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.

References ASCIICHAT_OK, crypto_is_ready(), crypto_context_t::encrypt_data, error_packet_t::error_code, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, HOST_TO_NET_U32, log_warn, MAX_ERROR_MESSAGE_LENGTH, error_packet_t::message_length, network_error_public_code(), packet_send(), PACKET_TYPE_ERROR_MESSAGE, SAFE_FREE, SAFE_MALLOC, send_packet_secure(), and SET_ERRNO.

◆ packet_send_remote_log()

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 )

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

Send a remote log packet with optional encryption context.

Parameters
sockfdSocket file descriptor
crypto_ctxCrypto context for encryption (NULL or not ready sends plaintext)
levelLog level to transmit
directionDirection flag (REMOTE_LOG_DIRECTION_*)
flagsAdditional flags (REMOTE_LOG_FLAG_*)
messageLog message text
Returns
ASCIICHAT_OK on success, error code otherwise

Definition at line 830 of file packet.c.

830 {
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}
#define REMOTE_LOG_FLAG_TRUNCATED
Remote log packet flag definitions.
Definition packet.h:787

References ASCIICHAT_OK, crypto_is_ready(), remote_log_packet_t::direction, crypto_context_t::encrypt_data, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, remote_log_packet_t::flags, HOST_TO_NET_U16, HOST_TO_NET_U32, LOG_FATAL, remote_log_packet_t::log_level, MAX_REMOTE_LOG_MESSAGE_LENGTH, remote_log_packet_t::message_length, packet_send(), PACKET_TYPE_REMOTE_LOG, REMOTE_LOG_FLAG_TRUNCATED, SAFE_FREE, SAFE_MALLOC, send_packet_secure(), and SET_ERRNO.

◆ packet_validate()

asciichat_error_t packet_validate ( const void * packet,
size_t length,
size_t limit,
packet_header_t * header )

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

Validate exactly one complete packet, including the empty-payload checksum. A zero limit uses MAX_PACKET_SIZE. The optional header output is a copy.

Definition at line 81 of file packet.c.

81 {
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}
#define NET_TO_HOST_U64(val)
Definition endian.h:224

References asciichat_crc32, ASCIICHAT_OK, ERROR_NETWORK_PROTOCOL, MAX_PACKET_SIZE, NET_TO_HOST_U32, NET_TO_HOST_U64, PACKET_MAGIC, and SET_ERRNO.

Referenced by acip_packet_open_sequence(), acip_security_open(), acip_security_rekey_receive(), browser_client_receive_packet(), browser_session_receive(), packet_decoder_feed(), packet_parse_envelope(), packet_receive_via_transport(), and receive_packet_secure_with_timeout().

◆ protocol_version_packet_init()

void protocol_version_packet_init ( protocol_version_packet_t * version,
uint8_t supports_encryption )

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

Initialize a protocol version packet with the current wire version.

Parameters
versionPacket to initialize.
supports_encryptionACIP encryption/authentication capability mask.

Definition at line 37 of file packet.c.

37 {
38 if (!version)
39 return;
40 memset(version, 0, sizeof(*version));
44 version->supports_encryption = supports_encryption;
45}
#define PROTOCOL_VERSION_MAJOR
Major protocol version number.
#define PROTOCOL_VERSION_MINOR
Minor protocol version number.
#define PROTOCOL_VERSION_PATCH
Patch protocol version number.
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

References HOST_TO_NET_U16, protocol_version_packet_t::protocol_patch, protocol_version_packet_t::protocol_revision, protocol_version_packet_t::protocol_version, PROTOCOL_VERSION_MAJOR, PROTOCOL_VERSION_MINOR, PROTOCOL_VERSION_PATCH, and protocol_version_packet_t::supports_encryption.

Referenced by acds_handshake_begin(), and acip_security_start().

◆ receive_packet()

int receive_packet ( socket_t sockfd,
packet_type_t * type,
void ** data,
size_t * len )

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

Receive a basic packet without encryption.

Parameters
sockfdSocket file descriptor
typeOutput: Packet type
dataOutput: Packet payload data (allocated by function)
lenOutput: Payload data length in bytes
Returns
0 on success, -1 on error

Receives a plaintext packet without decryption. Allocates buffer for payload data which must be freed by caller.

Note
Use receive_packet_secure() if decryption support is needed.
Warning
Allocated data buffer must be freed by caller.
Parameters
sockfdSocket file descriptor
typeOutput: packet type
dataOutput: packet data
lenOutput: data length
Returns
0 on success, -1 on error

Definition at line 594 of file packet.c.

594 {
595 asciichat_error_t result = packet_receive(sockfd, type, data, len);
596 return result == ASCIICHAT_OK ? 0 : -1;
597}
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

References ASCIICHAT_OK, and packet_receive().

◆ receive_packet_secure()

packet_recv_result_t receive_packet_secure ( socket_t sockfd,
void * crypto_ctx,
bool enforce_encryption,
packet_envelope_t * envelope )

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

Receive a packet with decryption and decompression support.

Parameters
sockfdSocket file descriptor
crypto_ctxCryptographic context for decryption (NULL for plaintext)
enforce_encryptionIf true, reject unencrypted packets (except handshake)
envelopeOutput: Received packet envelope with all metadata
Returns
PACKET_RECV_SUCCESS on success, error code on failure

Receives a packet with automatic decryption (if encrypted) and decompression (if compressed). Validates encryption policy and packet integrity.

Note
Decryption is applied automatically when packet is encrypted and crypto_ctx is provided.
Decompression is applied automatically when packet is compressed.
If enforce_encryption is true, unencrypted packets (except handshake packets) cause PACKET_RECV_SECURITY_VIOLATION.
Warning
Envelope's allocated_buffer must be freed by caller to prevent memory leaks.
Parameters
sockfdSocket file descriptor
crypto_ctxCrypto context for decryption
enforce_encryptionWhether to require encryption
envelopeOutput: received packet envelope
Returns
Packet receive result

Definition at line 563 of file packet.c.

563 {
564 return receive_packet_secure_with_timeout(sockfd, crypto_ctx, enforce_encryption, envelope, RECV_TIMEOUT * NS_PER_SEC_INT);
565}
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

References NS_PER_SEC_INT, receive_packet_secure_with_timeout(), and RECV_TIMEOUT.

◆ receive_packet_secure_with_timeout()

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 )

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

Definition at line 1106 of file packet.c.

1106 {
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}
#define MAX(a, b)
Definition param.h:10

References ASCIICHAT_OK, buffer_alloc(), buffer_release, ERROR_CRYPTO, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, ERROR_NETWORK_PROTOCOL, MAX, MAX_PACKET_SIZE, NET_TO_HOST_U16, NET_TO_HOST_U32, NET_TO_HOST_U64, packet_decrypt_envelope(), PACKET_MAGIC, PACKET_RECV_EOF, PACKET_RECV_ERROR, PACKET_RECV_SUCCESS, packet_send_timeout_ns(), PACKET_TYPE_ENCRYPTED, packet_validate(), recv_with_timeout(), and SET_ERRNO.

Referenced by receive_packet_secure().

◆ recv_with_timeout()

ssize_t recv_with_timeout ( socket_t sockfd,
void * buf,
size_t len,
uint64_t timeout_ns )

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

Receive data with timeout.

Parameters
sockfdSocket file descriptor
bufBuffer to receive data
lenLength of buffer in bytes
timeout_nsTimeout in nanoseconds
Returns
Number of bytes received on success, -1 on error

Receives data from socket with timeout support. Waits up to timeout_ns for data to arrive.

Note
Partial receives are possible - function returns number of bytes actually received.
Returns -1 on timeout or error. Use network_error_string() to get human-readable error description.
Parameters
sockfdSocket file descriptor
bufBuffer to receive data
lenLength of buffer
timeout_secondsTimeout in seconds
Returns
Number of bytes received, or -1 on error

Definition at line 193 of file lib/network/network.c.

194 {
195 if (sockfd == INVALID_SOCKET_VALUE) {
196 errno = EBADF;
197 return -1;
198 }
199
200 ssize_t total_received = 0;
201 char *data = (char *)buf;
202 uint64_t receive_start = time_get_ns();
203
204 while (total_received < (ssize_t)len) {
205 // Set up poll for read timeout (in nanoseconds)
206 struct pollfd pfd;
207 pfd.fd = sockfd;
208 pfd.events = POLLIN;
209 pfd.revents = 0;
210
211 // Use provided timeout for recv() calls - don't artificially limit data
212 // packets in test mode Timeouts should only apply to initial handshake, not
213 // to receiving data on active connections
214 uint64_t elapsed = time_get_ns() - receive_start;
215 if (elapsed >= timeout_ns) {
217 "Receive deadline expired");
218 return -1;
219 }
220 int result = socket_poll(&pfd, 1, (int64_t)(timeout_ns - elapsed));
221 if (result <= 0) {
222 if (result == 0) {
223 /* A read timeout is the ordinary idle state for signaling sockets.
224 * Do not emit an error on every polling interval. */
226 __func__, ETIMEDOUT);
227 if (total_received > 0)
229 "Receive timed out after consuming %zd/%zu bytes",
230 total_received, len);
231 return -1;
232 }
233 if (network_handle_select_error(result)) {
234 continue; // Retry
235 }
236 return -1; // Fatal error
237 }
238
239 // Poll can return readiness for a hangup or socket error without POLLIN.
240 // Treat those as terminal network errors so callers tear down the dead
241 // connection instead of retrying it as an idle timeout in a tight loop.
242 // Linux zerocopy completions also raise POLLERR with SO_ERROR == 0.
243 // The serialized sender owns the error queue and will consume those events.
244 if ((pfd.revents & POLLERR) && !(pfd.revents & (POLLHUP | POLLNVAL))) {
245 int socket_error = 0;
246 socklen_t error_len = sizeof(socket_error);
247 if (socket_getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &socket_error,
248 &error_len) == 0 &&
249 !socket_error) {
250 pfd.revents &= (short)~POLLERR;
251 if (!(pfd.revents & POLLIN)) {
252 platform_sleep_ns(NS_PER_MS_INT);
253 continue;
254 }
255 }
256 }
257 if (pfd.revents & (POLLERR | POLLNVAL)) {
258 SET_ERRNO(ERROR_NETWORK, "poll reported socket flags 0x%x", pfd.revents);
259 return -1;
260 }
261 // A drained asynchronous writer may close while readable bytes remain.
262 // Consume POLLIN before treating POLLHUP as EOF (notably WSAPoll).
263 if ((pfd.revents & POLLHUP) && !(pfd.revents & POLLIN))
264 return total_received;
265
266 // Other readiness flags without POLLIN are an ordinary no-data result.
267 if (!(pfd.revents & POLLIN)) {
269 __func__, ETIMEDOUT);
270 if (total_received > 0)
272 "Receive stalled after consuming %zd/%zu bytes",
273 total_received, len);
274 return -1;
275 }
276
277 // Calculate how much we still need to receive
278 size_t bytes_to_recv = len - (size_t)total_received;
279 ssize_t received =
280 socket_recv(sockfd, data + total_received, bytes_to_recv, 0);
281
282 if (received < 0) {
283 int error = errno;
284 if (network_handle_recv_error(error)) {
285 continue; // Retry
286 }
287 return -1; // Fatal error
288 }
289
290 if (received == 0) {
291 // Connection closed by peer
292 log_debug("Connection closed by peer during recv");
293 return total_received; // Return what we got so far
294 }
295
296 total_received += received;
297 }
298
299 return total_received;
300}
#define NS_PER_MS_INT
Definition time.h:172
ssize_t socket_recv(socket_t, void *, size_t, int)

References errno_set_with_system_error(), ERROR_NETWORK, ERROR_NETWORK_TIMEOUT, log_debug, NS_PER_MS_INT, SET_ERRNO, socket_poll(), and socket_recv().

Referenced by packet_receive(), and receive_packet_secure_with_timeout().

◆ send_crypto_capabilities_packet()

int send_crypto_capabilities_packet ( socket_t sockfd,
const crypto_capabilities_packet_t * caps )

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

Send crypto capabilities packet.

Parameters
sockfdSocket file descriptor
capsCrypto capabilities packet structure
Returns
0 on success, -1 on error

Sends a PACKET_TYPE_CRYPTO_CAPABILITIES packet to advertise supported cryptographic algorithms (key exchange, authentication, cipher).

Note
Crypto capabilities packets are always sent unencrypted (handshake packets).
Parameters
sockfdSocket file descriptor
capsCrypto capabilities packet
Returns
0 on success, -1 on error

Definition at line 956 of file packet.c.

956 {
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}
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

References ERROR_INVALID_PARAM, PACKET_TYPE_CRYPTO_CAPABILITIES, send_packet(), and SET_ERRNO.

◆ send_crypto_parameters_packet()

int send_crypto_parameters_packet ( socket_t sockfd,
const crypto_parameters_packet_t * params )

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

Send crypto parameters packet.

Parameters
sockfdSocket file descriptor
paramsCrypto parameters packet structure
Returns
0 on success, -1 on error

Sends a PACKET_TYPE_CRYPTO_PARAMETERS packet containing chosen cryptographic algorithms and data sizes for handshake continuation.

Note
Crypto parameters packets are always sent unencrypted (handshake packets).
Parameters
sockfdSocket file descriptor
paramsCrypto parameters packet
Returns
0 on success, -1 on error

Definition at line 970 of file packet.c.

970 {
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}
Crypto parameters packet structure (Packet Type 15).
Definition packet.h:1060
uint16_t auth_public_key_size
Authentication public key size in bytes (e.g., 32 for Ed25519, 1952 for Dilithium3).
Definition packet.h:1072
uint16_t signature_size
Signature size in bytes (e.g., 64 for Ed25519, 3309 for Dilithium3).
Definition packet.h:1074
uint16_t shared_secret_size
Shared secret size in bytes (e.g., 32 for X25519).
Definition packet.h:1076
uint16_t kex_public_key_size
Key exchange public key size in bytes (e.g., 32 for X25519, 1568 for Kyber1024).
Definition packet.h:1070

References crypto_parameters_packet_t::auth_public_key_size, ERROR_INVALID_PARAM, HOST_TO_NET_U16, crypto_parameters_packet_t::kex_public_key_size, log_debug, PACKET_TYPE_CRYPTO_PARAMETERS, send_packet(), SET_ERRNO, crypto_parameters_packet_t::shared_secret_size, and crypto_parameters_packet_t::signature_size.

◆ send_image_frame_packet()

asciichat_error_t send_image_frame_packet ( socket_t sockfd,
const void * image_data,
uint16_t width,
uint16_t height,
uint8_t format )

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

Send image frame packet.

Parameters
sockfdSocket file descriptor
image_dataImage pixel data buffer
widthImage width in pixels
heightImage height in pixels
formatPixel format (0=RGB24)
Returns
ASCIICHAT_OK on success, error code on failure

Sends PACKET_TYPE_IMAGE_FRAME with RGB image data. Used for transmitting camera frames or video input.

Note
Maximum dimensions: 4096x4096 pixels (~25MB per frame).
Pixel data must be in RGB24 format (3 bytes per pixel).

Definition at line 1049 of file packet.c.

1049 {
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}
Describes one compressed image sent through ACIP. width, height, and pixel_format tell the decoder ho...
Definition packet.h:952
uint32_t pixel_format
Pixel format enum (1=RGB24, 2=RGBA32, 3=BGR24, 4=BGRA32).
Definition packet.h:958
uint32_t timestamp
Timestamp when frame was captured (milliseconds since epoch).
Definition packet.h:964
uint32_t compressed_size
Compressed data size (0 = not compressed, >0 = compressed).
Definition packet.h:960
uint32_t checksum
CRC32 checksum of pixel data.
Definition packet.h:962
uint32_t height
Image height in pixels.
Definition packet.h:956
uint32_t width
Image width in pixels.
Definition packet.h:954

References ASCIICHAT_OK, buffer_alloc(), buffer_release, image_frame_packet_t::checksum, image_frame_packet_t::compressed_size, ERROR_BUFFER_OVERFLOW, ERROR_INVALID_PARAM, ERROR_MEMORY, height, image_frame_packet_t::height, HOST_TO_NET_U32, packet_send(), PACKET_TYPE_IMAGE_FRAME, image_frame_packet_t::pixel_format, SET_ERRNO, image_frame_packet_t::timestamp, image_frame_packet_t::width, and width.

◆ send_packet()

int send_packet ( socket_t sockfd,
packet_type_t type,
const void * data,
size_t len )

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

Send a basic packet without encryption.

Parameters
sockfdSocket file descriptor
typePacket type (from packet_types.h)
dataPacket payload data
lenPayload data length in bytes
Returns
0 on success, -1 on error

Sends a plaintext packet without encryption. Equivalent to packet_send() but returns int instead of asciichat_error_t for compatibility.

Note
Use send_packet_secure() if encryption support is needed.
Parameters
sockfdSocket file descriptor
typePacket type
dataPacket data
lenData length
Returns
0 on success, -1 on error

Definition at line 581 of file packet.c.

581 {
582 asciichat_error_t result = packet_send(sockfd, type, data, len);
583 return result == ASCIICHAT_OK ? 0 : -1;
584}

References ASCIICHAT_OK, and packet_send().

Referenced by acip_server_send_error(), send_crypto_capabilities_packet(), send_crypto_parameters_packet(), send_error_packet_message(), send_ping_packet(), send_pong_packet(), and send_protocol_version_packet().

◆ send_packet_secure()

asciichat_error_t send_packet_secure ( socket_t sockfd,
packet_type_t type,
const void * data,
size_t len,
crypto_context_t * crypto_ctx )

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

Send a packet with encryption and compression support.

Parameters
sockfdSocket file descriptor
typePacket type (from packet_types.h)
dataPacket payload data
lenPayload data length in bytes
crypto_ctxCryptographic context for encryption (NULL for plaintext)
Returns
0 on success, negative on error

Sends a packet with automatic encryption (if crypto context provided) and compression (if packet is large enough). Handshake packets are never encrypted.

Note
Encryption is applied automatically when crypto_ctx is provided and packet type is not a handshake packet.
Compression is applied automatically to large packets based on size thresholds and compression ratios.
Handshake packets (packet_is_handshake_type(type) == true) are always sent unencrypted, even when crypto_ctx is provided.
Parameters
sockfdSocket file descriptor
typePacket type
dataPacket data
lenData length
crypto_ctxCrypto context for encryption
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 471 of file packet.c.

471 {
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};
532 acip_packet_plan_t plan = {0};
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}
#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:35
#define COMPRESSION_RATIO_THRESHOLD
Compression ratio threshold - only use if <80% original size.
Definition compression.h:63
#define LOG_RATE_FAST
Log rate limit: 1 second (1,000,000 microseconds).
Definition log_rates.h:31
#define GET_OPTION(field)
Definition options.h:1339
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
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
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

References acip_packet_encrypt(), acip_packet_plan(), ASCIICHAT_OK, buffer_alloc(), buffer_release, acip_packet_plan_t::ciphertext_capacity, compress_data(), COMPRESSION_MIN_SIZE, COMPRESSION_RATIO_THRESHOLD, crypto_is_ready(), acip_packet_plan_t::domain, crypto_context_t::encrypt_data, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, ERROR_NETWORK_SIZE, GET_OPTION, log_debug_every, LOG_RATE_FAST, log_warn_every, MAX_PACKET_SIZE, packet_header_build(), packet_send(), packet_send_timeout_ns(), SET_ERRNO, should_compress(), and US_PER_SEC_INT.

Referenced by av_send_audio_opus_batch(), packet_send_error(), and packet_send_remote_log().

◆ send_ping_packet()

int send_ping_packet ( socket_t sockfd)

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

Send a ping packet (keepalive).

Parameters
sockfdSocket file descriptor
Returns
0 on success, -1 on error

Sends a PACKET_TYPE_PING packet to keep connection alive. Server/client responds with PACKET_TYPE_PONG.

Note
Ping packets are always sent unencrypted (handshake packets).

Send a ping packet (keepalive).

Parameters
sockfdSocket file descriptor
Returns
0 on success, -1 on error

Definition at line 610 of file packet.c.

610 {
611 return send_packet(sockfd, PACKET_TYPE_PING, NULL, 0);
612}

References PACKET_TYPE_PING, and send_packet().

◆ send_pong_packet()

int send_pong_packet ( socket_t sockfd)

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

Send a pong packet (keepalive response).

Parameters
sockfdSocket file descriptor
Returns
0 on success, -1 on error

Sends a PACKET_TYPE_PONG packet in response to PACKET_TYPE_PING. Indicates that connection is alive and responsive.

Note
Pong packets are always sent unencrypted (handshake packets).

Send a pong packet (keepalive response).

Parameters
sockfdSocket file descriptor
Returns
0 on success, -1 on error

Definition at line 619 of file packet.c.

619 {
620 return send_packet(sockfd, PACKET_TYPE_PONG, NULL, 0);
621}

References PACKET_TYPE_PONG, and send_packet().

◆ send_protocol_version_packet()

int send_protocol_version_packet ( socket_t sockfd,
const protocol_version_packet_t * version )

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

Send protocol version negotiation packet.

Parameters
sockfdSocket file descriptor
versionProtocol version packet structure
Returns
0 on success, -1 on error

Sends a PACKET_TYPE_PROTOCOL_VERSION packet for protocol capability negotiation. Both client and server send this during handshake.

Note
Protocol version packets are always sent unencrypted (handshake packets).

Send protocol version negotiation packet.

Parameters
sockfdSocket file descriptor
versionProtocol version packet
Returns
0 on success, -1 on error

Definition at line 942 of file packet.c.

942 {
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}

References ERROR_INVALID_PARAM, PACKET_TYPE_PROTOCOL_VERSION, send_packet(), and SET_ERRNO.

◆ send_with_timeout()

ssize_t send_with_timeout ( socket_t sockfd,
const void * data,
size_t len,
uint64_t timeout_ns )

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

Send data with timeout using chunked transmission.

Parameters
sockfdSocket file descriptor
dataData to send
lenLength of data in bytes
timeout_nsTimeout in nanoseconds
Returns
Number of bytes sent on success, -1 on error

Sends data to socket with timeout support. Uses chunked transmission for large data to prevent blocking and enable progress tracking.

Note
Chunked transmission automatically handles large frames by sending in smaller chunks, preventing timeout issues.
Partial sends are handled automatically - function retries until all data is sent or timeout occurs.
Parameters
sockfdSocket file descriptor
dataData to send
lenLength of data
timeout_secondsTimeout in seconds
Returns
Number of bytes sent, or -1 on error

Definition at line 118 of file lib/network/network.c.

119 {
120 if (sockfd == INVALID_SOCKET_VALUE) {
121 errno = EBADF;
122 return -1;
123 }
124
125 size_t total_sent = 0;
126 const char *data_ptr = (const char *)data;
127
128 while (total_sent < len) {
129 // Calculate chunk size
130 size_t bytes_to_send = len - total_sent;
131 const size_t MAX_CHUNK_SIZE =
132 65536; // 64KB chunks for reliable TCP transmission
133 if (bytes_to_send > MAX_CHUNK_SIZE) {
134 bytes_to_send = MAX_CHUNK_SIZE;
135 }
136
137 // Set up poll for write timeout (in nanoseconds)
138 struct pollfd pfd;
139 pfd.fd = sockfd;
140 pfd.events = POLLOUT;
141 pfd.revents = 0;
142
143 int64_t effective_timeout_ns = network_is_test_environment()
144 ? (int64_t)(100LL * NS_PER_MS_INT)
145 : (int64_t)timeout_ns;
146 int result = socket_poll(&pfd, 1, effective_timeout_ns);
147 if (result <= 0) {
148 if (result == 0) {
149 SET_ERRNO_SYS(ERROR_NETWORK_TIMEOUT, "timed out after %llu nanoseconds",
150 (unsigned long long)timeout_ns);
151 return -1;
152 }
153 if (network_handle_select_error(result)) {
154 continue; // Retry
155 }
156 return -1; // Fatal error
157 }
158
159 // Check if socket is ready for writing
160 if (!(pfd.revents & POLLOUT)) {
162 "socket not ready for writing after poll");
163 return -1;
164 }
165
166 // Use platform-specific send
167 ssize_t sent = socket_send(sockfd, data_ptr + total_sent, bytes_to_send, 0);
168
169 if (sent < 0) {
170 int error = errno;
171 if (network_handle_send_error(error)) {
172 continue; // Retry
173 }
174 return -1; // Fatal error
175 }
176
177 if (sent > 0) {
178 total_sent += (size_t)sent;
179 }
180 }
181
182 return (ssize_t)total_sent;
183}
#define network_is_test_environment()
Check if we're in a test environment.
Definition network.h:168
ssize_t socket_send(socket_t, const void *, size_t, int)

References ERROR_NETWORK_TIMEOUT, network_is_test_environment, NS_PER_MS_INT, SET_ERRNO_SYS, socket_poll(), and socket_send().

◆ set_socket_keepalive()

asciichat_error_t set_socket_keepalive ( socket_t sockfd)

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

Enable TCP keepalive on socket.

Parameters
sockfdSocket file descriptor
Returns
ASCIICHAT_OK on success, error code on failure

Enables TCP keepalive probes on socket using KEEPALIVE_IDLE, KEEPALIVE_INTERVAL, and KEEPALIVE_COUNT settings.

Note
Keepalive helps detect dead connections (broken network path) without application-level heartbeats.

Enable TCP keepalive on socket.

Parameters
sockfdSocket file descriptor
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 416 of file lib/network/network.c.

416 {
417 if (sockfd == INVALID_SOCKET_VALUE) {
418 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket file descriptor");
419 }
420 int result = socket_set_keepalive_params(sockfd, true, KEEPALIVE_IDLE,
422 if (result != 0) {
424 "Failed to set socket keepalive parameters");
425 }
426 return ASCIICHAT_OK;
427}
#define KEEPALIVE_COUNT
Keepalive probe count (8 probes).
Definition network.h:207
#define KEEPALIVE_INTERVAL
Keepalive interval in seconds (10 seconds).
Definition network.h:198
#define KEEPALIVE_IDLE
Keepalive idle time in seconds (60 seconds).
Definition network.h:189

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, KEEPALIVE_COUNT, KEEPALIVE_IDLE, KEEPALIVE_INTERVAL, SET_ERRNO, and SET_ERRNO_SYS.

◆ set_socket_nonblocking()

asciichat_error_t set_socket_nonblocking ( socket_t sockfd)

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

Set socket to non-blocking mode.

Parameters
sockfdSocket file descriptor
Returns
ASCIICHAT_OK on success, error code on failure

Sets socket to non-blocking mode. I/O operations return immediately with error if data is not available.

Note
Non-blocking sockets require different error handling - EAGAIN/EWOULDBLOCK indicates operation would block.
Useful for asynchronous I/O patterns with select/poll/epoll.

Set socket to non-blocking mode.

Parameters
sockfdSocket file descriptor
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 434 of file lib/network/network.c.

434 {
435 if (sockfd == INVALID_SOCKET_VALUE) {
436 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket file descriptor");
437 }
438 int result = socket_set_nonblocking(sockfd, true);
439 if (result != 0) {
441 "Failed to set socket non-blocking mode");
442 }
443 return ASCIICHAT_OK;
444}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, SET_ERRNO, and SET_ERRNO_SYS.

Referenced by connect_with_timeout().

◆ set_socket_timeout()

asciichat_error_t set_socket_timeout ( socket_t sockfd,
uint64_t timeout_ns )

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

Set socket timeout for send/receive operations.

Parameters
sockfdSocket file descriptor
timeout_nsTimeout in nanoseconds (0 to disable timeout)
Returns
ASCIICHAT_OK on success, error code on failure

Configures socket-level timeout for send and receive operations. This sets SO_SNDTIMEO and SO_RCVTIMEO socket options.

Note
Socket-level timeouts work in addition to application-level timeouts in send_with_timeout() and recv_with_timeout().

Set socket timeout for send/receive operations.

Parameters
sockfdSocket file descriptor
timeout_nsTimeout in nanoseconds (converted to milliseconds for socket level)
Returns
ASCIICHAT_OK on success, error code on failure

Sets socket-level timeouts (SO_RCVTIMEO/SO_SNDTIMEO) as a safety net fallback. Actual precision depends on platform: milliseconds on most systems, microseconds on some. Works in conjunction with application-level timeouts via socket_poll.

Definition at line 379 of file lib/network/network.c.

379 {
380 if (sockfd == INVALID_SOCKET_VALUE) {
381 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket file descriptor");
382 }
383
384 // Convert nanoseconds to milliseconds for socket-level timeout
385 // Note: socket-level timeouts have ~millisecond granularity on most platforms
386 uint64_t timeout_ms = timeout_ns / (1000 * 1000);
387 if (timeout_ms == 0 && timeout_ns > 0) {
388 timeout_ms = 1; // Ensure at least 1ms for non-zero timeouts
389 }
390
391 // Set both receive and send timeouts using struct timeval
392 struct timeval tv;
393 tv.tv_sec = (long)(timeout_ms / 1000);
394 tv.tv_usec = (long)((timeout_ms % 1000) * 1000);
395
396 // Set receive timeout
397 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) !=
398 0) {
399 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to set socket receive timeout");
400 }
401
402 // Set send timeout
403 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) !=
404 0) {
405 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to set socket send timeout");
406 }
407
408 return ASCIICHAT_OK;
409}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, SET_ERRNO, and SET_ERRNO_SYS.

◆ socket_configure_buffers()

asciichat_error_t socket_configure_buffers ( socket_t sockfd)

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

Configure socket buffers and TCP_NODELAY for optimal performance.

Parameters
sockfdSocket file descriptor
Returns
ASCIICHAT_OK on success, or ERROR_NETWORK if all options fail

Configures socket with large send/receive buffers (1MB each) and enables TCP_NODELAY for low-latency real-time video streaming.

CONFIGURATION:

  • Send buffer: 1MB (SO_SNDBUF)
  • Receive buffer: 1MB (SO_RCVBUF)
  • TCP_NODELAY: enabled (disables Nagle's algorithm)

BEHAVIOR: Attempts to set all three socket options independently. Individual failures are logged as warnings but do not prevent attempting other options. This ensures TCP_NODELAY is always set even if buffer size configuration fails (common on systems with strict limits). Only returns error if ALL options fail.

Note
Large buffers prevent packet loss during frame bursts
TCP_NODELAY ensures frames are sent immediately without buffering
Call this immediately after socket creation/connection
Parameters
sockfdSocket file descriptor
Returns
ASCIICHAT_OK on success, ERROR_NETWORK_CONFIG on failure

Definition at line 451 of file lib/network/network.c.

451 {
452 if (sockfd == INVALID_SOCKET_VALUE) {
453 return SET_ERRNO_SYS(ERROR_NETWORK, "Invalid socket file descriptor");
454 }
455
456 int failed_options = 0;
457
458 // Attempt to configure 1MB send buffer for optimal frame transmission
459 int send_buffer_size = 1024 * 1024;
460 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &send_buffer_size,
461 sizeof(send_buffer_size)) < 0) {
462 log_warn("Failed to set send buffer size to 1MB: %s",
464 failed_options++;
465 }
466
467 // Attempt to configure 1MB receive buffer for optimal frame reception
468 int recv_buffer_size = 1024 * 1024;
469 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recv_buffer_size,
470 sizeof(recv_buffer_size)) < 0) {
471 log_warn("Failed to set receive buffer size to 1MB: %s",
473 failed_options++;
474 }
475
476 // Attempt to enable TCP_NODELAY to disable Nagle's algorithm for low-latency
477 // transmission This must be set even if buffer configuration fails, as it's
478 // essential for real-time video.
479 int tcp_nodelay = 1;
480 if (socket_setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &tcp_nodelay,
481 sizeof(tcp_nodelay)) < 0) {
482 log_warn("Failed to set TCP_NODELAY: %s", network_error_string());
483 failed_options++;
484 }
485
486 // Return error only if ALL options failed
487 if (failed_options >= 3) {
489 "Failed to configure all socket options");
490 }
491
492 return ASCIICHAT_OK;
493}
const char * network_error_string()
Get human-readable error string for network errors.

References ASCIICHAT_OK, ERROR_NETWORK, log_warn, network_error_string(), and SET_ERRNO_SYS.

◆ update_check_detect_install_method()

install_method_t update_check_detect_install_method ( void )

#include <include/ascii-chat/network/update_checker.h>

Detect installation method.

Checks binary path and system files to determine how ascii-chat was installed.

Returns
Installation method enum

Definition at line 493 of file update_checker.c.

493 {
494#if defined(ASCIICHAT_INSTALLED_BY_HOMEBREW)
496#elif defined(ASCIICHAT_INSTALLED_BY_SCOOP)
498#elif defined(ASCIICHAT_INSTALLED_BY_AUR)
500#elif defined(_WIN32)
502#else
503 if (is_homebrew_install()) {
505 }
506
507 if (is_arch_linux()) {
509 }
510
511 // The published Unix installer is the default outside package-managed
512 // installs.
514#endif
515}

References INSTALL_METHOD_ARCH_AUR, INSTALL_METHOD_HOMEBREW, INSTALL_METHOD_INSTALLER, and INSTALL_METHOD_SCOOP.

Referenced by update_banner_install_update(), update_banner_set_result(), and update_check_format_notification().

◆ update_check_dismiss_for_a_week()

void update_check_dismiss_for_a_week ( update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Persist a seven-day dismissal for the currently cached release.

Definition at line 263 of file update_checker.c.

263 {
264 if (!result) {
265 return;
266 }
268 (void)update_check_save_cache(result);
269}
asciichat_error_t update_check_save_cache(const update_check_result_t *result)
Save update check result to cache.
time_t dismissed_until
Suppress this available release until this time.
#define UPDATE_CHECK_CACHE_MAX_AGE_SECONDS

References update_check_result_t::dismissed_until, UPDATE_CHECK_CACHE_MAX_AGE_SECONDS, and update_check_save_cache().

Referenced by update_banner_show_prompt().

◆ update_check_format_notification()

void update_check_format_notification ( const update_check_result_t * result,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/network/update_checker.h>

Format update notification message.

Creates human-readable update notification with version comparison and upgrade suggestion. Example: "Update available: v0.8.1 (f8dc35e1) β†’ v0.9.0 (a1b2c3d4). Run: brew upgrade ascii-chat"

Parameters
resultUpdate check result
[out]bufferOutput buffer for formatted message
buffer_sizeSize of output buffer

Definition at line 578 of file update_checker.c.

579 {
580 if (!result || !buffer || buffer_size == 0) {
581 return;
582 }
583
584 // Get upgrade suggestion
588 suggestion, sizeof(suggestion));
589
590 // Keep the notification useful even when it is displayed in a log line:
591 // identify the versions, provide an actionable command or download URL, and
592 // point to the exact GitHub release that was returned by the API.
593 snprintf(buffer, buffer_size,
594 "Update available: %s β†’ %s. %s%s. Release notes: %s",
595 result->current_version, result->latest_version,
596 (method == INSTALL_METHOD_GITHUB || method == INSTALL_METHOD_UNKNOWN)
597 ? "Download: "
598 : "Run: ",
599 suggestion, result->release_url);
600}
int buffer_size
Size of circular buffer.
Definition grep.c:69
void update_check_get_upgrade_suggestion(install_method_t method, const char *latest_version, char *buffer, size_t buffer_size)
Get upgrade suggestion string.
install_method_t update_check_detect_install_method(void)
Detect installation method.
char current_version[64]
string
#define NETWORK_UPDATE_CHECKER_SUGGESTION_BUFFER_SIZE

References buffer_size, update_check_result_t::current_version, INSTALL_METHOD_GITHUB, INSTALL_METHOD_UNKNOWN, update_check_result_t::latest_version, NETWORK_UPDATE_CHECKER_SUGGESTION_BUFFER_SIZE, update_check_result_t::release_url, update_check_detect_install_method(), and update_check_get_upgrade_suggestion().

Referenced by action_check_update_immediate().

◆ update_check_get_aur_helper()

const char * update_check_get_aur_helper ( void )

#include <include/ascii-chat/network/update_checker.h>

Return the detected AUR helper (paru or yay), or NULL if unavailable.

Definition at line 517 of file update_checker.c.

517 {
518 static _Atomic int cached_helper = -1;
519 int helper = atomic_load(&cached_helper);
520 if (helper == -1) {
521 const char *paru[] = {"paru", "--version", NULL};
522 const char *yay[] = {"yay", "--version", NULL};
523 helper =
524 platform_execute_subprocess("paru", paru, NULL, 0, NULL, NULL) == 0 ? 1
525 : platform_execute_subprocess("yay", yay, NULL, 0, NULL, NULL) == 0 ? 2
526 : 0;
527 atomic_store(&cached_helper, helper);
528 }
529 return helper == 1 ? "paru" : helper == 2 ? "yay" : NULL;
530}
int platform_execute_subprocess(const char *executable, const char **argv, char *output_buffer, size_t output_size, bool(*cancel)(void *), void *data)
Definition system.c:35

References platform_execute_subprocess().

Referenced by update_banner_install_update(), update_banner_set_result(), and update_check_get_upgrade_suggestion().

◆ update_check_get_upgrade_suggestion()

void update_check_get_upgrade_suggestion ( install_method_t method,
const char * latest_version,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/network/update_checker.h>

Get upgrade suggestion string.

Returns appropriate upgrade command or URL based on installation method.

Parameters
methodInstallation method
latest_versionLatest version tag for GitHub URL
[out]bufferOutput buffer for suggestion string
buffer_sizeSize of output buffer

Definition at line 532 of file update_checker.c.

534 {
535 if (!buffer || buffer_size == 0) {
536 return;
537 }
538
539 switch (method) {
541 snprintf(buffer, buffer_size, "brew upgrade ascii-chat");
542 break;
543
545 snprintf(buffer, buffer_size, "scoop update ascii-chat");
546 break;
547
549#ifdef _WIN32
550 snprintf(buffer, buffer_size,
551 "irm https://ascii-chat.com/install.ps1 | iex");
552#else
553 snprintf(buffer, buffer_size,
554 "curl -fsSL https://ascii-chat.com/install.sh | bash");
555#endif
556 break;
557
559 const char *helper = update_check_get_aur_helper();
560 if (helper) {
561 snprintf(buffer, buffer_size, "%s -S ascii-chat", helper);
562 } else {
563 snprintf(buffer, buffer_size, "<your-aur-helper> -Ss ascii-chat");
564 }
565 break;
566 }
567
570 default:
571 snprintf(buffer, buffer_size,
572 "https://github.com/zfogg/ascii-chat/releases/tag/%s",
573 latest_version ? latest_version : "latest");
574 break;
575 }
576}
const char * update_check_get_aur_helper(void)

References buffer_size, INSTALL_METHOD_ARCH_AUR, INSTALL_METHOD_GITHUB, INSTALL_METHOD_HOMEBREW, INSTALL_METHOD_INSTALLER, INSTALL_METHOD_SCOOP, INSTALL_METHOD_UNKNOWN, and update_check_get_aur_helper().

Referenced by update_check_format_notification().

◆ update_check_is_cache_fresh()

bool update_check_is_cache_fresh ( const update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Check if cache is fresh (< 7 days old).

Parameters
resultCached result to check
Returns
true if cache is < 7 days old, false otherwise

Definition at line 252 of file update_checker.c.

252 {
253 if (!result || result->last_check_time == 0) {
254 return false;
255 }
256
257 time_t now = time(NULL);
258 time_t age = now - result->last_check_time;
259
261}
time_t last_check_time
Timestamp of last check.

References update_check_result_t::last_check_time, and UPDATE_CHECK_CACHE_MAX_AGE_SECONDS.

Referenced by update_check_startup(), and update_check_try_fresh_cache().

◆ update_check_is_dismissed()

bool update_check_is_dismissed ( const update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

True when the cached available release remains dismissed.

Definition at line 271 of file update_checker.c.

271 {
272 return result && result->dismissed_until > time(NULL);
273}

References update_check_result_t::dismissed_until.

Referenced by update_banner_show_prompt().

◆ update_check_load_cache()

asciichat_error_t update_check_load_cache ( update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Load cached update check result.

Reads cache file from ~/.config/ascii-chat/last_update_check. Cache format (4 lines):

  • Line 1: Unix timestamp
  • Line 2: Latest version tag (or empty if check failed)
  • Line 3: Latest SHA (full 40 chars, or empty if check failed)
  • Line 4: Exact GitHub release URL
Parameters
[out]resultOutput structure with cached results
Returns
ASCIICHAT_OK if cache valid, error if missing/corrupt

Definition at line 108 of file update_checker.c.

108 {
109 if (!result) {
110 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL result pointer");
111 }
112
113 memset(result, 0, sizeof(*result));
114
115 char *cache_path = get_cache_file_path();
116 if (!cache_path) {
118 "Could not determine cache file path");
119 }
120 defer(SAFE_FREE(cache_path));
121
122 /* A cache miss is expected on first launch. Check existence through the
123 * platform layer before opening so Windows does not turn the missing file
124 * into a stale errno-stack notification. */
125 if (platform_access(cache_path, PLATFORM_ACCESS_EXISTS) != 0)
126 return ASCIICHAT_OK;
127
128 FILE *f = platform_fopen("file_stream", cache_path, "r");
129 if (!f) {
130 const char *error_msg = file_read_error_message(cache_path);
131 return SET_ERRNO(ERROR_FILE_OPERATION, "%s", error_msg);
132 }
133 defer(SAFE_FCLOSE(f));
134
135 // Read line 1: timestamp
137 if (!fgets(line, sizeof(line), f)) {
139 "Failed to read timestamp from cache");
140 }
141
142 // Parse timestamp safely with error checking
143 errno = 0;
144 char *endptr = NULL;
145 long long timestamp_ll = strtoll(line, &endptr, 10);
146 if (errno != 0 || endptr == line) {
147 log_error("Failed to parse timestamp from cache: invalid value '%s'", line);
148 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid timestamp in cache file");
149 }
150 result->last_check_time = (time_t)timestamp_ll;
151
152 // Read line 2: latest version (may be empty if check failed)
153 if (fgets(line, sizeof(line), f)) {
154 trim_line_ending(line);
155 SAFE_STRNCPY(result->latest_version, line, sizeof(result->latest_version));
156 }
157
158 // Read line 3: latest SHA (may be empty if check failed)
159 if (fgets(line, sizeof(line), f)) {
160 trim_line_ending(line);
161 SAFE_STRNCPY(result->latest_sha, line, sizeof(result->latest_sha));
162 }
163
164 // Read line 4: release URL. This field is required in the current cache
165 // format; an older or partially-written cache must be refreshed.
166 if (!fgets(line, sizeof(line), f)) {
167 SAFE_FCLOSE(f);
168 // Treat a legacy cache exactly like a missing cache. Close the file before
169 // removing it so this also works on Windows, where open files cannot be
170 // deleted.
171 (void)remove(cache_path);
172 return SET_ERRNO(ERROR_FORMAT, "Update cache format is obsolete");
173 }
174 trim_line_ending(line);
175 SAFE_STRNCPY(result->release_url, line, sizeof(result->release_url));
176
177 // Older four-line cache files remain valid; they simply have no dismissal.
178 if (fgets(line, sizeof(line), f)) {
179 result->dismissed_until = (time_t)strtoll(line, NULL, 10);
180 }
181
182 SAFE_FCLOSE(f);
183
184 // Fill in current version/SHA
185 SAFE_STRNCPY(result->current_version, ASCII_CHAT_VERSION_STRING,
186 sizeof(result->current_version));
187 SAFE_STRNCPY(result->current_sha, ASCII_CHAT_GIT_COMMIT_HASH,
188 sizeof(result->current_sha));
189
190 // Determine if update is available using version comparison (if we have
191 // cached data)
192 if (result->latest_version[0] != '\0') {
193 semantic_version_t current_ver = version_parse(result->current_version);
194 semantic_version_t latest_ver = version_parse(result->latest_version);
195
196 if (current_ver.valid && latest_ver.valid) {
197 int cmp = version_compare(latest_ver, current_ver);
198 result->update_available =
199 (cmp > 0); // Update available if latest > current
200 result->check_succeeded = true;
201 } else {
202 // Cache contains invalid version data - delete it
203 log_warn("Update cache contains invalid version data (current:%s, "
204 "latest:%s) - deleting corrupted cache",
205 result->current_version, result->latest_version);
206 if (remove(cache_path) != 0) {
207 log_warn("Failed to delete corrupted cache file: %s", cache_path);
208 }
209 return SET_ERRNO(ERROR_FORMAT, "Corrupted cache file deleted");
210 }
211 }
212
213 return ASCIICHAT_OK;
214}
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FCLOSE(fp)
@ ERROR_FILE_OPERATION
@ ERROR_FORMAT
char current_sha[41]
Current commit SHA.
bool update_available
True if newer version exists.
bool check_succeeded
True if check completed (even if no update).
#define NETWORK_UPDATE_CHECKER_LINE_BUFFER_SIZE
int version_compare(semantic_version_t a, semantic_version_t b)
Definition version.c:113
semantic_version_t version_parse(const char *version_string)
Definition version.c:50

References ASCIICHAT_OK, update_check_result_t::check_succeeded, update_check_result_t::current_sha, update_check_result_t::current_version, update_check_result_t::dismissed_until, ERROR_FILE_OPERATION, ERROR_FORMAT, ERROR_INVALID_PARAM, update_check_result_t::last_check_time, update_check_result_t::latest_sha, update_check_result_t::latest_version, log_error, log_warn, NETWORK_UPDATE_CHECKER_LINE_BUFFER_SIZE, platform_access(), platform_fopen(), update_check_result_t::release_url, SAFE_FCLOSE, SAFE_FREE, SAFE_STRNCPY, SET_ERRNO, update_check_result_t::update_available, version_compare(), and version_parse().

◆ update_check_perform()

asciichat_error_t update_check_perform ( update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Check for updates from GitHub releases API.

Performs DNS connectivity test, fetches latest release from GitHub API, compares SHA with current build, and caches the result.

Parameters
[out]resultOutput structure with check results
Returns
ASCIICHAT_OK on success (check completed), error otherwise
Note
On timeout or network error, logs warning and marks as checked in cache
On DNS failure, does not update cache (will retry when online)
Timeout is 2 seconds for the entire operation

Definition at line 335 of file update_checker.c.

335 {
336 if (!result) {
337 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL result pointer");
338 }
339
340 update_check_result_t cached = {0};
341 bool have_cached = load_optional_cache(&cached) == ASCIICHAT_OK;
342 memset(result, 0, sizeof(*result));
343
344 // Fill in current version and SHA
345 SAFE_STRNCPY(result->current_version, ASCII_CHAT_VERSION_STRING,
346 sizeof(result->current_version));
347 SAFE_STRNCPY(result->current_sha, ASCII_CHAT_GIT_COMMIT_HASH,
348 sizeof(result->current_sha));
349 result->last_check_time = time(NULL);
350
351#ifndef NDEBUG
352 // Deterministic local seam for PTY smoke coverage. Release builds never
353 // consult it, and ordinary debug runs continue through the network path.
354 const char *test_latest =
355 SAFE_GETENV("ASCII_CHAT_TEST_UPDATE_LATEST_VERSION");
356 if (test_latest && test_latest[0]) {
357 SAFE_STRNCPY(result->latest_version, test_latest,
358 sizeof(result->latest_version));
359 const char *test_slow = SAFE_GETENV("ASCII_CHAT_TEST_UPDATE_SLOW");
360 if (test_slow && strcmp(test_slow, "1") == 0)
361 platform_sleep_ms(1000);
362 const char *test_gate = SAFE_GETENV("ASCII_CHAT_TEST_UPDATE_GATE");
363 if (test_gate && test_gate[0]) {
364 uint64_t deadline = time_get_ns() + 30 * NS_PER_SEC_INT;
365 while (platform_access(test_gate, PLATFORM_ACCESS_EXISTS) != 0 &&
366 time_get_ns() < deadline)
367 platform_sleep_ms(10);
368 }
370 "https://github.com/zfogg/ascii-chat/releases/latest",
371 sizeof(result->release_url));
372 result->check_succeeded = true;
373 semantic_version_t current_ver = version_parse(result->current_version);
374 semantic_version_t latest_ver = version_parse(result->latest_version);
375 result->update_available = current_ver.valid && latest_ver.valid &&
376 version_compare(latest_ver, current_ver) > 0;
377 if (have_cached &&
378 strcmp(cached.latest_version, result->latest_version) == 0) {
379 result->dismissed_until = cached.dismissed_until;
380 }
381 (void)update_check_save_cache(result);
382 return ASCIICHAT_OK;
383 }
384#endif
385
386 // Fetch latest release from GitHub API
387 log_info("Checking for updates from GitHub releases...");
389 if (!response) {
390 log_warn("Failed to fetch GitHub releases API (timeout or network error)");
391 // Don't save cache on network failure β€” retry next startup
392 result->check_succeeded = false;
393 return SET_ERRNO(ERROR_NETWORK, "Failed to fetch GitHub releases");
394 }
395
396 defer(SAFE_FREE(response));
397
398 // Parse JSON response
401
402 if (!parse_github_release_json(response, latest_tag, sizeof(latest_tag),
403 release_url, sizeof(release_url))) {
404 log_error("Failed to parse GitHub API response");
405 // Don't save cache on parse failure β€” retry next startup
406 result->check_succeeded = false;
407 return SET_ERRNO(ERROR_FORMAT, "Failed to parse GitHub API JSON");
408 }
409
410 // Fill in result
411 SAFE_STRNCPY(result->latest_version, latest_tag,
412 sizeof(result->latest_version));
413 SAFE_STRNCPY(result->release_url, release_url, sizeof(result->release_url));
414 result->latest_sha[0] = '\0';
415 result->check_succeeded = true;
416 if (have_cached &&
417 strcmp(cached.latest_version, result->latest_version) == 0) {
418 result->dismissed_until = cached.dismissed_until;
419 }
420
421 // Compare versions semantically
422 semantic_version_t current_ver = version_parse(result->current_version);
423 semantic_version_t latest_ver = version_parse(result->latest_version);
424
425 if (!current_ver.valid || !latest_ver.valid) {
426 log_warn("Failed to parse version strings for comparison (current: %s, "
427 "latest: %s)",
428 result->current_version, result->latest_version);
429 result->update_available = false;
430 } else {
431 int cmp = version_compare(latest_ver, current_ver);
432 result->update_available =
433 (cmp > 0); // Update available if latest > current
434 }
435
436 if (result->update_available) {
437 log_info("Update available: %s β†’ %s", result->current_version,
438 result->latest_version);
439 } else {
440 log_info("Already on latest version: %s", result->current_version);
441 }
442
443 // Save to cache
445
446 return ASCIICHAT_OK;
447}
#define SAFE_GETENV(name)
#define NETWORK_UPDATE_CHECKER_RELEASE_URL_BUFFER_SIZE
char * https_get(const char *hostname, const char *path)
Perform HTTPS GET request.
update check result keeps the values that move through the subsystem: update_available,...
#define GITHUB_API_HOSTNAME
#define GITHUB_RELEASES_PATH
#define NETWORK_UPDATE_CHECKER_LATEST_TAG_BUFFER_SIZE

References ASCIICHAT_OK, update_check_result_t::check_succeeded, update_check_result_t::current_sha, update_check_result_t::current_version, update_check_result_t::dismissed_until, ERROR_FORMAT, ERROR_INVALID_PARAM, ERROR_NETWORK, GITHUB_API_HOSTNAME, GITHUB_RELEASES_PATH, https_get(), update_check_result_t::last_check_time, update_check_result_t::latest_sha, update_check_result_t::latest_version, log_error, log_info, log_warn, NETWORK_UPDATE_CHECKER_LATEST_TAG_BUFFER_SIZE, NETWORK_UPDATE_CHECKER_RELEASE_URL_BUFFER_SIZE, NS_PER_SEC_INT, platform_access(), update_check_result_t::release_url, SAFE_FREE, SAFE_GETENV, SAFE_STRNCPY, SET_ERRNO, update_check_result_t::update_available, update_check_save_cache(), version_compare(), and version_parse().

Referenced by action_check_update_immediate(), and update_check_startup().

◆ update_check_save_cache()

asciichat_error_t update_check_save_cache ( const update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Save update check result to cache.

Writes cache file to ~/.config/ascii-chat/last_update_check.

Parameters
resultResult to cache
Returns
ASCIICHAT_OK on success, error otherwise

Definition at line 216 of file update_checker.c.

216 {
217 if (!result) {
218 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL result pointer");
219 }
220
221 char *cache_path = get_cache_file_path();
222 if (!cache_path) {
224 "Could not determine cache file path");
225 }
226 defer(SAFE_FREE(cache_path));
227
228 FILE *f = platform_fopen("file_stream", cache_path, "w");
229 if (!f) {
230 const char *error_msg = file_write_error_message(cache_path);
231 return SET_ERRNO(ERROR_FILE_OPERATION, "%s", error_msg);
232 }
233
234 // Write timestamp
235 fprintf(f, "%lld\n", (long long)result->last_check_time);
236
237 // Write version (may be empty if check failed)
238 fprintf(f, "%s\n", result->latest_version);
239
240 // Write SHA (may be empty if check failed)
241 fprintf(f, "%s\n", result->latest_sha);
242
243 // Write the release URL so cached notifications retain the exact GitHub
244 // source returned by the API.
245 fprintf(f, "%s\n", result->release_url);
246 fprintf(f, "%lld\n", (long long)result->dismissed_until);
247
248 fclose(f);
249 return ASCIICHAT_OK;
250}

References ASCIICHAT_OK, update_check_result_t::dismissed_until, ERROR_FILE_OPERATION, ERROR_INVALID_PARAM, update_check_result_t::last_check_time, update_check_result_t::latest_sha, update_check_result_t::latest_version, platform_fopen(), update_check_result_t::release_url, SAFE_FREE, and SET_ERRNO.

Referenced by update_check_dismiss_for_a_week(), and update_check_perform().

◆ update_check_startup()

asciichat_error_t update_check_startup ( update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Perform startup update check with caching.

Designed for automatic startup checks. Uses cache if fresh (< 7 days), otherwise performs fresh check. Non-blocking and silent on failure.

Parameters
[out]resultOutput structure with check results (can be NULL if you only want logging)
Returns
ASCIICHAT_OK if check succeeded, error otherwise
Note
Does nothing if cache is fresh
Logs warning on network failure but does not fail
Updates cache only if check succeeds

Definition at line 602 of file update_checker.c.

602 {
603 update_check_result_t local_result;
604 update_check_result_t *target = result ? result : &local_result;
605
606 // Try to load from cache first
607 asciichat_error_t cache_err = load_optional_cache(target);
608 if (cache_err == ASCIICHAT_OK && update_check_is_cache_fresh(target)) {
609 // Cache is fresh, use it
610 log_debug("Using cached update check result (age: %.1f days)",
611 (time(NULL) - target->last_check_time) / (double)SEC_PER_DAY);
612 return ASCIICHAT_OK;
613 }
614
615 // Cache is stale or missing, perform fresh check
616 log_debug("Performing automatic update check (cache %s)",
617 cache_err == ASCIICHAT_OK ? "stale" : "missing");
618 asciichat_error_t check_err = update_check_perform(target);
619 if (check_err != ASCIICHAT_OK) {
620 // Check failed, but don't fail startup
621 log_debug("Automatic update check failed (continuing startup)");
622 return check_err;
623 }
624
625 return ASCIICHAT_OK;
626}
#define SEC_PER_DAY
Definition time.h:185
bool update_check_is_cache_fresh(const update_check_result_t *result)
Check if cache is fresh (< 7 days old).
asciichat_error_t update_check_perform(update_check_result_t *result)
Check for updates from GitHub releases API.

References ASCIICHAT_OK, update_check_result_t::last_check_time, log_debug, SEC_PER_DAY, update_check_is_cache_fresh(), and update_check_perform().

◆ update_check_try_fresh_cache()

bool update_check_try_fresh_cache ( update_check_result_t * result)

#include <include/ascii-chat/network/update_checker.h>

Load a fresh cached result without treating a cache miss as an error.

Definition at line 330 of file update_checker.c.

330 {
331 return result && load_optional_cache(result) == ASCIICHAT_OK &&
333}

References ASCIICHAT_OK, and update_check_is_cache_fresh().