From 1657bd45576fa4f25941e35d9b1955dbf0b52e7f Mon Sep 17 00:00:00 2001 From: Evgeny Date: Wed, 22 Jul 2026 10:13:40 +0300 Subject: [PATCH] chatgui: unify config update logic, fix node_id derivation, fix test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config_updater.{h,cpp}: single implementation — config_update_in_lines for batch updates + config_update_option for file-level. REPLACE/APPEND modes, section auto-creation - node_config.cpp: generateIdentity() now derives node_id via SHA256(pubkey) (like sc_derive_node_id_from_pubkey) instead of random. save() uses config_update_in_lines for line-level update when file exists, saveFull() only for new file and addServer/addClient. Removed duplicate findSectionBounds/updateOptionInSection/configUpdateOption - test_config_updater.cpp: Q_ASSERT replaced with VERIFY macro — Q_ASSERT in Release mode does not evaluate the expression, causing false positives. Test now works in both Debug and Release --- tools/chatgui/tests/test_config_updater.cpp | 116 ++++++++++--------- tools/chatgui/transport/config_updater.cpp | 120 ++++++++++++-------- tools/chatgui/transport/config_updater.h | 16 ++- tools/chatgui/transport/node_config.cpp | 70 +++++++++--- tools/chatgui/transport/node_config.h | 1 + 5 files changed, 200 insertions(+), 123 deletions(-) diff --git a/tools/chatgui/tests/test_config_updater.cpp b/tools/chatgui/tests/test_config_updater.cpp index 61b599a8b..cbdcc2e09 100644 --- a/tools/chatgui/tests/test_config_updater.cpp +++ b/tools/chatgui/tests/test_config_updater.cpp @@ -1,101 +1,109 @@ // tests/test_config_updater.cpp — Verify universal config updater #include "../transport/config_updater.h" #include -#include -#include +#include + +#define VERIFY(cond, msg) do { if (!(cond)) { qCritical("FAIL: %s", msg); abort(); } } while(0) static void test_new_file() { const char* path = "/tmp/test_cfg_new.ini"; QFile::remove(path); - bool ok = config_update_option(path, "global", "my_name", "testnode"); - Q_ASSERT(ok); + VERIFY(config_update_option(path, "global", "my_name", "testnode"), "new file write"); QFile f(path); - Q_ASSERT(f.open(QIODevice::ReadOnly | QIODevice::Text)); + VERIFY(f.open(QIODevice::ReadOnly | QIODevice::Text), "new file open for read"); QString content = f.readAll(); f.close(); - Q_ASSERT(content.contains("[global]")); - Q_ASSERT(content.contains("my_name=testnode")); + VERIFY(content.contains("[global]"), "new file has [global]"); + VERIFY(content.contains("my_name=testnode"), "new file has my_name"); QFile::remove(path); } static void test_replace_existing() { const char* path = "/tmp/test_cfg_replace.ini"; + { + QFile f(path); + VERIFY(f.open(QIODevice::WriteOnly | QIODevice::Text), "replace: create file"); + f.write("[global]\nmy_name=oldname\nmy_id=abc\n\n[control]\naddr=1.2.3.4\n"); + f.close(); + } + + VERIFY(config_update_option(path, "global", "my_name", "newname"), "replace: update"); + QFile f(path); - Q_ASSERT(f.open(QIODevice::WriteOnly | QIODevice::Text)); - f.write("[global]\nmy_name=oldname\nmy_id=abc\n\n[control]\naddr=1.2.3.4\n"); - f.close(); - - bool ok = config_update_option(path, "global", "my_name", "newname"); - Q_ASSERT(ok); - - Q_ASSERT(f.open(QIODevice::ReadOnly | QIODevice::Text)); + VERIFY(f.open(QIODevice::ReadOnly | QIODevice::Text), "replace: open for read"); QString content = f.readAll(); f.close(); - Q_ASSERT(!content.contains("my_name=oldname")); - Q_ASSERT(content.contains("my_name=newname")); - Q_ASSERT(content.contains("my_id=abc")); - Q_ASSERT(content.contains("[control]")); - Q_ASSERT(content.contains("addr=1.2.3.4")); + VERIFY(!content.contains("my_name=oldname"), "replace: old value gone"); + VERIFY(content.contains("my_name=newname"), "replace: new value present"); + VERIFY(content.contains("my_id=abc"), "replace: my_id preserved"); + VERIFY(content.contains("[control]"), "replace: [control] preserved"); + VERIFY(content.contains("addr=1.2.3.4"), "replace: addr preserved"); QFile::remove(path); } static void test_replace_new_param_in_section() { const char* path = "/tmp/test_cfg_newparam.ini"; + { + QFile f(path); + VERIFY(f.open(QIODevice::WriteOnly | QIODevice::Text), "newparam: create file"); + f.write("[global]\nmy_name=test\n\n[control]\naddr=1.2.3.4\n"); + f.close(); + } + + VERIFY(config_update_option(path, "global", "new_param", "newval"), "newparam: insert"); + QFile f(path); - Q_ASSERT(f.open(QIODevice::WriteOnly | QIODevice::Text)); - f.write("[global]\nmy_name=test\n\n[control]\naddr=1.2.3.4\n"); - f.close(); - - bool ok = config_update_option(path, "global", "new_param", "newval"); - Q_ASSERT(ok); - - Q_ASSERT(f.open(QIODevice::ReadOnly | QIODevice::Text)); + VERIFY(f.open(QIODevice::ReadOnly | QIODevice::Text), "newparam: open for read"); QString content = f.readAll(); f.close(); - Q_ASSERT(content.contains("my_name=test")); - Q_ASSERT(content.contains("new_param=newval")); - Q_ASSERT(content.contains("[control]")); + VERIFY(content.contains("my_name=test"), "newparam: my_name preserved"); + VERIFY(content.contains("new_param=newval"), "newparam: new_param inserted"); + VERIFY(content.contains("[control]"), "newparam: [control] preserved"); QFile::remove(path); } static void test_append_mode() { const char* path = "/tmp/test_cfg_append.ini"; + { + QFile f(path); + VERIFY(f.open(QIODevice::WriteOnly | QIODevice::Text), "append: create file"); + f.write("[client:peer1]\nlink=srv:addr1:port1\nlink=srv:addr2:port2\n\n[global]\nname=x\n"); + f.close(); + } + + VERIFY(config_update_option(path, "client:peer1", "link", "srv:addr3:port3", CONFIG_UPDATE_APPEND), "append: add link"); + QFile f(path); - Q_ASSERT(f.open(QIODevice::WriteOnly | QIODevice::Text)); - f.write("[client:peer1]\nlink=srv:addr1:port1\nlink=srv:addr2:port2\n\n[global]\nname=x\n"); - f.close(); - - bool ok = config_update_option(path, "client:peer1", "link", "srv:addr3:port3", CONFIG_UPDATE_APPEND); - Q_ASSERT(ok); - - Q_ASSERT(f.open(QIODevice::ReadOnly | QIODevice::Text)); + VERIFY(f.open(QIODevice::ReadOnly | QIODevice::Text), "append: open for read"); QString content = f.readAll(); f.close(); - Q_ASSERT(content.contains("link=srv:addr1:port1")); - Q_ASSERT(content.contains("link=srv:addr2:port2")); - Q_ASSERT(content.contains("link=srv:addr3:port3")); + VERIFY(content.contains("link=srv:addr1:port1"), "append: link1 preserved"); + VERIFY(content.contains("link=srv:addr2:port2"), "append: link2 preserved"); + VERIFY(content.contains("link=srv:addr3:port3"), "append: link3 added"); QFile::remove(path); } static void test_new_section() { const char* path = "/tmp/test_cfg_newsect.ini"; + { + QFile f(path); + VERIFY(f.open(QIODevice::WriteOnly | QIODevice::Text), "newsect: create file"); + f.write("[global]\nname=x\n"); + f.close(); + } + + VERIFY(config_update_option(path, "gui", "theme", "dark"), "newsect: add [gui]"); + QFile f(path); - Q_ASSERT(f.open(QIODevice::WriteOnly | QIODevice::Text)); - f.write("[global]\nname=x\n"); - f.close(); - - bool ok = config_update_option(path, "gui", "theme", "dark"); - Q_ASSERT(ok); - - Q_ASSERT(f.open(QIODevice::ReadOnly | QIODevice::Text)); + VERIFY(f.open(QIODevice::ReadOnly | QIODevice::Text), "newsect: open for read"); QString content = f.readAll(); f.close(); - Q_ASSERT(content.contains("[global]")); - Q_ASSERT(content.contains("name=x")); - Q_ASSERT(content.contains("[gui]")); - Q_ASSERT(content.contains("theme=dark")); + VERIFY(content.contains("[global]"), "newsect: [global] preserved"); + VERIFY(content.contains("name=x"), "newsect: name preserved"); + VERIFY(content.contains("[gui]"), "newsect: [gui] added"); + VERIFY(content.contains("theme=dark"), "newsect: theme added"); QFile::remove(path); } diff --git a/tools/chatgui/transport/config_updater.cpp b/tools/chatgui/transport/config_updater.cpp index f519632b1..ffabf0880 100644 --- a/tools/chatgui/transport/config_updater.cpp +++ b/tools/chatgui/transport/config_updater.cpp @@ -1,67 +1,87 @@ -// config_updater.cpp — Universal INI config file updater +// config_updater.cpp — Universal INI config file updater (like insert_or_replace_option in utun) #include "config_updater.h" #include #include +static std::pair find_section_bounds(const QStringList& lines, const QString& section) { + QString tag = "[" + section + "]"; + for (int i = 0; i < lines.size(); i++) { + if (lines[i].trimmed() == tag) { + int se = lines.size(); + for (int j = i + 1; j < lines.size(); j++) { + QString t = lines[j].trimmed(); + if (t.startsWith('[') && t.endsWith(']')) { se = j; break; } + } + return {i, se}; + } + } + return {-1, -1}; +} + +bool config_update_in_lines(QStringList& lines, const QString& section, + const QString& key, const QString& value, bool replace) { + auto bounds = find_section_bounds(lines, section); + if (bounds.first < 0) { + if (!lines.isEmpty() && !lines.last().trimmed().isEmpty()) + lines.append(""); + lines.append("[" + section + "]"); + lines.append(key + "=" + value); + return true; + } + + int si = bounds.first, se = bounds.second; + int ki = -1; + for (int i = si + 1; i < se; i++) { + int eq = lines[i].indexOf('='); + if (eq > 0 && lines[i].left(eq).trimmed() == key) { ki = i; break; } + } + + QString newLine = key + "=" + value; + + if (replace) { + if (ki >= 0) + lines[ki] = newLine; + else + lines.insert(si + 1, newLine); + } else { + if (ki >= 0) { + int lastKi = ki; + for (int i = ki + 1; i < se; i++) { + int eq = lines[i].indexOf('='); + if (eq > 0 && lines[i].left(eq).trimmed() == key) lastKi = i; + } + lines.insert(lastKi + 1, newLine); + } else { + lines.insert(si + 1, newLine); + } + } + return true; +} + bool config_update_option(const QString& filePath, const QString& section, - const QString& param, const QString& value, int flags) -{ + const QString& param, const QString& value, int flags) { + QFile f(filePath); QStringList lines; - QFile f(filePath); if (f.exists()) { - if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) - return false; + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) return false; QTextStream in(&f); - while (!in.atEnd()) - lines.append(in.readLine()); + while (!in.atEnd()) { + QString line = in.readLine(0); + if (line.endsWith('\r')) line.chop(1); + lines.append(line); + } f.close(); } - const QString sectionHdr = "[" + section + "]"; - const QString newLine = param + "=" + value; - - int secIdx = -1; - for (int i = 0; i < lines.size(); i++) { - if (lines[i].trimmed() == sectionHdr) { secIdx = i; break; } - } - - int secEnd = lines.size(); - if (secIdx >= 0) { - for (int i = secIdx + 1; i < lines.size(); i++) { - if (lines[i].trimmed().startsWith('[')) { secEnd = i; break; } - } - } - - if (secIdx >= 0) { - int ins = secEnd; - while (ins > secIdx + 1 && lines[ins - 1].trimmed().isEmpty()) - ins--; - - if (flags == CONFIG_UPDATE_REPLACE) { - int paramIdx = -1; - for (int i = secIdx + 1; i < secEnd; i++) { - if (lines[i].trimmed().startsWith(param + "=")) { paramIdx = i; break; } - } - if (paramIdx >= 0) - lines[paramIdx] = newLine; - else - lines.insert(ins, newLine); - } else { - lines.insert(ins, newLine); - } - } else { - if (!lines.isEmpty() && !lines.last().trimmed().isEmpty()) - lines.append(""); - lines.append(sectionHdr); - lines.append(newLine); - } - - if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) + bool replace = (flags != CONFIG_UPDATE_APPEND); + if (!config_update_in_lines(lines, section, param, value, replace)) return false; + + if (!f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) return false; QTextStream out(&f); - for (const QString& line : lines) - out << line << "\n"; + for (int i = 0; i < lines.size(); i++) + out << lines[i] << '\n'; f.close(); return true; } diff --git a/tools/chatgui/transport/config_updater.h b/tools/chatgui/transport/config_updater.h index 059c3a595..9d21d6a3b 100644 --- a/tools/chatgui/transport/config_updater.h +++ b/tools/chatgui/transport/config_updater.h @@ -1,18 +1,22 @@ -// config_updater.h — Universal INI config file updater +// config_updater.h — Universal INI config file updater (like insert_or_replace_option in utun) #ifndef CONFIG_UPDATER_H #define CONFIG_UPDATER_H #include +#include enum ConfigUpdateFlag { CONFIG_UPDATE_REPLACE = 0, // replace existing param (single value) CONFIG_UPDATE_APPEND = 1 // add new param even if exists (multi-value) }; -bool config_update_option(const QString& filePath, - const QString& section, - const QString& param, - const QString& value, - int flags = CONFIG_UPDATE_REPLACE); +// Batch update — for callers that read/write the file once (e.g. NodeConfig::save) +bool config_update_in_lines(QStringList& lines, const QString& section, + const QString& key, const QString& value, bool replace); + +// File-level wrapper — reads, updates, writes +bool config_update_option(const QString& filePath, const QString& section, + const QString& param, const QString& value, + int flags = CONFIG_UPDATE_REPLACE); #endif // CONFIG_UPDATER_H diff --git a/tools/chatgui/transport/node_config.cpp b/tools/chatgui/transport/node_config.cpp index 5ea5dd142..73b8fcb69 100644 --- a/tools/chatgui/transport/node_config.cpp +++ b/tools/chatgui/transport/node_config.cpp @@ -1,9 +1,9 @@ // node_config.cpp — Simplified INI config manager for embedded uTun node #include "node_config.h" +#include "config_updater.h" extern "C" { #include -#include } #include #include @@ -142,7 +142,6 @@ bool NodeConfig::exists() const { } void NodeConfig::generateIdentity() { - // X25519 keypair EVP_PKEY* pkey = nullptr; EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_X25519, nullptr); if (ctx) { @@ -158,13 +157,17 @@ void NodeConfig::generateIdentity() { m_pubKey = formatKeyHex(pk, 32); m_privKey = formatKeyHex(sk, 32); EVP_PKEY_free(pkey); - } - // Random 63-bit node_id - uint64_t id = 0; - RAND_bytes(reinterpret_cast(&id), sizeof(id)); - id &= 0x7FFFFFFFFFFFFFFFULL; - m_nodeId = QString("%1").arg(id, 16, 16, QChar('0')).right(16); + uint8_t hash[32]; unsigned int hashLen = 32; + EVP_MD_CTX* mdctx = EVP_MD_CTX_new(); + EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL); + EVP_DigestUpdate(mdctx, pk, 32); + EVP_DigestFinal_ex(mdctx, hash, &hashLen); + EVP_MD_CTX_free(mdctx); + uint64_t id; memcpy(&id, hash, 8); + id &= 0x7FFFFFFFFFFFFFFFULL; + m_nodeId = QString("%1").arg(id, 16, 16, QChar('0')).right(16); + } } bool NodeConfig::create(const QString& nodeName, quint16 listenPort) { @@ -309,7 +312,7 @@ bool NodeConfig::load() { return true; } -bool NodeConfig::save() { +bool NodeConfig::saveFull() { QFile f(m_path); if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) return false; @@ -364,6 +367,47 @@ bool NodeConfig::save() { return true; } +bool NodeConfig::save() { + if (!QFileInfo::exists(m_path)) + return saveFull(); + + QFile f(m_path); + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) return false; + QStringList lines; + QTextStream in(&f); + while (!in.atEnd()) { + QString line = in.readLine(0); + if (line.endsWith('\r')) line.chop(1); + lines.append(line); + } + f.close(); + + config_update_in_lines(lines, "global", "my_node_name", m_nodeName, true); + config_update_in_lines(lines, "global", "my_node_id", m_nodeId, true); + config_update_in_lines(lines, "global", "my_private_key", m_privKey, true); + config_update_in_lines(lines, "global", "my_public_key", m_pubKey, true); + + if (!m_controlAddr.isEmpty()) { + int sep = m_controlAddr.lastIndexOf(':'); + if (sep > 0) { + config_update_in_lines(lines, "control", "ip", m_controlAddr.left(sep), true); + config_update_in_lines(lines, "control", "port", m_controlAddr.mid(sep + 1), true); + } + } + + config_update_in_lines(lines, "gui", "db_path", m_dbPath.isEmpty() ? "chat_data" : m_dbPath, true); + config_update_in_lines(lines, "gui", "debug_file", m_debugFile, true); + config_update_in_lines(lines, "gui", "debug_level", m_debugLevel.isEmpty() ? "info" : m_debugLevel, true); + config_update_in_lines(lines, "gui", "debug_categories", m_debugCategories, true); + + if (!f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) return false; + QTextStream out(&f); + for (int i = 0; i < lines.size(); i++) + out << lines[i] << '\n'; + f.close(); + return true; +} + uint64_t NodeConfig::nodeIdU64() const { if (m_nodeId.length() != 16) return 0; return m_nodeId.toULongLong(nullptr, 16); @@ -387,12 +431,12 @@ void NodeConfig::setControlPort(quint16 p) { bool NodeConfig::addServer(const QString& name, const QString& addr) { for (auto& s : m_servers) { if (s.first == name) return false; } m_servers.append({name, addr}); - return save(); + return saveFull(); } bool NodeConfig::removeServer(const QString& name) { for (int i = 0; i < m_servers.size(); ++i) { - if (m_servers[i].first == name) { m_servers.removeAt(i); return save(); } + if (m_servers[i].first == name) { m_servers.removeAt(i); return saveFull(); } } return false; } @@ -401,12 +445,12 @@ bool NodeConfig::addClient(const QString& name, const QString& pubKeyHex, const QString& serverName, const QString& remoteAddr) { for (auto& c : m_clients) { if (c.name == name) return false; } m_clients.append({name, pubKeyHex, serverName, remoteAddr}); - return save(); + return saveFull(); } bool NodeConfig::removeClient(const QString& name) { for (int i = 0; i < m_clients.size(); ++i) { - if (m_clients[i].name == name) { m_clients.removeAt(i); return save(); } + if (m_clients[i].name == name) { m_clients.removeAt(i); return saveFull(); } } return false; } diff --git a/tools/chatgui/transport/node_config.h b/tools/chatgui/transport/node_config.h index 358f2b09e..e591fef7f 100644 --- a/tools/chatgui/transport/node_config.h +++ b/tools/chatgui/transport/node_config.h @@ -22,6 +22,7 @@ public: bool create(const QString& nodeName, quint16 listenPort); bool load(); bool save(); + bool saveFull(); QString nodeName() const { return m_nodeName; } void setNodeName(const QString& n) { m_nodeName = n; }