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

Session string generation and validation implementation. More...

Go to the source code of this file.

Data Structures

struct  word_cache_entry_t
 One owned word in the adjective or noun validation hash table. More...

Macros

#define DISCOVERY_STRINGS_ADJ_BUFFER_SIZE   32
#define DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE   32
#define DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE   32
#define PCRE2_CODE_UNIT_WIDTH   8

Functions

void acds_strings_destroy (void)
 Cleanup function for session string cache Called by asciichat_shared_destroy() during library cleanup. Safe to call multiple times (idempotent).
asciichat_error_t acds_string_init (void)
 Initialize session string system with cached word validation.
asciichat_error_t acds_string_generate (char *output, size_t output_size)
 Generate random session string.
bool is_session_string (const char *str)
 Check if a string is a valid session string.

Detailed Description

Session string generation and validation implementation.

This module generates memorable session strings in the format: adjective-noun-noun (e.g., "swift-river-mountain")

It maintains cached hashtables of adjectives and nouns for fast O(1) validation, ensuring session strings only contain real words.

Definition in file discovery/strings.c.

Macro Definition Documentation

◆ DISCOVERY_STRINGS_ADJ_BUFFER_SIZE

#define DISCOVERY_STRINGS_ADJ_BUFFER_SIZE   32

Definition at line 13 of file discovery/strings.c.

Referenced by is_session_string().

◆ DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE

#define DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE   32

Definition at line 14 of file discovery/strings.c.

Referenced by is_session_string().

◆ DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE

#define DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE   32

Definition at line 15 of file discovery/strings.c.

Referenced by is_session_string().

◆ PCRE2_CODE_UNIT_WIDTH

#define PCRE2_CODE_UNIT_WIDTH   8

Definition at line 26 of file discovery/strings.c.

Function Documentation

◆ acds_string_generate()

asciichat_error_t acds_string_generate ( char * output,
size_t output_size )

Generate random session string.

Parameters
outputOutput buffer for session string
output_sizeSize of output buffer (should be at least SESSION_STRING_BUFFER_SIZE bytes)
Returns
ASCIICHAT_OK on success, error code otherwise

Generates strings in format: adjective-noun-noun Example: "affectionate-acquaintance-acquaintance" (38 characters max)

Use acds_string_get_max_length() to get the maximum possible length. Entropy: 2500 adjectives * 5000 nouns * 5000 nouns = 62.5 billion combinations

Definition at line 233 of file discovery/strings.c.

233 {
234 if (!output || output_size < SESSION_STRING_BUFFER_SIZE) {
235 return SET_ERRNO(ERROR_INVALID_PARAM, "output buffer must be at least %zu bytes", (size_t)SESSION_STRING_BUFFER_SIZE);
236 }
237
238 // libsodium is guaranteed to be initialized by acds_string_init() before this is called
239 // No need to call sodium_init() again (redundant initialization removed)
240
241 // Pick random adjective
242 uint32_t adj_idx = randombytes_uniform((uint32_t)adjectives_count);
243 const char *adj = adjectives[adj_idx];
244
245 // Pick two random nouns
246 uint32_t noun1_idx = randombytes_uniform((uint32_t)nouns_count);
247 uint32_t noun2_idx = randombytes_uniform((uint32_t)nouns_count);
248 const char *noun1 = nouns[noun1_idx];
249 const char *noun2 = nouns[noun2_idx];
250
251 // Format: adjective-noun-noun
252 int written = safe_snprintf(output, output_size, "%s-%s-%s", adj, noun1, noun2);
253 if (written < 0 || (size_t)written >= output_size) {
254 return SET_ERRNO(ERROR_BUFFER_OVERFLOW, "Session string too long for buffer");
255 }
256
257 log_dev("Generated session string: %s", output);
258 return ASCIICHAT_OK;
259}
const char * adjectives[]
Array of English adjectives for ACDS session naming.
Definition adjectives.c:51
const size_t adjectives_count
Count of adjectives in the adjectives array.
Definition adjectives.c:262
#define SET_ERRNO(code,...)
unsigned int uint32_t
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_BUFFER_OVERFLOW
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
const char * nouns[]
Array of English nouns for session and client naming.
Definition nouns.c:55
const size_t nouns_count
Count of nouns in the nouns array.
Definition nouns.c:474
#define SESSION_STRING_BUFFER_SIZE

