ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Utility Functions

🛠️ String, path, IP, UTF-8, CRC32, and formatting utilities More...

Files

file  musl_c23_compat.c
 🔄 musl C23 compatibility wrappers for __isoc23_* symbol aliases (glibc 2.38+ compatibility)
file  crc32.c
 CRC32-C with cached CPU dispatch and a portable table fallback.
file  aspect_ratio.c
 📐 Terminal cell aspect ratio calculations for accurate image dimension scaling
file  format.c
 📊 Byte size formatting utilities for human-readable output (B, KB, MB, GB, TB, PB, EB)
file  image.c
 🖼️ Safe overflow-checked buffer size calculations for images and video frames
file  ip.c
 🌍 IPv4/IPv6 address parsing, validation, and formatting utilities
file  parsing.c
 🔍 Safe string parsing utilities for integers, sizes, and protocol messages
file  password.c
 🔑 Password prompting utilities with secure input and formatting
file  path.c
 Cross-platform path manipulation with normalization and Windows/Unix separator handling.
file  pcre2.c
 PCRE2 compilation and match helpers.
file  string.c
 🔤 String manipulation utilities: ASCII escaping, trimming, case conversion, and formatting
file  url.c
 Production-grade URL parsing and validation using PCRE2.
file  utf8.c
 🔤 UTF-8 encoding and decoding with multi-byte character support
file  version.c
 🏷️ Binary-embedded version information in custom ELF/Mach-O sections for runtime inspection
file  atomic.h
 ⚛️ Atomic operations abstraction layer with debug tracking
file  crc32.h
 Hardware-Accelerated CRC32 Checksum Computation.
file  aspect_ratio.h
 📐 Aspect Ratio Calculation Functions
file  bits.h
 🔢 Bit Manipulation Utilities
file  bytes.h
 🔢 Byte-Level Access and Arithmetic Utilities
file  display.h
 🖥️ Display Width and Terminal Centering Utilities
file  endian.h
 🔄 Network byte order conversion helpers
file  fnv1a.h
 #️⃣ FNV-1a Hash Function Implementation
file  format.h
 📊 String Formatting Utilities
file  image.h
 🖼️ Safe overflow-checked buffer size calculations for images and video frames
file  ip.h
 🌍 IP Address Parsing and Formatting Utilities
file  magic.h
 Magic number validation constants and macros.
file  math.h
 🔢 Mathematical Utility Functions
file  number.h
 🔢 Number Formatting and Conversion Utilities
file  overflow.h
 ✅ Safe Integer Arithmetic and Overflow Detection
file  parsing.h
 🔍 Safe Parsing Utilities
file  password.h
 Password prompting utilities with secure input and formatting.
file  path.h
 📂 Path Manipulation Utilities
file  pcre2.h
 PCRE2 compilation and match helpers.
file  string.h
 🔤 String Manipulation and Shell Escaping Utilities
file  thread.h
 🧵 Thread lifecycle management helpers
file  url.h
 🌐 Production-Grade URL Validation and Parsing
file  utf8.h
 🔤 UTF-8 Encoding and Decoding Utilities
file  util.h
 🛠️ Master Utility Header

Data Structures

struct  atomic_t
 Atomic value wrapper for integral/boolean types. More...
struct  atomic_ptr_t
 Atomic value wrapper for integral/boolean types. More...
struct  url_parts_t
 Structure containing parsed URL components. More...

Macros

#define asciichat_crc32(data, len)
 Main CRC32 dispatcher macro - use this in application code.
#define FNV1A_32_OFFSET_BASIS   2166136261ULL
 FNV-1a 32-bit offset basis.
#define FNV1A_32_PRIME   16777619ULL
 FNV-1a 32-bit prime.
#define FNV1A_32_MASK   0xFFFFFFFFULL
 FNV-1a 32-bit mask.
#define FNV1A_INIT(hash)
 FNV-1a 32-bit hash macro.
#define FNV1A_32_HASH(hash, byte)
 FNV-1a 32-bit hash macro for a single byte.
#define ROUND(xfloat)
 Round floating-point value to nearest integer.
#define UTIL_NUMBER_TEMP_BUFFER_SIZE   10
#define SIZE_MUL_SAFE(a, b)
 Multiply with overflow check inline (macro form for tight loops).
#define SIZE_ADD_SAFE(a, b)
 Add with overflow check inline (macro form for tight loops).
#define PASSWORD_MAX_LEN   260
 Buffer size for password input.
#define PATH_COMPONENT_DOT   '.'
 Path component: current directory (single dot).
#define PATH_COMPONENT_DOTDOT   ".."
 Path component: parent directory (double dot).
#define PATH_TILDE   '~'
 Path component: home directory tilde.
#define PATH_DRIVE_SEPARATOR   ':'
 Path component: Windows drive separator (colon).
#define MAX_PATH_BASES   16
 Maximum number of path base directories.

Enumerations

enum  path_role_t {
  PATH_ROLE_CONFIG_FILE , PATH_ROLE_LOG_FILE , PATH_ROLE_KEY_PRIVATE , PATH_ROLE_KEY_PUBLIC ,
  PATH_ROLE_CLIENT_KEYS
}
 Classification for user-supplied filesystem paths. More...

Functions

long __isoc23_wcstol (const wchar_t *str, wchar_t **endptr, int base)
 Wide string to integer conversion.
int __isoc23_scanf (const char *format,...)
 Formatted input functions.
int __isoc23_wscanf (const wchar_t *format,...)
 Wide character formatted input functions.
void arc4random_buf (void *buf, size_t nbytes)
 glibc-specific random functions for expat and fontconfig compatibility
uint32_t asciichat_crc32_update (uint32_t previous, const void *data, size_t len)
 Compute CRC32 checksum with hardware acceleration (if available).
uint32_t asciichat_crc32_sw_update (uint32_t previous, const void *data, size_t len)
uint32_t asciichat_crc32_hw (const void *data, size_t len)
uint32_t asciichat_crc32_sw (const void *data, size_t len)
 Compute CRC32 checksum using software implementation only.
bool crc32_hw_is_available (void)
 Check if hardware CRC32 acceleration is available at runtime.
void aspect_ratio (const ssize_t img_width, const ssize_t img_height, const ssize_t width, const ssize_t height, const bool stretch, ssize_t *out_width, ssize_t *out_height)
 Calculate aspect ratio with terminal character correction.
void aspect_ratio2 (const ssize_t img_width, const ssize_t img_height, const ssize_t target_width, const ssize_t target_height, ssize_t *out_width, ssize_t *out_height)
 Simple aspect ratio calculation without terminal character correction.
void calculate_fit_dimensions_pixel (int img_width, int img_height, int max_width, int max_height, int *out_width, int *out_height)
 Calculate fit dimensions for pixel-based images.
int display_width (const char *text)
 Calculate the visible display width of text with ANSI escape codes.
int display_center_horizontal (const char *text, int terminal_width)
 Calculate left padding needed to center text horizontally.
int display_center_vertical (int content_height, int terminal_height)
 Calculate top padding needed to vertically center content.
int display_height (const char *text, int terminal_width)
 Calculate how many display lines text will consume when wrapped.
void format_bytes_pretty (size_t bytes, char *out, size_t out_capacity)
 Format byte count into human-readable string.
int is_valid_ipv4 (const char *ip)
 Check if a string is a valid IPv4 address.
int is_valid_ipv6 (const char *ip)
 Check if a string is a valid IPv6 address.
int parse_ipv6_address (const char *input, char *output, size_t output_size)
 Parse IPv6 address, removing brackets if present.
int parse_ip_with_port (const char *input, char *ip_output, size_t ip_output_size, uint16_t *port_output)
 Parse IP address and port from string.
int parse_address_with_optional_port (const char *input, char *address_output, size_t address_output_size, uint16_t *port_output, uint16_t default_port)
 Parse address with optional port from string.
asciichat_error_t format_ip_address (int family, const struct sockaddr *addr, char *output, size_t output_size)
 Format IP address from socket address structure.
asciichat_error_t format_ip_with_port (const char *ip, uint16_t port, char *output, size_t output_size)
 Format IP address with port number.
int get_ip_version (const char *ip)
 Get IP address version.
int is_valid_ip (const char *ip)
 Check if string is a valid IP address (IPv4 or IPv6).
int ip_equals (const char *ip1, const char *ip2)
 Compare two IP addresses for equality.
int ip_compare (const char *ip1, const char *ip2)
 Compare two IP addresses for sorting.
int compare_ip_port_strings (const char *ip_port1, const char *ip_port2)
 Compare two "IP:port" strings with IPv6 normalization.
int parse_cidr (const char *cidr, char *ip_out, size_t ip_out_size, int *prefix_out)
 Parse CIDR notation into IP and prefix length.
int ip_in_cidr (const char *ip, const char *cidr)
 Check if IP address is within CIDR range.
int ip_in_cidr_parsed (const char *ip, const char *network, int prefix_len)
 Check if IP is within CIDR range (parsed form).
asciichat_error_t ipv4_to_ipv6_mapped (const char *ipv4, char *ipv6_out, size_t out_size)
 Convert IPv4 address to IPv6-mapped format.
asciichat_error_t extract_ipv4_from_mapped_ipv6 (const char *ipv6, char *ipv4_out, size_t out_size)
 Extract IPv4 address from IPv6-mapped format.
int is_ipv4_mapped_ipv6 (const char *ipv6)
 Check if IPv6 address is IPv4-mapped.
asciichat_error_t canonicalize_ipv6 (const char *ipv6, char *canonical_out, size_t out_size)
 Canonicalize IPv6 address to standard form.
asciichat_error_t expand_ipv6 (const char *ipv6, char *expanded_out, size_t out_size)
 Expand IPv6 address to full form.
asciichat_error_t compact_ipv6 (const char *ipv6, char *compact_out, size_t out_size)
 Compress IPv6 address using :: notation.
int is_anycast_ipv6 (const char *ipv6)
 Check if IPv6 address is anycast.
int is_lan_ipv4 (const char *ip)
 Check if IPv4 address is a private/LAN address.
int is_lan_ipv6 (const char *ip)
 Check if IPv6 address is a private/LAN address.
int is_broadcast_ipv4 (const char *ip)
 Check if IPv4 address is a broadcast address.
int is_broadcast_ipv6 (const char *ip)
 Check if IPv6 address is a multicast address.
int is_localhost_ipv4 (const char *ip)
 Check if IPv4 address is localhost.
int is_localhost_ipv6 (const char *ip)
 Check if IPv6 address is localhost.
int is_link_local_ipv4 (const char *ip)
 Check if IPv4 address is a link-local address.
int is_link_local_ipv6 (const char *ip)
 Check if IPv6 address is a link-local address.
int is_internet_ipv4 (const char *ip)
 Check if IPv4 address is a public internet address.
int is_internet_ipv6 (const char *ip)
 Check if IPv6 address is a public internet address.
int extract_ip_from_address (const char *addr_with_port, char *ip_out, size_t ip_out_size)
 Extract IP address (without port) from formatted address string.
const char * get_ip_type_string (const char *ip)
 Get human-readable string describing IP address type.
asciichat_error_t safe_parse_size_message (const char *message, unsigned int *width, unsigned int *height)
 Parse SIZE message format.
asciichat_error_t safe_parse_audio_message (const char *message, unsigned int *num_samples)
 Parse AUDIO message format.
int prompt_password (const char *prompt, char *password, size_t max_len)
 Prompt the user for a password with secure input.
int prompt_password_simple (const char *prompt, char *password, size_t max_len)
 Prompt the user for a password with simple formatting.
int prompt_password_simple_kind (const char *prompt, char *password, size_t max_len, ui_prompt_kind_t kind)
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.
const char * path_last_components (const char *path, size_t component_count)
 Return a pointer to the last components of a path.
char * expand_path (const char *path)
 Expand path with tilde (~) support.
char * get_config_dir (void)
 Get configuration directory path with XDG_CONFIG_HOME support.
char * get_data_dir (void)
 Get application data directory path.
char * get_log_dir (void)
 Get log directory path appropriate for current build type.
char * get_discovery_database_dir (void)
 Get discovery service database directory with Homebrew-aware system-wide fallback.
bool path_normalize_copy (const char *path, char *out, size_t out_len)
 Normalize a path and copy it into the provided buffer.
bool path_is_absolute (const char *path)
 Determine whether a path is absolute on the current platform.
bool path_is_within_base (const char *path, const char *base)
 Check whether a path resides within a specified base directory.
bool path_is_within_any_base (const char *path, const char *const *bases, size_t base_count)
 Check whether a path resides within any of several base directories.
bool path_looks_like_path (const char *value)
 Determine if a string is likely intended to reference the filesystem.
asciichat_error_t path_validate_user_path (const char *input, path_role_t role, char **normalized_out)
 Validate and canonicalize a user-supplied filesystem path.
void path_cleanup_thread_locals (void)
 Cleanup thread-local path resources.
void escape_ascii (const char *str, const char *escape_char, char *out_buffer, size_t out_buffer_size)
 Escape ASCII characters in a string.
bool escape_shell_single_quotes (const char *str, char *out_buffer, size_t out_buffer_size)
 Validate that a string contains only safe characters for shell commands.
bool escape_shell_double_quotes (const char *str, char *out_buffer, size_t out_buffer_size)
 Escape a string for safe use in shell commands (double quotes, Windows-compatible).
bool escape_path_for_shell (const char *path, char *out_buffer, size_t out_buffer_size)
 Check if a string needs shell quoting (contains spaces or special chars).
const char * colored_string (log_color_t color, const char *text)
 Build a colored string for terminal output.
int colored_string_set_output_fd (int fd)
void truncate_with_ellipsis (const char *input, char *output, size_t output_size, int max_width)
 Truncate a string to a maximum display width, with ellipsis.
void truncate_with_ellipsis_mode (const char *input, char *output, size_t output_size, int max_width, bool utf8)
 Truncate a string to a maximum display width with a terminal-appropriate ellipsis.
void strip_ansi_codes (const char *input, char *output, size_t output_size)
 Strip ANSI escape codes from a string.
asciichat_error_t hostname_to_ascii (const char *hostname, char *output, size_t capacity)
bool url_is_valid (const char *url)
 URL validation using shared parsing and ICU hostname checks.
asciichat_error_t url_parse (const char *url, url_parts_t *parts_out)
 Parse HTTP(S), WebSocket, and TCP URL into components.
void url_parts_destroy (url_parts_t *parts)
 Free parsed URL components.
bool url_is_websocket_scheme (const char *scheme)
 Check if URL scheme is WebSocket (ws or wss).
bool url_is_websocket (const char *url)
 Check if a URL string is a valid WebSocket URL.
bool url_looks_like_websocket (const char *url)
 Quick check if a string is a WebSocket URL.
bool url_is_tcp_scheme (const char *scheme)
 Check if URL scheme is TCP.
bool url_is_tcp (const char *url)
 Check if a URL string is a valid TCP URL.
bool url_looks_like_tcp (const char *url)
 Quick check if a string is a TCP URL.
void url_redact_diagnostic (char *text, bool truncated)
int utf8_decode (const uint8_t *s, uint32_t *codepoint)
 Decode a UTF-8 sequence to a Unicode codepoint.
int utf8_display_width (const char *str)
 Calculate terminal display width of a UTF-8 string.
int utf8_display_width_n (const char *str, size_t max_bytes)
 Calculate terminal display width of a UTF-8 string up to byte limit.
bool utf8_output_enabled (void)
 Return whether terminal output should use UTF-8 according to –utf8.
bool utf8_is_valid (const char *str)
 Check if a string is valid UTF-8.
bool utf8_is_ascii_only (const char *str)
 Check if a string contains only ASCII characters.
size_t utf8_char_count (const char *str)
 Count UTF-8 characters (not bytes).
size_t utf8_to_codepoints (const char *str, uint32_t *out_codepoints, size_t max_codepoints)
 Convert UTF-8 string to array of Unicode codepoints.
int utf8_next_char_bytes (const char *str, size_t max_bytes)
 Get byte length of next UTF-8 character.
const char * utf8_strcasestr (const char *haystack, const char *needle)
 Case-insensitive substring search with full Unicode support.
void utf8_write_lowercase (FILE *output, const char *text)
 Write UTF-8 string to file with ASCII lowercase conversion.

Detailed Description

🛠️ String, path, IP, UTF-8, CRC32, and formatting utilities

This header provides CRC32 checksum computation with automatic hardware acceleration when available. The system automatically dispatches to hardware implementations (SSE4.2, ARM CRC32) for optimal performance, falling back to a software implementation on platforms without hardware support.

CORE FEATURES:

  • Automatic hardware acceleration detection
  • Hardware-accelerated CRC32 on supported platforms (SSE4.2, ARM)
  • Software fallback implementation (always available)
  • Transparent performance optimization
  • Used for network packet integrity verification

HARDWARE ACCELERATION:

The system supports:

  • SSE4.2 CRC32 instruction (x86/x64 processors)
  • ARM CRC32 instructions (ARMv8 and later)
  • Automatic runtime detection and dispatch
  • Significant performance improvement over software implementation

SOFTWARE FALLBACK:

  • Always available on all platforms
  • Polynomial: Castagnoli (CRC32-C)
  • Optimized lookup table implementation
  • Reliable for packet integrity verification

PERFORMANCE:

Hardware acceleration provides:

  • Processes eight bytes per hardware CRC instruction
  • Caches the selected function pointer per thread
  • Automatic fallback ensures compatibility
Note
Use the asciichat_crc32() macro for automatic hardware dispatch.
Hardware acceleration is detected at runtime, so no compile-time CPU-specific compiler flags are required for callers.
CRC32 is used primarily for network packet integrity verification to detect transmission errors.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides functions for calculating image dimensions while maintaining aspect ratio. Functions handle terminal character correction for ASCII art rendering and pixel-based calculations for image scaling.

CORE FEATURES:

  • Aspect ratio calculations with terminal character correction
  • Simple aspect ratio calculations without terminal correction
  • Image dimension fitting within maximum bounds
  • Stretch/no-stretch mode support
  • Pixel-based and character-based calculations

TERMINAL CHARACTER CORRECTION:

Terminal characters have different aspect ratios than square pixels:

  • Terminal characters are typically taller than wide (e.g., 2:1 ratio)
  • This correction ensures ASCII art maintains proper proportions
  • aspect_ratio() applies terminal correction automatically
  • aspect_ratio2() skips correction for pixel-based calculations

ASPECT RATIO CALCULATIONS:

Functions calculate dimensions that maintain image aspect ratio:

Note
Terminal character aspect ratio correction is essential for proper ASCII art rendering that matches the original image proportions.
All output parameters are modified only on successful calculation.
This file contains functions based on jp2a code: Copyright (C) 2006 Christian Stigen Larsen, http://csl.sublevel3.org Distributed under the GNU General Public License (GPL) v2. Project homepage on http://jp2a.sf.net
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

Portable bit manipulation functions including power-of-two checks, bit counting, and leading/trailing zero detection across platforms.

CORE FEATURES:

  • Power-of-two validation and rounding
  • Find first/last set bit (platform-optimized)
  • Bit counting operations

PLATFORM SUPPORT:

  • GCC/Clang: Uses built-in intrinsics for optimal performance
  • MSVC: Uses Windows intrinsic functions
  • Fallback: Software implementations for all operations
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025

This header provides low-level utilities for safely reading and writing multi-byte values from/to unaligned memory addresses, with overflow detection for size calculations.

CORE FEATURES:

  • Safe unaligned memory access (16-bit and 32-bit values)
  • Safe size_t multiplication with overflow detection
  • Platform-safe byte manipulation (uses memcpy for portability)

UNALIGNED ACCESS:

Direct pointer casts like (uint32_t)ptr cause undefined behavior on architectures requiring aligned access (ARM, SPARC, etc.). These functions use memcpy which compilers optimize to single instructions when possible while remaining safe on all platforms.

Note
These functions are used extensively in network and crypto modules for parsing and generating packets.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025

This header provides a shared FNV-1a hash function implementation used throughout the codebase for consistent hashing with UBSan-safe arithmetic.

FNV-1a (Fowler-Noll-Vo) is a fast, non-cryptographic hash function with good distribution properties. This implementation uses 64-bit arithmetic to avoid unsigned overflow, then masks to 32-bit for the final result.

All functions are static inline for performance, allowing the compiler to inline them at call sites.

Note
This hash function is NOT for cryptographic purposes.
All arithmetic is done in 64-bit space to avoid UBSan warnings.

This header provides utilities for formatting various data types into human-readable strings. Functions handle byte counts, sizes, and other numeric values with appropriate units and formatting.

CORE FEATURES:

  • Byte count formatting with units (B, KB, MB, GB, TB)
  • Human-readable size strings
  • Automatic unit selection based on value
  • Fixed decimal precision
  • Buffer overflow protection

BYTE FORMATTING:

Byte counts are formatted with appropriate binary units:

  • Bytes (B): 0-1023 bytes
  • Kilobytes (KB): 1024-1048575 bytes
  • Megabytes (MB): 1048576-1073741823 bytes
  • Gigabytes (GB): 1073741824-1099511627775 bytes
  • Terabytes (TB): 1099511627776 and above
Note
All formatting functions ensure buffer overflow protection.
Output strings are null-terminated.
Decimal precision is fixed (2 decimal places for units >= KB).
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides utilities for validating, parsing, and formatting IPv4 and IPv6 addresses with proper bracket notation support. Functions handle various address formats including bracketed IPv6 addresses.

CORE FEATURES:

  • IPv4 address validation and parsing
  • IPv6 address validation and parsing
  • Bracket notation support for IPv6 ([::1])
  • IP address with port formatting and parsing
  • Hostname support (non-IP addresses)
  • Cross-platform compatibility

IP ADDRESS FORMATS:

The system supports various IP address formats:

  • IPv4: "192.0.2.1" (standard dotted decimal)
  • IPv6: "::1" or "[::1]" (with or without brackets)
  • IPv6: "2001:db8::1" or "[2001:db8::1]" (full format)
  • With port: "192.0.2.1:8080" or "[::1]:8080"

BRACKET NOTATION:

IPv6 addresses in URLs and socket addresses use bracket notation:

  • Format: "[2001:db8::1]:8080"
  • Brackets separate address from port (colons are part of IPv6 address)
  • parse_ipv6_address() removes brackets for internal use
  • format_ip_with_port() adds brackets for IPv6 addresses
Note
All parsing functions validate input addresses.
IPv6 addresses are normalized (brackets removed) for internal storage.
Port numbers are validated (0-65535 range).
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides lightweight mathematical utilities for image processing, including rounding and RGB value clamping.

CORE FEATURES:

  • RGB value clamping (0-255 range)
  • Floating-point to integer rounding
Note
For aspect ratio calculations, see util/aspect_ratio.h
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

Utilities for converting numbers to strings and calculating digit counts. Designed for minimal overhead, suitable for real-time video processing.

CORE FEATURES:

  • Digit counting for integers (no string allocation needed)
  • Decimal number to string conversion
  • Byte-to-string formatting (1-3 digits)
  • Fast and allocation-free implementations

USAGE:

// Count digits needed for allocation int digits = digits_u32(12345); // Returns 5 char buffer[digits]; size_t len = write_decimal(12345, buffer);

// Format u8 into ANSI sequence char ansi_seq[3]; char *end = write_u8(ansi_seq, 255); // Write "255" // ansi_seq now contains "255", end points after last char

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

Safe arithmetic operations that detect and handle integer overflow/underflow without undefined behavior. Essential for buffer size calculations and dimension validations to prevent security issues and crashes.

CORE FEATURES:

  • Safe multiplication with overflow detection
  • Safe addition with overflow detection
  • Checked size calculations (width * height * depth)
  • Clear error reporting

MOTIVATION:

Integer overflow in buffer size calculations is a common source of:

  • Buffer overflows (security vulnerability)
  • Crashes due to undersized allocations
  • Silent memory corruption

USAGE:

// Safe multiplication size_t result; if (checked_size_mul(width, height, &result) != ASCIICHAT_OK) { log_error("Dimension overflow: %zu x %zu", width, height); return ERROR_OVERFLOW; } uint8_t *buffer = SAFE_MALLOC(result, uint8_t *);

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

This header provides safe, validated parsing utilities for protocol message formats. Functions validate input strings, check for overflow conditions, and return structured error codes on failure.

CORE FEATURES:

  • Protocol message format parsing (SIZE, AUDIO)
  • Input validation and sanitization
  • Overflow protection for numeric values
  • Structured error reporting (asciichat_error_t)
  • Safe parsing without undefined behavior

PROTOCOL MESSAGE FORMATS:

The system supports parsing of ascii-chat protocol messages:

  • SIZE: "SIZE:width,height" - Video frame dimensions
  • AUDIO: "AUDIO:num_samples" - Audio sample count

VALIDATION:

All parsing functions validate:

  • Message format correctness
  • Numeric value ranges (no overflow)
  • Required fields presence
  • Delimiter correctness
Note
All parsing functions are safe and do not cause undefined behavior.
Invalid input returns error codes (ASCIICHAT_ERROR_*) for proper handling.
Output parameters are only modified on successful parsing.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

Provides high-level password prompting functionality built on top of the platform question API. Includes formatting with visual separators and consistent user experience across the application.

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

This header provides cross-platform utilities for working with file paths, including path expansion, configuration directory resolution, and project relative path extraction.

Core Features

  • Cross-platform path handling (Unix and Windows)
  • Tilde (~) expansion for home directory
  • XDG_CONFIG_HOME support for configuration paths
  • Project relative path extraction for logging
  • Path normalization and validation

Path Expansion

The system supports:

  • Tilde expansion: ~/path -> /home/user/path
  • Environment variable expansion (Windows VAR%)
  • Automatic platform-specific path separator handling

Configuration Directories

All ascii-chat data files (config, known_hosts, etc.) use a single directory:

  • Unix: $XDG_CONFIG_HOME/ascii-chat/ if set, otherwise ~/.ascii-chat/
  • Windows: APPDATA%\ascii-chat\ if set, otherwise ~.ascii-chat\
Note
All returned paths that require freeing are allocated with malloc() and must be freed by the caller using free().
Path operations handle both Unix (/) and Windows () separators.
Configuration paths include directory separator at the end.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides utilities for string manipulation, shell command escaping, and validation. Functions ensure strings are safe for use in shell commands and command-line interfaces.

CORE FEATURES:

  • Shell-safe string validation
  • Single and double quote escaping
  • ASCII character escaping
  • Cross-platform shell compatibility (Unix shells and Windows cmd.exe)
  • Buffer overflow protection

SHELL ESCAPING:

The system provides different escaping strategies:

  • Single quotes: Escapes for Unix shells (sh, bash, zsh)
  • Double quotes: Escapes for Windows cmd.exe compatibility
  • ASCII escaping: Escapes specific characters for terminal output

SHELL METACHARACTERS:

