mirror of
https://github.com/amnezia-vpn/amnezia-client.git
synced 2026-06-22 02:01:08 +07:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3e719aac56 | |||
| f87925c819 | |||
| 63c6d7a77b | |||
| 90ef4ec3de | |||
| eb7bfc2815 | |||
| ac77b4ee75 | |||
| fbf652f818 | |||
| bbbf4891e6 | |||
| 20d005d66c | |||
| c81ae2b060 | |||
| 105c42db1c | |||
| 89818ff63d | |||
| 414c422177 | |||
| b39ac8556c | |||
| 5e1742262d | |||
| 5a07a1274f | |||
| 7b8ff1fd6e | |||
| c7221832e0 | |||
| eb7d031c7d | |||
| 3b3a0aaceb | |||
| 01ec79b7d5 | |||
| 3d6339e2dd | |||
| b4d78d865a |
@@ -44,6 +44,13 @@ jobs:
|
||||
submodules: 'true'
|
||||
fetch-depth: 10
|
||||
|
||||
- name: 'Get version from CMakeLists.txt'
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(grep 'set(AMNEZIAVPN_VERSION' CMakeLists.txt | sed -E 's/.*AMNEZIAVPN_VERSION ([0-9]+.[0-9]+.[0-9]+.[0-9]+)\)/\1/')
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
@@ -55,13 +62,13 @@ jobs:
|
||||
bash deploy/build_linux.sh
|
||||
|
||||
- name: 'Pack installer'
|
||||
run: cd deploy && tar -cf AmneziaVPN_Linux_Installer.tar AmneziaVPN_Linux_Installer.bin
|
||||
run: cd deploy && tar -cf AmneziaVPN_Linux_Installer.tar AmneziaVPN_Linux_Installer.bin && zip AmneziaVPN_${VERSION}_linux_x64.tar.zip AmneziaVPN_Linux_Installer.tar
|
||||
|
||||
- name: 'Upload installer artifact'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN_Linux_installer.tar
|
||||
path: deploy/AmneziaVPN_Linux_Installer.tar
|
||||
name: AmneziaVPN_${{ env.VERSION }}_linux_x64.tar.zip
|
||||
path: deploy/AmneziaVPN_${{ env.VERSION }}_linux_x64.tar.zip
|
||||
retention-days: 7
|
||||
|
||||
- name: 'Upload unpacked artifact'
|
||||
@@ -102,6 +109,14 @@ jobs:
|
||||
submodules: 'true'
|
||||
fetch-depth: 10
|
||||
|
||||
- name: 'Get version from CMakeLists.txt'
|
||||
id: get_version
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION=$(grep 'set(AMNEZIAVPN_VERSION' CMakeLists.txt | sed -E 's/.*AMNEZIAVPN_VERSION ([0-9]+.[0-9]+.[0-9]+.[0-9]+)\)/\1/')
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
@@ -132,11 +147,16 @@ jobs:
|
||||
set QIF_BIN_DIR="${{ runner.temp }}\\Qt\\Tools\\QtInstallerFramework\\${{ env.QIF_VERSION }}\\bin"
|
||||
call deploy\\build_windows.bat
|
||||
|
||||
- name: 'Rename Windows installer'
|
||||
shell: cmd
|
||||
run: |
|
||||
copy AmneziaVPN_x${{ env.BUILD_ARCH }}.exe AmneziaVPN_%VERSION%_x64.exe
|
||||
|
||||
- name: 'Upload installer artifact'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN_Windows_installer
|
||||
path: AmneziaVPN_x${{ env.BUILD_ARCH }}.exe
|
||||
name: AmneziaVPN_${{ env.VERSION }}_x64.exe
|
||||
path: AmneziaVPN_${{ env.VERSION }}_x64.exe
|
||||
retention-days: 7
|
||||
|
||||
- name: 'Upload unpacked artifact'
|
||||
@@ -331,7 +351,7 @@ jobs:
|
||||
runs-on: macos-latest
|
||||
|
||||
env:
|
||||
QT_VERSION: 6.8.0
|
||||
QT_VERSION: 6.8.3
|
||||
|
||||
MAC_TEAM_ID: ${{ secrets.MAC_TEAM_ID }}
|
||||
|
||||
@@ -361,7 +381,7 @@ jobs:
|
||||
xcode-version: '16.2.0'
|
||||
|
||||
- name: 'Install Qt'
|
||||
uses: jurplel/install-qt-action@v3
|
||||
uses: jurplel/install-qt-action@v4
|
||||
with:
|
||||
version: ${{ env.QT_VERSION }}
|
||||
host: 'mac'
|
||||
@@ -369,10 +389,15 @@ jobs:
|
||||
arch: 'clang_64'
|
||||
modules: 'qtremoteobjects qt5compat qtshadertools'
|
||||
dir: ${{ runner.temp }}
|
||||
#setup-python: 'true'
|
||||
#set-env: 'true'
|
||||
#extra: '--external 7z --base ${{ env.QT_MIRROR }}'
|
||||
setup-python: 'true'
|
||||
set-env: 'true'
|
||||
extra: '--external 7z --base ${{ env.QT_MIRROR }}'
|
||||
|
||||
aqtversion: '==3.3.0'
|
||||
py7zrversion: '==0.22.*'
|
||||
extra: '--base ${{ env.QT_MIRROR }}'
|
||||
cache: 'true'
|
||||
|
||||
- name: 'Get sources'
|
||||
uses: actions/checkout@v4
|
||||
@@ -380,6 +405,13 @@ jobs:
|
||||
submodules: 'true'
|
||||
fetch-depth: 10
|
||||
|
||||
- name: 'Get version from CMakeLists.txt'
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(grep 'set(AMNEZIAVPN_VERSION' CMakeLists.txt | sed -E 's/.*AMNEZIAVPN_VERSION ([0-9]+.[0-9]+.[0-9]+.[0-9]+)\)/\1/')
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
@@ -388,11 +420,17 @@ jobs:
|
||||
export QT_BIN_DIR="${{ runner.temp }}/Qt/${{ env.QT_VERSION }}/macos/bin"
|
||||
bash deploy/build_macos.sh -n
|
||||
|
||||
- name: 'Pack macOS installer'
|
||||
run: |
|
||||
cd deploy/build/pkg
|
||||
zip -r ../../AmneziaVPN_${VERSION}_macos.zip AmneziaVPN.pkg
|
||||
cd ../../..
|
||||
|
||||
- name: 'Upload installer artifact'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN_MacOS_installer
|
||||
path: deploy/build/pkg/AmneziaVPN.pkg
|
||||
name: AmneziaVPN_${{ env.VERSION }}_macos.zip
|
||||
path: deploy/AmneziaVPN_${{ env.VERSION }}_macos.zip
|
||||
retention-days: 7
|
||||
|
||||
- name: 'Upload unpacked artifact'
|
||||
@@ -551,6 +589,13 @@ jobs:
|
||||
with:
|
||||
submodules: 'true'
|
||||
|
||||
- name: 'Get version from CMakeLists.txt'
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(grep 'set(AMNEZIAVPN_VERSION' CMakeLists.txt | sed -E 's/.*AMNEZIAVPN_VERSION ([0-9]+.[0-9]+.[0-9]+.[0-9]+)\)/\1/')
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
@@ -584,35 +629,44 @@ jobs:
|
||||
shell: bash
|
||||
run: ./deploy/build_android.sh --aab --apk all --build-platform ${{ env.ANDROID_BUILD_PLATFORM }}
|
||||
|
||||
- name: 'Rename Android APKs'
|
||||
run: |
|
||||
cd deploy/build
|
||||
mv AmneziaVPN-x86_64-release.apk AmneziaVPN_${VERSION}_android9+_x86_64.apk
|
||||
mv AmneziaVPN-x86-release.apk AmneziaVPN_${VERSION}_android9+_x86.apk
|
||||
mv AmneziaVPN-arm64-v8a-release.apk AmneziaVPN_${VERSION}_android9+_arm64-v8a.apk
|
||||
mv AmneziaVPN-armeabi-v7a-release.apk AmneziaVPN_${VERSION}_android9+_armeabi-v7a.apk
|
||||
cd ../..
|
||||
|
||||
- name: 'Upload x86_64 apk'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN-android-x86_64
|
||||
path: deploy/build/AmneziaVPN-x86_64-release.apk
|
||||
name: AmneziaVPN_${{ env.VERSION }}_android9+_x86_64.apk
|
||||
path: deploy/build/AmneziaVPN_${{ env.VERSION }}_android9+_x86_64.apk
|
||||
compression-level: 0
|
||||
retention-days: 7
|
||||
|
||||
- name: 'Upload x86 apk'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN-android-x86
|
||||
path: deploy/build/AmneziaVPN-x86-release.apk
|
||||
name: AmneziaVPN_${{ env.VERSION }}_android9+_x86.apk
|
||||
path: deploy/build/AmneziaVPN_${{ env.VERSION }}_android9+_x86.apk
|
||||
compression-level: 0
|
||||
retention-days: 7
|
||||
|
||||
- name: 'Upload arm64-v8a apk'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN-android-arm64-v8a
|
||||
path: deploy/build/AmneziaVPN-arm64-v8a-release.apk
|
||||
name: AmneziaVPN_${{ env.VERSION }}_android9+_arm64-v8a.apk
|
||||
path: deploy/build/AmneziaVPN_${{ env.VERSION }}_android9+_arm64-v8a.apk
|
||||
compression-level: 0
|
||||
retention-days: 7
|
||||
|
||||
- name: 'Upload armeabi-v7a apk'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AmneziaVPN-android-armeabi-v7a
|
||||
path: deploy/build/AmneziaVPN-armeabi-v7a-release.apk
|
||||
name: AmneziaVPN_${{ env.VERSION }}_android9+_armeabi-v7a.apk
|
||||
path: deploy/build/AmneziaVPN_${{ env.VERSION }}_android9+_armeabi-v7a.apk
|
||||
compression-level: 0
|
||||
retention-days: 7
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
|
||||
|
||||
set(PROJECT AmneziaVPN)
|
||||
set(AMNEZIAVPN_VERSION 4.8.11.2)
|
||||
set(AMNEZIAVPN_VERSION 4.8.11.5)
|
||||
|
||||
project(${PROJECT} VERSION ${AMNEZIAVPN_VERSION}
|
||||
DESCRIPTION "AmneziaVPN"
|
||||
@@ -12,7 +12,7 @@ string(TIMESTAMP CURRENT_DATE "%Y-%m-%d")
|
||||
set(RELEASE_DATE "${CURRENT_DATE}")
|
||||
|
||||
set(APP_MAJOR_VERSION ${CMAKE_PROJECT_VERSION_MAJOR}.${CMAKE_PROJECT_VERSION_MINOR}.${CMAKE_PROJECT_VERSION_PATCH})
|
||||
set(APP_ANDROID_VERSION_CODE 2097)
|
||||
set(APP_ANDROID_VERSION_CODE 2100)
|
||||
|
||||
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
|
||||
set(MZ_PLATFORM_NAME "linux")
|
||||
|
||||
@@ -56,7 +56,7 @@ target_include_directories(${PROJECT} PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
|
||||
)
|
||||
|
||||
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
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)
|
||||
@@ -76,6 +76,7 @@ set(AMNEZIAVPN_TS_FILES
|
||||
${CMAKE_CURRENT_LIST_DIR}/translations/amneziavpn_uk_UA.ts
|
||||
${CMAKE_CURRENT_LIST_DIR}/translations/amneziavpn_ur_PK.ts
|
||||
${CMAKE_CURRENT_LIST_DIR}/translations/amneziavpn_hi_IN.ts
|
||||
${CMAKE_CURRENT_LIST_DIR}/translations/amneziavpn_es_ES.ts
|
||||
)
|
||||
|
||||
file(GLOB_RECURSE AMNEZIAVPN_TS_SOURCES *.qrc *.cpp *.h *.ui)
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
#include <QTimer>
|
||||
#include <QTranslator>
|
||||
#include <QEvent>
|
||||
#include <QDir>
|
||||
#include <QSettings>
|
||||
|
||||
#include "logger.h"
|
||||
#include "ui/controllers/pageController.h"
|
||||
@@ -53,16 +55,44 @@ AmneziaApplication::AmneziaApplication(int &argc, char *argv[]) : AMNEZIA_BASE_C
|
||||
|
||||
AmneziaApplication::~AmneziaApplication()
|
||||
{
|
||||
if (m_vpnConnection) {
|
||||
QMetaObject::invokeMethod(m_vpnConnection.get(), "disconnectSlots", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(m_vpnConnection.get(), "disconnectFromVpn", Qt::QueuedConnection);
|
||||
QThread::msleep(2000);
|
||||
}
|
||||
|
||||
m_vpnConnectionThread.requestInterruption();
|
||||
m_vpnConnectionThread.quit();
|
||||
|
||||
if (!m_vpnConnectionThread.wait(3000)) {
|
||||
m_vpnConnectionThread.terminate();
|
||||
m_vpnConnectionThread.wait(500);
|
||||
}
|
||||
|
||||
if (m_engine) {
|
||||
QObject::disconnect(m_engine, 0, 0, 0);
|
||||
delete m_engine;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
namespace {
|
||||
static void clearQtCaches()
|
||||
{
|
||||
const QString cacheRoot = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
|
||||
if (!cacheRoot.isEmpty()) {
|
||||
QDir(cacheRoot + "/QtShaderCache").removeRecursively();
|
||||
QDir(cacheRoot + "/qmlcache").removeRecursively();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void AmneziaApplication::init()
|
||||
{
|
||||
#ifdef Q_OS_ANDROID
|
||||
clearQtCaches();
|
||||
#endif
|
||||
m_engine = new QQmlApplicationEngine;
|
||||
|
||||
const QUrl url(QStringLiteral("qrc:/ui/qml/main2.qml"));
|
||||
|
||||
@@ -28,6 +28,7 @@ set(HEADERS ${HEADERS}
|
||||
${CLIENT_ROOT_DIR}/../common/logger/logger.h
|
||||
${CLIENT_ROOT_DIR}/utils/qmlUtils.h
|
||||
${CLIENT_ROOT_DIR}/core/api/apiUtils.h
|
||||
${CLIENT_ROOT_DIR}/core/osSignalHandler.h
|
||||
)
|
||||
|
||||
# Mozilla headres
|
||||
@@ -36,7 +37,6 @@ set(HEADERS ${HEADERS}
|
||||
${CLIENT_ROOT_DIR}/mozilla/shared/ipaddress.h
|
||||
${CLIENT_ROOT_DIR}/mozilla/shared/leakdetector.h
|
||||
${CLIENT_ROOT_DIR}/mozilla/controllerimpl.h
|
||||
${CLIENT_ROOT_DIR}/mozilla/localsocketcontroller.h
|
||||
)
|
||||
|
||||
if(NOT IOS AND NOT MACOS_NE)
|
||||
@@ -79,6 +79,7 @@ set(SOURCES ${SOURCES}
|
||||
${CLIENT_ROOT_DIR}/../common/logger/logger.cpp
|
||||
${CLIENT_ROOT_DIR}/utils/qmlUtils.cpp
|
||||
${CLIENT_ROOT_DIR}/core/api/apiUtils.cpp
|
||||
${CLIENT_ROOT_DIR}/core/osSignalHandler.cpp
|
||||
)
|
||||
|
||||
# Mozilla sources
|
||||
@@ -86,7 +87,6 @@ set(SOURCES ${SOURCES}
|
||||
${CLIENT_ROOT_DIR}/mozilla/models/server.cpp
|
||||
${CLIENT_ROOT_DIR}/mozilla/shared/ipaddress.cpp
|
||||
${CLIENT_ROOT_DIR}/mozilla/shared/leakdetector.cpp
|
||||
${CLIENT_ROOT_DIR}/mozilla/localsocketcontroller.cpp
|
||||
)
|
||||
|
||||
if(NOT IOS AND NOT MACOS_NE)
|
||||
@@ -175,7 +175,7 @@ if(WIN32)
|
||||
)
|
||||
endif()
|
||||
|
||||
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
if(WIN32 OR (APPLE AND NOT IOS AND NOT MACOS_NE) OR (LINUX AND NOT ANDROID))
|
||||
message("Client desktop build")
|
||||
add_compile_definitions(AMNEZIA_DESKTOP)
|
||||
|
||||
@@ -189,11 +189,13 @@ if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
${CLIENT_ROOT_DIR}/protocols/wireguardprotocol.h
|
||||
${CLIENT_ROOT_DIR}/protocols/xrayprotocol.h
|
||||
${CLIENT_ROOT_DIR}/protocols/awgprotocol.h
|
||||
${CLIENT_ROOT_DIR}/mozilla/localsocketcontroller.h
|
||||
)
|
||||
|
||||
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
|
||||
${CLIENT_ROOT_DIR}/protocols/openvpnovercloakprotocol.cpp
|
||||
@@ -203,3 +205,14 @@ if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
${CLIENT_ROOT_DIR}/protocols/awgprotocol.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
if(APPLE AND MACOS_NE)
|
||||
# Include only the tray notification handler in NE builds
|
||||
set(HEADERS ${HEADERS}
|
||||
${CLIENT_ROOT_DIR}/ui/systemtray_notificationhandler.h
|
||||
)
|
||||
|
||||
set(SOURCES ${SOURCES}
|
||||
${CLIENT_ROOT_DIR}/ui/systemtray_notificationhandler.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -324,7 +324,7 @@ void CoreController::initContainerModelUpdateHandler()
|
||||
&ContainersModel::updateModel);
|
||||
connect(m_serversModel.get(), &ServersModel::gatewayStacksExpanded, this, [this]() {
|
||||
if (m_serversModel->hasServersFromGatewayApi()) {
|
||||
m_apiNewsController->fetchNews();
|
||||
m_apiNewsController->fetchNews(false);
|
||||
}
|
||||
});
|
||||
m_serversModel->resetModel();
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
#include "gatewayController.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
@@ -107,7 +109,8 @@ GatewayController::EncryptedRequestData GatewayController::prepareRequest(const
|
||||
encryptedKeyPayload = rsa.encrypt(QJsonDocument(keyPayload).toJson(), publicKey, RSA_PKCS1_PADDING);
|
||||
EVP_PKEY_free(publicKey);
|
||||
|
||||
encryptedApiPayload = blockCipher.encryptAesBlockCipher(QJsonDocument(apiPayload).toJson(), encRequestData.key, encRequestData.iv, "", encRequestData.salt);
|
||||
encryptedApiPayload = blockCipher.encryptAesBlockCipher(QJsonDocument(apiPayload).toJson(), encRequestData.key, encRequestData.iv,
|
||||
"", encRequestData.salt);
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error when encrypting the request body";
|
||||
@@ -137,7 +140,7 @@ ErrorCode GatewayController::post(const QString &endpoint, const QJsonObject api
|
||||
|
||||
QList<QSslError> sslErrors;
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec();
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
QString replyErrorString = reply->errorString();
|
||||
@@ -146,19 +149,21 @@ ErrorCode GatewayController::post(const QString &endpoint, const QJsonObject api
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
if (sslErrors.isEmpty() && shouldBypassProxy(replyError, encryptedResponseBody, true, encRequestData.key, encRequestData.iv, encRequestData.salt)) {
|
||||
if (sslErrors.isEmpty()
|
||||
&& shouldBypassProxy(replyError, encryptedResponseBody, true, encRequestData.key, encRequestData.iv, encRequestData.salt)) {
|
||||
auto requestFunction = [&encRequestData, &encryptedResponseBody](const QString &url) {
|
||||
encRequestData.request.setUrl(url);
|
||||
return amnApp->networkManager()->post(encRequestData.request, encRequestData.requestBody);
|
||||
};
|
||||
|
||||
auto replyProcessingFunction = [&encryptedResponseBody, &replyErrorString, &replyError, &httpStatusCode, &sslErrors, &encRequestData,
|
||||
this](QNetworkReply *reply, const QList<QSslError> &nestedSslErrors) {
|
||||
auto replyProcessingFunction = [&encryptedResponseBody, &replyErrorString, &replyError, &httpStatusCode, &sslErrors,
|
||||
&encRequestData, this](QNetworkReply *reply, const QList<QSslError> &nestedSslErrors) {
|
||||
encryptedResponseBody = reply->readAll();
|
||||
replyErrorString = reply->errorString();
|
||||
replyError = reply->error();
|
||||
httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (!sslErrors.isEmpty() || shouldBypassProxy(replyError, encryptedResponseBody, true, encRequestData.key, encRequestData.iv, encRequestData.salt)) {
|
||||
if (!sslErrors.isEmpty()
|
||||
|| shouldBypassProxy(replyError, encryptedResponseBody, true, encRequestData.key, encRequestData.iv, encRequestData.salt)) {
|
||||
sslErrors = nestedSslErrors;
|
||||
return false;
|
||||
}
|
||||
@@ -177,7 +182,8 @@ ErrorCode GatewayController::post(const QString &endpoint, const QJsonObject api
|
||||
|
||||
try {
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
responseBody = blockCipher.decryptAesBlockCipher(encryptedResponseBody, encRequestData.key, encRequestData.iv, "", encRequestData.salt);
|
||||
responseBody =
|
||||
blockCipher.decryptAesBlockCipher(encryptedResponseBody, encRequestData.key, encRequestData.iv, "", encRequestData.salt);
|
||||
return ErrorCode::NoError;
|
||||
} catch (...) { // todo change error handling in QSimpleCrypto?
|
||||
Utils::logException();
|
||||
@@ -202,11 +208,9 @@ QFuture<QPair<ErrorCode, QByteArray>> GatewayController::postAsync(const QString
|
||||
|
||||
auto sslErrors = QSharedPointer<QList<QSslError>>::create();
|
||||
|
||||
connect(reply, &QNetworkReply::sslErrors, [sslErrors](const QList<QSslError> &errors) {
|
||||
*sslErrors = errors;
|
||||
});
|
||||
connect(reply, &QNetworkReply::sslErrors, [sslErrors](const QList<QSslError> &errors) { *sslErrors = errors; });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, reply, [=]() {
|
||||
connect(reply, &QNetworkReply::finished, reply, [promise, sslErrors, encRequestData, endpoint, apiPayload, reply, this]() mutable {
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
QString replyErrorString = reply->errorString();
|
||||
auto replyError = reply->error();
|
||||
@@ -214,23 +218,61 @@ QFuture<QPair<ErrorCode, QByteArray>> GatewayController::postAsync(const QString
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
auto errorCode = apiUtils::checkNetworkReplyErrors(*sslErrors, replyErrorString, replyError, httpStatusCode, encryptedResponseBody);
|
||||
if (errorCode) {
|
||||
promise->addResult(qMakePair(errorCode, QByteArray()));
|
||||
promise->finish();
|
||||
return;
|
||||
}
|
||||
auto processResponse = [promise, encRequestData](const QByteArray &ecryptedResponseBody, const QList<QSslError> &sslErrors,
|
||||
QNetworkReply::NetworkError replyError, const QString &replyErrorString,
|
||||
int httpStatusCode) {
|
||||
auto errorCode = apiUtils::checkNetworkReplyErrors(sslErrors, replyErrorString, replyError, httpStatusCode, ecryptedResponseBody);
|
||||
if (errorCode) {
|
||||
promise->addResult(qMakePair(errorCode, QByteArray()));
|
||||
promise->finish();
|
||||
return;
|
||||
}
|
||||
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
try {
|
||||
QByteArray responseBody = blockCipher.decryptAesBlockCipher(encryptedResponseBody, encRequestData.key, encRequestData.iv, "", encRequestData.salt);
|
||||
promise->addResult(qMakePair(ErrorCode::NoError, responseBody));
|
||||
promise->finish();
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error when decrypting the request body";
|
||||
promise->addResult(qMakePair(ErrorCode::ApiConfigDecryptionError, QByteArray()));
|
||||
promise->finish();
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
try {
|
||||
QByteArray responseBody = blockCipher.decryptAesBlockCipher(ecryptedResponseBody, encRequestData.key, encRequestData.iv, "",
|
||||
encRequestData.salt);
|
||||
promise->addResult(qMakePair(ErrorCode::NoError, responseBody));
|
||||
promise->finish();
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error when decrypting the request body";
|
||||
promise->addResult(qMakePair(ErrorCode::ApiConfigDecryptionError, QByteArray()));
|
||||
promise->finish();
|
||||
}
|
||||
};
|
||||
|
||||
if (sslErrors->isEmpty()
|
||||
&& shouldBypassProxy(replyError, encryptedResponseBody, true, encRequestData.key, encRequestData.iv, encRequestData.salt)) {
|
||||
auto serviceType = apiPayload.value(apiDefs::key::serviceType).toString("");
|
||||
auto userCountryCode = apiPayload.value(apiDefs::key::userCountryCode).toString("");
|
||||
|
||||
QStringList baseUrls;
|
||||
if (m_isDevEnvironment) {
|
||||
baseUrls = QString(DEV_S3_ENDPOINT).split(", ");
|
||||
} else {
|
||||
baseUrls = QString(PROD_S3_ENDPOINT).split(", ");
|
||||
}
|
||||
|
||||
QStringList proxyStorageUrls;
|
||||
if (!serviceType.isEmpty()) {
|
||||
for (const auto &baseUrl : baseUrls) {
|
||||
QByteArray path = ("endpoints-" + serviceType + "-" + userCountryCode).toUtf8();
|
||||
proxyStorageUrls.push_back(baseUrl + path.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)
|
||||
+ ".json");
|
||||
}
|
||||
}
|
||||
for (const auto &baseUrl : baseUrls)
|
||||
proxyStorageUrls.push_back(baseUrl + "endpoints.json");
|
||||
|
||||
getProxyUrlsAsync(proxyStorageUrls, 0, [this, encRequestData, endpoint, processResponse](const QStringList &proxyUrls) {
|
||||
getProxyUrlAsync(proxyUrls, 0, [this, encRequestData, endpoint, processResponse](const QString &proxyUrls) {
|
||||
bypassProxyAsync(endpoint, proxyUrls, encRequestData, processResponse);
|
||||
});
|
||||
});
|
||||
|
||||
} else {
|
||||
processResponse(encryptedResponseBody, *sslErrors, replyError, replyErrorString, httpStatusCode);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -273,7 +315,7 @@ QStringList GatewayController::getProxyUrls(const QString &serviceType, const QS
|
||||
|
||||
connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec();
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
if (reply->error() == QNetworkReply::NetworkError::NoError) {
|
||||
auto encryptedResponseBody = reply->readAll();
|
||||
@@ -385,7 +427,7 @@ void GatewayController::bypassProxy(const QString &endpoint, const QString &serv
|
||||
|
||||
QObject::connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec();
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
auto result = replyProcessingFunction(reply, sslErrors);
|
||||
reply->deleteLater();
|
||||
@@ -407,7 +449,7 @@ void GatewayController::bypassProxy(const QString &endpoint, const QString &serv
|
||||
|
||||
connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec();
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
if (reply->error() == QNetworkReply::NetworkError::NoError) {
|
||||
reply->deleteLater();
|
||||
@@ -435,3 +477,134 @@ void GatewayController::bypassProxy(const QString &endpoint, const QString &serv
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GatewayController::getProxyUrlsAsync(const QStringList proxyStorageUrls, const int currentProxyStorageIndex,
|
||||
std::function<void(const QStringList &)> onComplete)
|
||||
{
|
||||
if (currentProxyStorageIndex >= proxyStorageUrls.size()) {
|
||||
onComplete({});
|
||||
return;
|
||||
}
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(m_requestTimeoutMsecs);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setUrl(proxyStorageUrls[currentProxyStorageIndex]);
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->get(request);
|
||||
|
||||
// connect(reply, &QNetworkReply::sslErrors, this, [state](const QList<QSslError> &e) { *(state->sslErrors) = e; });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [this, proxyStorageUrls, currentProxyStorageIndex, onComplete, reply]() {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray encrypted = reply->readAll();
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray responseBody;
|
||||
try {
|
||||
QByteArray key = m_isDevEnvironment ? DEV_AGW_PUBLIC_KEY : PROD_AGW_PUBLIC_KEY;
|
||||
if (!m_isDevEnvironment) {
|
||||
QCryptographicHash hash(QCryptographicHash::Sha512);
|
||||
hash.addData(key);
|
||||
QByteArray h = hash.result().toHex();
|
||||
|
||||
QByteArray decKey = QByteArray::fromHex(h.left(64));
|
||||
QByteArray iv = QByteArray::fromHex(h.mid(64, 32));
|
||||
QByteArray ba = QByteArray::fromBase64(encrypted);
|
||||
|
||||
QSimpleCrypto::QBlockCipher cipher;
|
||||
responseBody = cipher.decryptAesBlockCipher(ba, decKey, iv);
|
||||
} else {
|
||||
responseBody = encrypted;
|
||||
}
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error decrypting payload";
|
||||
QMetaObject::invokeMethod(
|
||||
this, [=]() { getProxyUrlsAsync(proxyStorageUrls, currentProxyStorageIndex + 1, onComplete); }, Qt::QueuedConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonArray endpointsArray = QJsonDocument::fromJson(responseBody).array();
|
||||
QStringList endpoints;
|
||||
for (const QJsonValue &endpoint : endpointsArray)
|
||||
endpoints.push_back(endpoint.toString());
|
||||
|
||||
QStringList shuffled = endpoints;
|
||||
std::random_device randomDevice;
|
||||
std::mt19937 generator(randomDevice());
|
||||
std::shuffle(shuffled.begin(), shuffled.end(), generator);
|
||||
|
||||
onComplete(shuffled);
|
||||
return;
|
||||
}
|
||||
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
qDebug() << httpStatusCode;
|
||||
qDebug() << "go to the next storage endpoint";
|
||||
reply->deleteLater();
|
||||
QMetaObject::invokeMethod(
|
||||
this, [=]() { getProxyUrlsAsync(proxyStorageUrls, currentProxyStorageIndex + 1, onComplete); }, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
|
||||
void GatewayController::getProxyUrlAsync(const QStringList proxyUrls, const int currentProxyIndex, std::function<void(const QString &)> onComplete)
|
||||
{
|
||||
if (currentProxyIndex >= proxyUrls.size()) {
|
||||
onComplete("");
|
||||
return;
|
||||
}
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(1000);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setUrl(proxyUrls[currentProxyIndex] + "lmbd-health");
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->get(request);
|
||||
|
||||
// connect(reply, &QNetworkReply::sslErrors, this, [state](const QList<QSslError> &e) {
|
||||
// *(state->sslErrors) = e;
|
||||
// });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [this, proxyUrls, currentProxyIndex, onComplete, reply]() {
|
||||
reply->deleteLater();
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
m_proxyUrl = proxyUrls[currentProxyIndex];
|
||||
onComplete(m_proxyUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
qDebug() << "go to the next proxy endpoint";
|
||||
QMetaObject::invokeMethod(this, [=]() { getProxyUrlAsync(proxyUrls, currentProxyIndex + 1, onComplete); }, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
|
||||
void GatewayController::bypassProxyAsync(
|
||||
const QString &endpoint, const QString &proxyUrl, EncryptedRequestData encRequestData,
|
||||
std::function<void(const QByteArray &, const QList<QSslError> &, QNetworkReply::NetworkError, const QString &, int)> onComplete)
|
||||
{
|
||||
auto sslErrors = QSharedPointer<QList<QSslError>>::create();
|
||||
if (proxyUrl.isEmpty()) {
|
||||
onComplete(QByteArray(), *sslErrors, QNetworkReply::InternalServerError, "empty proxy url", 0);
|
||||
return;
|
||||
}
|
||||
|
||||
QNetworkRequest request = encRequestData.request;
|
||||
request.setUrl(endpoint.arg(proxyUrl));
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->post(request, encRequestData.requestBody);
|
||||
|
||||
connect(reply, &QNetworkReply::sslErrors, this, [sslErrors](const QList<QSslError> &errors) { *sslErrors = errors; });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [sslErrors, onComplete, reply]() {
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
QString replyErrorString = reply->errorString();
|
||||
auto replyError = reply->error();
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
onComplete(encryptedResponseBody, *sslErrors, replyError, replyErrorString, httpStatusCode);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
#include <QNetworkReply>
|
||||
#include <QObject>
|
||||
#include <QPair>
|
||||
#include <QPromise>
|
||||
#include <QSharedPointer>
|
||||
|
||||
#include "core/defs.h"
|
||||
|
||||
@@ -24,7 +26,8 @@ public:
|
||||
QFuture<QPair<amnezia::ErrorCode, QByteArray>> postAsync(const QString &endpoint, const QJsonObject apiPayload);
|
||||
|
||||
private:
|
||||
struct EncryptedRequestData {
|
||||
struct EncryptedRequestData
|
||||
{
|
||||
QNetworkRequest request;
|
||||
QByteArray requestBody;
|
||||
QByteArray key;
|
||||
@@ -34,7 +37,7 @@ private:
|
||||
};
|
||||
|
||||
EncryptedRequestData prepareRequest(const QString &endpoint, const QJsonObject &apiPayload);
|
||||
|
||||
|
||||
QStringList getProxyUrls(const QString &serviceType, const QString &userCountryCode);
|
||||
bool shouldBypassProxy(const QNetworkReply::NetworkError &replyError, const QByteArray &responseBody, bool checkEncryption,
|
||||
const QByteArray &key = "", const QByteArray &iv = "", const QByteArray &salt = "");
|
||||
@@ -42,6 +45,13 @@ private:
|
||||
std::function<QNetworkReply *(const QString &url)> requestFunction,
|
||||
std::function<bool(QNetworkReply *reply, const QList<QSslError> &sslErrors)> replyProcessingFunction);
|
||||
|
||||
void getProxyUrlsAsync(const QStringList proxyStorageUrls, const int currentProxyStorageIndex,
|
||||
std::function<void(const QStringList &)> onComplete);
|
||||
void getProxyUrlAsync(const QStringList proxyUrls, const int currentProxyIndex, std::function<void(const QString &)> onComplete);
|
||||
void bypassProxyAsync(
|
||||
const QString &endpoint, const QString &proxyUrl, EncryptedRequestData encRequestData,
|
||||
std::function<void(const QByteArray &, const QList<QSslError> &, QNetworkReply::NetworkError, const QString &, int)> onComplete);
|
||||
|
||||
int m_requestTimeoutMsecs;
|
||||
QString m_gatewayEndpoint;
|
||||
bool m_isDevEnvironment = false;
|
||||
|
||||
@@ -18,6 +18,22 @@ bool IpcClient::isSocketConnected() const
|
||||
return m_isSocketConnected;
|
||||
}
|
||||
|
||||
void IpcClient::closeAndResetInstance(bool deleteSelf)
|
||||
{
|
||||
if (m_localSocket)
|
||||
{
|
||||
m_localSocket->disconnectFromServer();
|
||||
m_localSocket->deleteLater();
|
||||
m_localSocket.clear();
|
||||
}
|
||||
m_ipcClient.reset();
|
||||
m_Tun2SocksClient.reset();
|
||||
m_isSocketConnected = false;
|
||||
if (deleteSelf) {
|
||||
m_instance = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
IpcClient *IpcClient::Instance()
|
||||
{
|
||||
return m_instance;
|
||||
@@ -39,6 +55,10 @@ QSharedPointer<IpcProcessTun2SocksReplica> IpcClient::InterfaceTun2Socks()
|
||||
|
||||
bool IpcClient::init(IpcClient *instance)
|
||||
{
|
||||
if (m_instance && m_instance != instance) {
|
||||
m_instance->closeAndResetInstance(false);
|
||||
m_instance->deleteLater();
|
||||
}
|
||||
m_instance = instance;
|
||||
|
||||
Instance()->m_localSocket = new QLocalSocket(Instance());
|
||||
@@ -85,8 +105,9 @@ bool IpcClient::init(IpcClient *instance)
|
||||
}
|
||||
|
||||
qDebug() << "IpcClient::init succeed";
|
||||
instance->m_isSocketConnected = (Instance()->m_ipcClient->isReplicaValid() && Instance()->m_Tun2SocksClient->isReplicaValid());
|
||||
|
||||
return (Instance()->m_ipcClient->isReplicaValid() && Instance()->m_Tun2SocksClient->isReplicaValid());
|
||||
return Instance()->isSocketConnected();
|
||||
}
|
||||
|
||||
QSharedPointer<PrivilegedProcess> IpcClient::CreatePrivilegedProcess()
|
||||
|
||||
@@ -23,6 +23,7 @@ public:
|
||||
static QSharedPointer<PrivilegedProcess> CreatePrivilegedProcess();
|
||||
|
||||
bool isSocketConnected() const;
|
||||
void closeAndResetInstance(bool deleteSelf = false);
|
||||
|
||||
signals:
|
||||
|
||||
|
||||
@@ -170,7 +170,7 @@ int NetworkUtilities::AdapterIndexTo(const QHostAddress& dst) {
|
||||
#ifdef Q_OS_WIN
|
||||
qDebug() << "Getting Current Internet Adapter that routes to"
|
||||
<< dst.toString();
|
||||
quint32_be ipBigEndian;
|
||||
quint32 ipBigEndian;
|
||||
quint32 ip = dst.toIPv4Address();
|
||||
qToBigEndian(ip, &ipBigEndian);
|
||||
_MIB_IPFORWARDROW routeInfo;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "osSignalHandler.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QSocketNotifier>
|
||||
|
||||
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <sys/signalfd.h>
|
||||
#include <unistd.h>
|
||||
#elif defined(Q_OS_MACOS)
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
#include <QMetaObject>
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
static bool initialized = false;
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
static BOOL WINAPI consoleHandler(DWORD signal)
|
||||
{
|
||||
switch (signal) {
|
||||
case CTRL_CLOSE_EVENT:
|
||||
case CTRL_C_EVENT:
|
||||
case CTRL_BREAK_EVENT:
|
||||
case CTRL_LOGOFF_EVENT:
|
||||
case CTRL_SHUTDOWN_EVENT:
|
||||
if (QCoreApplication::instance()) {
|
||||
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
|
||||
}
|
||||
return TRUE;
|
||||
default: return FALSE;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
|
||||
static int signalFd = -1;
|
||||
static QSocketNotifier *socketNotifier = nullptr;
|
||||
|
||||
static void setupUnixSignalHandler()
|
||||
{
|
||||
sigset_t set;
|
||||
sigemptyset(&set);
|
||||
sigaddset(&set, SIGINT);
|
||||
sigaddset(&set, SIGTERM);
|
||||
|
||||
pthread_sigmask(SIG_BLOCK, &set, nullptr);
|
||||
|
||||
signalFd = signalfd(-1, &set, SFD_NONBLOCK | SFD_CLOEXEC);
|
||||
if (signalFd < 0)
|
||||
return;
|
||||
|
||||
socketNotifier = new QSocketNotifier(signalFd, QSocketNotifier::Read, QCoreApplication::instance());
|
||||
|
||||
QObject::connect(socketNotifier, &QSocketNotifier::activated, QCoreApplication::instance(), [](int) {
|
||||
signalfd_siginfo fdsi;
|
||||
::read(signalFd, &fdsi, sizeof(fdsi));
|
||||
|
||||
if (fdsi.ssi_signo == SIGINT || fdsi.ssi_signo == SIGTERM) {
|
||||
QCoreApplication::quit();
|
||||
}
|
||||
});
|
||||
}
|
||||
#elif defined(Q_OS_MACX)
|
||||
static int signalPipe[2] = { -1, -1 };
|
||||
static QSocketNotifier *socketNotifier = nullptr;
|
||||
|
||||
static void macSignalHandler(int)
|
||||
{
|
||||
const char ch = 1;
|
||||
::write(signalPipe[1], &ch, sizeof(ch));
|
||||
}
|
||||
|
||||
static void setupUnixSignalHandler()
|
||||
{
|
||||
if (::pipe(signalPipe) != 0)
|
||||
return;
|
||||
|
||||
::fcntl(signalPipe[0], F_SETFL, O_NONBLOCK);
|
||||
::fcntl(signalPipe[1], F_SETFL, O_NONBLOCK);
|
||||
|
||||
struct sigaction sa {};
|
||||
sa.sa_handler = macSignalHandler;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sa.sa_flags = 0;
|
||||
|
||||
sigaction(SIGINT, &sa, nullptr);
|
||||
sigaction(SIGTERM, &sa, nullptr);
|
||||
|
||||
socketNotifier = new QSocketNotifier(signalPipe[0], QSocketNotifier::Read, QCoreApplication::instance());
|
||||
|
||||
QObject::connect(socketNotifier, &QSocketNotifier::activated, QCoreApplication::instance(), [](int) {
|
||||
char buf[16];
|
||||
::read(signalPipe[0], buf, sizeof(buf));
|
||||
QCoreApplication::quit();
|
||||
});
|
||||
}
|
||||
#endif
|
||||
|
||||
static void cleanupUnixSignalHandler()
|
||||
{
|
||||
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
|
||||
if (socketNotifier) {
|
||||
socketNotifier->setEnabled(false);
|
||||
}
|
||||
|
||||
if (signalFd >= 0) {
|
||||
::close(signalFd);
|
||||
signalFd = -1;
|
||||
}
|
||||
|
||||
#elif defined(Q_OS_MACOS)
|
||||
if (socketNotifier) {
|
||||
socketNotifier->setEnabled(false);
|
||||
}
|
||||
|
||||
if (signalPipe[0] >= 0) {
|
||||
::close(signalPipe[0]);
|
||||
signalPipe[0] = -1;
|
||||
}
|
||||
|
||||
if (signalPipe[1] >= 0) {
|
||||
::close(signalPipe[1]);
|
||||
signalPipe[1] = -1;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
OsSignalHandler::OsSignalHandler(QObject *parent) : QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
void OsSignalHandler::setup()
|
||||
{
|
||||
if (initialized)
|
||||
return;
|
||||
|
||||
initialized = true;
|
||||
|
||||
#if (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) || defined(Q_OS_MACX)
|
||||
setupUnixSignalHandler();
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
SetConsoleCtrlHandler(consoleHandler, TRUE);
|
||||
#endif
|
||||
|
||||
QObject::connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, [] { cleanupUnixSignalHandler(); });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef OSSIGNALHANDLER_H
|
||||
#define OSSIGNALHANDLER_H
|
||||
|
||||
#include <QObject>
|
||||
|
||||
class OsSignalHandler : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
static void setup();
|
||||
|
||||
private:
|
||||
explicit OsSignalHandler(QObject *parent = nullptr);
|
||||
static void handleSignal(int signal);
|
||||
};
|
||||
|
||||
#endif // OSSIGNALHANDLER_H
|
||||
@@ -21,6 +21,7 @@ namespace amnezia::serialization
|
||||
namespace vless
|
||||
{
|
||||
QJsonObject Deserialize(const QString &vless, QString *alias, QString *errMessage);
|
||||
const QString Serialize(const VlessServerObject &server, const QString &alias);
|
||||
} // namespace vless
|
||||
|
||||
namespace ss
|
||||
|
||||
@@ -42,6 +42,25 @@ struct VMessServerObject
|
||||
};
|
||||
|
||||
|
||||
struct VlessServerObject
|
||||
{
|
||||
QString address;
|
||||
QString id; // UUID
|
||||
int port;
|
||||
QString flow = "xtls-rprx-vision";
|
||||
QString encryption = "none";
|
||||
QString network = "tcp";
|
||||
QString security = "reality";
|
||||
QString serverName; // SNI
|
||||
QString publicKey;
|
||||
QString shortId;
|
||||
QString fingerprint = "chrome";
|
||||
QString spiderX = "";
|
||||
JSONSTRUCT_COMPARE(VlessServerObject, address, id, port, flow, encryption)
|
||||
JSONSTRUCT_REGISTER(VlessServerObject, F(address, id, port, flow, encryption, network, security, serverName, publicKey, shortId, fingerprint, spiderX))
|
||||
};
|
||||
|
||||
|
||||
namespace transfer
|
||||
{
|
||||
|
||||
|
||||
@@ -252,5 +252,65 @@ QJsonObject Deserialize(const QString &str, QString *alias, QString *errMessage)
|
||||
root["inbounds"] = QJsonArray { inbound };
|
||||
return root;
|
||||
}
|
||||
} // namespace amnezia::serialization::vless
|
||||
|
||||
const QString Serialize(const VlessServerObject &server, const QString &alias)
|
||||
{
|
||||
|
||||
QUrl url;
|
||||
|
||||
// Set basic URL components
|
||||
url.setScheme("vless");
|
||||
url.setUserInfo(server.id);
|
||||
url.setHost(server.address);
|
||||
url.setPort(server.port);
|
||||
|
||||
QUrlQuery query;
|
||||
|
||||
if (!server.network.isEmpty() && server.network != "tcp") {
|
||||
query.addQueryItem("type", server.network);
|
||||
}
|
||||
|
||||
if (!server.encryption.isEmpty()) {
|
||||
query.addQueryItem("encryption", server.encryption);
|
||||
}
|
||||
|
||||
if (!server.security.isEmpty() && server.security != "none") {
|
||||
query.addQueryItem("security", server.security);
|
||||
}
|
||||
|
||||
if (!server.flow.isEmpty() && (server.security == "xtls" || server.security == "reality")) {
|
||||
query.addQueryItem("flow", server.flow);
|
||||
}
|
||||
|
||||
if (!server.serverName.isEmpty()) {
|
||||
query.addQueryItem("sni", server.serverName);
|
||||
}
|
||||
|
||||
if (server.security == "reality") {
|
||||
if (!server.fingerprint.isEmpty()) {
|
||||
query.addQueryItem("fp", server.fingerprint);
|
||||
}
|
||||
|
||||
if (!server.publicKey.isEmpty()) {
|
||||
query.addQueryItem("pbk", server.publicKey);
|
||||
}
|
||||
|
||||
if (!server.shortId.isEmpty()) {
|
||||
query.addQueryItem("sid", server.shortId);
|
||||
}
|
||||
|
||||
if (!server.spiderX.isEmpty()) {
|
||||
query.addQueryItem("spiderX", server.spiderX);
|
||||
}
|
||||
}
|
||||
|
||||
url.setQuery(query);
|
||||
|
||||
if (!alias.isEmpty()) {
|
||||
url.setFragment(alias);
|
||||
}
|
||||
|
||||
return url.toString(QUrl::ComponentFormattingOption::FullyEncoded);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <QList>
|
||||
#include <QMap>
|
||||
#include <QString>
|
||||
|
||||
#include <QMap>
|
||||
#include "ipaddress.h"
|
||||
|
||||
class QJsonObject;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include <QTimer>
|
||||
|
||||
#include "amnezia_application.h"
|
||||
#include "core/osSignalHandler.h"
|
||||
#include "migrations.h"
|
||||
#include "version.h"
|
||||
|
||||
@@ -44,6 +45,7 @@ int main(int argc, char *argv[])
|
||||
#endif
|
||||
|
||||
AmneziaApplication app(argc, argv);
|
||||
OsSignalHandler::setup();
|
||||
|
||||
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS) && !defined(MACOS_NE)
|
||||
if (isAnotherInstanceRunning()) {
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QHostAddress>
|
||||
@@ -12,12 +15,13 @@
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonValue>
|
||||
#include <QLocalSocket>
|
||||
#include <QObject>
|
||||
#include <QStandardPaths>
|
||||
#include <QTimer>
|
||||
|
||||
#include "ipaddress.h"
|
||||
#include "leakdetector.h"
|
||||
#include "logger.h"
|
||||
#include "models/server.h"
|
||||
#include "daemon/daemonerrors.h"
|
||||
|
||||
#include "protocols/protocols_defs.h"
|
||||
@@ -115,7 +119,6 @@ void LocalSocketController::daemonConnected() {
|
||||
}
|
||||
|
||||
void LocalSocketController::activate(const QJsonObject &rawConfig) {
|
||||
|
||||
QString protocolName = rawConfig.value("protocol").toString();
|
||||
|
||||
int splitTunnelType = rawConfig.value("splitTunnelType").toInt();
|
||||
@@ -132,13 +135,16 @@ void LocalSocketController::activate(const QJsonObject &rawConfig) {
|
||||
// json.insert("hopindex", QJsonValue((double)hop.m_hopindex));
|
||||
json.insert("privateKey", wgConfig.value(amnezia::config_key::client_priv_key));
|
||||
json.insert("deviceIpv4Address", wgConfig.value(amnezia::config_key::client_ip));
|
||||
m_deviceIpv4 = wgConfig.value(amnezia::config_key::client_ip).toString();
|
||||
|
||||
// set up IPv6 unique-local-address, ULA, with "fd00::/8" prefix, not globally routable.
|
||||
// this will be default IPv6 gateway, OS recognizes that IPv6 link is local and switches to IPv4.
|
||||
// Otherwise some OSes (Linux) try IPv6 forever and hang.
|
||||
// https://en.wikipedia.org/wiki/Unique_local_address (RFC 4193)
|
||||
// https://man7.org/linux/man-pages/man5/gai.conf.5.html
|
||||
json.insert("deviceIpv6Address", "fd58:baa6:dead::1"); // simply "dead::1" is globally-routable, don't use it
|
||||
|
||||
// simply "dead::1" is globally-routable, don't use it
|
||||
json.insert("deviceIpv6Address", "fd58:baa6:dead::1");
|
||||
|
||||
json.insert("serverPublicKey", wgConfig.value(amnezia::config_key::server_pub_key));
|
||||
json.insert("serverPskKey", wgConfig.value(amnezia::config_key::psk_key));
|
||||
@@ -220,7 +226,6 @@ void LocalSocketController::activate(const QJsonObject &rawConfig) {
|
||||
|
||||
json.insert("allowedIPAddressRanges", jsAllowedIPAddesses);
|
||||
|
||||
|
||||
QJsonArray jsExcludedAddresses;
|
||||
jsExcludedAddresses.append(wgConfig.value(amnezia::config_key::hostName));
|
||||
if (splitTunnelType == 2) {
|
||||
@@ -449,6 +454,7 @@ void LocalSocketController::parseCommand(const QByteArray& command) {
|
||||
}
|
||||
|
||||
if (type == "status") {
|
||||
|
||||
QJsonValue serverIpv4Gateway = obj.value("serverIpv4Gateway");
|
||||
if (!serverIpv4Gateway.isString()) {
|
||||
logger.error() << "Unexpected serverIpv4Gateway value";
|
||||
@@ -493,6 +499,11 @@ void LocalSocketController::parseCommand(const QByteArray& command) {
|
||||
|
||||
logger.debug() << "Handshake completed with:"
|
||||
<< pubkey.toString();
|
||||
|
||||
checkStatus();
|
||||
|
||||
emit statusUpdated("", m_deviceIpv4, 0, 0);
|
||||
|
||||
emit connected(pubkey.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
#include "controllerimpl.h"
|
||||
|
||||
|
||||
class QJsonObject;
|
||||
|
||||
class LocalSocketController final : public ControllerImpl {
|
||||
@@ -58,6 +59,7 @@ class LocalSocketController final : public ControllerImpl {
|
||||
|
||||
QByteArray m_buffer;
|
||||
|
||||
QString m_deviceIpv4;
|
||||
std::function<void(const QString&)> m_logCallback = nullptr;
|
||||
|
||||
QTimer m_initializingTimer;
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
#include "logger.h"
|
||||
//#include "mozillavpn.h"
|
||||
#include "networkwatcherimpl.h"
|
||||
#include "platforms/dummy/dummynetworkwatcher.h"
|
||||
//#include "settingsholder.h"
|
||||
|
||||
#ifdef MZ_WINDOWS
|
||||
@@ -51,7 +50,7 @@ NetworkWatcher::NetworkWatcher() { MZ_COUNT_CTOR(NetworkWatcher); }
|
||||
NetworkWatcher::~NetworkWatcher() { MZ_COUNT_DTOR(NetworkWatcher); }
|
||||
|
||||
void NetworkWatcher::initialize() {
|
||||
logger.debug() << "Initialize";
|
||||
logger.debug() << "Initialize NetworkWatcher";
|
||||
|
||||
#if defined(MZ_WINDOWS)
|
||||
m_impl = new WindowsNetworkWatcher(this);
|
||||
@@ -69,59 +68,45 @@ void NetworkWatcher::initialize() {
|
||||
m_impl = new DummyNetworkWatcher(this);
|
||||
#endif
|
||||
|
||||
|
||||
connect(m_impl, &NetworkWatcherImpl::unsecuredNetwork, this,
|
||||
&NetworkWatcher::unsecuredNetwork);
|
||||
connect(m_impl, &NetworkWatcherImpl::networkChanged, this,
|
||||
&NetworkWatcher::networkChange);
|
||||
|
||||
connect(m_impl, &NetworkWatcherImpl::sleepMode, this,
|
||||
&NetworkWatcher::onSleepMode);
|
||||
m_impl->initialize();
|
||||
|
||||
|
||||
// TODO: IMPL FOR AMNEZIA
|
||||
#if 0
|
||||
SettingsHolder* settingsHolder = SettingsHolder::instance();
|
||||
Q_ASSERT(settingsHolder);
|
||||
|
||||
m_active = settingsHolder->unsecuredNetworkAlert() ||
|
||||
settingsHolder->captivePortalAlert();
|
||||
m_reportUnsecuredNetwork = settingsHolder->unsecuredNetworkAlert();
|
||||
if (m_active) {
|
||||
// Enable sleep/wake monitoring for VPN auto-reconnection
|
||||
logger.debug() << "Starting NetworkWatcher for sleep/wake monitoring";
|
||||
logger.debug() << "About to call m_impl->start()";
|
||||
try {
|
||||
m_impl->start();
|
||||
logger.debug() << "m_impl->start() completed successfully";
|
||||
} catch (const std::exception& e) {
|
||||
logger.error() << "Exception in m_impl->start():" << e.what();
|
||||
} catch (...) {
|
||||
logger.error() << "Unknown exception in m_impl->start()";
|
||||
}
|
||||
|
||||
connect(settingsHolder, &SettingsHolder::unsecuredNetworkAlertChanged, this,
|
||||
&NetworkWatcher::settingsChanged);
|
||||
connect(settingsHolder, &SettingsHolder::captivePortalAlertChanged, this,
|
||||
&NetworkWatcher::settingsChanged);
|
||||
|
||||
#endif
|
||||
m_active = true;
|
||||
m_reportUnsecuredNetwork = false; // Disable unsecured network alerts for Amnezia
|
||||
}
|
||||
|
||||
void NetworkWatcher::settingsChanged() {
|
||||
// TODO: IMPL FOR AMNEZIA
|
||||
#if 0
|
||||
SettingsHolder* settingsHolder = SettingsHolder::instance();
|
||||
m_active = settingsHolder->unsecuredNetworkAlert() ||
|
||||
settingsHolder->captivePortalAlert();
|
||||
m_reportUnsecuredNetwork = settingsHolder->unsecuredNetworkAlert();
|
||||
// For Amnezia: Keep NetworkWatcher always active for sleep/wake monitoring
|
||||
logger.debug() << "NetworkWatcher settings changed - keeping sleep monitoring active";
|
||||
}
|
||||
|
||||
if (m_active) {
|
||||
logger.debug()
|
||||
<< "Starting Network Watcher; Reporting of Unsecured Networks: "
|
||||
<< m_reportUnsecuredNetwork;
|
||||
m_impl->start();
|
||||
} else {
|
||||
logger.debug() << "Stopping Network Watcher";
|
||||
m_impl->stop();
|
||||
}
|
||||
#endif
|
||||
void NetworkWatcher::onSleepMode()
|
||||
{
|
||||
logger.debug() << "Resumed from sleep mode";
|
||||
emit sleepMode();
|
||||
}
|
||||
|
||||
void NetworkWatcher::unsecuredNetwork(const QString& networkName,
|
||||
const QString& networkId) {
|
||||
logger.debug() << "Unsecured network:" << logger.sensitive(networkName)
|
||||
<< "id:" << logger.sensitive(networkId);
|
||||
|
||||
#ifndef UNIT_TEST
|
||||
if (!m_reportUnsecuredNetwork) {
|
||||
logger.debug() << "Disabled. Ignoring unsecured network";
|
||||
|
||||
@@ -29,10 +29,13 @@ public:
|
||||
// false to restore.
|
||||
void simulateDisconnection(bool simulatedDisconnection);
|
||||
|
||||
void onSleepMode();
|
||||
|
||||
QNetworkInformation::Reachability getReachability();
|
||||
|
||||
signals:
|
||||
void networkChange();
|
||||
void sleepMode();
|
||||
|
||||
private:
|
||||
void settingsChanged();
|
||||
|
||||
@@ -41,6 +41,8 @@ signals:
|
||||
// TODO: Only windows-networkwatcher has this, the other plattforms should
|
||||
// too.
|
||||
void networkChanged(QString newBSSID);
|
||||
void sleepMode();
|
||||
|
||||
|
||||
private:
|
||||
bool m_active = false;
|
||||
|
||||
@@ -41,6 +41,7 @@ void PingHelper::start(const QString& serverIpv4Gateway,
|
||||
|
||||
m_gateway = QHostAddress(serverIpv4Gateway);
|
||||
m_source = QHostAddress(deviceIpv4Address.section('/', 0, 0));
|
||||
|
||||
m_pingSender = PingSenderFactory::create(m_source, this);
|
||||
|
||||
// Some platforms require root access to send and receive ICMP pings. If
|
||||
@@ -53,8 +54,10 @@ void PingHelper::start(const QString& serverIpv4Gateway,
|
||||
|
||||
connect(m_pingSender, &PingSender::recvPing, this, &PingHelper::pingReceived,
|
||||
Qt::QueuedConnection);
|
||||
connect(m_pingSender, &PingSender::criticalPingError, this,
|
||||
[]() { logger.info() << "Encountered Unrecoverable ping error"; });
|
||||
connect(m_pingSender, &PingSender::criticalPingError, this, [this]() {
|
||||
logger.info() << "Encountered Unrecoverable ping error";
|
||||
emit connectionLose();
|
||||
});
|
||||
|
||||
// Reset the ping statistics
|
||||
m_sequence = 0;
|
||||
|
||||
@@ -33,6 +33,8 @@ class PingHelper final : public QObject {
|
||||
|
||||
signals:
|
||||
void pingSentAndReceived(qint64 msec);
|
||||
void connectionLose();
|
||||
|
||||
|
||||
private:
|
||||
void nextPing();
|
||||
|
||||
@@ -5,27 +5,26 @@
|
||||
#include "pingsenderfactory.h"
|
||||
|
||||
#if defined(MZ_LINUX) || defined(MZ_ANDROID)
|
||||
//# include "platforms/linux/linuxpingsender.h"
|
||||
# include "platforms/linux/linuxpingsender.h"
|
||||
#elif defined(MZ_MACOS) || defined(MZ_IOS)
|
||||
# include "platforms/macos/macospingsender.h"
|
||||
# include "platforms/macos/macospingsender.h"
|
||||
#elif defined(MZ_WINDOWS)
|
||||
# include "platforms/windows/windowspingsender.h"
|
||||
#elif defined(MZ_DUMMY) || defined(UNIT_TEST)
|
||||
# include "platforms/dummy/dummypingsender.h"
|
||||
# include "platforms/windows/windowspingsender.h"
|
||||
#elif defined(MZ_WASM) || defined(UNIT_TEST)
|
||||
# include "platforms/dummy/dummypingsender.h"
|
||||
#else
|
||||
# error "Unsupported platform"
|
||||
# error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
PingSender* PingSenderFactory::create(const QHostAddress& source,
|
||||
QObject* parent) {
|
||||
#if defined(MZ_LINUX) || defined(MZ_ANDROID)
|
||||
return nullptr;
|
||||
// return new LinuxPingSender(source, parent);
|
||||
return new LinuxPingSender(source, parent);
|
||||
#elif defined(MZ_MACOS) || defined(MZ_IOS)
|
||||
return new MacOSPingSender(source, parent);
|
||||
return new MacOSPingSender(source, parent);
|
||||
#elif defined(MZ_WINDOWS)
|
||||
return new WindowsPingSender(source, parent);
|
||||
return new WindowsPingSender(source, parent);
|
||||
#else
|
||||
return new DummyPingSender(source, parent);
|
||||
return new DummyPingSender(source, parent);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -10,9 +10,10 @@ class QHostAddress;
|
||||
class QObject;
|
||||
|
||||
class PingSenderFactory final {
|
||||
public:
|
||||
PingSenderFactory() = delete;
|
||||
static PingSender* create(const QHostAddress& source, QObject* parent);
|
||||
public:
|
||||
PingSenderFactory() = delete;
|
||||
static PingSender* create(const QHostAddress& source, QObject* parent);
|
||||
};
|
||||
|
||||
|
||||
#endif // PINGSENDERFACTORY_H
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
import WireGuardKitGo
|
||||
|
||||
enum XrayErrors: Error {
|
||||
case noXrayConfig
|
||||
|
||||
@@ -34,6 +34,9 @@ void IOSNetworkWatcher::initialize() {
|
||||
});
|
||||
nw_path_monitor_start(m_networkMonitor);
|
||||
|
||||
// Call start() to initialize sleep/wake monitoring (will call MacOSNetworkWatcher::start() if this is macOS)
|
||||
this->start();
|
||||
|
||||
//TODO IMPL FOR AMNEZIA
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ void LinuxNetworkWatcher::initialize() {
|
||||
connect(m_worker, &LinuxNetworkWatcherWorker::unsecuredNetwork, this,
|
||||
&LinuxNetworkWatcher::unsecuredNetwork);
|
||||
|
||||
connect(m_worker, &LinuxNetworkWatcherWorker::sleepMode, this,
|
||||
&NetworkWatcherImpl::sleepMode);
|
||||
|
||||
// Let's wait a few seconds to allow the UI to be fully loaded and shown.
|
||||
// This is not strictly needed, but it's better for user experience because
|
||||
// it makes the UI faster to appear, plus it gives a bit of delay between the
|
||||
|
||||
@@ -33,7 +33,21 @@
|
||||
#define NM_802_11_AP_SEC_WEAK_CRYPTO \
|
||||
(NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104)
|
||||
|
||||
|
||||
enum NMState {
|
||||
NM_STATE_UNKNOWN = 0,
|
||||
NM_STATE_ASLEEP = 10,
|
||||
NM_STATE_DISCONNECTED = 20,
|
||||
NM_STATE_DISCONNECTING = 30,
|
||||
NM_STATE_CONNECTING = 40,
|
||||
NM_STATE_CONNECTED_LOCAL = 50,
|
||||
NM_STATE_CONNECTED_SITE = 60,
|
||||
NM_STATE_CONNECTED_GLOBAL = 70
|
||||
};
|
||||
|
||||
|
||||
constexpr const char* DBUS_NETWORKMANAGER = "org.freedesktop.NetworkManager";
|
||||
constexpr const char* DBUS_NETWORKMANAGER_PATH = "/org/freedesktop/NetworkManager";
|
||||
|
||||
namespace {
|
||||
Logger logger("LinuxNetworkWatcherWorker");
|
||||
@@ -73,7 +87,7 @@ void LinuxNetworkWatcherWorker::initialize() {
|
||||
// documentation:
|
||||
// https://developer.gnome.org/NetworkManager/stable/gdbus-org.freedesktop.NetworkManager.html
|
||||
|
||||
QDBusInterface nm(DBUS_NETWORKMANAGER, "/org/freedesktop/NetworkManager",
|
||||
QDBusInterface nm(DBUS_NETWORKMANAGER, DBUS_NETWORKMANAGER_PATH,
|
||||
DBUS_NETWORKMANAGER, QDBusConnection::systemBus());
|
||||
if (!nm.isValid()) {
|
||||
logger.error()
|
||||
@@ -108,6 +122,12 @@ void LinuxNetworkWatcherWorker::initialize() {
|
||||
SLOT(propertyChanged(QString, QVariantMap, QStringList)));
|
||||
}
|
||||
|
||||
QDBusConnection::systemBus().connect(DBUS_NETWORKMANAGER,
|
||||
DBUS_NETWORKMANAGER_PATH,
|
||||
DBUS_NETWORKMANAGER,
|
||||
"StateChanged",
|
||||
this, SLOT(NMStateChanged(quint32)));
|
||||
|
||||
if (m_devicePaths.isEmpty()) {
|
||||
logger.warning() << "No wifi devices found";
|
||||
return;
|
||||
@@ -173,5 +193,16 @@ void LinuxNetworkWatcherWorker::checkDevices() {
|
||||
emit unsecuredNetwork(ssid, bssid);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void LinuxNetworkWatcherWorker::NMStateChanged(quint32 state)
|
||||
{
|
||||
if (state == NM_STATE_ASLEEP) {
|
||||
emit sleepMode();
|
||||
}
|
||||
|
||||
logger.debug() << "NMStateChanged " << state;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ class LinuxNetworkWatcherWorker final : public QObject {
|
||||
|
||||
signals:
|
||||
void unsecuredNetwork(const QString& networkName, const QString& networkId);
|
||||
void sleepMode();
|
||||
|
||||
public slots:
|
||||
void initialize();
|
||||
@@ -30,6 +31,7 @@ class LinuxNetworkWatcherWorker final : public QObject {
|
||||
private slots:
|
||||
void propertyChanged(QString interface, QVariantMap properties,
|
||||
QStringList list);
|
||||
void NMStateChanged(quint32 state);
|
||||
|
||||
private:
|
||||
// We collect the list of DBus wifi network device paths during the
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
#include "linuxpingsender.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <linux/filter.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/ip.h>
|
||||
#include <netinet/ip_icmp.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <QSocketNotifier>
|
||||
#include <QtEndian>
|
||||
|
||||
#include "leakdetector.h"
|
||||
#include "logger.h"
|
||||
#include "qhostaddress.h"
|
||||
|
||||
namespace {
|
||||
Logger logger("LinuxPingSender");
|
||||
}
|
||||
|
||||
int LinuxPingSender::createSocket() {
|
||||
// Try creating an ICMP socket. This would be the ideal choice, but it can
|
||||
// fail depending on the kernel config (see: sys.net.ipv4.ping_group_range)
|
||||
m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
|
||||
if (m_socket >= 0) {
|
||||
m_ident = 0;
|
||||
return m_socket;
|
||||
}
|
||||
if ((errno != EPERM) && (errno != EACCES)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// As a fallback, create a raw socket, which requires root permissions
|
||||
// or CAP_NET_RAW to be granted to the VPN client.
|
||||
m_socket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
|
||||
if (m_socket < 0) {
|
||||
return -1;
|
||||
}
|
||||
m_ident = getpid() & 0xffff;
|
||||
|
||||
// Attach a BPF filter to discard everything but replies to our echo.
|
||||
struct sock_filter bpf_prog[] = {
|
||||
BPF_STMT(BPF_LDX | BPF_B | BPF_MSH, 0), /* Skip IP header. */
|
||||
BPF_STMT(BPF_LD | BPF_H | BPF_IND, 4), /* Load icmp echo ident */
|
||||
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, m_ident, 1, 0), /* Ours? */
|
||||
BPF_STMT(BPF_RET | BPF_K, 0), /* Unexpected identifier. Reject. */
|
||||
BPF_STMT(BPF_LD | BPF_B | BPF_IND, 0), /* Load icmp type */
|
||||
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP_ECHOREPLY, 1, 0), /* Echo? */
|
||||
BPF_STMT(BPF_RET | BPF_K, 0), /* Unexpected type. Reject. */
|
||||
BPF_STMT(BPF_RET | BPF_K, ~0U), /* Packet passes the filter. */
|
||||
};
|
||||
struct sock_fprog filter = {
|
||||
.len = sizeof(bpf_prog) / sizeof(struct sock_filter),
|
||||
.filter = bpf_prog,
|
||||
};
|
||||
setsockopt(m_socket, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter));
|
||||
|
||||
return m_socket;
|
||||
}
|
||||
|
||||
LinuxPingSender::LinuxPingSender(const QHostAddress& source, QObject* parent)
|
||||
: PingSender(parent) {
|
||||
MZ_COUNT_CTOR(LinuxPingSender);
|
||||
|
||||
logger.debug() << "LinuxPingSender(" + logger.sensitive(source.toString()) +
|
||||
") created";
|
||||
|
||||
m_socket = createSocket();
|
||||
if (m_socket < 0) {
|
||||
logger.error() << "Socket creation error: " << strerror(errno);
|
||||
return;
|
||||
}
|
||||
|
||||
quint32 ipv4addr = INADDR_ANY;
|
||||
if (!source.isNull()) {
|
||||
ipv4addr = source.toIPv4Address();
|
||||
}
|
||||
struct sockaddr_in addr;
|
||||
memset(&addr, 0, sizeof addr);
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = qToBigEndian<quint32>(ipv4addr);
|
||||
|
||||
if (bind(m_socket, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
|
||||
close(m_socket);
|
||||
m_socket = -1;
|
||||
logger.error() << "bind error:" << strerror(errno);
|
||||
return;
|
||||
}
|
||||
|
||||
m_notifier = new QSocketNotifier(m_socket, QSocketNotifier::Read, this);
|
||||
if (m_ident) {
|
||||
connect(m_notifier, &QSocketNotifier::activated, this,
|
||||
&LinuxPingSender::rawSocketReady);
|
||||
} else {
|
||||
connect(m_notifier, &QSocketNotifier::activated, this,
|
||||
&LinuxPingSender::icmpSocketReady);
|
||||
}
|
||||
}
|
||||
|
||||
LinuxPingSender::~LinuxPingSender() {
|
||||
MZ_COUNT_DTOR(LinuxPingSender);
|
||||
if (m_socket >= 0) {
|
||||
close(m_socket);
|
||||
}
|
||||
}
|
||||
|
||||
void LinuxPingSender::sendPing(const QHostAddress& dest, quint16 sequence) {
|
||||
quint32 ipv4dest = dest.toIPv4Address();
|
||||
struct sockaddr_in addr;
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = qToBigEndian<quint32>(ipv4dest);
|
||||
|
||||
struct icmphdr packet;
|
||||
memset(&packet, 0, sizeof(packet));
|
||||
packet.type = ICMP_ECHO;
|
||||
packet.un.echo.id = htons(m_ident);
|
||||
packet.un.echo.sequence = htons(sequence);
|
||||
packet.checksum = inetChecksum(&packet, sizeof(packet));
|
||||
|
||||
int rc = sendto(m_socket, &packet, sizeof(packet), 0, (struct sockaddr*)&addr,
|
||||
sizeof(addr));
|
||||
if (rc < 0) {
|
||||
logger.error() << "failed to send:" << strerror(errno);
|
||||
if (errno == ENETUNREACH) {
|
||||
emit criticalPingError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void LinuxPingSender::icmpSocketReady() {
|
||||
socklen_t slen = 0;
|
||||
unsigned char data[2048];
|
||||
int rc = recvfrom(m_socket, data, sizeof(data), MSG_DONTWAIT, NULL, &slen);
|
||||
if (rc <= 0) {
|
||||
logger.error() << "recvfrom failed:" << strerror(errno);
|
||||
return;
|
||||
}
|
||||
|
||||
struct icmphdr packet;
|
||||
if (rc >= (int)sizeof(packet)) {
|
||||
memcpy(&packet, data, sizeof(packet));
|
||||
if (packet.type == ICMP_ECHOREPLY) {
|
||||
emit recvPing(htons(packet.un.echo.sequence));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void LinuxPingSender::rawSocketReady() {
|
||||
socklen_t slen = 0;
|
||||
unsigned char data[2048];
|
||||
int rc = recvfrom(m_socket, data, sizeof(data), MSG_DONTWAIT, NULL, &slen);
|
||||
if (rc <= 0) {
|
||||
logger.error() << "recvfrom failed:" << strerror(errno);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the IP header
|
||||
const struct iphdr* ip = (struct iphdr*)data;
|
||||
int iphdrlen = ip->ihl * 4;
|
||||
if (rc < iphdrlen || iphdrlen < (int)sizeof(struct iphdr)) {
|
||||
logger.error() << "malformed IP packet:" << strerror(errno);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the ICMP packet
|
||||
struct icmphdr packet;
|
||||
if (inetChecksum(data + iphdrlen, rc - iphdrlen) != 0) {
|
||||
logger.warning() << "invalid checksum";
|
||||
return;
|
||||
}
|
||||
if (rc >= (iphdrlen + (int)sizeof(packet))) {
|
||||
memcpy(&packet, data + iphdrlen, sizeof(packet));
|
||||
quint16 id = htons(m_ident);
|
||||
if ((packet.type == ICMP_ECHOREPLY) && (packet.un.echo.id == id)) {
|
||||
emit recvPing(htons(packet.un.echo.sequence));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
#ifndef LINUXPINGSENDER_H
|
||||
#define LINUXPINGSENDER_H
|
||||
|
||||
#include <QObject>
|
||||
|
||||
#include "../../mozilla/pingsender.h"
|
||||
|
||||
class QSocketNotifier;
|
||||
|
||||
class LinuxPingSender final : public PingSender {
|
||||
Q_OBJECT
|
||||
Q_DISABLE_COPY_MOVE(LinuxPingSender)
|
||||
|
||||
public:
|
||||
LinuxPingSender(const QHostAddress& source, QObject* parent = nullptr);
|
||||
~LinuxPingSender();
|
||||
|
||||
bool isValid() override { return (m_socket >= 0); };
|
||||
|
||||
void sendPing(const QHostAddress& dest, quint16 sequence) override;
|
||||
|
||||
private:
|
||||
int createSocket();
|
||||
|
||||
private slots:
|
||||
void rawSocketReady();
|
||||
void icmpSocketReady();
|
||||
|
||||
private:
|
||||
QSocketNotifier* m_notifier = nullptr;
|
||||
int m_socket = -1;
|
||||
quint16 m_ident = 0;
|
||||
};
|
||||
|
||||
#endif // LINUXPINGSENDER_H
|
||||
@@ -10,8 +10,31 @@
|
||||
#include "../ios/iosnetworkwatcher.h"
|
||||
#include "networkwatcherimpl.h"
|
||||
|
||||
#include <IOKit/pwr_mgt/IOPMLib.h>
|
||||
#include <IOKit/IOMessage.h>
|
||||
|
||||
|
||||
class QString;
|
||||
|
||||
// Inspired by https://ladydebug.com/blog/2020/05/21/programmatically-capture-energy-saver-event-on-mac/
|
||||
class PowerNotificationsListener
|
||||
{
|
||||
public:
|
||||
PowerNotificationsListener(class MacOSNetworkWatcher* watcher) : m_watcher(watcher) {}
|
||||
void registerForNotifications();
|
||||
void cleanup();
|
||||
|
||||
private:
|
||||
static void sleepWakeupCallBack(void *refParam, io_service_t service, natural_t messageType, void *messageArgument);
|
||||
|
||||
private:
|
||||
class MacOSNetworkWatcher* m_watcher = nullptr;
|
||||
IONotificationPortRef notifyPortRef = nullptr; // notification port allocated by IORegisterForSystemPower
|
||||
io_object_t notifierObj = IO_OBJECT_NULL; // notifier object, used to deregister later
|
||||
io_connect_t rootPowerDomain = IO_OBJECT_NULL; // a reference to the Root Power Domain IOService
|
||||
};
|
||||
|
||||
|
||||
class MacOSNetworkWatcher final : public IOSNetworkWatcher {
|
||||
public:
|
||||
MacOSNetworkWatcher(QObject* parent);
|
||||
@@ -25,6 +48,7 @@ class MacOSNetworkWatcher final : public IOSNetworkWatcher {
|
||||
|
||||
private:
|
||||
void* m_delegate = nullptr;
|
||||
PowerNotificationsListener m_powerlistener;
|
||||
};
|
||||
|
||||
#endif // MACOSNETWORKWATCHER_H
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
#include "leakdetector.h"
|
||||
#include "logger.h"
|
||||
|
||||
#include <QProcess>
|
||||
#include <QMetaObject>
|
||||
#include <pthread.h>
|
||||
#include <iostream>
|
||||
|
||||
#import <CoreWLAN/CoreWLAN.h>
|
||||
#import <Network/Network.h>
|
||||
|
||||
@@ -13,6 +18,37 @@ namespace {
|
||||
Logger logger("MacOSNetworkWatcher");
|
||||
}
|
||||
|
||||
// Global variables for CFRunLoop thread
|
||||
static pthread_t g_powerThread;
|
||||
static CFRunLoopRef g_powerRunLoop = nullptr;
|
||||
static bool g_shouldStopPowerThread = false;
|
||||
static PowerNotificationsListener* g_powerListener = nullptr;
|
||||
|
||||
// Thread function for dedicated CFRunLoop
|
||||
void* powerMonitoringThread(void* arg) {
|
||||
logger.debug() << "Power monitoring thread started";
|
||||
|
||||
PowerNotificationsListener* listener = static_cast<PowerNotificationsListener*>(arg);
|
||||
|
||||
// Get the runloop for this thread
|
||||
g_powerRunLoop = CFRunLoopGetCurrent();
|
||||
|
||||
// Register for power notifications in this thread
|
||||
listener->registerForNotifications();
|
||||
|
||||
// Run the CFRunLoop - this will block until CFRunLoopStop is called
|
||||
while (!g_shouldStopPowerThread) {
|
||||
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, true);
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
listener->cleanup();
|
||||
g_powerRunLoop = nullptr;
|
||||
|
||||
logger.debug() << "Power monitoring thread finished";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@interface MacOSNetworkWatcherDelegate : NSObject <CWEventDelegate> {
|
||||
MacOSNetworkWatcher* m_watcher;
|
||||
}
|
||||
@@ -33,17 +69,145 @@ Logger logger("MacOSNetworkWatcher");
|
||||
|
||||
if (m_watcher) {
|
||||
m_watcher->checkInterface();
|
||||
// Emit networkChanged signal when BSSID changes
|
||||
emit m_watcher->networkChanged(QString::fromNSString(interfaceName));
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
MacOSNetworkWatcher::MacOSNetworkWatcher(QObject* parent) : IOSNetworkWatcher(parent) {
|
||||
void PowerNotificationsListener::registerForNotifications()
|
||||
{
|
||||
logger.debug() << "Registering for system power notifications in dedicated thread";
|
||||
|
||||
rootPowerDomain = IORegisterForSystemPower(this, ¬ifyPortRef, sleepWakeupCallBack, ¬ifierObj);
|
||||
if (rootPowerDomain == IO_OBJECT_NULL) {
|
||||
logger.error() << "Failed to register for system power notifications!";
|
||||
return;
|
||||
}
|
||||
|
||||
// Add the notification port to the current runloop (dedicated thread)
|
||||
CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);
|
||||
logger.debug() << "Power notifications registered successfully";
|
||||
}
|
||||
|
||||
void PowerNotificationsListener::cleanup()
|
||||
{
|
||||
if (notifyPortRef != nullptr) {
|
||||
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes);
|
||||
IONotificationPortDestroy(notifyPortRef);
|
||||
notifyPortRef = nullptr;
|
||||
}
|
||||
|
||||
if (notifierObj != IO_OBJECT_NULL) {
|
||||
IODeregisterForSystemPower(¬ifierObj);
|
||||
notifierObj = IO_OBJECT_NULL;
|
||||
}
|
||||
|
||||
if (rootPowerDomain != IO_OBJECT_NULL) {
|
||||
IOServiceClose(rootPowerDomain);
|
||||
rootPowerDomain = IO_OBJECT_NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void PowerNotificationsListener::sleepWakeupCallBack(void *refParam, io_service_t service, natural_t messageType, void *messageArgument)
|
||||
{
|
||||
Q_UNUSED(service)
|
||||
|
||||
auto listener = static_cast<PowerNotificationsListener *>(refParam);
|
||||
|
||||
logger.debug() << "Power callback received, messageType:" << messageType;
|
||||
switch (messageType) {
|
||||
case kIOMessageCanSystemSleep:
|
||||
/* Idle sleep is about to kick in. This message will not be sent for forced sleep.
|
||||
* Applications have a chance to prevent sleep by calling IOCancelPowerChange.
|
||||
* Most applications should not prevent idle sleep. Power Management waits up to
|
||||
* 30 seconds for you to either allow or deny idle sleep. If you don’t acknowledge
|
||||
* this power change by calling either IOAllowPowerChange or IOCancelPowerChange,
|
||||
* the system will wait 30 seconds then go to sleep.
|
||||
*/
|
||||
|
||||
logger.debug() << "System power message: can system sleep?";
|
||||
|
||||
// Uncomment to cancel idle sleep
|
||||
// IOCancelPowerChange(thiz->rootPowerDomain, reinterpret_cast<long>(messageArgument));
|
||||
|
||||
// Allow idle sleep
|
||||
IOAllowPowerChange(listener->rootPowerDomain, reinterpret_cast<long>(messageArgument));
|
||||
break;
|
||||
|
||||
case kIOMessageSystemWillNotSleep:
|
||||
/* Announces that the system has retracted a previous attempt to sleep; it
|
||||
* follows `kIOMessageCanSystemSleep`.
|
||||
*/
|
||||
logger.debug() << "System power message: system will NOT sleep.";
|
||||
break;
|
||||
|
||||
case kIOMessageSystemWillSleep:
|
||||
/* The system WILL go to sleep. If you do not call IOAllowPowerChange or
|
||||
* IOCancelPowerChange to acknowledge this message, sleep will be delayed by
|
||||
* 30 seconds.
|
||||
*
|
||||
* NOTE: If you call IOCancelPowerChange to deny sleep it returns kIOReturnSuccess,
|
||||
* however the system WILL still go to sleep.
|
||||
*/
|
||||
|
||||
logger.debug() << "System power message: system WILL sleep";
|
||||
IOAllowPowerChange(listener->rootPowerDomain, reinterpret_cast<long>(messageArgument));
|
||||
break;
|
||||
|
||||
case kIOMessageSystemWillPowerOn:
|
||||
/* Announces that the system is beginning to power the device tree; most devices
|
||||
* are still unavailable at this point.
|
||||
*/
|
||||
/* From the documentation:
|
||||
*
|
||||
* - kIOMessageSystemWillPowerOn is delivered at early wakeup time, before most hardware
|
||||
* has been powered on. Be aware that any attempts to access disk, network, the display,
|
||||
* etc. may result in errors or blocking your process until those resources become
|
||||
* available.
|
||||
*
|
||||
* So we do NOT log this event.
|
||||
*/
|
||||
break;
|
||||
|
||||
case kIOMessageSystemHasPoweredOn:
|
||||
/* Announces that the system and its devices have woken up. */
|
||||
logger.debug() << "System has powered on - emitting sleepMode signal from dedicated CFRunLoop thread";
|
||||
if (listener->m_watcher) {
|
||||
// Use QMetaObject::invokeMethod for thread-safe signal emission
|
||||
QMetaObject::invokeMethod(listener->m_watcher, "sleepMode", Qt::QueuedConnection);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.debug() << "System power message: other event: " << messageType;
|
||||
/* Not a system sleep and wake notification. */
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
MacOSNetworkWatcher::MacOSNetworkWatcher(QObject* parent) : IOSNetworkWatcher(parent), m_powerlistener(this) {
|
||||
MZ_COUNT_CTOR(MacOSNetworkWatcher);
|
||||
}
|
||||
|
||||
MacOSNetworkWatcher::~MacOSNetworkWatcher() {
|
||||
MZ_COUNT_DTOR(MacOSNetworkWatcher);
|
||||
|
||||
// Stop the dedicated power monitoring thread
|
||||
if (g_powerListener) {
|
||||
logger.debug() << "Stopping dedicated power monitoring thread";
|
||||
g_shouldStopPowerThread = true;
|
||||
|
||||
if (g_powerRunLoop) {
|
||||
CFRunLoopStop(g_powerRunLoop);
|
||||
}
|
||||
|
||||
// Wait for thread to finish
|
||||
pthread_join(g_powerThread, nullptr);
|
||||
g_powerListener = nullptr;
|
||||
}
|
||||
|
||||
if (m_delegate) {
|
||||
CWWiFiClient* client = CWWiFiClient.sharedWiFiClient;
|
||||
if (!client) {
|
||||
@@ -66,6 +230,20 @@ void MacOSNetworkWatcher::start() {
|
||||
logger.debug() << "Delegate already registered";
|
||||
return;
|
||||
}
|
||||
|
||||
// Start dedicated power monitoring thread with CFRunLoop
|
||||
if (!g_powerListener) {
|
||||
g_powerListener = &m_powerlistener;
|
||||
g_shouldStopPowerThread = false;
|
||||
|
||||
int result = pthread_create(&g_powerThread, nullptr, powerMonitoringThread, &m_powerlistener);
|
||||
if (result != 0) {
|
||||
logger.error() << "Failed to create power monitoring thread:" << result;
|
||||
g_powerListener = nullptr;
|
||||
} else {
|
||||
logger.debug() << "Power monitoring enabled";
|
||||
}
|
||||
}
|
||||
|
||||
CWWiFiClient* client = CWWiFiClient.sharedWiFiClient;
|
||||
if (!client) {
|
||||
@@ -77,6 +255,8 @@ void MacOSNetworkWatcher::start() {
|
||||
m_delegate = [[MacOSNetworkWatcherDelegate alloc] initWithObject:this];
|
||||
[client setDelegate:static_cast<MacOSNetworkWatcherDelegate*>(m_delegate)];
|
||||
[client startMonitoringEventWithType:CWEventTypeBSSIDDidChange error:nullptr];
|
||||
|
||||
logger.debug() << "MacOSNetworkWatcher started successfully";
|
||||
}
|
||||
|
||||
void MacOSNetworkWatcher::checkInterface() {
|
||||
@@ -87,42 +267,70 @@ void MacOSNetworkWatcher::checkInterface() {
|
||||
return;
|
||||
}
|
||||
|
||||
CWWiFiClient* client = CWWiFiClient.sharedWiFiClient;
|
||||
if (!client) {
|
||||
logger.debug() << "Unable to retrieve the CWWiFiClient shared instance";
|
||||
// Use wdutil to get reliable WiFi information
|
||||
QProcess process;
|
||||
process.start("wdutil", QStringList() << "info");
|
||||
process.waitForFinished(5000);
|
||||
|
||||
QString output = process.readAllStandardOutput();
|
||||
QString errorOutput = process.readAllStandardError();
|
||||
|
||||
logger.debug() << "wdutil exit code:" << process.exitCode();
|
||||
|
||||
if (process.exitCode() != 0) {
|
||||
logger.debug() << "wdutil failed with exit code:" << process.exitCode();
|
||||
return;
|
||||
}
|
||||
|
||||
CWInterface* interface = [client interface];
|
||||
if (!interface) {
|
||||
logger.debug() << "No default wifi interface";
|
||||
return;
|
||||
|
||||
// Parse wdutil output to find WiFi connection info
|
||||
QStringList lines = output.split('\n');
|
||||
QString ssid, interfaceName, security;
|
||||
bool wifiSectionFound = false;
|
||||
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
QString trimmedLine = lines[i].trimmed();
|
||||
|
||||
if (trimmedLine == "WIFI") {
|
||||
wifiSectionFound = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (wifiSectionFound) {
|
||||
// Stop parsing when we reach next section header (all caps after separator line)
|
||||
if (trimmedLine.startsWith("————————")) {
|
||||
if (i + 1 < lines.size()) {
|
||||
QString nextLine = lines[i + 1].trimmed();
|
||||
if (!nextLine.isEmpty() && nextLine.length() > 2 && nextLine.toUpper() == nextLine && nextLine != "WIFI") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue; // Skip separator lines
|
||||
}
|
||||
|
||||
if (trimmedLine.startsWith("Interface Name")) {
|
||||
QStringList parts = trimmedLine.split(":");
|
||||
if (parts.size() >= 2) {
|
||||
interfaceName = parts[1].trimmed();
|
||||
}
|
||||
} else if (trimmedLine.startsWith("SSID")) {
|
||||
QStringList parts = trimmedLine.split(":");
|
||||
if (parts.size() >= 2) {
|
||||
ssid = parts[1].trimmed();
|
||||
}
|
||||
} else if (trimmedLine.startsWith("Security")) {
|
||||
QStringList parts = trimmedLine.split(":");
|
||||
if (parts.size() >= 2) {
|
||||
security = parts[1].trimmed();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (![interface powerOn]) {
|
||||
logger.debug() << "The interface is off";
|
||||
return;
|
||||
|
||||
if (!ssid.isEmpty() && !interfaceName.isEmpty()) {
|
||||
logger.debug() << "Found active WiFi connection on" << interfaceName
|
||||
<< "SSID:" << ssid << "Security:" << security;
|
||||
} else {
|
||||
logger.debug() << "No active WiFi connection found";
|
||||
}
|
||||
|
||||
NSString* ssidNS = [interface ssid];
|
||||
if (!ssidNS) {
|
||||
logger.debug() << "WiFi is not in used";
|
||||
return;
|
||||
}
|
||||
|
||||
QString ssid = QString::fromNSString(ssidNS);
|
||||
if (ssid.isEmpty()) {
|
||||
logger.debug() << "WiFi doesn't have a valid SSID";
|
||||
return;
|
||||
}
|
||||
|
||||
CWSecurity security = [interface security];
|
||||
if (security == kCWSecurityNone || security == kCWSecurityWEP) {
|
||||
logger.debug() << "Unsecured network found!";
|
||||
emit unsecuredNetwork(ssid, ssid);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug() << "Secure WiFi interface";
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
#include "logger.h"
|
||||
#include "platforms/windows/daemon/windowsfirewall.h"
|
||||
#include "platforms/windows/daemon/windowssplittunnel.h"
|
||||
#include "platforms/windows/windowscommons.h"
|
||||
#include "windowsfirewall.h"
|
||||
|
||||
#include "core/networkUtilities.h"
|
||||
|
||||
@@ -32,9 +32,28 @@ WindowsNetworkWatcher::~WindowsNetworkWatcher() {
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT WindowsNetworkWatcher::PowerWndProcCallback(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
|
||||
auto obj = reinterpret_cast<WindowsNetworkWatcher*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
|
||||
if (!obj){
|
||||
logger.debug() << "obj not casted";
|
||||
return DefWindowProc(hwnd, uMsg, wParam, lParam);
|
||||
}
|
||||
switch (uMsg) {
|
||||
case WM_POWERBROADCAST:
|
||||
if (wParam == PBT_APMRESUMESUSPEND) {
|
||||
emit obj->sleepMode();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return DefWindowProc(hwnd, uMsg, wParam, lParam);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void WindowsNetworkWatcher::initialize() {
|
||||
logger.debug() << "initialize";
|
||||
|
||||
|
||||
DWORD negotiatedVersion;
|
||||
if (WlanOpenHandle(2, nullptr, &negotiatedVersion, &m_wlanHandle) !=
|
||||
ERROR_SUCCESS) {
|
||||
@@ -51,6 +70,25 @@ void WindowsNetworkWatcher::initialize() {
|
||||
return;
|
||||
}
|
||||
|
||||
const wchar_t* className = L"PowerMonitorClass";
|
||||
WNDCLASS wc = { 0 };
|
||||
wc.lpfnWndProc = &WindowsNetworkWatcher::PowerWndProcCallback;
|
||||
wc.hInstance = GetModuleHandle(NULL);
|
||||
wc.lpszClassName = className;
|
||||
wc.cbWndExtra = sizeof(WindowsNetworkWatcher*);
|
||||
|
||||
if (!RegisterClass(&wc)) {
|
||||
logger.debug() << "Failed to register window class in createPowerMonitorWindow.";
|
||||
return;
|
||||
}
|
||||
|
||||
HWND hwnd = CreateWindowEx(0, className, L"Power Monitor", 0, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), static_cast<LPVOID>(this));
|
||||
if (!hwnd) {
|
||||
logger.debug() << "Failed to create window in createPowerMonitorWindow.";
|
||||
return;
|
||||
}
|
||||
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
|
||||
|
||||
logger.debug() << "callback registered";
|
||||
}
|
||||
|
||||
@@ -137,4 +175,4 @@ void WindowsNetworkWatcher::processWlan(PWLAN_NOTIFICATION_DATA data) {
|
||||
logger.debug() << "Unsecure network:" << logger.sensitive(ssid)
|
||||
<< "id:" << logger.sensitive(bssid);
|
||||
emit unsecuredNetwork(ssid, bssid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ class WindowsNetworkWatcher final : public NetworkWatcherImpl {
|
||||
|
||||
private:
|
||||
static void wlanCallback(PWLAN_NOTIFICATION_DATA data, PVOID context);
|
||||
static LRESULT PowerWndProcCallback(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
|
||||
|
||||
void processWlan(PWLAN_NOTIFICATION_DATA data);
|
||||
|
||||
|
||||
@@ -179,6 +179,7 @@ void WindowsPingSender::pingEventReady() {
|
||||
return;
|
||||
}
|
||||
QString errmsg = WindowsUtils::getErrorMessage();
|
||||
emit criticalPingError();
|
||||
logger.error() << "No ping reply. Code: " << error
|
||||
<< " Message: " << errmsg;
|
||||
return;
|
||||
|
||||
@@ -56,7 +56,8 @@ void OpenVpnProtocol::stop()
|
||||
}
|
||||
|
||||
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
|
||||
IpcClient::Interface()->disableKillSwitch();
|
||||
QRemoteObjectPendingReply<bool> disableKillSwitchResp = IpcClient::Interface()->disableKillSwitch();
|
||||
disableKillSwitchResp.waitForFinished(1000);
|
||||
#endif
|
||||
|
||||
setConnectionState(Vpn::ConnectionState::Disconnected);
|
||||
|
||||
@@ -103,6 +103,11 @@ QString VpnProtocol::vpnGateway() const
|
||||
return m_vpnGateway;
|
||||
}
|
||||
|
||||
QString VpnProtocol::vpnLocalAddress() const
|
||||
{
|
||||
return m_vpnLocalAddress;
|
||||
}
|
||||
|
||||
VpnProtocol *VpnProtocol::factory(DockerContainer container, const QJsonObject &configuration)
|
||||
{
|
||||
switch (container) {
|
||||
|
||||
@@ -63,6 +63,7 @@ public:
|
||||
|
||||
QString routeGateway() const;
|
||||
QString vpnGateway() const;
|
||||
QString vpnLocalAddress() const;
|
||||
|
||||
static VpnProtocol* factory(amnezia::DockerContainer container, const QJsonObject &configuration);
|
||||
|
||||
@@ -71,6 +72,7 @@ signals:
|
||||
void connectionStateChanged(Vpn::ConnectionState state);
|
||||
void timeoutTimerEvent();
|
||||
void protocolError(amnezia::ErrorCode e);
|
||||
void tunnelAddressesUpdated(const QString& gateway, const QString& localAddress);
|
||||
|
||||
public slots:
|
||||
virtual void onTimeout(); // todo: remove?
|
||||
|
||||
@@ -17,6 +17,26 @@ WireguardProtocol::WireguardProtocol(const QJsonObject &configuration, QObject *
|
||||
[this](const QString &pubkey, const QDateTime &connectionTimestamp) {
|
||||
emit connectionStateChanged(Vpn::ConnectionState::Connected);
|
||||
});
|
||||
connect(m_impl.get(), &ControllerImpl::statusUpdated, this,
|
||||
[this](const QString& serverIpv4Gateway,
|
||||
const QString& deviceIpv4Address, uint64_t txBytes,
|
||||
uint64_t rxBytes) {
|
||||
const QString previousGateway = m_vpnGateway;
|
||||
const QString previousLocal = m_vpnLocalAddress;
|
||||
|
||||
if (!serverIpv4Gateway.isEmpty()) {
|
||||
m_vpnGateway = serverIpv4Gateway;
|
||||
}
|
||||
if (!deviceIpv4Address.isEmpty()) {
|
||||
m_vpnLocalAddress = deviceIpv4Address;
|
||||
}
|
||||
|
||||
if ((!m_vpnGateway.isEmpty() && m_vpnGateway != previousGateway) ||
|
||||
(!m_vpnLocalAddress.isEmpty() && m_vpnLocalAddress != previousLocal)) {
|
||||
emit tunnelAddressesUpdated(m_vpnGateway, m_vpnLocalAddress);
|
||||
}
|
||||
});
|
||||
|
||||
connect(m_impl.get(), &ControllerImpl::disconnected, this,
|
||||
[this]() { emit connectionStateChanged(Vpn::ConnectionState::Disconnected); });
|
||||
m_impl->initialize(nullptr, nullptr);
|
||||
@@ -57,4 +77,3 @@ ErrorCode WireguardProtocol::start()
|
||||
{
|
||||
return startMzImpl();
|
||||
}
|
||||
|
||||
|
||||
@@ -166,10 +166,17 @@ ErrorCode XrayProtocol::startTun2Sock()
|
||||
|
||||
void XrayProtocol::stop()
|
||||
{
|
||||
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
|
||||
IpcClient::Interface()->disableKillSwitch();
|
||||
IpcClient::Interface()->StartRoutingIpv6();
|
||||
IpcClient::Interface()->restoreResolvers();
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
QRemoteObjectPendingReply<bool> disableKillSwitchResp = IpcClient::Interface()->disableKillSwitch();
|
||||
disableKillSwitchResp.waitForFinished(1000);
|
||||
QRemoteObjectPendingReply<bool> StartRoutingIpv6Resp = IpcClient::Interface()->StartRoutingIpv6();
|
||||
StartRoutingIpv6Resp.waitForFinished(1000);
|
||||
QRemoteObjectPendingReply<bool> restoreResolvers = IpcClient::Interface()->restoreResolvers();
|
||||
restoreResolvers.waitForFinished(1000);
|
||||
#if !defined(Q_OS_MACOS)
|
||||
QRemoteObjectPendingReply<bool> deleteTunResp = IpcClient::Interface()->deleteTun("tun2");
|
||||
deleteTunResp.waitForFinished(1000);
|
||||
#endif
|
||||
#endif
|
||||
qDebug() << "XrayProtocol::stop()";
|
||||
m_xrayProcess.disconnect();
|
||||
@@ -177,6 +184,7 @@ void XrayProtocol::stop()
|
||||
m_xrayProcess.waitForFinished(3000);
|
||||
if (m_t2sProcess) {
|
||||
m_t2sProcess->stop();
|
||||
QThread::msleep(200);
|
||||
}
|
||||
|
||||
setConnectionState(Vpn::ConnectionState::Disconnected);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,7 @@ ApiNewsController::ApiNewsController(const QSharedPointer<NewsModel> &newsModel,
|
||||
{
|
||||
}
|
||||
|
||||
void ApiNewsController::fetchNews()
|
||||
void ApiNewsController::fetchNews(bool showError)
|
||||
{
|
||||
if (m_serversModel.isNull()) {
|
||||
qWarning() << "ServersModel is null, skip fetchNews";
|
||||
@@ -30,8 +30,9 @@ void ApiNewsController::fetchNews()
|
||||
qDebug() << "No Gateway stacks, skip fetchNews";
|
||||
return;
|
||||
}
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
auto gatewayController = QSharedPointer<GatewayController>::create(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(),
|
||||
apiDefs::requestTimeoutMsecs, m_settings->isStrictKillSwitchEnabled());
|
||||
QJsonObject payload;
|
||||
payload.insert("locale", m_settings->getAppLanguage().name().split("_").first());
|
||||
|
||||
@@ -43,11 +44,11 @@ void ApiNewsController::fetchNews()
|
||||
payload.insert(configKey::serviceType, stacksJson.value(configKey::serviceType));
|
||||
}
|
||||
|
||||
auto future = gatewayController.postAsync(QString("%1v1/news"), payload);
|
||||
future.then(this, [this](QPair<ErrorCode, QByteArray> result) {
|
||||
auto future = gatewayController->postAsync(QString("%1v1/news"), payload);
|
||||
future.then(this, [this, showError, gatewayController](QPair<ErrorCode, QByteArray> result) {
|
||||
auto [errorCode, responseBody] = result;
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
emit errorOccurred(errorCode);
|
||||
emit errorOccurred(errorCode, showError);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -19,10 +19,10 @@ public:
|
||||
explicit ApiNewsController(const QSharedPointer<NewsModel> &newsModel, const std::shared_ptr<Settings> &settings,
|
||||
const QSharedPointer<ServersModel> &serversModel, QObject *parent = nullptr);
|
||||
|
||||
Q_INVOKABLE void fetchNews();
|
||||
Q_INVOKABLE void fetchNews(bool showError);
|
||||
|
||||
signals:
|
||||
void errorOccurred(ErrorCode errorCode);
|
||||
void errorOccurred(ErrorCode errorCode, bool showError);
|
||||
void fetchNewsFinished();
|
||||
|
||||
private:
|
||||
|
||||
@@ -82,7 +82,7 @@ void ApiPremV1MigrationController::sendMigrationCode(const int subscriptionIndex
|
||||
{
|
||||
QEventLoop wait;
|
||||
QTimer::singleShot(1000, &wait, &QEventLoop::quit);
|
||||
wait.exec();
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
@@ -46,7 +46,7 @@ bool ApiSettingsController::getAccountInfo(bool reload)
|
||||
if (reload) {
|
||||
QEventLoop wait;
|
||||
QTimer::singleShot(1000, &wait, &QEventLoop::quit);
|
||||
wait.exec();
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
}
|
||||
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), requestTimeoutMsecs,
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
|
||||
#include "core/controllers/vpnConfigurationController.h"
|
||||
#include "core/qrCodeUtils.h"
|
||||
#include "core/serialization/serialization.h"
|
||||
#include "core/serialization/transfer.h"
|
||||
#include "systemController.h"
|
||||
#include <QDebug>
|
||||
|
||||
ExportController::ExportController(const QSharedPointer<ServersModel> &serversModel, const QSharedPointer<ContainersModel> &containersModel,
|
||||
const QSharedPointer<ClientManagementModel> &clientManagementModel,
|
||||
@@ -249,6 +252,7 @@ void ExportController::generateCloakConfig()
|
||||
|
||||
void ExportController::generateXrayConfig(const QString &clientName)
|
||||
{
|
||||
//Xray data
|
||||
QJsonObject nativeConfig;
|
||||
ErrorCode errorCode = generateNativeConfig(DockerContainer::Xray, clientName, Proto::Xray, nativeConfig);
|
||||
if (errorCode) {
|
||||
@@ -258,8 +262,72 @@ void ExportController::generateXrayConfig(const QString &clientName)
|
||||
|
||||
QStringList lines = QString(QJsonDocument(nativeConfig).toJson()).replace("\r", "").split("\n");
|
||||
for (const QString &line : std::as_const(lines)) {
|
||||
m_config.append(line + "\n");
|
||||
m_config.append(line+ "\n");
|
||||
}
|
||||
//Xray data
|
||||
|
||||
// Parse the Xray data to extract VLESS parameters and generate string
|
||||
QString configString = QString(QJsonDocument(nativeConfig).toJson(QJsonDocument::Compact));
|
||||
|
||||
QJsonDocument doc = QJsonDocument::fromJson(configString.toUtf8());
|
||||
if (doc.isNull() || !doc.isObject()) {
|
||||
qDebug() << "ERROR: Failed to parse config JSON";
|
||||
emit exportErrorOccurred(ErrorCode::InternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject xrayConfig = doc.object();
|
||||
QJsonArray outbounds = xrayConfig.value("outbounds").toArray();
|
||||
|
||||
if (outbounds.isEmpty()) {
|
||||
qDebug() << "ERROR: Outbounds array is empty";
|
||||
emit exportErrorOccurred(ErrorCode::InternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject outbound = outbounds[0].toObject();
|
||||
QJsonObject settings = outbound.value("settings").toObject();
|
||||
QJsonObject streamSettings = outbound.value("streamSettings").toObject();
|
||||
|
||||
QJsonArray vnext = settings.value("vnext").toArray();
|
||||
if (vnext.isEmpty()) {
|
||||
qDebug() << "ERROR: vnext array is empty";
|
||||
emit exportErrorOccurred(ErrorCode::InternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject server = vnext[0].toObject();
|
||||
QJsonArray users = server.value("users").toArray();
|
||||
if (users.isEmpty()) {
|
||||
qDebug() << "ERROR: users array is empty";
|
||||
emit exportErrorOccurred(ErrorCode::InternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonObject user = users[0].toObject();
|
||||
|
||||
amnezia::serialization::VlessServerObject vlessServer;
|
||||
vlessServer.address = server.value("address").toString();
|
||||
vlessServer.port = server.value("port").toInt();
|
||||
vlessServer.id = user.value("id").toString();
|
||||
vlessServer.flow = user.value("flow").toString("xtls-rprx-vision");
|
||||
vlessServer.encryption = user.value("encryption").toString("none");
|
||||
|
||||
vlessServer.network = streamSettings.value("network").toString("tcp");
|
||||
vlessServer.security = streamSettings.value("security").toString("reality");
|
||||
|
||||
|
||||
if (vlessServer.security == "reality") {
|
||||
QJsonObject realitySettings = streamSettings.value("realitySettings").toObject();
|
||||
vlessServer.serverName = realitySettings.value("serverName").toString();
|
||||
vlessServer.publicKey = realitySettings.value("publicKey").toString();
|
||||
vlessServer.shortId = realitySettings.value("shortId").toString();
|
||||
vlessServer.fingerprint = realitySettings.value("fingerprint").toString("chrome");
|
||||
vlessServer.spiderX = realitySettings.value("spiderX").toString("");
|
||||
}
|
||||
|
||||
m_nativeConfigString = amnezia::serialization::vless::Serialize(vlessServer, "AmneziaVPN");
|
||||
|
||||
|
||||
emit exportConfigChanged();
|
||||
}
|
||||
|
||||
@@ -208,6 +208,7 @@ bool ImportController::extractConfigFromData(QString data)
|
||||
}
|
||||
case ConfigTypes::Invalid: {
|
||||
emit importErrorOccurred(ErrorCode::ImportInvalidConfigError, false);
|
||||
m_configFileName.clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -341,6 +342,11 @@ void ImportController::importConfig()
|
||||
m_maliciousWarningText.clear();
|
||||
}
|
||||
|
||||
void ImportController::clearConfigFileName()
|
||||
{
|
||||
m_configFileName.clear();
|
||||
}
|
||||
|
||||
QJsonObject ImportController::extractOpenVpnConfig(const QString &data)
|
||||
{
|
||||
QJsonObject openVpnConfig;
|
||||
|
||||
@@ -30,6 +30,7 @@ public:
|
||||
|
||||
public slots:
|
||||
void importConfig();
|
||||
void clearConfigFileName();
|
||||
bool extractConfigFromFile(const QString &fileName);
|
||||
bool extractConfigFromData(QString data);
|
||||
bool extractConfigFromQr(const QByteArray &data);
|
||||
|
||||
@@ -48,6 +48,7 @@ QString LanguageModel::getLocalLanguageName(const LanguageSettings::AvailableLan
|
||||
case LanguageSettings::AvailableLanguageEnum::Burmese: strLanguage = "မြန်မာဘာသာ"; break;
|
||||
case LanguageSettings::AvailableLanguageEnum::Urdu: strLanguage = "اُرْدُوْ"; break;
|
||||
case LanguageSettings::AvailableLanguageEnum::Hindi: strLanguage = "हिन्दी"; break;
|
||||
case LanguageSettings::AvailableLanguageEnum::Spanish: strLanguage = "Español"; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
@@ -66,6 +67,7 @@ void LanguageModel::changeLanguage(const LanguageSettings::AvailableLanguageEnum
|
||||
case LanguageSettings::AvailableLanguageEnum::Burmese: emit updateTranslations(QLocale::Burmese); break;
|
||||
case LanguageSettings::AvailableLanguageEnum::Urdu: emit updateTranslations(QLocale::Urdu); break;
|
||||
case LanguageSettings::AvailableLanguageEnum::Hindi: emit updateTranslations(QLocale::Hindi); break;
|
||||
case LanguageSettings::AvailableLanguageEnum::Spanish: emit updateTranslations(QLocale::Spanish); break;
|
||||
default: emit updateTranslations(QLocale::English); break;
|
||||
}
|
||||
}
|
||||
@@ -83,6 +85,7 @@ int LanguageModel::getCurrentLanguageIndex()
|
||||
case QLocale::Burmese: return static_cast<int>(LanguageSettings::AvailableLanguageEnum::Burmese); break;
|
||||
case QLocale::Urdu: return static_cast<int>(LanguageSettings::AvailableLanguageEnum::Urdu); break;
|
||||
case QLocale::Hindi: return static_cast<int>(LanguageSettings::AvailableLanguageEnum::Hindi); break;
|
||||
case QLocale::Spanish: return static_cast<int>(LanguageSettings::AvailableLanguageEnum::Spanish); break;
|
||||
default: return static_cast<int>(LanguageSettings::AvailableLanguageEnum::English); break;
|
||||
}
|
||||
}
|
||||
@@ -113,6 +116,7 @@ LanguageSettings::AvailableLanguageEnum LanguageModel::getSystemLanguageEnum()
|
||||
case QLocale::Burmese: return LanguageSettings::AvailableLanguageEnum::Burmese;
|
||||
case QLocale::Urdu: return LanguageSettings::AvailableLanguageEnum::Urdu;
|
||||
case QLocale::Hindi: return LanguageSettings::AvailableLanguageEnum::Hindi;
|
||||
case QLocale::Spanish: return LanguageSettings::AvailableLanguageEnum::Spanish;
|
||||
case QLocale::English: return LanguageSettings::AvailableLanguageEnum::English;
|
||||
default: return LanguageSettings::AvailableLanguageEnum::English;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,8 @@ namespace LanguageSettings
|
||||
Arabic,
|
||||
Burmese,
|
||||
Urdu,
|
||||
Hindi
|
||||
Hindi,
|
||||
Spanish
|
||||
};
|
||||
Q_ENUM_NS(AvailableLanguageEnum)
|
||||
|
||||
|
||||
@@ -78,34 +78,28 @@ void NewsModel::setProcessedIndex(int index)
|
||||
|
||||
void NewsModel::updateModel(const QJsonArray &serverItems)
|
||||
{
|
||||
QSet<QString> existingIds;
|
||||
for (const NewsItem &item : m_items) {
|
||||
existingIds.insert(item.id);
|
||||
}
|
||||
QList<NewsItem> updatedItems;
|
||||
|
||||
QList<NewsItem> newItems;
|
||||
for (const QJsonValue &value : serverItems) {
|
||||
if (!value.isObject())
|
||||
continue;
|
||||
const QJsonObject obj = value.toObject();
|
||||
QString id = obj.value("id").toString();
|
||||
|
||||
if (!existingIds.contains(id)) {
|
||||
NewsItem item;
|
||||
item.id = id;
|
||||
item.title = obj.value("title").toString();
|
||||
item.content = obj.value("content").toString();
|
||||
item.timestamp = QDateTime::fromString(obj.value("timestamp").toString(), Qt::ISODate);
|
||||
item.read = m_readIds.contains(id);
|
||||
newItems.append(item);
|
||||
existingIds.insert(id);
|
||||
}
|
||||
QJsonObject object = value.toObject();
|
||||
|
||||
NewsItem item;
|
||||
item.id = object.value("id").toString();
|
||||
item.title = object.value("title").toString();
|
||||
item.content = object.value("content").toString();
|
||||
item.timestamp = QDateTime::fromString(object.value("timestamp").toString(), Qt::ISODate);
|
||||
item.read = m_readIds.contains(object.value("id").toString());
|
||||
updatedItems.append(item);
|
||||
}
|
||||
|
||||
beginResetModel();
|
||||
m_items.append(newItems);
|
||||
m_items = updatedItems;
|
||||
std::sort(m_items.begin(), m_items.end(), [](const NewsItem &a, const NewsItem &b) { return a.timestamp > b.timestamp; });
|
||||
endResetModel();
|
||||
loadReadIds();
|
||||
emit hasUnreadChanged();
|
||||
}
|
||||
|
||||
|
||||
@@ -20,10 +20,12 @@ PageType {
|
||||
PageController.showBusyIndicator(false)
|
||||
}
|
||||
|
||||
function onErrorOccurred(errorCode) {
|
||||
PageController.showErrorMessage(errorCode)
|
||||
PageController.closePage()
|
||||
PageController.showBusyIndicator(false)
|
||||
function onErrorOccurred(errorCode, showError) {
|
||||
if (showError) {
|
||||
PageController.showErrorMessage(errorCode)
|
||||
PageController.closePage()
|
||||
PageController.showBusyIndicator(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,7 +155,7 @@ PageType {
|
||||
return;
|
||||
}
|
||||
PageController.showBusyIndicator(true)
|
||||
ApiNewsController.fetchNews()
|
||||
ApiNewsController.fetchNews(true)
|
||||
PageController.goToPage(PageEnum.PageSettingsNewsNotifications)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,18 @@ PageType {
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
text: newsItem.content
|
||||
|
||||
textFormat: Text.RichText
|
||||
|
||||
onLinkActivated: function(link) {
|
||||
Qt.openUrlExternally(link)
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
acceptedButtons: Qt.NoButton
|
||||
cursorShape: parent.hoveredLink ? Qt.PointingHandCursor : Qt.ArrowCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ PageType {
|
||||
|
||||
clickedFunc: function () {
|
||||
clickedHandler()
|
||||
buttonImageSource = textField.text !== "" ? imageSource : ""
|
||||
}
|
||||
|
||||
textField.onFocusChanged: {
|
||||
@@ -78,8 +79,8 @@ PageType {
|
||||
}
|
||||
|
||||
textField.onTextChanged: {
|
||||
if (hideContent) {
|
||||
buttonImageSource = textField.text !== "" ? (hideContent ? "qrc:/images/controls/eye.svg" : "qrc:/images/controls/eye-off.svg") : ""
|
||||
if (headerText == qsTr("Password or SSH private key")) {
|
||||
buttonImageSource = textField.text !== "" ? imageSource : ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,8 +212,10 @@ PageType {
|
||||
property string title: qsTr("Password or SSH private key")
|
||||
readonly property string placeholderContent: ""
|
||||
property bool hideContent: true
|
||||
property string imageSource: "qrc:/images/controls/eye.svg"
|
||||
readonly property var clickedHandler: function() {
|
||||
hideContent = !hideContent
|
||||
imageSource = hideContent ? "qrc:/images/controls/eye.svg" : "qrc:/images/controls/eye-off.svg"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,14 @@ PageType {
|
||||
}
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: PageController
|
||||
|
||||
function onClosePage() {
|
||||
ImportController.clearConfigFileName()
|
||||
}
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: ImportController
|
||||
|
||||
|
||||
@@ -311,7 +311,7 @@ PageType {
|
||||
DropDownType {
|
||||
id: serverSelector
|
||||
|
||||
signal severSelectorIndexChanged
|
||||
signal serverSelectorIndexChanged
|
||||
property int currentIndex: -1
|
||||
|
||||
Layout.fillWidth: true
|
||||
@@ -348,7 +348,7 @@ PageType {
|
||||
|
||||
if (serverSelector.currentIndex !== serverSelectorListView.selectedIndex) {
|
||||
serverSelector.currentIndex = serverSelectorListView.selectedIndex
|
||||
serverSelector.severSelectorIndexChanged()
|
||||
serverSelector.serverSelectorIndexChanged()
|
||||
}
|
||||
|
||||
serverSelector.closeTriggered()
|
||||
@@ -375,6 +375,8 @@ PageType {
|
||||
DropDownType {
|
||||
id: protocolSelector
|
||||
|
||||
signal protocolSelectorTextChanged
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
|
||||
@@ -414,7 +416,7 @@ PageType {
|
||||
Connections {
|
||||
target: serverSelector
|
||||
|
||||
function onSeverSelectorIndexChanged() {
|
||||
function onServerSelectorIndexChanged() {
|
||||
var defaultContainer = proxyContainersModel.mapFromSource(ServersModel.getProcessedServerData("defaultContainer"))
|
||||
protocolSelectorListView.selectedIndex = defaultContainer
|
||||
protocolSelectorListView.positionViewAtIndex(selectedIndex, ListView.Beginning)
|
||||
@@ -436,17 +438,14 @@ PageType {
|
||||
|
||||
fillConnectionTypeModel()
|
||||
|
||||
if (exportTypeSelector.currentIndex >= root.connectionTypesModel.length) {
|
||||
exportTypeSelector.currentIndex = 0
|
||||
exportTypeSelector.text = root.connectionTypesModel[0].name
|
||||
}
|
||||
|
||||
if (accessTypeSelector.currentIndex === 1) {
|
||||
PageController.showBusyIndicator(true)
|
||||
ExportController.updateClientManagementModel(ContainersModel.getProcessedContainerIndex(),
|
||||
ServersModel.getProcessedServerCredentials())
|
||||
PageController.showBusyIndicator(false)
|
||||
}
|
||||
|
||||
protocolSelector.protocolSelectorTextChanged()
|
||||
}
|
||||
|
||||
function fillConnectionTypeModel() {
|
||||
@@ -499,6 +498,14 @@ PageType {
|
||||
exportTypeSelector.text = exportTypeSelectorListView.selectedText
|
||||
}
|
||||
|
||||
onModelChanged: {
|
||||
if (exportTypeSelector.currentIndex >= model.length || exportTypeSelector.currentIndex < 0) {
|
||||
exportTypeSelector.currentIndex = 0
|
||||
}
|
||||
selectedIndex = exportTypeSelector.currentIndex
|
||||
exportTypeSelector.text = selectedText
|
||||
}
|
||||
|
||||
rootWidth: root.width
|
||||
|
||||
imageSource: "qrc:/images/controls/check.svg"
|
||||
@@ -506,16 +513,23 @@ PageType {
|
||||
model: root.connectionTypesModel
|
||||
currentIndex: 0
|
||||
|
||||
Connections {
|
||||
target: protocolSelector
|
||||
|
||||
function onProtocolSelectorTextChanged() {
|
||||
if (exportTypeSelector.currentIndex >= root.connectionTypesModel.length) {
|
||||
exportTypeSelectorListView.selectedIndex = 0
|
||||
exportTypeSelector.currentIndex = 0
|
||||
exportTypeSelector.text = root.connectionTypesModel[0].name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clickedFunction: function() {
|
||||
exportTypeSelector.text = exportTypeSelectorListView.selectedText
|
||||
exportTypeSelector.currentIndex = exportTypeSelectorListView.selectedIndex
|
||||
exportTypeSelector.closeTriggered()
|
||||
}
|
||||
|
||||
Component.onCompleted: {
|
||||
exportTypeSelector.text = exportTypeSelectorListView.selectedText
|
||||
exportTypeSelector.currentIndex = exportTypeSelectorListView.selectedIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,6 +580,7 @@ PageType {
|
||||
textField.placeholderText: qsTr("Search")
|
||||
|
||||
Keys.onEscapePressed: {
|
||||
searchTextField.textField.text = ""
|
||||
root.isSearchBarVisible = false
|
||||
}
|
||||
|
||||
@@ -586,6 +601,7 @@ PageType {
|
||||
imageColor: AmneziaStyle.color.paleGray
|
||||
|
||||
function clickedFunc() {
|
||||
searchTextField.textField.text = ""
|
||||
root.isSearchBarVisible = false
|
||||
}
|
||||
|
||||
@@ -602,6 +618,8 @@ PageType {
|
||||
|
||||
visible: accessTypeSelector.currentIndex === 1
|
||||
|
||||
function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') }
|
||||
|
||||
property bool isFocusable: true
|
||||
property bool freezeFilter: false
|
||||
|
||||
@@ -611,7 +629,7 @@ PageType {
|
||||
filters: RegExpFilter {
|
||||
roleName: "clientName"
|
||||
enabled: !clientsListView.freezeFilter
|
||||
pattern: ".*" + searchTextField.textField.text + ".*"
|
||||
pattern: ".*" + clientsListView.escapeRe(searchTextField.textField.text) + ".*"
|
||||
caseSensitivity: Qt.CaseInsensitive
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ PageType {
|
||||
// configExtension = ".vpn"
|
||||
// configCaption = qsTr("Save AmneziaVPN config")
|
||||
// configFileName = "amnezia_config"
|
||||
|
||||
|
||||
// if (visible) {
|
||||
// var serverName = ServersModel.getProcessedServerData("name") || ServersModel.getProcessedServerData("hostName") || "Server"
|
||||
// headerText = qsTr("Connection to ") + serverName
|
||||
|
||||
@@ -73,7 +73,7 @@ PageType {
|
||||
id: serverSelector
|
||||
objectName: "serverSelector"
|
||||
|
||||
signal severSelectorIndexChanged
|
||||
signal serverSelectorIndexChanged
|
||||
property int currentIndex: 0
|
||||
|
||||
Layout.fillWidth: true
|
||||
|
||||
+164
-43
@@ -1,12 +1,16 @@
|
||||
#include "qtimer.h"
|
||||
#include "vpnconnection.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QEventLoop>
|
||||
#include <QFile>
|
||||
#include <QHostInfo>
|
||||
#include <QJsonObject>
|
||||
#include <QObject>
|
||||
#include <QSharedPointer>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QTimer>
|
||||
|
||||
#include "core/controllers/serverController.h"
|
||||
#include <configurators/cloak_configurator.h>
|
||||
#include <configurators/openvpn_configurator.h>
|
||||
#include <configurators/shadowsocks_configurator.h>
|
||||
@@ -14,12 +18,13 @@
|
||||
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
#include "core/ipcclient.h"
|
||||
#include "ipc.h"
|
||||
#include <protocols/wireguardprotocol.h>
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
#include "platforms/android/android_controller.h"
|
||||
#include <QThread>
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(Q_OS_IOS) || defined(MACOS_NE)
|
||||
@@ -32,8 +37,8 @@
|
||||
VpnConnection::VpnConnection(std::shared_ptr<Settings> settings, QObject *parent)
|
||||
: QObject(parent), m_settings(settings), m_checkTimer(new QTimer(this))
|
||||
{
|
||||
m_checkTimer.setInterval(1000);
|
||||
#if defined(Q_OS_IOS) || defined(MACOS_NE)
|
||||
m_checkTimer.setInterval(1000);
|
||||
connect(IosController::Instance(), &IosController::connectionStateChanged, this, &VpnConnection::onConnectionStateChanged);
|
||||
connect(IosController::Instance(), &IosController::bytesChanged, this, &VpnConnection::onBytesChanged);
|
||||
|
||||
@@ -42,9 +47,6 @@ VpnConnection::VpnConnection(std::shared_ptr<Settings> settings, QObject *parent
|
||||
|
||||
VpnConnection::~VpnConnection()
|
||||
{
|
||||
#if defined AMNEZIA_DESKTOP
|
||||
disconnectFromVpn();
|
||||
#endif
|
||||
}
|
||||
|
||||
void VpnConnection::onBytesChanged(quint64 receivedBytes, quint64 sentBytes)
|
||||
@@ -55,19 +57,7 @@ void VpnConnection::onBytesChanged(quint64 receivedBytes, quint64 sentBytes)
|
||||
void VpnConnection::onKillSwitchModeChanged(bool enabled)
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (!m_IpcClient) {
|
||||
m_IpcClient = new IpcClient(this);
|
||||
}
|
||||
|
||||
if (!m_IpcClient->isSocketConnected()) {
|
||||
if (!IpcClient::init(m_IpcClient)) {
|
||||
qWarning() << "Error occurred when init IPC client";
|
||||
emit serviceIsNotReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (IpcClient::Interface()) {
|
||||
if (InterfaceReady()) {
|
||||
qDebug() << "Set KillSwitch Strict mode enabled " << enabled;
|
||||
IpcClient::Interface()->refreshKillSwitch(enabled);
|
||||
}
|
||||
@@ -76,11 +66,10 @@ void VpnConnection::onKillSwitchModeChanged(bool enabled)
|
||||
|
||||
void VpnConnection::onConnectionStateChanged(Vpn::ConnectionState state)
|
||||
{
|
||||
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
auto container = m_settings->defaultContainer(m_settings->defaultServerIndex());
|
||||
|
||||
if (IpcClient::Interface()) {
|
||||
if (InterfaceReady()) {
|
||||
if (state == Vpn::ConnectionState::Connected) {
|
||||
IpcClient::Interface()->resetIpStack();
|
||||
IpcClient::Interface()->flushDns();
|
||||
@@ -107,7 +96,20 @@ 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;
|
||||
IpcClient::Interface()->flushDns();
|
||||
|
||||
if (m_settings->isSitesSplitTunnelingEnabled()) {
|
||||
@@ -118,6 +120,9 @@ void VpnConnection::onConnectionStateChanged(Vpn::ConnectionState state)
|
||||
} else if (state == Vpn::ConnectionState::Connecting) {
|
||||
|
||||
} else if (state == Vpn::ConnectionState::Disconnected) {
|
||||
m_pendingNetworkCheck = false;
|
||||
auto result = IpcClient::Interface()->stopNetworkCheck();
|
||||
result.waitForFinished(3000);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -212,14 +217,46 @@ void VpnConnection::deleteRoutes(const QStringList &ips)
|
||||
#endif
|
||||
}
|
||||
|
||||
bool VpnConnection::InterfaceReady()
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (m_IpcClient) {
|
||||
m_IpcClient->closeAndResetInstance(true);
|
||||
m_IpcClient->deleteLater();
|
||||
m_IpcClient = nullptr;
|
||||
}
|
||||
if (!m_IpcClient) {
|
||||
m_IpcClient = new IpcClient(this);
|
||||
}
|
||||
|
||||
if (!m_IpcClient->isSocketConnected()) {
|
||||
if (!IpcClient::init(m_IpcClient)) {
|
||||
qWarning() << "Error occurred when init IPC client";
|
||||
emit serviceIsNotReady();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return IpcClient::Interface() != nullptr;
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
void VpnConnection::flushDns()
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (IpcClient::Interface())
|
||||
if (InterfaceReady())
|
||||
IpcClient::Interface()->flushDns();
|
||||
#endif
|
||||
}
|
||||
|
||||
void VpnConnection::disconnectSlots()
|
||||
{
|
||||
if (m_vpnProtocol) {
|
||||
m_vpnProtocol->disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
ErrorCode VpnConnection::lastError() const
|
||||
{
|
||||
#ifdef Q_OS_ANDROID
|
||||
@@ -240,25 +277,20 @@ void VpnConnection::connectToVpn(int serverIndex, const ServerCredentials &crede
|
||||
.arg(serverIndex)
|
||||
.arg(ContainerProps::containerToString(container))
|
||||
<< m_settings->routeMode();
|
||||
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS) && !defined(MACOS_NE)
|
||||
if (!m_IpcClient) {
|
||||
m_IpcClient = new IpcClient(this);
|
||||
}
|
||||
|
||||
if (!m_IpcClient->isSocketConnected()) {
|
||||
if (!IpcClient::init(m_IpcClient)) {
|
||||
qWarning() << "Error occurred when init IPC client";
|
||||
emit serviceIsNotReady();
|
||||
emit connectionStateChanged(Vpn::ConnectionState::Error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (!InterfaceReady()) {
|
||||
emit connectionStateChanged(Vpn::ConnectionState::Error);
|
||||
return;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -297,12 +329,70 @@ 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();
|
||||
|
||||
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()
|
||||
@@ -406,6 +496,31 @@ void VpnConnection::appendSplitTunnelingConfig()
|
||||
m_vpnConfiguration.insert(config_key::splitTunnelApps, appsJsonArray);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
auto iface = IpcClient::Interface();
|
||||
if (!iface) {
|
||||
return false;
|
||||
}
|
||||
|
||||
iface->startNetworkCheck(gateway, localAddress);
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
void VpnConnection::restoreConnection()
|
||||
{
|
||||
@@ -440,13 +555,18 @@ QString VpnConnection::bytesPerSecToText(quint64 bytes)
|
||||
void VpnConnection::disconnectFromVpn()
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
QString proto = m_settings->defaultContainerName(m_settings->defaultServerIndex());
|
||||
if (IpcClient::Interface()) {
|
||||
IpcClient::Interface()->flushDns();
|
||||
if (InterfaceReady()) {
|
||||
|
||||
m_vpnProtocol.data()->stop();
|
||||
qDebug() << "Interface is ready!";
|
||||
|
||||
QRemoteObjectPendingReply<bool> flushDnsResp = IpcClient::Interface()->flushDns();
|
||||
flushDnsResp.waitForFinished(1000);
|
||||
|
||||
qDebug() << "Flushed DNS";
|
||||
// delete cached routes
|
||||
QRemoteObjectPendingReply<bool> response = IpcClient::Interface()->clearSavedRoutes();
|
||||
response.waitForFinished(1000);
|
||||
QRemoteObjectPendingReply<bool> clearSavedRoutesResp = IpcClient::Interface()->clearSavedRoutes();
|
||||
clearSavedRoutesResp.waitForFinished(1000);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -475,12 +595,13 @@ void VpnConnection::disconnectFromVpn()
|
||||
return;
|
||||
}
|
||||
|
||||
#ifndef Q_OS_ANDROID
|
||||
#if !defined(Q_OS_ANDROID) && !defined(AMNEZIA_DESKTOP)
|
||||
if (m_vpnProtocol) {
|
||||
m_vpnProtocol->deleteLater();
|
||||
}
|
||||
m_vpnProtocol = nullptr;
|
||||
#endif
|
||||
|
||||
m_vpnProtocol = nullptr;
|
||||
}
|
||||
|
||||
Vpn::ConnectionState VpnConnection::connectionState()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#define VPNCONNECTION_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QMetaObject>
|
||||
#include <QString>
|
||||
#include <QScopedPointer>
|
||||
#include <QRemoteObjectNode>
|
||||
@@ -51,11 +52,13 @@ public slots:
|
||||
const ServerCredentials &credentials, DockerContainer container, const QJsonObject &vpnConfiguration);
|
||||
|
||||
void disconnectFromVpn();
|
||||
void restartConnection();
|
||||
|
||||
void addRoutes(const QStringList &ips);
|
||||
void deleteRoutes(const QStringList &ips);
|
||||
void flushDns();
|
||||
void onKillSwitchModeChanged(bool enabled);
|
||||
void disconnectSlots();
|
||||
|
||||
signals:
|
||||
void bytesChanged(quint64 receivedBytes, quint64 sentBytes);
|
||||
@@ -70,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;
|
||||
@@ -77,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;
|
||||
|
||||
@@ -95,6 +108,8 @@ private:
|
||||
|
||||
void appendSplitTunnelingConfig();
|
||||
void appendKillSwitchConfig();
|
||||
bool startNetworkCheckIfReady();
|
||||
bool InterfaceReady();
|
||||
};
|
||||
|
||||
#endif // VPNCONNECTION_H
|
||||
|
||||
@@ -12,7 +12,7 @@ class IpcInterface
|
||||
SLOT( int routeAddList(const QString &gw, const QStringList &ips) );
|
||||
SLOT( bool clearSavedRoutes() );
|
||||
SLOT( bool routeDeleteList(const QString &gw, const QStringList &ip) );
|
||||
SLOT( void flushDns() );
|
||||
SLOT( bool flushDns() );
|
||||
SLOT( void resetIpStack() );
|
||||
|
||||
SLOT( bool checkAndInstallDriver() );
|
||||
@@ -25,8 +25,8 @@ class IpcInterface
|
||||
SLOT( bool createTun(const QString &dev, const QString &subnet) );
|
||||
SLOT( bool deleteTun(const QString &dev) );
|
||||
|
||||
SLOT( void StartRoutingIpv6() );
|
||||
SLOT( void StopRoutingIpv6() );
|
||||
SLOT( bool StartRoutingIpv6() );
|
||||
SLOT( bool StopRoutingIpv6() );
|
||||
|
||||
SLOT( bool disableKillSwitch() );
|
||||
SLOT( bool disableAllTraffic() );
|
||||
@@ -37,5 +37,10 @@ class IpcInterface
|
||||
SLOT( bool enableKillSwitch( const QJsonObject &excludeAddr, int vpnAdapterIndex) );
|
||||
SLOT( bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers) );
|
||||
SLOT( bool restoreResolvers() );
|
||||
};
|
||||
|
||||
SLOT( bool startNetworkCheck(const QString& serverIpv4Gateway, const QString& deviceIpv4Address) );
|
||||
SLOT( bool stopNetworkCheck() );
|
||||
|
||||
SIGNAL( connectionLose() );
|
||||
SIGNAL( networkChange() );
|
||||
};
|
||||
|
||||
+29
-6
@@ -1,9 +1,17 @@
|
||||
#include "ipcserver.h"
|
||||
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QFileInfo>
|
||||
#include <QHostAddress>
|
||||
#include <QJsonObject>
|
||||
#include <QLocalServer>
|
||||
#include <QLocalSocket>
|
||||
#include <QObject>
|
||||
#include <QRemoteObjectHost>
|
||||
#include <QRemoteObjectNode>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
#include "logger.h"
|
||||
#include "router.h"
|
||||
@@ -16,8 +24,8 @@
|
||||
|
||||
|
||||
IpcServer::IpcServer(QObject *parent) : IpcInterfaceSource(parent)
|
||||
|
||||
{
|
||||
connect(&m_pingHelper, &PingHelper::connectionLose, this, &IpcServer::connectionLose);
|
||||
}
|
||||
|
||||
int IpcServer::createPrivilegedProcess()
|
||||
@@ -83,7 +91,7 @@ bool IpcServer::routeDeleteList(const QString &gw, const QStringList &ips)
|
||||
return Router::routeDeleteList(gw, ips);
|
||||
}
|
||||
|
||||
void IpcServer::flushDns()
|
||||
bool IpcServer::flushDns()
|
||||
{
|
||||
#ifdef MZ_DEBUG
|
||||
qDebug() << "IpcServer::flushDns";
|
||||
@@ -161,13 +169,14 @@ bool IpcServer::restoreResolvers() {
|
||||
return Router::restoreResolvers();
|
||||
}
|
||||
|
||||
void IpcServer::StartRoutingIpv6()
|
||||
bool IpcServer::StartRoutingIpv6()
|
||||
{
|
||||
Router::StartRoutingIpv6();
|
||||
return Router::StartRoutingIpv6();
|
||||
}
|
||||
void IpcServer::StopRoutingIpv6()
|
||||
|
||||
bool IpcServer::StopRoutingIpv6()
|
||||
{
|
||||
Router::StopRoutingIpv6();
|
||||
return Router::StopRoutingIpv6();
|
||||
}
|
||||
|
||||
void IpcServer::setLogsEnabled(bool enabled)
|
||||
@@ -183,6 +192,20 @@ void IpcServer::setLogsEnabled(bool enabled)
|
||||
}
|
||||
}
|
||||
|
||||
bool IpcServer::startNetworkCheck(const QString& serverIpv4Gateway, const QString& deviceIpv4Address)
|
||||
{
|
||||
qDebug() << "startNetworkCheck";
|
||||
m_pingHelper.start(serverIpv4Gateway, deviceIpv4Address);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IpcServer::stopNetworkCheck()
|
||||
{
|
||||
qDebug() << "stopNetworkCheck";
|
||||
m_pingHelper.stop();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IpcServer::resetKillSwitchAllowedRange(QStringList ranges)
|
||||
{
|
||||
return KillSwitch::instance()->resetAllowedRange(ranges);
|
||||
|
||||
+7
-3
@@ -6,6 +6,7 @@
|
||||
#include <QRemoteObjectNode>
|
||||
#include <QJsonObject>
|
||||
#include "../client/daemon/interfaceconfig.h"
|
||||
#include "../client/mozilla/pinghelper.h"
|
||||
|
||||
#include "ipc.h"
|
||||
#include "ipcserverprocess.h"
|
||||
@@ -23,7 +24,7 @@ public:
|
||||
virtual int routeAddList(const QString &gw, const QStringList &ips) override;
|
||||
virtual bool clearSavedRoutes() override;
|
||||
virtual bool routeDeleteList(const QString &gw, const QStringList &ips) override;
|
||||
virtual void flushDns() override;
|
||||
virtual bool flushDns() override;
|
||||
virtual void resetIpStack() override;
|
||||
virtual bool checkAndInstallDriver() override;
|
||||
virtual QStringList getTapList() override;
|
||||
@@ -32,8 +33,8 @@ public:
|
||||
virtual void setLogsEnabled(bool enabled) override;
|
||||
virtual bool createTun(const QString &dev, const QString &subnet) override;
|
||||
virtual bool deleteTun(const QString &dev) override;
|
||||
virtual void StartRoutingIpv6() override;
|
||||
virtual void StopRoutingIpv6() override;
|
||||
virtual bool StartRoutingIpv6() override;
|
||||
virtual bool StopRoutingIpv6() override;
|
||||
virtual bool disableAllTraffic() override;
|
||||
virtual bool addKillSwitchAllowedRange(QStringList ranges) override;
|
||||
virtual bool resetKillSwitchAllowedRange(QStringList ranges) override;
|
||||
@@ -43,6 +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 startNetworkCheck(const QString& serverIpv4Gateway, const QString& deviceIpv4Address) override;
|
||||
virtual bool stopNetworkCheck() override;
|
||||
|
||||
private:
|
||||
int m_localpid = 0;
|
||||
@@ -62,6 +65,7 @@ private:
|
||||
};
|
||||
|
||||
QMap<int, ProcessDescriptor> m_processes;
|
||||
PingHelper m_pingHelper;
|
||||
};
|
||||
|
||||
#endif // IPCSERVER_H
|
||||
|
||||
@@ -109,7 +109,6 @@ set(HEADERS ${HEADERS}
|
||||
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/controllerimpl.h
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/dnspingsender.h
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/localsocketcontroller.h
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/networkwatcher.h
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/networkwatcherimpl.h
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/pinghelper.h
|
||||
@@ -133,7 +132,6 @@ set(SOURCES ${SOURCES}
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/shared/leakdetector.cpp
|
||||
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/dnspingsender.cpp
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/localsocketcontroller.cpp
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/networkwatcher.cpp
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/pinghelper.cpp
|
||||
${CMAKE_CURRENT_LIST_DIR}/../../client/mozilla/pingsender.cpp
|
||||
@@ -282,6 +280,7 @@ if(LINUX)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxnetworkwatcher.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxnetworkwatcherworker.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxdependencies.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxpingsender.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/daemon/iputilslinux.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/daemon/dbustypeslinux.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/daemon/linuxdaemon.h
|
||||
@@ -296,6 +295,7 @@ if(LINUX)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxnetworkwatcher.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxnetworkwatcherworker.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxdependencies.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/linuxpingsender.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/daemon/dnsutilslinux.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/daemon/iputilslinux.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../client/platforms/linux/daemon/linuxdaemon.cpp
|
||||
|
||||
@@ -98,6 +98,17 @@ bool KillSwitch::disableKillSwitch() {
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("320.allowDNS"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("400.allowPIA"), false);
|
||||
} else {
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("000.allowLoopback"), true);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("100.blockAll"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("110.allowNets"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("120.blockNets"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("200.allowVPN"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv6, QStringLiteral("250.blockIPv6"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("290.allowDHCP"), true);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("300.allowLAN"), true);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("310.blockDNS"), false);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("320.allowDNS"), true);
|
||||
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("400.allowPIA"), false);
|
||||
LinuxFirewall::uninstall();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
#include "localserver.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QFileInfo>
|
||||
#include <QLocalServer>
|
||||
#include <QLocalSocket>
|
||||
#include <QObject>
|
||||
#include <QSharedPointer>
|
||||
#include <QString>
|
||||
|
||||
#include "ipc.h"
|
||||
#include "localserver.h"
|
||||
|
||||
#include "killswitch.h"
|
||||
#include "logger.h"
|
||||
|
||||
@@ -46,6 +50,9 @@ LocalServer::LocalServer(QObject *parent) : QObject(parent),
|
||||
return;
|
||||
}
|
||||
|
||||
m_networkWatcher.initialize();
|
||||
connect(&m_networkWatcher, &NetworkWatcher::sleepMode, &m_ipcServer, &IpcServer::networkChange);
|
||||
connect(&m_networkWatcher, &NetworkWatcher::networkChange, &m_ipcServer, &IpcServer::networkChange);
|
||||
KillSwitch::instance()->init();
|
||||
|
||||
#ifdef Q_OS_LINUX
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
#include "ipcserver.h"
|
||||
|
||||
#include "../../client/daemon/daemonlocalserver.h"
|
||||
|
||||
#include "../../client/mozilla/networkwatcher.h"
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
#include "windows/daemon/windowsdaemon.h"
|
||||
@@ -41,6 +41,8 @@ public:
|
||||
IpcProcessTun2Socks m_tun2socks;
|
||||
QRemoteObjectHost m_serverNode;
|
||||
bool m_isRemotingEnabled = false;
|
||||
|
||||
NetworkWatcher m_networkWatcher;
|
||||
#ifdef Q_OS_LINUX
|
||||
DaemonLocalServer server{qApp};
|
||||
LinuxDaemon daemon;
|
||||
|
||||
+12
-12
@@ -42,14 +42,14 @@ int Router::routeDeleteList(const QString &gw, const QStringList &ips)
|
||||
#endif
|
||||
}
|
||||
|
||||
void Router::flushDns()
|
||||
bool Router::flushDns()
|
||||
{
|
||||
#ifdef Q_OS_WIN
|
||||
RouterWin::Instance().flushDns();
|
||||
return RouterWin::Instance().flushDns();
|
||||
#elif defined (Q_OS_MAC)
|
||||
RouterMac::Instance().flushDns();
|
||||
return RouterMac::Instance().flushDns();
|
||||
#elif defined Q_OS_LINUX
|
||||
RouterLinux::Instance().flushDns();
|
||||
return RouterLinux::Instance().flushDns();
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -111,25 +111,25 @@ bool Router::restoreResolvers() {
|
||||
#endif
|
||||
}
|
||||
|
||||
void Router::StopRoutingIpv6()
|
||||
bool Router::StopRoutingIpv6()
|
||||
{
|
||||
#ifdef Q_OS_WIN
|
||||
RouterWin::Instance().StopRoutingIpv6();
|
||||
return RouterWin::Instance().StopRoutingIpv6();
|
||||
#elif defined (Q_OS_MAC)
|
||||
// todo fixme
|
||||
return true;// todo fixme
|
||||
#elif defined Q_OS_LINUX
|
||||
RouterLinux::Instance().StopRoutingIpv6();
|
||||
return RouterLinux::Instance().StopRoutingIpv6();
|
||||
#endif
|
||||
}
|
||||
|
||||
void Router::StartRoutingIpv6()
|
||||
bool Router::StartRoutingIpv6()
|
||||
{
|
||||
#ifdef Q_OS_WIN
|
||||
RouterWin::Instance().StartRoutingIpv6();
|
||||
return RouterWin::Instance().StartRoutingIpv6();
|
||||
#elif defined (Q_OS_MAC)
|
||||
// todo fixme
|
||||
return true;// todo fixme
|
||||
#elif defined Q_OS_LINUX
|
||||
RouterLinux::Instance().StartRoutingIpv6();
|
||||
return RouterLinux::Instance().StartRoutingIpv6();
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -19,12 +19,12 @@ public:
|
||||
static int routeAddList(const QString &gw, const QStringList &ips);
|
||||
static bool clearSavedRoutes();
|
||||
static int routeDeleteList(const QString &gw, const QStringList &ips);
|
||||
static void flushDns();
|
||||
static bool flushDns();
|
||||
static void resetIpStack();
|
||||
static bool createTun(const QString &dev, const QString &subnet);
|
||||
static bool deleteTun(const QString &dev);
|
||||
static void StartRoutingIpv6();
|
||||
static void StopRoutingIpv6();
|
||||
static bool StartRoutingIpv6();
|
||||
static bool StopRoutingIpv6();
|
||||
static bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers);
|
||||
static bool restoreResolvers();
|
||||
};
|
||||
|
||||
@@ -160,7 +160,7 @@ bool RouterLinux::isServiceActive(const QString &serviceName) {
|
||||
return process.exitCode() == 0;
|
||||
}
|
||||
|
||||
void RouterLinux::flushDns()
|
||||
bool RouterLinux::flushDns()
|
||||
{
|
||||
QProcess p;
|
||||
p.setProcessChannelMode(QProcess::MergedChannels);
|
||||
@@ -174,7 +174,7 @@ void RouterLinux::flushDns()
|
||||
p.start("systemctl", { "restart", "systemd-resolved" });
|
||||
} else {
|
||||
qDebug() << "No suitable DNS manager found.";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
p.waitForFinished();
|
||||
@@ -183,6 +183,8 @@ void RouterLinux::flushDns()
|
||||
qDebug().noquote() << "Flush dns completed";
|
||||
else
|
||||
qDebug().noquote() << "OUTPUT systemctl restart nscd/systemd-resolved: " + output;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RouterLinux::createTun(const QString &dev, const QString &subnet) {
|
||||
@@ -283,7 +285,7 @@ bool RouterLinux::restoreResolvers() {
|
||||
return m_dnsUtil->restoreResolvers();
|
||||
}
|
||||
|
||||
void RouterLinux::StartRoutingIpv6()
|
||||
bool RouterLinux::StartRoutingIpv6()
|
||||
{
|
||||
QProcess process;
|
||||
QStringList commands;
|
||||
@@ -293,12 +295,12 @@ void RouterLinux::StartRoutingIpv6()
|
||||
if (!process.waitForStarted(1000))
|
||||
{
|
||||
qDebug().noquote() << "Could not start activate ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
else if (!process.waitForFinished(2000))
|
||||
{
|
||||
qDebug().noquote() << "Could not activate ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
commands.clear();
|
||||
|
||||
@@ -307,19 +309,20 @@ void RouterLinux::StartRoutingIpv6()
|
||||
if (!process.waitForStarted(1000))
|
||||
{
|
||||
qDebug().noquote() << "Could not start activate ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
else if (!process.waitForFinished(2000))
|
||||
{
|
||||
qDebug().noquote() << "Could not activate ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
commands.clear();
|
||||
|
||||
qDebug().noquote() << "StartRoutingIpv6 OK";
|
||||
return true;
|
||||
}
|
||||
|
||||
void RouterLinux::StopRoutingIpv6()
|
||||
bool RouterLinux::StopRoutingIpv6()
|
||||
{
|
||||
QProcess process;
|
||||
QStringList commands;
|
||||
@@ -329,12 +332,12 @@ void RouterLinux::StopRoutingIpv6()
|
||||
if (!process.waitForStarted(1000))
|
||||
{
|
||||
qDebug().noquote() << "Could not start disable ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
else if (!process.waitForFinished(2000))
|
||||
{
|
||||
qDebug().noquote() << "Could not disable ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
commands.clear();
|
||||
|
||||
@@ -343,14 +346,15 @@ void RouterLinux::StopRoutingIpv6()
|
||||
if (!process.waitForStarted(1000))
|
||||
{
|
||||
qDebug().noquote() << "Could not start disable ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
else if (!process.waitForFinished(2000))
|
||||
{
|
||||
qDebug().noquote() << "Could not disable ipv6\n";
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
commands.clear();
|
||||
|
||||
qDebug().noquote() << "StopRoutingIpv6 OK";
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -30,11 +30,11 @@ public:
|
||||
bool routeDelete(const QString &ip, const QString &gw, const int &sock);
|
||||
bool routeDeleteList(const QString &gw, const QStringList &ips);
|
||||
QString getgatewayandiface();
|
||||
void flushDns();
|
||||
bool flushDns();
|
||||
bool createTun(const QString &dev, const QString &subnet);
|
||||
bool deleteTun(const QString &dev);
|
||||
void StartRoutingIpv6();
|
||||
void StopRoutingIpv6();
|
||||
bool StartRoutingIpv6();
|
||||
bool StopRoutingIpv6();
|
||||
bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers);
|
||||
bool restoreResolvers();
|
||||
public slots:
|
||||
|
||||
@@ -169,7 +169,7 @@ bool RouterMac::deleteTun(const QString &dev)
|
||||
return true;
|
||||
}
|
||||
|
||||
void RouterMac::flushDns()
|
||||
bool RouterMac::flushDns()
|
||||
{
|
||||
// sudo killall -HUP mDNSResponder
|
||||
QProcess p;
|
||||
@@ -177,5 +177,7 @@ void RouterMac::flushDns()
|
||||
|
||||
p.start("killall", QStringList() << "-HUP" << "mDNSResponder");
|
||||
p.waitForFinished();
|
||||
|
||||
qDebug().noquote() << "OUTPUT killall -HUP mDNSResponder: " + p.readAll();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ public:
|
||||
bool clearSavedRoutes();
|
||||
bool routeDelete(const QString &ip, const QString &gw);
|
||||
bool routeDeleteList(const QString &gw, const QStringList &ips);
|
||||
void flushDns();
|
||||
bool flushDns();
|
||||
bool createTun(const QString &dev, const QString &subnet);
|
||||
bool deleteTun(const QString &dev);
|
||||
bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers);
|
||||
|
||||
@@ -273,7 +273,7 @@ int RouterWin::routeDeleteList(const QString &gw, const QStringList &ips)
|
||||
return success_count;
|
||||
}
|
||||
|
||||
void RouterWin::flushDns()
|
||||
bool RouterWin::flushDns()
|
||||
{
|
||||
QProcess p;
|
||||
p.setProcessChannelMode(QProcess::MergedChannels);
|
||||
@@ -281,6 +281,7 @@ void RouterWin::flushDns()
|
||||
|
||||
p.start(command);
|
||||
p.waitForFinished();
|
||||
return true;
|
||||
//qDebug().noquote() << "OUTPUT ipconfig /flushdns: " + p.readAll();
|
||||
}
|
||||
|
||||
@@ -447,7 +448,7 @@ bool RouterWin::restoreResolvers() {
|
||||
return m_dnsUtil->restoreResolvers();
|
||||
}
|
||||
|
||||
void RouterWin::StopRoutingIpv6()
|
||||
bool RouterWin::StopRoutingIpv6()
|
||||
{
|
||||
{
|
||||
QProcess p;
|
||||
@@ -467,9 +468,10 @@ void RouterWin::StopRoutingIpv6()
|
||||
p.start(command);
|
||||
p.waitForFinished();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void RouterWin::StartRoutingIpv6()
|
||||
bool RouterWin::StartRoutingIpv6()
|
||||
{
|
||||
{
|
||||
QProcess p;
|
||||
@@ -489,5 +491,6 @@ void RouterWin::StartRoutingIpv6()
|
||||
p.start(command);
|
||||
p.waitForFinished();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -39,11 +39,11 @@ public:
|
||||
int routeAddList(const QString &gw, const QStringList &ips);
|
||||
bool clearSavedRoutes();
|
||||
int routeDeleteList(const QString &gw, const QStringList &ips);
|
||||
void flushDns();
|
||||
bool flushDns();
|
||||
void resetIpStack();
|
||||
|
||||
void StartRoutingIpv6();
|
||||
void StopRoutingIpv6();
|
||||
bool StartRoutingIpv6();
|
||||
bool StopRoutingIpv6();
|
||||
|
||||
void suspendWcmSvc(bool suspend);
|
||||
bool updateResolvers(const QString& ifname, const QList<QHostAddress>& resolvers);
|
||||
|
||||
Reference in New Issue
Block a user