// utun_node.cpp — embedded uTun node running in a dedicated thread #include "utun_node.h" #include #include #include "../../lib/socket_compat.h" // === C headers === extern "C" { #include "utun_instance.h" #include "etcp_router.h" #include "etcp_api.h" #include "etcp.h" #include "config_parser.h" #include "config_updater.h" #include "control_server.h" #include "secure_channel.h" #include "../lib/u_async.h" #include "../lib/ll_queue.h" #include "../lib/memory_pool.h" #include "../lib/debug_config.h" #include "../lib/mem.h" #include "chat/chat_sync.h" #include "chat/chat_core.h" #include "chat/chat_event.h" #include "chat/db_sync.h" #include "call/call.h" #include "dm/dm_core.h" #include "dm/dm_mailbox.h" #include "gui_bridge.h" #include "topo_node_sqlite.h" #include "topo_node.h" #include "topo_group.h" } UtunNode::UtunNode(QObject* parent) : QObject(parent) {} UtunNode::~UtunNode() { stop(); } bool UtunNode::start(const QString& configPath) { if (m_running) return false; m_configPath = configPath; m_stop = false; m_running = true; m_thread = std::thread(&UtunNode::runLoop, this); for (int i = 0; i < 50 && m_running && !m_instance; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(10)); if (!m_instance) { m_stop = true; if (m_thread.joinable()) m_thread.join(); m_running = false; return false; } emit started(); return true; } void UtunNode::setDebugFile(const QString& path) { m_debugFile = path; } void UtunNode::setDbPath(const QString& path) { m_dbPath = path; QDir(path).mkpath("."); } void UtunNode::setDebugLevel(const QString& level) { m_debugLevel = level; } void UtunNode::setDebugCategories(const QString& categories) { m_debugCategories = categories; } void UtunNode::requestStop() { m_stop = true; if (m_ua) uasync_wakeup(m_ua); } void UtunNode::stop() { if (!m_running) return; requestStop(); if (m_thread.joinable()) m_thread.join(); finalize(); m_running = false; } void UtunNode::finalize() { gui_bridge_set_inst(nullptr); if (m_ua) { uasync_destroy(m_ua, 0); m_ua = nullptr; } m_instance = nullptr; m_running = false; DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "finalize: cleanup done"); } QString UtunNode::nodeIdHex() const { if (!m_instance) return {}; char buf[32]; snprintf(buf, sizeof(buf), "%016" PRIx64, m_instance->node_id); return QString(buf); } QString UtunNode::pubKeyHex() const { if (!m_instance || !m_instance->config) return {}; return QString::fromLatin1(m_instance->config->global.my_public_key_hex, 64); } int64_t UtunNode::ntpOffsetUs() const { return m_instance ? m_instance->ntp.offset_us : 0; } bool UtunNode::ntpSynced() const { return m_instance ? m_instance->ntp.synced : false; } bool UtunNode::ntpEnabled() const { return m_instance ? m_instance->ntp.enabled : false; } void UtunNode::runLoop() { debug_config_init(); debug_enable_function_name(0); /* ── debug level from config ── */ if (!m_debugLevel.isEmpty()) { QString lvl = m_debugLevel.toLower(); debug_level_t dl = DEBUG_LEVEL_INFO; if (lvl == "none") dl = DEBUG_LEVEL_NONE; else if (lvl == "error") dl = DEBUG_LEVEL_ERROR; else if (lvl == "warn") dl = DEBUG_LEVEL_WARN; else if (lvl == "info") dl = DEBUG_LEVEL_INFO; else if (lvl == "debug") dl = DEBUG_LEVEL_DEBUG; else if (lvl == "trace") dl = DEBUG_LEVEL_TRACE; g_debug_config.level = dl; } else { g_debug_config.level = DEBUG_LEVEL_INFO; } /* chatgui defaults: suppress spam, verbose for our categories */ g_debug_config.category_levels[DEBUG_CATEGORY_SYS] = DEBUG_LEVEL_DISABLED; g_debug_config.category_levels[DEBUG_CATEGORY_BGP] = DEBUG_LEVEL_INFO; /* per-category overrides from config: cat=level,cat=level,... */ if (!m_debugCategories.isEmpty()) { QByteArray cats = m_debugCategories.toUtf8(); char* token = strtok(cats.data(), ","); while (token) { while (*token == ' ') token++; char* eq = strchr(token, '='); if (eq) { *eq = '\0'; char* cat_name = token; char* lvl_name = eq + 1; while (*lvl_name == ' ') lvl_name++; debug_category_t cat = get_category_by_name(cat_name); debug_level_t lvl = debug_level_from_name(lvl_name); if (cat != DEBUG_CATEGORY_NONE && lvl != DEBUG_LEVEL_NONE) { g_debug_config.category_levels[cat] = lvl; DEBUG_DEBUG(DEBUG_CATEGORY_DEBUG, "debug category: %s=%s", debug_get_category_name(cat), lvl_name); } } token = strtok(NULL, ","); } } /* file output (shared with GUI via debug_config) */ if (!m_debugFile.isEmpty()) { debug_enable_file_output(m_debugFile.toUtf8().constData(), 0); debug_enable_console(1); g_debug_config.thread_marker = 2; } utun_instance_set_tun_init_enabled(0); struct UASYNC* ua = uasync_create(); if (!ua) { QMetaObject::invokeMethod(this, [this] { emit error("uasync_create failed"); }); return; } m_ua = ua; /* Читаем конфиг и выставляем db_path ДО создания инстанса, чтобы topo_groups_init * (внутри utun_instance_create_from_config) открыл общую SQLite-БД раньше auto_socket_init — * иначе auto_socket не сможет сохранить/переиспользовать порты (БД ещё не открыта). */ struct utun_config* cfg = parse_config(m_configPath.toUtf8().constData()); if (!cfg) { QMetaObject::invokeMethod(this, [this] { emit error("parse_config failed"); }); uasync_destroy(ua, 0); m_ua = nullptr; return; } cfg->global.db_sync_enabled = 1; if (!m_dbPath.isEmpty()) snprintf(cfg->global.db_path, sizeof(cfg->global.db_path), "%s", m_dbPath.toUtf8().constData()); m_instance = utun_instance_create_from_config(ua, cfg); if (!m_instance) { free_config(cfg); QMetaObject::invokeMethod(this, [this] { emit error("utun_instance_create_from_config failed"); }); uasync_destroy(ua, 0); m_ua = nullptr; return; } m_instance->test_user_ptr = this; /* set ua for gui_bridge before init, so GUI can post */ gui_bridge_set_uasync(ua); gui_bridge_set_inst(m_instance); if (utun_instance_init(m_instance) != 0) { QMetaObject::invokeMethod(this, [this] { emit error("utun_instance_init failed"); }); utun_instance_destroy(m_instance); m_instance = nullptr; uasync_destroy(ua, 0); m_ua = nullptr; return; } { int sock_count = 0; for (struct ETCP_SOCKET* s = m_instance->etcp_sockets; s; s = s->next) sock_count++; DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "utun_node: after instance_init, etcp_sockets=%d conns=%d", sock_count, queue_entry_count(m_instance->connections)); } utun_add_nodeinfo_cbk(m_instance, gui_nodeinfo_cb_impl, nullptr); /* Bridge chat events to GUI via gui_bridge */ chat_event_set_handler(m_instance, [](struct UTUN_INSTANCE* inst, int type, const uint8_t* data, int len) { (void)inst; gui_bridge_post(type, data, len); }); /* Initialize chat_core (DB) and chat_sync (channel/message P2P sync) */ chat_core_init(m_instance, QString(m_dbPath + "/chats.db").toUtf8().constData()); chat_sync_init(m_instance); chat_media_backfill(m_instance); chat_media_startup_backfill_init(m_instance); dm_mailbox_init(m_instance); dm_core_init(m_instance); call_init(m_instance); chat_core_sync_my_addresses(m_instance); DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "chat_core + chat_sync initialized"); DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "utun_node: entering poll loop"); while (!m_stop) { uasync_poll(ua, 100); } DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "runLoop: poll exit m_stop=%d", (int)m_stop); if (m_instance) { DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "runLoop: destroying instance in worker thread"); utun_instance_destroy(m_instance); m_instance = nullptr; } DEBUG_DEBUG(DEBUG_CATEGORY_GENERAL, "runLoop: emitting stopped"); QMetaObject::invokeMethod(this, [this] { emit stopped(); }); }