ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
packet.c File Reference

Go to the source code of this file.

Functions

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 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 *output)
uint64_t packet_send_timeout_ns (size_t packet_size)
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.
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.
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.
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.
int send_ping_packet (socket_t sockfd)
 Send a ping packet.
int send_pong_packet (socket_t sockfd)
 Send a pong packet.
asciichat_error_t packet_decrypt_envelope (packet_envelope_t *envelope, void *crypto_ctx)
 Send a clear console packet.
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)
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_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.
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.
int send_protocol_version_packet (socket_t sockfd, const protocol_version_packet_t *version)
 Send protocol version 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.
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)

Function Documentation

◆ packet_envelope_release()

void packet_envelope_release ( packet_envelope_t * envelope)

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}
size_t buffer_capacity(const void *data)
Definition buffer.c:278
bool buffer_is_unique(const void *data)
Definition buffer.c:315
#define buffer_release(data)
Definition buffer.h:99
Packet envelope containing received packet data.
Definition packet.h:1204

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 )

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:132

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_parse_envelope()

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.

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}
#define SET_ERRNO(code,...)
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
#define NET_TO_HOST_U16(val)
Definition endian.h:115
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
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
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
#define MAX_PACKET_SIZE
Maximum packet size (5MB).
Definition packet.h:144
void packet_envelope_release(packet_envelope_t *envelope)
Definition packet.c:711
static bool size_t gotel_query_t * out
Definition queries.h:8
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641

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 )

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 NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned int uint32_t
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
#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 )

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}
unsigned short uint16_t
enum remote_log_direction remote_log_direction_t
Remote log packet direction enumeration.
log_level_t
Logging levels enumeration.
Definition types.h:33
@ REMOTE_LOG_DIRECTION_UNKNOWN
Definition network/log.h:20
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:20
#define MAX_REMOTE_LOG_MESSAGE_LENGTH
Maximum remote log message length (512 bytes).
Definition packet.h:163
Remote log packet structure carrying log level and message text.
Definition packet.h:792
uint16_t flags
Additional flags (REMOTE_LOG_FLAG_*).
Definition packet.h:798
uint32_t message_length
Message payload length in bytes (0-512).
Definition packet.h:800
uint8_t log_level
Log level associated with the message (log_level_t cast to uint8_t).
Definition packet.h:794
uint8_t direction
Direction hint so receivers can annotate origin.
Definition packet.h:796
#define LOG_FATAL
Definition types.h:47

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_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 )

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 HOST_TO_NET_U32(val)
Definition endian.h:70
#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.
@ ERROR_NETWORK
Definition error_codes.h:76
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
asciichat_error_t send_packet_secure(socket_t sockfd, packet_type_t type, const void *data, size_t len, crypto_context_t *crypto_ctx)
Send a packet with encryption and compression support.
Definition packet.c:471
asciichat_error_t packet_send(socket_t sockfd, packet_type_t type, const void *data, size_t len)
Send a packet with proper header and CRC32.
Definition packet.c:348
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
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 )

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 HOST_TO_NET_U16(val)
Definition endian.h:100
#define REMOTE_LOG_FLAG_TRUNCATED
Remote log packet flag definitions.
Definition packet.h:787
@ PACKET_TYPE_REMOTE_LOG
Bidirectional remote logging packet.
Definition packet.h:390

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_send_timeout_ns()

uint64_t packet_send_timeout_ns ( size_t packet_size)

Calculate timeout based on packet size Large packets need more time to transmit reliably

Note
Returns timeout in nanoseconds for use with send/recv APIs

Definition at line 111 of file packet.c.

111 {
112 uint64_t base_timeout = SEND_TIMEOUT * NS_PER_SEC_INT;
113
114 // For large packets, increase timeout proportionally
115 if (packet_size > LARGE_PACKET_THRESHOLD) {
116 // Add extra timeout per MB above the threshold
117 uint64_t extra_timeout = (uint64_t)(((double)packet_size - LARGE_PACKET_THRESHOLD) / 1000000.0 * LARGE_PACKET_EXTRA_TIMEOUT_PER_MB) + NS_PER_MS_INT;
118 uint64_t total_timeout = base_timeout + extra_timeout;
119
120 // Ensure client timeout is longer than server's RECV_TIMEOUT (30s) to prevent deadlock
121 // Add 10 seconds buffer to account for server processing delays
122 if (total_timeout < MIN_CLIENT_TIMEOUT) {
123 total_timeout = MIN_CLIENT_TIMEOUT;
124 }
125
126 // Cap at maximum timeout
127 return (total_timeout > MAX_CLIENT_TIMEOUT) ? MAX_CLIENT_TIMEOUT : total_timeout;
128 }
129
130 return base_timeout;
131}
unsigned long long uint64_t
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define LARGE_PACKET_THRESHOLD
Large packet size threshold (100KB).
Definition packet.h:134
#define MAX_CLIENT_TIMEOUT
Maximum client timeout in nanoseconds (60 seconds).
Definition packet.h:214
#define LARGE_PACKET_EXTRA_TIMEOUT_PER_MB
Extra timeout per MB for large packets (0.8 seconds per MB).
Definition packet.h:194
#define MIN_CLIENT_TIMEOUT
Minimum client timeout in nanoseconds (10 seconds).
Definition packet.h:204
#define SEND_TIMEOUT
Send timeout in seconds (5 seconds).
Definition network.h:117

References LARGE_PACKET_EXTRA_TIMEOUT_PER_MB, LARGE_PACKET_THRESHOLD, MAX_CLIENT_TIMEOUT, MIN_CLIENT_TIMEOUT, NS_PER_MS_INT, NS_PER_SEC_INT, and SEND_TIMEOUT.

Referenced by packet_receive(), packet_send(), receive_packet_secure_with_timeout(), and send_packet_secure().

◆ 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 )

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 NET_TO_HOST_U64(val)
Definition endian.h:232
@ ERROR_CRYPTO
Definition error_codes.h:97
ssize_t recv_with_timeout(socket_t sockfd, void *buf, size_t len, uint64_t timeout_ns)
Receive data with timeout.
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define PACKET_MAGIC
Packet magic number (alias for MAGIC_PACKET_VALID).
Definition packet.h:284
@ PACKET_TYPE_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ PACKET_RECV_ERROR
Network error occurred.
Definition packet.h:1237
@ PACKET_RECV_EOF
Connection closed (EOF).
Definition packet.h:1235
@ PACKET_RECV_SUCCESS
Packet received successfully.
Definition packet.h:1233
uint64_t packet_send_timeout_ns(size_t packet_size)
Definition packet.c:111
#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().