ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
discovery/strings.c
Go to the documentation of this file.
1
11
12/* Storage capacities in elements; text buffers include the terminating NUL. */
13#define DISCOVERY_STRINGS_ADJ_BUFFER_SIZE 32
14#define DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE 32
15#define DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE 32
16
20#include <ascii-chat/uthash.h>
22#include <string.h>
23#include <stdlib.h>
24#include <stdio.h>
25#include <sodium.h>
26#define PCRE2_CODE_UNIT_WIDTH 8
27#include <pcre2.h>
29#include <ascii-chat/log/log.h>
30
31#include <libplatform/lifecycle.h>
32
33// ============================================================================
34// Word Cache Implementation (Hashtable for O(1) validation)
35// ============================================================================
36
44typedef struct {
45 char *word;
46 UT_hash_handle hh;
48
52static word_cache_entry_t *g_adjectives_cache = NULL;
53static word_cache_entry_t *g_nouns_cache = NULL;
54// Lifecycle for thread-safe one-time cache initialization (replaces C11 call_once)
55static lifecycle_t g_cache_lc = LIFECYCLE_INIT;
56
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}
88
99static void do_build_validation_caches(void) {
100 // Build adjectives cache
101 for (size_t i = 0; i < adjectives_count; i++) {
103 if (!entry) {
104 log_warn("Failed to allocate adjectives cache entry - validation will be slower");
105 return;
106 }
107
108 size_t word_len = strlen(adjectives[i]) + 1;
109 entry->word = SAFE_MALLOC(word_len, char *);
110 if (!entry->word) {
111 SAFE_FREE(entry);
112 log_warn("Failed to allocate memory for adjective word - validation will be slower");
113 return;
114 }
115 memcpy(entry->word, adjectives[i], word_len);
116
117 HASH_ADD_KEYPTR(hh, g_adjectives_cache, entry->word, strlen(entry->word), entry);
118 }
119
120 // Build nouns cache
121 for (size_t i = 0; i < nouns_count; i++) {
123 if (!entry) {
124 log_warn("Failed to allocate nouns cache entry - validation will be slower");
125 return;
126 }
127
128 size_t word_len = strlen(nouns[i]) + 1;
129 entry->word = SAFE_MALLOC(word_len, char *);
130 if (!entry->word) {
131 SAFE_FREE(entry);
132 log_warn("Failed to allocate memory for noun word - validation will be slower");
133 return;
134 }
135 memcpy(entry->word, nouns[i], word_len);
136
137 HASH_ADD_KEYPTR(hh, g_nouns_cache, entry->word, strlen(entry->word), entry);
138 }
139
140 log_dev("Session string word cache initialized (%zu adjectives, %zu nouns)", adjectives_count, nouns_count);
141}
142
147static void build_validation_caches(void) {
148 if (!lifecycle_init_once(&g_cache_lc)) {
149 // Already initialized or in progress - spin-wait for completion
150 while (!lifecycle_is_initialized(&g_cache_lc)) {
151 // Spin until initialization completes
152 }
153 return;
154 }
155
156 // Winner: do the initialization
157 do_build_validation_caches();
158 lifecycle_init_commit(&g_cache_lc);
159}
160
161// ============================================================================
162// PCRE2 Session String Format Validator
163// ============================================================================
164
177
178static const char *SESSION_STRING_FORMAT_PATTERN = "^[a-z]{2,12}-[a-z]{2,12}-[a-z]{2,12}$";
179
180static pcre2_code *g_session_format_regex = NULL;
181static lifecycle_t g_regex_lc = LIFECYCLE_INIT;
182
186static void session_regex_init_once(void) {
187 int error_code;
188 PCRE2_SIZE error_offset;
189 g_session_format_regex = pcre2_compile((PCRE2_SPTR8)SESSION_STRING_FORMAT_PATTERN, PCRE2_ZERO_TERMINATED, 0, &error_code, &error_offset, NULL);
190
191 if (!g_session_format_regex) {
192 PCRE2_UCHAR error_buf[256];
193 pcre2_get_error_message(error_code, error_buf, sizeof(error_buf));
194 log_error("Failed to compile session string regex at offset %zu: %s", error_offset, (const char *)error_buf);
195 return;
196 }
197
198 // JIT is an optional optimization, including for browser builds.
199 uint32_t jit_available = 0;
200 if (!SAFE_GETENV("ASCII_CHAT_PCRE2_DISABLE_JIT") && pcre2_config(PCRE2_CONFIG_JIT, &jit_available) == 0 && jit_available) {
201 int jit_ret = pcre2_jit_compile(g_session_format_regex, PCRE2_JIT_COMPLETE);
202 if (jit_ret < 0) {
203 log_debug("Session string regex JIT compilation failed (code %d), falling back to interpreter", jit_ret);
204 }
205 }
206
207 log_dev("Session string format validator initialized");
208}
209
214static pcre2_code *session_format_regex_get(void) {
215 if (!lifecycle_init_once(&g_regex_lc)) {
216 // Already initialized or in progress - spin-wait for completion
217 while (!lifecycle_is_initialized(&g_regex_lc)) {
218 // Spin until initialization completes
219 }
220 return g_session_format_regex;
221 }
222
223 // Winner: do the initialization
224 session_regex_init_once();
225 lifecycle_init_commit(&g_regex_lc);
226 return g_session_format_regex;
227}
228
232
233asciichat_error_t acds_string_generate(char *output, size_t output_size) {
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}
260
261bool is_session_string(const char *str) {
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}
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
Wordlist for generating friendly session identifiers in ACDS.
#define SET_ERRNO(code,...)
asciichat_error_t acds_string_init(void)
Initialize session string system with cached word validation.
#define DISCOVERY_STRINGS_ADJ_BUFFER_SIZE
#define DISCOVERY_STRINGS_NOUN1_BUFFER_SIZE
bool is_session_string(const char *str)
Check if a string is a valid session string.
void acds_strings_destroy(void)
Cleanup function for session string cache Called by asciichat_shared_destroy() during library cleanup...
asciichat_error_t acds_string_generate(char *output, size_t output_size)
Generate random session string.
#define DISCOVERY_STRINGS_NOUN2_BUFFER_SIZE
#define SESSION_STRING_MAX_LEN
Maximum length of a session string (without null terminator).
Error and exit codes - unified status values (0-255).
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_BUFFER_OVERFLOW
@ ERROR_INTERNAL
Definition error_codes.h:91
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
bool utf8_is_ascii_only(const char *str)
Check if a string contains only ASCII characters.
Definition utf8.c:137
📝 Logging API with multiple log levels and terminal output control
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
Wordlist and utilities for generating friendly session and client names.
PCRE2 compilation and match helpers.
🔤 String Manipulation and Shell Escaping Utilities
#define SESSION_STRING_BUFFER_SIZE
One owned word in the adjective or noun validation hash table.
UT_hash_handle hh
uthash handle
char * word
The word string (key).
🔤 UTF-8 Encoding and Decoding Utilities