diff --git a/tests/test_android_bridge.c b/tests/test_android_bridge.c index c4e6373b4..70c299082 100644 --- a/tests/test_android_bridge.c +++ b/tests/test_android_bridge.c @@ -1,13 +1,20 @@ -/* Регрессии native bridge: владение config callbacks и границы батчей настоящего Opus-декодера. */ +/* Регрессии native bridge: config callbacks, сохранение идентичности и батчи настоящего Opus-декодера. */ #include #include #include #include +#include +#include +#include +#include #include "../lib/debug_config.h" #include "../lib/mem.h" #include "../src/media_async/voice_file.h" +#include "../src/config_parser.h" +#include "../src/transport_layer/secure_channel.h" #include "../tools/chatgui-android/jni_bridge/android_jni_bridge.h" +#include "../tools/chatgui-android/libutun_lite/instance_lite.h" #include "../tools/chatgui-android/libutun_lite/utun_config_api.h" #include "test_utils.h" @@ -120,6 +127,86 @@ static int check_database_cleanup(const char* directory) { return 0; } +/* Только полностью записанная пара, права 0600, согласованность X25519 и отсутствие оставшихся temp. */ +static int check_identity_file(const char* directory, const struct global_config* identity) { + char path[1024], text[256], expected[256]; + snprintf(path, sizeof(path), "%s/keys.conf", directory); + FILE* file = fopen(path, "rb"); REQUIRE(file); + size_t length = fread(text, 1, sizeof(text), file); + int read_error = ferror(file), closed = fclose(file); + int expected_length = snprintf(expected, sizeof(expected), "public_key=%s\nprivate_key=%s\n", + identity->my_public_key_hex, identity->my_private_key_hex); + REQUIRE(!read_error && !closed && length == (size_t)expected_length && !memcmp(text, expected, length)); + struct stat info; + REQUIRE(!stat(path, &info) && (info.st_mode & 0777) == 0600); + struct SC_MYKEYS keys; uint8_t derived[SC_PUBKEY_SIZE]; + REQUIRE(sc_init_local_keys(&keys, identity->my_public_key_hex, identity->my_private_key_hex) == SC_OK); + REQUIRE(sc_compute_public_key_from_private(keys.private_key, derived) == SC_OK); + REQUIRE(!memcmp(keys.public_key, derived, sizeof(derived))); + REQUIRE(sc_derive_node_id_from_pubkey(derived) == identity->my_node_id); + DIR* entries = opendir(directory); REQUIRE(entries); + int unexpected = 0; + struct dirent* entry; + while ((entry = readdir(entries))) + unexpected += strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..") && strcmp(entry->d_name, "keys.conf"); + REQUIRE(!closedir(entries) && !unexpected); + return 0; +} + +/* Настоящие ошибки open, flush и publish не меняют config и не разрушают прежний keys.conf. */ +static int check_identity_persistence(const char* directory) { + struct utun_config* config = u_calloc(1, sizeof(*config)); REQUIRE(config); + REQUIRE(instance_lite_generate_keys(NULL) == -1); + REQUIRE(instance_lite_generate_keys(config) == -1); + /* Выбранный общим INI-парсером каталог: пробелы и последнее значение должны сохранять смысл. */ + char ini[1024]; + int length = snprintf(ini, sizeof(ini), "[global]\ndb_path=/nonexistent/utun-identity\n db_path = %s \n", directory); + struct utun_config* parsed = parse_config_from_buf(ini, (size_t)length, "android-identity-test"); REQUIRE(parsed); + config->global = parsed->global; + free_config(parsed); + REQUIRE(!instance_lite_generate_keys(config)); + REQUIRE(!check_identity_file(directory, &config->global)); + struct global_config previous = config->global; + REQUIRE(!instance_lite_generate_keys(config)); + REQUIRE(strcmp(previous.my_public_key_hex, config->global.my_public_key_hex)); + REQUIRE(!check_identity_file(directory, &config->global)); + previous = config->global; + + struct rlimit original, limited; + REQUIRE(!getrlimit(RLIMIT_FSIZE, &original)); + limited = original; limited.rlim_cur = 64; + struct sigaction ignore = {0}, old_signal; + ignore.sa_handler = SIG_IGN; + REQUIRE(!sigemptyset(&ignore.sa_mask) && !sigaction(SIGXFSZ, &ignore, &old_signal)); + int limit_result = setrlimit(RLIMIT_FSIZE, &limited); + int result = limit_result ? 0 : instance_lite_generate_keys(config); + int restored = setrlimit(RLIMIT_FSIZE, &original); + int signal_restored = sigaction(SIGXFSZ, &old_signal, NULL); + REQUIRE(!limit_result && !restored && !signal_restored && result == -1); + REQUIRE(!memcmp(&previous, &config->global, sizeof(previous))); + REQUIRE(!check_identity_file(directory, &previous)); + + char path[1024], backup[1024]; + snprintf(path, sizeof(path), "%s/keys.conf", directory); + snprintf(backup, sizeof(backup), "%s/identity-backup", directory); + REQUIRE(!rename(path, backup) && !utun_mkdir(path, 0700)); + REQUIRE(instance_lite_generate_keys(config) == -1); + REQUIRE(!memcmp(&previous, &config->global, sizeof(previous))); + REQUIRE(!test_rmdir(path) && !rename(backup, path)); + REQUIRE(!check_identity_file(directory, &previous)); + snprintf(config->global.db_path, sizeof(config->global.db_path), "%s/missing", directory); + struct global_config missing = config->global; + REQUIRE(instance_lite_generate_keys(config) == -1); + REQUIRE(!memcmp(&missing, &config->global, sizeof(missing))); + REQUIRE(!check_identity_file(directory, &previous)); + config->global = previous; + REQUIRE(!instance_lite_generate_keys(config) && !check_identity_file(directory, &config->global)); + REQUIRE(!test_unlink(path)); + u_free(config); + printf("[PASS] identity persistence: coherent keys, private mode, parsed path, flush/open/publish failures and retry\n"); + return 0; +} + /* Один и тот же файл декодируется покадрово и батчами: PCM и количество отсчётов должны совпасть. */ static int check_voice_batches(const char* path, int rate, int channels) { int frame = rate / 50 * channels, count = frame * 27; @@ -177,6 +264,7 @@ int main(void) { REQUIRE(length > 0 && length < (int)sizeof(directory)); REQUIRE(!test_mkdtemp(directory)); failed += check_database_cleanup(directory); + failed += check_identity_persistence(directory); snprintf(path, sizeof(path), "%s/voice.opus", directory); const int rates[] = {8000, 12000, 16000, 24000, 48000}; for (unsigned i = 0; i < sizeof(rates) / sizeof(rates[0]); i++) diff --git a/tools/chatgui-android/libutun_lite/instance_lite.c b/tools/chatgui-android/libutun_lite/instance_lite.c index 1894eddef..cae1e07d2 100644 --- a/tools/chatgui-android/libutun_lite/instance_lite.c +++ b/tools/chatgui-android/libutun_lite/instance_lite.c @@ -12,6 +12,7 @@ #include "utun_instance.h" #include "config_parser.h" #include "config_updater.h" +#include "file_io.h" #include "secure_channel.h" #include "topo_node_sqlite.h" #include "chat/chat_core.h" @@ -44,7 +45,6 @@ #include #include #include -#include #ifdef __ANDROID__ #include @@ -63,7 +63,7 @@ * Each variable has exactly ONE writer — no data races by construction. * * Kotlin-writes (signals/commands to C): - * g_stop, g_do_restart, g_restart_config, g_event_handler, g_db_path + * g_stop, g_do_restart, g_restart_config, g_event_handler * C-writes (state to Kotlin): * g_ua, g_inst, g_running, g_thread_exited, g_thread_running */ @@ -93,87 +93,60 @@ static volatile int g_running = 0; /* C-write, Kotlin-read */ static volatile int g_thread_running = 0; /* C-write + Kotlin CAS-guard for start() */ static volatile int g_thread_exited = 0; /* C-write (under mutex), Kotlin-read */ static volatile int g_generation = 0; /* Kotlin-write, C-read */ -static char g_db_path[512]; /* Kotlin-write (start), C-read (init) */ static instance_lite_event_fn g_event_handler = NULL; /* Kotlin-write, C-read+call */ -static char g_generated_pub[65]; -static char g_generated_priv[65]; static pthread_mutex_t g_stop_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_stop_cond = PTHREAD_COND_INITIALIZER; -/* ── Generate X25519 key pair, hex-encode to out buffers ── */ - -static int generate_x25519_keys(char pub_hex[65], char priv_hex[65]) { - EVP_PKEY* pkey = NULL; - EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_X25519, NULL); - if (!ctx) return -1; - if (EVP_PKEY_keygen_init(ctx) <= 0 || EVP_PKEY_generate(ctx, &pkey) <= 0) { - EVP_PKEY_CTX_free(ctx); - return -1; +/* Генерируем отдельно от config: не публикуем в памяти ключи, которые не удалось сохранить. */ +int instance_lite_generate_keys(struct utun_config* config) { + if (!config || !config->global.db_path[0]) { + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Android identity generation requires a database directory"); return -1; } - EVP_PKEY_CTX_free(ctx); - size_t pkLen = 32, skLen = 32; - uint8_t pk[32], sk[32]; - EVP_PKEY_get_raw_public_key(pkey, pk, &pkLen); - EVP_PKEY_get_raw_private_key(pkey, sk, &skLen); - EVP_PKEY_free(pkey); - for (int i = 0; i < 32; i++) snprintf(pub_hex + i * 2, 3, "%02x", pk[i]); - for (int i = 0; i < 32; i++) snprintf(priv_hex + i * 2, 3, "%02x", sk[i]); - pub_hex[64] = '\0'; - priv_hex[64] = '\0'; + struct SC_MYKEYS keys; + if (sc_generate_keypair(&keys) != SC_OK) { + DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Android identity key generation failed"); return -1; + } + uint64_t node_id = sc_derive_node_id_from_pubkey(keys.public_key); + if (!node_id) { DEBUG_ERROR(DEBUG_CATEGORY_CRYPTO, "Android identity derived zero node_id"); return -1; } + char pub[65], priv[65]; + bytes_to_hex(keys.public_key, sizeof(keys.public_key), pub, sizeof(pub)); + bytes_to_hex(keys.private_key, sizeof(keys.private_key), priv, sizeof(priv)); + char filename[sizeof(config->global.db_path) + sizeof("/keys.conf")]; + snprintf(filename, sizeof(filename), "%s/keys.conf", config->global.db_path); + struct file_io_temp output = {0}; + const char* phase = "open"; + if (file_io_temp_open(&output, filename, FILE_IO_DURABLE)) goto failed; + phase = "write"; + if (fprintf(output.file, "public_key=%s\nprivate_key=%s\n", pub, priv) < 0) { + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Android identity write failed path=%s errno=%d: %s", filename, errno, strerror(errno)); + goto failed; + } + phase = "finish"; + if (file_io_temp_finish(&output)) goto failed; + phase = "publish"; + if (file_io_temp_publish(&output, output.temporary, filename)) goto failed; + file_io_temp_discard(&output); + memcpy(config->global.my_public_key_hex, pub, sizeof(pub)); + memcpy(config->global.my_private_key_hex, priv, sizeof(priv)); + config->global.my_node_id = node_id; + DEBUG_INFO(DEBUG_CATEGORY_CONFIG, "Android identity saved path=%s node_id=%016llx", filename, (unsigned long long)node_id); return 0; -} - -static void save_keys_to_file(const char* pub, const char* priv) { - if (!g_db_path[0]) { IL_LOGE("save_keys_to_file: g_db_path is empty, keys not saved to disk"); return; } - char fname[512]; - snprintf(fname, sizeof(fname), "%s/keys.conf", g_db_path); - FILE* f = fopen(fname, "w"); - if (!f) { IL_LOGE("cannot write %s: %s", fname, strerror(errno)); return; } - fchmod(fileno(f), 0600); - fprintf(f, "public_key=%s\nprivate_key=%s\n", pub, priv); - fclose(f); - IL_LOGI("keys saved to %s", fname); +failed: + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Android identity save failed path=%s phase=%s published=%d", + filename, phase, !strcmp(phase, "publish") && !output.temporary[0]); + file_io_temp_discard(&output); + return -1; } /* ── Ensure valid keys in config, generate if missing ── */ -static void ensure_keys(struct utun_config* config) { +static int ensure_keys(struct utun_config* config) { if (strlen(config->global.my_private_key_hex) != 64 || strlen(config->global.my_public_key_hex) != 64) { IL_LOGI("config keys missing or invalid, generating new X25519 keypair"); - if (generate_x25519_keys(g_generated_pub, g_generated_priv) == 0) { - memcpy(config->global.my_public_key_hex, g_generated_pub, 65); - memcpy(config->global.my_private_key_hex, g_generated_priv, 65); - IL_LOGI("new keys generated pub=%s", g_generated_pub); - save_keys_to_file(g_generated_pub, g_generated_priv); - } else { - IL_LOGE("key generation failed"); - } + return instance_lite_generate_keys(config); } -} - -/* ── Helper: extract single config value by key ── */ - -static const char* cfg_get(const char* text, const char* key) { - size_t klen = strlen(key); - const char* p = text; - while (*p) { - if (strncmp(p, key, klen) == 0 && p[klen] == '=') { - return p + klen + 1; - } - while (*p && *p != '\n') p++; - if (*p == '\n') p++; - } - return NULL; -} - -static void cfg_get_val(const char* text, const char* key, char* out, size_t out_sz) { - const char* v = cfg_get(text, key); - if (!v) { out[0] = '\0'; return; } - size_t i = 0; - while (*v && *v != '\n' && *v != '\r' && i < out_sz - 1) - out[i++] = *v++; - out[i] = '\0'; + return 0; } /* ── Chat event forward → Kotlin callback ── */ @@ -304,6 +277,13 @@ static void* instance_thread(void* arg) { config->global.client_type = CLIENT_TYPE_MOBILE; /* Android — всегда мобильный узел (keepalive standby/normal) */ install_crash_handlers(); + if (ensure_keys(config)) { + IL_LOGE("startup refused: Android identity is not saved"); + free_config(config); + __atomic_store_n(&g_thread_running, 0, __ATOMIC_RELEASE); + pthread_detach(pthread_self()); + return NULL; + } g_ua = uasync_create(); my_ua = g_ua; @@ -314,8 +294,6 @@ static void* instance_thread(void* arg) { udp_log_attach(g_ua); IL_LOGI("[EVT_DIAG] thread: about to set chat_event handler, g_event_handler=%p", (void*)g_event_handler); - ensure_keys(config); - g_inst = utun_instance_create_from_config(g_ua, config); my_inst = g_inst; if (!g_inst) { @@ -416,6 +394,7 @@ static void* instance_thread(void* arg) { struct utun_config* config = parse_config_from_buf(cfg, strlen(cfg), "android"); u_free(cfg); if (!config) { IL_LOGE("poll exit: parse_config failed"); break; } + if (ensure_keys(config)) { IL_LOGE("poll exit: Android identity is not saved"); free_config(config); break; } config->global.client_type = CLIENT_TYPE_MOBILE; /* Android — всегда мобильный узел */ udp_log_set_target(config->global.log_udp_ip, config->global.log_udp_port); udp_log_attach(g_ua); @@ -512,8 +491,6 @@ int instance_lite_start(const char* config_text) { debug_set_category_level(DEBUG_CATEGORY_DUMP, DEBUG_LEVEL_WARN); debug_enable_function_name(0); - cfg_get_val(config_text, "db_path", g_db_path, sizeof(g_db_path)); - char* config_copy = u_strdup(config_text); if (!config_copy) { __atomic_store_n(&g_thread_running, 0, __ATOMIC_RELEASE); return -1; } @@ -739,16 +716,11 @@ static void regenerate_trampoline(void* arg) { if (!g_inst || !g_inst->config) { IL_LOGE("regenerate_keys: instance not running"); return; } struct utun_config* config = g_inst->config; IL_LOGI("regenerating keys..."); - config->global.my_public_key_hex[0] = '\0'; - config->global.my_private_key_hex[0] = '\0'; - ensure_keys(config); - if (g_generated_pub[0]) { - uint8_t pk_bin[32]; - for (int i = 0; i < 32; i++) { unsigned int b; sscanf(g_generated_pub + i * 2, "%2x", &b); pk_bin[i] = (uint8_t)b; } - g_inst->node_id = sc_derive_node_id_from_pubkey(pk_bin); - sc_init_local_keys(&g_inst->my_keys, g_generated_pub, g_generated_priv); + if (instance_lite_generate_keys(config) == 0) { + g_inst->node_id = config->global.my_node_id; + sc_init_local_keys(&g_inst->my_keys, config->global.my_public_key_hex, config->global.my_private_key_hex); IL_LOGI("keys regenerated, node_id=0x%016llx", (unsigned long long)g_inst->node_id); - chat_event_post(g_inst, CHAT_EVT_KEYS_GENERATED, (const uint8_t*)g_generated_pub, 64); + chat_event_post(g_inst, CHAT_EVT_KEYS_GENERATED, (const uint8_t*)config->global.my_public_key_hex, 64); } } diff --git a/tools/chatgui-android/libutun_lite/instance_lite.h b/tools/chatgui-android/libutun_lite/instance_lite.h index 0c68e67ae..9fe202763 100644 --- a/tools/chatgui-android/libutun_lite/instance_lite.h +++ b/tools/chatgui-android/libutun_lite/instance_lite.h @@ -18,9 +18,11 @@ extern "C" { struct UASYNC; struct UTUN_INSTANCE; +struct utun_config; /* Копирует INI и запускает поток. 0 = поток создан либо уже запущен, -1 = ошибка запуска. - * Готовность самого ядра появляется позже: проверять is_running и события инициализации. */ + * Готовность самого ядра появляется позже: проверять is_running и события инициализации. + * При отсутствующих ключах startup/restart сначала сохраняет новую пару; ошибка запрещает запуск ядра. */ int instance_lite_start(const char* config_text); /* При существующем instance сигнализировать stop и ждать поток до 2с; обычно затем pthread_join. @@ -48,7 +50,15 @@ int instance_lite_join_link(uint64_t request, const char* link, size_t len); typedef void (*instance_lite_event_fn)(int type, const uint8_t* data, int len); void instance_lite_set_event_handler(instance_lite_event_fn handler); -/* Поставить генерацию X25519-ключей в uasync; обновляет config, my_keys, node_id и пытается сохранить db_path/keys.conf. +/* Создать X25519-пару и атомарно сохранить в config->global.db_path/keys.conf с правами 0600. + * config — разобранный конфиг с непустым db_path; caller исключает параллельную смену идентичности. + * 0 — файл и каталог синхронизированы, ключи/node_id config обновлены; -1 — config не изменён, ошибка залогирована. + * До rename прежний файл сохраняется; при ошибке sync каталога после rename файл уже заменён (published=1 в логе). + * Не меняет работающее ядро; для новой идентичности его нужно пересоздать. */ +int instance_lite_generate_keys(struct utun_config* config); + +/* Поставить генерацию X25519-ключей в uasync; сохраняет db_path/keys.conf, затем обновляет config, my_keys, node_id. + * При ошибке сохранения прежние ключи остаются в памяти, событие не отправляется. * CHAT_EVT_KEYS_GENERATED несёт 64 HEX-байта публичного ключа. Само ядро/соединения здесь не пересоздаются. */ void instance_lite_regenerate_keys(void);