The following characters are considered unsafe for shell commands:

  • Control characters: ; & | $ ` \ " ' < > ( ) [ ] { } * ? ! ~ # @ - These characters can be used for command injection or shell expansion @note All escaping functions ensure buffer overflow protection. @note Escaped strings are safe for use in system() and popen() calls. @note Validation functions check for all common shell metacharacters. @author Zachary Fogg <me@zfo.gg> @date October 2025 */ int platform_vsnprintf(char *str, size_t size, const char *format, va_list ap); int platform_asprintf(char **strp, const char *format, ...); int platform_vasprintf(char **strp, const char *format, va_list ap); char *platform_strdup(const char *s); int platform_strcasecmp(const char *s1, const char *s2); int platform_strncasecmp(const char *s1, const char *s2, size_t n); char *platform_strtok_r(char *str, const char *delim, char **saveptr); size_t platform_strlcpy(char *dst, const char *src, size_t size); int platform_strncpy(char *dst, size_t dst_size, const char *src, size_t count); ssize_t platform_getline(char **lineptr, size_t *n, FILE *stream); asciichat_error_t platform_escape_shell_path(const char *path, char *output, size_t output_size); /* ============================================================================ String Escaping Functions \ifile "/home/runner/work/ascii-chat/ascii-chat/include/ascii-chat/util/url.h"

This header provides robust URL validation and parsing using PCRE2 regular expressions. Based on the production-grade HTTP(S) URL regex by Diego Perini (MIT License), extended for WebSocket.

CORE FEATURES:

  • Production-grade HTTP(S), WebSocket, and TCP URL validation via PCRE2
  • Comprehensive URL parsing (extract scheme, host, port, path)
  • Scheme support: http, https, ws, wss, tcp (case-insensitive)
  • IPv4, IPv6, and hostname support (localhost, bare hosts, FQDNs)
  • Private IP filtering (10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x)
  • JIT-compiled regex for 10-100x performance boost
  • Input validation and error reporting
  • Consistent error codes (asciichat_error_t)
  • Memory-safe operations

USAGE EXAMPLES:

Fast validation only (bool return):

if (url_is_valid("https://github.com/user/repo")) {
// URL is valid and can be safely used
}
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:156

Full parsing (extract components):

url_parts_t parts = {0};
if (url_parse("https://api.github.com:443/users", &parts) == ASCIICHAT_OK) {
printf("scheme: %s, host: %s, port: %d, path: %s\\n",
parts.scheme, parts.host, parts.port, parts.path);
}
@ ASCIICHAT_OK
Definition error_codes.h:50
void url_parts_destroy(url_parts_t *parts)
Free parsed URL components.
Definition url.c:299
asciichat_error_t url_parse(const char *url, url_parts_t *parts_out)
Parse HTTP(S), WebSocket, and TCP URL into components.
Definition url.c:163
Structure containing parsed URL components.
Definition url.h:69
char * path
Extracted path, query, and fragment (allocated if present, may be NULL).
Definition url.h:75
char * scheme
Extracted scheme: "http" or "https" (allocated).
Definition url.h:70
char * host
Canonical ASCII hostname or IP address (allocated).
Definition url.h:72
int port
Extracted port number (0 if not specified).
Definition url.h:74
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

Utility Functions

Overview

The Utility module provides a collection of helper functions and utilities used throughout ascii-chat. These include string manipulation, path handling, IP address parsing, mathematical operations, and format conversion.

Implementation: lib/util/*.h

Key Features:

  • Hardware-accelerated CRC32 checksums (SSE4.2, ARM CRC32)
  • Aspect ratio calculations and frame fitting
  • IP address parsing and validation (IPv4/IPv6)
  • UTF-8 string handling and validation
  • Path manipulation and normalization
  • String parsing and formatting utilities
  • Cross-platform mathematical operations

Utility Modules

CRC32 Checksums

Hardware Acceleration:

// CRC32 with automatic hardware acceleration
uint32_t checksum = crc32_compute(data, length);
// Check if hardware acceleration is available
if (crc32_hw_supported()) {
log_info("Using hardware CRC32 acceleration");
}
unsigned int uint32_t
#define log_info(...)
Log an INFO message.
Definition log/log.h:602

Platforms:

  • x86/x64: SSE4.2 instructions (CRC32C)
  • ARM: ARM CRC32 instructions
  • Fallback: Software table-based CRC32

Aspect Ratio

Calculate Aspect Ratio:

// Calculate aspect ratio for fitting
int image_width = 1920, image_height = 1080;
dimensions_t fitted = fit_to_aspect_ratio(
image_width, image_height
);
log_info("Fitted size: %dx%d", fitted.width, fitted.height);
int display_width(const char *text)
Calculate the visible display width of text with ANSI escape codes.
int display_height(const char *text, int terminal_width)
Calculate how many display lines text will consume when wrapped.

Maintain Aspect Ratio:

// Get dimensions that maintain aspect ratio
dimensions_t dims = calculate_aspect_ratio_fit(
src_width, src_height,
dst_width, dst_height,
maintain_aspect_ratio // true/false
);

IP Address Utilities

Parse IP Addresses:

// Parse IPv4 address
struct in_addr addr4;
if (parse_ipv4("192.168.1.1", &addr4)) {
log_info("Valid IPv4 address");
}
// Parse IPv6 address
struct in6_addr addr6;
if (parse_ipv6("::1", &addr6)) {
log_info("Valid IPv6 address");
}

Validate IP Addresses:

// Check if string is valid IP
if (is_valid_ipv4("192.168.1.1")) {
log_info("Valid IPv4");
}
if (is_valid_ipv6("2001:db8::1")) {
log_info("Valid IPv6");
}
int is_valid_ipv4(const char *ip)
Check if a string is a valid IPv4 address.
Definition ip.c:32
int is_valid_ipv6(const char *ip)
Check if a string is a valid IPv6 address.
Definition ip.c:63

Format IP Addresses:

char ip_str[INET6_ADDRSTRLEN];
format_ip_address(&addr, ip_str, sizeof(ip_str));
log_info("IP: %s", ip_str);
asciichat_error_t format_ip_address(int family, const struct sockaddr *addr, char *output, size_t output_size)
Format IP address from socket address structure.

UTF-8 String Handling

Validate UTF-8:

const char *text = "Hello, 世界!";
if (is_valid_utf8(text)) {
log_info("Valid UTF-8 string");
}

Count UTF-8 Characters:

size_t char_count = utf8_strlen(text);
size_t byte_count = strlen(text);
log_info("Characters: %zu, Bytes: %zu", char_count, byte_count);

Iterate UTF-8 Characters:

const char *p = text;
while (*p) {
uint32_t codepoint;
size_t bytes = utf8_decode(p, &codepoint);
log_debug("Codepoint: U+%04X", codepoint);
p += bytes;
}
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
int utf8_decode(const uint8_t *s, uint32_t *codepoint)
Decode a UTF-8 sequence to a Unicode codepoint.
Definition utf8.c:27

Path Utilities

Normalize Paths:

char normalized[PATH_MAX];
normalize_path("/path/to/../file.txt", normalized, sizeof(normalized));
// Result: "/path/file.txt"

Join Paths:

char joined[PATH_MAX];
join_path("/home/user", ".ssh/id_ed25519", joined, sizeof(joined));
// Result: "/home/user/.ssh/id_ed25519"

Expand Home Directory:

char expanded[PATH_MAX];
expand_home_dir("~/.ssh/known_hosts", expanded, sizeof(expanded));
// Result: "/home/username/.ssh/known_hosts"

Get File Extension:

const char *ext = get_file_extension("document.pdf");
// Result: "pdf"

String Utilities

Trim Whitespace:

char text[] = " hello world ";
trim_whitespace(text);
// Result: "hello world"

String Matching:

if (str_starts_with(text, "hello")) {
log_info("Text starts with 'hello'");
}
if (str_ends_with(text, "world")) {
log_info("Text ends with 'world'");
}

Case-Insensitive Compare:

if (strcasecmp_safe(str1, str2) == 0) {
log_info("Strings are equal (case-insensitive)");
}

Parsing Utilities

Parse Integers:

int value;
if (parse_int("1234", &value)) {
log_info("Parsed: %d", value);
}
// Parse with range validation
if (parse_int_range("42", &value, 0, 100)) {
log_info("Valid value in range: %d", value);
}

Parse Floating Point:

double value;
if (parse_double("3.14159", &value)) {
log_info("Parsed: %f", value);
}

Parse Boolean:

bool value;
if (parse_bool("true", &value)) {
log_info("Boolean: %s", value ? "true" : "false");
}
// Accepts: "true", "false", "yes", "no", "1", "0" (case-insensitive)

Format Utilities

Format Byte Sizes:

char size_str[32];
format_bytes(1024 * 1024 * 5, size_str, sizeof(size_str));
// Result: "5.00 MB"

Format Duration:

char duration[64];
format_duration(3665, duration, sizeof(duration));
// Result: "1h 1m 5s"

Format Timestamp:

char timestamp[32];
format_timestamp(time(NULL), timestamp, sizeof(timestamp));
// Result: "2025-01-15 14:23:45"

Mathematical Utilities

Safe Integer Math:

// Clamp value to range
int clamped = clamp(value, 0, 100);
// Get minimum/maximum
int min_val = min(a, b);
int max_val = max(a, b);

Rounding:

// Round to nearest integer
int rounded = round_to_int(3.7); // Result: 4
// Round up/down
int ceil_val = round_up(3.2); // Result: 4
int floor_val = round_down(3.8); // Result: 3

Alignment:

// Align to power of 2
size_t aligned = align_up(123, 16); // Result: 128
size_t aligned_down = align_down(123, 16); // Result: 112

Performance Notes

CRC32 Hardware Acceleration:

  • ~10x faster on x86 with SSE4.2
  • ~8x faster on ARM with CRC32 instructions
  • Automatically detected at runtime

UTF-8 Validation:

  • Optimized for ASCII-common case
  • SIMD acceleration where available
  • Early exit on invalid sequences

Path Operations:

  • In-place modifications where possible
  • Minimal allocations
  • Platform-specific optimizations

Best Practices

DO:

  • Validate input strings before processing
  • Use UTF-8 functions for international text
  • Check return values from parsing functions
  • Use hardware-accelerated CRC32 when available
  • Normalize paths before comparison

DON'T:

  • Don't assume ASCII-only input
  • Don't ignore parse errors
  • Don't use strcpy/sprintf (use safe versions)
  • Don't hard-code path separators
  • Don't perform string operations without bounds checking
See also
lib/crc32.h
lib/util/aspect_ratio.h
lib/util/ip.h
lib/util/utf8.h
lib/util/path.h
lib/util/string.h
lib/util/parsing.h
lib/util/format.h
lib/util/math.h

Macro Definition Documentation

◆ asciichat_crc32

#define asciichat_crc32 ( data,
len )

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

Value:
asciichat_crc32_hw((data), (len))
uint32_t asciichat_crc32_hw(const void *data, size_t len)
Definition crc32.c:120

Main CRC32 dispatcher macro - use this in application code.

Parameters
dataData to compute checksum for
lenLength of data in bytes
Returns
CRC32 checksum value (32-bit unsigned integer)

Recommended macro for CRC32 computation. Automatically dispatches to hardware-accelerated implementation when available, otherwise uses software fallback.

Note
This macro expands to asciichat_crc32_hw() which performs automatic hardware detection and fallback.
Use this macro in all application code for optimal performance with automatic hardware acceleration.
Example:
uint32_t checksum = asciichat_crc32(packet_data, packet_size);
#define asciichat_crc32(data, len)
Main CRC32 dispatcher macro - use this in application code.
Definition crc32.h:151

Definition at line 151 of file crc32.h.

Referenced by acds_receive_packet(), acip_send_ascii_frame_contract(), browser_client_validate_frame(), client_validate_frame(), packet_queue_validate_packet(), packet_send(), and packet_validate().

◆ FNV1A_32_HASH

#define FNV1A_32_HASH ( hash,
byte )

#include <include/ascii-chat/util/fnv1a.h>

Value:
do { \
(hash) = (((hash) ^ (uint64_t)(byte)) * FNV1A_32_PRIME) & FNV1A_32_MASK; \
} while (0)
unsigned long long uint64_t
#define FNV1A_32_MASK
FNV-1a 32-bit mask.
Definition fnv1a.h:45
#define FNV1A_32_PRIME
FNV-1a 32-bit prime.
Definition fnv1a.h:42

FNV-1a 32-bit hash macro for a single byte.

Definition at line 55 of file fnv1a.h.

55#define FNV1A_32_HASH(hash, byte) \
56 do { \
57 (hash) = (((hash) ^ (uint64_t)(byte)) * FNV1A_32_PRIME) & FNV1A_32_MASK; \
58 } while (0)

◆ FNV1A_32_MASK

#define FNV1A_32_MASK   0xFFFFFFFFULL

#include <include/ascii-chat/util/fnv1a.h>

FNV-1a 32-bit mask.

Definition at line 45 of file fnv1a.h.

◆ FNV1A_32_OFFSET_BASIS

#define FNV1A_32_OFFSET_BASIS   2166136261ULL

#include <include/ascii-chat/util/fnv1a.h>

FNV-1a 32-bit offset basis.

Definition at line 39 of file fnv1a.h.

◆ FNV1A_32_PRIME

#define FNV1A_32_PRIME   16777619ULL

#include <include/ascii-chat/util/fnv1a.h>

FNV-1a 32-bit prime.

Definition at line 42 of file fnv1a.h.

◆ FNV1A_INIT

#define FNV1A_INIT ( hash)

#include <include/ascii-chat/util/fnv1a.h>

Value:
#define FNV1A_32_OFFSET_BASIS
FNV-1a 32-bit offset basis.
Definition fnv1a.h:39

FNV-1a 32-bit hash macro.

Definition at line 52 of file fnv1a.h.

◆ MAX_PATH_BASES

#define MAX_PATH_BASES   16

#include <include/ascii-chat/util/path.h>

Maximum number of path base directories.

Maximum number of base directories that can be checked in path validation.

Definition at line 89 of file path.h.

Referenced by path_validate_user_path().

◆ PASSWORD_MAX_LEN

#define PASSWORD_MAX_LEN   260

#include <include/ascii-chat/util/password.h>

Buffer size for password input.

Passwords are limited to 256 characters per validate_opt_password(). Adding space for null terminator and some margin.

Definition at line 31 of file password.h.

Referenced by read_password_from_stdin().

◆ PATH_COMPONENT_DOT

#define PATH_COMPONENT_DOT   '.'

#include <include/ascii-chat/util/path.h>

Path component: current directory (single dot).

Character constant for the current directory component in paths.

Definition at line 63 of file path.h.

Referenced by path_looks_like_path().

◆ PATH_COMPONENT_DOTDOT

#define PATH_COMPONENT_DOTDOT   ".."

#include <include/ascii-chat/util/path.h>

Path component: parent directory (double dot).

String constant for the parent directory component in paths.

Definition at line 70 of file path.h.

◆ PATH_DRIVE_SEPARATOR

#define PATH_DRIVE_SEPARATOR   ':'

#include <include/ascii-chat/util/path.h>

Path component: Windows drive separator (colon).

Definition at line 82 of file path.h.

Referenced by path_is_absolute().

◆ PATH_TILDE

#define PATH_TILDE   '~'

#include <include/ascii-chat/util/path.h>

Path component: home directory tilde.

The home directory component in paths (e.g., "~/path").

Definition at line 77 of file path.h.

Referenced by expand_path(), and path_looks_like_path().

◆ ROUND

#define ROUND ( xfloat)

#include <include/ascii-chat/util/math.h>

Value:
(int)(0.5f + (xfloat))

Round floating-point value to nearest integer.

Parameters
xfloatFloating-point value to round
Returns
Nearest integer value

Rounds a floating-point value to the nearest integer using standard rounding rules (0.5 rounds up). Uses simple addition of 0.5 and truncation.

Note
This is a macro for performance (inlined at compile time).
Uses standard rounding (banker's rounding not applied).
Example
int rounded = ROUND(3.7); // Returns 4
int rounded = ROUND(3.2); // Returns 3
int rounded = ROUND(-2.5); // Returns -2
#define ROUND(xfloat)
Round floating-point value to nearest integer.
Definition math.h:57

Definition at line 57 of file math.h.

◆ SIZE_ADD_SAFE

#define SIZE_ADD_SAFE ( a,
b )

#include <include/ascii-chat/util/overflow.h>

Value:
(size_add_would_overflow(a, b) ? SIZE_MAX : (a) + (b))

Add with overflow check inline (macro form for tight loops).

Parameters
aFirst operand
bSecond operand
Returns
Sum if no overflow, SIZE_MAX if would overflow

Macro version of checked addition that returns SIZE_MAX on overflow.

Warning
The result SIZE_MAX might be a valid sum. Use the function version (checked_size_add) for proper error handling in most code.

Definition at line 248 of file overflow.h.

◆ SIZE_MUL_SAFE

#define SIZE_MUL_SAFE ( a,
b )

#include <include/ascii-chat/util/overflow.h>

Value:
(size_mul_would_overflow(a, b) ? SIZE_MAX : (a) * (b))

Multiply with overflow check inline (macro form for tight loops).

Parameters
aFirst operand
bSecond operand
Returns
Product if no overflow, SIZE_MAX if would overflow

Macro version of checked multiplication that returns SIZE_MAX on overflow. Useful in performance-critical loops where you want to avoid function calls.

Warning
The result SIZE_MAX might be a valid product. Use the function version (checked_size_mul) for proper error handling in most code.

Definition at line 233 of file overflow.h.

◆ UTIL_NUMBER_TEMP_BUFFER_SIZE

#define UTIL_NUMBER_TEMP_BUFFER_SIZE   10

#include <include/ascii-chat/util/number.h>

Definition at line 37 of file number.h.

Enumeration Type Documentation

◆ path_role_t

#include <include/ascii-chat/util/path.h>

Classification for user-supplied filesystem paths.

Enumerator
PATH_ROLE_CONFIG_FILE 

Configuration files such as config.toml

PATH_ROLE_LOG_FILE 

Log file destinations

PATH_ROLE_KEY_PRIVATE 

Private key files (SSH/GPG)

PATH_ROLE_KEY_PUBLIC 

Public key files or expected server keys

PATH_ROLE_CLIENT_KEYS 

Client key whitelist files

Definition at line 322 of file path.h.

324 {
@ PATH_ROLE_CONFIG_FILE
Definition path.h:323
@ PATH_ROLE_KEY_PUBLIC
Definition path.h:326
@ PATH_ROLE_LOG_FILE
Definition path.h:324
@ PATH_ROLE_KEY_PRIVATE
Definition path.h:325

Function Documentation

◆ __isoc23_scanf()

int __isoc23_scanf ( const char * format,
... )

#include <lib/musl_c23_compat.c>

Formatted input functions.

Read formatted input from stdin (C23 compatible)

Parameters
formatFormat string
...Variable arguments
Returns
Number of successfully read items

Definition at line 114 of file musl_c23_compat.c.

114 {
115 va_list args;
116 va_start(args, format);
117 int result = vscanf(format, args);
118 va_end(args);
119 return result;
120}
action_args_t args

References args.

◆ __isoc23_wcstol()

long __isoc23_wcstol ( const wchar_t * str,
wchar_t ** endptr,
int base )

#include <lib/musl_c23_compat.c>

Wide string to integer conversion.

Convert wide string to long (C23 compatible)

Parameters
strWide string to convert
endptrPointer to first non-digit character (optional)
baseNumeric base (0-36)
Returns
Converted value

Definition at line 67 of file musl_c23_compat.c.

67 {
68 return wcstol(str, endptr, base);
69}

◆ __isoc23_wscanf()

int __isoc23_wscanf ( const wchar_t * format,
... )

#include <lib/musl_c23_compat.c>

Wide character formatted input functions.

Read formatted wide input from stdin (C23 compatible)

Parameters
formatFormat string
...Variable arguments
Returns
Number of successfully read items

Definition at line 194 of file musl_c23_compat.c.

194 {
195 va_list args;
196 va_start(args, format);
197 int result = vwscanf(format, args);
198 va_end(args);
199 return result;
200}

References args.

◆ arc4random_buf()

void arc4random_buf ( void * buf,
size_t nbytes )

#include <lib/musl_c23_compat.c>

glibc-specific random functions for expat and fontconfig compatibility

Fill buffer with cryptographically secure random bytes

Used by expat for hash seeding and other security-critical operations. Attempts getrandom syscall first (Linux 3.17+), falls back to /dev/urandom.

Parameters
bufOutput buffer (must not be NULL if nbytes > 0)
nbytesNumber of random bytes to generate

Definition at line 283 of file musl_c23_compat.c.

283 {
284 if (nbytes == 0 || buf == NULL) {
285 return;
286 }
287
288/* Prefer getrandom syscall: available in Linux 3.17+, no file descriptor needed */
289#ifdef SYS_getrandom
290 long result = syscall(SYS_getrandom, buf, nbytes, 0);
291 if (result == (long)nbytes) {
292 return;
293 }
294#endif
295
296 /* Fallback to /dev/urandom device */
297 int fd = open("/dev/urandom", O_RDONLY);
298 if (fd >= 0) {
299 ssize_t n = read(fd, buf, nbytes);
300 close(fd);
301 if (n == (ssize_t)nbytes) {
302 return;
303 }
304 }
305
306 /* Fatal error: unable to obtain random bytes */
307 abort();
308}

Referenced by random_r().

◆ asciichat_crc32_hw()

uint32_t asciichat_crc32_hw ( const void * data,
size_t len )

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

Definition at line 120 of file crc32.c.

120 {
121 return asciichat_crc32_update(0, data, len);
122}
uint32_t asciichat_crc32_update(uint32_t previous, const void *data, size_t len)
Compute CRC32 checksum with hardware acceleration (if available).
Definition crc32.c:81

References asciichat_crc32_update().

◆ asciichat_crc32_sw()

uint32_t asciichat_crc32_sw ( const void * data,
size_t len )

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

Compute CRC32 checksum using software implementation only.

Parameters
dataData to compute checksum for (may be NULL when len is zero)
lenLength of data in bytes
Returns
CRC32 checksum value (32-bit unsigned integer)

Computes CRC32 checksum using a software lookup table implementation. Always uses software implementation regardless of hardware availability.

Note
This function bypasses runtime dispatch for testing and benchmarking.
For production code, prefer asciichat_crc32() macro which automatically uses hardware acceleration when available.
The CRC32 polynomial used is Castagnoli (CRC32-C), which is compatible with SSE4.2 and ARM CRC32-C instructions.

Definition at line 124 of file crc32.c.

124 {
125 return asciichat_crc32_sw_update(0, data, len);
126}
uint32_t asciichat_crc32_sw_update(uint32_t previous, const void *data, size_t len)
Definition crc32.c:112

References asciichat_crc32_sw_update().

◆ asciichat_crc32_sw_update()

uint32_t asciichat_crc32_sw_update ( uint32_t previous,
const void * data,
size_t len )

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

Definition at line 112 of file crc32.c.

112 {
113 const uint8_t *bytes = (const uint8_t *)data;
114 uint32_t crc = ~previous;
115 for (size_t i = 0; i < len; i++)
116 crc = (crc >> 8) ^ crc32c_table[(crc ^ bytes[i]) & 0xFFu];
117 return ~crc;
118}
unsigned char uint8_t

Referenced by asciichat_crc32_sw(), and crc32_hw_is_available().

◆ asciichat_crc32_update()

uint32_t asciichat_crc32_update ( uint32_t previous,
const void * data,
size_t len )

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

Compute CRC32 checksum with hardware acceleration (if available).

Parameters
dataData to compute checksum for (may be NULL when len is zero)
lenLength of data in bytes
Returns
CRC32 checksum value (32-bit unsigned integer)

Computes CRC32 checksum using hardware acceleration when available. Automatically falls back to software implementation if hardware is not available on the current platform.

Note
This function performs runtime CPU feature detection to determine whether to use hardware or software implementation.
Hardware acceleration is available on:
  • x86/x64 processors with SSE4.2 (CRC32 instruction)
  • ARM processors with ARMv8 (CRC32 instructions)
For consistent performance testing or when hardware detection is not desired, use asciichat_crc32_sw() directly.
The CRC32 polynomial used is Castagnoli (CRC32-C), which is compatible with SSE4.2 and ARM CRC32-C instructions. Extend a finalized CRC32-C; pass zero for the first slice.

Definition at line 81 of file crc32.c.

81 {
82 return crc32_backend()(previous, data, len);
83}

Referenced by asciichat_crc32_hw(), and packet_header_build().

◆ aspect_ratio()

void aspect_ratio ( const ssize_t img_width,
const ssize_t img_height,
const ssize_t width,
const ssize_t height,
const bool stretch,
ssize_t * out_width,
ssize_t * out_height )

#include <include/ascii-chat/util/aspect_ratio.h>

Calculate aspect ratio with terminal character correction.

Parameters
img_widthInput image width in pixels (must be > 0)
img_heightInput image height in pixels (must be > 0)
widthTarget width in terminal characters (must be > 0)
heightTarget height in terminal lines (must be > 0)
stretchWhether to allow stretching (true) or maintain aspect ratio (false)
out_widthOutput parameter for calculated width (must not be NULL)
out_heightOutput parameter for calculated height (must not be NULL)

Calculates output dimensions for ASCII art rendering with terminal character aspect ratio correction. Terminal characters are typically taller than wide (e.g., 2:1 ratio), so this function corrects for that to maintain proper image proportions in ASCII art.

TERMINAL CORRECTION:

  • Applies character aspect ratio correction (accounts for terminal font)
  • Ensures ASCII art matches original image proportions
  • When stretch=false, maintains original image aspect ratio
  • When stretch=true, fills target dimensions exactly
Note
Output dimensions respect target size while maintaining aspect ratio.
Terminal character correction is essential for proper ASCII art rendering.
Output parameters are modified to contain calculated dimensions.
Example
ssize_t out_w, out_h;
aspect_ratio(1920, 1080, 80, 40, false, &out_w, &out_h);
// Calculates dimensions that fit within 80x40 terminal while maintaining 16:9 aspect
void aspect_ratio(const ssize_t img_w, const ssize_t img_h, const ssize_t width, const ssize_t height, const bool stretch, ssize_t *out_width, ssize_t *out_height)
Calculate aspect ratio with terminal character correction.

Definition at line 68 of file aspect_ratio.c.

68 {
69 // Input validation
70 if (!out_width || !out_height) {
71 return; // or log error
72 }
73
74 if (img_w <= 0 || img_h <= 0) {
75 // Handle degenerate image dimensions
76 *out_width = MIN_DIMENSION;
77 *out_height = MIN_DIMENSION;
78 return;
79 }
80
81 if (stretch) {
82 // If stretching is enabled, just use the full terminal dimensions
83 *out_width = width;
84 *out_height = height;
85 } else {
86 // Calculate aspect-correct dimensions to fit within the given width/height
87 calculate_fit_dimensions(img_w, img_h, width, height, out_width, out_height);
88 }
89}
@ MIN_DIMENSION
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24

References height, MIN_DIMENSION, and width.

Referenced by ascii_convert().

◆ aspect_ratio2()

void aspect_ratio2 ( const ssize_t img_width,
const ssize_t img_height,
const ssize_t target_width,
const ssize_t target_height,
ssize_t * out_width,
ssize_t * out_height )

#include <include/ascii-chat/util/aspect_ratio.h>

Simple aspect ratio calculation without terminal character correction.

Parameters
img_widthInput image width in pixels (must be > 0)
img_heightInput image height in pixels (must be > 0)
target_widthTarget width (must be > 0)
target_heightTarget height (must be > 0)
out_widthOutput parameter for calculated width (must not be NULL)
out_heightOutput parameter for calculated height (must not be NULL)

Calculates output dimensions that maintain the input image's aspect ratio while fitting within target dimensions. This is a simple pixel-based calculation without terminal character correction.

Note
This function does NOT apply terminal character correction.
Use aspect_ratio() for ASCII art rendering (with terminal correction).
Output dimensions are calculated to fit within target while maintaining ratio.
Example
ssize_t out_w, out_h;
aspect_ratio2(1920, 1080, 800, 600, &out_w, &out_h);
// Calculates dimensions that fit within 800x600 while maintaining 16:9 aspect
void aspect_ratio2(const ssize_t img_w, const ssize_t img_h, const ssize_t target_w, const ssize_t target_h, ssize_t *out_width, ssize_t *out_height)
Simple aspect ratio calculation without terminal character correction.

Definition at line 93 of file aspect_ratio.c.

93 {
94 // Input validation
95 if (!out_width || !out_height) {
96 return;
97 }
98
99 if (img_w <= 0 || img_h <= 0 || target_w <= 0 || target_h <= 0) {
100 // Handle invalid dimensions
101 *out_width = MIN_DIMENSION;
102 *out_height = MIN_DIMENSION;
103 return;
104 }
105
106 // Calculate aspect ratio
107 float img_aspect = (float)img_w / (float)img_h;
108
109 // We want the image to fill at least one dimension of the target box
110 // while maintaining aspect ratio and fitting within the box
111
112 // Calculate dimensions if we scale to fill width
113 ssize_t width_if_fill_width = target_w;
114 ssize_t height_if_fill_width = (ssize_t)((float)target_w / img_aspect);
115
116 // Calculate dimensions if we scale to fill height
117 ssize_t width_if_fill_height = (ssize_t)((float)target_h * img_aspect);
118 ssize_t height_if_fill_height = target_h;
119
120 // Choose the scaling that maximizes usage of the target box
121 // We want to fill at least one dimension completely
122 if (height_if_fill_width <= target_h) {
123 // Filling width fits within height - use it
124 *out_width = width_if_fill_width;
125 *out_height = height_if_fill_width;
126 } else {
127 // Filling width would exceed height, so fill height instead
128 *out_width = width_if_fill_height;
129 *out_height = height_if_fill_height;
130 }
131
132 // Ensure minimum dimensions
133 if (*out_width <= 0) {
134 *out_width = MIN_DIMENSION;
135 }
136 if (*out_height <= 0) {
137 *out_height = MIN_DIMENSION;
138 }
139}

References MIN_DIMENSION.

◆ calculate_fit_dimensions_pixel()

void calculate_fit_dimensions_pixel ( int img_width,
int img_height,
int max_width,
int max_height,
int * out_width,
int * out_height )

#include <include/ascii-chat/util/aspect_ratio.h>

Calculate fit dimensions for pixel-based images.

Parameters
img_widthInput image width in pixels (must be > 0)
img_heightInput image height in pixels (must be > 0)
max_widthMaximum allowed width in pixels (must be > 0)
max_heightMaximum allowed height in pixels (must be > 0)
out_widthOutput parameter for calculated width (must not be NULL)
out_heightOutput parameter for calculated height (must not be NULL)

Calculates dimensions that fit the input image within maximum bounds while maintaining the original aspect ratio. Useful for scaling images to fit within display constraints.

Note
Output dimensions never exceed max_width or max_height.
Aspect ratio is always maintained (image is not stretched).
Output dimensions are calculated to fit within maximum bounds.
Example
int out_w, out_h;
calculate_fit_dimensions_pixel(1920, 1080, 1280, 720, &out_w, &out_h);
// Calculates dimensions that fit within 1280x720 while maintaining 16:9 aspect
// Result: out_w=1280, out_h=720 (fits exactly)
void calculate_fit_dimensions_pixel(int img_width, int img_height, int max_width, int max_height, int *out_width, int *out_height)
Calculate fit dimensions for pixel-based images.

Definition at line 143 of file aspect_ratio.c.

143 {
144 if (!out_width || !out_height || img_width <= 0 || img_height <= 0) {
145 if (out_width)
146 *out_width = max_width;
147 if (out_height)
148 *out_height = max_height;
149 return;
150 }
151
152 float src_aspect = (float)img_width / (float)img_height;
153
154 // Try filling width
155 int width_if_fill_w = max_width;
156 int height_if_fill_w = (int)(((float)max_width / src_aspect) + 0.5f);
157
158 // Try filling height
159 int width_if_fill_h = (int)(((float)max_height * src_aspect) + 0.5f);
160 int height_if_fill_h = max_height;
161
162 // log_debug("calculate_fit_dimensions: img %dx%d (aspect %.3f), max %dx%d", img_width, img_height, src_aspect,
163 // max_width, max_height);
164 // log_debug(" Fill width: %dx%d, Fill height: %dx%d", width_if_fill_w, height_if_fill_w, width_if_fill_h,
165 // height_if_fill_h);
166
167 // Choose the option that fits
168 if (height_if_fill_w <= max_height) {
169 // Filling width fits
170 // log_debug(" Choosing fill width: %dx%d", width_if_fill_w, height_if_fill_w);
171 *out_width = width_if_fill_w;
172 *out_height = height_if_fill_w;
173 } else {
174 // Fill height instead
175 // log_debug(" Choosing fill height: %dx%d", width_if_fill_h, height_if_fill_h);
176 *out_width = width_if_fill_h;
177 *out_height = height_if_fill_h;
178 }
179
180 // Clamp to bounds
181 if (*out_width > max_width)
182 *out_width = max_width;
183 if (*out_height > max_height)
184 *out_height = max_height;
185 if (*out_width < 1)
186 *out_width = 1;
187 if (*out_height < 1)
188 *out_height = 1;
189
190 // log_debug(" Final output: %dx%d", *out_width, *out_height);
191}

◆ canonicalize_ipv6()

asciichat_error_t canonicalize_ipv6 ( const char * ipv6,
char * canonical_out,
size_t out_size )

#include <include/ascii-chat/util/ip.h>

Canonicalize IPv6 address to standard form.

Parameters
ipv6IPv6 address (must not be NULL)
canonical_outOutput buffer for canonical form (must not be NULL)
out_sizeSize of output buffer
Returns
ASCIICHAT_OK on success, error code on failure

Converts an IPv6 address to canonical form following RFC 5952:

  • Lowercase hexadecimal digits
  • Leading zeros removed from each group
  • Longest run of consecutive zero groups compressed to ::
  • Brackets removed

EXAMPLES:

  • "2001:0DB8:0000:0000:0000:0000:0000:0001" -> "2001:db8::1"
  • "[::1]" -> "::1"
  • "2001:DB8::1" -> "2001:db8::1"
Note
Output buffer should be at least 64 bytes.
Returns error if input is not a valid IPv6 address.
Example
char canonical[64];
if (canonicalize_ipv6("[2001:0DB8::1]", canonical, sizeof(canonical)) == ASCIICHAT_OK) {
// canonical = "2001:db8::1"
}
asciichat_error_t canonicalize_ipv6(const char *ipv6, char *canonical_out, size_t out_size)
Canonicalize IPv6 address to standard form.
Definition ip.c:880

Definition at line 880 of file ip.c.

880 {
881 if (!ipv6 || !canonical_out || out_size == 0) {
882 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
883 }
884
885 // Normalize (remove brackets)
886 char normalized[INET6_ADDRSTRLEN];
887 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
888 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to parse IPv6 address");
889 }
890
891 // Validate
892 if (!is_valid_ipv6(normalized)) {
893 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv6 address: %s", ipv6);
894 }
895
896 struct in6_addr addr;
897 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
898 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to convert IPv6 address");
899 }
900
901 // Use inet_ntop which produces canonical form
902 if (inet_ntop(AF_INET6, &addr, canonical_out, (socklen_t)out_size) == NULL) {
903 return SET_ERRNO(ERROR_NETWORK, "Failed to format IPv6 address");
904 }
905
906 return ASCIICHAT_OK;
907}
#define SET_ERRNO(code,...)
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_INVALID_PARAM
int parse_ipv6_address(const char *input, char *output, size_t output_size)
Parse IPv6 address, removing brackets if present.
Definition ip.c:116

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, is_valid_ipv6(), parse_ipv6_address(), and SET_ERRNO.

Referenced by compact_ipv6(), and compare_ip_port_strings().

◆ colored_string()

const char * colored_string ( log_color_t color,
const char * text )

#include <include/ascii-chat/util/string.h>

Build a colored string for terminal output.

Wraps text with ANSI color codes based on terminal capabilities. Uses a rotating buffer to handle multiple colored strings in the same scope. Checks if stdout is a TTY and CLAUDECODE environment variable.

BEHAVIOR:

  • If stdout is a TTY and CLAUDECODE is not set: Returns colored text with ANSI codes
  • If stdout is not a TTY or CLAUDECODE is set: Returns plain text without colors
  • Detects terminal color capabilities (respects NO_COLOR and terminal restrictions)

USAGE:

// Single colored string
fprintf(stderr, "%s\n", colored_string(LOG_COLOR_FATAL, "Error"));
// Multiple colored strings in same scope (uses rotating buffers)
fprintf(stderr, "%s %s\n",
colored_string(LOG_COLOR_WARN, "warning message"));
@ LOG_COLOR_FATAL
Definition log/log.h:152
@ LOG_COLOR_WARN
Definition log/log.h:150
const char * colored_string(log_color_t color, const char *text)
Build a colored string for terminal output.
Parameters
colorThe log color to apply (LOG_COLOR_DEBUG, LOG_COLOR_FATAL, LOG_COLOR_WARN, etc.)
textThe text to color
Returns
Colored string with ANSI codes, or plain text if colors disabled
Note
The returned pointer points to a thread-local rotating buffer. Use or copy the result before calling colored_string() again in tight loops.
Color codes are applied based on log_level_color() from logging subsystem.

Definition at line 284 of file lib/util/string.c.

284 {
285#define COLORED_BUFFERS 4
286#define COLORED_BUFFER_SIZE 256
287 static _Thread_local char buffers[COLORED_BUFFERS][COLORED_BUFFER_SIZE];
288 static _Thread_local int buffer_idx = 0;
289
290 if (!text) {
291 return "";
292 }
293
294 // Check if we should use colors
295 // Use global flag that persists even after options cleanup
296 bool use_colors = false;
297
298 // Priority 1: If --color was explicitly passed, force colors
300 use_colors = true;
301 }
302 // Priority 2: If --color NOT explicitly passed, use terminal detection
303 else if (!g_color_flag_passed) {
304 use_colors = terminal_should_color_output(g_colored_string_fd, options_terminal_settings());
305 }
306 // Priority 3: If --color=false was explicitly passed, disable colors
307 // (use_colors stays false)
308
309 if (GET_OPTION(strip_ansi) || GET_OPTION(color_mode) == TERM_COLOR_NONE)
310 use_colors = false;
311 if (!use_colors) {
312 // No colors, just return the text directly
313 return text;
314 }
315
316 // Use rotating buffer to handle multiple calls in same fprintf
317 char *current_buf = buffers[buffer_idx];
318 buffer_idx = (buffer_idx + 1) % COLORED_BUFFERS;
319
320 const char *color_code = log_level_color_for_output(color, true);
321 const char *reset_code = log_level_color_for_output(LOG_COLOR_RESET, true);
322
323 // Ensure we never pass NULL to snprintf (handle uninitialized color system)
324 if (!color_code)
325 color_code = "";
326 if (!reset_code)
327 reset_code = "";
328
329 // Format into rotating static buffer: color_code + text + reset_code
330 safe_snprintf(current_buf, COLORED_BUFFER_SIZE, "%s%s%s", color_code, text, reset_code);
331 return current_buf;
332}
int color_mode
Definition fft.c:26
bool g_color_flag_value
Value of –color flag (true if –color was in argv) Set by options_init() before RCU is initialized,...
Definition common.c:66
bool g_color_flag_passed
Was –color explicitly passed in command-line arguments? Set by options_init() before RCU is initializ...
Definition common.c:65
const char * log_level_color_for_output(log_color_t color, bool enabled)
@ LOG_COLOR_RESET
Definition log/log.h:154
#define GET_OPTION(field)
Definition options.h:1333
#define options_terminal_settings()
Definition options.h:1287
#define COLORED_BUFFERS
#define COLORED_BUFFER_SIZE
bool terminal_should_color_output(int fd, const terminal_options_t *options)

References color_mode, COLORED_BUFFER_SIZE, COLORED_BUFFERS, g_color_flag_passed, g_color_flag_value, GET_OPTION, LOG_COLOR_RESET, log_level_color_for_output(), options_terminal_settings, and terminal_should_color_output().

Referenced by action_show_capabilities_immediate(), action_show_version(), colorize_named_string(), mutex_stack_detect_deadlocks(), print_project_links(), ui_buttons_render(), ui_error_popup_preserve(), ui_error_popup_render(), ui_help_keys(), ui_popup_frame(), ui_popup_frame_titled(), ui_popup_render(), ui_popup_rule(), ui_progress_format(), ui_scrollbar_cell(), ui_session_context_help_render(), ui_session_help_render(), ui_session_logs_render(), ui_session_splash_render(), ui_spinner_glyph(), ui_spinner_render(), ui_status_log_controls(), ui_status_render_header(), ui_text_color_prefix(), ui_text_values_style(), and update_banner_print_instructions().

◆ colored_string_set_output_fd()

int colored_string_set_output_fd ( int fd)

#include <include/ascii-chat/util/string.h>

Scope automatic color detection to the actual output terminal on this thread. Returns the previous descriptor for restoration by the caller.

Definition at line 274 of file lib/util/string.c.

274 {
275 int previous = g_colored_string_fd;
276 if (fd < 0) {
277 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid colored string output descriptor");
278 return previous;
279 }
280 g_colored_string_fd = fd;
281 return previous;
282}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by frame_buffer_set_screen_output_fd(), and ui_sync_render().

◆ compact_ipv6()

asciichat_error_t compact_ipv6 ( const char * ipv6,
char * compact_out,
size_t out_size )

#include <include/ascii-chat/util/ip.h>

Compress IPv6 address using :: notation.

Parameters
ipv6IPv6 address (must not be NULL)
compact_outOutput buffer for compressed form (must not be NULL)
out_sizeSize of output buffer
Returns
ASCIICHAT_OK on success, error code on failure

Compresses an IPv6 address by replacing the longest run of consecutive zero groups with ::. Follows RFC 5952 compression rules.

EXAMPLES:

  • "2001:0db8:0000:0000:0000:0000:0000:0001" -> "2001:db8::1"
  • "fe80:0000:0000:0000:0000:0000:0000:0001" -> "fe80::1"
  • "2001:db8:0:0:1:0:0:1" -> "2001:db8::1:0:0:1"
Note
Output buffer should be at least 64 bytes.
Returns error if input is not a valid IPv6 address.
Alias for canonicalize_ipv6() - both produce the same output.
Example
char compact[64];
if (compact_ipv6("2001:0db8:0000:0000:0000:0000:0000:0001", compact, sizeof(compact)) == ASCIICHAT_OK) {
// compact = "2001:db8::1"
}
asciichat_error_t compact_ipv6(const char *ipv6, char *compact_out, size_t out_size)
Compress IPv6 address using :: notation.
Definition ip.c:910

Definition at line 910 of file ip.c.

910 {
911 return canonicalize_ipv6(ipv6, compact_out, out_size);
912}

References canonicalize_ipv6().

◆ compare_ip_port_strings()

int compare_ip_port_strings ( const char * ip_port1,
const char * ip_port2 )

#include <include/ascii-chat/util/ip.h>

Compare two "IP:port" strings with IPv6 normalization.

Compares two formatted address strings (e.g., "192.168.1.1:8080" or "[::1]:8080") with proper handling of different IPv6 representations.

Handles IPv6 normalization so different representations are treated as equal:

  • "[::1]:8080" equals "[0:0:0:0:0:0:0:1]:8080"
  • "[2001:db8::1]:80" equals "[2001:0db8:0000:0000:0000:0000:0000:0001]:80"

For IPv4 addresses, uses robust comparison via ip_equals() that handles different binary representations correctly.

Parameters
ip_port1First "IP:port" string (IPv4: "192.168.1.1:8080", IPv6: "[::1]:8080")
ip_port2Second "IP:port" string to compare
Returns
1 if addresses match (after normalization), 0 otherwise
Example
// IPv6 normalization
int match1 = compare_ip_port_strings("[::1]:8080", "[0:0:0:0:0:0:0:1]:8080");
// Returns 1 (equal after normalization)
// IPv4 comparison
int match2 = compare_ip_port_strings("192.168.1.1:80", "192.168.1.1:80");
// Returns 1 (equal)
// Different ports
int match3 = compare_ip_port_strings("192.168.1.1:80", "192.168.1.1:8080");
// Returns 0 (different ports)
int compare_ip_port_strings(const char *ip_port1, const char *ip_port2)
Compare two "IP:port" strings with IPv6 normalization.
Definition ip.c:1043

Definition at line 1043 of file ip.c.

1043 {
1044 if (!ip_port1 || !ip_port2) {
1045 return 0; // Not equal
1046 }
1047
1048 // Fast path: if strings are identical, no parsing needed
1049 if (strcmp(ip_port1, ip_port2) == 0) {
1050 return 1; // Equal
1051 }
1052
1053 // Parse both IP:port strings
1055 uint16_t port1 = 0, port2 = 0;
1056
1057 if (parse_ip_with_port(ip_port1, ip1, sizeof(ip1), &port1) != 0) {
1058 return 0; // Invalid format - not equal
1059 }
1060 if (parse_ip_with_port(ip_port2, ip2, sizeof(ip2), &port2) != 0) {
1061 return 0; // Invalid format - not equal
1062 }
1063
1064 // Ports must match exactly
1065 if (port1 != port2) {
1066 return 0; // Not equal
1067 }
1068
1069 // For IPv6, normalize both addresses before comparison
1070 int version1 = get_ip_version(ip1);
1071 int version2 = get_ip_version(ip2);
1072
1073 // IP versions must match
1074 if (version1 != version2 || version1 == 0) {
1075 return 0; // Not equal
1076 }
1077
1078 if (version1 == 6) {
1079 // Normalize both IPv6 addresses
1080 char canonical1[INET6_ADDRSTRLEN], canonical2[INET6_ADDRSTRLEN];
1081 if (canonicalize_ipv6(ip1, canonical1, sizeof(canonical1)) != ASCIICHAT_OK) {
1082 return 0; // Failed to normalize - not equal
1083 }
1084 if (canonicalize_ipv6(ip2, canonical2, sizeof(canonical2)) != ASCIICHAT_OK) {
1085 return 0; // Failed to normalize - not equal
1086 }
1087 return (strcmp(canonical1, canonical2) == 0) ? 1 : 0;
1088 } else {
1089 // IPv4: use ip_equals for robust comparison
1090 return ip_equals(ip1, ip2) ? 1 : 0;
1091 }
1092}
unsigned short uint16_t
#define IP_ADDRESS_BUFFER_SIZE
int parse_ip_with_port(const char *input, char *ip_output, size_t ip_output_size, uint16_t *port_output)
Parse IP address and port from string.
Definition ip.c:209
int ip_equals(const char *ip1, const char *ip2)
Compare two IP addresses for equality.
Definition ip.c:471
int get_ip_version(const char *ip)
Get IP address version.
Definition ip.c:424
#define UTIL_IP_IP2_BUFFER_SIZE
Definition ip.c:10

References ASCIICHAT_OK, canonicalize_ipv6(), get_ip_version(), IP_ADDRESS_BUFFER_SIZE, ip_equals(), parse_ip_with_port(), and UTIL_IP_IP2_BUFFER_SIZE.

Referenced by check_known_host_no_identity(), and check_known_host_with_key().

◆ crc32_hw_is_available()

bool crc32_hw_is_available ( void )

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

Check if hardware CRC32 acceleration is available at runtime.

Returns
true if hardware acceleration is available, false otherwise

Performs runtime CPU feature detection to determine if hardware CRC32 acceleration can be used on the current platform.

Note
Detection is performed once per thread and cached. Subsequent calls return the cached result.
Hardware acceleration is available on:
  • x86/x64: Processors with SSE4.2 feature (CRC32 instruction)
  • ARM: Processors with ARMv8 architecture (CRC32 instructions)
Use this function to determine if hardware acceleration will be used before calling asciichat_crc32_hw().

Definition at line 85 of file crc32.c.

85 {
86 return crc32_backend() != asciichat_crc32_sw_update;
87}

References asciichat_crc32_sw_update().

◆ display_center_horizontal()

int display_center_horizontal ( const char * text,
int terminal_width )

#include <include/ascii-chat/util/display.h>

Calculate left padding needed to center text horizontally.

Calculates how many spaces are needed before text to center it within a given terminal width. Properly handles ANSI escape codes and UTF-8.

Parameters
textText to center (may contain ANSI codes, must not be NULL)
terminal_widthTotal width available for centering (e.g., 80)
Returns
Number of spaces to print before text, or 0 if text is wider than terminal
Example
// Center "Hello" in 80-char line
int padding = display_center_horizontal("\033[1;36mHello\033[0m", 80);
// Returns 38 ((80-5)/2 = 37.5, rounds to 38)
int display_center_horizontal(const char *text, int terminal_width)
Calculate left padding needed to center text horizontally.

Definition at line 32 of file lib/util/display.c.

32 {
33 if (!text || terminal_width <= 0) {
34 return 0;
35 }
36
37 int text_width = display_width(text);
38
39 // If text is empty or wider than terminal, don't add padding
40 if (text_width == 0 || text_width >= terminal_width) {
41 return 0;
42 }
43
44 // Calculate left padding to center
45 return (terminal_width - text_width) / 2;
46}

References display_width().

Referenced by ui_status_render_header().

◆ display_center_vertical()

int display_center_vertical ( int content_height,
int terminal_height )

#include <include/ascii-chat/util/display.h>

Calculate top padding needed to vertically center content.

Calculates how many newlines are needed before content to center it vertically within a terminal of given height.

Parameters
content_heightHeight of content in lines
terminal_heightTotal height available (typical: 24-30 lines)
Returns
Number of newlines to print before content
Example
// Center 8-line status screen in 24-line terminal
int padding = display_center_vertical(8, 24);
// Returns 8 ((24-8)/2 = 8 lines)
int display_center_vertical(int content_height, int terminal_height)
Calculate top padding needed to vertically center content.

Definition at line 48 of file lib/util/display.c.

48 {
49 if (content_height <= 0 || terminal_height <= 0) {
50 return 0;
51 }
52
53 if (content_height >= terminal_height) {
54 return 0;
55 }
56
57 return (terminal_height - content_height) / 2;
58}

◆ display_height()

int display_height ( const char * text,
int terminal_width )

#include <include/ascii-chat/util/display.h>

Calculate how many display lines text will consume when wrapped.

Splits text by newlines and calculates how many terminal rows it will occupy when wrapped to the given terminal width. Properly handles ANSI escape codes (ignored in width calculation) and UTF-8 multi-byte characters.

Parameters
textInput text which may contain ANSI codes and newlines (NULL-safe)
terminal_widthWidth available for wrapping (e.g., 80)
Returns
Number of display lines consumed, or 0 if text is empty
Example
// "Hello\nWorld" in 80-char terminal = 2 lines
int height = display_height("Hello\nWorld", 80); // Returns 2
// "This is a very long line..." wrapped to 40 chars
int height = display_height("This is a very long line that exceeds...", 40);
// Returns 2-3 depending on exact length
// With ANSI codes: "\033[1;36m" is not counted in width
int height = display_height("\033[1;36m50-char line\033[0m", 40);
// Returns 2 (50 visible chars / 40 width)

Definition at line 60 of file lib/util/display.c.

60 {
61 if (!text || terminal_width <= 0) {
62 return 0;
63 }
64
65 int total_lines = 0;
66 const char *p = text;
67
68 // Count lines by processing the text and counting newlines + final segment
69 while (*p) {
70 // Find the end of this line (next newline or end of string)
71 const char *line_end = p;
72 while (*line_end && *line_end != '\n') {
73 line_end++;
74 }
75
76 // Calculate display width of this line
77 size_t line_len = line_end - p;
78 if (line_len > 0) {
79 // Strip ANSI codes and calculate display width
80 char *stripped = ansi_strip_escapes(p, line_len);
81 if (stripped) {
82 int line_width = utf8_display_width(stripped);
83 SAFE_FREE(stripped);
84
85 if (line_width > 0) {
86 // Calculate how many display lines this wraps to
87 int display_lines = (line_width + terminal_width - 1) / terminal_width; // Ceiling division
88 total_lines += display_lines;
89 } else {
90 total_lines += 1;
91 }
92 } else {
93 // If stripping fails, count as 1 line
94 total_lines += 1;
95 }
96 } else {
97 // Empty line still counts as 1 line
98 total_lines += 1;
99 }
100
101 // Move to next line
102 if (*line_end == '\n') {
103 p = line_end + 1;
104 } else {
105 break;
106 }
107 }
108
109 return total_lines;
110}
char * ansi_strip_escapes(const char *input, size_t input_len)
When code needs to work with rgb error, it keeps r, g, b here instead of scattering it across globals...
Definition ansi.c:27
#define SAFE_FREE(ptr)
int utf8_display_width(const char *str)
Calculate terminal display width of a UTF-8 string.
Definition utf8.c:98

References ansi_strip_escapes(), SAFE_FREE, and utf8_display_width().

Referenced by terminal_screen_compose().

◆ display_width()

int display_width ( const char * text)

#include <include/ascii-chat/util/display.h>

Calculate the visible display width of text with ANSI escape codes.

Strips ANSI escape sequences and calculates the actual terminal display width. Properly handles UTF-8 multi-byte characters and wide characters.

Parameters
textInput text which may contain ANSI escape codes (must not be NULL)
Returns
Display width in terminal columns, or -1 on error
Example
int width = display_width("\033[1;36mHello\033[0m"); // Returns 5

Definition at line 13 of file lib/util/display.c.

13 {
14 if (!text) {
15 return 0;
16 }
17
18 // Strip ANSI escape codes
19 char *stripped = ansi_strip_escapes(text, strlen(text));
20
21 // Use stripped version if available, otherwise use original text
22 const char *to_measure = stripped ? stripped : text;
23
24 // Calculate display width using UTF-8 aware calculation
25 int width = utf8_display_width(to_measure);
26 SAFE_FREE(stripped);
27
28 // Return 0 for empty or invalid input, otherwise return calculated width
29 return width < 0 ? 0 : width;
30}

References ansi_strip_escapes(), SAFE_FREE, utf8_display_width(), and width.

Referenced by display_center_horizontal(), frame_buffer_render_centered(), layout_print_two_column_row(), terminal_fd_reader_next(), ui_buttons_render(), ui_help_menu_measure(), ui_popup_frame_titled(), ui_popup_render(), ui_session_splash_render(), and ui_table_row().

◆ escape_ascii()

void escape_ascii ( const char * str,
const char * escape_char,
char * out_buffer,
size_t out_buffer_size )

#include <include/ascii-chat/util/string.h>

Escape ASCII characters in a string.

Parameters
strInput string to escape (must not be NULL)
escape_charCharacter to escape (must not be NULL)
out_bufferOutput buffer for escaped string (must not be NULL)
out_buffer_sizeSize of output buffer (must be > 0)

Escapes a specific ASCII character in a string by adding an escape prefix. Useful for terminal output or string formatting where certain characters need to be escaped.

Note
Output buffer must be large enough to hold the escaped string.
Function truncates output if buffer is too small.
Does not validate input parameters for NULL (caller's responsibility).

Referenced by display_mitm_warning().

◆ escape_path_for_shell()

bool escape_path_for_shell ( const char * path,
char * out_buffer,
size_t out_buffer_size )

#include <include/ascii-chat/util/string.h>

Check if a string needs shell quoting (contains spaces or special chars).

Parameters
strString to check (must not be NULL)
Returns
true if string contains characters that require shell quoting, false otherwise

Detects if a string contains whitespace or special characters that require shell quoting when used in command-line arguments. Useful for determining whether to apply shell escaping functions.

CHARACTERS REQUIRING QUOTING:

  • Whitespace: space, tab
  • Special shell characters: " ' $ ` \ < > & ; | ( ) [ ] { } * ? ! ~ # @ - Control characters: newline, carriage return, etc. @note Empty strings return false (no quoting needed). @note Alphanumeric and some safe punctuation (- . _) return false. @par Example @code if (string_needs_shell_quoting("/path/to file.txt")) { // Path contains a space, needs quoting } @endcode */ bool string_needs_shell_quoting(const char *str); /** Escape a path for safe use in shell commands (auto-platform) @param path Path string to escape (must not be NULL) @param out_buffer Output buffer for escaped path (must not be NULL) @param out_buffer_size Size of output buffer (must be > 0) @return true on success, false on failure Automatically escapes a path for safe use in shell commands. If the path contains special characters or whitespace, it applies the appropriate platform-specific escaping (single quotes on Unix, double quotes on Windows). If no escaping is needed, the path is copied as-is. PLATFORM BEHAVIOR: - Unix/Linux/macOS: Uses single quote escaping (escape_shell_single_quotes) - Windows: Uses double quote escaping (escape_shell_double_quotes) @note Output buffer must be large enough (worst case: 4x input size for Unix). @note Returns false if buffer is too small or escaping fails. @note Automatically detects if quoting is needed (no unnecessary escaping). @par Example @code char escaped[1024]; if (escape_path_for_shell("/usr/local/bin/tool", escaped, sizeof(escaped))) { // escaped contains the path, properly escaped if needed }

