ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
options.c
Go to the documentation of this file.
1
51
52/* Storage capacities in elements; text buffers include the terminating NUL. */
53#define OPTIONS_OPT_BUFFER_SIZE 64
54#define OPTIONS_LOG_FILENAME_BUFFER_SIZE 256
55#define OPTIONS_RESULT_BUFFER_SIZE 512
56#define OPTIONS_LONG_FORM_BUFFER_SIZE 256
57#define OPTIONS_LONG_FORM_EQ_BUFFER_SIZE 256
58#define OPTIONS_NORMALIZED_URL_BUFFER_SIZE 2048
59
61#include <ascii-chat/source_root.h>
62#include <ctype.h>
63#include <options/actions.h>
64#include <options/common.h>
65#include <options/options.h>
66#include <options/parsers.h>
67#include <options/rcu.h> // RCU-based thread-safe options
68#include <options/registry/core.h>
69#include <options/registry/mode_defaults.h> // Mode-aware defaults
71#include <options/validation.h>
72#include <sys/stat.h>
73
75#include <ascii-chat/common.h>
77#include <ascii-chat/log/grep.h>
78#include <ascii-chat/log/log.h>
81#include <ascii-chat/util/url.h>
83#include <libflags/builder.h>
84#include <libflags/commands.h>
85#include <libflags/completions/completions.h>
86#include <libflags/explicit.h>
87#include <libflags/flags.h>
88#include <libplatform/filesystem.h>
89#include <libplatform/system.h>
90#include <libplatform/systemd.h>
91#include <libplatform/terminal.h>
92#include <options/colorscheme.h>
93#include <options/config.h>
94#include <options/strings.h> // Enum/mode string conversions
95#include <yyjson.h>
96
97#ifdef _WIN32
98#include <io.h>
99#else
100#include <unistd.h>
101#endif
102
103#include <math.h>
104#include <stdio.h>
105#include <stdlib.h>
106#include <string.h>
107
108static void options_flags_log_event(const flags_log_event_t *event,
109 void *user_data) {
110 (void)user_data;
111 if (event && event->message)
112 log_error("%s", event->message);
113}
114
115static const char *options_json_type(const registry_entry_t *entry) {
116 if (entry->type == OPTION_TYPE_BOOL)
117 return "boolean";
118 if (entry->type == OPTION_TYPE_INT || !strcmp(entry->long_name, "zalgo"))
119 return "integer";
120 if (entry->type == OPTION_TYPE_DOUBLE ||
121 (entry->type == OPTION_TYPE_CALLBACK && !entry->metadata.enum_values &&
122 entry->metadata.numeric_range.max && strcmp(entry->long_name, "seek")))
123 return "number";
124 return "string";
125}
126
128options_json_validate_value(const registry_entry_t *entry, yyjson_val *value) {
129 if (!strcmp(entry->long_name, "test-pattern")) {
130 if (yyjson_is_bool(value) ||
131 (yyjson_is_int(value) && yyjson_get_sint(value) >= 0 &&
132 yyjson_get_sint(value) <= 1) ||
133 (yyjson_is_str(value) && (!strcmp(yyjson_get_str(value), "0") ||
134 !strcmp(yyjson_get_str(value), "1"))))
135 return ASCIICHAT_OK;
137 "test-pattern must be boolean, 0 or 1");
138 }
139 const char *type = options_json_type(entry);
140 bool valid = (!strcmp(type, "boolean") && yyjson_is_bool(value)) ||
141 (!strcmp(type, "integer") && yyjson_is_int(value)) ||
142 (!strcmp(type, "number") && yyjson_is_num(value)) ||
143 (!strcmp(type, "string") && yyjson_is_str(value)) ||
144 (!strcmp(entry->long_name, "seek") && yyjson_is_num(value));
145 if (!valid)
146 return SET_ERRNO(ERROR_INVALID_PARAM, "Wrong type for %s",
147 entry->long_name);
148 if (yyjson_is_str(value) &&
149 (yyjson_get_len(value) > 4096 ||
150 strlen(yyjson_get_str(value)) != yyjson_get_len(value)))
151 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid or oversized option %s",
152 entry->long_name);
153 if (yyjson_is_num(value) && !isfinite(yyjson_get_num(value)))
154 return SET_ERRNO(ERROR_INVALID_PARAM, "Non-finite option");
155 return ASCIICHAT_OK;
156}
157
158yyjson_mut_val *options_json_schema_for_option(yyjson_mut_doc *document,
159 const char *name) {
160 if (!document || !name) {
161 SET_ERRNO(ERROR_INVALID_PARAM, "Missing option schema argument");
162 return NULL;
163 }
165 if (!entry || entry->type == OPTION_TYPE_ACTION) {
166 SET_ERRNO(ERROR_INVALID_PARAM, "Unknown value option: %s", name);
167 return NULL;
168 }
169 yyjson_mut_val *schema = yyjson_mut_obj(document);
170 yyjson_mut_obj_add_str(document, schema, "type", options_json_type(entry));
171 yyjson_mut_obj_add_str(document, schema, "description", entry->help_text);
172 if (entry->metadata.enum_values) {
173 yyjson_mut_val *values = yyjson_mut_arr(document);
174 for (size_t i = 0; entry->metadata.enum_values[i]; ++i)
175 yyjson_mut_arr_add_str(document, values, entry->metadata.enum_values[i]);
176 yyjson_mut_obj_add_val(document, schema, "enum", values);
177 }
178 if (!strcmp(name, "test-pattern")) {
179 yyjson_mut_obj_remove_str(schema, "type");
180 yyjson_mut_obj_remove_str(schema, "enum");
181 yyjson_mut_val *values = yyjson_mut_arr(document);
182 yyjson_mut_arr_add_bool(document, values, true);
183 yyjson_mut_arr_add_bool(document, values, false);
184 yyjson_mut_arr_add_int(document, values, 0);
185 yyjson_mut_arr_add_int(document, values, 1);
186 yyjson_mut_arr_add_str(document, values, "0");
187 yyjson_mut_arr_add_str(document, values, "1");
188 yyjson_mut_obj_add_val(document, schema, "enum", values);
189 }
190 if (!strcmp(name, "seek")) {
191 yyjson_mut_obj_remove_str(schema, "type");
192 yyjson_mut_val *types = yyjson_mut_arr(document);
193 yyjson_mut_arr_add_str(document, types, "string");
194 yyjson_mut_arr_add_str(document, types, "number");
195 yyjson_mut_obj_add_val(document, schema, "type", types);
196 }
197 return schema;
198}
199
200asciichat_error_t options_json_parse_value(const char *name, yyjson_val *value,
201 char *output, size_t output_size,
202 bool *omitted) {
203 if (!name || !value || !output || !output_size || !omitted)
204 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing JSON option argument");
205 *omitted = false;
207 if (!entry || entry->type == OPTION_TYPE_ACTION || entry->owns_memory)
208 return SET_ERRNO(ERROR_INVALID_PARAM, "Unsupported value option: %s", name);
209 asciichat_error_t error = options_json_validate_value(entry, value);
210 if (error != ASCIICHAT_OK)
211 return error;
212 if (yyjson_is_str(value)) {
213 size_t length = yyjson_get_len(value);
214 if (length >= output_size ||
215 (entry->type == OPTION_TYPE_STRING && entry->default_value_size &&
216 length >= entry->default_value_size))
217 return SET_ERRNO(ERROR_INVALID_PARAM, "Option value too long: %s", name);
218 SAFE_STRNCPY(output, yyjson_get_str(value), output_size);
219 } else if (yyjson_is_bool(value)) {
220 SAFE_SNPRINTF(output, output_size, "%s",
221 yyjson_get_bool(value) ? "true" : "false");
222 } else {
223 SAFE_SNPRINTF(output, output_size, "%.17g", yyjson_get_num(value));
224 }
225 if (!strcmp(name, "test-pattern") && yyjson_is_bool(value)) {
226 if (!yyjson_get_bool(value)) {
227 *omitted = true;
228 return ASCIICHAT_OK;
229 }
230 SAFE_SNPRINTF(output, output_size, "0");
231 }
232 flags_schema_builder_t *builder = flags_schema_builder_create();
233 if (!builder)
234 return SET_ERRNO(ERROR_MEMORY, "Failed to build JSON validation schema");
236 ASCIICHAT_OK) {
237 flags_schema_builder_destroy(builder);
238 return SET_ERRNO(ERROR_CONFIG, "Failed to populate JSON validation schema");
239 }
240 options_t *scratch = SAFE_CALLOC(1, sizeof(*scratch), options_t *);
241 flags_context_t *context = flags_create(flags_schema_builder_schema(builder),
242 scratch, sizeof(*scratch));
243 if (!context) {
244 SAFE_FREE(scratch);
245 flags_schema_builder_destroy(builder);
246 return SET_ERRNO(ERROR_MEMORY, "Failed to create JSON validation context");
247 }
248 const bool valid =
249 flags_set_text(context, name, output, FLAGS_SOURCE_COMMAND_LINE);
250 flags_destroy_preserving_storage(context);
251 SAFE_FREE(scratch);
252 flags_schema_builder_destroy(builder);
253 return valid ? ASCIICHAT_OK
254 : SET_ERRNO(ERROR_INVALID_PARAM, "Invalid value for option: %s",
255 name);
256}
257
258static void js_log_options(const char *msg) { (void)msg; }
259
260// ============================================================================
261// Global Action Flag Tracking
262// ============================================================================
263
266static bool g_action_flag = false;
267
272static void set_action_flag(bool action_present) {
273 g_action_flag = action_present;
274}
275
280bool has_action_flag(void) { return g_action_flag; }
281
282// ============================================================================
283// Mode Detection Helper
284// ============================================================================
285
311static bool is_binary_level_option_with_args(const char *arg,
312 bool *out_takes_arg,
313 bool *out_takes_optional_arg,
314 void *user_data) {
315 (void)user_data;
316 if (!arg) {
317 SET_ERRNO(ERROR_INVALID_PARAM, "arg is null");
318 return false;
319 }
320
321 if (out_takes_arg)
322 *out_takes_arg = false;
323 if (out_takes_optional_arg)
324 *out_takes_optional_arg = false;
325
326 // Extract option name (without leading dashes and without value after '=')
327 const char *opt_name = arg;
328 if (arg[0] == '-') {
329 opt_name = arg + (arg[1] == '-' ? 2 : 1); // Skip - or --
330 }
331
332 // For --option=value format, stop at the '=' sign
333 const char *equals = strchr(opt_name, '=');
334 size_t opt_len = equals ? (size_t)(equals - opt_name) : strlen(opt_name);
335 char opt_buffer[OPTIONS_OPT_BUFFER_SIZE];
336 if (opt_len >= sizeof(opt_buffer)) {
337 opt_len = sizeof(opt_buffer) - 1;
338 }
339 SAFE_STRNCPY(opt_buffer, opt_name, opt_len + 1);
340 opt_name = opt_buffer;
341
342 // Check option against binary-level options
343 if (strcmp(opt_name, "help") == 0 || strcmp(arg, "-h") == 0) {
344 return true;
345 }
346 if (strcmp(opt_name, "version") == 0 || strcmp(arg, "-v") == 0) {
347 return true;
348 }
349 if (strcmp(opt_name, "verbose") == 0 || strcmp(arg, "-V") == 0) {
350 if (out_takes_optional_arg)
351 *out_takes_optional_arg = true;
352 return true;
353 }
354 if (strcmp(opt_name, "quiet") == 0 || strcmp(arg, "-q") == 0) {
355 return true;
356 }
357 if (strcmp(opt_name, "log-file") == 0 || strcmp(arg, "-L") == 0) {
358 if (out_takes_arg)
359 *out_takes_arg = true;
360 return true;
361 }
362 if (strcmp(opt_name, "log-level") == 0) {
363 if (out_takes_arg)
364 *out_takes_arg = true;
365 return true;
366 }
367 if (strcmp(opt_name, "config") == 0) {
368 if (out_takes_arg)
369 *out_takes_arg = true;
370 return true;
371 }
372 if (strcmp(opt_name, "config-create") == 0) {
373 if (out_takes_optional_arg)
374 *out_takes_optional_arg = true;
375 return true;
376 }
377 if (strcmp(opt_name, "color") == 0) {
378 // --color takes an optional argument (auto/true/false)
379 // Can be used as --color (defaults to true) or --color=auto or --color auto
380 if (out_takes_optional_arg)
381 *out_takes_optional_arg = true;
382 return true;
383 }
384 if (strcmp(opt_name, "check-update") == 0) {
385 return true;
386 }
387 if (strcmp(opt_name, "no-check-update") == 0) {
388 return true;
389 }
390 if (strcmp(opt_name, "json") == 0) {
391 return true;
392 }
393 if (strcmp(opt_name, "log-format-console") == 0) {
394 return true;
395 }
396
397 return false;
398}
399
400static bool options_command_mode(const char *name, asciichat_mode_t *mode) {
401 static const struct {
402 const char *name;
403 asciichat_mode_t mode;
404 } commands[] = {
405 {"server", MODE_SERVER},
406 {"client", MODE_CLIENT},
407 {"mirror", MODE_MIRROR},
408 {"discovery-service", MODE_DISCOVERY_SERVICE},
409 {"discovery", MODE_DISCOVERY},
410 {"mcp-server", MODE_MCP_SERVER},
411 {"api-server", MODE_API_SERVER},
412 };
413 if (!name || !mode)
414 return false;
415 for (size_t i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i)
416 if (!strcmp(name, commands[i].name)) {
417 *mode = commands[i].mode;
418 return true;
419 }
420 return false;
421}
422
423static asciichat_error_t options_detect_mode(int argc, char **argv,
424 asciichat_mode_t *out_mode,
425 char *out_session_string,
426 int *out_mode_index) {
427 if (out_mode == NULL || out_mode_index == NULL) {
428 return SET_ERRNO(ERROR_INVALID_PARAM, "Output parameters must not be NULL");
429 }
430
431 *out_mode_index = -1;
432 if (out_session_string) {
433 out_session_string[0] = '\0';
434 }
435
436 log_dev("argv[0] '%s' is not a mode name, resolving command and positionals "
437 "with libflags",
438 argv[0]);
439 flags_command_t *root =
440 flags_command_create(NULL, "ascii-chat", "ascii-chat root command");
441 flags_command_t *server = flags_command_create(root, "server", "server mode");
442 flags_command_t *client = flags_command_create(root, "client", "client mode");
443 flags_command_t *mirror = flags_command_create(root, "mirror", "mirror mode");
444 flags_command_t *discovery_service =
445 flags_command_create(root, "discovery-service", "discovery service mode");
446 flags_command_t *discovery =
447 flags_command_create(root, "discovery", "discovery mode");
448 flags_command_t *mcp_server =
449 flags_command_create(root, "mcp-server", "MCP server mode");
450 flags_command_t *api_server =
451 flags_command_create(root, "api-server", "API server mode");
452 if (!root || !server || !client || !mirror || !discovery_service ||
453 !discovery || !mcp_server || !api_server) {
454 flags_command_destroy(root);
455 return SET_ERRNO(ERROR_MEMORY, "Failed to construct command schema");
456 }
457 if (!flags_command_set_default(root, discovery) ||
458 !flags_command_set_implicit_for_option(root, mirror, "file") ||
459 !flags_command_set_implicit_for_option(root, mirror, "url")) {
460 flags_command_destroy(root);
461 return SET_ERRNO(ERROR_MEMORY, "Failed to configure command defaults");
462 }
463 flags_schema_builder_t *schema_builder = flags_schema_builder_create();
464 if (!schema_builder || registry_add_all_to_flags_builder(
465 schema_builder, OPTION_MODE_ALL) != ASCIICHAT_OK) {
466 flags_schema_builder_destroy(schema_builder);
467 flags_command_destroy(root);
468 return SET_ERRNO(ERROR_CONFIG, "Failed to construct command option schema");
469 }
470 const flags_schema_t *schema = flags_schema_builder_schema(schema_builder);
471 const option_mode_bitmask_t command_modes[] = {
475 flags_command_t *command_nodes[] = {
476 server, client, mirror, discovery_service,
477 discovery, mcp_server, api_server};
478 for (size_t i = 0; i < schema->option_count; ++i) {
479 const flags_option_spec_t *option = &schema->options[i];
480 const registry_entry_t *entry = option->user_data;
481 if (entry->mode_bitmask == OPTION_MODE_NONE ||
483 if (!flags_command_add_option(root, option)) {
484 flags_schema_builder_destroy(schema_builder);
485 flags_command_destroy(root);
486 return SET_ERRNO(ERROR_MEMORY, "Failed to register binary option");
487 }
488 for (size_t mode_index = 0;
489 mode_index < sizeof(command_modes) / sizeof(command_modes[0]);
490 ++mode_index)
491 if (entry->mode_bitmask & command_modes[mode_index])
492 if (!flags_command_add_option(command_nodes[mode_index], option)) {
493 flags_schema_builder_destroy(schema_builder);
494 flags_command_destroy(root);
495 return SET_ERRNO(ERROR_MEMORY,
496 "Failed to register command-specific option");
497 }
498 }
499 flags_command_resolution_t resolution;
500 if (!flags_resolve_command_ex(root, argc, argv, &resolution)) {
501 flags_schema_builder_destroy(schema_builder);
502 flags_command_destroy(root);
503 return SET_ERRNO(ERROR_USAGE, "Unable to resolve command");
504 }
505 flags_context_t *command_context =
506 flags_create(flags_schema_builder_schema(schema_builder), NULL, 0);
507 if (!command_context) {
508 flags_schema_builder_destroy(schema_builder);
509 flags_command_destroy(root);
510 return SET_ERRNO(ERROR_MEMORY,
511 "Failed to create command validation context");
512 }
513 flags_logging_config_t logging = {.callback = options_flags_log_event,
514 .user_data = NULL};
515 flags_set_logging(command_context, &logging);
516 bool order_valid = flags_command_validate_order(command_context, root, argc,
517 argv, &resolution);
518 flags_destroy(command_context);
519 if (!order_valid) {
520 flags_schema_builder_destroy(schema_builder);
521 flags_command_destroy(root);
522 return SET_ERRNO(ERROR_USAGE, "Invalid command-line option order");
523 }
524 flags_command_t *resolved_command = resolution.command;
525 int first_positional_idx = resolution.first_positional_index;
526 if (resolution.used_implicit_command) {
527 *out_mode = MODE_MIRROR;
528 flags_schema_builder_destroy(schema_builder);
529 flags_command_destroy(root);
530 return ASCIICHAT_OK;
531 }
532 if (resolution.command_index >= 0) {
533 const char *name = flags_command_name(resolved_command);
534 if (options_command_mode(name, out_mode)) {
535 *out_mode_index = resolution.command_index;
536 flags_schema_builder_destroy(schema_builder);
537 flags_command_destroy(root);
538 return ASCIICHAT_OK;
539 }
540 }
541 flags_schema_builder_destroy(schema_builder);
542 flags_command_destroy(root);
543
544 // If no positional argument found, check for mirror-specific options
545 if (first_positional_idx == -1) {
546 // Otherwise default to discovery mode (start new session)
547 *out_mode = MODE_DISCOVERY;
548 *out_mode_index = -1;
549 return ASCIICHAT_OK;
550 }
551
552 const char *positional = argv[first_positional_idx];
553
554 // Not a known mode - check if it's a session string (word-word-word pattern)
555 if (is_session_string(positional)) {
556 *out_mode = MODE_DISCOVERY;
557 *out_mode_index = first_positional_idx;
558 if (out_session_string) {
559 SAFE_STRNCPY(out_session_string, positional, SESSION_STRING_BUFFER_SIZE);
560 }
561 return ASCIICHAT_OK;
562 }
563
564 // Unknown positional argument - suggest closest match
565 const char *suggestion = asciichat_suggest_mode(positional);
566 if (suggestion) {
567 return SET_ERRNO(ERROR_USAGE, "Unknown mode '%s'. Did you mean '%s'?",
568 positional, suggestion);
569 }
570 return SET_ERRNO(ERROR_USAGE, "Unknown mode or invalid argument: %s",
571 positional);
572}
573
574// ============================================================================
575// Default Initialization
576// ============================================================================
577
592typedef struct {
594 unsigned short int verbose_level;
595 bool quiet;
597 bool help;
601 int color; // Color setting (COLOR_SETTING_AUTO/TRUE/FALSE) - binary-level
602 // option parsed early
603 bool json; // JSON logging format - binary-level option
604 bool log_format_console_only; // Apply log template only to console -
605 // binary-level option
606 bool no_check_update; // Disable the startup update check
619
620static inline binary_level_opts_t extract_binary_level(const options_t *opts) {
621 binary_level_opts_t binary = {0};
622 if (!opts)
623 return binary;
624 binary.log_level = opts->log_level;
625 binary.verbose_level = opts->verbose_level;
626 binary.quiet = opts->quiet;
627 SAFE_STRNCPY(binary.log_file, opts->log_file, sizeof(binary.log_file));
628 binary.help = opts->help;
629 binary.version = opts->version;
631 sizeof(binary.config_file));
632 binary.detected_mode = opts->detected_mode;
633 binary.color = opts->color; // Save color setting (parsed in STAGE 1A)
634 binary.json = opts->json; // Save JSON logging flag (binary-level option)
636 opts->log_format_console_only; // Save log format console setting
637 binary.no_check_update = opts->no_check_update;
639 sizeof(binary.otel_log_level));
641 sizeof(binary.otel_endpoint));
643 sizeof(binary.otel_ca_file));
645 sizeof(binary.otel_enabled_telemetry));
649 binary.otel_timeout = opts->otel_timeout;
651
652 return binary;
653}
654
655static inline void restore_binary_level(options_t *opts,
656 const binary_level_opts_t *binary) {
657 if (!opts || !binary)
658 return;
659 opts->log_level = binary->log_level;
660 opts->verbose_level = binary->verbose_level;
661 opts->quiet = binary->quiet;
662 SAFE_STRNCPY(opts->log_file, binary->log_file, sizeof(opts->log_file));
663 opts->help = binary->help;
664 opts->version = binary->version;
665 SAFE_STRNCPY(opts->config_file, binary->config_file,
666 sizeof(opts->config_file));
667 opts->detected_mode = binary->detected_mode;
668 opts->color = binary->color; // Restore color setting (parsed in STAGE 1A)
669 opts->json = binary->json; // Restore JSON logging flag (binary-level option)
671 binary->log_format_console_only; // Restore log format console setting
672 opts->no_check_update = binary->no_check_update;
674 sizeof(opts->otel_log_level));
676 sizeof(opts->otel_endpoint));
678 sizeof(opts->otel_ca_file));
680 sizeof(opts->otel_enabled_telemetry));
684 opts->otel_timeout = binary->otel_timeout;
686}
687
689 options_t opts;
690
691 // Zero-initialize all fields first
692 memset(&opts, 0, sizeof(opts));
693 opts.mode_arg_index = -1;
694
695 // ============================================================================
696 // GENERAL CATEGORY - General-purpose options
697 // ============================================================================
698 opts.help = OPT_HELP_DEFAULT;
705
706 // ============================================================================
707 // LOGGING CATEGORY - Binary-level logging and output control options
708 // ============================================================================
709 // log_file is mode-dependent at startup and intentionally left empty here
714 sizeof(opts.otel_endpoint));
715 SAFE_STRNCPY(opts.otel_enabled_telemetry, "traces,logs,metrics",
716 sizeof(opts.otel_enabled_telemetry));
717 opts.otel_realtime_sample_rate = 0.01;
719 opts.otel_metrics_interval = 10000;
720 SAFE_STRNCPY(opts.otel_log_level, "info", sizeof(opts.otel_log_level));
721 opts.otel_timeout = 5000;
722 opts.otel_queue_capacity = 4096;
723 if (platform_systemd_is_managed()) {
724 opts.splash_screen = false;
725 opts.status_screen = false;
726 opts.no_check_update = true;
727 SAFE_STRNCPY(opts.log_file, "/dev/null", sizeof(opts.log_file));
728 opts.otel_endpoint[0] = '\0';
729 }
730 opts.grep_pattern[0] = '\0'; // Explicitly ensure grep_pattern is empty
731 opts.json = OPT_JSON_DEFAULT;
733 sizeof(opts.color_scheme_name));
734 // log_template and log_format are set by get_default_log_template()
735
736 // ============================================================================
737 // TERMINAL CATEGORY - Terminal display options
738 // ============================================================================
748 if (platform_systemd_is_managed())
750
751 // ============================================================================
752 // DISPLAY CATEGORY - Display and rendering options
753 // ============================================================================
757 opts.stabilize = true;
759 // palette_custom is already zeroed by memset
762 opts.fps = OPT_FPS_DEFAULT;
766 opts.waveform = false;
767 opts.fft = false;
768 SAFE_STRNCPY(opts.fft_scale, "-62:-6", sizeof(opts.fft_scale));
771
772 // ============================================================================
773 // WEBCAM CATEGORY - Webcam and capture device options
774 // ============================================================================
778
779 // ============================================================================
780 // MEDIA CATEGORY - Media file streaming and playback options
781 // ============================================================================
782 // media_file is already zeroed by memset
783 // media_url is already zeroed by memset
788 // yt_dlp_options is already zeroed by memset
789
790 // Render-to-file options
791 // render_file is already zeroed by memset
793 // render_font is already zeroed by memset
795
796 // ============================================================================
797 // NETWORK CATEGORY - Network connectivity and protocol options
798 // ============================================================================
799 SAFE_STRNCPY(opts.address, OPT_ADDRESS_DEFAULT, sizeof(opts.address));
807 // Discovery Service (ACDS) Options
811 sizeof(opts.discovery_server));
816 // discovery_service_key is already zeroed by memset
818 '\0'; // Explicitly ensure discovery_database_path is empty
819 // LAN Discovery & WebRTC Options
823 // WebRTC Mode & Strategy Options
827 opts.webrtc_relay_only = false;
832 sizeof(opts.stun_servers));
834 sizeof(opts.turn_servers));
836 sizeof(opts.turn_username));
838 sizeof(opts.turn_credential));
839 // turn_secret is already zeroed by memset
840
841 // ============================================================================
842 // AUDIO CATEGORY - Audio capture, playback and processing options
843 // ============================================================================
844 opts.audio_fft_size = 1024;
845 opts.test_audio = false;
846 opts.audio_spectral = true;
847 opts.audio_spectral_mixer = false;
848 opts.audio_spectral_gate = true;
849 opts.reduce_noise = true;
853 opts.microphone_channels = 1;
854 opts.microphone_channel = 0;
862
863 // ============================================================================
864 // SECURITY CATEGORY - Encryption and authentication options
865 // ============================================================================
867 // encrypt_key is already zeroed by memset
868 // password is already zeroed by memset
869 // encrypt_keyfile is already zeroed by memset
872 // server_key is already zeroed by memset
873 // client_keys is already zeroed by memset
874 // identity_keys array is already zeroed by memset
875 opts.num_identity_keys = 0;
878
879 // ============================================================================
880 // CONFIGURATION CATEGORY - Application configuration options
881 // ============================================================================
882 // config_file is already zeroed by memset
883
884 // ============================================================================
885 // DATABASE CATEGORY - Database and persistent storage options
886 // ============================================================================
887 // discovery_database_path is already zeroed by memset (set above in NETWORK)
888
889 // ============================================================================
890 // Internal/System Fields
891 // ============================================================================
892 // session_string is already zeroed by memset
893 // detected_mode is already zeroed by memset
894
895 return opts;
896}
897
912 // Extract binary-level options before reset
913 binary_level_opts_t binary = extract_binary_level(source);
914
915 // Create fresh options with all defaults
916 options_t opts = options_t_new();
917
918 // Restore binary-level options (overwrite defaults)
919 restore_binary_level(&opts, &binary);
920
921 return opts;
922}
923
924static char *options_get_log_filepath(asciichat_mode_t detected_mode,
925 options_t *opts) {
926 // Use static buffers to avoid SAFE_MALLOC and malloc before memory tracking
927 // is initialized
928 static char log_filename_buf[OPTIONS_LOG_FILENAME_BUFFER_SIZE];
929 static char default_log_path_buf[PLATFORM_MAX_PATH_LENGTH];
930 static char tmp_dir_buf[PLATFORM_MAX_PATH_LENGTH];
931 // Use a smaller static buffer to avoid WASM memory issues
932 static char result_buf[OPTIONS_RESULT_BUFFER_SIZE]; // Reduced size for WASM
933 // compatibility
934
935 // Determine log filename based on mode
936 const char *log_filename_literal;
937 switch (detected_mode) {
938 case MODE_SERVER:
939 log_filename_literal = "server.log";
940 break;
941 case MODE_CLIENT:
942 log_filename_literal = "client.log";
943 break;
944 case MODE_MIRROR:
945 log_filename_literal = "mirror.log";
946 break;
947 case MODE_MCP_SERVER:
948 log_filename_literal = "mcp-server.log";
949 break;
950 case MODE_API_SERVER:
951 log_filename_literal = "api-server.log";
952 break;
954 log_filename_literal = "acds.log";
955 break;
956 case MODE_DISCOVERY:
957 log_filename_literal = "discovery.log";
958 break;
959 default:
960 log_filename_literal = "ascii-chat.log";
961 break;
962 }
963 SAFE_STRNCPY(log_filename_buf, log_filename_literal,
964 sizeof(log_filename_buf) - 1);
965 log_filename_buf[sizeof(log_filename_buf) - 1] = '\0';
966
967 /* options_init() runs before the tracked allocator is initialized. Debug
968 * builds already have a stable checkout path, so avoid get_log_dir()'s
969 * allocation and path-validation work during this early phase. */
970#ifndef NDEBUG
971 const char *debug_log_dir = ASCIICHAT_SOURCE_ROOT;
972 if (debug_log_dir && *debug_log_dir) {
973 safe_snprintf(default_log_path_buf, PLATFORM_MAX_PATH_LENGTH, "%s%s%s",
974 debug_log_dir, PATH_SEPARATOR_STR, log_filename_buf);
976 default_log_path_buf);
977 SAFE_STRNCPY(result_buf, default_log_path_buf, sizeof(result_buf) - 1);
978 result_buf[sizeof(result_buf) - 1] = '\0';
979 return result_buf;
980 }
981#endif
982
983 char *log_dir = get_log_dir();
984 if (log_dir) {
985 // Build full log file path: log_dir + separator + log_filename
986 safe_snprintf(default_log_path_buf, PLATFORM_MAX_PATH_LENGTH, "%s%s%s",
987 log_dir, PATH_SEPARATOR_STR, log_filename_buf);
988
989 // get_log_dir() already selected a trusted application-owned directory.
990 // Avoid sending this internally constructed path through the user-path
991 // validator during pre-parse startup, where platform services are not
992 // fully initialized yet. User-supplied paths are still validated at their
993 // parsing sites.
995 default_log_path_buf);
996
997 // Free log_dir allocated by get_log_dir() using SAFE_MALLOC
998 SAFE_FREE(log_dir);
999
1000 // Copy to static result buffer
1001 SAFE_STRNCPY(result_buf, default_log_path_buf, sizeof(result_buf) - 1);
1002 result_buf[sizeof(result_buf) - 1] = '\0';
1003 return result_buf;
1004
1005 } else {
1006 SAFE_FREE(log_dir);
1007 if (platform_get_temp_dir(tmp_dir_buf, PLATFORM_MAX_PATH_LENGTH)) {
1008 safe_snprintf(default_log_path_buf, PLATFORM_MAX_PATH_LENGTH, "%s%s%s",
1009 tmp_dir_buf, PATH_SEPARATOR_STR, "ascii-chat.log");
1010 SAFE_STRNCPY(result_buf, default_log_path_buf, sizeof(result_buf) - 1);
1011 result_buf[sizeof(result_buf) - 1] = '\0';
1012 return result_buf;
1013 } else {
1014 // Fallback to just the filename
1015 SAFE_STRNCPY(result_buf, log_filename_buf, sizeof(result_buf) - 1);
1016 result_buf[sizeof(result_buf) - 1] = '\0';
1017 return result_buf;
1018 }
1019 }
1020}
1021
1022// ============================================================================
1023// Binary-Level Boolean Option Parser
1024// ============================================================================
1025
1026// Parses binary-level boolean options with support for multiple formats:
1027// - --long-name → sets field to true
1028// - --long-name=true/false/yes/no/1/0/on/off → parses value
1029// - -X (short form) → sets field to true
1030// - -X=value (short form with value) → parses value
1031static bool parse_binary_bool_arg(const char *arg, bool *field,
1032 const char *long_name, char short_name) {
1033 if (!arg || !field || !long_name)
1034 return false;
1035
1036 // Check long form: --long-name
1037 char long_form[OPTIONS_LONG_FORM_BUFFER_SIZE];
1038 snprintf(long_form, sizeof(long_form), "--%s", long_name);
1039 if (strcmp(arg, long_form) == 0) {
1040 *field = true;
1041 return true;
1042 }
1043
1044 // Check long form with =value: --long-name=...
1045 char long_form_eq[OPTIONS_LONG_FORM_EQ_BUFFER_SIZE];
1046 snprintf(long_form_eq, sizeof(long_form_eq), "--%s=", long_name);
1047 if (strncmp(arg, long_form_eq, strlen(long_form_eq)) == 0) {
1048 const char *value = arg + strlen(long_form_eq);
1049 if (strcasecmp(value, "true") == 0 || strcasecmp(value, "yes") == 0 ||
1050 strcasecmp(value, "1") == 0 || strcasecmp(value, "on") == 0) {
1051 *field = true;
1052 return true;
1053 } else if (strcasecmp(value, "false") == 0 ||
1054 strcasecmp(value, "no") == 0 || strcasecmp(value, "0") == 0 ||
1055 strcasecmp(value, "off") == 0) {
1056 *field = false;
1057 return true;
1058 }
1059 // If invalid value, still consume it (builder will validate later)
1060 return true;
1061 }
1062
1063 // Check short form: -X (if defined)
1064 if (short_name != '\0') {
1065 char short_form[3];
1066 snprintf(short_form, sizeof(short_form), "-%c", short_name);
1067 if (strcmp(arg, short_form) == 0) {
1068 *field = true;
1069 return true;
1070 }
1071 }
1072
1073 return false;
1074}
1075
1076// ============================================================================
1077// Option Initialization Stages
1078// ============================================================================
1079
1080// State collected before mode detection and full command-line parsing.
1096
1097// argv entries borrow the original strings; only the pointer array is owned.
1104typedef struct {
1105 int argc;
1106 char **argv;
1115
1116static asciichat_error_t validate_options_argv(int argc, char **argv) {
1117 // Validate arguments (safety check for tests)
1118 if (argc < 0 || argc > 128) {
1119 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid argc: %d", argc);
1120 }
1121 if (argv == NULL) {
1122 return SET_ERRNO(ERROR_INVALID_PARAM, "argv is NULL");
1123 }
1124 // Validate all argv elements are non-NULL up to argc
1125 for (int i = 0; i < argc; i++) {
1126 if (argv[i] == NULL) {
1127 return SET_ERRNO(ERROR_INVALID_PARAM, "argv[%d] is NULL (argc=%d)", i,
1128 argc);
1129 }
1130 }
1131 return ASCIICHAT_OK;
1132}
1133
1134static void handle_help_option(int argc, char **argv) {
1135 // FIRST: Scan entire argv for --help (special case - works before OR after
1136 // mode)
1137 for (int i = 1; i < argc; i++) {
1138 if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
1139 // Scan backwards to find if a mode was specified before --help
1140 asciichat_mode_t help_mode =
1141 MODE_DISCOVERY; // Default to discovery mode (binary-level help)
1142 for (int j = i - 1; j >= 1; j--) {
1143 if (argv[j][0] != '-') {
1144 if (strcmp(argv[j], "server") == 0) {
1145 help_mode = MODE_SERVER;
1146 } else if (strcmp(argv[j], "client") == 0) {
1147 help_mode = MODE_CLIENT;
1148 } else if (strcmp(argv[j], "mirror") == 0) {
1149 help_mode = MODE_MIRROR;
1150 } else if (strcmp(argv[j], "mcp-server") == 0) {
1151 help_mode = MODE_MCP_SERVER;
1152 } else if (strcmp(argv[j], "api-server") == 0) {
1153 help_mode = MODE_API_SERVER;
1154 } else if (strcmp(argv[j], "discovery-service") == 0) {
1155 help_mode = MODE_DISCOVERY_SERVICE;
1156 } else if (strcmp(argv[j], "discovery") == 0) {
1157 help_mode = MODE_DISCOVERY;
1158 }
1159 break; // Found first non-flag argument
1160 }
1161 }
1162
1163 // Show help for the detected mode (or binary-level if no mode)
1164 usage(stdout, help_mode);
1165 fflush(NULL);
1166 asciichat_coverage_flush();
1167 _Exit(0);
1168 }
1169 }
1170}
1171
1172static asciichat_error_t scan_binary_actions(int argc, char **argv,
1173 binary_actions_t *actions) {
1174 // THEN: Scan for other binary-level actions (stops at mode name)
1175 for (int i = 1; i < argc; i++) {
1176 // Stop scanning at mode name - binary-level options must come before the
1177 // mode
1178 if (argv[i][0] != '-') {
1179 bool is_mode =
1180 (strcmp(argv[i], "server") == 0 || strcmp(argv[i], "client") == 0 ||
1181 strcmp(argv[i], "mirror") == 0 ||
1182 strcmp(argv[i], "discovery") == 0 ||
1183 strcmp(argv[i], "discovery-service") == 0);
1184 if (is_mode) {
1185 break; // Stop processing at mode name
1186 }
1187 }
1188 if (argv[i][0] == '-') {
1189 // Handle --quiet, -q, --quiet=value formats
1190 bool temp_quiet = false;
1191 if (parse_binary_bool_arg(argv[i], &temp_quiet, "quiet", 'q')) {
1192 if (temp_quiet) {
1193 actions->user_quiet = true;
1194 }
1195 }
1196 // Validate --log-level and --log-file require arguments
1197 if (strcmp(argv[i], "--log-level") == 0) {
1198 if (i + 1 >= argc || argv[i + 1][0] == '-') {
1199 log_error("--log-level requires a value (dev, debug, info, warn, "
1200 "error, fatal)");
1201 return ERROR_USAGE;
1202 }
1203 i++; // Skip the argument in this loop
1204 }
1205 if (strcmp(argv[i], "-L") == 0 || strcmp(argv[i], "--log-file") == 0) {
1206 if (i + 1 >= argc || argv[i + 1][0] == '-') {
1207 log_error("%s requires a file path", argv[i]);
1208 return ERROR_USAGE;
1209 }
1210 i++; // Skip the argument in this loop
1211 }
1212 // --help is handled in the first scan loop above (works before OR after
1213 // mode) Parse --color early so it affects help output colors
1214 if (strcmp(argv[i], "--color") == 0) {
1215 if (i + 1 < argc && argv[i + 1][0] != '-') {
1216 // Check if next arg is a mode name (not a color value)
1217 const char *next_arg = argv[i + 1];
1218 bool is_mode = (strcmp(next_arg, "server") == 0 ||
1219 strcmp(next_arg, "client") == 0 ||
1220 strcmp(next_arg, "mirror") == 0 ||
1221 strcmp(next_arg, "discovery") == 0 ||
1222 strcmp(next_arg, "discovery-service") == 0);
1223
1224 if (is_mode) {
1225 // Next arg is a mode, not a color value - default to true
1227 actions->color_setting_found = true;
1228 } else {
1229 // Try to parse as color value
1230 char *error_msg = NULL;
1231 if (parse_color_setting(next_arg, &actions->parsed_color_setting,
1232 &error_msg)) {
1233 actions->color_setting_found = true;
1234 i++; // Skip the setting argument
1235 } else {
1236 if (error_msg) {
1237 log_error("Error parsing --color: %s", error_msg);
1238 SAFE_FREE(error_msg);
1239 }
1240 }
1241 }
1242 } else {
1243 // --color without argument defaults to true (enable colors)
1245 actions->color_setting_found = true;
1246 }
1247 }
1248 // Check for --color=value format
1249 if (strncmp(argv[i], "--color=", 8) == 0) {
1250 const char *value = argv[i] + 8;
1251 char *error_msg = NULL;
1252 if (parse_color_setting(value, &actions->parsed_color_setting,
1253 &error_msg)) {
1254 actions->color_setting_found = true;
1255 } else {
1256 if (error_msg) {
1257 log_error("Error parsing --color: %s", error_msg);
1258 SAFE_FREE(error_msg);
1259 }
1260 }
1261 }
1262 if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
1263 actions->show_version = true;
1264 actions->has_action = true;
1265 break;
1266 }
1267 if (strcmp(argv[i], "--check-update") == 0) {
1268 actions->check_update_flag_seen = true;
1269 if (actions->no_check_update_flag_seen) {
1270 log_error("Cannot specify both --check-update and --no-check-update");
1271 return ERROR_USAGE;
1272 }
1273 actions->has_action = true;
1275 // action_check_update_immediate() calls _Exit(), so we don't reach here
1276 break;
1277 }
1278 if (strcmp(argv[i], "--no-check-update") == 0) {
1279 actions->no_check_update_flag_seen = true;
1280 if (actions->check_update_flag_seen) {
1281 log_error("Cannot specify both --check-update and --no-check-update");
1282 return ERROR_USAGE;
1283 }
1284 // Flag will be parsed normally later
1285 }
1286 if (strcmp(argv[i], "--config-create") == 0) {
1287 actions->create_config = true;
1288 actions->has_action = true;
1289 // Check for optional [FILE] argument
1290 if (i + 1 < argc && argv[i + 1][0] != '-') {
1291 actions->config_create_path = argv[i + 1];
1292 i++; // Consume the file path argument
1293 }
1294 break;
1295 }
1296 if (strcmp(argv[i], "--man-page-create") == 0) {
1297 actions->create_manpage = true;
1298 actions->has_action = true;
1299 // Check for optional [FILE] argument
1300 if (i + 1 < argc && argv[i + 1][0] != '-') {
1301 actions->manpage_create_path = argv[i + 1];
1302 i++; // Consume the file path argument
1303 }
1304 break;
1305 }
1306 if (strcmp(argv[i], "--completions") == 0) {
1307 actions->has_action = true;
1308 // Handle --completions: generate shell completion scripts
1309 if (i + 1 < argc && argv[i + 1][0] != '-') {
1310 const char *shell_name = argv[i + 1];
1311 i++; // Consume shell name
1312
1313 // Check for optional output file
1314 const char *output_file = NULL;
1315 if (i + 1 < argc && argv[i + 1][0] != '-') {
1316 output_file = argv[i + 1];
1317 i++; // Consume output file
1318 }
1319
1320 action_completions(shell_name, output_file);
1321 // action_completions() calls _Exit(), so we don't reach here
1322 } else {
1323 log_error("--completions requires shell name (bash, fish, zsh, "
1324 "powershell)");
1325 return ERROR_USAGE;
1326 }
1327 break; // Unreachable, but for clarity
1328 }
1329 if (strncmp(argv[i], "--", 2) == 0) {
1330 option_action_fn action = options_action_callback(argv[i] + 2, true);
1331 if (action) {
1332 actions->has_action = true;
1333 action();
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 return ASCIICHAT_OK;
1340}
1341
1348static asciichat_error_t validate_early_color_mode(int argc, char **argv) {
1349 for (int i = 1; i < argc; i++) {
1350 const char *value = NULL;
1351 if (strcmp(argv[i], "--color-mode") == 0) {
1352 if (i + 1 >= argc || argv[i + 1][0] == '-') {
1353 return SET_ERRNO(ERROR_USAGE, "--color-mode requires a value (auto, "
1354 "none, 16, 256, or truecolor)");
1355 }
1356 value = argv[++i];
1357 } else if (strncmp(argv[i], "--color-mode=", 13) == 0) {
1358 value = argv[i] + 13;
1359 }
1360
1361 if (value) {
1362 terminal_color_mode_t parsed = TERM_COLOR_AUTO;
1363 char *error_msg = NULL;
1364 if (!parse_color_mode(value, &parsed, &error_msg)) {
1366 ERROR_USAGE, "%s", error_msg ? error_msg : "Invalid color mode");
1367 SAFE_FREE(error_msg);
1368 return result;
1369 }
1370 SAFE_FREE(error_msg);
1371 }
1372 }
1373 return ASCIICHAT_OK;
1374}
1375
1376static void initialize_binary_options(options_t *opts,
1377 asciichat_mode_t detected_mode,
1378 const binary_actions_t *actions) {
1379 log_dev("initialize_binary_options: before systemd");
1380 opts->no_check_update =
1381 actions->no_check_update_flag_seen || platform_systemd_is_managed();
1382 log_dev("initialize_binary_options: after systemd");
1383 opts->detected_mode = detected_mode;
1384 if (actions->has_action) {
1385 // Immediate output actions must not allocate or validate a log path before
1386 // the diagnostic allocator has completed initialization.
1387#ifdef _WIN32
1388 SAFE_STRNCPY(opts->log_file, "NUL", sizeof(opts->log_file));
1389#else
1390 SAFE_STRNCPY(opts->log_file, "/dev/null", sizeof(opts->log_file));
1391#endif
1392 } else if (!platform_systemd_is_managed()) {
1393 log_dev("initialize_binary_options: before log path");
1394 char *log_filename = options_get_log_filepath(detected_mode, opts);
1395 log_dev("initialize_binary_options: after log path");
1396 SAFE_SNPRINTF(opts->log_file, OPTIONS_BUFF_SIZE, "%s", log_filename);
1397 } else {
1398 SAFE_STRNCPY(opts->log_file, "/dev/null", sizeof(opts->log_file));
1399 }
1400 // Note: log_init() is called earlier in asciichat_shared_init() and will be
1401 // reconfigured with the actual log level and file in main.c after options are
1402 // fully parsed NOTE: --color detection now happens in src/main.c BEFORE
1403 // asciichat_shared_init() This ensures g_color_flag_passed and
1404 // g_color_flag_value are set before any logging.
1405 //
1406 // NOTE: Timer system and shared subsystems are initialized by src/main.c
1407 // via asciichat_shared_init() BEFORE options_init() is called.
1408 // This allows options_init() to use properly configured logging.
1409
1410 // If an action flag is detected OR user passed --quiet, silence logs for
1411 // clean output
1412 if (actions->user_quiet || actions->has_action) {
1414 false); // Suppress console logging for clean action output
1415 }
1416 // Apply parsed color setting from STAGE 1A
1417 if (actions->color_setting_found) {
1418 opts->color = actions->parsed_color_setting;
1419 } else {
1420 opts->color =
1421 platform_systemd_is_managed() ? COLOR_SETTING_FALSE : OPT_COLOR_DEFAULT;
1422 }
1423}
1424
1425static asciichat_error_t
1426handle_immediate_actions(options_t *opts, const binary_actions_t *actions,
1427 bool *handled) {
1428 // Handle output actions before loading configuration files and parsing mode
1429 // options.
1430 if (actions->show_version || actions->create_config ||
1431 actions->create_manpage) {
1432 if (actions->show_version) {
1433 opts->version = true;
1434 options_state_set(opts);
1435 *handled = true;
1436 return ASCIICHAT_OK;
1437 } else if (actions->create_config) {
1438
1439 // Call action handler which handles all output and prompts properly
1441 // action_create_config() calls _Exit(), so we don't reach here
1442 } else if (actions->create_manpage) {
1443 // Call action handler which handles all output and prompts properly
1445 // action_create_manpage() calls _Exit(), so we don't reach here
1446 }
1447 }
1448 return ASCIICHAT_OK;
1449}
1450
1451static asciichat_error_t parse_binary_options(options_t *opts, int argc,
1452 char **argv) {
1453 // Check for binary-level options that can appear before or after mode
1454 // Search entire argv to find --quiet, --log-file, --log-level, -V, etc.
1455 // These are documented as binary-level options that can appear anywhere
1456 for (int i = 1; i < argc; i++) {
1457 if (argv[i][0] == '-') {
1458 // Handle -V and --verbose (stackable verbosity)
1459 if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--verbose") == 0) {
1460 // Check if next argument is a number (optional argument)
1461 if (i + 1 < argc && argv[i + 1][0] != '-') {
1462 // Try to parse as integer count
1463 char *endptr;
1464 long value = strtol(argv[i + 1], &endptr, 10);
1465 if (*endptr == '\0' && value >= 0 && value <= 100) {
1466 opts->verbose_level = (unsigned short int)value;
1467 i++; // Skip next argument
1468 continue;
1469 }
1470 }
1471 // No valid number, just increment
1472 opts->verbose_level++;
1473 }
1474 // Handle binary-level boolean options using the abstraction function
1475 // -q/--quiet, --json, --log-format-console all use the same parser
1476 if (parse_binary_bool_arg(argv[i], &opts->quiet, "quiet", 'q')) {
1477 continue;
1478 }
1479 if (parse_binary_bool_arg(argv[i], &opts->json, "json", '\0')) {
1480 continue;
1481 }
1482 if (parse_binary_bool_arg(argv[i], &opts->log_format_console_only,
1483 "log-format-console", '\0')) {
1484 continue;
1485 }
1486 // Handle --log-level LEVEL (set log threshold)
1487 if (strcmp(argv[i], "--log-level") == 0) {
1488 if (i + 1 >= argc) {
1489 log_error("--log-level requires a value (dev, debug, info, warn, "
1490 "error, fatal)");
1491 return ERROR_USAGE;
1492 }
1493 if (argv[i + 1][0] == '-') {
1494 log_error("--log-level requires a value (dev, debug, info, warn, "
1495 "error, fatal)");
1496 return ERROR_USAGE;
1497 }
1498 char *error_msg = NULL;
1499 if (parse_log_level(argv[i + 1], &opts->log_level, &error_msg)) {
1500 i++; // Skip the level argument
1501 } else {
1502 if (error_msg) {
1503 log_error("%s", error_msg);
1504 SAFE_FREE(error_msg);
1505 } else {
1506 log_error("invalid log level value: %s", argv[i + 1]);
1507 }
1508 return ERROR_USAGE;
1509 }
1510 }
1511 if (strcmp(argv[i], "--config") == 0 ||
1512 strncmp(argv[i], "--config=", 9) == 0) {
1513 const char *path = argv[i] + 9;
1514 if (strcmp(argv[i], "--config") == 0) {
1515 if (i + 1 >= argc || argv[i + 1][0] == '-')
1516 return SET_ERRNO(ERROR_USAGE, "--config requires a file path");
1517 path = argv[++i];
1518 }
1519 if (!path[0] || strlen(path) >= sizeof(opts->config_file))
1520 return SET_ERRNO(ERROR_USAGE, "Invalid --config file path");
1521 SAFE_STRNCPY(opts->config_file, path, sizeof(opts->config_file));
1522 continue;
1523 }
1524 // Handle -L and --log-file FILE (set log file path)
1525 if ((strcmp(argv[i], "-L") == 0 || strcmp(argv[i], "--log-file") == 0)) {
1526 if (i + 1 >= argc) {
1527 log_error("%s requires a file path", argv[i]);
1528 return ERROR_USAGE;
1529 }
1530 if (argv[i + 1][0] == '-') {
1531 log_error("%s requires a file path", argv[i]);
1532 return ERROR_USAGE;
1533 }
1534 SAFE_STRNCPY(opts->log_file, argv[i + 1], sizeof(opts->log_file));
1535 i++; // Skip the file argument
1536 }
1537 // NOTE: --color is now parsed in STAGE 1A (early, before help processing)
1538 // to ensure help output colors are applied correctly
1539 }
1540 }
1541 return ASCIICHAT_OK;
1542}
1543
1544static asciichat_error_t
1545handle_fallback_actions(options_t *opts, const binary_actions_t *actions) {
1546 if (actions->show_version) {
1547 // Show binary-level version from src/main.c
1548 opts->version = true;
1549 options_state_set(opts);
1550 return ASCIICHAT_OK;
1551 }
1552
1553 if (actions->create_config) {
1554 // Handle --config-create: create default config file and exit
1555 // Use provided path or default to user config location
1556 char config_path[PLATFORM_MAX_PATH_LENGTH];
1557 if (actions->config_create_path) {
1558 SAFE_STRNCPY(config_path, actions->config_create_path,
1559 sizeof(config_path));
1560 } else {
1561 // Use default config path: ~/.ascii-chat/config.toml
1562 char *config_dir = get_config_dir();
1563 if (!config_dir) {
1564 log_error("Failed to determine default config directory");
1565 return ERROR_CONFIG;
1566 }
1567 safe_snprintf(config_path, sizeof(config_path), "%sconfig.toml",
1568 config_dir);
1569 SAFE_FREE(config_dir);
1570 }
1571
1572 // Create config with default options
1573 asciichat_error_t result = config_create_default(config_path);
1574 if (result != ASCIICHAT_OK) {
1576 if (HAS_ERRNO(&err_ctx)) {
1577 log_error("Error creating config: %s", err_ctx.context_message);
1578 } else {
1579 log_error("Failed to create config file at %s", config_path);
1580 }
1581 return result;
1582 }
1583
1584 log_plain("Created default config file at: %s", config_path);
1585 return ASCIICHAT_OK; // Return successfully after creating config
1586 }
1587
1588 if (actions->create_manpage) {
1590 }
1591 return ASCIICHAT_OK;
1592}
1593
1594static asciichat_error_t build_mode_argv(int argc, char **argv, int mode_index,
1596 if (argc > 256)
1597 return SET_ERRNO(ERROR_INVALID_PARAM, "Too many arguments: %d", argc);
1598 int filtered_argc = 0;
1599 char **filtered_argv = NULL;
1600 if (!flags_command_build_argv(argc, argv, mode_index,
1601 is_binary_level_option_with_args, NULL,
1602 &filtered_argc, &filtered_argv))
1603 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate mode_argv");
1604 args->argc = filtered_argc;
1605 args->argv = filtered_argv;
1606 args->allocated = filtered_argv;
1607 return ASCIICHAT_OK;
1608}
1609
1610static void initialize_mode_defaults(options_t *opts,
1611 asciichat_mode_t detected_mode,
1612 const char *detected_session_string) {
1613 // Initialize all defaults using options_t_new_preserve_binary() to keep
1614 // binary-level options (--quiet, --verbose, --log-level, etc.) from being
1615 // reset
1616 (*opts) = options_t_new_preserve_binary(opts);
1617 if (detected_mode == MODE_MCP_SERVER || detected_mode == MODE_API_SERVER) {
1618 opts->port = OPT_MCP_PORT_DEFAULT;
1619 // Zero means use the available CPU count unless max-clients is configured.
1620 opts->max_clients = 0;
1621 }
1622 // If a session string was detected during mode detection, restore it after
1623 // options reset This ensures discovery mode knows which session to join
1624 if (detected_session_string[0] != '\0') {
1625 SAFE_STRNCPY(opts->session_string, detected_session_string,
1626 sizeof(opts->session_string));
1627 log_info("Detected session string from argv: '%s'",
1628 detected_session_string);
1629 }
1630
1631 // Encryption options default to disabled/empty
1632 opts->no_encrypt = 0;
1633 opts->encrypt_key[0] = '\0';
1634 opts->password[0] = '\0';
1635 opts->encrypt_keyfile[0] = '\0';
1636 opts->server_key[0] = '\0';
1637 opts->client_keys[0] = '\0';
1638 opts->palette_custom[0] = '\0';
1639
1640 // Set different default addresses for different modes
1641 if (detected_mode == MODE_CLIENT || detected_mode == MODE_MIRROR ||
1642 detected_mode == MODE_DISCOVERY) {
1643 // Client/Mirror/Discovery: connects to localhost by default (discovery uses
1644 // ACDS to find server)
1645 SAFE_SNPRINTF(opts->address, OPTIONS_BUFF_SIZE, "localhost");
1646 opts->address6[0] = '\0'; // Client doesn't use address6
1647 } else if (detected_mode == MODE_SERVER || detected_mode == MODE_MCP_SERVER) {
1648 // Server: binds to 127.0.0.1 (IPv4) and ::1 (IPv6) by default
1649 SAFE_SNPRINTF(opts->address, OPTIONS_BUFF_SIZE, "127.0.0.1");
1650 // address6 is now a positional argument, not an option
1651 opts->address6[0] = '\0';
1652 } else if (detected_mode == MODE_DISCOVERY_SERVICE) {
1653 // ACDS: binds to all interfaces by default
1654 SAFE_SNPRINTF(opts->address, OPTIONS_BUFF_SIZE, "0.0.0.0");
1655 opts->address6[0] = '\0';
1656 }
1657}
1658
1659static void build_options_schema(void) {}
1660
1661static asciichat_error_t load_options_config(options_t *opts,
1662 asciichat_mode_t detected_mode) {
1663#ifdef EMSCRIPTEN_BUILD
1664 // Browser options are supplied through OptionsBinding. There is no native
1665 // user/system configuration directory in a WASM module, and probing it
1666 // would make startup depend on the host filesystem emulation.
1667 (void)opts;
1668 (void)detected_mode;
1669 return ASCIICHAT_OK;
1670#endif
1671 // Isolated MCP renderers never load user/system configuration.
1672 if (SAFE_GETENV("ASCII_CHAT_MCP_WORKER")) {
1673 return ASCIICHAT_OK;
1674 }
1675 // Extract binary-level options BEFORE config loading (config may reset them)
1676 binary_level_opts_t binary_before_config = extract_binary_level(opts);
1677 // Publish options to RCU before config loading so that config logs get proper
1678 // colors from the parsed --color setting (e.g., --color=true)
1679 asciichat_error_t config_publish_result = options_state_set(opts);
1680 (void)config_publish_result; // Suppress unused variable warning
1681 // Load config files - now uses detected_mode directly for bitmask validation
1682 // Preserve the existing vertical flip configuration behavior.
1683 bool saved_flip_y_from_config = opts->flip_y;
1684 asciichat_error_t config_result =
1685 config_load_system_and_user(detected_mode, false, opts);
1686 (void)config_result; // Continue with defaults and CLI parsing regardless of
1687 // result
1688 if (binary_before_config.config_file[0]) {
1689 config_result = config_load_and_apply(
1690 detected_mode, binary_before_config.config_file, true, opts);
1691 if (config_result != ASCIICHAT_OK)
1692 return config_result;
1693 }
1694 // Telemetry CLI values are parsed again after config and environment
1695 // resolution.
1696 SAFE_STRNCPY(binary_before_config.otel_log_level, opts->otel_log_level,
1697 sizeof(binary_before_config.otel_log_level));
1698 SAFE_STRNCPY(binary_before_config.otel_endpoint, opts->otel_endpoint,
1699 sizeof(binary_before_config.otel_endpoint));
1700 SAFE_STRNCPY(binary_before_config.otel_ca_file, opts->otel_ca_file,
1701 sizeof(binary_before_config.otel_ca_file));
1702 SAFE_STRNCPY(binary_before_config.otel_enabled_telemetry,
1704 sizeof(binary_before_config.otel_enabled_telemetry));
1705 binary_before_config.otel_realtime_sample_rate =
1707 binary_before_config.otel_realtime_max_per_second =
1709 binary_before_config.otel_metrics_interval = opts->otel_metrics_interval;
1710 binary_before_config.otel_timeout = opts->otel_timeout;
1711 binary_before_config.otel_queue_capacity = opts->otel_queue_capacity;
1712 // Restore binary-level options (don't let config override command-line
1713 // options)
1714 restore_binary_level(opts, &binary_before_config);
1715
1716 // Preserve the existing vertical flip default.
1717 opts->flip_y = saved_flip_y_from_config;
1718 return ASCIICHAT_OK;
1719}
1720
1721static bool add_ascii_chat_dependencies(flags_schema_builder_t *builder) {
1722 static const flags_dependency_t dependencies[] = {
1723 {"url", "file", FLAGS_DEPENDENCY_CONFLICTS,
1724 "Option --url cannot be used with --file"},
1725 {"url", "loop", FLAGS_DEPENDENCY_CONFLICTS,
1726 "Option --url cannot be used with --loop"},
1727 {"no-encrypt", "encrypt", FLAGS_DEPENDENCY_CONFLICTS,
1728 "Cannot use --no-encrypt with --encrypt"},
1729 {"no-auth", "key", FLAGS_DEPENDENCY_CONFLICTS,
1730 "Cannot use --no-auth with --key"},
1731 {"no-auth", "password", FLAGS_DEPENDENCY_CONFLICTS,
1732 "Cannot use --no-auth with --password"},
1733 {"no-auth", "client-keys", FLAGS_DEPENDENCY_CONFLICTS,
1734 "Cannot use --no-auth with --client-keys"},
1735 {"no-auth", "server-key", FLAGS_DEPENDENCY_CONFLICTS,
1736 "Cannot use --no-auth with --server-key"},
1737 {"no-compress", "compression-level", FLAGS_DEPENDENCY_CONFLICTS,
1738 "Cannot use --no-compress with --compression-level"},
1739 {"encode-audio", "no-encode-audio", FLAGS_DEPENDENCY_CONFLICTS,
1740 "Cannot use both --encode-audio and --no-encode-audio"},
1741 {"waveform", "matrix", FLAGS_DEPENDENCY_CONFLICTS,
1742 "Option --waveform cannot be used with --matrix"},
1743 {"fft", "matrix", FLAGS_DEPENDENCY_CONFLICTS,
1744 "Option --fft cannot be used with --matrix"},
1745 {"waveform", "fft", FLAGS_DEPENDENCY_CONFLICTS,
1746 "Options --waveform and --fft cannot be used together"},
1747 {"waveform", "stretch", FLAGS_DEPENDENCY_CONFLICTS,
1748 "Option --waveform cannot be used with --stretch"},
1749 {"fft", "stretch", FLAGS_DEPENDENCY_CONFLICTS,
1750 "Option --fft cannot be used with --stretch"},
1751 {"snapshot-delay", "snapshot", FLAGS_DEPENDENCY_REQUIRES,
1752 "Option --snapshot-delay requires --snapshot"},
1753 {"loop", "file", FLAGS_DEPENDENCY_REQUIRES,
1754 "Option --loop requires --file"},
1755 };
1756 for (size_t i = 0; i < sizeof(dependencies) / sizeof(dependencies[0]); ++i)
1757 if (!flags_schema_builder_add_dependency(builder, &dependencies[i]))
1758 return false;
1759 return true;
1760}
1761
1763 if (!options)
1764 return SET_ERRNO(ERROR_INVALID_PARAM, "Options storage is NULL");
1765 const option_mode_bitmask_t mode_mask =
1766 options->detected_mode == MODE_DISCOVERY
1769 (1U << options->detected_mode));
1770 flags_schema_builder_t *builder = flags_schema_builder_create();
1771 if (!builder)
1772 return SET_ERRNO(ERROR_MEMORY,
1773 "Failed to create libflags validation schema");
1774 if (registry_add_all_to_flags_builder(builder, mode_mask) != ASCIICHAT_OK ||
1775 !add_ascii_chat_dependencies(builder)) {
1776 flags_schema_builder_destroy(builder);
1777 return SET_ERRNO(ERROR_CONFIG,
1778 "Failed to build libflags validation schema");
1779 }
1780 flags_context_t *context = flags_create(flags_schema_builder_schema(builder),
1781 options, sizeof(*options));
1782 if (!context) {
1783 flags_schema_builder_destroy(builder);
1784 return SET_ERRNO(ERROR_MEMORY,
1785 "Failed to create libflags validation context");
1786 }
1787 const bool valid = flags_validate(context);
1788 flags_destroy_preserving_storage(context);
1789 flags_schema_builder_destroy(builder);
1790 if (!valid)
1792 "One or more options failed libflags validation");
1793 return ASCIICHAT_OK;
1794}
1795
1796static asciichat_error_t parse_mode_options(options_t *opts,
1797 asciichat_mode_t detected_mode,
1798 int mode_argc, char **mode_argv,
1799 int *remaining_argc,
1800 char ***remaining_argv) {
1801 // Extract binary-level options BEFORE applying unified defaults
1802 // (which might override them from config files)
1803 binary_level_opts_t binary_before_defaults = extract_binary_level(opts);
1804 asciichat_mode_t mode_saved_for_parsing =
1805 detected_mode; // Save before defaults reset
1806 // Save flip_x and flip_y before applying defaults (should not be reset by
1807 // defaults)
1808 bool saved_flip_x = opts->flip_x;
1809 bool saved_flip_y = opts->flip_y;
1810 if (SAFE_GETENV("ASCII_CHAT_FLIP_X"))
1811 opts->flip_x = OPT_FLIP_X_DEFAULT;
1812 // An enabled environment flag overrides the opposite config-file choice.
1813 const char *encrypt_env = SAFE_GETENV("ASCII_CHAT_ENCRYPT");
1814 const char *no_encrypt_env = SAFE_GETENV("ASCII_CHAT_NO_ENCRYPT");
1815 if (encrypt_env && !no_encrypt_env && opts->encrypt_enabled)
1816 opts->no_encrypt = false;
1817 if (no_encrypt_env && !encrypt_env && opts->no_encrypt)
1818 opts->encrypt_enabled = false;
1819
1820 bool cli_encrypt = false, cli_no_encrypt = false;
1821 bool cli_flip_x = false, cli_flip_y = false;
1822 flags_parse_result_t argument_split = {0};
1823 const bool split_ok =
1824 flags_split_arguments(mode_argc, mode_argv, &argument_split);
1825 const int option_scan_end = split_ok && argument_split.options_ended
1826 ? argument_split.first_positional_index
1827 : mode_argc;
1828 for (int i = 1; i < option_scan_end; ++i) {
1829 cli_encrypt |= strcmp(mode_argv[i], "--encrypt") == 0 ||
1830 strcmp(mode_argv[i], "-E") == 0 ||
1831 strncmp(mode_argv[i], "--encrypt=", 10) == 0;
1832 cli_no_encrypt |= strcmp(mode_argv[i], "--no-encrypt") == 0 ||
1833 strncmp(mode_argv[i], "--no-encrypt=", 13) == 0;
1834 cli_flip_x |= strcmp(mode_argv[i], "--flip-x") == 0 ||
1835 strncmp(mode_argv[i], "--flip-x=", 9) == 0;
1836 cli_flip_y |= strcmp(mode_argv[i], "--flip-y") == 0 ||
1837 strncmp(mode_argv[i], "--flip-y=", 9) == 0;
1838 }
1839 // Bare boolean CLI flags toggle from false, independent of lower layers.
1840 if (cli_encrypt)
1841 opts->encrypt_enabled = false;
1842 if (cli_no_encrypt)
1843 opts->no_encrypt = false;
1844 // Restore binary-level options (they should never be overridden by defaults)
1845 restore_binary_level(opts, &binary_before_defaults);
1846
1847 // Restore flip_x and flip_y - they should keep the values from
1848 // options_t_new() unless explicitly set by the user (but defaults shouldn't
1849 // override them)
1850 if (!SAFE_GETENV("ASCII_CHAT_FLIP_X"))
1851 opts->flip_x = saved_flip_x;
1852 if (cli_flip_x)
1853 opts->flip_x = false;
1854 opts->flip_y = saved_flip_y;
1855
1856 // Restore detected_mode before parsing so mode validation works.
1857 opts->detected_mode = mode_saved_for_parsing;
1858
1859 // Save flip_x and flip_y before parsing - they should not be reset by the
1860 // parser
1861 bool saved_flip_x_for_parse = opts->flip_x;
1862 bool saved_flip_y_for_parse = opts->flip_y;
1863 // Note: json is already saved via extract_binary_level/restore_binary_level
1864 // mechanism Parse generic flags through libflags. Mode detection and
1865 // positional interpretation remain application-owned; the option schema,
1866 // storage, defaults, environment names, scalar parsing, callbacks, and
1867 // actions do not.
1868 option_mode_bitmask_t mode_bitmask = (1 << mode_saved_for_parsing);
1869 flags_schema_builder_t *flags_builder = flags_schema_builder_create();
1870 if (!flags_builder)
1871 return SET_ERRNO(ERROR_MEMORY, "Failed to create libflags schema builder");
1872 if (registry_add_all_to_flags_builder(flags_builder, mode_bitmask) !=
1873 ASCIICHAT_OK) {
1874 flags_schema_builder_destroy(flags_builder);
1875 return SET_ERRNO(ERROR_CONFIG, "Failed to build libflags option schema");
1876 }
1877 // The application interprets positional addresses and media after flags are
1878 // parsed.
1879 const flags_positional_spec_t positionals = {
1880 .name = "mode-arguments", .arity = FLAGS_POSITIONAL_ZERO_OR_MORE};
1881 if (!flags_schema_builder_add_positional(flags_builder, &positionals) ||
1882 !flags_schema_builder_set_argument_order(flags_builder,
1883 FLAGS_POSITIONAL_PERMUTE) ||
1884 !add_ascii_chat_dependencies(flags_builder)) {
1885 flags_schema_builder_destroy(flags_builder);
1886 return SET_ERRNO(ERROR_CONFIG, "Failed to configure libflags mode schema");
1887 }
1888 flags_context_t *flags_context = flags_create(
1889 flags_schema_builder_schema(flags_builder), opts, sizeof(*opts));
1890 if (!flags_context) {
1891 flags_schema_builder_destroy(flags_builder);
1892 return SET_ERRNO(ERROR_MEMORY, "Failed to create libflags option context");
1893 }
1894 const flags_environment_config_t environment = {.prefix = "ASCII_CHAT_",
1895 .derive_names = true};
1896 if (!flags_set_environment_config(flags_context, &environment) ||
1897 !flags_apply_environment(flags_context)) {
1898 flags_destroy_preserving_storage(flags_context);
1899 flags_schema_builder_destroy(flags_builder);
1900 return SET_ERRNO(ERROR_CONFIG, "Failed to apply environment options");
1901 }
1902 flags_parse_result_t parsed = {0};
1903 const bool parsed_ok =
1904 flags_parse(flags_context, mode_argc, mode_argv, &parsed);
1905 if (parsed_ok && parsed.positional_argc > 0) {
1906 char *error_message = NULL;
1907 int consumed = 0;
1908 if (detected_mode == MODE_CLIENT || detected_mode == MODE_DISCOVERY) {
1909 consumed = parse_client_address(
1910 parsed.positional_argv[0], opts, parsed.positional_argv + 1,
1911 parsed.positional_argc - 1, &error_message);
1912 } else if (detected_mode == MODE_SERVER ||
1913 detected_mode == MODE_DISCOVERY_SERVICE) {
1914 consumed = parse_server_bind_address(
1915 parsed.positional_argv[0], opts, parsed.positional_argv + 1,
1916 parsed.positional_argc - 1, &error_message);
1917 } else if (detected_mode == MODE_MIRROR) {
1918 consumed = parse_mirror_media(parsed.positional_argv[0], opts,
1919 parsed.positional_argv + 1,
1920 parsed.positional_argc - 1, &error_message);
1921 }
1922 if (consumed < 0 || consumed != parsed.positional_argc) {
1923 const char *detail =
1924 error_message ? error_message : "invalid positional argument";
1925 asciichat_error_t positional_error = SET_ERRNO(ERROR_USAGE, "%s", detail);
1926 SAFE_FREE(error_message);
1927 flags_destroy_preserving_storage(flags_context);
1928 flags_schema_builder_destroy(flags_builder);
1929 return positional_error;
1930 }
1931 SAFE_FREE(error_message);
1932 parsed.positional_argc = 0;
1933 }
1934 const bool schema_valid = parsed_ok && flags_validate(flags_context);
1935 if (parsed_ok && schema_valid && !flags_explicit_state_merge(flags_context)) {
1936 flags_destroy_preserving_storage(flags_context);
1937 flags_schema_builder_destroy(flags_builder);
1938 return SET_ERRNO(ERROR_MEMORY, "Failed to record explicit option state");
1939 }
1940 if (parsed_ok && schema_valid)
1942 flags_was_explicitly_set(flags_context, "flip-x"));
1943 flags_destroy_preserving_storage(flags_context);
1944 flags_schema_builder_destroy(flags_builder);
1945 if (!parsed_ok || !schema_valid)
1946 return SET_ERRNO(ERROR_USAGE,
1947 !parsed_ok ? "Failed to parse command-line options"
1948 : "Options violate a libflags dependency");
1949 if (remaining_argc)
1950 *remaining_argc = parsed.positional_argc;
1951 if (remaining_argv)
1952 *remaining_argv = parsed.positional_argv;
1954 if (cli_encrypt && !cli_no_encrypt && opts->encrypt_enabled)
1955 opts->no_encrypt = false;
1956 if (cli_no_encrypt && !cli_encrypt && opts->no_encrypt)
1957 opts->encrypt_enabled = false;
1958 // Restore flip_x and flip_y - they should keep their values unless explicitly
1959 // overridden
1960 if (!cli_flip_x && !SAFE_GETENV("ASCII_CHAT_FLIP_X"))
1961 opts->flip_x = saved_flip_x_for_parse;
1962 if (!cli_flip_y)
1963 opts->flip_y = saved_flip_y_for_parse;
1964 // json is already restored via the call to options_state_set which calls
1965 // restore_binary_level
1966 if (result != ASCIICHAT_OK) {
1967 // Convert ERROR_CONFIG to ERROR_USAGE for command-line parsing errors
1968 if (result == ERROR_CONFIG) {
1970 const char *error_detail = "invalid options";
1971 if (HAS_ERRNO(&err_ctx)) {
1972 error_detail = err_ctx.context_message;
1973 }
1974 return SET_ERRNO(ERROR_USAGE, "Failed to parse options: %s",
1975 error_detail);
1976 }
1977 return result;
1978 }
1979 return ASCIICHAT_OK;
1980}
1981
1982static asciichat_error_t publish_options_for_validation(options_t *opts) {
1983 // Publish options to RCU as soon as they're parsed
1984 // This ensures GET_OPTION() works during cleanup even if validation fails
1985 // Audio visualizers inherently need an audio capture pipeline. Make that
1986 // implication explicit so --waveform and --fft work without requiring a
1987 // redundant --audio flag (and override a stale false config value).
1988 if (opts->test_audio || opts->waveform || opts->fft)
1989 opts->audio_enabled = true;
1990 log_dev("Publishing parsed options to RCU before validation");
1991 asciichat_error_t early_publish = options_state_set(opts);
1992 if (early_publish != ASCIICHAT_OK) {
1993 log_error("Failed to publish parsed options to RCU state early");
1994
1995 return early_publish;
1996 }
1997 log_dev("Successfully published options to RCU");
1998 return ASCIICHAT_OK;
1999}
2000
2001static asciichat_error_t validate_custom_palette(options_t *opts) {
2002 // Auto-enable custom palette if palette-chars was set
2003 if (opts->palette_custom[0] != '\0') {
2004 // palette-chars was set - always use PALETTE_CUSTOM (overrides any explicit
2005 // --palette setting)
2007 opts->palette_custom_set = true;
2008 log_debug("Set PALETTE_CUSTOM because --palette-chars was provided");
2009
2010 // Validate palette characters for UTF-8 correctness
2011 if (!utf8_is_valid(opts->palette_custom)) {
2012 log_error("--palette-chars contains invalid UTF-8 sequences");
2013
2014 return option_error_invalid();
2015 }
2016
2017 // Check if palette contains non-ASCII characters
2018 bool has_non_ascii = !utf8_is_ascii_only(opts->palette_custom);
2019 if (has_non_ascii) {
2020 // Non-ASCII characters require UTF-8 support
2021 // Check if UTF-8 is explicitly disabled or unavailable
2022 bool utf8_disabled = (opts->force_utf8 == COLOR_SETTING_FALSE);
2023 bool utf8_auto_unavailable =
2025
2026 if (utf8_disabled) {
2027 log_error("--palette-chars contains non-ASCII characters but "
2028 "--utf8=false was specified");
2029 log_error(
2030 " Remove --utf8=false or use ASCII-only palette characters");
2031
2032 return option_error_invalid();
2033 }
2034
2035 if (utf8_auto_unavailable) {
2036 log_error("--palette-chars contains non-ASCII characters but terminal "
2037 "does not support UTF-8");
2038 log_error(" Use --utf8=true to force UTF-8 mode or use "
2039 "ASCII-only palette characters");
2040
2041 return option_error_invalid();
2042 }
2043 }
2044 }
2045 return ASCIICHAT_OK;
2046}
2047
2048static asciichat_error_t validate_encryption_key(options_t *opts) {
2049 crypto_policy_t policy = {
2050 .encrypt = opts->encrypt_enabled,
2051 .no_encrypt = opts->no_encrypt,
2052 .no_auth = opts->no_auth,
2053 .has_password = opts->password[0] != '\0',
2054 .has_identity =
2055 opts->encrypt_key[0] != '\0' || opts->num_identity_keys > 0,
2056 .has_verification_key =
2057 opts->server_key[0] != '\0' || opts->client_keys[0] != '\0',
2058 };
2059 uint8_t mode;
2060 asciichat_error_t result = crypto_policy_resolve(&policy, &mode);
2061 if (result != ASCIICHAT_OK)
2062 return result;
2063
2064 // Validate identity paths without changing the encryption policy.
2065 if (opts->encrypt_key[0] != '\0') {
2066 // A key may be a local file, a remote reference, or inline key material.
2067 // Only validate filesystem paths when the value is actually path-like;
2068 // inline SSH/base64/password keys must not be rejected by stat().
2069 bool key_is_inline = !path_looks_like_path(opts->encrypt_key);
2070 if (!is_remote_key_path(opts->encrypt_key) && !key_is_inline) {
2071 struct stat st;
2072 if (stat(opts->encrypt_key, &st) != 0) {
2073 log_error("Key file not found: %s", opts->encrypt_key);
2074
2075 return SET_ERRNO(ERROR_CRYPTO_KEY, "Key file not found: %s",
2076 opts->encrypt_key);
2077 }
2078 if ((st.st_mode & S_IFMT) != S_IFREG) {
2079 log_error("Key path is not a regular file: %s", opts->encrypt_key);
2080
2081 return SET_ERRNO(ERROR_CRYPTO_KEY, "Key path is not a regular file: %s",
2082 opts->encrypt_key);
2083 }
2084 }
2085 // Identity keys select authentication independently of payload encryption.
2086 }
2087 return ASCIICHAT_OK;
2088}
2089
2090static asciichat_error_t validate_color_filter(options_t *opts) {
2091 // Color filter validation and auto-enable
2092 if (opts->color_filter != COLOR_FILTER_NONE) {
2093 // Color filter requires color to be enabled
2094 if (opts->color == COLOR_SETTING_FALSE) {
2095 log_error("--color-filter cannot be used with --color=false");
2096
2097 return option_error_invalid();
2098 }
2099 // Auto-enable color when color filter is specified
2100 opts->color = COLOR_SETTING_TRUE;
2101 log_debug("Auto-enabled color because --color-filter was provided");
2102 }
2103 return ASCIICHAT_OK;
2104}
2105
2106static void apply_screen_defaults(options_t *opts, int mode_argc,
2107 char **mode_argv) {
2108 // Auto-disable splash when grep is used (since it's one-time startup screen)
2109 // UNLESS it was explicitly set by the user
2110 // Status screen is now compatible with --grep since we support auto-loading
2111 // patterns
2112 bool grep_was_provided = false;
2113 for (int i = 0; i < mode_argc; i++) {
2114 if (mode_argv[i] && (strcmp(mode_argv[i], "--grep") == 0 ||
2115 strncmp(mode_argv[i], "--grep=", 7) == 0)) {
2116 grep_was_provided = true;
2117 break;
2118 }
2119 }
2120
2121 if (grep_was_provided) {
2122 if (!flags_explicit_state_was_set("splash-screen")) {
2123 opts->splash_screen = false;
2124 log_debug("Auto-disabled splash because --grep was provided");
2125 }
2126 }
2127
2128 // Auto-disable splash and status screens when terminal is non-interactive or
2129 // CLAUDECODE is set This ensures clean output when running under LLM
2130 // automation or non-interactive shells
2131 bool is_terminal_interactive = terminal_is_interactive();
2132 bool is_claudecode_set = platform_getenv("CLAUDECODE") != NULL;
2133 bool should_auto_disable_screens =
2134 !is_terminal_interactive || is_claudecode_set;
2135
2136 if (should_auto_disable_screens) {
2137 if (!flags_explicit_state_was_set("splash-screen")) {
2138 opts->splash_screen = false;
2139 log_debug(
2140 "Auto-disabled splash (non-interactive terminal or CLAUDECODE set)");
2141 }
2142 if (!flags_explicit_state_was_set("status-screen")) {
2143 opts->status_screen = false;
2144 log_debug("Auto-disabled status screen (non-interactive terminal or "
2145 "CLAUDECODE set)");
2146 }
2147 }
2148}
2149
2150static asciichat_error_t validate_option_strings(const options_t *opts) {
2151// Validate all string options contain valid UTF-8
2152// This prevents crashes and corruption from invalid UTF-8 in any option
2153// DISABLED IN RELEASE BUILDS: utf8_is_valid() has performance issues with musl
2154#ifndef NDEBUG
2155 const char *string_fields[][2] = {
2156 {"address", opts->address},
2157 {"address6", opts->address6},
2158 {"encrypt_key", opts->encrypt_key},
2159 {"encrypt_keyfile", opts->encrypt_keyfile},
2160 {"server_key", opts->server_key},
2161 {"client_keys", opts->client_keys},
2162 {"discovery_server", opts->discovery_server},
2163 {"discovery_service_key", opts->discovery_service_key},
2164 {"discovery_database_path", opts->discovery_database_path},
2165 {"log_file", opts->log_file},
2166 {"media_file", opts->media_file},
2167 {"palette_custom", opts->palette_custom},
2168 {"stun_servers", opts->stun_servers},
2169 {"turn_servers", opts->turn_servers},
2170 {"turn_username", opts->turn_username},
2171 {"turn_credential", opts->turn_credential},
2172 {"turn_secret", opts->turn_secret},
2173 {"session_string", opts->session_string},
2174 {NULL, NULL}};
2175
2176 for (int i = 0; string_fields[i][0] != NULL; i++) {
2177 const char *field_name = string_fields[i][0];
2178 const char *field_value = string_fields[i][1];
2179
2180 // Skip empty strings
2181 if (!field_value || field_value[0] == '\0') {
2182 continue;
2183 }
2184
2185 // Validate UTF-8
2186 if (!utf8_is_valid(field_value)) {
2187 log_error("Option --%s contains invalid UTF-8 sequences", field_name);
2188 log_error(" Value: %s", field_value);
2189
2190 return option_error_invalid();
2191 }
2192 }
2193#else
2194 (void)(*opts);
2195#endif
2196 return ASCIICHAT_OK;
2197}
2198
2199static asciichat_error_t validate_parsed_options(options_t *opts,
2200 int remaining_argc,
2201 char **remaining_argv) {
2202 // Validate options
2203 log_dev("★ VALIDATE_OPTIONS_AND_REPORT: About to call");
2205 log_dev("★ VALIDATE_OPTIONS_AND_REPORT: Returned with result=%s",
2206 asciichat_error_format(NULL, result));
2207 if (result != ASCIICHAT_OK) {
2208 return result;
2209 }
2210 // Check for unexpected remaining arguments
2211 if (remaining_argc > 0) {
2212 log_error("Unexpected arguments after options:");
2213 for (int i = 0; i < remaining_argc; i++) {
2214 log_error(" %s", remaining_argv[i]);
2215 }
2216
2217 return option_error_invalid();
2218 }
2219 return ASCIICHAT_OK;
2220}
2221
2222static asciichat_error_t
2223finalize_mode_defaults(options_t *opts, asciichat_mode_t detected_mode) {
2224 // Mode-specific post-processing
2225 // Apply mode-specific defaults (port, websocket-port)
2226 log_dev("★ APPLY_MODE_SPECIFIC: About to call");
2228 log_dev("★ APPLY_MODE_SPECIFIC: Done");
2229 log_dev("Applied mode-specific defaults: port=%d, websocket_port=%d",
2230 opts->port, opts->websocket_port);
2231
2232 if (detected_mode == MODE_DISCOVERY_SERVICE) {
2233 // Set default paths if not specified
2234 log_debug("★ DISCOVERY_SERVICE: Handling discovery service defaults");
2235 if (opts->discovery_database_path[0] == '\0') {
2236 // Database: Try system-wide location first, fall back to user directories
2237 // Preference: /usr/local/var/ascii-chat/ > ~/.local/share/ascii-chat/ >
2238 // ~/.config/ascii-chat/
2239 log_debug(
2240 "★ DISCOVERY_SERVICE: About to call get_discovery_database_dir()");
2241 char *db_dir = get_discovery_database_dir();
2242 log_debug("★ DISCOVERY_SERVICE: get_discovery_database_dir() returned %p",
2243 (void *)db_dir);
2244 if (!db_dir) {
2245
2246 return SET_ERRNO(ERROR_CONFIG, "Failed to get database directory "
2247 "(tried system and user locations)");
2248 }
2249 safe_snprintf(opts->discovery_database_path,
2250 sizeof(opts->discovery_database_path), "%sdiscovery.db",
2251 db_dir);
2252 SAFE_FREE(db_dir);
2253 }
2254 }
2255 return ASCIICHAT_OK;
2256}
2257
2258static asciichat_error_t
2259collect_server_identity_keys(options_t *opts, asciichat_mode_t detected_mode,
2260 int argc, char **argv) {
2261 // Collect multiple --key flags for multi-key support (server/ACDS only)
2262 // This enables servers to load both SSH and GPG keys and select the right one
2263 // during handshake based on what the client expects
2264 if (detected_mode == MODE_SERVER || detected_mode == MODE_DISCOVERY_SERVICE) {
2265 log_debug("★ STAGE 7.1: About to collect identity keys");
2266 int num_keys = options_collect_identity_keys(opts, argc, argv);
2267 log_debug("★ STAGE 7.1: options_collect_identity_keys returned %d",
2268 num_keys);
2269 if (num_keys < 0) {
2270
2271 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to collect identity keys");
2272 }
2273 // num_keys == 0 is OK (no --key flags provided)
2274 }
2275 return ASCIICHAT_OK;
2276}
2277
2278static void finalize_dimensions(options_t *opts) {
2279 log_dev("★ STAGE 7.2: About to update dimensions");
2280
2281 // After parsing command line options, update dimensions
2282 // First set any auto dimensions to terminal size, then apply full height
2283 // logic
2284
2285 // Clear auto flags if dimensions were explicitly parsed from options
2286 // This must happen before update_dimensions_to_terminal_size to prevent
2287 // auto-detected values from overwriting user-specified dimensions Note:
2288 // width=0 and height=0 are special values meaning "auto-detect", so don't
2289 // clear auto flags for those
2290 if (opts->width != OPT_WIDTH_DEFAULT && opts->width != 0) {
2291 opts->auto_width = false;
2292 }
2293 if (opts->height != OPT_HEIGHT_DEFAULT && opts->height != 0) {
2294 opts->auto_height = false;
2295 }
2297 js_log_options("BEFORE_UPDATE_DIMS");
2298 js_log_options("CALLING_UPDATE_DIM");
2300 js_log_options("AFTER_UPDATE_DIM");
2301
2302 js_log_options("L11");
2303 js_log_options("L12");
2304 js_log_options("L13");
2305 js_log_options("L14");
2306 js_log_options("L15");
2307 js_log_options("CHECKPOINT B");
2308
2309 // SKIP: Check WEBCAM_DISABLED environment variable to enable test pattern
2310 // mode
2311 // TODO: Debug why logging here causes hang
2312 // const char *webcam_disabled = SAFE_GETENV("WEBCAM_DISABLED");
2313 // if (webcam_disabled &&
2314 // (strcmp(webcam_disabled, "1") == 0 ||
2315 // platform_strcasecmp(webcam_disabled, "true") == 0 ||
2316 // platform_strcasecmp(webcam_disabled, "yes") == 0 ||
2317 // platform_strcasecmp(webcam_disabled, "on") == 0)) {
2318 // opts.test_pattern = true;
2319 // }
2320
2321 js_log_options("CHECKPOINT C");
2322}
2323
2324static asciichat_error_t finalize_media_options(options_t *opts) {
2325 if (opts->test_pattern && opts->media_file[0] != '\0') {
2326 return SET_ERRNO(ERROR_USAGE, "--test-pattern and --file are mutually "
2327 "exclusive; choose one video source");
2328 }
2329 if (opts->test_pattern && opts->media_url[0] != '\0') {
2330 return SET_ERRNO(ERROR_USAGE, "--test-pattern and --url are mutually "
2331 "exclusive; choose one video source");
2332 }
2333 if (opts->test_pattern && (opts->waveform || opts->fft)) {
2334 return SET_ERRNO(ERROR_USAGE,
2335 "--test-pattern cannot be used with --waveform or --fft; "
2336 "choose video or audio visualization");
2337 }
2338
2339 // Apply --no-compress interaction with audio encoding
2340 js_log_options("Before --no-compress check");
2341 if (opts->no_compress) {
2342 js_log_options("In no_compress block");
2343 opts->encode_audio = false;
2344 js_log_options("Set encode_audio to false");
2345 log_debug("--no-compress set: disabling audio encoding");
2346 js_log_options("After log_debug in no_compress");
2347 }
2348 js_log_options("After --no-compress check");
2349
2350 // Let libflags classify the generic file-stream sentinel; ascii-chat keeps
2351 // ownership of the application-specific seek and output compatibility rules.
2352 js_log_options("Before media_from_stdin check");
2353 static const flags_option_spec_t media_file_schema = {.name = "file",
2354 .type = FLAGS_TYPE_FILE,
2355 .dash_behavior =
2356 FLAGS_DASH_STDIN};
2357 flags_stream_value_t media_stream = {0};
2358 if (opts->media_file[0] != '\0' &&
2359 flags_classify_stream(&media_file_schema, opts->media_file,
2360 &media_stream) &&
2361 media_stream.kind == FLAGS_STREAM_STDIN) {
2362 js_log_options("In media_from_stdin block");
2363 opts->media_from_stdin = true;
2364 js_log_options("Set media_from_stdin to true");
2365 log_debug("Media file set to stdin");
2366 js_log_options("After log_debug in media_from_stdin");
2367 }
2368 js_log_options("After media_from_stdin check");
2369
2370 // Validate --seek option
2371 js_log_options("Before --seek validation");
2372 js_log_options("Checking media_seek_timestamp");
2373 if (opts->media_seek_timestamp > 0.0) {
2374 js_log_options("In seek validation block");
2375 // Can't seek stdin
2376 if (opts->media_from_stdin) {
2377 js_log_options("Seek error: media_from_stdin");
2378 log_error("--seek cannot be used with stdin (--file -)");
2379
2380 return ERROR_INVALID_PARAM;
2381 }
2382
2383 // Require --file or --url
2384 js_log_options("Checking media_file and media_url for seek");
2385 if (opts->media_file[0] == '\0' && opts->media_url[0] == '\0') {
2386 js_log_options("Seek error: no media_file or media_url");
2387 log_error("--seek requires --file or --url");
2388
2389 return ERROR_INVALID_PARAM;
2390 }
2391 js_log_options("Seek validation passed");
2392 }
2393 js_log_options("After --seek validation");
2394
2395 // Validate --pause option
2396 js_log_options("Before --pause validation");
2397 js_log_options("Checking pause flag");
2398 if (opts->pause) {
2399 js_log_options("In pause validation block");
2400 // Require --file or --url (not webcam, not test pattern)
2401 if (opts->media_file[0] == '\0' && opts->media_url[0] == '\0') {
2402 js_log_options("Pause error: no media_file or media_url");
2403 log_error("--pause requires --file or --url");
2404
2405 return ERROR_INVALID_PARAM;
2406 }
2407 js_log_options("Pause validation passed");
2408 }
2409 js_log_options("After --pause validation");
2410
2411 js_log_options("Before media_url check");
2412 js_log_options("Checking media_url[0]");
2413 if (opts->media_url[0] != '\0') {
2414 js_log_options("Entering media_url block");
2415 // URL must be a valid HTTP(S) URL (YouTube URLs are HTTPS URLs)
2416 js_log_options("About to call url_is_valid");
2417 js_log_options("Before url_is_valid call");
2418 if (!url_is_valid(opts->media_url)) {
2419 js_log_options("url_is_valid returned false");
2420 log_error("--url must be a valid HTTP(S) URL: %s", opts->media_url);
2421
2422 return ERROR_INVALID_PARAM;
2423 }
2424 js_log_options("url_is_valid returned true");
2425 js_log_options("url_is_valid returned, before strstr check");
2426
2427 // Normalize bare URLs by prepending http:// if not present
2428 js_log_options("Before strstr check");
2429 if (!strstr(opts->media_url, "://")) {
2430 js_log_options("URL needs normalization");
2431 char normalized_url[OPTIONS_NORMALIZED_URL_BUFFER_SIZE];
2432 js_log_options("Before snprintf");
2433 int result = snprintf(normalized_url, sizeof(normalized_url), "http://%s",
2434 opts->media_url);
2435 js_log_options("After snprintf");
2436 if (result > 0 && result < (int)sizeof(normalized_url)) {
2437 js_log_options("snprintf successful, before SAFE_STRNCPY");
2438 SAFE_STRNCPY(opts->media_url, normalized_url, sizeof(opts->media_url));
2439 js_log_options("URL normalized");
2440 } else {
2441 js_log_options("snprintf failed");
2442 log_error("Failed to normalize URL (too long): %s", opts->media_url);
2443
2444 return ERROR_INVALID_PARAM;
2445 }
2446 }
2447 js_log_options("After normalization check");
2448 }
2449 js_log_options("After media_url block");
2450 return ASCIICHAT_OK;
2451}
2452
2453static asciichat_error_t publish_final_options(options_t *opts,
2454 asciichat_mode_t detected_mode,
2455 int mode_index) {
2456 opts->media_input = opts->media_file[0] != '\0' || opts->media_url[0] != '\0';
2457 if (opts->test_pattern)
2458 opts->flip_x = false;
2459
2460 // Save the quiet flag before publishing (RCU will be cleaned up before memory
2461 // report runs)
2462#if defined(DEBUG_MEMORY) && !defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
2463 js_log_options("Before quiet_for_memory_report assignment");
2464 bool quiet_for_memory_report = opts->quiet;
2465 js_log_options("After quiet_for_memory_report assignment");
2466#endif
2467
2468 // Publish parsed options to RCU state (replaces
2469 // options_state_populate_from_globals) This makes the options visible to all
2470 // threads via lock-free reads
2471 js_log_options("STAGE 8 RCU: Before options_state_set");
2472 js_log_options("Before log_info PERF");
2473 js_log_options("After log_info PERF");
2474 js_log_options("Calling options_state_set...");
2475 js_log_options("Before options_state_set call");
2476 opts->mode_arg_index = detected_mode == MODE_DISCOVERY ? -1 : mode_index;
2477 asciichat_error_t publish_result = options_state_set(opts);
2478 js_log_options("After options_state_set call");
2479 js_log_options("options_state_set returned");
2480 js_log_options("Before log_info options_state_set done");
2481 js_log_options("After log_info options_state_set done");
2482 js_log_options("Before publish_result check");
2483 if (publish_result != ASCIICHAT_OK) {
2484 js_log_options("publish_result not OK");
2485 log_error("Failed to publish parsed options to RCU state: %d",
2486 publish_result);
2487
2488 return publish_result;
2489 }
2490 js_log_options("publish_result is OK");
2491 js_log_options("options_state_set successful");
2492
2493 // Now update debug memory quiet mode with the saved quiet value
2494#if defined(DEBUG_MEMORY) && !defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
2495 debug_memory_set_quiet_mode(quiet_for_memory_report);
2496#endif
2497 return ASCIICHAT_OK;
2498}
2499
2500static void apply_logging_color_scheme(const options_t *opts) {
2501 // Now that options are parsed, set and apply the selected color scheme to
2502 // logging
2503 js_log_options("STAGE 8 ColorScheme: Checking color_scheme_name");
2504 js_log_options("Before color_scheme_name[0] check");
2505 if (opts->color_scheme_name[0] != '\0') {
2506 js_log_options("Color scheme name is set");
2507 js_log_options("Before colorscheme_set_active_scheme");
2508 js_log_options("Before colorscheme_set_active_scheme call");
2509 asciichat_error_t scheme_result =
2511 js_log_options("After colorscheme_set_active_scheme call");
2512 js_log_options("colorscheme_set_active_scheme returned");
2513 js_log_options("Before log_info colorscheme done");
2514 js_log_options("After log_info colorscheme done");
2515 js_log_options("Before scheme_result check");
2516 if (scheme_result == ASCIICHAT_OK) {
2517 js_log_options("scheme_result is OK");
2518 js_log_options("Before colorscheme_get_active_scheme");
2520 js_log_options("After colorscheme_get_active_scheme");
2521 js_log_options("Before scheme null check");
2522 if (scheme) {
2523 js_log_options("scheme is not null");
2524 js_log_options("Before log_set_color_scheme");
2525 log_set_color_scheme(scheme);
2526 js_log_options("After log_set_color_scheme");
2527 js_log_options("Color scheme applied");
2528 js_log_options("Before log_debug color scheme");
2529 log_dev("Color scheme applied: %s", opts->color_scheme_name);
2530 js_log_options("After log_debug color scheme");
2531 } else {
2532 js_log_options("scheme is null");
2533 js_log_options("No scheme returned from colorscheme_get_active_scheme");
2534 }
2535 } else {
2536 log_warn("Failed to apply color scheme: %s", opts->color_scheme_name);
2537 }
2538 }
2539}
2540
2541asciichat_error_t options_init(int argc, char **argv) {
2542 log_dev("starting with argc=%d, argv[0]=%s, argv[1]=%s", argc,
2543 (argv && argc > 0 && argv[0]) ? argv[0] : "(null)",
2544 (argv && argc > 1 && argv[1]) ? argv[1] : "N/A");
2545 asciichat_error_t result = validate_options_argv(argc, argv);
2546 if (result != ASCIICHAT_OK) {
2547 return result;
2548 }
2549 result = options_state_init();
2550 if (result != ASCIICHAT_OK) {
2551 return result;
2552 }
2553 log_dev("options_init: state initialized");
2554
2555 // Discover binary actions before mode parsing so help and early exits need no
2556 // media setup.
2557 handle_help_option(argc, argv);
2558 binary_actions_t actions = {.parsed_color_setting = COLOR_SETTING_AUTO};
2559 result = scan_binary_actions(argc, argv, &actions);
2560 if (result != ASCIICHAT_OK) {
2561 return result;
2562 }
2563 log_dev("options_init: binary actions scanned");
2564 set_action_flag(actions.has_action);
2565
2566 asciichat_mode_t detected_mode = MODE_DISCOVERY;
2567 char detected_session_string[SESSION_STRING_BUFFER_SIZE] = {0};
2568 int mode_index = -1;
2569 if (actions.show_version || actions.create_config || actions.create_manpage) {
2570 // Binary actions do not have a session mode. Avoid treating an optional
2571 // output path as a positional mode before the action is dispatched.
2572 detected_mode = MODE_DISCOVERY;
2573 mode_index = -1;
2574 } else {
2575 result = options_detect_mode(argc, argv, &detected_mode,
2576 detected_session_string, &mode_index);
2577 if (result != ASCIICHAT_OK) {
2578 return result;
2579 }
2580 }
2581 result = validate_early_color_mode(argc, argv);
2582 if (result != ASCIICHAT_OK) {
2583 return result;
2584 }
2585
2586 options_t opts = options_t_new();
2587 log_dev("options_init: options constructed");
2588 initialize_binary_options(&opts, detected_mode, &actions);
2589 log_dev("options_init: binary options initialized");
2590 bool handled = false;
2591 result = handle_immediate_actions(&opts, &actions, &handled);
2592 if (result != ASCIICHAT_OK || handled) {
2593 if (result != ASCIICHAT_OK)
2594 return result;
2595 }
2596 result = parse_binary_options(&opts, argc, argv);
2597 if (result != ASCIICHAT_OK) {
2598 return result;
2599 }
2600 if (actions.show_version || actions.create_config || actions.create_manpage) {
2601 result = handle_fallback_actions(&opts, &actions);
2602 if (result != ASCIICHAT_OK) {
2603 return result;
2604 }
2605 return ASCIICHAT_OK;
2606 }
2607
2608 // Mode parsing owns the temporary argv and schema until the shared cleanup
2609 // path.
2610 mode_arguments_t mode_args = {.argc = argc, .argv = argv};
2611 result = build_mode_argv(argc, argv, mode_index, &mode_args);
2612 if (result != ASCIICHAT_OK) {
2613 goto cleanup;
2614 }
2615 initialize_mode_defaults(&opts, detected_mode, detected_session_string);
2616 build_options_schema();
2617 // Apply defaults, config, environment, then CLI values in increasing
2618 // precedence.
2619 result = load_options_config(&opts, detected_mode);
2620 if (result != ASCIICHAT_OK) {
2621 goto cleanup;
2622 }
2623 int remaining_argc = 0;
2624 char **remaining_argv = NULL;
2625 result = parse_mode_options(&opts, detected_mode, mode_args.argc,
2626 mode_args.argv, &remaining_argc, &remaining_argv);
2627 if (result != ASCIICHAT_OK) {
2628 goto cleanup;
2629 }
2630 result = validate_custom_palette(&opts);
2631 if (result != ASCIICHAT_OK) {
2632 goto cleanup;
2633 }
2634 result = validate_glyph_palette(&opts);
2635 if (result != ASCIICHAT_OK)
2636 goto cleanup;
2637 // Remaining validators consume a published snapshot.
2638 result = publish_options_for_validation(&opts);
2639 if (result != ASCIICHAT_OK) {
2640 goto cleanup;
2641 }
2642 result = validate_encryption_key(&opts);
2643 if (result != ASCIICHAT_OK) {
2644 goto cleanup;
2645 }
2646 result = validate_color_filter(&opts);
2647 if (result != ASCIICHAT_OK) {
2648 goto cleanup;
2649 }
2650 apply_screen_defaults(&opts, mode_args.argc, mode_args.argv);
2651 result = validate_option_strings(&opts);
2652 if (result != ASCIICHAT_OK) {
2653 goto cleanup;
2654 }
2655 result = validate_parsed_options(&opts, remaining_argc, remaining_argv);
2656 if (result != ASCIICHAT_OK) {
2657 goto cleanup;
2658 }
2659 result = finalize_mode_defaults(&opts, detected_mode);
2660 if (result != ASCIICHAT_OK) {
2661 goto cleanup;
2662 }
2663 log_dev("★ STAGE 7: Starting post-processing");
2664 // Resolve identity, dimensions, and media before exposing the final options
2665 // to actions.
2666 result = collect_server_identity_keys(&opts, detected_mode, argc, argv);
2667 if (result != ASCIICHAT_OK) {
2668 goto cleanup;
2669 }
2670 finalize_dimensions(&opts);
2671 result = finalize_media_options(&opts);
2672 if (result != ASCIICHAT_OK) {
2673 goto cleanup;
2674 }
2675 result = publish_final_options(&opts, detected_mode, mode_index);
2676 if (result != ASCIICHAT_OK) {
2677 goto cleanup;
2678 }
2679 apply_logging_color_scheme(&opts);
2680
2681 // Deferred actions must see the final published options and may print output.
2682 if (actions.has_action) {
2684 }
2686
2687cleanup:
2688 flags_command_free_argv(mode_args.allocated);
2689 return result;
2690}
2691
2692void options_resolve_flip_x(options_t *opts, bool explicitly_set) {
2693 if (!opts)
2694 return;
2695 if (explicitly_set)
2696 return;
2697 if (opts->test_pattern)
2698 opts->flip_x = false;
2699 else
2700 opts->flip_x = !opts->media_input && !opts->waveform && !opts->fft;
2701}
Action option callbacks for ascii-chat.
void(* option_action_fn)(void)
Definition actions.h:234
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
@ OPTION_TYPE_INT
Integer value (–count 42).
Definition builder.h:182
@ OPTION_TYPE_DOUBLE
Floating point (–ratio 1.5).
Definition builder.h:184
@ OPTION_TYPE_STRING
String value (–name foo).
Definition builder.h:183
@ OPTION_TYPE_ACTION
Definition builder.h:186
@ OPTION_TYPE_CALLBACK
Custom parser function.
Definition builder.h:185
@ OPTION_TYPE_BOOL
Boolean flag (–flag, no value).
Definition builder.h:181
const color_scheme_t * colorscheme_get_active_scheme(void)
Get currently active color scheme.
asciichat_error_t colorscheme_set_active_scheme(const char *name)
Set the active color scheme.
const registry_entry_t * registry_find_entry_by_name(const char *long_name)
Get a registry entry by long name.
Definition core.c:136
bool is_session_string(const char *str)
Check if a string is a valid session string.
bool valid
Definition fft.c:29
audio_visualization_source_t source
Definition fft.c:25
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_GETENV(name)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
asciichat_error_t config_load_system_and_user(asciichat_mode_t detected_mode, bool strict, options_t *opts)
Load system config first, then user config (user config overrides system).
asciichat_error_t config_create_default(const char *config_path)
Create default configuration file with all default values.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_CRYPTO_KEY
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_USAGE
Definition error_codes.h:52
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
log_level_t
Logging levels enumeration.
Definition log/types.h:33
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
Definition log/log.c:818
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:635
void log_set_color_scheme(const color_scheme_t *scheme)
Set the color scheme for logging output.
Definition log/log.c:2179
#define OPT_STRIP_ANSI_DEFAULT
Default strip ANSI escape sequences flag.
Definition options.h:446
#define OPT_WEBRTC_SKIP_STUN_DEFAULT
Default WebRTC skip STUN flag (false = use STUN).
Definition options.h:677
#define OPT_ACDS_EXPOSE_IP_DEFAULT
Default ACDS expose IP flag (false = private by default).
Definition options.h:599
#define OPT_ENDPOINT_DISCOVERY_SERVICE
Default discovery service endpoint (what to connect to by default).
Definition options.h:555
#define OPT_COLOR_DEFAULT
Default color setting (COLOR_SETTING_AUTO = smart detection).
Definition options.h:449
#define OPT_NO_AUDIO_MIXER_DEFAULT
Default no audio mixer flag (false = enable mixer).
Definition options.h:513
#define OPT_FLIP_Y_DEFAULT
Default vertical flip state (false = no vertical flip).
Definition options.h:500
#define OPT_SHOW_CAPABILITIES_DEFAULT
Default show terminal capabilities flag.
Definition options.h:440
#define OPT_NO_ENCRYPT_DEFAULT
Default no encrypt flag (false = allow encryption).
Definition options.h:738
#define OPT_QUIET_DEFAULT
Default quiet mode flag (false = logging enabled).
Definition options.h:343
asciichat_mode_t
Mode type for options parsing.
Definition options.h:916
#define OPT_MICROPHONE_INDEX_DEFAULT
Default microphone device index (-1 means system default).
Definition options.h:710
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
#define OPT_TURN_SERVERS_DEFAULT
Default TURN server URLs (comma-separated).
Definition options.h:663
#define OPT_ENCODE_AUDIO_DEFAULT
Default audio encoding state (true = Opus encoding enabled).
Definition options.h:728
#define OPT_COLOR_MODE_DEFAULT
Default color mode (auto-detect terminal capabilities).
Definition options.h:428
#define OPT_PALETTE_TYPE_DEFAULT
Default palette type (standard ASCII art).
Definition options.h:462
#define OPT_RECONNECT_ATTEMPTS_DEFAULT
Default reconnect attempts (-1 means auto/infinite).
Definition options.h:581
#define OPT_SPEAKERS_VOLUME_DEFAULT
Default speakers volume (1.0 = normal volume).
Definition options.h:719
void update_dimensions_to_terminal_size(options_t *opts)
Update dimensions to match current terminal size.
#define OPT_NO_AUTH_DEFAULT
Default no auth flag (false = allow authentication).
Definition options.h:741
#define OPT_TEST_PATTERN_DEFAULT
Default test pattern mode (false = use actual webcam).
Definition options.h:510
#define OPT_OTEL_ENDPOINT_DEFAULT
Debug and Dev builds export to the local Spaniel Compose collector.
Definition options.h:349
#define OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT
Default WebRTC ICE gathering timeout in milliseconds (10 seconds).
Definition options.h:686
#define OPT_COMPRESSION_LEVEL_DEFAULT
Default compression level (1-9).
Definition options.h:584
#define OPT_ENCRYPT_ENABLED_DEFAULT
Default encrypt enabled flag (true = encryption required).
Definition options.h:735
#define OPT_REQUIRE_SERVER_IDENTITY_DEFAULT
Default require-server-identity setting for ACDS.
Definition options.h:605
#define OPT_ENABLE_KEEPAWAKE_DEFAULT
Default keep-awake (prevent system sleep) flag (false = normal system sleep).
Definition options.h:330
#define OPT_RENDER_MODE_DEFAULT
Default render mode (foreground characters only).
Definition options.h:459
#define OPT_ACDS_PORT_INT_DEFAULT
Default ACDS discovery service port (integer).
Definition options.h:593
#define OPT_AUDIO_ENABLED_DEFAULT
Default audio enabled flag (true = audio enabled by default).
Definition options.h:702
#define OPT_MATRIX_RAIN_DEFAULT
Default Matrix rain effect flag (false = disabled).
Definition options.h:491
#define OPT_FORCE_UTF8_DEFAULT
Default force UTF-8 support setting (auto-detect).
Definition options.h:443
#define OPT_STUN_SERVERS_DEFAULT
Default STUN server URLs (comma-separated).
Definition options.h:660
#define OPT_HELP_DEFAULT
Default help flag (false = don't show help).
Definition options.h:312
asciichat_error_t validate_glyph_palette(const options_t *opts)
Definition validation.c:25
#define OPT_ADDRESS6_DEFAULT
Default IPv6 server address.
Definition options.h:539
#define OPT_RENDER_FONT_SIZE_DEFAULT
Definition options.h:774
#define OPT_SPLASH_DEFAULT
Default splash screen flag (true = show splash, false = hide splash).
Definition options.h:318
#define OPT_RENDER_THEME_DEFAULT
Definition options.h:772
#define OPT_MEDIA_FROM_STDIN_DEFAULT
Default media from stdin flag (false = not reading from stdin).
Definition options.h:523
#define OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT
Default audio analysis enabled flag.
Definition options.h:722
#define OPT_VERSION_DEFAULT
Default version flag (false = don't show version).
Definition options.h:315
#define OPT_ACDS_DEFAULT
Default ACDS registration flag (false = disabled).
Definition options.h:590
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
#define OPT_NO_COMPRESS_DEFAULT
Default no compression flag (false = enable compression).
Definition options.h:587
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments with unified mode detection.
Definition options.c:2541
#define OPT_AUTO_HEIGHT_DEFAULT
Default auto-detect height flag (true = auto-detect from terminal).
Definition options.h:425
#define ASCII_RENDERER_DEFAULT
Consolidated options structure.
Definition options.h:962
#define OPT_REQUIRE_CLIENT_VERIFY_DEFAULT
Default require client verify flag (false = not required).
Definition options.h:747
option_mode_bitmask_t
Option mode bitmask.
Definition options.h:933
#define OPT_AUDIO_NO_PLAYBACK_DEFAULT
Default audio playback flag (false = enable playback).
Definition options.h:725
#define OPT_PAUSE_DEFAULT
Default pause media flag (false = play immediately).
Definition options.h:529
#define OPT_REQUIRE_SERVER_VERIFY_DEFAULT
Default require server verify flag (false = not required).
Definition options.h:744
#define OPT_NO_MDNS_ADVERTISE_DEFAULT
Default no mDNS advertise flag (false = advertise enabled).
Definition options.h:614
#define OPT_AUDIO_SOURCE_DEFAULT
Visualize all available sources by default.
Definition options.h:705
#define OPT_COLOR_FILTER_DEFAULT
Default color filter (none - no filtering).
Definition options.h:456
#define OPT_WEBCAM_INDEX_DEFAULT
Default webcam device index.
Definition options.h:507
void usage(FILE *desc, asciichat_mode_t mode)
Print usage information for a specific mode.
#define OPT_HEIGHT_DEFAULT
Default terminal height in characters.
Definition options.h:419
#define OPT_SNAPSHOT_MODE_DEFAULT
Default snapshot mode flag (false = continuous).
Definition options.h:474
#define OPT_MCP_PORT_DEFAULT
Definition options.h:575
#define OPT_COLOR_SCHEME_NAME_DEFAULT
Default color scheme name (pastel).
Definition options.h:365
#define OPT_MEDIA_LOOP_DEFAULT
Default loop media flag (false = play once).
Definition options.h:520
#define OPT_NO_CHECK_UPDATE_DEFAULT
Default no-check-update flag (false = check for updates enabled).
Definition options.h:336
#define OPT_STRETCH_DEFAULT
Default allow aspect ratio distortion flag.
Definition options.h:468
#define OPT_STATUS_SCREEN_DEFAULT
Default status screen flag (true = show status, false = hide status).
Definition options.h:324
#define OPT_LAN_DISCOVERY_DEFAULT
Default LAN discovery flag (false = discovery disabled).
Definition options.h:611
#define OPT_AUTO_WIDTH_DEFAULT
Default auto-detect width flag (true = auto-detect from terminal).
Definition options.h:422
#define OPT_JSON_DEFAULT
Default JSON logging flag (false = text output).
Definition options.h:362
#define OPT_ACDS_INSECURE_DEFAULT
Default ACDS insecure mode flag (false = verify server).
Definition options.h:602
bool has_action_flag(void)
Check if an action flag was detected.
Definition options.c:280
#define OPT_FPS_DEFAULT
Default FPS (frames per second).
Definition options.h:471
#define OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT
Default require-client-identity setting for ACDS.
Definition options.h:608
#define OPT_DISABLE_KEEPAWAKE_DEFAULT
Default disable keep-awake flag (false = allow system sleep prevention).
Definition options.h:333
#define OPT_ENABLE_UPNP_DEFAULT
Default enable UPnP flag (false = UPnP disabled).
Definition options.h:617
#define OPT_TURN_CREDENTIAL_DEFAULT
Default TURN credential (empty = use ACDS credentials).
Definition options.h:695
#define OPT_WEBRTC_SKIP_HOST_DEFAULT
Default WebRTC skip host candidates flag (false = use host candidates).
Definition options.h:683
bool is_remote_key_path(const char *key_path)
Check if a key path is a remote/virtual key (not a local file).
Definition validation.c:597
#define OPT_VERBOSE_LEVEL_DEFAULT
Default verbose level (0 = not verbose).
Definition options.h:353
#define OPT_SNAPSHOT_DELAY_DEFAULT
Default snapshot delay in seconds.
Definition options.h:487
#define OPT_LOG_LEVEL_DEFAULT
Default log level (LOG_INFO).
Definition options.h:356
#define OPT_MICROPHONE_SENSITIVITY_DEFAULT
Default microphone sensitivity (1.0 = normal volume).
Definition options.h:716
#define OPT_FLIP_X_DEFAULT
Webcam input is mirrored unless an orientation is explicitly selected.
Definition options.h:497
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:562
int options_collect_identity_keys(options_t *opts, int argc, char *argv[])
Collect multiple –key flags into identity_keys array.
Definition validation.c:525
#define OPT_MAX_CLIENTS_DEFAULT
Default maximum concurrent clients (server only).
Definition options.h:578
#define OPT_PREFER_WEBRTC_DEFAULT
Default prefer WebRTC flag (false = try direct TCP first).
Definition options.h:671
options_t options_t_new(void)
Initialize options by parsing command-line arguments.
Definition options.c:688
#define OPT_WEBRTC_DISABLE_TURN_DEFAULT
Default WebRTC disable TURN flag (false = use TURN).
Definition options.h:680
#define OPT_NO_WEBRTC_DEFAULT
Default no WebRTC flag (false = WebRTC enabled).
Definition options.h:674
#define OPT_ADDRESS_DEFAULT
Default server address for client connections.
Definition options.h:536
#define OPT_AUDIO_CAPTURE_SOURCE_DEFAULT
Preserve automatic local audio capture selection by default.
Definition options.h:707
#define OPT_PALETTE_CUSTOM_SET_DEFAULT
Default custom palette set flag (false = not set).
Definition options.h:465
#define OPT_TURN_USERNAME_DEFAULT
Default TURN username (empty = use ACDS credentials).
Definition options.h:692
#define OPT_SPEAKERS_INDEX_DEFAULT
Default speakers device index (-1 means system default).
Definition options.h:713
void update_dimensions_for_full_height(options_t *opts)
Update dimensions to use full terminal height while maintaining aspect ratio.
#define OPT_WEBSOCKET_PORT_SERVER_DEFAULT
Default WebSocket port for server mode (integer).
Definition options.h:565
#define OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT
Default media seek timestamp (start from beginning).
Definition options.h:526
#define OPT_WIDTH_DEFAULT
Default terminal width in characters.
Definition options.h:408
@ MODE_CLIENT
Client mode - network client options.
Definition options.h:918
@ MODE_MCP_SERVER
Model Context Protocol rendering server.
Definition options.h:922
@ MODE_DISCOVERY_SERVICE
Discovery server mode - session management and WebRTC signaling.
Definition options.h:920
@ MODE_API_SERVER
Image-to-ASCII HTTP API server.
Definition options.h:923
@ MODE_SERVER
Server mode - network server options.
Definition options.h:917
@ MODE_MIRROR
Mirror mode - local webcam viewing (no network).
Definition options.h:919
@ MODE_DISCOVERY
Discovery mode - participant that can dynamically become host.
Definition options.h:921
@ OPTION_MODE_ALL
All modes + binary.
Definition options.h:943
@ OPTION_MODE_BINARY
Binary-level options (parsed before mode detection).
Definition options.h:942
@ OPTION_MODE_CLIENT
Client mode (bit 1).
Definition options.h:936
@ OPTION_MODE_API_SERVER
Definition options.h:941
@ OPTION_MODE_DISCOVERY
Discovery mode (bit 4).
Definition options.h:939
@ OPTION_MODE_SERVER
Server mode (bit 0).
Definition options.h:935
@ OPTION_MODE_MIRROR
Mirror mode (bit 2).
Definition options.h:937
@ OPTION_MODE_NONE
No modes (invalid).
Definition options.h:934
@ OPTION_MODE_MCP_SERVER
Definition options.h:940
@ OPTION_MODE_DISCOVERY_SVC
Discovery server mode (bit 3).
Definition options.h:938
@ COLOR_SETTING_TRUE
Force colors ON: always colorize regardless of TTY/piping/CLAUDECODE.
Definition options.h:248
@ COLOR_SETTING_FALSE
Force colors OFF: disable all colors and logging colors.
Definition options.h:250
@ COLOR_SETTING_AUTO
Smart detection (default): colors if TTY and not CLAUDECODE and not piping.
Definition options.h:246
@ PALETTE_CUSTOM
User-defined via –palette-chars.
Definition palette.h:110
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:518
bool utf8_is_ascii_only(const char *str)
Check if a string contains only ASCII characters.
Definition utf8.c:141
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:132
char * get_log_dir(void)
Get log directory path appropriate for current build type.
Definition path.c:303
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:181
char * get_discovery_database_dir(void)
Get discovery service database directory with Homebrew-aware system-wide fallback.
Definition path.c:388
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:293
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Common utilities and helpers for option parsing across all modes.
Capture stdout/stderr and redirect to logging system.
Central registry of all command-line options with mode applicability.
struct flags_schema_builder flags_schema_builder_t
📝 Logging API with multiple log levels and terminal output control
🔢 Mathematical Utility Functions
void apply_mode_specific_defaults(options_t *opts)
Apply mode-specific defaults to an options struct after mode detection.
asciichat_error_t validate_options_and_report(const void *config, const void *opts)
Validate options and report errors to stderr.
asciichat_error_t config_load_and_apply(asciichat_mode_t detected_mode, const char *config_path, bool strict, options_t *opts)
Load configuration from TOML file and apply to global options.
TOML configuration file support for ascii-chat.
option_action_fn options_action_callback(const char *name, bool immediate)
void action_check_update_immediate(void)
Execute update check immediately (for early binary-level execution).
action_args_t args
void action_create_manpage(const char *output_path)
Generate man page template from options builder.
void action_completions(const char *shell_name, const char *output_path)
Generate shell completions and output to stdout or file.
deferred_action_t action
void action_create_config(const char *output_path)
Create default configuration file and exit.
void actions_execute_deferred(void)
Execute the deferred action (if any).
const char * asciichat_suggest_mode(const char *input)
Suggest closest matching mode using fuzzy matching.
Centralized enum and mode string conversion API.
Validation functions for options parsing.
#define OPTIONS_RESULT_BUFFER_SIZE
Definition options.c:55
void options_resolve_flip_x(options_t *opts, bool explicitly_set)
Definition options.c:2692
asciichat_error_t options_json_parse_value(const char *name, yyjson_val *value, char *output, size_t output_size, bool *omitted)
Definition options.c:200
yyjson_mut_val * options_json_schema_for_option(yyjson_mut_doc *document, const char *name)
Definition options.c:158
#define OPTIONS_NORMALIZED_URL_BUFFER_SIZE
Definition options.c:58
#define OPTIONS_LONG_FORM_BUFFER_SIZE
Definition options.c:56
options_t options_t_new_preserve_binary(const options_t *source)
Create a new options_t struct with all defaults set.
Definition options.c:911
#define OPTIONS_OPT_BUFFER_SIZE
Definition options.c:53
#define OPTIONS_LONG_FORM_EQ_BUFFER_SIZE
Definition options.c:57
asciichat_error_t options_validate_libflags(options_t *options)
Definition options.c:1762
#define OPTIONS_LOG_FILENAME_BUFFER_SIZE
Definition options.c:54
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
int parse_server_bind_address(const char *arg, void *config, char **remaining, int num_remaining, char **error_msg)
Parse server bind address positional argument.
Definition parsers.c:497
bool parse_color_setting(const char *arg, void *dest, char **error_msg)
Parse color setting option (–color flag).
Definition parsers.c:105
int parse_mirror_media(const char *arg, void *config, char **remaining, int num_remaining, char **error_msg)
Parse mirror mode positional argument (file path or URL).
Definition parsers.c:806
bool parse_log_level(const char *arg, void *dest, char **error_msg)
Parse log level option.
Definition parsers.c:383
int parse_client_address(const char *arg, void *config, char **remaining, int num_remaining, char **error_msg)
Parse client address positional argument.
Definition parsers.c:617
bool parse_color_mode(const char *arg, void *dest, char **error_msg)
Parse terminal color level option.
Definition parsers.c:151
Custom option parsers for enum types.
📂 Path Manipulation Utilities
asciichat_error_t crypto_policy_resolve(const crypto_policy_t *policy, uint8_t *mode)
Definition policy.c:4
asciichat_error_t registry_add_all_to_flags_builder(flags_schema_builder_t *builder, option_mode_bitmask_t mode_mask)
Definition public_api.c:84
asciichat_error_t options_state_init(void)
Initialize RCU options system.
Definition rcu.c:382
asciichat_error_t options_state_set(const options_t *opts)
Set options from a parsed options struct.
Definition rcu.c:459
bool terminal_supports_utf8(void)
bool terminal_is_interactive(void)
🔤 String Manipulation and Shell Escaping Utilities
#define SESSION_STRING_BUFFER_SIZE
const char * manpage_create_path
Definition options.c:1087
const char * config_create_path
Definition options.c:1086
bool check_update_flag_seen
Definition options.c:1091
int parsed_color_setting
Definition options.c:1089
bool no_check_update_flag_seen
Definition options.c:1092
bool color_setting_found
Definition options.c:1090
Create a new options_t struct with all defaults set.
Definition options.c:592
int otel_realtime_max_per_second
Definition options.c:612
log_level_t log_level
Definition options.c:593
unsigned short int verbose_level
Definition options.c:594
char otel_ca_file[OPTIONS_BUFF_SIZE]
Definition options.c:609
char log_file[OPTIONS_BUFF_SIZE]
Definition options.c:596
char config_file[OPTIONS_BUFF_SIZE]
Definition options.c:599
bool log_format_console_only
Definition options.c:604
char otel_log_level[OPTIONS_BUFF_SIZE]
Definition options.c:607
char otel_enabled_telemetry[OPTIONS_BUFF_SIZE]
Definition options.c:610
asciichat_mode_t detected_mode
Definition options.c:600
double otel_realtime_sample_rate
Definition options.c:611
char otel_endpoint[OPTIONS_BUFF_SIZE]
Definition options.c:608
Color scheme definition.
Definition colorscheme.h:81
The useful part of crypto policy is in transport_secure, encrypt, no_encrypt, no_auth: together they ...
Definition policy.h:19
The useful part of mcp job is in server, message, response, request: together they describe what is p...
Definition mcp.h:86
The useful part of binary actions is in show_version, create_config, create_manpage,...
Definition options.c:1104
char ** allocated
Definition options.c:1107
int max
Maximum value (or 0 if no limit).
Definition builder.h:227
struct option_metadata_t::@061372117173071240020206164036331043262170062306 numeric_range
const char ** enum_values
Definition builder.h:216
char otel_ca_file[256]
Definition options.h:1152
bool snapshot_mode
Snapshot mode (one frame and exit).
Definition options.h:1142
int otel_realtime_max_per_second
Definition options.h:1155
float speakers_volume
Speaker volume multiplier (0.0-1.0, default 1.0).
Definition options.h:1124
int discovery_port
discovery server port (default: 27225)
Definition options.h:1035
char media_url[256]
Network URL (HTTP/HTTPS/YouTube/RTSP) - takes priority over media_file.
Definition options.h:1072
double otel_realtime_sample_rate
Definition options.h:1154
size_t num_identity_keys
Number of identity keys loaded (0 means single-key mode using encrypt_key).
Definition options.h:1183
audio_capture_source_t audio_capture_source
Local capture/media selection policy.
Definition options.h:1115
bool encrypt_enabled
Enable encryption.
Definition options.h:1171
int otel_metrics_interval
Definition options.h:1156
terminal_color_mode_t color_mode
Color mode (auto/none/16/256/truecolor).
Definition options.h:1084
bool audio_spectral_gate
Definition options.h:1108
bool discovery_expose_ip
ACDS: explicitly allow public IP disclosure without verification (opt-in).
Definition options.h:1192
char turn_servers[256]
ACDS: Comma-separated list of TURN server URLs.
Definition options.h:1212
int force_utf8
UTF-8 support setting (auto/true/false).
Definition options.h:1089
int webrtc_ice_timeout_ms
–webrtc-ice-timeout: ICE gathering timeout in milliseconds (default: 10000)
Definition options.h:1205
bool discovery
Enable discovery session registration (default: false).
Definition options.h:1027
bool webrtc_relay_only
–webrtc-relay-only: Require TURN relay candidates
Definition options.h:1202
bool disable_keepawake
Explicitly disable system sleep prevention (allow OS to sleep).
Definition options.h:1166
int otel_queue_capacity
Definition options.h:1158
bool test_audio
Replace microphone capture with a repeating audible test signal.
Definition options.h:1104
int microphone_channel
First zero-based input channel; -1 downmixes all inputs.
Definition options.h:1120
float microphone_sensitivity
Microphone volume multiplier (0.0-1.0, default 1.0).
Definition options.h:1123
int microphone_channels
Selected microphone channels: 1 (speech) or 2 (stereo).
Definition options.h:1119
int compression_level
zstd compression level (1-9)
Definition options.h:1050
bool fft
Replace the video image with a live audio frequency spectrogram.
Definition options.h:1117
bool enable_keepawake
Explicitly enable system sleep prevention.
Definition options.h:1165
char otel_endpoint[256]
Definition options.h:1151
bool show_capabilities
Show terminal capabilities and exit.
Definition options.h:1088
bool no_mdns_advertise
Disable mDNS service advertisement (server only).
Definition options.h:1045
char password[256]
Password string.
Definition options.h:1173
int microphone_index
Microphone device index (-1 = default).
Definition options.h:1121
char config_file[256]
Config file path (–config).
Definition options.h:986
asciichat_mode_t detected_mode
Mode detected from command-line arguments.
Definition options.h:978
bool strip_ansi
Strip ANSI escape sequences.
Definition options.h:1147
bool audio_analysis_enabled
Enable audio analysis (debug).
Definition options.h:1125
int websocket_port
WebSocket server port (server/discovery-service only).
Definition options.h:1005
bool pause
Start playback paused (toggle with spacebar).
Definition options.h:1076
audio_source_t audio_source
Visualization source (all/call/mic/media).
Definition options.h:1114
bool json
Enable JSON logging (–json flag).
Definition options.h:1162
char stun_servers[256]
ACDS: Comma-separated list of STUN server URLs.
Definition options.h:1211
int height
Terminal height in characters (int for OPTION_TYPE_INT compat).
Definition options.h:992
bool enable_upnp
Opt-in TCP/WebSocket and WebRTC UDP mapping via –port-forwarding.
Definition options.h:1210
bool webrtc_skip_stun
–webrtc-skip-stun: Skip Stage 2 (STUN), go to TURN
Definition options.h:1201
bool log_format_console_only
Apply log format only to console output.
Definition options.h:1164
bool lan_discovery
Enable LAN service discovery via mDNS (client only).
Definition options.h:1044
char session_string[(38+1)]
Definition options.h:1021
bool audio_enabled
Enable audio streaming.
Definition options.h:1113
bool no_encrypt
Disable encryption (opt-out).
Definition options.h:1175
bool no_webrtc
–no-webrtc: Disable WebRTC, use Direct TCP only
Definition options.h:1199
bool matrix_rain
Matrix digital rain effect (false = disabled).
Definition options.h:1145
bool webrtc_disable_turn
–webrtc-disable-turn: Disable Stage 3 (TURN), use STUN only
Definition options.h:1203
bool audio_no_playback
Disable speaker playback (debug).
Definition options.h:1126
bool auto_height
Auto-detect height from terminal.
Definition options.h:994
log_level_t log_level
Log level threshold.
Definition options.h:1160
char turn_credential[256]
ACDS: Credential/password for TURN authentication.
Definition options.h:1214
bool require_server_identity
ACDS: require servers to provide signed Ed25519 identity.
Definition options.h:1188
int audio_fft_size
Definition options.h:1112
char palette_custom[256]
Custom palette characters.
Definition options.h:1221
bool status_screen
Show status screen (default: true = show, use –no-status-screen to hide).
Definition options.h:1230
char otel_log_level[256]
Definition options.h:1150
int max_clients
Maximum concurrent clients (server only).
Definition options.h:1020
bool palette_custom_set
True if custom palette was set.
Definition options.h:1222
bool no_auth
Disable authentication layer (–no-auth).
Definition options.h:1176
terminal_render_mode_t render_mode
Render mode (foreground/background/half-block).
Definition options.h:1087
bool splash_screen
Show splash screen (default: true = show, use –no-splash-screen to hide).
Definition options.h:1228
char discovery_database_path[256]
~/.ascii-chat/discovery.db)
Definition options.h:1038
char server_key[256]
Expected server public key (client).
Definition options.h:1177
bool media_input
Active input is a file/URL rather than the webcam.
Definition options.h:1097
bool no_audio_mixer
Disable audio mixer (debug).
Definition options.h:1065
bool audio_spectral_mixer
Explicit post-mix processing; disabled by default.
Definition options.h:1107
char encrypt_keyfile[256]
Alternative key file path.
Definition options.h:1174
bool webrtc_skip_host
–webrtc-skip-host: Skip host candidates, force STUN/TURN only
Definition options.h:1204
bool version
Show version information.
Definition options.h:985
int webcam_index
Webcam device index (0 = first).
Definition options.h:1062
bool stabilize
Reduce frame-to-frame character flicker.
Definition options.h:1131
bool no_compress
Disable compression entirely.
Definition options.h:1051
char address6[256]
IPv6 bind address (server only).
Definition options.h:1003
int speakers_index
Speakers device index (-1 = default).
Definition options.h:1122
color_filter_t color_filter
Monochromatic color filter (none/black/white/green/etc).
Definition options.h:1085
bool help
Show help message.
Definition options.h:984
bool prefer_webrtc
–prefer-webrtc: Try WebRTC before Direct TCP
Definition options.h:1198
bool quiet
Quiet mode (suppress logs).
Definition options.h:1140
double snapshot_delay
Snapshot delay in seconds.
Definition options.h:1143
bool audio_spectral
Definition options.h:1106
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1091
bool stretch
Allow aspect ratio distortion.
Definition options.h:1134
ascii_renderer_t renderer
Character selection algorithm.
Definition options.h:1133
bool waveform
Replace the video image with a live audio waveform.
Definition options.h:1116
int reconnect_attempts
Number of reconnection attempts (-1=infinite, 0=none).
Definition options.h:1057
bool test_pattern
Use test pattern instead of webcam.
Definition options.h:1063
char fft_scale[32]
Amplitude scale for the FFT visualization.
Definition options.h:1118
int port
Server port number.
Definition options.h:1004
bool media_from_stdin
Reading from stdin (detected from "--file -").
Definition options.h:1074
bool require_client_verify
Client: only connect to servers whose identity was verified by ACDS.
Definition options.h:1191
char discovery_server[256]
discovery server address (default: 127.0.0.1)
Definition options.h:1028
int width
Terminal width in characters (int for OPTION_TYPE_INT compat).
Definition options.h:991
int mode_arg_index
Explicit mode token in original argv, or -1 for implicit discovery/session strings.
Definition options.h:979
bool require_server_verify
Server: only accept clients who verified via ACDS.
Definition options.h:1190
palette_type_t palette_type
Selected palette type.
Definition options.h:1220
bool flip_y
Flip video vertically (Y-axis).
Definition options.h:1098
char color_scheme_name[64]
Color scheme name (e.g., "pastel", "nord").
Definition options.h:1086
char turn_secret[256]
ACDS: Shared secret for dynamic TURN credential generation (HMAC-SHA1).
Definition options.h:1215
bool media_loop
Loop media file playback.
Definition options.h:1073
char discovery_service_key[256]
HTTPS URL).
Definition options.h:1036
bool require_client_identity
ACDS: require clients to provide signed Ed25519 identity.
Definition options.h:1189
bool discovery_insecure
ACDS: skip server key verification (MITM-vulnerable, requires explicit opt-in).
Definition options.h:1193
bool no_check_update
Disable automatic update checks (default: false = checks enabled).
Definition options.h:1232
bool encode_audio
Enable Opus audio encoding.
Definition options.h:1052
int render_theme
0=dark 1=light 2=auto
Definition options.h:1253
char encrypt_key[256]
SSH/GPG key file path (first –key flag, kept for compatibility).
Definition options.h:1172
char media_file[256]
Media file path or "-" for stdin.
Definition options.h:1071
char otel_enabled_telemetry[256]
Definition options.h:1153
int color
Color setting (COLOR_SETTING_AUTO/TRUE/FALSE).
Definition options.h:1083
char turn_username[256]
ACDS: Username for TURN authentication.
Definition options.h:1213
char log_file[256]
Log file path.
Definition options.h:1159
unsigned short int verbose_level
Verbosity level (stackable -V).
Definition options.h:1141
char address[256]
Server address (client) or bind address (server).
Definition options.h:1002
bool reduce_noise
Apply neural microphone noise reduction in client-like modes.
Definition options.h:1109
bool flip_x
Effective horizontal orientation.
Definition options.h:1095
char grep_pattern[256]
PCRE2 regex for log filtering.
Definition options.h:1161
bool auto_width
Auto-detect width from terminal.
Definition options.h:993
char client_keys[256]
Allowed client keys (server).
Definition options.h:1178
double render_font_size
Font size in points (0 selects an automatic size).
Definition options.h:1255
double media_seek_timestamp
Seek to timestamp in seconds before playback.
Definition options.h:1075
Registry entry - stores option definition with mode bitmask and metadata.
option_type_t type
bool owns_memory
const char * long_name
size_t default_value_size
option_mode_bitmask_t mode_bitmask
option_metadata_t metadata
Enum values, numeric ranges, examples.
const char * help_text
const char * platform_getenv(const char *name)
Definition system.c:45
⏱️ High-precision timing utilities using sokol_time.h and uthash
🌐 Production-Grade URL Validation and Parsing
🔤 UTF-8 Encoding and Decoding Utilities
bool platform_get_temp_dir(char *temp_dir, size_t path_size)
Definition util.c:81