id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
4,103
QJsonIO.cpp
Qv2ray_Qv2ray/test/libs/QJsonStruct/QJsonIO.cpp
#include "3rdparty/QJsonStruct/QJsonIO.hpp" #include <QJsonDocument> #include <QJsonObject> #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("QJsonIO Get Simple Value") { const auto obj = QJsonObject{ { "string", "a quick brown fox jumps over the lazy dog" }, // { "integer", -32767 }, // { "boolean", true }, // { "decimal", 0.618 }, // }; const auto arr = QJsonArray{ obj }; SECTION("Get Array Object") { const auto val = QJsonIO::GetValue(arr, 0); REQUIRE(val.isObject()); REQUIRE(val.toObject() == obj); } SECTION("Get Object String") { const auto val = QJsonIO::GetValue(obj, "string"); REQUIRE(val.isString()); REQUIRE(val.toString() == obj["string"].toString()); } SECTION("Get Object Integer") { const auto val = QJsonIO::GetValue(obj, "integer"); REQUIRE(val.toInt() == obj["integer"].toInt()); } SECTION("Get Object Boolean") { const auto val = QJsonIO::GetValue(obj, "boolean"); REQUIRE(val.isBool()); REQUIRE(val.toBool() == obj["boolean"].toBool()); } SECTION("Get Object Decimal") { const auto val = QJsonIO::GetValue(obj, "decimal"); REQUIRE(val.isDouble()); REQUIRE(val.toDouble() == obj["decimal"].toDouble()); } } TEST_CASE("QJsonIO Get Simple Value Using std::tuple") { const auto obj = QJsonObject{ { "string", "a quick brown fox jumps over the lazy dog" }, // { "integer", -32767 }, // { "boolean", true }, // { "decimal", 0.618 }, // }; const auto arr = QJsonArray{ obj }; SECTION("Get Array Object") { const auto val = QJsonIO::GetValue(arr, std::tuple{ 0 }); REQUIRE(val.isObject()); REQUIRE(val.toObject() == obj); } SECTION("Get Object String") { const auto val = QJsonIO::GetValue(obj, std::tuple{ "string" }); REQUIRE(val.isString()); REQUIRE(val.toString() == obj["string"].toString()); } SECTION("Get Object Integer") { const auto val = QJsonIO::GetValue(obj, std::tuple{ "integer" }); REQUIRE(val.toInt() == obj["integer"].toInt()); } SECTION("Get Object Boolean") { const auto val = QJsonIO::GetValue(obj, std::tuple{ "boolean" }); REQUIRE(val.isBool()); REQUIRE(val.toBool() == obj["boolean"].toBool()); } SECTION("Get Object Decimal") { const auto val = QJsonIO::GetValue(obj, std::tuple{ "decimal" }); REQUIRE(val.isDouble()); REQUIRE(val.toDouble() == obj["decimal"].toDouble()); } } TEST_CASE("QJsonIO Set Simple Value") { auto obj = QJsonObject{}; auto arr = QJsonArray{ obj }; SECTION("Set Object String") { QJsonIO::SetValue(obj, "qv2ray_test", "string"); const auto val = QJsonIO::GetValue(obj, "string"); REQUIRE(val.isString()); REQUIRE(val.toString().toStdString() == "qv2ray_test"); } SECTION("Set Object Decimal") { QJsonIO::SetValue(obj, 13.14, "decimal"); const auto val = QJsonIO::GetValue(obj, "decimal"); REQUIRE(val.isDouble()); REQUIRE(val.toDouble() == 13.14); } SECTION("Set Object Integer") { QJsonIO::SetValue(obj, 114514, "integer"); const auto val = QJsonIO::GetValue(obj, "integer"); REQUIRE(val.toInt() == 114514); } SECTION("Set Object Boolean") { QJsonIO::SetValue(obj, true, "boolean"); const auto val = QJsonIO::GetValue(obj, "boolean"); REQUIRE(val.isBool()); REQUIRE(val.toBool() == true); } } TEST_CASE("QJsonIO Set Path") { SECTION("Path Test 1") { auto obj = QJsonObject{}; QJsonIO::SetValue(obj, "vmess", "outbounds", 0, "protocol"); QJsonIO::SetValue(obj, "0.0.0.0", "outbounds", 0, "sendThrough"); QJsonIO::SetValue(obj, "114.51.41.191", "outbounds", 0, "settings", "vnext", 0, "address"); QJsonIO::SetValue(obj, 9810, "outbounds", 0, "settings", "vnext", 0, "port"); INFO("QJsonIO Result:" << QJsonDocument(obj).toJson().toStdString()); const auto ans = QJsonObject{ { "outbounds", QJsonArray{ QJsonObject{ { "protocol", "vmess" }, { "sendThrough", "0.0.0.0" }, { "settings", QJsonObject{ { "vnext", QJsonArray{ QJsonObject{ { "address", "114.51.41.191" }, { "port", 9810 } } } } } } } } } }; INFO("QJsonObject Result: " << QJsonDocument(ans).toJson().toStdString()) REQUIRE(ans == obj); } SECTION("Path remove test") { auto obj = QJsonObject{ { "qv2ray", "shit" } }; QJsonIO::SetValue(obj, QJsonValue(QJsonValue::Undefined), "qv2ray"); REQUIRE(obj == QJsonObject{}); } }
5,116
C++
.cpp
142
29.112676
145
0.548081
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,104
TestParseVLESS.cpp
Qv2ray_Qv2ray/test/src/core/connection/TestParseVLESS.cpp
#include "3rdparty/QJsonStruct/QJsonIO.hpp" #include "Common.hpp" #include "src/core/connection/Serialization.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("Test VLESS URL Parsing") { QvTestApplication app; QString alias; QString errMessage; SECTION("VLESSTCPXTLSSplice") { const static auto url = "vless://b0dd64e4-0fbd-4038-9139-d1f32a68a0dc@qv2ray.net:3279?security=xtls&flow=rprx-xtls-splice#VLESSTCPXTLSSplice"; const auto result = vless::Deserialize(url, &alias, &errMessage); INFO("Parsed: " << QJsonDocument(result).toJson().toStdString()); REQUIRE(errMessage.isEmpty()); REQUIRE(alias.toStdString() == "VLESSTCPXTLSSplice"); } SECTION("ALPN Parse Test") { const static auto url = "vless://24a613c1-de83-4c63-ba73-a9d08c88fec3@qv2ray.net:13432?security=xtls&alpn=h2%2Chttp%2F1.1"; const auto result = vless::Deserialize(url, &alias, &errMessage); INFO("Parsed: " << QJsonDocument(result).toJson().toStdString()); REQUIRE(errMessage.isEmpty()); const auto alpnField = QJsonIO::GetValue(result, "outbounds", 0, "streamSettings", "xtlsSettings", "alpn"); REQUIRE(alpnField.isArray()); const auto alpnArray = alpnField.toArray(); REQUIRE(!alpnArray.empty()); REQUIRE(alpnArray.size() == 2); const auto firstALPN = alpnArray.first(); REQUIRE(firstALPN.isString()); const auto firstALPNString = firstALPN.toString(); REQUIRE(firstALPNString.toStdString() == "h2"); const auto lastALPN = alpnArray.last(); REQUIRE(lastALPN.isString()); const auto lastALPNString = lastALPN.toString(); REQUIRE(lastALPNString.toStdString() == "http/1.1"); } SECTION("gRPC Parse Test") { const static auto url = "vless://6d76fa31-8de2-40d4-8fee-6e61339c416f@qv2ray.net:123?type=grpc&security=tls&serviceName=FuckGFW&mode=multi"; const auto result = vless::Deserialize(url, &alias, &errMessage); INFO("Parsed: " << QJsonDocument(result).toJson().toStdString()); REQUIRE(errMessage.isEmpty()); const auto grpcSettings = QJsonIO::GetValue(result, { "outbounds", 0, "streamSettings", "grpcSettings" }); REQUIRE(grpcSettings.isObject()); const auto grpcSettingsObj = grpcSettings.toObject(); REQUIRE(grpcSettingsObj.contains("serviceName")); REQUIRE(grpcSettingsObj.contains("multiMode")); const auto serviceName = grpcSettingsObj["serviceName"]; REQUIRE(serviceName.isString()); const auto serviceNameString = serviceName.toString(); REQUIRE(serviceNameString == "FuckGFW"); const auto mode = grpcSettingsObj["multiMode"]; REQUIRE(mode.isBool()); const auto modeString = mode.toBool(); REQUIRE(mode == true); } }
2,888
C++
.cpp
59
41.491525
150
0.679487
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,105
TestParseSS.cpp
Qv2ray_Qv2ray/test/src/core/connection/TestParseSS.cpp
#include "3rdparty/QJsonStruct/QJsonIO.hpp" #include "Common.hpp" #include "src/core/connection/Serialization.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" using namespace Qv2ray::core::connection::serialization; SCENARIO("Test Parse Shadowsocks url", "[ParseSSUrl]") { QvTestApplication app; GIVEN("A shadowsocks server object") { ShadowSocksServerObject s; QString err; QString alias = "ssurl1"; WHEN("the url without padding") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.100.1"); REQUIRE(s.port == 8888); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("the url with padding") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xLjE6ODM4OA==", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.1.1"); REQUIRE(s.port == 8388); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("the url with remarks") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xMDAuMTo4ODg4#example-server", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.100.1"); REQUIRE(s.port == 8888); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("the url with remarks and padding") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3RAMTkyLjE2OC4xLjE6ODM4OA==#example-server", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.1.1"); REQUIRE(s.port == 8388); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("the url with sip003 plugin") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.100.1"); REQUIRE(s.port == 8888); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("another url with sip003 plugin") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.1.1"); REQUIRE(s.port == 8388); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("the url with sip003 plugin and remarks") { auto c = ss::Deserialize( "ss://YmYtY2ZiOnRlc3Q@192.168.100.1:8888/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com#example-server", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.100.1"); REQUIRE(s.port == 8888); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } WHEN("another url with sip003 plugin and remarks") { auto c = ss::Deserialize("ss://YmYtY2ZiOnRlc3Q@192.168.1.1:8388/?plugin=obfs-local%3bobfs%3dhttp%3bobfs-host%3dgoogle.com#example-server", &alias, &err); s = ShadowSocksServerObject::fromJson(QJsonIO::GetValue(c, "outbounds", 0, "settings", "servers", 0)); REQUIRE(s.address.toStdString() == "192.168.1.1"); REQUIRE(s.port == 8388); REQUIRE(s.password.toStdString() == "test"); REQUIRE(s.method.toStdString() == "bf-cfb"); } } }
4,758
C++
.cpp
91
41.637363
150
0.593656
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,106
TestParseVmess.cpp
Qv2ray_Qv2ray/test/src/core/connection/TestParseVmess.cpp
#include "3rdparty/QJsonStruct/QJsonIO.hpp" #include "Common.hpp" #include "src/core/connection/Serialization.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" SCENARIO("Test Parse VMess V2 url", "[ParseVMessV2]") { QvTestApplication app; GIVEN("vmess+tcp") { QString _; const QString address = "42.255.255.254"; const int alterId = 4; const QString uuid = "59f34e8c-f310-49b0-b240-11663e365601"; const QString network = "tcp"; const int port = 11451; const QString comment = "日本 VIP节点5 - 10Mbps带宽 苏州-日本 IPLC-CEN专线 游戏加速用 30倍流量比例 原生日本IP落地"; WHEN("parse Qv2ray 2.5.0 generated uri") { const QString vmessString = "vmess://eyJhZGQiOiI0Mi4yNTUuMjU1LjI1NCIsImFpZCI6NCwiaWQiOiI1OWYzNGU4Yy1mMzEw" "LTQ5YjAtYjI0MC0xMTY2M2UzNjU2MDEiLCJuZXQiOiJ0Y3AiLCJwb3J0IjoxMTQ1MSwicHMiOiLm" "l6XmnKwgVklQ6IqC54K5NSAtIDEwTWJwc+W4puWuvSDoi4/lt54t5pel5pysIElQTEMtQ0VO5LiT" "57q/IOa4uOaIj+WKoOmAn+eUqCAzMOWAjea1gemHj+avlOS+iyDljp/nlJ/ml6XmnKxJUOiQveWc" "sCIsInRscyI6Im5vbmUiLCJ0eXBlIjoibm9uZSIsInYiOjJ9Cg=="; QString commentParsed; const auto result = vmess::Deserialize(vmessString, &commentParsed, &_); INFO("Raw VMess: " << vmessString.toStdString()); INFO("Parsed JSON: " << QJsonDocument(result).toJson().toStdString()); const auto networkParsed = QJsonIO::GetValue(result, "outbounds", 0, "streamSettings", "network").toString(); const auto addressParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "address").toString(); const auto portParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "port").toInt(); const auto idParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "users", 0, "id").toString(); const auto alterIdParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "users", 0, "alterId").toInt(); REQUIRE(commentParsed.toStdString() == comment.toStdString()); REQUIRE(addressParsed.toStdString() == address.toStdString()); REQUIRE(portParsed == port); REQUIRE(idParsed.toStdString() == uuid.toStdString()); REQUIRE(alterIdParsed == alterId); REQUIRE(networkParsed.toStdString() == ""); } } } SCENARIO("Test Parse VMess V1 url", "[ParseVMessV1]") { QvTestApplication app; GIVEN("vmess+ws") { QString _; const QString address = "motherfucker.net"; const int alterId = 0; const QString path = "/yaboviss"; const QString network = "ws"; const QString uuid = "40980939-f6bd-4b17-ad26-c2aed2f1b3fc"; const QString comment = "good bye vmess v1"; const int port = 8003; WHEN("parse all stringified vmess v1") { const QString vmessString = "vmess://eyJwcyI6Imdvb2QgYnllIHZtZXNzIHYxIiwiYWRkIjoibW90aGVyZnVja2VyLm5ldCIs" "InBvcnQiOiI4MDAzIiwiaWQiOiI0MDk4MDkzOS1mNmJkLTRiMTctYWQyNi1jMmFlZDJmMWIzZmMi" "LCJhaWQiOiIwIiwibmV0Ijoid3MiLCJ0eXBlIjoibm9uZSIsImhvc3QiOiIveWFib3Zpc3MiLCJ0" "bHMiOiIifQo="; QString commentParsed; const auto result = vmess::Deserialize(vmessString, &commentParsed, &_); INFO("Raw VMess: " << vmessString.toStdString()); INFO("Parsed JSON: " << QJsonDocument(result).toJson().toStdString()); const auto networkParsed = QJsonIO::GetValue(result, "outbounds", 0, "streamSettings", "network").toString(); const auto addressParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "address").toString(); const auto portParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "port").toInt(); const auto idParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "users", 0, "id").toString(); const auto alterIdParsed = QJsonIO::GetValue(result, "outbounds", 0, "settings", "vnext", 0, "users", 0, "alterId").toInt(); const auto typeParsed = QJsonIO::GetValue(result, "outbounds", 0, "streamSettings", "tcpSettings", "header", "type").toString(); const auto tlsParsed = QJsonIO::GetValue(result, "outbounds", 0, "streamSettings", "security").toString(); REQUIRE(commentParsed.toStdString() == comment.toStdString()); REQUIRE(addressParsed.toStdString() == address.toStdString()); REQUIRE(portParsed == port); REQUIRE(idParsed.toStdString() == uuid.toStdString()); REQUIRE(alterIdParsed == alterId); REQUIRE(networkParsed.toStdString() == network.toStdString()); } } }
5,062
C++
.cpp
81
49.716049
140
0.631943
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,107
TestRealPing.cpp
Qv2ray_Qv2ray/test/src/components/latency/TestRealPing.cpp
#include "Common.hpp" #include "src/components/latency/RealPing.hpp" #include "uvw.hpp" #define CATCH_CONFIG_MAIN #include "catch.hpp" SCENARIO("Test RealPing get proxy address", "[RealPing]") { QvTestApplication app; GIVEN("A realping object") { auto loop = uvw::Loop::create(); LatencyTestHost *p; LatencyTestRequest req; auto realping = std::make_shared<Qv2ray::components::latency::realping::RealPing>(loop, req, p); WHEN("test IPv4 any address") { GlobalConfig.inboundConfig.listenip = "0.0.0.0"; GlobalConfig.inboundConfig.useHTTP = true; GlobalConfig.inboundConfig.httpSettings.useAuth = true; GlobalConfig.inboundConfig.httpSettings.port = 9090; GlobalConfig.inboundConfig.httpSettings.account.user = "usr"; GlobalConfig.inboundConfig.httpSettings.account.pass = "pp"; REQUIRE(realping->getProxyAddress() == "http://usr:pp@127.0.0.1:9090"); } WHEN("test IPv6 any address") { GlobalConfig.inboundConfig.listenip = "::"; GlobalConfig.inboundConfig.useHTTP = false; GlobalConfig.inboundConfig.useSocks = true; GlobalConfig.inboundConfig.socksSettings.useAuth = true; GlobalConfig.inboundConfig.socksSettings.port = 9090; GlobalConfig.inboundConfig.socksSettings.account.user = "ausr"; GlobalConfig.inboundConfig.socksSettings.account.pass = ""; REQUIRE(realping->getProxyAddress() == "socks5://ausr:@[::1]:9090"); } WHEN("test IPv4 address without usr/pwd") { GlobalConfig.inboundConfig.listenip = "192.168.1.1"; GlobalConfig.inboundConfig.useHTTP = true; GlobalConfig.inboundConfig.httpSettings.useAuth = false; GlobalConfig.inboundConfig.httpSettings.port = 9090; GlobalConfig.inboundConfig.httpSettings.account.user = "usr"; GlobalConfig.inboundConfig.httpSettings.account.pass = "pp"; REQUIRE(realping->getProxyAddress() == "http://192.168.1.1:9090"); } WHEN("test IPv6 address without usr/pwd") { GlobalConfig.inboundConfig.listenip = "6:6:6:6:6:6:6:6"; GlobalConfig.inboundConfig.useHTTP = false; GlobalConfig.inboundConfig.useSocks = true; GlobalConfig.inboundConfig.socksSettings.useAuth = false; GlobalConfig.inboundConfig.socksSettings.port = 9090; GlobalConfig.inboundConfig.socksSettings.account.user = "ausr"; GlobalConfig.inboundConfig.socksSettings.account.pass = ""; REQUIRE(realping->getProxyAddress() == "socks5://[6:6:6:6:6:6:6:6]:9090"); } } }
2,774
C++
.cpp
58
38.12069
104
0.651197
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,108
version.cpp
Qv2ray_Qv2ray/3rdparty/libsemver/version.cpp
/* * Copyright (c) 2016-2017 Enrico M. Crisostomo * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @mainpage * * @section introduction Introduction * * `libsemver` is a C++ library with C bindings that provides the following * functionality: * * - Parsing a version number into an object. * - Comparing versions. * - Modifying versions object. * * Versions are checked against _Semantic Versioning 2.0.0_ * (http://semver.org/). * * @section changelog Changelog * * See the @ref history "History" page. * * @section bindings Available Bindings * * `libsemver` is a C++ library with C bindings which makes it available to a * wide range of programming languages. If a programming language has C * bindings, then `libsemver` can be used from it. The C binding provides all * the functionality provided by the C++ implementation and it can be used as a * fallback solution when the C++ API cannot be used. * * @section libtools-versioning libtool's versioning scheme * * `libtool`'s versioning scheme is described by three integers: * `current:revision:age` where: * * - `current` is the most recent interface number implemented by the * library. * - `revision` is the implementation number of the current interface. * - `age` is the difference between the newest and the oldest interface that * the library implements. * * @section bug-reports Reporting Bugs and Suggestions * * If you find problems or have suggestions about this program or this manual, * please report them as new issues in the official GitHub repository at * https://github.com/emcrisostomo/semver-utils. Please, read the * `CONTRIBUTING.md` file for detailed instructions on how to contribute to * `fswatch`. */ /** * @page history History * * @section v600 1:0:0 * * - Initial release. */ #include "version.hpp" #include <algorithm> #include <iostream> #include <iterator> // back_inserter #include <regex> namespace semver { static std::vector<unsigned int> parse_version(const std::string &v); static void match_prerelease(const std::string &s); static void match_metadata(const std::string &s); static void check_identifier(const std::string &s); static const std::string PRERELEASE_PATTERN("([0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)"); static const std::string METADATA_PATTERN("([0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)"); prerelease_component::prerelease_component(std::string s) : identifier(std::move(s)) { is_number = !identifier.empty() && std::find_if(identifier.begin(), identifier.end(), [](char c) { return !std::isdigit(c); }) == identifier.end(); value_as_number = is_number ? std::stoul(identifier) : 0; } bool prerelease_component::operator==(const prerelease_component &v) const { return identifier == v.identifier; } bool prerelease_component::operator<(const prerelease_component &rh) const { if (is_number && rh.is_number) return value_as_number < rh.value_as_number; if (!is_number && !rh.is_number) return identifier < rh.identifier; return is_number; } bool prerelease_component::operator>(const prerelease_component &rh) const { return (rh < *this); } version version::from_string(std::string v) { // SemVer 2.0.0 // // 2. A normal version number MUST take the form X.Y.Z where X, Y, and Z are // non-negative integers, and MUST NOT contain leading zeroes. [...] // // This implementation allows for a version number containing more than 3 // components. const std::string version_pattern = "((0|[1-9][[:digit:]]*)(\\.(0|[1-9][[:digit:]]*)){1,})"; const int VERSION_INDEX = 1; // 9. A pre-release version MAY be denoted by appending a hyphen and a series // of dot separated identifiers immediately following the patch version. // Identifiers MUST comprise only ASCII alphanumerics and hyphen // [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers MUST // NOT include leading zeroes. const std::string prerelease_pattern = "(-" + PRERELEASE_PATTERN + ")?"; const int PRERELEASE_INDEX = 6; // 10. Build metadata MAY be denoted by appending a plus sign and a series of // dot separated identifiers immediately following the patch or // pre-release version. Identifiers MUST comprise only ASCII // alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be // empty. const std::string metadata_pattern = "(\\+" + METADATA_PATTERN + ")?"; const int METADATA_INDEX = 9; const std::string grammar = std::string("^") + version_pattern + prerelease_pattern + metadata_pattern + "$"; std::regex version_grammar(grammar, std::regex_constants::extended); std::smatch fragments; if (!std::regex_match(v, fragments, version_grammar)) throw std::invalid_argument("Invalid version: " + v); return semver::version(parse_version(fragments[VERSION_INDEX].str()), fragments[PRERELEASE_INDEX].str(), fragments[METADATA_INDEX].str()); } version::version(std::vector<unsigned int> versions, std::string prerelease, std::string metadata) : versions(std::move(versions)), prerelease(std::move(prerelease)), metadata(std::move(metadata)) { if (this->versions.size() < 2) throw std::invalid_argument("Version must contain at least two numbers."); if (!this->prerelease.empty()) { match_prerelease(this->prerelease); parse_prerelease(); } if (!this->metadata.empty()) { match_metadata(this->metadata); } } std::string version::str() const { std::string out = std::to_string(versions[0]); for (size_t i = 1; i < versions.size(); ++i) { out += "."; out += std::to_string(versions[i]); } if (!prerelease.empty()) { out += "-"; out += prerelease; } if (!metadata.empty()) { out += "+"; out += metadata; } return out; } version version::bump_major() const { return bump(0); } version version::bump_minor() const { return bump(1); } version version::bump_patch() const { return bump(2); } version version::bump(unsigned int index) const { std::vector<unsigned int> bumped_versions = versions; if (index >= bumped_versions.size()) { std::fill_n(std::back_inserter(bumped_versions), index - bumped_versions.size() + 1, 0); bumped_versions[index] = 1; } else { bumped_versions[index] += 1; for (size_t i = index + 1; i < bumped_versions.size(); ++i) bumped_versions[i] = 0; } return version(bumped_versions, prerelease, metadata); } std::vector<unsigned int> version::get_version() const { return versions; } std::string version::get_prerelease() const { return prerelease; } std::string version::get_metadata() const { return metadata; } version version::strip_prerelease() const { return version(versions, "", metadata); } version version::strip_metadata() const { return version(versions, prerelease, ""); } bool version::is_release() const { return (prerelease.empty()); } bool version::operator==(const version &v) const { return versions == v.versions && prerelease == v.prerelease; } bool version::operator<(const version &v) const { // Compare version numbers. if (versions < v.versions) return true; if (versions > v.versions) return false; // Compare prerelease identifiers. if (prerelease == v.prerelease) return false; // If either one, but not both, are release versions, release is greater. if (is_release() ^ v.is_release()) return !is_release(); return prerelease_comp < v.prerelease_comp; } bool version::operator>(const version &v) const { return (v < *this); } unsigned int version::get_version(unsigned int index) const { if (index >= versions.size()) return 0; return versions[index]; } std::vector<unsigned int> parse_version(const std::string &v) { std::regex numbers("\\d+"); std::sregex_token_iterator first(v.begin(), v.end(), numbers); std::sregex_token_iterator last; std::vector<unsigned int> results; std::for_each(first, last, [&results](std::string s) { results.push_back((unsigned int) std::stoul(s)); }); return results; } void version::parse_prerelease() { std::regex separator("\\."); std::sregex_token_iterator first(prerelease.begin(), prerelease.end(), separator, -1); std::sregex_token_iterator last; std::for_each(first, last, [this](std::string s) { check_identifier(s); prerelease_comp.emplace_back(s); }); } void check_identifier(const std::string &s) { if (s.empty()) throw std::invalid_argument("Invalid identifier: " + s); if (s[0] != '0') return; for (size_t i = 1; i < s.size(); ++i) { if (!std::isdigit(s[i])) return; } throw std::invalid_argument("Numerical identifier cannot contain leading zeroes."); } void match_prerelease(const std::string &s) { if (!std::regex_match(s, std::regex(PRERELEASE_PATTERN))) throw std::invalid_argument("Invalid prerelease: " + s); } void match_metadata(const std::string &s) { if (!std::regex_match(s, std::regex(METADATA_PATTERN))) throw std::invalid_argument("Invalid metadata: " + s); } } // namespace semver
10,887
C++
.cpp
294
30.292517
132
0.622129
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
true
true
false
4,109
main.cpp
Qv2ray_Qv2ray/src/main.cpp
#include <QtGlobal> #ifdef QV2RAY_CLI #include "ui/cli/Qv2rayCliApplication.hpp" #endif #ifdef QV2RAY_GUI_QWIDGETS #include "ui/widgets/Qv2rayWidgetApplication.hpp" #endif #ifdef QV2RAY_GUI_QML #include "ui/qml/Qv2rayQMLApplication.hpp" #endif #include "utils/QvHelpers.hpp" #include <csignal> #ifndef Q_OS_WIN #include <unistd.h> #else #include <Windows.h> // #include <DbgHelp.h> #endif #define QV_MODULE_NAME "Init" int globalArgc; char **globalArgv; void BootstrapMessageBox(const QString &title, const QString &text) { #ifdef QV2RAY_GUI if (qApp) { QMessageBox::warning(nullptr, title, text); } else { QApplication p(globalArgc, globalArgv); QMessageBox::warning(nullptr, title, text); } #else std::cout << title.toStdString() << NEWLINE << text.toStdString() << std::endl; #endif } const QString SayLastWords() noexcept { QStringList msg; msg << "------- BEGIN QV2RAY CRASH REPORT -------"; { #ifdef Q_OS_WIN void *stack[1024]; HANDLE process = GetCurrentProcess(); SymInitialize(process, NULL, TRUE); SymSetOptions(SYMOPT_LOAD_ANYTHING); WORD numberOfFrames = CaptureStackBackTrace(0, 1024, stack, NULL); SYMBOL_INFO *symbol = (SYMBOL_INFO *) malloc(sizeof(SYMBOL_INFO) + (512 - 1) * sizeof(TCHAR)); symbol->MaxNameLen = 512; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); DWORD displacement; IMAGEHLP_LINE64 *line = (IMAGEHLP_LINE64 *) malloc(sizeof(IMAGEHLP_LINE64)); line->SizeOfStruct = sizeof(IMAGEHLP_LINE64); // for (int i = 0; i < numberOfFrames; i++) { const auto address = (DWORD64) stack[i]; SymFromAddr(process, address, NULL, symbol); if (SymGetLineFromAddr64(process, address, &displacement, line)) { msg << QString("[%1]: %2 (%3:%4)").arg(symbol->Address).arg(symbol->Name).arg(line->FileName).arg(line->LineNumber); } else { msg << QString("[%1]: %2 SymGetLineFromAddr64[%3]").arg(symbol->Address).arg(symbol->Name).arg(GetLastError()); } } #endif } if (KernelInstance) { msg << "Active Kernel Instances:"; const auto kernels = KernelInstance->GetActiveKernelProtocols(); msg << JsonToString(JsonStructHelper::Serialize(static_cast<QList<QString>>(kernels)).toArray(), QJsonDocument::Compact); msg << "Current Connection:"; // const auto currentConnection = KernelInstance->CurrentConnection(); msg << JsonToString(currentConnection.toJson(), QJsonDocument::Compact); msg << NEWLINE; // if (ConnectionManager && !currentConnection.isEmpty()) { msg << "Active Connection Settings:"; const auto connection = ConnectionManager->GetConnectionMetaObject(currentConnection.connectionId); auto group = ConnectionManager->GetGroupMetaObject(currentConnection.groupId); // // Do not collect private data. // msg << NEWLINE; // msg << JsonToString(ConnectionManager->GetConnectionRoot(currentConnection.connectionId)); group.subscriptionOption.address = "HIDDEN"; // msg << JsonToString(connection.toJson(), QJsonDocument::Compact); msg << NEWLINE; msg << "Group:"; msg << JsonToString(group.toJson(), QJsonDocument::Compact); msg << NEWLINE; } } if (PluginHost) { msg << "Plugins:"; const auto plugins = PluginHost->AllPlugins(); for (const auto &plugin : plugins) { const auto data = PluginHost->GetPlugin(plugin)->metadata; QList<QString> dataList; dataList << data.Name; dataList << data.Author; dataList << data.InternalName; dataList << data.Description; msg << JsonToString(JsonStructHelper::Serialize(dataList).toArray(), QJsonDocument::Compact); } msg << NEWLINE; } if (QvCoreApplication) { msg << "GlobalConfig:"; msg << JsonToString(GlobalConfig.toJson(), QJsonDocument::Compact); } msg << "------- END OF QV2RAY CRASH REPORT -------"; return msg.join(NEWLINE); } void signalHandler(int signum) { #ifndef Q_OS_WIN if (signum == SIGTRAP) { exit(-99); return; } #endif std::cout << "Qv2ray: Interrupt signal (" << signum << ") received." << std::endl; if (signum == SIGTERM) { if (qApp) qApp->exit(); return; } std::cout << "Collecting StackTrace" << std::endl; const auto msg = "Signal: " + QSTRN(signum) + NEWLINE + SayLastWords(); std::cout << msg.toStdString() << std::endl; if (qApp && QvCoreApplication) { QDir().mkpath(QV2RAY_CONFIG_DIR + "bugreport/"); const auto filePath = QV2RAY_CONFIG_DIR + "bugreport/QvBugReport_" + QSTRN(system_clock::to_time_t(system_clock::now())) + ".stacktrace"; StringToFile(msg, filePath); std::cout << "Backtrace saved in: " + filePath.toStdString() << std::endl; const auto message = QObject::tr("Qv2ray has encountered an uncaught exception: ") + NEWLINE + // QObject::tr("Please report a bug via Github with the file located here: ") + NEWLINE + // NEWLINE + filePath; BootstrapMessageBox("UNCAUGHT EXCEPTION", message); } #if defined Q_OS_WIN || defined QT_DEBUG exit(-99); #else kill(getpid(), SIGTRAP); #endif } #ifdef Q_OS_WIN LONG WINAPI TopLevelExceptionHandler(PEXCEPTION_POINTERS) { signalHandler(-1); return EXCEPTION_CONTINUE_SEARCH; } #endif int main(int argc, char *argv[]) { globalArgc = argc; globalArgv = argv; // Register signal handlers. signal(SIGABRT, signalHandler); signal(SIGSEGV, signalHandler); signal(SIGTERM, signalHandler); #ifndef Q_OS_WIN signal(SIGHUP, signalHandler); signal(SIGKILL, signalHandler); #else // AddVectoredExceptionHandler(0, TopLevelExceptionHandler); #endif // // This line must be called before any other ones, since we are using these // values to identify instances. QCoreApplication::setApplicationVersion(QV2RAY_VERSION_STRING); #ifdef QT_DEBUG QCoreApplication::setApplicationName("qv2ray_debug"); #else QCoreApplication::setApplicationName("qv2ray"); #endif #ifdef QV2RAY_GUI QApplication::setApplicationDisplayName("Qv2ray"); #endif #ifdef QT_DEBUG std::cerr << "WARNING: ================ This is a debug build, many features are not stable enough. ================" << std::endl; #endif if (qEnvironmentVariableIsSet("QV2RAY_NO_SCALE_FACTORS")) { LOG("Force set QT_SCALE_FACTOR to 1."); DEBUG("UI", "Original QT_SCALE_FACTOR was:", qEnvironmentVariable("QT_SCALE_FACTOR")); qputenv("QT_SCALE_FACTOR", "1"); } else { DEBUG("High DPI scaling is enabled."); #ifndef QV2RAY_QT6 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) #ifdef QV2RAY_GUI QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); #endif #endif } #ifndef QV2RAY_QT6 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true); #endif Qv2rayApplication app(argc, argv); if (const auto list = app.CheckPrerequisites(); !list.isEmpty()) { BootstrapMessageBox("Qv2ray Prerequisites Check Failed", list.join(NEWLINE)); return Qv2rayExitReason::EXIT_PRECONDITION_FAILED; } if (!app.Initialize()) { const auto reason = app.GetExitReason(); if (reason == EXIT_INITIALIZATION_FAILED) { BootstrapMessageBox("Qv2ray Initialization Failed", "PreInitialization Failed." NEWLINE "For more information, please see the log."); LOG("Qv2ray initialization failed:", reason); } return reason; } #ifndef Q_OS_WIN signal(SIGUSR1, [](int) { ConnectionManager->RestartConnection(); }); signal(SIGUSR2, [](int) { ConnectionManager->StopConnection(); }); #endif app.RunQv2ray(); const auto reason = app.GetExitReason(); if (reason == EXIT_NEW_VERSION_TRIGGER) { LOG("Starting new version of Qv2ray: " + app.StartupArguments._qvNewVersionPath); QProcess::startDetached(app.StartupArguments._qvNewVersionPath, {}); } return reason; }
8,639
C++
.cpp
246
28.752033
145
0.642592
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,110
CoreUtils.cpp
Qv2ray_Qv2ray/src/core/CoreUtils.cpp
#include "CoreUtils.hpp" #include "core/connection/Serialization.hpp" #include "core/handler/ConfigHandler.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "CoreUtils" namespace Qv2ray::core { bool IsComplexConfig(const ConnectionId &id) { return IsComplexConfig(ConnectionManager->GetConnectionRoot(id)); } bool IsComplexConfig(const CONFIGROOT &root) { bool cRouting = root.contains("routing"); bool cRule = cRouting && root["routing"].toObject().contains("rules"); bool cRules = cRule && root["routing"].toObject()["rules"].toArray().count() > 0; // bool cInbounds = root.contains("inbounds"); bool cInboundCount = cInbounds && root["inbounds"].toArray().count() > 0; // bool cOutbounds = root.contains("outbounds"); bool cOutboundCount = cOutbounds && root["outbounds"].toArray().count() > 1; return cRules || cInboundCount || cOutboundCount; } bool GetOutboundInfo(const OUTBOUND &out, QString *host, int *port, QString *protocol) { *protocol = out["protocol"].toString(QObject::tr("N/A")).toLower(); bool ok; const auto info = PluginHost->GetOutboundInfo(*protocol, out["settings"].toObject(), ok); if (ok) { *host = info[INFO_SERVER].toString(); *port = info[INFO_PORT].toInt(); } else { *host = QObject::tr("N/A"); *port = 0; } return ok; } /// /// [Protocol, Host, Port] const ProtocolSettingsInfoObject GetConnectionInfo(const ConnectionId &id, bool *status) { if (status != nullptr) *status = false; const auto root = ConnectionManager->GetConnectionRoot(id); return GetConnectionInfo(root, status); } const ProtocolSettingsInfoObject GetConnectionInfo(const CONFIGROOT &out, bool *status) { if (status != nullptr) *status = false; // // for (const auto &item : out["outbounds"].toArray()) { const auto outboundRoot = OUTBOUND(item.toObject()); QString host; int port; QString outboundType = ""; if (GetOutboundInfo(outboundRoot, &host, &port, &outboundType)) { if (status != nullptr) *status = true; // These lines will mess up the detection of protocols in subscription update. // if (IsComplexConfig(out)) //{ // outboundType += " " + QObject::tr("(Guessed)"); // host += " " + QObject::tr("(Guessed)"); //} return ProtocolSettingsInfoObject{ outboundType, host, port }; } else { LOG("Unknown outbound type: " + outboundType + ", cannot deduce host and port."); } } return { QObject::tr("N/A"), QObject::tr("N/A"), 0 }; } const std::tuple<quint64, quint64> GetConnectionUsageAmount(const ConnectionId &id) { auto connection = ConnectionManager->GetConnectionMetaObject(id); return { connection.stats[CurrentStatAPIType].upLinkData, connection.stats[CurrentStatAPIType].downLinkData }; } uint64_t GetConnectionTotalData(const ConnectionId &id) { const auto &[a, b] = GetConnectionUsageAmount(id); return a + b; } int64_t GetConnectionLatency(const ConnectionId &id) { const auto connection = ConnectionManager->GetConnectionMetaObject(id); return std::max(connection.latency, {}); } const QString GetConnectionProtocolString(const ConnectionId &id) { // Don't bother with the complex connection configs. if (IsComplexConfig(id)) { return QV2RAY_SERIALIZATION_COMPLEX_CONFIG_PLACEHOLDER; } const auto root = ConnectionManager->GetConnectionRoot(id); const auto outbound = root["outbounds"].toArray().first().toObject(); QStringList result; result << outbound["protocol"].toString(); const auto streamSettings = outbound["streamSettings"].toObject(); if (streamSettings.contains("network")) result << streamSettings["network"].toString(); const auto security = streamSettings["security"].toString(); if (!security.isEmpty() && security != "none") result << streamSettings["security"].toString(); return result.join("+"); } const QString GetDisplayName(const ConnectionId &id, int limit) { return TruncateString(ConnectionManager->GetConnectionMetaObject(id).displayName, limit); } const QString GetDisplayName(const GroupId &id, int limit) { return TruncateString(ConnectionManager->GetGroupMetaObject(id).displayName, limit); } bool GetInboundInfo(const INBOUND &in, QString *listen, int *port, QString *protocol) { *protocol = in["protocol"].toString(); *listen = in["listen"].toString(); *port = in["port"].toVariant().toInt(); return true; } const QMap<QString, ProtocolSettingsInfoObject> GetInboundInfo(const CONFIGROOT &root) { QMap<QString, ProtocolSettingsInfoObject> inboundPorts; for (const auto &inboundVal : root["inbounds"].toArray()) { INBOUND in{ inboundVal.toObject() }; QString host, protocol; int port; if (GetInboundInfo(in, &host, &port, &protocol)) inboundPorts[getTag(in)] = { protocol, host, port }; } return inboundPorts; } const QMap<QString, ProtocolSettingsInfoObject> GetInboundInfo(const ConnectionId &id) { return GetInboundInfo(ConnectionManager->GetConnectionRoot(id)); } } // namespace Qv2ray::core
5,910
C++
.cpp
148
31.162162
118
0.615679
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,111
Serialization.cpp
Qv2ray_Qv2ray/src/core/connection/Serialization.cpp
#include "Serialization.hpp" #include "Generation.hpp" #include "core/handler/ConfigHandler.hpp" namespace Qv2ray::core::connection { namespace serialization { QList<std::pair<QString, CONFIGROOT>> ConvertConfigFromString(const QString &link, QString *aliasPrefix, QString *errMessage, QString *newGroup) { const auto TLSOptionsFilter = [](QJsonObject &conf) { const auto disableSystemRoot = GlobalConfig.advancedConfig.disableSystemRoot; for (const QString &prefix : { "tls", "xtls" }) QJsonIO::SetValue(conf, disableSystemRoot, { "outbounds", 0, "streamSettings", prefix + "Settings", "disableSystemRoot" }); }; QList<std::pair<QString, CONFIGROOT>> connectionConf; if (link.startsWith("vmess://") && link.contains("@")) { auto conf = vmess_new::Deserialize(link, aliasPrefix, errMessage); TLSOptionsFilter(conf); connectionConf << std::pair{ *aliasPrefix, conf }; } else if (link.startsWith("vless://")) { auto conf = vless::Deserialize(link, aliasPrefix, errMessage); TLSOptionsFilter(conf); connectionConf << std::pair{ *aliasPrefix, conf }; } else if (link.startsWith("vmess://")) { auto conf = vmess::Deserialize(link, aliasPrefix, errMessage); TLSOptionsFilter(conf); connectionConf << std::pair{ *aliasPrefix, conf }; } else if (link.startsWith("ss://") && !link.contains("plugin=")) { auto conf = ss::Deserialize(link, aliasPrefix, errMessage); connectionConf << std::pair{ *aliasPrefix, conf }; } else if (link.startsWith("ssd://")) { QStringList errMessageList; connectionConf << ssd::Deserialize(link, newGroup, &errMessageList); *errMessage = errMessageList.join(NEWLINE); } else { bool ok = false; const auto configs = PluginHost->TryDeserializeShareLink(link, aliasPrefix, errMessage, newGroup, ok); if (ok) { errMessage->clear(); for (const auto &[_alias, _protocol, _outbound] : configs) { CONFIGROOT root; auto outbound = GenerateOutboundEntry(OUTBOUND_TAG_PROXY, _protocol, OUTBOUNDSETTING(_outbound), {}); QJsonIO::SetValue(root, outbound, "outbounds", 0); connectionConf << std::pair{ _alias, root }; } } else if (errMessage->isEmpty()) { *errMessage = QObject::tr("Unsupported share link format."); } } return connectionConf; } const QString ConvertConfigToString(const ConnectionGroupPair &identifier, bool isSip002) { auto alias = GetDisplayName(identifier.connectionId); if (IsComplexConfig(identifier.connectionId)) { return QV2RAY_SERIALIZATION_COMPLEX_CONFIG_PLACEHOLDER; } auto server = ConnectionManager->GetConnectionRoot(identifier.connectionId); return ConvertConfigToString(alias, GetDisplayName(identifier.groupId), server, isSip002); } const QString ConvertConfigToString(const QString &alias, const QString &groupName, const CONFIGROOT &server, bool isSip002) { const auto outbound = OUTBOUND(server["outbounds"].toArray().first().toObject()); const auto type = outbound["protocol"].toString(); const auto settings = outbound["settings"].toObject(); const auto streamSettings = outbound["streamSettings"].toObject(); QString sharelink; if (type.isEmpty()) { return ""; } if (type == "vmess") { const auto vmessServer = VMessServerObject::fromJson(settings["vnext"].toArray().first().toObject()); const auto transport = StreamSettingsObject::fromJson(streamSettings); if (GlobalConfig.uiConfig.useOldShareLinkFormat) sharelink = vmess::Serialize(transport, vmessServer, alias); else sharelink = vmess_new::Serialize(transport, vmessServer, alias); } else if (type == "shadowsocks") { auto ssServer = ShadowSocksServerObject::fromJson(settings["servers"].toArray().first().toObject()); sharelink = ss::Serialize(ssServer, alias, isSip002); } else { bool ok = false; sharelink = PluginHost->SerializeOutbound(type, settings, streamSettings, alias, groupName, &ok); Q_UNUSED(ok) } return sharelink; } } // namespace serialization } // namespace Qv2ray::core::connection
5,337
C++
.cpp
112
32.964286
143
0.550825
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,112
ConnectionIO.cpp
Qv2ray_Qv2ray/src/core/connection/ConnectionIO.cpp
#include "ConnectionIO.hpp" #include "Serialization.hpp" #include "utils/QvHelpers.hpp" namespace Qv2ray::core::connection::connectionIO { CONFIGROOT ConvertConfigFromFile(const QString &sourceFilePath, bool importComplex) { auto root = CONFIGROOT(JsonFromString(StringFromFile(sourceFilePath))); if (!importComplex) { root.remove("inbounds"); root.remove("routing"); root.remove("dns"); } root.remove("log"); root.remove("api"); root.remove("stats"); return root; } } // namespace Qv2ray::core::connection::connectionIO
637
C++
.cpp
20
25.05
87
0.650897
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,113
routing.cpp
Qv2ray_Qv2ray/src/core/connection/generation/routing.cpp
#include "core/connection/Generation.hpp" namespace Qv2ray::core::connection::generation::routing { QJsonObject GenerateDNS(const QvConfig_DNS &dnsServer) { QJsonObject root = dnsServer.toJson(); QJsonArray servers; for (const auto &serv : dnsServer.servers) servers << (serv.QV2RAY_DNS_IS_COMPLEX_DNS ? serv.toJson() : QJsonValue(serv.address)); root["servers"] = servers; return root; } ROUTERULE GenerateSingleRouteRule(RuleType t, const QString &str, const QString &outboundTag, const QString &type) { return GenerateSingleRouteRule(t, QStringList{ str }, outboundTag, type); } ROUTERULE GenerateSingleRouteRule(RuleType t, const QStringList &rules, const QString &outboundTag, const QString &type) { ROUTERULE root; auto list = rules; list.removeAll(""); switch (t) { case RULE_DOMAIN: root.insert("domain", QJsonArray::fromStringList(rules)); break; case RULE_IP: root.insert("ip", QJsonArray::fromStringList(rules)); break; default: Q_UNREACHABLE(); } JADD(outboundTag, type) return root; } // -------------------------- BEGIN CONFIG GENERATIONS ROUTING GenerateRoutes(bool enableProxy, bool bypassCN, bool bypassLAN, const QString &outTag, const QvConfig_Route &routeConfig) { ROUTING root; root.insert("domainStrategy", routeConfig.domainStrategy); root.insert("domainMatcher", routeConfig.domainMatcher); // // For Rules list QJsonArray rulesList; if (bypassLAN) rulesList << GenerateSingleRouteRule(RULE_IP, "geoip:private", OUTBOUND_TAG_DIRECT); // if (!enableProxy) { // This is added to disable all proxies, as a alternative influence of #64 rulesList << GenerateSingleRouteRule(RULE_DOMAIN, "regexp:.*", OUTBOUND_TAG_DIRECT); rulesList << GenerateSingleRouteRule(RULE_IP, "0.0.0.0/0", OUTBOUND_TAG_DIRECT); rulesList << GenerateSingleRouteRule(RULE_IP, "::/0", OUTBOUND_TAG_DIRECT); } else { // // Blocked. if (!routeConfig.ips.block.isEmpty()) rulesList << GenerateSingleRouteRule(RULE_IP, routeConfig.ips.block, OUTBOUND_TAG_BLACKHOLE); if (!routeConfig.domains.block.isEmpty()) rulesList << GenerateSingleRouteRule(RULE_DOMAIN, routeConfig.domains.block, OUTBOUND_TAG_BLACKHOLE); // // Proxied if (!routeConfig.ips.proxy.isEmpty()) rulesList << GenerateSingleRouteRule(RULE_IP, routeConfig.ips.proxy, outTag); if (!routeConfig.domains.proxy.isEmpty()) rulesList << GenerateSingleRouteRule(RULE_DOMAIN, routeConfig.domains.proxy, outTag); // // Directed if (!routeConfig.ips.direct.isEmpty()) rulesList << GenerateSingleRouteRule(RULE_IP, routeConfig.ips.direct, OUTBOUND_TAG_DIRECT); if (!routeConfig.domains.direct.isEmpty()) rulesList << GenerateSingleRouteRule(RULE_DOMAIN, routeConfig.domains.direct, OUTBOUND_TAG_DIRECT); // // Check if CN needs proxy, or direct. if (bypassCN) { // No proxy agains CN addresses. rulesList << GenerateSingleRouteRule(RULE_IP, "geoip:cn", OUTBOUND_TAG_DIRECT); rulesList << GenerateSingleRouteRule(RULE_DOMAIN, "geosite:cn", OUTBOUND_TAG_DIRECT); } } root.insert("rules", rulesList); return root; } } // namespace Qv2ray::core::connection::generation::routing
3,768
C++
.cpp
82
35.768293
133
0.623744
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,114
filters.cpp
Qv2ray_Qv2ray/src/core/connection/generation/filters.cpp
#include "core/connection/Generation.hpp" #include "utils/QvHelpers.hpp" namespace Qv2ray::core::connection::generation::filters { void OutboundMarkSettingFilter(CONFIGROOT &root, const int mark) { for (auto i = 0; i < root["outbounds"].toArray().count(); i++) { QJsonIO::SetValue(root, mark, "outbounds", i, "streamSettings", "sockopt", "mark"); } } void RemoveEmptyMuxFilter(CONFIGROOT &root) { for (auto i = 0; i < root["outbounds"].toArray().count(); i++) { if (!QJsonIO::GetValue(root, "outbounds", i, "mux", "enabled").toBool(false)) { QJsonIO::SetValue(root, QJsonIO::Undefined, "outbounds", i, "mux"); } } } void DNSInterceptFilter(CONFIGROOT &root, const bool have_tproxy, const bool have_tproxy_v6, const bool have_socks) { // Static DNS Objects static const QJsonObject dnsOutboundObj{ { "protocol", "dns" }, { "tag", "dns-out" } }; QJsonArray dnsRouteInTag; if (have_tproxy) dnsRouteInTag.append("tproxy_IN"); if (have_tproxy_v6) dnsRouteInTag.append("tproxy_IN_V6"); if (have_socks) dnsRouteInTag.append("socks_IN"); // If no UDP inbound, then DNS outbound is useless. if (dnsRouteInTag.isEmpty()) return; const QJsonObject dnsRoutingRuleObj{ { "outboundTag", "dns-out" }, { "port", "53" }, { "type", "field" }, { "inboundTag", dnsRouteInTag } }; // DNS Outbound QJsonIO::SetValue(root, dnsOutboundObj, "outbounds", root["outbounds"].toArray().count()); // DNS Route auto _rules = QJsonIO::GetValue(root, "routing", "rules").toArray(); _rules.prepend(dnsRoutingRuleObj); QJsonIO::SetValue(root, _rules, "routing", "rules"); } void BypassBTFilter(CONFIGROOT &root) { static const QJsonObject bypassBTRuleObj{ { "protocol", QJsonArray{ "bittorrent" } }, { "outboundTag", OUTBOUND_TAG_DIRECT }, { "type", "field" } }; auto _rules = QJsonIO::GetValue(root, "routing", "rules").toArray(); _rules.prepend(bypassBTRuleObj); QJsonIO::SetValue(root, _rules, "routing", "rules"); } void mKCPSeedFilter(CONFIGROOT &root) { for (auto i = 0; i < root["outbounds"].toArray().count(); i++) { const auto seedItem = QJsonIO::GetValue(root, "outbounds", i, "streamSettings", "kcpSettings", "seed"); bool shouldProcess = !seedItem.isNull() && !seedItem.isUndefined(); bool isEmptySeed = seedItem.toString().isEmpty(); if (shouldProcess && isEmptySeed) QJsonIO::SetValue(root, QJsonIO::Undefined, "outbounds", i, "streamSettings", "kcpSettings", "seed"); } } void FillupTagsFilter(CONFIGROOT &root, const QString &subKey) { for (auto i = 0; i < root[subKey].toArray().count(); i++) { if (QJsonIO::GetValue(root, subKey, i, "tag").toString().isEmpty()) { const auto tag = GenerateRandomString(8); QJsonIO::SetValue(root, tag, subKey, i, "tag"); } } } } // namespace Qv2ray::core::connection::generation::filters
3,380
C++
.cpp
75
35.053333
148
0.578196
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,115
final.cpp
Qv2ray_Qv2ray/src/core/connection/generation/final.cpp
#include "core/CoreUtils.hpp" #include "core/connection/Generation.hpp" #include "utils/QvHelpers.hpp" namespace Qv2ray::core::connection::generation::final { } // namespace Qv2ray::core::connection::generation::final
220
C++
.cpp
6
35.333333
58
0.79717
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,116
misc.cpp
Qv2ray_Qv2ray/src/core/connection/generation/misc.cpp
#include "core/connection/Generation.hpp" namespace Qv2ray::core::connection::generation::misc { QJsonObject GenerateAPIEntry(const QString &tag, bool withHandler, bool withLogger, bool withStats) { QJsonObject root; QJsonArray services; services << "ReflectionService"; if (withHandler) services << "HandlerService"; if (withLogger) services << "LoggerService"; if (withStats) services << "StatsService"; JADD(services, tag) return root; } } // namespace Qv2ray::core::connection::generation::misc
617
C++
.cpp
18
26.722222
103
0.650927
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,117
inbounds.cpp
Qv2ray_Qv2ray/src/core/connection/generation/inbounds.cpp
#include "core/connection/Generation.hpp" #define QV_MODULE_NAME "InboundGenerator" namespace Qv2ray::core::connection::generation::inbounds { INBOUNDSETTING GenerateDokodemoIN(const QString &address, int port, const QString &network, int timeout, bool followRedirect) { INBOUNDSETTING root; JADD(address, port, network, timeout, followRedirect) return root; } INBOUNDSETTING GenerateHTTPIN(bool enableAuth, const QList<AccountObject> &_accounts, int timeout, bool allowTransparent) { INBOUNDSETTING root; QJsonArray accounts; for (const auto &account : _accounts) { if (account.user.isEmpty() && account.pass.isEmpty()) continue; accounts.append(account.toJson()); } if (enableAuth && !accounts.isEmpty()) JADD(accounts) JADD(timeout, allowTransparent) return root; } INBOUNDSETTING GenerateSocksIN(const QString &auth, const QList<AccountObject> &_accounts, bool udp, const QString &ip) { INBOUNDSETTING root; QJsonArray accounts; for (const auto &acc : _accounts) { if (acc.user.isEmpty() && acc.pass.isEmpty()) continue; accounts.append(acc.toJson()); } if (!accounts.isEmpty()) JADD(accounts) if (udp) { JADD(auth, udp, ip) } else { JADD(auth) } return root; } INBOUND GenerateInboundEntry(const QString &tag, const QString &protocol, const QString &listen, int port, const INBOUNDSETTING &settings, const QJsonObject &sniffing, const QJsonObject &allocate) { INBOUND root; DEBUG("Allocation is not used here, Not Implemented"); Q_UNUSED(allocate) JADD(listen, port, protocol, settings, tag, sniffing) return root; } QJsonObject GenerateSniffingObject(bool enabled, QList<QString> destOverride, bool metadataOnly) { QJsonObject root; QStringList list; const auto size = destOverride.size(); if (!enabled) return root; root.insert("enabled", enabled); root["metadataOnly"] = metadataOnly; if (!destOverride.isEmpty()) { for (auto i = 0; i < size; ++i) list << destOverride.at(i); root.insert("destOverride", QJsonArray::fromStringList(list)); } return root; } INBOUNDS GenerateDefaultInbounds() { #define INCONF GlobalConfig.inboundConfig INBOUNDS inboundsList; // HTTP Inbound if (GlobalConfig.inboundConfig.useHTTP) { const auto httpInSettings = GenerateHTTPIN(INCONF.httpSettings.useAuth, { INCONF.httpSettings.account }); const auto httpSniffingObject = GenerateSniffingObject(INCONF.httpSettings.sniffing, // INCONF.httpSettings.destOverride); const auto httpInboundObject = GenerateInboundEntry("http_IN", "http", // INCONF.listenip, // INCONF.httpSettings.port, // httpInSettings, // httpSniffingObject); inboundsList.append(httpInboundObject); } // SOCKS Inbound if (INCONF.useSocks) { const auto socksInSettings = GenerateSocksIN(INCONF.socksSettings.useAuth ? "password" : "noauth", // { INCONF.socksSettings.account }, // INCONF.socksSettings.enableUDP, // INCONF.socksSettings.localIP); const auto socksSniffingObject = GenerateSniffingObject(INCONF.socksSettings.sniffing, // INCONF.socksSettings.destOverride); const auto socksInboundObject = GenerateInboundEntry("socks_IN", "socks", // INCONF.listenip, // INCONF.socksSettings.port, // socksInSettings, // socksSniffingObject); inboundsList.append(socksInboundObject); } // TPROXY if (INCONF.useTPROXY) { QList<QString> networks; if (INCONF.tProxySettings.hasTCP) networks << "tcp"; if (INCONF.tProxySettings.hasUDP) networks << "udp"; const auto tproxy_network = networks.join(","); const auto tProxySettings = GenerateDokodemoIN("", 0, tproxy_network, 0, true); const auto tproxySniffingObject = GenerateSniffingObject(INCONF.tProxySettings.sniffing, // INCONF.tProxySettings.destOverride); // tProxy IPv4 Settings { LOG("Processing tProxy IPv4 inbound"); auto tProxyIn = GenerateInboundEntry("tproxy_IN", "dokodemo-door", // INCONF.tProxySettings.tProxyIP, // INCONF.tProxySettings.port, // tProxySettings, // tproxySniffingObject); tProxyIn.insert("streamSettings", QJsonObject{ { "sockopt", QJsonObject{ { "tproxy", INCONF.tProxySettings.mode } } } }); inboundsList.append(tProxyIn); } if (!INCONF.tProxySettings.tProxyV6IP.isEmpty()) { LOG("Processing tProxy IPv6 inbound"); auto tProxyIn = GenerateInboundEntry("tproxy_IN_V6", "dokodemo-door", // INCONF.tProxySettings.tProxyV6IP, // INCONF.tProxySettings.port, // tProxySettings, // tproxySniffingObject); tProxyIn.insert("streamSettings", QJsonObject{ { "sockopt", QJsonObject{ { "tproxy", INCONF.tProxySettings.mode } } } }); inboundsList.append(tProxyIn); } } #undef INCONF return inboundsList; } } // namespace Qv2ray::core::connection::generation::inbounds
7,073
C++
.cpp
145
30.937931
142
0.50246
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,118
outbounds.cpp
Qv2ray_Qv2ray/src/core/connection/generation/outbounds.cpp
#include "core/connection/Generation.hpp" namespace Qv2ray::core::connection::generation::outbounds { OUTBOUNDSETTING GenerateFreedomOUT(const QString &domainStrategy, const QString &redirect) { OUTBOUNDSETTING root; JADD(domainStrategy, redirect) return root; } OUTBOUNDSETTING GenerateBlackHoleOUT(bool useHTTP) { OUTBOUNDSETTING root; QJsonObject resp; resp.insert("type", useHTTP ? "http" : "none"); root.insert("response", resp); return root; } OUTBOUNDSETTING GenerateShadowSocksOUT(const QList<ShadowSocksServerObject> &_servers) { OUTBOUNDSETTING root; QJsonArray x; for (const auto &server : _servers) { x.append(GenerateShadowSocksServerOUT(server.address, server.port, server.method, server.password)); } root.insert("servers", x); return root; } OUTBOUNDSETTING GenerateShadowSocksServerOUT(const QString &address, int port, const QString &method, const QString &password) { OUTBOUNDSETTING root; JADD(address, port, method, password) return root; } OUTBOUNDSETTING GenerateHTTPSOCKSOut(const QString &addr, int port, bool useAuth, const QString &username, const QString &password) { OUTBOUNDSETTING root; QJsonIO::SetValue(root, addr, "servers", 0, "address"); QJsonIO::SetValue(root, port, "servers", 0, "port"); if (useAuth) { QJsonIO::SetValue(root, username, "servers", 0, "users", 0, "user"); QJsonIO::SetValue(root, password, "servers", 0, "users", 0, "pass"); } return root; } OUTBOUND GenerateOutboundEntry(const QString &tag, const QString &protocol, const OUTBOUNDSETTING &settings, const QJsonObject &streamSettings, const QJsonObject &mux, const QString &sendThrough) { OUTBOUND root; JADD(sendThrough, protocol, settings, tag, streamSettings, mux) return root; } } // namespace Qv2ray::core::connection::generation::outbounds
2,126
C++
.cpp
54
31.444444
147
0.65908
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,119
ssd.cpp
Qv2ray_Qv2ray/src/core/connection/serialization/ssd.cpp
/** * A Naive SSD Decoder for Qv2ray * * @author DuckSoft <realducksoft@gmail.com> * @copyright Licensed under GPLv3. */ #include "base/Qv2rayBase.hpp" #include "core/connection/Generation.hpp" #include "core/connection/Serialization.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "SSDConverter" namespace Qv2ray::core::connection::serialization { namespace ssd { // These below are super strict checking schemes, but necessary. #define MUST_EXIST(fieldName) \ if (!obj.contains((fieldName)) || obj[(fieldName)].isUndefined() || obj[(fieldName)].isNull()) \ { \ *logList << QObject::tr("Invalid ssd link: json: field %1 must exist").arg(fieldName); \ return {}; \ } #define MUST_PORT(fieldName) \ MUST_EXIST(fieldName); \ if (int value = obj[(fieldName)].toInt(-1); value < 0 || value > 65535) \ { \ *logList << QObject::tr("Invalid ssd link: json: field %1 must be valid port number"); \ return {}; \ } #define MUST_STRING(fieldName) \ MUST_EXIST(fieldName); \ if (!obj[(fieldName)].isString()) \ { \ *logList << QObject::tr("Invalid ssd link: json: field %1 must be of type 'string'").arg(fieldName); \ return {}; \ } #define MUST_ARRAY(fieldName) \ MUST_EXIST(fieldName); \ if (!obj[(fieldName)].isArray()) \ { \ *logList << QObject::tr("Invalid ssd link: json: field %1 must be an array").arg(fieldName); \ return {}; \ } #define SERVER_SHOULD_BE_OBJECT(server) \ if (!server.isObject()) \ { \ *logList << QObject::tr("Skipping invalid ssd server: server must be an object"); \ continue; \ } #define SHOULD_EXIST(fieldName) \ if (serverObject[(fieldName)].isUndefined()) \ { \ *logList << QObject::tr("Skipping invalid ssd server: missing required field %1").arg(fieldName); \ continue; \ } #define SHOULD_STRING(fieldName) \ SHOULD_EXIST(fieldName); \ if (!serverObject[(fieldName)].isString()) \ { \ *logList << QObject::tr("Skipping invalid ssd server: field %1 should be of type 'string'").arg(fieldName); \ continue; \ } QList<std::pair<QString, CONFIGROOT>> Deserialize(const QString &uri, QString *groupName, QStringList *logList) { LOG("SSD Link format is now deprecated."); // ssd links should begin with "ssd://" if (!uri.startsWith("ssd://")) { *logList << QObject::tr("Invalid ssd link: should begin with ssd://"); return {}; } // decode base64 const auto ssdURIBody = uri.mid(6, uri.length() - 6); //(&uri, 6, uri.length() - 6); const auto decodedJSON = SafeBase64Decode(ssdURIBody).toUtf8(); if (decodedJSON.length() == 0) { *logList << QObject::tr("Invalid ssd link: base64 parse failed"); return {}; } const auto decodeError = VerifyJsonString(decodedJSON); if (!decodeError.isEmpty()) { *logList << QObject::tr("Invalid ssd link: json parse failed: ") % decodeError; return {}; } // casting to object const auto obj = JsonFromString(decodedJSON); // obj.airport MUST_STRING("airport"); *groupName = obj["airport"].toString(); // obj.port MUST_PORT("port"); const int port = obj["port"].toInt(); // obj.encryption MUST_STRING("encryption"); const auto encryption = obj["encryption"].toString(); // check: rc4-md5 is not supported by v2ray-core // TODO: more checks, including all algorithms if (encryption.toLower() == "rc4-md5") { *logList << QObject::tr("Invalid ssd link: rc4-md5 encryption is not supported by v2ray-core"); return {}; } // obj.password MUST_STRING("password"); const auto password = obj["password"].toString(); // obj.servers MUST_ARRAY("servers"); // QList<std::pair<QString, CONFIGROOT>> serverList; // // iterate through the servers for (const auto &server : obj["servers"].toArray()) { SERVER_SHOULD_BE_OBJECT(server); const auto serverObject = server.toObject(); ShadowSocksServerObject ssObject; // encryption ssObject.method = encryption; // password ssObject.password = password; // address :-> "server" SHOULD_STRING("server"); const auto serverAddress = serverObject["server"].toString(); ssObject.address = serverAddress; // port selection: // normal: use global settings // overriding: use current config if (serverObject["port"].isUndefined()) { ssObject.port = port; } else if (auto currPort = serverObject["port"].toInt(-1); (currPort >= 0 && currPort <= 65535)) { ssObject.port = currPort; } else { ssObject.port = port; } // name decision: // untitled: using server:port as name // entitled: using given name QString nodeName; if (serverObject["remarks"].isUndefined()) { nodeName = QString("%1:%2").arg(ssObject.address).arg(ssObject.port); } else if (serverObject["remarks"].isString()) { nodeName = serverObject["remarks"].toString(); } else { nodeName = QString("%1:%2").arg(ssObject.address).arg(ssObject.port); } // ratio decision: // unspecified: ratio = 1 // specified: use given value double ratio = 1.0; if (auto currRatio = serverObject["ratio"].toDouble(-1.0); currRatio != -1.0) { ratio = currRatio; } // else if (!serverObject["ratio"].isUndefined()) // { // //*logList << QObject::tr("Invalid ratio encountered. using fallback value."); // } // format the total name of the node. const auto finalName = QV2RAY_SSD_DEFAULT_NAME_PATTERN.arg(*groupName, nodeName).arg(ratio); // appending to the total list CONFIGROOT root; OUTBOUNDS outbounds; outbounds.append(GenerateOutboundEntry(OUTBOUND_TAG_PROXY, "shadowsocks", GenerateShadowSocksOUT({ ssObject }), {})); root["outbounds"] = outbounds; serverList.append({ finalName, root }); } // returns the current result return serverList; } #undef MUST_EXIST #undef MUST_PORT #undef MUST_ARRAY #undef MUST_STRING #undef SERVER_SHOULD_BE_OBJECT #undef SHOULD_EXIST #undef SHOULD_STRING } // namespace ssd } // namespace Qv2ray::core::connection::serialization
11,804
C++
.cpp
189
51.015873
150
0.340437
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,120
vmess_new.cpp
Qv2ray_Qv2ray/src/core/connection/serialization/vmess_new.cpp
#include "core/CoreUtils.hpp" #include "core/connection/Generation.hpp" #include "core/connection/Serialization.hpp" #include "utils/QvHelpers.hpp" #include <QUrl> #include <QUrlQuery> namespace Qv2ray::core::connection { namespace serialization::vmess_new { const static QStringList NetworkType{ "tcp", "http", "ws", "kcp", "quic", "grpc" }; const static QStringList QuicSecurityTypes{ "none", "aes-128-gcm", "chacha20-poly1305" }; const static QStringList QuicKcpHeaderTypes{ "none", "srtp", "utp", "wechat-video", "dtls", "wireguard" }; const static QStringList FalseTypes{ "false", "False", "No", "Off", "0" }; CONFIGROOT Deserialize(const QString &vmessStr, QString *alias, QString *errMessage) { QUrl url{ vmessStr }; QUrlQuery query{ url }; // #define default CONFIGROOT() if (!url.isValid()) { *errMessage = QObject::tr("vmess:// url is invalid"); return default; } // If previous alias is empty, just the PS is needed, else, append a "_" const auto name = url.fragment(QUrl::FullyDecoded).trimmed(); *alias = alias->isEmpty() ? name : (*alias + "_" + name); VMessServerObject server; server.users << VMessServerObject::UserObject{}; StreamSettingsObject stream; QString net; bool tls = false; // Check streamSettings { for (const auto &_protocol : url.userName().split("+")) { if (_protocol == "tls") tls = true; else net = _protocol; } if (!NetworkType.contains(net)) { *errMessage = QObject::tr("Invalid streamSettings protocol: ") + net; return default; } // L("net: " << net.toStdString()); // L("tls: " << tls); stream.network = net; stream.security = tls ? "tls" : ""; } // Host Port UUID AlterID { const auto host = url.host(); int port = url.port(); QString uuid; int aid; { const auto pswd = url.password(); const auto index = pswd.lastIndexOf("-"); uuid = pswd.mid(0, index); aid = pswd.right(pswd.length() - index - 1).toInt(); } server.address = host; server.port = port; server.users.first().id = uuid; server.users.first().alterId = aid; server.users.first().security = "auto"; } const static auto getQueryValue = [&query](const QString &key, const QString &defaultValue) { if (query.hasQueryItem(key)) return query.queryItemValue(key, QUrl::FullyDecoded); else return defaultValue; }; // // Begin transport settings parser { if (net == "tcp") { stream.tcpSettings.header.type = getQueryValue("type", "none"); } else if (net == "http") { stream.httpSettings.host.append(getQueryValue("host", "")); stream.httpSettings.path = getQueryValue("path", "/"); } else if (net == "ws") { stream.wsSettings.headers["Host"] = getQueryValue("host", ""); stream.wsSettings.path = getQueryValue("path", "/"); } else if (net == "kcp") { stream.kcpSettings.seed = getQueryValue("seed", ""); stream.kcpSettings.header.type = getQueryValue("type", "none"); } else if (net == "quic") { stream.quicSettings.security = getQueryValue("security", "none"); stream.quicSettings.key = getQueryValue("key", ""); stream.quicSettings.header.type = getQueryValue("type", "none"); } else if (net == "grpc") { stream.grpcSettings.serviceName = getQueryValue("serviceName", ""); } else { *errMessage = QObject::tr("Unknown transport method: ") + net; return default; } } #undef default if (tls) { stream.tlsSettings.allowInsecure = !FalseTypes.contains(getQueryValue("allowInsecure", "false")); stream.tlsSettings.serverName = getQueryValue("tlsServerName", ""); } CONFIGROOT root; OUTBOUNDSETTING vConf; QJsonArray vnextArray; vnextArray.append(server.toJson()); vConf["vnext"] = vnextArray; auto outbound = GenerateOutboundEntry(OUTBOUND_TAG_PROXY, "vmess", vConf, stream.toJson()); // root["outbounds"] = QJsonArray{ outbound }; return root; } const QString Serialize(const StreamSettingsObject &stream, const VMessServerObject &server, const QString &alias) { if (server.users.empty()) return QObject::tr("(Empty Users)"); QUrl url; QUrlQuery query; url.setFragment(alias, QUrl::StrictMode); if (stream.network == "tcp") { if (!stream.tcpSettings.header.type.isEmpty() && stream.tcpSettings.header.type != "none") query.addQueryItem("type", stream.tcpSettings.header.type); } else if (stream.network == "http") { if (!stream.httpSettings.host.isEmpty()) query.addQueryItem("host", stream.httpSettings.host.first()); query.addQueryItem("path", stream.httpSettings.path.isEmpty() ? "/" : stream.httpSettings.path); } else if (stream.network == "ws") { if (stream.wsSettings.headers.contains("Host") && !stream.wsSettings.headers["Host"].isEmpty()) query.addQueryItem("host", stream.wsSettings.headers["Host"]); if (!stream.wsSettings.path.isEmpty() && stream.wsSettings.path != "/") query.addQueryItem("path", stream.wsSettings.path); } else if (stream.network == "kcp") { if (!stream.kcpSettings.seed.isEmpty() && stream.kcpSettings.seed != "") query.addQueryItem("seed", stream.kcpSettings.seed); if (!stream.kcpSettings.header.type.isEmpty() && stream.kcpSettings.header.type != "none") query.addQueryItem("type", stream.kcpSettings.header.type); } else if (stream.network == "quic") { if (!stream.quicSettings.security.isEmpty() && stream.quicSettings.security != "none") query.addQueryItem("security", stream.quicSettings.security); if (!stream.quicSettings.key.isEmpty()) query.addQueryItem("key", stream.quicSettings.key); if (!stream.quicSettings.header.type.isEmpty() && stream.quicSettings.header.type != "none") query.addQueryItem("headers", stream.quicSettings.header.type); } else if (stream.network == "grpc") { if (!stream.grpcSettings.serviceName.isEmpty()) query.addQueryItem("serviceName", stream.grpcSettings.serviceName); } else { return {}; } bool hasTLS = stream.security == "tls" || stream.security == "xtls"; auto protocol = stream.network; if (hasTLS) protocol += "+tls"; if (stream.security == "tls") { if (!stream.tlsSettings.serverName.isEmpty()) query.addQueryItem("tlsServerName", stream.tlsSettings.serverName); } else if (stream.security == "xtls") { if (!stream.xtlsSettings.serverName.isEmpty()) query.addQueryItem("tlsServerName", stream.xtlsSettings.serverName); } url.setPath("/"); url.setScheme("vmess"); url.setPassword(server.users.first().id + "-" + QSTRN(server.users.first().alterId)); url.setHost(server.address); url.setPort(server.port); url.setUserName(protocol); url.setQuery(query); return url.toString(); } } // namespace serialization::vmess_new } // namespace Qv2ray::core::connection
9,163
C++
.cpp
205
29.873171
122
0.507823
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,121
ss.cpp
Qv2ray_Qv2ray/src/core/connection/serialization/ss.cpp
#include "core/CoreUtils.hpp" #include "core/connection/Generation.hpp" #include "core/connection/Serialization.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "ShadowsocksImporter" namespace Qv2ray::core::connection { namespace serialization::ss { CONFIGROOT Deserialize(const QString &ssUri, QString *alias, QString *errMessage) { ShadowSocksServerObject server; QString d_name; // auto ssUri = _ssUri.toStdString(); if (ssUri.length() < 5) { LOG("ss:// string too short"); *errMessage = QObject::tr("SS URI is too short"); } auto uri = ssUri.mid(5); auto hashPos = uri.lastIndexOf("#"); DEBUG("Hash sign position: " + QSTRN(hashPos)); if (hashPos >= 0) { // Get the name/remark d_name = uri.mid(uri.lastIndexOf("#") + 1); uri.truncate(hashPos); } auto atPos = uri.indexOf('@'); DEBUG("At sign position: " + QSTRN(atPos)); if (atPos < 0) { // Old URI scheme QString decoded = QByteArray::fromBase64(uri.toUtf8(), QByteArray::Base64Option::OmitTrailingEquals); auto colonPos = decoded.indexOf(':'); DEBUG("Colon position: " + QSTRN(colonPos)); if (colonPos < 0) { *errMessage = QObject::tr("Can't find the colon separator between method and password"); } server.method = decoded.left(colonPos); decoded.remove(0, colonPos + 1); atPos = decoded.lastIndexOf('@'); DEBUG("At sign position: " + QSTRN(atPos)); if (atPos < 0) { *errMessage = QObject::tr("Can't find the at separator between password and hostname"); } server.password = decoded.mid(0, atPos); decoded.remove(0, atPos + 1); colonPos = decoded.lastIndexOf(':'); DEBUG("Colon position: " + QSTRN(colonPos)); if (colonPos < 0) { *errMessage = QObject::tr("Can't find the colon separator between hostname and port"); } server.address = decoded.mid(0, colonPos); server.port = decoded.mid(colonPos + 1).toInt(); } else { // SIP002 URI scheme auto x = QUrl::fromUserInput(uri); server.address = x.host(); server.port = x.port(); const auto userInfo = SafeBase64Decode(x.userName()); const auto userInfoSp = userInfo.indexOf(':'); // DEBUG("Userinfo splitter position: " + QSTRN(userInfoSp)); if (userInfoSp < 0) { *errMessage = QObject::tr("Can't find the colon separator between method and password"); return CONFIGROOT{}; } const auto method = userInfo.mid(0, userInfoSp); server.method = method; server.password = userInfo.mid(userInfoSp + 1); } d_name = QUrl::fromPercentEncoding(d_name.toUtf8()); CONFIGROOT root; OUTBOUNDS outbounds; outbounds.append(GenerateOutboundEntry(OUTBOUND_TAG_PROXY, "shadowsocks", GenerateShadowSocksOUT({ server }), {})); JADD(outbounds) *alias = alias->isEmpty() ? d_name : *alias + "_" + d_name; LOG("Deduced alias: " + *alias); return root; } const QString Serialize(const ShadowSocksServerObject &server, const QString &alias, bool) { QUrl url; const auto plainUserInfo = server.method + ":" + server.password; const auto userinfo = plainUserInfo.toUtf8().toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); url.setUserInfo(userinfo); url.setScheme("ss"); url.setHost(server.address); url.setPort(server.port); url.setFragment(alias); return url.toString(QUrl::ComponentFormattingOption::FullyEncoded); } } // namespace serialization::ss } // namespace Qv2ray::core::connection
4,497
C++
.cpp
101
30.722772
130
0.532313
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,122
vmess.cpp
Qv2ray_Qv2ray/src/core/connection/serialization/vmess.cpp
#include "core/CoreUtils.hpp" #include "core/connection/Generation.hpp" #include "core/connection/Serialization.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "VMessImporter" namespace Qv2ray::core::connection { namespace serialization::vmess { // From https://github.com/2dust/v2rayN/wiki/分享链接格式说明(ver-2) const QString Serialize(const StreamSettingsObject &transfer, const VMessServerObject &server, const QString &alias) { QJsonObject vmessUriRoot; // Constant vmessUriRoot["v"] = 2; vmessUriRoot["ps"] = alias; vmessUriRoot["add"] = server.address; vmessUriRoot["port"] = server.port; vmessUriRoot["id"] = server.users.front().id; vmessUriRoot["aid"] = server.users.front().alterId; const auto scy = server.users.front().security; vmessUriRoot["scy"] = (scy == "aes-128-gcm" || scy == "chacha20-poly1305" || scy == "none" || scy == "zero") ? scy : "auto"; vmessUriRoot["net"] = transfer.network == "http" ? "h2" : transfer.network; vmessUriRoot["tls"] = (transfer.security == "tls" || transfer.security == "xtls") ? "tls" : "none"; if (transfer.security == "tls") { vmessUriRoot["sni"] = transfer.tlsSettings.serverName; } else if (transfer.security == "xtls") { vmessUriRoot["sni"] = transfer.xtlsSettings.serverName; } if (transfer.network == "tcp") { vmessUriRoot["type"] = transfer.tcpSettings.header.type; } else if (transfer.network == "kcp") { vmessUriRoot["type"] = transfer.kcpSettings.header.type; } else if (transfer.network == "quic") { vmessUriRoot["type"] = transfer.quicSettings.header.type; vmessUriRoot["host"] = transfer.quicSettings.security; vmessUriRoot["path"] = transfer.quicSettings.key; } else if (transfer.network == "ws") { auto x = transfer.wsSettings.headers; auto host = x.contains("host"); auto CapHost = x.contains("Host"); auto realHost = host ? x["host"] : (CapHost ? x["Host"] : ""); // vmessUriRoot["host"] = realHost; vmessUriRoot["path"] = transfer.wsSettings.path; } else if (transfer.network == "h2" || transfer.network == "http") { vmessUriRoot["host"] = transfer.httpSettings.host.join(","); vmessUriRoot["path"] = transfer.httpSettings.path; } else if (transfer.network == "grpc") { vmessUriRoot["path"] = transfer.grpcSettings.serviceName; } if (!vmessUriRoot.contains("type") || vmessUriRoot["type"].toString().isEmpty()) { vmessUriRoot["type"] = "none"; } // auto vmessPart = Base64Encode(JsonToString(vmessUriRoot, QJsonDocument::JsonFormat::Compact)); return "vmess://" + vmessPart; } // This generates global config containing only one outbound.... CONFIGROOT Deserialize(const QString &vmessStr, QString *alias, QString *errMessage) { #define default CONFIGROOT() QString vmess = vmessStr; if (vmess.trimmed() != vmess) { LOG("VMess string has some prefix/postfix spaces, trimming."); vmess = vmessStr.trimmed(); } // Reset errMessage *errMessage = ""; if (!vmess.toLower().startsWith("vmess://")) { *errMessage = QObject::tr("VMess string should start with 'vmess://'"); return default; } const auto b64Str = vmess.mid(8, vmess.length() - 8); if (b64Str.isEmpty()) { *errMessage = QObject::tr("VMess string should be a valid base64 string"); return default; } auto vmessString = SafeBase64Decode(b64Str); auto jsonErr = VerifyJsonString(vmessString); if (!jsonErr.isEmpty()) { *errMessage = jsonErr; return default; } auto vmessConf = JsonFromString(vmessString); if (vmessConf.isEmpty()) { *errMessage = QObject::tr("JSON should not be empty"); return default; } // -------------------------------------------------------------------------------------- CONFIGROOT root; QString ps, add, id, net, type, host, path, tls, scy, sni; int port, aid; // // __vmess_checker__func(key, values) // // - Key = Key in JSON and the variable name. // - Values = Candidate variable list, if not match, the first one is used as default. // // - [[val.size() <= 1]] is used when only the default value exists. // // - It can be empty, if so, if the key is not in the JSON, or the value is empty, report an error. // - Else if it contains one thing. if the key is not in the JSON, or the value is empty, use that one. // - Else if it contains many things, when the key IS in the JSON but not within the THINGS, use the first in the THINGS // - Else -------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> use the JSON value // #define __vmess_checker__func(key, values) \ { \ auto val = QStringList() values; \ if (vmessConf.contains(#key) && !vmessConf[#key].toVariant().toString().trimmed().isEmpty() && \ (val.size() <= 1 || val.contains(vmessConf[#key].toVariant().toString()))) \ { \ key = vmessConf[#key].toVariant().toString(); \ } \ else if (!val.isEmpty()) \ { \ key = val.first(); \ DEBUG("Using key \"" #key "\" from the first candidate list: " + key); \ } \ else \ { \ *errMessage = QObject::tr(#key " does not exist."); \ LOG("Cannot process \"" #key "\" since it's not included in the json object."); \ LOG(" --> values: " + val.join(";")); \ LOG(" --> PS: " + ps); \ } \ } // vmess v1 upgrader if (!vmessConf.contains("v")) { LOG("Detected deprecated vmess v1. Trying to upgrade..."); if (const auto network = vmessConf["net"].toString(); network == "ws" || network == "h2") { const QStringList hostComponents = vmessConf["host"].toString().replace(" ", "").split(";"); if (const auto nParts = hostComponents.length(); nParts == 1) vmessConf["path"] = hostComponents[0], vmessConf["host"] = ""; else if (nParts == 2) vmessConf["path"] = hostComponents[0], vmessConf["host"] = hostComponents[1]; else vmessConf["path"] = "/", vmessConf["host"] = ""; } } // Strict check of VMess protocol, to check if the specified value // is in the correct range. // // Get Alias (AKA ps) from address and port. { // Some idiot vmess:// links are using alterId... aid = vmessConf.contains("aid") ? vmessConf.value("aid").toInt(VMESS_USER_ALTERID_DEFAULT) : vmessConf.value("alterId").toInt(VMESS_USER_ALTERID_DEFAULT); // // __vmess_checker__func(ps, << vmessConf["add"].toVariant().toString() + ":" + vmessConf["port"].toVariant().toString()); // __vmess_checker__func(add, nothing); // __vmess_checker__func(id, nothing); // __vmess_checker__func(scy, << "aes-128-gcm" // << "chacha20-poly1305" // << "auto" // << "none" // << "zero"); // // __vmess_checker__func(type, << "none" // << "http" // << "srtp" // << "utp" // << "wechat-video"); // // __vmess_checker__func(net, << "tcp" // << "http" // << "h2" // << "ws" // << "kcp" // << "quic" // << "grpc"); // // __vmess_checker__func(tls, << "none" // << "tls"); // // path = vmessConf.contains("path") ? vmessConf["path"].toVariant().toString() : (net == "quic" ? "" : "/"); host = vmessConf.contains("host") ? vmessConf["host"].toVariant().toString() : (net == "quic" ? "none" : ""); } // Respect connection type rather than obfs type if (QStringList{ "srtp", "utp", "wechat-video" }.contains(type)) // { // if (net != "quic" && net != "kcp") // { // LOG("Reset obfs settings from " + type + " to none"); // type = "none"; // } // } port = vmessConf["port"].toVariant().toInt(); aid = vmessConf["aid"].toVariant().toInt(); // // Apply the settings. // User VMessServerObject::UserObject user; user.id = id; user.alterId = aid; user.security = scy; // // Server VMessServerObject serv; serv.port = port; serv.address = add; serv.users.push_back(user); // // // Stream Settings StreamSettingsObject streaming; if (net == "tcp") { streaming.tcpSettings.header.type = type; } else if (net == "http" || net == "h2") { // Fill hosts for HTTP for (const auto &_host : host.split(',')) { if (!_host.isEmpty()) { streaming.httpSettings.host << _host.trimmed(); } } streaming.httpSettings.path = path; } else if (net == "ws") { if (!host.isEmpty()) streaming.wsSettings.headers["Host"] = host; streaming.wsSettings.path = path; } else if (net == "kcp") { streaming.kcpSettings.header.type = type; } else if (net == "quic") { streaming.quicSettings.security = host; streaming.quicSettings.header.type = type; streaming.quicSettings.key = path; } else if (net == "grpc") { streaming.grpcSettings.serviceName = path; } streaming.security = tls; if (tls == "tls") { if (sni.isEmpty() && !host.isEmpty()) sni = host; streaming.tlsSettings.serverName = sni; streaming.tlsSettings.allowInsecure = false; } // // Network type // NOTE(DuckSoft): Damn vmess:// just don't write 'http' properly if (net == "h2") net = "http"; streaming.network = net; // // VMess root config OUTBOUNDSETTING vConf; vConf["vnext"] = QJsonArray{ serv.toJson() }; const auto outbound = GenerateOutboundEntry(OUTBOUND_TAG_PROXY, "vmess", vConf, streaming.toJson()); root["outbounds"] = QJsonArray{ outbound }; // If previous alias is empty, just the PS is needed, else, append a "_" *alias = alias->trimmed().isEmpty() ? ps : *alias + "_" + ps; return root; #undef default } } // namespace serialization::vmess } // namespace Qv2ray::core::connection
17,724
C++
.cpp
292
43.609589
150
0.33364
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,123
vless.cpp
Qv2ray_Qv2ray/src/core/connection/serialization/vless.cpp
#include "core/CoreUtils.hpp" #include "core/connection/Generation.hpp" #include "core/connection/Serialization.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "VLESSImporter" namespace Qv2ray::core::connection { namespace serialization::vless { CONFIGROOT Deserialize(const QString &str, QString *alias, QString *errMessage) { // must start with vless:// if (!str.startsWith("vless://")) { *errMessage = QObject::tr("VLESS link should start with vless://"); return CONFIGROOT(); } // parse url QUrl url(str); if (!url.isValid()) { *errMessage = QObject::tr("link parse failed: %1").arg(url.errorString()); return CONFIGROOT(); } // fetch host const auto hostRaw = url.host(); if (hostRaw.isEmpty()) { *errMessage = QObject::tr("empty host"); return CONFIGROOT(); } const auto host = (hostRaw.startsWith('[') && hostRaw.endsWith(']')) ? hostRaw.mid(1, hostRaw.length() - 2) : hostRaw; // fetch port const auto port = url.port(); if (port == -1) { *errMessage = QObject::tr("missing port"); return CONFIGROOT(); } // fetch remarks const auto remarks = url.fragment(); if (!remarks.isEmpty()) { *alias = remarks; } // fetch uuid const auto uuid = url.userInfo(); if (uuid.isEmpty()) { *errMessage = QObject::tr("missing uuid"); return CONFIGROOT(); } // initialize QJsonObject with basic info QJsonObject outbound; QJsonObject stream; QJsonIO::SetValue(outbound, "vless", "protocol"); QJsonIO::SetValue(outbound, host, { "settings", "vnext", 0, "address" }); QJsonIO::SetValue(outbound, port, { "settings", "vnext", 0, "port" }); QJsonIO::SetValue(outbound, uuid, { "settings", "vnext", 0, "users", 0, "id" }); // parse query QUrlQuery query(url.query()); // handle type const auto hasType = query.hasQueryItem("type"); const auto type = hasType ? query.queryItemValue("type") : "tcp"; if (type != "tcp") QJsonIO::SetValue(stream, type, "network"); // handle encryption const auto hasEncryption = query.hasQueryItem("encryption"); const auto encryption = hasEncryption ? query.queryItemValue("encryption") : "none"; QJsonIO::SetValue(outbound, encryption, { "settings", "vnext", 0, "users", 0, "encryption" }); // type-wise settings if (type == "kcp") { const auto hasSeed = query.hasQueryItem("seed"); if (hasSeed) QJsonIO::SetValue(stream, query.queryItemValue("seed"), { "kcpSettings", "seed" }); const auto hasHeaderType = query.hasQueryItem("headerType"); const auto headerType = hasHeaderType ? query.queryItemValue("headerType") : "none"; if (headerType != "none") QJsonIO::SetValue(stream, headerType, { "kcpSettings", "header", "type" }); } else if (type == "http") { const auto hasPath = query.hasQueryItem("path"); const auto path = hasPath ? QUrl::fromPercentEncoding(query.queryItemValue("path").toUtf8()) : "/"; if (path != "/") QJsonIO::SetValue(stream, path, { "httpSettings", "path" }); const auto hasHost = query.hasQueryItem("host"); if (hasHost) { const auto hosts = QJsonArray::fromStringList(query.queryItemValue("host").split(",")); QJsonIO::SetValue(stream, hosts, { "httpSettings", "host" }); } } else if (type == "ws") { const auto hasPath = query.hasQueryItem("path"); const auto path = hasPath ? QUrl::fromPercentEncoding(query.queryItemValue("path").toUtf8()) : "/"; if (path != "/") QJsonIO::SetValue(stream, path, { "wsSettings", "path" }); const auto hasHost = query.hasQueryItem("host"); if (hasHost) { QJsonIO::SetValue(stream, query.queryItemValue("host"), { "wsSettings", "headers", "Host" }); } } else if (type == "quic") { const auto hasQuicSecurity = query.hasQueryItem("quicSecurity"); if (hasQuicSecurity) { const auto quicSecurity = query.queryItemValue("quicSecurity"); QJsonIO::SetValue(stream, quicSecurity, { "quicSettings", "security" }); if (quicSecurity != "none") { const auto key = query.queryItemValue("key"); QJsonIO::SetValue(stream, key, { "quicSettings", "key" }); } const auto hasHeaderType = query.hasQueryItem("headerType"); const auto headerType = hasHeaderType ? query.queryItemValue("headerType") : "none"; if (headerType != "none") QJsonIO::SetValue(stream, headerType, { "quicSettings", "header", "type" }); } } else if (type == "grpc") { const auto hasServiceName = query.hasQueryItem("serviceName"); if (hasServiceName) { const auto serviceName = QUrl::fromPercentEncoding(query.queryItemValue("serviceName").toUtf8()); QJsonIO::SetValue(stream, serviceName, { "grpcSettings", "serviceName" }); } const auto hasMode = query.hasQueryItem("mode"); if (hasMode) { const auto multiMode = QUrl::fromPercentEncoding(query.queryItemValue("mode").toUtf8()) == "multi"; QJsonIO::SetValue(stream, multiMode, { "grpcSettings", "multiMode" }); } } // tls-wise settings const auto hasSecurity = query.hasQueryItem("security"); const auto security = hasSecurity ? query.queryItemValue("security") : "none"; const auto tlsKey = security == "xtls" ? "xtlsSettings" : "tlsSettings"; if (security != "none") { QJsonIO::SetValue(stream, security, "security"); } // sni const auto hasSNI = query.hasQueryItem("sni"); if (hasSNI) { const auto sni = query.queryItemValue("sni"); QJsonIO::SetValue(stream, sni, { tlsKey, "serverName" }); } // alpn const auto hasALPN = query.hasQueryItem("alpn"); if (hasALPN) { const auto alpnRaw = QUrl::fromPercentEncoding(query.queryItemValue("alpn").toUtf8()); const auto alpnArray = QJsonArray::fromStringList(alpnRaw.split(",")); QJsonIO::SetValue(stream, alpnArray, { tlsKey, "alpn" }); } // xtls-specific if (security == "xtls") { const auto flow = query.queryItemValue("flow"); QJsonIO::SetValue(outbound, flow, { "settings", "vnext", 0, "users", 0, "flow" }); } // assembling config CONFIGROOT root; outbound["streamSettings"] = stream; root["outbounds"] = QJsonArray{ outbound }; // return return root; } } // namespace serialization::vless } // namespace Qv2ray::core::connection
8,184
C++
.cpp
177
31.644068
130
0.510457
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,124
RouteHandler.cpp
Qv2ray_Qv2ray/src/core/handler/RouteHandler.cpp
#include "RouteHandler.hpp" #include "base/models/QvComplexConfigModels.hpp" #include "core/CoreUtils.hpp" #include "core/connection/Generation.hpp" #include "core/handler/ConfigHandler.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "RouteHandler" namespace Qv2ray::core::handler { RouteHandler::RouteHandler(QObject *parent) : QObject(parent) { const auto routesJson = JsonFromString(StringFromFile(QV2RAY_CONFIG_DIR + "routes.json")); for (const auto &routeId : routesJson.keys()) { configs.insert(GroupRoutingId{ routeId }, GroupRoutingConfig::fromJson(routesJson.value(routeId).toObject())); } } RouteHandler::~RouteHandler() { SaveRoutes(); } void RouteHandler::SaveRoutes() const { QJsonObject routingObject; for (const auto &key : configs.keys()) { routingObject[key.toString()] = configs[key].toJson(); } StringToFile(JsonToString(routingObject), QV2RAY_CONFIG_DIR + "routes.json"); } bool RouteHandler::SetDNSSettings(const GroupRoutingId &id, bool overrideGlobal, const QvConfig_DNS &dns, const QvConfig_FakeDNS &fakeDNS) { configs[id].overrideDNS = overrideGlobal; configs[id].dnsConfig = dns; configs[id].fakeDNSConfig = fakeDNS; return true; } bool RouteHandler::SetAdvancedRouteSettings(const GroupRoutingId &id, bool overrideGlobal, const QvConfig_Route &route) { configs[id].overrideRoute = overrideGlobal; configs[id].routeConfig = route; return true; } bool RouteHandler::ExpandChainedOutbounds(CONFIGROOT &root) const { // Proxy Chain Expansion const auto outbounds = root["outbounds"].toArray(); const auto inbounds = root["inbounds"].toArray(); const auto rules = root["routing"].toObject()["rules"].toArray(); QJsonArray newOutbounds, newInbounds, newRules; QMap<QString, QJsonObject> outboundCache; // First pass - Resolve Indexes (tags), build cache for (const auto &singleOutboundVal : outbounds) { const auto outbound = singleOutboundVal.toObject(); const auto meta = OutboundObjectMeta::loadFromOutbound(OUTBOUND(outbound)); if (meta.metaType != METAOUTBOUND_CHAIN) outboundCache[outbound["tag"].toString()] = outbound; } // Second pass - Build Chains for (const auto &singleOutboundVal : outbounds) { const auto outbound = singleOutboundVal.toObject(); const auto meta = OutboundObjectMeta::loadFromOutbound(OUTBOUND(outbound)); if (meta.metaType != METAOUTBOUND_CHAIN) { newOutbounds << outbound; continue; } if (meta.outboundTags.isEmpty()) { LOG("Trying to expand an empty chain."); continue; } int nextInboundPort = meta.chainPortAllocation; const auto firstOutboundTag = meta.getDisplayName(); const auto lastOutboundTag = meta.outboundTags.first(); OutboundInfoObject lastOutbound; const auto outbountTagCount = meta.outboundTags.count(); for (auto i = outbountTagCount - 1; i >= 0; i--) { const auto chainOutboundTag = meta.outboundTags[i]; const auto isFirstOutbound = i == outbountTagCount - 1; const auto isLastOutbound = i == 0; const auto newOutboundTag = [&]() { if (isFirstOutbound) return firstOutboundTag; else if (isLastOutbound) return lastOutboundTag; else return (firstOutboundTag + "_" + chainOutboundTag + "_" + QSTRN(nextInboundPort)); }(); if (!outboundCache.contains(chainOutboundTag)) { LOG("Cannot build outbound chain: Missing tag: " + firstOutboundTag); return false; } auto newOutbound = outboundCache[chainOutboundTag]; // Create Inbound if (!isFirstOutbound) { const auto inboundTag = firstOutboundTag + ":" + QSTRN(nextInboundPort) + "->" + newOutboundTag; const auto inboundSettings = GenerateDokodemoIN(lastOutbound[INFO_SERVER].toString(), lastOutbound[INFO_PORT].toInt(), "tcp,udp"); const auto newInbound = GenerateInboundEntry(inboundTag, "dokodemo-door", "127.0.0.1", nextInboundPort, inboundSettings); nextInboundPort++; newInbounds << newInbound; // QJsonObject ruleObject; ruleObject["type"] = "field"; ruleObject["inboundTag"] = QJsonArray{ inboundTag }; ruleObject["outboundTag"] = newOutboundTag; newRules.prepend(ruleObject); } if (!isLastOutbound) { // Begin process outbound. const auto outboundProtocol = newOutbound["protocol"].toString(); auto outboundSettings = newOutbound["settings"].toObject(); // Get Outbound Info for next Inbound bool getOutboundInfoStatus = false; lastOutbound = PluginHost->GetOutboundInfo(outboundProtocol, outboundSettings, getOutboundInfoStatus); if (!getOutboundInfoStatus) { LOG("Cannot get outbound info for: " + chainOutboundTag); return false; } // Update allocated port as outbound server/port OutboundInfoObject newOutboundInfo; newOutboundInfo[INFO_SERVER] = "127.0.0.1"; newOutboundInfo[INFO_PORT] = nextInboundPort; // For those kernels deducing SNI from the server name. if (!lastOutbound.contains(INFO_SNI) || lastOutbound[INFO_SNI].toString().trimmed().isEmpty()) newOutboundInfo[INFO_SNI] = lastOutbound[INFO_SERVER]; // PluginHost->SetOutboundInfo(outboundProtocol, newOutboundInfo, outboundSettings); newOutbound.insert("settings", outboundSettings); // Create new outbound newOutbound.insert("tag", newOutboundTag); } newOutbounds << newOutbound; } } // // Finalize { QJsonArray _newInbounds = inbounds, _newRules = rules; for (const auto &in : newInbounds) _newInbounds << in; for (const auto &rule : newRules) _newRules.prepend(rule); root["outbounds"] = newOutbounds; root["inbounds"] = _newInbounds; QJsonIO::SetValue(root, _newRules, "routing", "rules"); } return true; } OUTBOUNDS RouteHandler::ExpandExternalConnection(const OUTBOUNDS &outbounds) const { OUTBOUNDS result; for (const auto &out : outbounds) { auto outObject = out.toObject(); const auto meta = OutboundObjectMeta::loadFromOutbound(OUTBOUND(outObject)); if (meta.metaType == METAOUTBOUND_EXTERNAL) { outObject = ConnectionManager->GetConnectionRoot(meta.connectionId)["outbounds"].toArray().first().toObject(); outObject["tag"] = meta.getDisplayName(); } result << outObject; } return result; } CONFIGROOT RouteHandler::GenerateFinalConfig(const ConnectionGroupPair &p, bool api) const { return GenerateFinalConfig(ConnectionManager->GetConnectionRoot(p.connectionId), ConnectionManager->GetGroupRoutingId(p.groupId), api); } // // BEGIN RUNTIME CONFIG GENERATION // We need copy construct here CONFIGROOT RouteHandler::GenerateFinalConfig(CONFIGROOT root, const GroupRoutingId &routingId, bool hasAPI) const { const auto &config = configs.contains(routingId) ? configs[routingId] : GlobalConfig.defaultRouteConfig; // const auto &connConf = config.overrideConnectionConfig ? config.connectionConfig : GlobalConfig.defaultRouteConfig.connectionConfig; const auto &dnsConf = config.overrideDNS ? config.dnsConfig : GlobalConfig.defaultRouteConfig.dnsConfig; const auto &fakeDNSConf = config.overrideDNS ? config.fakeDNSConfig : GlobalConfig.defaultRouteConfig.fakeDNSConfig; const auto &routeConf = config.overrideRoute ? config.routeConfig : GlobalConfig.defaultRouteConfig.routeConfig; const auto &fpConf = config.overrideForwardProxyConfig ? config.forwardProxyConfig : GlobalConfig.defaultRouteConfig.forwardProxyConfig; const auto &browserForwardingConf = GlobalConfig.inboundConfig.browserForwarderSettings; // // // Note: The part below always makes the whole functionality in // trouble...... BE EXTREME CAREFUL when changing these code // below... // // Check if is complex BEFORE adding anything. bool isComplex = IsComplexConfig(root); if (isComplex) { // For some config files that has routing entries already. // We DO NOT add extra routings. // // HOWEVER, we need to verify the QV2RAY_RULE_ENABLED entry. // And what's more, process (by removing unused items) from a // rule object. ROUTING routing(root["routing"].toObject()); QJsonArray newRules; LOG("Processing an existing routing table."); for (const auto &_rule : routing["rules"].toArray()) { auto rule = _rule.toObject(); // For backward compatibility if (rule.contains("QV2RAY_RULE_USE_BALANCER")) { // We use balancer, or the normal outbound rule.remove(rule["QV2RAY_RULE_USE_BALANCER"].toBool(false) ? "outboundTag" : "balancerTag"); } else { LOG("We found a rule without QV2RAY_RULE_USE_BALANCER, so didn't process it."); } // If this entry has been disabled. if (rule.contains("QV2RAY_RULE_ENABLED") && rule["QV2RAY_RULE_ENABLED"].toBool() == false) { LOG("Discarded a rule as it's been set DISABLED"); } else { newRules.append(rule); } } routing["rules"] = newRules; root["routing"] = routing; root["outbounds"] = ExpandExternalConnection(OUTBOUNDS(root["outbounds"].toArray())); const auto result = ExpandChainedOutbounds(root); if (!result) LOG("Cannot expand chained outbounds!"); } else { LOG("Processing a simple connection config"); if (root["outbounds"].toArray().count() != 1) { // There are no ROUTING but 2 or more outbounds.... This is rare, but possible. LOG("WARN: This message usually indicates the config file has logic errors:"); LOG("WARN: --> The config file has NO routing section, however more than 1 outbounds are detected."); } // auto tag = QJsonIO::GetValue(root, "outbounds", 0, "tag").toString(); if (tag.isEmpty()) { LOG("Applying workaround when an outbound tag is empty"); tag = GenerateRandomString(15); QJsonIO::SetValue(root, tag, "outbounds", 0, "tag"); } root["routing"] = GenerateRoutes(connConf.enableProxy, connConf.bypassCN, connConf.bypassLAN, tag, routeConf); // Browser Forwarding if (QJsonIO::GetValue(root, "outbounds", 0, "streamSettings", "wsSettings", "useBrowserForwarding").toBool(false)) { LOG("Applying browserForwarder configuration"); QJsonIO::SetValue(root, browserForwardingConf.address, "browserForwarder", "listenAddr"); QJsonIO::SetValue(root, browserForwardingConf.port, "browserForwarder", "listenPort"); } // // Forward proxy if (fpConf.enableForwardProxy) { if (QJsonIO::GetValue(root, "outbounds", 0, QV2RAY_USE_FPROXY_KEY).toBool(false)) { if (fpConf.type.isEmpty()) { DEBUG("WARNING: Empty forward proxy type."); } else if (fpConf.type.toLower() != "http" && fpConf.type.toLower() != "socks") { DEBUG("WARNING: Unsupported forward proxy type: " + fpConf.type); } else { const static QJsonObject proxySettings{ { "tag", OUTBOUND_TAG_FORWARD_PROXY }, // { "transportLayer", true } // }; // LOG("Applying forward proxy to current connection."); QJsonIO::SetValue(root, proxySettings, "outbounds", 0, "proxySettings"); const auto forwardProxySettings = GenerateHTTPSOCKSOut(fpConf.serverAddress, // fpConf.port, // fpConf.useAuth, // fpConf.username, // fpConf.password); const auto forwardProxyOutbound = GenerateOutboundEntry(OUTBOUND_TAG_FORWARD_PROXY, // fpConf.type.toLower(), // forwardProxySettings, {}); auto outboundArray = root["outbounds"].toArray(); outboundArray.push_back(forwardProxyOutbound); root["outbounds"] = outboundArray; } } else { // Remove proxySettings from first outbound QJsonIO::SetValue(root, QJsonIO::Undefined, "outbounds", 0, "proxySettings"); } } // // Process FREEDOM and BLACKHOLE outbound { OUTBOUNDS outbounds(root["outbounds"].toArray()); const auto freeDS = (connConf.v2rayFreedomDNS) ? "UseIP" : "AsIs"; outbounds.append(GenerateOutboundEntry(OUTBOUND_TAG_DIRECT, "freedom", GenerateFreedomOUT(freeDS, ":0"), {})); outbounds.append(GenerateOutboundEntry(OUTBOUND_TAG_BLACKHOLE, "blackhole", GenerateBlackHoleOUT(false), {})); root["outbounds"] = outbounds; } // // Connection Filters { if (GlobalConfig.defaultRouteConfig.connectionConfig.dnsIntercept) { const auto hasTProxy = GlobalConfig.inboundConfig.useTPROXY && GlobalConfig.inboundConfig.tProxySettings.hasUDP; const auto hasIPv6 = hasTProxy && (!GlobalConfig.inboundConfig.tProxySettings.tProxyV6IP.isEmpty()); const auto hasSocksUDP = GlobalConfig.inboundConfig.useSocks && GlobalConfig.inboundConfig.socksSettings.enableUDP; DNSInterceptFilter(root, hasTProxy, hasIPv6, hasSocksUDP); } if (GlobalConfig.inboundConfig.useTPROXY && GlobalConfig.outboundConfig.mark > 0) OutboundMarkSettingFilter(root, GlobalConfig.outboundConfig.mark); // Process bypass bitTorrent if (connConf.bypassBT) BypassBTFilter(root); // Process mKCP seed mKCPSeedFilter(root); // Remove empty Mux object from settings RemoveEmptyMuxFilter(root); } } // // Process Log QJsonIO::SetValue(root, V2RayLogLevel[GlobalConfig.logLevel], "log", "loglevel"); // // Process DNS const auto hasDNS = root.contains("dns") && !root.value("dns").toObject().isEmpty(); if (!hasDNS) { root.insert("dns", GenerateDNS(dnsConf)); root.insert("fakedns", fakeDNSConf.toJson()); LOG("Added global DNS config"); } // // If inbounds list is empty, we append our global configured inbounds to the config. // The setting applies to BOTH complex config AND simple config. // Just to ensure there's AT LEAST 1 possible inbound is being configured. if (!root.contains("inbounds") || root.value("inbounds").toArray().empty()) { root["inbounds"] = GenerateDefaultInbounds(); DEBUG("Added global inbound config"); } // // API 0 speed issue occured when no tag is configured. FillupTagsFilter(root, "inbounds"); FillupTagsFilter(root, "outbounds"); // // Let's process some api features. if (hasAPI && GlobalConfig.kernelConfig.enableAPI) { // // Stats root.insert("stats", QJsonObject()); // // Routes QJsonObject routing = root["routing"].toObject(); QJsonArray routingRules = routing["rules"].toArray(); const static QJsonObject APIRouteRoot{ { "type", "field" }, // { "outboundTag", API_TAG_DEFAULT }, // { "inboundTag", QJsonArray{ API_TAG_INBOUND } } }; routingRules.push_front(APIRouteRoot); routing["rules"] = routingRules; root["routing"] = routing; // // Policy QJsonIO::SetValue(root, true, "policy", "system", "statsInboundUplink"); QJsonIO::SetValue(root, true, "policy", "system", "statsInboundDownlink"); QJsonIO::SetValue(root, true, "policy", "system", "statsOutboundUplink"); QJsonIO::SetValue(root, true, "policy", "system", "statsOutboundDownlink"); // // Inbounds INBOUNDS inbounds(root["inbounds"].toArray()); static const QJsonObject fakeDocodemoDoor{ { "address", "127.0.0.1" } }; const auto apiInboundsRoot = GenerateInboundEntry(API_TAG_INBOUND, "dokodemo-door", // "127.0.0.1", // GlobalConfig.kernelConfig.statsPort, // INBOUNDSETTING(fakeDocodemoDoor)); inbounds.push_front(apiInboundsRoot); root["inbounds"] = inbounds; // // API root["api"] = GenerateAPIEntry(API_TAG_DEFAULT); } return root; } } // namespace Qv2ray::core::handler
20,006
C++
.cpp
399
34.769424
150
0.549665
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,125
ConfigHandler.cpp
Qv2ray_Qv2ray/src/core/handler/ConfigHandler.cpp
#include "ConfigHandler.hpp" #include "components/plugins/QvPluginHost.hpp" #include "core/connection/Serialization.hpp" #include "core/handler/RouteHandler.hpp" #include "core/settings/SettingsBackend.hpp" #include "utils/HTTPRequestHelper.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "ConfigHandler" namespace Qv2ray::core::handler { QvConfigHandler::QvConfigHandler(QObject *parent) : QObject(parent) { DEBUG("ConnectionHandler Constructor."); const auto connectionJson = JsonFromString(StringFromFile(QV2RAY_CONFIG_DIR + "connections.json")); const auto groupJson = JsonFromString(StringFromFile(QV2RAY_CONFIG_DIR + "groups.json")); // for (const auto &connectionId : connectionJson.keys()) { connections.insert(ConnectionId{ connectionId }, ConnectionObject::fromJson(connectionJson.value(connectionId).toObject())); } // for (const auto &groupId : groupJson.keys()) { auto groupObject = GroupObject::fromJson(groupJson.value(groupId).toObject()); if (groupObject.displayName.isEmpty()) { groupObject.displayName = tr("Group: %1").arg(GenerateRandomString(5)); } groups.insert(GroupId{ groupId }, groupObject); for (const auto &connId : groupObject.connections) { connections[connId].__qvConnectionRefCount++; } } // for (const auto &id : connections.keys()) { auto const &connectionObject = connections.value(id); if (connectionObject.__qvConnectionRefCount == 0) { QFile connectionFile(QV2RAY_CONNECTIONS_DIR + id.toString() + QV2RAY_CONFIG_FILE_EXTENSION); if (connectionFile.exists()) { if (!connectionFile.remove()) LOG("Failed to remove connection config file"); } connections.remove(id); LOG("Dropped connection id: " + id.toString() + " since it's not in a group"); } else { const auto connectionFilePath = QV2RAY_CONNECTIONS_DIR + id.toString() + QV2RAY_CONFIG_FILE_EXTENSION; connectionRootCache[id] = CONFIGROOT(JsonFromString(StringFromFile(connectionFilePath))); DEBUG("Loaded connection id: " + id.toString() + " into cache."); } } // Force default group name. if (!groups.contains(DefaultGroupId)) { groups.insert(DefaultGroupId, {}); groups[DefaultGroupId].displayName = tr("Default Group"); groups[DefaultGroupId].isSubscription = false; } // kernelHandler = new KernelInstanceHandler(this); connect(kernelHandler, &KernelInstanceHandler::OnCrashed, this, &QvConfigHandler::p_OnKernelCrashed); connect(kernelHandler, &KernelInstanceHandler::OnStatsDataAvailable, this, &QvConfigHandler::p_OnStatsDataArrived); connect(kernelHandler, &KernelInstanceHandler::OnKernelLogAvailable, this, &QvConfigHandler::OnKernelLogAvailable); connect(kernelHandler, &KernelInstanceHandler::OnConnected, this, &QvConfigHandler::OnConnected); connect(kernelHandler, &KernelInstanceHandler::OnDisconnected, this, &QvConfigHandler::OnDisconnected); // pingHelper = new LatencyTestHost(5, this); connect(pingHelper, &LatencyTestHost::OnLatencyTestCompleted, this, &QvConfigHandler::p_OnLatencyDataArrived); // // Save per 1 hour. saveTimerId = startTimer(1 * 60 * 60 * 1000); // Do not ping all... pingConnectionTimerId = startTimer(60 * 1000); } void QvConfigHandler::SaveConnectionConfig() { QJsonObject connectionsObject; for (const auto &key : connections.keys()) { connectionsObject[key.toString()] = connections[key].toJson(); } StringToFile(JsonToString(connectionsObject), QV2RAY_CONFIG_DIR + "connections.json"); // QJsonObject groupObject; for (const auto &key : groups.keys()) { groupObject[key.toString()] = groups[key].toJson(); } StringToFile(JsonToString(groupObject), QV2RAY_CONFIG_DIR + "groups.json"); } void QvConfigHandler::timerEvent(QTimerEvent *event) { if (event->timerId() == saveTimerId) { SaveConnectionConfig(); } else if (event->timerId() == pingAllTimerId) { StartLatencyTest(); } else if (event->timerId() == pingConnectionTimerId) { auto id = kernelHandler->CurrentConnection(); if (!id.isEmpty() && GlobalConfig.advancedConfig.testLatencyPeriodically) { StartLatencyTest(id.connectionId, GlobalConfig.networkConfig.latencyTestingMethod); } } } void QvConfigHandler::StartLatencyTest() { for (const auto &connection : connections.keys()) { emit OnLatencyTestStarted(connection); } pingHelper->TestLatency(connections.keys(), GlobalConfig.networkConfig.latencyTestingMethod); } void QvConfigHandler::StartLatencyTest(const GroupId &id) { for (const auto &connection : groups[id].connections) { emit OnLatencyTestStarted(connection); } pingHelper->TestLatency(groups[id].connections, GlobalConfig.networkConfig.latencyTestingMethod); } void QvConfigHandler::StartLatencyTest(const ConnectionId &id, Qv2rayLatencyTestingMethod method) { emit OnLatencyTestStarted(id); pingHelper->TestLatency(id, method); } const QList<GroupId> QvConfigHandler::Subscriptions() const { QList<GroupId> subsList; for (const auto &group : groups) { if (group.isSubscription) { subsList.push_back(groups.key(group)); } } return subsList; } void QvConfigHandler::ClearGroupUsage(const GroupId &id) { for (const auto &conn : groups[id].connections) { ClearConnectionUsage({ conn, id }); } } void QvConfigHandler::ClearConnectionUsage(const ConnectionGroupPair &id) { CheckValidId(id.connectionId, nothing); connections[id.connectionId].stats.Clear(); emit OnStatsAvailable(id, {}); PluginHost->SendEvent({ GetDisplayName(id.connectionId), 0, 0, 0, 0 }); return; } const QList<GroupId> QvConfigHandler::GetConnectionContainedIn(const ConnectionId &connId) const { CheckValidId(connId, {}); QList<GroupId> grps; for (const auto &group : groups) { if (group.connections.contains(connId)) grps.push_back(groups.key(group)); } return grps; } const std::optional<QString> QvConfigHandler::RenameConnection(const ConnectionId &id, const QString &newName) { CheckValidId(id, {}); emit OnConnectionRenamed(id, connections[id].displayName, newName); PluginHost->SendEvent({ Events::ConnectionEntry::Renamed, newName, connections[id].displayName }); connections[id].displayName = newName; SaveConnectionConfig(); return {}; } bool QvConfigHandler::RemoveConnectionFromGroup(const ConnectionId &id, const GroupId &gid) { CheckValidId(id, false); LOG("Removing connection : " + id.toString()); if (groups[gid].connections.contains(id)) { auto removedEntries = groups[gid].connections.removeAll(id); if (removedEntries > 1) { LOG("Found same connection occured multiple times in a group."); } // Decrease reference count. connections[id].__qvConnectionRefCount -= removedEntries; } if (GlobalConfig.autoStartId == ConnectionGroupPair{ id, gid }) { GlobalConfig.autoStartId.clear(); } // Emit everything first then clear the connection map. PluginHost->SendEvent({ Events::ConnectionEntry::RemovedFromGroup, GetDisplayName(id), "" }); emit OnConnectionRemovedFromGroup({ id, gid }); if (connections[id].__qvConnectionRefCount <= 0) { LOG("Fully removing a connection from cache."); connectionRootCache.remove(id); // QFile connectionFile(QV2RAY_CONNECTIONS_DIR + id.toString() + QV2RAY_CONFIG_FILE_EXTENSION); if (connectionFile.exists()) { if (!connectionFile.remove()) LOG("Failed to remove connection config file"); } connections.remove(id); } return true; } bool QvConfigHandler::LinkConnectionWithGroup(const ConnectionId &id, const GroupId &newGroupId) { CheckValidId(id, false); if (groups[newGroupId].connections.contains(id)) { LOG("Connection not linked since " + id.toString() + " is already in the group " + newGroupId.toString()); return false; } groups[newGroupId].connections.append(id); connections[id].__qvConnectionRefCount++; PluginHost->SendEvent({ Events::ConnectionEntry::LinkedWithGroup, connections[id].displayName, "" }); emit OnConnectionLinkedWithGroup({ id, newGroupId }); return true; } bool QvConfigHandler::MoveConnectionFromToGroup(const ConnectionId &id, const GroupId &sourceGid, const GroupId &targetGid) { CheckValidId(id, false); CheckValidId(targetGid, false); CheckValidId(sourceGid, false); // if (!groups[sourceGid].connections.contains(id)) { LOG("Trying to move a connection away from a group it does not belong to."); return false; } if (groups[targetGid].connections.contains(id)) { LOG("The connection: " + id.toString() + " has already been in the target group: " + targetGid.toString()); const auto removedCount = groups[sourceGid].connections.removeAll(id); connections[id].__qvConnectionRefCount -= removedCount; } else { // If the target group does not contain this connection. const auto removedCount = groups[sourceGid].connections.removeAll(id); connections[id].__qvConnectionRefCount -= removedCount; // groups[targetGid].connections.append(id); connections[id].__qvConnectionRefCount++; } emit OnConnectionRemovedFromGroup({ id, sourceGid }); emit OnConnectionLinkedWithGroup({ id, targetGid }); return true; } const std::optional<QString> QvConfigHandler::DeleteGroup(const GroupId &id) { CheckValidId(id, tr("Group does not exist")); // Copy construct auto list = groups[id].connections; for (const auto &conn : list) { MoveConnectionFromToGroup(conn, id, DefaultGroupId); } PluginHost->SendEvent({ Events::ConnectionEntry::FullyRemoved, groups[id].displayName, "" }); groups.remove(id); SaveConnectionConfig(); emit OnGroupDeleted(id, list); if (id == DefaultGroupId) { groups[id].displayName = tr("Default Group"); } return {}; } bool QvConfigHandler::StartConnection(const ConnectionGroupPair &identifier) { CheckValidId(identifier, false); connections[identifier.connectionId].lastConnected = system_clock::to_time_t(system_clock::now()); // CONFIGROOT root = GetConnectionRoot(identifier.connectionId); const auto fullConfig = RouteManager->GenerateFinalConfig(root, groups[identifier.groupId].routeConfigId); // auto errMsg = kernelHandler->StartConnection(identifier, fullConfig); if (errMsg) { QvMessageBoxWarn(nullptr, tr("Failed to start connection"), *errMsg); return false; } GlobalConfig.lastConnectedId = identifier; return true; } void QvConfigHandler::RestartConnection() { StopConnection(); StartConnection(GlobalConfig.lastConnectedId); } void QvConfigHandler::StopConnection() { kernelHandler->StopConnection(); } void QvConfigHandler::p_OnKernelCrashed(const ConnectionGroupPair &id, const QString &errMessage) { LOG("Kernel crashed: " + errMessage); emit OnDisconnected(id); PluginHost->SendEvent({ GetDisplayName(id.connectionId), QMap<QString, int>{}, Events::Connectivity::Disconnected }); emit OnKernelCrashed(id, errMessage); } QvConfigHandler::~QvConfigHandler() { LOG("Triggering save settings from destructor"); delete kernelHandler; SaveConnectionConfig(); } const CONFIGROOT QvConfigHandler::GetConnectionRoot(const ConnectionId &id) const { CheckValidId(id, CONFIGROOT()); return connectionRootCache.value(id); } void QvConfigHandler::p_OnLatencyDataArrived(const ConnectionId &id, const LatencyTestResult &result) { CheckValidId(id, nothing); connections[id].latency = result.avg; emit OnLatencyTestFinished(id, result.avg); } bool QvConfigHandler::UpdateConnection(const ConnectionId &id, const CONFIGROOT &root, bool skipRestart) { CheckValidId(id, false); // auto path = QV2RAY_CONNECTIONS_DIR + id.toString() + QV2RAY_CONFIG_FILE_EXTENSION; auto content = JsonToString(root); bool result = StringToFile(content, path); // connectionRootCache[id] = root; // emit OnConnectionModified(id); PluginHost->SendEvent({ Events::ConnectionEntry::Edited, connections[id].displayName, "" }); if (!skipRestart && kernelHandler->CurrentConnection().connectionId == id) { RestartConnection(); } return result; } const GroupId QvConfigHandler::CreateGroup(const QString &displayName, bool isSubscription) { GroupId id(GenerateRandomString()); groups[id].displayName = displayName; groups[id].isSubscription = isSubscription; groups[id].creationDate = system_clock::to_time_t(system_clock::now()); PluginHost->SendEvent({ Events::ConnectionEntry::Created, displayName, "" }); emit OnGroupCreated(id, displayName); SaveConnectionConfig(); return id; } const GroupRoutingId QvConfigHandler::GetGroupRoutingId(const GroupId &id) { if (groups[id].routeConfigId == NullRoutingId) { groups[id].routeConfigId = GroupRoutingId{ GenerateRandomString() }; } return groups[id].routeConfigId; } const std::optional<QString> QvConfigHandler::RenameGroup(const GroupId &id, const QString &newName) { CheckValidId(id, tr("Group does not exist")); OnGroupRenamed(id, groups[id].displayName, newName); PluginHost->SendEvent({ Events::ConnectionEntry::Renamed, newName, groups[id].displayName }); groups[id].displayName = newName; return {}; } bool QvConfigHandler::SetSubscriptionData(const GroupId &id, std::optional<bool> isSubscription, const std::optional<QString> &address, std::optional<float> updateInterval) { CheckValidId(id, false); if (isSubscription.has_value()) groups[id].isSubscription = *isSubscription; if (address.has_value()) groups[id].subscriptionOption.address = *address; if (updateInterval.has_value()) groups[id].subscriptionOption.updateInterval = *updateInterval; return true; } bool QvConfigHandler::SetSubscriptionType(const GroupId &id, const QString &type) { CheckValidId(id, false); groups[id].subscriptionOption.type = type; return true; } bool QvConfigHandler::SetSubscriptionIncludeKeywords(const GroupId &id, const QStringList &keywords) { CheckValidId(id, false); groups[id].subscriptionOption.IncludeKeywords.clear(); for (const auto &keyword : keywords) { if (!keyword.trimmed().isEmpty()) { groups[id].subscriptionOption.IncludeKeywords.push_back(keyword); } } return true; } bool QvConfigHandler::SetSubscriptionIncludeRelation(const GroupId &id, SubscriptionFilterRelation relation) { CheckValidId(id, false); groups[id].subscriptionOption.IncludeRelation = relation; return true; } bool QvConfigHandler::SetSubscriptionExcludeKeywords(const GroupId &id, const QStringList &keywords) { CheckValidId(id, false); groups[id].subscriptionOption.ExcludeKeywords.clear(); for (const auto &keyword : keywords) { if (!keyword.trimmed().isEmpty()) { groups[id].subscriptionOption.ExcludeKeywords.push_back(keyword); } } return true; } bool QvConfigHandler::SetSubscriptionExcludeRelation(const GroupId &id, SubscriptionFilterRelation relation) { CheckValidId(id, false); groups[id].subscriptionOption.ExcludeRelation = relation; return true; } void QvConfigHandler::UpdateSubscriptionAsync(const GroupId &id) { CheckValidId(id, nothing); if (!groups[id].isSubscription) return; NetworkRequestHelper::AsyncHttpGet(groups[id].subscriptionOption.address, [=](const QByteArray &d) { p_CHUpdateSubscription(id, d); emit OnSubscriptionAsyncUpdateFinished(id); }); } bool QvConfigHandler::UpdateSubscription(const GroupId &id) { if (!groups[id].isSubscription) return false; const auto data = NetworkRequestHelper::HttpGet(groups[id].subscriptionOption.address); return p_CHUpdateSubscription(id, data); } bool QvConfigHandler::p_CHUpdateSubscription(const GroupId &id, const QByteArray &data) { CheckValidId(id, false); // // ====================================================================================== Begin reading subscription std::shared_ptr<SubscriptionDecoder> decoder; { const auto type = groups[id].subscriptionOption.type; for (const auto &plugin : PluginHost->UsablePlugins()) { const auto pluginInfo = PluginHost->GetPlugin(plugin); if (pluginInfo->hasComponent(COMPONENT_SUBSCRIPTION_ADAPTER)) { const auto adapterInterface = pluginInfo->pluginInterface->GetSubscriptionAdapter(); for (const auto &[t, _] : adapterInterface->SupportedSubscriptionTypes()) { if (t == type) decoder = adapterInterface->GetSubscriptionDecoder(t); } } } if (decoder == nullptr) { QvMessageBoxWarn(nullptr, tr("Cannot Update Subscription"), tr("Unknown subscription type: %1").arg(type) + NEWLINE + tr("A subscription plugin is missing?")); return false; } } const auto groupName = groups[id].displayName; const auto result = decoder->DecodeData(data); QList<std::pair<QString, CONFIGROOT>> _newConnections; for (const auto &[name, json] : result.connections) { _newConnections.append({ name, CONFIGROOT(json) }); } for (const auto &link : result.links) { // Assign a group name, to pass the name check. QString _alias; QString errMessage; QString __groupName = groupName; const auto connectionConfigMap = ConvertConfigFromString(link.trimmed(), &_alias, &errMessage, &__groupName); if (!errMessage.isEmpty()) LOG("Error: ", errMessage); _newConnections << connectionConfigMap; } if (_newConnections.count() < 5) { LOG("Found a subscription with less than 5 connections."); if (QvMessageBoxAsk( nullptr, tr("Update Subscription"), tr("%n entrie(s) have been found from the subscription source, do you want to continue?", "", _newConnections.count())) != Yes) return false; } // // ====================================================================================== Begin Connection Data Storage // Anyway, we try our best to preserve the connection id. QMultiMap<QString, ConnectionId> nameMap; QMultiMap<std::tuple<QString, QString, int>, ConnectionId> typeMap; { // Store connection type metadata into map. for (const auto &conn : groups[id].connections) { nameMap.insert(GetDisplayName(conn), conn); const auto &&[protocol, host, port] = GetConnectionInfo(conn); if (port != 0) { typeMap.insert({ protocol, host, port }, conn); } } } // ====================================================================================== End Connection Data Storage // bool hasErrorOccured = false; // Copy construct here. auto originalConnectionIdList = groups[id].connections; groups[id].connections.clear(); // decltype(_newConnections) filteredConnections; // for (const auto &config : _newConnections) { // filter connections const bool isIncludeOperationAND = groups[id].subscriptionOption.IncludeRelation == RELATION_AND; const bool isExcludeOperationOR = groups[id].subscriptionOption.ExcludeRelation == RELATION_OR; // // Initial includeConfig value bool includeconfig = isIncludeOperationAND; { bool hasIncludeItemMatched = false; for (const auto &key : groups[id].subscriptionOption.IncludeKeywords) { if (!key.trimmed().isEmpty()) { hasIncludeItemMatched = true; // WARN: MAGIC, DO NOT TOUCH if (!isIncludeOperationAND == config.first.contains(key.trimmed())) { includeconfig = !isIncludeOperationAND; break; } } } // If includekeywords is empty then include all configs. if (!hasIncludeItemMatched) includeconfig = true; } if (includeconfig) { bool hasExcludeItemMatched = false; includeconfig = isExcludeOperationOR; for (const auto &key : groups[id].subscriptionOption.ExcludeKeywords) { if (!key.trimmed().isEmpty()) { hasExcludeItemMatched = true; // WARN: MAGIC, DO NOT TOUCH if (isExcludeOperationOR == config.first.contains(key.trimmed())) { includeconfig = !isExcludeOperationOR; break; } } } // If excludekeywords is empty then don't exclude any configs. if (!hasExcludeItemMatched) includeconfig = true; } if (includeconfig) { filteredConnections << config; } } LOG("Filtered out less than 5 connections."); const auto useFilteredConnections = filteredConnections.count() > 5 || QvMessageBoxAsk(nullptr, tr("Update Subscription"), tr("%1 out of %n entrie(s) have been filtered out, do you want to continue?", "", _newConnections.count()) .arg(filteredConnections.count()) + NEWLINE + GetDisplayName(id)) == Yes; for (const auto &config : useFilteredConnections ? filteredConnections : _newConnections) { const auto &_alias = config.first; // Should not have complex connection we assume. bool canGetOutboundData = false; const auto &&[protocol, host, port] = GetConnectionInfo(config.second, &canGetOutboundData); const auto outboundData = std::make_tuple(protocol, host, port); // // ====================================================================================== Begin guessing new ConnectionId if (nameMap.contains(_alias)) { // Just go and save the connection... LOG("Reused connection id from name: " + _alias); const auto _conn = nameMap.take(_alias); groups[id].connections << _conn; UpdateConnection(_conn, config.second, true); // Remove Connection Id from the list. originalConnectionIdList.removeAll(_conn); typeMap.remove(typeMap.key(_conn)); } else if (canGetOutboundData && typeMap.contains(outboundData)) { LOG("Reused connection id from protocol/host/port pair for connection: " + _alias); const auto _conn = typeMap.take(outboundData); groups[id].connections << _conn; // Update Connection Properties UpdateConnection(_conn, config.second, true); RenameConnection(_conn, _alias); // Remove Connection Id from the list. originalConnectionIdList.removeAll(_conn); nameMap.remove(nameMap.key(_conn)); } else { // New connection id is required since nothing matched found... LOG("Generated new connection id for connection: " + _alias); CreateConnection(config.second, _alias, id, true); } // ====================================================================================== End guessing new ConnectionId } // Check if anything left behind (not being updated or changed significantly) if (!originalConnectionIdList.isEmpty()) { bool needContinue = QvMessageBoxAsk(nullptr, // tr("Update Subscription"), tr("There're %n connection(s) in the group that do not belong the current subscription (any more).", "", originalConnectionIdList.count()) + NEWLINE + GetDisplayName(id) + NEWLINE + tr("Would you like to remove them?")) == Yes; if (needContinue) { LOG("Removed old connections not have been matched."); for (const auto &conn : originalConnectionIdList) { LOG("Removing connections not in the new subscription: " + conn.toString()); RemoveConnectionFromGroup(conn, id); } } } // Update the time groups[id].lastUpdatedDate = system_clock::to_time_t(system_clock::now()); return hasErrorOccured; } void QvConfigHandler::p_OnStatsDataArrived(const ConnectionGroupPair &id, const QMap<StatisticsType, QvStatsSpeed> &data) { if (id.isEmpty()) return; const auto &cid = id.connectionId; QMap<StatisticsType, QvStatsSpeedData> result; for (const auto t : data.keys()) { const auto &stat = data[t]; connections[cid].stats[t].upLinkData += stat.first; connections[cid].stats[t].downLinkData += stat.second; result[t] = { stat, connections[cid].stats[t].toData() }; } emit OnStatsAvailable(id, result); PluginHost->SendEvent({ GetDisplayName(cid), // result[CurrentStatAPIType].first.first, // result[CurrentStatAPIType].first.second, // result[CurrentStatAPIType].second.first, // result[CurrentStatAPIType].second.second }); } const ConnectionGroupPair QvConfigHandler::CreateConnection(const CONFIGROOT &root, const QString &displayName, const GroupId &groupId, bool skipSaveConfig) { LOG("Creating new connection: " + displayName); ConnectionId newId(GenerateUuid()); groups[groupId].connections << newId; connections[newId].creationDate = system_clock::to_time_t(system_clock::now()); connections[newId].displayName = displayName; connections[newId].__qvConnectionRefCount = 1; emit OnConnectionCreated({ newId, groupId }, displayName); PluginHost->SendEvent({ Events::ConnectionEntry::Created, displayName, "" }); UpdateConnection(newId, root); if (!skipSaveConfig) { SaveConnectionConfig(); } return { newId, groupId }; } } // namespace Qv2ray::core::handler #undef CheckIdExistance #undef CheckGroupExistanceEx #undef CheckGroupExistance #undef CheckConnectionExistanceEx #undef CheckConnectionExistance
30,320
C++
.cpp
695
32.322302
148
0.59209
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,126
KernelInstanceHandler.cpp
Qv2ray_Qv2ray/src/core/handler/KernelInstanceHandler.cpp
#include "KernelInstanceHandler.hpp" #include "components/port/QvPortDetector.hpp" #include "core/connection/Generation.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "KernelHandler" namespace Qv2ray::core::handler { #define isConnected (vCoreInstance->IsKernelRunning() || !activeKernels.empty()) KernelInstanceHandler::KernelInstanceHandler(QObject *parent) : QObject(parent) { KernelInstance = this; vCoreInstance = new V2RayKernelInstance(this); connect(vCoreInstance, &V2RayKernelInstance::OnNewStatsDataArrived, this, &KernelInstanceHandler::OnV2RayStatsDataRcvd_p); connect(vCoreInstance, &V2RayKernelInstance::OnProcessOutputReadyRead, this, &KernelInstanceHandler::OnV2RayKernelLog_p); connect(vCoreInstance, &V2RayKernelInstance::OnProcessErrored, this, &KernelInstanceHandler::OnKernelCrashed_p); // auto kernelList = PluginHost->UsablePlugins(); for (const auto &internalName : kernelList) { const auto info = PluginHost->GetPlugin(internalName); if (!info->hasComponent(COMPONENT_KERNEL)) continue; auto kernel = info->pluginInterface->GetKernel(); for (const auto &protocol : kernel->GetKernelProtocols()) { if (kernelMap.contains(protocol)) { LOG("Found multiple kernel providers for a protocol: " + protocol); continue; } kernelMap.insert(protocol, internalName); } } } KernelInstanceHandler::~KernelInstanceHandler() { StopConnection(); } std::optional<QString> KernelInstanceHandler::CheckPort(const QMap<QString, ProtocolSettingsInfoObject> &info, int plugins) { QStringList portDetectionErrorMessage; auto portDetectionMsg = tr("There are other processes occupying the ports necessary to start the connection:") + NEWLINE + NEWLINE; for (const auto &key : info.keys()) { const auto result = components::port::CheckTCPPortStatus(info[key].address, info[key].port); if (!result) portDetectionErrorMessage << tr("Endpoint: %1:%2 for inbound: \"%3\"").arg(info[key].address).arg(info[key].port).arg(key); } if (GlobalConfig.pluginConfig.v2rayIntegration) { for (auto i = 0; i < plugins; i++) { const auto thisPort = GlobalConfig.pluginConfig.portAllocationStart + i; const auto result = components::port::CheckTCPPortStatus("127.0.0.1", thisPort); if (!result) portDetectionErrorMessage << tr("Local port: %1 for plugin integration.").arg(thisPort); } } if (!portDetectionErrorMessage.isEmpty()) { portDetectionMsg += portDetectionErrorMessage.join(NEWLINE); return portDetectionMsg; } else { return std::nullopt; } } std::optional<QString> KernelInstanceHandler::StartConnection(const ConnectionGroupPair &id, CONFIGROOT fullConfig) { StopConnection(); inboundInfo = GetInboundInfo(fullConfig); // const auto inboundPorts = GetInboundPorts(); const auto inboundHosts = GetInboundHosts(); PluginHost->SendEvent({ GetDisplayName(id.connectionId), inboundPorts, Events::Connectivity::Connecting }); // QList<std::tuple<QString, int, QString>> inboundInfo; // for (const auto &inbound_v : fullConfig["inbounds"].toArray()) //{ // const auto &inbound = inbound_v.toObject(); // inboundInfo.push_back({ inbound["protocol"].toString(), inbound["port"].toInt(), inbound["tag"].toString() }); //} // if (GlobalConfig.pluginConfig.v2rayIntegration) { // Process outbounds. OUTBOUNDS processedOutbounds; auto pluginPort = GlobalConfig.pluginConfig.portAllocationStart; // for (auto i = 0; i < fullConfig["outbounds"].toArray().count(); i++) { auto outbound = QJsonIO::GetValue(fullConfig, "outbounds", i).toObject(); const auto outProtocol = outbound["protocol"].toString(); // if (!kernelMap.contains(outProtocol)) { // Normal outbound, or the one without a plugin supported. // Marked as processed. processedOutbounds.push_back(outbound); LOG("Outbound protocol " + outProtocol + " is not a registered plugin outbound."); continue; } LOG("Creating kernel plugin instance for protocol" + outProtocol); auto kernel = PluginHost->GetPlugin(kernelMap[outProtocol])->pluginInterface->GetKernel()->CreateKernel(); // New object does not need disconnect? // disconnect(kernel, &QvPluginKernel::OnKernelStatsAvailable, this, &KernelInstanceHandler::OnStatsDataArrived_p); // QMap<KernelOptionFlags, QVariant> _inboundSettings; LOG("V2RayIntegration: " + QSTRN(pluginPort) + " = " + outProtocol); _inboundSettings[KERNEL_HTTP_ENABLED] = false; _inboundSettings[KERNEL_SOCKS_ENABLED] = true; _inboundSettings[KERNEL_SOCKS_PORT] = pluginPort; _inboundSettings[KERNEL_SOCKS_UDP_ENABLED] = GlobalConfig.inboundConfig.socksSettings.enableUDP; _inboundSettings[KERNEL_SOCKS_LOCAL_ADDRESS] = GlobalConfig.inboundConfig.socksSettings.localIP; _inboundSettings[KERNEL_LISTEN_ADDRESS] = "127.0.0.1"; LOG("Sending connection settings to kernel."); kernel->SetConnectionSettings(_inboundSettings, outbound["settings"].toObject()); activeKernels.push_back({ outProtocol, std::move(kernel) }); // const auto pluginOutSettings = GenerateHTTPSOCKSOut("127.0.0.1", pluginPort, false, "", ""); // const auto pluginOut = GenerateOutboundEntry(outbound["tag"].toString(), "socks", pluginOutSettings, {}); // // Add the integration outbound to the list. processedOutbounds.push_back(pluginOut); pluginPort++; } LOG("Applying new outbound settings."); fullConfig["outbounds"] = processedOutbounds; RemoveEmptyMuxFilter(fullConfig); } // // ======================================================================= Start Kernels // { const auto portResult = CheckPort(inboundInfo, activeKernels.size()); if (portResult) { LOG(*portResult); return portResult; } auto firstOutbound = fullConfig["outbounds"].toArray().first().toObject(); const auto firstOutboundProtocol = firstOutbound["protocol"].toString(); if (GlobalConfig.pluginConfig.v2rayIntegration) { LOG("Starting kernels with V2RayIntegration."); bool hasAllKernelStarted = true; for (auto &[outboundProtocol, kernelObject] : activeKernels) { LOG("Starting kernel for protocol: " + outboundProtocol); bool status = kernelObject->StartKernel(); connect(kernelObject.get(), &PluginKernel::OnKernelCrashed, this, &KernelInstanceHandler::OnKernelCrashed_p, Qt::QueuedConnection); connect(kernelObject.get(), &PluginKernel::OnKernelLogAvailable, this, &KernelInstanceHandler::OnPluginKernelLog_p, Qt::QueuedConnection); hasAllKernelStarted = hasAllKernelStarted && status; if (!status) { LOG("Plugin Kernel: " + outboundProtocol + " failed to start."); break; } } if (!hasAllKernelStarted) { StopConnection(); return tr("A plugin kernel failed to start. Please check the outbound settings."); } currentId = id; // // Also start V2Ray-core. auto result = vCoreInstance->StartConnection(fullConfig); // if (result.has_value()) { StopConnection(); PluginHost->SendEvent({ GetDisplayName(id.connectionId), inboundPorts, Events::Connectivity::Disconnected }); return result; } else { emit OnConnected(id); PluginHost->SendEvent({ GetDisplayName(id.connectionId), inboundPorts, Events::Connectivity::Connected }); } } else if (kernelMap.contains(firstOutboundProtocol)) { // Connections without V2Ray Integration will have and ONLY have ONE kernel. LOG("Starting kernel " + firstOutboundProtocol + " without V2Ray Integration"); { auto kernel = PluginHost->GetPlugin(kernelMap[firstOutbound["protocol"].toString()])->pluginInterface->GetKernel()->CreateKernel(); activeKernels.push_back({ firstOutboundProtocol, std::move(kernel) }); } Q_ASSERT(activeKernels.size() == 1); #define theKernel (activeKernels.front().second.get()) connect(theKernel, &PluginKernel::OnKernelStatsAvailable, this, &KernelInstanceHandler::OnPluginStatsDataRcvd_p, Qt::QueuedConnection); connect(theKernel, &PluginKernel::OnKernelCrashed, this, &KernelInstanceHandler::OnKernelCrashed_p, Qt::QueuedConnection); connect(theKernel, &PluginKernel::OnKernelLogAvailable, this, &KernelInstanceHandler::OnPluginKernelLog_p, Qt::QueuedConnection); currentId = id; // QMap<KernelOptionFlags, QVariant> pluginSettings; for (const auto &v : inboundInfo) { if (v.protocol != "http" && v.protocol != "socks") continue; pluginSettings[KERNEL_HTTP_ENABLED] = pluginSettings[KERNEL_HTTP_ENABLED].toBool() || v.protocol == "http"; pluginSettings[KERNEL_SOCKS_ENABLED] = pluginSettings[KERNEL_SOCKS_ENABLED].toBool() || v.protocol == "socks"; pluginSettings.insert(v.protocol.toLower() == "http" ? KERNEL_HTTP_PORT : KERNEL_SOCKS_PORT, v.port); } pluginSettings[KERNEL_SOCKS_UDP_ENABLED] = GlobalConfig.inboundConfig.socksSettings.enableUDP; pluginSettings[KERNEL_SOCKS_LOCAL_ADDRESS] = GlobalConfig.inboundConfig.socksSettings.localIP; pluginSettings[KERNEL_LISTEN_ADDRESS] = GlobalConfig.inboundConfig.listenip; // theKernel->SetConnectionSettings(pluginSettings, firstOutbound["settings"].toObject()); bool kernelStarted = theKernel->StartKernel(); #undef theKernel if (kernelStarted) { emit OnConnected(id); PluginHost->SendEvent({ GetDisplayName(id.connectionId), inboundPorts, Events::Connectivity::Connected }); } else { return tr("A plugin kernel failed to start. Please check the outbound settings."); StopConnection(); } } else { LOG("Starting V2Ray without plugin."); currentId = id; auto result = vCoreInstance->StartConnection(fullConfig); if (result.has_value()) { PluginHost->SendEvent({ GetDisplayName(id.connectionId), inboundPorts, Events::Connectivity::Disconnected }); StopConnection(); return result; } else { emit OnConnected(id); PluginHost->SendEvent({ GetDisplayName(id.connectionId), inboundPorts, Events::Connectivity::Connected }); } } } // Return return std::nullopt; } void KernelInstanceHandler::OnKernelCrashed_p(const QString &msg) { emit OnCrashed(currentId, msg); StopConnection(); } void KernelInstanceHandler::emitLogMessage(const QString &l) { emit OnKernelLogAvailable(currentId, l); } void KernelInstanceHandler::OnPluginKernelLog_p(const QString &log) { if (pluginLogPrefixPadding <= 0) for (const auto &[_, kernel] : activeKernels) pluginLogPrefixPadding = std::max(pluginLogPrefixPadding, kernel->GetKernelName().length()); const auto kernel = static_cast<PluginKernel *>(sender()); const auto name = kernel ? kernel->GetKernelName() : "UNKNOWN"; for (const auto &line : SplitLines(log)) emitLogMessage(QString("[%1] ").arg(name, pluginLogPrefixPadding) + line.trimmed()); } void KernelInstanceHandler::OnV2RayKernelLog_p(const QString &log) { for (auto line : SplitLines(log)) emitLogMessage(line.trimmed()); } void KernelInstanceHandler::StopConnection() { if (isConnected) { const auto inboundPorts = GetInboundPorts(); PluginHost->SendEvent({ GetDisplayName(currentId.connectionId), inboundPorts, Events::Connectivity::Disconnecting }); if (vCoreInstance->IsKernelRunning()) { vCoreInstance->StopConnection(); } for (const auto &[kernel, kernelObject] : activeKernels) { LOG("Stopping plugin kernel: " + kernel); kernelObject->StopKernel(); } pluginLogPrefixPadding = 0; emit OnDisconnected(currentId); PluginHost->SendEvent({ GetDisplayName(currentId.connectionId), inboundPorts, Events::Connectivity::Disconnected }); } else { LOG("Cannot disconnect when there's nothing connected."); } currentId.clear(); activeKernels.clear(); } void KernelInstanceHandler::OnV2RayStatsDataRcvd_p(const QMap<StatisticsType, QvStatsSpeed> &data) { if (isConnected) { emit OnStatsDataAvailable(currentId, data); } } void KernelInstanceHandler::OnPluginStatsDataRcvd_p(const long uploadSpeed, const long downloadSpeed) { OnV2RayStatsDataRcvd_p({ { API_OUTBOUND_PROXY, { uploadSpeed, downloadSpeed } } }); } } // namespace Qv2ray::core::handler
15,249
C++
.cpp
311
35.575563
145
0.585456
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,127
SettingsBackend.cpp
Qv2ray_Qv2ray/src/core/settings/SettingsBackend.cpp
#include "SettingsBackend.hpp" #include "base/Qv2rayLog.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "SettingsBackend" constexpr auto QV2RAY_CONFIG_PATH_ENV_NAME = "QV2RAY_CONFIG_PATH"; namespace Qv2ray::core::config { void SaveGlobalSettings() { const auto str = JsonToString(GlobalConfig.toJson()); StringToFile(str, QV2RAY_CONFIG_FILE); } void SetConfigDirPath(const QString &path) { QvCoreApplication->ConfigPath = path; if (!path.endsWith("/")) { QvCoreApplication->ConfigPath += "/"; } } bool CheckSettingsPathAvailability(const QString &_path, bool checkExistingConfig) { auto path = _path; if (!path.endsWith("/")) path.append("/"); // Does not exist. if (!QDir(path).exists()) return false; { // A temp file used to test file permissions in that folder. QFile testFile(path + ".qv2ray_test_file" + QSTRN(QTime::currentTime().msecsSinceStartOfDay())); if (!testFile.open(QFile::OpenModeFlag::ReadWrite)) { LOG("Directory at: " + path + " cannot be used as a valid config file path."); LOG("---> Cannot create a new file or open a file for writing."); return false; } testFile.write("Qv2ray test file, feel free to remove."); testFile.flush(); testFile.close(); if (!testFile.remove()) { // This is rare, as we can create a file but failed to remove it. LOG("Directory at: " + path + " cannot be used as a valid config file path."); LOG("---> Cannot remove a file."); return false; } } if (!checkExistingConfig) { // Just pass the test return true; } // Check if an existing config is found. QFile configFile(path + "Qv2ray.conf"); // No such config file. if (!configFile.exists()) return false; if (!configFile.open(QIODevice::ReadWrite)) { LOG("File: " + configFile.fileName() + " cannot be opened!"); return false; } const auto err = VerifyJsonString(StringFromFile(configFile)); if (!err.isEmpty()) { LOG("Json parse returns:", err); return false; } // If the file format is valid. const auto conf = JsonFromString(StringFromFile(configFile)); LOG("Found a config file," QVLOG_A(conf["config_version"].toString()) QVLOG_A(path)); configFile.close(); return true; } bool LocateConfiguration() { LOG("Application exec path: " + qApp->applicationDirPath()); // Non-standard paths needs special handing for "_debug" const auto currentPathConfig = qApp->applicationDirPath() + "/config" QV2RAY_CONFIG_DIR_SUFFIX; const auto homeQv2ray = QDir::homePath() + "/.qv2ray" QV2RAY_CONFIG_DIR_SUFFIX; // // Standard paths already handles the "_debug" suffix for us. const auto configQv2ray = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); // // // Some built-in search paths for Qv2ray to find configs. (load the first one if possible). const auto useManualConfigPath = qEnvironmentVariableIsSet(QV2RAY_CONFIG_PATH_ENV_NAME); const auto manualConfigPath = qEnvironmentVariable(QV2RAY_CONFIG_PATH_ENV_NAME); // QStringList configFilePaths; if (useManualConfigPath) { LOG("Using config path from env: " + manualConfigPath); configFilePaths << manualConfigPath; } else { configFilePaths << currentPathConfig; configFilePaths << configQv2ray; configFilePaths << homeQv2ray; } QString configPath = ""; bool hasExistingConfig = false; for (const auto &path : configFilePaths) { // Verify the config path, check if the config file exists and in the // correct JSON format. True means we check for config existence as // well. ---------------------------------------------|HERE| bool isValidConfigPath = CheckSettingsPathAvailability(path, true); // If we already found a valid config file. just simply load it... if (hasExistingConfig) break; if (isValidConfigPath) { DEBUG("Path:", path, " is valid."); configPath = path; hasExistingConfig = true; } else { LOG("Path:", path, "does not contain a valid config file."); } } if (hasExistingConfig) { // Use the config path found by the checks above SetConfigDirPath(configPath); LOG("Using ", QV2RAY_CONFIG_DIR, " as the config path."); } else { // If there's no existing config. // // Create new config at these dirs, these are default values for each platform. if (useManualConfigPath) { configPath = manualConfigPath; } else { #if defined(Q_OS_WIN) && !defined(QV2RAY_NO_ASIDECONFIG) configPath = currentPathConfig; #else configPath = configQv2ray; #endif } bool hasPossibleNewLocation = QDir().mkpath(configPath) && CheckSettingsPathAvailability(configPath, false); // Check if the dirs are write-able if (!hasPossibleNewLocation) { // None of the path above can be used as a dir for storing config. // Even the last folder failed to pass the check. LOG("FATAL"); LOG(" ---> CANNOT find a proper place to store Qv2ray config files."); QvMessageBoxWarn(nullptr, QObject::tr("Cannot Start Qv2ray"), QObject::tr("Cannot find a place to store config files.") + NEWLINE + // QObject::tr("Qv2ray has searched these paths below:") + NEWLINE + NEWLINE + // configFilePaths.join(NEWLINE) + NEWLINE + // QObject::tr("It usually means you don't have the write permission to all of those locations.") + NEWLINE + // QObject::tr("Qv2ray will now exit.")); // return false; } // Found a valid config dir, with write permission, but assume no config is located in it. LOG("Set " + configPath + " as the config path."); SetConfigDirPath(configPath); if (QFile::exists(QV2RAY_CONFIG_FILE)) { // As we already tried to load config from every possible dir. // // This condition branch (!hasExistingConfig check) holds the fact that current config dir, // should NOT contain any valid file (at least in the same name) // // It usually means that QV2RAY_CONFIG_FILE here has a corrupted JSON format. // // Otherwise Qv2ray would have loaded this config already instead of notifying to create a new config in this folder. // LOG("This should not occur: Qv2ray config exists but failed to load."); QvMessageBoxWarn(nullptr, QObject::tr("Failed to initialise Qv2ray"), QObject::tr("Failed to determine the location of config file:") + NEWLINE + // QObject::tr("Qv2ray has found a config file, but it failed to be loaded due to some errors.") + NEWLINE + // QObject::tr("A workaround is to remove the this file and restart Qv2ray:") + NEWLINE + // QV2RAY_CONFIG_FILE + NEWLINE + // QObject::tr("Qv2ray will now exit.") + NEWLINE + // QObject::tr("Please report if you think it's a bug.")); // return false; } GlobalConfig.kernelConfig.KernelPath(QV2RAY_DEFAULT_VCORE_PATH); GlobalConfig.kernelConfig.AssetsPath(QV2RAY_DEFAULT_VASSETS_PATH); GlobalConfig.logLevel = 3; GlobalConfig.uiConfig.language = QLocale::system().name(); GlobalConfig.defaultRouteConfig.dnsConfig.servers.append({ "1.1.1.1" }); GlobalConfig.defaultRouteConfig.dnsConfig.servers.append({ "8.8.8.8" }); GlobalConfig.defaultRouteConfig.dnsConfig.servers.append({ "8.8.4.4" }); // Save initial config. SaveGlobalSettings(); LOG("Created initial config file."); } if (!QDir(QV2RAY_GENERATED_DIR).exists()) { // The dir used to generate final config file, for V2Ray interaction. QDir().mkdir(QV2RAY_GENERATED_DIR); LOG("Created config generation dir at: " + QV2RAY_GENERATED_DIR); } // // BEGIN LOAD CONFIGURATIONS // { // Load the config for upgrade, but do not parse it to the struct. auto conf = JsonFromString(StringFromFile(QV2RAY_CONFIG_FILE)); const auto configVersion = conf["config_version"].toInt(); if (configVersion > QV2RAY_CONFIG_VERSION) { // Config version is larger than the current version... // This is rare but it may happen.... QvMessageBoxWarn(nullptr, QObject::tr("Qv2ray Cannot Continue"), // QObject::tr("You are running a lower version of Qv2ray compared to the current config file.") + NEWLINE + // QObject::tr("Please check if there's an issue explaining about it.") + NEWLINE + // QObject::tr("Or submit a new issue if you think this is an error.") + NEWLINE + NEWLINE + // QObject::tr("Qv2ray will now exit.")); return false; } else if (configVersion < QV2RAY_CONFIG_VERSION) { // That is the config file needs to be upgraded. conf = Qv2ray::UpgradeSettingsVersion(configVersion, QV2RAY_CONFIG_VERSION, conf); } // Let's save the config. GlobalConfig.loadJson(conf); SaveGlobalSettings(); return true; } } } // namespace Qv2ray::core::config using namespace Qv2ray::core::config;
11,513
C++
.cpp
235
35.855319
146
0.53028
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,128
SettingsUpgrade.cpp
Qv2ray_Qv2ray/src/core/settings/SettingsUpgrade.cpp
// // This file handles some important migration // from old to newer versions of Qv2ray. // #include "base/Qv2rayBase.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "SettingsUpgrade" #define UPGRADELOG(msg) LOG("[" + QSTRN(fromVersion) + "-" + QSTRN(fromVersion + 1) + "] --> " + msg) namespace Qv2ray { // Private member QJsonObject UpgradeConfig_Inc(int fromVersion, const QJsonObject &original) { auto root = original; switch (fromVersion) { // Qv2ray version 2, RC 4 case 6: { // Moved API Stats port from connectionConfig to apiConfig QJsonObject apiConfig; apiConfig["enableAPI"] = true; apiConfig["statsPort"] = root["connectionConfig"].toObject()["statsPort"].toInt(); root["apiConfig"] = apiConfig; break; } case 7: { auto lang = root["uiConfig"].toObject()["language"].toString().replace("-", "_"); auto uiConfig = root["uiConfig"].toObject(); uiConfig["language"] = lang; root["uiConfig"] = uiConfig; UPGRADELOG("Changed language: " + lang); break; } // From version 8 to 9, we introduced a lot of new connection metainfo(s) case 8: { // Generate a default group QJsonObject defaultGroup; QStringList defaultGroupConnectionId; defaultGroup["displayName"] = QObject::tr("Default Group"); QString defaultGroupId = "000000000000"; if (!QDir(QV2RAY_CONNECTIONS_DIR + defaultGroupId).exists()) { QDir().mkpath(QV2RAY_CONNECTIONS_DIR + defaultGroupId); } QString autoStartId; UPGRADELOG("Upgrading connections..."); QJsonObject rootConnections; for (auto config : root["configs"].toArray()) { UPGRADELOG("Migrating: " + config.toString()); // // MOVE FILES. // OLD PATH is at QV2RAY_CONFIG_DIR auto filePath = QV2RAY_CONFIG_DIR + config.toString() + QV2RAY_CONFIG_FILE_EXTENSION; auto configFile = QFile(filePath); auto newUuid = GenerateUuid(); DEBUG("Generated new UUID: " + newUuid); // Check Autostart Id if (root["autoStartConfig"].toObject()["subscriptionName"].toString().isEmpty()) { if (root["autoStartConfig"].toObject()["connectionName"].toString() == config.toString()) { autoStartId = newUuid; } } if (configFile.exists()) { auto newPath = QV2RAY_CONNECTIONS_DIR + defaultGroupId + "/" + newUuid + QV2RAY_CONFIG_FILE_EXTENSION; configFile.rename(newPath); UPGRADELOG("Moved: " + filePath + " to " + newPath); } else { UPGRADELOG("WARNING! This file is not found, possible loss of data!"); continue; } QJsonObject connectionObject; connectionObject["displayName"] = config.toString(); defaultGroupConnectionId << newUuid; DEBUG("Pushed uuid: " + newUuid + " to default group."); rootConnections[newUuid] = connectionObject; } // Upgrading subscriptions. QJsonObject rootSubscriptions = root.take("subscriptions").toObject(); QJsonObject newSubscriptions; for (auto i = 0; i < rootSubscriptions.count(); i++) { auto key = rootSubscriptions.keys().at(i); auto value = rootSubscriptions.value(key); // UPGRADELOG("Upgrading subscription: " + key); QString subsUuid = GenerateUuid(); QJsonObject subs; QStringList subsConnectionIds; subs["address"] = value["address"].toString(); subs["lastUpdated"] = value["lastUpdated"]; subs["updateInterval"] = value["updateInterval"]; subs["displayName"] = key; // auto baseDirPath = QV2RAY_CONFIG_DIR + "/subscriptions/" + key; auto newDirPath = QV2RAY_CONFIG_DIR + "/subscriptions/" + subsUuid; QDir newDir(newDirPath); if (!newDir.exists()) { newDir.mkpath(newDirPath); } // With extensions auto fileList = GetFileList(baseDirPath); // Copy every file within a subscription. for (const auto &fileName : fileList) { auto subsConnectionId = GenerateUuid(); auto baseFilePath = baseDirPath + "/" + fileName; auto newFilePath = newDirPath + "/" + subsConnectionId + QV2RAY_CONFIG_FILE_EXTENSION; // QJsonObject subsConnection; subsConnection["displayName"] = fileName.chopped(QString(QV2RAY_CONFIG_FILE_EXTENSION).count()); QFile(baseFilePath).rename(newFilePath); UPGRADELOG("Moved subscription file from: " + baseFilePath + " to: " + newFilePath); subsConnectionIds << subsConnectionId; rootConnections[subsConnectionId] = subsConnection; // // Check Autostart Id if (root["autoStartConfig"].toObject()["subscriptionName"].toString() == key) { if (root["autoStartConfig"].toObject()["connectionName"].toString() == subsConnection["displayName"].toString()) { autoStartId = subsConnectionId; } } } subs["connections"] = QJsonArray::fromStringList(subsConnectionIds); newSubscriptions[subsUuid] = subs; QDir().rmdir(baseDirPath); } defaultGroup["connections"] = QJsonArray::fromStringList(defaultGroupConnectionId); QJsonObject groups; groups[defaultGroupId] = defaultGroup; root["autoStartId"] = autoStartId; root["groups"] = groups; root["connections"] = rootConnections; root["subscriptions"] = newSubscriptions; UPGRADELOG("Finished upgrading config, version 8."); break; } // Added cross-platform vCore and vAssets path support; case 9: { QJsonObject kernelConfig; #ifdef Q_OS_LINUX #define _VARNAME_VCOREPATH_ kernelConfig["v2CorePath_linux"] #define _VARNAME_VASSETSPATH_ kernelConfig["v2AssetsPath_linux"] UPGRADELOG("Update kernel and assets paths for linux"); #elif defined(Q_OS_MACOS) #define _VARNAME_VCOREPATH_ kernelConfig["v2CorePath_macx"] #define _VARNAME_VASSETSPATH_ kernelConfig["v2AssetsPath_macx"] UPGRADELOG("Update kernel and assets paths for macOS"); #elif defined(Q_OS_WIN) #define _VARNAME_VCOREPATH_ kernelConfig["v2CorePath_win"] #define _VARNAME_VASSETSPATH_ kernelConfig["v2AssetsPath_win"] UPGRADELOG("Update kernel and assets paths for Windows"); #endif _VARNAME_VCOREPATH_ = root["v2CorePath"].toString(); _VARNAME_VASSETSPATH_ = root["v2AssetsPath"].toString(); // root["kernelConfig"] = kernelConfig; #undef _VARNAME_VCOREPATH_ #undef _VARNAME_VASSETSPATH_ break; } case 10: { // It's worth that use a seperated config number to notify all users about the deprecation of PAC if (root["inboundConfig"].toObject()["pacConfig"].toObject()["enablePAC"].toBool(false)) { QvMessageBoxWarn( nullptr, QObject::tr("Deprecated"), QObject::tr("PAC is now deprecated and is not encouraged to be used anymore.") + NEWLINE + QObject::tr("It will be removed or be provided as a plugin in the future.") + NEWLINE + NEWLINE + QObject::tr("PAC will still work currently, but please switch to the V2Ray built-in routing as soon as possible.")); } else { UPGRADELOG("It's a wise choice not to use PAC."); } break; } // Splitted Qv2ray.conf, case 11: { // Process AutoStartSettings ConnectionGroupPair autoStartIdPair{ ConnectionId{ root["autoStartId"].toString() }, NullGroupId }; // Process connection entries. // { // Moved root["connections"] into separated file: $QV2RAY_CONFIG_PATH/connections.json QDir connectionsDir(QV2RAY_CONNECTIONS_DIR); if (!connectionsDir.exists()) { connectionsDir.mkpath(QV2RAY_CONNECTIONS_DIR); } const auto connectionsArray = root["connections"].toObject().keys(); QJsonObject newConnectionsArray; /// /// Connection.json /// { /// "connections" : [ /// {ID1, connectionObject 1}, /// {ID2, connectionObject 2}, /// {ID3, connectionObject 3}, /// {ID4, connectionObject 4}, /// ] /// } /// for (const auto &connectionVal : connectionsArray) { // Config file migrations: // Connection Object: // importDate --> creationDate // lastUpdatedDate --> now // auto connection = root["connections"].toObject()[connectionVal].toObject(); connection["creationDate"] = connection.take("importDate"); connection["lastUpdatedDate"] = (qint64) system_clock::to_time_t(system_clock::now()); UPGRADELOG("Migrating connection: " + connectionVal + " -- " + connection["displayName"].toString()); newConnectionsArray[connectionVal] = connection; } QJsonObject ConnectionJsonObject; root["connections"] = QJsonArray::fromStringList(connectionsArray); // // Store Connection.json StringToFile(JsonToString(newConnectionsArray), QV2RAY_CONFIG_DIR + "connections.json"); } // Merged groups and subscriptions. $QV2RAY_GROUPS_PATH + groupId.json { // Susbcription Object // Doesn't exist anymore, convert into normal group Object. // QMap<QString, QJsonObject> ConnectionsCache; QJsonObject allGroupsObject; const auto subscriptionKeys = root["subscriptions"].toObject().keys(); for (const auto &key : subscriptionKeys) { auto aSubscription = root["subscriptions"].toObject()[key].toObject(); QJsonObject subscriptionSettings; subscriptionSettings["address"] = aSubscription.take("address"); subscriptionSettings["updateInterval"] = aSubscription.take("updateInterval"); aSubscription["lastUpdatedDate"] = (qint64) system_clock::to_time_t(system_clock::now()); aSubscription["creationDate"] = (qint64) system_clock::to_time_t(system_clock::now()); aSubscription["subscriptionOption"] = subscriptionSettings; UPGRADELOG("Migrating subscription: " + key + " -- " + aSubscription["displayName"].toString()); // if (autoStartIdPair.groupId != NullGroupId && aSubscription["connections"].toArray().contains(autoStartIdPair.connectionId.toString())) { autoStartIdPair.groupId = GroupId{ key }; } // for (const auto &cid : aSubscription["connections"].toArray()) { ConnectionsCache[cid.toString()] = JsonFromString( StringFromFile(QV2RAY_CONFIG_DIR + "subscriptions/" + key + "/" + cid.toString() + QV2RAY_CONFIG_FILE_EXTENSION)); } // allGroupsObject[key] = aSubscription; } // root.remove("subscriptions"); // const auto groupKeys = root["groups"].toObject().keys(); for (const auto &key : groupKeys) { // Group Object // connections ---> ConnectionID // idSubscription ---> if the group is a subscription // subscriptionSettings ---> Originally SubscriptionObject // creationDate ---> Now // lastUpdateDate ---> Now auto aGroup = root["groups"].toObject()[key].toObject(); aGroup["lastUpdatedDate"] = (qint64) system_clock::to_time_t(system_clock::now()); aGroup["creationDate"] = (qint64) system_clock::to_time_t(system_clock::now()); UPGRADELOG("Migrating group: " + key + " -- " + aGroup["displayName"].toString()); // if (autoStartIdPair.groupId != NullGroupId && aGroup["connections"].toArray().contains(autoStartIdPair.connectionId.toString())) { autoStartIdPair.groupId = GroupId{ key }; } for (const auto &cid : aGroup["connections"].toArray()) { ConnectionsCache[cid.toString()] = JsonFromString( StringFromFile(QV2RAY_CONFIG_DIR + "connections/" + key + "/" + cid.toString() + QV2RAY_CONFIG_FILE_EXTENSION)); } // allGroupsObject[key] = aGroup; } // StringToFile(JsonToString(allGroupsObject), QV2RAY_CONFIG_DIR + "groups.json"); // root.remove("groups"); // UPGRADELOG("Removing unused directory"); QDir(QV2RAY_CONFIG_DIR + "subscriptions/").removeRecursively(); QDir(QV2RAY_CONFIG_DIR + "connections/").removeRecursively(); // QDir().mkpath(QV2RAY_CONFIG_DIR + "connections/"); // // // FileSystem Migrations // Move all files in GROUPS / SUBSCRIPTION subfolders into CONNECTIONS. // Only Store (connections.json in CONFIG_PATH) and ($groupID.json in GROUP_PATH) for (const auto &cid : ConnectionsCache.keys()) { StringToFile(JsonToString(ConnectionsCache[cid]), QV2RAY_CONFIG_DIR + "connections/" + cid + QV2RAY_CONFIG_FILE_EXTENSION); } // } // // Main Object // Drop recentConnections since it's ill-formed and not supported yet. // convert autoStartId into ConnectionGroupPair / instead of QString // Remove subscriptions item. root.remove("recentConnections"); root["autoStartId"] = autoStartIdPair.toJson(); // 1 here means FIXED root["autoStartBehavior"] = 1; // Moved apiConfig into kernelConfig auto kernelConfig = root["kernelConfig"].toObject(); kernelConfig["enableAPI"] = root["apiConfig"].toObject()["enableAPI"]; kernelConfig["statsPort"] = root["apiConfig"].toObject()["statsPort"]; root["kernelConfig"] = kernelConfig; UPGRADELOG("Finished upgrading config file for Qv2ray Group Routing update."); break; } case 12: { auto inboundConfig = root["inboundConfig"].toObject(); // QJsonObject socksSettings; QJsonObject httpSettings; QJsonObject tProxySettings; QJsonObject systemProxySettings; systemProxySettings["setSystemProxy"] = inboundConfig["setSystemProxy"]; // socksSettings["port"] = inboundConfig["socks_port"]; socksSettings["useAuth"] = inboundConfig["socks_useAuth"]; socksSettings["enableUDP"] = inboundConfig["socksUDP"]; socksSettings["localIP"] = inboundConfig["socksLocalIP"]; socksSettings["account"] = inboundConfig["socksAccount"]; socksSettings["sniffing"] = inboundConfig["socksSniffing"]; // httpSettings["port"] = inboundConfig["http_port"]; httpSettings["useAuth"] = inboundConfig["http_useAuth"]; httpSettings["account"] = inboundConfig["httpAccount"]; httpSettings["sniffing"] = inboundConfig["httpSniffing"]; // tProxySettings["tProxyIP"] = inboundConfig["tproxy_ip"]; tProxySettings["port"] = inboundConfig["tproxy_port"]; tProxySettings["hasTCP"] = inboundConfig["tproxy_use_tcp"]; tProxySettings["hasUDP"] = inboundConfig["tproxy_use_udp"]; tProxySettings["followRedirect"] = inboundConfig["tproxy_followRedirect"]; tProxySettings["mode"] = inboundConfig["tproxy_mode"]; tProxySettings["dnsIntercept"] = inboundConfig["dnsIntercept"]; // inboundConfig["systemProxySettings"] = systemProxySettings; inboundConfig["socksSettings"] = socksSettings; inboundConfig["httpSettings"] = httpSettings; inboundConfig["tProxySettings"] = tProxySettings; // root["inboundConfig"] = inboundConfig; break; } case 13: { const auto dnsList = QJsonIO::GetValue(root, "connectionConfig", "dnsList").toArray(); auto connectionConfig = root["connectionConfig"].toObject(); QJsonObject defaultRouteConfig; defaultRouteConfig["forwardProxyConfig"] = connectionConfig.take("forwardProxyConfig"); defaultRouteConfig["routeConfig"] = connectionConfig.take("routeConfig"); for (auto i = 0; i < dnsList.count(); i++) { QJsonIO::SetValue(defaultRouteConfig, dnsList[i], "dnsConfig", "servers", i, "address"); QJsonIO::SetValue(defaultRouteConfig, false, "dnsConfig", "servers", i, "QV2RAY_DNS_IS_COMPLEX_DNS"); } root["defaultRouteConfig"] = defaultRouteConfig; break; } default: { // // Due to technical issue, we cannot maintain all of those upgrade processes anymore. Check // https://github.com/Qv2ray/Qv2ray/issues/353#issuecomment-586117507 // for more information, see commit 2f716a9a443b71ddb96aaab081de73c0095cb637 // QvMessageBoxWarn(nullptr, QObject::tr("Configuration Upgrade Failed"), QObject::tr("Unsupported config version number: ") + QSTRN(fromVersion) + NEWLINE + NEWLINE + QObject::tr("Please upgrade firstly up to Qv2ray v2.0/v2.1 and try again.")); LOG("The configuration version of your old Qv2ray installation is out-of-date and that" " version is not supported anymore, please try to update to an intermediate version of Qv2ray first."); qApp->exit(1); } } root["config_version"] = root["config_version"].toInt() + 1; return root; } // Exported function QJsonObject UpgradeSettingsVersion(int fromVersion, int toVersion, const QJsonObject &original) { auto root = original; LOG("Migrating config from version ", fromVersion, "to", toVersion); for (int i = fromVersion; i < toVersion; i++) { root = UpgradeConfig_Inc(i, root); } return root; } } // namespace Qv2ray
22,354
C++
.cpp
419
34.821002
147
0.507807
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,129
V2RayKernelInteractions.cpp
Qv2ray_Qv2ray/src/core/kernel/V2RayKernelInteractions.cpp
#include "V2RayKernelInteractions.hpp" #include "APIBackend.hpp" #include "core/connection/ConnectionIO.hpp" #include "utils/QvHelpers.hpp" #include <QProcess> #define QV2RAY_GENERATED_FILE_PATH (QV2RAY_GENERATED_DIR + "config.gen.json") #define QV_MODULE_NAME "V2RayInteraction" #ifdef QV2RAY_USE_V5_CORE #define V2RAY_CORE_VERSION_ARGV "version" #define V2RAY_CORE_CONFIG_ARGV "run", "-config" #else #define V2RAY_CORE_VERSION_ARGV "--version" #define V2RAY_CORE_CONFIG_ARGV "--config" #endif namespace Qv2ray::core::kernel { #if QV2RAY_FEATURE(kernel_check_permission) std::pair<bool, std::optional<QString>> V2RayKernelInstance::CheckAndSetCoreExecutableState(const QString &vCorePath) { #ifdef Q_OS_UNIX // For Linux/macOS users: if they cannot execute the core, // then we shall grant the permission to execute it. QFile coreFile(vCorePath); if (!coreFile.permissions().testFlag(QFileDevice::ExeUser)) { #if QV2RAY_FEATURE(kernel_set_permission) DEBUG("Core file not executable. Trying to enable."); const auto result = coreFile.setPermissions(coreFile.permissions().setFlag(QFileDevice::ExeUser)); if (!result) { DEBUG("Failed to enable executable permission."); const auto message = tr("Core file is lacking executable permission for the current user.") + tr("Qv2ray tried to set, but failed because permission denied."); return { false, message }; } else { DEBUG("Core executable permission set."); } #endif LOG("Core file not executable."); return { false, tr("Core file not executable.") }; } else { DEBUG("Core file is executable."); } return { true, std::nullopt }; #else // For Windows and other users: just skip this check. DEBUG("Skipped check and set core executable state."); return { true, tr("Check is skipped") }; #endif } #endif std::pair<bool, std::optional<QString>> V2RayKernelInstance::ValidateKernel(const QString &corePath, const QString &assetsPath) { QFile coreFile(corePath); if (!coreFile.exists()) return { false, tr("V2Ray core executable not found.") }; // Use open() here to prevent `executing` a folder, which may have the // same name as the V2Ray core. if (!coreFile.open(QFile::ReadOnly)) return { false, tr("V2Ray core file cannot be opened, please ensure there's a file instead of a folder.") }; coreFile.close(); #if QV2RAY_FEATURE(kernel_check_abi) // Get Core ABI. const auto [abi, err] = kernel::abi::deduceKernelABI(corePath); if (err) { LOG("Core ABI deduction failed: " + *err); return { false, *err }; } LOG("Core ABI: " + kernel::abi::abiToString(*abi)); // Get Compiled ABI auto compiledABI = kernel::abi::COMPILED_ABI_TYPE; LOG("Host ABI: " + kernel::abi::abiToString(compiledABI)); // Check ABI Compatibility. switch (kernel::abi::checkCompatibility(compiledABI, *abi)) { case kernel::abi::ABI_NOPE: { LOG("Host is incompatible with core"); const auto msg = tr("V2Ray core is incompatible with your platform.\r\n" "Expected core ABI is %1, but got actual %2.\r\n" "Maybe you have downloaded the wrong core?") .arg(kernel::abi::abiToString(compiledABI), kernel::abi::abiToString(*abi)); return { false, msg }; } case kernel::abi::ABI_MAYBE: { LOG("WARNING: Host maybe incompatible with core"); break; } case kernel::abi::ABI_PERFECT: { LOG("Host is compatible with core"); break; } } #endif #if QV2RAY_FEATURE(kernel_check_permission) // Check executable permissions. const auto [isExecutableOk, strExecutableErr] = CheckAndSetCoreExecutableState(corePath); if (!isExecutableOk) return { false, strExecutableErr.value_or("") }; #endif // // Check file existance. // From: https://www.v2fly.org/chapter_02/env.html#asset-location bool hasGeoIP = FileExistsIn(QDir(assetsPath), "geoip.dat"); bool hasGeoSite = FileExistsIn(QDir(assetsPath), "geosite.dat"); if (!hasGeoIP && !hasGeoSite) return { false, tr("V2Ray assets path is not valid.") }; if (!hasGeoIP) return { false, tr("No geoip.dat in assets path.") }; if (!hasGeoSite) return { false, tr("No geosite.dat in assets path.") }; // Check if V2Ray core returns a version number correctly. QProcess proc; #ifdef Q_OS_WIN32 // nativeArguments are required for Windows platform, without a // reason... proc.setProcessChannelMode(QProcess::MergedChannels); proc.setProgram(corePath); proc.setNativeArguments(V2RAY_CORE_VERSION_ARGV); proc.start(); #else proc.start(corePath, { V2RAY_CORE_VERSION_ARGV }); #endif proc.waitForStarted(); proc.waitForFinished(); auto exitCode = proc.exitCode(); if (exitCode != 0) return { false, tr("V2Ray core failed with an exit code: ") + QSTRN(exitCode) }; const auto output = proc.readAllStandardOutput(); LOG("V2Ray output: " + SplitLines(output).join(";")); if (SplitLines(output).isEmpty()) return { false, tr("V2Ray core returns empty string.") }; return { true, SplitLines(output).at(0) }; } std::optional<QString> V2RayKernelInstance::ValidateConfig(const QString &path) { const auto kernelPath = GlobalConfig.kernelConfig.KernelPath(); const auto assetsPath = GlobalConfig.kernelConfig.AssetsPath(); if (const auto &[result, msg] = ValidateKernel(kernelPath, assetsPath); result) { DEBUG("V2Ray version: " + *msg); // Append assets location env. auto env = QProcessEnvironment::systemEnvironment(); env.insert("v2ray.location.asset", assetsPath); env.insert("XRAY_LOCATION_ASSET", assetsPath); // QProcess process; process.setProcessEnvironment(env); DEBUG("Starting V2Ray core with test options"); #ifdef QV2RAY_USE_V5_CORE process.start(kernelPath, { "test", "-c", path }, QIODevice::ReadWrite | QIODevice::Text); #else process.start(kernelPath, { "-test", "-config", path }, QIODevice::ReadWrite | QIODevice::Text); #endif process.waitForFinished(); if (process.exitCode() != 0) { QString output = QString(process.readAllStandardOutput()); QvMessageBoxWarn(nullptr, tr("Configuration Error"), output.mid(output.indexOf("anti-censorship.") + 17)); return std::nullopt; } DEBUG("Config file check passed."); return std::nullopt; } else { return msg; } } V2RayKernelInstance::V2RayKernelInstance(QObject *parent) : QObject(parent) { vProcess = new QProcess(); connect(vProcess, &QProcess::readyReadStandardOutput, this, [&]() { emit OnProcessOutputReadyRead(vProcess->readAllStandardOutput().trimmed()); }); connect(vProcess, &QProcess::stateChanged, [&](QProcess::ProcessState state) { DEBUG("V2Ray kernel process status changed: " + QVariant::fromValue(state).toString()); // If V2Ray crashed AFTER we start it. if (kernelStarted && state == QProcess::NotRunning) { LOG("V2Ray kernel crashed."); StopConnection(); emit OnProcessErrored("V2Ray kernel crashed."); } }); apiWorker = new APIWorker(); qRegisterMetaType<StatisticsType>(); qRegisterMetaType<QMap<StatisticsType, QvStatsSpeed>>(); connect(apiWorker, &APIWorker::onAPIDataReady, this, &V2RayKernelInstance::OnNewStatsDataArrived); kernelStarted = false; } std::optional<QString> V2RayKernelInstance::StartConnection(const CONFIGROOT &root) { if (kernelStarted) { LOG("Status is invalid, expect STOPPED when calling StartConnection"); return tr("Invalid V2Ray Instance Status."); } const auto json = JsonToString(root); StringToFile(json, QV2RAY_GENERATED_FILE_PATH); // auto filePath = QV2RAY_GENERATED_FILE_PATH; if (const auto &result = ValidateConfig(filePath); result) { kernelStarted = false; return tr("V2Ray kernel failed to start: ") + *result; } auto env = QProcessEnvironment::systemEnvironment(); env.insert("v2ray.location.asset", GlobalConfig.kernelConfig.AssetsPath()); env.insert("XRAY_LOCATION_ASSET", GlobalConfig.kernelConfig.AssetsPath()); vProcess->setProcessEnvironment(env); vProcess->start(GlobalConfig.kernelConfig.KernelPath(), { V2RAY_CORE_CONFIG_ARGV, filePath }, QIODevice::ReadWrite | QIODevice::Text); vProcess->waitForStarted(); kernelStarted = true; QMap<bool, QMap<QString, QString>> tagProtocolMap; for (const auto isOutbound : { GlobalConfig.uiConfig.graphConfig.useOutboundStats, false }) { for (const auto &item : root[isOutbound ? "outbounds" : "inbounds"].toArray()) { const auto tag = item.toObject()["tag"].toString(""); if (tag == API_TAG_INBOUND) continue; if (tag.isEmpty()) { LOG("Ignored inbound with empty tag."); continue; } tagProtocolMap[isOutbound][tag] = item.toObject()["protocol"].toString(); } } apiEnabled = false; if (QvCoreApplication->StartupArguments.noAPI) { LOG("API has been disabled by the command line arguments"); } else if (!GlobalConfig.kernelConfig.enableAPI) { LOG("API has been disabled by the global config option"); } else if (tagProtocolMap.isEmpty()) { LOG("RARE: API is disabled since no inbound tags configured. This is usually caused by a bad complex config."); } else { DEBUG("Starting API"); apiWorker->StartAPI(tagProtocolMap); apiEnabled = true; } return std::nullopt; } void V2RayKernelInstance::StopConnection() { if (apiEnabled) { apiWorker->StopAPI(); apiEnabled = false; } // Set this to false BEFORE close the Process, since we need this flag // to capture the real kernel CRASH kernelStarted = false; vProcess->close(); // Block until V2Ray core exits // Should we use -1 instead of waiting for 30secs? vProcess->waitForFinished(); } V2RayKernelInstance::~V2RayKernelInstance() { if (kernelStarted) { StopConnection(); } delete apiWorker; delete vProcess; } } // namespace Qv2ray::core::kernel
11,745
C++
.cpp
282
31.588652
142
0.59951
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,130
APIBackend.cpp
Qv2ray_Qv2ray/src/core/kernel/APIBackend.cpp
#include "APIBackend.hpp" #include "v2ray_api.pb.h" using namespace v2ray::core::app::stats::command; using grpc::Channel; using grpc::ClientContext; using grpc::Status; #define QV_MODULE_NAME "gRPCBackend" namespace Qv2ray::core::kernel { constexpr auto Qv2ray_GRPC_ERROR_RETCODE = -1; static QvAPIDataTypeConfig DefaultInboundAPIConfig{ { API_INBOUND, { "dokodemo-door", "http", "socks" } } }; static QvAPIDataTypeConfig DefaultOutboundAPIConfig{ { API_OUTBOUND_PROXY, { "dns", "http", "mtproto", "shadowsocks", "socks", "vmess", "vless", "trojan" } }, { API_OUTBOUND_DIRECT, { "freedom" } }, { API_OUTBOUND_BLACKHOLE, { "blackhole" } } }; APIWorker::APIWorker() { workThread = new QThread(); this->moveToThread(workThread); DEBUG("API Worker initialised."); connect(workThread, &QThread::started, this, &APIWorker::process); connect(workThread, &QThread::finished, [] { LOG("API thread stopped"); }); started = true; workThread->start(); } void APIWorker::StartAPI(const QMap<bool, QMap<QString, QString>> &tagProtocolPair) { // Config API tagProtocolConfig.clear(); for (const auto &key : tagProtocolPair.keys()) { const auto config = key ? DefaultOutboundAPIConfig : DefaultInboundAPIConfig; for (const auto &[tag, protocol] : tagProtocolPair[key].toStdMap()) { for (const auto &[type, protocols] : config) { if (protocols.contains(protocol)) tagProtocolConfig[tag] = { protocol, type }; } } } running = true; } void APIWorker::StopAPI() { running = false; } // --- DESTRUCTOR --- APIWorker::~APIWorker() { StopAPI(); // Set started signal to false and wait for API thread to stop. started = false; workThread->wait(); delete workThread; } // API Core Operations // Start processing data. void APIWorker::process() { DEBUG("API Worker started."); while (started) { QThread::msleep(1000); bool dialed = false; int apiFailCounter = 0; while (running) { if (!dialed) { const auto channelAddress = "127.0.0.1:" + QString::number(GlobalConfig.kernelConfig.statsPort); LOG("gRPC Version: " + QString::fromStdString(grpc::Version())); grpc_channel = grpc::CreateChannel(channelAddress.toStdString(), grpc::InsecureChannelCredentials()); v2ray::core::app::stats::command::StatsService service; stats_service_stub = service.NewStub(grpc_channel); dialed = true; } if (apiFailCounter == QV2RAY_API_CALL_FAILEDCHECK_THRESHOLD) { LOG("API call failure threshold reached, cancelling further API aclls."); emit OnAPIErrored(tr("Failed to get statistics data, please check if V2Ray is running properly")); apiFailCounter++; QThread::msleep(1000); continue; } else if (apiFailCounter > QV2RAY_API_CALL_FAILEDCHECK_THRESHOLD) { // Ignored future requests. QThread::msleep(1000); continue; } QMap<StatisticsType, QvStatsSpeed> statsResult; bool hasError = false; for (const auto &[tag, config] : tagProtocolConfig) { const QString prefix = config.type == API_INBOUND ? "inbound" : "outbound"; const auto value_up = CallStatsAPIByName(prefix % ">>>" % tag % ">>>traffic>>>uplink"); const auto value_down = CallStatsAPIByName(prefix % ">>>" % tag % ">>>traffic>>>downlink"); hasError = hasError || value_up == Qv2ray_GRPC_ERROR_RETCODE || value_down == Qv2ray_GRPC_ERROR_RETCODE; statsResult[config.type].first += std::max(value_up, 0LL); statsResult[config.type].second += std::max(value_down, 0LL); } apiFailCounter = hasError ? apiFailCounter + 1 : 0; // Changed: Removed isrunning check here emit onAPIDataReady(statsResult); QThread::msleep(1000); } // end while running } // end while started workThread->exit(); } qint64 APIWorker::CallStatsAPIByName(const QString &name) { ClientContext context; GetStatsRequest request; GetStatsResponse response; request.set_name(name.toStdString()); request.set_reset(true); const auto status = stats_service_stub->GetStats(&context, request, &response); if (!status.ok()) { LOG("API call returns: " + QSTRN(status.error_code()) + " (" + QString::fromStdString(status.error_message()) + ")"); return Qv2ray_GRPC_ERROR_RETCODE; } else { return response.stat().value(); } } } // namespace Qv2ray::core::kernel
5,548
C++
.cpp
129
30.325581
142
0.543756
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,131
QvKernelABIChecker.cpp
Qv2ray_Qv2ray/src/core/kernel/QvKernelABIChecker.cpp
#include "QvKernelABIChecker.hpp" #include <iostream> #if QV2RAY_FEATURE(kernel_check_abi) namespace Qv2ray::core::kernel::abi { QvKernelABICompatibility checkCompatibility(QvKernelABIType hostType, QvKernelABIType targetType) { #ifndef QV2RAY_TRUSTED_ABI switch (hostType) { case ABI_WIN32: case ABI_MACH_O: case ABI_ELF_AARCH64: case ABI_ELF_ARM: case ABI_ELF_X86: return targetType == hostType ? ABI_PERFECT : ABI_NOPE; case ABI_ELF_X86_64: return targetType == hostType ? ABI_PERFECT : targetType == ABI_ELF_X86 ? ABI_MAYBE : ABI_NOPE; case ABI_ELF_OTHER: return targetType == hostType ? ABI_PERFECT : ABI_MAYBE; case ABI_TRUSTED: return ABI_PERFECT; default: return ABI_MAYBE; } #else return ABI_PERFECT; #endif } std::pair<std::optional<QvKernelABIType>, std::optional<QString>> deduceKernelABI(const QString &pathCoreExecutable) { #ifdef QV2RAY_TRUSTED_ABI return { QvKernelABIType::ABI_TRUSTED, std::nullopt }; #else QFile file(pathCoreExecutable); if (!file.exists()) return { std::nullopt, QObject::tr("core executable file %1 does not exist").arg(pathCoreExecutable) }; if (!file.open(QIODevice::ReadOnly)) return { std::nullopt, QObject::tr("cannot open core executable file %1 in read-only mode").arg(pathCoreExecutable) }; if (file.atEnd()) return { std::nullopt, QObject::tr("core executable file %1 is an empty file").arg(pathCoreExecutable) }; const QByteArray arr = file.read(0x100); if (arr.length() < 0x100) return { std::nullopt, QObject::tr("core executable file %1 is too short to be executed").arg(pathCoreExecutable) }; if (quint32 elfMagicMaybe; QDataStream(arr) >> elfMagicMaybe, 0x7F454C46u == elfMagicMaybe) { quint16 elfInstruction; if (QDataStream stream(arr); stream.skipRawData(0x12), stream >> elfInstruction, elfInstruction == 0x3E00u) return { QvKernelABIType::ABI_ELF_X86_64, std::nullopt }; else if (elfInstruction == 0x0300u) return { QvKernelABIType::ABI_ELF_X86, std::nullopt }; else if (elfInstruction == 0xB700u) return { QvKernelABIType::ABI_ELF_AARCH64, std::nullopt }; else if (elfInstruction == 0x2800u) return { QvKernelABIType::ABI_ELF_ARM, std::nullopt }; else return { QvKernelABIType::ABI_ELF_OTHER, std::nullopt }; } else if (quint16 dosMagicMaybe; QDataStream(arr) >> dosMagicMaybe, dosMagicMaybe == 0x4D5Au) return { QvKernelABIType::ABI_WIN32, std::nullopt }; else if (quint32 machOMagicMaybe; QDataStream(arr) >> machOMagicMaybe, machOMagicMaybe == 0xCFFAEDFEu) return { QvKernelABIType::ABI_MACH_O, std::nullopt }; else return { std::nullopt, QObject::tr("cannot deduce the type of core executable file %1").arg(pathCoreExecutable) }; #endif } QString abiToString(QvKernelABIType abi) { switch (abi) { case ABI_WIN32: return QObject::tr("Windows PE executable"); case ABI_MACH_O: return QObject::tr("macOS Mach-O executable"); case ABI_ELF_X86: return QObject::tr("ELF x86 executable"); case ABI_ELF_X86_64: return QObject::tr("ELF amd64 executable"); case ABI_ELF_AARCH64: return QObject::tr("ELF arm64 executable"); case ABI_ELF_ARM: return QObject::tr("ELF arm executable"); case ABI_ELF_OTHER: return QObject::tr("other ELF executable"); case ABI_TRUSTED: return QObject::tr("trusted abi"); default: return QObject::tr("unknown abi"); } } } // namespace Qv2ray::core::kernel::abi #endif
3,907
C++
.cpp
78
40.653846
130
0.639696
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,132
QvProxyConfigurator.cpp
Qv2ray_Qv2ray/src/components/proxy/QvProxyConfigurator.cpp
#include "QvProxyConfigurator.hpp" #include "base/Qv2rayBase.hpp" #include "components/plugins/QvPluginHost.hpp" #include "utils/QvHelpers.hpp" #ifdef Q_OS_WIN // #include <Windows.h> // #include <WinInet.h> #include <ras.h> #include <raserror.h> #include <vector> #endif #define QV_MODULE_NAME "SystemProxy" namespace Qv2ray::components::proxy { using ProcessArgument = QPair<QString, QStringList>; #ifdef Q_OS_MACOS QStringList macOSgetNetworkServices() { QProcess p; p.setProgram("/usr/sbin/networksetup"); p.setArguments(QStringList{ "-listallnetworkservices" }); p.start(); p.waitForStarted(); p.waitForFinished(); LOG(p.errorString()); auto str = p.readAllStandardOutput(); auto lines = SplitLines(str); QStringList result; // Start from 1 since first line is unneeded. for (auto i = 1; i < lines.count(); i++) { // * means disabled. if (!lines[i].contains("*")) { result << lines[i]; } } LOG("Found " + QSTRN(result.size()) + " network services: " + result.join(";")); return result; } #endif #ifdef Q_OS_WIN #define NO_CONST(expr) const_cast<wchar_t *>(expr) // static auto DEFAULT_CONNECTION_NAME = // NO_CONST(L"DefaultConnectionSettings"); /// /// INTERNAL FUNCTION bool __QueryProxyOptions() { INTERNET_PER_CONN_OPTION_LIST List; INTERNET_PER_CONN_OPTION Option[5]; // unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); Option[0].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL; Option[1].dwOption = INTERNET_PER_CONN_AUTODISCOVERY_FLAGS; Option[2].dwOption = INTERNET_PER_CONN_FLAGS; Option[3].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; Option[4].dwOption = INTERNET_PER_CONN_PROXY_SERVER; // List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); List.pszConnection = nullptr; // NO_CONST(DEFAULT_CONNECTION_NAME); List.dwOptionCount = 5; List.dwOptionError = 0; List.pOptions = Option; if (!InternetQueryOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) { LOG("InternetQueryOption failed, GLE=" + QSTRN(GetLastError())); } LOG("System default proxy info:"); if (Option[0].Value.pszValue != nullptr) { LOG(QString::fromWCharArray(Option[0].Value.pszValue)); } if ((Option[2].Value.dwValue & PROXY_TYPE_AUTO_PROXY_URL) == PROXY_TYPE_AUTO_PROXY_URL) { LOG("PROXY_TYPE_AUTO_PROXY_URL"); } if ((Option[2].Value.dwValue & PROXY_TYPE_AUTO_DETECT) == PROXY_TYPE_AUTO_DETECT) { LOG("PROXY_TYPE_AUTO_DETECT"); } if ((Option[2].Value.dwValue & PROXY_TYPE_DIRECT) == PROXY_TYPE_DIRECT) { LOG("PROXY_TYPE_DIRECT"); } if ((Option[2].Value.dwValue & PROXY_TYPE_PROXY) == PROXY_TYPE_PROXY) { LOG("PROXY_TYPE_PROXY"); } if (!InternetQueryOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) { LOG("InternetQueryOption failed,GLE=" + QSTRN(GetLastError())); } if (Option[4].Value.pszValue != nullptr) { LOG(QString::fromStdWString(Option[4].Value.pszValue)); } INTERNET_VERSION_INFO Version; nSize = sizeof(INTERNET_VERSION_INFO); InternetQueryOption(nullptr, INTERNET_OPTION_VERSION, &Version, &nSize); if (Option[0].Value.pszValue != nullptr) { GlobalFree(Option[0].Value.pszValue); } if (Option[3].Value.pszValue != nullptr) { GlobalFree(Option[3].Value.pszValue); } if (Option[4].Value.pszValue != nullptr) { GlobalFree(Option[4].Value.pszValue); } return false; } bool __SetProxyOptions(LPWSTR proxy_full_addr, bool isPAC) { INTERNET_PER_CONN_OPTION_LIST list; DWORD dwBufSize = sizeof(list); // Fill the list structure. list.dwSize = sizeof(list); // NULL == LAN, otherwise connectoid name. list.pszConnection = nullptr; if (nullptr == proxy_full_addr) { LOG("Clearing system proxy"); // list.dwOptionCount = 1; list.pOptions = new INTERNET_PER_CONN_OPTION[1]; // Ensure that the memory was allocated. if (nullptr == list.pOptions) { // Return if the memory wasn't allocated. return false; } // Set flags. list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS; list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT; } else if (isPAC) { LOG("Setting system proxy for PAC"); // list.dwOptionCount = 2; list.pOptions = new INTERNET_PER_CONN_OPTION[2]; if (nullptr == list.pOptions) { return false; } // Set flags. list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS; list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT | PROXY_TYPE_AUTO_PROXY_URL; // Set proxy name. list.pOptions[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL; list.pOptions[1].Value.pszValue = proxy_full_addr; } else { LOG("Setting system proxy for Global Proxy"); // list.dwOptionCount = 2; list.pOptions = new INTERNET_PER_CONN_OPTION[2]; if (nullptr == list.pOptions) { return false; } // Set flags. list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS; list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT | PROXY_TYPE_PROXY; // Set proxy name. list.pOptions[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER; list.pOptions[1].Value.pszValue = proxy_full_addr; // Set proxy override. // list.pOptions[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; // auto localhost = L"localhost"; // list.pOptions[2].Value.pszValue = NO_CONST(localhost); } // Set proxy for LAN. if (!InternetSetOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, dwBufSize)) { LOG("InternetSetOption failed for LAN, GLE=" + QSTRN(GetLastError())); } RASENTRYNAME entry; entry.dwSize = sizeof(entry); std::vector<RASENTRYNAME> entries; DWORD size = sizeof(entry), count; LPRASENTRYNAME entryAddr = &entry; auto ret = RasEnumEntries(nullptr, nullptr, entryAddr, &size, &count); if (ERROR_BUFFER_TOO_SMALL == ret) { entries.resize(count); entries[0].dwSize = sizeof(RASENTRYNAME); entryAddr = entries.data(); ret = RasEnumEntries(nullptr, nullptr, entryAddr, &size, &count); } if (ERROR_SUCCESS != ret) { LOG("Failed to list entry names"); return false; } // Set proxy for each connectoid. for (DWORD i = 0; i < count; ++i) { list.pszConnection = entryAddr[i].szEntryName; if (!InternetSetOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, dwBufSize)) { LOG("InternetSetOption failed for connectoid " + QString::fromWCharArray(list.pszConnection) + ", GLE=" + QSTRN(GetLastError())); } } delete[] list.pOptions; InternetSetOption(nullptr, INTERNET_OPTION_SETTINGS_CHANGED, nullptr, 0); InternetSetOption(nullptr, INTERNET_OPTION_REFRESH, nullptr, 0); return true; } #endif void SetSystemProxy(const QString &address, int httpPort, int socksPort) { LOG("Setting up System Proxy"); bool hasHTTP = (httpPort > 0 && httpPort < 65536); bool hasSOCKS = (socksPort > 0 && socksPort < 65536); #ifdef Q_OS_WIN if (!hasHTTP) { LOG("Nothing?"); return; } else { LOG("Qv2ray will set system proxy to use HTTP"); } #else if (!hasHTTP && !hasSOCKS) { LOG("Nothing?"); return; } if (hasHTTP) { LOG("Qv2ray will set system proxy to use HTTP"); } if (hasSOCKS) { LOG("Qv2ray will set system proxy to use SOCKS"); } #endif #ifdef Q_OS_WIN QString __a; const QHostAddress ha(address); const auto type = ha.protocol(); if (type == QAbstractSocket::IPv6Protocol) { // many software do not recognize IPv6 proxy server string though const auto str = ha.toString(); // RFC5952 __a = "[" + str + "]:" + QSTRN(httpPort); } else { __a = address + ":" + QSTRN(httpPort); } LOG("Windows proxy string: " + __a); auto proxyStrW = new WCHAR[__a.length() + 1]; wcscpy(proxyStrW, __a.toStdWString().c_str()); // __QueryProxyOptions(); if (!__SetProxyOptions(proxyStrW, false)) { LOG("Failed to set proxy."); } __QueryProxyOptions(); #elif defined(Q_OS_LINUX) QList<ProcessArgument> actions; actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy", "mode", "manual" } }; // bool isKDE = qEnvironmentVariable("XDG_SESSION_DESKTOP") == "KDE" || qEnvironmentVariable("XDG_SESSION_DESKTOP") == "plasma"; const auto configPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation); // // Configure HTTP Proxies for HTTP, FTP and HTTPS if (hasHTTP) { // iterate over protocols... for (const auto &protocol : QStringList{ "http", "ftp", "https" }) { // for GNOME: { actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy." + protocol, "host", address } }; actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy." + protocol, "port", QSTRN(httpPort) } }; } // for KDE: if (isKDE) { actions << ProcessArgument{ "kwriteconfig5", { "--file", configPath + "/kioslaverc", // "--group", "Proxy Settings", // "--key", protocol + "Proxy", // "http://" + address + " " + QSTRN(httpPort) } }; } } } // Configure SOCKS5 Proxies if (hasSOCKS) { // for GNOME: { actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy.socks", "host", address } }; actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy.socks", "port", QSTRN(socksPort) } }; // for KDE: if (isKDE) { actions << ProcessArgument{ "kwriteconfig5", { "--file", configPath + "/kioslaverc", // "--group", "Proxy Settings", // "--key", "socksProxy", // "socks://" + address + " " + QSTRN(socksPort) } }; } } } // Setting Proxy Mode to Manual { // for GNOME: { actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy", "mode", "manual" } }; } // for KDE: if (isKDE) { actions << ProcessArgument{ "kwriteconfig5", { "--file", configPath + "/kioslaverc", // "--group", "Proxy Settings", // "--key", "ProxyType", "1" } }; } } // Notify kioslaves to reload system proxy configuration. if (isKDE) { actions << ProcessArgument{ "dbus-send", { "--type=signal", "/KIO/Scheduler", // "org.kde.KIO.Scheduler.reparseSlaveConfiguration", // "string:''" } }; } // Execute them all! // // note: do not use std::all_of / any_of / none_of, // because those are short-circuit and cannot guarantee atomicity. QList<bool> results; for (const auto &action : actions) { // execute and get the code const auto returnCode = QProcess::execute(action.first, action.second); // print out the commands and result codes DEBUG(QString("[%1] Program: %2, Args: %3").arg(returnCode).arg(action.first).arg(action.second.join(";"))); // give the code back results << (returnCode == QProcess::NormalExit); } if (results.count(true) != actions.size()) { LOG("Something wrong when setting proxies."); } #else for (const auto &service : macOSgetNetworkServices()) { LOG("Setting proxy for interface: " + service); if (hasHTTP) { QProcess::execute("/usr/sbin/networksetup", { "-setwebproxystate", service, "on" }); QProcess::execute("/usr/sbin/networksetup", { "-setsecurewebproxystate", service, "on" }); QProcess::execute("/usr/sbin/networksetup", { "-setwebproxy", service, address, QSTRN(httpPort) }); QProcess::execute("/usr/sbin/networksetup", { "-setsecurewebproxy", service, address, QSTRN(httpPort) }); } if (hasSOCKS) { QProcess::execute("/usr/sbin/networksetup", { "-setsocksfirewallproxystate", service, "on" }); QProcess::execute("/usr/sbin/networksetup", { "-setsocksfirewallproxy", service, address, QSTRN(socksPort) }); } } #endif // // Trigger plugin events QMap<Events::SystemProxy::SystemProxyType, int> portSettings; if (hasHTTP) portSettings.insert(Events::SystemProxy::SystemProxyType::SystemProxy_HTTP, httpPort); if (hasSOCKS) portSettings.insert(Events::SystemProxy::SystemProxyType::SystemProxy_SOCKS, socksPort); PluginHost->SendEvent({ portSettings, Events::SystemProxy::SystemProxyStateType::SetProxy }); } void ClearSystemProxy() { LOG("Clearing System Proxy"); #ifdef Q_OS_WIN if (!__SetProxyOptions(nullptr, false)) { LOG("Failed to clear proxy."); } #elif defined(Q_OS_LINUX) QList<ProcessArgument> actions; const bool isKDE = qEnvironmentVariable("XDG_SESSION_DESKTOP") == "KDE" || qEnvironmentVariable("XDG_SESSION_DESKTOP") == "plasma"; const auto configRoot = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation); // Setting System Proxy Mode to: None { // for GNOME: { actions << ProcessArgument{ "gsettings", { "set", "org.gnome.system.proxy", "mode", "none" } }; } // for KDE: if (isKDE) { actions << ProcessArgument{ "kwriteconfig5", { "--file", configRoot + "/kioslaverc", // "--group", "Proxy Settings", // "--key", "ProxyType", "0" } }; } } // Notify kioslaves to reload system proxy configuration. if (isKDE) { actions << ProcessArgument{ "dbus-send", { "--type=signal", "/KIO/Scheduler", // "org.kde.KIO.Scheduler.reparseSlaveConfiguration", // "string:''" } }; } // Execute the Actions for (const auto &action : actions) { // execute and get the code const auto returnCode = QProcess::execute(action.first, action.second); // print out the commands and result codes DEBUG(QString("[%1] Program: %2, Args: %3").arg(returnCode).arg(action.first).arg(action.second.join(";"))); } #else for (const auto &service : macOSgetNetworkServices()) { LOG("Clearing proxy for interface: " + service); QProcess::execute("/usr/sbin/networksetup", { "-setautoproxystate", service, "off" }); QProcess::execute("/usr/sbin/networksetup", { "-setwebproxystate", service, "off" }); QProcess::execute("/usr/sbin/networksetup", { "-setsecurewebproxystate", service, "off" }); QProcess::execute("/usr/sbin/networksetup", { "-setsocksfirewallproxystate", service, "off" }); } #endif // // Trigger plugin events PluginHost->SendEvent(Events::SystemProxy::EventObject{ {}, Events::SystemProxy::SystemProxyStateType::ClearProxy }); } } // namespace Qv2ray::components::proxy
17,981
C++
.cpp
443
28.740406
145
0.530347
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,133
RealPing.cpp
Qv2ray_Qv2ray/src/components/latency/RealPing.cpp
#include "RealPing.hpp" #include <chrono> #include <memory> #include <uvw.hpp> #define QV_MODULE_NAME "RealPingWorker" struct RealPingContext { std::shared_ptr<uvw::PollHandle> handle; curl_socket_t sockfd; RealPingContext(curl_socket_t sockfd, uvw::Loop &loop) : handle{ loop.resource<uvw::PollHandle>(uvw::OSSocketHandle{ sockfd }) }, sockfd{ sockfd } { } }; struct RealPingGlobalInfo { std::shared_ptr<Qv2ray::components::latency::realping::RealPing> _preserve_life_time; CURLM *multiHandle; std::shared_ptr<uvw::TimerHandle> timer; int *successCountPtr; LatencyTestResult *latencyResultPtr; }; static void check_multi_info(CURLM *curl_handle, int *success_num, LatencyTestResult *latencyTestResultPtr, RealPingGlobalInfo *info) { CURLMsg *message; int pending; CURL *easy_handle; while ((message = curl_multi_info_read(curl_handle, &pending))) { switch (message->msg) { case CURLMSG_DONE: /* Do not use message data after calling curl_multi_remove_handle() and curl_easy_cleanup(). As per curl_multi_info_read() docs: "WARNING: The data the returned pointer points to will not survive calling curl_multi_cleanup, curl_multi_remove_handle or curl_easy_cleanup." */ easy_handle = message->easy_handle; if (message->data.result == CURLE_OK) { success_num[0] += 1; auto ms = info->_preserve_life_time->getHandleTime(easy_handle); latencyTestResultPtr->avg += ms; latencyTestResultPtr->best = std::min(latencyTestResultPtr->best, ms); latencyTestResultPtr->worst = std::max(latencyTestResultPtr->worst, ms); } else latencyTestResultPtr->failedCount += 1; curl_multi_remove_handle(curl_handle, easy_handle); curl_easy_cleanup(easy_handle); break; default: break; } } } static int start_timeout(CURLM *, long timeout_ms, void *userp) { auto globalInfo = static_cast<RealPingGlobalInfo *>(userp); if (timeout_ms < 0) { globalInfo->timer->stop(); } else { if (timeout_ms == 0) timeout_ms = 1; /* 0 means directly call socket_action, but we'll do it in a bit */ globalInfo->timer->start(uvw::TimerHandle::Time{ timeout_ms }, uvw::TimerHandle::Time{ 0 }); } return 0; } static int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) { auto pRealPingGlobalInfo = static_cast<RealPingGlobalInfo *>(userp); RealPingContext *curl_context; uvw::Flags<uvw::PollHandle::Event> events{}; switch (action) { case CURL_POLL_IN: case CURL_POLL_OUT: curl_context = socketp ? (RealPingContext *) socketp : new RealPingContext{ s, pRealPingGlobalInfo->timer->loop() }; if (!socketp) curl_multi_assign(pRealPingGlobalInfo->multiHandle, s, (void *) curl_context); if (action == CURL_POLL_IN) events = events | uvw::Flags<uvw::PollHandle::Event>::from<uvw::PollHandle::Event::READABLE>(); if (action == CURL_POLL_OUT) events = events | uvw::Flags<uvw::PollHandle::Event>::from<uvw::PollHandle::Event::WRITABLE>(); curl_context->handle->on<uvw::ErrorEvent>([sockfd = curl_context->sockfd, pRealPingGlobalInfo](uvw::ErrorEvent &, uvw::PollHandle &) { pRealPingGlobalInfo->timer->stop(); int running_handles; auto flags = CURL_CSELECT_ERR; curl_multi_socket_action(pRealPingGlobalInfo->multiHandle, sockfd, flags, &running_handles); check_multi_info(pRealPingGlobalInfo->multiHandle, pRealPingGlobalInfo->successCountPtr, pRealPingGlobalInfo->latencyResultPtr, pRealPingGlobalInfo); pRealPingGlobalInfo->_preserve_life_time->notifyTestHost(); }); curl_context->handle->on<uvw::PollEvent>([sockfd = curl_context->sockfd, pRealPingGlobalInfo](uvw::PollEvent &e, uvw::PollHandle &) { pRealPingGlobalInfo->timer->stop(); int running_handles; int flags = 0; if (e.flags & uvw::Flags<uvw::PollHandle::Event>{ uvw::PollHandle::Event::READABLE }) flags |= CURL_CSELECT_IN; if (e.flags & uvw::Flags<uvw::PollHandle::Event>{ uvw::PollHandle::Event::WRITABLE }) flags |= CURL_CSELECT_OUT; curl_multi_socket_action(pRealPingGlobalInfo->multiHandle, sockfd, flags, &running_handles); check_multi_info(pRealPingGlobalInfo->multiHandle, pRealPingGlobalInfo->successCountPtr, pRealPingGlobalInfo->latencyResultPtr, pRealPingGlobalInfo); pRealPingGlobalInfo->_preserve_life_time->notifyTestHost(); }); pRealPingGlobalInfo->_preserve_life_time->recordHanleTime(easy); curl_context->handle->start(events); break; case CURL_POLL_REMOVE: if (socketp) { curl_context = static_cast<RealPingContext *>(socketp); curl_context->handle->stop(); curl_context->handle->close(); delete curl_context; curl_multi_assign(pRealPingGlobalInfo->multiHandle, s, nullptr); } break; default: break; } return 0; } static size_t noop_cb(void *, size_t size, size_t nmemb, void *) { return size * nmemb; } namespace { bool isIPv6Any(in6_addr &addr) { return memcmp(reinterpret_cast<char *>(&addr), reinterpret_cast<char *>(const_cast<in6_addr *>(&in6addr_any)), sizeof(addr)) == 0; } bool isIPv4Any(in_addr &addr) { return addr.s_addr == INADDR_ANY; } } // namespace namespace Qv2ray::components::latency::realping { RealPing::RealPing(std::shared_ptr<uvw::Loop> loopin, LatencyTestRequest &req, LatencyTestHost *testHost) : req(std::move(req)), testHost(testHost), loop(std::move(loopin)), timeout(loop->resource<uvw::TimerHandle>()) { } std::string RealPing::getProxyAddress() { struct sockaddr_storage addr { }; const auto &ip = GlobalConfig.inboundConfig.listenip.toStdString(); bool is_addr_any = false; bool is_ipv4 = (uv_ip4_addr(ip.c_str(), 0, reinterpret_cast<sockaddr_in *>(&addr)) == 0); QString proxy_ip; if (!is_ipv4) { uv_ip6_addr(ip.c_str(), 0, reinterpret_cast<sockaddr_in6 *>(&addr)); is_addr_any = isIPv6Any(reinterpret_cast<sockaddr_in6 &>(addr).sin6_addr); if (!is_addr_any) proxy_ip = "[" + GlobalConfig.inboundConfig.listenip + "]"; else proxy_ip = "[::1]"; } else { is_addr_any = isIPv4Any(reinterpret_cast<sockaddr_in &>(addr).sin_addr); if (!is_addr_any) proxy_ip = GlobalConfig.inboundConfig.listenip; else proxy_ip = "127.0.0.1"; } QString protocolWithUsrPwd; int port; if (GlobalConfig.inboundConfig.useHTTP) { protocolWithUsrPwd = "http://"; if (GlobalConfig.inboundConfig.httpSettings.useAuth) protocolWithUsrPwd += GlobalConfig.inboundConfig.httpSettings.account.user + ":" + GlobalConfig.inboundConfig.httpSettings.account.pass + "@"; port = GlobalConfig.inboundConfig.httpSettings.port; } else { protocolWithUsrPwd = "socks5://"; if (GlobalConfig.inboundConfig.socksSettings.useAuth) protocolWithUsrPwd += GlobalConfig.inboundConfig.socksSettings.account.user + ":" + GlobalConfig.inboundConfig.socksSettings.account.pass + "@"; port = GlobalConfig.inboundConfig.socksSettings.port; } return (protocolWithUsrPwd + proxy_ip + ":" + QSTRN(port)).toStdString(); } void RealPing::start() { if (!GlobalConfig.inboundConfig.useSocks && !GlobalConfig.inboundConfig.useHTTP) { data.avg = LATENCY_TEST_VALUE_ERROR; testHost->OnLatencyTestCompleted(req.id, data); return; } auto request_name = GlobalConfig.networkConfig.latencyRealPingTestURL.toStdString(); data.totalCount = 0; data.failedCount = 0; data.worst = 0; data.avg = 0; auto local_proxy_address = getProxyAddress(); auto curlMultiHandle = curl_multi_init(); auto globalInfo = std::make_shared<RealPingGlobalInfo>( RealPingGlobalInfo{ shared_from_this(), curlMultiHandle, timeout->shared_from_this(), &successCount, &data }); timeout->once<uvw::CloseEvent>([globalInfo, curlMultiHandle](auto &, auto &h) { curl_multi_cleanup(curlMultiHandle); h.clear(); }); timeout->on<uvw::TimerEvent>([globalInfo, curlMultiHandle, suc_cnt_ptr = &successCount, fail_cnt_ptr = &data, this](auto &, auto &) { int running_handles; curl_multi_socket_action(curlMultiHandle, CURL_SOCKET_TIMEOUT, 0, &running_handles); check_multi_info(curlMultiHandle, suc_cnt_ptr, fail_cnt_ptr, globalInfo.get()); notifyTestHost(); }); curl_multi_setopt(curlMultiHandle, CURLMOPT_SOCKETFUNCTION, handle_socket); curl_multi_setopt(curlMultiHandle, CURLMOPT_SOCKETDATA, globalInfo.get()); curl_multi_setopt(curlMultiHandle, CURLMOPT_TIMERDATA, globalInfo.get()); curl_multi_setopt(curlMultiHandle, CURLMOPT_TIMERFUNCTION, start_timeout); for (int i = 0; i < req.totalCount; ++i) { auto handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_URL, request_name.c_str()); curl_easy_setopt(handle, CURLOPT_PROXY, local_proxy_address.c_str()); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, noop_cb); /* complete within 5 seconds */ curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 5L); curl_easy_setopt(handle, CURLOPT_TIMEOUT, 5L); curl_multi_add_handle(curlMultiHandle, handle); } } void RealPing::notifyTestHost() { if (data.failedCount + successCount == req.totalCount) { if (data.failedCount == req.totalCount) data.avg = LATENCY_TEST_VALUE_ERROR; else data.errorMessage.clear(), data.avg = data.avg / successCount; testHost->OnLatencyTestCompleted(req.id, data); timeout->close(); } } RealPing::~RealPing() { LOG("Realping done!"); } long RealPing::getHandleTime(CURL *h) { if (reqStartTime.find(h) == reqStartTime.end()) return 0; return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - reqStartTime[h]).count(); } void RealPing::recordHanleTime(CURL *h) { reqStartTime.emplace(h, std::chrono::system_clock::now()); } } // namespace Qv2ray::components::latency::realping
11,525
C++
.cpp
262
33.835878
150
0.607625
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,134
LatencyTestThread.cpp
Qv2ray_Qv2ray/src/components/latency/LatencyTestThread.cpp
#include "LatencyTestThread.hpp" #include "RealPing.hpp" #include "TCPing.hpp" #include "core/CoreUtils.hpp" #ifdef Q_OS_UNIX #include "unix/ICMPPing.hpp" #else #include "win/ICMPPing.hpp" #endif #include "uvw.hpp" namespace Qv2ray::components::latency { LatencyTestThread::LatencyTestThread(QObject *parent) : QThread(parent) { } void LatencyTestThread::pushRequest(const ConnectionId &id, int totalTestCount, Qv2rayLatencyTestingMethod method) { if (isStop) return; std::unique_lock<std::mutex> lockGuard{ m }; const auto &[protocol, host, port] = GetConnectionInfo(id); requests.emplace_back(LatencyTestRequest{ id, host, port, totalTestCount, method }); } void LatencyTestThread::run() { loop = uvw::Loop::create(); stopTimer = loop->resource<uvw::TimerHandle>(); stopTimer->on<uvw::TimerEvent>([this](auto &, auto &handle) { if (isStop) { if (!requests.empty()) requests.clear(); int timer_count = 0; uv_walk( loop->raw(), [](uv_handle_t *handle, void *arg) { int &counter = *static_cast<int *>(arg); if (uv_is_closing(handle) == 0) counter++; }, &timer_count); if (timer_count == 1) // only current timer { handle.stop(); handle.close(); loop->clear(); loop->close(); loop->stop(); } } else { if (requests.empty()) return; std::unique_lock<std::mutex> lockGuard{ m }; auto parent = qobject_cast<LatencyTestHost *>(this->parent()); for (auto &req : requests) { switch (req.method) { case ICMPING: { auto ptr = std::make_shared<icmping::ICMPPing>(loop, req, parent); ptr->start(); } break; case TCPING: default: { auto ptr = std::make_shared<tcping::TCPing>(loop, req, parent); ptr->start(); break; } case REALPING: { auto ptr = std::make_shared<realping::RealPing>(loop, req, parent); ptr->start(); break; } } } requests.clear(); } }); stopTimer->start(uvw::TimerHandle::Time{ 500 }, uvw::TimerHandle::Time{ 500 }); loop->run(); } void LatencyTestThread::pushRequest(const QList<ConnectionId> &ids, int totalTestCount, Qv2rayLatencyTestingMethod method) { if (isStop) return; std::unique_lock<std::mutex> lockGuard{ m }; for (const auto &id : ids) { const auto &[protocol, host, port] = GetConnectionInfo(id); requests.emplace_back(LatencyTestRequest{ id, host, port, totalTestCount, method }); } } } // namespace Qv2ray::components::latency
3,593
C++
.cpp
99
21.69697
126
0.456995
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,135
TCPing.cpp
Qv2ray_Qv2ray/src/components/latency/TCPing.cpp
#include "TCPing.hpp" #include "uvw.hpp" #define QV_MODULE_NAME "TCPingWorker" namespace Qv2ray::components::latency::tcping { constexpr int conn_timeout_sec = 5; int getSocket(int af, int socktype, int proto) { uv_os_sock_t fd; #ifndef INVALID_SOCKET #define INVALID_SOCKET -1 #endif if ((fd = socket(af, socktype, proto)) == INVALID_SOCKET) { return 0; } // Set TCP connection timeout per-socket level. // See [https://github.com/libuv/help/issues/54] for details. #if defined(_WIN32) && !defined(__SYMBIAN32__) #ifndef TCP_MAXRT #define TCP_MAXRT 5 #endif setsockopt(fd, IPPROTO_TCP, TCP_MAXRT, (char *) &conn_timeout_sec, sizeof(conn_timeout_sec)); #elif defined(__APPLE__) // (billhoo) MacOS uses TCP_CONNECTIONTIMEOUT to do so. setsockopt(fd, IPPROTO_TCP, TCP_CONNECTIONTIMEOUT, (char *) &conn_timeout_sec, sizeof(conn_timeout_sec)); #else // Linux like systems uint32_t conn_timeout_ms = conn_timeout_sec * 1000; setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, (char *) &conn_timeout_ms, sizeof(conn_timeout_ms)); #endif return (int) fd; } void TCPing::start() { data.totalCount = 0; data.failedCount = 0; data.worst = 0; data.avg = 0; af = isAddr(); if (af == -1) { getAddrHandle = loop->resource<uvw::GetAddrInfoReq>(); sprintf(digitBuffer, "%d", req.port); } async_DNS_lookup(0, 0); } TCPing::~TCPing() { } void TCPing::notifyTestHost() { if (data.failedCount + successCount == req.totalCount) { if (data.failedCount == req.totalCount) data.avg = LATENCY_TEST_VALUE_ERROR; else data.errorMessage.clear(), data.avg = data.avg / successCount; testHost->OnLatencyTestCompleted(req.id, data); } } void TCPing::ping() { for (; data.totalCount < req.totalCount; ++data.totalCount) { auto tcpClient = loop->resource<uvw::TCPHandle>(); tcpClient->open(getSocket(af, SOCK_STREAM, IPPROTO_TCP)); tcpClient->once<uvw::ErrorEvent>([ptr = shared_from_this(), this](const uvw::ErrorEvent &e, uvw::TCPHandle &h) { LOG("error connecting to host: " + req.host + ":" + QSTRN(req.port) + " " + e.what()); data.failedCount += 1; data.errorMessage = e.what(); notifyTestHost(); h.clear(); h.close(); }); tcpClient->once<uvw::ConnectEvent>([ptr = shared_from_this(), start = system_clock::now(), this](auto &, auto &h) { ++successCount; system_clock::time_point end = system_clock::now(); auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); long ms = milliseconds.count(); data.avg += ms; data.worst = std::max(data.worst, ms); data.best = std::min(data.best, ms); notifyTestHost(); h.clear(); h.close(); }); tcpClient->connect(reinterpret_cast<const sockaddr &>(storage)); } } } // namespace Qv2ray::components::latency::tcping
3,381
C++
.cpp
90
28.455556
127
0.566819
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,136
LatencyTest.cpp
Qv2ray_Qv2ray/src/components/latency/LatencyTest.cpp
#include "LatencyTest.hpp" #include "LatencyTestThread.hpp" #include "core/handler/ConfigHandler.hpp" namespace Qv2ray::components::latency { LatencyTestHost::LatencyTestHost(const int defaultCount, QObject *parent) : QObject(parent) { qRegisterMetaType<ConnectionId>(); qRegisterMetaType<LatencyTestResult>(); totalTestCount = defaultCount; latencyThread = new LatencyTestThread(this); latencyThread->start(); } LatencyTestHost::~LatencyTestHost() { latencyThread->stopLatencyTest(); latencyThread->wait(); } void LatencyTestHost::StopAllLatencyTest() { latencyThread->stopLatencyTest(); latencyThread->wait(); latencyThread->start(); } void LatencyTestHost::TestLatency(const ConnectionId &id, Qv2rayLatencyTestingMethod method) { latencyThread->pushRequest(id, totalTestCount, method); } void LatencyTestHost::TestLatency(const QList<ConnectionId> &ids, Qv2rayLatencyTestingMethod method) { latencyThread->pushRequest(ids, totalTestCount, method); } } // namespace Qv2ray::components::latency
1,158
C++
.cpp
33
29.181818
104
0.716711
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,137
ICMPPing.cpp
Qv2ray_Qv2ray/src/components/latency/unix/ICMPPing.cpp
/* Author: Maciek Muszkowski * * This is a simple ping implementation for Linux. * It will work ONLY on kernels 3.x+ and you need * to set allowed groups in /proc/sys/net/ipv4/ping_group_range */ #include "ICMPPing.hpp" #include <QObject> #ifdef Q_OS_UNIX #include <netinet/in.h> #include <netinet/ip.h> //macos need that #include <netinet/ip_icmp.h> #include <sys/socket.h> #include <sys/time.h> #include <unistd.h> #ifdef Q_OS_MAC #define SOL_IP 0 #endif namespace Qv2ray::components::latency::icmping { /// 1s complementary checksum uint16_t ping_checksum(const char *buf, size_t size) { size_t i; uint64_t sum = 0; for (i = 0; i < size; i += 2) { sum += *(uint16_t *) buf; buf += 2; } if (size - i > 0) { sum += *(uint8_t *) buf; } while ((sum >> 16) != 0) { sum = (sum & 0xffff) + (sum >> 16); } return (uint16_t) ~sum; } void ICMPPing::deinit() { if (socketId >= 0) { close(socketId); socketId = -1; } } void ICMPPing::start(int ttl) { if (((socketId = socket(PF_INET, SOCK_DGRAM, IPPROTO_ICMP)) < 0)) { data.errorMessage = "EPING_SOCK: " + QObject::tr("Socket creation failed"); data.avg = LATENCY_TEST_VALUE_ERROR; testHost->OnLatencyTestCompleted(req.id, data); return; } // set TTL if (setsockopt(socketId, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) != 0) { data.errorMessage = "EPING_TTL: " + QObject::tr("Failed to setup TTL value"); data.avg = LATENCY_TEST_VALUE_ERROR; testHost->OnLatencyTestCompleted(req.id, data); return; } data.totalCount = req.totalCount; data.failedCount = 0; data.worst = 0; data.avg = 0; if (isAddr() == -1) { getAddrHandle = loop->resource<uvw::GetAddrInfoReq>(); sprintf(digitBuffer, "%d", req.port); } async_DNS_lookup(0, 0); } bool ICMPPing::notifyTestHost() { if (data.failedCount + successCount == data.totalCount) { if (data.failedCount == data.totalCount) data.avg = LATENCY_TEST_VALUE_ERROR; else data.errorMessage.clear(), data.avg = data.avg / successCount; testHost->OnLatencyTestCompleted(req.id, data); if (timeoutTimer) { timeoutTimer->stop(); timeoutTimer->clear(); timeoutTimer->close(); } if (pollHandle) { if (!pollHandle->closing()) pollHandle->stop(); pollHandle->clear(); pollHandle->close(); } return true; } return false; } void ICMPPing::ping() { timeoutTimer = loop->resource<uvw::TimerHandle>(); uvw::OSSocketHandle osSocketHandle{ socketId }; pollHandle = loop->resource<uvw::PollHandle>(osSocketHandle); timeoutTimer->once<uvw::TimerEvent>([this, ptr = std::weak_ptr<ICMPPing>{ shared_from_this() }](auto &, uvw::TimerHandle &h) { if (ptr.expired()) return; else { auto p = ptr.lock(); pollHandle->clear(); if (!pollHandle->closing()) pollHandle->stop(); pollHandle->close(); successCount = 0; data.failedCount = data.totalCount = req.totalCount; notifyTestHost(); } }); timeoutTimer->start(uvw::TimerHandle::Time{ 10000 }, uvw::TimerHandle::Time{ 0 }); auto pollEvent = uvw::Flags<uvw::PollHandle::Event>::from<uvw::PollHandle::Event::READABLE>(); pollHandle->on<uvw::PollEvent>([this, ptr = shared_from_this()](uvw::PollEvent &, uvw::PollHandle &h) { timeval end; sockaddr_in addr; socklen_t slen = sizeof(sockaddr_in); int rlen = 0; char buf[1024]; do { do { rlen = recvfrom(socketId, buf, 1024, 0, (struct sockaddr *) &addr, &slen); } while (rlen == -1 && errno == EINTR); // skip malformed #ifdef Q_OS_MAC if (rlen < sizeof(icmp) + 20) #else if (rlen < sizeof(icmp)) #endif continue; #ifdef Q_OS_MAC auto &resp = *reinterpret_cast<icmp *>(buf + 20); #else auto &resp = *reinterpret_cast<icmp *>(buf); #endif // skip the ones we didn't send auto cur_seq = resp.icmp_hun.ih_idseq.icd_seq; if (cur_seq >= seq) continue; switch (resp.icmp_type) { case ICMP_ECHOREPLY: gettimeofday(&end, nullptr); data.avg += 1000 * (end.tv_sec - startTimevals[cur_seq - 1].tv_sec) + (end.tv_usec - startTimevals[cur_seq - 1].tv_usec) / 1000; successCount++; notifyTestHost(); continue; case ICMP_UNREACH: data.errorMessage = "EPING_DST: " + QObject::tr("Destination unreachable"); data.failedCount++; if (notifyTestHost()) { h.clear(); h.close(); return; } continue; case ICMP_TIMXCEED: data.errorMessage = "EPING_TIME: " + QObject::tr("Timeout"); data.failedCount++; if (notifyTestHost()) { h.clear(); h.close(); return; } continue; default: data.errorMessage = "EPING_UNK: " + QObject::tr("Unknown error"); data.failedCount++; if (notifyTestHost()) { h.clear(); h.close(); return; } continue; } } while (rlen > 0); }); pollHandle->start(pollEvent); for (int i = 0; i < req.totalCount; ++i) { // prepare echo request packet icmp _icmp_request; memset(&_icmp_request, 0, sizeof(_icmp_request)); _icmp_request.icmp_type = ICMP_ECHO; _icmp_request.icmp_hun.ih_idseq.icd_id = 0; // SOCK_DGRAM & 0 => id will be set by kernel _icmp_request.icmp_hun.ih_idseq.icd_seq = seq++; _icmp_request.icmp_cksum = ping_checksum(reinterpret_cast<char *>(&_icmp_request), sizeof(_icmp_request)); int n; timeval start; gettimeofday(&start, nullptr); startTimevals.push_back(start); do { n = ::sendto(socketId, &_icmp_request, sizeof(icmp), 0, (struct sockaddr *) &storage, sizeof(struct sockaddr)); } while (n < 0 && errno == EINTR); } } ICMPPing::~ICMPPing() { deinit(); } } // namespace Qv2ray::components::latency::icmping #endif
7,998
C++
.cpp
219
22.557078
145
0.45764
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,138
ICMPPing.cpp
Qv2ray_Qv2ray/src/components/latency/win/ICMPPing.cpp
#include "ICMPPing.hpp" #ifdef Q_OS_WIN #define QV_MODULE_NAME "ICMPingWorker" typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; PVOID Pointer; } DUMMYUNIONNAME; ULONG_PTR Information; } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; typedef VOID(NTAPI *PIO_APC_ROUTINE)(IN PVOID ApcContext, IN PIO_STATUS_BLOCK IoStatusBlock, IN ULONG Reserved); #define PIO_APC_ROUTINE_DEFINED #include <WS2tcpip.h> // #include <Windows.h> // #include <iphlpapi.h> // #include <IcmpAPI.h> // #include <QString> namespace Qv2ray::components::latency::icmping { ICMPPing ::~ICMPPing() { } void ICMPPing::ping() { waitHandleTimer = loop->resource<uvw::TimerHandle>(); waitHandleTimer->on<uvw::TimerEvent>([ptr = shared_from_this(), this](auto &&, auto &&) { SleepEx(0, TRUE); if (data.failedCount + successCount == data.totalCount) { waitHandleTimer->stop(); waitHandleTimer->close(); waitHandleTimer->clear(); } }); for (; data.totalCount < req.totalCount; ++data.totalCount) { pingImpl(); } waitHandleTimer->start(uvw::TimerHandle::Time{ 500 }, uvw::TimerHandle::Time{ 500 }); } void ICMPPing::pingImpl() { constexpr WORD payload_size = 1; constexpr DWORD reply_buf_size = sizeof(ICMP_ECHO_REPLY) + payload_size + 8; struct ICMPReply { ICMPReply(std::function<void(bool, long, const QString &, HANDLE)> f) : whenIcmpFailed(std::move(f)) { hIcmpFile = IcmpCreateFile(); } unsigned char reply_buf[reply_buf_size]{}; unsigned char payload[payload_size]{ 42 }; HANDLE hIcmpFile; std::function<void(bool, long, const QString &, HANDLE)> whenIcmpFailed; ~ICMPReply() { if (hIcmpFile != INVALID_HANDLE_VALUE) IcmpCloseHandle(hIcmpFile); } }; auto icmpReply = new ICMPReply{ [this, id = req.id](bool isSuccess, long res, const QString &message, HANDLE h) { if (!isSuccess) { data.errorMessage = message; data.failedCount++; } else { data.avg += res; data.best = std::min(res, data.best); data.worst = std::max(res, data.worst); successCount++; } notifyTestHost(testHost, id); } }; if (icmpReply->hIcmpFile == INVALID_HANDLE_VALUE) { data.errorMessage = "IcmpCreateFile failed"; data.failedCount++; notifyTestHost(testHost, req.id); delete icmpReply; return; } IcmpSendEcho2( icmpReply->hIcmpFile, NULL, [](PVOID ctx, PIO_STATUS_BLOCK b, ULONG r) { static int i = 1; LOG("hit" + QSTRN(i++)); auto replyPtr = reinterpret_cast<ICMPReply *>(ctx); auto isSuccess = (NTSTATUS(b->Status)) >= 0; long res = 0; QString message; if (isSuccess) { const ICMP_ECHO_REPLY *r = (const ICMP_ECHO_REPLY *) replyPtr->reply_buf; res = r->RoundTripTime * 1000; } else { auto e = GetLastError(); DWORD buf_size = 1000; TCHAR buf[1000]; GetIpErrorString(e, buf, &buf_size); message = "IcmpSendEcho returned error (" + QString::fromStdWString(buf) + ")"; } replyPtr->whenIcmpFailed(isSuccess, res, message, replyPtr->hIcmpFile); delete replyPtr; }, icmpReply, reinterpret_cast<IPAddr &>(reinterpret_cast<sockaddr_in &>(storage).sin_addr), icmpReply->payload, payload_size, NULL, icmpReply->reply_buf, reply_buf_size, 10000); } bool ICMPPing::notifyTestHost(LatencyTestHost *testHost, const ::Qv2ray::base::ConnectionId &id) { if (data.failedCount + successCount == data.totalCount) { if (data.failedCount == data.totalCount) data.avg = LATENCY_TEST_VALUE_ERROR; else data.errorMessage.clear(), data.avg = data.avg / successCount / 1000; testHost->OnLatencyTestCompleted(id, data); return true; } return false; } void ICMPPing::start() { data.totalCount = 0; data.failedCount = 0; data.worst = 0; data.avg = 0; af = isAddr(); if (af == -1) { getAddrHandle = loop->resource<uvw::GetAddrInfoReq>(); sprintf(digitBuffer, "%d", req.port); } async_DNS_lookup(0, 0); } } // namespace Qv2ray::components::latency::icmping #endif
5,062
C++
.cpp
146
24.150685
141
0.538462
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,139
QvPluginHost.cpp
Qv2ray_Qv2ray/src/components/plugins/QvPluginHost.cpp
#include "QvPluginHost.hpp" #include "base/Qv2rayBase.hpp" #include "base/Qv2rayLog.hpp" #include "core/settings/SettingsBackend.hpp" #include "utils/QvHelpers.hpp" #include <QPluginLoader> #define QV_MODULE_NAME "PluginHost" namespace Qv2ray::components::plugins { QvPluginHost::QvPluginHost(QObject *parent) : QObject(parent) { if (!QvCoreApplication->StartupArguments.noPlugins) { if (auto dir = QDir(QV2RAY_PLUGIN_SETTINGS_DIR); !dir.exists()) { dir.mkpath(QV2RAY_PLUGIN_SETTINGS_DIR); } initializePluginHost(); } else { LOG("PluginHost initilization skipped by command line option."); } } int QvPluginHost::refreshPluginList() { clearPlugins(); LOG("Reloading plugin list"); for (const auto &pluginDirPath : QvCoreApplication->GetAssetsPaths("plugins")) { const QStringList entries = QDir(pluginDirPath).entryList(QDir::Files); for (const auto &fileName : entries) { if (!fileName.endsWith(QV2RAY_LIBRARY_SUFFIX)) { DEBUG("Skipping: " + fileName + " in: " + pluginDirPath); continue; } DEBUG("Loading plugin: " + fileName + " from: " + pluginDirPath); // QvPluginInfo info; auto pluginFullPath = QDir(pluginDirPath).absoluteFilePath(fileName); info.libraryPath = pluginFullPath; info.pluginLoader = new QPluginLoader(pluginFullPath, this); // auto meta = pluginLoader.metaData(); // You should not call "delete" on this object, it's handled by the QPluginLoader QObject *plugin = info.pluginLoader->instance(); if (plugin == nullptr) { const auto errMessage = info.pluginLoader->errorString(); LOG(errMessage); QvMessageBoxWarn(nullptr, tr("Failed to load plugin"), errMessage); continue; } info.pluginInterface = qobject_cast<Qv2rayInterface *>(plugin); if (info.pluginInterface == nullptr) { LOG("Failed to cast from QObject to Qv2rayPluginInterface"); info.pluginLoader->unload(); continue; } if (info.pluginInterface->QvPluginInterfaceVersion != QV2RAY_PLUGIN_INTERFACE_VERSION) { // The plugin was built for a not-compactable version of Qv2ray. Don't load the plugin by default. LOG(info.libraryPath + " is built with an older Interface, ignoring"); QvMessageBoxWarn(nullptr, tr("Cannot load plugin"), tr("The plugin cannot be loaded: ") + NEWLINE + info.libraryPath + NEWLINE NEWLINE + tr("This plugin was built against a different version of the Plugin Interface.") + NEWLINE + tr("Please contact the plugin provider or report the issue to Qv2ray Workgroup.")); info.pluginLoader->unload(); continue; } info.metadata = info.pluginInterface->GetMetadata(); if (plugins.contains(info.metadata.InternalName)) { LOG("Found another plugin with the same internal name: " + info.metadata.InternalName + ". Skipped"); continue; } connect(plugin, SIGNAL(PluginLog(const QString &)), this, SLOT(QvPluginLog(const QString &))); connect(plugin, SIGNAL(PluginErrorMessageBox(const QString &, const QString &)), this, SLOT(QvPluginMessageBox(const QString &, const QString &))); LOG("Loaded plugin: \"" + info.metadata.Name + "\" made by: \"" + info.metadata.Author + "\""); plugins.insert(info.metadata.InternalName, info); } } return plugins.count(); } void QvPluginHost::QvPluginLog(const QString &log) { auto _sender = sender(); if (auto _interface = qobject_cast<Qv2rayInterface *>(_sender); _interface) { LOG(_interface->GetMetadata().InternalName, log); } else { LOG("UNKNOWN CLIENT: " + log); } } void QvPluginHost::QvPluginMessageBox(const QString &title, const QString &message) { const auto _sender = sender(); const auto _interface = qobject_cast<Qv2rayInterface *>(_sender); if (_interface) QvMessageBoxWarn(nullptr, _interface->GetMetadata().Name + " - " + title, message); else QvMessageBoxWarn(nullptr, "Unknown Plugin - " + title, message); } bool QvPluginHost::GetPluginEnabled(const QString &internalName) const { return GlobalConfig.pluginConfig.pluginStates[internalName]; } void QvPluginHost::SetPluginEnabled(const QString &internalName, bool isEnabled) { LOG("Set plugin: \"" + internalName + "\" enable state: " + (isEnabled ? "true" : "false")); GlobalConfig.pluginConfig.pluginStates[internalName] = isEnabled; if (isEnabled && !plugins[internalName].isLoaded) { // Load plugin if it haven't been loaded. initializePlugin(internalName); QvMessageBoxInfo(nullptr, tr("Enabling a plugin"), tr("The plugin will become fully functional after restarting Qv2ray.")); } } void QvPluginHost::initializePluginHost() { refreshPluginList(); for (auto &plugin : plugins.keys()) { initializePlugin(plugin); } } void QvPluginHost::clearPlugins() { for (auto &&plugin : plugins) { DEBUG("Unloading: \"" + plugin.metadata.Name + "\""); plugin.pluginLoader->unload(); plugin.pluginLoader->deleteLater(); } plugins.clear(); } bool QvPluginHost::initializePlugin(const QString &internalName) { const auto &plugin = plugins[internalName]; if (plugin.isLoaded) { LOG("The plugin: \"" + internalName + "\" has already been loaded."); return true; } if (!GlobalConfig.pluginConfig.pluginStates.contains(internalName)) { // If not contained, default to enabled. GlobalConfig.pluginConfig.pluginStates[internalName] = true; } // If the plugin is disabled if (!GlobalConfig.pluginConfig.pluginStates[internalName]) { LOG("Cannot load a plugin that's been disabled."); return false; } auto conf = JsonFromString(StringFromFile(QV2RAY_PLUGIN_SETTINGS_DIR + internalName + ".conf")); plugins[internalName].pluginInterface->InitializePlugin(QV2RAY_PLUGIN_SETTINGS_DIR + internalName + "/", conf); plugins[internalName].isLoaded = true; return true; } void QvPluginHost::SavePluginSettings() const { for (const auto &name : plugins.keys()) { if (plugins[name].isLoaded) { LOG("Saving plugin settings for: \"" + name + "\""); auto &conf = plugins[name].pluginInterface->GetSettngs(); StringToFile(JsonToString(conf), QV2RAY_PLUGIN_SETTINGS_DIR + name + ".conf"); } } } QvPluginHost::~QvPluginHost() { SavePluginSettings(); clearPlugins(); } // ================== BEGIN SEND EVENTS ================== void QvPluginHost::SendEvent(const Events::ConnectionStats::EventObject &object) { for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_EVENT_HANDLER)) plugin.pluginInterface->GetEventHandler()->ProcessEvent_ConnectionStats(object); } } void QvPluginHost::SendEvent(const Events::Connectivity::EventObject &object) { for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_EVENT_HANDLER)) plugin.pluginInterface->GetEventHandler()->ProcessEvent_Connectivity(object); } } void QvPluginHost::SendEvent(const Events::ConnectionEntry::EventObject &object) { for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_EVENT_HANDLER)) plugin.pluginInterface->GetEventHandler()->ProcessEvent_ConnectionEntry(object); } } void QvPluginHost::SendEvent(const Events::SystemProxy::EventObject &object) { for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_EVENT_HANDLER)) plugin.pluginInterface->GetEventHandler()->ProcessEvent_SystemProxy(object); } } const QList<std::tuple<QString, QString, QJsonObject>> QvPluginHost::TryDeserializeShareLink(const QString &sharelink, // QString *aliasPrefix, // QString *errMessage, // QString *newGroupName, // bool &ok) const { Q_UNUSED(newGroupName) QList<std::tuple<QString, QString, QJsonObject>> data; ok = false; for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_OUTBOUND_HANDLER)) { auto serializer = plugin.pluginInterface->GetOutboundHandler(); bool thisPluginCanHandle = false; for (const auto &prefix : serializer->SupportedLinkPrefixes()) { thisPluginCanHandle = thisPluginCanHandle || sharelink.startsWith(prefix); } if (thisPluginCanHandle) { // Populate Plugin Options { auto opt = plugin.pluginLoader->instance()->property(QV2RAY_PLUGIN_INTERNAL_PROPERTY_KEY).value<Qv2rayPluginOption>(); opt[OPTION_SET_TLS_DISABLE_SYSTEM_CERTS] = GlobalConfig.advancedConfig.disableSystemRoot; plugin.pluginLoader->instance()->setProperty(QV2RAY_PLUGIN_INTERNAL_PROPERTY_KEY, QVariant::fromValue(opt)); } const auto &[protocol, outboundSettings] = serializer->DeserializeOutbound(sharelink, aliasPrefix, errMessage); if (errMessage->isEmpty()) { data << std::tuple{ *aliasPrefix, protocol, outboundSettings }; ok = true; } break; } } } return data; } const OutboundInfoObject QvPluginHost::GetOutboundInfo(const QString &protocol, const QJsonObject &o, bool &status) const { status = false; for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_OUTBOUND_HANDLER)) { auto serializer = plugin.pluginInterface->GetOutboundHandler(); if (serializer && serializer->SupportedProtocols().contains(protocol)) { auto info = serializer->GetOutboundInfo(protocol, o); status = true; return info; } } } return {}; } void QvPluginHost::SetOutboundInfo(const QString &protocol, const OutboundInfoObject &info, QJsonObject &o) const { for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_OUTBOUND_HANDLER)) { auto serializer = plugin.pluginInterface->GetOutboundHandler(); if (serializer && serializer->SupportedProtocols().contains(protocol)) { serializer->SetOutboundInfo(protocol, info, o); } } } } const QString QvPluginHost::SerializeOutbound(const QString &protocol, // const QJsonObject &out, // const QJsonObject &streamSettings, // const QString &name, // const QString &group, // bool *ok) const { *ok = false; for (const auto &plugin : plugins) { if (plugin.isLoaded && plugin.metadata.Components.contains(COMPONENT_OUTBOUND_HANDLER)) { auto serializer = plugin.pluginInterface->GetOutboundHandler(); if (serializer && serializer->SupportedProtocols().contains(protocol)) { auto link = serializer->SerializeOutbound(protocol, name, group, out, streamSettings); *ok = true; return link; } } } return ""; } const QStringList GetPluginComponentsString(const QList<PluginGuiComponentType> &types) { QStringList typesList; if (types.isEmpty()) typesList << QObject::tr("None"); for (auto type : types) { switch (type) { case GUI_COMPONENT_SETTINGS: typesList << QObject::tr("Settings Widget"); break; case GUI_COMPONENT_INBOUND_EDITOR: typesList << QObject::tr("Inbound Editor"); break; case GUI_COMPONENT_OUTBOUND_EDITOR: typesList << QObject::tr("Outbound Editor"); break; case GUI_COMPONENT_MAINWINDOW_WIDGET: typesList << QObject::tr("MainWindow Widget"); break; default: typesList << QObject::tr("Unknown type."); break; } } return typesList; } const QStringList GetPluginComponentsString(const QList<PluginComponentType> &types) { QStringList typesList; if (types.isEmpty()) typesList << QObject::tr("None"); for (auto type : types) { switch (type) { case COMPONENT_KERNEL: typesList << QObject::tr("Kernel"); break; case COMPONENT_OUTBOUND_HANDLER: typesList << QObject::tr("Outbound Handler/Parser"); break; case COMPONENT_SUBSCRIPTION_ADAPTER: typesList << QObject::tr("Subscription Adapter"); break; case COMPONENT_EVENT_HANDLER: typesList << QObject::tr("Event Handler"); break; case COMPONENT_GUI: typesList << QObject::tr("GUI Components"); break; default: typesList << QObject::tr("Unknown type."); break; } } return typesList; } } // namespace Qv2ray::components::plugins
15,691
C++
.cpp
347
31.636888
142
0.55557
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,140
UpdateChecker.cpp
Qv2ray_Qv2ray/src/components/update/UpdateChecker.cpp
#include "UpdateChecker.hpp" #include "3rdparty/libsemver/version.hpp" #include "base/Qv2rayBase.hpp" #include "core/settings/SettingsBackend.hpp" #include "utils/HTTPRequestHelper.hpp" #include "utils/QvHelpers.hpp" const inline QMap<int, QString> UpdateChannelLink // { { 0, "https://api.github.com/repos/Qv2ray/Qv2ray/releases/latest" }, // { 1, "https://api.github.com/repos/Qv2ray/Qv2ray/releases?per_page=1" } // }; #define QV_MODULE_NAME "Update" namespace Qv2ray::components { QvUpdateChecker::QvUpdateChecker(QObject *parent) : QObject(parent) { } QvUpdateChecker::~QvUpdateChecker() { } void QvUpdateChecker::CheckUpdate() { #ifndef DISABLE_AUTO_UPDATE if (QFile(QV2RAY_CONFIG_DIR + "QV2RAY_FEATURE_DISABLE_AUTO_UPDATE").exists()) return; const auto &updateChannel = GlobalConfig.updateConfig.updateChannel; LOG("Start checking update for channel ID: " + QSTRN(updateChannel)); requestHelper->AsyncHttpGet(UpdateChannelLink[updateChannel], &QvUpdateChecker::VersionUpdate); #endif } void QvUpdateChecker::VersionUpdate(const QByteArray &data) { // Version update handler. const auto doc = QJsonDocument::fromJson(data); const auto root = doc.isArray() ? doc.array().first().toObject() : doc.object(); if (root.isEmpty()) return; const auto newVersionStr = root["tag_name"].toString("v").mid(1); const auto currentVersionStr = QString(QV2RAY_VERSION_STRING); const auto ignoredVersionStr = GlobalConfig.updateConfig.ignoredVersion.isEmpty() ? "0.0.0" : GlobalConfig.updateConfig.ignoredVersion; // bool hasUpdate = false; try { const auto newVersion = semver::version::from_string(newVersionStr.toStdString()); const auto currentVersion = semver::version::from_string(currentVersionStr.toStdString()); const auto ignoredVersion = semver::version::from_string(ignoredVersionStr.toStdString()); // LOG(QString("Received update info:") + NEWLINE + // " --> Latest: " + newVersionStr + NEWLINE + // " --> Current: " + currentVersionStr + NEWLINE + // " --> Ignored: " + ignoredVersionStr); // If the version is newer than us. // And new version is newer than the ignored version. hasUpdate = (newVersion > currentVersion && newVersion > ignoredVersion); } catch (...) { LOG("Some strange exception occured, cannot check update."); } if (hasUpdate) { const auto name = root["name"].toString(""); if (name.contains("NO_RELEASE")) { LOG("Found the recent release title with NO_RELEASE tag. Ignoring"); return; } const auto link = root["html_url"].toString(""); const auto versionMessage = QString("A new version of Qv2ray has been found:" NEWLINE "v%1" NEWLINE NEWLINE "%2" NEWLINE "------------" NEWLINE "%3") .arg(newVersionStr) .arg(name) .arg(root["body"].toString()); const auto result = QvMessageBoxAsk(nullptr, tr("Qv2ray Update"), versionMessage, { Yes, No, Ignore }); if (result == Yes) { QvCoreApplication->OpenURL(link); } else if (result == Ignore) { // Set and save ingored version. GlobalConfig.updateConfig.ignoredVersion = newVersionStr; SaveGlobalSettings(); } } else { LOG("No suitable updates found on channel " + QSTRN(GlobalConfig.updateConfig.updateChannel)); } } } // namespace Qv2ray::components
3,934
C++
.cpp
92
33.065217
143
0.602504
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,142
QvGeositeReader.cpp
Qv2ray_Qv2ray/src/components/geosite/QvGeositeReader.cpp
#include "QvGeositeReader.hpp" #ifndef ANDROID #include "v2ray_geosite.pb.h" #endif #define QV_MODULE_NAME "GeositeReader" namespace Qv2ray::components::geosite { QMap<QString, QStringList> GeositeEntries; QStringList ReadGeoSiteFromFile(const QString &filepath) { if (GeositeEntries.contains(filepath)) { return GeositeEntries.value(filepath); } else { QStringList list; #ifndef ANDROID LOG("Reading geosites from: " + filepath); // GOOGLE_PROTOBUF_VERIFY_VERSION; // QFile f(filepath); bool opened = f.open(QFile::OpenModeFlag::ReadOnly); if (!opened) { LOG("File cannot be opened: " + filepath); return list; } auto content = f.readAll(); f.close(); // v2ray::core::app::router::GeoSiteList sites; sites.ParseFromArray(content.data(), content.size()); for (const auto &e : sites.entry()) { // We want to use lower string. list << QString::fromStdString(e.country_code()).toLower(); } LOG("Loaded " + QSTRN(list.count()) + " geosite entries from data file."); // Optional: Delete all global objects allocated by libprotobuf. google::protobuf::ShutdownProtobufLibrary(); #endif list.sort(); GeositeEntries[filepath] = list; return list; } } } // namespace Qv2ray::components::geosite
1,621
C++
.cpp
49
23.204082
86
0.559744
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,143
QvNTPClient.cpp
Qv2ray_Qv2ray/src/components/ntp/QvNTPClient.cpp
/* This file from part of QNtp, a library that implements NTP protocol. * * Copyright (C) 2011 Alexander Fokin <apfokin@gmail.com> * * QNtp is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * QNtp is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public * License along with QNtp. If not, see <http://www.gnu.org/licenses/>. */ #include "QvNTPClient.hpp" #if QV2RAY_FEATURE(util_has_ntp) #include <cmath> namespace Qv2ray::components::ntp { NtpTimestamp NtpTimestamp::fromDateTime(const QDateTime &dateTime) { qint64 ntpMSecs = dateTime.toMSecsSinceEpoch() - january_1_1900; quint32 seconds = ntpMSecs / 1000; quint32 fraction = 0x100000000ll * (ntpMSecs % 1000) / 1000; NtpTimestamp result; result.seconds = qToBigEndian(seconds); result.fraction = qToBigEndian(fraction); return result; } QDateTime NtpTimestamp::toDateTime(const NtpTimestamp &ntpTime) { /* Convert to local-endian. */ quint32 seconds = qFromBigEndian(ntpTime.seconds); quint32 fraction = qFromBigEndian(ntpTime.fraction); /* Convert NTP timestamp to number of milliseconds passed since Jan 1 1900. */ qint64 ntpMSecs = seconds * 1000ll + fraction * 1000ll / 0x100000000ll; /* Construct Qt date time. */ return QDateTime::fromMSecsSinceEpoch(ntpMSecs + january_1_1900); } NtpReply::NtpReply() : d(new NtpReplyPrivate()) { /* We don't use shared null because NtpReplyPrivate isn't a POD type and * allocation overhead is negligible here. */ memset(&d->packet, 0, sizeof(d->packet)); } NtpReply::NtpReply(NtpReplyPrivate *dd) : d(dd) { Q_ASSERT(dd != NULL); } NtpReply::NtpReply(const NtpReply &other) : d(other.d) { } NtpReply::~NtpReply() { } NtpReply &NtpReply::operator=(const NtpReply &other) { d = other.d; return *this; } NtpLeapIndicator NtpReply::leapIndicator() const { return static_cast<NtpLeapIndicator>(d->packet.basic.flags.leapIndicator); } quint8 NtpReply::versionNumber() const { return d->packet.basic.flags.versionNumber; } NtpMode NtpReply::mode() const { return static_cast<NtpMode>(d->packet.basic.flags.mode); } quint8 NtpReply::stratum() const { return d->packet.basic.stratum; } qreal NtpReply::pollInterval() const { return std::pow(static_cast<qreal>(2), static_cast<qreal>(d->packet.basic.poll)); } qreal NtpReply::precision() const { return std::pow(static_cast<qreal>(2), static_cast<qreal>(d->packet.basic.precision)); } QDateTime NtpReply::referenceTime() const { return NtpTimestamp::toDateTime(d->packet.basic.referenceTimestamp); } QDateTime NtpReply::originTime() const { return NtpTimestamp::toDateTime(d->packet.basic.originateTimestamp); } QDateTime NtpReply::receiveTime() const { return NtpTimestamp::toDateTime(d->packet.basic.receiveTimestamp); } QDateTime NtpReply::transmitTime() const { return NtpTimestamp::toDateTime(d->packet.basic.transmitTimestamp); } QDateTime NtpReply::destinationTime() const { return d->destinationTime; } qint64 NtpReply::roundTripDelay() const { return originTime().msecsTo(destinationTime()) - receiveTime().msecsTo(transmitTime()); } qint64 NtpReply::localClockOffset() const { return (originTime().msecsTo(receiveTime()) + destinationTime().msecsTo(transmitTime())) / 2; } bool NtpReply::isNull() const { return d->destinationTime.isNull(); } NtpClient::NtpClient(QObject *parent) : QObject(parent) { init(QHostAddress::Any, 0); } NtpClient::NtpClient(const QHostAddress &bindAddress, quint16 bindPort, QObject *parent) : QObject(parent) { init(bindAddress, bindPort); } void NtpClient::init(const QHostAddress &bindAddress, quint16 bindPort) { mSocket = new QUdpSocket(this); mSocket->bind(bindAddress, bindPort); connect(mSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); } NtpClient::~NtpClient() { return; } bool NtpClient::sendRequest(const QHostAddress &address, quint16 port) { if (mSocket->state() != QAbstractSocket::BoundState) return false; /* Initialize the NTP packet. */ NtpPacket packet; memset(&packet, 0, sizeof(packet)); packet.flags.mode = ClientMode; packet.flags.versionNumber = 4; packet.transmitTimestamp = NtpTimestamp::fromDateTime(QDateTime::currentDateTimeUtc()); /* Send it. */ if (mSocket->writeDatagram(reinterpret_cast<const char *>(&packet), sizeof(packet), address, port) < 0) return false; return true; } void NtpClient::readPendingDatagrams() { while (mSocket->hasPendingDatagrams()) { NtpFullPacket packet; memset(&packet, 0, sizeof(packet)); QHostAddress address; quint16 port; if (mSocket->readDatagram(reinterpret_cast<char *>(&packet), sizeof(packet), &address, &port) < (qint64) sizeof(NtpPacket)) continue; QDateTime now = QDateTime::currentDateTime(); /* Prepare reply. */ NtpReplyPrivate *replyPrivate = new NtpReplyPrivate(); replyPrivate->packet = packet; replyPrivate->destinationTime = now; NtpReply reply(replyPrivate); /* Notify. */ Q_EMIT replyReceived(address, port, reply); } } } // namespace Qv2ray::components::ntp #endif
6,280
C++
.cpp
173
29.491329
135
0.660508
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,144
QvPortDetector.cpp
Qv2ray_Qv2ray/src/components/port/QvPortDetector.cpp
#include "QvPortDetector.hpp" #include <QHostAddress> #include <QTcpServer> namespace Qv2ray::components::port { bool CheckTCPPortStatus(const QString &addr, int port) { QTcpServer server; QHostAddress address(addr); if (address == QHostAddress::AnyIPv4 || address == QHostAddress::AnyIPv6) { address = QHostAddress::Any; } return server.listen(address, port); } } // namespace Qv2ray::components::port
478
C++
.cpp
16
24.1875
81
0.668845
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,145
BuiltinProtocolPlugin.cpp
Qv2ray_Qv2ray/src/plugins/protocols/BuiltinProtocolPlugin.cpp
#include "BuiltinProtocolPlugin.hpp" #include "core/OutboundHandler.hpp" #include "ui/Interface.hpp" bool InternalProtocolSupportPlugin::InitializePlugin(const QString &, const QJsonObject &settings) { this->settings = settings; InternalProtocolSupportPluginInstance = this; outboundHandler = std::make_shared<BuiltinSerializer>(); guiInterface = new ProtocolGUIInterface(); return true; }
412
C++
.cpp
11
34.454545
98
0.794486
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,146
OutboundHandler.cpp
Qv2ray_Qv2ray/src/plugins/protocols/core/OutboundHandler.cpp
#include "OutboundHandler.hpp" #include "3rdparty/QJsonStruct/QJsonIO.hpp" #include <QUrl> #include <QUrlQuery> using namespace Qv2rayPlugin; const Qv2rayPlugin::OutboundInfoObject BuiltinSerializer::GetOutboundInfo(const QString &protocol, const QJsonObject &outbound) const { OutboundInfoObject obj; obj[INFO_PROTOCOL] = protocol; if (protocol == "http") { const auto http = HttpServerObject::fromJson(outbound["servers"].toArray().first()); obj[INFO_SERVER] = http.address; obj[INFO_PORT] = http.port; } else if (protocol == "socks") { const auto socks = SocksServerObject::fromJson(outbound["servers"].toArray().first()); obj[INFO_SERVER] = socks.address; obj[INFO_PORT] = socks.port; } else if (protocol == "vmess") { const auto vmess = VMessServerObject::fromJson(outbound["vnext"].toArray().first()); obj[INFO_SERVER] = vmess.address; obj[INFO_PORT] = vmess.port; } else if (protocol == "vless") { const auto vless = VLESSServerObject::fromJson(outbound["vnext"].toArray().first()); obj[INFO_SERVER] = vless.address; obj[INFO_PORT] = vless.port; } else if (protocol == "shadowsocks") { const auto ss = ShadowSocksServerObject::fromJson(outbound["servers"].toArray().first()); obj[INFO_SERVER] = ss.address; obj[INFO_PORT] = ss.port; } return obj; } const void BuiltinSerializer::SetOutboundInfo(const QString &protocol, const Qv2rayPlugin::OutboundInfoObject &info, QJsonObject &outbound) const { if ((QStringList{ "http", "socks", "shadowsocks" }).contains(protocol)) { QJsonIO::SetValue(outbound, info[INFO_SERVER].toString(), "servers", 0, "address"); QJsonIO::SetValue(outbound, info[INFO_PORT].toInt(), "servers", 0, "port"); } else if ((QStringList{ "vless", "vmess" }).contains(protocol)) { QJsonIO::SetValue(outbound, info[INFO_SERVER].toString(), "vnext", 0, "address"); QJsonIO::SetValue(outbound, info[INFO_PORT].toInt(), "vnext", 0, "port"); } } const QString BuiltinSerializer::SerializeOutbound(const QString &protocol, const QString &alias, const QString &, const QJsonObject &obj, const QJsonObject &objStream) const { if (protocol == "http" || protocol == "socks") { QUrl url; url.setScheme(protocol); url.setHost(QJsonIO::GetValue(obj, { "servers", 0, "address" }).toString()); url.setPort(QJsonIO::GetValue(obj, { "servers", 0, "port" }).toInt()); if (QJsonIO::GetValue(obj, { "servers", 0 }).toObject().contains("users")) { url.setUserName(QJsonIO::GetValue(obj, { "servers", 0, "users", 0, "user" }).toString()); url.setPassword(QJsonIO::GetValue(obj, { "servers", 0, "users", 0, "pass" }).toString()); } return url.toString(); } if (protocol == "vless") { QUrl url; url.setFragment(QUrl::toPercentEncoding(alias)); url.setScheme(protocol); url.setHost(QJsonIO::GetValue(obj, { "vnext", 0, "address" }).toString()); url.setPort(QJsonIO::GetValue(obj, { "vnext", 0, "port" }).toInt()); url.setUserName(QJsonIO::GetValue(obj, { "vnext", 0, "users", 0, "id" }).toString()); // -------- COMMON INFORMATION -------- QUrlQuery query; const auto encryption = QJsonIO::GetValue(obj, { "vnext", 0, "users", 0, "encryption" }).toString("none"); if (encryption != "none") query.addQueryItem("encryption", encryption); const auto network = QJsonIO::GetValue(objStream, "network").toString("tcp"); if (network != "tcp") query.addQueryItem("type", network); const auto security = QJsonIO::GetValue(objStream, "security").toString("none"); if (security != "none") query.addQueryItem("security", security); // -------- TRANSPORT RELATED -------- if (network == "kcp") { const auto seed = QJsonIO::GetValue(objStream, { "kcpSettings", "seed" }).toString(); if (!seed.isEmpty()) query.addQueryItem("seed", QUrl::toPercentEncoding(seed)); const auto headerType = QJsonIO::GetValue(objStream, { "kcpSettings", "header", "type" }).toString("none"); if (headerType != "none") query.addQueryItem("headerType", headerType); } else if (network == "http") { const auto path = QJsonIO::GetValue(objStream, { "httpSettings", "path" }).toString("/"); query.addQueryItem("path", QUrl::toPercentEncoding(path)); const auto hosts = QJsonIO::GetValue(objStream, { "httpSettings", "host" }).toArray(); QStringList hostList; for (const auto item : hosts) { const auto host = item.toString(); if (!host.isEmpty()) hostList << host; } query.addQueryItem("host", QUrl::toPercentEncoding(hostList.join(","))); } else if (network == "ws") { const auto path = QJsonIO::GetValue(objStream, { "wsSettings", "path" }).toString("/"); query.addQueryItem("path", QUrl::toPercentEncoding(path)); const auto host = QJsonIO::GetValue(objStream, { "wsSettings", "headers", "Host" }).toString(); query.addQueryItem("host", host); } else if (network == "quic") { const auto quicSecurity = QJsonIO::GetValue(objStream, { "quicSettings", "security" }).toString("none"); if (quicSecurity != "none") { query.addQueryItem("quicSecurity", quicSecurity); const auto key = QJsonIO::GetValue(objStream, { "quicSettings", "key" }).toString(); query.addQueryItem("key", QUrl::toPercentEncoding(key)); const auto headerType = QJsonIO::GetValue(objStream, { "quicSettings", "header", "type" }).toString("none"); if (headerType != "none") query.addQueryItem("headerType", headerType); } } else if (network == "grpc") { const auto serviceName = QJsonIO::GetValue(objStream, { "grpcSettings", "serviceName" }).toString("GunService"); if (serviceName != "GunService") query.addQueryItem("serviceName", QUrl::toPercentEncoding(serviceName)); const auto multiMode = QJsonIO::GetValue(objStream, { "grpcSettings", "multiMode" }).toBool(false); if (multiMode) query.addQueryItem("mode", "multi"); } // -------- TLS RELATED -------- const auto tlsKey = security == "xtls" ? "xtlsSettings" : "tlsSettings"; const auto sni = QJsonIO::GetValue(objStream, { tlsKey, "serverName" }).toString(); if (!sni.isEmpty()) query.addQueryItem("sni", sni); // ALPN const auto alpnArray = QJsonIO::GetValue(objStream, { tlsKey, "alpn" }).toArray(); QStringList alpnList; for (const auto v : alpnArray) { const auto alpn = v.toString(); if (!alpn.isEmpty()) alpnList << alpn; } query.addQueryItem("alpn", QUrl::toPercentEncoding(alpnList.join(","))); // -------- XTLS Flow -------- if (security == "xtls") { const auto flow = QJsonIO::GetValue(obj, "vnext", 0, "users", 0, "flow").toString(); query.addQueryItem("flow", flow); } // ======== END OF QUERY ======== url.setQuery(query); return url.toString(QUrl::FullyEncoded); } return "(Unsupported)"; } const QPair<QString, QJsonObject> BuiltinSerializer::DeserializeOutbound(const QString &link, QString *alias, QString *errorMessage) const { if (link.startsWith("http://") || link.startsWith("socks://")) { const QUrl url = link; QJsonObject root; QJsonIO::SetValue(root, url.host(), "servers", 0, "address"); QJsonIO::SetValue(root, url.port(), "servers", 0, "port"); if (!url.userName().isEmpty()) { QJsonIO::SetValue(root, url.userName(), "servers", 0, "users", 0, "user"); } if (!url.password().isEmpty()) { QJsonIO::SetValue(root, url.password(), "servers", 0, "users", 0, "pass"); } return { url.scheme(), root }; } return {}; } const QList<QString> BuiltinSerializer::SupportedLinkPrefixes() const { return { "http", "socks" }; }
8,694
C++
.cpp
193
35.917098
145
0.585093
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,149
loopback.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/loopback.cpp
#include "loopback.hpp" LoopbackSettingsEditor::LoopbackSettingsEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); } void LoopbackSettingsEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void LoopbackSettingsEditor::on_inboundTagTxt_textEdited(const QString &arg1) { loopbackSettings["inboundTag"] = arg1; }
487
C++
.cpp
18
23.666667
102
0.744635
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,150
socksout.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/socksout.cpp
#include "socksout.hpp" SocksOutboundEditor::SocksOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", true); } void SocksOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void SocksOutboundEditor::on_socks_UserNameTxt_textEdited(const QString &arg1) { if (socks.users.isEmpty()) socks.users << HTTPSOCKSUserObject{}; socks.users.front().user = arg1; } void SocksOutboundEditor::on_socks_PasswordTxt_textEdited(const QString &arg1) { if (socks.users.isEmpty()) socks.users << HTTPSOCKSUserObject{}; socks.users.front().pass = arg1; }
869
C++
.cpp
28
27.178571
96
0.725209
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,151
vmess.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/vmess.cpp
#include "vmess.hpp" #include "BuiltinProtocolPlugin.hpp" VmessOutboundEditor::VmessOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", true); } void VmessOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void VmessOutboundEditor::SetContent(const QJsonObject &content) { this->content = content; PLUGIN_EDITOR_LOADING_SCOPE({ if (content["vnext"].toArray().isEmpty()) content["vnext"] = QJsonArray{ QJsonObject{} }; vmess = VMessServerObject::fromJson(content["vnext"].toArray().first().toObject()); if (vmess.users.empty()) vmess.users.push_back({}); const auto &user = vmess.users.front(); idLineEdit->setText(user.id); alterLineEdit->setValue(user.alterId); securityCombo->setCurrentText(user.security); }) if (alterLineEdit->value() > 0) { const auto msg = tr("VMess MD5 with Non-zero AlterID has been deprecated, please use VMessAEAD."); InternalProtocolSupportPluginInstance->PluginErrorMessageBox(tr("Non AEAD VMess detected"), msg); } } void VmessOutboundEditor::on_idLineEdit_textEdited(const QString &arg1) { const static QRegularExpression regExpUUID("^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", QRegularExpression::CaseInsensitiveOption); if (!regExpUUID.match(arg1).hasMatch()) { RED(idLineEdit) } else { BLACK(idLineEdit) } if (vmess.users.isEmpty()) vmess.users << VMessServerObject::UserObject{}; vmess.users.front().id = arg1; } void VmessOutboundEditor::on_securityCombo_currentTextChanged(const QString &arg1) { if (vmess.users.isEmpty()) vmess.users << VMessServerObject::UserObject{}; vmess.users.front().security = arg1; } void VmessOutboundEditor::on_alterLineEdit_valueChanged(int arg1) { if (vmess.users.isEmpty()) vmess.users << VMessServerObject::UserObject{}; vmess.users.front().alterId = arg1; }
2,251
C++
.cpp
64
30.015625
137
0.690859
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,152
blackhole.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/blackhole.cpp
#include "blackhole.hpp" BlackholeOutboundEditor::BlackholeOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", false); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", false); } void BlackholeOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void BlackholeOutboundEditor::SetContent(const QJsonObject &_content) { this->content = _content; PLUGIN_EDITOR_LOADING_SCOPE({ if (content.contains("response") && content["response"].toObject().contains("type")) responseTypeCB->setCurrentText(content["response"].toObject()["type"].toString()); }) } void BlackholeOutboundEditor::on_responseTypeCB_currentTextChanged(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD content = QJsonObject{ { "response", QJsonObject{ { "type", arg1 } } } }; }
1,025
C++
.cpp
29
31.310345
104
0.722782
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,153
freedom.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/freedom.cpp
#include "freedom.hpp" FreedomOutboundEditor::FreedomOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); // Should freedom outbound use StreamSettings? setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", true); } void FreedomOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void FreedomOutboundEditor::on_DSCB_currentTextChanged(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD content["domainStrategy"] = arg1; } void FreedomOutboundEditor::on_redirectTxt_textEdited(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD content["redirect"] = arg1; }
824
C++
.cpp
27
27
100
0.750315
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,154
httpout.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/httpout.cpp
#include "httpout.hpp" HttpOutboundEditor::HttpOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", true); } void HttpOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void HttpOutboundEditor::on_http_UserNameTxt_textEdited(const QString &arg1) { if (http.users.isEmpty()) http.users << HTTPSOCKSUserObject{}; http.users.front().user = arg1; } void HttpOutboundEditor::on_http_PasswordTxt_textEdited(const QString &arg1) { if (http.users.isEmpty()) http.users << HTTPSOCKSUserObject{}; http.users.front().pass = arg1; }
855
C++
.cpp
28
26.678571
94
0.720535
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,155
shadowsocks.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/shadowsocks.cpp
#include "shadowsocks.hpp" ShadowsocksOutboundEditor::ShadowsocksOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", true); } void ShadowsocksOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void ShadowsocksOutboundEditor::on_ss_passwordTxt_textEdited(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD shadowsocks.password = arg1; } void ShadowsocksOutboundEditor::on_ss_encryptionMethod_currentTextChanged(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD shadowsocks.method = arg1; }
809
C++
.cpp
26
27.653846
108
0.766367
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,156
dns.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/dns.cpp
#include "dns.hpp" DnsOutboundEditor::DnsOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", false); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", false); } void DnsOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void DnsOutboundEditor::on_tcpCB_clicked() { PLUGIN_EDITOR_LOADING_GUARD content["network"] = "tcp"; } void DnsOutboundEditor::on_udpCB_clicked() { PLUGIN_EDITOR_LOADING_GUARD content["network"] = "udp"; } void DnsOutboundEditor::on_originalCB_clicked() { PLUGIN_EDITOR_LOADING_GUARD content.remove("network"); } void DnsOutboundEditor::on_addressTxt_textEdited(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD if (arg1.isEmpty()) content.remove("network"); else content["network"] = arg1; } void DnsOutboundEditor::on_portSB_valueChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD if (arg1 < 0) content.remove("port"); else content["port"] = arg1; }
1,199
C++
.cpp
47
21.723404
92
0.708297
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,157
vless.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/outbound/vless.cpp
#include "vless.hpp" #define ENSURE_USERS \ if (vless.users.isEmpty()) \ vless.users.push_back({}); VlessOutboundEditor::VlessOutboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); setProperty("QV2RAY_INTERNAL_HAS_FORWARD_PROXY", true); } void VlessOutboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void VlessOutboundEditor::on_vLessIDTxt_textEdited(const QString &arg1) { const static QRegularExpression regExpUUID("^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", QRegularExpression::CaseInsensitiveOption); if (!regExpUUID.match(arg1).hasMatch()) { RED(vLessIDTxt); } else { BLACK(vLessIDTxt); } ENSURE_USERS vless.users.front().id = arg1; } void VlessOutboundEditor::on_vLessSecurityCombo_currentTextChanged(const QString &arg1) { ENSURE_USERS vless.users.front().encryption = arg1; } void VlessOutboundEditor::on_flowCombo_currentTextChanged(const QString &arg1) { ENSURE_USERS PLUGIN_EDITOR_LOADING_GUARD vless.users.front().flow = arg1; }
1,528
C++
.cpp
44
30.659091
150
0.59174
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,158
dokodemo-door.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/inbound/dokodemo-door.cpp
#include "dokodemo-door.hpp" DokodemoDoorInboundEditor::DokodemoDoorInboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); } void DokodemoDoorInboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void DokodemoDoorInboundEditor::SetContent(const QJsonObject &content) { PLUGIN_EDITOR_LOADING_SCOPE({ this->content = content; // Dokodemo-Door dokoFollowRedirectCB->setChecked(content["followRedirect"].toBool()); dokoIPAddrTxt->setText(content["address"].toString()); dokoPortSB->setValue(content["port"].toInt()); dokoTimeoutSB->setValue(content["timeout"].toInt()); dokoTCPCB->setChecked(content["network"].toString().contains("tcp")); dokoUDPCB->setChecked(content["network"].toString().contains("udp")); }) } const QJsonObject DokodemoDoorInboundEditor::GetContent() const { return content; } void DokodemoDoorInboundEditor::on_dokoIPAddrTxt_textEdited(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD content["address"] = arg1; } void DokodemoDoorInboundEditor::on_dokoPortSB_valueChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["port"] = arg1; } #define SET_NETWORK \ bool hasTCP = dokoTCPCB->checkState() == Qt::Checked; \ bool hasUDP = dokoUDPCB->checkState() == Qt::Checked; \ QStringList list; \ if (hasTCP) \ list << "tcp"; \ if (hasUDP) \ list << "udp"; \ content["network"] = list.join(",") void DokodemoDoorInboundEditor::on_dokoTCPCB_stateChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD Q_UNUSED(arg1) SET_NETWORK; } void DokodemoDoorInboundEditor::on_dokoUDPCB_stateChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD Q_UNUSED(arg1) SET_NETWORK; } void DokodemoDoorInboundEditor::on_dokoTimeoutSB_valueChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["timeout"] = arg1; } void DokodemoDoorInboundEditor::on_dokoFollowRedirectCB_stateChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["followRedirect"] = arg1 == Qt::Checked; }
3,235
C++
.cpp
73
40.273973
150
0.501904
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,160
socksin.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/inbound/socksin.cpp
#include "socksin.hpp" #include "BuiltinProtocolPlugin.hpp" SocksInboundEditor::SocksInboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); } void SocksInboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void SocksInboundEditor::SetContent(const QJsonObject &content) { PLUGIN_EDITOR_LOADING_SCOPE({ this->content = content; // SOCKS socksAuthCombo->setCurrentText(content["auth"].toString()); socksUDPCB->setChecked(content["udp"].toBool()); socksUDPIPAddrTxt->setText(content["ip"].toString()); for (auto user : content["accounts"].toArray()) { socksAccountListBox->addItem(user.toObject()["user"].toString() + ":" + user.toObject()["pass"].toString()); } }) } void SocksInboundEditor::on_socksRemoveUserBtn_clicked() { PLUGIN_EDITOR_LOADING_GUARD if (socksAccountListBox->currentRow() != -1) { auto item = socksAccountListBox->currentItem(); auto list = content["accounts"].toArray(); for (int i = 0; i < list.count(); i++) { auto user = list[i].toObject(); auto entry = user["user"].toString() + ":" + user["pass"].toString(); if (entry == item->text().trimmed()) { list.removeAt(i); content["accounts"] = list; socksAccountListBox->takeItem(socksAccountListBox->currentRow()); return; } } } else { InternalProtocolSupportPluginInstance->PluginErrorMessageBox(tr("Removing a user"), tr("You haven't selected a user yet.")); } } void SocksInboundEditor::on_socksAddUserBtn_clicked() { PLUGIN_EDITOR_LOADING_GUARD auto user = socksAddUserTxt->text(); auto pass = socksAddPasswordTxt->text(); // auto list = content["accounts"].toArray(); for (int i = 0; i < list.count(); i++) { auto _user = list[i].toObject(); if (_user["user"].toString() == user) { InternalProtocolSupportPluginInstance->PluginErrorMessageBox(tr("Add a user"), tr("This user exists already.")); return; } } socksAddUserTxt->clear(); socksAddPasswordTxt->clear(); QJsonObject entry; entry["user"] = user; entry["pass"] = pass; list.append(entry); socksAccountListBox->addItem(user + ":" + pass); content["accounts"] = list; } void SocksInboundEditor::on_socksUDPCB_stateChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["udp"] = arg1 == Qt::Checked; } void SocksInboundEditor::on_socksUDPIPAddrTxt_textEdited(const QString &arg1) { PLUGIN_EDITOR_LOADING_GUARD content["ip"] = arg1; } void SocksInboundEditor::on_socksAuthCombo_currentIndexChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["auth"] = socksAuthCombo->itemText(arg1).toLower(); }
3,109
C++
.cpp
95
26.642105
132
0.642881
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,161
httpin.cpp
Qv2ray_Qv2ray/src/plugins/protocols/ui/inbound/httpin.cpp
#include "httpin.hpp" #include "BuiltinProtocolPlugin.hpp" HTTPInboundEditor::HTTPInboundEditor(QWidget *parent) : Qv2rayPlugin::QvPluginEditor(parent) { setupUi(this); setProperty("QV2RAY_INTERNAL_HAS_STREAMSETTINGS", true); } void HTTPInboundEditor::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void HTTPInboundEditor::SetContent(const QJsonObject &content) { PLUGIN_EDITOR_LOADING_SCOPE({ this->content = content; // HTTP httpTimeoutSpinBox->setValue(content["timeout"].toInt()); httpTransparentCB->setChecked(content["allowTransparent"].toBool()); httpAccountListBox->clear(); for (const auto &user : content["accounts"].toArray()) { httpAccountListBox->addItem(user.toObject()["user"].toString() + ":" + user.toObject()["pass"].toString()); } }) } void HTTPInboundEditor::on_httpTimeoutSpinBox_valueChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["timtout"] = arg1; } void HTTPInboundEditor::on_httpTransparentCB_stateChanged(int arg1) { PLUGIN_EDITOR_LOADING_GUARD content["allowTransparent"] = arg1 == Qt::Checked; } void HTTPInboundEditor::on_httpRemoveUserBtn_clicked() { PLUGIN_EDITOR_LOADING_GUARD if (httpAccountListBox->currentRow() < 0) { InternalProtocolSupportPluginInstance->PluginErrorMessageBox(tr("Removing a user"), tr("You haven't selected a user yet.")); return; } const auto item = httpAccountListBox->currentItem(); auto list = content["accounts"].toArray(); for (int i = 0; i < list.count(); i++) { const auto user = list[i].toObject(); const auto entry = user["user"].toString() + ":" + user["pass"].toString(); if (entry == item->text().trimmed()) { list.removeAt(i); content["accounts"] = list; httpAccountListBox->takeItem(httpAccountListBox->currentRow()); return; } } } void HTTPInboundEditor::on_httpAddUserBtn_clicked() { PLUGIN_EDITOR_LOADING_GUARD const auto user = httpAddUserTxt->text(); const auto pass = httpAddPasswordTxt->text(); // auto list = content["accounts"].toArray(); for (int i = 0; i < list.count(); i++) { const auto _user = list[i].toObject(); if (_user["user"].toString() == user) { InternalProtocolSupportPluginInstance->PluginErrorMessageBox(tr("Add a user"), tr("This user exists already.")); return; } } httpAddUserTxt->clear(); httpAddPasswordTxt->clear(); list.append(QJsonObject{ { "user", user }, { "pass", pass } }); httpAccountListBox->addItem(user + ":" + pass); content["accounts"] = list; }
2,862
C++
.cpp
84
28.404762
132
0.654375
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,162
BuiltinUtils.cpp
Qv2ray_Qv2ray/src/plugins/utils/BuiltinUtils.cpp
#include "BuiltinUtils.hpp" #include "core/EventHandler.hpp" #include "core/GUIInterface.hpp" bool InternalUtilsPlugin::InitializePlugin(const QString &, const QJsonObject &settings) { this->settings = settings; this->eventHandler = std::make_shared<EventHandler>(); this->guiInterface = new GUIInterface; return true; }
339
C++
.cpp
10
31.1
88
0.767584
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,163
EventHandler.cpp
Qv2ray_Qv2ray/src/plugins/utils/core/EventHandler.cpp
#include "EventHandler.hpp" EventHandler::EventHandler() { } QvPlugin_EventHandler(EventHandler, ConnectionStats) { Q_UNUSED(pluginEvent); } QvPlugin_EventHandler(EventHandler, SystemProxy) { Q_UNUSED(pluginEvent); } QvPlugin_EventHandler(EventHandler, Connectivity) { Q_UNUSED(pluginEvent); } QvPlugin_EventHandler(EventHandler, ConnectionEntry) { Q_UNUSED(pluginEvent); }
395
C++
.cpp
20
17.7
52
0.808108
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,165
GUIInterface.cpp
Qv2ray_Qv2ray/src/plugins/utils/core/GUIInterface.cpp
#include "GUIInterface.hpp" #include "MainWindowWidget.hpp" GUIInterface::GUIInterface() { } QList<GUIInterface::typed_plugin_editor> GUIInterface::createInboundEditors() const { return {}; } QList<GUIInterface::typed_plugin_editor> GUIInterface::createOutboundEditors() const { return {}; } std::unique_ptr<Qv2rayPlugin::QvPluginSettingsWidget> GUIInterface::createSettingsWidgets() const { return nullptr; } std::unique_ptr<Qv2rayPlugin::QvPluginMainWindowWidget> GUIInterface::createMainWindowWidget() const { return std::make_unique<MainWindowWidget>(); }
582
C++
.cpp
21
25.666667
100
0.803604
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,166
BuiltinSubscriptionAdapter.cpp
Qv2ray_Qv2ray/src/plugins/subscription-adapters/BuiltinSubscriptionAdapter.cpp
#include "BuiltinSubscriptionAdapter.hpp" #include "core/SubscriptionAdapter.hpp" bool InternalSubscriptionSupportPlugin::InitializePlugin(const QString &, const QJsonObject &settings) { this->settings = settings; subscriptionAdapter = std::make_shared<BuiltinSubscriptionAdapterInterface>(); return true; }
322
C++
.cpp
8
37.5
102
0.817308
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,167
SubscriptionAdapter.cpp
Qv2ray_Qv2ray/src/plugins/subscription-adapters/core/SubscriptionAdapter.cpp
#include "SubscriptionAdapter.hpp" #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QUrl> #include <QUrlQuery> QString SafeBase64Decode(QString string) { QByteArray ba = string.replace(QChar('-'), QChar('+')).replace(QChar('_'), QChar('/')).toUtf8(); return QByteArray::fromBase64(ba, QByteArray::Base64Option::OmitTrailingEquals); } QString SafeBase64Encode(const QString &string) { QString base64 = string.toUtf8().toBase64(); return base64.replace(QChar('+'), QChar('-')).replace(QChar('/'), QChar('_')); } // Simple Base64 Decoder SubscriptionDecoder::SubscriptionDecodeResult SimpleBase64Decoder::DecodeData(const QByteArray &data) const { auto source = QString::fromUtf8(data).trimmed(); const auto resultList = source.contains("://") ? source : SafeBase64Decode(source); // SubscriptionDecodeResult result; result.links = SplitLines(resultList); return result; } // SIP008 Decoder SubscriptionDecoder::SubscriptionDecodeResult SIP008Decoder::DecodeData(const QByteArray &data) const { const auto root = QJsonDocument::fromJson(data).object(); // const auto version = root["version"].toString(); const auto username = root["username"].toString(); const auto user_uuid = root["user_uuid"].toString(); const auto servers = root["servers"].toArray(); // ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpwYXNzQGhvc3Q6MTIzNA/?plugin=plugin%3Bopt#sssip003 SubscriptionDecodeResult result; #define GetVal(x) const auto x = serverObj[#x].toString() for (const auto &servVal : servers) { const auto serverObj = servVal.toObject(); GetVal(server); GetVal(password); GetVal(method); GetVal(plugin); GetVal(plugin_opts); GetVal(remarks); GetVal(id); const auto server_port = serverObj["server_port"].toInt(); bool isSIP003 = !plugin.isEmpty(); const auto userInfo = SafeBase64Encode(method + ":" + password); // QUrl link; link.setScheme("ss"); link.setUserInfo(userInfo); link.setHost(server); link.setPort(server_port); link.setFragment(remarks); if (isSIP003) { QUrlQuery q; q.addQueryItem("plugin", QUrl::toPercentEncoding(plugin + ";" + plugin_opts)); link.setQuery(q); } result.links << link.toString(QUrl::FullyEncoded); } #undef GetVal return result; }
2,502
C++
.cpp
70
30.357143
107
0.680825
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,169
HTTPRequestHelper.cpp
Qv2ray_Qv2ray/src/utils/HTTPRequestHelper.cpp
#include "HTTPRequestHelper.hpp" #include "base/Qv2rayBase.hpp" #include <QByteArray> #include <QNetworkProxy> #define QV_MODULE_NAME "NetworkCore" namespace Qv2ray::common::network { void NetworkRequestHelper::setHeader(QNetworkRequest &request, const QByteArray &key, const QByteArray &value) { DEBUG("Adding HTTP request header: " + key + ":" + value); request.setRawHeader(key, value); } void NetworkRequestHelper::setAccessManagerAttributes(QNetworkRequest &request, QNetworkAccessManager &accessManager) { switch (GlobalConfig.networkConfig.proxyType) { case Qv2rayConfig_Network::QVPROXY_NONE: { DEBUG("Get without proxy."); accessManager.setProxy(QNetworkProxy(QNetworkProxy::ProxyType::NoProxy)); break; } case Qv2rayConfig_Network::QVPROXY_SYSTEM: { accessManager.setProxy(QNetworkProxyFactory::systemProxyForQuery().first()); break; } case Qv2rayConfig_Network::QVPROXY_CUSTOM: { QNetworkProxy p{ GlobalConfig.networkConfig.type == "http" ? QNetworkProxy::HttpProxy : QNetworkProxy::Socks5Proxy, // GlobalConfig.networkConfig.address, // quint16(GlobalConfig.networkConfig.port) // }; accessManager.setProxy(p); break; } default: Q_UNREACHABLE(); } if (accessManager.proxy().type() == QNetworkProxy::Socks5Proxy) { DEBUG("Adding HostNameLookupCapability to proxy."); accessManager.proxy().setCapabilities(accessManager.proxy().capabilities() | QNetworkProxy::HostNameLookupCapability); } request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // request.setAttribute(QNetworkRequest::Http2AllowedAttribute, true); #else // request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); #endif auto ua = GlobalConfig.networkConfig.userAgent; ua.replace("$VERSION", QV2RAY_VERSION_STRING); request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, ua); } QByteArray NetworkRequestHelper::HttpGet(const QUrl &url) { QNetworkRequest request; QNetworkAccessManager accessManager; request.setUrl(url); setAccessManagerAttributes(request, accessManager); auto _reply = accessManager.get(request); // { QEventLoop loop; QObject::connect(&accessManager, &QNetworkAccessManager::finished, &loop, &QEventLoop::quit); loop.exec(); } // // Data or timeout? LOG(_reply->errorString()); auto data = _reply->readAll(); return data; } void NetworkRequestHelper::AsyncHttpGet(const QString &url, std::function<void(const QByteArray &)> funcPtr) { QNetworkRequest request; request.setUrl(url); auto accessManagerPtr = new QNetworkAccessManager(); setAccessManagerAttributes(request, *accessManagerPtr); auto reply = accessManagerPtr->get(request); QObject::connect(reply, &QNetworkReply::finished, [=]() { { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) bool h2Used = reply->attribute(QNetworkRequest::Http2WasUsedAttribute).toBool(); #else bool h2Used = reply->attribute(QNetworkRequest::HTTP2WasUsedAttribute).toBool(); #endif if (h2Used) DEBUG("HTTP/2 was used."); if (reply->error() != QNetworkReply::NoError) LOG("Network error: " + QString(QMetaEnum::fromType<QNetworkReply::NetworkError>().key(reply->error()))); funcPtr(reply->readAll()); accessManagerPtr->deleteLater(); } }); } } // namespace Qv2ray::common::network
4,227
C++
.cpp
97
33.525773
130
0.613217
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,170
Qv2rayPlatformApplication.cpp
Qv2ray_Qv2ray/src/ui/Qv2rayPlatformApplication.cpp
#include "Qv2rayPlatformApplication.hpp" #include "core/settings/SettingsBackend.hpp" #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include <QSessionManager> #endif #include <QSslSocket> #define QV_MODULE_NAME "PlatformApplication" #ifdef QT_DEBUG const static inline QString QV2RAY_URL_SCHEME = "qv2ray-debug"; #else const static inline QString QV2RAY_URL_SCHEME = "qv2ray"; #endif QStringList Qv2rayPlatformApplication::CheckPrerequisites() { QStringList errors; if (!QSslSocket::supportsSsl()) { // Check OpenSSL version for auto-update and subscriptions const auto osslReqVersion = QSslSocket::sslLibraryBuildVersionString(); const auto osslCurVersion = QSslSocket::sslLibraryVersionString(); LOG("Current OpenSSL version: " + osslCurVersion); LOG("Required OpenSSL version: " + osslReqVersion); errors << "Qv2ray cannot run without OpenSSL."; errors << "This is usually caused by using the wrong version of OpenSSL"; errors << "Required=" + osslReqVersion + "Current=" + osslCurVersion; } return errors + checkPrerequisitesInternal(); } bool Qv2rayPlatformApplication::Initialize() { QString errorMessage; bool canContinue; const auto hasError = parseCommandLine(&errorMessage, &canContinue); if (hasError) { LOG("Command line:" QVLOG_A(errorMessage)); if (!canContinue) { LOG("Fatal, Qv2ray cannot continue."); return false; } else { LOG("Non-fatal error, continue starting up."); } } #ifdef Q_OS_WIN const auto appPath = QDir::toNativeSeparators(applicationFilePath()); const auto regPath = "HKEY_CURRENT_USER\\Software\\Classes\\" + QV2RAY_URL_SCHEME; QSettings reg(regPath, QSettings::NativeFormat); reg.setValue("Default", "Qv2ray"); reg.setValue("URL Protocol", ""); reg.beginGroup("DefaultIcon"); reg.setValue("Default", QString("%1,1").arg(appPath)); reg.endGroup(); reg.beginGroup("shell"); reg.beginGroup("open"); reg.beginGroup("command"); reg.setValue("Default", appPath + " %1"); #endif connect(this, &Qv2rayPlatformApplication::aboutToQuit, this, &Qv2rayPlatformApplication::quitInternal); #ifndef QV2RAY_NO_SINGLEAPPLICATON connect(this, &SingleApplication::receivedMessage, this, &Qv2rayPlatformApplication::onMessageReceived, Qt::QueuedConnection); if (isSecondary()) { StartupArguments.version = QV2RAY_VERSION_STRING; StartupArguments.buildVersion = QV2RAY_VERSION_BUILD; StartupArguments.fullArgs = arguments(); if (StartupArguments.arguments.isEmpty()) StartupArguments.arguments << Qv2rayStartupArguments::NORMAL; bool status = sendMessage(JsonToString(StartupArguments.toJson(), QJsonDocument::Compact).toUtf8()); if (!status) LOG("Cannot send message."); SetExitReason(EXIT_SECONDARY_INSTANCE); return false; } #endif #ifdef QV2RAY_GUI #ifdef Q_OS_LINUX #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) setFallbackSessionManagementEnabled(false); #endif connect(this, &QGuiApplication::commitDataRequest, [] { RouteManager->SaveRoutes(); ConnectionManager->SaveConnectionConfig(); PluginHost->SavePluginSettings(); SaveGlobalSettings(); }); #endif #ifdef Q_OS_WIN SetCurrentDirectory(applicationDirPath().toStdWString().c_str()); // Set special font in Windows QFont font; font.setPointSize(9); font.setFamily("Microsoft YaHei"); setFont(font); #endif #endif // Install a default translater. From the OS/DE Qv2rayTranslator = std::make_unique<QvTranslator>(); Qv2rayTranslator->InstallTranslation(QLocale::system().name()); const auto allTranslations = Qv2rayTranslator->GetAvailableLanguages(); const auto osLanguage = QLocale::system().name(); // LocateConfiguration(); if (!allTranslations.contains(GlobalConfig.uiConfig.language)) { // If we need to reset the language. if (allTranslations.contains(osLanguage)) { GlobalConfig.uiConfig.language = osLanguage; } else if (!allTranslations.isEmpty()) { GlobalConfig.uiConfig.language = allTranslations.first(); } } if (!Qv2rayTranslator->InstallTranslation(GlobalConfig.uiConfig.language)) { QvMessageBoxWarn(nullptr, "Translation Failed", "Cannot load translation for " + GlobalConfig.uiConfig.language + NEWLINE + // "English is now used." + NEWLINE + NEWLINE + // "Please go to Preferences Window to change language or open an Issue"); GlobalConfig.uiConfig.language = "en_US"; } return true; } Qv2rayExitReason Qv2rayPlatformApplication::RunQv2ray() { PluginHost = new QvPluginHost(); RouteManager = new RouteHandler(); ConnectionManager = new QvConfigHandler(); return runQv2rayInternal(); } void Qv2rayPlatformApplication::quitInternal() { // Do not change the order. ConnectionManager->StopConnection(); RouteManager->SaveRoutes(); ConnectionManager->SaveConnectionConfig(); PluginHost->SavePluginSettings(); SaveGlobalSettings(); terminateUIInternal(); delete ConnectionManager; delete RouteManager; delete PluginHost; ConnectionManager = nullptr; RouteManager = nullptr; PluginHost = nullptr; } bool Qv2rayPlatformApplication::parseCommandLine(QString *errorMessage, bool *canContinue) { *canContinue = true; QStringList filteredArgs; for (const auto &arg : arguments()) { #ifdef Q_OS_MACOS if (arg.contains("-psn")) continue; #endif filteredArgs << arg; } QCommandLineParser parser; // QCommandLineOption noAPIOption("noAPI", QObject::tr("Disable gRPC API subsystem")); QCommandLineOption noPluginsOption("noPlugin", QObject::tr("Disable plugins feature")); QCommandLineOption debugLogOption("debug", QObject::tr("Enable debug output")); QCommandLineOption noAutoConnectionOption("noAutoConnection", QObject::tr("Do not automatically connect")); QCommandLineOption disconnectOption("disconnect", QObject::tr("Stop current connection")); QCommandLineOption reconnectOption("reconnect", QObject::tr("Reconnect last connection")); QCommandLineOption exitOption("exit", QObject::tr("Exit Qv2ray")); // parser.setApplicationDescription(QObject::tr("Qv2ray - A cross-platform Qt frontend for V2Ray.")); parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); // parser.addOption(noAPIOption); parser.addOption(noPluginsOption); parser.addOption(debugLogOption); parser.addOption(noAutoConnectionOption); parser.addOption(disconnectOption); parser.addOption(reconnectOption); parser.addOption(exitOption); // const auto helpOption = parser.addHelpOption(); const auto versionOption = parser.addVersionOption(); if (!parser.parse(filteredArgs)) { *canContinue = true; *errorMessage = parser.errorText(); return false; } if (parser.isSet(versionOption)) { parser.showVersion(); return true; } if (parser.isSet(helpOption)) { parser.showHelp(); return true; } for (const auto &arg : parser.positionalArguments()) { if (arg.startsWith(QV2RAY_URL_SCHEME + "://")) { StartupArguments.arguments << Qv2rayStartupArguments::QV2RAY_LINK; StartupArguments.links << arg; } } if (parser.isSet(exitOption)) { DEBUG("disconnectOption is set."); StartupArguments.arguments << Qv2rayStartupArguments::EXIT; } if (parser.isSet(disconnectOption)) { DEBUG("disconnectOption is set."); StartupArguments.arguments << Qv2rayStartupArguments::DISCONNECT; } if (parser.isSet(reconnectOption)) { DEBUG("reconnectOption is set."); StartupArguments.arguments << Qv2rayStartupArguments::RECONNECT; } #define ProcessExtraStartupOptions(option) \ DEBUG("Startup Options:" QVLOG_A(parser.isSet(option##Option))); \ StartupArguments.option = parser.isSet(option##Option); ProcessExtraStartupOptions(noAPI); ProcessExtraStartupOptions(debugLog); ProcessExtraStartupOptions(noAutoConnection); ProcessExtraStartupOptions(noPlugins); return true; }
8,777
C++
.cpp
233
31.708155
150
0.680831
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,171
Qv2rayWidgetApplication.cpp
Qv2ray_Qv2ray/src/ui/widgets/Qv2rayWidgetApplication.cpp
#include "Qv2rayWidgetApplication.hpp" #include "base/Qv2rayBase.hpp" #include "components/translations/QvTranslator.hpp" #include "core/settings/SettingsBackend.hpp" #include "ui/widgets/styles/StyleManager.hpp" #include "ui/widgets/windows/w_MainWindow.hpp" #include "utils/QvHelpers.hpp" #include <QApplication> #include <QDesktopServices> #include <QMessageBox> #include <QUrl> #include <QUrlQuery> #ifdef Q_OS_WIN #include <Winbase.h> #endif #define QV_MODULE_NAME "WidgetApplication" constexpr auto QV2RAY_WIDGETUI_STATE_FILENAME = "UIState.json"; Qv2rayWidgetApplication::Qv2rayWidgetApplication(int &argc, char *argv[]) : Qv2rayPlatformApplication(argc, argv) { } QStringList Qv2rayWidgetApplication::checkPrerequisitesInternal() { return {}; } void Qv2rayWidgetApplication::terminateUIInternal() { delete mainWindow; delete hTray; delete StyleManager; StringToFile(JsonToString(UIStates), QV2RAY_CONFIG_DIR + QV2RAY_WIDGETUI_STATE_FILENAME); } #ifndef QV2RAY_NO_SINGLEAPPLICATON void Qv2rayWidgetApplication::onMessageReceived(quint32 clientId, QByteArray _msg) { // Sometimes SingleApplication will send message with clientId == 0, ignore them. if (clientId == instanceId()) return; if (!isInitialized) return; const auto msg = Qv2rayStartupArguments::fromJson(JsonFromString(_msg)); LOG("Client ID:", clientId, ", message received, version:", msg.buildVersion); DEBUG(_msg); // if (msg.buildVersion > QV2RAY_VERSION_BUILD) { const auto newPath = msg.fullArgs.first(); QString message; message += tr("A new version of Qv2ray is starting:") + NEWLINE; message += NEWLINE; message += tr("New version information: ") + NEWLINE; message += tr("Version: %1:%2").arg(msg.version).arg(msg.buildVersion) + NEWLINE; message += tr("Path: %1").arg(newPath) + NEWLINE; message += NEWLINE; message += tr("Do you want to exit and launch that new version?"); const auto result = QvMessageBoxAsk(nullptr, tr("New version detected"), message); if (result == Yes) { StartupArguments._qvNewVersionPath = newPath; SetExitReason(EXIT_NEW_VERSION_TRIGGER); QCoreApplication::quit(); } } for (const auto &argument : msg.arguments) { switch (argument) { case Qv2rayStartupArguments::EXIT: { SetExitReason(EXIT_NORMAL); quit(); break; } case Qv2rayStartupArguments::NORMAL: { mainWindow->show(); mainWindow->raise(); mainWindow->activateWindow(); break; } case Qv2rayStartupArguments::RECONNECT: { ConnectionManager->RestartConnection(); break; } case Qv2rayStartupArguments::DISCONNECT: { ConnectionManager->StopConnection(); break; } case Qv2rayStartupArguments::QV2RAY_LINK: { for (const auto &link : msg.links) { const auto url = QUrl::fromUserInput(link); const auto command = url.host(); auto subcommands = url.path().split("/"); subcommands.removeAll(""); QMap<QString, QString> args; for (const auto &kvp : QUrlQuery(url).queryItems()) { args.insert(kvp.first, kvp.second); } if (command == "open") { emit mainWindow->ProcessCommand(command, subcommands, args); } } break; } } } } #endif Qv2rayExitReason Qv2rayWidgetApplication::runQv2rayInternal() { setQuitOnLastWindowClosed(false); hTray = new QSystemTrayIcon(); StyleManager = new QvStyleManager(); StyleManager->ApplyStyle(GlobalConfig.uiConfig.theme); // Show MainWindow UIStates = JsonFromString(StringFromFile(QV2RAY_CONFIG_DIR + QV2RAY_WIDGETUI_STATE_FILENAME)); mainWindow = new MainWindow(); if (StartupArguments.arguments.contains(Qv2rayStartupArguments::QV2RAY_LINK)) { for (const auto &link : StartupArguments.links) { const auto url = QUrl::fromUserInput(link); const auto command = url.host(); auto subcommands = url.path().split("/"); subcommands.removeAll(""); QMap<QString, QString> args; for (const auto &kvp : QUrlQuery(url).queryItems()) { args.insert(kvp.first, kvp.second); } if (command == "open") { emit mainWindow->ProcessCommand(command, subcommands, args); } } } #ifdef Q_OS_MACOS connect(this, &QApplication::applicationStateChanged, [this](Qt::ApplicationState state) { switch (state) { case Qt::ApplicationActive: { mainWindow->show(); mainWindow->raise(); mainWindow->activateWindow(); break; } case Qt::ApplicationHidden: case Qt::ApplicationInactive: case Qt::ApplicationSuspended: break; } }); #endif isInitialized = true; return (Qv2rayExitReason) exec(); } void Qv2rayWidgetApplication::OpenURL(const QString &url) { QDesktopServices::openUrl(url); } void Qv2rayWidgetApplication::MessageBoxWarn(QWidget *parent, const QString &title, const QString &text) { QMessageBox::warning(parent, title, text, QMessageBox::Ok); } void Qv2rayWidgetApplication::MessageBoxInfo(QWidget *parent, const QString &title, const QString &text) { QMessageBox::information(parent, title, text, QMessageBox::Ok); } MessageOpt Qv2rayWidgetApplication::MessageBoxAsk(QWidget *parent, const QString &title, const QString &text, const QList<MessageOpt> &buttons) { QFlags<QMessageBox::StandardButton> btns; for (const auto &b : buttons) { btns.setFlag(MessageBoxButtonMap[b]); } return MessageBoxButtonMap.key(QMessageBox::question(parent, title, text, btns)); } void Qv2rayWidgetApplication::ShowTrayMessage(const QString &m, int msecs) { hTray->showMessage("Qv2ray", m, QIcon(":/assets/icons/qv2ray.png"), msecs); }
6,581
C++
.cpp
186
26.817204
143
0.619981
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,172
ConnectionModelHelper.cpp
Qv2ray_Qv2ray/src/ui/widgets/models/ConnectionModelHelper.cpp
#include "ConnectionModelHelper.hpp" #include "core/handler/ConfigHandler.hpp" #include "ui/widgets/widgets/ConnectionItemWidget.hpp" #define NumericString(i) (QString("%1").arg(i, 30, 10, QLatin1Char('0'))) ConnectionListHelper::ConnectionListHelper(QTreeView *view, QObject *parent) : QObject(parent) { parentView = view; model = new QStandardItemModel(); view->setModel(model); for (const auto &group : ConnectionManager->AllGroups()) { addGroupItem(group); for (const auto &connection : ConnectionManager->GetConnections(group)) { addConnectionItem({ connection, group }); } } const auto renamedLambda = [&](const ConnectionId &id, const QString &, const QString &newName) { for (const auto &gid : ConnectionManager->GetConnectionContainedIn(id)) { ConnectionGroupPair pair{ id, gid }; if (pairs.contains(pair)) pairs[pair]->setData(newName, ROLE_DISPLAYNAME); } }; const auto latencyLambda = [&](const ConnectionId &id, const int avg) { for (const auto &gid : ConnectionManager->GetConnectionContainedIn(id)) { ConnectionGroupPair pair{ id, gid }; if (pairs.contains(pair)) pairs[pair]->setData(NumericString(avg), ROLE_LATENCY); } }; const auto statsLambda = [&](const ConnectionGroupPair &id, const QMap<StatisticsType, QvStatsSpeedData> &data) { if (connections.contains(id.connectionId)) { for (const auto &index : connections[id.connectionId]) index->setData(NumericString(GetConnectionTotalData(id.connectionId)), ROLE_DATA_USAGE); } }; connect(ConnectionManager, &QvConfigHandler::OnConnectionRemovedFromGroup, this, &ConnectionListHelper::OnConnectionDeleted); connect(ConnectionManager, &QvConfigHandler::OnConnectionCreated, this, &ConnectionListHelper::OnConnectionCreated); connect(ConnectionManager, &QvConfigHandler::OnConnectionLinkedWithGroup, this, &ConnectionListHelper::OnConnectionLinkedWithGroup); connect(ConnectionManager, &QvConfigHandler::OnGroupCreated, this, &ConnectionListHelper::OnGroupCreated); connect(ConnectionManager, &QvConfigHandler::OnGroupDeleted, this, &ConnectionListHelper::OnGroupDeleted); connect(ConnectionManager, &QvConfigHandler::OnConnectionRenamed, renamedLambda); connect(ConnectionManager, &QvConfigHandler::OnLatencyTestFinished, latencyLambda); connect(ConnectionManager, &QvConfigHandler::OnStatsAvailable, statsLambda); } ConnectionListHelper::~ConnectionListHelper() { delete model; } void ConnectionListHelper::Sort(ConnectionInfoRole role, Qt::SortOrder order) { model->setSortRole(role); model->sort(0, order); } void ConnectionListHelper::Filter(const QString &key) { for (const auto &groupId : ConnectionManager->AllGroups()) { const auto groupItem = model->indexFromItem(groups[groupId]); bool isTotallyHide = true; for (const auto &connectionId : ConnectionManager->GetConnections(groupId)) { const auto connectionItem = model->indexFromItem(pairs[{ connectionId, groupId }]); const auto willTotallyHide = static_cast<ConnectionItemWidget *>(parentView->indexWidget(connectionItem))->NameMatched(key); parentView->setRowHidden(connectionItem.row(), connectionItem.parent(), !willTotallyHide); isTotallyHide &= willTotallyHide; } parentView->indexWidget(groupItem)->setHidden(isTotallyHide); if (!isTotallyHide) parentView->expand(groupItem); } } QStandardItem *ConnectionListHelper::addConnectionItem(const ConnectionGroupPair &id) { // Create Standard Item auto connectionItem = new QStandardItem(); connectionItem->setData(GetDisplayName(id.connectionId), ConnectionInfoRole::ROLE_DISPLAYNAME); connectionItem->setData(NumericString(GetConnectionLatency(id.connectionId)), ConnectionInfoRole::ROLE_LATENCY); connectionItem->setData(NumericString(GetConnectionTotalData(id.connectionId)), ConnectionInfoRole::ROLE_DATA_USAGE); // // Find groups const auto groupIndex = groups.contains(id.groupId) ? groups[id.groupId] : addGroupItem(id.groupId); // Append into model groupIndex->appendRow(connectionItem); const auto connectionIndex = connectionItem->index(); // auto widget = new ConnectionItemWidget(id, parentView); connect(widget, &ConnectionItemWidget::RequestWidgetFocus, [widget, connectionIndex, this]() { parentView->setCurrentIndex(connectionIndex); parentView->scrollTo(connectionIndex); parentView->clicked(connectionIndex); }); // parentView->setIndexWidget(connectionIndex, widget); pairs[id] = connectionItem; connections[id.connectionId].append(connectionItem); return connectionItem; } QStandardItem *ConnectionListHelper::addGroupItem(const GroupId &groupId) { // Create Item const auto item = new QStandardItem(); // Set item into model model->appendRow(item); // Get item index const auto index = item->index(); parentView->setIndexWidget(index, new ConnectionItemWidget(groupId, parentView)); groups[groupId] = item; return item; } void ConnectionListHelper::OnConnectionCreated(const ConnectionGroupPair &id, const QString &) { addConnectionItem(id); } void ConnectionListHelper::OnConnectionDeleted(const ConnectionGroupPair &id) { auto item = pairs.take(id); const auto index = model->indexFromItem(item); if (!index.isValid()) return; model->removeRow(index.row(), index.parent()); connections[id.connectionId].removeAll(item); } void ConnectionListHelper::OnConnectionLinkedWithGroup(const ConnectionGroupPair &pairId) { addConnectionItem(pairId); } void ConnectionListHelper::OnGroupCreated(const GroupId &id, const QString &) { addGroupItem(id); } void ConnectionListHelper::OnGroupDeleted(const GroupId &id, const QList<ConnectionId> &connections) { for (const auto &conn : connections) { const ConnectionGroupPair pair{ conn, id }; OnConnectionDeleted(pair); } const auto item = groups.take(id); const auto index = model->indexFromItem(item); if (!index.isValid()) return; model->removeRow(index.row(), index.parent()); }
6,414
C++
.cpp
148
37.662162
136
0.72768
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,173
DnsSettingsWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/DnsSettingsWidget.cpp
#include "DnsSettingsWidget.hpp" #include "components/geosite/QvGeositeReader.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "ui/widgets/widgets/QvAutoCompleteTextEdit.hpp" #include "utils/QvHelpers.hpp" using Qv2ray::common::validation::IsIPv4Address; using Qv2ray::common::validation::IsIPv6Address; using Qv2ray::common::validation::IsValidDNSServer; using Qv2ray::common::validation::IsValidIPAddress; #define CHECK_DISABLE_MOVE_BTN \ if (serversListbox->count() <= 1) \ { \ moveServerUpBtn->setEnabled(false); \ moveServerDownBtn->setEnabled(false); \ } #define UPDATE_UI_ENABLED_STATE \ detailsSettingsGB->setEnabled(serversListbox->count() > 0); \ serverAddressTxt->setEnabled(serversListbox->count() > 0); \ removeServerBtn->setEnabled(serversListbox->count() > 0); \ ProcessDnsPortEnabledState(); \ CHECK_DISABLE_MOVE_BTN #define currentServerIndex serversListbox->currentRow() void DnsSettingsWidget::updateColorScheme() { addServerBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); removeServerBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("minus"))); moveServerUpBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("arrow-up"))); moveServerDownBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("arrow-down"))); addStaticHostBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); removeStaticHostBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("minus"))); } DnsSettingsWidget::DnsSettingsWidget(QWidget *parent) : QWidget(parent) { setupUi(this); QvMessageBusConnect(DnsSettingsWidget); // auto sourceStringsDomain = ReadGeoSiteFromFile(GlobalConfig.kernelConfig.AssetsPath() + "/geosite.dat"); auto sourceStringsIP = ReadGeoSiteFromFile(GlobalConfig.kernelConfig.AssetsPath() + "/geoip.dat"); // domainListTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this); ipListTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this); connect(domainListTxt, &AutoCompleteTextEdit::textChanged, [&]() { this->dns.servers[currentServerIndex].domains = SplitLines(domainListTxt->toPlainText()); }); connect(ipListTxt, &AutoCompleteTextEdit::textChanged, [&]() { this->dns.servers[currentServerIndex].expectIPs = SplitLines(ipListTxt->toPlainText()); }); domainsLayout->addWidget(domainListTxt); expectedIPsLayout->addWidget(ipListTxt); detailsSettingsGB->setCheckable(true); detailsSettingsGB->setChecked(false); UPDATE_UI_ENABLED_STATE; updateColorScheme(); } QvMessageBusSlotImpl(DnsSettingsWidget) { switch (msg) { MBRetranslateDefaultImpl; case HIDE_WINDOWS: case SHOW_WINDOWS: break; case UPDATE_COLORSCHEME: { updateColorScheme(); break; } } } void DnsSettingsWidget::SetDNSObject(const DNSObject &_dns, const FakeDNSObject &_fakeDNS) { this->dns = _dns; this->fakeDNS = _fakeDNS; dnsClientIPTxt->setText(dns.clientIp); dnsTagTxt->setText(dns.tag); serversListbox->clear(); std::for_each(dns.servers.begin(), dns.servers.end(), [&](const auto &dns) { serversListbox->addItem(dns.address); }); if (serversListbox->count() > 0) { serversListbox->setCurrentRow(0); ShowCurrentDnsServerDetails(); } staticResolvedDomainsTable->clearContents(); for (const auto &[host, ip] : dns.hosts.toStdMap()) { const auto rowId = staticResolvedDomainsTable->rowCount(); staticResolvedDomainsTable->insertRow(rowId); staticResolvedDomainsTable->setItem(rowId, 0, new QTableWidgetItem(host)); staticResolvedDomainsTable->setItem(rowId, 1, new QTableWidgetItem(ip)); } staticResolvedDomainsTable->resizeColumnsToContents(); dnsQueryStrategyCB->setCurrentText(dns.queryStrategy); dnsDisableFallbackCB->setChecked(dns.disableFallback); dnsDisableCacheCB->setChecked(dns.disableCache); fakeDNSIPPool->setCurrentText(fakeDNS.ipPool); fakeDNSIPPoolSize->setValue(fakeDNS.poolSize); UPDATE_UI_ENABLED_STATE } bool DnsSettingsWidget::CheckIsValidDNS() const { if (!dns.clientIp.isEmpty() && !IsValidIPAddress(dns.clientIp)) return false; for (const auto &server : dns.servers) { if (!IsValidDNSServer(server.address)) return false; } return true; } void DnsSettingsWidget::ProcessDnsPortEnabledState() { if (detailsSettingsGB->isChecked()) { const auto isDoHDoT = serverAddressTxt->text().startsWith("https:") || serverAddressTxt->text().startsWith("https+"); serverPortSB->setEnabled(!isDoHDoT); } } void DnsSettingsWidget::ShowCurrentDnsServerDetails() { serverAddressTxt->setText(dns.servers[currentServerIndex].address); // domainListTxt->setPlainText(dns.servers[currentServerIndex].domains.join(NEWLINE)); ipListTxt->setPlainText(dns.servers[currentServerIndex].expectIPs.join(NEWLINE)); // serverPortSB->setValue(dns.servers[currentServerIndex].port); detailsSettingsGB->setChecked(dns.servers[currentServerIndex].QV2RAY_DNS_IS_COMPLEX_DNS); // if (serverAddressTxt->text().isEmpty() || IsValidDNSServer(serverAddressTxt->text())) { BLACK(serverAddressTxt); } else { RED(serverAddressTxt); } ProcessDnsPortEnabledState(); } std::pair<DNSObject, FakeDNSObject> DnsSettingsWidget::GetDNSObject() { dns.hosts.clear(); for (auto i = 0; i < staticResolvedDomainsTable->rowCount(); i++) { const auto &item1 = staticResolvedDomainsTable->item(i, 0); const auto &item2 = staticResolvedDomainsTable->item(i, 1); if (item1 && item2) dns.hosts[item1->text()] = item2->text(); } return { dns, fakeDNS }; } void DnsSettingsWidget::on_dnsClientIPTxt_textEdited(const QString &arg1) { dns.clientIp = arg1; } void DnsSettingsWidget::on_dnsTagTxt_textEdited(const QString &arg1) { dns.tag = arg1; } void DnsSettingsWidget::on_addServerBtn_clicked() { DNSObject::DNSServerObject o; o.address = "1.1.1.1"; o.port = 53; dns.servers.push_back(o); serversListbox->addItem(o.address); serversListbox->setCurrentRow(serversListbox->count() - 1); UPDATE_UI_ENABLED_STATE ShowCurrentDnsServerDetails(); } void DnsSettingsWidget::on_removeServerBtn_clicked() { dns.servers.removeAt(currentServerIndex); // Block the signals serversListbox->blockSignals(true); auto item = serversListbox->item(currentServerIndex); serversListbox->removeItemWidget(item); delete item; serversListbox->blockSignals(false); UPDATE_UI_ENABLED_STATE if (serversListbox->count() > 0) { if (currentServerIndex < 0) serversListbox->setCurrentRow(0); ShowCurrentDnsServerDetails(); } } void DnsSettingsWidget::on_serversListbox_currentRowChanged(int currentRow) { if (currentRow < 0) return; moveServerUpBtn->setEnabled(true); moveServerDownBtn->setEnabled(true); if (currentRow == 0) { moveServerUpBtn->setEnabled(false); } if (currentRow == serversListbox->count() - 1) { moveServerDownBtn->setEnabled(false); } ShowCurrentDnsServerDetails(); } void DnsSettingsWidget::on_moveServerUpBtn_clicked() { auto temp = dns.servers[currentServerIndex - 1]; dns.servers[currentServerIndex - 1] = dns.servers[currentServerIndex]; dns.servers[currentServerIndex] = temp; serversListbox->currentItem()->setText(dns.servers[currentServerIndex].address); serversListbox->setCurrentRow(currentServerIndex - 1); serversListbox->currentItem()->setText(dns.servers[currentServerIndex].address); } void DnsSettingsWidget::on_moveServerDownBtn_clicked() { auto temp = dns.servers[currentServerIndex + 1]; dns.servers[currentServerIndex + 1] = dns.servers[currentServerIndex]; dns.servers[currentServerIndex] = temp; serversListbox->currentItem()->setText(dns.servers[currentServerIndex].address); serversListbox->setCurrentRow(currentServerIndex + 1); serversListbox->currentItem()->setText(dns.servers[currentServerIndex].address); } void DnsSettingsWidget::on_serverAddressTxt_textEdited(const QString &arg1) { dns.servers[currentServerIndex].address = arg1; serversListbox->currentItem()->setText(arg1); if (arg1.isEmpty() || IsValidDNSServer(arg1)) { BLACK(serverAddressTxt); } else { RED(serverAddressTxt); } ProcessDnsPortEnabledState(); } void DnsSettingsWidget::on_serverPortSB_valueChanged(int arg1) { dns.servers[currentServerIndex].port = arg1; } void DnsSettingsWidget::on_addStaticHostBtn_clicked() { if (staticResolvedDomainsTable->rowCount() >= 0) staticResolvedDomainsTable->insertRow(staticResolvedDomainsTable->rowCount()); } void DnsSettingsWidget::on_removeStaticHostBtn_clicked() { if (staticResolvedDomainsTable->rowCount() >= 0) staticResolvedDomainsTable->removeRow(staticResolvedDomainsTable->currentRow()); staticResolvedDomainsTable->resizeColumnsToContents(); } void DnsSettingsWidget::on_staticResolvedDomainsTable_cellChanged(int, int) { staticResolvedDomainsTable->resizeColumnsToContents(); } void DnsSettingsWidget::on_detailsSettingsGB_toggled(bool arg1) { if (currentServerIndex >= 0) dns.servers[currentServerIndex].QV2RAY_DNS_IS_COMPLEX_DNS = arg1; // detailsSettingsGB->setChecked(dns.servers[currentServerIndex].QV2RAY_DNS_IS_COMPLEX_DNS); } void DnsSettingsWidget::on_fakeDNSIPPool_currentTextChanged(const QString &arg1) { fakeDNS.ipPool = arg1; } void DnsSettingsWidget::on_fakeDNSIPPoolSize_valueChanged(int arg1) { fakeDNS.poolSize = arg1; } void DnsSettingsWidget::on_dnsDisableCacheCB_stateChanged(int arg1) { dns.disableCache = arg1 == Qt::Checked; } void DnsSettingsWidget::on_dnsDisableFallbackCB_stateChanged(int arg1) { dns.disableFallback = arg1 == Qt::Checked; } void DnsSettingsWidget::on_dnsQueryStrategyCB_currentTextChanged(const QString &arg1) { dns.queryStrategy = arg1; }
11,197
C++
.cpp
275
36.185455
150
0.666146
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,174
StreamSettingsWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/StreamSettingsWidget.cpp
#include "StreamSettingsWidget.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "ui/widgets/editors/w_ChainSha256Editor.hpp" #include "ui/widgets/editors/w_JsonEditor.hpp" #include "utils/QvHelpers.hpp" #define QV_MODULE_NAME "StreamSettingsWidget" StreamSettingsWidget::StreamSettingsWidget(QWidget *parent) : QWidget(parent) { setupUi(this); QvMessageBusConnect(StreamSettingsWidget); } QvMessageBusSlotImpl(StreamSettingsWidget) { switch (msg) { MBRetranslateDefaultImpl; case UPDATE_COLORSCHEME: case HIDE_WINDOWS: case SHOW_WINDOWS: break; } } StreamSettingsObject StreamSettingsWidget::GetStreamSettings() const { return stream; } void StreamSettingsWidget::SetStreamObject(const StreamSettingsObject &sso) { stream = sso; transportCombo->setCurrentText(stream.network); // TLS XTLS { const static QMap<QString, int> securityIndexMap{ { "none", 0 }, { "tls", 1 }, { "xtls", 2 } }; if (securityIndexMap.contains(stream.security)) securityTypeCB->setCurrentIndex(securityIndexMap[stream.security]); else LOG("Unsupported Security Type:", stream.security); #define tls_xtls_process(prefix) \ { \ serverNameTxt->setText(stream.prefix##Settings.serverName); \ allowInsecureCB->setChecked(stream.prefix##Settings.allowInsecure); \ enableSessionResumptionCB->setChecked(stream.prefix##Settings.enableSessionResumption); \ disableSystemRoot->setChecked(stream.prefix##Settings.disableSystemRoot); \ alpnTxt->setText(stream.prefix##Settings.alpn.join("|")); \ } tls_xtls_process(tls); if (stream.security == "xtls") tls_xtls_process(xtls); } // TCP { tcpHeaderTypeCB->setCurrentText(stream.tcpSettings.header.type); tcpRequestTxt->setPlainText(JsonToString(stream.tcpSettings.header.request.toJson())); tcpRespTxt->setPlainText(JsonToString(stream.tcpSettings.header.response.toJson())); } // HTTP { httpHostTxt->setPlainText(stream.httpSettings.host.join(NEWLINE)); httpPathTxt->setText(stream.httpSettings.path); httpMethodCB->setCurrentText(stream.httpSettings.method); httpHeadersTxt->setPlainText(JsonToString(stream.httpSettings.toJson()["headers"].toObject())); } // WS { wsPathTxt->setText(stream.wsSettings.path); QString wsHeaders; for (const auto &[key, value] : stream.wsSettings.headers.toStdMap()) { wsHeaders = wsHeaders % key % "|" % value % NEWLINE; } wsHeadersTxt->setPlainText(wsHeaders); wsEarlyDataSB->setValue(stream.wsSettings.maxEarlyData); wsBrowserForwardCB->setChecked(stream.wsSettings.useBrowserForwarding); wsEarlyDataHeaderNameCB->setCurrentText(stream.wsSettings.earlyDataHeaderName); } // mKCP { kcpMTU->setValue(stream.kcpSettings.mtu); kcpTTI->setValue(stream.kcpSettings.tti); kcpHeaderType->setCurrentText(stream.kcpSettings.header.type); kcpCongestionCB->setChecked(stream.kcpSettings.congestion); kcpReadBufferSB->setValue(stream.kcpSettings.readBufferSize); kcpUploadCapacSB->setValue(stream.kcpSettings.uplinkCapacity); kcpDownCapacitySB->setValue(stream.kcpSettings.downlinkCapacity); kcpWriteBufferSB->setValue(stream.kcpSettings.writeBufferSize); kcpSeedTxt->setText(stream.kcpSettings.seed); } // DS { dsPathTxt->setText(stream.dsSettings.path); } // QUIC { quicKeyTxt->setText(stream.quicSettings.key); quicSecurityCB->setCurrentText(stream.quicSettings.security); quicHeaderTypeCB->setCurrentText(stream.quicSettings.header.type); } // gRPC { grpcServiceNameTxt->setText(stream.grpcSettings.serviceName); grpcModeCB->setCurrentText(stream.grpcSettings.multiMode ? "multi" : "gun"); } // SOCKOPT { tProxyCB->setCurrentText(stream.sockopt.tproxy); tcpFastOpenCB->setChecked(stream.sockopt.tcpFastOpen); soMarkSpinBox->setValue(stream.sockopt.mark); tcpKeepAliveIntervalSpinBox->setValue(stream.sockopt.tcpKeepAliveInterval); } } void StreamSettingsWidget::on_httpPathTxt_textEdited(const QString &arg1) { stream.httpSettings.path = arg1; } void StreamSettingsWidget::on_httpHostTxt_textChanged() { const auto hosts = httpHostTxt->toPlainText().replace("\r", "").split("\n"); stream.httpSettings.host.clear(); for (const auto &host : hosts) { if (!host.trimmed().isEmpty()) stream.httpSettings.host.push_back(host.trimmed()); } } void StreamSettingsWidget::on_wsHeadersTxt_textChanged() { const auto headers = SplitLines(wsHeadersTxt->toPlainText()); stream.wsSettings.headers.clear(); for (const auto &header : headers) { if (header.isEmpty()) continue; if (!header.contains("|")) { LOG("Header missing '|' separator"); RED(wsHeadersTxt); return; } const auto index = header.indexOf("|"); auto key = header.left(index); auto value = header.right(header.length() - index - 1); stream.wsSettings.headers[key] = value; } BLACK(wsHeadersTxt); } void StreamSettingsWidget::on_tcpRequestDefBtn_clicked() { tcpRequestTxt->clear(); tcpRequestTxt->setPlainText(JsonToString(HTTPRequestObject().toJson())); stream.tcpSettings.header.request = HTTPRequestObject(); } void StreamSettingsWidget::on_tcpRespDefBtn_clicked() { tcpRespTxt->clear(); tcpRespTxt->setPlainText(JsonToString(HTTPResponseObject().toJson())); stream.tcpSettings.header.response = HTTPResponseObject(); } void StreamSettingsWidget::on_soMarkSpinBox_valueChanged(int arg1) { stream.sockopt.mark = arg1; } void StreamSettingsWidget::on_tcpFastOpenCB_stateChanged(int arg1) { stream.sockopt.tcpFastOpen = arg1 == Qt::Checked; } void StreamSettingsWidget::on_tProxyCB_currentIndexChanged(int arg1) { stream.sockopt.tproxy = tProxyCB->itemText(arg1); } void StreamSettingsWidget::on_quicSecurityCB_currentIndexChanged(int arg1) { stream.quicSettings.security = quicSecurityCB->itemText(arg1); } void StreamSettingsWidget::on_quicKeyTxt_textEdited(const QString &arg1) { stream.quicSettings.key = arg1; } void StreamSettingsWidget::on_quicHeaderTypeCB_currentIndexChanged(int arg1) { stream.quicSettings.header.type = quicHeaderTypeCB->itemText(arg1); } void StreamSettingsWidget::on_tcpHeaderTypeCB_currentIndexChanged(int arg1) { stream.tcpSettings.header.type = tcpHeaderTypeCB->itemText(arg1); } void StreamSettingsWidget::on_wsPathTxt_textEdited(const QString &arg1) { stream.wsSettings.path = arg1; } void StreamSettingsWidget::on_kcpMTU_valueChanged(int arg1) { stream.kcpSettings.mtu = arg1; } void StreamSettingsWidget::on_kcpTTI_valueChanged(int arg1) { stream.kcpSettings.tti = arg1; } void StreamSettingsWidget::on_kcpUploadCapacSB_valueChanged(int arg1) { stream.kcpSettings.uplinkCapacity = arg1; } void StreamSettingsWidget::on_kcpCongestionCB_stateChanged(int arg1) { stream.kcpSettings.congestion = arg1 == Qt::Checked; } void StreamSettingsWidget::on_kcpDownCapacitySB_valueChanged(int arg1) { stream.kcpSettings.downlinkCapacity = arg1; } void StreamSettingsWidget::on_kcpReadBufferSB_valueChanged(int arg1) { stream.kcpSettings.readBufferSize = arg1; } void StreamSettingsWidget::on_kcpWriteBufferSB_valueChanged(int arg1) { stream.kcpSettings.writeBufferSize = arg1; } void StreamSettingsWidget::on_kcpHeaderType_currentIndexChanged(int arg1) { stream.kcpSettings.header.type = kcpHeaderType->itemText(arg1); } void StreamSettingsWidget::on_kcpSeedTxt_textEdited(const QString &arg1) { stream.kcpSettings.seed = arg1; } void StreamSettingsWidget::on_dsPathTxt_textEdited(const QString &arg1) { stream.dsSettings.path = arg1; } void StreamSettingsWidget::on_tcpRequestEditBtn_clicked() { JsonEditor w(JsonFromString(tcpRequestTxt->toPlainText()), this); auto rJson = w.OpenEditor(); tcpRequestTxt->setPlainText(JsonToString(rJson)); auto tcpReqObject = HTTPRequestObject::fromJson(rJson); stream.tcpSettings.header.request = tcpReqObject; } void StreamSettingsWidget::on_tcpResponseEditBtn_clicked() { JsonEditor w(JsonFromString(tcpRespTxt->toPlainText()), this); auto rJson = w.OpenEditor(); tcpRespTxt->setPlainText(JsonToString(rJson)); auto tcpRspObject = HTTPResponseObject::fromJson(rJson); stream.tcpSettings.header.response = tcpRspObject; } void StreamSettingsWidget::on_transportCombo_currentIndexChanged(int arg1) { stream.network = transportCombo->itemText(arg1); v2rayStackView->setCurrentIndex(arg1); } void StreamSettingsWidget::on_securityTypeCB_currentIndexChanged(int arg1) { stream.security = securityTypeCB->itemText(arg1).toLower(); } // // Dirty hack, since XTLSSettings are the same as TLSSettings (Split them if required in the future) // void StreamSettingsWidget::on_serverNameTxt_textEdited(const QString &arg1) { stream.tlsSettings.serverName = arg1.trimmed(); stream.xtlsSettings.serverName = arg1.trimmed(); } void StreamSettingsWidget::on_allowInsecureCB_stateChanged(int arg1) { stream.tlsSettings.allowInsecure = arg1 == Qt::Checked; stream.xtlsSettings.allowInsecure = arg1 == Qt::Checked; } void StreamSettingsWidget::on_enableSessionResumptionCB_stateChanged(int arg1) { stream.tlsSettings.enableSessionResumption = arg1 == Qt::Checked; stream.xtlsSettings.enableSessionResumption = arg1 == Qt::Checked; } void StreamSettingsWidget::on_alpnTxt_textEdited(const QString &arg1) { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) stream.tlsSettings.alpn = arg1.split('|', Qt::SplitBehaviorFlags::SkipEmptyParts); stream.xtlsSettings.alpn = arg1.split('|', Qt::SplitBehaviorFlags::SkipEmptyParts); #else stream.tlsSettings.alpn = arg1.split('|', QString::SkipEmptyParts); stream.xtlsSettings.alpn = arg1.split('|', QString::SkipEmptyParts); #endif } void StreamSettingsWidget::on_disableSystemRoot_stateChanged(int arg1) { stream.tlsSettings.disableSystemRoot = arg1; stream.xtlsSettings.disableSystemRoot = arg1; } void StreamSettingsWidget::on_openCertEditorBtn_clicked() { } void StreamSettingsWidget::on_grpcServiceNameTxt_textEdited(const QString &arg1) { stream.grpcSettings.serviceName = arg1; } void StreamSettingsWidget::on_grpcModeCB_currentIndexChanged(int arg1) { stream.grpcSettings.multiMode = grpcModeCB->itemText(arg1).toLower() == "multi"; } void StreamSettingsWidget::on_wsEarlyDataSB_valueChanged(int arg1) { stream.wsSettings.maxEarlyData = arg1; } void StreamSettingsWidget::on_wsBrowserForwardCB_stateChanged(int arg1) { stream.wsSettings.useBrowserForwarding = arg1 == Qt::Checked; } void StreamSettingsWidget::on_pinnedPeerCertificateChainSha256Btn_clicked() { ChainSha256Editor ed(this, stream.tlsSettings.pinnedPeerCertificateChainSha256); if (ed.exec() == QDialog::Accepted) { stream.tlsSettings.pinnedPeerCertificateChainSha256 = QList<QString>(ed); } } void StreamSettingsWidget::on_wsEarlyDataHeaderNameCB_currentIndexChanged(int arg1) { stream.wsSettings.earlyDataHeaderName = wsEarlyDataHeaderNameCB->itemText(arg1); } void StreamSettingsWidget::on_httpMethodCB_currentTextChanged(const QString &arg1) { stream.httpSettings.method = arg1; } void StreamSettingsWidget::on_tcpKeepAliveIntervalSpinBox_valueChanged(int arg1) { stream.sockopt.tcpKeepAliveInterval = arg1; } void StreamSettingsWidget::on_httpHeadersDefBtn_clicked() { httpHeadersTxt->clear(); httpHeadersTxt->setPlainText(JsonToString(HttpObject().toJson()["headers"].toObject())); stream.httpSettings.headers = HttpObject().headers; } void StreamSettingsWidget::on_httpHeadersEditBtn_clicked() { JsonEditor w(JsonFromString(httpHeadersTxt->toPlainText()), this); auto rJson = w.OpenEditor(); httpHeadersTxt->setPlainText(JsonToString(rJson)); auto json = HttpObject().toJson(); json["headers"] = rJson; stream.httpSettings.headers = HttpObject::fromJson(json).headers; }
12,945
C++
.cpp
340
33.817647
150
0.714661
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,175
ConnectionItemWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/ConnectionItemWidget.cpp
#include "ConnectionItemWidget.hpp" #include "core/handler/ConfigHandler.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" #include <QStyleFactory> #define QV_MODULE_NAME "ConnectionItemWidget" ConnectionItemWidget::ConnectionItemWidget(QWidget *parent) : QWidget(parent), connectionId(NullConnectionId), groupId(NullGroupId) { setupUi(this); connect(ConnectionManager, &QvConfigHandler::OnConnected, this, &ConnectionItemWidget::OnConnected); connect(ConnectionManager, &QvConfigHandler::OnDisconnected, this, &ConnectionItemWidget::OnDisConnected); connect(ConnectionManager, &QvConfigHandler::OnStatsAvailable, this, &ConnectionItemWidget::OnConnectionStatsArrived); connect(ConnectionManager, &QvConfigHandler::OnLatencyTestStarted, this, &ConnectionItemWidget::OnLatencyTestStart); connect(ConnectionManager, &QvConfigHandler::OnLatencyTestFinished, this, &ConnectionItemWidget::OnLatencyTestFinished); } ConnectionItemWidget::ConnectionItemWidget(const ConnectionGroupPair &id, QWidget *parent) : ConnectionItemWidget(parent) { connectionId = id.connectionId; groupId = id.groupId; originalItemName = GetDisplayName(id.connectionId); // indentSpacer->changeSize(10, indentSpacer->sizeHint().height()); // auto latency = GetConnectionLatency(id.connectionId); latencyLabel->setText(latency == LATENCY_TEST_VALUE_NODATA ? // tr("Not Tested") : // (latency == LATENCY_TEST_VALUE_ERROR ? // tr("Error") : // (QSTRN(latency) + " ms"))); // // connTypeLabel->setText(GetConnectionProtocolString(id.connectionId).toUpper()); auto [uplink, downlink] = GetConnectionUsageAmount(connectionId); dataLabel->setText(FormatBytes(uplink) + " / " + FormatBytes(downlink)); // if (ConnectionManager->IsConnected(id)) { emit RequestWidgetFocus(this); } // Fake trigger OnConnectionItemRenamed(id.connectionId, "", originalItemName); connect(ConnectionManager, &QvConfigHandler::OnConnectionRenamed, this, &ConnectionItemWidget::OnConnectionItemRenamed); // // Rename events connect(renameTxt, &QLineEdit::returnPressed, this, &ConnectionItemWidget::on_doRenameBtn_clicked); connect(ConnectionManager, &QvConfigHandler::OnConnectionModified, this, &ConnectionItemWidget::OnConnectionModified); } // ======================================= Initialisation for root nodes. ConnectionItemWidget::ConnectionItemWidget(const GroupId &id, QWidget *parent) : ConnectionItemWidget(parent) { layout()->removeWidget(connTypeLabel); layout()->removeWidget(dataLabel); delete connTypeLabel; delete dataLabel; // delete doRenameBtn; delete renameTxt; // groupId = id; originalItemName = GetDisplayName(id); RecalculateConnectionsCount(); // auto font = connNameLabel->font(); font.setBold(true); connNameLabel->setFont(font); // OnGroupItemRenamed(id, "", originalItemName); connect(ConnectionManager, &QvConfigHandler::OnConnectionCreated, this, &ConnectionItemWidget::RecalculateConnectionsCount); connect(ConnectionManager, &QvConfigHandler::OnConnectionModified, this, &ConnectionItemWidget::RecalculateConnectionsCount); connect(ConnectionManager, &QvConfigHandler::OnConnectionLinkedWithGroup, this, &ConnectionItemWidget::RecalculateConnectionsCount); connect(ConnectionManager, &QvConfigHandler::OnSubscriptionAsyncUpdateFinished, this, &ConnectionItemWidget::RecalculateConnectionsCount); connect(ConnectionManager, &QvConfigHandler::OnConnectionRemovedFromGroup, this, &ConnectionItemWidget::RecalculateConnectionsCount); // connect(ConnectionManager, &QvConfigHandler::OnGroupRenamed, this, &ConnectionItemWidget::OnGroupItemRenamed); } void ConnectionItemWidget::BeginConnection() { if (IsConnection()) { ConnectionManager->StartConnection({ connectionId, groupId }); } else { LOG("Trying to start a non-connection entry, this call is illegal."); } } bool ConnectionItemWidget::NameMatched(const QString &arg) const { auto searchString = arg.toLower(); auto isGroupNameMatched = GetDisplayName(groupId).toLower().contains(arg); if (IsConnection()) { return isGroupNameMatched || GetDisplayName(connectionId).toLower().contains(searchString); } else { return isGroupNameMatched; } } void ConnectionItemWidget::RecalculateConnectionsCount() { auto connectionCount = ConnectionManager->GetConnections(groupId).count(); latencyLabel->setText(QSTRN(connectionCount) + " " + (connectionCount < 2 ? tr("connection") : tr("connections"))); OnGroupItemRenamed(groupId, "", originalItemName); } void ConnectionItemWidget::OnConnected(const ConnectionGroupPair &id) { if (id == ConnectionGroupPair{ connectionId, groupId }) { connNameLabel->setText("● " + originalItemName); DEBUG("ConnectionItemWidgetOnConnected signal received for: " + id.connectionId.toString()); emit RequestWidgetFocus(this); } } void ConnectionItemWidget::OnDisConnected(const ConnectionGroupPair &id) { if (id == ConnectionGroupPair{ connectionId, groupId }) { connNameLabel->setText(originalItemName); } } void ConnectionItemWidget::OnConnectionStatsArrived(const ConnectionGroupPair &id, const QMap<StatisticsType, QvStatsSpeedData> &data) { if (id.connectionId == connectionId) { dataLabel->setText(FormatBytes(data[CurrentStatAPIType].second.first) + " / " + FormatBytes(data[CurrentStatAPIType].second.second)); } } void ConnectionItemWidget::OnConnectionModified(const ConnectionId &id) { if (connectionId == id) connTypeLabel->setText(GetConnectionProtocolString(id).toUpper()); } void ConnectionItemWidget::OnLatencyTestStart(const ConnectionId &id) { if (id == connectionId) { latencyLabel->setText(tr("Testing...")); } } void ConnectionItemWidget::OnLatencyTestFinished(const ConnectionId &id, const int average) { if (id == connectionId) { latencyLabel->setText(average == LATENCY_TEST_VALUE_ERROR ? tr("Error") : QSTRN(average) + tr("ms")); } } void ConnectionItemWidget::CancelRename() { stackedWidget->setCurrentIndex(0); } void ConnectionItemWidget::BeginRename() { if (IsConnection()) { stackedWidget->setCurrentIndex(1); renameTxt->setStyle(QStyleFactory::create("Fusion")); renameTxt->setStyleSheet("background-color: " + this->palette().color(this->backgroundRole()).name(QColor::HexRgb)); renameTxt->setText(originalItemName); renameTxt->setFocus(); } } ConnectionItemWidget::~ConnectionItemWidget() { } void ConnectionItemWidget::on_doRenameBtn_clicked() { if (renameTxt->text().isEmpty()) return; if (connectionId == NullConnectionId) ConnectionManager->RenameGroup(groupId, renameTxt->text()); else ConnectionManager->RenameConnection(connectionId, renameTxt->text()); stackedWidget->setCurrentIndex(0); } void ConnectionItemWidget::OnConnectionItemRenamed(const ConnectionId &id, const QString &, const QString &newName) { if (id == connectionId) { connNameLabel->setText((ConnectionManager->IsConnected({ connectionId, groupId }) ? "● " : "") + newName); originalItemName = newName; const auto conn = ConnectionManager->GetConnectionMetaObject(connectionId); this->setToolTip(newName + // NEWLINE + tr("Last Connected: ") + timeToString(conn.lastConnected) + // NEWLINE + tr("Last Updated: ") + timeToString(conn.lastUpdatedDate)); } } void ConnectionItemWidget::OnGroupItemRenamed(const GroupId &id, const QString &, const QString &newName) { if (id == groupId) { originalItemName = newName; connNameLabel->setText(newName); const auto grp = ConnectionManager->GetGroupMetaObject(id); this->setToolTip(newName + NEWLINE + // (grp.isSubscription ? (tr("Subscription") + NEWLINE) : "") + // tr("Last Updated: ") + timeToString(grp.lastUpdatedDate)); } }
8,497
C++
.cpp
198
37.434343
142
0.708726
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,176
RouteSettingsMatrix.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/RouteSettingsMatrix.cpp
#include "RouteSettingsMatrix.hpp" #include "components/geosite/QvGeositeReader.hpp" #include "components/route/RouteSchemeIO.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" #include <QFileDialog> #include <QInputDialog> #define QV_MODULE_NAME "RouteSettingsMatrix" RouteSettingsMatrixWidget::RouteSettingsMatrixWidget(const QString &assetsDirPath, QWidget *parent) : QWidget(parent), assetsDirPath(assetsDirPath) { setupUi(this); // builtInSchemesMenu = new QMenu(this); builtInSchemesMenu->addActions(this->getBuiltInSchemes()); builtInSchemeBtn->setMenu(builtInSchemesMenu); // auto sourceStringsDomain = ReadGeoSiteFromFile(assetsDirPath + "/geosite.dat"); directDomainTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this); proxyDomainTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this); blockDomainTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this); // auto sourceStringsIP = ReadGeoSiteFromFile(assetsDirPath + "/geoip.dat"); directIPTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this); proxyIPTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this); blockIPTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this); // directTxtLayout->addWidget(directDomainTxt, 0, 0); proxyTxtLayout->addWidget(proxyDomainTxt, 0, 0); blockTxtLayout->addWidget(blockDomainTxt, 0, 0); // directIPLayout->addWidget(directIPTxt, 0, 0); proxyIPLayout->addWidget(proxyIPTxt, 0, 0); blockIPLayout->addWidget(blockIPTxt, 0, 0); } /** * @brief RouteSettingsMatrixWidget::getBuiltInSchemes * @return */ QList<QAction *> RouteSettingsMatrixWidget::getBuiltInSchemes() { QList<QAction *> list; list.append(this->schemeToAction(tr("empty scheme"), emptyScheme)); list.append(this->schemeToAction(tr("empty scheme (no ads)"), noAdsScheme)); return list; } QAction *RouteSettingsMatrixWidget::schemeToAction(const QString &name, const QvConfig_Route &scheme) { QAction *action = new QAction(this); action->setText(name); connect(action, &QAction::triggered, [this, &scheme] { this->SetRouteConfig(scheme); }); return action; } void RouteSettingsMatrixWidget::SetRouteConfig(const QvConfig_Route &conf) { domainStrategyCombo->setCurrentText(conf.domainStrategy); domainMatcherCombo->setCurrentIndex(conf.domainMatcher == "mph" ? 1 : 0); // directDomainTxt->setPlainText(conf.domains.direct.join(NEWLINE)); proxyDomainTxt->setPlainText(conf.domains.proxy.join(NEWLINE)); blockDomainTxt->setPlainText(conf.domains.block.join(NEWLINE)); // blockIPTxt->setPlainText(conf.ips.block.join(NEWLINE)); directIPTxt->setPlainText(conf.ips.direct.join(NEWLINE)); proxyIPTxt->setPlainText(conf.ips.proxy.join(NEWLINE)); } QvConfig_Route RouteSettingsMatrixWidget::GetRouteConfig() const { QvConfig_Route conf; // Workaround for translation const auto index = domainMatcherCombo->currentIndex(); conf.domainMatcher = index == 0 ? "" : "mph"; conf.domainStrategy = domainStrategyCombo->currentText(); conf.domains.block = SplitLines(blockDomainTxt->toPlainText().replace(" ", "")); conf.domains.direct = SplitLines(directDomainTxt->toPlainText().replace(" ", "")); conf.domains.proxy = SplitLines(proxyDomainTxt->toPlainText().replace(" ", "")); // conf.ips.block = SplitLines(blockIPTxt->toPlainText().replace(" ", "")); conf.ips.direct = SplitLines(directIPTxt->toPlainText().replace(" ", "")); conf.ips.proxy = SplitLines(proxyIPTxt->toPlainText().replace(" ", "")); return conf; } RouteSettingsMatrixWidget::~RouteSettingsMatrixWidget() { } /** * @brief RouteSettingsMatrixWidget::on_importSchemeBtn_clicked * @author DuckSoft <realducksoft@gmail.com> * @todo add some debug output */ void RouteSettingsMatrixWidget::on_importSchemeBtn_clicked() { try { // open up the file dialog and choose a file. auto filePath = this->openFileDialog(); if (!filePath) return; // read the file and parse back to struct. // if error occurred on parsing, an exception will be thrown. auto content = StringFromFile(*filePath); auto scheme = Qv2rayRouteScheme::fromJson(JsonFromString(content)); // show the information of this scheme to user, // and ask user if he/she wants to import and apply this. auto strPrompt = tr("Import scheme '%1' made by '%2'? \r\n Description: %3").arg(scheme.name, scheme.author, scheme.description); auto decision = QvMessageBoxAsk(this, tr("Importing Scheme"), strPrompt); // if user don't want to import, just leave. if (decision != Yes) return; // write the scheme onto the window this->SetRouteConfig(static_cast<QvConfig_Route>(scheme)); // done LOG("Imported route config: " + scheme.name + " by: " + scheme.author); } catch (std::exception &e) { LOG("Exception: ", e.what()); // TODO: Give some error as Notification } } /** * @brief RouteSettingsMatrixWidget::on_exportSchemeBtn_clicked * @author DuckSoft <realducksoft@gmail.com> */ void RouteSettingsMatrixWidget::on_exportSchemeBtn_clicked() { try { // parse the config back from the window components auto config = this->GetRouteConfig(); // init some constants const auto dialogTitle = tr("Exporting Scheme"); // scheme name? bool ok = false; auto schemeName = QInputDialog::getText(this, dialogTitle, tr("Scheme name:"), QLineEdit::Normal, tr("Unnamed Scheme"), &ok); if (!ok) return; // scheme author? auto schemeAuthor = QInputDialog::getText(this, dialogTitle, tr("Author:"), QLineEdit::Normal, "Anonymous <mystery@example.com>", &ok); if (!ok) return; // scheme description? auto schemeDescription = QInputDialog::getText(this, dialogTitle, tr("Description:"), QLineEdit::Normal, tr("The author is too lazy to leave a comment")); if (!ok) return; // where to save? auto savePath = this->saveFileDialog(); if (!savePath) return; // construct the data structure Qv2rayRouteScheme scheme; scheme.name = schemeName; scheme.author = schemeAuthor; scheme.description = schemeDescription; scheme.domainStrategy = config.domainStrategy; scheme.ips = config.ips; scheme.domains = config.domains; // serialize and write out auto content = JsonToString(scheme.toJson()); StringToFile(content, *savePath); // done // TODO: Give some success as Notification QvMessageBoxInfo(this, dialogTitle, tr("Your route scheme has been successfully exported!")); } catch (...) { // TODO: Give some error as Notification } } /** * @brief opens a save dialog and asks user to specify the save path. * @return the selected file path, if any * @author DuckSoft <realducksoft@gmail.com> */ std::optional<QString> RouteSettingsMatrixWidget::saveFileDialog() { QFileDialog dialog; dialog.setFileMode(QFileDialog::AnyFile); dialog.setOption(QFileDialog::Option::DontConfirmOverwrite, false); dialog.setNameFilter(tr("QvRoute Schemes(*.json)")); dialog.setAcceptMode(QFileDialog::AcceptMode::AcceptSave); if (!dialog.exec() || dialog.selectedFiles().length() != 1) { return std::nullopt; } return dialog.selectedFiles().first(); } /** * @brief opens up a dialog and asks user to choose a scheme file. * @return the selected file path, if any * @author DuckSoft <realducksoft@gmail.com> */ std::optional<QString> RouteSettingsMatrixWidget::openFileDialog() { QFileDialog dialog; dialog.setFileMode(QFileDialog::ExistingFile); dialog.setNameFilter(tr("QvRoute Schemes(*.json)")); if (!dialog.exec() || dialog.selectedFiles().length() != 1) { return std::nullopt; } return dialog.selectedFiles().first(); }
8,205
C++
.cpp
203
35.083744
147
0.699724
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,177
ConnectionInfoWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/ConnectionInfoWidget.cpp
#include "ConnectionInfoWidget.hpp" #include "core/CoreUtils.hpp" #include "core/connection/Serialization.hpp" #include "ui/common/QRCodeHelper.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" constexpr auto INDEX_CONNECTION = 0; constexpr auto INDEX_GROUP = 1; QvMessageBusSlotImpl(ConnectionInfoWidget) { switch (msg) { MBRetranslateDefaultImpl; MBUpdateColorSchemeDefaultImpl; case HIDE_WINDOWS: case SHOW_WINDOWS: break; } } void ConnectionInfoWidget::updateColorScheme() { latencyBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ping_gauge"))); deleteBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); editBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("edit"))); editJsonBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("code"))); shareLinkTxt->setStyleSheet("border-bottom: 1px solid gray; border-radius: 0px; padding: 2px; background-color: " + this->palette().color(this->backgroundRole()).name(QColor::HexRgb)); groupSubsLinkTxt->setStyleSheet("border-bottom: 1px solid gray; border-radius: 0px; padding: 2px; background-color: " + this->palette().color(this->backgroundRole()).name(QColor::HexRgb)); // auto isDarkTheme = GlobalConfig.uiConfig.useDarkTheme; qrPixmapBlured = BlurImage(ColorizeImage(qrPixmap, isDarkTheme ? QColor(Qt::black) : QColor(Qt::white), 0.7), 35); qrLabel->setPixmap(IsComplexConfig(connectionId) ? QPixmap(":/assets/icons/qv2ray.png") : (isRealPixmapShown ? qrPixmap : qrPixmapBlured)); const auto isCurrentItem = KernelInstance->CurrentConnection().connectionId == connectionId; connectBtn->setIcon(QIcon(isCurrentItem ? QV2RAY_COLORSCHEME_FILE("stop") : QV2RAY_COLORSCHEME_FILE("start"))); } ConnectionInfoWidget::ConnectionInfoWidget(QWidget *parent) : QWidget(parent) { setupUi(this); // QvMessageBusConnect(ConnectionInfoWidget); updateColorScheme(); // shareLinkTxt->setAutoFillBackground(true); shareLinkTxt->setCursor(QCursor(Qt::CursorShape::IBeamCursor)); shareLinkTxt->installEventFilter(this); groupSubsLinkTxt->installEventFilter(this); qrLabel->installEventFilter(this); // connect(ConnectionManager, &QvConfigHandler::OnConnected, this, &ConnectionInfoWidget::OnConnected); connect(ConnectionManager, &QvConfigHandler::OnDisconnected, this, &ConnectionInfoWidget::OnDisConnected); connect(ConnectionManager, &QvConfigHandler::OnGroupRenamed, this, &ConnectionInfoWidget::OnGroupRenamed); connect(ConnectionManager, &QvConfigHandler::OnConnectionModified, this, &ConnectionInfoWidget::OnConnectionModified); connect(ConnectionManager, &QvConfigHandler::OnConnectionLinkedWithGroup, this, &ConnectionInfoWidget::OnConnectionModified_Pair); connect(ConnectionManager, &QvConfigHandler::OnConnectionRemovedFromGroup, this, &ConnectionInfoWidget::OnConnectionModified_Pair); } void ConnectionInfoWidget::ShowDetails(const ConnectionGroupPair &_identifier) { this->groupId = _identifier.groupId; this->connectionId = _identifier.connectionId; bool isConnection = connectionId != NullConnectionId; // editBtn->setEnabled(isConnection); editJsonBtn->setEnabled(isConnection); connectBtn->setEnabled(isConnection); stackedWidget->setCurrentIndex(isConnection ? INDEX_CONNECTION : INDEX_GROUP); if (isConnection) { auto shareLink = ConvertConfigToString(_identifier); // shareLinkTxt->setText(shareLink); protocolLabel->setText(GetConnectionProtocolString(connectionId)); // groupLabel->setText(GetDisplayName(groupId, 175)); auto [protocol, host, port] = GetConnectionInfo(connectionId); Q_UNUSED(protocol) addressLabel->setText(host); portLabel->setNum(port); // shareLinkTxt->setCursorPosition(0); auto isDarkTheme = GlobalConfig.uiConfig.useDarkTheme; qrPixmap = QPixmap::fromImage(EncodeQRCode(shareLink, qrLabel->width() * devicePixelRatio())); // qrPixmapBlured = BlurImage(ColorizeImage(qrPixmap, isDarkTheme ? QColor(Qt::black) : QColor(Qt::white), 0.7), 35); // isRealPixmapShown = false; qrLabel->setPixmap(IsComplexConfig(connectionId) ? QPixmap(":/assets/icons/qv2ray.png") : qrPixmapBlured); qrLabel->setScaledContents(true); const auto isCurrentItem = KernelInstance->CurrentConnection().connectionId == connectionId; connectBtn->setIcon(QIcon(isCurrentItem ? QV2RAY_COLORSCHEME_FILE("stop") : QV2RAY_COLORSCHEME_FILE("start"))); } else { connectBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("start"))); groupNameLabel->setText(GetDisplayName(groupId)); QStringList shareLinks; for (const auto &connection : ConnectionManager->GetConnections(groupId)) { shareLinks << ConvertConfigToString({ connection, groupId }, !GlobalConfig.uiConfig.useOldShareLinkFormat); } // auto complexCount = shareLinks.removeAll(QV2RAY_SERIALIZATION_COMPLEX_CONFIG_PLACEHOLDER); complexCount += shareLinks.removeAll(""); if (complexCount > 0) { shareLinks << "# " + tr("(Ignored %n complex config(s))", "", complexCount); } // groupShareTxt->setPlainText(shareLinks.join(NEWLINE)); const auto &groupMetaData = ConnectionManager->GetGroupMetaObject(groupId); groupSubsLinkTxt->setText(groupMetaData.isSubscription ? groupMetaData.subscriptionOption.address : tr("Not a subscription")); } } ConnectionInfoWidget::~ConnectionInfoWidget() { } void ConnectionInfoWidget::OnConnectionModified(const ConnectionId &id) { if (id == this->connectionId) ShowDetails({ id, groupId }); } void ConnectionInfoWidget::OnConnectionModified_Pair(const ConnectionGroupPair &id) { if (id.connectionId == this->connectionId && id.groupId == this->groupId) ShowDetails(id); } void ConnectionInfoWidget::OnGroupRenamed(const GroupId &id, const QString &oldName, const QString &newName) { Q_UNUSED(oldName) if (this->groupId == id) { groupNameLabel->setText(newName); groupLabel->setText(newName); } } void ConnectionInfoWidget::on_connectBtn_clicked() { if (ConnectionManager->IsConnected({ connectionId, groupId })) { ConnectionManager->StopConnection(); } else { ConnectionManager->StartConnection({ connectionId, groupId }); } } void ConnectionInfoWidget::on_editBtn_clicked() { emit OnEditRequested(connectionId); } void ConnectionInfoWidget::on_editJsonBtn_clicked() { emit OnJsonEditRequested(connectionId); } void ConnectionInfoWidget::on_deleteBtn_clicked() { if (QvMessageBoxAsk(this, tr("Delete an item"), tr("Are you sure to delete the current item?")) == Yes) { if (connectionId != NullConnectionId) { ConnectionManager->RemoveConnectionFromGroup(connectionId, groupId); } else { ConnectionManager->DeleteGroup(groupId); } } } bool ConnectionInfoWidget::eventFilter(QObject *object, QEvent *event) { if (shareLinkTxt->underMouse() && event->type() == QEvent::MouseButtonRelease) { if (!shareLinkTxt->hasSelectedText()) shareLinkTxt->selectAll(); } else if (groupSubsLinkTxt->underMouse() && event->type() == QEvent::MouseButtonRelease) { if (!groupSubsLinkTxt->hasSelectedText()) groupSubsLinkTxt->selectAll(); } else if (qrLabel->underMouse() && event->type() == QEvent::MouseButtonRelease) { qrLabel->setPixmap(IsComplexConfig(connectionId) ? QPixmap(":/assets/icons/qv2ray.png") : (isRealPixmapShown ? qrPixmapBlured : qrPixmap)); isRealPixmapShown = !isRealPixmapShown; } return QWidget::eventFilter(object, event); } void ConnectionInfoWidget::OnConnected(const ConnectionGroupPair &id) { if (id == ConnectionGroupPair{ connectionId, groupId }) { connectBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("stop"))); } } void ConnectionInfoWidget::OnDisConnected(const ConnectionGroupPair &id) { if (id == ConnectionGroupPair{ connectionId, groupId }) { connectBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("start"))); } } void ConnectionInfoWidget::on_latencyBtn_clicked() { if (connectionId != NullConnectionId) { ConnectionManager->StartLatencyTest(connectionId); } else { ConnectionManager->StartLatencyTest(groupId); } }
8,658
C++
.cpp
211
35.322275
147
0.716455
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,178
QvAutoCompleteTextEdit.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/QvAutoCompleteTextEdit.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "QvAutoCompleteTextEdit.hpp" #include <QAbstractItemModel> #include <QAbstractItemView> #include <QApplication> #include <QCompleter> #include <QKeyEvent> #include <QModelIndex> #include <QScrollBar> #include <QStringListModel> #include <QToolTip> #include <QtDebug> namespace Qv2ray::ui::widgets { AutoCompleteTextEdit::AutoCompleteTextEdit(const QString &prefix, const QStringList &sourceStrings, QWidget *parent) : QPlainTextEdit(parent) { this->prefix = prefix; this->setLineWrapMode(QPlainTextEdit::NoWrap); c = new QCompleter(this); c->setModel(new QStringListModel(sourceStrings, c)); c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); QObject::connect(c, QOverload<const QString &>::of(&QCompleter::activated), this, &AutoCompleteTextEdit::insertCompletion); } AutoCompleteTextEdit::~AutoCompleteTextEdit() { } void AutoCompleteTextEdit::insertCompletion(const QString &completion) { QTextCursor tc = textCursor(); int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); } QString AutoCompleteTextEdit::lineUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::LineUnderCursor); return tc.selectedText(); } QString AutoCompleteTextEdit::wordUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } void AutoCompleteTextEdit::focusInEvent(QFocusEvent *e) { if (c) c->setWidget(this); QPlainTextEdit::focusInEvent(e); } void AutoCompleteTextEdit::keyPressEvent(QKeyEvent *e) { const bool hasCtrlOrShiftModifier = e->modifiers().testFlag(Qt::ControlModifier) || e->modifiers().testFlag(Qt::ShiftModifier); const bool hasOtherModifiers = (e->modifiers() != Qt::NoModifier) && !hasCtrlOrShiftModifier; // has other modifiers // const bool isSpace = (e->modifiers().testFlag(Qt::ShiftModifier) || e->modifiers().testFlag(Qt::NoModifier)) // && e->key() == Qt::Key_Space; const bool isTab = (e->modifiers().testFlag(Qt::NoModifier) && e->key() == Qt::Key_Tab); const bool isOtherSpace = e->text() == " "; // if (isSpace || isTab || isOtherSpace) { QToolTip::showText(this->mapToGlobal(QPoint(0, 0)), tr("You can not input space characters here."), this, QRect{}, 2000); return; } // if (c && c->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: case Qt::Key_Tab: case Qt::Key_Backtab: e->ignore(); return; // let the completer do default behavior default: break; } } QPlainTextEdit::keyPressEvent(e); if (!c || (hasCtrlOrShiftModifier && e->text().isEmpty())) return; // if we have other modifiers, or the text is empty, or the line does not start with our prefix. if (hasOtherModifiers || e->text().isEmpty() || !lineUnderCursor().startsWith(prefix)) { c->popup()->hide(); return; } if (auto word = wordUnderCursor(); word != c->completionPrefix()) { c->setCompletionPrefix(word); c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); } QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); // popup it up! } } // namespace Qv2ray::ui::widgets
6,583
C++
.cpp
151
37.609272
145
0.65851
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,180
InboundSettingsWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/InboundSettingsWidget.cpp
#include "InboundSettingsWidget.hpp" InboundSettingsWidget::InboundSettingsWidget(QWidget *parent) : QWidget(parent) { setupUi(this); } QvMessageBusSlotImpl(InboundSettingsWidget) { switch (msg) { MBRetranslateDefaultImpl; case HIDE_WINDOWS: case SHOW_WINDOWS: break; default: break; } } void InboundSettingsWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } }
546
C++
.cpp
24
18.333333
79
0.696154
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,181
ChainEditorWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/complex/ChainEditorWidget.cpp
#include "ChainEditorWidget.hpp" #include "ui/widgets/node/NodeBase.hpp" constexpr auto GRAPH_GLOBAL_OFFSET_X = -20; constexpr auto GRAPH_GLOBAL_OFFSET_Y = -300; ChainEditorWidget::ChainEditorWidget(std::shared_ptr<NodeDispatcher> dispatcher, QWidget *parent) : QWidget(parent), dispatcher(dispatcher) { setupUi(this); QvMessageBusConnect(ChainEditorWidget); scene = new QtNodes::FlowScene(this); view = new QtNodes::FlowView(scene, this); view->scaleDown(); if (!viewWidget->layout()) { // The QWidget will take ownership of layout. viewWidget->setLayout(new QVBoxLayout()); } auto l = viewWidget->layout(); l->addWidget(view); l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); // connect(dispatcher.get(), &NodeDispatcher::OnChainedOutboundCreated, this, &ChainEditorWidget::OnDispatcherChainedOutboundCreated); connect(dispatcher.get(), &NodeDispatcher::OnChainedOutboundDeleted, this, &ChainEditorWidget::OnDispatcherChainedOutboundDeleted); connect(dispatcher.get(), &NodeDispatcher::OnChainedCreated, this, &ChainEditorWidget::OnDispatcherChainCreated); connect(dispatcher.get(), &NodeDispatcher::OnChainedDeleted, this, &ChainEditorWidget::OnDispatcherChainDeleted); connect(dispatcher.get(), &NodeDispatcher::OnObjectTagChanged, this, &ChainEditorWidget::OnDispatcherObjectTagChanged); // connect(dispatcher.get(), &NodeDispatcher::OnFullConfigLoadCompleted, [this]() { if (!chains.isEmpty()) currentChain = chains.first(); ShowChainLinkedList(); }); // connect(dispatcher.get(), &NodeDispatcher::RequestEditChain, this, &ChainEditorWidget::BeginEditChain); // connect(scene, &QtNodes::FlowScene::connectionCreated, this, &ChainEditorWidget::OnSceneConnectionCreated); connect(scene, &QtNodes::FlowScene::connectionDeleted, this, &ChainEditorWidget::OnSceneConnectionRemoved); } QvMessageBusSlotImpl(ChainEditorWidget) { switch (msg) { MBRetranslateDefaultImpl; MBUpdateColorSchemeDefaultImpl; default: break; } } void ChainEditorWidget::OnDispatcherChainedOutboundCreated(std::shared_ptr<OutboundObjectMeta> data, QtNodes::Node &node) { outboundNodes[data->getDisplayName()] = node.id(); const auto outboundCount = outboundNodes.count(); const static int offsets[]{ 300, 0, -300 }; auto pos = this->pos(); pos.setX(pos.x() + GRAPH_GLOBAL_OFFSET_X + offsets[outboundCount % 3]); pos.setY(pos.y() + outboundCount * 100 + GRAPH_GLOBAL_OFFSET_Y); scene->setNodePosition(node, pos); } void ChainEditorWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void ChainEditorWidget::BeginEditChain(const QString &chain) { const auto index = chainComboBox->findText(chain); if (index >= 0) { // Triggers the on_chainComboBox_currentIndexChanged function. chainComboBox->setCurrentIndex(index); } } void ChainEditorWidget::ShowChainLinkedList() { if (dispatcher->IsNodeConstructing()) return; connectionSignalBlocked = true; const auto connections = scene->connections(); for (const auto &connection : connections) { scene->deleteConnection(*connection.second); } // // Warn: Some outbound node MAY NOT be created YET! if (!currentChain) return; const auto &outbounds = currentChain->outboundTags; for (auto index = 0; index < outbounds.count() - 1; index++) { const auto &inTag = outbounds[index + 1]; const auto &outTag = outbounds[index]; bool hasErrorOccured = false; for (const auto &tag : { inTag, outTag }) { if (!outboundNodes.contains(tag)) { QvMessageBoxWarn(this, tr("Chain Editor"), tr("Could not find outbound tag: %1, The chain may be corrupted").arg(tag)); hasErrorOccured = true; } } if (!hasErrorOccured) { const auto &nodeIn = scene->node(outboundNodes[inTag]); const auto &nodeOut = scene->node(outboundNodes[outTag]); scene->createConnection(*nodeIn, 0, *nodeOut, 0); } } connectionSignalBlocked = false; } std::tuple<bool, QString, QStringList> ChainEditorWidget::VerifyChainLinkedList(const QUuid &ignoredConnectionId) { QList<QString> resultList; auto conns = scene->connections(); bool needReIterate = true; const auto expectedChainLength = conns.size() + uint(ignoredConnectionId.isNull()); for (auto i = 0u; i < expectedChainLength; i++) { auto iter = conns.begin(); // Loop against all items. while (iter != conns.end()) { #define NEED_ITERATE(x) \ needReIterate = x; \ continue const auto &id = iter->first; const auto &connection = iter->second; const auto &nodeInId = connection->getNode(QtNodes::PortType::In)->id(); const auto &nodeOutId = connection->getNode(QtNodes::PortType::Out)->id(); // const auto &nextTag = outboundNodes.key(nodeInId); const auto &previousTag = outboundNodes.key(nodeOutId); // // If we are ignoring this node. if (id == ignoredConnectionId) { iter++; NEED_ITERATE(false); } // if (resultList.isEmpty()) { iter++; resultList << previousTag << nextTag; NEED_ITERATE(false); } if (resultList.last() != previousTag && resultList.first() != nextTag) { iter++; NEED_ITERATE(true); // return std::make_tuple(false, tr("Two different chains detected."), QStringList()); } if (resultList.contains(previousTag) && resultList.contains(nextTag)) { iter++; NEED_ITERATE(true); // return std::make_tuple(false, tr("Looped chain detected."), QStringList()); } if (resultList.last() == previousTag) { resultList << nextTag; iter = conns.erase(iter); NEED_ITERATE(false); } if (resultList.front() == nextTag) { resultList.prepend(previousTag); iter = conns.erase(iter); NEED_ITERATE(false); } #undef NEED_ITERATE } if ((ulong) resultList.count() == expectedChainLength) { return { true, tr("OK"), resultList }; } } return { false, tr("There's an error in your connection."), resultList }; } void ChainEditorWidget::on_chainComboBox_currentIndexChanged(int arg1) { currentChain = chains[chainComboBox->itemText(arg1)]; ShowChainLinkedList(); } void ChainEditorWidget::TrySaveChainOutboudData(const QUuid &ignoredConnectionId) { if (!currentChain) { QvMessageBoxWarn(this, tr("Chain Editor"), tr("Please Select a Chain")); return; } const auto &[result, errMessage, list] = VerifyChainLinkedList(ignoredConnectionId); if (!result) { RED(statusLabel); statusLabel->setText(errMessage); } else { BLACK(statusLabel); statusLabel->setText(list.join(" >> ")); currentChain->outboundTags = list; } } void ChainEditorWidget::OnSceneConnectionCreated(const QtNodes::Connection &) { if (connectionSignalBlocked) return; TrySaveChainOutboudData(); } void ChainEditorWidget::OnSceneConnectionRemoved(const QtNodes::Connection &c) { if (connectionSignalBlocked) return; TrySaveChainOutboudData(c.id()); } void ChainEditorWidget::OnDispatcherChainedOutboundDeleted(const OutboundObjectMeta &data) { const auto displayName = data.getDisplayName(); if (outboundNodes.contains(displayName)) { scene->removeNode(*scene->node(outboundNodes[displayName])); outboundNodes.remove(displayName); } } void ChainEditorWidget::OnDispatcherChainCreated(std::shared_ptr<OutboundObjectMeta> data) { const auto displayName = data->getDisplayName(); chains[displayName] = data; chainComboBox->addItem(displayName); } void ChainEditorWidget::OnDispatcherChainDeleted(const OutboundObjectMeta &data) { const auto displayName = data.getDisplayName(); const auto index = chainComboBox->findText(displayName); chainComboBox->removeItem(index); chains.remove(displayName); } void ChainEditorWidget::OnDispatcherObjectTagChanged(ComplexTagNodeMode mode, const QString originalTag, const QString newTag) { if (mode == NODE_OUTBOUND) { // Simply compare if there is a match (Since no duplication of DisplayName should occur.) if (outboundNodes.contains(originalTag)) outboundNodes[newTag] = outboundNodes.take(originalTag); // Check Chains. if (chains.contains(originalTag)) chains[newTag] = chains.take(originalTag); const auto index = chainComboBox->findText(originalTag); if (index >= 0) { chainComboBox->setItemText(index, newTag); } for (const auto &chain : chains) { if (chain->outboundTags.contains(originalTag)) chain->outboundTags.replace(chain->outboundTags.indexOf(originalTag), newTag); } } }
9,900
C++
.cpp
262
30.522901
150
0.636014
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,182
RoutingEditorWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/widgets/complex/RoutingEditorWidget.cpp
#include "RoutingEditorWidget.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "ui/widgets/node/NodeBase.hpp" constexpr auto GRAPH_GLOBAL_OFFSET_X = -100; constexpr auto GRAPH_GLOBAL_OFFSET_Y = -100; RoutingEditorWidget::RoutingEditorWidget(std::shared_ptr<NodeDispatcher> dispatcher, QWidget *parent) : QWidget(parent), dispatcher(dispatcher) { setupUi(this); QvMessageBusConnect(RoutingEditorWidget); // scene = new QtNodes::FlowScene(this); connect(dispatcher.get(), &NodeDispatcher::OnInboundCreated, this, &RoutingEditorWidget::OnDispatcherInboundCreated); connect(dispatcher.get(), &NodeDispatcher::OnOutboundCreated, this, &RoutingEditorWidget::OnDispatcherOutboundCreated); connect(dispatcher.get(), &NodeDispatcher::OnRuleCreated, this, &RoutingEditorWidget::OnDispatcherRuleCreated); // view = new QtNodes::FlowView(scene, this); view->scaleDown(); if (!viewWidget->layout()) { // The QWidget will take ownership of layout. viewWidget->setLayout(new QVBoxLayout()); } auto l = viewWidget->layout(); l->addWidget(view); l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); } void RoutingEditorWidget::updateColorScheme() { addRouteBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); delBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); } QvMessageBusSlotImpl(RoutingEditorWidget) { switch (msg) { MBRetranslateDefaultImpl; MBUpdateColorSchemeDefaultImpl; default: break; } } void RoutingEditorWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void RoutingEditorWidget::OnDispatcherInboundCreated(std::shared_ptr<INBOUND>, QtNodes::Node &node) { QPoint pos{ 0 + GRAPH_GLOBAL_OFFSET_X, dispatcher->InboundsCount() * 130 + GRAPH_GLOBAL_OFFSET_Y }; scene->setNodePosition(node, pos); } void RoutingEditorWidget::OnDispatcherOutboundCreated(std::shared_ptr<OutboundObjectMeta>, QtNodes::Node &node) { auto pos = this->pos(); pos.setX(pos.x() + 850 + GRAPH_GLOBAL_OFFSET_X); pos.setY(pos.y() + dispatcher->OutboundsCount() * 120 + GRAPH_GLOBAL_OFFSET_Y); scene->setNodePosition(node, pos); } void RoutingEditorWidget::OnDispatcherRuleCreated(std::shared_ptr<RuleObject>, QtNodes::Node &node) { auto pos = this->pos(); pos.setX(pos.x() + 350 + GRAPH_GLOBAL_OFFSET_X); pos.setY(pos.y() + dispatcher->RulesCount() * 120 + GRAPH_GLOBAL_OFFSET_Y); scene->setNodePosition(node, pos); } void RoutingEditorWidget::on_addRouteBtn_clicked() { const auto _ = dispatcher->CreateRule({}); } void RoutingEditorWidget::on_delBtn_clicked() { if (scene->selectedNodes().empty()) { QvMessageBoxWarn(this, tr("Remove Items"), tr("Please select a node from the graph to continue.")); return; } const auto selecteNodes = scene->selectedNodes(); if (selecteNodes.empty()) { QvMessageBoxWarn(this, tr("Deleting a node"), tr("You need to select a node first")); return; } scene->removeNode(*selecteNodes.front()); }
3,199
C++
.cpp
88
32.170455
143
0.715392
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,183
NodeBase.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/NodeBase.cpp
#include "NodeBase.hpp" std::shared_ptr<NodeDataType> InboundNodeModel::dataType(PortType, PortIndex) const { return NODE_TYPE_INBOUND; } std::shared_ptr<NodeDataType> OutboundNodeModel::dataType(PortType, PortIndex) const { return NODE_TYPE_OUTBOUND; } std::shared_ptr<NodeDataType> RuleNodeModel::dataType(PortType portType, PortIndex) const { switch (portType) { case PortType::In: return NODE_TYPE_INBOUND; case PortType::Out: return NODE_TYPE_OUTBOUND; default: return {}; } } std::shared_ptr<NodeDataType> ChainOutboundNodeModel::dataType(PortType, PortIndex) const { return NODE_TYPE_CHAINED_OUTBOUND; } // // ******************************************************************************************* // unsigned int InboundNodeModel::nPorts(PortType portType) const { return portType == PortType::Out ? 1 : 0; } unsigned int OutboundNodeModel::nPorts(PortType portType) const { return portType == PortType::Out ? 0 : 1; } unsigned int RuleNodeModel::nPorts(PortType) const { return 1; } unsigned int ChainOutboundNodeModel::nPorts(PortType) const { return 1; } // // ******************************************************************************************* // std::shared_ptr<NodeData> InboundNodeModel::outData(PortIndex) { return std::make_shared<InboundNodeData>(dataptr); } std::shared_ptr<NodeData> OutboundNodeModel::outData(PortIndex) { return std::make_shared<OutboundNodeData>(dataptr); } std::shared_ptr<NodeData> RuleNodeModel::outData(PortIndex) { return std::make_shared<RuleNodeData>(dataptr); } std::shared_ptr<NodeData> ChainOutboundNodeModel::outData(PortIndex) { return std::make_shared<ChainOutboundData>(dataptr); } // // ******************************************************************************************* // // Forwards all data to std::vector-based override function. void InboundNodeModel::setInData(std::shared_ptr<NodeData> nodeData, PortIndex port) { setInData(std::vector{ nodeData }, port); } void OutboundNodeModel::setInData(std::shared_ptr<NodeData> nodeData, PortIndex port) { setInData(std::vector{ nodeData }, port); } void RuleNodeModel::setInData(std::shared_ptr<NodeData> nodeData, PortIndex port) { setInData(std::vector{ nodeData }, port); } void ChainOutboundNodeModel::setInData(std::shared_ptr<NodeData> nodeData, PortIndex port) { setInData(std::vector{ nodeData }, port); } // // ******************************************************************************************* // QtNodes::NodeDataModel::ConnectionPolicy InboundNodeModel::portInConnectionPolicy(PortIndex) const { // No port return NodeDataModel::ConnectionPolicy::One; } QtNodes::NodeDataModel::ConnectionPolicy OutboundNodeModel::portInConnectionPolicy(PortIndex) const { return NodeDataModel::ConnectionPolicy::Many; } QtNodes::NodeDataModel::ConnectionPolicy RuleNodeModel::portInConnectionPolicy(PortIndex) const { return NodeDataModel::ConnectionPolicy::Many; } QtNodes::NodeDataModel::ConnectionPolicy ChainOutboundNodeModel::portInConnectionPolicy(PortIndex) const { return NodeDataModel::ConnectionPolicy::One; } // // ******************************************************************************************* // QtNodes::NodeDataModel::ConnectionPolicy InboundNodeModel::portOutConnectionPolicy(PortIndex) const { return NodeDataModel::ConnectionPolicy::Many; } QtNodes::NodeDataModel::ConnectionPolicy OutboundNodeModel::portOutConnectionPolicy(PortIndex) const { // No port return NodeDataModel::ConnectionPolicy::One; } QtNodes::NodeDataModel::ConnectionPolicy RuleNodeModel::portOutConnectionPolicy(PortIndex) const { return NodeDataModel::ConnectionPolicy::One; } QtNodes::NodeDataModel::ConnectionPolicy ChainOutboundNodeModel::portOutConnectionPolicy(PortIndex) const { return NodeDataModel::ConnectionPolicy::One; }
3,910
C++
.cpp
120
30.333333
105
0.692532
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,184
NodeDispatcher.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/NodeDispatcher.cpp
#include "NodeDispatcher.hpp" #include "core/CoreUtils.hpp" #include "models/InboundNodeModel.hpp" #include "models/OutboundNodeModel.hpp" #include "models/RuleNodeModel.hpp" #include "utils/QvHelpers.hpp" #include <nodes/Node> #define QV_MODULE_NAME "NodeDispatcher" NodeDispatcher::NodeDispatcher(QObject *parent) : QObject(parent) { } NodeDispatcher::~NodeDispatcher() { } std::tuple<QMap<QString, INBOUND>, QMap<QString, RuleObject>, QMap<QString, OutboundObjectMeta>> NodeDispatcher::GetData() const { QMap<QString, INBOUND> _inbounds; QMap<QString, RuleObject> _rules; QMap<QString, OutboundObjectMeta> _outbounds; for (const auto &[key, val] : inbounds.toStdMap()) _inbounds[key] = *val; for (const auto &[key, val] : rules.toStdMap()) _rules[key] = *val; for (const auto &[key, val] : outbounds.toStdMap()) _outbounds[key] = *val; return std::make_tuple(_inbounds, _rules, _outbounds); } void NodeDispatcher::LoadFullConfig(const CONFIGROOT &root) { isOperationLocked = true; // Show connections in the node graph for (const auto &in : root["inbounds"].toArray()) { auto inObject = in.toObject(); if (inObject["tag"].toString().isEmpty()) inObject["tag"] = GenerateRandomString(); auto _ = CreateInbound(INBOUND(in.toObject())); } for (const auto &out : root["outbounds"].toArray()) { const auto meta = OutboundObjectMeta::loadFromOutbound(OUTBOUND(out.toObject())); if (meta.metaType == METAOUTBOUND_ORIGINAL && meta.realOutbound["tag"].toString().isEmpty()) meta.realOutbound["tag"] = GenerateRandomString(); auto _ = CreateOutbound(meta); } for (const auto &item : root["routing"].toObject()["rules"].toArray()) { auto _ = CreateRule(RuleObject::fromJson(item.toObject())); } for (const auto &balancer : root["routing"].toObject()["balancers"].toArray()) { const auto array = balancer.toObject()["selector"].toArray(); QStringList selector; for (const auto &item : array) { selector << item.toString(); } QString strategyType = balancer.toObject()["strategy"].toObject()["type"].toString("random"); const auto meta = make_balancer_outbound(selector, strategyType, balancer.toObject()["tag"].toString()); auto _ = CreateOutbound(meta); } for (const auto &rule : rules) { if (!ruleNodes.contains(rule->QV2RAY_RULE_TAG)) { LOG("Could not find rule: ", rule->QV2RAY_RULE_TAG); continue; } const auto ruleNodeId = ruleNodes[rule->QV2RAY_RULE_TAG]; // Process inbounds. for (const auto &inboundTag : rule->inboundTag) { if (!inboundNodes.contains(inboundTag)) { LOG("Could not find inbound: ", inboundTag); continue; } const auto inboundNodeId = inboundNodes.value(inboundTag); ruleScene->createConnection(*ruleScene->node(ruleNodeId), 0, *ruleScene->node(inboundNodeId), 0); } const auto &outboundTag = rule->outboundTag.isEmpty() ? rule->balancerTag : rule->outboundTag; if (!outboundNodes.contains(outboundTag)) { LOG("Could not find outbound: ", outboundTag); continue; } const auto &outboundNodeId = outboundNodes[outboundTag]; ruleScene->createConnection(*ruleScene->node(outboundNodeId), 0, *ruleScene->node(ruleNodeId), 0); } isOperationLocked = false; emit OnFullConfigLoadCompleted(); } void NodeDispatcher::OnNodeDeleted(const QtNodes::Node &node) { if (isOperationLocked) return; const auto nodeId = node.id(); bool isInbound = inboundNodes.values().contains(nodeId); bool isOutbound = outboundNodes.values().contains(nodeId); bool isRule = ruleNodes.values().contains(nodeId); // Lots of duplicated checks. { Q_ASSERT_X(isInbound || isOutbound || isRule, "Delete Node", "Node type error."); if (isInbound) Q_ASSERT_X(!isOutbound && !isRule, "Delete Node", "Node Type Error"); if (isOutbound) Q_ASSERT_X(!isInbound && !isRule, "Delete Node", "Node Type Error"); if (isRule) Q_ASSERT_X(!isInbound && !isOutbound, "Delete Node", "Node Type Error"); } #define CLEANUP(type) \ if (!type##Nodes.values().contains(nodeId)) \ { \ LOG("Could not find a " #type " with id: " + nodeId.toString()); \ return; \ } \ const auto type##Tag = type##Nodes.key(nodeId); \ const auto type = type##s.value(type##Tag); \ \ type##Nodes.remove(type##Tag); \ type##s.remove(type##Tag); if (isInbound) { CLEANUP(inbound); } else if (isOutbound) { CLEANUP(outbound); const auto object = *outbound; if (object.metaType == METAOUTBOUND_CHAIN) { emit OnChainedOutboundDeleted(object); } emit OnOutboundDeleted(object); } else if (isRule) { CLEANUP(rule); emit OnRuleDeleted(*rule); } else { Q_UNREACHABLE(); } #undef CLEANUP } QString NodeDispatcher::CreateInbound(INBOUND in) { auto tag = getTag(in); while (inbounds.contains(tag)) { tag += "_" + GenerateRandomString(5); } in["tag"] = tag; auto dataPtr = std::make_shared<INBOUND>(in); inbounds.insert(tag, dataPtr); // Create node and emit signals. { auto nodeData = std::make_unique<InboundNodeModel>(shared_from_this(), dataPtr); auto &node = ruleScene->createNode(std::move(nodeData)); inboundNodes.insert(tag, node.id()); emit OnInboundCreated(dataPtr, node); } return tag; } QString NodeDispatcher::CreateOutbound(OutboundObjectMeta out) { QString tag = out.getDisplayName(); // In case the tag is duplicated: while (outbounds.contains(tag)) { tag += "_" + GenerateRandomString(5); // It's ok to set them directly without checking. out.displayName = tag; out.realOutbound["tag"] = tag; } auto dataPtr = std::make_shared<OutboundObjectMeta>(out); outbounds.insert(tag, dataPtr); // Create node and emit signals. { auto nodeData = std::make_unique<OutboundNodeModel>(shared_from_this(), dataPtr); auto &node = ruleScene->createNode(std::move(nodeData)); outboundNodes.insert(tag, node.id()); emit OnOutboundCreated(dataPtr, node); } // Create node and emit signals. if (dataPtr->metaType == METAOUTBOUND_EXTERNAL || dataPtr->metaType == METAOUTBOUND_ORIGINAL) { auto nodeData = std::make_unique<ChainOutboundNodeModel>(shared_from_this(), dataPtr); auto &node = chainScene->createNode(std::move(nodeData)); emit OnChainedOutboundCreated(dataPtr, node); } else if (dataPtr->metaType == METAOUTBOUND_CHAIN) { emit OnChainedCreated(dataPtr); } else { LOG("Ignored non-connection outbound for Chain Editor."); } return tag; } QString NodeDispatcher::CreateRule(RuleObject rule) { auto &tag = rule.QV2RAY_RULE_TAG; while (rules.contains(tag)) { tag += "_" + GenerateRandomString(5); } auto dataPtr = std::make_shared<RuleObject>(rule); rules.insert(tag, dataPtr); // Create node and emit signals. { auto nodeData = std::make_unique<RuleNodeModel>(shared_from_this(), dataPtr); auto &node = ruleScene->createNode(std::move(nodeData)); ruleNodes.insert(tag, node.id()); emit OnRuleCreated(dataPtr, node); } return tag; }
8,942
C++
.cpp
220
33.513636
150
0.550678
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,185
ChainOutboundNodeModel.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/models/ChainOutboundNodeModel.cpp
#include "ChainOutboundNodeModel.hpp" #include "ui/widgets/node/widgets/ChainOutboundWidget.hpp" ChainOutboundNodeModel::ChainOutboundNodeModel(std::shared_ptr<NodeDispatcher> dispatcher, std::shared_ptr<node_data_t> data) { this->dispatcher = dispatcher; widget = new ChainOutboundWidget(dispatcher); ((ChainOutboundWidget *) widget)->setValue(data); } void ChainOutboundNodeModel::setInData(std::vector<std::shared_ptr<NodeData>>, PortIndex){}; void ChainOutboundNodeModel::inputConnectionCreated(const QtNodes::Connection &){}; void ChainOutboundNodeModel::inputConnectionDeleted(const QtNodes::Connection &){}; void ChainOutboundNodeModel::outputConnectionCreated(const QtNodes::Connection &){}; void ChainOutboundNodeModel::outputConnectionDeleted(const QtNodes::Connection &){}; void ChainOutboundNodeModel::onNodeHoverLeave(){}; void ChainOutboundNodeModel::onNodeHoverEnter(){};
902
C++
.cpp
15
58.133333
125
0.819005
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,186
InboundNodeModel.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/models/InboundNodeModel.cpp
#include "InboundNodeModel.hpp" #include "core/CoreUtils.hpp" #include "ui/widgets/node/widgets/InboundOutboundWidget.hpp" InboundNodeModel::InboundNodeModel(std::shared_ptr<NodeDispatcher> _dispatcher, std::shared_ptr<node_data_t> data) : NodeDataModel() { dataptr = data; dispatcher = _dispatcher; widget = new InboundOutboundWidget(NODE_INBOUND, dispatcher); connect(widget, &QvNodeWidget::OnSizeUpdated, this, &InboundNodeModel::embeddedWidgetSizeUpdated); ((InboundOutboundWidget *) widget)->setValue(data); widget->setWindowFlags(Qt::FramelessWindowHint); widget->setAttribute(Qt::WA_TranslucentBackground); } void InboundNodeModel::inputConnectionCreated(const QtNodes::Connection &){}; void InboundNodeModel::inputConnectionDeleted(const QtNodes::Connection &){}; void InboundNodeModel::outputConnectionCreated(const QtNodes::Connection &){}; void InboundNodeModel::outputConnectionDeleted(const QtNodes::Connection &){}; void InboundNodeModel::setInData(std::vector<std::shared_ptr<NodeData>>, PortIndex){}; void InboundNodeModel::onNodeHoverLeave(){}; void InboundNodeModel::onNodeHoverEnter() { emit dispatcher->OnInboundOutboundNodeHovered(getTag(*dataptr.get()), GetInboundInfo(*dataptr.get())); }
1,247
C++
.cpp
23
51.652174
132
0.797541
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,187
OutboundNodeModel.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/models/OutboundNodeModel.cpp
#include "OutboundNodeModel.hpp" #include "core/CoreUtils.hpp" #include "ui/widgets/node/widgets/BalancerWidget.hpp" #include "ui/widgets/node/widgets/ChainWidget.hpp" #include "ui/widgets/node/widgets/InboundOutboundWidget.hpp" #define QV_MODULE_NAME "Node::OutboundNodeModel" OutboundNodeModel::OutboundNodeModel(std::shared_ptr<NodeDispatcher> _dispatcher, std::shared_ptr<node_data_t> data) : NodeDataModel() { dataptr = data; dispatcher = _dispatcher; switch (data->metaType) { case complex::METAOUTBOUND_ORIGINAL: case complex::METAOUTBOUND_EXTERNAL: { widget = new InboundOutboundWidget(NODE_OUTBOUND, dispatcher); ((InboundOutboundWidget *) widget)->setValue(data); break; } case complex::METAOUTBOUND_BALANCER: { widget = new BalancerWidget(dispatcher); ((BalancerWidget *) widget)->setValue(data); break; } case complex::METAOUTBOUND_CHAIN: { widget = new ChainWidget(dispatcher); ((ChainWidget *) widget)->setValue(data); break; } } connect(widget, &QvNodeWidget::OnSizeUpdated, this, &OutboundNodeModel::embeddedWidgetSizeUpdated); widget->setWindowFlags(Qt::FramelessWindowHint); widget->setAttribute(Qt::WA_TranslucentBackground); } void OutboundNodeModel::inputConnectionCreated(const QtNodes::Connection &){}; void OutboundNodeModel::inputConnectionDeleted(const QtNodes::Connection &){}; void OutboundNodeModel::outputConnectionCreated(const QtNodes::Connection &){}; void OutboundNodeModel::outputConnectionDeleted(const QtNodes::Connection &){}; void OutboundNodeModel::setInData(std::vector<std::shared_ptr<NodeData>> indata, PortIndex) { if (dispatcher->IsNodeConstructing()) return; for (const auto &d : indata) { if (!d) { LOG("Invalid inbound nodedata to rule."); continue; } const auto rule = static_cast<RuleNodeData *>(d.get()); if (!rule) { LOG("Invalid rule nodedata to outbound."); return; } const auto rulePtr = rule->GetData(); // if (dataptr->metaType == METAOUTBOUND_BALANCER) rulePtr->balancerTag = dataptr->getDisplayName(); else rulePtr->outboundTag = dataptr->getDisplayName(); // DEBUG("Connecting rule:", rulePtr->QV2RAY_RULE_TAG, "to", dataptr->getDisplayName()); } } void OutboundNodeModel::onNodeHoverLeave(){}; void OutboundNodeModel::onNodeHoverEnter() { if (dataptr->metaType == METAOUTBOUND_ORIGINAL) { emit dispatcher->OnInboundOutboundNodeHovered(dataptr->getDisplayName(), GetOutboundInfo(dataptr->realOutbound)); } else if (dataptr->metaType == METAOUTBOUND_EXTERNAL) { emit dispatcher->OnInboundOutboundNodeHovered(dataptr->getDisplayName(), GetConnectionInfo(dataptr->connectionId)); } }
3,006
C++
.cpp
79
31.164557
134
0.675222
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,188
RuleNodeModel.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/models/RuleNodeModel.cpp
#include "RuleNodeModel.hpp" #include "core/CoreUtils.hpp" #include "ui/widgets/node/widgets/RuleWidget.hpp" #define QV_MODULE_NAME "Node::RuleNodeModel" RuleNodeModel::RuleNodeModel(std::shared_ptr<NodeDispatcher> _dispatcher, std::shared_ptr<node_data_t> data) : NodeDataModel() { dataptr = data; dispatcher = _dispatcher; widget = new QvNodeRuleWidget(dispatcher); connect(widget, &QvNodeWidget::OnSizeUpdated, this, &NodeDataModel::embeddedWidgetSizeUpdated); ((QvNodeRuleWidget *) widget)->setValue(data); widget->setWindowFlags(Qt::FramelessWindowHint); widget->setAttribute(Qt::WA_TranslucentBackground); // const auto renameFunc = [this](ComplexTagNodeMode mode, const QString originalTag, const QString newTag) { if (mode == NODE_INBOUND) { if (dataptr->inboundTag.contains(originalTag)) { dataptr->inboundTag.removeAll(originalTag); dataptr->inboundTag.push_back(newTag); } } else if (mode == NODE_OUTBOUND) { if (dataptr->outboundTag == originalTag) dataptr->outboundTag = newTag; if (dataptr->balancerTag == originalTag) dataptr->balancerTag = newTag; } }; connect(dispatcher.get(), &NodeDispatcher::OnObjectTagChanged, renameFunc); } void RuleNodeModel::inputConnectionCreated(const QtNodes::Connection &){}; void RuleNodeModel::inputConnectionDeleted(const QtNodes::Connection &c) { if (dispatcher->IsNodeConstructing()) return; const auto &inNodeData = convert_nodedata<InboundNodeData>(c.getNode(PortType::Out)); const auto inboundTag = getTag(*inNodeData->GetData()); dataptr->inboundTag.removeAll(inboundTag); } void RuleNodeModel::outputConnectionCreated(const QtNodes::Connection &){}; void RuleNodeModel::outputConnectionDeleted(const QtNodes::Connection &) { if (dispatcher->IsNodeConstructing()) return; dataptr->balancerTag.clear(); dataptr->outboundTag.clear(); } void RuleNodeModel::setInData(std::vector<std::shared_ptr<NodeData>> indata, PortIndex) { if (dispatcher->IsNodeConstructing()) return; dataptr->inboundTag.clear(); for (const auto d : indata) { if (!d) { LOG("Invalid inbound nodedata to rule."); continue; } const auto inboundTag = getTag(*static_cast<InboundNodeData *>(d.get())->GetData()); dataptr->inboundTag.push_back(inboundTag); DEBUG("Connecting inbound:", inboundTag, "to", dataptr->QV2RAY_RULE_TAG); } } void RuleNodeModel::onNodeHoverEnter(){}; void RuleNodeModel::onNodeHoverLeave(){};
2,705
C++
.cpp
69
32.884058
126
0.686192
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,189
ChainWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/widgets/ChainWidget.cpp
#include "ChainWidget.hpp" #include "base/Qv2rayBase.hpp" ChainWidget::ChainWidget(std::shared_ptr<NodeDispatcher> _dispatcher, QWidget *parent) : QvNodeWidget(_dispatcher, parent) { setupUi(this); editChainBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("edit"))); } void ChainWidget::setValue(std::shared_ptr<OutboundObjectMeta> data) { dataptr = data; displayNameTxt->setText(data->getDisplayName()); } void ChainWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void ChainWidget::on_displayNameTxt_textEdited(const QString &arg1) { const auto originalTag = dataptr->getDisplayName(); if (originalTag == arg1 || dispatcher->RenameTag<NODE_OUTBOUND>(originalTag, arg1)) { dataptr->displayName = arg1; BLACK(displayNameTxt); } else { RED(displayNameTxt); } } void ChainWidget::on_editChainBtn_clicked() { emit dispatcher->RequestEditChain(dataptr->getDisplayName()); }
1,081
C++
.cpp
38
24.552632
122
0.715526
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,190
BalancerWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/widgets/BalancerWidget.cpp
#include "BalancerWidget.hpp" #include "base/Qv2rayBase.hpp" BalancerWidget::BalancerWidget(std::shared_ptr<NodeDispatcher> _dispatcher, QWidget *parent) : QvNodeWidget(_dispatcher, parent) { setupUi(this); balancerAddBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); balancerDelBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); connect(dispatcher.get(), &NodeDispatcher::OnOutboundCreated, this, &BalancerWidget::OutboundCreated); connect(dispatcher.get(), &NodeDispatcher::OnOutboundDeleted, this, &BalancerWidget::OutboundDeleted); connect(dispatcher.get(), &NodeDispatcher::OnObjectTagChanged, this, &BalancerWidget::OnTagChanged); } void BalancerWidget::setValue(std::shared_ptr<OutboundObjectMeta> data) { outboundData = data; balancerSelectionCombo->clear(); balancerSelectionCombo->addItems(dispatcher->GetRealOutboundTags()); balancerTagTxt->setText(data->getDisplayName()); balancerList->addItems(data->outboundTags); strategyCB->setCurrentText(data->strategyType); } void BalancerWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void BalancerWidget::on_balancerAddBtn_clicked() { const auto balancerTx = balancerSelectionCombo->currentText().trimmed(); if (!balancerTx.isEmpty()) { outboundData->outboundTags.append(balancerSelectionCombo->currentText()); balancerList->addItem(balancerTx); balancerSelectionCombo->setEditText(""); } } void BalancerWidget::OutboundCreated(std::shared_ptr<OutboundObjectMeta> data, QtNodes::Node &) { if (data->metaType != METAOUTBOUND_BALANCER) balancerSelectionCombo->addItem(data->getDisplayName()); } void BalancerWidget::OutboundDeleted(const OutboundObjectMeta &data) { if (data.metaType != METAOUTBOUND_BALANCER) balancerSelectionCombo->removeItem(balancerSelectionCombo->findText(data.getDisplayName())); } void BalancerWidget::OnTagChanged(ComplexTagNodeMode type, const QString originalTag, const QString newTag) { if (type != NODE_OUTBOUND) return; const auto index = balancerSelectionCombo->findText(originalTag); if (index >= 0) balancerSelectionCombo->setItemText(index, newTag); } void BalancerWidget::on_balancerDelBtn_clicked() { if (balancerList->currentRow() < 0) return; outboundData->outboundTags.removeOne(balancerList->currentItem()->text()); balancerList->takeItem(balancerList->currentRow()); } void BalancerWidget::on_balancerTagTxt_textEdited(const QString &arg1) { const auto originalName = outboundData->getDisplayName(); if (originalName == arg1 || dispatcher->RenameTag<NODE_OUTBOUND>(originalName, arg1)) { outboundData->displayName = arg1; BLACK(balancerTagTxt); } else { RED(balancerTagTxt); } } void BalancerWidget::on_showHideBtn_clicked() { tabWidget->setVisible(!tabWidget->isVisible()); } void BalancerWidget::on_strategyCB_currentIndexChanged(const QString &arg1) { outboundData->strategyType = arg1; }
3,169
C++
.cpp
85
33.152941
128
0.749186
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,191
RuleWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/widgets/RuleWidget.cpp
#include "RuleWidget.hpp" #include "base/Qv2rayBase.hpp" #include "utils/QvHelpers.hpp" #define LOAD_FLAG_END isLoading = false; #define LOAD_FLAG_BEGIN isLoading = true; #define LOADINGCHECK \ if (isLoading) \ return; #define rule (*(this->ruleptr)) const static auto Split_RemoveDuplicate_Sort = [](const QString &in) { auto entries = SplitLines(in); entries.removeDuplicates(); entries.sort(); return entries; }; QvNodeRuleWidget::QvNodeRuleWidget(std::shared_ptr<NodeDispatcher> _dispatcher, QWidget *parent) : QvNodeWidget(_dispatcher, parent) { setupUi(this); settingsFrame->setVisible(false); adjustSize(); } void QvNodeRuleWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: { retranslateUi(this); break; } default: break; } } void QvNodeRuleWidget::setValue(std::shared_ptr<RuleObject> _ruleptr) { this->ruleptr = _ruleptr; // Switch to the detailed page. ruleEnableCB->setEnabled(true); ruleEnableCB->setChecked(rule.QV2RAY_RULE_ENABLED); ruleTagLineEdit->setEnabled(true); LOAD_FLAG_BEGIN ruleTagLineEdit->setText(rule.QV2RAY_RULE_TAG); isLoading = false; // Networks auto network = rule.network.toLower(); netUDPRB->setChecked(network.contains("udp")); netTCPRB->setChecked(network.contains("tcp")); // // Set protocol checkboxes. auto protocol = rule.protocol; routeProtocolHTTPCB->setChecked(protocol.contains("http")); routeProtocolTLSCB->setChecked(protocol.contains("tls")); routeProtocolBTCB->setChecked(protocol.contains("bittorrent")); // // Port routePortTxt->setText(rule.port); // // Users const auto sourcePorts = rule.sourcePort; // // Incoming Sources const auto sources = rule.source.join(NEWLINE); sourceIPList->setPlainText(sources); // // Domains QString domains = rule.domain.join(NEWLINE); hostList->setPlainText(domains); // // Outcoming IPs QString ips = rule.ip.join(NEWLINE); ipList->setPlainText(ips); LOAD_FLAG_END } void QvNodeRuleWidget::on_routeProtocolHTTPCB_stateChanged(int) { LOADINGCHECK SetProtocolProperty(); } void QvNodeRuleWidget::on_routeProtocolTLSCB_stateChanged(int) { LOADINGCHECK SetProtocolProperty(); } void QvNodeRuleWidget::on_routeProtocolBTCB_stateChanged(int) { LOADINGCHECK SetProtocolProperty(); } void QvNodeRuleWidget::on_hostList_textChanged() { LOADINGCHECK rule.domain = Split_RemoveDuplicate_Sort(hostList->toPlainText()); } void QvNodeRuleWidget::on_ipList_textChanged() { LOADINGCHECK rule.ip = Split_RemoveDuplicate_Sort(ipList->toPlainText()); } void QvNodeRuleWidget::on_routePortTxt_textEdited(const QString &arg1) { LOADINGCHECK rule.port = arg1; } void QvNodeRuleWidget::on_netUDPRB_clicked() { LOADINGCHECK SetNetworkProperty(); } void QvNodeRuleWidget::on_netTCPRB_clicked() { LOADINGCHECK SetNetworkProperty(); } void QvNodeRuleWidget::on_sourceIPList_textChanged() { LOADINGCHECK rule.source = Split_RemoveDuplicate_Sort(sourceIPList->toPlainText()); } void QvNodeRuleWidget::on_ruleEnableCB_stateChanged(int arg1) { bool _isEnabled = arg1 == Qt::Checked; rule.QV2RAY_RULE_ENABLED = _isEnabled; settingsFrame->setEnabled(_isEnabled); } void QvNodeRuleWidget::on_toolButton_clicked() { settingsFrame->setVisible(!settingsFrame->isVisible()); adjustSize(); emit OnSizeUpdated(); } void QvNodeRuleWidget::on_ruleTagLineEdit_textEdited(const QString &arg1) { const auto originalTag = rule.QV2RAY_RULE_TAG; if (originalTag == arg1 || dispatcher->RenameTag<NODE_RULE>(originalTag, arg1)) { BLACK(ruleTagLineEdit); rule.QV2RAY_RULE_TAG = arg1; return; } RED(ruleTagLineEdit); }
4,188
C++
.cpp
142
25.542254
150
0.675937
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,192
InboundOutboundWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/widgets/InboundOutboundWidget.cpp
#include "InboundOutboundWidget.hpp" #include "base/Qv2rayBase.hpp" #include "core/CoreUtils.hpp" #include "core/handler/ConfigHandler.hpp" #include "ui/widgets/editors/w_InboundEditor.hpp" #include "ui/widgets/editors/w_JsonEditor.hpp" #include "ui/widgets/editors/w_OutboundEditor.hpp" InboundOutboundWidget::InboundOutboundWidget(ComplexTagNodeMode mode, std::shared_ptr<NodeDispatcher> _d, QWidget *parent) : QvNodeWidget(_d, parent) { workingMode = mode; setupUi(this); editBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("edit"))); editJsonBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("code"))); } void InboundOutboundWidget::setValue(std::shared_ptr<INBOUND> data) { assert(workingMode == NODE_INBOUND); inboundObject = data; tagTxt->setText(getTag(*data)); } void InboundOutboundWidget::setValue(std::shared_ptr<OutboundObjectMeta> data) { assert(workingMode == NODE_OUTBOUND); outboundObject = data; tagTxt->setText(outboundObject->getDisplayName()); isExternalOutbound = outboundObject->metaType == METAOUTBOUND_EXTERNAL; statusLabel->setText(isExternalOutbound ? tr("External Config") : ""); tagTxt->setEnabled(!isExternalOutbound); } void InboundOutboundWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: { retranslateUi(this); break; } default: break; } } void InboundOutboundWidget::on_editBtn_clicked() { if (workingMode == NODE_INBOUND) { InboundEditor editor{ *inboundObject, parentWidget() }; *inboundObject = editor.OpenEditor(); // Set tag const auto newTag = getTag(*inboundObject); tagTxt->setText(newTag); (*inboundObject)["tag"] = newTag; } else { if (isExternalOutbound) { if (QvMessageBoxAsk(parentWidget(), tr("Edit Outbound"), editExternalMsg) != Yes) { return; } const auto externalId = outboundObject->connectionId; const auto root = ConnectionManager->GetConnectionRoot(externalId); if (IsComplexConfig(root)) { if (QvMessageBoxAsk(parentWidget(), tr("Trying to edit an Complex Config"), editExternalComplexMsg) != Yes) { return; } } OUTBOUND outbound{ QJsonIO::GetValue(root, "outbounds", 0).toObject() }; OutboundEditor editor{ outbound, parentWidget() }; outbound = editor.OpenEditor(); if (editor.result() == QDialog::Accepted) ConnectionManager->UpdateConnection(externalId, CONFIGROOT{ QJsonObject{ { "outbounds", QJsonArray{ outbound } } } }); } else { OutboundEditor editor{ outboundObject->realOutbound, parentWidget() }; outboundObject->realOutbound = editor.OpenEditor(); // Set tag const auto newTag = getTag(outboundObject->realOutbound); tagTxt->setText(newTag); outboundObject->realOutbound["tag"] = newTag; } } } void InboundOutboundWidget::on_editJsonBtn_clicked() { if (workingMode == NODE_INBOUND) { JsonEditor editor{ *inboundObject, parentWidget() }; *inboundObject = INBOUND{ editor.OpenEditor() }; const auto newTag = getTag(*inboundObject); // Set tag tagTxt->setText(newTag); (*inboundObject)["tag"] = newTag; } else { if (isExternalOutbound) { if (QvMessageBoxAsk(parentWidget(), tr("Edit Outbound"), editExternalMsg) != Yes) return; const auto externalId = outboundObject->connectionId; const auto root = ConnectionManager->GetConnectionRoot(externalId); OUTBOUND outbound{ QJsonIO::GetValue(root, "outbounds", 0).toObject() }; JsonEditor editor{ outbound, parentWidget() }; outbound = OUTBOUND{ editor.OpenEditor() }; if (editor.result() == QDialog::Accepted) ConnectionManager->UpdateConnection(externalId, CONFIGROOT{ QJsonObject{ { "outbounds", QJsonArray{ outbound } } } }); } else { // Open Editor JsonEditor editor{ outboundObject->realOutbound, parentWidget() }; outboundObject->realOutbound = OUTBOUND{ editor.OpenEditor() }; // // Set tag (only for local connections) const auto newTag = getTag(outboundObject->realOutbound); tagTxt->setText(newTag); outboundObject->realOutbound["tag"] = newTag; } } } void InboundOutboundWidget::on_tagTxt_textEdited(const QString &arg1) { if (workingMode == NODE_INBOUND) { const auto originalTag = (*inboundObject)["tag"].toString(); if (originalTag == arg1 || dispatcher->RenameTag<NODE_INBOUND>(originalTag, arg1)) { BLACK(tagTxt); (*inboundObject)["tag"] = arg1; return; } RED(tagTxt); } else { const auto originalTag = outboundObject->getDisplayName(); if (originalTag == arg1 || dispatcher->RenameTag<NODE_OUTBOUND>(originalTag, arg1)) { BLACK(tagTxt); outboundObject->realOutbound["tag"] = arg1; return; } RED(tagTxt); } }
5,461
C++
.cpp
150
28.226667
149
0.625236
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,193
ChainOutboundWidget.cpp
Qv2ray_Qv2ray/src/ui/widgets/node/widgets/ChainOutboundWidget.cpp
#include "ChainOutboundWidget.hpp" ChainOutboundWidget::ChainOutboundWidget(std::shared_ptr<NodeDispatcher> _dispatcher, QWidget *parent) : QvNodeWidget(_dispatcher, parent) { setupUi(this); // Simple slot to update UI connect(_dispatcher.get(), &NodeDispatcher::OnObjectTagChanged, [this](ComplexTagNodeMode, const QString _t2, const QString _t3) { if (tagLabel->text() == _t2) { tagLabel->setText(_t3); emit OnSizeUpdated(); } }); } void ChainOutboundWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void ChainOutboundWidget::setValue(std::shared_ptr<OutboundObjectMeta> data) { chain = data; tagLabel->setText(data->getDisplayName()); chainPortSB->setValue(data->chainPortAllocation); } void ChainOutboundWidget::on_chainPortSB_valueChanged(int arg1) { chain->chainPortAllocation = arg1; }
1,016
C++
.cpp
32
27.125
138
0.702041
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,195
w_ChainSha256Editor.cpp
Qv2ray_Qv2ray/src/ui/widgets/editors/w_ChainSha256Editor.cpp
#include "w_ChainSha256Editor.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" #include <QDesktopServices> ChainSha256Editor::ChainSha256Editor(QWidget *parent, const QList<QString> &chain) : QDialog(parent) { setupUi(this); chainSha256Edit->setPlainText(chain.join("\r\n")); QvMessageBusConnect(ChainSha256Editor); } QvMessageBusSlotImpl(ChainSha256Editor) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; case UPDATE_COLORSCHEME: break; } } void ChainSha256Editor::accept() { const auto newChain = ChainSha256Editor::convertFromString(chainSha256Edit->toPlainText()); if (const auto err = ChainSha256Editor::validateError(newChain); err) { QvMessageBoxWarn(this, tr("Invalid Certificate Hash Chain"), *err); return; } this->chain = newChain; this->QDialog::accept(); } QList<QString> ChainSha256Editor::convertFromString(const QString &&str) { const static QRegularExpression newLine("[\r\n]"); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) return str.split(newLine, Qt::SplitBehaviorFlags::SkipEmptyParts); #else return str.split(newLine, QString::SkipEmptyParts); #endif } std::optional<QString> ChainSha256Editor::validateError(const QList<QString> &newChain) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) const static QRegularExpression sha256(QRegularExpression::anchoredPattern("[0-9a-fA-F]{64}")); #else const static QRegularExpression sha256("^[0-9a-fA-F]{64}$"); #endif for (const auto &entry : newChain) { if(!sha256.match(entry).hasMatch()) return tr("invalid SHA256: %1").arg(entry); } return std::nullopt; } void ChainSha256Editor::on_buttonBox_helpRequested() { QDesktopServices::openUrl(QUrl("https://www.v2fly.org/config/transport.html#tlsobject")); }
1,900
C++
.cpp
58
28.913793
100
0.729405
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,196
w_InboundEditor.cpp
Qv2ray_Qv2ray/src/ui/widgets/editors/w_InboundEditor.cpp
#include "w_InboundEditor.hpp" #include "core/CoreUtils.hpp" #include "core/connection/ConnectionIO.hpp" #include "plugin-interface/QvGUIPluginInterface.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "ui/widgets/widgets/StreamSettingsWidget.hpp" #include "utils/QvHelpers.hpp" #include <QGridLayout> #define QV_MODULE_NAME "InboundEditor" #define CHECKLOADING \ if (isLoading) \ return; InboundEditor::InboundEditor(INBOUND source, QWidget *parent) : QDialog(parent), original(source) { QvMessageBusConnect(InboundEditor); setupUi(this); streamSettingsWidget = new StreamSettingsWidget(this); streamSettingsWidget->SetStreamObject({}); if (!transportFrame->layout()) { auto l = new QGridLayout(); l->setHorizontalSpacing(0); l->setVerticalSpacing(0); transportFrame->setLayout(l); } transportFrame->layout()->addWidget(streamSettingsWidget); this->current = source; inboundProtocol = current["protocol"].toString("http"); allocateSettings = current["allocate"].toObject(); sniffingSettings = current["sniffing"].toObject(); isLoading = true; for (const auto &name : PluginHost->UsablePlugins()) { const auto &plugin = PluginHost->GetPlugin(name); if (!plugin->hasComponent(COMPONENT_GUI)) continue; const auto guiInterface = plugin->pluginInterface->GetGUIInterface(); if (!guiInterface) { LOG("Found a plugin with COMPONENT_GUI but returns an invalid GUI interface: ", plugin->metadata.Name); continue; } if (!guiInterface->GetComponents().contains(GUI_COMPONENT_INBOUND_EDITOR)) continue; const auto editors = guiInterface->GetInboundEditors(); for (const auto &editorInfo : editors) { inboundProtocolCombo->addItem(editorInfo.first.displayName, editorInfo.first.protocol); stackedWidget->addWidget(editorInfo.second); pluginWidgets.insert(editorInfo.first.protocol, editorInfo.second); } } inboundProtocolCombo->model()->sort(0); isLoading = false; loadUI(); } QvMessageBusSlotImpl(InboundEditor) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; case UPDATE_COLORSCHEME: break; } } INBOUND InboundEditor::OpenEditor() { int resultCode = this->exec(); return resultCode == QDialog::Accepted ? getResult() : original; } INBOUND InboundEditor::getResult() { INBOUND newRoot = current; for (const auto &[protocol, widget] : pluginWidgets.toStdMap()) { if (protocol == inboundProtocol) { newRoot["settings"] = INBOUNDSETTING(widget->GetContent()); break; } } if (streamSettingsWidget->isEnabled()) { newRoot["streamSettings"] = streamSettingsWidget->GetStreamSettings().toJson(); } newRoot["protocol"] = inboundProtocol; newRoot["sniffing"] = sniffingSettings; newRoot["allocate"] = allocateSettings; return newRoot; } void InboundEditor::loadUI() { isLoading = true; streamSettingsWidget->SetStreamObject(StreamSettingsObject::fromJson(original["streamSettings"].toObject())); { inboundTagTxt->setText(current["tag"].toString()); inboundHostTxt->setText(current["listen"].toString()); inboundPortTxt->setText(current["port"].toVariant().toString()); } { const auto allocationStrategy = allocateSettings["strategy"].toString(); allocateSettings["strategy"] = allocationStrategy.isEmpty() ? "always" : allocationStrategy; strategyCombo->setCurrentText(allocationStrategy); refreshNumberBox->setValue(allocateSettings["refresh"].toInt()); concurrencyNumberBox->setValue(allocateSettings["concurrency"].toInt()); } { sniffingGroupBox->setChecked(sniffingSettings["enabled"].toBool()); sniffMetaDataOnlyCB->setChecked(sniffingSettings["metadataOnly"].toBool()); const auto data = sniffingSettings["destOverride"].toArray(); sniffHTTPCB->setChecked(data.contains("http")); sniffTLSCB->setChecked(data.contains("tls")); sniffFakeDNSCB->setChecked(data.contains("fakedns")); sniffFakeDNSOtherCB->setChecked(data.contains("fakedns+others")); } bool processed = false; const auto settings = current["settings"].toObject(); for (const auto &[protocol, widget] : pluginWidgets.toStdMap()) { if (protocol == inboundProtocol) { widget->SetContent(settings); inboundProtocolCombo->setCurrentIndex(inboundProtocolCombo->findData(protocol)); processed = true; break; } } if (!processed) { LOG("Inbound protocol: " + inboundProtocol + " is not supported."); QvMessageBoxWarn(this, tr("Unknown inbound."), tr("The specified inbound type is invalid, this may be caused by a plugin failure.") + NEWLINE + tr("Please use the JsonEditor or reload the plugin.")); reject(); } isLoading = false; on_stackedWidget_currentChanged(0); } InboundEditor::~InboundEditor() { } void InboundEditor::on_inboundProtocolCombo_currentIndexChanged(int) { CHECKLOADING on_stackedWidget_currentChanged(0); } void InboundEditor::on_inboundTagTxt_textEdited(const QString &arg1) { CHECKLOADING current["tag"] = arg1; } void InboundEditor::on_strategyCombo_currentIndexChanged(int arg1) { CHECKLOADING allocateSettings["strategy"] = strategyCombo->itemText(arg1).toLower(); } void InboundEditor::on_refreshNumberBox_valueChanged(int arg1) { CHECKLOADING allocateSettings["refresh"] = arg1; } void InboundEditor::on_concurrencyNumberBox_valueChanged(int arg1) { CHECKLOADING allocateSettings["concurrency"] = arg1; } void InboundEditor::on_inboundHostTxt_textEdited(const QString &arg1) { CHECKLOADING current["listen"] = arg1; } void InboundEditor::on_inboundPortTxt_textEdited(const QString &arg1) { CHECKLOADING current["port"] = arg1; } void InboundEditor::on_sniffingGroupBox_clicked(bool checked) { CHECKLOADING sniffingSettings["enabled"] = checked; } void InboundEditor::on_sniffMetaDataOnlyCB_clicked(bool checked) { CHECKLOADING sniffingSettings["metadataOnly"] = checked; } #define SET_SNIFF_DEST_OVERRIDE \ do \ { \ const auto hasHTTP = sniffHTTPCB->isChecked(); \ const auto hasTLS = sniffTLSCB->isChecked(); \ const auto hasFakeDNS = sniffFakeDNSCB->isChecked(); \ const auto hasFakeDNSOthers = sniffFakeDNSOtherCB->isChecked(); \ QStringList list; \ if (hasHTTP) \ list << "http"; \ if (hasTLS) \ list << "tls"; \ if (hasFakeDNS) \ list << "fakedns"; \ if (hasFakeDNSOthers) \ list << "fakedns+others"; \ sniffingSettings["destOverride"] = QJsonArray::fromStringList(list); \ } while (0) void InboundEditor::on_sniffHTTPCB_stateChanged(int) { CHECKLOADING SET_SNIFF_DEST_OVERRIDE; } void InboundEditor::on_sniffTLSCB_stateChanged(int) { CHECKLOADING SET_SNIFF_DEST_OVERRIDE; } void InboundEditor::on_sniffFakeDNSOtherCB_stateChanged(int) { CHECKLOADING SET_SNIFF_DEST_OVERRIDE; } void InboundEditor::on_sniffFakeDNSCB_stateChanged(int) { CHECKLOADING SET_SNIFF_DEST_OVERRIDE; } void InboundEditor::on_stackedWidget_currentChanged(int) { CHECKLOADING inboundProtocol = inboundProtocolCombo->currentData().toString(); auto widget = pluginWidgets[inboundProtocol]; if (!widget) return; stackedWidget->setCurrentWidget(widget); const auto hasStreamSettings = GetProperty(widget, "QV2RAY_INTERNAL_HAS_STREAMSETTINGS"); streamSettingsWidget->setEnabled(hasStreamSettings); }
10,160
C++
.cpp
236
37.415254
150
0.541027
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,197
w_JsonEditor.cpp
Qv2ray_Qv2ray/src/ui/widgets/editors/w_JsonEditor.cpp
#include "w_JsonEditor.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" JsonEditor::JsonEditor(QJsonObject rootObject, QWidget *parent) : QDialog(parent) { setupUi(this); QvMessageBusConnect(JsonEditor); // original = rootObject; final = rootObject; QString jsonString = JsonToString(rootObject); if (VerifyJsonString(jsonString).isEmpty()) { jsonTree->setModel(&model); model.loadJson(QJsonDocument(rootObject).toJson()); } else { QvMessageBoxWarn(this, tr("Json Contains Syntax Errors"), tr("Original Json may contain syntax errors. Json tree is disabled.")); } jsonEditor->setText(JsonToString(rootObject)); jsonTree->expandAll(); jsonTree->resizeColumnToContents(0); } QvMessageBusSlotImpl(JsonEditor) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; case UPDATE_COLORSCHEME: break; } } QJsonObject JsonEditor::OpenEditor() { int resultCode = this->exec(); auto string = jsonEditor->toPlainText(); while (resultCode == QDialog::Accepted && !VerifyJsonString(string).isEmpty()) { QvMessageBoxWarn(this, tr("Json Contains Syntax Errors"), tr("You must correct these errors before continuing.")); resultCode = this->exec(); string = jsonEditor->toPlainText(); } return resultCode == QDialog::Accepted ? final : original; } JsonEditor::~JsonEditor() { } void JsonEditor::on_jsonEditor_textChanged() { auto string = jsonEditor->toPlainText(); auto VerifyResult = VerifyJsonString(string); jsonValidateStatus->setText(VerifyResult); if (VerifyResult.isEmpty()) { BLACK(jsonEditor); final = JsonFromString(string); model.loadJson(QJsonDocument(final).toJson()); jsonTree->expandAll(); jsonTree->resizeColumnToContents(0); } else { RED(jsonEditor); } } void JsonEditor::on_formatJsonBtn_clicked() { auto string = jsonEditor->toPlainText(); auto VerifyResult = VerifyJsonString(string); jsonValidateStatus->setText(VerifyResult); if (VerifyResult.isEmpty()) { BLACK(jsonEditor); jsonEditor->setPlainText(JsonToString(JsonFromString(string))); model.loadJson(QJsonDocument(JsonFromString(string)).toJson()); jsonTree->setModel(&model); jsonTree->expandAll(); jsonTree->resizeColumnToContents(0); } else { RED(jsonEditor); QvMessageBoxWarn(this, tr("Syntax Errors"), tr("Please fix the JSON errors or remove the comments before continue")); } } void JsonEditor::on_removeCommentsBtn_clicked() { jsonEditor->setPlainText(JsonToString(JsonFromString(jsonEditor->toPlainText()))); }
2,816
C++
.cpp
91
25.791209
137
0.696791
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,198
w_RoutesEditor.cpp
Qv2ray_Qv2ray/src/ui/widgets/editors/w_RoutesEditor.cpp
#include "w_RoutesEditor.hpp" #include "components/plugins/QvPluginHost.hpp" #include "core/connection/Generation.hpp" #include "core/handler/ConfigHandler.hpp" #include "ui/widgets/node/NodeBase.hpp" #include "ui/widgets/node/models/InboundNodeModel.hpp" #include "ui/widgets/node/models/OutboundNodeModel.hpp" #include "ui/widgets/node/models/RuleNodeModel.hpp" #include "ui/widgets/widgets/DnsSettingsWidget.hpp" #include "ui/widgets/widgets/complex/ChainEditorWidget.hpp" #include "ui/widgets/widgets/complex/RoutingEditorWidget.hpp" #include "ui/widgets/windows/w_ImportConfig.hpp" #include "w_InboundEditor.hpp" #include "w_JsonEditor.hpp" #include "w_OutboundEditor.hpp" #include <nodes/ConnectionStyle> #include <nodes/FlowScene> #include <nodes/FlowView> #include <nodes/FlowViewStyle> #include <nodes/Node> #ifdef QT_DEBUG #include "nodes/../../src/ConnectionPainter.hpp" #endif #define QV_MODULE_NAME "RouteEditor" using namespace QtNodes; using namespace Qv2ray::ui::nodemodels; namespace { constexpr auto NODE_TAB_ROUTE_EDITOR = 0; constexpr auto NODE_TAB_CHAIN_EDITOR = 1; constexpr auto DarkConnectionStyle = R"({"ConnectionStyle": {"ConstructionColor": "gray","NormalColor": "black","SelectedColor": "gray", "SelectedHaloColor": "deepskyblue","HoveredColor": "deepskyblue","LineWidth": 3.0, "ConstructionLineWidth": 2.0,"PointDiameter": 10.0,"UseDataDefinedColors": true}})"; constexpr auto LightNodeStyle = R"({"NodeStyle": {"NormalBoundaryColor": "darkgray","SelectedBoundaryColor": "deepskyblue", "GradientColor0": "mintcream","GradientColor1": "mintcream","GradientColor2": "mintcream", "GradientColor3": "mintcream","ShadowColor": [200, 200, 200],"FontColor": [10, 10, 10], "FontColorFaded": [100, 100, 100],"ConnectionPointColor": "white","PenWidth": 2.0,"HoveredPenWidth": 2.5, "ConnectionPointDiameter": 10.0,"Opacity": 1.0}})"; constexpr auto LightViewStyle = R"({"FlowViewStyle": {"BackgroundColor": [255, 255, 240],"FineGridColor": [245, 245, 230],"CoarseGridColor": [235, 235, 220]}})"; constexpr auto LightConnectionStyle = R"({"ConnectionStyle": {"ConstructionColor": "gray","NormalColor": "black","SelectedColor": "gray", "SelectedHaloColor": "deepskyblue","HoveredColor": "deepskyblue","LineWidth": 3.0,"ConstructionLineWidth": 2.0, "PointDiameter": 10.0,"UseDataDefinedColors": false}})"; constexpr auto IMPORT_ALL_CONNECTIONS_FAKE_ID = "__ALL_CONNECTIONS__"; constexpr auto IMPORT_ALL_CONNECTIONS_SEPARATOR = "_"; } // namespace #define LOADINGCHECK \ if (isLoading) \ return; #define LOAD_FLAG_BEGIN isLoading = true; #define LOAD_FLAG_END isLoading = false; void RouteEditor::updateColorScheme() { // Setup icons according to the theme settings. addInboundBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); addOutboundBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); if (GlobalConfig.uiConfig.useDarkTheme) { QtNodes::NodeStyle::reset(); QtNodes::FlowViewStyle::reset(); ConnectionStyle::setConnectionStyle(DarkConnectionStyle); } else { QtNodes::NodeStyle::setNodeStyle(LightNodeStyle); QtNodes::FlowViewStyle::setStyle(LightViewStyle); ConnectionStyle::setConnectionStyle(LightConnectionStyle); } } RouteEditor::RouteEditor(QJsonObject connection, QWidget *parent) : QvDialog("RouteEditor", parent), root(connection), original(connection) { setupUi(this); QvMessageBusConnect(RouteEditor); // isLoading = true; setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint); RouteEditor::updateColorScheme(); // // Do not change the order. nodeDispatcher = std::make_shared<NodeDispatcher>(); ruleWidget = new RoutingEditorWidget(nodeDispatcher, ruleEditorUIWidget); chainWidget = new ChainEditorWidget(nodeDispatcher, chainEditorUIWidget); dnsWidget = new DnsSettingsWidget(this); nodeDispatcher->InitializeScenes(ruleWidget->getScene(), chainWidget->getScene()); connect(nodeDispatcher.get(), &NodeDispatcher::OnOutboundCreated, this, &RouteEditor::OnDispatcherOutboundCreated); connect(nodeDispatcher.get(), &NodeDispatcher::OnOutboundDeleted, this, &RouteEditor::OnDispatcherOutboundDeleted); connect(nodeDispatcher.get(), &NodeDispatcher::OnRuleCreated, this, &RouteEditor::OnDispatcherRuleCreated); connect(nodeDispatcher.get(), &NodeDispatcher::OnRuleDeleted, this, &RouteEditor::OnDispatcherRuleDeleted); connect(nodeDispatcher.get(), &NodeDispatcher::OnInboundOutboundNodeHovered, this, &RouteEditor::OnDispatcherInboundOutboundHovered); connect(nodeDispatcher.get(), &NodeDispatcher::RequestEditChain, this, &RouteEditor::OnDispatcherEditChainRequested); connect(nodeDispatcher.get(), &NodeDispatcher::OnObjectTagChanged, this, &RouteEditor::OnDispatcherObjectTagChanged); const auto SetUpLayout = [](QWidget *parent, QWidget *child) { if (!parent->layout()) parent->setLayout(new QVBoxLayout()); auto l = parent->layout(); l->addWidget(child); l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); }; SetUpLayout(ruleEditorUIWidget, ruleWidget); SetUpLayout(chainEditorUIWidget, chainWidget); SetUpLayout(dnsEditorUIWidget, dnsWidget); // nodeDispatcher->LoadFullConfig(root); dnsWidget->SetDNSObject(DNSObject::fromJson(root["dns"].toObject()), FakeDNSObject::fromJson(root["fakedns"].toObject())); // domainStrategy = root["routing"].toObject()["domainStrategy"].toString(); domainStrategyCombo->setCurrentText(domainStrategy); // // Set default outboung combo text AFTER adding all outbounds. defaultOutboundTag = getTag(OUTBOUND(root["outbounds"].toArray().first().toObject())); defaultOutboundCombo->setCurrentText(defaultOutboundTag); // bfListenIPTxt->setText(root["browserForwarder"].toObject()["listenAddr"].toString()); bfListenPortTxt->setValue(root["browserForwarder"].toObject()["listenPort"].toInt()); obSubjectSelectorTxt->setPlainText(root["observatory"].toObject()["subjectSelector"].toVariant().toStringList().join(NEWLINE)); for (const auto &group : ConnectionManager->AllGroups()) { importGroupBtn->addItem(GetDisplayName(group), group.toString()); } #ifndef QT_DEBUG debugPainterCB->setVisible(false); #endif isLoading = false; } QvMessageBusSlotImpl(RouteEditor) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; MBUpdateColorSchemeDefaultImpl; } } void RouteEditor::OnDispatcherInboundOutboundHovered(const QString &tag, const ProtocolSettingsInfoObject &info) { tagLabel->setText(tag); hostLabel->setText(info.address); portLabel->setNum(info.port); protocolLabel->setText(info.protocol); } void RouteEditor::OnDispatcherOutboundCreated(std::shared_ptr<OutboundObjectMeta> out, QtNodes::Node &) { if (out->metaType != METAOUTBOUND_BALANCER) defaultOutboundCombo->addItem(out->getDisplayName()); } void RouteEditor::OnDispatcherRuleCreated(std::shared_ptr<RuleObject> rule, QtNodes::Node &) { ruleListWidget->addItem(rule->QV2RAY_RULE_TAG); } void RouteEditor::OnDispatcherRuleDeleted(const RuleObject &rule) { const auto items = ruleListWidget->findItems(rule.QV2RAY_RULE_TAG, Qt::MatchExactly); if (!items.isEmpty()) ruleListWidget->takeItem(ruleListWidget->row(items.first())); } void RouteEditor::OnDispatcherOutboundDeleted(const OutboundObjectMeta &data) { const auto id = defaultOutboundCombo->findText(data.getDisplayName()); if (id >= 0) { defaultOutboundCombo->removeItem(id); } } void RouteEditor::OnDispatcherObjectTagChanged(ComplexTagNodeMode t, const QString original, const QString current) { Q_UNUSED(original) Q_UNUSED(current) // if (t == NODE_INBOUND) { // Pass } else if (t == NODE_RULE) { for (auto i = 0; i < ruleListWidget->count(); i++) { if (ruleListWidget->item(i)->text() == original) ruleListWidget->item(i)->setText(current); } } else if (t == NODE_OUTBOUND) { const auto id = defaultOutboundCombo->findText(original); if (id >= 0) defaultOutboundCombo->setItemText(id, current); } } void RouteEditor::OnDispatcherEditChainRequested(const QString &) { nodesTab->setCurrentIndex(NODE_TAB_CHAIN_EDITOR); } CONFIGROOT RouteEditor::OpenEditor() { auto result = this->exec(); if (result != QDialog::Accepted) return original; const auto &[inbounds, rules, outbounds] = nodeDispatcher->GetData(); // // Inbounds QJsonArray inboundsJson; for (const auto &in : inbounds) { inboundsJson << in; } root["inbounds"] = inboundsJson; // // QJsonArray rules QJsonArray rulesJsonArray; for (auto i = 0; i < ruleListWidget->count(); i++) { // Sorted const auto ruleTag = ruleListWidget->item(i)->text(); if (rules.contains(ruleTag)) { const auto &ruleObject = rules[ruleTag]; auto ruleJson = ruleObject.toJson(); if (ruleJson["outboundTag"].toString().isEmpty()) ruleJson.remove("outboundTag"); else ruleJson.remove("balancerTag"); rulesJsonArray << ruleJson; } else { LOG("Could not find rule tag:", ruleTag); } } // // QJsonArray balancers QJsonArray balancersArray; for (const auto &out : outbounds) { if (out.metaType != METAOUTBOUND_BALANCER) continue; BalancerObject o; o.tag = out.getDisplayName(); o.selector = out.outboundTags; o.strategy.type = out.strategyType; balancersArray << o.toJson(); } QJsonObject routingObject; routingObject["domainStrategy"] = domainStrategy; routingObject["rules"] = rulesJsonArray; routingObject["balancers"] = balancersArray; root["routing"] = routingObject; // QJsonArray Outbounds QJsonArray outboundsArray; for (const auto &out : outbounds) { QJsonObject outboundJsonObject; if (out.metaType == METAOUTBOUND_BALANCER) continue; if (out.metaType == METAOUTBOUND_ORIGINAL) { outboundJsonObject = out.realOutbound; } outboundJsonObject[META_OUTBOUND_KEY_NAME] = out.toJson(); const auto displayName = out.getDisplayName(); if (displayName == defaultOutboundTag) outboundsArray.prepend(outboundJsonObject); else outboundsArray.append(outboundJsonObject); } root["outbounds"] = outboundsArray; // Process DNS const auto &[dns, fakedns] = dnsWidget->GetDNSObject(); root["dns"] = GenerateDNS(dns); root["fakedns"] = fakedns.toJson(); { // Process Browser Forwarder if (!bfListenIPTxt->text().trimmed().isEmpty()) { root["browserForwarder"] = QJsonObject{ { "listenAddr", bfListenIPTxt->text() }, { "listenPort", bfListenPortTxt->value() }, }; } } { // Process Observatory QJsonObject observatory; observatory["subjectSelector"] = QJsonArray::fromStringList(SplitLines(obSubjectSelectorTxt->toPlainText())); root["observatory"] = observatory; } return root; } RouteEditor::~RouteEditor() { nodeDispatcher->LockOperation(); } void RouteEditor::on_insertDirectBtn_clicked() { auto freedom = GenerateFreedomOUT("AsIs", ""); auto tag = "Freedom_" + QSTRN(QTime::currentTime().msecsSinceStartOfDay()); auto out = GenerateOutboundEntry(tag, "freedom", freedom, {}); // ADD NODE const auto _ = nodeDispatcher->CreateOutbound(make_normal_outbound(out)); Q_UNUSED(_) statusLabel->setText(tr("Added DIRECT outbound")); } void RouteEditor::on_addDefaultBtn_clicked() { LOADINGCHECK // Add default connection from GlobalConfig // const auto &inboundConfig = GlobalConfig.inboundConfig; const static QJsonObject sniffingOff{ { "enabled", false } }; const static QJsonObject sniffingOn{ { "enabled", true }, { "destOverride", QJsonArray{ "http", "tls" } } }; // if (inboundConfig.useHTTP) { const auto httpSettings = GenerateHTTPIN(inboundConfig.httpSettings.useAuth, { inboundConfig.httpSettings.account }); const auto httpConfig = GenerateInboundEntry("GlobalConfig-HTTP", "http", // inboundConfig.listenip, // inboundConfig.httpSettings.port, // httpSettings, // inboundConfig.httpSettings.sniffing ? sniffingOn : sniffingOff); const auto _ = nodeDispatcher->CreateInbound(httpConfig); Q_UNUSED(_) } if (inboundConfig.useSocks) { const auto socks = GenerateSocksIN((inboundConfig.socksSettings.useAuth ? "password" : "noauth"), // { inboundConfig.socksSettings.account }, // inboundConfig.socksSettings.enableUDP, // inboundConfig.socksSettings.localIP); const auto socksConfig = GenerateInboundEntry("GlobalConfig-Socks", "socks", // inboundConfig.listenip, // inboundConfig.socksSettings.port, // socks, // (inboundConfig.socksSettings.sniffing ? sniffingOn : sniffingOff)); const auto _ = nodeDispatcher->CreateInbound(socksConfig); } if (inboundConfig.useTPROXY) { QList<QString> networks; #define ts inboundConfig.tProxySettings if (ts.hasTCP) networks << "tcp"; if (ts.hasUDP) networks << "udp"; const auto tproxy_network = networks.join(","); auto tproxyInSettings = GenerateDokodemoIN("", 0, tproxy_network, 0, true); // const static QJsonObject tproxy_sniff{ { "enabled", true }, { "destOverride", QJsonArray{ "http", "tls" } } }; const QJsonObject tproxy_streamSettings{ { "sockopt", QJsonObject{ { "tproxy", ts.mode } } } }; { auto tProxyIn = GenerateInboundEntry("tProxy IPv4", "dokodemo-door", ts.tProxyIP, ts.port, tproxyInSettings); tProxyIn.insert("sniffing", tproxy_sniff); tProxyIn.insert("streamSettings", tproxy_streamSettings); auto _ = nodeDispatcher->CreateInbound(tProxyIn); Q_UNUSED(_) } if (!ts.tProxyV6IP.isEmpty()) { auto tProxyV6In = GenerateInboundEntry("tProxy IPv6", "dokodemo-door", ts.tProxyV6IP, ts.port, tproxyInSettings); tProxyV6In.insert("sniffing", tproxy_sniff); tProxyV6In.insert("streamSettings", tproxy_streamSettings); auto _ = nodeDispatcher->CreateInbound(tProxyV6In); Q_UNUSED(_) } #undef ts } } void RouteEditor::on_insertBlackBtn_clicked() { LOADINGCHECK auto blackHole = GenerateBlackHoleOUT(false); auto tag = "BlackHole-" + QSTRN(QTime::currentTime().msecsSinceStartOfDay()); auto outbound = GenerateOutboundEntry(tag, "blackhole", blackHole, {}); const auto _ = nodeDispatcher->CreateOutbound(make_normal_outbound(outbound)); Q_UNUSED(_) } void RouteEditor::on_addInboundBtn_clicked() { LOADINGCHECK InboundEditor w(INBOUND(), this); auto _result = w.OpenEditor(); if (w.result() == QDialog::Accepted) { auto _ = nodeDispatcher->CreateInbound(_result); Q_UNUSED(_) } } void RouteEditor::on_addOutboundBtn_clicked() { LOADINGCHECK OutboundEditor w(OUTBOUND(), this); auto _result = w.OpenEditor(); if (w.result() == QDialog::Accepted) { auto _ = nodeDispatcher->CreateOutbound(make_normal_outbound(_result)); } } void RouteEditor::on_domainStrategyCombo_currentIndexChanged(int arg1) { LOADINGCHECK domainStrategy = domainStrategyCombo->itemText(arg1); } void RouteEditor::on_defaultOutboundCombo_currentTextChanged(const QString &arg1) { LOADINGCHECK if (defaultOutboundTag != arg1) { LOG("Default outbound changed:", arg1); defaultOutboundTag = arg1; } } void RouteEditor::on_importExistingBtn_clicked() { const auto ImportConnection = [this](const ConnectionId &_id) { const auto root = ConnectionManager->GetConnectionRoot(_id); auto outbound = OUTBOUND(root["outbounds"].toArray()[0].toObject()); outbound["tag"] = GetDisplayName(_id); auto _ = nodeDispatcher->CreateOutbound(make_normal_outbound(outbound)); Q_UNUSED(_) }; const auto cid = ConnectionId{ importConnBtn->currentData(Qt::UserRole).toString() }; if (cid.toString() == IMPORT_ALL_CONNECTIONS_SEPARATOR) return; if (cid.toString() == IMPORT_ALL_CONNECTIONS_FAKE_ID) { const auto group = GroupId{ importGroupBtn->currentData(Qt::UserRole).toString() }; if (QvMessageBoxAsk(this, tr("Importing All Connections"), tr("Do you want to import all the connections?")) != Yes) return; for (const auto &connId : ConnectionManager->GetConnections(group)) { ImportConnection(connId); } return; } else { ImportConnection(cid); } } void RouteEditor::on_linkExistingBtn_clicked() { const auto ImportConnection = [this](const ConnectionId &_id) { auto _ = nodeDispatcher->CreateOutbound(make_external_outbound(_id, GetDisplayName(_id))); Q_UNUSED(_) }; const auto cid = ConnectionId{ importConnBtn->currentData(Qt::UserRole).toString() }; if (cid.toString() == IMPORT_ALL_CONNECTIONS_SEPARATOR) return; if (cid.toString() == IMPORT_ALL_CONNECTIONS_FAKE_ID) { const auto group = GroupId{ importGroupBtn->currentData(Qt::UserRole).toString() }; if (QvMessageBoxAsk(this, tr("Importing All Connections"), tr("Do you want to import all the connections?")) != Yes) return; for (const auto &connId : ConnectionManager->GetConnections(group)) { ImportConnection(connId); } return; } else { ImportConnection(cid); } } void RouteEditor::on_importGroupBtn_currentIndexChanged(int) { const auto group = GroupId{ importGroupBtn->currentData(Qt::UserRole).toString() }; importConnBtn->clear(); for (const auto &connId : ConnectionManager->GetConnections(group)) { importConnBtn->addItem(GetDisplayName(connId), connId.toString()); } importConnBtn->addItem("————————————————", IMPORT_ALL_CONNECTIONS_SEPARATOR); importConnBtn->addItem(tr("(All Connections)"), IMPORT_ALL_CONNECTIONS_FAKE_ID); } void RouteEditor::on_addBalancerBtn_clicked() { auto _ = nodeDispatcher->CreateOutbound(make_balancer_outbound({}, "random", "Balancer")); Q_UNUSED(_) } void RouteEditor::on_addChainBtn_clicked() { auto _ = nodeDispatcher->CreateOutbound(make_chained_outbound({}, "Chained Outbound")); Q_UNUSED(_) } void RouteEditor::on_debugPainterCB_clicked(bool checked) { #ifdef QT_DEBUG QtNodes::ConnectionPainter::IsDebuggingEnabled = checked; ruleWidget->getScene()->update(); chainWidget->getScene()->update(); #endif } void RouteEditor::on_importOutboundBtn_clicked() { LOADINGCHECK ImportConfigWindow w(this); // True here for not keep the inbounds. auto configs = w.SelectConnection(true); for (auto i = 0; i < configs.count(); i++) { const auto conf = configs.values()[i]; const auto name = configs.key(conf, ""); if (name.isEmpty()) continue; // conf is rootObject, needs to unwrap it. const auto confList = conf["outbounds"].toArray(); for (int i = 0; i < confList.count(); i++) { auto _ = nodeDispatcher->CreateOutbound(make_normal_outbound(OUTBOUND(confList[i].toObject()))); Q_UNUSED(_) } } }
21,173
C++
.cpp
513
33.896686
153
0.648523
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,199
w_OutboundEditor.cpp
Qv2ray_Qv2ray/src/ui/widgets/editors/w_OutboundEditor.cpp
#include "w_OutboundEditor.hpp" #include "core/connection/Generation.hpp" #include "plugin-interface/QvGUIPluginInterface.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "ui/widgets/editors/w_JsonEditor.hpp" #include "ui/widgets/editors/w_RoutesEditor.hpp" #include <QFile> #include <QIntValidator> #define QV_MODULE_NAME "OutboundEditor" OutboundEditor::OutboundEditor(QWidget *parent) : QDialog(parent), tag(OUTBOUND_TAG_PROXY) { QvMessageBusConnect(OutboundEditor); setupUi(this); // streamSettingsWidget = new StreamSettingsWidget(this); streamSettingsWidget->SetStreamObject({}); transportFrame->addWidget(streamSettingsWidget); // for (const auto &name : PluginHost->UsablePlugins()) { const auto &plugin = PluginHost->GetPlugin(name); if (!plugin->hasComponent(COMPONENT_GUI)) continue; const auto guiInterface = plugin->pluginInterface->GetGUIInterface(); if (!guiInterface) LOG("Found a plugin with COMPONENT_GUI but returns an invalid GUI interface: " + plugin->metadata.Name); if (!guiInterface->GetComponents().contains(GUI_COMPONENT_OUTBOUND_EDITOR)) continue; const auto editors = guiInterface->GetOutboundEditors(); for (const auto &editorInfo : editors) { outBoundTypeCombo->addItem(editorInfo.first.displayName, editorInfo.first.protocol); outboundTypeStackView->addWidget(editorInfo.second); pluginWidgets.insert(editorInfo.first.protocol, editorInfo.second); } } outBoundTypeCombo->model()->sort(0); useForwardProxy = false; } QvMessageBusSlotImpl(OutboundEditor) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; case UPDATE_COLORSCHEME: break; } } OutboundEditor::OutboundEditor(const OUTBOUND &outboundEntry, QWidget *parent) : OutboundEditor(parent) { originalConfig = outboundEntry; reloadGUI(); } OutboundEditor::~OutboundEditor() { } OUTBOUND OutboundEditor::OpenEditor() { int resultCode = this->exec(); return resultCode == QDialog::Accepted ? resultConfig : originalConfig; } QString OutboundEditor::GetFriendlyName() { auto host = ipLineEdit->text().replace(":", "-").replace("/", "_").replace("\\", "_"); auto port = portLineEdit->text().replace(":", "-").replace("/", "_").replace("\\", "_"); return tag.isEmpty() ? outboundType + "@" + host + ":" + port : tag; } OUTBOUND OutboundEditor::generateConnectionJson() { OUTBOUNDSETTING settings; auto streaming = streamSettingsWidget->GetStreamSettings().toJson(); bool processed = false; for (const auto &[protocol, widget] : pluginWidgets.toStdMap()) { if (protocol == outboundType) { widget->SetHostAddress(serverAddress, serverPort); settings = OUTBOUNDSETTING(widget->GetContent()); const auto prop = widget->property(""); const auto hasStreamSettings = GetProperty(widget, "QV2RAY_INTERNAL_HAS_STREAMSETTINGS"); if (!hasStreamSettings) streaming = {}; processed = true; break; } } if (!processed) { QvMessageBoxWarn(this, tr("Unknown outbound type."), tr("The specified outbound type is not supported, this may happen due to a plugin failure.")); } auto root = GenerateOutboundEntry(tag, outboundType, settings, streaming, muxConfig); root[QV2RAY_USE_FPROXY_KEY] = useForwardProxy; return root; } void OutboundEditor::reloadGUI() { tag = originalConfig["tag"].toString(); tagTxt->setText(tag); outboundType = originalConfig["protocol"].toString("vmess"); muxConfig = originalConfig.contains("mux") ? originalConfig["mux"].toObject() : QJsonObject{}; useForwardProxy = originalConfig[QV2RAY_USE_FPROXY_KEY].toBool(false); streamSettingsWidget->SetStreamObject(StreamSettingsObject::fromJson(originalConfig["streamSettings"].toObject())); // useFPCB->setChecked(useForwardProxy); muxEnabledCB->setChecked(muxConfig["enabled"].toBool()); muxConcurrencyTxt->setValue(muxConfig["concurrency"].toInt()); // const auto &settings = originalConfig["settings"].toObject(); // bool processed = false; for (const auto &[protocol, widget] : pluginWidgets.toStdMap()) { if (protocol == outboundType) { outBoundTypeCombo->setCurrentIndex(outBoundTypeCombo->findData(protocol)); widget->SetContent(settings); const auto &[_address, _port] = widget->GetHostAddress(); serverAddress = _address; serverPort = _port; ipLineEdit->setText(_address); portLineEdit->setText(QSTRN(_port)); processed = true; break; } } if (!processed) { LOG("Outbound type: ", outboundType, " is not supported."); QvMessageBoxWarn(this, tr("Unknown outbound."), tr("The specified outbound type is invalid, this may be caused by a plugin failure.") + NEWLINE + tr("Please use the JsonEditor or reload the plugin.")); reject(); } } void OutboundEditor::on_buttonBox_accepted() { resultConfig = generateConnectionJson(); } void OutboundEditor::on_ipLineEdit_textEdited(const QString &arg1) { serverAddress = arg1; } void OutboundEditor::on_portLineEdit_textEdited(const QString &arg1) { serverPort = arg1.toInt(); } void OutboundEditor::on_tagTxt_textEdited(const QString &arg1) { tag = arg1; } void OutboundEditor::on_muxEnabledCB_stateChanged(int arg1) { muxConfig["enabled"] = arg1 == Qt::Checked; } void OutboundEditor::on_muxConcurrencyTxt_valueChanged(int arg1) { muxConfig["concurrency"] = arg1; } void OutboundEditor::on_useFPCB_stateChanged(int arg1) { useForwardProxy = arg1 == Qt::Checked; streamSettingsWidget->setEnabled(!useForwardProxy); } void OutboundEditor::on_outBoundTypeCombo_currentIndexChanged(int) { outboundType = outBoundTypeCombo->currentData().toString(); auto newWidget = pluginWidgets[outboundType]; if (!newWidget) return; outboundTypeStackView->setCurrentWidget(newWidget); const auto hasStreamSettings = GetProperty(newWidget, "QV2RAY_INTERNAL_HAS_STREAMSETTINGS"); const auto hasForwardProxy = GetProperty(newWidget, "QV2RAY_INTERNAL_HAS_FORWARD_PROXY"); streamSettingsWidget->setEnabled(hasStreamSettings); useFPCB->setEnabled(hasForwardProxy); if (!hasForwardProxy) useFPCB->setToolTip(tr("Forward proxy has been disabled when using plugin outbound")); }
6,739
C++
.cpp
179
31.810056
122
0.691296
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,200
StyleManager.cpp
Qv2ray_Qv2ray/src/ui/widgets/styles/StyleManager.cpp
#include "StyleManager.hpp" #include "base/Qv2rayBase.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" #include <QApplication> #include <QColor> #include <QPalette> #include <QStyle> #include <QStyleFactory> constexpr auto QV2RAY_BUILT_IN_DARK_MODE_NAME = "Built-in Darkmode"; #define QV_MODULE_NAME "StyleManager" namespace Qv2ray::ui::styles { QvStyleManager::QvStyleManager(QObject *parent) : QObject(parent) { ReloadStyles(); } void QvStyleManager::ReloadStyles() { styles.clear(); styles.insert(QV2RAY_BUILT_IN_DARK_MODE_NAME, {}); for (const auto &key : QStyleFactory::keys()) { LOG("Found factory style: " + key); QvStyle style; style.Name = key; style.Type = QvStyle::QVSTYLE_FACTORY; styles.insert(key, style); } for (const auto &styleDir : QvCoreApplication->GetAssetsPaths("uistyles")) { for (const auto &file : GetFileList(QDir(styleDir))) { QFileInfo fileInfo(styleDir + "/" + file); if (fileInfo.suffix() == "css" || fileInfo.suffix() == "qss" || fileInfo.suffix() == "qvstyle") { LOG("Found QSS style at: \"" + fileInfo.absoluteFilePath() + "\""); QvStyle style; style.Name = fileInfo.baseName(); style.qssPath = fileInfo.absoluteFilePath(); style.Type = QvStyle::QVSTYLE_QSS; styles.insert(style.Name, style); } } } } bool QvStyleManager::ApplyStyle(const QString &style) { if (!styles.contains(style)) return false; qApp->setStyle("fusion"); if (style == QV2RAY_BUILT_IN_DARK_MODE_NAME) { LOG("Applying built-in darkmode theme."); // From https://forum.qt.io/topic/101391/windows-10-dark-theme/4 static const QColor darkColor(45, 45, 45); static const QColor disabledColor(70, 70, 70); static const QColor defaultTextColor(210, 210, 210); // QPalette darkPalette; darkPalette.setColor(QPalette::Window, darkColor); darkPalette.setColor(QPalette::Button, darkColor); darkPalette.setColor(QPalette::AlternateBase, darkColor); // darkPalette.setColor(QPalette::Text, defaultTextColor); darkPalette.setColor(QPalette::ButtonText, defaultTextColor); darkPalette.setColor(QPalette::WindowText, defaultTextColor); darkPalette.setColor(QPalette::ToolTipBase, defaultTextColor); darkPalette.setColor(QPalette::ToolTipText, defaultTextColor); // darkPalette.setColor(QPalette::Disabled, QPalette::Text, disabledColor); darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, disabledColor); darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, disabledColor); darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, disabledColor); // darkPalette.setColor(QPalette::Base, QColor(18, 18, 18)); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); // darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::HighlightedText, Qt::black); qApp->setPalette(darkPalette); qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return true; } const auto &s = styles[style]; switch (s.Type) { case QvStyle::QVSTYLE_QSS: { LOG("Applying UI QSS style: " + s.qssPath); const auto content = StringFromFile(s.qssPath); qApp->setStyleSheet(content); break; } case QvStyle::QVSTYLE_FACTORY: { LOG("Applying UI style: " + s.Name); const auto &_style = QStyleFactory::create(s.Name); qApp->setPalette(_style->standardPalette()); qApp->setStyle(_style); qApp->setStyleSheet(""); break; } default: { return false; } } qApp->processEvents(); return true; } } // namespace Qv2ray::ui::styles
4,641
C++
.cpp
113
29.876106
116
0.580752
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,201
w_PluginManager.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_PluginManager.cpp
#include "w_PluginManager.hpp" #include "components/plugins/QvPluginHost.hpp" #include "core/settings/SettingsBackend.hpp" #include "ui/widgets/editors/w_JsonEditor.hpp" #include "utils/QvHelpers.hpp" #include <QDesktopServices> PluginManageWindow::PluginManageWindow(QWidget *parent) : QvDialog("PluginManager", parent) { addStateOptions("width", { [&] { return width(); }, [&](QJsonValue val) { resize(val.toInt(), size().height()); } }); addStateOptions("height", { [&] { return height(); }, [&](QJsonValue val) { resize(size().width(), val.toInt()); } }); addStateOptions("x", { [&] { return x(); }, [&](QJsonValue val) { move(val.toInt(), y()); } }); addStateOptions("y", { [&] { return y(); }, [&](QJsonValue val) { move(x(), val.toInt()); } }); setupUi(this); for (auto &plugin : PluginHost->AllPlugins()) { const auto &info = PluginHost->GetPlugin(plugin)->metadata; auto item = new QListWidgetItem(pluginListWidget); item->setCheckState(PluginHost->GetPluginEnabled(info.InternalName) ? Qt::Checked : Qt::Unchecked); item->setData(Qt::UserRole, info.InternalName); item->setText(info.Name + " (" + (PluginHost->GetPlugin(info.InternalName)->isLoaded ? tr("Loaded") : tr("Not loaded")) + ")"); pluginListWidget->addItem(item); } pluginListWidget->sortItems(); isLoading = false; if (pluginListWidget->count() > 0) on_pluginListWidget_currentItemChanged(pluginListWidget->item(0), nullptr); } QvMessageBusSlotImpl(PluginManageWindow){ Q_UNUSED(msg) } PluginManageWindow::~PluginManageWindow() { on_pluginListWidget_currentItemChanged(nullptr, nullptr); } void PluginManageWindow::on_pluginListWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous) if (currentPluginInfo && currentSettingsWidget) { currentPluginInfo->pluginInterface->UpdateSettings(currentSettingsWidget->GetSettings()); pluginSettingsLayout->removeWidget(currentSettingsWidget.get()); currentSettingsWidget.reset(); } pluginIconLabel->clear(); if (!current) return; currentPluginInfo = PluginHost->GetPlugin(current->data(Qt::UserRole).toString()); auto &info = currentPluginInfo->metadata; pluginNameLabel->setText(info.Name); pluginAuthorLabel->setText(info.Author); pluginDescriptionLabel->setText(info.Description); pluginLibPathLabel->setText(currentPluginInfo->libraryPath); pluginStateLabel->setText(currentPluginInfo->isLoaded ? tr("Loaded") : tr("Not loaded")); pluginComponentsLabel->setText(GetPluginComponentsString(info.Components).join(NEWLINE)); if (!currentPluginInfo->isLoaded) { pluginUnloadLabel->setVisible(true); pluginUnloadLabel->setText(tr("Plugin Not Loaded")); return; } if (currentPluginInfo->hasComponent(COMPONENT_GUI)) { const auto pluginUIInterface = currentPluginInfo->pluginInterface->GetGUIInterface(); pluginGuiComponentsLabel->setText(GetPluginComponentsString(pluginUIInterface->GetComponents()).join(NEWLINE)); pluginIconLabel->setPixmap(pluginUIInterface->Icon().pixmap(pluginIconLabel->size() * devicePixelRatio())); if (pluginUIInterface->GetComponents().contains(GUI_COMPONENT_SETTINGS)) { currentSettingsWidget = pluginUIInterface->GetSettingsWidget(); currentSettingsWidget->SetSettings(currentPluginInfo->pluginInterface->GetSettngs()); pluginUnloadLabel->setVisible(false); pluginSettingsLayout->addWidget(currentSettingsWidget.get()); } else { pluginUnloadLabel->setVisible(true); pluginUnloadLabel->setText(tr("Plugin does not have settings widget.")); } } else { pluginGuiComponentsLabel->setText(tr("None")); } } void PluginManageWindow::on_pluginListWidget_itemClicked(QListWidgetItem *item) { Q_UNUSED(item) // on_pluginListWidget_currentItemChanged(item, nullptr); } void PluginManageWindow::on_pluginListWidget_itemChanged(QListWidgetItem *item) { if (isLoading) return; bool isEnabled = item->checkState() == Qt::Checked; const auto pluginInternalName = item->data(Qt::UserRole).toString(); PluginHost->SetPluginEnabled(pluginInternalName, isEnabled); const auto info = PluginHost->GetPlugin(pluginInternalName); item->setText(info->metadata.Name + " (" + (info->isLoaded ? tr("Loaded") : tr("Not loaded")) + ")"); } void PluginManageWindow::on_pluginEditSettingsJsonBtn_clicked() { if (const auto &current = pluginListWidget->currentItem(); current != nullptr) { const auto &info = PluginHost->GetPlugin(current->data(Qt::UserRole).toString()); if (!info->isLoaded) { QvMessageBoxWarn(this, tr("Plugin not loaded"), tr("This plugin is not loaded, please enable or reload the plugin to continue.")); return; } JsonEditor w(info->pluginInterface->GetSettngs()); auto newConf = w.OpenEditor(); if (w.result() == QDialog::Accepted) { info->pluginInterface->UpdateSettings(newConf); } } } void PluginManageWindow::on_pluginListWidget_itemSelectionChanged() { auto needEnable = !pluginListWidget->selectedItems().isEmpty(); pluginEditSettingsJsonBtn->setEnabled(needEnable); } void PluginManageWindow::on_openPluginFolder_clicked() { QDir pluginPath(QV2RAY_CONFIG_DIR + "plugins/"); if (!pluginPath.exists()) { pluginPath.mkpath(QV2RAY_CONFIG_DIR + "plugins/"); } QDesktopServices::openUrl(QUrl::fromLocalFile(pluginPath.absolutePath())); } void PluginManageWindow::on_toolButton_clicked() { QDesktopServices::openUrl(QUrl("https://qv2ray.net/plugins/")); }
5,849
C++
.cpp
132
38.606061
142
0.703684
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,202
w_PreferencesWindow.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_PreferencesWindow.cpp
#include "w_PreferencesWindow.hpp" #include "components/ntp/QvNTPClient.hpp" #include "components/translations/QvTranslator.hpp" #include "core/connection/ConnectionIO.hpp" #include "core/handler/ConfigHandler.hpp" #include "core/kernel/V2RayKernelInteractions.hpp" #include "core/settings/SettingsBackend.hpp" #include "src/plugin-interface/QvPluginInterface.hpp" #include "ui/common/autolaunch/QvAutoLaunch.hpp" #include "ui/widgets/styles/StyleManager.hpp" #include "ui/widgets/widgets/DnsSettingsWidget.hpp" #include "ui/widgets/widgets/RouteSettingsMatrix.hpp" #include "utils/HTTPRequestHelper.hpp" #include "utils/QvHelpers.hpp" #include <QColorDialog> #include <QCompleter> #include <QDesktopServices> #include <QFileDialog> #include <QHostInfo> #include <QInputDialog> #include <QMessageBox> using Qv2ray::common::validation::IsIPv4Address; using Qv2ray::common::validation::IsIPv6Address; using Qv2ray::common::validation::IsValidDNSServer; using Qv2ray::common::validation::IsValidIPAddress; #define LOADINGCHECK \ if (!finishedLoading) \ return; #define NEEDRESTART \ LOADINGCHECK \ if (finishedLoading) \ NeedRestart = true; #define SET_PROXY_UI_ENABLE(_enabled) \ qvProxyTypeCombo->setEnabled(_enabled); \ qvProxyAddressTxt->setEnabled(_enabled); \ qvProxyPortCB->setEnabled(_enabled); #define SET_AUTOSTART_UI_ENABLED(_enabled) \ autoStartConnCombo->setEnabled(_enabled); \ autoStartSubsCombo->setEnabled(_enabled); #define SET_AUTOSTART_START_MINIMIZED_ENABLED(_enabled) startMinimizedCB->setEnabled(_enabled); PreferencesWindow::PreferencesWindow(QWidget *parent) : QvDialog("PreferenceWindow", parent), CurrentConfig() { addStateOptions("width", { [&] { return width(); }, [&](QJsonValue val) { resize(val.toInt(), size().height()); } }); addStateOptions("height", { [&] { return height(); }, [&](QJsonValue val) { resize(size().width(), val.toInt()); } }); addStateOptions("x", { [&] { return x(); }, [&](QJsonValue val) { move(val.toInt(), y()); } }); addStateOptions("y", { [&] { return y(); }, [&](QJsonValue val) { move(x(), val.toInt()); } }); setupUi(this); // QvMessageBusConnect(PreferencesWindow); textBrowser->setHtml(StringFromFile(":/assets/credit.html")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); configdirLabel->setText(QV2RAY_CONFIG_DIR); // We add locales auto langs = Qv2rayTranslator->GetAvailableLanguages(); if (!langs.empty()) { languageComboBox->clear(); languageComboBox->addItems(langs); } else { languageComboBox->setDisabled(true); // Since we can't have languages detected. It worths nothing to translate these. languageComboBox->setToolTip("Cannot find any language providers."); } // Set auto start button state SetAutoStartButtonsState(GetLaunchAtLoginStatus()); themeCombo->addItems(StyleManager->AllStyles()); // qvVersion->setText(QV2RAY_VERSION_STRING ":" + QSTRN(QV2RAY_VERSION_BUILD)); qvBuildInfo->setText(QV2RAY_BUILD_INFO); qvBuildExInfo->setText(QV2RAY_BUILD_EXTRA_INFO); qvBuildTime->setText(__DATE__ " " __TIME__); qvPluginInterfaceVersionLabel->setText(tr("Version: %1").arg(QV2RAY_PLUGIN_INTERFACE_VERSION)); // // Deep copy CurrentConfig.loadJson(GlobalConfig.toJson()); // themeCombo->setCurrentText(CurrentConfig.uiConfig.theme); darkThemeCB->setChecked(CurrentConfig.uiConfig.useDarkTheme); darkTrayCB->setChecked(CurrentConfig.uiConfig.useDarkTrayIcon); glyphTrayCB->setChecked(CurrentConfig.uiConfig.useGlyphTrayIcon); languageComboBox->setCurrentText(CurrentConfig.uiConfig.language); logLevelComboBox->setCurrentIndex(CurrentConfig.logLevel); quietModeCB->setChecked(CurrentConfig.uiConfig.quietMode); useOldShareLinkFormatCB->setChecked(CurrentConfig.uiConfig.useOldShareLinkFormat); startMinimizedCB->setChecked(CurrentConfig.uiConfig.startMinimized); startMinimizedCB->setEnabled(CurrentConfig.autoStartBehavior != AUTO_CONNECTION_NONE); exitByCloseEventCB->setChecked(CurrentConfig.uiConfig.exitByCloseEvent); // // listenIPTxt->setText(CurrentConfig.inboundConfig.listenip); // { const auto &httpSettings = CurrentConfig.inboundConfig.httpSettings; const auto has_http = CurrentConfig.inboundConfig.useHTTP; httpGroupBox->setChecked(has_http); httpPortLE->setValue(httpSettings.port); httpAuthCB->setChecked(httpSettings.useAuth); // httpAuthUsernameTxt->setEnabled(has_http && httpSettings.useAuth); httpAuthPasswordTxt->setEnabled(has_http && httpSettings.useAuth); httpAuthUsernameTxt->setText(httpSettings.account.user); httpAuthPasswordTxt->setText(httpSettings.account.pass); // httpSniffingCB->setChecked(httpSettings.sniffing); httpSniffingMetadataOnly->setEnabled(has_http && httpSettings.sniffing); httpOverrideHTTPCB->setEnabled(has_http && httpSettings.sniffing); httpOverrideTLSCB->setEnabled(has_http && httpSettings.sniffing); httpOverrideFakeDNSCB->setEnabled(has_http && httpSettings.sniffing); httpOverrideFakeDNSOthersCB->setEnabled(has_http && httpSettings.sniffing); httpOverrideHTTPCB->setChecked(httpSettings.destOverride.contains("http")); httpOverrideTLSCB->setChecked(httpSettings.destOverride.contains("tls")); httpOverrideFakeDNSCB->setChecked(httpSettings.destOverride.contains("fakedns")); httpOverrideFakeDNSOthersCB->setChecked(httpSettings.destOverride.contains("fakedns+others")); httpSniffingMetadataOnly->setChecked(httpSettings.metadataOnly); } { const auto &socksSettings = CurrentConfig.inboundConfig.socksSettings; const auto has_socks = CurrentConfig.inboundConfig.useSocks; socksGroupBox->setChecked(has_socks); socksPortLE->setValue(socksSettings.port); // socksAuthCB->setChecked(socksSettings.useAuth); socksAuthUsernameTxt->setEnabled(has_socks && socksSettings.useAuth); socksAuthPasswordTxt->setEnabled(has_socks && socksSettings.useAuth); socksAuthUsernameTxt->setText(socksSettings.account.user); socksAuthPasswordTxt->setText(socksSettings.account.pass); // Socks UDP Options socksUDPCB->setChecked(socksSettings.enableUDP); socksUDPIP->setEnabled(has_socks && socksSettings.enableUDP); socksUDPIP->setText(socksSettings.localIP); // socksSniffingCB->setChecked(socksSettings.sniffing); socksSniffingMetadataOnly->setEnabled(has_socks && socksSettings.sniffing); socksOverrideHTTPCB->setEnabled(has_socks && socksSettings.sniffing); socksOverrideTLSCB->setEnabled(has_socks && socksSettings.sniffing); socksOverrideFakeDNSCB->setEnabled(has_socks && socksSettings.sniffing); socksOverrideFakeDNSOthersCB->setEnabled(has_socks && socksSettings.sniffing); socksOverrideHTTPCB->setChecked(socksSettings.destOverride.contains("http")); socksOverrideTLSCB->setChecked(socksSettings.destOverride.contains("tls")); socksOverrideFakeDNSCB->setChecked(socksSettings.destOverride.contains("fakedns")); socksOverrideFakeDNSOthersCB->setChecked(socksSettings.destOverride.contains("fakedns+others")); socksSniffingMetadataOnly->setChecked(socksSettings.metadataOnly); } { const auto &tProxySettings = CurrentConfig.inboundConfig.tProxySettings; const auto has_tproxy = CurrentConfig.inboundConfig.useTPROXY; tproxyGroupBox->setChecked(has_tproxy); tproxyListenAddr->setText(tProxySettings.tProxyIP); tproxyListenV6Addr->setText(tProxySettings.tProxyV6IP); tProxyPort->setValue(tProxySettings.port); tproxyEnableTCP->setChecked(tProxySettings.hasTCP); tproxyEnableUDP->setChecked(tProxySettings.hasUDP); // tproxySniffingCB->setChecked(tProxySettings.sniffing); tproxySniffingMetadataOnlyCB->setEnabled(has_tproxy && tProxySettings.sniffing); tproxyOverrideHTTPCB->setEnabled(has_tproxy && tProxySettings.sniffing); tproxyOverrideTLSCB->setEnabled(has_tproxy && tProxySettings.sniffing); tproxyOverrideFakeDNSCB->setEnabled(has_tproxy && tProxySettings.sniffing); tproxyOverrideFakeDNSOthersCB->setEnabled(has_tproxy && tProxySettings.sniffing); tproxyOverrideHTTPCB->setChecked(tProxySettings.destOverride.contains("http")); tproxyOverrideTLSCB->setChecked(tProxySettings.destOverride.contains("tls")); tproxyOverrideFakeDNSCB->setChecked(tProxySettings.destOverride.contains("fakedns")); tproxyOverrideFakeDNSOthersCB->setChecked(tProxySettings.destOverride.contains("fakedns+others")); tproxySniffingMetadataOnlyCB->setChecked(tProxySettings.metadataOnly); tproxyMode->setCurrentText(tProxySettings.mode); } { const auto &browserForwarderSettings = CurrentConfig.inboundConfig.browserForwarderSettings; browserForwarderAddressTxt->setText(browserForwarderSettings.address); browserForwarderPortSB->setValue(browserForwarderSettings.port); } outboundMark->setValue(CurrentConfig.outboundConfig.mark); // dnsIntercept->setChecked(CurrentConfig.defaultRouteConfig.connectionConfig.dnsIntercept); dnsFreedomCb->setChecked(CurrentConfig.defaultRouteConfig.connectionConfig.v2rayFreedomDNS); // // Kernel Settings { vCorePathTxt->setText(CurrentConfig.kernelConfig.KernelPath()); vCoreAssetsPathTxt->setText(CurrentConfig.kernelConfig.AssetsPath()); enableAPI->setChecked(CurrentConfig.kernelConfig.enableAPI); statsPortBox->setValue(CurrentConfig.kernelConfig.statsPort); // V2RayOutboundStatsCB->setChecked(CurrentConfig.uiConfig.graphConfig.useOutboundStats); hasDirectStatisticsCB->setEnabled(CurrentConfig.uiConfig.graphConfig.useOutboundStats); hasDirectStatisticsCB->setChecked(CurrentConfig.uiConfig.graphConfig.hasDirectStats); // pluginKernelV2RayIntegrationCB->setChecked(CurrentConfig.pluginConfig.v2rayIntegration); pluginKernelPortAllocateCB->setValue(CurrentConfig.pluginConfig.portAllocationStart); pluginKernelPortAllocateCB->setEnabled(CurrentConfig.pluginConfig.v2rayIntegration); } // Connection Settings { bypassCNCb->setChecked(CurrentConfig.defaultRouteConfig.connectionConfig.bypassCN); bypassBTCb->setChecked(CurrentConfig.defaultRouteConfig.connectionConfig.bypassBT); proxyDefaultCb->setChecked(!CurrentConfig.defaultRouteConfig.connectionConfig.enableProxy); bypassPrivateCb->setChecked(CurrentConfig.defaultRouteConfig.connectionConfig.bypassLAN); } // // latencyTCPingRB->setChecked(CurrentConfig.networkConfig.latencyTestingMethod == TCPING); latencyICMPingRB->setChecked(CurrentConfig.networkConfig.latencyTestingMethod == ICMPING); latencyRealPingTestURLTxt->setText(CurrentConfig.networkConfig.latencyRealPingTestURL); // { qvProxyPortCB->setValue(CurrentConfig.networkConfig.port); qvProxyAddressTxt->setText(CurrentConfig.networkConfig.address); qvProxyTypeCombo->setCurrentText(CurrentConfig.networkConfig.type); qvNetworkUATxt->setEditText(CurrentConfig.networkConfig.userAgent); // qvProxyNoProxy->setChecked(CurrentConfig.networkConfig.proxyType == Qv2rayConfig_Network::QVPROXY_NONE); qvProxySystemProxy->setChecked(CurrentConfig.networkConfig.proxyType == Qv2rayConfig_Network::QVPROXY_SYSTEM); qvProxyCustomProxy->setChecked(CurrentConfig.networkConfig.proxyType == Qv2rayConfig_Network::QVPROXY_CUSTOM); SET_PROXY_UI_ENABLE(CurrentConfig.networkConfig.proxyType == Qv2rayConfig_Network::QVPROXY_CUSTOM) } // // // // Advanced config. { setTestLatencyCB->setChecked(CurrentConfig.advancedConfig.testLatencyPeriodically); setTestLatencyOnConnectedCB->setChecked(CurrentConfig.advancedConfig.testLatencyOnConnected); disableSystemRootCB->setChecked(CurrentConfig.advancedConfig.disableSystemRoot); } // { dnsSettingsWidget = new DnsSettingsWidget(this); dnsSettingsWidget->SetDNSObject(CurrentConfig.defaultRouteConfig.dnsConfig, CurrentConfig.defaultRouteConfig.fakeDNSConfig); dnsSettingsLayout->addWidget(dnsSettingsWidget); // routeSettingsWidget = new RouteSettingsMatrixWidget(CurrentConfig.kernelConfig.AssetsPath(), this); routeSettingsWidget->SetRouteConfig(CurrentConfig.defaultRouteConfig.routeConfig); advRouteSettingsLayout->addWidget(routeSettingsWidget); } // #ifdef DISABLE_AUTO_UPDATE updateSettingsGroupBox->setEnabled(false); updateSettingsGroupBox->setToolTip(tr("Update is disabled by your vendor.")); #endif // updateChannelCombo->setCurrentIndex(CurrentConfig.updateConfig.updateChannel); cancelIgnoreVersionBtn->setEnabled(!CurrentConfig.updateConfig.ignoredVersion.isEmpty()); ignoredNextVersion->setText(CurrentConfig.updateConfig.ignoredVersion); // // { noAutoConnectRB->setChecked(CurrentConfig.autoStartBehavior == AUTO_CONNECTION_NONE); lastConnectedRB->setChecked(CurrentConfig.autoStartBehavior == AUTO_CONNECTION_LAST_CONNECTED); fixedAutoConnectRB->setChecked(CurrentConfig.autoStartBehavior == AUTO_CONNECTION_FIXED); // SET_AUTOSTART_UI_ENABLED(CurrentConfig.autoStartBehavior == AUTO_CONNECTION_FIXED); // if (CurrentConfig.autoStartId.isEmpty()) { CurrentConfig.autoStartId.groupId = DefaultGroupId; } // const auto &autoStartConnId = CurrentConfig.autoStartId.connectionId; const auto &autoStartGroupId = CurrentConfig.autoStartId.groupId; // for (const auto &group : ConnectionManager->AllGroups()) // autoStartSubsCombo->addItem(GetDisplayName(group), group.toString()); autoStartSubsCombo->setCurrentText(GetDisplayName(autoStartGroupId)); for (const auto &conn : ConnectionManager->GetConnections(autoStartGroupId)) autoStartConnCombo->addItem(GetDisplayName(conn), conn.toString()); autoStartConnCombo->setCurrentText(GetDisplayName(autoStartConnId)); } // FP Settings if (CurrentConfig.defaultRouteConfig.forwardProxyConfig.type.trimmed().isEmpty()) { CurrentConfig.defaultRouteConfig.forwardProxyConfig.type = "http"; } fpGroupBox->setChecked(CurrentConfig.defaultRouteConfig.forwardProxyConfig.enableForwardProxy); fpUsernameTx->setText(CurrentConfig.defaultRouteConfig.forwardProxyConfig.username); fpPasswordTx->setText(CurrentConfig.defaultRouteConfig.forwardProxyConfig.password); fpAddressTx->setText(CurrentConfig.defaultRouteConfig.forwardProxyConfig.serverAddress); fpTypeCombo->setCurrentText(CurrentConfig.defaultRouteConfig.forwardProxyConfig.type); fpPortSB->setValue(CurrentConfig.defaultRouteConfig.forwardProxyConfig.port); fpUseAuthCB->setChecked(CurrentConfig.defaultRouteConfig.forwardProxyConfig.useAuth); fpUsernameTx->setEnabled(fpUseAuthCB->isChecked()); fpPasswordTx->setEnabled(fpUseAuthCB->isChecked()); // maxLogLinesSB->setValue(CurrentConfig.uiConfig.maximumLogLines); jumpListCountSB->setValue(CurrentConfig.uiConfig.maxJumpListCount); // setSysProxyCB->setChecked(CurrentConfig.inboundConfig.systemProxySettings.setSystemProxy); // finishedLoading = true; } QvMessageBusSlotImpl(PreferencesWindow) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; case UPDATE_COLORSCHEME: break; } } PreferencesWindow::~PreferencesWindow(){}; std::optional<QString> PreferencesWindow::checkTProxySettings() const { if (CurrentConfig.inboundConfig.useTPROXY) { if (!IsIPv4Address(CurrentConfig.inboundConfig.tProxySettings.tProxyIP)) { return tr("Invalid tproxy listening ipv4 address."); } else if (CurrentConfig.inboundConfig.tProxySettings.tProxyV6IP != "" && !IsIPv6Address(CurrentConfig.inboundConfig.tProxySettings.tProxyV6IP)) { return tr("Invalid tproxy listening ipv6 address."); } } return std::nullopt; } void PreferencesWindow::on_buttonBox_accepted() { // Note: // A signal-slot connection from buttonbox_accpted to QDialog::accepted() // has been removed. To prevent closing this Dialog. QSet<int> ports; auto size = 0; if (CurrentConfig.inboundConfig.useHTTP) { size++; ports << CurrentConfig.inboundConfig.httpSettings.port; } if (CurrentConfig.inboundConfig.useSocks) { size++; ports << CurrentConfig.inboundConfig.socksSettings.port; } if (CurrentConfig.inboundConfig.useTPROXY) { size++; ports << CurrentConfig.inboundConfig.tProxySettings.port; } if (!QvCoreApplication->StartupArguments.noAPI) { size++; ports << CurrentConfig.kernelConfig.statsPort; } if (ports.size() != size) { // Duplicates detected. QvMessageBoxWarn(this, tr("Preferences"), tr("Duplicated port numbers detected, please check the port number settings.")); } else if (!IsValidIPAddress(CurrentConfig.inboundConfig.listenip)) { QvMessageBoxWarn(this, tr("Preferences"), tr("Invalid inbound listening address.")); } else if (const auto err = checkTProxySettings(); err.has_value()) { QvMessageBoxWarn(this, tr("Preferences"), *err); } else if (!dnsSettingsWidget->CheckIsValidDNS()) { QvMessageBoxWarn(this, tr("Preferences"), tr("Invalid DNS settings.")); } else { if (CurrentConfig.uiConfig.language != GlobalConfig.uiConfig.language) { // Install translator if (Qv2rayTranslator->InstallTranslation(CurrentConfig.uiConfig.language)) { UIMessageBus.EmitGlobalSignal(QvMBMessage::RETRANSLATE); QApplication::processEvents(); } } CurrentConfig.defaultRouteConfig.routeConfig = routeSettingsWidget->GetRouteConfig(); if (!(CurrentConfig.defaultRouteConfig.routeConfig == GlobalConfig.defaultRouteConfig.routeConfig)) { NEEDRESTART } const auto &[dns, fakedns] = dnsSettingsWidget->GetDNSObject(); CurrentConfig.defaultRouteConfig.dnsConfig = dns; CurrentConfig.defaultRouteConfig.fakeDNSConfig = fakedns; if (!(CurrentConfig.defaultRouteConfig.dnsConfig == GlobalConfig.defaultRouteConfig.dnsConfig)) { NEEDRESTART } // // if (CurrentConfig.uiConfig.theme != GlobalConfig.uiConfig.theme) { StyleManager->ApplyStyle(CurrentConfig.uiConfig.theme); } GlobalConfig.loadJson(CurrentConfig.toJson()); SaveGlobalSettings(); UIMessageBus.EmitGlobalSignal(QvMBMessage::UPDATE_COLORSCHEME); if (NeedRestart && !KernelInstance->CurrentConnection().isEmpty()) { const auto message = tr("You may need to reconnect to apply the settings now.") + NEWLINE + // tr("Otherwise they will be applied next time you connect to a server.") + NEWLINE + // NEWLINE + // tr("Do you want to reconnect now?"); const auto askResult = QvMessageBoxAsk(this, tr("Reconnect Required"), message); if (askResult == Yes) { ConnectionManager->RestartConnection(); this->setEnabled(false); } } accept(); } } void PreferencesWindow::on_httpAuthCB_stateChanged(int checked) { NEEDRESTART bool enabled = checked == Qt::Checked; httpAuthUsernameTxt->setEnabled(enabled); httpAuthPasswordTxt->setEnabled(enabled); CurrentConfig.inboundConfig.httpSettings.useAuth = enabled; } void PreferencesWindow::on_socksAuthCB_stateChanged(int checked) { NEEDRESTART bool enabled = checked == Qt::Checked; socksAuthUsernameTxt->setEnabled(enabled); socksAuthPasswordTxt->setEnabled(enabled); CurrentConfig.inboundConfig.socksSettings.useAuth = enabled; } void PreferencesWindow::on_languageComboBox_currentTextChanged(const QString &arg1) { LOADINGCHECK CurrentConfig.uiConfig.language = arg1; } void PreferencesWindow::on_logLevelComboBox_currentIndexChanged(int index) { NEEDRESTART CurrentConfig.logLevel = index; } void PreferencesWindow::on_vCoreAssetsPathTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.kernelConfig.AssetsPath(arg1); } void PreferencesWindow::on_listenIPTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.listenip = arg1; if (arg1 == "" || IsValidIPAddress(arg1)) { BLACK(listenIPTxt); } else { RED(listenIPTxt); } // pacAccessPathTxt->setText("http://" + arg1 + ":" + // QSTRN(pacPortSB->value()) + "/pac"); } void PreferencesWindow::on_httpAuthUsernameTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.httpSettings.account.user = arg1; } void PreferencesWindow::on_httpAuthPasswordTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.httpSettings.account.pass = arg1; } void PreferencesWindow::on_socksAuthUsernameTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.socksSettings.account.user = arg1; } void PreferencesWindow::on_socksAuthPasswordTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.socksSettings.account.pass = arg1; } void PreferencesWindow::on_latencyRealPingTestURLTxt_textEdited(const QString &arg1) { CurrentConfig.networkConfig.latencyRealPingTestURL = arg1; } void PreferencesWindow::on_proxyDefaultCb_stateChanged(int arg1) { NEEDRESTART CurrentConfig.defaultRouteConfig.connectionConfig.enableProxy = !(arg1 == Qt::Checked); } void PreferencesWindow::on_selectVAssetBtn_clicked() { NEEDRESTART QString dir = QFileDialog::getExistingDirectory(this, tr("Open V2Ray assets folder"), QDir::currentPath()); if (!dir.isEmpty()) { vCoreAssetsPathTxt->setText(dir); on_vCoreAssetsPathTxt_textEdited(dir); } } void PreferencesWindow::on_selectVCoreBtn_clicked() { QString core = QFileDialog::getOpenFileName(this, tr("Open V2Ray core file"), QDir::currentPath()); if (!core.isEmpty()) { vCorePathTxt->setText(core); on_vCorePathTxt_textEdited(core); } } void PreferencesWindow::on_vCorePathTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.kernelConfig.KernelPath(arg1); } void PreferencesWindow::on_aboutQt_clicked() { QApplication::aboutQt(); } void PreferencesWindow::on_cancelIgnoreVersionBtn_clicked() { CurrentConfig.updateConfig.ignoredVersion.clear(); cancelIgnoreVersionBtn->setEnabled(false); } void PreferencesWindow::on_bypassCNCb_stateChanged(int arg1) { NEEDRESTART CurrentConfig.defaultRouteConfig.connectionConfig.bypassCN = arg1 == Qt::Checked; } void PreferencesWindow::on_bypassBTCb_stateChanged(int arg1) { NEEDRESTART if (arg1 == Qt::Checked) { QvMessageBoxInfo(this, tr("Note"), tr("To recognize the protocol of a connection, one must enable sniffing option in inbound proxy.") + NEWLINE + tr("tproxy inbound's sniffing is enabled by default.")); } CurrentConfig.defaultRouteConfig.connectionConfig.bypassBT = arg1 == Qt::Checked; } void PreferencesWindow::on_statsPortBox_valueChanged(int arg1) { NEEDRESTART CurrentConfig.kernelConfig.statsPort = arg1; } void PreferencesWindow::on_socksPortLE_valueChanged(int arg1) { NEEDRESTART CurrentConfig.inboundConfig.socksSettings.port = arg1; } void PreferencesWindow::on_httpPortLE_valueChanged(int arg1) { NEEDRESTART CurrentConfig.inboundConfig.httpSettings.port = arg1; } void PreferencesWindow::on_socksUDPCB_stateChanged(int arg1) { NEEDRESTART CurrentConfig.inboundConfig.socksSettings.enableUDP = arg1 == Qt::Checked; socksUDPIP->setEnabled(arg1 == Qt::Checked); } void PreferencesWindow::on_socksUDPIP_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.socksSettings.localIP = arg1; if (IsValidIPAddress(arg1)) { BLACK(socksUDPIP); } else { RED(socksUDPIP); } } void PreferencesWindow::on_themeCombo_currentTextChanged(const QString &arg1) { LOADINGCHECK CurrentConfig.uiConfig.theme = arg1; } void PreferencesWindow::on_darkThemeCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.useDarkTheme = arg1 == Qt::Checked; } void PreferencesWindow::on_darkTrayCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.useDarkTrayIcon = arg1 == Qt::Checked; } void PreferencesWindow::on_glyphTrayCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.useGlyphTrayIcon = arg1 == Qt::Checked; } void PreferencesWindow::on_setSysProxyCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.systemProxySettings.setSystemProxy = arg1 == Qt::Checked; } void PreferencesWindow::on_autoStartSubsCombo_currentIndexChanged(int arg1) { LOADINGCHECK if (arg1 == -1) { CurrentConfig.autoStartId.clear(); autoStartConnCombo->clear(); } else { auto list = ConnectionManager->GetConnections(GroupId(autoStartSubsCombo->currentData().toString())); autoStartConnCombo->clear(); for (const auto &id : list) { autoStartConnCombo->addItem(GetDisplayName(id), id.toString()); } } } void PreferencesWindow::on_autoStartConnCombo_currentIndexChanged(int arg1) { LOADINGCHECK if (arg1 == -1) { CurrentConfig.autoStartId.clear(); } else { CurrentConfig.autoStartId.groupId = GroupId(autoStartSubsCombo->currentData().toString()); CurrentConfig.autoStartId.connectionId = ConnectionId(autoStartConnCombo->currentData().toString()); } } void PreferencesWindow::on_startWithLoginCB_stateChanged(int arg1) { bool isEnabled = arg1 == Qt::Checked; SetLaunchAtLoginStatus(isEnabled); if (GetLaunchAtLoginStatus() != isEnabled) { QvMessageBoxWarn(this, tr("Start with boot"), tr("Failed to set auto start option.")); } SetAutoStartButtonsState(GetLaunchAtLoginStatus()); } void PreferencesWindow::SetAutoStartButtonsState(bool isAutoStart) { startWithLoginCB->setChecked(isAutoStart); } void PreferencesWindow::on_fpTypeCombo_currentIndexChanged(int arg1) { LOADINGCHECK CurrentConfig.defaultRouteConfig.forwardProxyConfig.type = fpTypeCombo->itemText(arg1).toLower(); } void PreferencesWindow::on_fpAddressTx_textEdited(const QString &arg1) { LOADINGCHECK CurrentConfig.defaultRouteConfig.forwardProxyConfig.serverAddress = arg1; if (IsValidIPAddress(arg1)) { BLACK(fpAddressTx); } else { RED(fpAddressTx); } } void PreferencesWindow::on_fpUseAuthCB_stateChanged(int arg1) { bool authEnabled = arg1 == Qt::Checked; CurrentConfig.defaultRouteConfig.forwardProxyConfig.useAuth = authEnabled; fpUsernameTx->setEnabled(authEnabled); fpPasswordTx->setEnabled(authEnabled); } void PreferencesWindow::on_fpUsernameTx_textEdited(const QString &arg1) { LOADINGCHECK CurrentConfig.defaultRouteConfig.forwardProxyConfig.username = arg1; } void PreferencesWindow::on_fpPasswordTx_textEdited(const QString &arg1) { LOADINGCHECK CurrentConfig.defaultRouteConfig.forwardProxyConfig.password = arg1; } void PreferencesWindow::on_fpPortSB_valueChanged(int arg1) { LOADINGCHECK CurrentConfig.defaultRouteConfig.forwardProxyConfig.port = arg1; } void PreferencesWindow::on_checkVCoreSettings_clicked() { auto vcorePath = vCorePathTxt->text(); auto vAssetsPath = vCoreAssetsPathTxt->text(); #if QV2RAY_FEATURE(kernel_check_filename) // prevent some bullshit situations. if (const auto vCorePathSmallCased = vcorePath.toLower(); vCorePathSmallCased.endsWith("qv2ray") || vCorePathSmallCased.endsWith("qv2ray.exe")) { const auto content = tr("You may be about to set V2Ray core incorrectly to Qv2ray itself, which is absolutely not correct.\r\n" "This won't trigger a fork bomb, however, since Qv2ray works in singleton mode.\r\n" "If your V2Ray core filename happened to be 'qv2ray'-something, you are totally free to ignore this warning."); QvMessageBoxWarn(this, tr("Watch Out!"), content); } #if !defined(QV2RAY_USE_V5_CORE) else if (vCorePathSmallCased.endsWith("v2ctl") || vCorePathSmallCased.endsWith("v2ctl.exe")) { const auto content = tr("You may be about to set V2Ray core incorrectly to V2Ray Control executable, which is absolutely not correct.\r\n" "The filename of V2Ray core is usually 'v2ray' or 'v2ray.exe'. Make sure to choose it wisely.\r\n" "If you insist to proceed, we're not providing with any support."); QvMessageBoxWarn(this, tr("Watch Out!"), content); } #endif #endif if (const auto &&[result, msg] = V2RayKernelInstance::ValidateKernel(vcorePath, vAssetsPath); !result) { QvMessageBoxWarn(this, tr("V2Ray Core Settings"), *msg); } #if QV2RAY_FEATURE(kernel_check_output) else if (!msg->toLower().contains("v2ray") && !msg->toLower().contains("xray")) { const auto content = tr("This does not seem like an output from V2Ray Core.") + NEWLINE + // tr("If you are looking for plugins settings, you should go to plugin settings.") + NEWLINE + // tr("Output:") + NEWLINE + // NEWLINE + *msg; QvMessageBoxWarn(this, tr("'V2Ray Core' Settings"), content); } #endif else { const auto content = tr("V2Ray path configuration check passed.") + NEWLINE + NEWLINE + tr("Current version of V2Ray is: ") + NEWLINE + *msg; QvMessageBoxInfo(this, tr("V2Ray Core Settings"), content); } } void PreferencesWindow::on_httpGroupBox_clicked(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.useHTTP = checked; httpAuthUsernameTxt->setEnabled(checked && CurrentConfig.inboundConfig.httpSettings.useAuth); httpAuthPasswordTxt->setEnabled(checked && CurrentConfig.inboundConfig.httpSettings.useAuth); httpOverrideHTTPCB->setEnabled(checked && CurrentConfig.inboundConfig.httpSettings.sniffing); httpOverrideTLSCB->setEnabled(checked && CurrentConfig.inboundConfig.httpSettings.sniffing); httpOverrideFakeDNSCB->setEnabled(checked && CurrentConfig.inboundConfig.httpSettings.sniffing); httpOverrideFakeDNSOthersCB->setEnabled(checked && CurrentConfig.inboundConfig.httpSettings.sniffing); } void PreferencesWindow::on_socksGroupBox_clicked(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.useSocks = checked; socksUDPIP->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.enableUDP); socksAuthUsernameTxt->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.useAuth); socksAuthPasswordTxt->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.useAuth); socksOverrideHTTPCB->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.sniffing); socksOverrideTLSCB->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.sniffing); socksOverrideFakeDNSCB->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.sniffing); socksOverrideFakeDNSOthersCB->setEnabled(checked && CurrentConfig.inboundConfig.socksSettings.sniffing); } void PreferencesWindow::on_fpGroupBox_clicked(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.defaultRouteConfig.forwardProxyConfig.enableForwardProxy = checked; } void PreferencesWindow::on_maxLogLinesSB_valueChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.uiConfig.maximumLogLines = arg1; } void PreferencesWindow::on_enableAPI_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.kernelConfig.enableAPI = arg1 == Qt::Checked; } void PreferencesWindow::on_updateChannelCombo_currentIndexChanged(int index) { LOADINGCHECK CurrentConfig.updateConfig.updateChannel = (Qv2rayConfig_Update::UpdateChannel) index; CurrentConfig.updateConfig.ignoredVersion.clear(); } void PreferencesWindow::on_pluginKernelV2RayIntegrationCB_stateChanged(int arg1) { LOADINGCHECK if (KernelInstance->ActivePluginKernelsCount() > 0) NEEDRESTART; CurrentConfig.pluginConfig.v2rayIntegration = arg1 == Qt::Checked; pluginKernelPortAllocateCB->setEnabled(arg1 == Qt::Checked); } void PreferencesWindow::on_pluginKernelPortAllocateCB_valueChanged(int arg1) { LOADINGCHECK if (KernelInstance->ActivePluginKernelsCount() > 0) NEEDRESTART; CurrentConfig.pluginConfig.portAllocationStart = arg1; } void PreferencesWindow::on_qvProxyAddressTxt_textEdited(const QString &arg1) { LOADINGCHECK CurrentConfig.networkConfig.address = arg1; } void PreferencesWindow::on_qvProxyTypeCombo_currentTextChanged(const QString &arg1) { LOADINGCHECK CurrentConfig.networkConfig.type = arg1.toLower(); } void PreferencesWindow::on_qvProxyPortCB_valueChanged(int arg1) { LOADINGCHECK CurrentConfig.networkConfig.port = arg1; } void PreferencesWindow::on_setTestlatencyCB_stateChanged(int arg1) { LOADINGCHECK if (arg1 == Qt::Checked) { QvMessageBoxWarn(this, tr("Dangerous Operation"), tr("This will (probably) make it easy to fingerprint your connection.")); } CurrentConfig.advancedConfig.testLatencyPeriodically = arg1 == Qt::Checked; } void PreferencesWindow::on_setTestlatencyOnConnectedCB_stateChanged(int arg1) { LOADINGCHECK if (arg1 == Qt::Checked) { QvMessageBoxWarn(this, tr("Dangerous Operation"), tr("This will (probably) make it easy to fingerprint your connection.")); } CurrentConfig.advancedConfig.testLatencyOnConnected = arg1 == Qt::Checked; } void PreferencesWindow::on_quietModeCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.quietMode = arg1 == Qt::Checked; } void PreferencesWindow::on_tproxyGroupBox_toggled(bool arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.useTPROXY = arg1; tproxyOverrideHTTPCB->setEnabled(arg1 && CurrentConfig.inboundConfig.tProxySettings.sniffing); tproxyOverrideTLSCB->setEnabled(arg1 && CurrentConfig.inboundConfig.tProxySettings.sniffing); tproxyOverrideFakeDNSCB->setEnabled(arg1 && CurrentConfig.inboundConfig.tProxySettings.sniffing); tproxyOverrideFakeDNSOthersCB->setEnabled(arg1 && CurrentConfig.inboundConfig.tProxySettings.sniffing); } void PreferencesWindow::on_tProxyPort_valueChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.port = arg1; } void PreferencesWindow::on_tproxyEnableTCP_toggled(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.hasTCP = checked; } void PreferencesWindow::on_tproxyEnableUDP_toggled(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.hasUDP = checked; } void PreferencesWindow::on_tproxySniffingCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.sniffing = arg1 == Qt::Checked; tproxySniffingMetadataOnlyCB->setEnabled(arg1 == Qt::Checked); tproxyOverrideHTTPCB->setEnabled(arg1 == Qt::Checked); tproxyOverrideTLSCB->setEnabled(arg1 == Qt::Checked); tproxyOverrideFakeDNSCB->setEnabled(arg1 == Qt::Checked); tproxyOverrideFakeDNSOthersCB->setEnabled(arg1 == Qt::Checked); } void PreferencesWindow::on_tproxyOverrideHTTPCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.tProxySettings.destOverride.removeAll("http"); else if (!CurrentConfig.inboundConfig.tProxySettings.destOverride.contains("http")) CurrentConfig.inboundConfig.tProxySettings.destOverride.append("http"); } void PreferencesWindow::on_tproxyOverrideTLSCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.tProxySettings.destOverride.removeAll("tls"); else if (!CurrentConfig.inboundConfig.tProxySettings.destOverride.contains("tls")) CurrentConfig.inboundConfig.tProxySettings.destOverride.append("tls"); } void PreferencesWindow::on_tproxyMode_currentTextChanged(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.mode = arg1; } void PreferencesWindow::on_tproxyListenAddr_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.tProxyIP = arg1; if (arg1 == "" || IsIPv4Address(arg1)) BLACK(tproxyListenAddr); else RED(tproxyListenAddr); } void PreferencesWindow::on_tproxyListenV6Addr_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.tProxyV6IP = arg1; if (arg1 == "" || IsIPv6Address(arg1)) BLACK(tproxyListenV6Addr); else RED(tproxyListenV6Addr); } void PreferencesWindow::on_jumpListCountSB_valueChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.maxJumpListCount = arg1; } void PreferencesWindow::on_outboundMark_valueChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.outboundConfig.mark = arg1; } void PreferencesWindow::on_dnsIntercept_toggled(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.defaultRouteConfig.connectionConfig.dnsIntercept = checked; } void PreferencesWindow::on_qvProxyCustomProxy_clicked() { CurrentConfig.networkConfig.proxyType = Qv2rayConfig_Network::QVPROXY_CUSTOM; SET_PROXY_UI_ENABLE(true); qvProxyNoProxy->setChecked(false); qvProxySystemProxy->setChecked(false); qvProxyCustomProxy->setChecked(true); } void PreferencesWindow::on_qvProxySystemProxy_clicked() { CurrentConfig.networkConfig.proxyType = Qv2rayConfig_Network::QVPROXY_SYSTEM; SET_PROXY_UI_ENABLE(false); qvProxyNoProxy->setChecked(false); qvProxyCustomProxy->setChecked(false); qvProxySystemProxy->setChecked(true); } void PreferencesWindow::on_qvProxyNoProxy_clicked() { CurrentConfig.networkConfig.proxyType = Qv2rayConfig_Network::QVPROXY_NONE; SET_PROXY_UI_ENABLE(false); qvProxySystemProxy->setChecked(false); qvProxyCustomProxy->setChecked(false); qvProxyNoProxy->setChecked(true); } void PreferencesWindow::on_dnsFreedomCb_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.defaultRouteConfig.connectionConfig.v2rayFreedomDNS = arg1 == Qt::Checked; } void PreferencesWindow::on_httpSniffingCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.httpSettings.sniffing = arg1 == Qt::Checked; httpSniffingMetadataOnly->setEnabled(arg1 == Qt::Checked); httpOverrideHTTPCB->setEnabled(arg1 == Qt::Checked); httpOverrideTLSCB->setEnabled(arg1 == Qt::Checked); httpOverrideFakeDNSCB->setEnabled(arg1 == Qt::Checked); httpOverrideFakeDNSOthersCB->setEnabled(arg1 == Qt::Checked); } void PreferencesWindow::on_httpOverrideHTTPCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.httpSettings.destOverride.removeAll("http"); else if (!CurrentConfig.inboundConfig.httpSettings.destOverride.contains("http")) CurrentConfig.inboundConfig.httpSettings.destOverride.append("http"); } void PreferencesWindow::on_httpOverrideTLSCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.httpSettings.destOverride.removeAll("tls"); else if (!CurrentConfig.inboundConfig.httpSettings.destOverride.contains("tls")) CurrentConfig.inboundConfig.httpSettings.destOverride.append("tls"); } void PreferencesWindow::on_socksSniffingCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.socksSettings.sniffing = arg1 == Qt::Checked; socksSniffingMetadataOnly->setEnabled(arg1 == Qt::Checked); socksOverrideHTTPCB->setEnabled(arg1 == Qt::Checked); socksOverrideTLSCB->setEnabled(arg1 == Qt::Checked); socksOverrideFakeDNSCB->setEnabled(arg1 == Qt::Checked); socksOverrideFakeDNSOthersCB->setEnabled(arg1 == Qt::Checked); } void PreferencesWindow::on_socksOverrideHTTPCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.socksSettings.destOverride.removeAll("http"); else if (!CurrentConfig.inboundConfig.socksSettings.destOverride.contains("http")) CurrentConfig.inboundConfig.socksSettings.destOverride.append("http"); } void PreferencesWindow::on_socksOverrideTLSCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.socksSettings.destOverride.removeAll("tls"); else if (!CurrentConfig.inboundConfig.socksSettings.destOverride.contains("tls")) CurrentConfig.inboundConfig.socksSettings.destOverride.append("tls"); } void PreferencesWindow::on_pushButton_clicked() { #if QV2RAY_FEATURE(util_has_ntp) const auto ntpTitle = tr("NTP Checker"); const auto ntpHint = tr("Check date and time from server:"); const static QStringList ntpServerList = { "cn.pool.ntp.org", "cn.ntp.org.cn", "edu.ntp.org.cn", "time.pool.aliyun.com", "time1.cloud.tencent.com", "ntp.neu.edu.cn" }; bool ok = false; const auto ntpServer = QInputDialog::getItem(this, ntpTitle, ntpHint, ntpServerList, 0, true, &ok).trimmed(); if (!ok) return; auto client = new ntp::NtpClient(this); connect(client, &ntp::NtpClient::replyReceived, [&](const QHostAddress &, quint16, const ntp::NtpReply &reply) { const int offsetSecTotal = reply.localClockOffset() / 1000; if (offsetSecTotal >= 90 || offsetSecTotal <= -90) { const auto inaccurateWarning = tr("Your time offset is %1 seconds, which is too high.") + NEWLINE + // tr("Please synchronize your system to use the VMess protocol."); QvMessageBoxWarn(this, tr("Time Inaccurate"), inaccurateWarning.arg(offsetSecTotal)); } else if (offsetSecTotal > 15 || offsetSecTotal < -15) { const auto smallErrorWarning = tr("Your time offset is %1 seconds, which is a little high.") + NEWLINE + // tr("VMess protocol may still work, but we suggest you synchronize your clock."); QvMessageBoxInfo(this, tr("Time Somewhat Inaccurate"), smallErrorWarning.arg(offsetSecTotal)); } else { const auto accurateInfo = tr("Your time offset is %1 seconds, which looks good.") + NEWLINE + // tr("VMess protocol may not suffer from time inaccuracy."); QvMessageBoxInfo(this, tr("Time Accurate"), accurateInfo.arg(offsetSecTotal)); } }); const auto hostInfo = QHostInfo::fromName(ntpServer); if (hostInfo.error() == QHostInfo::NoError) client->sendRequest(hostInfo.addresses().first(), 123); else QvMessageBoxWarn(this, ntpTitle, tr("Failed to lookup server: %1").arg(hostInfo.errorString())); #else QvMessageBoxWarn(this, tr("No NTP Backend"), tr("Qv2ray was not built with NTP support.")); #endif } void PreferencesWindow::on_noAutoConnectRB_clicked() { LOADINGCHECK CurrentConfig.autoStartBehavior = AUTO_CONNECTION_NONE; SET_AUTOSTART_UI_ENABLED(false); SET_AUTOSTART_START_MINIMIZED_ENABLED(false); } void PreferencesWindow::on_lastConnectedRB_clicked() { LOADINGCHECK CurrentConfig.autoStartBehavior = AUTO_CONNECTION_LAST_CONNECTED; SET_AUTOSTART_UI_ENABLED(false); SET_AUTOSTART_START_MINIMIZED_ENABLED(true); } void PreferencesWindow::on_fixedAutoConnectRB_clicked() { LOADINGCHECK CurrentConfig.autoStartBehavior = AUTO_CONNECTION_FIXED; SET_AUTOSTART_UI_ENABLED(true); SET_AUTOSTART_START_MINIMIZED_ENABLED(true); } void PreferencesWindow::on_latencyTCPingRB_clicked() { LOADINGCHECK CurrentConfig.networkConfig.latencyTestingMethod = TCPING; latencyICMPingRB->setChecked(false); latencyTCPingRB->setChecked(true); } void PreferencesWindow::on_latencyICMPingRB_clicked() { LOADINGCHECK CurrentConfig.networkConfig.latencyTestingMethod = ICMPING; latencyICMPingRB->setChecked(true); latencyTCPingRB->setChecked(false); } void PreferencesWindow::on_qvNetworkUATxt_editTextChanged(const QString &arg1) { LOADINGCHECK CurrentConfig.networkConfig.userAgent = arg1; } void PreferencesWindow::on_V2RayOutboundStatsCB_stateChanged(int arg1) { hasDirectStatisticsCB->setEnabled(arg1 == Qt::Checked); LOADINGCHECK NEEDRESTART CurrentConfig.uiConfig.graphConfig.useOutboundStats = arg1 == Qt::Checked; } void PreferencesWindow::on_hasDirectStatisticsCB_stateChanged(int arg1) { NEEDRESTART LOADINGCHECK CurrentConfig.uiConfig.graphConfig.hasDirectStats = arg1 == Qt::Checked; } void PreferencesWindow::on_useOldShareLinkFormatCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.useOldShareLinkFormat = arg1 == Qt::Checked; } void PreferencesWindow::on_bypassPrivateCb_clicked(bool checked) { LOADINGCHECK NEEDRESTART CurrentConfig.defaultRouteConfig.connectionConfig.bypassLAN = checked; } void PreferencesWindow::on_disableSystemRootCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.advancedConfig.disableSystemRoot = arg1 == Qt::Checked; } void PreferencesWindow::on_openConfigDirCB_clicked() { QvCoreApplication->OpenURL(QV2RAY_CONFIG_DIR); } void PreferencesWindow::on_startMinimizedCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.startMinimized = arg1 == Qt::Checked; } void PreferencesWindow::on_exitByCloseEventCB_stateChanged(int arg1) { LOADINGCHECK CurrentConfig.uiConfig.exitByCloseEvent = arg1 == Qt::Checked; } void PreferencesWindow::on_httpSniffingMetadataOnly_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.httpSettings.metadataOnly = arg1 == Qt::Checked; } void PreferencesWindow::on_socksSniffingMetadataOnly_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.socksSettings.metadataOnly = arg1 == Qt::Checked; } void PreferencesWindow::on_tproxySniffingMetadataOnlyCB_stateChanged(int arg1) { LOADINGCHECK NEEDRESTART CurrentConfig.inboundConfig.tProxySettings.metadataOnly = arg1 == Qt::Checked; } void PreferencesWindow::on_socksOverrideFakeDNSCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.socksSettings.destOverride.removeAll("fakedns"); else if (!CurrentConfig.inboundConfig.socksSettings.destOverride.contains("fakedns")) CurrentConfig.inboundConfig.socksSettings.destOverride.append("fakedns"); } void PreferencesWindow::on_socksOverrideFakeDNSOthersCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.socksSettings.destOverride.removeAll("fakedns+others"); else if (!CurrentConfig.inboundConfig.socksSettings.destOverride.contains("fakedns+others")) CurrentConfig.inboundConfig.socksSettings.destOverride.append("fakedns+others"); } void PreferencesWindow::on_httpOverrideFakeDNSCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.httpSettings.destOverride.removeAll("fakedns"); else if (!CurrentConfig.inboundConfig.httpSettings.destOverride.contains("fakedns")) CurrentConfig.inboundConfig.httpSettings.destOverride.append("fakedns"); } void PreferencesWindow::on_httpOverrideFakeDNSOthersCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.httpSettings.destOverride.removeAll("fakedns+others"); else if (!CurrentConfig.inboundConfig.httpSettings.destOverride.contains("fakedns+others")) CurrentConfig.inboundConfig.httpSettings.destOverride.append("fakedns+others"); } void PreferencesWindow::on_tproxyOverrideFakeDNSCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.tProxySettings.destOverride.removeAll("fakedns"); else if (!CurrentConfig.inboundConfig.tProxySettings.destOverride.contains("fakedns")) CurrentConfig.inboundConfig.tProxySettings.destOverride.append("fakedns"); } void PreferencesWindow::on_tproxyOverrideFakeDNSOthersCB_stateChanged(int arg1) { NEEDRESTART if (arg1 != Qt::Checked) CurrentConfig.inboundConfig.tProxySettings.destOverride.removeAll("fakedns+others"); else if (!CurrentConfig.inboundConfig.tProxySettings.destOverride.contains("fakedns+others")) CurrentConfig.inboundConfig.tProxySettings.destOverride.append("fakedns+others"); } void PreferencesWindow::on_browserForwarderAddressTxt_textEdited(const QString &arg1) { NEEDRESTART CurrentConfig.inboundConfig.browserForwarderSettings.address = arg1; } void PreferencesWindow::on_browserForwarderPortSB_valueChanged(int arg1) { NEEDRESTART CurrentConfig.inboundConfig.browserForwarderSettings.port = arg1; }
51,623
C++
.cpp
1,207
37.415079
150
0.729627
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,203
w_GroupManager.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_GroupManager.cpp
#include "w_GroupManager.hpp" #include "core/connection/Generation.hpp" #include "core/handler/ConfigHandler.hpp" #include "core/handler/RouteHandler.hpp" #include "core/settings/SettingsBackend.hpp" #include "ui/widgets/widgets/DnsSettingsWidget.hpp" #include "ui/widgets/widgets/RouteSettingsMatrix.hpp" #include "utils/QvHelpers.hpp" #include <QDesktopServices> #include <QFileDialog> #include <QListWidgetItem> #define SELECTED_ROWS_INDEX \ ([&]() { \ const auto &__selection = connectionsTable->selectedItems(); \ QSet<int> rows; \ for (const auto &selection : __selection) \ { \ rows.insert(connectionsTable->row(selection)); \ } \ return rows; \ }()) #define GET_SELECTED_CONNECTION_IDS(connectionIdList) \ ([&]() { \ QList<ConnectionId> _list; \ for (const auto &i : connectionIdList) \ { \ _list.push_back(ConnectionId(connectionsTable->item(i, 0)->data(Qt::UserRole).toString())); \ } \ return _list; \ }()) GroupManager::GroupManager(QWidget *parent) : QvDialog("GroupManager", parent) { addStateOptions("width", { [&] { return width(); }, [&](QJsonValue val) { resize(val.toInt(), size().height()); } }); addStateOptions("height", { [&] { return height(); }, [&](QJsonValue val) { resize(size().width(), val.toInt()); } }); addStateOptions("x", { [&] { return x(); }, [&](QJsonValue val) { move(val.toInt(), y()); } }); addStateOptions("y", { [&] { return y(); }, [&](QJsonValue val) { move(x(), val.toInt()); } }); setupUi(this); QvMessageBusConnect(GroupManager); for (const auto &plugin : PluginHost->UsablePlugins()) { const auto pluginInfo = PluginHost->GetPlugin(plugin); if (!pluginInfo->hasComponent(COMPONENT_SUBSCRIPTION_ADAPTER)) continue; const auto subscriptionAdapterInterface = pluginInfo->pluginInterface->GetSubscriptionAdapter(); const auto types = subscriptionAdapterInterface->SupportedSubscriptionTypes(); for (const auto &type : types) { subscriptionTypeCB->addItem(pluginInfo->metadata.Name + ": " + type.displayName, type.protocol); } } // dnsSettingsWidget = new DnsSettingsWidget(this); routeSettingsWidget = new RouteSettingsMatrixWidget(GlobalConfig.kernelConfig.AssetsPath(), this); // dnsSettingsGB->setLayout(new QGridLayout(dnsSettingsGB)); dnsSettingsGB->layout()->addWidget(dnsSettingsWidget); // routeSettingsGB->setLayout(new QGridLayout(routeSettingsGB)); routeSettingsGB->layout()->addWidget(routeSettingsWidget); // updateColorScheme(); connectionListRCMenu->addSection(tr("Connection Management")); connectionListRCMenu->addAction(exportConnectionAction); connectionListRCMenu->addAction(deleteConnectionAction); connectionListRCMenu->addSeparator(); connectionListRCMenu->addMenu(connectionListRCMenu_CopyToMenu); connectionListRCMenu->addMenu(connectionListRCMenu_MoveToMenu); connectionListRCMenu->addMenu(connectionListRCMenu_LinkToMenu); // connect(exportConnectionAction, &QAction::triggered, this, &GroupManager::onRCMExportConnectionTriggered); connect(deleteConnectionAction, &QAction::triggered, this, &GroupManager::onRCMDeleteConnectionTriggered); // connect(ConnectionManager, &QvConfigHandler::OnConnectionLinkedWithGroup, [this] { reloadConnectionsList(currentGroupId); }); // connect(ConnectionManager, &QvConfigHandler::OnGroupCreated, this, &GroupManager::reloadGroupRCMActions); connect(ConnectionManager, &QvConfigHandler::OnGroupDeleted, this, &GroupManager::reloadGroupRCMActions); connect(ConnectionManager, &QvConfigHandler::OnGroupRenamed, this, &GroupManager::reloadGroupRCMActions); // for (const auto &group : ConnectionManager->AllGroups()) { auto item = new QListWidgetItem(GetDisplayName(group)); item->setData(Qt::UserRole, group.toString()); groupList->addItem(item); } if (groupList->count() > 0) { groupList->setCurrentItem(groupList->item(0)); } else { groupInfoGroupBox->setEnabled(false); tabWidget->setEnabled(false); } reloadGroupRCMActions(); } void GroupManager::onRCMDeleteConnectionTriggered() { const auto list = GET_SELECTED_CONNECTION_IDS(SELECTED_ROWS_INDEX); for (const auto &item : list) { ConnectionManager->RemoveConnectionFromGroup(ConnectionId(item), currentGroupId); } reloadConnectionsList(currentGroupId); } void GroupManager::onRCMExportConnectionTriggered() { const auto &list = GET_SELECTED_CONNECTION_IDS(SELECTED_ROWS_INDEX); QFileDialog d; switch (list.count()) { case 0: return; case 1: { const auto id = ConnectionId(list.first()); auto filePath = d.getSaveFileName(this, GetDisplayName(id)); if (filePath.isEmpty()) return; auto root = RouteManager->GenerateFinalConfig({ id, currentGroupId }, false); // // Apply export filter exportConnectionFilter(root); // if (filePath.endsWith(".json")) { filePath += ".json"; } // StringToFile(JsonToString(root), filePath); QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(filePath).absoluteDir().absolutePath())); break; } default: { const auto path = d.getExistingDirectory(); if (path.isEmpty()) return; for (const auto &connId : list) { ConnectionId id(connId); auto root = RouteManager->GenerateFinalConfig({ id, currentGroupId }); // // Apply export filter exportConnectionFilter(root); // const auto fileName = RemoveInvalidFileName(GetDisplayName(id)) + ".json"; StringToFile(JsonToString(root), path + "/" + fileName); } QDesktopServices::openUrl(QUrl::fromLocalFile(path)); break; } } } void GroupManager::reloadGroupRCMActions() { connectionListRCMenu_CopyToMenu->clear(); connectionListRCMenu_MoveToMenu->clear(); connectionListRCMenu_LinkToMenu->clear(); for (const auto &group : ConnectionManager->AllGroups()) { auto cpAction = new QAction(GetDisplayName(group), connectionListRCMenu_CopyToMenu); auto mvAction = new QAction(GetDisplayName(group), connectionListRCMenu_MoveToMenu); auto lnAction = new QAction(GetDisplayName(group), connectionListRCMenu_LinkToMenu); // cpAction->setData(group.toString()); mvAction->setData(group.toString()); lnAction->setData(group.toString()); // connectionListRCMenu_CopyToMenu->addAction(cpAction); connectionListRCMenu_MoveToMenu->addAction(mvAction); connectionListRCMenu_LinkToMenu->addAction(lnAction); // connect(cpAction, &QAction::triggered, this, &GroupManager::onRCMActionTriggered_Copy); connect(mvAction, &QAction::triggered, this, &GroupManager::onRCMActionTriggered_Move); connect(lnAction, &QAction::triggered, this, &GroupManager::onRCMActionTriggered_Link); } } void GroupManager::reloadConnectionsList(const GroupId &group) { if (group == NullGroupId) return; connectionsTable->clearContents(); connectionsTable->model()->removeRows(0, connectionsTable->rowCount()); const auto &connections = ConnectionManager->GetConnections(group); for (auto i = 0; i < connections.count(); i++) { const auto &conn = connections.at(i); connectionsTable->insertRow(i); // auto displayNameItem = new QTableWidgetItem(GetDisplayName(conn)); displayNameItem->setData(Qt::UserRole, conn.toString()); auto typeItem = new QTableWidgetItem(GetConnectionProtocolString(conn)); // const auto [type, host, port] = GetConnectionInfo(conn); auto hostPortItem = new QTableWidgetItem(host + ":" + QSTRN(port)); // QStringList groupsNamesString; for (const auto &group : ConnectionManager->GetConnectionContainedIn(conn)) { groupsNamesString.append(GetDisplayName(group)); } auto groupsItem = new QTableWidgetItem(groupsNamesString.join(";")); connectionsTable->setItem(i, 0, displayNameItem); connectionsTable->setItem(i, 1, typeItem); connectionsTable->setItem(i, 2, hostPortItem); connectionsTable->setItem(i, 3, groupsItem); } connectionsTable->resizeColumnsToContents(); } void GroupManager::onRCMActionTriggered_Copy() { const auto _sender = qobject_cast<QAction *>(sender()); const GroupId groupId{ _sender->data().toString() }; // const auto list = GET_SELECTED_CONNECTION_IDS(SELECTED_ROWS_INDEX); for (const auto &connId : list) { const auto &connectionId = ConnectionId(connId); ConnectionManager->CreateConnection(ConnectionManager->GetConnectionRoot(connectionId), GetDisplayName(connectionId), groupId, true); } reloadConnectionsList(currentGroupId); } void GroupManager::onRCMActionTriggered_Link() { const auto _sender = qobject_cast<QAction *>(sender()); const GroupId groupId{ _sender->data().toString() }; // const auto list = GET_SELECTED_CONNECTION_IDS(SELECTED_ROWS_INDEX); for (const auto &connId : list) { ConnectionManager->LinkConnectionWithGroup(ConnectionId(connId), groupId); } reloadConnectionsList(currentGroupId); } void GroupManager::onRCMActionTriggered_Move() { const auto _sender = qobject_cast<QAction *>(sender()); const GroupId groupId{ _sender->data().toString() }; // const auto list = GET_SELECTED_CONNECTION_IDS(SELECTED_ROWS_INDEX); for (const auto &connId : list) { ConnectionManager->MoveConnectionFromToGroup(ConnectionId(connId), currentGroupId, groupId); } reloadConnectionsList(currentGroupId); } void GroupManager::updateColorScheme() { addGroupButton->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); removeGroupButton->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); } QvMessageBusSlotImpl(GroupManager) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; MBUpdateColorSchemeDefaultImpl } } GroupManager::~GroupManager(){}; void GroupManager::on_addGroupButton_clicked() { auto const key = tr("New Group") + " - " + GenerateRandomString(5); auto id = ConnectionManager->CreateGroup(key, false); // auto item = new QListWidgetItem(key); item->setData(Qt::UserRole, id.toString()); groupList->addItem(item); groupList->setCurrentRow(groupList->count() - 1); } void GroupManager::on_updateButton_clicked() { const auto address = subAddrTxt->text().trimmed(); if (address.isEmpty()) { QvMessageBoxWarn(this, tr("Update Subscription"), tr("The subscription link is empty.")); return; } if (!QUrl(address).isValid()) { QvMessageBoxWarn(this, tr("Update Subscription"), tr("The subscription link is invalid.")); return; } if (QvMessageBoxAsk(this, tr("Update Subscription"), tr("Would you like to update the subscription?")) == Yes) { this->setEnabled(false); qApp->processEvents(); ConnectionManager->UpdateSubscription(currentGroupId); this->setEnabled(true); on_groupList_itemClicked(groupList->currentItem()); } } void GroupManager::on_removeGroupButton_clicked() { if (QvMessageBoxAsk(this, tr("Remove a Group"), tr("All connections will be moved to default group, do you want to continue?")) == Yes) { ConnectionManager->DeleteGroup(currentGroupId); auto item = groupList->currentItem(); int index = groupList->row(item); groupList->removeItemWidget(item); delete item; if (groupList->count() > 0) { index = std::max(index, 0); index = std::min(index, groupList->count() - 1); groupList->setCurrentItem(groupList->item(index)); on_groupList_itemClicked(groupList->item(index)); } else { groupInfoGroupBox->setEnabled(false); tabWidget->setEnabled(false); } } } void GroupManager::on_buttonBox_accepted() { if (currentGroupId != NullGroupId) { const auto routeId = ConnectionManager->GetGroupRoutingId(currentGroupId); const auto &[dns, fakedns] = dnsSettingsWidget->GetDNSObject(); RouteManager->SetDNSSettings(routeId, dnsSettingsGB->isChecked(), dns, fakedns); RouteManager->SetAdvancedRouteSettings(routeId, routeSettingsGB->isChecked(), routeSettingsWidget->GetRouteConfig()); } // Nothing? } void GroupManager::on_groupList_itemSelectionChanged() { groupInfoGroupBox->setEnabled(groupList->selectedItems().count() > 0); } void GroupManager::on_groupList_itemClicked(QListWidgetItem *item) { if (item == nullptr) { return; } groupInfoGroupBox->setEnabled(true); currentGroupId = GroupId(item->data(Qt::UserRole).toString()); groupNameTxt->setText(GetDisplayName(currentGroupId)); // const auto _group = ConnectionManager->GetGroupMetaObject(currentGroupId); groupIsSubscriptionGroup->setChecked(_group.isSubscription); subAddrTxt->setText(_group.subscriptionOption.address); lastUpdatedLabel->setText(timeToString(_group.lastUpdatedDate)); createdAtLabel->setText(timeToString(_group.creationDate)); updateIntervalSB->setValue(_group.subscriptionOption.updateInterval); { const auto &type = _group.subscriptionOption.type; const auto index = subscriptionTypeCB->findData(type); if (index < 0) QvMessageBoxWarn(this, tr("Unknown Subscription Type"), tr("Unknown subscription type \"%1\", a plugin may be missing.").arg(type)); else subscriptionTypeCB->setCurrentIndex(index); } // // Import filters { IncludeRelation->setCurrentIndex(_group.subscriptionOption.IncludeRelation); IncludeKeywords->clear(); for (const auto &key : _group.subscriptionOption.IncludeKeywords) { auto str = key.trimmed(); if (!str.isEmpty()) { IncludeKeywords->appendPlainText(str); } } ExcludeRelation->setCurrentIndex(_group.subscriptionOption.ExcludeRelation); ExcludeKeywords->clear(); for (const auto &key : _group.subscriptionOption.ExcludeKeywords) { auto str = key.trimmed(); if (!str.isEmpty()) { ExcludeKeywords->appendPlainText(str); } } } // // Load DNS / Route config const auto routeId = ConnectionManager->GetGroupRoutingId(currentGroupId); { const auto &[overrideDns, dns, fakedns] = RouteManager->GetDNSSettings(routeId); dnsSettingsWidget->SetDNSObject(dns, fakedns); dnsSettingsGB->setChecked(overrideDns); // const auto &[overrideRoute, route] = RouteManager->GetAdvancedRoutingSettings(routeId); routeSettingsWidget->SetRouteConfig(route); routeSettingsGB->setChecked(overrideRoute); } reloadConnectionsList(currentGroupId); } void GroupManager::on_IncludeRelation_currentTextChanged(const QString &) { ConnectionManager->SetSubscriptionIncludeRelation(currentGroupId, (SubscriptionFilterRelation) IncludeRelation->currentIndex()); } void GroupManager::on_ExcludeRelation_currentTextChanged(const QString &) { ConnectionManager->SetSubscriptionExcludeRelation(currentGroupId, (SubscriptionFilterRelation) ExcludeRelation->currentIndex()); } void GroupManager::on_IncludeKeywords_textChanged() { QStringList keywords = IncludeKeywords->toPlainText().replace("\r", "").split("\n"); ConnectionManager->SetSubscriptionIncludeKeywords(currentGroupId, keywords); } void GroupManager::on_ExcludeKeywords_textChanged() { QStringList keywords = ExcludeKeywords->toPlainText().replace("\r", "").split("\n"); ConnectionManager->SetSubscriptionExcludeKeywords(currentGroupId, keywords); } void GroupManager::on_groupList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *priv) { if (priv) { const auto group = ConnectionManager->GetGroupMetaObject(currentGroupId); const auto &[dns, fakedns] = dnsSettingsWidget->GetDNSObject(); RouteManager->SetDNSSettings(group.routeConfigId, dnsSettingsGB->isChecked(), dns, fakedns); RouteManager->SetAdvancedRouteSettings(group.routeConfigId, routeSettingsGB->isChecked(), routeSettingsWidget->GetRouteConfig()); } if (current) { on_groupList_itemClicked(current); } } void GroupManager::on_subAddrTxt_textEdited(const QString &arg1) { ConnectionManager->SetSubscriptionData(currentGroupId, std::nullopt, arg1); } void GroupManager::on_updateIntervalSB_valueChanged(double arg1) { ConnectionManager->SetSubscriptionData(currentGroupId, std::nullopt, std::nullopt, arg1); } void GroupManager::on_connectionsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous) if (current != nullptr) { currentConnectionId = ConnectionId(current->data(Qt::UserRole).toString()); } } void GroupManager::on_groupIsSubscriptionGroup_clicked(bool checked) { ConnectionManager->SetSubscriptionData(currentGroupId, checked); } void GroupManager::on_groupNameTxt_textEdited(const QString &arg1) { groupList->selectedItems().first()->setText(arg1); ConnectionManager->RenameGroup(currentGroupId, arg1.trimmed()); } void GroupManager::on_deleteSelectedConnBtn_clicked() { onRCMDeleteConnectionTriggered(); } void GroupManager::on_exportSelectedConnBtn_clicked() { if (connectionsTable->selectedItems().isEmpty()) { connectionsTable->selectAll(); } onRCMExportConnectionTriggered(); } void GroupManager::exportConnectionFilter(CONFIGROOT &root) { root.remove("api"); root.remove("stats"); auto inbounds = root["inbounds"].toArray(); for (auto iter = inbounds.begin(); iter != inbounds.end();) { auto obj = iter->toObject(); if (obj["tag"] == API_TAG_INBOUND) iter = inbounds.erase(iter); iter++; } root["inbounds"] = inbounds; } #undef GET_SELECTED_CONNECTION_IDS void GroupManager::on_connectionsTable_customContextMenuRequested(const QPoint &pos) { Q_UNUSED(pos) connectionListRCMenu->popup(QCursor::pos()); } void GroupManager::on_subscriptionTypeCB_currentIndexChanged(int) { ConnectionManager->SetSubscriptionType(currentGroupId, subscriptionTypeCB->currentData().toString()); }
21,068
C++
.cpp
486
37.032922
150
0.625207
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,204
w_ImportConfig.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_ImportConfig.cpp
#include "w_ImportConfig.hpp" #include "core/connection/Serialization.hpp" #include "core/handler/ConfigHandler.hpp" #include "ui/common/QRCodeHelper.hpp" #include "ui/widgets/editors/w_JsonEditor.hpp" #include "ui/widgets/editors/w_OutboundEditor.hpp" #include "ui/widgets/editors/w_RoutesEditor.hpp" #include "ui/widgets/windows/w_GroupManager.hpp" #include "w_ScreenShot_Core.hpp" #include <QFileDialog> #define QV_MODULE_NAME "ImportWindow" namespace { constexpr auto LINK_PAGE = 0; #if QV2RAY_FEATURE(ui_has_import_qrcode) constexpr auto QRCODE_PAGE = 1; constexpr auto ADVANCED_PAGE = 2; #else constexpr auto ADVANCED_PAGE = 1; #endif } // namespace ImportConfigWindow::ImportConfigWindow(QWidget *parent) : QvDialog("ImportWindow", parent) { addStateOptions("width", { [&] { return width(); }, [&](QJsonValue val) { resize(val.toInt(), size().height()); } }); addStateOptions("height", { [&] { return height(); }, [&](QJsonValue val) { resize(size().width(), val.toInt()); } }); addStateOptions("x", { [&] { return x(); }, [&](QJsonValue val) { move(val.toInt(), y()); } }); addStateOptions("y", { [&] { return y(); }, [&](QJsonValue val) { move(x(), val.toInt()); } }); setupUi(this); QvMessageBusConnect(ImportConfigWindow); RESTORE_RUNTIME_CONFIG(screenShotHideQv2ray, hideQv2rayCB->setChecked) // auto defaultItemIndex = 0; for (const auto &gid : ConnectionManager->AllGroups()) { groupCombo->addItem(GetDisplayName(gid), gid.toString()); if (gid == DefaultGroupId) defaultItemIndex = groupCombo->count() - 1; } groupCombo->setCurrentIndex(defaultItemIndex); #if !QV2RAY_FEATURE(ui_has_import_qrcode) qrCodeTab->setVisible(false); tabWidget->removeTab(1); #endif } void ImportConfigWindow::updateColorScheme() { // Stub } QvMessageBusSlotImpl(ImportConfigWindow) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBRetranslateDefaultImpl; MBUpdateColorSchemeDefaultImpl; } } ImportConfigWindow::~ImportConfigWindow() { } QMultiMap<QString, CONFIGROOT> ImportConfigWindow::SelectConnection(bool outboundsOnly) { // partial import means only import as an outbound, will set outboundsOnly to // false and disable the checkbox keepImportedInboundCheckBox->setEnabled(!outboundsOnly); groupCombo->setEnabled(false); this->exec(); QMultiMap<QString, CONFIGROOT> conn; for (const auto &connEntry : connectionsToNewGroup.values()) { conn += connEntry; } for (const auto &connEntry : connectionsToExistingGroup.values()) { conn += connEntry; } return result() == Accepted ? conn : QMultiMap<QString, CONFIGROOT>{}; } int ImportConfigWindow::PerformImportConnection() { this->exec(); int count = 0; for (const auto &groupObject : connectionsToNewGroup) { const auto groupName = connectionsToNewGroup.key(groupObject); GroupId groupId = ConnectionManager->CreateGroup(groupName, false); for (const auto &connConf : groupObject) { auto connName = groupObject.key(connConf); auto [protocol, host, port] = GetConnectionInfo(connConf); if (connName.isEmpty()) { connName = protocol + "/" + host + ":" + QSTRN(port) + "-" + GenerateRandomString(5); } ConnectionManager->CreateConnection(connConf, connName, groupId, true); } } for (const auto &groupObject : connectionsToExistingGroup) { const auto groupId = connectionsToExistingGroup.key(groupObject); for (const auto &connConf : groupObject) { auto connName = groupObject.key(connConf); auto [protocol, host, port] = GetConnectionInfo(connConf); if (connName.isEmpty()) { connName = protocol + "/" + host + ":" + QSTRN(port) + "-" + GenerateRandomString(5); } ConnectionManager->CreateConnection(connConf, connName, groupId, true); } } return count; } #if QV2RAY_FEATURE(ui_has_import_qrcode) void ImportConfigWindow::on_qrFromScreenBtn_clicked() { bool hideQv2ray = hideQv2rayCB->isChecked(); if (hideQv2ray) { UIMessageBus.EmitGlobalSignal(QvMBMessage::HIDE_WINDOWS); } QApplication::processEvents(); QThread::msleep(doubleSpinBox->value() * 1000UL); ScreenShotWindow w; auto pix = w.DoScreenShot(); if (hideQv2ray) { UIMessageBus.EmitGlobalSignal(QvMBMessage::SHOW_WINDOWS); } if (w.result() == QDialog::Accepted) { auto str = DecodeQRCode(pix); if (str.trimmed().isEmpty()) { LOG("Cannot decode QR Code from an image, size:", pix.width(), pix.height()); QvMessageBoxWarn(this, tr("Capture QRCode"), tr("Cannot find a valid QRCode from this region.")); } else { qrCodeLinkTxt->setText(str.trimmed()); } } } void ImportConfigWindow::on_selectImageBtn_clicked() { const auto dir = QFileDialog::getOpenFileName(this, tr("Select an image to import")); imageFileEdit->setText(dir); // QFile file(dir); if (!file.exists()) return; file.open(QFile::OpenModeFlag::ReadOnly); auto buf = file.readAll(); file.close(); // const auto str = DecodeQRCode(QImage::fromData(buf)); if (str.isEmpty()) { QvMessageBoxWarn(this, tr("QRCode scanning failed"), tr("Cannot find any QRCode from the image.")); return; } qrCodeLinkTxt->setText(str.trimmed()); } void ImportConfigWindow::on_hideQv2rayCB_stateChanged(int arg1) { Q_UNUSED(arg1) SET_RUNTIME_CONFIG(screenShotHideQv2ray, hideQv2rayCB->isChecked) } #endif void ImportConfigWindow::on_beginImportBtn_clicked() { QString aliasPrefix = nameTxt->text(); switch (tabWidget->currentIndex()) { case LINK_PAGE: { QStringList linkList = SplitLines(vmessConnectionStringTxt->toPlainText()); // // Clear UI and error lists linkErrors.clear(); vmessConnectionStringTxt->clear(); errorsList->clear(); // LOG(linkList.count(), "entries found."); while (!linkList.isEmpty()) { aliasPrefix = nameTxt->text(); const auto link = linkList.takeFirst().trimmed(); if (link.isEmpty() || link.startsWith("#") || link.startsWith("//")) continue; // warn if someone tries to import a https:// link if (link.startsWith("https://")) { errorsList->addItem(tr("WARNING: You may have mistaken 'subscription link' with 'share link'")); } QString errMessage; QString newGroupName; const auto config = ConvertConfigFromString(link, &aliasPrefix, &errMessage, &newGroupName); // If the config is empty or we have any err messages. if (config.isEmpty() || !errMessage.isEmpty()) { // To prevent duplicated values. linkErrors[link] = QSTRN(linkErrors.count() + 1) + ": " + errMessage; continue; } else if (newGroupName.isEmpty()) { for (const auto &conf : config) { connectionsToExistingGroup[GroupId{ groupCombo->currentData().toString() }].insert(conf.first, conf.second); } } else { for (const auto &conf : config) { connectionsToNewGroup[newGroupName].insert(conf.first, conf.second); } } } if (!linkErrors.isEmpty()) { for (const auto &item : qAsConst(linkErrors)) { vmessConnectionStringTxt->appendPlainText(linkErrors.key(item)); errorsList->addItem(item); } vmessConnectionStringTxt->setLineWidth(errorsList->lineWidth()); errorsList->sortItems(); return; } break; } #if QV2RAY_FEATURE(ui_has_import_qrcode) case QRCODE_PAGE: { QString errorMsg; const auto root = ConvertConfigFromString(qrCodeLinkTxt->text(), &aliasPrefix, &errorMsg); if (!errorMsg.isEmpty()) { QvMessageBoxWarn(this, tr("Failed to import connection"), errorMsg); break; } for (const auto &conf : root) { connectionsToExistingGroup[GroupId{ groupCombo->currentData().toString() }].insert(conf.first, conf.second); } break; } #endif case ADVANCED_PAGE: { // From File... bool ImportAsComplex = keepImportedInboundCheckBox->isChecked(); const auto path = fileLineTxt->text(); if (const auto &result = V2RayKernelInstance::ValidateConfig(path); result) { QvMessageBoxWarn(this, tr("Import config file"), *result); return; } aliasPrefix += "_" + QFileInfo(path).fileName(); CONFIGROOT config = ConvertConfigFromFile(path, ImportAsComplex); connectionsToExistingGroup[GroupId{ groupCombo->currentData().toString() }].insert(aliasPrefix, config); break; } } accept(); } void ImportConfigWindow::on_errorsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous) if (!current) return; const auto currentErrorText = current->text(); const auto vmessEntry = linkErrors.key(currentErrorText); // const auto startPos = vmessConnectionStringTxt->toPlainText().indexOf(vmessEntry); const auto endPos = startPos + vmessEntry.length(); if (startPos < 0) return; // Select vmess string that is invalid. auto c = vmessConnectionStringTxt->textCursor(); c.setPosition(startPos); c.setPosition(endPos, QTextCursor::KeepAnchor); vmessConnectionStringTxt->setTextCursor(c); } void ImportConfigWindow::on_cancelImportBtn_clicked() { reject(); } void ImportConfigWindow::on_routeEditBtn_clicked() { RouteEditor w(QJsonObject(), this); const auto result = w.OpenEditor(); const auto alias = nameTxt->text(); bool isChanged = w.result() == QDialog::Accepted; if (isChanged) { connectionsToExistingGroup[GroupId{ groupCombo->currentData().toString() }].insert(alias, result); accept(); } } void ImportConfigWindow::on_jsonEditBtn_clicked() { JsonEditor w(QJsonObject(), this); const auto result = w.OpenEditor(); const auto alias = nameTxt->text(); const auto isChanged = w.result() == QDialog::Accepted; if (isChanged) { connectionsToExistingGroup[GroupId{ groupCombo->currentData().toString() }].insert(alias, CONFIGROOT(result)); accept(); } } void ImportConfigWindow::on_selectFileBtn_clicked() { const auto dir = QFileDialog::getOpenFileName(this, tr("Select file to import")); fileLineTxt->setText(dir); }
11,531
C++
.cpp
320
27.9375
132
0.619538
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,205
w_MainWindow_extra.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_MainWindow_extra.cpp
#include "components/proxy/QvProxyConfigurator.hpp" #include "ui/widgets/Qv2rayWidgetApplication.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "utils/QvHelpers.hpp" #include "w_MainWindow.hpp" #ifdef Q_OS_MAC #include <ApplicationServices/ApplicationServices.h> #endif #define QV_MODULE_NAME "MainWindowExtra" void MainWindow::MWToggleVisibilitySetText() { if (isHidden() || isMinimized()) tray_action_ToggleVisibility->setText(tr("Show")); else tray_action_ToggleVisibility->setText(tr("Hide")); } void MainWindow::MWToggleVisibility() { if (isHidden() || isMinimized()) MWShowWindow(); else MWHideWindow(); } void MainWindow::MWShowWindow() { #if QV2RAY_FEATURE(ui_has_store_state) RestoreState(); #endif this->show(); #ifdef Q_OS_WIN setWindowState(Qt::WindowNoState); SetWindowPos(HWND(this->winId()), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); QThread::msleep(20); SetWindowPos(HWND(this->winId()), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #endif #ifdef Q_OS_MAC ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToForegroundApplication); #endif MWToggleVisibilitySetText(); } void MainWindow::MWHideWindow() { #ifdef Q_OS_MAC ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToUIElementApplication); #endif #if QV2RAY_FEATURE(ui_has_store_state) SaveState(); #endif this->hide(); MWToggleVisibilitySetText(); } void MainWindow::MWSetSystemProxy() { const auto inboundInfo = KernelInstance->GetCurrentConnectionInboundInfo(); bool httpEnabled = false; bool socksEnabled = false; int httpPort = 0; int socksPort = 0; QString httpAddress; QString socksAddress; for (const auto &info : inboundInfo) { if (info.protocol == "http") { httpEnabled = true; httpPort = info.port; httpAddress = info.address; } else if (info.protocol == "socks") { socksEnabled = true; socksPort = info.port; socksAddress = info.address; } } QString proxyAddress; if (httpEnabled) proxyAddress = httpAddress; else if (socksEnabled) proxyAddress = socksAddress; const QHostAddress ha(proxyAddress); if (ha.isEqual(QHostAddress::AnyIPv4)) // "0.0.0.0" proxyAddress = "127.0.0.1"; else if (ha.isEqual(QHostAddress::AnyIPv6)) // "::" proxyAddress = "::1"; if (!proxyAddress.isEmpty()) { LOG("ProxyAddress: " + proxyAddress); LOG("HTTP Port: " + QSTRN(httpPort)); LOG("SOCKS Port: " + QSTRN(socksPort)); SetSystemProxy(proxyAddress, httpPort, socksPort); qvAppTrayIcon->setIcon(Q_TRAYICON("tray-systemproxy")); if (!GlobalConfig.uiConfig.quietMode) { QvWidgetApplication->ShowTrayMessage(tr("System proxy configured.")); } } else { LOG("Neither of HTTP nor SOCKS is enabled, cannot set system proxy."); QvMessageBoxWarn(this, tr("Cannot set system proxy"), tr("Both HTTP and SOCKS inbounds are not enabled")); } } void MainWindow::MWClearSystemProxy() { ClearSystemProxy(); qvAppTrayIcon->setIcon(KernelInstance->CurrentConnection().isEmpty() ? Q_TRAYICON("tray") : Q_TRAYICON("tray-connected")); if (!GlobalConfig.uiConfig.quietMode) { QvWidgetApplication->ShowTrayMessage(tr("System proxy removed.")); } } bool MainWindow::StartAutoConnectionEntry() { if (QvCoreApplication->StartupArguments.noAutoConnection) return false; switch (GlobalConfig.autoStartBehavior) { case AUTO_CONNECTION_NONE: return false; case AUTO_CONNECTION_FIXED: return ConnectionManager->StartConnection(GlobalConfig.autoStartId); case AUTO_CONNECTION_LAST_CONNECTED: return ConnectionManager->StartConnection(GlobalConfig.lastConnectedId); } Q_UNREACHABLE(); } void MainWindow::CheckSubscriptionsUpdate() { QList<std::pair<QString, GroupId>> updateList; QStringList updateNamesList; for (const auto &entry : ConnectionManager->Subscriptions()) { const auto info = ConnectionManager->GetGroupMetaObject(entry); // // The update is ignored. if (info.subscriptionOption.updateInterval == 0) continue; // const auto lastRenewDate = QDateTime::fromSecsSinceEpoch(info.lastUpdatedDate); const auto renewTime = lastRenewDate.addSecs(info.subscriptionOption.updateInterval * 86400); if (renewTime <= QDateTime::currentDateTime()) { updateList << std::pair{ info.displayName, entry }; updateNamesList << info.displayName; LOG(QString("Subscription update \"%1\": L=%2 R=%3 I=%4") .arg(info.displayName) .arg(lastRenewDate.toString()) .arg(QSTRN(info.subscriptionOption.updateInterval)) .arg(renewTime.toString())); } } if (!updateList.isEmpty()) { const auto result = GlobalConfig.uiConfig.quietMode ? Yes : QvMessageBoxAsk(this, tr("Update Subscriptions"), // tr("Do you want to update these subscriptions?") + NEWLINE + // updateNamesList.join(NEWLINE), // { Yes, No, Ignore }); for (const auto &[name, id] : updateList) { if (result == Yes) { LOG("Updating subscription: " + name); ConnectionManager->UpdateSubscriptionAsync(id); } else if (result == Ignore) { LOG("Ignored subscription update: " + name); ConnectionManager->IgnoreSubscriptionUpdate(id); } } } } void MainWindow::updateColorScheme() { qvAppTrayIcon->setIcon(KernelInstance->CurrentConnection().isEmpty() ? Q_TRAYICON("tray") : Q_TRAYICON("tray-connected")); // importConfigButton->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("add"))); updownImageBox->setStyleSheet("image: url(" + QV2RAY_COLORSCHEME_FILE("netspeed_arrow") + ")"); updownImageBox_2->setStyleSheet("image: url(" + QV2RAY_COLORSCHEME_FILE("netspeed_arrow") + ")"); // tray_action_ToggleVisibility->setIcon(this->windowIcon()); action_RCM_Start->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("start"))); action_RCM_Edit->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("edit"))); action_RCM_EditJson->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("code"))); action_RCM_EditComplex->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("edit"))); action_RCM_DuplicateConnection->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("copy"))); action_RCM_DeleteConnection->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); action_RCM_ResetStats->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); action_RCM_TestLatency->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ping_gauge"))); action_RCM_RealLatencyTest->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ping_gauge"))); // clearChartBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); clearlogButton->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("ashbin"))); // locateBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("map"))); sortBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("arrow-down-filling"))); collapseGroupsBtn->setIcon(QIcon(QV2RAY_COLORSCHEME_FILE("arrow-up"))); } void MainWindow::UpdateActionTranslations() { tray_BypassCNMenu->setTitle(tr("Bypass CN Mainland")); tray_SystemProxyMenu->setTitle(tr("System Proxy")); tray_RecentConnectionsMenu->setTitle(tr("Recent Connections")); tray_ClearRecentConnectionsAction->setText(tr("Clear Recent Connections")); // tray_action_ToggleVisibility->setText(tr("Hide")); tray_action_Preferences->setText(tr("Preferences")); tray_action_Quit->setText(tr("Quit")); tray_action_Start->setText(tr("Connect")); tray_action_Restart->setText(tr("Reconnect")); tray_action_Stop->setText(tr("Disconnect")); tray_action_SetBypassCN->setText(tr("Enable Bypassing CN Mainland")); tray_action_ClearBypassCN->setText(tr("Disable Bypassing CN Mainland")); tray_action_SetSystemProxy->setText(tr("Enable System Proxy")); tray_action_ClearSystemProxy->setText(tr("Disable System Proxy")); // action_RCM_Start->setText(tr("Connect to this")); action_RCM_SetAutoConnection->setText(tr("Set as automatically connected")); action_RCM_EditJson->setText(tr("Edit as JSON")); action_RCM_UpdateSubscription->setText(tr("Update Subscription")); action_RCM_EditComplex->setText(tr("Edit as Complex Config")); action_RCM_RenameConnection->setText(tr("Rename")); action_RCM_Edit->setText(tr("Edit")); action_RCM_DuplicateConnection->setText(tr("Duplicate to the Same Group")); action_RCM_TestLatency->setText(tr("Test Latency")); action_RCM_RealLatencyTest->setText(tr("Test Real Latency")); action_RCM_ResetStats->setText(tr("Clear Usage Data")); action_RCM_DeleteConnection->setText(tr("Delete Connection")); // sortMenu->setTitle(tr("Sort connection list.")); sortAction_SortByName_Asc->setText(tr("By connection name, A-Z")); sortAction_SortByName_Dsc->setText(tr("By connection name, Z-A")); sortAction_SortByPing_Asc->setText(tr("By latency, Ascending")); sortAction_SortByPing_Dsc->setText(tr("By latency, Descending")); sortAction_SortByData_Asc->setText(tr("By data, Ascending")); sortAction_SortByData_Dsc->setText(tr("By data, Descending")); // action_RCM_SwitchCoreLog->setText(tr("Switch to Core log")); action_RCM_SwitchQv2rayLog->setText(tr("Switch to Qv2ray log")); // action_RCM_CopyGraph->setText(tr("Copy graph as image.")); action_RCM_CopyRecentLogs->setText(tr("Copy latest logs.")); action_RCM_CopySelected->setText(tr("Copy selected.")); }
10,344
C++
.cpp
245
35.061224
141
0.663525
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,206
w_MainWindow.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_MainWindow.cpp
#include "w_MainWindow.hpp" #include "components/update/UpdateChecker.hpp" #include "core/handler/ConfigHandler.hpp" #include "core/settings/SettingsBackend.hpp" #include "plugin-interface/QvGUIPluginInterface.hpp" #include "ui/widgets/Qv2rayWidgetApplication.hpp" #include "ui/widgets/common/WidgetUIBase.hpp" #include "ui/widgets/editors/w_JsonEditor.hpp" #include "ui/widgets/editors/w_OutboundEditor.hpp" #include "ui/widgets/editors/w_RoutesEditor.hpp" #include "ui/widgets/widgets/ConnectionInfoWidget.hpp" #include "ui/widgets/windows/w_GroupManager.hpp" #include "ui/widgets/windows/w_ImportConfig.hpp" #include "ui/widgets/windows/w_PluginManager.hpp" #include "ui/widgets/windows/w_PreferencesWindow.hpp" #include <QClipboard> #include <QInputDialog> #include <QScrollBar> #define QV_MODULE_NAME "MainWindow" #define TRAY_TOOLTIP_PREFIX "Qv2ray " QV2RAY_VERSION_STRING #define CheckCurrentWidget \ auto widget = GetIndexWidget(connectionTreeView->currentIndex()); \ if (widget == nullptr) \ return; #define GetIndexWidget(item) (qobject_cast<ConnectionItemWidget *>(connectionTreeView->indexWidget(item))) #define NumericString(i) (QString("%1").arg(i, 30, 10, QLatin1Char('0'))) #define PLUGIN_BUTTON_PROPERTY_KEY "plugin_list_index" QvMessageBusSlotImpl(MainWindow) { switch (msg) { MBShowDefaultImpl; MBHideDefaultImpl; MBUpdateColorSchemeDefaultImpl; case RETRANSLATE: { retranslateUi(this); UpdateActionTranslations(); break; } } } void MainWindow::SortConnectionList(ConnectionInfoRole byCol, bool asending) { modelHelper->Sort(byCol, asending ? Qt::AscendingOrder : Qt::DescendingOrder); on_locateBtn_clicked(); } void MainWindow::ReloadRecentConnectionList() { QList<ConnectionGroupPair> newRecentConnections; const auto iterateRange = std::min(GlobalConfig.uiConfig.maxJumpListCount, (int) GlobalConfig.uiConfig.recentConnections.count()); for (auto i = 0; i < iterateRange; i++) { const auto &item = GlobalConfig.uiConfig.recentConnections.at(i); if (newRecentConnections.contains(item) || item.isEmpty()) continue; newRecentConnections << item; } GlobalConfig.uiConfig.recentConnections = newRecentConnections; } void MainWindow::OnRecentConnectionsMenuReadyToShow() { tray_RecentConnectionsMenu->clear(); tray_RecentConnectionsMenu->addAction(tray_ClearRecentConnectionsAction); tray_RecentConnectionsMenu->addSeparator(); for (const auto &conn : GlobalConfig.uiConfig.recentConnections) { if (ConnectionManager->IsValidId(conn)) { const auto name = GetDisplayName(conn.connectionId) + " (" + GetDisplayName(conn.groupId) + ")"; tray_RecentConnectionsMenu->addAction(name, [=]() { emit ConnectionManager->StartConnection(conn); }); } } } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), QvStateObject("MainWindow") { setupUi(this); addStateOptions("width", { [&] { return width(); }, [&](QJsonValue val) { resize(val.toInt(), size().height()); } }); addStateOptions("height", { [&] { return height(); }, [&](QJsonValue val) { resize(size().width(), val.toInt()); } }); addStateOptions("x", { [&] { return x(); }, [&](QJsonValue val) { move(val.toInt(), y()); } }); addStateOptions("y", { [&] { return y(); }, [&](QJsonValue val) { move(x(), val.toInt()); } }); #if 0 const auto setSplitterSize = [&](QJsonValue val) { splitter->setSizes({ val.toArray()[0].toInt(), val.toArray()[1].toInt() }); }; addStateOptions("splitterSizes", { [&] { return QJsonArray{ splitter->sizes()[0], splitter->sizes()[1] }; }, setSplitterSize }); const auto setSpeedWidgetVisibility = [&](QJsonValue val) { speedChartHolderWidget->setVisible(val.toBool()); }; const auto setLogWidgetVisibility = [&](QJsonValue val) { masterLogBrowser->setVisible(val.toBool()); }; addStateOptions("speedchart.visibility", { [&] { return speedChartHolderWidget->isVisible(); }, setSpeedWidgetVisibility }); addStateOptions("log.visibility", { [&] { return masterLogBrowser->isVisible(); }, setLogWidgetVisibility }); #else constexpr auto sizeRatioA = 0.382; constexpr auto sizeRatioB = 1 - sizeRatioA; splitter->setSizes({ (int) (width() * sizeRatioA), (int) (width() * sizeRatioB) }); #endif QvMessageBusConnect(MainWindow); // infoWidget = new ConnectionInfoWidget(this); connectionInfoLayout->addWidget(infoWidget); // masterLogBrowser->setDocument(vCoreLogDocument); vCoreLogHighlighter = new SyntaxHighlighter(GlobalConfig.uiConfig.useDarkTheme, masterLogBrowser->document()); // For charts speedChartWidget = new SpeedWidget(this); speedChart->addWidget(speedChartWidget); // modelHelper = new ConnectionListHelper(connectionTreeView); // this->setWindowIcon(QIcon(":/assets/icons/qv2ray.png")); updateColorScheme(); UpdateActionTranslations(); // // connect(ConnectionManager, &QvConfigHandler::OnKernelCrashed, [this](const ConnectionGroupPair &, const QString &reason) { MWShowWindow(); QvMessageBoxWarn(this, tr("Kernel terminated."), tr("The kernel terminated unexpectedly:") + NEWLINE + reason + NEWLINE + NEWLINE + tr("To solve the problem, read the kernel log in the log text browser.")); }); // connect(ConnectionManager, &QvConfigHandler::OnConnected, this, &MainWindow::OnConnected); connect(ConnectionManager, &QvConfigHandler::OnDisconnected, this, &MainWindow::OnDisconnected); connect(ConnectionManager, &QvConfigHandler::OnStatsAvailable, this, &MainWindow::OnStatsAvailable); connect(ConnectionManager, &QvConfigHandler::OnKernelLogAvailable, this, &MainWindow::OnVCoreLogAvailable); // connect(ConnectionManager, &QvConfigHandler::OnSubscriptionAsyncUpdateFinished, [](const GroupId &gid) { QvWidgetApplication->ShowTrayMessage(tr("Subscription \"%1\" has been updated").arg(GetDisplayName(gid))); // }); // connect(infoWidget, &ConnectionInfoWidget::OnEditRequested, this, &MainWindow::OnEditRequested); connect(infoWidget, &ConnectionInfoWidget::OnJsonEditRequested, this, &MainWindow::OnEditJsonRequested); // connect(masterLogBrowser->verticalScrollBar(), &QSlider::valueChanged, this, &MainWindow::OnLogScrollbarValueChanged); // // Setup System tray icons and menus qvAppTrayIcon->setToolTip(TRAY_TOOLTIP_PREFIX); qvAppTrayIcon->show(); // // Basic tray actions tray_action_Start->setEnabled(true); tray_action_Stop->setEnabled(false); tray_action_Restart->setEnabled(false); // tray_BypassCNMenu->setEnabled(false); tray_BypassCNMenu->addAction(tray_action_SetBypassCN); tray_BypassCNMenu->addAction(tray_action_ClearBypassCN); // tray_SystemProxyMenu->setEnabled(false); tray_SystemProxyMenu->addAction(tray_action_SetSystemProxy); tray_SystemProxyMenu->addAction(tray_action_ClearSystemProxy); // tray_RootMenu->addAction(tray_action_ToggleVisibility); tray_RootMenu->addSeparator(); tray_RootMenu->addAction(tray_action_Preferences); tray_RootMenu->addMenu(tray_BypassCNMenu); tray_RootMenu->addMenu(tray_SystemProxyMenu); // tray_RootMenu->addSeparator(); tray_RootMenu->addMenu(tray_RecentConnectionsMenu); connect(tray_RecentConnectionsMenu, &QMenu::aboutToShow, this, &MainWindow::OnRecentConnectionsMenuReadyToShow); // tray_RootMenu->addSeparator(); tray_RootMenu->addAction(tray_action_Start); tray_RootMenu->addAction(tray_action_Stop); tray_RootMenu->addAction(tray_action_Restart); tray_RootMenu->addSeparator(); tray_RootMenu->addAction(tray_action_Quit); qvAppTrayIcon->setContextMenu(tray_RootMenu); // connect(tray_action_ToggleVisibility, &QAction::triggered, this, &MainWindow::MWToggleVisibility); connect(tray_action_Preferences, &QAction::triggered, this, &MainWindow::on_preferencesBtn_clicked); connect(tray_action_Start, &QAction::triggered, [this] { ConnectionManager->StartConnection(lastConnected); }); connect(tray_action_Stop, &QAction::triggered, ConnectionManager, &QvConfigHandler::StopConnection); connect(tray_action_Restart, &QAction::triggered, ConnectionManager, &QvConfigHandler::RestartConnection); connect(tray_action_Quit, &QAction::triggered, this, &MainWindow::Action_Exit); connect(tray_action_SetBypassCN, &QAction::triggered, this, &MainWindow::on_setBypassCNBtn_clicked); connect(tray_action_ClearBypassCN, &QAction::triggered, this, &MainWindow::on_clearBypassCNBtn_clicked); connect(tray_action_SetSystemProxy, &QAction::triggered, this, &MainWindow::MWSetSystemProxy); connect(tray_action_ClearSystemProxy, &QAction::triggered, this, &MainWindow::MWClearSystemProxy); connect(tray_ClearRecentConnectionsAction, &QAction::triggered, [this]() { GlobalConfig.uiConfig.recentConnections.clear(); ReloadRecentConnectionList(); if (!GlobalConfig.uiConfig.quietMode) QvWidgetApplication->ShowTrayMessage(tr("Recent Connection list cleared.")); }); connect(qvAppTrayIcon, &QSystemTrayIcon::activated, this, &MainWindow::on_activatedTray); // // Actions for right click the log text browser // logRCM_Menu->addAction(action_RCM_CopySelected); logRCM_Menu->addAction(action_RCM_CopyRecentLogs); logRCM_Menu->addSeparator(); logRCM_Menu->addAction(action_RCM_SwitchCoreLog); logRCM_Menu->addAction(action_RCM_SwitchQv2rayLog); connect(masterLogBrowser, &QTextBrowser::customContextMenuRequested, [this](const QPoint &) { logRCM_Menu->popup(QCursor::pos()); }); connect(action_RCM_SwitchCoreLog, &QAction::triggered, [this] { masterLogBrowser->setDocument(vCoreLogDocument); }); connect(action_RCM_SwitchQv2rayLog, &QAction::triggered, [this] { masterLogBrowser->setDocument(qvLogDocument); }); connect(action_RCM_CopyRecentLogs, &QAction::triggered, this, &MainWindow::Action_CopyRecentLogs); connect(action_RCM_CopySelected, &QAction::triggered, masterLogBrowser, &QTextBrowser::copy); // speedChartWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(speedChartWidget, &QWidget::customContextMenuRequested, [this](const QPoint &) { graphWidgetMenu->popup(QCursor::pos()); }); // masterLogBrowser->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); { auto font = masterLogBrowser->font(); font.setPointSize(9); masterLogBrowser->setFont(font); qvLogDocument->setDefaultFont(font); vCoreLogDocument->setDefaultFont(font); } // // Globally invokable signals. // connect(this, &MainWindow::StartConnection, ConnectionManager, &QvConfigHandler::RestartConnection); connect(this, &MainWindow::StopConnection, ConnectionManager, &QvConfigHandler::StopConnection); connect(this, &MainWindow::RestartConnection, ConnectionManager, &QvConfigHandler::RestartConnection); // // Actions for right click the connection list // connectionListRCM_Menu->addAction(action_RCM_Start); connectionListRCM_Menu->addSeparator(); connectionListRCM_Menu->addAction(action_RCM_Edit); connectionListRCM_Menu->addAction(action_RCM_EditJson); connectionListRCM_Menu->addAction(action_RCM_EditComplex); connectionListRCM_Menu->addSeparator(); connectionListRCM_Menu->addAction(action_RCM_TestLatency); connectionListRCM_Menu->addAction(action_RCM_RealLatencyTest); connectionListRCM_Menu->addSeparator(); connectionListRCM_Menu->addAction(action_RCM_SetAutoConnection); connectionListRCM_Menu->addSeparator(); connectionListRCM_Menu->addAction(action_RCM_RenameConnection); connectionListRCM_Menu->addAction(action_RCM_DuplicateConnection); connectionListRCM_Menu->addAction(action_RCM_ResetStats); connectionListRCM_Menu->addAction(action_RCM_UpdateSubscription); connectionListRCM_Menu->addSeparator(); connectionListRCM_Menu->addAction(action_RCM_DeleteConnection); // connect(action_RCM_Start, &QAction::triggered, this, &MainWindow::Action_Start); connect(action_RCM_SetAutoConnection, &QAction::triggered, this, &MainWindow::Action_SetAutoConnection); connect(action_RCM_Edit, &QAction::triggered, this, &MainWindow::Action_Edit); connect(action_RCM_EditJson, &QAction::triggered, this, &MainWindow::Action_EditJson); connect(action_RCM_EditComplex, &QAction::triggered, this, &MainWindow::Action_EditComplex); connect(action_RCM_TestLatency, &QAction::triggered, this, &MainWindow::Action_TestLatency); connect(action_RCM_RealLatencyTest, &QAction::triggered, this, &MainWindow::Action_TestRealLatency); connect(action_RCM_RenameConnection, &QAction::triggered, this, &MainWindow::Action_RenameConnection); connect(action_RCM_DuplicateConnection, &QAction::triggered, this, &MainWindow::Action_DuplicateConnection); connect(action_RCM_ResetStats, &QAction::triggered, this, &MainWindow::Action_ResetStats); connect(action_RCM_UpdateSubscription, &QAction::triggered, this, &MainWindow::Action_UpdateSubscription); connect(action_RCM_DeleteConnection, &QAction::triggered, this, &MainWindow::Action_DeleteConnections); // // Sort Menu // sortMenu->addAction(sortAction_SortByName_Asc); sortMenu->addAction(sortAction_SortByName_Dsc); sortMenu->addSeparator(); sortMenu->addAction(sortAction_SortByData_Asc); sortMenu->addAction(sortAction_SortByData_Dsc); sortMenu->addSeparator(); sortMenu->addAction(sortAction_SortByPing_Asc); sortMenu->addAction(sortAction_SortByPing_Dsc); // connect(sortAction_SortByName_Asc, &QAction::triggered, [this] { SortConnectionList(ROLE_DISPLAYNAME, true); }); connect(sortAction_SortByName_Dsc, &QAction::triggered, [this] { SortConnectionList(ROLE_DISPLAYNAME, false); }); connect(sortAction_SortByData_Asc, &QAction::triggered, [this] { SortConnectionList(ROLE_DATA_USAGE, true); }); connect(sortAction_SortByData_Dsc, &QAction::triggered, [this] { SortConnectionList(ROLE_DATA_USAGE, false); }); connect(sortAction_SortByPing_Asc, &QAction::triggered, [this] { SortConnectionList(ROLE_LATENCY, true); }); connect(sortAction_SortByPing_Dsc, &QAction::triggered, [this] { SortConnectionList(ROLE_LATENCY, false); }); // sortBtn->setMenu(sortMenu); // graphWidgetMenu->addAction(action_RCM_CopyGraph); connect(action_RCM_CopyGraph, &QAction::triggered, this, &MainWindow::Action_CopyGraphAsImage); // // Find and start if there is an auto-connection const auto connectionStarted = StartAutoConnectionEntry(); if (!connectionStarted && !ConnectionManager->GetConnections().isEmpty()) { // Select the first connection. const auto groups = ConnectionManager->AllGroups(); if (!groups.isEmpty()) { const auto connections = ConnectionManager->GetConnections(groups.first()); if (!connections.empty()) { const auto index = modelHelper->GetConnectionPairIndex({ connections.first(), groups.first() }); connectionTreeView->setCurrentIndex(index); on_connectionTreeView_clicked(index); } } } ReloadRecentConnectionList(); // // if (!connectionStarted || !GlobalConfig.uiConfig.startMinimized) MWShowWindow(); if (GlobalConfig.uiConfig.startMinimized) MWToggleVisibilitySetText(); // CheckSubscriptionsUpdate(); qvLogTimerId = startTimer(1000); auto checker = new QvUpdateChecker(this); checker->CheckUpdate(); // for (const auto &name : PluginHost->UsablePlugins()) { const auto &plugin = PluginHost->GetPlugin(name); if (!plugin->hasComponent(COMPONENT_GUI)) continue; const auto guiInterface = plugin->pluginInterface->GetGUIInterface(); if (!guiInterface) continue; if (!guiInterface->GetComponents().contains(GUI_COMPONENT_MAINWINDOW_WIDGET)) continue; auto mainWindowWidgetPtr = guiInterface->GetMainWindowWidget(); if (!mainWindowWidgetPtr) continue; const auto index = pluginWidgets.count(); { // Let Qt manage the ownership. auto widget = mainWindowWidgetPtr.release(); pluginWidgets.append(widget); } auto btn = new QPushButton(plugin->metadata.Name, this); connect(btn, &QPushButton::clicked, this, &MainWindow::OnPluginButtonClicked); btn->setProperty(PLUGIN_BUTTON_PROPERTY_KEY, index); topButtonsLayout->addWidget(btn); } } void MainWindow::OnPluginButtonClicked() { const auto senderWidget = qobject_cast<QPushButton *>(sender()); if (!senderWidget) return; bool ok = false; const auto index = senderWidget->property(PLUGIN_BUTTON_PROPERTY_KEY).toInt(&ok); if (!ok) return; const auto widget = pluginWidgets.at(index); if (!widget) return; widget->setVisible(!widget->isVisible()); } void MainWindow::ProcessCommand(QString command, QStringList commands, QMap<QString, QString> args) { if (commands.isEmpty()) return; if (command == "open") { const auto subcommand = commands.takeFirst(); QvDialog *w; if (subcommand == "preference") w = new PreferencesWindow(); else if (subcommand == "plugin") w = new PluginManageWindow(); else if (subcommand == "group") w = new GroupManager(); else if (subcommand == "import") w = new ImportConfigWindow(); else return; w->processCommands(command, commands, args); w->exec(); delete w; } } void MainWindow::timerEvent(QTimerEvent *event) { if (event->timerId() == qvLogTimerId) { auto log = ReadLog().trimmed(); if (!log.isEmpty()) { FastAppendTextDocument(NEWLINE + log, qvLogDocument); } } } void MainWindow::keyPressEvent(QKeyEvent *e) { if (focusWidget() == connectionTreeView) { CheckCurrentWidget; if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { // If pressed enter or return on connectionListWidget. Try to connect to the selected connection. if (widget->IsConnection()) { widget->BeginConnection(); } else { connectionTreeView->expand(connectionTreeView->currentIndex()); } } else if (e->key() == Qt::Key_F2) { widget->BeginRename(); } else if (e->key() == Qt::Key_Delete) { Action_DeleteConnections(); } } if (e->key() == Qt::Key_Escape) { auto widget = GetIndexWidget(connectionTreeView->currentIndex()); // Check if this key was accpted by the ConnectionItemWidget if (widget && widget->IsRenaming()) { widget->CancelRename(); return; } else if (this->isActiveWindow()) { this->close(); } } // Ctrl + Q = Exit else if (e->modifiers() & Qt::ControlModifier && e->key() == Qt::Key_Q) { if (QvMessageBoxAsk(this, tr("Quit Qv2ray"), tr("Are you sure to exit Qv2ray?")) == Yes) Action_Exit(); } // Control + W = Close Window else if (e->modifiers() & Qt::ControlModifier && e->key() == Qt::Key_W) { if (this->isActiveWindow()) this->close(); } } void MainWindow::keyReleaseEvent(QKeyEvent *e) { // Workaround of QtWidget not grabbing KeyDown and KeyUp in keyPressEvent if (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down) { if (focusWidget() == connectionTreeView) { CheckCurrentWidget; on_connectionTreeView_clicked(connectionTreeView->currentIndex()); } } } void MainWindow::changeEvent(QEvent *e) { if (e->type() == QEvent::WindowStateChange) { MWToggleVisibilitySetText(); } } void MainWindow::Action_Start() { CheckCurrentWidget; if (widget->IsConnection()) { widget->BeginConnection(); } } MainWindow::~MainWindow() { #if QV2RAY_FEATURE(ui_has_store_state) SaveState(); #endif delete modelHelper; for (auto &widget : pluginWidgets) widget->accept(); } void MainWindow::closeEvent(QCloseEvent *event) { if (GlobalConfig.uiConfig.exitByCloseEvent) { Action_Exit(); } else { MWHideWindow(); event->ignore(); } } void MainWindow::on_activatedTray(QSystemTrayIcon::ActivationReason reason) { #ifndef __APPLE__ const auto toggleTriggerEvent = QSystemTrayIcon::Trigger; #else const auto toggleTriggerEvent = QSystemTrayIcon::DoubleClick; #endif if (reason == toggleTriggerEvent) MWToggleVisibility(); } void MainWindow::Action_Exit() { ConnectionManager->StopConnection(); QvWidgetApplication->quit(); } void MainWindow::on_preferencesBtn_clicked() { PreferencesWindow{ this }.exec(); } void MainWindow::on_setBypassCNBtn_clicked() { GlobalConfig.defaultRouteConfig.connectionConfig.bypassCN = true; SaveGlobalSettings(); if (!KernelInstance->CurrentConnection().isEmpty()) { qApp->processEvents(); ConnectionManager->RestartConnection(); } } void MainWindow::on_clearBypassCNBtn_clicked() { GlobalConfig.defaultRouteConfig.connectionConfig.bypassCN = false; SaveGlobalSettings(); if (!KernelInstance->CurrentConnection().isEmpty()) { qApp->processEvents(); ConnectionManager->RestartConnection(); } } void MainWindow::on_clearlogButton_clicked() { masterLogBrowser->document()->clear(); } void MainWindow::on_connectionTreeView_customContextMenuRequested(const QPoint &pos) { Q_UNUSED(pos) auto _pos = QCursor::pos(); auto item = connectionTreeView->indexAt(connectionTreeView->mapFromGlobal(_pos)); if (item.isValid()) { bool isConnection = GetIndexWidget(item)->IsConnection(); // Disable connection-specific settings. action_RCM_Start->setEnabled(isConnection); action_RCM_SetAutoConnection->setEnabled(isConnection); action_RCM_Edit->setEnabled(isConnection); action_RCM_EditJson->setEnabled(isConnection); action_RCM_EditComplex->setEnabled(isConnection); action_RCM_RenameConnection->setEnabled(isConnection); action_RCM_DuplicateConnection->setEnabled(isConnection); action_RCM_UpdateSubscription->setEnabled(!isConnection); action_RCM_RealLatencyTest->setEnabled(isConnection && ConnectionManager->IsConnected(GetIndexWidget(item)->Identifier())); connectionListRCM_Menu->popup(_pos); } } void MainWindow::Action_DeleteConnections() { QList<ConnectionGroupPair> connlist; QList<GroupId> groupsList; for (const auto &item : connectionTreeView->selectionModel()->selectedIndexes()) { const auto widget = GetIndexWidget(item); if (!widget) continue; const auto identifier = widget->Identifier(); if (widget->IsConnection()) { // Simply add the connection id connlist.append(identifier); continue; } for (const auto &conns : ConnectionManager->GetConnections(identifier.groupId)) { connlist.append(ConnectionGroupPair{ conns, identifier.groupId }); } const auto message = tr("Do you want to remove this group as well?") + NEWLINE + tr("Group: ") + GetDisplayName(identifier.groupId); if (QvMessageBoxAsk(this, tr("Removing Connection"), message) == Yes) { groupsList << identifier.groupId; } } const auto strRemoveConnTitle = tr("Removing Connection(s)", "", connlist.count()); const auto strRemoveConnContent = tr("Are you sure to remove selected connection(s)?", "", connlist.count()); if (QvMessageBoxAsk(this, strRemoveConnTitle, strRemoveConnContent) != Yes) { return; } for (const auto &conn : connlist) { ConnectionManager->RemoveConnectionFromGroup(conn.connectionId, conn.groupId); } for (const auto &group : groupsList) { ConnectionManager->DeleteGroup(group); } } void MainWindow::on_importConfigButton_clicked() { ImportConfigWindow w(this); w.PerformImportConnection(); } void MainWindow::Action_EditComplex() { CheckCurrentWidget; if (widget->IsConnection()) { auto id = widget->Identifier(); CONFIGROOT root = ConnectionManager->GetConnectionRoot(id.connectionId); bool isChanged = false; // LOG("INFO: Opening route editor."); RouteEditor routeWindow(root, this); root = routeWindow.OpenEditor(); isChanged = routeWindow.result() == QDialog::Accepted; if (isChanged) { ConnectionManager->UpdateConnection(id.connectionId, root); } } } void MainWindow::on_subsButton_clicked() { GroupManager().exec(); } void MainWindow::OnDisconnected(const ConnectionGroupPair &id) { Q_UNUSED(id) qvAppTrayIcon->setIcon(Q_TRAYICON("tray")); tray_action_Start->setEnabled(true); tray_action_Stop->setEnabled(false); tray_action_Restart->setEnabled(false); tray_BypassCNMenu->setEnabled(false); tray_SystemProxyMenu->setEnabled(false); lastConnected = id; locateBtn->setEnabled(false); if (!GlobalConfig.uiConfig.quietMode) { QvWidgetApplication->ShowTrayMessage(tr("Disconnected from: ") + GetDisplayName(id.connectionId)); } qvAppTrayIcon->setToolTip(TRAY_TOOLTIP_PREFIX); netspeedLabel->setText("0.00 B/s" NEWLINE "0.00 B/s"); dataamountLabel->setText("0.00 B" NEWLINE "0.00 B"); connetionStatusLabel->setText(tr("Not Connected")); if (GlobalConfig.inboundConfig.systemProxySettings.setSystemProxy) { MWClearSystemProxy(); } } void MainWindow::OnConnected(const ConnectionGroupPair &id) { Q_UNUSED(id) qvAppTrayIcon->setIcon(Q_TRAYICON("tray-connected")); tray_action_Start->setEnabled(false); tray_action_Stop->setEnabled(true); tray_action_Restart->setEnabled(true); tray_BypassCNMenu->setEnabled(true); tray_SystemProxyMenu->setEnabled(true); lastConnected = id; locateBtn->setEnabled(true); on_clearlogButton_clicked(); auto name = GetDisplayName(id.connectionId); if (!GlobalConfig.uiConfig.quietMode) { QvWidgetApplication->ShowTrayMessage(tr("Connected: ") + name); } qvAppTrayIcon->setToolTip(TRAY_TOOLTIP_PREFIX NEWLINE + tr("Connected: ") + name); connetionStatusLabel->setText(tr("Connected: ") + name); // GlobalConfig.uiConfig.recentConnections.removeAll(id); GlobalConfig.uiConfig.recentConnections.push_front(id); ReloadRecentConnectionList(); // QTimer::singleShot(1000, ConnectionManager, [id]() { // After the kernel initialization is complete, we can test the delay without worry if (GlobalConfig.advancedConfig.testLatencyOnConnected) { ConnectionManager->StartLatencyTest(id.connectionId); } }); if (GlobalConfig.inboundConfig.systemProxySettings.setSystemProxy) { MWSetSystemProxy(); } } void MainWindow::on_connectionFilterTxt_textEdited(const QString &arg1) { modelHelper->Filter(arg1); } void MainWindow::OnStatsAvailable(const ConnectionGroupPair &id, const QMap<StatisticsType, QvStatsSpeedData> &data) { if (!ConnectionManager->IsConnected(id)) return; // This may not be, or may not precisely be, speed per second if the backend // has "any" latency. (Hope not...) // QMap<SpeedWidget::GraphType, long> pointData; bool isOutbound = GlobalConfig.uiConfig.graphConfig.useOutboundStats; bool hasDirect = isOutbound && GlobalConfig.uiConfig.graphConfig.hasDirectStats; for (const auto &[type, data] : data.toStdMap()) { const auto upSpeed = data.first.first; const auto downSpeed = data.first.second; switch (type) { case API_INBOUND: if (!isOutbound) { pointData[SpeedWidget::INBOUND_UP] = upSpeed; pointData[SpeedWidget::INBOUND_DOWN] = downSpeed; } break; case API_OUTBOUND_PROXY: if (isOutbound) { pointData[SpeedWidget::OUTBOUND_PROXY_UP] = upSpeed; pointData[SpeedWidget::OUTBOUND_PROXY_DOWN] = downSpeed; } break; case API_OUTBOUND_DIRECT: if (hasDirect) { pointData[SpeedWidget::OUTBOUND_DIRECT_UP] = upSpeed; pointData[SpeedWidget::OUTBOUND_DIRECT_DOWN] = downSpeed; } break; case API_OUTBOUND_BLACKHOLE: break; } } speedChartWidget->AddPointData(pointData); // const auto upSpeed = data[CurrentStatAPIType].first.first; const auto downSpeed = data[CurrentStatAPIType].first.second; auto totalSpeedUp = FormatBytes(upSpeed) + "/s"; auto totalSpeedDown = FormatBytes(downSpeed) + "/s"; auto totalDataUp = FormatBytes(data[CurrentStatAPIType].second.first); auto totalDataDown = FormatBytes(data[CurrentStatAPIType].second.second); // netspeedLabel->setText(totalSpeedUp + NEWLINE + totalSpeedDown); dataamountLabel->setText(totalDataUp + NEWLINE + totalDataDown); // qvAppTrayIcon->setToolTip(TRAY_TOOLTIP_PREFIX NEWLINE + tr("Connected: ") + GetDisplayName(id.connectionId) + // NEWLINE "Up: " + totalSpeedUp + " Down: " + totalSpeedDown); } void MainWindow::OnVCoreLogAvailable(const ConnectionGroupPair &id, const QString &log) { Q_UNUSED(id); FastAppendTextDocument(log.trimmed(), vCoreLogDocument); // vCoreLogDocument->setPlainText(vCoreLogDocument->toPlainText() + log); // From https://gist.github.com/jemyzhang/7130092 auto maxLines = GlobalConfig.uiConfig.maximumLogLines; auto block = vCoreLogDocument->begin(); while (block.isValid()) { if (vCoreLogDocument->blockCount() > maxLines) { QTextCursor cursor(block); block = block.next(); cursor.select(QTextCursor::BlockUnderCursor); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); cursor.removeSelectedText(); continue; } break; } } void MainWindow::OnEditRequested(const ConnectionId &id) { auto outBoundRoot = ConnectionManager->GetConnectionRoot(id); CONFIGROOT root; bool isChanged; if (IsComplexConfig(outBoundRoot)) { LOG("INFO: Opening route editor."); RouteEditor routeWindow(outBoundRoot, this); root = routeWindow.OpenEditor(); isChanged = routeWindow.result() == QDialog::Accepted; } else { LOG("INFO: Opening single connection edit window."); auto out = OUTBOUND(outBoundRoot["outbounds"].toArray().first().toObject()); OutboundEditor w(out, this); auto outboundEntry = w.OpenEditor(); isChanged = w.result() == QDialog::Accepted; QJsonArray outboundsList; outboundsList.push_back(outboundEntry); root.insert("outbounds", outboundsList); } if (isChanged) { ConnectionManager->UpdateConnection(id, root); } } void MainWindow::OnEditJsonRequested(const ConnectionId &id) { JsonEditor w(ConnectionManager->GetConnectionRoot(id), this); auto root = CONFIGROOT(w.OpenEditor()); if (w.result() == QDialog::Accepted) { ConnectionManager->UpdateConnection(id, root); } } void MainWindow::OnLogScrollbarValueChanged(int value) { if (masterLogBrowser->verticalScrollBar()->maximum() == value) qvLogAutoScoll = true; else qvLogAutoScoll = false; } void MainWindow::on_locateBtn_clicked() { auto id = KernelInstance->CurrentConnection(); if (!id.isEmpty()) { const auto index = modelHelper->GetConnectionPairIndex(id); connectionTreeView->setCurrentIndex(index); connectionTreeView->scrollTo(index); on_connectionTreeView_clicked(index); } } void MainWindow::Action_RenameConnection() { CheckCurrentWidget; widget->BeginRename(); } void MainWindow::Action_DuplicateConnection() { QList<ConnectionGroupPair> connlist; for (const auto &item : connectionTreeView->selectionModel()->selectedIndexes()) { auto widget = GetIndexWidget(item); if (widget->IsConnection()) { connlist.append(widget->Identifier()); } } LOG("Selected ", connlist.count(), " items"); const auto strDupConnTitle = tr("Duplicating Connection(s)", "", connlist.count()); const auto strDupConnContent = tr("Are you sure to duplicate these connection(s)?", "", connlist.count()); if (connlist.count() > 1 && QvMessageBoxAsk(this, strDupConnTitle, strDupConnContent) != Yes) { return; } for (const auto &conn : connlist) { ConnectionManager->CreateConnection(ConnectionManager->GetConnectionRoot(conn.connectionId), GetDisplayName(conn.connectionId) + tr(" (Copy)"), conn.groupId); } } void MainWindow::Action_Edit() { CheckCurrentWidget; OnEditRequested(widget->Identifier().connectionId); } void MainWindow::Action_EditJson() { CheckCurrentWidget; OnEditJsonRequested(widget->Identifier().connectionId); } void MainWindow::on_chartVisibilityBtn_clicked() { speedChartHolderWidget->setVisible(!speedChartWidget->isVisible()); } void MainWindow::on_logVisibilityBtn_clicked() { masterLogBrowser->setVisible(!masterLogBrowser->isVisible()); } void MainWindow::on_clearChartBtn_clicked() { speedChartWidget->Clear(); } void MainWindow::on_masterLogBrowser_textChanged() { if (!qvLogAutoScoll) return; auto bar = masterLogBrowser->verticalScrollBar(); bar->setValue(bar->maximum()); } void MainWindow::Action_SetAutoConnection() { auto current = connectionTreeView->currentIndex(); if (current.isValid()) { auto widget = GetIndexWidget(current); const auto identifier = widget->Identifier(); GlobalConfig.autoStartId = identifier; GlobalConfig.autoStartBehavior = AUTO_CONNECTION_FIXED; if (!GlobalConfig.uiConfig.quietMode) { QvWidgetApplication->ShowTrayMessage(tr("%1 has been set as auto connect.").arg(GetDisplayName(identifier.connectionId))); } SaveGlobalSettings(); } } void MainWindow::Action_ResetStats() { auto current = connectionTreeView->currentIndex(); if (current.isValid()) { auto widget = GetIndexWidget(current); if (widget) { if (widget->IsConnection()) ConnectionManager->ClearConnectionUsage(widget->Identifier()); else ConnectionManager->ClearGroupUsage(widget->Identifier().groupId); } } } void MainWindow::Action_UpdateSubscription() { auto current = connectionTreeView->currentIndex(); if (current.isValid()) { auto widget = GetIndexWidget(current); if (widget) { if (widget->IsConnection()) return; const auto gid = widget->Identifier().groupId; if (ConnectionManager->GetGroupMetaObject(gid).isSubscription) ConnectionManager->UpdateSubscriptionAsync(gid); else QvMessageBoxInfo(this, tr("Update Subscription"), tr("Selected group is not a subscription")); } } } void MainWindow::Action_TestLatency() { for (const auto &current : connectionTreeView->selectionModel()->selectedIndexes()) { if (!current.isValid()) continue; const auto widget = GetIndexWidget(current); if (!widget) continue; if (widget->IsConnection()) ConnectionManager->StartLatencyTest(widget->Identifier().connectionId); else ConnectionManager->StartLatencyTest(widget->Identifier().groupId); } } void MainWindow::Action_TestRealLatency() { for (const auto &current : connectionTreeView->selectionModel()->selectedIndexes()) { if (!current.isValid()) continue; const auto widget = GetIndexWidget(current); if (!widget) continue; if (widget->IsConnection() && ConnectionManager->IsConnected(widget->Identifier())) ConnectionManager->StartLatencyTest(widget->Identifier().connectionId, REALPING); } } void MainWindow::Action_CopyGraphAsImage() { const auto image = speedChartWidget->grab(); qApp->clipboard()->setImage(image.toImage()); } void MainWindow::on_pluginsBtn_clicked() { PluginManageWindow(this).exec(); } void MainWindow::on_newConnectionBtn_clicked() { OutboundEditor w(OUTBOUND{}, this); auto outboundEntry = w.OpenEditor(); bool isChanged = w.result() == QDialog::Accepted; if (isChanged) { const auto alias = w.GetFriendlyName(); OUTBOUNDS outboundsList; outboundsList.push_back(outboundEntry); CONFIGROOT root; root.insert("outbounds", outboundsList); const auto item = connectionTreeView->currentIndex(); const auto id = item.isValid() ? GetIndexWidget(item)->Identifier().groupId : DefaultGroupId; ConnectionManager->CreateConnection(root, alias, id); } } void MainWindow::on_newComplexConnectionBtn_clicked() { RouteEditor w({}, this); auto root = w.OpenEditor(); bool isChanged = w.result() == QDialog::Accepted; if (isChanged) { const auto item = connectionTreeView->currentIndex(); const auto id = item.isValid() ? GetIndexWidget(item)->Identifier().groupId : DefaultGroupId; ConnectionManager->CreateConnection(root, QJsonIO::GetValue(root, "outbounds", 0, "tag").toString(), id); } } void MainWindow::on_collapseGroupsBtn_clicked() { connectionTreeView->collapseAll(); } void MainWindow::Action_CopyRecentLogs() { const auto lines = SplitLines(masterLogBrowser->document()->toPlainText()); bool accepted = false; const auto line = QInputDialog::getInt(this, tr("Copy latest logs"), tr("Number of lines of logs to copy"), 20, 0, 2500, 1, &accepted); if (!accepted) return; const auto totalLinesCount = lines.count(); const auto linesToCopy = std::min((int) totalLinesCount, line); QStringList result; for (auto i = totalLinesCount - linesToCopy; i < totalLinesCount; i++) { result.append(lines[i]); } qApp->clipboard()->setText(result.join(NEWLINE)); } void MainWindow::on_connectionTreeView_doubleClicked(const QModelIndex &index) { auto widget = GetIndexWidget(index); if (widget == nullptr) return; if (widget->IsConnection()) widget->BeginConnection(); } void MainWindow::on_connectionTreeView_clicked(const QModelIndex &index) { auto widget = GetIndexWidget(index); if (widget == nullptr) return; infoWidget->ShowDetails(widget->Identifier()); }
40,141
C++
.cpp
1,013
33.399803
150
0.683239
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,207
w_ScreenShot_Core.cpp
Qv2ray_Qv2ray/src/ui/widgets/windows/w_ScreenShot_Core.cpp
#include "w_ScreenShot_Core.hpp" #include "base/Qv2rayBase.hpp" #include "utils/QvHelpers.hpp" #include <QMessageBox> #include <QStyleFactory> #include <QThread> #define QV2RAY_SCREENSHOT_DIM_RATIO 0.6f ScreenShotWindow::ScreenShotWindow() : QDialog(), rubber(QRubberBand::Rectangle, this) { setupUi(this); // Fusion prevents the KDE Plasma Breeze's "Move window when dragging in the empty area" issue this->setStyle(QStyleFactory::create("Fusion")); // label->setAttribute(Qt::WA_TranslucentBackground); startBtn->setAttribute(Qt::WA_TranslucentBackground); // QPalette pal; pal.setColor(QPalette::WindowText, Qt::white); label->setPalette(pal); startBtn->setPalette(pal); // label->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); startBtn->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); // label->hide(); startBtn->hide(); } QImage ScreenShotWindow::DoScreenShot() { // The msleep is the only solution which prevent capturing our windows again. It works on KDE, // https://www.qtcentre.org/threads/55708-Get-Desktop-Screenshot-Without-Application-Window-Being-Shown?p=248993#post248993 QThread::msleep(100); QApplication::processEvents(); // desktopImage = qApp->screenAt(QCursor::pos())->grabWindow(0); scale = qApp->screenAt(QCursor::pos())->devicePixelRatio(); // int w = desktopImage.width(); int h = desktopImage.height(); // int r, g, b; const auto _xdesktopImg = desktopImage.toImage(); QImage bg_grey(w, h, QImage::Format_RGB32); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { r = static_cast<int>(qRed(_xdesktopImg.pixel(i, j)) * QV2RAY_SCREENSHOT_DIM_RATIO); g = static_cast<int>(qGreen(_xdesktopImg.pixel(i, j)) * QV2RAY_SCREENSHOT_DIM_RATIO); b = static_cast<int>(qBlue(_xdesktopImg.pixel(i, j)) * QV2RAY_SCREENSHOT_DIM_RATIO); bg_grey.setPixel(i, j, qRgb(r, g, b)); } } setStyleSheet("QDialog { background-color: transparent; }"); bg_grey = bg_grey.scaled(bg_grey.size() / scale, Qt::KeepAspectRatio, Qt::TransformationMode::SmoothTransformation); auto p = this->palette(); p.setBrush(QPalette::Window, bg_grey); setPalette(p); setWindowState(Qt::WindowState::WindowFullScreen); setMouseTracking(true); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); this->showFullScreen(); this->exec(); return resultImage; } void ScreenShotWindow::pSize() { imgW = abs(end.x() - origin.x()); imgH = abs(end.y() - origin.y()); imgX = origin.x() < end.x() ? origin.x() : end.x(); imgY = origin.y() < end.y() ? origin.y() : end.y(); rubber.setGeometry(imgX, imgY, imgW, imgH); fg->setGeometry(rubber.geometry()); fg->setPixmap(desktopImage.copy(imgX * scale, imgY * scale, imgW * scale, imgH * scale)); } void ScreenShotWindow::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) { reject(); } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { on_startBtn_clicked(); } } void ScreenShotWindow::mousePressEvent(QMouseEvent *e) { origin = e->pos(); rubber.setGeometry(origin.x(), origin.y(), 0, 0); rubber.show(); rubber.raise(); // label->hide(); // startBtn->hide(); } void ScreenShotWindow::mouseMoveEvent(QMouseEvent *e) { if (e->buttons() & Qt::LeftButton) { end = e->pos(); pSize(); // label->setText(QString("%1x%2").arg(imgW).arg(imgH)); label->adjustSize(); // QRect labelRect(label->contentsRect()); QRect btnRect(startBtn->contentsRect()); if (imgY > labelRect.height()) { label->move(imgX, imgY - labelRect.height()); } else { label->move(imgX, imgY); } if (height() - imgY - imgH > btnRect.height()) { startBtn->move(imgX + imgW - btnRect.width(), imgY + imgH); } else { startBtn->move(imgX + imgW - btnRect.width(), imgY + imgH - btnRect.height()); } label->show(); startBtn->show(); } } void ScreenShotWindow::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::RightButton) { reject(); } else if (e->button() == Qt::LeftButton) { rubber.hide(); } } ScreenShotWindow::~ScreenShotWindow() { } void ScreenShotWindow::on_startBtn_clicked() { resultImage = desktopImage.copy(imgX, imgY, imgW, imgH).toImage(); rubber.hide(); accept(); }
4,701
C++
.cpp
147
26.571429
127
0.630013
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,208
QRCodeHelper.cpp
Qv2ray_Qv2ray/src/ui/common/QRCodeHelper.cpp
#include "QRCodeHelper.hpp" #include "QtQrCode" #include "QtQrCodePainter" #include <QImage> namespace Qv2ray::ui { QString DecodeQRCode(const QImage &) { return ""; } QImage EncodeQRCode(const QString content, int size) { QtQrCode c; c.setData(content.toUtf8()); return QtQrCodePainter(2.0).toImage(c, size); } } // namespace Qv2ray::ui
398
C++
.cpp
17
18.882353
56
0.665782
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,209
LogHighlighter.cpp
Qv2ray_Qv2ray/src/ui/common/LogHighlighter.cpp
#include "LogHighlighter.hpp" #include "utils/QvHelpers.hpp" #define TO_EOL "(([\\s\\S]*)|([\\d\\D]*)|([\\w\\W]*))$" namespace Qv2ray::ui { SyntaxHighlighter::SyntaxHighlighter(bool darkMode, QTextDocument *parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; if (darkMode) { tcpudpFormat.setForeground(QColor(0, 200, 230)); ipHostFormat.setForeground(Qt::yellow); warningFormat.setForeground(QColor(255, 160, 15)); } else { ipHostFormat.setForeground(Qt::black); ipHostFormat.setFontWeight(QFont::Bold); warningFormat.setForeground(Qt::white); tcpudpFormat.setForeground(QColor(0, 52, 130)); warningFormat.setBackground(QColor(255, 160, 15)); } for (const auto &pattern : { "tcp", "udp" }) { tcpudpFormat.setFontWeight(QFont::Bold); rule.pattern = QRegularExpression(pattern); rule.format = tcpudpFormat; highlightingRules.append(rule); } dateFormat.setForeground(darkMode ? Qt::cyan : Qt::darkCyan); rule.pattern = QRegularExpression("\\d\\d\\d\\d/\\d\\d/\\d\\d"); rule.format = dateFormat; highlightingRules.append(rule); // timeFormat.setForeground(darkMode ? Qt::cyan : Qt::darkCyan); rule.pattern = QRegularExpression("\\d\\d:\\d\\d:\\d\\d"); rule.format = timeFormat; highlightingRules.append(rule); // debugFormat.setForeground(Qt::darkGray); rule.pattern = QRegularExpression("\\[[Dd]ebug\\]" TO_EOL); rule.format = debugFormat; highlightingRules.append(rule); // infoFormat.setForeground(darkMode ? Qt::lightGray : Qt::darkCyan); rule.pattern = QRegularExpression("\\[[Ii]nfo\\]" TO_EOL); rule.format = infoFormat; highlightingRules.append(rule); // // { // IP IPv6 Host; rule.pattern = QRegularExpression(REGEX_IPV4_ADDR ":" REGEX_PORT_NUMBER); rule.pattern.setPatternOptions(QRegularExpression::ExtendedPatternSyntaxOption); rule.format = ipHostFormat; highlightingRules.append(rule); // rule.pattern = QRegularExpression(REGEX_IPV6_ADDR ":" REGEX_PORT_NUMBER); rule.pattern.setPatternOptions(QRegularExpression::ExtendedPatternSyntaxOption); rule.format = ipHostFormat; highlightingRules.append(rule); // rule.pattern = QRegularExpression("([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/|):" REGEX_PORT_NUMBER); rule.pattern.setPatternOptions(QRegularExpression::PatternOption::ExtendedPatternSyntaxOption); rule.format = ipHostFormat; highlightingRules.append(rule); } const static QColor darkGreenColor(10, 180, 0); // // acceptedFormat.setForeground(darkGreenColor); acceptedFormat.setFontItalic(true); acceptedFormat.setFontWeight(QFont::Bold); rule.pattern = QRegularExpression("\\saccepted\\s"); rule.format = acceptedFormat; highlightingRules.append(rule); // rejectedFormat.setFontWeight(QFont::Bold); rejectedFormat.setBackground(Qt::red); rejectedFormat.setForeground(Qt::white); rejectedFormat.setFontItalic(true); rejectedFormat.setFontWeight(QFont::Bold); rule.pattern = QRegularExpression("\\srejected\\s" TO_EOL); rule.format = rejectedFormat; highlightingRules.append(rule); // v2rayComponentFormat.setForeground(darkMode ? darkGreenColor : Qt::darkYellow); rule.pattern = QRegularExpression(R"( (\w+\/)+\w+: )"); rule.format = v2rayComponentFormat; highlightingRules.append(rule); // warningFormat.setFontWeight(QFont::Bold); rule.pattern = QRegularExpression("\\[[Ww]arning\\]" TO_EOL); rule.format = warningFormat; highlightingRules.append(rule); // failedFormat.setFontWeight(QFont::Bold); failedFormat.setBackground(Qt::red); failedFormat.setForeground(Qt::white); rule.pattern = QRegularExpression("failed"); rule.format = failedFormat; highlightingRules.append(rule); // qvAppLogFormat.setForeground(darkMode ? Qt::cyan : Qt::darkCyan); rule.pattern = QRegularExpression("\\[[A-Z]*\\]:"); rule.format = qvAppLogFormat; highlightingRules.append(rule); // qvAppDebugLogFormat.setForeground(darkMode ? Qt::yellow : Qt::darkYellow); rule.pattern = QRegularExpression(R"( \[\w+\] )"); rule.format = qvAppDebugLogFormat; highlightingRules.append(rule); } void SyntaxHighlighter::highlightBlock(const QString &text) { for (const HighlightingRule &rule : qAsConst(highlightingRules)) { QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); while (matchIterator.hasNext()) { QRegularExpressionMatch match = matchIterator.next(); setFormat(match.capturedStart(), match.capturedLength(), rule.format); } } setCurrentBlockState(0); } } // namespace Qv2ray::ui
5,432
C++
.cpp
127
33.15748
137
0.625118
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,210
speedwidget.cpp
Qv2ray_Qv2ray/src/ui/common/speedchart/speedwidget.cpp
/* * Bittorrent Client using Qt and libtorrent. * Copyright (C) 2015 Anton Lashkov <lenton_91@mail.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. You must obey the GNU General Public * License in all respects for all of the code used other than "OpenSSL". If * you modify file(s), you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. */ #include "speedwidget.hpp" #include "base/Qv2rayBase.hpp" #include <QPainter> #define VIEWABLE 120 // table of supposed nice steps for grid marks to get nice looking quarters of scale const static double roundingTable[] = { 1.2, 1.6, 2, 2.4, 2.8, 3.2, 4, 6, 8 }; SpeedWidget::SpeedWidget(QWidget *parent) : QGraphicsView(parent) { UpdateSpeedPlotSettings(); } void SpeedWidget::AddPointData(QMap<SpeedWidget::GraphType, long> data) { SpeedWidget::PointData point; point.x = QDateTime::currentMSecsSinceEpoch() / 1000; for (const auto &[id, data] : data.toStdMap()) { if (m_properties.contains(id)) point.y[id] = data; } dataCollection.push_back(point); while (dataCollection.length() > VIEWABLE) { dataCollection.removeFirst(); } replot(); } // use binary prefix standards from IEC 60027-2 // see http://en.wikipedia.org/wiki/Kilobyte enum SizeUnit : int { Byte, // 1000^0, KByte, // 1000^1, MByte, // 1000^2, GByte, // 1000^3, TByte, // 1000^4, PByte, // 1000^5, EByte // 1000^6 }; QString unitString(const SizeUnit unit, const bool isSpeed) { const static QStringList units{ "B", "KB", "MB", "GB", "TB", "PB", "EB" }; auto unitString = units[unit]; if (isSpeed) unitString += "/s"; return unitString; } int friendlyUnitPrecision(const SizeUnit unit) { // friendlyUnit's number of digits after the decimal point switch (unit) { case SizeUnit::Byte: return 0; case SizeUnit::KByte: case SizeUnit::MByte: return 1; case SizeUnit::GByte: return 2; default: return 3; } } struct SplittedValue { double arg; SizeUnit unit; qint64 sizeInBytes() const { auto size = arg; for (int i = 0; i < static_cast<int>(unit); ++i) { size *= 1024; } return size; } }; SplittedValue getRoundedYScale(double value) { if (value == 0.0) return { 0, SizeUnit::Byte }; if (value <= 12.0) return { 12, SizeUnit::Byte }; auto calculatedUnit = SizeUnit::Byte; while (value > 1000) { value /= 1000; calculatedUnit = static_cast<SizeUnit>(static_cast<int>(calculatedUnit) + 1); } if (value > 100.0) { int roundedValue = static_cast<int>(value / 40) * 40; while (roundedValue < value) roundedValue += 40; return { static_cast<double>(roundedValue), calculatedUnit }; } if (value > 10.0) { int roundedValue = static_cast<int>(value / 4) * 4; while (roundedValue < value) roundedValue += 4; return { static_cast<double>(roundedValue), calculatedUnit }; } for (const auto &roundedValue : roundingTable) { if (value <= roundedValue) return { roundedValue, calculatedUnit }; } return { 10.0, calculatedUnit }; } QString formatLabel(const double argValue, const SizeUnit unit) { // check is there need for digits after decimal separator const int precision = (argValue < 10) ? friendlyUnitPrecision(unit) : 0; return QLocale::system().toString(argValue, 'f', precision) + " " + unitString(unit, true); } void SpeedWidget::UpdateSpeedPlotSettings() { auto &Graph = GlobalConfig.uiConfig.graphConfig; const auto apply_penconfig = [&](StatisticsType x, QvPair<QvGraphPenConfig> y) { if (!Graph.colorConfig.contains(x)) Graph.colorConfig[x] = y; }; apply_penconfig(API_INBOUND, Qv2rayConfig_Graph::DefaultPen); apply_penconfig(API_OUTBOUND_PROXY, Graph.colorConfig[API_INBOUND]); apply_penconfig(API_OUTBOUND_DIRECT, Qv2rayConfig_Graph::DirectPen); const auto getPen = [](const QvGraphPenConfig &conf) { QPen p{ { conf.R, conf.G, conf.B } }; p.setStyle(conf.style); p.setWidthF(conf.width); return p; }; m_properties.clear(); if (Graph.useOutboundStats) { m_properties[OUTBOUND_PROXY_UP] = { tr("Proxy") + " ↑", getPen(Graph.colorConfig[API_OUTBOUND_PROXY].value1) }; m_properties[OUTBOUND_PROXY_DOWN] = { tr("Proxy") + " ↓", getPen(Graph.colorConfig[API_OUTBOUND_PROXY].value2) }; if (Graph.hasDirectStats) { m_properties[OUTBOUND_DIRECT_UP] = { tr("Direct") + " ↑", getPen(Graph.colorConfig[API_OUTBOUND_DIRECT].value1) }; m_properties[OUTBOUND_DIRECT_DOWN] = { tr("Direct") + " ↓", getPen(Graph.colorConfig[API_OUTBOUND_DIRECT].value2) }; } } else { m_properties[INBOUND_UP] = { tr("Total") + " ↑", getPen(Graph.colorConfig[API_INBOUND].value1) }; m_properties[INBOUND_DOWN] = { tr("Total") + " ↓", getPen(Graph.colorConfig[API_INBOUND].value2) }; } } void SpeedWidget::Clear() { dataCollection.clear(); m_properties.clear(); UpdateSpeedPlotSettings(); replot(); } void SpeedWidget::replot() { viewport()->update(); } quint64 SpeedWidget::maxYValue() { quint64 maxYValue = 0; for (int id = 0; id < NB_GRAPHS; ++id) for (int i = dataCollection.size() - 1, j = 0; (i >= 0) && (j <= VIEWABLE); --i, ++j) if (dataCollection[i].y[id] > maxYValue) maxYValue = dataCollection[i].y[id]; return maxYValue; } void SpeedWidget::paintEvent(QPaintEvent *) { const auto fullRect = viewport()->rect(); auto rect = viewport()->rect(); rect.adjust(4, 4, 0, -4); // Add padding const auto niceScale = getRoundedYScale(maxYValue()); // draw Y axis speed labels const QVector<QString> speedLabels = { formatLabel(niceScale.arg, niceScale.unit), formatLabel((0.75 * niceScale.arg), niceScale.unit), formatLabel((0.50 * niceScale.arg), niceScale.unit), formatLabel((0.25 * niceScale.arg), niceScale.unit), formatLabel(0.0, niceScale.unit), }; QPainter painter(viewport()); painter.setRenderHints(QPainter::Antialiasing); // const auto fontMetrics = painter.fontMetrics(); rect.adjust(0, fontMetrics.height(), 0, 0); // Add top padding for top speed text // int yAxisWidth = 0; for (const auto &label : speedLabels) if (fontMetrics.horizontalAdvance(label) > yAxisWidth) yAxisWidth = fontMetrics.horizontalAdvance(label); int i = 0; for (const auto &label : speedLabels) { QRectF labelRect(rect.topLeft() + QPointF(-yAxisWidth, (i++) * 0.25 * rect.height() - fontMetrics.height()), QSizeF(2 * yAxisWidth, fontMetrics.height())); painter.drawText(labelRect, label, Qt::AlignRight | Qt::AlignTop); } // draw grid lines rect.adjust(yAxisWidth + 4, 0, 0, 0); QPen gridPen; gridPen.setStyle(Qt::DashLine); gridPen.setWidthF(1); gridPen.setColor(QColor(128, 128, 128, 128)); // Set antialiasing for graphs painter.setPen(gridPen); painter.drawLine(fullRect.left(), rect.top(), rect.right(), rect.top()); painter.drawLine(fullRect.left(), rect.top() + 0.25 * rect.height(), rect.right(), rect.top() + 0.25 * rect.height()); painter.drawLine(fullRect.left(), rect.top() + 0.50 * rect.height(), rect.right(), rect.top() + 0.50 * rect.height()); painter.drawLine(fullRect.left(), rect.top() + 0.75 * rect.height(), rect.right(), rect.top() + 0.75 * rect.height()); painter.drawLine(fullRect.left(), rect.bottom(), rect.right(), rect.bottom()); constexpr auto TIME_AXIS_DIVISIONS = 6; for (int i = 0; i < TIME_AXIS_DIVISIONS; ++i) { const int x = rect.left() + (i * rect.width()) / TIME_AXIS_DIVISIONS; painter.drawLine(x, fullRect.top(), x, fullRect.bottom()); } // draw graphs // Need, else graphs cross left gridline rect.adjust(3, 0, 0, 0); // const double yMultiplier = (niceScale.arg == 0.0) ? 0.0 : (static_cast<double>(rect.height()) / niceScale.sizeInBytes()); const double xTickSize = static_cast<double>(rect.width()) / VIEWABLE; for (const auto &id : m_properties.keys()) { QVector<QPoint> points; for (int i = static_cast<int>(dataCollection.size()) - 1, j = 0; (i >= 0) && (j <= VIEWABLE); --i, ++j) { const int newX = rect.right() - j * xTickSize; const int newY = rect.bottom() - dataCollection[i].y[id] * yMultiplier; points.push_back({ newX, newY }); } painter.setPen(m_properties[id].pen); painter.drawPolyline(points.data(), points.size()); } // draw legend double legendHeight = 0; int legendWidth = 0; for (const auto &property : m_properties) { if (fontMetrics.horizontalAdvance(property.name) > legendWidth) legendWidth = fontMetrics.horizontalAdvance(property.name); legendHeight += 1.5 * fontMetrics.height(); } { QPoint legendTopLeft(rect.left() + 4, fullRect.top() + 4); QRectF legendBackgroundRect(QPoint(legendTopLeft.x() - 4, legendTopLeft.y() - 4), QSizeF(legendWidth + 8, legendHeight + 8)); auto legendBackgroundColor = QWidget::palette().color(QWidget::backgroundRole()); legendBackgroundColor.setAlpha(128); // 50% transparent painter.fillRect(legendBackgroundRect, legendBackgroundColor); int i = 0; for (const auto &property : m_properties) { int nameSize = fontMetrics.horizontalAdvance(property.name); double indent = 1.5 * (i++) * fontMetrics.height(); painter.setPen(property.pen); painter.drawLine(legendTopLeft + QPointF(0, indent + fontMetrics.height()), legendTopLeft + QPointF(nameSize, indent + fontMetrics.height())); painter.drawText(QRectF(legendTopLeft + QPointF(0, indent), QSizeF(2 * nameSize, fontMetrics.height())), property.name, QTextOption(Qt::AlignVCenter)); } } }
11,392
C++
.cpp
288
33.604167
133
0.647357
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false