Referenced by gpg_sign_with_key().

◆ escape_shell_double_quotes()

bool escape_shell_double_quotes ( const char * str,
char * out_buffer,
size_t out_buffer_size )

#include <include/ascii-chat/util/string.h>

Escape a string for safe use in shell commands (double quotes, Windows-compatible).

Parameters
strString to escape (must not be NULL)
out_bufferOutput buffer for escaped string (must not be NULL)
out_buffer_sizeSize of output buffer (must be > 0)
Returns
true on success, false on failure (buffer too small)

Escapes a string for safe use in shell commands using double quotes, with Windows cmd.exe compatibility. Escapes double quotes and backslashes as required by Windows command-line parsing rules.

ESCAPING STRATEGY:

  • Input: "C:\Program Files"
  • Output: "C:\\Program Files"
  • Double quotes and backslashes are escaped: " -> \", \ -> \
Note
Output buffer must be large enough (worst case: 2x input size + quotes).
Returns false if buffer is too small to hold escaped string.
This escaping method is compatible with Windows cmd.exe and PowerShell.
Warning
Buffer overflow protection is enforced - function fails safely.

◆ escape_shell_single_quotes()

bool escape_shell_single_quotes ( const char * str,
char * out_buffer,
size_t out_buffer_size )

#include <include/ascii-chat/util/string.h>

Validate that a string contains only safe characters for shell commands.

Parameters
strString to validate (must not be NULL)
allowed_charsAdditional allowed characters (e.g., "-:_", can be NULL)
Returns
true if string is safe, false otherwise

Validates that a string contains only safe characters for use in shell commands. Rejects shell metacharacters that could be used for command injection or shell expansion.