References adjectives, adjectives_count, ASCIICHAT_OK, ERROR_BUFFER_OVERFLOW, ERROR_INVALID_PARAM, log_dev, nouns, nouns_count, SESSION_STRING_BUFFER_SIZE, and SET_ERRNO.

Referenced by options_preset_unified().

◆ acds_string_init()

asciichat_error_t acds_string_init ( void )

Initialize session string system with cached word validation.

Returns
ASCIICHAT_OK on success, error code otherwise

Initializes the random number generator and caches adjectives/nouns in a hashtable for fast validation. Must be called before acds_string_generate() and before any is_session_string() validation calls.

Uses libsodium's randombytes for cryptographically secure randomness. Cleans up cached data on program exit via atexit() handler.

Definition at line 229 of file discovery/strings.c.

229 {
230 return ASCIICHAT_OK;
231}

References ASCIICHAT_OK.

◆ acds_strings_destroy()

void acds_strings_destroy ( void )

Cleanup function for session string cache Called by asciichat_shared_destroy() during library cleanup. Safe to call multiple times (idempotent).

Definition at line 62 of file discovery/strings.c.

62 {
63 // Shutdown if initialized
64 if (!lifecycle_shutdown(&g_cache_lc)) {
65 return; // Not initialized
66 }
67
68 // Cleanup adjectives cache
69 word_cache_entry_t *adj_entry, *adj_tmp;
70 HASH_ITER(hh, g_adjectives_cache, adj_entry, adj_tmp) {
71 HASH_DEL(g_adjectives_cache, adj_entry);
72 SAFE_FREE(adj_entry->word);
73 SAFE_FREE(adj_entry);
74 }
75 g_adjectives_cache = NULL;
76
77 // Cleanup nouns cache
78 word_cache_entry_t *noun_entry, *noun_tmp;
79 HASH_ITER(hh, g_nouns_cache, noun_entry, noun_tmp) {
80 HASH_DEL(g_nouns_cache, noun_entry);
81 SAFE_FREE(noun_entry->word);
82 SAFE_FREE(noun_entry);
83 }
84 g_nouns_cache = NULL;
85
86 log_dev("Session string word cache cleaned up");
87}
#define SAFE_FREE(ptr)
One owned word in the adjective or noun validation hash table.
char * word
The word string (key).

References log_dev, SAFE_FREE, and word_cache_entry_t::word.

Referenced by asciichat_shared_destroy().

◆ is_session_string()

bool is_session_string ( const char * str)

Check if a string is a valid session string.

Parameters
strString to validate
Returns
true if valid session string (adjective-noun-noun format), false otherwise

A valid session string must:

  • Be in format: adjective-noun-noun
  • Contain exactly 3 words separated by exactly 2 hyphens
  • Have each word be a real adjective or noun from cached wordlists
  • Contain only lowercase ASCII letters and hyphens
  • Be 5-47 characters long
  • Not start or end with hyphen
  • Not contain consecutive hyphens

This function validates against the cached wordlists populated by acds_string_init(). Non-session inputs return false without setting an error. Internal failures set errno.

Definition at line 261 of file discovery/strings.c.

