Compare commits

..

1 Commits

Author SHA1 Message Date
Mitternacht822 582f21b0b1 fix(linux): force Qt6 modules to link from bundled lib via rpath 2026-02-09 21:31:16 +04:00
37 changed files with 713 additions and 1094 deletions
+33
View File
@@ -37,6 +37,10 @@ if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
set(PACKAGES ${PACKAGES} Widgets)
endif()
if(LINUX AND NOT ANDROID)
list(APPEND PACKAGES QuickTemplates2 QmlModels OpenGL)
endif()
find_package(Qt6 REQUIRED COMPONENTS ${PACKAGES})
set(LIBS ${LIBS}
@@ -52,6 +56,23 @@ endif()
qt_standard_project_setup()
qt_add_executable(${PROJECT} MANUAL_FINALIZATION)
if(LINUX AND NOT ANDROID)
target_link_options(${PROJECT} PRIVATE "-Wl,--no-as-needed")
target_link_options(${PROJECT} PRIVATE "LINKER:--disable-new-dtags")
set_target_properties(${PROJECT} PROPERTIES
BUILD_RPATH "\$ORIGIN/../lib"
INSTALL_RPATH "\$ORIGIN/../lib"
INSTALL_RPATH_USE_LINK_PATH FALSE
)
set_property(TARGET ${PROJECT} PROPERTY BUILD_WITH_INSTALL_RPATH TRUE)
target_link_libraries(${PROJECT} PRIVATE
Qt6::QuickTemplates2
Qt6::QmlModels
Qt6::OpenGL
)
endif()
target_include_directories(${PROJECT} PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
)
@@ -59,6 +80,7 @@ target_include_directories(${PROJECT} PUBLIC
if(WIN32 OR (APPLE AND NOT IOS AND NOT MACOS_NE) OR (LINUX AND NOT ANDROID))
qt_add_repc_replicas(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}/../ipc/ipc_interface.rep)
qt_add_repc_replicas(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}/../ipc/ipc_process_interface.rep)
qt_add_repc_replicas(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}/../ipc/ipc_process_tun2socks.rep)
endif()
qt6_add_resources(QRC ${QRC} ${CMAKE_CURRENT_LIST_DIR}/resources.qrc)
@@ -194,6 +216,17 @@ elseif(APPLE)
endif()
target_link_libraries(${PROJECT} PRIVATE ${LIBS})
if(LINUX AND NOT ANDROID)
target_link_libraries(${PROJECT} PRIVATE
"-Wl,--push-state,--no-as-needed"
Qt6::QuickTemplates2
Qt6::QmlModels
Qt6::OpenGL
"-Wl,--pop-state"
)
endif()
target_compile_definitions(${PROJECT} PRIVATE "MZ_$<UPPER_CASE:${MZ_PLATFORM_NAME}>")
# deploy artifacts required to run the application to the debug build folder
@@ -90,10 +90,6 @@ class AmneziaActivity : QtActivity() {
private val actionResultHandlers = mutableMapOf<Int, ActivityResultHandler>()
private val permissionRequestHandlers = mutableMapOf<Int, PermissionRequestHandler>()
private var isActivityResumed = false
private var hasWindowFocus = false
private val resumeHandler = Handler(Looper.getMainLooper())
private val vpnServiceEventHandler: Handler by lazy(NONE) {
object : Handler(Looper.getMainLooper()) {
@@ -266,10 +262,6 @@ class AmneziaActivity : QtActivity() {
}
override fun onStop() {
isActivityResumed = false
hasWindowFocus = false
// Cancel all pending operations when activity stops
resumeHandler.removeCallbacksAndMessages(null)
Log.d(TAG, "Stop Amnezia activity")
doUnbindService()
mainScope.launch {
@@ -281,13 +273,7 @@ class AmneziaActivity : QtActivity() {
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
hasWindowFocus = hasFocus
Log.d(TAG, "Window focus changed: hasFocus=$hasFocus")
// Cancel pending operations if window loses focus
if (!hasFocus) {
resumeHandler.removeCallbacksAndMessages(null)
}
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
@@ -330,42 +316,30 @@ class AmneziaActivity : QtActivity() {
override fun onPause() {
super.onPause()
isActivityResumed = false
// Cancel all pending operations when activity pauses
resumeHandler.removeCallbacksAndMessages(null)
Log.d(TAG, "Pause Amnezia activity")
}
override fun onResume() {
super.onResume()
isActivityResumed = true
Log.d(TAG, "Resume Amnezia activity")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
window.decorView.apply {
invalidate()
resumeHandler.postDelayed({
// Check if activity is still resumed and has focus before executing
if (isActivityResumed && hasWindowFocus && !isFinishing && !isDestroyed) {
sendTouch(1f, 1f)
}
postDelayed({
sendTouch(1f, 1f)
}, 100)
resumeHandler.postDelayed({
if (isActivityResumed && hasWindowFocus && !isFinishing && !isDestroyed) {
sendTouch(2f, 2f)
}
postDelayed({
sendTouch(2f, 2f)
}, 200)
resumeHandler.postDelayed({
if (isActivityResumed && hasWindowFocus && !isFinishing && !isDestroyed) {
requestLayout()
invalidate()
}
postDelayed({
requestLayout()
invalidate()
}, 250)
}
}
} */
Log.d(TAG, "Resume Amnezia activity")
}
private fun configureWindowForEdgeToEdge() {
@@ -428,10 +402,6 @@ class AmneziaActivity : QtActivity() {
}
override fun onDestroy() {
isActivityResumed = false
hasWindowFocus = false
// Cancel all pending operations when activity is destroyed
resumeHandler.removeCallbacksAndMessages(null)
Log.d(TAG, "Destroy Amnezia activity")
unregisterBroadcastReceiver(notificationStateReceiver)
notificationStateReceiver = null
+2
View File
@@ -181,6 +181,7 @@ if(WIN32 OR (APPLE AND NOT IOS AND NOT MACOS_NE) OR (LINUX AND NOT ANDROID))
set(HEADERS ${HEADERS}
${CLIENT_ROOT_DIR}/core/ipcclient.h
${CLIENT_ROOT_DIR}/core/privileged_process.h
${CLIENT_ROOT_DIR}/ui/systemtray_notificationhandler.h
${CLIENT_ROOT_DIR}/protocols/openvpnprotocol.h
${CLIENT_ROOT_DIR}/protocols/openvpnovercloakprotocol.h
@@ -193,6 +194,7 @@ if(WIN32 OR (APPLE AND NOT IOS AND NOT MACOS_NE) OR (LINUX AND NOT ANDROID))
set(SOURCES ${SOURCES}
${CLIENT_ROOT_DIR}/core/ipcclient.cpp
${CLIENT_ROOT_DIR}/core/privileged_process.cpp
${CLIENT_ROOT_DIR}/mozilla/localsocketcontroller.cpp
${CLIENT_ROOT_DIR}/ui/systemtray_notificationhandler.cpp
${CLIENT_ROOT_DIR}/protocols/openvpnprotocol.cpp
+63 -37
View File
@@ -7,6 +7,7 @@ IpcClient::IpcClient(QObject *parent) : QObject(parent)
{
m_node.connectToNode(QUrl("local:" + amnezia::getIpcServiceUrl()));
m_interface.reset(m_node.acquire<IpcInterfaceReplica>());
m_tun2socks.reset(m_node.acquire<IpcProcessTun2SocksReplica>());
}
IpcClient& IpcClient::Instance()
@@ -32,43 +33,68 @@ QSharedPointer<IpcInterfaceReplica> IpcClient::Interface()
return rep;
}
QSharedPointer<IpcProcessInterfaceReplica> IpcClient::CreatePrivilegedProcess()
QSharedPointer<IpcProcessTun2SocksReplica> IpcClient::InterfaceTun2Socks()
{
return withInterface([](QSharedPointer<IpcInterfaceReplica> &iface) -> QSharedPointer<IpcProcessInterfaceReplica> {
auto createPrivilegedProcess = iface->createPrivilegedProcess();
if (!createPrivilegedProcess.waitForFinished()) {
qCritical() << "Failed to create privileged process";
return nullptr;
}
const int pid = createPrivilegedProcess.returnValue();
auto* node = new QRemoteObjectNode();
node->connectToNode(QUrl(QString("local:%1").arg(amnezia::getIpcProcessUrl(pid))));
QSharedPointer<IpcProcessInterfaceReplica> rep(
node->acquire<IpcProcessInterfaceReplica>(),
[node] (IpcProcessInterfaceReplica *ptr) {
delete ptr;
node->deleteLater();
}
);
if (rep.isNull()) {
qCritical() << "IpcClient::CreatePrivilegedProcess(): Failed to acquire replica";
return nullptr;
}
if (!rep->waitForSource()) {
qCritical() << "IpcClient::CreatePrivilegedProcess(): Failed to initialize replica";
return nullptr;
}
if (!rep->isReplicaValid()) {
qCritical() << "IpcClient::CreatePrivilegedProcess(): Replica is invalid";
return nullptr;
}
return rep;
},
[]() -> QSharedPointer<IpcProcessInterfaceReplica> {
QSharedPointer<IpcProcessTun2SocksReplica> rep = Instance().m_tun2socks;
if (rep.isNull()) {
qCritical() << "IpcClient::InterfaceTun2Socks: Replica is undefined";
return nullptr;
});
}
if (!rep->waitForSource(1000)) {
qCritical() << "IpcClient::InterfaceTun2Socks: Failed to initialize replica";
return nullptr;
}
if (!rep->isReplicaValid()) {
qWarning() << "IpcClient::InterfaceTun2Socks(): Replica is invalid";
}
return rep;
}
QSharedPointer<PrivilegedProcess> IpcClient::CreatePrivilegedProcess()
{
QSharedPointer<IpcInterfaceReplica> rep = Interface();
if (!rep) {
qCritical() << "IpcClient::createPrivilegedProcess: Replica is invalid";
return nullptr;
}
QRemoteObjectPendingReply<int> pidReply = rep->createPrivilegedProcess();
if (!pidReply.waitForFinished(5000)){
qCritical() << "IpcClient::createPrivilegedProcess: Failed to execute RO createPrivilegedProcess call";
return nullptr;
}
int pid = pidReply.returnValue();
QSharedPointer<ProcessDescriptor> pd(new ProcessDescriptor());
pd->localSocket.reset(new QLocalSocket(pd->replicaNode.data()));
connect(pd->localSocket.data(), &QLocalSocket::connected, pd->replicaNode.data(), [pd]() {
pd->replicaNode->addClientSideConnection(pd->localSocket.data());
IpcProcessInterfaceReplica *repl = pd->replicaNode->acquire<IpcProcessInterfaceReplica>();
// TODO: rework the unsafe cast below
PrivilegedProcess *priv = static_cast<PrivilegedProcess *>(repl);
pd->ipcProcess.reset(priv);
if (!pd->ipcProcess) {
qWarning() << "Acquire PrivilegedProcess failed";
} else {
pd->ipcProcess->waitForSource(1000);
if (!pd->ipcProcess->isReplicaValid()) {
qWarning() << "PrivilegedProcess replica is not connected!";
}
QObject::connect(pd->ipcProcess.data(), &PrivilegedProcess::destroyed, pd->ipcProcess.data(),
[pd]() { pd->replicaNode->deleteLater(); });
}
});
pd->localSocket->connectToServer(amnezia::getIpcProcessUrl(pid));
if (!pd->localSocket->waitForConnected()) {
qCritical() << "IpcClient::createPrivilegedProcess: Failed to connect to process' socket";
return nullptr;
}
auto processReplica = QSharedPointer<PrivilegedProcess>(pd->ipcProcess);
return processReplica;
}
+17 -2
View File
@@ -5,7 +5,9 @@
#include <QObject>
#include "rep_ipc_interface_replica.h"
#include "rep_ipc_process_interface_replica.h"
#include "rep_ipc_process_tun2socks_replica.h"
#include "privileged_process.h"
class IpcClient : public QObject
{
@@ -16,7 +18,8 @@ public:
static IpcClient& Instance();
static QSharedPointer<IpcInterfaceReplica> Interface();
static QSharedPointer<IpcProcessInterfaceReplica> CreatePrivilegedProcess();
static QSharedPointer<IpcProcessTun2SocksReplica> InterfaceTun2Socks();
static QSharedPointer<PrivilegedProcess> CreatePrivilegedProcess();
template <typename Func>
static auto withInterface(Func func)
@@ -51,6 +54,18 @@ signals:
private:
QRemoteObjectNode m_node;
QSharedPointer<IpcInterfaceReplica> m_interface;
QSharedPointer<IpcProcessTun2SocksReplica> m_tun2socks;
struct ProcessDescriptor {
ProcessDescriptor () {
replicaNode = QSharedPointer<QRemoteObjectNode>(new QRemoteObjectNode());
ipcProcess = QSharedPointer<PrivilegedProcess>();
localSocket = QSharedPointer<QLocalSocket>();
}
QSharedPointer<PrivilegedProcess> ipcProcess;
QSharedPointer<QRemoteObjectNode> replicaNode;
QSharedPointer<QLocalSocket> localSocket;
};
};
#endif // IPCCLIENT_H
+27
View File
@@ -0,0 +1,27 @@
#include "privileged_process.h"
PrivilegedProcess::PrivilegedProcess() :
IpcProcessInterfaceReplica()
{
}
PrivilegedProcess::~PrivilegedProcess()
{
qDebug() << "PrivilegedProcess::~PrivilegedProcess()";
}
void PrivilegedProcess::waitForFinished(int msecs)
{
QSharedPointer<QEventLoop> loop(new QEventLoop);
connect(this, &PrivilegedProcess::finished, this, [this, loop](int exitCode, QProcess::ExitStatus exitStatus) mutable{
loop->quit();
loop.clear();
});
QTimer::singleShot(msecs, this, [this, loop]() mutable {
loop->quit();
loop.clear();
});
loop->exec();
}
+24
View File
@@ -0,0 +1,24 @@
#ifndef PRIVILEGED_PROCESS_H
#define PRIVILEGED_PROCESS_H
#include <QObject>
#include "rep_ipc_process_interface_replica.h"
// This class is dangerous - instance of this class casted from base class,
// so it support only functions
// Do not add any members into it
//
class PrivilegedProcess : public IpcProcessInterfaceReplica
{
Q_OBJECT
public:
PrivilegedProcess();
~PrivilegedProcess() override;
void waitForFinished(int msecs);
};
#endif // PRIVILEGED_PROCESS_H
@@ -62,9 +62,6 @@ void WindowsDaemon::prepareActivation(const InterfaceConfig& config, int inetAda
}
void WindowsDaemon::activateSplitTunnel(const InterfaceConfig& config, int vpnAdapterIndex) {
if (m_splitTunnelManager == nullptr)
return;
if (config.m_vpnDisabledApps.length() > 0) {
m_splitTunnelManager->start(m_inetAdapterIndex, vpnAdapterIndex);
m_splitTunnelManager->excludeApps(config.m_vpnDisabledApps);
+9 -3
View File
@@ -232,6 +232,12 @@ ErrorCode OpenVpnProtocol::start()
return ErrorCode::AmneziaServiceConnectionFailed;
}
m_openVpnProcess->waitForSource(5000);
if (!m_openVpnProcess->isInitialized()) {
qWarning() << "IpcProcess replica is not connected!";
setLastError(ErrorCode::AmneziaServiceConnectionFailed);
return ErrorCode::AmneziaServiceConnectionFailed;
}
m_openVpnProcess->setProgram(PermittedProcess::OpenVPN);
QStringList arguments({
"--config", configPath(), "--management", m_managementHost, QString::number(mgmtPort),
@@ -240,13 +246,13 @@ ErrorCode OpenVpnProtocol::start()
m_openVpnProcess->setArguments(arguments);
qDebug() << arguments.join(" ");
connect(m_openVpnProcess.data(), &IpcProcessInterfaceReplica::errorOccurred,
connect(m_openVpnProcess.data(), &PrivilegedProcess::errorOccurred,
[&](QProcess::ProcessError error) { qDebug() << "PrivilegedProcess errorOccurred" << error; });
connect(m_openVpnProcess.data(), &IpcProcessInterfaceReplica::stateChanged,
connect(m_openVpnProcess.data(), &PrivilegedProcess::stateChanged,
[&](QProcess::ProcessState newState) { qDebug() << "PrivilegedProcess stateChanged" << newState; });
connect(m_openVpnProcess.data(), &IpcProcessInterfaceReplica::finished, this,
connect(m_openVpnProcess.data(), &PrivilegedProcess::finished, this,
[&]() { setConnectionState(Vpn::ConnectionState::Disconnected); });
m_openVpnProcess->start();
+1 -1
View File
@@ -53,7 +53,7 @@ private:
void updateRouteGateway(QString line);
void updateVpnGateway(const QString &line);
QSharedPointer<IpcProcessInterfaceReplica> m_openVpnProcess;
QSharedPointer<PrivilegedProcess> m_openVpnProcess;
};
#endif // OPENVPNPROTOCOL_H
+1 -1
View File
@@ -233,7 +233,7 @@ namespace amnezia
constexpr char defaultResponsePacketMagicHeader[] = "3288052141";
constexpr char defaultTransportPacketMagicHeader[] = "2528465083";
constexpr char defaultUnderloadPacketMagicHeader[] = "1766607858";
constexpr char defaultSpecialJunk1[] = "<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>";
constexpr char defaultSpecialJunk1[] = "<b 0x084481800001000300000000077469636b65747306776964676574096b696e6f706f69736b0272750000010001c00c0005000100000039001806776964676574077469636b6574730679616e646578c025c0390005000100000039002b1765787465726e616c2d7469636b6574732d776964676574066166697368610679616e646578036e657400c05d000100010000001c000457fafe25>";
constexpr char defaultSpecialJunk2[] = "";
constexpr char defaultSpecialJunk3[] = "";
constexpr char defaultSpecialJunk4[] = "";
+114 -184
View File
@@ -1,7 +1,6 @@
#include "xrayprotocol.h"
#include "core/ipcclient.h"
#include "ipc.h"
#include "utilities.h"
#include "core/networkUtilities.h"
@@ -10,37 +9,14 @@
#include <QJsonObject>
#include <QNetworkInterface>
#include <QJsonDocument>
#include <QtCore/qlogging.h>
#include <QtCore/qobjectdefs.h>
#include <QtCore/qprocess.h>
#ifdef Q_OS_MACOS
static const QString tunName = "utun22";
#else
static const QString tunName = "tun2";
#endif
XrayProtocol::XrayProtocol(const QJsonObject &configuration, QObject *parent) : VpnProtocol(configuration, parent)
{
readXrayConfiguration(configuration);
m_routeGateway = NetworkUtilities::getGatewayAndIface().first;
m_vpnGateway = amnezia::protocols::xray::defaultLocalAddr;
m_vpnLocalAddress = amnezia::protocols::xray::defaultLocalAddr;
m_routeGateway = NetworkUtilities::getGatewayAndIface().first;
m_routeMode = static_cast<Settings::RouteMode>(configuration.value(amnezia::config_key::splitTunnelType).toInt());
m_remoteAddress = NetworkUtilities::getIPAddress(m_rawConfig.value(amnezia::config_key::hostName).toString());
const QString primaryDns = configuration.value(amnezia::config_key::dns1).toString();
m_dnsServers.push_back(QHostAddress(primaryDns));
if (primaryDns != amnezia::protocols::dns::amneziaDnsIp) {
const QString secondaryDns = configuration.value(amnezia::config_key::dns2).toString();
m_dnsServers.push_back(QHostAddress(secondaryDns));
}
QJsonObject xrayConfiguration = configuration.value(ProtocolProps::key_proto_config_data(Proto::Xray)).toObject();
if (xrayConfiguration.isEmpty()) {
xrayConfiguration = configuration.value(ProtocolProps::key_proto_config_data(Proto::SSXray)).toObject();
}
m_xrayConfig = xrayConfiguration;
m_t2sProcess = IpcClient::InterfaceTun2Socks();
}
XrayProtocol::~XrayProtocol()
@@ -52,193 +28,71 @@ XrayProtocol::~XrayProtocol()
ErrorCode XrayProtocol::start()
{
qDebug() << "XrayProtocol::start()";
setConnectionState(Vpn::ConnectionState::Connecting);
return IpcClient::withInterface([&](QSharedPointer<IpcInterfaceReplica> iface) {
auto xrayStart = iface->xrayStart(QJsonDocument(m_xrayConfig).toJson());
if (!xrayStart.waitForFinished() || !xrayStart.returnValue()) {
qCritical() << "Failed to start xray";
return ErrorCode::XrayExecutableCrashed;
}
return startTun2Socks();
const ErrorCode err = IpcClient::withInterface([&](QSharedPointer<IpcInterfaceReplica> iface) {
iface->xrayStart(QJsonDocument(m_xrayConfig).toJson());
return ErrorCode::NoError;
}, [] () {
return ErrorCode::AmneziaServiceConnectionFailed;
});
}
if (err != ErrorCode::NoError)
return err;
void XrayProtocol::stop()
{
qDebug() << "XrayProtocol::stop()";
setConnectionState(Vpn::ConnectionState::Disconnecting);
IpcClient::withInterface([](QSharedPointer<IpcInterfaceReplica> iface) {
auto disableKillSwitch = iface->disableKillSwitch();
if (!disableKillSwitch.waitForFinished() || !disableKillSwitch.returnValue())
qWarning() << "Failed to disable killswitch";
auto StartRoutingIpv6 = iface->StartRoutingIpv6();
if (!StartRoutingIpv6.waitForFinished() || !StartRoutingIpv6.returnValue())
qWarning() << "Failed to start routing ipv6";
auto restoreResolvers = iface->restoreResolvers();
if (!restoreResolvers.waitForFinished() || !restoreResolvers.returnValue())
qWarning() << "Failed to restore resolvers";
auto deleteTun = iface->deleteTun(tunName);
if (!deleteTun.waitForFinished() || !deleteTun.returnValue())
qWarning() << "Failed to delete tun";
auto xrayStop = iface->xrayStop();
if (!xrayStop.waitForFinished() || !xrayStop.returnValue())
qWarning() << "Failed to stop xray";
});
if (m_tun2socksProcess) {
m_tun2socksProcess->blockSignals(true);
#ifndef Q_OS_WIN
m_tun2socksProcess->terminate();
auto waitForFinished = m_tun2socksProcess->waitForFinished(1000);
if (!waitForFinished.waitForFinished() || !waitForFinished.returnValue()) {
qWarning() << "Failed to terminate tun2socks. Killing the process...";
m_tun2socksProcess->kill();
}
#else
// terminate does not do anything useful on Windows
// so just kill the process
m_tun2socksProcess->kill();
#endif
m_tun2socksProcess->close();
m_tun2socksProcess.reset();
}
setConnectionState(Vpn::ConnectionState::Disconnected);
}
ErrorCode XrayProtocol::startTun2Socks()
{
m_tun2socksProcess = IpcClient::CreatePrivilegedProcess();
if (!m_tun2socksProcess->waitForSource()) {
return ErrorCode::AmneziaServiceConnectionFailed;
}
m_tun2socksProcess->setProgram(PermittedProcess::Tun2Socks);
m_tun2socksProcess->setArguments({"-device", QString("tun://%1").arg(tunName), "-proxy", "socks5://127.0.0.1:10808" });
connect(m_tun2socksProcess.data(), &IpcProcessInterfaceReplica::readyReadStandardOutput, this, [this]() {
auto readAllStandardOutput = m_tun2socksProcess->readAllStandardOutput();
if (!readAllStandardOutput.waitForFinished()) {
qWarning() << "Failed to read output from tun2socks";
return;
}
const QString line = readAllStandardOutput.returnValue();
if (!line.contains("[TCP]") && !line.contains("[UDP]"))
qDebug() << "[tun2socks]:" << line;
if (line.contains("[STACK] tun://") && line.contains("<-> socks5://127.0.0.1")) {
disconnect(m_tun2socksProcess.data(), &IpcProcessInterfaceReplica::readyReadStandardOutput, this, nullptr);
if (ErrorCode res = setupRouting(); res != ErrorCode::NoError) {
stop();
setLastError(res);
} else {
setConnectionState(Vpn::ConnectionState::Connected);
}
}
}, Qt::QueuedConnection);
connect(m_tun2socksProcess.data(), &IpcProcessInterfaceReplica::finished, this, [this](int exitCode, QProcess::ExitStatus exitStatus) {
if (exitStatus == QProcess::ExitStatus::CrashExit) {
qCritical() << "Tun2socks process crashed!";
} else {
qCritical() << QString("Tun2socks process was closed with %1 exit code").arg(exitCode);
}
stop();
setLastError(ErrorCode::Tun2SockExecutableCrashed);
}, Qt::QueuedConnection);
m_tun2socksProcess->start();
return ErrorCode::NoError;
setConnectionState(Vpn::ConnectionState::Connecting);
return startTun2Sock();
}
ErrorCode XrayProtocol::setupRouting() {
return IpcClient::withInterface([this](QSharedPointer<IpcInterfaceReplica> iface) -> ErrorCode {
#ifdef Q_OS_WIN
const int inetAdapterIndex = NetworkUtilities::AdapterIndexTo(QHostAddress(m_remoteAddress));
#endif
QList<QHostAddress> dnsAddr;
dnsAddr.push_back(QHostAddress(m_primaryDNS));
// We don't use secondary DNS if primary DNS is AmneziaDNS
if (!m_primaryDNS.contains(amnezia::protocols::dns::amneziaDnsIp)) {
dnsAddr.push_back(QHostAddress(m_secondaryDNS));
}
#ifdef AMNEZIA_DESKTOP
#ifdef Q_OS_MACOS
const QString tunName = "utun22";
#else
const QString tunName = "tun2";
#endif
auto createTun = iface->createTun(tunName, amnezia::protocols::xray::defaultLocalAddr);
if (!createTun.waitForFinished() || !createTun.returnValue()) {
qCritical() << "Failed to assign IP address for TUN";
if (!createTun.waitForFinished(1000) || !createTun.returnValue()) {
qWarning() << "Failed to assign IP address for TUN";
return ErrorCode::InternalError;
}
auto updateResolvers = iface->updateResolvers(tunName, m_dnsServers);
if (!updateResolvers.waitForFinished() || !updateResolvers.returnValue()) {
qCritical() << "Failed to set DNS resolvers for TUN";
auto updateResolvers = iface->updateResolvers(tunName, dnsAddr);
if (!updateResolvers.waitForFinished(1000) || !updateResolvers.returnValue()) {
qWarning() << "Failed to set DNS resolvers for TUN";
return ErrorCode::InternalError;
}
#ifdef Q_OS_WIN
int vpnAdapterIndex = -1;
QList<QNetworkInterface> netInterfaces = QNetworkInterface::allInterfaces();
for (auto& netInterface : netInterfaces) {
for (auto& address : netInterface.addressEntries()) {
if (m_vpnLocalAddress == address.ip().toString())
vpnAdapterIndex = netInterface.index();
}
}
#else
static const int vpnAdapterIndex = 0;
#endif
const bool killSwitchEnabled = QVariant(m_rawConfig.value(config_key::killSwitchOption).toString()).toBool();
if (killSwitchEnabled) {
if (vpnAdapterIndex != -1) {
QJsonObject config = m_rawConfig;
config.insert("vpnServer", m_remoteAddress);
auto enableKillSwitch = IpcClient::Interface()->enableKillSwitch(config, vpnAdapterIndex);
if (!enableKillSwitch.waitForFinished() || !enableKillSwitch.returnValue()) {
qCritical() << "Failed to enable killswitch";
return ErrorCode::InternalError;
}
} else
qWarning() << "Failed to get vpnAdapterIndex. Killswitch disabled";
}
if (m_routeMode == Settings::RouteMode::VpnAllSites) {
static const QStringList subnets = { "1.0.0.0/8", "2.0.0.0/7", "4.0.0.0/6", "8.0.0.0/5", "16.0.0.0/4", "32.0.0.0/3", "64.0.0.0/2", "128.0.0.0/1" };
auto routeAddList = iface->routeAddList(m_vpnGateway, subnets);
if (!routeAddList.waitForFinished() || routeAddList.returnValue() != subnets.count()) {
qCritical() << "Failed to set routes for TUN";
if (!routeAddList.waitForFinished(1000) || routeAddList.returnValue() != subnets.count()) {
qWarning() << "Failed to set routes for TUN";
return ErrorCode::InternalError;
}
}
auto StopRoutingIpv6 = iface->StopRoutingIpv6();
if (!StopRoutingIpv6.waitForFinished() || !StopRoutingIpv6.returnValue()) {
qCritical() << "Failed to disable IPv6 routing";
if (!StopRoutingIpv6.waitForFinished(1000) || !StopRoutingIpv6.returnValue()) {
qWarning() << "Failed to disable IPv6 routing";
return ErrorCode::InternalError;
}
#ifdef Q_OS_WIN
if (inetAdapterIndex != -1 && vpnAdapterIndex != -1) {
QJsonObject config = m_rawConfig;
config.insert("inetAdapterIndex", inetAdapterIndex);
config.insert("vpnAdapterIndex", vpnAdapterIndex);
config.insert("vpnGateway", m_vpnGateway);
config.insert("vpnServer", m_remoteAddress);
auto enablePeerTraffic = iface->enablePeerTraffic(config);
if (!enablePeerTraffic.waitForFinished() || !enablePeerTraffic.returnValue()) {
qCritical() << "Failed to enable peer traffic";
return ErrorCode::InternalError;
}
} else
qWarning() << "Failed to get adapter indexes. Split-tunneling disabled";
auto enablePeerTraffic = iface->enablePeerTraffic(m_xrayConfig);
if (!enablePeerTraffic.waitForFinished(5000) || !enablePeerTraffic.returnValue()) {
qWarning() << "Failed to enable peer traffic";
return ErrorCode::InternalError;
}
#endif
return ErrorCode::NoError;
},
@@ -246,3 +100,79 @@ ErrorCode XrayProtocol::setupRouting() {
return ErrorCode::AmneziaServiceConnectionFailed;
});
}
ErrorCode XrayProtocol::startTun2Sock()
{
m_t2sProcess->start();
connect(m_t2sProcess.data(), &IpcProcessTun2SocksReplica::stateChanged, this,
[&](QProcess::ProcessState newState) { qDebug() << "PrivilegedProcess stateChanged" << newState; });
connect(m_t2sProcess.data(), &IpcProcessTun2SocksReplica::setConnectionState, this, [&](int vpnState) {
QMetaObject::invokeMethod(this, [this, vpnState]() {
qDebug() << "PrivilegedProcess setConnectionState " << vpnState;
if (vpnState == Vpn::ConnectionState::Connected) {
setConnectionState(Vpn::ConnectionState::Connecting);
if (ErrorCode res = setupRouting(); res != ErrorCode::NoError) {
stop();
setLastError(res);
} else
setConnectionState(Vpn::ConnectionState::Connected);
}
if (vpnState == Vpn::ConnectionState::Disconnected)
stop();
}, Qt::QueuedConnection);
});
return ErrorCode::NoError;
}
void XrayProtocol::stop()
{
qDebug() << "XrayProtocol::stop()";
IpcClient::withInterface([](QSharedPointer<IpcInterfaceReplica> iface) {
#ifdef AMNEZIA_DESKTOP
auto StartRoutingIpv6 = iface->StartRoutingIpv6();
if (!StartRoutingIpv6.waitForFinished(1000) || !StartRoutingIpv6.returnValue()) {
qWarning() << "XrayProtocol::stop(): Failed to start routing ipv6";
}
auto restoreResolvers = iface->restoreResolvers();
if (!restoreResolvers.waitForFinished(1000) || !restoreResolvers.returnValue()) {
qWarning() << "XrayProtocol::stop(): Failed to restore resolvers";
}
#if !defined(Q_OS_MACOS)
auto deleteTun = iface->deleteTun("tun2");
if (!deleteTun.waitForFinished(1000) || !deleteTun.returnValue()) {
qWarning() << "XrayProtocol::stop(): Failed to delete tun";
}
#endif
#endif
iface->xrayStop();
});
if (m_t2sProcess) {
m_t2sProcess->stop();
QThread::msleep(200);
}
setConnectionState(Vpn::ConnectionState::Disconnected);
}
void XrayProtocol::readXrayConfiguration(const QJsonObject &configuration)
{
QJsonObject xrayConfiguration = configuration.value(ProtocolProps::key_proto_config_data(Proto::Xray)).toObject();
if (xrayConfiguration.isEmpty()) {
xrayConfiguration = configuration.value(ProtocolProps::key_proto_config_data(Proto::SSXray)).toObject();
}
m_xrayConfig = xrayConfiguration;
m_routeMode = static_cast<Settings::RouteMode>(configuration.value(amnezia::config_key::splitTunnelType).toInt());
m_primaryDNS = configuration.value(amnezia::config_key::dns1).toString();
m_secondaryDNS = configuration.value(amnezia::config_key::dns2).toString();
}
+8 -7
View File
@@ -6,7 +6,6 @@
#include "core/ipcclient.h"
#include "vpnprotocol.h"
#include "settings.h"
#include <QtCore/qsharedpointer.h>
class XrayProtocol : public VpnProtocol
{
@@ -19,14 +18,16 @@ public:
private:
ErrorCode setupRouting();
ErrorCode startTun2Socks();
ErrorCode startTun2Sock();
void readXrayConfiguration(const QJsonObject &configuration);
QJsonObject m_xrayConfig;
Settings::RouteMode m_routeMode;
QList<QHostAddress> m_dnsServers;
QString m_remoteAddress;
QSharedPointer<IpcProcessInterfaceReplica> m_tun2socksProcess;
QString m_primaryDNS;
QString m_secondaryDNS;
#ifndef Q_OS_IOS
QSharedPointer<IpcProcessTun2SocksReplica> m_t2sProcess;
#endif
};
#endif // XRAYPROTOCOL_H
@@ -291,8 +291,6 @@ void ImportController::processNativeWireGuardConfig()
clientProtocolConfig[config_key::cookieReplyPacketJunkSize] = "0";
clientProtocolConfig[config_key::transportPacketJunkSize] = "0";
clientProtocolConfig[config_key::specialJunk1] = protocols::awg::defaultSpecialJunk1;
clientProtocolConfig[config_key::isObfuscationEnabled] = true;
serverProtocolConfig[config_key::last_config] = QString(QJsonDocument(clientProtocolConfig).toJson());
+26 -365
View File
@@ -1,8 +1,6 @@
#include "apiCountryModel.h"
#include <QJsonObject>
#include <QSettings>
#include <utility>
#include "core/api/apiDefs.h"
#include "logger.h"
@@ -10,143 +8,14 @@
namespace
{
Logger logger("ApiCountryModel");
constexpr QLatin1String countryConfig("country_config");
constexpr QLatin1String regionEurope("Europe");
constexpr QLatin1String regionAmerica("America");
constexpr QLatin1String regionAsia("Asia");
constexpr QLatin1String regionOceaniaAfrica("Oceania and Africa");
constexpr QLatin1String regionOther("Other");
struct RegionRowData
{
bool isRegionHeader = false;
QString regionName;
bool isExpanded = true;
int sourceIndex = -1;
QString countryName;
QString sourceCountryName;
QString countryCode;
QString countryImageCode;
};
QString resolveRegionByIsoCode(const QString &isoCode)
{
static const QHash<QString, QString> isoToRegion = {
{"BE", regionEurope},
{"EE", regionEurope},
{"FI", regionEurope},
{"FR", regionEurope},
{"GE", regionEurope},
{"DE", regionEurope},
{"NL", regionEurope},
{"PL", regionEurope},
{"RU", regionEurope},
{"ES", regionEurope},
{"SE", regionEurope},
{"CH", regionEurope},
{"TR", regionEurope},
{"BR", regionAmerica},
{"CA", regionAmerica},
{"US", regionAmerica},
{"AE", regionAsia},
{"JP", regionAsia},
{"KZ", regionAsia},
{"KR", regionAsia},
{"SG", regionAsia},
{"AU", regionOceaniaAfrica},
{"NZ", regionOceaniaAfrica},
{"ZA", regionOceaniaAfrica},
};
return isoToRegion.value(isoCode, regionOther);
}
}
class ApiCountryModel::RegionRowsModel : public QAbstractListModel
ApiCountryModel::ApiCountryModel(QObject *parent) : QAbstractListModel(parent)
{
public:
enum Roles {
RowTypeRole = Qt::UserRole + 1,
RegionNameRole,
IsExpandedRole,
SourceIndexRole,
CountryNameRole,
SourceCountryNameRole,
CountryCodeRole,
CountryImageCodeRole
};
explicit RegionRowsModel(QObject *parent = nullptr) : QAbstractListModel(parent) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const override
{
Q_UNUSED(parent)
return m_rows.size();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_rows.size()) {
return QVariant();
}
const RegionRowData &row = m_rows.at(index.row());
switch (role) {
case RowTypeRole:
return row.isRegionHeader ? "region" : "country";
case RegionNameRole:
return row.regionName;
case IsExpandedRole:
return row.isExpanded;
case SourceIndexRole:
return row.sourceIndex;
case CountryNameRole:
return row.countryName;
case SourceCountryNameRole:
return row.sourceCountryName;
case CountryCodeRole:
return row.countryCode;
case CountryImageCodeRole:
return row.countryImageCode;
default:
return QVariant();
}
}
QHash<int, QByteArray> roleNames() const override
{
QHash<int, QByteArray> roles;
roles[RowTypeRole] = "rowType";
roles[RegionNameRole] = "regionName";
roles[IsExpandedRole] = "isExpanded";
roles[SourceIndexRole] = "sourceIndex";
roles[CountryNameRole] = "countryName";
roles[SourceCountryNameRole] = "sourceCountryName";
roles[CountryCodeRole] = "countryCode";
roles[CountryImageCodeRole] = "countryImageCode";
return roles;
}
void setRows(QVector<RegionRowData> &&rows)
{
beginResetModel();
m_rows = std::move(rows);
endResetModel();
}
private:
QVector<RegionRowData> m_rows;
};
ApiCountryModel::ApiCountryModel(QObject *parent)
: QAbstractListModel(parent), m_regionRowsModel(std::make_unique<RegionRowsModel>(this))
{
loadRegionExpansionState();
rebuildGroupedRegions();
}
ApiCountryModel::~ApiCountryModel() = default;
int ApiCountryModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
@@ -155,28 +24,32 @@ int ApiCountryModel::rowCount(const QModelIndex &parent) const
QVariant ApiCountryModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= static_cast<int>(rowCount())) {
if (!index.isValid() || index.row() < 0 || index.row() >= static_cast<int>(rowCount()))
return QVariant();
}
const CountryInfo &countryInfo = m_countries.at(index.row());
const IssuedConfigInfo issuedConfigInfo = m_issuedConfigs.value(countryInfo.countryCode);
const bool isIssued = issuedConfigInfo.sourceType == countryConfig;
CountryInfo countryInfo = m_countries.at(index.row());
IssuedConfigInfo issuedConfigInfo = m_issuedConfigs.value(countryInfo.countryCode);
bool isIssued = issuedConfigInfo.sourceType == countryConfig;
switch (role) {
case CountryCodeRole:
case CountryCodeRole: {
return countryInfo.countryCode;
case CountryNameRole:
return countryInfo.countryName;
case CountryImageCodeRole:
return countryInfo.countryCode.toUpper();
case IsIssuedRole:
return isIssued;
case IsWorkerExpiredRole:
return issuedConfigInfo.lastDownloaded < issuedConfigInfo.workerLastUpdated;
default:
return QVariant();
}
case CountryNameRole: {
return countryInfo.countryName;
}
case CountryImageCodeRole: {
return countryInfo.countryCode.toUpper();
}
case IsIssuedRole: {
return isIssued;
}
case IsWorkerExpiredRole: {
return issuedConfigInfo.lastDownloaded < issuedConfigInfo.workerLastUpdated;
}
}
return QVariant();
}
void ApiCountryModel::updateModel(const QJsonArray &countries, const QString &currentCountryCode)
@@ -184,9 +57,9 @@ void ApiCountryModel::updateModel(const QJsonArray &countries, const QString &cu
beginResetModel();
m_countries.clear();
for (int i = 0; i < countries.size(); ++i) {
for (int i = 0; i < countries.size(); i++) {
CountryInfo countryInfo;
const QJsonObject countryObject = countries.at(i).toObject();
QJsonObject countryObject = countries.at(i).toObject();
countryInfo.countryName = countryObject.value(apiDefs::key::serverCountryName).toString();
countryInfo.countryCode = countryObject.value(apiDefs::key::serverCountryCode).toString();
@@ -199,7 +72,6 @@ void ApiCountryModel::updateModel(const QJsonArray &countries, const QString &cu
}
endResetModel();
rebuildGroupedRegions();
}
void ApiCountryModel::updateIssuedConfigsInfo(const QJsonArray &issuedConfigs)
@@ -207,9 +79,9 @@ void ApiCountryModel::updateIssuedConfigsInfo(const QJsonArray &issuedConfigs)
beginResetModel();
m_issuedConfigs.clear();
for (int i = 0; i < issuedConfigs.size(); ++i) {
for (int i = 0; i < issuedConfigs.size(); i++) {
IssuedConfigInfo issuedConfigInfo;
const QJsonObject issuedConfigObject = issuedConfigs.at(i).toObject();
QJsonObject issuedConfigObject = issuedConfigs.at(i).toObject();
if (issuedConfigObject.value(apiDefs::key::sourceType).toString() != countryConfig) {
continue;
@@ -238,52 +110,6 @@ void ApiCountryModel::setCurrentIndex(const int i)
emit currentIndexChanged(m_currentIndex);
}
QString ApiCountryModel::searchText() const
{
return m_searchText;
}
void ApiCountryModel::setSearchText(const QString &text)
{
if (m_searchText == text) {
return;
}
m_searchText = text;
emit searchTextChanged();
rebuildGroupedRegions();
}
QAbstractListModel *ApiCountryModel::regionRowsModel() const
{
return m_regionRowsModel.get();
}
bool ApiCountryModel::hasVisibleRegions() const
{
return m_regionRowsModel && m_regionRowsModel->rowCount() > 0;
}
bool ApiCountryModel::isRegionExpanded(const QString &regionName) const
{
if (isSearchActive()) {
return true;
}
return m_regionsExpanded.contains(regionName) ? m_regionsExpanded.value(regionName) : true;
}
void ApiCountryModel::toggleRegionExpanded(const QString &regionName)
{
if (regionName.isEmpty() || isSearchActive()) {
return;
}
const bool currentValue = isRegionExpanded(regionName);
m_regionsExpanded.insert(regionName, !currentValue);
saveRegionExpansionState();
rebuildGroupedRegions();
}
QHash<int, QByteArray> ApiCountryModel::roleNames() const
{
QHash<int, QByteArray> roles;
@@ -294,168 +120,3 @@ QHash<int, QByteArray> ApiCountryModel::roleNames() const
roles[IsWorkerExpiredRole] = "isWorkerExpired";
return roles;
}
QString ApiCountryModel::normalizeCountryCode(const QString &countryCode) const
{
return countryCode.trimmed().toUpper();
}
QString ApiCountryModel::extractCountryIsoCode(const QString &countryCode) const
{
const QString normalizedCode = normalizeCountryCode(countryCode);
for (int i = 0; i + 1 < normalizedCode.size(); ++i) {
const QChar first = normalizedCode.at(i);
const QChar second = normalizedCode.at(i + 1);
if (first.isUpper() && second.isUpper()) {
return normalizedCode.mid(i, 2);
}
}
return normalizedCode;
}
QString ApiCountryModel::normalizeCountryName(const QString &countryName) const
{
return countryName.trimmed().toLower();
}
QString ApiCountryModel::normalizeSearchComparableText(const QString &textValue) const
{
QString normalizedText = normalizeCountryName(textValue);
normalizedText.replace(QChar(0x0451), QChar(0x0435)); // ё -> е
normalizedText.replace(QChar(0x0439), QChar(0x0438)); // й -> и
QString result;
result.reserve(normalizedText.size());
for (int i = 0; i < normalizedText.size(); ++i) {
const QChar currentChar = normalizedText.at(i);
if (currentChar.isSpace()) {
const QChar prevChar = i > 0 ? normalizedText.at(i - 1) : QChar();
const QChar nextChar = i + 1 < normalizedText.size() ? normalizedText.at(i + 1) : QChar();
const bool hasSpaceNeighbor = prevChar.isSpace() || nextChar.isSpace();
if (hasSpaceNeighbor) {
result.append(currentChar);
}
continue;
}
const bool isSeparator = currentChar == '.' || currentChar == '-';
if (!isSeparator) {
result.append(currentChar);
continue;
}
const QChar prevChar = i > 0 ? normalizedText.at(i - 1) : QChar();
const QChar nextChar = i + 1 < normalizedText.size() ? normalizedText.at(i + 1) : QChar();
const bool hasSeparatorNeighbor = prevChar == '.' || prevChar == '-' || nextChar == '.' || nextChar == '-';
if (hasSeparatorNeighbor) {
result.append(currentChar);
}
}
return result;
}
bool ApiCountryModel::isCountryMatchingSearch(const QString &countryName, const QString &sourceCountryCode,
const QString &normalizedSearchText) const
{
if (normalizedSearchText.isEmpty()) {
return true;
}
const QString normalizedCountryName = normalizeSearchComparableText(countryName);
const QString normalizedSourceCountryCode = normalizeCountryCode(sourceCountryCode).toLower();
return normalizedCountryName.startsWith(normalizedSearchText) || normalizedSourceCountryCode.startsWith(normalizedSearchText);
}
QString ApiCountryModel::getDisplayCountryName(const QString &countryName) const
{
const QString p2pPrefix = "[P2P] ";
if (countryName.startsWith(p2pPrefix)) {
return countryName.mid(p2pPrefix.size()) + " [P2P]";
}
return countryName;
}
void ApiCountryModel::rebuildGroupedRegions()
{
QVector<RegionRowData> rows;
const QString normalizedSearchText = normalizeSearchComparableText(m_searchText);
const QStringList orderedRegions = {
regionEurope,
regionAmerica,
regionAsia,
regionOceaniaAfrica,
regionOther,
};
QHash<QString, QVector<RegionRowData>> groupedCountries;
for (int sourceIndex = 0; sourceIndex < m_countries.size(); ++sourceIndex) {
const CountryInfo &sourceCountry = m_countries.at(sourceIndex);
if (!isCountryMatchingSearch(sourceCountry.countryName, sourceCountry.countryCode, normalizedSearchText)) {
continue;
}
const QString regionName = resolveRegionByIsoCode(extractCountryIsoCode(sourceCountry.countryCode));
RegionRowData countryRow;
countryRow.isRegionHeader = false;
countryRow.regionName = regionName;
countryRow.sourceIndex = sourceIndex;
countryRow.countryName = getDisplayCountryName(sourceCountry.countryName);
countryRow.sourceCountryName = sourceCountry.countryName;
countryRow.countryCode = sourceCountry.countryCode;
countryRow.countryImageCode = extractCountryIsoCode(sourceCountry.countryCode);
groupedCountries[regionName].push_back(std::move(countryRow));
}
for (const QString &regionName : orderedRegions) {
QVector<RegionRowData> countries = groupedCountries.value(regionName);
if (countries.isEmpty()) {
continue;
}
const bool expanded = isRegionExpanded(regionName);
RegionRowData headerRow;
headerRow.isRegionHeader = true;
headerRow.regionName = regionName;
headerRow.isExpanded = expanded;
rows.push_back(std::move(headerRow));
if (expanded) {
for (RegionRowData &countryRow : countries) {
countryRow.isExpanded = expanded;
rows.push_back(std::move(countryRow));
}
}
}
m_regionRowsModel->setRows(std::move(rows));
emit regionRowsChanged();
}
void ApiCountryModel::loadRegionExpansionState()
{
QSettings settings;
const QVariantMap stored = settings.value("PageSettingsApiAvailableCountries/regionsExpanded").toMap();
m_regionsExpanded.clear();
for (auto it = stored.constBegin(); it != stored.constEnd(); ++it) {
m_regionsExpanded.insert(it.key(), it.value().toBool());
}
}
void ApiCountryModel::saveRegionExpansionState() const
{
QVariantMap stored;
for (auto it = m_regionsExpanded.constBegin(); it != m_regionsExpanded.constEnd(); ++it) {
stored.insert(it.key(), it.value());
}
QSettings settings;
settings.setValue("PageSettingsApiAvailableCountries/regionsExpanded", stored);
}
bool ApiCountryModel::isSearchActive() const
{
return !normalizeSearchComparableText(m_searchText).isEmpty();
}
+1 -30
View File
@@ -4,7 +4,6 @@
#include <QAbstractListModel>
#include <QHash>
#include <QJsonArray>
#include <memory>
class ApiCountryModel : public QAbstractListModel
{
@@ -20,16 +19,12 @@ public:
};
explicit ApiCountryModel(QObject *parent = nullptr);
~ApiCountryModel() override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
Q_PROPERTY(int currentIndex READ getCurrentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged)
Q_PROPERTY(QAbstractListModel *regionRowsModel READ regionRowsModel CONSTANT)
Q_PROPERTY(bool hasVisibleRegions READ hasVisibleRegions NOTIFY regionRowsChanged)
public slots:
void updateModel(const QJsonArray &countries, const QString &currentCountryCode);
@@ -37,17 +32,9 @@ public slots:
int getCurrentIndex();
void setCurrentIndex(const int i);
QString searchText() const;
void setSearchText(const QString &text);
QAbstractListModel *regionRowsModel() const;
bool hasVisibleRegions() const;
Q_INVOKABLE bool isRegionExpanded(const QString &regionName) const;
Q_INVOKABLE void toggleRegionExpanded(const QString &regionName);
signals:
void currentIndexChanged(const int index);
void searchTextChanged();
void regionRowsChanged();
protected:
QHash<int, QByteArray> roleNames() const override;
@@ -70,23 +57,7 @@ private:
QVector<CountryInfo> m_countries;
QHash<QString, IssuedConfigInfo> m_issuedConfigs;
int m_currentIndex = -1;
QString m_searchText;
QHash<QString, bool> m_regionsExpanded;
class RegionRowsModel;
std::unique_ptr<RegionRowsModel> m_regionRowsModel;
QString normalizeCountryCode(const QString &countryCode) const;
QString extractCountryIsoCode(const QString &countryCode) const;
QString normalizeCountryName(const QString &countryName) const;
QString normalizeSearchComparableText(const QString &textValue) const;
bool isCountryMatchingSearch(const QString &countryName, const QString &sourceCountryCode,
const QString &normalizedSearchText) const;
QString getDisplayCountryName(const QString &countryName) const;
void rebuildGroupedRegions();
void loadRegionExpansionState();
void saveRegionExpansionState() const;
bool isSearchActive() const;
int m_currentIndex;
};
#endif // APICOUNTRYMODEL_H
@@ -1,6 +1,7 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
import SortFilterProxyModel 0.2
@@ -17,7 +18,6 @@ PageType {
id: root
property var processedServer
readonly property int topBarHeight: 20 + SettingsController.safeAreaTopMargin + backButton.implicitHeight + 12
Connections {
target: ServersModel
@@ -44,38 +44,12 @@ PageType {
}
}
Rectangle {
id: topBar
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: root.topBarHeight
color: AmneziaStyle.color.midnightBlack
z: 10
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.AllButtons
}
BackButtonType {
id: backButton
objectName: "backButton"
anchors.top: parent.top
anchors.left: parent.left
anchors.topMargin: 20 + SettingsController.safeAreaTopMargin
anchors.leftMargin: 16
z: 1
}
}
ListViewType {
id: menuContent
anchors.fill: parent
model: ApiCountryModel.regionRowsModel
model: ApiCountryModel
currentIndex: 0
@@ -88,6 +62,13 @@ PageType {
spacing: 4
BackButtonType {
id: backButton
objectName: "backButton"
Layout.topMargin: 20 + SettingsController.safeAreaTopMargin
}
HeaderTypeWithButton {
id: headerContent
objectName: "headerContent"
@@ -95,7 +76,6 @@ PageType {
Layout.fillWidth: true
Layout.leftMargin: 16
Layout.rightMargin: 16
Layout.topMargin: topBar.height + 4
Layout.bottomMargin: 10
actionButtonImage: "qrc:/images/controls/settings.svg"
@@ -114,238 +94,76 @@ PageType {
PageController.goToPage(PageEnum.PageSettingsApiServerInfo)
}
}
Rectangle {
Layout.fillWidth: true
Layout.leftMargin: 16
Layout.rightMargin: 16
Layout.bottomMargin: 10
implicitHeight: 56
radius: 16
color: AmneziaStyle.color.onyxBlack
border.color: searchField.activeFocus ? AmneziaStyle.color.paleGray : AmneziaStyle.color.slateGray
border.width: 1
Behavior on border.color {
PropertyAnimation { duration: 200 }
}
RowLayout {
anchors.fill: parent
anchors.leftMargin: 16
anchors.rightMargin: 8
spacing: 8
Image {
source: "qrc:/images/controls/search.svg"
}
TextField {
id: searchField
Layout.fillWidth: true
color: AmneziaStyle.color.paleGray
placeholderText: "country or country code"
placeholderTextColor: AmneziaStyle.color.charcoalGray
selectionColor: AmneziaStyle.color.richBrown
selectedTextColor: AmneziaStyle.color.paleGray
font.pixelSize: 16
font.weight: 400
font.family: "PT Root UI VF"
inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText
topPadding: 0
rightPadding: 0
leftPadding: 0
bottomPadding: 0
background: Rectangle {
color: AmneziaStyle.color.transparent
}
onTextChanged: {
const shouldRestoreFocus = activeFocus
const previousCursorPosition = cursorPosition
ApiCountryModel.searchText = text
if (shouldRestoreFocus) {
Qt.callLater(function() {
searchField.forceActiveFocus()
searchField.cursorPosition = Math.min(previousCursorPosition, searchField.text.length)
})
}
}
Keys.onEscapePressed: {
searchField.text = ""
}
ContextMenu.menu: ContextMenuType {
textObj: searchField
}
}
ImageButtonType {
visible: searchField.text !== ""
implicitWidth: 40
implicitHeight: 40
hoverEnabled: true
image: "qrc:/images/controls/close.svg"
imageColor: AmneziaStyle.color.paleGray
onClicked: {
searchField.text = ""
}
Keys.onEnterPressed: {
searchField.text = ""
}
Keys.onReturnPressed: {
searchField.text = ""
}
}
}
}
}
footer: Item {
delegate: ColumnLayout {
id: content
width: menuContent.width
height: ApiCountryModel.hasVisibleRegions ? 0 : emptyStateText.implicitHeight + 32
height: content.implicitHeight
CaptionTextType {
id: emptyStateText
RowLayout {
VerticalRadioButton {
id: containerRadioButton
anchors.left: parent.left
anchors.right: parent.right
anchors.leftMargin: 16
anchors.rightMargin: 16
anchors.top: parent.top
anchors.topMargin: 16
Layout.fillWidth: true
Layout.leftMargin: 16
visible: !ApiCountryModel.hasVisibleRegions
color: AmneziaStyle.color.mutedGray
text: countryName
font.pixelSize: 15
horizontalAlignment: Text.AlignLeft
wrapMode: Text.WordWrap
text: "Nothing found. Try a different spelling or switch keyboard layout."
}
}
ButtonGroup.group: containersRadioButtonGroup
delegate: Item {
width: menuContent.width
implicitHeight: rowType === "region" ? 44 : 88
imageSource: "qrc:/images/controls/download.svg"
Item {
anchors.fill: parent
visible: rowType === "region"
checked: index === ApiCountryModel.currentIndex
checkable: !ConnectionController.isConnected
RowLayout {
anchors.fill: parent
anchors.leftMargin: 16
anchors.rightMargin: 16
anchors.topMargin: 12
anchors.bottomMargin: 8
spacing: 8
CaptionTextType {
Layout.fillWidth: true
color: AmneziaStyle.color.mutedGray
text: regionName
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignVCenter
}
Image {
source: isExpanded ? "qrc:/images/controls/chevron-up.svg"
: "qrc:/images/controls/chevron-down.svg"
}
}
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: {
ApiCountryModel.toggleRegionExpanded(regionName)
if (ConnectionController.isConnectionInProgress) {
PageController.showNotificationMessage(qsTr("Unable change server location while trying to make an active connection"))
return
}
if (ConnectionController.isConnected) {
PageController.showNotificationMessage(qsTr("Unable change server location while there is an active connection"))
return
}
if (index !== ApiCountryModel.currentIndex) {
PageController.showBusyIndicator(true)
var prevIndex = ApiCountryModel.currentIndex
ApiCountryModel.currentIndex = index
if (!ApiConfigsController.updateServiceFromGateway(ServersModel.defaultIndex, countryCode, countryName)) {
ApiCountryModel.currentIndex = prevIndex
}
PageController.showBusyIndicator(false)
}
}
Keys.onEnterPressed: {
if (checkable) {
checked = true
}
containerRadioButton.clicked()
}
Keys.onReturnPressed: {
if (checkable) {
checked = true
}
containerRadioButton.clicked()
}
}
Image {
Layout.rightMargin: 32
Layout.alignment: Qt.AlignRight
source: "qrc:/countriesFlags/images/flagKit/" + countryImageCode + ".svg"
}
}
ColumnLayout {
anchors.fill: parent
visible: rowType === "country"
spacing: 0
RowLayout {
Layout.fillWidth: true
VerticalRadioButton {
id: containerRadioButton
Layout.fillWidth: true
Layout.leftMargin: 16
text: countryName
ButtonGroup.group: containersRadioButtonGroup
imageSource: "qrc:/images/controls/download.svg"
checked: sourceIndex >= 0 && sourceIndex === ApiCountryModel.currentIndex
checkable: !ConnectionController.isConnected
onClicked: {
if (ConnectionController.isConnectionInProgress) {
PageController.showNotificationMessage(qsTr("Unable change server location while trying to make an active connection"))
return
}
if (ConnectionController.isConnected) {
PageController.showNotificationMessage(qsTr("Unable change server location while there is an active connection"))
return
}
if (sourceIndex !== ApiCountryModel.currentIndex) {
PageController.showBusyIndicator(true)
var prevIndex = ApiCountryModel.currentIndex
ApiCountryModel.currentIndex = sourceIndex
if (!ApiConfigsController.updateServiceFromGateway(ServersModel.defaultIndex, countryCode, sourceCountryName)) {
ApiCountryModel.currentIndex = prevIndex
}
PageController.showBusyIndicator(false)
}
}
Keys.onEnterPressed: {
if (checkable) {
checked = true
}
containerRadioButton.clicked()
}
Keys.onReturnPressed: {
if (checkable) {
checked = true
}
containerRadioButton.clicked()
}
}
Image {
Layout.rightMargin: 32
Layout.alignment: Qt.AlignRight
source: "qrc:/countriesFlags/images/flagKit/" + countryImageCode + ".svg"
}
}
DividerType {
Layout.fillWidth: true
}
DividerType {
Layout.fillWidth: true
}
}
}
}
+105 -7
View File
@@ -99,7 +99,21 @@ void VpnConnection::onConnectionStateChanged(Vpn::ConnectionState state)
}
}
}
if (container != DockerContainer::Ipsec) {
if (startNetworkCheckIfReady()) {
m_pendingNetworkCheck = false;
} else {
m_pendingNetworkCheck = true;
qWarning() << "Deferring startNetworkCheck; missing gateway/local address"
<< m_vpnProtocol->vpnGateway() << m_vpnProtocol->vpnLocalAddress();
}
} else {
m_pendingNetworkCheck = false;
}
} else if (state == Vpn::ConnectionState::Error) {
m_pendingNetworkCheck = false;
iface->flushDns();
if (m_settings->isSitesSplitTunnelingEnabled()) {
@@ -107,6 +121,12 @@ void VpnConnection::onConnectionStateChanged(Vpn::ConnectionState state)
iface->clearSavedRoutes();
}
}
} else if (state == Vpn::ConnectionState::Connecting) {
} else if (state == Vpn::ConnectionState::Disconnected) {
m_pendingNetworkCheck = false;
auto result = iface->stopNetworkCheck();
result.waitForFinished(3000);
}
});
#endif
@@ -245,7 +265,7 @@ ErrorCode VpnConnection::lastError() const
void VpnConnection::connectToVpn(int serverIndex, const ServerCredentials &credentials, DockerContainer container,
const QJsonObject &vpnConfiguration)
{
qDebug() << QString("Trying to connect to VPN, server index is %1, container is %2, route mode is")
qDebug() << QString("ConnectToVpn, Server index is %1, container is %2, route mode is")
.arg(serverIndex)
.arg(ContainerProps::containerToString(container))
<< m_settings->routeMode();
@@ -253,7 +273,11 @@ void VpnConnection::connectToVpn(int serverIndex, const ServerCredentials &crede
m_remoteAddress = NetworkUtilities::getIPAddress(credentials.hostName);
emit connectionStateChanged(Vpn::ConnectionState::Connecting);
m_pendingNetworkCheck = false;
m_vpnConfiguration = vpnConfiguration;
m_serverIndex = serverIndex;
m_serverCredentials = credentials;
m_dockerContainer = container;
#ifdef AMNEZIA_DESKTOP
if (m_vpnProtocol) {
@@ -292,12 +316,71 @@ void VpnConnection::connectToVpn(int serverIndex, const ServerCredentials &crede
emit connectionStateChanged(Vpn::ConnectionState::Error);
}
void VpnConnection::restartConnection()
{
// Only reconnect if VPN was connected before sleep/network change
if (!m_wasConnectedBeforeSleep) {
qDebug() << "VPN was not connected before sleep/network change, skipping reconnection";
return;
}
qDebug() << "VPN was connected before sleep/network change, attempting reconnection";
this->disconnectFromVpn();
#ifdef Q_OS_LINUX
QThread::msleep(5000);
#endif
this->connectToVpn(m_serverIndex, m_serverCredentials, m_dockerContainer, m_vpnConfiguration);
// Reset the flag after reconnection attempt
m_wasConnectedBeforeSleep = false;
}
void VpnConnection::createProtocolConnections()
{
connect(m_vpnProtocol.data(), &VpnProtocol::protocolError, this, &VpnConnection::vpnProtocolError);
connect(m_vpnProtocol.data(), SIGNAL(connectionStateChanged(Vpn::ConnectionState)), this,
SLOT(onConnectionStateChanged(Vpn::ConnectionState)));
connect(m_vpnProtocol.data(), SIGNAL(bytesChanged(quint64, quint64)), this, SLOT(onBytesChanged(quint64, quint64)));
#ifdef AMNEZIA_DESKTOP
if (m_connectionLoseHandle)
disconnect(m_connectionLoseHandle);
if (m_networkChangeHandle)
disconnect(m_networkChangeHandle);
m_connectionLoseHandle = QMetaObject::Connection();
m_networkChangeHandle = QMetaObject::Connection();
// TODO: replace unsafe IpcClient::Interface() calls
m_connectionLoseHandle = connect(IpcClient::Interface().data(), &IpcInterfaceReplica::connectionLose,
this, [this]() {
qDebug() << "Connection Lose";
auto result = IpcClient::Interface()->stopNetworkCheck();
result.waitForFinished(3000);
// Track VPN state before connection loss
m_wasConnectedBeforeSleep = isConnected();
qDebug() << "VPN was connected before connection loss:" << m_wasConnectedBeforeSleep;
this->restartConnection();
});
m_networkChangeHandle = connect(IpcClient::Interface().data(), &IpcInterfaceReplica::networkChange,
this, [this]() {
qDebug() << "Network change";
// Track VPN state before network change (including sleep/wake)
m_wasConnectedBeforeSleep = isConnected();
qDebug() << "VPN was connected before network change:" << m_wasConnectedBeforeSleep;
this->restartConnection();
});
connect(m_vpnProtocol.data(), &VpnProtocol::tunnelAddressesUpdated,
this, [this](const QString& gateway, const QString& localAddress) {
Q_UNUSED(gateway)
Q_UNUSED(localAddress)
if (connectionState() != Vpn::ConnectionState::Connected) {
return;
}
if (startNetworkCheckIfReady()) {
m_pendingNetworkCheck = false;
}
});
#endif
}
void VpnConnection::appendKillSwitchConfig()
@@ -399,13 +482,28 @@ void VpnConnection::appendSplitTunnelingConfig()
m_vpnConfiguration.insert(config_key::appSplitTunnelType, appsRouteMode);
m_vpnConfiguration.insert(config_key::splitTunnelApps, appsJsonArray);
}
qDebug() << QString("Site split tunneling is %1, route mode is %2")
.arg(m_settings->isSitesSplitTunnelingEnabled() ? "enabled" : "disabled")
.arg(routeMode);
qDebug() << QString("App split tunneling is %1, route mode is %2")
.arg(m_settings->isAppsSplitTunnelingEnabled() ? "enabled" : "disabled")
.arg(appsRouteMode);
bool VpnConnection::startNetworkCheckIfReady()
{
#ifdef AMNEZIA_DESKTOP
if (!m_vpnProtocol || m_dockerContainer == DockerContainer::Ipsec) {
return false;
}
const QString gateway = m_vpnProtocol->vpnGateway();
const QString localAddress = m_vpnProtocol->vpnLocalAddress();
if (gateway.isEmpty() || localAddress.isEmpty()) {
return false;
}
return IpcClient::withInterface([&](QSharedPointer<IpcInterfaceReplica> iface) {
QRemoteObjectPendingReply<bool> reply = iface->startNetworkCheck(gateway, localAddress);
return reply.waitForFinished(1000) && reply.returnValue();
});
#else
return false;
#endif
}
#ifdef Q_OS_ANDROID
+12
View File
@@ -52,6 +52,7 @@ public slots:
const ServerCredentials &credentials, DockerContainer container, const QJsonObject &vpnConfiguration);
void disconnectFromVpn();
void restartConnection();
void addRoutes(const QStringList &ips);
void deleteRoutes(const QStringList &ips);
@@ -72,6 +73,8 @@ protected slots:
protected:
QSharedPointer<VpnProtocol> m_vpnProtocol;
QMetaObject::Connection m_connectionLoseHandle;
QMetaObject::Connection m_networkChangeHandle;
private:
std::shared_ptr<Settings> m_settings;
@@ -79,6 +82,14 @@ private:
QJsonObject m_routeMode;
QString m_remoteAddress;
ServerCredentials m_serverCredentials;
int m_serverIndex;
DockerContainer m_dockerContainer;
// Track VPN state before sleep for smart reconnection
bool m_wasConnectedBeforeSleep = false;
bool m_pendingNetworkCheck = false;
// Only for iOS for now, check counters
QTimer m_checkTimer;
@@ -93,6 +104,7 @@ private:
void appendSplitTunnelingConfig();
void appendKillSwitchConfig();
bool startNetworkCheckIfReady();
};
#endif // VPNCONNECTION_H
+9 -57
View File
@@ -11,7 +11,6 @@
namespace amnezia {
enum PermittedProcess {
Invalid,
OpenVPN,
Wireguard,
Tun2Socks,
@@ -20,18 +19,16 @@ enum PermittedProcess {
inline QString permittedProcessPath(PermittedProcess pid)
{
switch (pid) {
case PermittedProcess::OpenVPN:
return Utils::openVpnExecPath();
case PermittedProcess::Wireguard:
return Utils::wireguardExecPath();
case PermittedProcess::CertUtil:
return Utils::certUtilPath();
case PermittedProcess::Tun2Socks:
return Utils::tun2socksPath();
default:
return "";
if (pid == PermittedProcess::OpenVPN) {
return Utils::openVpnExecPath();
} else if (pid == PermittedProcess::Wireguard) {
return Utils::wireguardExecPath();
} else if (pid == PermittedProcess::CertUtil) {
return Utils::certUtilPath();
} else if (pid == PermittedProcess::Tun2Socks) {
return Utils::tun2socksPath();
}
return "";
}
@@ -51,51 +48,6 @@ inline QString getIpcProcessUrl(int pid) {
#endif
}
inline QStringList sanitizeArguments(PermittedProcess proc, const QStringList &args) {
using Validator = std::function<bool(const QString&)>;
QMap<QString, Validator> namedArgs;
QList<Validator> positionalArgs;
switch (proc) {
case Tun2Socks:
namedArgs["-device"] = [](const QString& v) { return v.startsWith("tun://"); };
namedArgs["-proxy"] = [](const QString& v) { return v.startsWith("socks5://"); };
break;
default:
//FIXME
return args;
}
QStringList sanitized;
for (int i = 0, pos = 0; i < args.size(); i++) {
const auto& key = args[i];
if (const auto found = namedArgs.find(key); found != namedArgs.end()) {
const auto validator = found.value();
if (validator) {
if (i + 1 < args.size()) {
const auto& value = args[i+1];
if (validator(value)) {
sanitized << key << value;
i++;
}
}
} else {
sanitized << key;
}
} else if (pos < positionalArgs.size()) {
if (const auto validator = positionalArgs[pos]; validator && validator(key)) {
sanitized << key;
pos++;
}
}
}
return sanitized;
}
} // namespace amnezia
+2 -2
View File
@@ -38,8 +38,8 @@ class IpcInterface
SLOT( bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers) );
SLOT( bool restoreResolvers() );
SLOT(bool xrayStart(const QString &config));
SLOT(bool xrayStop());
SLOT(void xrayStart(const QString &config));
SLOT(void xrayStop());
SLOT( bool startNetworkCheck(const QString& serverIpv4Gateway, const QString& deviceIpv4Address) );
SLOT( bool stopNetworkCheck() );
-7
View File
@@ -4,8 +4,6 @@
class IpcProcessInterface
{
SLOT( start() );
SLOT( terminate() );
SLOT( kill() );
SLOT( close() );
SLOT( setArguments(const QStringList &arguments) );
@@ -19,11 +17,6 @@ class IpcProcessInterface
SLOT( QByteArray readAllStandardError() );
SLOT( QByteArray readAllStandardOutput() );
SLOT( bool waitForFinished() );
SLOT( bool waitForFinished(int msecs) );
SLOT( bool waitForStarted() );
SLOT( bool waitForStarted(int msecs) );
SIGNAL( errorOccurred(QProcess::ProcessError error) );
SIGNAL( finished(int exitCode, QProcess::ExitStatus exitStatus) );
+11
View File
@@ -0,0 +1,11 @@
#include <QtCore>
#include <QString>
class IpcProcessTun2Socks
{
SLOT( start() );
SLOT( stop() );
SIGNAL( setConnectionState(int state) );
SIGNAL( stateChanged(QProcess::ProcessState newState) );
};
+2 -2
View File
@@ -304,7 +304,7 @@ bool IpcServer::refreshKillSwitch(bool enabled)
return KillSwitch::instance()->refresh(enabled);
}
bool IpcServer::xrayStart(const QString& cfg)
void IpcServer::xrayStart(const QString& cfg)
{
#ifdef MZ_DEBUG
qDebug() << "IpcServer::xrayStart";
@@ -313,7 +313,7 @@ bool IpcServer::xrayStart(const QString& cfg)
return Xray::getInstance().startXray(cfg);
}
bool IpcServer::xrayStop()
void IpcServer::xrayStop()
{
#ifdef MZ_DEBUG
qDebug() << "IpcServer::xrayStop";
+6 -2
View File
@@ -10,8 +10,10 @@
#include "ipc.h"
#include "ipcserverprocess.h"
#include "ipctun2socksprocess.h"
#include "rep_ipc_interface_source.h"
#include "rep_ipc_process_tun2socks_source.h"
class IpcServer : public IpcInterfaceSource
{
@@ -42,8 +44,8 @@ public:
virtual bool refreshKillSwitch( bool enabled ) override;
virtual bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers) override;
virtual bool restoreResolvers() override;
virtual bool xrayStart(const QString& cfg) override;
virtual bool xrayStop() override;
virtual void xrayStart(const QString& cfg) override;
virtual void xrayStop() override;
virtual bool startNetworkCheck(const QString& serverIpv4Gateway, const QString& deviceIpv4Address) override;
virtual bool stopNetworkCheck() override;
@@ -54,10 +56,12 @@ private:
ProcessDescriptor (QObject *parent = nullptr) {
serverNode = QSharedPointer<QRemoteObjectHost>(new QRemoteObjectHost(parent));
ipcProcess = QSharedPointer<IpcServerProcess>(new IpcServerProcess(parent));
tun2socksProcess = QSharedPointer<IpcProcessTun2Socks>(new IpcProcessTun2Socks(parent));
localServer = QSharedPointer<QLocalServer>(new QLocalServer(parent));
}
QSharedPointer<IpcServerProcess> ipcProcess;
QSharedPointer<IpcProcessTun2Socks> tun2socksProcess;
QSharedPointer<QRemoteObjectHost> serverNode;
QSharedPointer<QLocalServer> localServer;
};
+2 -28
View File
@@ -40,14 +40,6 @@ void IpcServerProcess::start()
m_process->waitForStarted();
}
void IpcServerProcess::terminate() {
m_process->terminate();
}
void IpcServerProcess::kill() {
m_process->kill();
}
void IpcServerProcess::close()
{
m_process->close();
@@ -55,7 +47,7 @@ void IpcServerProcess::close()
void IpcServerProcess::setArguments(const QStringList &arguments)
{
m_process->setArguments(amnezia::sanitizeArguments(m_program, arguments));
m_process->setArguments(arguments);
}
void IpcServerProcess::setInputChannelMode(QProcess::InputChannelMode mode)
@@ -77,9 +69,7 @@ void IpcServerProcess::setProcessChannelMode(QProcess::ProcessChannelMode mode)
void IpcServerProcess::setProgram(int programId)
{
m_program = static_cast<amnezia::PermittedProcess>(programId);
m_process->setProgram(amnezia::permittedProcessPath(m_program));
m_process->setArguments({});
m_process->setProgram(amnezia::permittedProcessPath(static_cast<amnezia::PermittedProcess>(programId)));
}
void IpcServerProcess::setWorkingDirectory(const QString &dir)
@@ -102,20 +92,4 @@ QByteArray IpcServerProcess::readAllStandardOutput()
return m_process->readAllStandardOutput();
}
bool IpcServerProcess::waitForStarted() {
return m_process->waitForStarted();
}
bool IpcServerProcess::waitForStarted(int msecs) {
return m_process->waitForStarted(msecs);
}
bool IpcServerProcess::waitForFinished() {
return m_process->waitForFinished();
}
bool IpcServerProcess::waitForFinished(int msecs) {
return m_process->waitForFinished(msecs);
}
#endif
-9
View File
@@ -1,7 +1,6 @@
#ifndef IPCSERVERPROCESS_H
#define IPCSERVERPROCESS_H
#include "ipc.h"
#include <QObject>
#ifndef Q_OS_IOS
@@ -15,8 +14,6 @@ public:
virtual ~IpcServerProcess();
void start() override;
void terminate() override;
void kill() override;
void close() override;
void setArguments(const QStringList &arguments) override;
@@ -30,15 +27,9 @@ public:
QByteArray readAllStandardError() override;
QByteArray readAllStandardOutput() override;
bool waitForStarted() override;
bool waitForStarted(int msecs) override;
bool waitForFinished() override;
bool waitForFinished(int msecs) override;
signals:
private:
amnezia::PermittedProcess m_program = amnezia::PermittedProcess::Invalid;
QSharedPointer<QProcess> m_process;
};
+75
View File
@@ -0,0 +1,75 @@
#include "ipctun2socksprocess.h"
#include "ipc.h"
#include <QProcess>
#include <QString>
#include "../protocols/protocols_defs.h"
#ifndef Q_OS_IOS
IpcProcessTun2Socks::IpcProcessTun2Socks(QObject *parent) :
IpcProcessTun2SocksSource(parent),
m_t2sProcess(QSharedPointer<QProcess>(new QProcess()))
{
qDebug() << "IpcProcessTun2Socks::IpcProcessTun2Socks()";
}
IpcProcessTun2Socks::~IpcProcessTun2Socks()
{
qDebug() << "IpcProcessTun2Socks::~IpcProcessTun2Socks()";
}
void IpcProcessTun2Socks::start()
{
connect(m_t2sProcess.data(), &QProcess::stateChanged, this, &IpcProcessTun2Socks::stateChanged);
qDebug() << "IpcProcessTun2Socks::start()";
m_t2sProcess->setProgram(amnezia::permittedProcessPath(static_cast<amnezia::PermittedProcess>(amnezia::PermittedProcess::Tun2Socks)));
QString XrayConStr = "socks5://127.0.0.1:10808";
#ifdef Q_OS_WIN
QStringList arguments({"-device", "tun://tun2?guid={081A8A84-8D12-4DF5-B8C4-396D5B0053E4}", "-proxy", XrayConStr });
#endif
#ifdef Q_OS_LINUX
QStringList arguments({"-device", "tun://tun2", "-proxy", XrayConStr});
#endif
#ifdef Q_OS_MAC
QStringList arguments({"-device", "utun22", "-proxy", XrayConStr});
#endif
m_t2sProcess->setArguments(arguments);
if (Utils::processIsRunning(Utils::executable("tun2socks", false))) {
qDebug().noquote() << "kill previos tun2socks";
Utils::killProcessByName(Utils::executable("tun2socks", false));
}
connect(m_t2sProcess.data(), &QProcess::readyReadStandardOutput, this, [this]() {
QString line = m_t2sProcess.data()->readAllStandardOutput();
if (line.contains("[STACK] tun://") && line.contains("<-> socks5://127.0.0.1")) {
emit setConnectionState(Vpn::ConnectionState::Connected);
}
});
connect(m_t2sProcess.data(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [this](int exitCode, QProcess::ExitStatus exitStatus) {
qDebug().noquote() << "tun2socks finished, exitCode, exiStatus" << exitCode << exitStatus;
emit setConnectionState(Vpn::ConnectionState::Disconnected);
if ((exitStatus != QProcess::NormalExit) || (exitCode != 0)) {
emit setConnectionState(Vpn::ConnectionState::Error);
}
});
m_t2sProcess->start();
m_t2sProcess->waitForStarted();
}
void IpcProcessTun2Socks::stop()
{
qDebug() << "IpcProcessTun2Socks::stop()";
m_t2sProcess->disconnect();
m_t2sProcess->kill();
m_t2sProcess->waitForFinished(3000);
}
#endif
+52
View File
@@ -0,0 +1,52 @@
#ifndef IPCTUN2SOCKSPROCESS_H
#define IPCTUN2SOCKSPROCESS_H
#include <QObject>
#ifndef Q_OS_IOS
#include "rep_ipc_process_tun2socks_source.h"
namespace Vpn
{
Q_NAMESPACE
enum ConnectionState {
Unknown,
Disconnected,
Preparing,
Connecting,
Connected,
Disconnecting,
Reconnecting,
Error
};
Q_ENUM_NS(ConnectionState)
}
class IpcProcessTun2Socks : public IpcProcessTun2SocksSource
{
Q_OBJECT
public:
explicit IpcProcessTun2Socks(QObject *parent = nullptr);
virtual ~IpcProcessTun2Socks();
void start() override;
void stop() override;
signals:
private:
QSharedPointer<QProcess> m_t2sProcess;
};
#else
class IpcProcessTun2Socks : public QObject
{
Q_OBJECT
public:
explicit IpcProcessTun2Socks(QObject *parent = nullptr);
};
#endif
#endif // IPCTUN2SOCKSPROCESS_H
+7
View File
@@ -6,6 +6,13 @@ project(${PROJECT} VERSION ${AMNEZIAVPN_VERSION})
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(LINUX)
set(CMAKE_BUILD_RPATH "\$ORIGIN/../lib")
set(CMAKE_INSTALL_RPATH "\$ORIGIN/../lib")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
endif()
if(NOT IOS AND NOT ANDROID AND NOT MACOS_NE)
add_subdirectory(server)
endif()
+13
View File
@@ -75,6 +75,7 @@ set(HEADERS
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipc.h
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipcserver.h
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipcserverprocess.h
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipctun2socksprocess.h
${CMAKE_CURRENT_LIST_DIR}/localserver.h
${CMAKE_CURRENT_LIST_DIR}/../../common/logger/logger.h
${CMAKE_CURRENT_LIST_DIR}/router.h
@@ -96,6 +97,7 @@ set(SOURCES
${CMAKE_CURRENT_LIST_DIR}/../../client/core/networkUtilities.cpp
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipcserver.cpp
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipcserverprocess.cpp
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipctun2socksprocess.cpp
${CMAKE_CURRENT_LIST_DIR}/localserver.cpp
${CMAKE_CURRENT_LIST_DIR}/../../common/logger/logger.cpp
${CMAKE_CURRENT_LIST_DIR}/main.cpp
@@ -351,6 +353,16 @@ include_directories(
add_executable(${PROJECT} ${SOURCES} ${HEADERS} ${RESOURCES})
if(LINUX)
target_link_options(${PROJECT} PRIVATE "LINKER:--disable-new-dtags")
set_target_properties(${PROJECT} PROPERTIES
BUILD_RPATH "\$ORIGIN/../lib"
INSTALL_RPATH "\$ORIGIN/../lib"
INSTALL_RPATH_USE_LINK_PATH FALSE
)
set_property(TARGET ${PROJECT} PROPERTY BUILD_WITH_INSTALL_RPATH TRUE)
endif()
target_link_libraries(${PROJECT} PRIVATE Qt6::Core Qt6::Widgets Qt6::Network Qt6::RemoteObjects Qt6::Core5Compat Qt6::DBus Qt6::Concurrent ${LIBS})
target_compile_definitions(${PROJECT} PRIVATE "MZ_$<UPPER_CASE:${MZ_PLATFORM_NAME}>")
@@ -387,6 +399,7 @@ endif()
qt_add_repc_sources(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipc_interface.rep)
qt_add_repc_sources(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipc_process_interface.rep)
qt_add_repc_sources(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipc_process_tun2socks.rep)
# copy deploy artifacts required to run the application to the debug build folder
if(WIN32)
+1
View File
@@ -40,6 +40,7 @@ LocalServer::LocalServer(QObject *parent) : QObject(parent),
if (!m_isRemotingEnabled) {
m_isRemotingEnabled = true;
m_serverNode.enableRemoting(&m_ipcServer);
m_serverNode.enableRemoting(&m_tun2socks);
}
});
+1
View File
@@ -38,6 +38,7 @@ public:
~LocalServer();
QSharedPointer<QLocalServer> m_server;
IpcServer m_ipcServer;
IpcProcessTun2Socks m_tun2socks;
QRemoteObjectHost m_serverNode;
bool m_isRemotingEnabled = false;
+1 -41
View File
@@ -318,40 +318,6 @@ bool RouterWin::createTun(const QString &dev, const QString &subnet)
return false;
}
HANDLE hEvent = CreateEvent(nullptr, true, false, nullptr);
if (!hEvent) {
qCritical() << "Failed to allocate event object";
return false;
}
auto _guardEvent = qScopeGuard([hEvent](){ CloseHandle(hEvent); });
struct {
HANDLE hEvent;
NET_LUID luid;
const QString &subnet;
bool found;
} ctx = { .hEvent = hEvent, .luid = luid, .subnet = subnet, .found = false };
auto cb = [](void *priv, MIB_UNICASTIPADDRESS_ROW *row, MIB_NOTIFICATION_TYPE NotificationType) {
auto* c = reinterpret_cast<decltype(ctx)*>(priv);
if (row != nullptr && row->InterfaceLuid.Value == c->luid.Value && row->Address.si_family == AF_INET) {
char ip[INET_ADDRSTRLEN];
inet_ntop(row->Address.Ipv4.sin_family, &row->Address.Ipv4.sin_addr, ip, INET_ADDRSTRLEN);
if (c->subnet == ip) {
c->found = true;
SetEvent(c->hEvent);
}
}
};
HANDLE hNotif;
res = NotifyUnicastIpAddressChange(AF_INET, cb, &ctx, false, &hNotif);
if (res != NO_ERROR) {
qCritical() << "Failed to subscribe to interface change";
return false;
}
auto _guardNotif = qScopeGuard([hNotif](){ CancelMibChangeNotify2(hNotif); });
MIB_UNICASTIPADDRESS_ROW row;
InitializeUnicastIpAddressEntry(&row);
@@ -371,13 +337,7 @@ bool RouterWin::createTun(const QString &dev, const QString &subnet)
return false;
}
res = WaitForSingleObject(hEvent, 10000);
if (res == WAIT_TIMEOUT) {
qCritical() << "Timeout of waiting for IP assignment for " << dev << " device";
return false;
}
return ctx.found;
return true;
}
void RouterWin::suspendWcmSvc(bool suspend)
+12 -16
View File
@@ -27,7 +27,7 @@
#include <sys/socket.h>
#endif
bool Xray::startXray(const QString &cfg)
void Xray::startXray(const QString &cfg)
{
qDebug() << "Xray::startXray()";
@@ -40,38 +40,34 @@ bool Xray::startXray(const QString &cfg)
if (auto err = amnezia_xray_setsockcallback(ctxSockCallback, this); err != nullptr) {
qDebug() << "[xray] sockopt failed: " << err;
amnezia_xray_free(err);
return false;
free(err);
return;
}
amnezia_xray_setloghandler(ctxLogHandler, this);
QByteArray bytes = cfg.toUtf8();
if (auto err = amnezia_xray_configure(bytes.data()); err != nullptr) {
qDebug() << "[xray] configuration failed: " << err;
amnezia_xray_free(err);
return false;
free(err);
return;
}
amnezia_xray_setloghandler(ctxLogHandler, this);
if (auto err = amnezia_xray_start(); err != nullptr) {
qDebug() << "[xray] failed to start: " << err;
amnezia_xray_free(err);
return false;
free(err);
return;
}
return true;
}
bool Xray::stopXray()
void Xray::stopXray()
{
qDebug() << "Xray::stopXray()";
if (auto err = amnezia_xray_stop(); err != nullptr) {
qDebug() << "[xray] failed to stop: " << err;
amnezia_xray_free(err);
return false;
free(err);
return;
}
return true;
}
void Xray::logHandler(char* str)
+2 -2
View File
@@ -12,8 +12,8 @@ public:
return instance;
}
bool startXray(const QString& cfg);
bool stopXray();
void startXray(const QString& cfg);
void stopXray();
private:
static void ctxSockCallback(uintptr_t fd, void* ctx) {