REJECTED METACHARACTERS:

  • Control operators: ; & | $ `
  • Quote characters: " ' - Redirection: < > - Brackets: ( ) [ ] { } - Wildcards: * ? - Special: \ ! ~ # @ @note The allowed_chars parameter adds exceptions to the safety check. @note Empty strings are considered safe (returns true). @note This function is essential for preventing command injection attacks. @par Example @code if (!validate_shell_safe(user_input, NULL)) { // Reject unsafe input } @endcode */ bool validate_shell_safe(const char *str, const char *allowed_chars); /** Escape a string for safe use in shell commands (single quotes) @param str String to escape (must not be NULL) @param out_buffer Output buffer for escaped string (must not be NULL) @param out_buffer_size Size of output buffer (must be > 0) @return true on success, false on failure (buffer too small) Escapes a string for safe use in Unix shell commands using single quotes. Single quotes in the input are escaped by replacing ' with '\'' (single quote, escaped quote, single quote). This ensures the string is safe for shell evaluation when wrapped in single quotes. ESCAPING STRATEGY: - Input: "don't" - Output: "don'\''t"
  • Shell command: echo 'don'\''t' -> prints: don't
Note
Output buffer must be large enough (worst case: 4x input size).
Returns false if buffer is too small to hold escaped string.
This escaping method is compatible with sh, bash, zsh, and other Unix shells.
Warning
Buffer overflow protection is enforced - function fails safely.

Referenced by gpg_get_public_key().

◆ expand_ipv6()

asciichat_error_t expand_ipv6 ( const char * ipv6,
char * expanded_out,
size_t out_size )

#include <include/ascii-chat/util/ip.h>

Expand IPv6 address to full form.

Parameters
ipv6IPv6 address (must not be NULL)
expanded_outOutput buffer for expanded form (must not be NULL)
out_sizeSize of output buffer
Returns
ASCIICHAT_OK on success, error code on failure

Expands an IPv6 address to its full uncompressed form with all 8 groups of 4 hexadecimal digits each, separated by colons.

EXAMPLES:

  • "::1" -> "0000:0000:0000:0000:0000:0000:0000:0001"
  • "2001:db8::1" -> "2001:0db8:0000:0000:0000:0000:0000:0001"
  • "fe80::1" -> "fe80:0000:0000:0000:0000:0000:0000:0001"
Note
Output buffer should be at least 64 bytes.
Returns error if input is not a valid IPv6 address.
Example
char expanded[64];
if (expand_ipv6("::1", expanded, sizeof(expanded)) == ASCIICHAT_OK) {
// expanded = "0000:0000:0000:0000:0000:0000:0000:0001"
}
asciichat_error_t expand_ipv6(const char *ipv6, char *expanded_out, size_t out_size)
Expand IPv6 address to full form.
Definition ip.c:846

Definition at line 846 of file ip.c.

846 {
847 if (!ipv6 || !expanded_out || out_size == 0) {
848 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
849 }
850
851 // Normalize (remove brackets)
852 char normalized[INET6_ADDRSTRLEN];
853 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
854 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to parse IPv6 address");
855 }
856
857 // Validate
858 if (!is_valid_ipv6(normalized)) {
859 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv6 address: %s", ipv6);
860 }
861
862 struct in6_addr addr;
863 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
864 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to convert IPv6 address");
865 }
866
867 // Format as full expanded form: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
868 size_t written = SAFE_SNPRINTF(expanded_out, out_size, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x", (addr.s6_addr[0] << 8) | addr.s6_addr[1], (addr.s6_addr[2] << 8) | addr.s6_addr[3],
869 (addr.s6_addr[4] << 8) | addr.s6_addr[5], (addr.s6_addr[6] << 8) | addr.s6_addr[7], (addr.s6_addr[8] << 8) | addr.s6_addr[9],
870 (addr.s6_addr[10] << 8) | addr.s6_addr[11], (addr.s6_addr[12] << 8) | addr.s6_addr[13], (addr.s6_addr[14] << 8) | addr.s6_addr[15]);
871
872 if (written >= out_size) {
873 return SET_ERRNO(ERROR_INVALID_PARAM, "Output buffer too small");
874 }
875
876 return ASCIICHAT_OK;
877}
#define SAFE_SNPRINTF(buffer, buffer_size,...)

References ASCIICHAT_OK, ERROR_INVALID_PARAM, is_valid_ipv6(), parse_ipv6_address(), SAFE_SNPRINTF, and SET_ERRNO.

◆ expand_path()

char * expand_path ( const char * path)

#include <include/ascii-chat/util/path.h>

Expand path with tilde (~) support.

Parameters
pathPath to expand (may contain ~, must not be NULL)
Returns
Expanded path (must be freed by caller), or NULL on failure

Expands a file path, replacing ~ with the user's home directory. On Unix, uses $HOME environment variable. On Windows, uses USERPROFILE% environment variable.

Note
Returned path is allocated with malloc() and must be freed by caller.
Returns NULL on failure (invalid path, memory allocation error, etc.).
Does not expand environment variables other than ~.
Example
char *expanded = expand_path("~/.config/ascii-chat");
// Returns: "/home/user/.config/ascii-chat" (on Unix)
free(expanded);
char * expand_path(const char *path)
Expand path with tilde (~) support.
Definition path.c:257

Definition at line 257 of file path.c.

257 {
258 if (path[0] == PATH_TILDE) {
259 const char *home = platform_get_home_dir();
260 if (!home) {
261 return NULL;
262 }
263
264 char *expanded;
265 size_t total_len = strlen(home) + strlen(path) + 1; // path includes the tilde
266 expanded = SAFE_MALLOC(total_len, char *);
267 if (!expanded) {
268 return NULL;
269 }
270 safe_snprintf(expanded, total_len, "%s%s", home, path + 1);
271
273
274 return expanded;
275 }
276 return platform_strdup(path);
277}
#define SAFE_MALLOC(size, cast)
#define PATH_TILDE
Path component: home directory tilde.
Definition path.h:77
char * platform_strdup(const char *s)
void platform_normalize_path_separators(char *path)
Definition util.c:110
const char * platform_get_home_dir(void)
Definition util.c:106

References PATH_TILDE, platform_get_home_dir(), platform_normalize_path_separators(), platform_strdup(), and SAFE_MALLOC.

Referenced by config_create_default(), config_load_and_apply(), detect_default_ssh_key(), and path_validate_user_path().

◆ extract_ip_from_address()

int extract_ip_from_address ( const char * addr_with_port,
char * ip_out,
size_t ip_out_size )

#include <include/ascii-chat/util/ip.h>

Extract IP address (without port) from formatted address string.

Extracts the IP address portion from a formatted address that includes a port. Handles both IPv4 (e.g., "192.168.1.1:27224") and IPv6 with brackets (e.g., "[2001:db8::1]:27224").

Parameters
addr_with_portFormatted address string with port
ip_outOutput buffer for IP address (without port)
ip_out_sizeSize of output buffer
Returns
0 on success, -1 on error
Example
char ip[64];
extract_ip_from_address("192.168.1.1:27224", ip, sizeof(ip));
// ip now contains "192.168.1.1"
extract_ip_from_address("[::1]:27224", ip, sizeof(ip));
// ip now contains "::1"
int extract_ip_from_address(const char *addr_with_port, char *ip_out, size_t ip_out_size)
Extract IP address (without port) from formatted address string.
Definition ip.c:963

Definition at line 963 of file ip.c.

963 {
964 if (!addr_with_port || !ip_out || ip_out_size == 0) {
965 return -1;
966 }
967
968 // Check for IPv6 bracket notation: [2001:db8::1]:27224
969 if (addr_with_port[0] == '[') {
970 const char *bracket_end = strchr(addr_with_port, ']');
971 if (!bracket_end) {
972 return -1;
973 }
974 size_t ip_len = (size_t)(bracket_end - addr_with_port - 1);
975 if (ip_len >= ip_out_size) {
976 return -1;
977 }
978 memcpy(ip_out, addr_with_port + 1, ip_len);
979 ip_out[ip_len] = '\0';
980 return 0;
981 }
982
983 // IPv4: Find last colon and extract IP part
984 const char *colon = strrchr(addr_with_port, ':');
985 if (!colon) {
986 // No port, just copy the whole thing
987 SAFE_STRNCPY(ip_out, addr_with_port, ip_out_size);
988 return 0;
989 }
990
991 size_t ip_len = (size_t)(colon - addr_with_port);
992 if (ip_len >= ip_out_size) {
993 return -1;
994 }
995 memcpy(ip_out, addr_with_port, ip_len);
996 ip_out[ip_len] = '\0';
997 return 0;
998}
#define SAFE_STRNCPY(dst, src, size)

References SAFE_STRNCPY.

Referenced by ui_status_render_header().

◆ extract_ipv4_from_mapped_ipv6()

asciichat_error_t extract_ipv4_from_mapped_ipv6 ( const char * ipv6,
char * ipv4_out,
size_t out_size )

#include <include/ascii-chat/util/ip.h>

Extract IPv4 address from IPv6-mapped format.

Parameters
ipv6IPv6-mapped address (must not be NULL)
ipv4_outOutput buffer for IPv4 address (must not be NULL)
out_sizeSize of output buffer
Returns
ASCIICHAT_OK on success, error code on failure

Extracts the IPv4 address from an IPv6-mapped address (::ffff:x.x.x.x).

INPUT FORMATS:

  • "::ffff:192.168.1.1" -> "192.168.1.1"
  • "::ffff:c0a8:0101" (hex notation) -> "192.168.1.1"
Note
Returns error if input is not a valid IPv6-mapped IPv4 address.
Output buffer should be at least 16 bytes.
Example
char ipv4[16];
if (extract_ipv4_from_mapped_ipv6("::ffff:192.168.1.1", ipv4, sizeof(ipv4)) == ASCIICHAT_OK) {
// ipv4 = "192.168.1.1"
}
asciichat_error_t extract_ipv4_from_mapped_ipv6(const char *ipv6, char *ipv4_out, size_t out_size)
Extract IPv4 address from IPv6-mapped format.
Definition ip.c:810

Definition at line 810 of file ip.c.

810 {
811 if (!ipv6 || !ipv4_out || out_size == 0) {
812 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
813 }
814
815 if (!is_ipv4_mapped_ipv6(ipv6)) {
816 return SET_ERRNO(ERROR_INVALID_PARAM, "Not an IPv4-mapped IPv6 address: %s", ipv6);
817 }
818
819 // Normalize
820 char normalized[INET6_ADDRSTRLEN];
821 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
822 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to parse IPv6 address");
823 }
824
825 struct in6_addr addr;
826 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
827 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to convert IPv6 address");
828 }
829
830 // Extract last 4 bytes and format as IPv4
831 struct in_addr ipv4_addr;
832 memcpy(&ipv4_addr.s_addr, &addr.s6_addr[12], 4);
833
834 if (inet_ntop(AF_INET, &ipv4_addr, ipv4_out, (socklen_t)out_size) == NULL) {
835 return SET_ERRNO(ERROR_NETWORK, "Failed to format IPv4 address");
836 }
837
838 return ASCIICHAT_OK;
839}
int is_ipv4_mapped_ipv6(const char *ipv6)
Check if IPv6 address is IPv4-mapped.
Definition ip.c:774

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, is_ipv4_mapped_ipv6(), parse_ipv6_address(), and SET_ERRNO.

◆ extract_project_relative_path()

const char * extract_project_relative_path ( const char * file,
const char *const * owned_dirs )

#include <include/ascii-chat/util/path.h>

Extract a path relative to the source root embedded by CMake.

Parameters
fileSource path (typically FILE), or NULL
Returns
Path relative to the build-time project directory, the unchanged input for paths outside that directory, or "unknown" for NULL.

Supports all directories beneath the source root, including src/ and lib/. Handles Unix (/) and Windows () separators and ignores case on Windows. Already-relative paths are returned unchanged. No runtime root discovery is used.

Note
Does not allocate, log, or access the filesystem; safe in memory reports.
Returns a pointer into the input, which must remain valid.

Definition at line 132 of file path.c.

132 {
133 // This runs inside logging and while the memory tracker holds its mutex.
134 // Avoid allocations, filesystem access, mutable caches, and error logging.
135 if (!file) {
136 return "unknown";
137 }
138 if (!owned_dirs) {
139 return file;
140 }
141
142 const char *root = NULL;
143 size_t root_length = 0;
144 if (owned_dirs) {
145 for (size_t dir_index = 0; owned_dirs[dir_index]; dir_index++) {
146 const char *candidate = owned_dirs[dir_index];
147 size_t candidate_length = strlen(candidate);
148 bool matches = true;
149 for (size_t i = 0; i < candidate_length; i++) {
150 unsigned char source_char = (unsigned char)candidate[i];
151 unsigned char file_char = (unsigned char)file[i];
152 if (source_char == '/' || source_char == '\\') {
153 if (file_char != '/' && file_char != '\\') {
154 matches = false;
155 break;
156 }
157 } else {
158#ifdef _WIN32
159 if (tolower(source_char) != tolower(file_char)) {
160 matches = false;
161 break;
162 }
163#else
164 if (source_char != file_char) {
165 matches = false;
166 break;
167 }
168#endif
169 }
170 }
171 if (matches && (file[candidate_length] == '/' || file[candidate_length] == '\\') && candidate_length > root_length) {
172 root = candidate;
173 root_length = candidate_length;
174 }
175 }
176 }
177 if (root) {
178 return file + root_length + 1;
179 }
180
181 root = ASCIICHAT_SOURCE_ROOT;
182 size_t i = 0;
183 bool root_matches = true;
184 for (; root[i]; i++) {
185 unsigned char source_char = (unsigned char)root[i];
186 unsigned char file_char = (unsigned char)file[i];
187 if (source_char == '/' || source_char == '\\') {
188 if (file_char != '/' && file_char != '\\') {
189 root_matches = false;
190 break;
191 }
192 } else {
193#ifdef _WIN32
194 // Windows source paths are case insensitive; POSIX paths are not.
195 if (tolower(source_char) != tolower(file_char)) {
196#else
197 if (source_char != file_char) {
198#endif
199 root_matches = false;
200 break;
201 }
202 }
203 }
204
205 // Match a whole directory, not a sibling whose name starts with the root.
206 if (root_matches && i > 0 && (file[i] == '/' || file[i] == '\\')) {
207 return file + i + 1;
208 }
209
210#ifdef _WIN32
211 // -ffile-prefix-map removes the checkout prefix from release debug records.
212 // CodeView/DbgHelp can anchor those relative records at the current drive
213 // root, producing paths such as C:\lib\debug\backtrace.c. Recognize only
214 // project source-tree roots so genuine external paths remain absolute.
215 if (isalpha((unsigned char)file[0]) && file[1] == ':' && (file[2] == '/' || file[2] == '\\')) {
216 const char *relative = file + 3;
217 static const char *project_roots[] = {"src", "lib", "tests", "include"};
218 for (size_t root_index = 0; root_index < sizeof(project_roots) / sizeof(project_roots[0]); root_index++) {
219 const char *project_root = project_roots[root_index];
220 size_t root_length = strlen(project_root);
221 if (_strnicmp(relative, project_root, root_length) == 0 && (relative[root_length] == '/' || relative[root_length] == '\\')) {
222 return relative;
223 }
224 }
225 }
226#endif
227 return file;
228}

Referenced by browser_error_file(), EMSCRIPTEN_DECLARE_VAL_TYPE(), log_json_async_safe(), log_json_write(), log_template_apply(), and packet_format_error_stack().

◆ format_bytes_pretty()

void format_bytes_pretty ( size_t bytes,
char * out,
size_t out_capacity )

#include <include/ascii-chat/util/format.h>

Format byte count into human-readable string.

Parameters
bytesNumber of bytes to format
outOutput buffer for formatted string (must not be NULL)
out_capacitySize of output buffer (must be > 0)

Formats a byte count into a human-readable string with appropriate units. Automatically selects the appropriate unit (B, KB, MB, GB, TB, PB, EB) based on the value. Units step up at 80% of the next tier to avoid awkward transitions. Uses binary units (1024-based) for calculations.

FORMATTING RULES (threshold at 80% of next unit):

  • 0-819 bytes: "N B" (e.g., "512 B")
  • 819-839,339 bytes: "N.NN KB" (e.g., "0.80 KB")
  • 839,339-858,993,459 bytes: "N.NN MB" (e.g., "0.80 MB")
  • 858,993,459-879,609,302,015 bytes: "N.NN GB" (e.g., "0.80 GB")
  • 879,609,302,015-900,719,925,374,591 bytes: "N.NN TB" (e.g., "0.80 TB")
  • 900,719,925,374,591-921,737,309,184,883,711 bytes: "N.NN PB" (e.g., "0.80 PB")
  • 921,737,309,184,883,711 and above: "N.NN EB" (e.g., "0.80 EB")
Note
Output buffer should be at least 32 bytes to accommodate all formats.
Function truncates output if buffer is too small.
Decimal precision is 2 places for units >= KB.
Uses binary units (1024-based), not decimal (1000-based).
Example
char buf[64];
format_bytes_pretty(512, buf, sizeof(buf)); // "512 B"
format_bytes_pretty(819, buf, sizeof(buf)); // "819 B" (just below KB threshold)
format_bytes_pretty(820, buf, sizeof(buf)); // "0.80 KB" (at 80% of 1 KB)
format_bytes_pretty(1048576, buf, sizeof(buf)); // "1.00 MB" (at 100% of 1 MB)
format_bytes_pretty(838860, buf, sizeof(buf)); // "0.80 MB" (at 80% of 1 MB)
format_bytes_pretty(1125899906842624, buf, sizeof(buf)); // "1.00 PB"
format_bytes_pretty(1152921504606846976ULL, buf, sizeof(buf)); // "1.00 EB"
void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity)
Format byte count into human-readable string.
Definition util/format.c:11

Definition at line 11 of file util/format.c.

11 {
12 const double KB = 1024.0;
13 const double MB = KB * 1024.0;
14 const double GB = MB * 1024.0;
15 const double TB = GB * 1024.0;
16 const double PB = TB * 1024.0;
17 const double EB = PB * 1024.0;
18
19 const double THRESHOLD = 0.8;
20
21 double byte_val = (double)bytes;
22
23 if (byte_val < THRESHOLD * KB) {
24 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%zu B", bytes));
25 } else if (byte_val < THRESHOLD * MB) {
26 double value = byte_val / KB;
27 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f KB", value));
28 } else if (byte_val < THRESHOLD * GB) {
29 double value = byte_val / MB;
30 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f MB", value));
31 } else if (byte_val < THRESHOLD * TB) {
32 double value = byte_val / GB;
33 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f GB", value));
34 } else if (byte_val < THRESHOLD * PB) {
35 double value = byte_val / TB;
36 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f TB", value));
37 } else if (byte_val < THRESHOLD * EB) {
38 double value = byte_val / PB;
39 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f PB", value));
40 } else {
41 double value = byte_val / EB;
42 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f EB", value));
43 }
44}
static bool size_t gotel_query_t * out
Definition queries.h:8

References out.

Referenced by crypto_destroy(), frame_check_size_overflow(), frame_validate_new(), handle_image_frame_packet(), and packet_validate_frame_dimensions().

◆ format_ip_address()

asciichat_error_t format_ip_address ( int family,
const struct sockaddr * addr,
char * output,
size_t output_size )

#include <include/ascii-chat/util/ip.h>

Format IP address from socket address structure.

Parameters
familyAddress family (AF_INET for IPv4 or AF_INET6 for IPv6)
addrSocket address pointer (must not be NULL)
outputOutput buffer for formatted IP address (must not be NULL)
output_sizeSize of output buffer (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Formats an IP address from a socket address structure. Automatically handles both IPv4 and IPv6 addresses by extracting the address from the appropriate socket structure fields.

OUTPUT FORMATS:

  • IPv4: "192.0.2.1"
  • IPv6: "2001:db8::1"
Note
Output buffer should be at least 64 bytes to accommodate any IPv6 address.
For IPv4: addr should point to sockaddr_in, for IPv6: should point to sockaddr_in6.
Returns error code on failure (invalid family, buffer too small, etc.).
Example
char ip_str[64];
struct sockaddr_in addr;
// ... initialize addr ...
if (format_ip_address(AF_INET, &addr, ip_str, sizeof(ip_str)) == ASCIICHAT_OK) {
// ip_str contains the formatted IP address
}

◆ format_ip_with_port()

asciichat_error_t format_ip_with_port ( const char * ip,
uint16_t port,
char * output,
size_t output_size )

#include <include/ascii-chat/util/ip.h>

Format IP address with port number.

Parameters
ipIP address (without brackets, must not be NULL)
portPort number (0-65535)
outputOutput buffer (must not be NULL)
output_sizeSize of output buffer (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Formats an IP address with port number. Automatically adds brackets for IPv6 addresses to separate address from port. IPv4 addresses are formatted without brackets.

OUTPUT FORMATS:

  • IPv4: "192.0.2.1:8080"
  • IPv6: "[2001:db8::1]:8080"
Note
Output buffer must be large enough (at least 64 bytes recommended).
IPv6 addresses automatically get brackets in output.
Returns error code on failure (buffer too small, invalid address, etc.).
Example
char output[64];
if (format_ip_with_port("::1", 8080, output, sizeof(output)) == ASCIICHAT_OK) {
// output = "[::1]:8080"
}
asciichat_error_t format_ip_with_port(const char *ip, uint16_t port, char *output, size_t output_size)
Format IP address with port number.
Definition ip.c:175

Definition at line 175 of file ip.c.

175 {
176 if (!ip || !output || output_size == 0) {
177 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", ip);
178 }
179
180 if (strlen(ip) == 0) {
181 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", ip);
182 }
183
184 if (strlen(ip) > 256) {
185 char ip_buffer[BUFFER_SIZE_SMALL];
186 SAFE_STRNCPY(ip_buffer, ip, sizeof(ip_buffer));
187 return SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", ip_buffer);
188 }
189
190 // Check if it's IPv6 (contains ':')
191 if (strchr(ip, ':') != NULL) {
192 // IPv6 - use bracket notation
193 size_t written = SAFE_SNPRINTF(output, output_size, "[%s]:%u", ip, port);
194 if (written >= output_size) {
195 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ip=%s or port=%u", ip, port);
196 }
197 } else {
198 // IPv4 - no brackets
199 size_t written = SAFE_SNPRINTF(output, output_size, "%s:%u", ip, port);
200 if (written >= output_size) {
201 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ip=%s or port=%u", ip, port);
202 }
203 }
204
205 return ASCIICHAT_OK;
206}
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, ERROR_INVALID_PARAM, SAFE_SNPRINTF, SAFE_STRNCPY, and SET_ERRNO.

Referenced by add_known_host(), check_known_host_no_identity(), check_known_host_with_key(), display_mitm_warning(), prompt_unknown_host(), prompt_unknown_host_no_identity(), and remove_known_host().

◆ get_config_dir()

char * get_config_dir ( void )

#include <include/ascii-chat/util/path.h>

Get configuration directory path with XDG_CONFIG_HOME support.

Returns
Path to configuration directory (must be freed by caller), or NULL on failure

Returns the appropriate configuration directory path according to platform conventions and environment variables. The path includes the directory separator at the end for convenience.

All ascii-chat data files use this single directory:

  • config.toml (configuration)
  • known_hosts (server key verification)

Configuration path resolution:

  • Unix: $XDG_CONFIG_HOME/ascii-chat/ if XDG_CONFIG_HOME is set, otherwise ~/.ascii-chat/
  • Windows: APPDATA%\ascii-chat\ if APPDATA is set, with fallback to USERPROFILE%\AppData\Roaming\ascii-chat\, HOME%.config\ascii-chat\, or C:\ProgramData\ascii-chat\
Note
Returned path is allocated with malloc() and must be freed by caller.
Path includes directory separator at the end (e.g., "/home/user/.config/ascii-chat/").
Returns NULL on failure (memory allocation error, etc.).
Example
char *config_dir = get_config_dir();
// Returns: "/home/user/.config/ascii-chat/" (on Unix with XDG_CONFIG_HOME unset)
// or: "C:\Users\user\AppData\Roaming\ascii-chat\" (on Windows)
free(config_dir);
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:279

Definition at line 279 of file path.c.

279 {
280 /* Delegate to platform abstraction layer */
282}
char * platform_get_config_dir(void)
Definition util.c:116

References platform_get_config_dir().

Referenced by config_load_and_apply(), config_load_system_and_user(), discovery_keys_get_cache_path(), get_known_hosts_path(), and path_validate_user_path().

◆ get_data_dir()

char * get_data_dir ( void )

#include <include/ascii-chat/util/path.h>

Get application data directory path.

Returns
Path to data directory (must be freed by caller), or NULL on failure

Returns XDG_DATA_HOME/ascii-chat/ on Unix (~/.local/share/ascii-chat/ by default) or AppData\ascii-chat\ on Windows.

Use this for application data files like databases, not configuration files.

Example:
char *data_dir = get_data_dir();
// Returns: "/home/user/.local/share/ascii-chat/" (on Unix)
// or: "C:\Users\user\AppData\Roaming\ascii-chat\" (on Windows)
free(data_dir);
char * get_data_dir(void)
Get application data directory path.
Definition path.c:284

Definition at line 284 of file path.c.

284 {
285 /* Delegate to platform abstraction layer */
286 return platform_get_data_dir();
287}
char * platform_get_data_dir(void)
Definition filesystem.c:101

References platform_get_data_dir().

Referenced by get_discovery_database_dir().

◆ get_discovery_database_dir()

char * get_discovery_database_dir ( void )

#include <include/ascii-chat/util/path.h>

Get discovery service database directory with Homebrew-aware system-wide fallback.

Returns
Path to database directory (must be freed by caller), or NULL on failure

Returns the appropriate directory for the discovery service database, with Homebrew-aware system-wide installation support. The path includes a trailing directory separator.

Directory resolution (in order of preference):

  1. System-wide location using baked-in install prefix:
    • Unix: ${ASCIICHAT_INSTALL_PREFIX}/var/ascii-chat/ (e.g., /opt/homebrew/var/ascii-chat/ or /usr/local/var/ascii-chat/)
    • Windows: PROGRAMDATA%\ascii-chat\
  2. macOS only: /usr/local/var/ascii-chat/ (if different from install prefix, typically user-writable)
  3. User data directory: $XDG_DATA_HOME/ascii-chat/ or ~/.local/share/ascii-chat/

The install prefix is determined at compile time from CMake's CMAKE_INSTALL_PREFIX, which Homebrew sets appropriately:

  • macOS Apple Silicon: /opt/homebrew
  • macOS Intel: /usr/local
  • Linux: /usr/local (default)

The function tries each location and automatically creates directories with appropriate permissions (0755 for system directories, 0700 for user directories). If a location is not writable, it falls back to the next option.

Note
Returned path is allocated with malloc() and must be freed by caller.
Path includes directory separator at the end (e.g., "/opt/homebrew/var/ascii-chat/").
Returns NULL if both system and user data directories are inaccessible.
Creates directories recursively if they don't exist and parent is writable.
Example
char *db_dir = get_discovery_database_dir();
// macOS (Apple Silicon): "/opt/homebrew/var/ascii-chat/", then "/usr/local/var/ascii-chat/"
// macOS (Intel): "/usr/local/var/ascii-chat/"
// Linux: "/usr/local/var/ascii-chat/"
// User fallback: "~/.local/share/ascii-chat/"
free(db_dir);
char * get_discovery_database_dir(void)
Get discovery service database directory with Homebrew-aware system-wide fallback.
Definition path.c:372

Definition at line 372 of file path.c.

372 {
373 platform_directory_list_t data_dirs = {0};
375 for (size_t i = 0; i < data_dirs.count; i++) {
376 platform_directory_candidate_t *candidate = &data_dirs.candidates[i];
377 if (platform_mkdir_recursive(candidate->path, candidate->mode) == ASCIICHAT_OK && platform_access(candidate->path, PLATFORM_ACCESS_WRITE) == 0) {
378 char *selected_dir = candidate->path;
379 candidate->path = NULL;
381 return selected_dir;
382 }
383 }
384 }
386
387 // Fall back to the platform's per-user application data directory.
388 char *data_dir = get_data_dir();
389 if (data_dir) {
390 asciichat_error_t mkdir_result = platform_mkdir_recursive(data_dir, DIR_PERM_PRIVATE);
391 if (mkdir_result == ASCIICHAT_OK) {
392 if (platform_access(data_dir, PLATFORM_ACCESS_WRITE) == 0) {
393 return data_dir;
394 }
395 }
396 SAFE_FREE(data_dir);
397 }
398
399 return NULL;
400}
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
int platform_get_data_dir_candidates(const char *install_prefix, platform_directory_list_t *list_out)
Definition filesystem.c:105
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
#define ASCIICHAT_INSTALL_PREFIX
Installation prefix.
Definition paths.h:30
void platform_directory_list_destroy(platform_directory_list_t *list)
Definition util.c:22

References ASCIICHAT_INSTALL_PREFIX, ASCIICHAT_OK, get_data_dir(), platform_access(), platform_directory_list_destroy(), platform_get_data_dir_candidates(), platform_mkdir_recursive(), and SAFE_FREE.

◆ get_ip_type_string()

const char * get_ip_type_string ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Get human-readable string describing IP address type.

Classifies an IP address and returns a descriptive string. Possible return values:

  • "All Interfaces" - Wildcard bind address (0.0.0.0 or ::)
  • "Localhost" - Loopback address (127.0.0.0/8 or ::1)
  • "LAN" - Private network address (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, or fc00::/7)
  • "Internet" - Public internet address
  • "Unknown" - Invalid or unrecognized address
  • "" - Empty/null input
Parameters
ipIP address to classify (without port)
Returns
Constant string describing the IP type
Example
const char *type1 = get_ip_type_string("0.0.0.0"); // Returns "All Interfaces"
const char *type2 = get_ip_type_string("127.0.0.1"); // Returns "Localhost"
const char *type3 = get_ip_type_string("192.168.1.1"); // Returns "LAN"
const char *type4 = get_ip_type_string("8.8.8.8"); // Returns "Internet"
const char *type5 = get_ip_type_string("::1"); // Returns "Localhost"
const char * get_ip_type_string(const char *ip)
Get human-readable string describing IP address type.
Definition ip.c:1001

Definition at line 1001 of file ip.c.

1001 {
1002 if (!ip || ip[0] == '\0') {
1003 return "";
1004 }
1005
1006 // Check for wildcard "bind to all interfaces" addresses
1007 // IPv4: 0.0.0.0
1008 if (strcmp(ip, "0.0.0.0") == 0) {
1009 return "All Interfaces";
1010 }
1011
1012 // IPv6: :: (unspecified address)
1013 if (strcmp(ip, "::") == 0) {
1014 return "All Interfaces";
1015 }
1016
1017 // Check IPv4
1018 if (is_localhost_ipv4(ip)) {
1019 return "Localhost";
1020 }
1021 if (is_lan_ipv4(ip)) {
1022 return "LAN";
1023 }
1024 if (is_internet_ipv4(ip)) {
1025 return "Internet";
1026 }
1027
1028 // Check IPv6
1029 if (is_localhost_ipv6(ip)) {
1030 return "Localhost";
1031 }
1032 if (is_lan_ipv6(ip)) {
1033 return "LAN";
1034 }
1035 if (is_internet_ipv6(ip)) {
1036 return "Internet";
1037 }
1038
1039 return "Unknown";
1040}
int is_lan_ipv6(const char *ip)
Check if IPv6 address is a private/LAN address.
Definition ip.c:1126
int is_localhost_ipv6(const char *ip)
Check if IPv6 address is localhost.
Definition ip.c:1230
int is_internet_ipv4(const char *ip)
Check if IPv4 address is a public internet address.
Definition ip.c:1318
int is_lan_ipv4(const char *ip)
Check if IPv4 address is a private/LAN address.
Definition ip.c:1095
int is_localhost_ipv4(const char *ip)
Check if IPv4 address is localhost.
Definition ip.c:1209
int is_internet_ipv6(const char *ip)
Check if IPv6 address is a public internet address.
Definition ip.c:1400

References is_internet_ipv4(), is_internet_ipv6(), is_lan_ipv4(), is_lan_ipv6(), is_localhost_ipv4(), and is_localhost_ipv6().

Referenced by ui_status_render_header().

◆ get_ip_version()

int get_ip_version ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Get IP address version.

Parameters
ipIP address string (must not be NULL)
Returns
4 for IPv4, 6 for IPv6, 0 for invalid

Detects the version of an IP address without validating its full correctness. Useful for protocol selection and dual-stack handling.

Note
Returns 0 for NULL, empty strings, or invalid addresses.
Does not validate address correctness beyond basic format.
Example
int version = get_ip_version("192.168.1.1"); // Returns 4
int version = get_ip_version("::1"); // Returns 6
int version = get_ip_version("invalid"); // Returns 0

Definition at line 424 of file ip.c.

424 {
425 if (!ip || strlen(ip) == 0) {
426 return 0;
427 }
428
429 // Quick heuristic: if it contains a colon, it's likely IPv6
430 // (unless it's a port separator, but we're just checking the IP part)
431 if (strchr(ip, ':') != NULL) {
432 // Could be IPv6 or bracketed IPv6
433 if (is_valid_ipv6(ip)) {
434 return 6;
435 }
436 return 0; // Has colon but not valid IPv6
437 }
438
439 // No colon, check if it's IPv4
440 if (is_valid_ipv4(ip)) {
441 return 4;
442 }
443
444 return 0; // Not valid IPv4 or IPv6
445}

References is_valid_ipv4(), and is_valid_ipv6().

Referenced by compare_ip_port_strings(), ip_compare(), ip_equals(), ip_in_cidr_parsed(), and parse_cidr().

◆ get_log_dir()

char * get_log_dir ( void )

#include <include/ascii-chat/util/path.h>

Get log directory path appropriate for current build type.

Returns
Path to log directory (must be freed by caller), or NULL on failure

Returns the appropriate log directory path based on build type. The directory is created if it doesn't exist (for release builds). The path does NOT include a trailing directory separator.

Log directory resolution:

  • Debug builds: Current working directory (for fast iteration)
  • Release builds: $TMPDIR/ascii-chat/ (Unix: /tmp/ascii-chat/, Windows: TEMP%\ascii-chat)

For release builds, this function automatically creates the ascii-chat subdirectory if it doesn't exist and verifies it's writable.

Note
Returned path is allocated with malloc() and must be freed by caller.
Path does NOT include directory separator at the end.
Returns NULL on failure (memory allocation error, directory creation failed, etc.).
For release builds, the directory is created with 0700 permissions (owner-only).
Example (Debug Build)
char *log_dir = get_log_dir();
// Returns: "/home/user/myproject" (current working directory)
free(log_dir);
char * get_log_dir(void)
Get log directory path appropriate for current build type.
Definition path.c:289
Example (Release Build)
char *log_dir = get_log_dir();
// Returns: "/tmp/ascii-chat" (on Unix)
// or: "C:\Users\user\AppData\Local\Temp\ascii-chat" (on Windows)
free(log_dir);

Definition at line 289 of file path.c.

289 {
290#ifdef __EMSCRIPTEN__
291 // WASM builds: Return NULL to skip SAFE_MALLOC before memory tracking is initialized
292 // The caller will use a fallback path (temp dir + filename)
293 return NULL;
294#endif
295
296#ifdef NDEBUG
297 // Release builds: Use $TMPDIR/ascii-chat/
298 // Get system temp directory
299 char temp_dir[PLATFORM_MAX_PATH_LENGTH];
300 if (!platform_get_temp_dir(temp_dir, sizeof(temp_dir))) {
301 // Fallback: Use current working directory if temp dir unavailable
302 char cwd_buf[PLATFORM_MAX_PATH_LENGTH];
303 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
304 return NULL;
305 }
306 char *result = SAFE_MALLOC(strlen(cwd_buf) + 1, char *);
307 if (!result) {
308 return NULL;
309 }
310 safe_snprintf(result, strlen(cwd_buf) + 1, "%s", cwd_buf);
311 return result;
312 }
313
314 // Build path to ascii-chat subdirectory
315 size_t log_dir_len = strlen(temp_dir) + strlen(PATH_SEPARATOR_STR) + strlen("ascii-chat") + 1;
316 char *log_dir = SAFE_MALLOC(log_dir_len, char *);
317 if (!log_dir) {
318 return NULL;
319 }
320 safe_snprintf(log_dir, log_dir_len, "%s%sascii-chat", temp_dir, PATH_SEPARATOR_STR);
321
322 // Create the directory if it doesn't exist (with owner-only permissions)
323 asciichat_error_t mkdir_result = platform_mkdir(log_dir, DIR_PERM_PRIVATE);
324 if (mkdir_result != ASCIICHAT_OK) {
325 // Directory creation failed - fall back to temp_dir without subdirectory
326 SAFE_FREE(log_dir);
327 char *result = SAFE_MALLOC(strlen(temp_dir) + 1, char *);
328 if (!result) {
329 return NULL;
330 }
331 safe_snprintf(result, strlen(temp_dir) + 1, "%s", temp_dir);
332 return result;
333 }
334
335 // Verify the directory is writable
336 if (platform_access(log_dir, PLATFORM_ACCESS_WRITE) != 0) {
337 // Directory not writable - fall back to temp_dir
338 SAFE_FREE(log_dir);
339 char *result = SAFE_MALLOC(strlen(temp_dir) + 1, char *);
340 if (!result) {
341 return NULL;
342 }
343 safe_snprintf(result, strlen(temp_dir) + 1, "%s", temp_dir);
344 return result;
345 }
346
347 return log_dir;
348#else
349 // Debug builds: Use the build checkout for logs when it is still writable.
350 const char *repo_root = ASCIICHAT_SOURCE_ROOT;
351 if (platform_access(repo_root, PLATFORM_ACCESS_WRITE) == 0) {
352 size_t len = strlen(repo_root) + 1;
353 char *result = SAFE_MALLOC(len, char *);
354 if (result) {
355 memcpy(result, repo_root, len);
356 }
357 return result;
358 }
359
360 // The binary may have been copied to a machine without the build checkout.
361 char cwd_buf[PLATFORM_MAX_PATH_LENGTH];
362 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
363 return NULL;
364 }
365
366 char *result = SAFE_MALLOC(strlen(cwd_buf) + 1, char *);
367 safe_snprintf(result, strlen(cwd_buf) + 1, "%s", cwd_buf);
368 return result;
369#endif
370}
#define PLATFORM_MAX_PATH_LENGTH
bool platform_get_cwd(char *cwd, size_t path_size)
Definition util.c:122
bool platform_get_temp_dir(char *temp_dir, size_t path_size)
Definition util.c:81

References ASCIICHAT_OK, platform_access(), platform_get_cwd(), platform_get_temp_dir(), PLATFORM_MAX_PATH_LENGTH, SAFE_FREE, and SAFE_MALLOC.

◆ hostname_to_ascii()

asciichat_error_t hostname_to_ascii ( const char * hostname,
char * output,
size_t capacity )

#include <include/ascii-chat/util/url.h>

Convert a UTF-8 DNS hostname to its canonical ASCII form using ICU UTS #46. Underscore hostnames remain accepted for local-service compatibility. Nontransitional processing preserves distinct names such as faß.de and fass.de. Valid IP literals are copied unchanged. Capacity includes NUL; output is unchanged on error. DNS label/name limits apply after conversion. URL paths are not processed.

Definition at line 103 of file url.c.

103 {
104 if (!hostname || !*hostname || !output || capacity == 0)
105 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing hostname or output buffer");
106 size_t length = strlen(hostname);
107 if (length > INT32_MAX)
108 return SET_ERRNO(ERROR_INVALID_PARAM, "Hostname input exceeds ICU length range");
109
110 // IP literals are addresses, not IDNA labels; preserve IPv6 zones and brackets.
111 if (length < HOSTNAME_BUFFER_SIZE && (is_valid_ipv4(hostname) || is_valid_ipv6(hostname))) {
112 if (length >= capacity)
113 return SET_ERRNO(ERROR_INVALID_PARAM, "Address exceeds output capacity");
114 memmove(output, hostname, length + 1);
115 return ASCIICHAT_OK;
116 }
117
118 UErrorCode status = U_ZERO_ERROR;
119#ifdef __EMSCRIPTEN__
120 while (!lifecycle_is_initialized(&g_icu_idna_data_lc)) {
121 if (lifecycle_init_once(&g_icu_idna_data_lc)) {
122 udata_setCommonData(asciichat_icu_idna_data, &status);
123 if (U_FAILURE(status)) {
124 lifecycle_init_abort(&g_icu_idna_data_lc);
125 return SET_ERRNO(ERROR_INIT, "Could not load ICU IDNA data: %s", u_errorName(status));
126 }
127 lifecycle_init_commit(&g_icu_idna_data_lc);
128 }
129 }
130#endif
131 UIDNA *idna = uidna_openUTS46(UIDNA_NONTRANSITIONAL_TO_ASCII | UIDNA_CHECK_BIDI | UIDNA_CHECK_CONTEXTJ | UIDNA_CHECK_CONTEXTO, &status);
132 if (U_FAILURE(status) || !idna)
133 return SET_ERRNO(ERROR_INIT, "Could not initialize ICU IDNA: %s", u_errorName(status));
134 char ascii[HOSTNAME_BUFFER_SIZE];
135 UIDNAInfo info = UIDNA_INFO_INITIALIZER;
136 int32_t written = uidna_nameToASCII_UTF8(idna, hostname, (int32_t)length, ascii, sizeof(ascii), &info, &status);
137 uidna_close(idna);
138 // A trailing root dot is allowed, but does not count towards the DNS name limit.
139 size_t max_length = MAX_HOSTNAME_LENGTH;
140 if (written > 0 && written < (int32_t)sizeof(ascii) && ascii[written - 1] == '.')
141 ++max_length;
142 if (U_FAILURE(status) || info.errors || written <= 0 || (size_t)written > max_length || (size_t)written >= sizeof(ascii) || (size_t)written >= capacity)
143 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IDNA hostname or insufficient capacity (ICU %s, errors 0x%x)", u_errorName(status), (unsigned)info.errors);
144 // Retain underscore hostnames used by local services, but reject other
145 // non-DNS ASCII punctuation permitted by ICU when STD3 rules are disabled.
146 for (int32_t i = 0; i < written; ++i) {
147 char c = ascii[i];
148 if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_'))
149 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ASCII character in IDNA hostname");
150 }
151 memcpy(output, ascii, (size_t)written);
152 output[written] = '\0';
153 return ASCIICHAT_OK;
154}
@ ERROR_INIT
Definition error_codes.h:60
#define HOSTNAME_BUFFER_SIZE
#define MAX_HOSTNAME_LENGTH

References ASCIICHAT_OK, ERROR_INIT, ERROR_INVALID_PARAM, HOSTNAME_BUFFER_SIZE, is_valid_ipv4(), is_valid_ipv6(), MAX_HOSTNAME_LENGTH, and SET_ERRNO.

Referenced by dns_test_connectivity(), https_get(), parallel_connect(), parse_address_with_optional_port(), and url_parse().

◆ ip_compare()

int ip_compare ( const char * ip1,
const char * ip2 )

#include <include/ascii-chat/util/ip.h>

Compare two IP addresses for sorting.

Parameters
ip1First IP address (must not be NULL)
ip2Second IP address (must not be NULL)
Returns
-1 if ip1 < ip2, 0 if equal, 1 if ip1 > ip2, -2 on error

Compares two IP addresses for sorting. IPv4 addresses sort before IPv6. Within the same version, compares numerically (not lexicographically).

SORT ORDER:

  • Invalid addresses sort last
  • IPv4 addresses sort before IPv6
  • Within IPv4: numeric comparison (10.0.0.1 < 192.168.1.1)
  • Within IPv6: numeric comparison (::1 < 2001::1)
Note
Returns -2 if either address is invalid.
Useful for qsort() callbacks.
Example
int result = ip_compare("10.0.0.1", "192.168.1.1"); // Returns -1
int result = ip_compare("::1", "192.168.1.1"); // Returns 1 (IPv6 > IPv4)
int ip_compare(const char *ip1, const char *ip2)
Compare two IP addresses for sorting.
Definition ip.c:515

Definition at line 515 of file ip.c.

515 {
516 if (!ip1 || !ip2) {
517 return -2; // Error
518 }
519
520 int v1 = get_ip_version(ip1);
521 int v2 = get_ip_version(ip2);
522
523 // Invalid addresses sort last
524 if (v1 == 0 && v2 == 0) {
525 return 0; // Both invalid, consider equal
526 }
527 if (v1 == 0) {
528 return 1; // ip1 invalid, sorts after ip2
529 }
530 if (v2 == 0) {
531 return -1; // ip2 invalid, sorts after ip1
532 }
533
534 // IPv4 sorts before IPv6
535 if (v1 != v2) {
536 return (v1 < v2) ? -1 : 1;
537 }
538
539 if (v1 == 4) {
540 // IPv4: compare numerically
541 struct in_addr addr1, addr2;
542 if (inet_pton(AF_INET, ip1, &addr1) != 1 || inet_pton(AF_INET, ip2, &addr2) != 1) {
543 return -2; // Error
544 }
545
546 uint32_t val1 = ntohl(addr1.s_addr);
547 uint32_t val2 = ntohl(addr2.s_addr);
548
549 if (val1 < val2)
550 return -1;
551 if (val1 > val2)
552 return 1;
553 return 0;
554 } else {
555 // IPv6: compare byte by byte
556 char norm1[INET6_ADDRSTRLEN], norm2[INET6_ADDRSTRLEN];
557
558 if (parse_ipv6_address(ip1, norm1, sizeof(norm1)) != 0) {
559 return -2;
560 }
561 if (parse_ipv6_address(ip2, norm2, sizeof(norm2)) != 0) {
562 return -2;
563 }
564
565 struct in6_addr addr1, addr2;
566 if (inet_pton(AF_INET6, norm1, &addr1) != 1 || inet_pton(AF_INET6, norm2, &addr2) != 1) {
567 return -2;
568 }
569
570 return memcmp(&addr1, &addr2, sizeof(addr1));
571 }
572}

References get_ip_version(), and parse_ipv6_address().

◆ ip_equals()

int ip_equals ( const char * ip1,
const char * ip2 )

#include <include/ascii-chat/util/ip.h>

Compare two IP addresses for equality.

Parameters
ip1First IP address (must not be NULL)
ip2Second IP address (must not be NULL)
Returns
1 if equal, 0 if not equal or invalid

Compares two IP addresses for equality, handling normalization automatically. Works with IPv4 and IPv6, including bracketed IPv6 notation.

NORMALIZATION RULES:

  • IPv6 addresses are normalized before comparison
  • Brackets are ignored: "[::1]" equals "::1"
  • IPv6 zero compression is normalized: "::1" equals "0:0:0:0:0:0:0:1"
  • IPv4 and IPv6 are never equal
Note
Returns 0 if either address is invalid.
Case-insensitive for IPv6 (A-F vs a-f).
Example
if (ip_equals("::1", "[::1]")) {
// True - brackets ignored
}
if (ip_equals("192.168.1.1", "192.168.1.2")) {
// False - different addresses
}

Definition at line 471 of file ip.c.

471 {
472 if (!ip1 || !ip2) {
473 return 0;
474 }
475
476 // Get versions
477 int v1 = get_ip_version(ip1);
478 int v2 = get_ip_version(ip2);
479
480 // If different versions or either invalid, not equal
481 if (v1 != v2 || v1 == 0) {
482 return 0;
483 }
484
485 if (v1 == 4) {
486 // IPv4: direct string comparison after validation
487 struct in_addr addr1, addr2;
488 if (inet_pton(AF_INET, ip1, &addr1) != 1 || inet_pton(AF_INET, ip2, &addr2) != 1) {
489 return 0;
490 }
491 return addr1.s_addr == addr2.s_addr;
492 } else {
493 // IPv6: normalize then compare
494 char norm1[INET6_ADDRSTRLEN], norm2[INET6_ADDRSTRLEN];
495
496 // Remove brackets if present
497 if (parse_ipv6_address(ip1, norm1, sizeof(norm1)) != 0) {
498 return 0;
499 }
500 if (parse_ipv6_address(ip2, norm2, sizeof(norm2)) != 0) {
501 return 0;
502 }
503
504 // Parse to binary and compare
505 struct in6_addr addr1, addr2;
506 if (inet_pton(AF_INET6, norm1, &addr1) != 1 || inet_pton(AF_INET6, norm2, &addr2) != 1) {
507 return 0;
508 }
509
510 return memcmp(&addr1, &addr2, sizeof(addr1)) == 0;
511 }
512}

References get_ip_version(), and parse_ipv6_address().

Referenced by compare_ip_port_strings().

◆ ip_in_cidr()

int ip_in_cidr ( const char * ip,
const char * cidr )

#include <include/ascii-chat/util/ip.h>

Check if IP address is within CIDR range.

Parameters
ipIP address to check (must not be NULL)
cidrCIDR range (e.g., "192.168.1.0/24", must not be NULL)
Returns
1 if IP is in range, 0 if not or on error

Checks if an IP address falls within a CIDR range. Automatically handles both IPv4 and IPv6. IP and CIDR must be the same version.

EXAMPLES:

  • "192.168.1.10" in "192.168.1.0/24" -> true
  • "192.168.2.10" in "192.168.1.0/24" -> false
  • "2001:db8::1" in "2001:db8::/32" -> true
Note
Returns 0 if IP and CIDR are different versions (IPv4 vs IPv6).
Returns 0 on error (invalid IP, invalid CIDR).
Example
if (ip_in_cidr("192.168.1.10", "192.168.1.0/24")) {
// IP is in the 192.168.1.0/24 subnet
}
int ip_in_cidr(const char *ip, const char *cidr)
Check if IP address is within CIDR range.
Definition ip.c:734

Definition at line 734 of file ip.c.

734 {
735 if (!ip || !cidr) {
736 return 0;
737 }
738
739 char network[UTIL_IP_NETWORK_BUFFER_SIZE];
740 int prefix;
741
742 if (parse_cidr(cidr, network, sizeof(network), &prefix) != 0) {
743 return 0; // Invalid CIDR
744 }
745
746 return ip_in_cidr_parsed(ip, network, prefix);
747}
int parse_cidr(const char *cidr, char *ip_out, size_t ip_out_size, int *prefix_out)
Parse CIDR notation into IP and prefix length.
Definition ip.c:579
int ip_in_cidr_parsed(const char *ip, const char *network, int prefix_len)
Check if IP is within CIDR range (parsed form).
Definition ip.c:680
#define UTIL_IP_NETWORK_BUFFER_SIZE
Definition ip.c:9

References ip_in_cidr_parsed(), parse_cidr(), and UTIL_IP_NETWORK_BUFFER_SIZE.

◆ ip_in_cidr_parsed()

int ip_in_cidr_parsed ( const char * ip,
const char * network,
int prefix_len )

#include <include/ascii-chat/util/ip.h>

Check if IP is within CIDR range (parsed form).

Parameters
ipIP address to check (must not be NULL)
networkNetwork address (must not be NULL)
prefix_lenPrefix length (0-32 for IPv4, 0-128 for IPv6)
Returns
1 if IP is in range, 0 if not or on error

Checks if an IP address falls within a CIDR range using pre-parsed network address and prefix length. More efficient than ip_in_cidr() when checking multiple IPs against the same range.

Note
IP and network must be the same version.
Returns 0 on error (invalid IP, invalid network, out of range prefix).
Example
if (ip_in_cidr_parsed("192.168.1.10", "192.168.1.0", 24)) {
// IP is in the 192.168.1.0/24 subnet
}

Definition at line 680 of file ip.c.

680 {
681 if (!ip || !network) {
682 return 0;
683 }
684
685 int ip_version = get_ip_version(ip);
686 int net_version = get_ip_version(network);
687
688 // Must be same version
689 if (ip_version != net_version || ip_version == 0) {
690 return 0;
691 }
692
693 if (ip_version == 4) {
694 // IPv4 comparison
695 struct in_addr ip_addr, net_addr;
696 if (inet_pton(AF_INET, ip, &ip_addr) != 1 || inet_pton(AF_INET, network, &net_addr) != 1) {
697 return 0;
698 }
699
700 uint32_t ip_val = ntohl(ip_addr.s_addr);
701 uint32_t net_val = ntohl(net_addr.s_addr);
702
703 uint32_t ip_masked = apply_ipv4_mask(ip_val, prefix_len);
704 uint32_t net_masked = apply_ipv4_mask(net_val, prefix_len);
705
706 return ip_masked == net_masked;
707 } else {
708 // IPv6 comparison
709 char ip_norm[INET6_ADDRSTRLEN], net_norm[INET6_ADDRSTRLEN];
710
711 if (parse_ipv6_address(ip, ip_norm, sizeof(ip_norm)) != 0) {
712 return 0;
713 }
714 if (parse_ipv6_address(network, net_norm, sizeof(net_norm)) != 0) {
715 return 0;
716 }
717
718 struct in6_addr ip_addr, net_addr;
719 if (inet_pton(AF_INET6, ip_norm, &ip_addr) != 1 || inet_pton(AF_INET6, net_norm, &net_addr) != 1) {
720 return 0;
721 }
722
723 // Apply mask to both addresses
724 struct in6_addr ip_masked = ip_addr;
725 struct in6_addr net_masked = net_addr;
726 apply_ipv6_mask(&ip_masked, prefix_len);
727 apply_ipv6_mask(&net_masked, prefix_len);
728
729 return memcmp(&ip_masked, &net_masked, sizeof(ip_masked)) == 0;
730 }
731}

References get_ip_version(), and parse_ipv6_address().

Referenced by ip_in_cidr().

◆ ipv4_to_ipv6_mapped()

asciichat_error_t ipv4_to_ipv6_mapped ( const char * ipv4,
char * ipv6_out,
size_t out_size )

#include <include/ascii-chat/util/ip.h>

Convert IPv4 address to IPv6-mapped format.

Parameters
ipv4IPv4 address (must not be NULL)
ipv6_outOutput buffer for IPv6-mapped address (must not be NULL)
out_sizeSize of output buffer
Returns
ASCIICHAT_OK on success, error code on failure

Converts an IPv4 address to IPv6-mapped format (::ffff:x.x.x.x). This format allows IPv4 addresses to be represented in IPv6.

OUTPUT FORMAT: "::ffff:192.168.1.1"

Note
Output buffer should be at least 64 bytes.
Returns error if input is not a valid IPv4 address.
Example
char ipv6[64];
if (ipv4_to_ipv6_mapped("192.168.1.1", ipv6, sizeof(ipv6)) == ASCIICHAT_OK) {
// ipv6 = "::ffff:192.168.1.1"
}
asciichat_error_t ipv4_to_ipv6_mapped(const char *ipv4, char *ipv6_out, size_t out_size)
Convert IPv4 address to IPv6-mapped format.
Definition ip.c:754

Definition at line 754 of file ip.c.

754 {
755 if (!ipv4 || !ipv6_out || out_size == 0) {
756 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
757 }
758
759 // Validate IPv4
760 if (!is_valid_ipv4(ipv4)) {
761 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv4 address: %s", ipv4);
762 }
763
764 // Format as ::ffff:x.x.x.x
765 size_t written = SAFE_SNPRINTF(ipv6_out, out_size, "::ffff:%s", ipv4);
766 if (written >= out_size) {
767 return SET_ERRNO(ERROR_INVALID_PARAM, "Output buffer too small");
768 }
769
770 return ASCIICHAT_OK;
771}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, is_valid_ipv4(), SAFE_SNPRINTF, and SET_ERRNO.

◆ is_anycast_ipv6()

int is_anycast_ipv6 ( const char * ipv6)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is anycast.

Parameters
ipv6IPv6 address (must not be NULL)
Returns
1 if anycast, 0 otherwise

Checks if an IPv6 address is a known anycast address. Anycast addresses are typically indistinguishable from unicast, but some well-known ranges exist:

  • Subnet-router anycast: last address in each subnet with all host bits zero
  • 6to4 relay anycast: 192.88.99.0/24 (mapped to 2002:c058:6301::)
Note
This function only detects known anycast ranges.
Most anycast addresses cannot be detected without network context.
Returns 0 for invalid IPv6 addresses.
Example
if (is_anycast_ipv6("2002:c058:6301::")) {
// This is a 6to4 relay anycast address
}
int is_anycast_ipv6(const char *ipv6)
Check if IPv6 address is anycast.
Definition ip.c:915

Definition at line 915 of file ip.c.

915 {
916 if (!ipv6) {
917 return 0;
918 }
919
920 // Normalize
921 char normalized[INET6_ADDRSTRLEN];
922 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
923 return 0;
924 }
925
926 // Validate
927 if (!is_valid_ipv6(normalized)) {
928 return 0;
929 }
930
931 struct in6_addr addr;
932 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
933 return 0;
934 }
935
936 // 6to4 relay anycast: 192.88.99.0/24 (mapped to 2002:c058:6301::)
937 // Check if it matches 2002:c058:6301::
938 if (addr.s6_addr[0] == 0x20 && addr.s6_addr[1] == 0x02 && addr.s6_addr[2] == 0xc0 && addr.s6_addr[3] == 0x58 && addr.s6_addr[4] == 0x63 && addr.s6_addr[5] == 0x01) {
939 // Check if remaining bytes are zero (anycast)
940 int is_zero = 1;
941 for (int i = 6; i < 16; i++) {
942 if (addr.s6_addr[i] != 0) {
943 is_zero = 0;
944 break;
945 }
946 }
947 if (is_zero) {
948 return 1;
949 }
950 }
951
952 // Subnet-router anycast: would need subnet context to determine
953 // We can't detect this without knowing the subnet
954
955 return 0;
956}

References is_valid_ipv6(), and parse_ipv6_address().

◆ is_broadcast_ipv4()

int is_broadcast_ipv4 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv4 address is a broadcast address.

Parameters
ipIPv4 address string (must not be NULL)
Returns
1 if broadcast address, 0 otherwise

Checks if an IPv4 address is the limited broadcast address:

  • 255.255.255.255
Note
Subnet-specific broadcast addresses (e.g., 192.168.1.255 for 192.168.1.0/24) cannot be determined without network mask information.
Returns 0 for invalid IPv4 addresses.
Example
if (is_broadcast_ipv4("255.255.255.255")) {
// This is the limited broadcast address
}
int is_broadcast_ipv4(const char *ip)
Check if IPv4 address is a broadcast address.
Definition ip.c:1157

Definition at line 1157 of file ip.c.

1157 {
1158 if (!is_valid_ipv4(ip)) {
1159 return 0;
1160 }
1161
1162 struct in_addr addr;
1163 if (inet_pton(AF_INET, ip, &addr) != 1) {
1164 return 0;
1165 }
1166
1167 uint32_t ip_val = ntohl(addr.s_addr);
1168
1169 // Limited broadcast: 255.255.255.255
1170 if (ip_val == 0xFFFFFFFF) {
1171 return 1;
1172 }
1173
1174 return 0;
1175}

References is_valid_ipv4().

Referenced by is_internet_ipv4().

◆ is_broadcast_ipv6()

int is_broadcast_ipv6 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is a multicast address.

Parameters
ipIPv6 address string (must not be NULL)
Returns
1 if multicast address, 0 otherwise

Checks if an IPv6 address is in the multicast range:

  • ff00::/8 (ff00:: - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff)
Note
IPv6 doesn't have broadcast; multicast is used instead.
Returns 0 for invalid IPv6 addresses.
Example
if (is_broadcast_ipv6("ff02::1")) {
// This is a multicast address (all-nodes link-local)
}
int is_broadcast_ipv6(const char *ip)
Check if IPv6 address is a multicast address.
Definition ip.c:1178

Definition at line 1178 of file ip.c.

1178 {
1179 if (!ip) {
1180 return 0;
1181 }
1182
1183 // Remove brackets if present
1184 char normalized[INET6_ADDRSTRLEN];
1185 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1186 return 0;
1187 }
1188
1189 // Validate the normalized address
1190 if (!is_valid_ipv6(normalized)) {
1191 return 0;
1192 }
1193
1194 struct in6_addr addr;
1195 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1196 return 0;
1197 }
1198
1199 // ff00::/8: Multicast addresses
1200 // First byte should be 0xff
1201 if (addr.s6_addr[0] == 0xFF) {
1202 return 1;
1203 }
1204
1205 return 0;
1206}

References is_valid_ipv6(), and parse_ipv6_address().

Referenced by is_internet_ipv6().

◆ is_internet_ipv4()

int is_internet_ipv4 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv4 address is a public internet address.

Parameters
ipIPv4 address string (must not be NULL)
Returns
1 if public internet address, 0 otherwise

Checks if an IPv4 address is a globally routable public address. Returns 0 for:

  • Private/LAN addresses (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
  • Loopback addresses (127.0.0.0/8)
  • Link-local addresses (169.254.0.0/16)
  • Broadcast addresses (255.255.255.255)
  • Multicast addresses (224.0.0.0/4)
  • Reserved/special use addresses
  • Invalid addresses
Note
Returns 0 for invalid IPv4 addresses.
Example
if (is_internet_ipv4("8.8.8.8")) {
// This is a public internet address
}

Definition at line 1318 of file ip.c.

1318 {
1319 if (!is_valid_ipv4(ip)) {
1320 return 0;
1321 }
1322
1323 struct in_addr addr;
1324 if (inet_pton(AF_INET, ip, &addr) != 1) {
1325 return 0;
1326 }
1327
1328 uint32_t ip_val = ntohl(addr.s_addr);
1329
1330 // Exclude private/LAN addresses
1331 if (is_lan_ipv4(ip)) {
1332 return 0;
1333 }
1334
1335 // Exclude loopback
1336 if (is_localhost_ipv4(ip)) {
1337 return 0;
1338 }
1339
1340 // Exclude link-local
1341 if (is_link_local_ipv4(ip)) {
1342 return 0;
1343 }
1344
1345 // Exclude broadcast
1346 if (is_broadcast_ipv4(ip)) {
1347 return 0;
1348 }
1349
1350 // Exclude multicast: 224.0.0.0/4
1351 if ((ip_val & 0xF0000000) == 0xE0000000) {
1352 return 0;
1353 }
1354
1355 // Exclude 0.0.0.0/8: "This network"
1356 if ((ip_val & 0xFF000000) == 0x00000000) {
1357 return 0;
1358 }
1359
1360 // Exclude 100.64.0.0/10: Shared Address Space (RFC 6598)
1361 if ((ip_val & 0xFFC00000) == 0x64400000) {
1362 return 0;
1363 }
1364
1365 // Exclude 192.0.0.0/24: IETF Protocol Assignments
1366 if ((ip_val & 0xFFFFFF00) == 0xC0000000) {
1367 return 0;
1368 }
1369
1370 // Exclude 192.0.2.0/24: TEST-NET-1
1371 if ((ip_val & 0xFFFFFF00) == 0xC0000200) {
1372 return 0;
1373 }
1374
1375 // Exclude 198.18.0.0/15: Benchmarking
1376 if ((ip_val & 0xFFFE0000) == 0xC6120000) {
1377 return 0;
1378 }
1379
1380 // Exclude 198.51.100.0/24: TEST-NET-2
1381 if ((ip_val & 0xFFFFFF00) == 0xC6336400) {
1382 return 0;
1383 }
1384
1385 // Exclude 203.0.113.0/24: TEST-NET-3
1386 if ((ip_val & 0xFFFFFF00) == 0xCB007100) {
1387 return 0;
1388 }
1389
1390 // Exclude 240.0.0.0/4: Reserved for future use
1391 if ((ip_val & 0xF0000000) == 0xF0000000) {
1392 return 0;
1393 }
1394
1395 // If none of the exclusions matched, it's a public internet address
1396 return 1;
1397}
int is_link_local_ipv4(const char *ip)
Check if IPv4 address is a link-local address.
Definition ip.c:1266

References is_broadcast_ipv4(), is_lan_ipv4(), is_link_local_ipv4(), is_localhost_ipv4(), and is_valid_ipv4().

Referenced by get_ip_type_string().

◆ is_internet_ipv6()

int is_internet_ipv6 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is a public internet address.

Parameters
ipIPv6 address string (must not be NULL)
Returns
1 if public internet address, 0 otherwise

Checks if an IPv6 address is a globally routable public address. Returns 0 for:

  • Loopback address (::1)
  • Link-local addresses (fe80::/10)
  • Unique local addresses (fc00::/7)
  • Multicast addresses (ff00::/8)
  • Special use/reserved addresses
  • Invalid addresses
Note
Returns 0 for invalid IPv6 addresses.
Example
if (is_internet_ipv6("2001:4860:4860::8888")) {
// This is a public internet address
}

Definition at line 1400 of file ip.c.

1400 {
1401 if (!ip) {
1402 return 0;
1403 }
1404
1405 // Remove brackets if present
1406 char normalized[INET6_ADDRSTRLEN];
1407 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1408 return 0;
1409 }
1410
1411 // Validate the normalized address
1412 if (!is_valid_ipv6(normalized)) {
1413 return 0;
1414 }
1415
1416 struct in6_addr addr;
1417 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1418 return 0;
1419 }
1420
1421 // Exclude loopback
1422 if (is_localhost_ipv6(ip)) {
1423 return 0;
1424 }
1425
1426 // Exclude link-local
1427 if (is_link_local_ipv6(ip)) {
1428 return 0;
1429 }
1430
1431 // Exclude ULA
1432 if (is_lan_ipv6(ip)) {
1433 return 0;
1434 }
1435
1436 // Exclude multicast
1437 if (is_broadcast_ipv6(ip)) {
1438 return 0;
1439 }
1440
1441 // Exclude unspecified address: ::
1442 int is_unspecified = 1;
1443 for (int i = 0; i < 16; i++) {
1444 if (addr.s6_addr[i] != 0) {
1445 is_unspecified = 0;
1446 break;
1447 }
1448 }
1449 if (is_unspecified) {
1450 return 0;
1451 }
1452
1453 // Exclude IPv4-mapped IPv6: ::ffff:0:0/96
1454 if (addr.s6_addr[0] == 0 && addr.s6_addr[1] == 0 && addr.s6_addr[2] == 0 && addr.s6_addr[3] == 0 && addr.s6_addr[4] == 0 && addr.s6_addr[5] == 0 && addr.s6_addr[6] == 0 && addr.s6_addr[7] == 0 &&
1455 addr.s6_addr[8] == 0 && addr.s6_addr[9] == 0 && addr.s6_addr[10] == 0xFF && addr.s6_addr[11] == 0xFF) {
1456 return 0;
1457 }
1458
1459 // Exclude IPv4-compatible IPv6: ::/96 (deprecated)
1460 if (addr.s6_addr[0] == 0 && addr.s6_addr[1] == 0 && addr.s6_addr[2] == 0 && addr.s6_addr[3] == 0 && addr.s6_addr[4] == 0 && addr.s6_addr[5] == 0 && addr.s6_addr[6] == 0 && addr.s6_addr[7] == 0 &&
1461 addr.s6_addr[8] == 0 && addr.s6_addr[9] == 0 && addr.s6_addr[10] == 0 && addr.s6_addr[11] == 0) {
1462 // But not ::, which we already excluded above
1463 if (addr.s6_addr[12] != 0 || addr.s6_addr[13] != 0 || addr.s6_addr[14] != 0 || addr.s6_addr[15] != 0) {
1464 return 0;
1465 }
1466 }
1467
1468 // Exclude documentation prefix: 2001:db8::/32
1469 if (addr.s6_addr[0] == 0x20 && addr.s6_addr[1] == 0x01 && addr.s6_addr[2] == 0x0D && addr.s6_addr[3] == 0xB8) {
1470 return 0;
1471 }
1472
1473 // Exclude 6to4: 2002::/16
1474 if (addr.s6_addr[0] == 0x20 && addr.s6_addr[1] == 0x02) {
1475 return 0;
1476 }
1477
1478 // If none of the exclusions matched, it's likely a global unicast address
1479 // Global unicast is typically 2000::/3, but let's accept anything that's not excluded
1480 return 1;
1481}
int is_link_local_ipv6(const char *ip)
Check if IPv6 address is a link-local address.
Definition ip.c:1287

References is_broadcast_ipv6(), is_lan_ipv6(), is_link_local_ipv6(), is_localhost_ipv6(), is_valid_ipv6(), and parse_ipv6_address().

Referenced by get_ip_type_string().

◆ is_ipv4_mapped_ipv6()

int is_ipv4_mapped_ipv6 ( const char * ipv6)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is IPv4-mapped.

Parameters
ipv6IPv6 address (must not be NULL)
Returns
1 if IPv4-mapped, 0 otherwise

Checks if an IPv6 address is in IPv4-mapped format (::ffff:x.x.x.x/96).

Note
Returns 0 for invalid IPv6 addresses.
Example
if (is_ipv4_mapped_ipv6("::ffff:192.168.1.1")) {
// This is an IPv4-mapped IPv6 address
}

Definition at line 774 of file ip.c.

774 {
775 if (!ipv6) {
776 return 0;
777 }
778
779 // Normalize (remove brackets)
780 char normalized[INET6_ADDRSTRLEN];
781 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
782 return 0;
783 }
784
785 // Validate IPv6
786 if (!is_valid_ipv6(normalized)) {
787 return 0;
788 }
789
790 struct in6_addr addr;
791 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
792 return 0;
793 }
794
795 // Check for ::ffff:0:0/96 prefix
796 // First 10 bytes should be 0, next 2 should be 0xff
797 for (int i = 0; i < 10; i++) {
798 if (addr.s6_addr[i] != 0) {
799 return 0;
800 }
801 }
802 if (addr.s6_addr[10] != 0xFF || addr.s6_addr[11] != 0xFF) {
803 return 0;
804 }
805
806 return 1;
807}

References is_valid_ipv6(), and parse_ipv6_address().

Referenced by extract_ipv4_from_mapped_ipv6().

◆ is_lan_ipv4()

int is_lan_ipv4 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv4 address is a private/LAN address.

Parameters
ipIPv4 address string (must not be NULL)
Returns
1 if LAN address, 0 otherwise

Checks if an IPv4 address is in private address ranges:

  • 10.0.0.0/8 (10.0.0.0 - 10.255.255.255)
  • 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
  • 192.168.0.0/16 (192.168.0.0 - 192.168.255.255)
Note
Returns 0 for invalid IPv4 addresses.
Example
if (is_lan_ipv4("192.168.1.1")) {
// This is a private LAN address
}

Definition at line 1095 of file ip.c.

1095 {
1096 if (!is_valid_ipv4(ip)) {
1097 return 0;
1098 }
1099
1100 struct in_addr addr;
1101 if (inet_pton(AF_INET, ip, &addr) != 1) {
1102 return 0;
1103 }
1104
1105 uint32_t ip_val = ntohl(addr.s_addr);
1106
1107 // 10.0.0.0/8: 10.0.0.0 - 10.255.255.255
1108 if ((ip_val & 0xFF000000) == 0x0A000000) {
1109 return 1;
1110 }
1111
1112 // 172.16.0.0/12: 172.16.0.0 - 172.31.255.255
1113 if ((ip_val & 0xFFF00000) == 0xAC100000) {
1114 return 1;
1115 }
1116
1117 // 192.168.0.0/16: 192.168.0.0 - 192.168.255.255
1118 if ((ip_val & 0xFFFF0000) == 0xC0A80000) {
1119 return 1;
1120 }
1121
1122 return 0;
1123}

References is_valid_ipv4().

Referenced by get_ip_type_string(), is_internet_ipv4(), and session_server_like_run().

◆ is_lan_ipv6()

int is_lan_ipv6 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is a private/LAN address.

Parameters
ipIPv6 address string (must not be NULL)
Returns
1 if LAN address, 0 otherwise

Checks if an IPv6 address is a Unique Local Address (ULA):

  • fc00::/7 (fc00:: - fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff)
Note
Returns 0 for invalid IPv6 addresses.
Example
if (is_lan_ipv6("fc00::1")) {
// This is a private ULA address
}

Definition at line 1126 of file ip.c.

1126 {
1127 if (!ip) {
1128 return 0;
1129 }
1130
1131 // Remove brackets if present
1132 char normalized[INET6_ADDRSTRLEN];
1133 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1134 return 0;
1135 }
1136
1137 // Validate the normalized address
1138 if (!is_valid_ipv6(normalized)) {
1139 return 0;
1140 }
1141
1142 struct in6_addr addr;
1143 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1144 return 0;
1145 }
1146
1147 // fc00::/7: Unique Local Addresses (ULA)
1148 // First byte should be 0xfc or 0xfd
1149 if ((addr.s6_addr[0] & 0xFE) == 0xFC) {
1150 return 1;
1151 }
1152
1153 return 0;
1154}

References is_valid_ipv6(), and parse_ipv6_address().

Referenced by get_ip_type_string(), and is_internet_ipv6().

◆ is_link_local_ipv4()

int is_link_local_ipv4 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv4 address is a link-local address.

Parameters
ipIPv4 address string (must not be NULL)
Returns
1 if link-local, 0 otherwise

Checks if an IPv4 address is in the link-local range:

  • 169.254.0.0/16 (169.254.0.0 - 169.254.255.255)

Link-local addresses are auto-configured when DHCP is unavailable (APIPA).

Note
Returns 0 for invalid IPv4 addresses.
Example
if (is_link_local_ipv4("169.254.1.1")) {
// This is an auto-configured link-local address
}

Definition at line 1266 of file ip.c.

1266 {
1267 if (!is_valid_ipv4(ip)) {
1268 return 0;
1269 }
1270
1271 struct in_addr addr;
1272 if (inet_pton(AF_INET, ip, &addr) != 1) {
1273 return 0;
1274 }
1275
1276 uint32_t ip_val = ntohl(addr.s_addr);
1277
1278 // 169.254.0.0/16: Link-local addresses (APIPA)
1279 if ((ip_val & 0xFFFF0000) == 0xA9FE0000) {
1280 return 1;
1281 }
1282
1283 return 0;
1284}

References is_valid_ipv4().

Referenced by is_internet_ipv4().

◆ is_link_local_ipv6()

int is_link_local_ipv6 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is a link-local address.

Parameters
ipIPv6 address string (must not be NULL)
Returns
1 if link-local, 0 otherwise

Checks if an IPv6 address is in the link-local range:

  • fe80::/10 (fe80:: - febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff)

Link-local addresses are auto-configured and only valid on a single link.

Note
Returns 0 for invalid IPv6 addresses.
Example
if (is_link_local_ipv6("fe80::1")) {
// This is a link-local address
}

Definition at line 1287 of file ip.c.

1287 {
1288 if (!ip) {
1289 return 0;
1290 }
1291
1292 // Remove brackets if present
1293 char normalized[INET6_ADDRSTRLEN];
1294 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1295 return 0;
1296 }
1297
1298 // Validate the normalized address
1299 if (!is_valid_ipv6(normalized)) {
1300 return 0;
1301 }
1302
1303 struct in6_addr addr;
1304 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1305 return 0;
1306 }
1307
1308 // fe80::/10: Link-local addresses
1309 // First byte should be 0xfe, second byte & 0xc0 should be 0x80
1310 if (addr.s6_addr[0] == 0xFE && (addr.s6_addr[1] & 0xC0) == 0x80) {
1311 return 1;
1312 }
1313
1314 return 0;
1315}

References is_valid_ipv6(), and parse_ipv6_address().

Referenced by is_internet_ipv6().

◆ is_localhost_ipv4()

int is_localhost_ipv4 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv4 address is localhost.

Parameters
ipIPv4 address string (must not be NULL)
Returns
1 if localhost, 0 otherwise

Checks if an IPv4 address is in the loopback range:

  • 127.0.0.0/8 (127.0.0.0 - 127.255.255.255)
Note
Returns 0 for invalid IPv4 addresses.
Example
if (is_localhost_ipv4("127.0.0.1")) {
// This is a loopback address
}

Definition at line 1209 of file ip.c.

1209 {
1210 if (!is_valid_ipv4(ip)) {
1211 return 0;
1212 }
1213
1214 struct in_addr addr;
1215 if (inet_pton(AF_INET, ip, &addr) != 1) {
1216 return 0;
1217 }
1218
1219 uint32_t ip_val = ntohl(addr.s_addr);
1220
1221 // 127.0.0.0/8: Loopback addresses
1222 if ((ip_val & 0xFF000000) == 0x7F000000) {
1223 return 1;
1224 }
1225
1226 return 0;
1227}

References is_valid_ipv4().

Referenced by get_ip_type_string(), is_internet_ipv4(), parse_server_bind_address(), and session_server_like_run().

◆ is_localhost_ipv6()

int is_localhost_ipv6 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if IPv6 address is localhost.

Parameters
ipIPv6 address string (must not be NULL)
Returns
1 if localhost, 0 otherwise

Checks if an IPv6 address is the loopback address:

  • ::1
Note
Returns 0 for invalid IPv6 addresses.
Example
if (is_localhost_ipv6("::1")) {
// This is the IPv6 loopback address
}

Definition at line 1230 of file ip.c.

1230 {
1231 if (!ip) {
1232 return 0;
1233 }
1234
1235 // Remove brackets if present
1236 char normalized[INET6_ADDRSTRLEN];
1237 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1238 return 0;
1239 }
1240
1241 // Validate the normalized address
1242 if (!is_valid_ipv6(normalized)) {
1243 return 0;
1244 }
1245
1246 struct in6_addr addr;
1247 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1248 return 0;
1249 }
1250
1251 // ::1: Loopback address
1252 // All bytes should be 0 except the last byte which should be 1
1253 for (int i = 0; i < 15; i++) {
1254 if (addr.s6_addr[i] != 0) {
1255 return 0;
1256 }
1257 }
1258 if (addr.s6_addr[15] != 1) {
1259 return 0;
1260 }
1261
1262 return 1;
1263}

References is_valid_ipv6(), and parse_ipv6_address().

Referenced by get_ip_type_string(), is_internet_ipv6(), and parse_server_bind_address().

◆ is_valid_ip()

int is_valid_ip ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if string is a valid IP address (IPv4 or IPv6).

Parameters
ipString to validate (must not be NULL)
Returns
1 if valid IPv4 or IPv6, 0 otherwise

Unified validation function that accepts either IPv4 or IPv6 addresses. Use this when you don't care about the IP version, just validity.

Note
IPv6 addresses can be with or without brackets.
Returns 0 for NULL, empty strings, or invalid addresses.
Example
if (is_valid_ip("192.168.1.1")) {
// Valid IPv4
}
if (is_valid_ip("::1")) {
// Valid IPv6
}
int is_valid_ip(const char *ip)
Check if string is a valid IP address (IPv4 or IPv6).
Definition ip.c:448

Definition at line 448 of file ip.c.

448 {
449 if (!ip) {
450 return 0;
451 }
452
453 // Try IPv4 first (faster check)
454 if (is_valid_ipv4(ip)) {
455 return 1;
456 }
457
458 // Try IPv6
459 if (is_valid_ipv6(ip)) {
460 return 1;
461 }
462
463 return 0;
464}

References is_valid_ipv4(), and is_valid_ipv6().

Referenced by quic_tls_client_configure().

◆ is_valid_ipv4()

int is_valid_ipv4 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if a string is a valid IPv4 address.

Parameters
ipString to validate (must not be NULL)
Returns
1 if valid IPv4, 0 otherwise

Validates that a string is a valid IPv4 address in dotted decimal notation (e.g., "192.0.2.1"). Checks format correctness and numeric value ranges for each octet (0-255).

Note
Returns 0 for invalid format, out-of-range values, or non-IPv4 strings.
Does not validate that address is routable or assigned.
Example
if (is_valid_ipv4("192.0.2.1")) {
// Valid IPv4 address
}

Definition at line 32 of file ip.c.

32 {
33 if (!ip) {
34 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: NULL");
35 return 0; // Invalid
36 }
37
38 size_t ip_len = strlen(ip);
39 if (ip_len == 0) {
40 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: empty string");
41 return 0; // Invalid
42 }
43
44 if (ip_len > 256) {
45 char ip_buffer[BUFFER_SIZE_SMALL];
46 SAFE_STRNCPY(ip_buffer, ip, sizeof(ip_buffer));
47 SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", ip_buffer);
48 return 0; // Invalid
49 }
50
51 // Some platforms accept octets with leading zeros; reject ambiguous forms
52 // consistently before using the system parser for the remaining validation.
53 for (const char *p = ip; *p; ++p) {
54 if ((p == ip || p[-1] == '.') && p[0] == '0' && p[1] >= '0' && p[1] <= '9')
55 return 0;
56 }
57 struct in_addr address;
58 return inet_pton(AF_INET, ip, &address) == 1;
59}

References BUFFER_SIZE_SMALL, ERROR_INVALID_PARAM, SAFE_STRNCPY, and SET_ERRNO.

Referenced by get_ip_version(), hostname_to_ascii(), ipv4_to_ipv6_mapped(), is_broadcast_ipv4(), is_internet_ipv4(), is_lan_ipv4(), is_link_local_ipv4(), is_localhost_ipv4(), is_tailscale_host(), is_valid_ip(), parse_client_address(), parse_server_bind_address(), and validate_opt_ip_address().

◆ is_valid_ipv6()

int is_valid_ipv6 ( const char * ip)

#include <include/ascii-chat/util/ip.h>

Check if a string is a valid IPv6 address.

Parameters
ipString to validate (with or without brackets, must not be NULL)
Returns
1 if valid IPv6, 0 otherwise

Validates that a string is a valid IPv6 address. Accepts addresses with or without brackets (e.g., "::1" or "[::1]"). Checks format correctness including compressed zero notation (::) and valid hexadecimal groups.

Note
Returns 0 for invalid format, malformed addresses, or non-IPv6 strings.
Handles both bracketed and unbracketed IPv6 addresses.
Does not validate that address is routable or assigned.
Example
if (is_valid_ipv6("[::1]")) {
// Valid IPv6 address
}

Definition at line 63 of file ip.c.

63 {
64 if (!ip) {
65 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: NULL");
66 return 0; // Invalid
67 }
68
69 size_t ip_len = strlen(ip);
70 if (ip_len == 0) {
71 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: empty string");
72 return 0; // Invalid
73 }
74
75 if (ip_len > 256) {
76 char ip_buffer[BUFFER_SIZE_SMALL];
77 SAFE_STRNCPY(ip_buffer, ip, sizeof(ip_buffer));
78 SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", ip_buffer);
79 return 0; // Invalid
80 }
81
82 // Remove brackets if present (IPv6 addresses can be bracketed)
83 char normalized[INET6_ADDRSTRLEN];
84 const char *ip_to_validate = ip;
85
86 if (ip[0] == '[') {
87 // Has brackets, need to remove them
88 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
89 return 0; // Failed to parse (malformed brackets)
90 }
91 ip_to_validate = normalized;
92 }
93
94 // Use POSIX inet_pton() for robust IPv6 validation
95 // It handles all RFC 5952 compliant formats:
96 // - Full format: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
97 // - Compressed: 2001:db8:85a3::8a2e:370:7334
98 // - Loopback: ::1
99 // - All zeros: ::
100 // - IPv4-mapped: ::ffff:192.0.2.1
101 struct in6_addr addr;
102 int result = inet_pton(AF_INET6, ip_to_validate, &addr);
103
104 if (result == 1) {
105 return 1; // Valid IPv6
106 } else if (result == 0) {
107 return 0; // Not a valid IPv6 address
108 } else {
109 // result < 0 means system error (e.g., unsupported address family)
110 SET_ERRNO(ERROR_INVALID_PARAM, "Failed to validate IPv6 address");
111 return 0;
112 }
113}

References BUFFER_SIZE_SMALL, ERROR_INVALID_PARAM, parse_ipv6_address(), SAFE_STRNCPY, and SET_ERRNO.

Referenced by canonicalize_ipv6(), expand_ipv6(), get_ip_version(), hostname_to_ascii(), is_anycast_ipv6(), is_broadcast_ipv6(), is_internet_ipv6(), is_ipv4_mapped_ipv6(), is_lan_ipv6(), is_link_local_ipv6(), is_localhost_ipv6(), is_tailscale_host(), is_valid_ip(), parse_address_with_optional_port(), parse_client_address(), parse_server_bind_address(), and validate_opt_ip_address().

◆ parse_address_with_optional_port()

int parse_address_with_optional_port ( const char * input,
char * address_output,
size_t address_output_size,
uint16_t * port_output,
uint16_t default_port )

#include <include/ascii-chat/util/ip.h>

Parse address with optional port from string.

Parameters
inputInput string (address or address:port, must not be NULL)
address_outputOutput buffer for address (without brackets, must not be NULL)
address_output_sizeSize of address output buffer (must be > 0)
port_outputPointer to store port number (must not be NULL)
default_portDefault port to use if not specified in input
Returns
0 on success, -1 on error

Parses an address (IPv4, IPv6, or hostname) with an optional port number. If no port is specified, uses the default_port value. Handles various formats including bracketed IPv6 addresses.

SUPPORTED FORMATS (without port - uses default_port):

  • IPv4: "192.0.2.1"
  • IPv6: "::1" or "[::1]"
  • Hostname: "example.com" or "localhost"

SUPPORTED FORMATS (with port):

  • IPv4: "192.0.2.1:8080"
  • IPv6: "[2001:db8::1]:8080" (brackets required with port)
  • Hostname: "example.com:8080"
Note
IPv6 addresses with port MUST use brackets: "[::1]:8080"
IPv6 addresses without port can omit brackets: "::1" or "[::1]"
Port numbers are validated (1-65535 range).
Output address is normalized (brackets removed for IPv6).
Returns -1 on error (invalid format, buffer too small, invalid port, etc.).
Example
char addr[64];
uint16_t port;
// Without port - uses default
parse_address_with_optional_port("localhost", addr, sizeof(addr), &port, 27224);
// addr = "localhost", port = 27224
// With port
parse_address_with_optional_port("192.168.1.1:8080", addr, sizeof(addr), &port, 27224);
// addr = "192.168.1.1", port = 8080
// IPv6 without port
parse_address_with_optional_port("::1", addr, sizeof(addr), &port, 27224);
// addr = "::1", port = 27224
// IPv6 with port
parse_address_with_optional_port("[::1]:8080", addr, sizeof(addr), &port, 27224);
// addr = "::1", port = 8080
int parse_address_with_optional_port(const char *input, char *address_output, size_t address_output_size, uint16_t *port_output, uint16_t default_port)
Parse address with optional port from string.
Definition ip.c:283

Definition at line 283 of file ip.c.

283 {
284 if (!input || !address_output || !port_output || address_output_size == 0) {
285 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
286 return -1;
287 }
288
289 size_t input_len = strlen(input);
290 if (input_len == 0) {
291 SET_ERRNO(ERROR_INVALID_PARAM, "Empty address string");
292 return -1;
293 }
294
295 if (input_len >= URL_BUFFER_SIZE) {
296 SET_ERRNO(ERROR_INVALID_PARAM, "Address string too long");
297 return -1;
298 }
299
300 // Case 1: Bracketed IPv6 address with or without port
301 // Examples: "[::1]" or "[::1]:8080" or "[2001:db8::1]:443"
302 if (input[0] == '[') {
303 const char *bracket_end = strchr(input, ']');
304 if (!bracket_end) {
305 SET_ERRNO(ERROR_INVALID_PARAM, "Malformed bracketed address (missing ']'): %s", input);
306 return -1;
307 }
308
309 // Extract address without brackets
310 size_t addr_len = (size_t)(bracket_end - input - 1);
311 if (addr_len == 0) {
312 SET_ERRNO(ERROR_INVALID_PARAM, "Empty bracketed address: %s", input);
313 return -1;
314 }
315 if (addr_len >= address_output_size) {
316 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
317 return -1;
318 }
319
320 memcpy(address_output, input + 1, addr_len);
321 address_output[addr_len] = '\0';
322
323 // Validate it's a valid IPv6 address
324 if (!is_valid_ipv6(address_output)) {
325 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv6 address: %s", address_output);
326 return -1;
327 }
328
329 // Check for port after closing bracket
330 if (bracket_end[1] == '\0') {
331 // No port specified, use default
332 *port_output = default_port;
333 } else if (bracket_end[1] == ':') {
334 // Port specified
335 if (parse_port(bracket_end + 2, port_output) != ASCIICHAT_OK) {
336 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid port in: %s", input);
337 return -1;
338 }
339 } else {
340 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid format after ']' (expected ':' or end): %s", input);
341 return -1;
342 }
343 return 0;
344 }
345
346 // Case 2: Check if it's a valid IPv6 address without brackets (no port allowed in this case)
347 // Examples: "::1" or "2001:db8::1" or "fe80::1"
348 // Note: IPv6 addresses contain colons, so we can't use ':' as port separator without brackets
349 if (input_len < HOSTNAME_BUFFER_SIZE && is_valid_ipv6(input)) {
350 if (strlen(input) >= address_output_size) {
351 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
352 return -1;
353 }
354 SAFE_STRNCPY(address_output, input, address_output_size);
355 *port_output = default_port;
356 return 0;
357 }
358
359 // Case 3: IPv4 or hostname, possibly with port
360 // Examples: "192.168.1.1" or "192.168.1.1:8080" or "localhost" or "example.com:443"
361 const char *last_colon = strrchr(input, ':');
362
363 if (last_colon == NULL) {
364 // No colon - just address/hostname, no port
365 // Validate and normalize before checking the ASCII output capacity.
366 char ascii[HOSTNAME_BUFFER_SIZE];
367 if (hostname_to_ascii(input, ascii, sizeof(ascii)) != ASCIICHAT_OK || strchr(ascii, '_') || ascii[strlen(ascii) - 1] == '.') {
368 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid address format: %s", input);
369 return -1;
370 }
371
372 if (strlen(ascii) >= address_output_size) {
373 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
374 return -1;
375 }
376 SAFE_STRNCPY(address_output, ascii, address_output_size);
377 *port_output = default_port;
378 return 0;
379 }
380
381 // Has colon - extract address and port
382 size_t addr_len = (size_t)(last_colon - input);
383 if (addr_len == 0) {
384 SET_ERRNO(ERROR_INVALID_PARAM, "Empty address before port: %s", input);
385 return -1;
386 }
387 char host_input[URL_BUFFER_SIZE];
388 memcpy(host_input, input, addr_len);
389 host_input[addr_len] = '\0';
390
391 // Check if extracted address contains ':' - that would be IPv6 without brackets (invalid with port)
392 if (strchr(host_input, ':') != NULL) {
393 SET_ERRNO(ERROR_INVALID_PARAM, "IPv6 addresses must use brackets when specifying port: [%s]:%s instead of %s", host_input, last_colon + 1, input);
394 return -1;
395 }
396
397 // Validate address part is valid IPv4 or hostname
398 char ascii[HOSTNAME_BUFFER_SIZE];
399 if (hostname_to_ascii(host_input, ascii, sizeof(ascii)) != ASCIICHAT_OK || strchr(ascii, '_') || ascii[strlen(ascii) - 1] == '.') {
400 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid address format: %s", host_input);
401 return -1;
402 }
403
404 if (strlen(ascii) >= address_output_size) {
405 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
406 return -1;
407 }
408 SAFE_STRNCPY(address_output, ascii, address_output_size);
409
410 // Parse port
411 if (parse_port(last_colon + 1, port_output) != ASCIICHAT_OK) {
412 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid port in: %s", input);
413 return -1;
414 }
415
416 return 0;
417}
#define URL_BUFFER_SIZE
asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity)
Definition url.c:103
asciichat_error_t parse_port(const char *str, uint16_t *out_port)
Parse port number (1-65535) from string.

References ASCIICHAT_OK, ERROR_INVALID_PARAM, HOSTNAME_BUFFER_SIZE, hostname_to_ascii(), is_valid_ipv6(), parse_port(), SAFE_STRNCPY, SET_ERRNO, and URL_BUFFER_SIZE.

◆ parse_cidr()

int parse_cidr ( const char * cidr,
char * ip_out,
size_t ip_out_size,
int * prefix_out )

#include <include/ascii-chat/util/ip.h>

Parse CIDR notation into IP and prefix length.

Parameters
cidrCIDR string (e.g., "192.168.1.0/24", must not be NULL)
ip_outOutput buffer for IP address (without prefix, must not be NULL)
ip_out_sizeSize of IP output buffer
prefix_outPointer to store prefix length (must not be NULL)
Returns
0 on success, -1 on error

Parses CIDR notation into separate IP address and prefix length components. Supports both IPv4 and IPv6 CIDR notation.

SUPPORTED FORMATS:

  • IPv4: "192.168.1.0/24" -> ip="192.168.1.0", prefix=24
  • IPv6: "2001:db8::/32" -> ip="2001:db8::", prefix=32
  • IPv6 with brackets: "[::1]/128" -> ip="::1", prefix=128
Note
Validates that prefix length is in valid range (0-32 for IPv4, 0-128 for IPv6).
Output IP has brackets removed for IPv6.
Returns -1 on error (invalid format, out of range prefix, buffer too small).
Example
char ip[64];
int prefix;
if (parse_cidr("192.168.1.0/24", ip, sizeof(ip), &prefix) == 0) {
// ip = "192.168.1.0", prefix = 24
}

Definition at line 579 of file ip.c.

579 {
580 if (!cidr || !ip_out || !prefix_out || ip_out_size == 0) {
581 return -1;
582 }
583
584 // Find the '/' separator
585 const char *slash = strchr(cidr, '/');
586 if (!slash) {
587 return -1; // No slash found
588 }
589
590 // Extract IP part
591 size_t ip_len = (size_t)(slash - cidr);
592 if (ip_len == 0 || ip_len >= ip_out_size) {
593 return -1;
594 }
595
596 char ip_temp[UTIL_IP_IP_TEMP_BUFFER_SIZE];
597 if (ip_len >= sizeof(ip_temp)) {
598 return -1;
599 }
600
601 memcpy(ip_temp, cidr, ip_len);
602 ip_temp[ip_len] = '\0';
603
604 // Remove brackets if IPv6
605 if (ip_temp[0] == '[') {
606 if (parse_ipv6_address(ip_temp, ip_out, ip_out_size) != 0) {
607 return -1;
608 }
609 } else {
610 if (ip_len >= ip_out_size) {
611 return -1;
612 }
613 memcpy(ip_out, ip_temp, ip_len + 1);
614 }
615
616 // Validate IP
617 int version = get_ip_version(ip_out);
618 if (version == 0) {
619 return -1; // Invalid IP
620 }
621
622 // Parse prefix length
623 const char *prefix_str = slash + 1;
624 if (strlen(prefix_str) == 0) {
625 return -1;
626 }
627
628 char *endptr;
629 long prefix = strtol(prefix_str, &endptr, 10);
630 if (*endptr != '\0' || prefix < 0) {
631 return -1; // Invalid prefix
632 }
633
634 // Validate prefix range based on IP version
635 if (version == 4 && (prefix > 32)) {
636 return -1;
637 }
638 if (version == 6 && (prefix > 128)) {
639 return -1;
640 }
641
642 *prefix_out = (int)prefix;
643 return 0;
644}
#define UTIL_IP_IP_TEMP_BUFFER_SIZE
Definition ip.c:8

References get_ip_version(), parse_ipv6_address(), and UTIL_IP_IP_TEMP_BUFFER_SIZE.

Referenced by ip_in_cidr().

◆ parse_ip_with_port()

int parse_ip_with_port ( const char * input,
char * ip_output,
size_t ip_output_size,
uint16_t * port_output )

#include <include/ascii-chat/util/ip.h>

Parse IP address and port from string.

Parameters
inputInput string with port (must not be NULL, format: "ip:port" or "[ip]:port")
ip_outputOutput buffer for IP address (without brackets, must not be NULL)
ip_output_sizeSize of IP output buffer (must be > 0)
port_outputPointer to store port number (must not be NULL)
Returns
0 on success, -1 on error

Parses an IP address (IPv4 or IPv6) with port number from a string. Handles various formats including bracketed IPv6 addresses. Also accepts hostnames (non-IP addresses).

SUPPORTED FORMATS:

  • IPv4: "192.0.2.1:8080"
  • IPv6: "[2001:db8::1]:8080"
  • Hostname: "example.com:8080"
Note
IPv6 addresses must use brackets in input format.
Port numbers are validated (0-65535 range).
Output IP address is normalized (brackets removed).
Returns -1 on error (invalid format, buffer too small, invalid port, etc.).
Example
char ip[64];
uint16_t port;
if (parse_ip_with_port("[::1]:8080", ip, sizeof(ip), &port) == 0) {
// ip = "::1", port = 8080
}

Definition at line 209 of file ip.c.

209 {
210 if (!input || !ip_output || !port_output || ip_output_size == 0) {
211 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", input);
212 return -1;
213 }
214
215 if (strlen(input) == 0) {
216 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", input);
217 return -1;
218 }
219
220 if (strlen(input) > 256) {
221 char input_buffer[BUFFER_SIZE_SMALL];
222 SAFE_STRNCPY(input_buffer, input, sizeof(input_buffer));
223 SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", input_buffer);
224 return -1;
225 }
226
227 // Check for IPv6 bracket notation: [2001:db8::1]:8080
228 if (input[0] == '[') {
229 // Find closing bracket
230 const char *bracket_end = strchr(input, ']');
231 if (!bracket_end)
232 return -1; // Malformed - opening bracket but no closing bracket
233
234 // Extract IP address (without brackets)
235 size_t ip_len = (size_t)(bracket_end - input - 1);
236 if (ip_len >= ip_output_size)
237 return -1; // IP too long
238
239 memcpy(ip_output, input + 1, ip_len);
240 ip_output[ip_len] = '\0';
241
242 // Check for port after closing bracket
243 if (bracket_end[1] == ':') {
244 // Parse port using safe integer parsing
245 if (parse_port(bracket_end + 2, port_output) != ASCIICHAT_OK) {
246 return -1; // Invalid port
247 }
248 } else {
249 return -1; // Expected ':' after closing bracket
250 }
251 } else {
252 // IPv4 or hostname: "192.0.2.1:8080" or "example.com:8080"
253 // Find last ':' for port separation
254 const char *colon = strrchr(input, ':');
255 if (!colon)
256 return -1; // No port separator
257
258 // Extract IP/hostname
259 size_t ip_len = (size_t)(colon - input);
260 if (ip_len >= ip_output_size)
261 return -1; // IP too long
262
263 memcpy(ip_output, input, ip_len);
264 ip_output[ip_len] = '\0';
265
266 // Reject IPv6 without brackets (check if extracted IP contains ':')
267 // This catches cases like "::1:8080" which should be "[::1]:8080"
268 if (strchr(ip_output, ':') != NULL)
269 return -1; // IPv6 address without brackets - invalid format
270
271 // Parse port using safe integer parsing
272 if (parse_port(colon + 1, port_output) != ASCIICHAT_OK) {
273 return -1; // Invalid port
274 }
275 }
276
277 return 0;
278}

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, ERROR_INVALID_PARAM, parse_port(), SAFE_STRNCPY, and SET_ERRNO.

Referenced by compare_ip_port_strings().

◆ parse_ipv6_address()

int parse_ipv6_address ( const char * input,
char * output,
size_t output_size )

#include <include/ascii-chat/util/ip.h>

Parse IPv6 address, removing brackets if present.

Parameters
inputInput address (may have brackets, must not be NULL)
outputOutput buffer for parsed address (without brackets, must not be NULL)
output_sizeSize of output buffer (must be > 0)
Returns
0 on success, -1 on error

Parses an IPv6 address and removes brackets if present. Handles both bracketed and unbracketed formats. Validates the address and normalizes it to unbracketed form for internal use.

SUPPORTED FORMATS:

  • "::1" -> "::1"
  • "[::1]" -> "::1"
  • "2001:db8::1" -> "2001:db8::1"
  • "[2001:db8::1]" -> "2001:db8::1"
Note
Output buffer must be large enough to hold IPv6 address (at least 39 bytes).
Returns -1 on error (invalid address, buffer too small, etc.).
Brackets are removed from output (address is normalized).

Definition at line 116 of file ip.c.

116 {
117 if (!input || !output || output_size == 0)
118 return -1;
119
120 size_t input_len = strlen(input);
121 if (input_len == 0)
122 return -1; // Empty string
123
124 const char *start = input;
125 const char *end = input + input_len;
126
127 // Remove brackets if present - but brackets must be matched
128 if (*start == '[') {
129 if (input_len < 2 || *(end - 1) != ']')
130 return -1; // Malformed brackets
131 start++;
132 end--;
133
134 // Check for double brackets [[...]]
135 if (start < end && *start == '[')
136 return -1; // Double opening bracket
137 } else if (*(end - 1) == ']') {
138 // Closing bracket without opening bracket
139 return -1;
140 }
141
142 size_t len = (size_t)(end - start);
143 if (len == 0)
144 return -1; // Empty content after removing brackets
145 if (len >= output_size)
146 return -1; // Buffer too small
147
148 memcpy(output, start, len);
149 output[len] = '\0';
150 return 0;
151}

Referenced by canonicalize_ipv6(), expand_ipv6(), extract_ipv4_from_mapped_ipv6(), ip_compare(), ip_equals(), ip_in_cidr_parsed(), is_anycast_ipv6(), is_broadcast_ipv6(), is_internet_ipv6(), is_ipv4_mapped_ipv6(), is_lan_ipv6(), is_link_local_ipv6(), is_localhost_ipv6(), is_valid_ipv6(), parse_cidr(), parse_server_bind_address(), and validate_opt_ip_address().

◆ path_cleanup_thread_locals()

void path_cleanup_thread_locals ( void )

#include <include/ascii-chat/util/path.h>

Cleanup thread-local path resources.

Frees PCRE2 match data allocated for thread-local path normalization. Called automatically on thread exit. Safe to call multiple times.

Note
This is called automatically by the threading system - users should not need to call this directly.

Retained for callers that used to release thread-local path resources.

Definition at line 32 of file path.c.

32{}

Referenced by main().

◆ path_is_absolute()

bool path_is_absolute ( const char * path)

#include <include/ascii-chat/util/path.h>

Determine whether a path is absolute on the current platform.

Parameters
pathPath string to test (may be NULL)
Returns
true if the path is absolute, false otherwise

Definition at line 422 of file path.c.

422 {
423 if (!path || !*path) {
424 return false;
425 }
426
427#ifdef _WIN32
428 if ((path[0] == '\\' && path[1] == '\\')) {
429 return true; // UNC path
430 }
431 if (isalpha((unsigned char)path[0]) && path[1] == PATH_DRIVE_SEPARATOR && path[2] == PATH_DELIM) {
432 return true;
433 }
434 return false;
435#else
436 return path[0] == PATH_DELIM;
437#endif
438}
#define PATH_DRIVE_SEPARATOR
Path component: Windows drive separator (colon).
Definition path.h:82

References PATH_DRIVE_SEPARATOR.

Referenced by path_is_within_base(), and path_validate_user_path().

◆ path_is_within_any_base()

bool path_is_within_any_base ( const char * path,
const char *const * bases,
size_t base_count )

#include <include/ascii-chat/util/path.h>

Check whether a path resides within any of several base directories.

Parameters
pathCandidate path to validate (must be absolute)
basesArray of base directory strings
base_countNumber of entries in bases
Returns
true if path is inside any allowed base, false otherwise

Definition at line 477 of file path.c.

477 {
478 if (!path || !bases || base_count == 0) {
479 return false;
480 }
481
482 for (size_t i = 0; i < base_count; ++i) {
483 const char *base = bases[i];
484 if (!base) {
485 continue;
486 }
487 if (path_is_within_base(path, base)) {
488 return true;
489 }
490 }
491
492 return false;
493}
bool path_is_within_base(const char *path, const char *base)
Check whether a path resides within a specified base directory.
Definition path.c:440

References path_is_within_base().

Referenced by path_validate_user_path().

◆ path_is_within_base()

bool path_is_within_base ( const char * path,
const char * base )

#include <include/ascii-chat/util/path.h>

Check whether a path resides within a specified base directory.

Both the candidate path and the base directory are normalized before comparison. The base directory must be absolute. The comparison honours the platform's case sensitivity rules (case-insensitive on Windows).

Parameters
pathCandidate path to validate (must be absolute)
baseAbsolute base directory to compare against
Returns
true if path is inside base (or exactly equal), false otherwise

Definition at line 440 of file path.c.

440 {
441 if (!path || !base) {
442 return false;
443 }
444
445 if (!path_is_absolute(path) || !path_is_absolute(base)) {
446 return false;
447 }
448
449 char normalized_path[PLATFORM_MAX_PATH_LENGTH];
450 char normalized_base[PLATFORM_MAX_PATH_LENGTH];
451
452 if (!path_normalize_copy(path, normalized_path, sizeof(normalized_path))) {
453 return false;
454 }
455 if (!path_normalize_copy(base, normalized_base, sizeof(normalized_base))) {
456 return false;
457 }
458
459 size_t base_len = strlen(normalized_base);
460 if (base_len == 0) {
461 return false;
462 }
463
464 if (platform_path_strcasecmp(normalized_path, normalized_base, base_len) != 0) {
465 return false;
466 }
467 if (normalized_base[base_len - 1] == PATH_DELIM) {
468 return true;
469 }
470 char next = normalized_path[base_len];
471 if (next == '\0') {
472 return true;
473 }
474 return next == PATH_DELIM;
475}
bool path_is_absolute(const char *path)
Determine whether a path is absolute on the current platform.
Definition path.c:422
bool path_normalize_copy(const char *path, char *out, size_t out_len)
Normalize a path and copy it into the provided buffer.
Definition path.c:402
int platform_path_strcasecmp(const char *a, const char *b, size_t n)
Definition util.c:131

References path_is_absolute(), path_normalize_copy(), PLATFORM_MAX_PATH_LENGTH, and platform_path_strcasecmp().

Referenced by path_is_within_any_base().

◆ path_last_components()

const char * path_last_components ( const char * path,
size_t component_count )

#include <include/ascii-chat/util/path.h>

Return a pointer to the last components of a path.

Parameters
pathPath using slash or backslash separators
component_countMaximum number of trailing components to retain
Returns
Pointer into path at the first retained component

The filename counts as one component. For example, a component count of 5 retains at most four parent directories and the filename.

Note
Does not allocate, modify the input, or access the filesystem.

Definition at line 230 of file path.c.

230 {
231 if (!path || component_count == 0) {
232 return path;
233 }
234
235 const char *cursor = path + strlen(path);
236 size_t components_seen = 0;
237 while (cursor > path) {
238 cursor--;
239 if (*cursor != '/' && *cursor != '\\') {
240 continue;
241 }
242
243 const char *component_start = cursor + 1;
244 // Treat repeated separators as one boundary.
245 while (cursor > path && (cursor[-1] == '/' || cursor[-1] == '\\')) {
246 cursor--;
247 }
248 components_seen++;
249 if (components_seen == component_count) {
250 return component_start;
251 }
252 }
253
254 return path;
255}

◆ path_looks_like_path()

bool path_looks_like_path ( const char * value)

#include <include/ascii-chat/util/path.h>

Determine if a string is likely intended to reference the filesystem.

Heuristics include presence of path separators, leading ~, relative prefixes, or Windows drive designators. Used to avoid treating tokens like "github:user" or raw hex keys as file paths.

Parameters
valueString to analyze
Returns
true if the string looks like a filesystem path

Definition at line 495 of file path.c.

495 {
496 if (!value || *value == '\0') {
497 return false;
498 }
499
500 if (value[0] == PATH_DELIM || value[0] == PATH_COMPONENT_DOT || value[0] == PATH_TILDE) {
501 return true;
502 }
503
504 if (strchr(value, PATH_DELIM)) {
505 return true;
506 }
507
508#ifdef _WIN32
509 if (isalpha((unsigned char)value[0]) && value[1] == ':' && value[2] == PATH_DELIM) {
510 return true;
511 }
512#endif
513
514 return false;
515}
#define PATH_COMPONENT_DOT
Path component: current directory (single dot).
Definition path.h:63

References PATH_COMPONENT_DOT, and PATH_TILDE.

Referenced by parse_keys_from_file(), parse_public_key(), parse_public_keys(), path_validate_user_path(), and validate_ssh_key_file().

◆ path_normalize_copy()

bool path_normalize_copy ( const char * path,
char * out,
size_t out_len )

#include <include/ascii-chat/util/path.h>

Normalize a path and copy it into the provided buffer.

Resolves '.' and '..' components without requiring the path to exist on disk. The output buffer receives a canonicalized representation using platform preferred separators.

Parameters
pathInput path string (must not be NULL)
outDestination buffer for normalized path
out_lenSize of destination buffer in bytes
Returns
true on success, false on failure (invalid arguments or buffer too small)

Definition at line 402 of file path.c.

402 {
403 if (!path || !out || out_len == 0) {
404 SET_ERRNO(ERROR_INVALID_PARAM, "null path or out or out_len is 0");
405 return false;
406 }
407
408 const char *normalized = normalize_path(path);
409 if (!normalized) {
410 return false;
411 }
412
413 size_t len = strlen(normalized);
414 if (len + 1 > out_len) {
415 return false;
416 }
417
418 memcpy(out, normalized, len + 1);
419 return true;
420}

References ERROR_INVALID_PARAM, out, and SET_ERRNO.

Referenced by path_is_within_base(), and path_validate_user_path().

◆ path_validate_user_path()

asciichat_error_t path_validate_user_path ( const char * input,
path_role_t role,
char ** normalized_out )

#include <include/ascii-chat/util/path.h>

Validate and canonicalize a user-supplied filesystem path.

Resolves ~, relative segments, and enforces that the resulting absolute path resides within the trusted base directories for the supplied role.

Trusted base directories include:

  • Current working directory
  • System temp directory
  • User config directory (~/.ascii-chat/ or APPDATA%\ascii-chat)
  • User home directory
  • User SSH directory (~/.ssh/)
  • System config directories (Unix: /etc/ascii-chat/, /usr/local/etc/ascii-chat/)
  • System log directories (Unix: /var/log/, /var/tmp/)
  • System-wide app data (Windows: PROGRAMDATA%\ascii-chat)
Note
For PATH_ROLE_LOG_FILE, the base directory check is skipped to allow logging to any writable location.
Parameters
inputOriginal user-provided path (must not be NULL)
roleIntended usage category
normalized_outOutput pointer receiving SAFE_MALLOC'd canonical path
Returns
ASCIICHAT_OK on success, error code on failure (and normalized_out is NULL)

Definition at line 705 of file path.c.

705 {
706 if (!normalized_out) {
707 return SET_ERRNO(map_role_to_error(role), "Output pointer is required");
708 }
709 *normalized_out = NULL;
710
711 if (!input || *input == '\0') {
712 return SET_ERRNO(map_role_to_error(role), "Path is empty for role %d", role);
713 }
714
715 // SECURITY: For log files, if input is a simple filename (no separators or ..), constrain it to a safe directory
716 if (role == PATH_ROLE_LOG_FILE) {
717 // Check if input contains path separators or parent directory references
718 bool is_simple_filename = true;
719 for (const char *p = input; *p; p++) {
720 if (*p == PATH_DELIM || *p == '/' || *p == '\\') {
721 is_simple_filename = false;
722 break;
723 }
724 }
725 // Also reject ".." components (even without separators like "..something")
726 if (strstr(input, "..") != NULL) {
727 is_simple_filename = false;
728 }
729
730 // If it's a simple filename, resolve it to a safe base directory
731 if (is_simple_filename) {
732 // Always prefer current working directory for simple log filenames
733 // This ensures logs go to where the user is running the command from
734 char safe_base[PLATFORM_MAX_PATH_LENGTH];
735
736 if (!platform_get_cwd(safe_base, sizeof(safe_base))) {
737 // If cwd fails, try config dir as fallback
738 char *config_dir = get_config_dir();
739 if (config_dir) {
740 SAFE_STRNCPY(safe_base, config_dir, sizeof(safe_base));
741 SAFE_FREE(config_dir);
742 } else {
743 return SET_ERRNO(ERROR_LOGGING_INIT, "Failed to determine safe directory for log file");
744 }
745 }
746
747 // Build the full path: safe_base + separator + input
748 size_t base_len = strlen(safe_base);
749 size_t input_len = strlen(input);
750 bool needs_sep = base_len > 0 && safe_base[base_len - 1] != PATH_DELIM;
751 size_t total_len = base_len + (needs_sep ? 1 : 0) + input_len + 1;
752
753 if (total_len > PLATFORM_MAX_PATH_LENGTH) {
754 return SET_ERRNO(ERROR_LOGGING_INIT, "Log file path too long: %s/%s", safe_base, input);
755 }
756
757 char resolved_buf[PLATFORM_MAX_PATH_LENGTH];
758 safe_snprintf(resolved_buf, sizeof(resolved_buf), "%s%s%s", safe_base, needs_sep ? PATH_SEPARATOR_STR : "", input);
759
760 // Normalize the resolved path
761 char normalized_buf[PLATFORM_MAX_PATH_LENGTH];
762 if (!path_normalize_copy(resolved_buf, normalized_buf, sizeof(normalized_buf))) {
763 return SET_ERRNO(ERROR_LOGGING_INIT, "Failed to normalize log file path: %s", resolved_buf);
764 }
765
766 // Allocate and return the result
767 char *result = SAFE_MALLOC(strlen(normalized_buf) + 1, char *);
768 if (!result) {
769 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate normalized path");
770 }
771 safe_snprintf(result, strlen(normalized_buf) + 1, "%s", normalized_buf);
772 *normalized_out = result;
773 return ASCIICHAT_OK;
774 }
775 // If not a simple filename (contains separators), continue with normal validation below
776 }
777
778 // For non-log-files or log files with path separators, validate as usual
779 if (role != PATH_ROLE_LOG_FILE && !path_looks_like_path(input)) {
780 return SET_ERRNO(map_role_to_error(role), "Value does not look like a filesystem path: %s", input);
781 }
782
783 char *expanded = expand_path(input);
784 if (!expanded) {
785 return SET_ERRNO(map_role_to_error(role), "Failed to expand path: %s", input);
786 }
787
788 defer(SAFE_FREE(expanded));
789
790 char candidate_buf[PLATFORM_MAX_PATH_LENGTH];
791 const char *candidate_path = expanded;
792
793 if (!path_is_absolute(candidate_path)) {
794 char cwd_buf[PLATFORM_MAX_PATH_LENGTH];
795 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
796 return SET_ERRNO(map_role_to_error(role), "Failed to determine current working directory");
797 }
798
799 size_t total_len = strlen(cwd_buf) + 1 + strlen(candidate_path) + 1;
800 if (total_len >= sizeof(candidate_buf)) {
801 return SET_ERRNO(map_role_to_error(role), "Resolved path is too long: %s/%s", cwd_buf, candidate_path);
802 }
803 if (strlen(candidate_path) > 0 && candidate_path[0] == PATH_DELIM) {
804 safe_snprintf(candidate_buf, sizeof(candidate_buf), "%s%s", cwd_buf, candidate_path);
805 } else {
806 safe_snprintf(candidate_buf, sizeof(candidate_buf), "%s%c%s", cwd_buf, PATH_DELIM, candidate_path);
807 }
808 candidate_path = candidate_buf;
809 }
810
811 char normalized_buf[PLATFORM_MAX_PATH_LENGTH];
812 if (!path_normalize_copy(candidate_path, normalized_buf, sizeof(normalized_buf))) {
813 return SET_ERRNO(map_role_to_error(role), "Failed to normalize path: %s", candidate_path);
814 }
815
816 if (!path_is_absolute(normalized_buf)) {
817 return SET_ERRNO(map_role_to_error(role), "Normalized path is not absolute: %s", normalized_buf);
818 }
819
820 const char *bases[MAX_PATH_BASES] = {0};
821 size_t base_count = 0;
822
823 // Always add current working directory as an allowed base
824 // This is critical for log files and other paths relative to where the user runs the command
825 char cwd_base[PLATFORM_MAX_PATH_LENGTH];
826 if (platform_get_cwd(cwd_base, sizeof(cwd_base))) {
827 append_base_if_valid(cwd_base, bases, &base_count);
828 }
829
830#ifndef NDEBUG
831 // Debug builds select the source checkout as their default log directory,
832 // even when the process was launched from another working directory.
833 if (role == PATH_ROLE_LOG_FILE)
834 append_base_if_valid(ASCIICHAT_SOURCE_ROOT, bases, &base_count);
835#endif
836
837 char temp_base[PLATFORM_MAX_PATH_LENGTH];
838 if (platform_get_temp_dir(temp_base, sizeof(temp_base))) {
839 append_base_if_valid(temp_base, bases, &base_count);
840 }
841
842 char *config_dir = get_config_dir();
843 defer(SAFE_FREE(config_dir));
844 if (config_dir) {
845 append_base_if_valid(config_dir, bases, &base_count);
846 }
847
848 char home_base[PLATFORM_MAX_PATH_LENGTH];
849 const char *home_env = platform_get_home_dir();
850 if (home_env) {
851 // Windows environment lookups reuse a thread-local buffer. Keep this base
852 // stable when PROGRAMDATA is read below.
853 SAFE_STRNCPY(home_base, home_env, sizeof(home_base));
854 home_env = home_base;
855 append_base_if_valid(home_env, bases, &base_count);
856 }
857
858 char ascii_chat_home[PLATFORM_MAX_PATH_LENGTH];
859 if (home_env) {
860 build_ascii_chat_path(home_env, ".ascii-chat", ascii_chat_home, sizeof(ascii_chat_home));
861 append_base_if_valid(ascii_chat_home, bases, &base_count);
862 }
863
864#ifndef _WIN32
865 char ascii_chat_home_tmp[PLATFORM_MAX_PATH_LENGTH];
866 build_ascii_chat_path("/tmp", ".ascii-chat", ascii_chat_home_tmp, sizeof(ascii_chat_home_tmp));
867 append_base_if_valid(ascii_chat_home_tmp, bases, &base_count);
868#endif
869
870 char ssh_home[PLATFORM_MAX_PATH_LENGTH];
871 if (home_env) {
872 build_ascii_chat_path(home_env, ".ssh", ssh_home, sizeof(ssh_home));
873 append_base_if_valid(ssh_home, bases, &base_count);
874 }
875
876#ifdef _WIN32
877 char program_data_logs[PLATFORM_MAX_PATH_LENGTH];
878 const char *program_data = platform_getenv("PROGRAMDATA");
879 if (program_data) {
880 build_ascii_chat_path(program_data, "ascii-chat", program_data_logs, sizeof(program_data_logs));
881 append_base_if_valid(program_data_logs, bases, &base_count);
882 }
883#else
884 // System-wide config directories (for server deployments)
885 append_base_if_valid("/etc/ascii-chat", bases, &base_count);
886 append_base_if_valid("/usr/local/etc/ascii-chat", bases, &base_count);
887 append_base_if_valid("/var/log", bases, &base_count);
888 append_base_if_valid("/var/tmp", bases, &base_count);
889 append_base_if_valid("/tmp", bases, &base_count);
890#ifdef __APPLE__
891 // On macOS, /tmp is a symlink to /private/tmp
892 append_base_if_valid("/private/tmp", bases, &base_count);
893 // On macOS, all user home directories are under /Users
894 append_base_if_valid("/Users", bases, &base_count);
895#endif
896#endif
897
898 // Security check: Reject paths that point to sensitive system files
899 // This applies to all path roles, not just logs
900 if (is_sensitive_system_path(normalized_buf)) {
901 return SET_ERRNO(map_role_to_error(role), "Cannot write to protected system path: %s", normalized_buf);
902 }
903
904 // For log files, apply special validation rules
905 if (role == PATH_ROLE_LOG_FILE) {
906 // Check if path is a regular file (not a directory, not non-existent)
907 // On macOS, fopen() can succeed on directories, so we must use platform_is_regular_file()
908 bool is_regular_file = platform_is_regular_file(normalized_buf);
909
910 // If a regular file exists, it MUST be an ascii-chat log or empty file to be overwritten
911 if (is_regular_file && !is_existing_ascii_chat_log(normalized_buf) && !is_file_empty(normalized_buf)) {
913 "Cannot overwrite existing non-ascii-chat file: %s\n"
914 "For safety, ascii-chat will only overwrite its own log files or empty files",
915 normalized_buf);
916 }
917
918 // If file doesn't exist (or is a directory), check that path is in safe locations
919 if (!is_regular_file) {
920 bool allowed = base_count == 0 ? true : path_is_within_any_base(normalized_buf, bases, base_count);
921 if (!allowed) {
923 "Log path %s is outside allowed directories (use -L /tmp/file.log, ~/file.log, or "
924 "relative/absolute paths in safe locations)",
925 normalized_buf);
926 }
927 }
928 } else {
929 // For non-log-file paths, apply standard whitelist validation
930 bool allowed = base_count == 0 ? true : path_is_within_any_base(normalized_buf, bases, base_count);
931 if (!allowed) {
932 return SET_ERRNO(map_role_to_error(role), "Path %s is outside allowed directories", normalized_buf);
933 }
934 }
935
936 char *result = SAFE_MALLOC(strlen(normalized_buf) + 1, char *);
937 if (!result) {
938 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate normalized path");
939 }
940 safe_snprintf(result, strlen(normalized_buf) + 1, "%s", normalized_buf);
941 *normalized_out = result;
942
943 return ASCIICHAT_OK;
944}
@ ERROR_LOGGING_INIT
Definition error_codes.h:58
@ ERROR_MEMORY
Definition error_codes.h:55
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:495
#define MAX_PATH_BASES
Maximum number of path base directories.
Definition path.h:89
bool path_is_within_any_base(const char *path, const char *const *bases, size_t base_count)
Check whether a path resides within any of several base directories.
Definition path.c:477
return true
Definition queries.h:13
const char * platform_getenv(const char *name)
Definition system.c:45
int platform_is_regular_file(const char *path)
Definition util.c:136

References ASCIICHAT_OK, ERROR_LOGGING_INIT, ERROR_MEMORY, expand_path(), get_config_dir(), MAX_PATH_BASES, path_is_absolute(), path_is_within_any_base(), path_looks_like_path(), path_normalize_copy(), PATH_ROLE_LOG_FILE, platform_get_cwd(), platform_get_home_dir(), platform_get_temp_dir(), platform_getenv(), platform_is_regular_file(), PLATFORM_MAX_PATH_LENGTH, SAFE_FREE, SAFE_MALLOC, SAFE_STRNCPY, SET_ERRNO, and true.

Referenced by config_create_default(), config_load_and_apply(), parse_keys_from_file(), parse_log_file(), parse_private_key(), parse_public_key(), and validate_ssh_key_file().

◆ prompt_password()

int prompt_password ( const char * prompt,
char * password,
size_t max_len )

#include <include/ascii-chat/util/password.h>

Prompt the user for a password with secure input.

Parameters
promptThe prompt message to display
passwordBuffer to store the entered password
max_lenMaximum length of the password buffer (including null terminator)
Returns
0 on success, -1 on failure or user cancellation

Displays a formatted password prompt with visual separators:

========================================
<prompt>
========================================
> ********
========================================

Input is masked with asterisks and echo is disabled for security.

Note
Returns -1 if stdin is not a TTY (non-interactive mode).
Acquires terminal lock during prompting.

Definition at line 15 of file password.c.

15 {
16 if (!prompt || !password || max_len < 2) {
17 return -1;
18 }
19
20 // The prompt renderer owns its header and masked input as one snapshot.
21 int result = platform_prompt_question(prompt, password, max_len, PROMPT_OPTS_PASSWORD);
22
23 // Validate password is valid UTF-8 (should always succeed since platform_prompt_question handles it)
24 if (result == 0 && !utf8_is_valid(password)) {
25 log_warn("Password contains invalid UTF-8 sequence, input may be corrupted");
26 }
27
28 return result;
29}
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:128

References ERROR_NOT_SUPPORTED, log_warn, SET_ERRNO, and utf8_is_valid().

Referenced by crypto_handshake_client_auth_response().

◆ prompt_password_simple()

int prompt_password_simple ( const char * prompt,
char * password,
size_t max_len )

#include <include/ascii-chat/util/password.h>

Prompt the user for a password with simple formatting.

Parameters
promptThe prompt message to display (shown inline)
passwordBuffer to store the entered password
max_lenMaximum length of the password buffer (including null terminator)
Returns
0 on success, -1 on failure or user cancellation

Displays a simple inline password prompt:

<prompt>: ********

Use this for simpler prompts like SSH key passphrases.

Note
Returns -1 if stdin is not a TTY (non-interactive mode).
Acquires terminal lock during prompting.

Definition at line 31 of file password.c.

31 {
32 return prompt_password_simple_kind(prompt, password, max_len, UI_PROMPT_PASSWORD);
33}
int prompt_password_simple_kind(const char *prompt, char *password, size_t max_len, ui_prompt_kind_t kind)
Definition password.c:35

References prompt_password_simple_kind().

Referenced by read_password_from_stdin().

◆ prompt_password_simple_kind()

int prompt_password_simple_kind ( const char * prompt,
char * password,
size_t max_len,
ui_prompt_kind_t kind )

#include <include/ascii-chat/util/password.h>

Definition at line 35 of file password.c.

35 {
36 if (!prompt || !password || max_len < 2) {
37 return -1;
38 }
39
40 // Build prompt with colon suffix, using byte-length for memcpy
41 char full_prompt[BUFFER_SIZE_SMALL];
42 size_t prompt_byte_len = strlen(prompt);
43 if (prompt_byte_len >= sizeof(full_prompt) - 2) {
44 prompt_byte_len = sizeof(full_prompt) - 3;
45 }
46 memcpy(full_prompt, prompt, prompt_byte_len);
47 full_prompt[prompt_byte_len] = ':';
48 full_prompt[prompt_byte_len + 1] = '\0';
49
50 // Prompt for password with asterisk masking, same line
51 prompt_opts_t opts = PROMPT_OPTS_PASSWORD;
52 opts.kind = kind;
53 int result = platform_prompt_question(full_prompt, password, max_len, opts);
54
55 // Validate password is valid UTF-8 (should always succeed since platform_prompt_question handles it)
56 if (result == 0 && !utf8_is_valid(password)) {
57 log_warn("Password contains invalid UTF-8 sequence, input may be corrupted");
58 }
59
60 return result;
61}

References BUFFER_SIZE_SMALL, log_warn, and utf8_is_valid().

Referenced by prompt_password_simple().

◆ safe_parse_audio_message()

asciichat_error_t safe_parse_audio_message ( const char * message,
unsigned int * num_samples )

#include <include/ascii-chat/util/parsing.h>

Parse AUDIO message format.

Parameters
messageInput message string (must not be NULL, format: "AUDIO:num_samples")
num_samplesOutput parameter for parsed sample count (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses an AUDIO protocol message in the format "AUDIO:num_samples" where num_samples is an unsigned integer. Validates the message format, parses the numeric value, and checks for overflow conditions.

MESSAGE FORMAT:

  • Must start with "AUDIO:"
  • Sample count must be a valid unsigned integer
  • No whitespace allowed in value
Note
num_samples is only modified on successful parsing.
Returns ASCIICHAT_ERROR_INVALID_ARGUMENT if format is invalid.
Returns ASCIICHAT_ERROR_OVERFLOW if numeric value exceeds limits.
Example
unsigned int num_samples;
if (safe_parse_audio_message("AUDIO:44100", &num_samples) == ASCIICHAT_OK) {
// num_samples = 44100
}
asciichat_error_t safe_parse_audio_message(const char *message, unsigned int *num_samples)
Parse AUDIO message format.

Definition at line 65 of file util/parsing.c.

65 {
66 if (!message || !num_samples) {
67 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for audio message parsing");
68 }
69
70 // Check if message starts with "AUDIO:"
71 if (strncmp(message, "AUDIO:", 6) != 0) {
72 return SET_ERRNO(ERROR_INVALID_PARAM, "Message does not start with 'AUDIO:'");
73 }
74
75 const char *ptr = message + 6; // Skip "AUDIO:"
76 char *endptr;
77
78 // Parse number
79 errno = 0;
80 unsigned long samples = strtoul(ptr, &endptr, 10);
81 if (errno != 0 || endptr == ptr || samples > UINT_MAX || samples == 0) {
82 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid sample count value in audio message");
83 }
84
85 // Should end with newline or null terminator
86 if (*endptr != '\n' && *endptr != '\0') {
87 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid format: audio message should end with newline or null terminator");
88 }
89
90 *num_samples = (unsigned int)samples;
91 return ASCIICHAT_OK;
92}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ safe_parse_size_message()

asciichat_error_t safe_parse_size_message ( const char * message,
unsigned int * width,
unsigned int * height )

#include <include/ascii-chat/util/parsing.h>

Parse SIZE message format.

Parameters
messageInput message string (must not be NULL, format: "SIZE:width,height")
widthOutput parameter for parsed width (must not be NULL)
heightOutput parameter for parsed height (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses a SIZE protocol message in the format "SIZE:width,height" where width and height are unsigned integers. Validates the message format, parses numeric values, and checks for overflow conditions.

MESSAGE FORMAT:

  • Must start with "SIZE:"
  • Width and height separated by comma
  • Both values must be valid unsigned integers
  • No whitespace allowed in values
Note
Width and height are only modified on successful parsing.
Returns ASCIICHAT_ERROR_INVALID_ARGUMENT if format is invalid.
Returns ASCIICHAT_ERROR_OVERFLOW if numeric values exceed limits.
Example
unsigned int width, height;
if (safe_parse_size_message("SIZE:1920,1080", &width, &height) == ASCIICHAT_OK) {
// width = 1920, height = 1080
}
asciichat_error_t safe_parse_size_message(const char *message, unsigned int *width, unsigned int *height)
Parse SIZE message format.

Definition at line 17 of file util/parsing.c.

17 {
18 if (!message || !width || !height) {
19 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for size message parsing");
20 }
21
22 // Check if message starts with "SIZE:"
23 if (strncmp(message, "SIZE:", 5) != 0) {
24 return SET_ERRNO(ERROR_INVALID_PARAM, "Message does not start with 'SIZE:'");
25 }
26
27 const char *ptr = message + 5; // Skip "SIZE:"
28 char *endptr;
29
30 // Parse first number (width)
31 errno = 0;
32 unsigned long w = strtoul(ptr, &endptr, 10);
33 if (errno != 0 || endptr == ptr || w > UINT_MAX || w == 0) {
34 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid width value in size message");
35 }
36
37 // Check for comma separator
38 if (*endptr != ',') {
39 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing comma separator in size message");
40 }
41 ptr = endptr + 1;
42
43 // Parse second number (height)
44 errno = 0;
45 unsigned long h = strtoul(ptr, &endptr, 10);
46 if (errno != 0 || endptr == ptr || h > UINT_MAX || h == 0) {
47 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid height value in size message");
48 }
49
50 // Should end with newline or null terminator
51 if (*endptr != '\n' && *endptr != '\0') {
52 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid format: size message should end with newline or null terminator");
53 }
54
55 // Additional bounds checking
56 if (w > 65535 || h > 65535) {
57 return SET_ERRNO(ERROR_INVALID_PARAM, "Size values too large (max 65535)");
58 }
59
60 *width = (unsigned int)w;
61 *height = (unsigned int)h;
62 return ASCIICHAT_OK;
63}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, height, SET_ERRNO, and width.

◆ strip_ansi_codes()

void strip_ansi_codes ( const char * input,
char * output,
size_t output_size )

#include <include/ascii-chat/util/string.h>

Strip ANSI escape codes from a string.

Removes all ANSI escape sequences from the input string, suitable for displaying colored/styled text in environments that don't support ANSI codes (e.g., browser console, plain text output).

Handles patterns like:

  • \033[...m (color and style codes)
  • \033[0m (reset code)
  • \033[38;5;Nm (256-color codes)
  • \033[38;2;R;G;Bm (truecolor codes)
  • \033[2J, \033[H, etc. (cursor and screen control)
Parameters
inputInput string with ANSI codes (must not be NULL)
outputOutput buffer for cleaned string (must not be NULL)
output_sizeSize of output buffer (must be > 0)

EXAMPLE:

char input[] = "\\033[31mError\\033[0m"; // Red "Error" text
char output[256];
strip_ansi_codes(input, output, sizeof(output));
// output now contains "Error" without ANSI codes
void strip_ansi_codes(const char *input, char *output, size_t output_size)
Strip ANSI escape codes from a string.
Note
Output buffer must be large enough for input (worst case: same size).
Function truncates output if buffer is too small.
Safe for use with formatted log messages.

Definition at line 374 of file lib/util/string.c.

374 {
375 if (!input || !output || output_size == 0) {
376 return;
377 }
378
379 size_t out_idx = 0;
380 size_t in_idx = 0;
381
382 while (input[in_idx] != '\0' && out_idx < output_size - 1) {
383 // Check for ANSI escape sequence: ESC[
384 // Standard ANSI codes use escape character (0x1B or \033) followed by [
385 if (input[in_idx] == '\033' && input[in_idx + 1] == '[') {
386 in_idx += 2; // Skip \033[
387
388 // Skip until we find the terminating letter (m is most common, also H, J, K, etc.)
389 // This handles patterns like: 38;5;74m, 0m, 38;2;255;0;0m, 2J, H, etc.
390 while (input[in_idx] != '\0') {
391 if ((input[in_idx] >= 'A' && input[in_idx] <= 'Z') || (input[in_idx] >= 'a' && input[in_idx] <= 'z')) {
392 in_idx++; // Skip the terminating letter
393 break;
394 }
395 in_idx++;
396 }
397 } else {
398 // Regular character (including [ in normal text), copy to output
399 output[out_idx++] = input[in_idx++];
400 }
401 }
402
403 output[out_idx] = '\0';
404}

Referenced by platform_log_hook(), and session_display_write_ascii_frame().

◆ truncate_with_ellipsis()

void truncate_with_ellipsis ( const char * input,
char * output,
size_t output_size,
int max_width )

#include <include/ascii-chat/util/string.h>

Truncate a string to a maximum display width, with ellipsis.

Handles ANSI escape sequences (never cuts inside one), multi-byte UTF-8, and wide characters (CJK = 2 columns). If truncation is needed, appends a color reset (\033[0m) followed by "…" (Unicode ellipsis, 1 column).

Returns an empty string for nonpositive widths or when truncation is needed but the buffer cannot hold the suffix. Byte limits never split UTF-8 or CSI. Safe for strings with or without ANSI codes. For plain text the reset is harmless (terminals ignore redundant resets).

Parameters
inputInput string (may contain ANSI escape sequences and UTF-8)
outputOutput buffer for truncated string
output_sizeSize of output buffer (8 bytes needed for reset + ellipsis + NUL)
max_widthMaximum display width in columns

Definition at line 370 of file lib/util/string.c.

370 {
371 truncate_with_ellipsis_mode(input, output, output_size, max_width, utf8_output_enabled());
372}
void truncate_with_ellipsis_mode(const char *input, char *output, size_t output_size, int max_width, bool utf8)
Truncate a string to a maximum display width with a terminal-appropriate ellipsis.
bool utf8_output_enabled(void)
Return whether terminal output should use UTF-8 according to –utf8.
Definition utf8.c:22

References truncate_with_ellipsis_mode(), and utf8_output_enabled().

Referenced by ui_popup_frame_titled(), ui_popup_render(), and ui_status_render_header().

◆ truncate_with_ellipsis_mode()

void truncate_with_ellipsis_mode ( const char * input,
char * output,
size_t output_size,
int max_width,
bool utf8 )

#include <include/ascii-chat/util/string.h>

Truncate a string to a maximum display width with a terminal-appropriate ellipsis.

Behaves like truncate_with_ellipsis(), except utf8 selects the suffix: "…" for UTF-8 terminals or "..." for ASCII-only terminals. The suffix is included in max_width and ANSI reset handling is preserved.

Definition at line 334 of file lib/util/string.c.

334 {
335 if (!output || output_size == 0) {
336 return;
337 }
338 output[0] = '\0';
339 if (!input || max_width <= 0) {
340 return;
341 }
342
343 size_t input_size = strlen(input);
344 size_t byte_limit = input_size < output_size - 1 ? input_size : output_size - 1;
345 size_t copy = utf8_prefix_bytes_for_width(input, byte_limit, max_width);
346 if (copy == input_size) {
347 memcpy(output, input, copy);
348 output[copy] = '\0';
349 return;
350 }
351
352 // Reserve the complete reset, terminal-appropriate ellipsis, and terminator before copying content.
353 static const char utf8_suffix[] = "\033[0m…";
354 static const char ascii_suffix[] = "\033[0m...";
355 const char *suffix = utf8 ? utf8_suffix : ascii_suffix;
356 int suffix_width = utf8 ? 1 : 3;
357 size_t suffix_size = strlen(suffix) + 1;
358 if (output_size < suffix_size || max_width < suffix_width) {
359 return;
360 }
361 byte_limit = output_size - suffix_size;
362 if (byte_limit > input_size) {
363 byte_limit = input_size;
364 }
365 copy = utf8_prefix_bytes_for_width(input, byte_limit, max_width - suffix_width);
366 memcpy(output, input, copy);
367 memcpy(output + copy, suffix, suffix_size);
368}
size_t utf8_prefix_bytes_for_width(const char *str, size_t max_bytes, int max_width)
Return the byte length of a prefix fitting a terminal column limit.
Definition utf8.c:93

References utf8_prefix_bytes_for_width().

Referenced by truncate_with_ellipsis(), and ui_table_row().

◆ url_is_tcp()

bool url_is_tcp ( const char * url)

#include <include/ascii-chat/util/url.h>

Check if a URL string is a valid TCP URL.

Parameters
urlURL string to validate
Returns
True if URL is valid and has TCP scheme, false otherwise

Parses a URL and checks if it has a TCP scheme. This is the primary function for TCP URL validation - use this instead of manually calling url_parse() and url_is_tcp_scheme().

Example
if (url_is_tcp("tcp://example.com:5000")) {
// Safe to use as TCP URL
connection_attempt_tcp(&ctx, "tcp://example.com:5000");
} else if (url_is_valid(address)) {
// Use regular HTTP(S) transport
}
bool url_is_tcp(const char *url)
Check if a URL string is a valid TCP URL.
Definition url.c:360

Definition at line 360 of file url.c.

360 {
361 if (!url || !*url) {
362 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
363 return false;
364 }
365
366 /* Parse URL to validate and check scheme */
367 url_parts_t parts = {0};
368 asciichat_error_t result = url_parse(url, &parts);
369 bool is_tcp = (result == ASCIICHAT_OK && url_is_tcp_scheme(parts.scheme));
370 url_parts_destroy(&parts);
371
372 return is_tcp;
373}
bool url_is_tcp_scheme(const char *scheme)
Check if URL scheme is TCP.
Definition url.c:350

References ASCIICHAT_OK, ERROR_INVALID_PARAM, url_parts_t::scheme, SET_ERRNO, url_is_tcp_scheme(), url_parse(), and url_parts_destroy().

Referenced by connection_endpoint_resolve().

◆ url_is_tcp_scheme()

bool url_is_tcp_scheme ( const char * scheme)

#include <include/ascii-chat/util/url.h>

Check if URL scheme is TCP.

Parameters
schemeScheme string to check (case-insensitive)
Returns
True if scheme is "tcp", false otherwise

Utility function to determine if a parsed URL is a TCP URL.

Example
url_parts_t parts = {0};
if (url_parse("tcp://example.com:5000", &parts) == ASCIICHAT_OK) {
if (url_is_tcp_scheme(parts.scheme)) {
// Handle TCP connection
}
}

Definition at line 350 of file url.c.

350 {
351 if (!scheme || !*scheme) {
352 SET_ERRNO(ERROR_INVALID_PARAM, "scheme is NULL or empty");
353 return false;
354 }
355
356 /* Case-insensitive comparison for "tcp" */
357 return (strcasecmp(scheme, "tcp") == 0);
358}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by url_is_tcp().

◆ url_is_valid()

bool url_is_valid ( const char * url)

#include <include/ascii-chat/util/url.h>

URL validation using shared parsing and ICU hostname checks.

Parameters
urlInput URL string to validate
Returns
True if URL is valid, false otherwise

Validates with the same parser and IDNA checks used by url_parse(), then frees the extracted components.

URL ACCEPTANCE CRITERIA:

  • Scheme: http, https, ws, wss, or tcp (case-insensitive)
  • Host: Public IPv4, IPv6, localhost, FQDN, or bare hostname
  • Rejects: Private IPs (10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x)
  • Port: Optional, must be 1-65535 if present
  • Path: Optional, may include query and fragment
Example
if (url_is_valid("https://github.com/octocat")) {
// Safe to use URL
}

Definition at line 156 of file url.c.

156 {
157 url_parts_t parts = {0};
158 asciichat_error_t result = url_parse(url, &parts);
159 url_parts_destroy(&parts);
160 return result == ASCIICHAT_OK;
161}

References ASCIICHAT_OK, url_parse(), and url_parts_destroy().

Referenced by ffmpeg_decoder_create_with_request_options(), and parse_public_key().

◆ url_is_websocket()

bool url_is_websocket ( const char * url)

#include <include/ascii-chat/util/url.h>

Check if a URL string is a valid WebSocket URL.

Parameters
urlURL string to validate
Returns
True if URL is valid and has WebSocket scheme (ws or wss), false otherwise

Parses a URL and checks if it has a WebSocket scheme. This is the primary function for WebSocket URL validation - use this instead of manually calling url_parse() and url_is_websocket_scheme().

Example
if (url_is_websocket("wss://example.com:443")) {
// Safe to use as WebSocket URL
connection_attempt_websocket(&ctx, "wss://example.com:443");
} else if (url_is_valid(address)) {
// Use regular HTTP(S) transport
}
bool url_is_websocket(const char *url)
Check if a URL string is a valid WebSocket URL.
Definition url.c:325

Definition at line 325 of file url.c.

325 {
326 if (!url || !*url) {
327 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
328 return false;
329 }
330
331 /* Parse URL to validate and check scheme */
332 url_parts_t parts = {0};
333 asciichat_error_t result = url_parse(url, &parts);
334 bool is_ws = (result == ASCIICHAT_OK && url_is_websocket_scheme(parts.scheme));
335 url_parts_destroy(&parts);
336
337 return is_ws;
338}
bool url_is_websocket_scheme(const char *scheme)
Check if URL scheme is WebSocket (ws or wss).
Definition url.c:315

References ASCIICHAT_OK, ERROR_INVALID_PARAM, url_parts_t::scheme, SET_ERRNO, url_is_websocket_scheme(), url_parse(), and url_parts_destroy().

Referenced by client_main(), and connection_endpoint_resolve().

◆ url_is_websocket_scheme()

bool url_is_websocket_scheme ( const char * scheme)

#include <include/ascii-chat/util/url.h>

Check if URL scheme is WebSocket (ws or wss).

Parameters
schemeScheme string to check (case-insensitive)
Returns
True if scheme is "ws" or "wss", false otherwise

Utility function to determine if a parsed URL is a WebSocket URL.

Example
url_parts_t parts = {0};
if (url_parse("wss://example.com:443", &parts) == ASCIICHAT_OK) {
// Handle WebSocket connection
}
}

Definition at line 315 of file url.c.

315 {
316 if (!scheme || !*scheme) {
317 SET_ERRNO(ERROR_INVALID_PARAM, "scheme is NULL or empty");
318 return false;
319 }
320
321 /* Case-insensitive comparison for "ws" or "wss" */
322 return (strcasecmp(scheme, "ws") == 0 || strcasecmp(scheme, "wss") == 0);
323}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by url_is_websocket().

◆ url_looks_like_tcp()

bool url_looks_like_tcp ( const char * url)

#include <include/ascii-chat/util/url.h>

Quick check if a string is a TCP URL.

Parameters
urlString to check
Returns
True if string starts with tcp://, false otherwise

Fast check without full URL parsing. Useful for determining transport type.

Example
if (url_looks_like_tcp("tcp://example.com:5000")) {
// Use TCP transport
} else if (url_is_valid(address)) {
// Use regular HTTP(S) transport
}
bool url_looks_like_tcp(const char *url)
Quick check if a string is a TCP URL.
Definition url.c:375

Definition at line 375 of file url.c.

375 {
376 if (!url || !*url) {
377 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
378 return false;
379 }
380
381 /* Quick check for tcp:// prefix (case-insensitive) */
382 return (strncasecmp(url, "tcp://", 6) == 0);
383}

References ERROR_INVALID_PARAM, and SET_ERRNO.

◆ url_looks_like_websocket()

bool url_looks_like_websocket ( const char * url)

#include <include/ascii-chat/util/url.h>

Quick check if a string is a WebSocket URL.

Parameters
urlString to check
Returns
True if string starts with ws:// or wss://, false otherwise

Fast check without full URL parsing. Useful for determining transport type.

Example
if (url_looks_like_websocket("wss://example.com:443")) {
// Use WebSocket transport
} else if (url_is_valid(address)) {
// Use regular HTTP(S) transport
}
bool url_looks_like_websocket(const char *url)
Quick check if a string is a WebSocket URL.
Definition url.c:340

Definition at line 340 of file url.c.

340 {
341 if (!url || !*url) {
342 SET_ERRNO(ERROR_INVALID_PARAM, "url is NULL or empty");
343 return false;
344 }
345
346 /* Quick check for ws:// or wss:// prefix (case-insensitive) */
347 return (strncasecmp(url, "ws://", 5) == 0 || strncasecmp(url, "wss://", 6) == 0);
348}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by client_main().

◆ url_parse()

asciichat_error_t url_parse ( const char * url,
url_parts_t * parts_out )

#include <include/ascii-chat/util/url.h>

Parse HTTP(S), WebSocket, and TCP URL into components.

Parameters
urlInput URL string to parse
parts_outOutput structure for parsed components (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Validates and parses an HTTP(S), WebSocket, or TCP URL into its component parts using production-grade PCRE2 regex with JIT compilation.

URL ACCEPTANCE CRITERIA:

  • Scheme: http, https, ws, wss, or tcp (case-insensitive)
  • Host: Public IPv4, IPv6, localhost, FQDN, or bare hostname
  • Rejects: Private IPs (10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x)
  • Port: Optional, 1-65535
  • Path/Query/Fragment: Optional

EXTRACTED COMPONENTS:

  • scheme: "http", "https", "ws", "wss", or "tcp" (always present)
  • host: Hostname, IPv4, or IPv6 (always present)
  • port: Port number (0 if not specified)
  • userinfo: user:pass@ prefix (NULL if not present)
  • ipv6: IPv6 address (NULL unless host is bracketed IPv6)
  • path: Path, query, and fragment (NULL if not present)

MEMORY MANAGEMENT:

Note
Returns ERROR_INVALID_PARAM if URL format is invalid
Returns ERROR_MEMORY if allocation fails
Example
url_parts_t parts = {0};
if (url_parse("https://user:pass@example.com:8443/api/v1?key=val#section", &parts) == ASCIICHAT_OK) {
printf("Host: %s, Port: %d, Path: %s\\n", parts.host, parts.port, parts.path);
}

Definition at line 163 of file url.c.

163 {
164 if (!url || !*url) {
165 return SET_ERRNO(ERROR_INVALID_PARAM, "URL is NULL or empty");
166 }
167
168 if (!parts_out) {
169 return SET_ERRNO(ERROR_INVALID_PARAM, "parts_out is NULL");
170 }
171
172 /* Clear output structure */
173 memset(parts_out, 0, sizeof(*parts_out));
174
175 /* Check if URL needs http:// prefix (bare hostname or IP) */
176 char url_with_scheme[URL_BUFFER_SIZE];
177 const char *url_to_match = url;
178 const char *original_url = url;
179
180 if (!strstr(url, "://")) {
181 /* No scheme - check if it looks like a bare hostname/IP */
182 if (strchr(url, '@'))
183 return SET_ERRNO(ERROR_INVALID_PARAM, "Ambiguous email address without URL scheme");
184
185 /* Reject bare scheme words like "http", "https", "ftp" */
186 if (strcmp(url, "http") == 0 || strcmp(url, "https") == 0 || strcmp(url, "ftp") == 0 || strcmp(url, "ftps") == 0) {
187 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format: %s", url);
188 }
189
190 /* Reject URLs that look like malformed schemes (http/ instead of http://) */
191 if (strncmp(url, "http/", 5) == 0 || strncmp(url, "https/", 6) == 0) {
192 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format (looks like malformed scheme): %s", url);
193 }
194
195 /* Reject pure hex strings (raw keys, not hostnames) */
196 if (strlen(url) == 64) {
197 bool all_hex = true;
198 for (const char *p = url; *p && all_hex; p++) {
199 if (!((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F'))) {
200 all_hex = false;
201 }
202 }
203 if (all_hex) {
204 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL: appears to be raw hex data, not a URL");
205 }
206 }
207
208 const char *colon_pos = strchr(url, ':');
209 if (colon_pos) {
210 /* Has colon - check if what follows is numeric (port) */
211 const char *after_colon = colon_pos + 1;
212 bool looks_like_port = true;
213 for (const char *p = after_colon; *p && *p != '/'; p++) {
214 if (!(*p >= '0' && *p <= '9')) {
215 looks_like_port = false;
216 break;
217 }
218 }
219 if (!looks_like_port) {
220 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format (invalid scheme): %s", url);
221 }
222 }
223
224 /* Looks like a bare hostname/IP - prepend http:// */
225 int result = snprintf(url_with_scheme, sizeof(url_with_scheme), "http://%s", url);
226 if (result < 0 || result >= (int)sizeof(url_with_scheme)) {
227 return SET_ERRNO(ERROR_INVALID_PARAM, "URL too long");
228 }
229 url_to_match = url_with_scheme;
230 }
231
232 int compile_error;
233 PCRE2_SIZE error_offset;
234 pcre2_code *regex = pcre2_compile((PCRE2_SPTR)URL_REGEX_PATTERN, PCRE2_ZERO_TERMINATED, PCRE2_CASELESS | PCRE2_UCP | PCRE2_UTF, &compile_error, &error_offset, NULL);
235 if (!regex) {
236 return SET_ERRNO(ERROR_CONFIG, "URL validator compilation failed at offset %zu (PCRE2 error %d)", (size_t)error_offset, compile_error);
237 }
238
239 pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(regex, NULL);
240 if (!match_data) {
241 pcre2_code_free(regex);
242 return SET_ERRNO(ERROR_MEMORY, "Failed to create match data");
243 }
244
245 /* Match using the interpreted pattern. */
246 int rc = asciichat_pcre2_match(regex, (PCRE2_SPTR)url_to_match, strlen(url_to_match), 0, /* startoffset */
247 0, /* options */
248 match_data, NULL); /* mcontext */
249
250 if (rc < 0) {
251 pcre2_match_data_free(match_data);
252 pcre2_code_free(regex);
253 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid URL format: %s", original_url);
254 }
255
256 /* Extract named groups */
257 parts_out->scheme = asciichat_pcre2_extract_named_group(regex, match_data, "scheme", url_to_match);
258 parts_out->userinfo = asciichat_pcre2_extract_named_group(regex, match_data, "userinfo", url_to_match);
259 parts_out->host = asciichat_pcre2_extract_named_group(regex, match_data, "host", url_to_match);
260 parts_out->ipv6 = asciichat_pcre2_extract_named_group(regex, match_data, "ipv6", url_to_match);
261 parts_out->path = asciichat_pcre2_extract_named_group(regex, match_data, "path_query_fragment", url_to_match);
262
263 /* Extract port number */
264 parts_out->port = 0;
265 char *port_str = asciichat_pcre2_extract_named_group(regex, match_data, "port", url_to_match);
266 if (port_str) {
267 parts_out->port = (int)strtol(port_str, NULL, 10);
268 SAFE_FREE(port_str);
269 if (parts_out->port <= 0 || parts_out->port > UINT16_MAX) {
270 pcre2_match_data_free(match_data);
271 pcre2_code_free(regex);
272 url_parts_destroy(parts_out);
273 return SET_ERRNO(ERROR_INVALID_PARAM, "URL port must be in the range 1-65535");
274 }
275 }
276
277 pcre2_match_data_free(match_data);
278 pcre2_code_free(regex);
279
280 /* Verify we got required fields */
281 if (!parts_out->scheme || !parts_out->host) {
282 url_parts_destroy(parts_out);
283 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing required URL components");
284 }
285
286 if (!parts_out->ipv6) {
287 char ascii[HOSTNAME_BUFFER_SIZE];
288 asciichat_error_t result = hostname_to_ascii(parts_out->host, ascii, sizeof(ascii));
289 if (result != ASCIICHAT_OK) {
290 url_parts_destroy(parts_out);
291 return result;
292 }
293 SAFE_FREE(parts_out->host);
294 SAFE_STRDUP(parts_out->host, ascii);
295 }
296 return ASCIICHAT_OK;
297}
#define SAFE_STRDUP(dst, src)
@ ERROR_CONFIG
Definition error_codes.h:56
int asciichat_pcre2_match(const pcre2_code *code, PCRE2_SPTR subject, PCRE2_SIZE length, PCRE2_SIZE startoffset, uint32_t options, pcre2_match_data *match_data, pcre2_match_context *context)
Definition pcre2.c:161
char * asciichat_pcre2_extract_named_group(pcre2_code *regex, pcre2_match_data *match_data, const char *group_name, const char *subject)
Extract named substring from PCRE2 match data.
Definition pcre2.c:34
char * userinfo
Optional userinfo (user:pass) - may be NULL (allocated if present).
Definition url.h:71
char * ipv6
IPv6 address if host is bracketed IPv6 - may be NULL (allocated if present).
Definition url.h:73

References ASCIICHAT_OK, asciichat_pcre2_extract_named_group(), asciichat_pcre2_match(), ERROR_CONFIG, ERROR_INVALID_PARAM, ERROR_MEMORY, url_parts_t::host, HOSTNAME_BUFFER_SIZE, hostname_to_ascii(), url_parts_t::ipv6, url_parts_t::path, url_parts_t::port, SAFE_FREE, SAFE_STRDUP, url_parts_t::scheme, SET_ERRNO, URL_BUFFER_SIZE, url_parts_destroy(), and url_parts_t::userinfo.

Referenced by connection_endpoint_override_port(), connection_endpoint_resolve(), parse_public_key(), url_is_tcp(), url_is_valid(), and url_is_websocket().

◆ url_parts_destroy()

void url_parts_destroy ( url_parts_t * parts)

#include <include/ascii-chat/util/url.h>

Free parsed URL components.

Parameters
partsPointer to url_parts_t structure to free

Safely frees all allocated string fields in a url_parts_t structure. Safe to call multiple times on same structure.

Example
url_parts_t parts = {0};
url_parse("https://example.com", &parts);
// Use parts...
// All internal strings are freed, parts is zeroed

Definition at line 299 of file url.c.

299 {
300 if (!parts) {
301 SET_ERRNO(ERROR_INVALID_PARAM, "parts is NULL");
302 return;
303 }
304
305 SAFE_FREE(parts->scheme);
306 SAFE_FREE(parts->userinfo);
307 SAFE_FREE(parts->host);
308 SAFE_FREE(parts->ipv6);
309 SAFE_FREE(parts->path);
310 parts->port = 0;
311
312 memset(parts, 0, sizeof(*parts));
313}

References ERROR_INVALID_PARAM, url_parts_t::host, url_parts_t::ipv6, url_parts_t::path, url_parts_t::port, SAFE_FREE, url_parts_t::scheme, SET_ERRNO, and url_parts_t::userinfo.

Referenced by connection_endpoint_override_port(), connection_endpoint_resolve(), parse_public_key(), url_is_tcp(), url_is_valid(), url_is_websocket(), and url_parse().

◆ url_redact_diagnostic()

void url_redact_diagnostic ( char * text,
bool truncated )

#include <include/ascii-chat/util/url.h>

Redact URL userinfo and query/fragment values in diagnostic text, in place. Set truncated when the text may end partway through a URL authority.

Definition at line 31 of file url.c.

31 {
32 if (!text)
33 return;
34 char *search = text;
35 while ((search = strstr(search, "://"))) {
36 char *authority = search + 3;
37 char *end = authority;
38 char *at = NULL;
39 while (!diagnostic_url_end(*end) && *end != '/' && *end != '?' && *end != '#') {
40 if (*end == '@')
41 at = end;
42 ++end;
43 }
44 // A truncated authority may end before its '@'; do not export a partial
45 // userinfo value when the caller's diagnostic buffer was cut short.
46 if (at)
47 memset(authority, '*', (size_t)(at - authority));
48 else if (truncated && !*end)
49 memset(authority, '*', (size_t)(end - authority));
50 char *url_end = end;
51 char *query = NULL;
52 while (!diagnostic_url_end(*url_end)) {
53 if (!query && (*url_end == '?' || *url_end == '#'))
54 query = url_end;
55 ++url_end;
56 }
57 if (query)
58 memset(query + 1, '*', (size_t)(url_end - query - 1));
59 search = url_end;
60 }
61}

Referenced by ascii_otel_error(), ascii_otel_error_code(), and ascii_otel_log().

◆ utf8_char_count()

size_t utf8_char_count ( const char * str)

#include <include/ascii-chat/util/utf8.h>

Count UTF-8 characters (not bytes).

Parameters
strString to count (must not be NULL)
Returns
Number of UTF-8 characters, or SIZE_MAX if invalid UTF-8 detected

Counts the number of Unicode codepoints in the string, not byte count. Properly handles multi-byte UTF-8 sequences (1-4 bytes per character).

Returns SIZE_MAX if the string contains invalid UTF-8 sequences.

Note
Empty string has 0 characters
Returns SIZE_MAX for NULL input or invalid UTF-8
Slower than strlen() but necessary for correct UTF-8 processing
Used by Levenshtein distance and other algorithms needing character counts
Example
// Check if password is long enough (in characters, not bytes)
size_t pwd_len = utf8_char_count(password);
if (pwd_len == SIZE_MAX) {
log_error("Password contains invalid UTF-8");
return false;
}
if (pwd_len < 8) {
return false; // Too short
}
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
size_t utf8_char_count(const char *str)
Count UTF-8 characters (not bytes).
Definition utf8.c:108

Definition at line 108 of file utf8.c.

108 {
109 if (!str) {
110 SET_ERRNO(ERROR_INVALID_PARAM, "str is NULL");
111 return SIZE_MAX;
112 }
113
114 size_t count = 0;
115 const uint8_t *p = (const uint8_t *)str;
116 while (*p) {
117 uint32_t codepoint;
118 int decode_len = utf8_decode(p, &codepoint);
119 if (decode_len < 0) {
120 return SIZE_MAX; // Invalid UTF-8
121 }
122 count++;
123 p += decode_len;
124 }
125 return count;
126}

References ERROR_INVALID_PARAM, SET_ERRNO, and utf8_decode().

Referenced by levenshtein(), mirror_convert_frame(), and utf8_is_valid().

◆ utf8_decode()

int utf8_decode ( const uint8_t * s,
uint32_t * codepoint )

#include <include/ascii-chat/util/utf8.h>

Decode a UTF-8 sequence to a Unicode codepoint.

Parameters
sPointer to UTF-8 byte sequence (must not be NULL)
codepointOutput parameter for decoded codepoint (must not be NULL)
Returns
Number of bytes consumed (1-4), or -1 if invalid sequence

Decodes a UTF-8 byte sequence starting at s to a Unicode codepoint. Validates the UTF-8 encoding during decoding and returns the number of bytes consumed. Returns -1 if the sequence is invalid (overlong encoding, invalid bytes, etc.).

Note
Input pointer must point to the start of a valid UTF-8 sequence.
Output codepoint is set even if sequence is invalid (check return value).
Function does not advance the pointer - caller must advance by return value.
Return value of -1 indicates invalid UTF-8 sequence.
Example
const uint8_t *str = (uint8_t*)"Hello 世界";
int len;
// Decode 'H' (1 byte)
len = utf8_decode(str, &cp); // Returns 1, cp = 'H'
str += len;
// Decode '世' (3 bytes)
len = utf8_decode(str, &cp); // Returns 3, cp = U+4E16
str += len;

Definition at line 27 of file utf8.c.

27 {
28 utf8proc_int32_t decoded;
29 utf8proc_ssize_t count = utf8proc_iterate(s, -1, &decoded);
30 if (count < 0)
31 return -1;
32 *codepoint = (uint32_t)decoded;
33 return (int)count;
34}

Referenced by digital_rain_render_at(), log_search_get_match_info(), utf8_char_count(), utf8_to_codepoints(), and visualization_encode().

◆ utf8_display_width()

int utf8_display_width ( const char * str)

#include <include/ascii-chat/util/utf8.h>

Calculate terminal display width of a UTF-8 string.

Parameters
strUTF-8 string (must not be NULL)
Returns
Display width in terminal columns (0 on empty or invalid input)

Converts UTF-8 byte sequences to Unicode codepoints and calculates the terminal display width using utf8proc_charwidth(). Properly handles:

  • Multi-byte UTF-8 sequences (1-4 bytes per character)
  • Wide characters (CJK, emoji - typically 2 columns)
  • Control characters and combining marks (0 width)
  • Invalid UTF-8 sequences (stops processing)

Terminal display width differs from byte count:

  • ASCII 'A' = 1 byte = 1 column
  • 'é' (é) = 2 bytes = 1 column
  • '中' (CJK) = 3 bytes = 2 columns
  • '😀' (emoji) = 4 bytes = 2 columns
Note
Uses utf8proc library for accurate Unicode character-width computation
Returns 0 for NULL or empty string
Invalid UTF-8 sequences stop processing (partial width returned)
Example
int width = utf8_display_width("Hello"); // Returns 5 (5 ASCII chars)
int width = utf8_display_width("Café"); // Returns 4 (é is 1 column)
int width = utf8_display_width("中国"); // Returns 4 (2 CJK chars × 2 columns)
int width = utf8_display_width("😀"); // Returns 2 (emoji is 2 columns)

Definition at line 98 of file utf8.c.

98 {
99 return utf8_display_width_n(str, str ? strlen(str) : 0);
100}
int utf8_display_width_n(const char *str, size_t max_bytes)
Calculate terminal display width of a UTF-8 string up to byte limit.
Definition utf8.c:102

References utf8_display_width_n().

Referenced by display_height(), display_width(), layout_print_two_column_row(), mirror_convert_frame(), ui_sync_render(), and validate_palette_chars().

◆ utf8_display_width_n()

int utf8_display_width_n ( const char * str,
size_t max_bytes )

#include <include/ascii-chat/util/utf8.h>

Calculate terminal display width of a UTF-8 string up to byte limit.

Parameters
strUTF-8 string (must not be NULL)
max_bytesMaximum bytes to process
Returns
Display width in terminal columns

Like utf8_display_width() but stops after processing max_bytes bytes. Useful for calculating display width of substrings or with length-limited buffers.

Note
Stops processing at max_bytes boundary or null terminator, whichever comes first
Invalid UTF-8 sequences stop processing (partial width returned)
Uses utf8proc library for accurate Unicode character-width computation
Example
const char *str = "Hello World";
int width = utf8_display_width_n(str, 5); // Returns 5 (width of "Hello")

Definition at line 102 of file utf8.c.

102 {
103 int width;
104 utf8_prefix_scan(str, max_bytes, INT_MAX, &width);
105 return width;
106}

References width.

Referenced by ascii_create_grid(), key_identity_art_end(), ui_input_render(), ui_media_panel_render(), ui_notice_render(), ui_sync_render(), ui_text_cell(), utf8_display_width(), and utf8_palette_create().

◆ utf8_is_ascii_only()

bool utf8_is_ascii_only ( const char * str)

#include <include/ascii-chat/util/utf8.h>

Check if a string contains only ASCII characters.

Parameters
strString to check (must not be NULL)
Returns
true if all characters are ASCII (0x00-0x7F), false if any non-ASCII found

Validates UTF-8 encoding and checks that all decoded codepoints are ASCII. Useful for security-sensitive strings that should only contain ASCII (e.g., session identifiers to prevent homograph attacks).

Returns false if string contains invalid UTF-8 sequences.

Note
Empty string is considered ASCII-only (returns true)
Returns false for NULL input (not validated)
Prevents homograph attack vector (e.g., Cyrillic 'а' vs ASCII 'a')
Example
// Verify session string contains only ASCII to prevent homograph spoofing
if (!utf8_is_ascii_only(session_string)) {
log_warn("Session string contains non-ASCII characters");
return false;
}
bool utf8_is_ascii_only(const char *str)
Check if a string contains only ASCII characters.
Definition utf8.c:137

Definition at line 137 of file utf8.c.

137 {
138 if (!str) {
139 SET_ERRNO(ERROR_INVALID_PARAM, "str is NULL");
140 return false;
141 }
142
143 // Fast path: Check if all bytes are in ASCII range (0x00-0x7F)
144 // ASCII characters are 0x00-0x7F (single byte, high bit clear)
145 // Multi-byte UTF-8 has continuation bytes with high bit set (10xxxxxx pattern)
146 // So if all bytes have high bit clear, it's guaranteed ASCII-only
147 const unsigned char *p = (const unsigned char *)str;
148 while (*p) {
149 if ((*p & ~0x7F) != 0) {
150 return false; // Non-ASCII byte found (high bit set)
151 }
152 p++;
153 }
154 return true;
155}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by is_session_string().

◆ utf8_is_valid()

bool utf8_is_valid ( const char * str)

#include <include/ascii-chat/util/utf8.h>

Check if a string is valid UTF-8.

Parameters
strString to validate (must not be NULL)
Returns
true if valid UTF-8, false if invalid sequences detected

Scans the entire string and validates that all byte sequences conform to UTF-8 encoding rules. Returns false immediately on first invalid sequence.

Note
Returns true for empty string (valid)
Returns false for NULL input (not validated)
More efficient than decoding all codepoints if only validation is needed
Example
if (!utf8_is_valid(user_input)) {
log_error("Invalid UTF-8 in user input");
return false;
}

Definition at line 128 of file utf8.c.

128 {
129 if (!str) {
130 SET_ERRNO(ERROR_INVALID_PARAM, "str is NULL");
131 return false;
132 }
133 // Reuse utf8_char_count to validate without duplicating loop
134 return utf8_char_count(str) != SIZE_MAX;
135}

References ERROR_INVALID_PARAM, SET_ERRNO, and utf8_char_count().

Referenced by media_input_normalize(), prompt_password(), prompt_password_simple_kind(), ui_input_edit_key(), ui_input_insert(), ui_input_media_begin(), ui_input_read_key(), ui_input_render(), ui_input_take_paste(), validate_private_key(), and validate_public_key().

◆ utf8_next_char_bytes()

int utf8_next_char_bytes ( const char * str,
size_t max_bytes )

#include <include/ascii-chat/util/utf8.h>

Get byte length of next UTF-8 character.

Parameters
strPointer to UTF-8 byte sequence (must not be NULL)
max_bytesMaximum bytes to read from str
Returns
Number of bytes in next character (1-4), or -1 if invalid UTF-8

Determines how many bytes are needed for the next complete UTF-8 character. Uses utf8proc for robust UTF-8 handling.

Useful for interactive text input where you need to handle multi-byte UTF-8 characters character-by-character (e.g., password prompts).

Note
Returns -1 for invalid UTF-8 sequences or if end of string reached
Requires utf8proc library which is already a project dependency
Example
// Handle multi-byte UTF-8 in password input
const char *input = "café";
int bytes_in_char = utf8_next_char_bytes(input, strlen(input));
// Returns 1 for 'c', 1 for 'a', 1 for 'f', 2 for 'é'
int utf8_next_char_bytes(const char *str, size_t max_bytes)
Get byte length of next UTF-8 character.
Definition utf8.c:177

Definition at line 177 of file utf8.c.

177 {
178 if (!str || max_bytes == 0) {
179 SET_ERRNO(ERROR_INVALID_PARAM, "str is NULL or max_bytes is 0");
180 return -1;
181 }
182
183 // Use utf8proc_iterate to get byte length of next character
184 utf8proc_int32_t codepoint;
185 utf8proc_ssize_t len = utf8proc_iterate((const utf8proc_uint8_t *)str, (utf8proc_ssize_t)max_bytes, &codepoint);
186
187 if (len <= 0) {
188 return -1; // Invalid UTF-8 or end of string
189 }
190
191 return (int)len;
192}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by layout_print_wrapped_description(), ui_input_edit_key(), ui_input_render(), ui_notice_render(), ui_sync_render(), ui_text_cell(), and ui_text_values_style().

◆ utf8_output_enabled()

bool utf8_output_enabled ( void )

#include <include/ascii-chat/util/utf8.h>

Return whether terminal output should use UTF-8 according to –utf8.

A forced setting wins; automatic mode uses terminal capability detection. Use this for output glyph selection rather than terminal_supports_utf8() when the user's UTF-8 preference must be honored.

Definition at line 22 of file utf8.c.

22 {
23 utf8_setting_t setting = GET_OPTION(force_utf8);
24 return setting == UTF8_SETTING_TRUE || (setting == UTF8_SETTING_AUTO && terminal_supports_utf8());
25}
utf8_setting_t
UTF-8 support setting (–utf8 flag values).
Definition options.h:263
@ UTF8_SETTING_AUTO
Smart detection (default): UTF-8 if terminal supports it.
Definition options.h:265
@ UTF8_SETTING_TRUE
Force UTF-8 ON: always use UTF-8 regardless of terminal capability.
Definition options.h:267
bool terminal_supports_utf8(void)

References GET_OPTION, terminal_supports_utf8(), UTF8_SETTING_AUTO, and UTF8_SETTING_TRUE.

Referenced by truncate_with_ellipsis().

◆ utf8_strcasestr()

const char * utf8_strcasestr ( const char * haystack,
const char * needle )

#include <include/ascii-chat/util/utf8.h>

Case-insensitive substring search with full Unicode support.

Parameters
haystackString to search in (must not be NULL)
needleSubstring to search for (must not be NULL)
Returns
Pointer to first occurrence of needle in haystack, or NULL if not found

Performs case-insensitive substring search using Unicode case folding. Properly handles all Unicode characters including accented letters, Greek, Cyrillic, CJK, emoji, and other scripts.

Uses utf8proc library for accurate Unicode case folding according to Unicode standard. This ensures correct matching for:

  • ASCII: "TEST" matches "test"
  • Accented: "CAFÉ" matches "café"
  • Greek: "ΕΛΛΗΝΙΚΆ" matches "ελληνικά"
  • Cyrillic: "РУССКИЙ" matches "русский"
Note
Returns NULL if needle is empty string
Returns haystack if needle is empty
Case folding follows Unicode standard (more complex than simple toupper/tolower)
Uses utf8proc for accurate Unicode handling
Example
const char *found = utf8_strcasestr("Hello WORLD", "world");
// Returns pointer to "WORLD" in the haystack
const char *found2 = utf8_strcasestr("Café français", "FRANÇAIS");
// Returns pointer to "français" (case-insensitive + accents)
const char * utf8_strcasestr(const char *haystack, const char *needle)
Case-insensitive substring search with full Unicode support.
Definition utf8.c:205

Uses utf8proc for Unicode case folding according to Unicode standard. This properly handles all Unicode scripts including Greek, Cyrillic, accented characters, and more.

Definition at line 205 of file utf8.c.

205 {
206 if (!haystack || !needle) {
207 SET_ERRNO(ERROR_INVALID_PARAM, "invalid params");
208 return NULL;
209 }
210
211 // Empty needle matches at start of haystack
212 if (needle[0] == '\0') {
213 return haystack;
214 }
215
216 // Get lengths
217 size_t haystack_len = strlen(haystack);
218 size_t needle_len = strlen(needle);
219
220 if (needle_len > haystack_len) {
221 return NULL;
222 }
223
224 // Case-fold both strings using utf8proc
225 // UTF8PROC_CASEFOLD performs Unicode case folding
226 // UTF8PROC_STABLE ensures stable output
227 // UTF8PROC_COMPOSE normalizes composed characters
228 utf8proc_option_t options = UTF8PROC_CASEFOLD | UTF8PROC_STABLE | UTF8PROC_COMPOSE;
229
230 // Case-fold the needle (pattern to search for)
231 utf8proc_uint8_t *needle_folded = NULL;
232 utf8proc_ssize_t needle_folded_len = utf8proc_map((const utf8proc_uint8_t *)needle, (utf8proc_ssize_t)needle_len, &needle_folded, options);
233
234 if (needle_folded_len < 0 || !needle_folded) {
235 // Invalid UTF-8 in needle
236 if (needle_folded) {
237 free(needle_folded);
238 }
239 return NULL;
240 }
241
242 // Try each position in haystack
243 const char *haystack_pos = haystack;
244 while (*haystack_pos != '\0') {
245 // Calculate remaining haystack length
246 size_t remaining = haystack_len - (size_t)(haystack_pos - haystack);
247
248 if (remaining < needle_len) {
249 // Not enough characters left to match
250 break;
251 }
252
253 // Case-fold the current haystack window
254 utf8proc_uint8_t *haystack_folded = NULL;
255 utf8proc_ssize_t haystack_folded_len = utf8proc_map((const utf8proc_uint8_t *)haystack_pos, (utf8proc_ssize_t)needle_len, &haystack_folded, options);
256
257 if (haystack_folded_len >= 0 && haystack_folded) {
258 // Compare case-folded strings
259 if ((size_t)haystack_folded_len == (size_t)needle_folded_len && memcmp(haystack_folded, needle_folded, (size_t)needle_folded_len) == 0) {
260 // Match found!
261 free(haystack_folded);
262 free(needle_folded);
263 return haystack_pos;
264 }
265 free(haystack_folded);
266 }
267
268 // Move to next UTF-8 character in haystack
269 utf8proc_int32_t codepoint;
270 utf8proc_ssize_t bytes = utf8proc_iterate((const utf8proc_uint8_t *)haystack_pos, -1, &codepoint);
271 if (bytes <= 0) {
272 // Invalid UTF-8, move by one byte
273 haystack_pos++;
274 } else {
275 haystack_pos += bytes;
276 }
277 }
278
279 free(needle_folded);
280 return NULL;
281}

References ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by grep_highlight_colored(), grep_should_output(), log_search_filter_buffer(), and log_search_get_match_info().

◆ utf8_to_codepoints()

size_t utf8_to_codepoints ( const char * str,
uint32_t * out_codepoints,
size_t max_codepoints )

#include <include/ascii-chat/util/utf8.h>

Convert UTF-8 string to array of Unicode codepoints.

Parameters
strUTF-8 string to convert (must not be NULL)
out_codepointsOutput array for decoded codepoints (must not be NULL)
max_codepointsMaximum number of codepoints to decode
Returns
Number of codepoints decoded, or SIZE_MAX if invalid UTF-8 detected

Decodes a UTF-8 string into an array of Unicode codepoints (32-bit values). Stops when reaching end of string, hitting max_codepoints limit, or detecting invalid UTF-8.

Returns SIZE_MAX if invalid UTF-8 sequences are encountered during decoding.

Note
Returns 0 if str is NULL, out_codepoints is NULL, or max_codepoints is 0
Used by fuzzy matching (Levenshtein), Unicode algorithms, and validation
More efficient than calling utf8_decode multiple times in a loop
Example
// Compare two strings at codepoint level
uint32_t str1_codepoints[256];
uint32_t str2_codepoints[256];
size_t count1 = utf8_to_codepoints("café", str1_codepoints, 256);
size_t count2 = utf8_to_codepoints("cafe", str2_codepoints, 256);
if (count1 == SIZE_MAX || count2 == SIZE_MAX) {
return false; // Invalid UTF-8
}
// Now compare at codepoint level instead of bytes
for (size_t i = 0; i < count1 && i < count2; i++) {
if (str1_codepoints[i] != str2_codepoints[i]) {
// Different codepoint
}
}
size_t utf8_to_codepoints(const char *str, uint32_t *out_codepoints, size_t max_codepoints)
Convert UTF-8 string to array of Unicode codepoints.
Definition utf8.c:157

Definition at line 157 of file utf8.c.

157 {
158 if (!str || !out_codepoints || max_codepoints == 0) {
159 SET_ERRNO(ERROR_INVALID_PARAM, "str is NULL or out_codepoints is NULL or max_codepoints is 0");
160 return 0;
161 }
162
163 size_t count = 0;
164 const uint8_t *p = (const uint8_t *)str;
165 while (*p && count < max_codepoints) {
166 uint32_t codepoint;
167 int decode_len = utf8_decode(p, &codepoint);
168 if (decode_len < 0) {
169 return SIZE_MAX; // Invalid UTF-8
170 }
171 out_codepoints[count++] = codepoint;
172 p += decode_len;
173 }
174 return count;
175}

References ERROR_INVALID_PARAM, SET_ERRNO, and utf8_decode().

Referenced by levenshtein(), and validate_palette_chars().

◆ utf8_write_lowercase()

void utf8_write_lowercase ( FILE * output,
const char * text )

#include <include/ascii-chat/util/utf8.h>

Write UTF-8 string to file with ASCII lowercase conversion.

Parameters
outputFile pointer to write to (must not be NULL)
textUTF-8 string to convert and write (may be NULL)

Writes text to output file, converting ASCII uppercase letters (A-Z) to lowercase (a-z) while preserving all UTF-8 multi-byte sequences unchanged. This is UTF-8 aware and does not modify non-ASCII characters.

Useful for terminal output where uppercase letters should be displayed as lowercase while preserving Unicode characters like emoji and accented letters.

Note
If text is NULL, function returns immediately without writing anything
Multi-byte UTF-8 sequences (e.g., emoji, CJK characters) are copied unchanged
Only ASCII uppercase (A-Z) is converted to lowercase (a-z)
Continuation bytes in multi-byte sequences are never modified
Example
FILE *fp = fopen("output.txt", "w");
// ASCII text: converts uppercase
utf8_write_lowercase(fp, "HELLO World"); // Writes "hello world"
// UTF-8 emoji and non-ASCII: preserved
utf8_write_lowercase(fp, "CAFÉ 😀"); // Writes "café 😀" (emoji unchanged)
// Mixed case with non-ASCII
utf8_write_lowercase(fp, "HELLO 世界"); // Writes "hello 世界" (CJK unchanged)
fclose(fp);
void utf8_write_lowercase(FILE *output, const char *text)
Write UTF-8 string to file with ASCII lowercase conversion.
Definition utf8.c:290

Converts ASCII uppercase to lowercase while preserving all UTF-8 multi-byte sequences unchanged. This ensures proper handling of emoji and non-ASCII characters while still performing ASCII case conversion.

Definition at line 290 of file utf8.c.

290 {
291 if (!text) {
292 return;
293 }
294
295 for (const unsigned char *p = (const unsigned char *)text; *p; p++) {
296 // Check if this is the start of a multi-byte UTF-8 sequence
297 if (*p >= 0xC0) {
298 // Multi-byte UTF-8 character - copy as-is without modification
299 fputc(*p, output);
300 // Copy continuation bytes (0x80-0xBF)
301 while (p[1] >= 0x80 && p[1] < 0xC0) {
302 fputc(*++p, output);
303 }
304 } else if (*p >= 'A' && *p <= 'Z') {
305 // ASCII uppercase - convert to lowercase
306 fputc(*p + 32, output);
307 } else {
308 // ASCII lowercase or control character - copy as-is
309 fputc(*p, output);
310 }
311 }
312}