261 {
262 if (!str || str[0] == '\0') {
263 return false;
264 }
265
266 size_t len = strlen(str);
267
268 // Check length bounds (min 4, max defined by SESSION_STRING_MAX_LEN)
269 if (len < 4 || len > SESSION_STRING_MAX_LEN) {
270 return false;
271 }
272
273 // Session strings must be ASCII-only (homograph attack prevention)
274 if (!utf8_is_ascii_only(str)) {
275 return false;
276 }
277
278 // Get compiled regex (lazy initialization)
279 pcre2_code *regex = session_format_regex_get();
280 if (!regex) {
281 SET_ERRNO(ERROR_INTERNAL, "Session string PCRE2 regex failed to initialize");
282 return false;
283 }
284
285 // Validate format using PCRE2 regex
286 pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(regex, NULL);
287 if (!match_data) {
288 log_error("Failed to allocate match data for session string regex");
289 SET_ERRNO(ERROR_MEMORY, "Failed to allocate match data");
290 return false;
291 }
292
293 int match_result = pcre2_match(regex, (PCRE2_SPTR8)str, len, 0, 0, match_data, NULL);
294
295 pcre2_match_data_free(match_data);
296
297 if (match_result < 0) {
298 if (match_result != PCRE2_ERROR_NOMATCH) {
299 SET_ERRNO(ERROR_INTERNAL, "Session string PCRE2 matching failed: %d", match_result);
300 }
301 return false;
302 }
303
304 // Extract the three words by finding hyphens
305 // Format is guaranteed to be: word-word-word where each word is 2-12 lowercase letters
306 const char *hyphen1 = strchr(str, '-');
307 if (!hyphen1) {
308 return false;
309 }
310
311 const char *hyphen2 = strchr(hyphen1 + 1, '-');
312 if (!hyphen2) {
313 return false;
314 }
315
316 // Extract three words
317 size_t adj_len = hyphen1 - str;
318 size_t noun1_len = hyphen2 - hyphen1 - 1;
319 size_t noun2_len = len - (hyphen2 - str) - 1;
320
321 if (adj_len >= 32 || noun1_len >= 32 || noun2_len >= 32) {
322 return false;
323 }
324
326 memcpy(adj, str, adj_len);
327 adj[adj_len] = '\0';
328 memcpy(noun1, hyphen1 + 1, noun1_len);
329 noun1[noun1_len] = '\0';
330 memcpy(noun2, hyphen2 + 1, noun2_len);
331 noun2[noun2_len] = '\0';
332
333 // Lazy initialization: build validation caches on first use
334 // call_once ensures thread-safe exactly-once execution
335 build_validation_caches();
336 // If initialization fails silently (logs warning), hashtables will be empty
337 // and validation will fail, which is safe behavior
338
339 // Validate first word is an adjective
340 word_cache_entry_t *adj_entry = NULL;
341 HASH_FIND_STR(g_adjectives_cache, adj, adj_entry);
342 if (!adj_entry) {
343 return false;
344 }
345
346 // Validate second and third words are nouns
347 word_cache_entry_t *noun_entry1 = NULL;
348 HASH_FIND_STR(g_nouns_cache, noun1, noun_entry1);
349 if (!noun_entry1) {
350 return false;
351 }
352
353 word_cache_entry_t *noun_entry2 = NULL;
354 HASH_FIND_STR(g_nouns_cache, noun2, noun_entry2);
355 if (!noun_entry2) {
356 return false;
357 }
358
359 log_dev("Valid session string: %s", str);
360 return true;
361}
#define DISCOVERY_STRINGS_ADJ_BUFFER_SIZE
#define DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE
#define DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE
#define SESSION_STRING_MAX_LEN
Maximum length of a session string (without null terminator).
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_INTERNAL
Definition error_codes.h:91
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
bool utf8_is_ascii_only(const char *str)
Check if a string contains only ASCII characters.
Definition utf8.c:137

References DISCOVERY_STRINGS_ADJ_BUFFER_SIZE, DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE, DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE, ERROR_INTERNAL, ERROR_MEMORY, log_dev, log_error, SESSION_STRING_MAX_LEN, SET_ERRNO, and utf8_is_ascii_only().

Referenced by discover_session_parallel(), and parse_client_address().