Compare commits

..
Author SHA1 Message Date
yp bf0bd2aec9 fix(windows): wintun adapter lifecycle 2026-11-26 17:12:00 +03:00
10 changed files with 339 additions and 89 deletions

No files matched your search

+48 -25
View File
@@ -139,28 +139,42 @@ void XrayProtocol::stop()
if (m_tun2socksProcess) {
m_tun2socksProcess->blockSignals(true);
bool stopped = m_tun2socksFinished;
// QProcess::terminate() posts WM_CLOSE, which a console process on Windows never sees
#ifndef Q_OS_WIN
m_tun2socksProcess->terminate();
auto waitForFinished = m_tun2socksProcess->waitForFinished(1000);
if (!waitForFinished.waitForFinished() || !waitForFinished.returnValue()) {
qWarning() << "Failed to terminate tun2socks. Killing the process...";
m_tun2socksProcess->kill();
if (!stopped) {
m_tun2socksProcess->terminate();
auto terminated = m_tun2socksProcess->waitForFinished(tun2socksShutdownTimeoutMs);
stopped = terminated.waitForFinished() && terminated.returnValue();
if (!stopped) {
qWarning() << "Failed to terminate tun2socks. Killing the process...";
}
}
#else
// terminate does not do anything useful on Windows
// so just kill the process
m_tun2socksProcess->kill();
#endif
if (!stopped) {
m_tun2socksProcess->kill();
auto killed = m_tun2socksProcess->waitForFinished(tun2socksShutdownTimeoutMs);
if (!killed.waitForFinished() || !killed.returnValue()) {
qWarning() << "tun2socks is still running, the tun device may stay busy";
}
}
m_tun2socksProcess->close();
m_tun2socksProcess.reset();
}
m_tun2socksErrorOutput.clear();
m_tun2socksFinished = false;
setConnectionState(Vpn::ConnectionState::Disconnected);
}
ErrorCode XrayProtocol::startTun2Socks()
{
m_tun2socksErrorOutput.clear();
m_tun2socksFinished = false;
m_tun2socksProcess = IpcClient::CreatePrivilegedProcess();
if (!m_tun2socksProcess->waitForSource()) {
return ErrorCode::AmneziaServiceConnectionFailed;
@@ -186,6 +200,11 @@ ErrorCode XrayProtocol::startTun2Socks()
const QString line = readAllStandardError.returnValue();
m_tun2socksErrorOutput.append(line);
if (m_tun2socksErrorOutput.size() > tun2socksErrorBufferSize) {
m_tun2socksErrorOutput = m_tun2socksErrorOutput.right(tun2socksErrorBufferSize);
}
if (!line.contains("[TCP]") && !line.contains("[UDP]"))
qDebug() << "[tun2socks]:" << line;
@@ -205,23 +224,24 @@ ErrorCode XrayProtocol::startTun2Socks()
connect(
m_tun2socksProcess.data(), &IpcProcessInterfaceReplica::finished, this,
[this](int exitCode, QProcess::ExitStatus exitStatus) {
// Check stdout for "resource busy" — the TUN device was not yet released
// by the previous tun2socks instance. Retry after a short delay.
bool resourceBusy = false;
if (m_tun2socksProcess) {
auto readOut = m_tun2socksProcess->readAllStandardOutput();
if (readOut.waitForFinished()) {
resourceBusy = readOut.returnValue().contains("resource busy");
}
}
m_tun2socksFinished = true;
if (resourceBusy && m_tun2socksRetryCount < maxTun2SocksRetries) {
const bool adapterCreationFailed = m_tun2socksErrorOutput.contains("Error creating interface");
const bool deviceBusy = m_tun2socksErrorOutput.contains("resource busy");
const int maxRetries = adapterCreationFailed ? maxTun2SocksAdapterRetries : maxTun2SocksRetries;
const int retryDelayMs = adapterCreationFailed ? tun2socksAdapterRetryDelayMs : tun2socksRetryDelayMs;
if ((adapterCreationFailed || deviceBusy) && m_tun2socksRetryCount < maxRetries) {
m_tun2socksRetryCount++;
qWarning() << QString("Tun2socks: TUN resource busy, retrying (%1/%2) in %3ms...")
.arg(m_tun2socksRetryCount)
.arg(maxTun2SocksRetries)
.arg(tun2socksRetryDelayMs);
QTimer::singleShot(tun2socksRetryDelayMs, this, [this]() {
qWarning() << QString("Tun2socks: failed to open the tun device, retrying (%1/%2) in %3ms...")
.arg(m_tun2socksRetryCount)
.arg(maxRetries)
.arg(retryDelayMs);
QTimer::singleShot(retryDelayMs, this, [this]() {
if (m_stopped) {
return;
}
if (ErrorCode err = startTun2Socks(); err != ErrorCode::NoError) {
stop();
setLastError(err);
@@ -237,8 +257,11 @@ ErrorCode XrayProtocol::startTun2Socks()
} else {
qCritical() << QString("Tun2socks process was closed with %1 exit code").arg(exitCode);
}
const ErrorCode error = adapterCreationFailed ? ErrorCode::Tun2SockAdapterCreationFailed
: ErrorCode::Tun2SockExecutableCrashed;
stop();
setLastError(ErrorCode::Tun2SockExecutableCrashed);
setLastError(error);
},
Qt::QueuedConnection);
+6
View File
@@ -35,9 +35,15 @@ private:
int m_socksPort = 10808;
QSharedPointer<IpcProcessInterfaceReplica> m_tun2socksProcess;
QString m_tun2socksErrorOutput;
bool m_tun2socksFinished = false;
int m_tun2socksRetryCount = 0;
static constexpr int maxTun2SocksRetries = 5;
static constexpr int maxTun2SocksAdapterRetries = 1;
static constexpr int tun2socksRetryDelayMs = 400;
static constexpr int tun2socksAdapterRetryDelayMs = 2000;
static constexpr int tun2socksShutdownTimeoutMs = 2000;
static constexpr int tun2socksErrorBufferSize = 4096;
// Owner token of the shared xray engine; a late stop with a stale token
// won't kill an engine restarted by another consumer (e.g. the local proxy).
+1
View File
@@ -81,6 +81,7 @@ namespace amnezia
OpenSslFailed = 800,
XrayExecutableCrashed = 803,
Tun2SockExecutableCrashed = 804,
Tun2SockAdapterCreationFailed = 805,
// import and install errors
ImportInvalidConfigError = 900,
+3
View File
@@ -102,6 +102,9 @@ QString errorString(ErrorCode code) {
case (ErrorCode::OpenVpnAdaptersInUseError): errorMessage = QObject::tr("Can't connect: another VPN connection is active"); break;
case (ErrorCode::OpenVpnTapAdapterError): errorMessage = QObject::tr("Can't setup OpenVPN TAP network adapter"); break;
case (ErrorCode::AddressPoolError): errorMessage = QObject::tr("VPN pool error: no available addresses"); break;
case (ErrorCode::XrayExecutableCrashed): errorMessage = QObject::tr("Can't start the XRay process"); break;
case (ErrorCode::Tun2SockExecutableCrashed): errorMessage = QObject::tr("The tun2socks process stopped unexpectedly"); break;
case (ErrorCode::Tun2SockAdapterCreationFailed): errorMessage = QObject::tr("Can't create the virtual network adapter. Reconnect, and if that doesn't help, restart your computer"); break;
case (ErrorCode::ImportInvalidConfigError): errorMessage = QObject::tr("The config does not contain any containers and credentials for connecting to the server"); break;
case (ErrorCode::ImportBackupFileUseRestoreInstead): errorMessage = QObject::tr("Backup files cannot be imported here. Use 'Restore from backup' instead."); break;
+28 -4
View File
@@ -213,9 +213,25 @@ bool Utils::processIsRunning(const QString &fileName, const bool fullFlag)
#endif
}
#ifdef Q_OS_WIN
static bool imagePathMatches(HANDLE process, const QString &expectedPath)
{
wchar_t image[MAX_PATH] = {};
DWORD size = MAX_PATH;
if (!QueryFullProcessImageNameW(process, 0, image, &size)) {
return false;
}
const QString actualPath = QDir::cleanPath(QString::fromWCharArray(image, size));
return actualPath.compare(expectedPath, Qt::CaseInsensitive) == 0;
}
#endif
bool Utils::killProcessByName(const QString &name)
{
qDebug().noquote() << "Kill process" << name;
const QFileInfo target(name);
const QString processName = target.fileName();
const QString processPath = processName == name ? QString() : QDir::cleanPath(target.absoluteFilePath());
qDebug().noquote() << "Kill process" << processName;
#ifdef Q_OS_WIN
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
@@ -230,8 +246,13 @@ bool Utils::killProcessByName(const QString &name)
do {
QString exeFile = QString::fromWCharArray(pe32.szExeFile);
if (exeFile.compare(name, Qt::CaseInsensitive) == 0) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe32.th32ProcessID);
if (exeFile.compare(processName, Qt::CaseInsensitive) == 0) {
HANDLE hProcess =
OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe32.th32ProcessID);
if (hProcess != NULL && !processPath.isEmpty() && !imagePathMatches(hProcess, processPath)) {
CloseHandle(hProcess);
continue;
}
if (hProcess != NULL) {
if (TerminateProcess(hProcess, 0)) {
success = true;
@@ -253,7 +274,10 @@ bool Utils::killProcessByName(const QString &name)
#elif defined Q_OS_IOS || defined(Q_OS_ANDROID)
return false;
#else
return QProcess::execute("pkill", { name }) == 0;
if (processPath.isEmpty()) {
return QProcess::execute("pkill", { processName }) == 0;
}
return QProcess::execute("pkill", { "-f", "^" + processPath + "( |$)" }) == 0;
#endif
}
@@ -20,6 +20,11 @@
"\\pipe\\ProtectedPrefix\\Administrators\\AmneziaWG\\AmneziaVPN"
constexpr uint32_t WINDOWS_TUNNEL_MONITOR_TIMEOUT_MSEC = 2000;
constexpr int WINDOWS_TUNNEL_START_ATTEMPTS = 2;
constexpr uint32_t WINDOWS_TUNNEL_START_RETRY_MSEC = 2000;
constexpr DWORD WINTUN_CREATION_EXIT_CODE = 3;
constexpr int SERVICE_CREATE_ATTEMPTS = 5;
constexpr uint32_t SERVICE_CREATE_RETRY_MSEC = 500;
namespace {
Logger logger("WindowsTunnelService");
@@ -28,6 +33,32 @@ Logger logger("WindowsTunnelService");
static bool stopAndDeleteTunnelService(SC_HANDLE service);
static bool waitForServiceStatus(SC_HANDLE service, DWORD expectedStatus);
// The name stays reserved for a moment after the tunnel unregisters itself,
// so creating it again right away can fail with ERROR_SERVICE_MARKED_FOR_DELETE
static SC_HANDLE createTunnelService(SC_HANDLE scm, const QString& cmdline) {
for (int attempt = 1; attempt <= SERVICE_CREATE_ATTEMPTS; ++attempt) {
SC_HANDLE service =
CreateService(scm, TUNNEL_SERVICE_NAME, L"Amnezia VPN (tunnel)",
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
(const wchar_t*)cmdline.utf16(), nullptr, 0,
TEXT("Nsi\0TcpIp\0"), nullptr, nullptr);
if (service != nullptr) {
return service;
}
if (GetLastError() != ERROR_SERVICE_MARKED_FOR_DELETE ||
attempt == SERVICE_CREATE_ATTEMPTS) {
return nullptr;
}
logger.debug() << "The tunnel service is still being deleted, waiting";
Sleep(SERVICE_CREATE_RETRY_MSEC);
}
return nullptr;
}
WindowsTunnelService::WindowsTunnelService(QObject* parent) : QObject(parent) {
MZ_COUNT_CTOR(WindowsTunnelService);
logger.debug() << "WindowsTunnelService created.";
@@ -128,17 +159,6 @@ bool WindowsTunnelService::start(const QString& configData) {
m_logworker = nullptr;
});
// Let's see if we have to delete a previous instance.
service = OpenService(scm, TUNNEL_SERVICE_NAME, SERVICE_ALL_ACCESS);
if (service) {
logger.debug() << "An existing service has been detected. Let's close it.";
if (!stopAndDeleteTunnelService(service)) {
return false;
}
CloseServiceHandle(service);
service = nullptr;
}
QString serviceCmdline;
{
QTextStream out(&serviceCmdline);
@@ -148,57 +168,84 @@ bool WindowsTunnelService::start(const QString& configData) {
logger.debug() << "Service:" << qApp->applicationFilePath();
service = CreateService(scm, TUNNEL_SERVICE_NAME, L"Amnezia VPN (tunnel)",
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
(const wchar_t*)serviceCmdline.utf16(), nullptr, 0,
TEXT("Nsi\0TcpIp\0"), nullptr, nullptr);
if (!service) {
WindowsUtils::windowsLog("Failed to create the tunnel service");
return false;
for (int attempt = 1; attempt <= WINDOWS_TUNNEL_START_ATTEMPTS; ++attempt) {
// The tunnel service unregisters itself when it exits, so every attempt
// has to register it again rather than reuse the previous handle.
service = OpenService(scm, TUNNEL_SERVICE_NAME, SERVICE_ALL_ACCESS);
if (service) {
logger.debug() << "An existing service has been detected. Let's close it.";
if (!stopAndDeleteTunnelService(service)) {
return false;
}
CloseServiceHandle(service);
service = nullptr;
}
service = createTunnelService(scm, serviceCmdline);
if (!service) {
WindowsUtils::windowsLog("Failed to create the tunnel service");
return false;
}
SERVICE_DESCRIPTION sd = {
(wchar_t*)L"Manages the Amnezia VPN tunnel connection"};
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &sd)) {
WindowsUtils::windowsLog(
"Failed to set the description to the tunnel service");
return false;
}
SERVICE_SID_INFO ssi;
ssi.dwServiceSidType = SERVICE_SID_TYPE_UNRESTRICTED;
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_SERVICE_SID_INFO, &ssi)) {
WindowsUtils::windowsLog("Failed to set the SID to the tunnel service");
return false;
}
if (!StartService(service, 0, nullptr)) {
WindowsUtils::windowsLog("Failed to start the service");
return false;
}
if (waitForServiceStatus(service, SERVICE_RUNNING)) {
logger.debug() << "The tunnel service is up and running";
guard.dismiss();
m_service = service;
m_timer.start(WINDOWS_TUNNEL_MONITOR_TIMEOUT_MSEC);
return true;
}
SERVICE_STATUS status;
if (!QueryServiceStatus(service, &status)) {
WindowsUtils::windowsLog("Failed to retrieve the service status");
return false;
}
logger.error() << "The tunnel service exited with status:"
<< status.dwWin32ExitCode << "-" << exitCodeToFailure(&status);
bool adapterCreationFailed =
status.dwWin32ExitCode == ERROR_SERVICE_SPECIFIC_ERROR &&
status.dwServiceSpecificExitCode == WINTUN_CREATION_EXIT_CODE;
if (adapterCreationFailed) {
WindowsUtils::logNetworkStackDiagnostics();
}
if (!adapterCreationFailed || attempt == WINDOWS_TUNNEL_START_ATTEMPTS) {
logger.error() << "Failed to run the tunnel service";
emit backendFailure();
return false;
}
CloseServiceHandle(service);
service = nullptr;
logger.warning() << "Retrying the tunnel service, attempt" << attempt + 1
<< "of" << WINDOWS_TUNNEL_START_ATTEMPTS;
Sleep(WINDOWS_TUNNEL_START_RETRY_MSEC);
}
SERVICE_DESCRIPTION sd = {
(wchar_t*)L"Manages the Amnezia VPN tunnel connection"};
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &sd)) {
WindowsUtils::windowsLog(
"Failed to set the description to the tunnel service");
return false;
}
SERVICE_SID_INFO ssi;
ssi.dwServiceSidType = SERVICE_SID_TYPE_UNRESTRICTED;
if (!ChangeServiceConfig2(service, SERVICE_CONFIG_SERVICE_SID_INFO, &ssi)) {
WindowsUtils::windowsLog("Failed to set the SID to the tunnel service");
return false;
}
if (!StartService(service, 0, nullptr)) {
WindowsUtils::windowsLog("Failed to start the service");
return false;
}
if (waitForServiceStatus(service, SERVICE_RUNNING)) {
logger.debug() << "The tunnel service is up and running";
guard.dismiss();
m_service = service;
m_timer.start(WINDOWS_TUNNEL_MONITOR_TIMEOUT_MSEC);
return true;
}
logger.error() << "Failed to run the tunnel service";
SERVICE_STATUS status;
if (!QueryServiceStatus(service, &status)) {
WindowsUtils::windowsLog("Failed to retrieve the service status");
return false;
}
logger.debug() << "The tunnel service exited with status:"
<< status.dwWin32ExitCode << "-" << exitCodeToFailure(&status);
emit backendFailure();
return false;
}
@@ -297,6 +344,11 @@ static bool waitForServiceStatus(SC_HANDLE service, DWORD expectedStatus) {
return true;
}
if (expectedStatus == SERVICE_RUNNING &&
status.dwCurrentState == SERVICE_STOPPED) {
return false;
}
logger.warning() << "The service is not in the right status yet.";
Sleep(1000);
+125
View File
@@ -5,10 +5,13 @@
#include "windowsutils.h"
#include <Windows.h>
#include <cfgmgr32.h>
#include <errhandlingapi.h>
#include <QScopeGuard>
#include <QSettings>
#include <QSysInfo>
#include <QVector>
#include "logger.h"
@@ -60,3 +63,125 @@ QString WindowsUtils::windowsVersion() {
void WindowsUtils::forceCrash() {
RaiseException(0x0000DEAD, EXCEPTION_NONCONTINUABLE, 0, NULL);
}
namespace {
QString serviceStateName(DWORD state) {
switch (state) {
case SERVICE_STOPPED:
return "stopped";
case SERVICE_START_PENDING:
return "start pending";
case SERVICE_STOP_PENDING:
return "stop pending";
case SERVICE_RUNNING:
return "running";
default:
return QString("state %1").arg(state);
}
}
QString serviceStartTypeName(DWORD startType) {
switch (startType) {
case SERVICE_AUTO_START:
return "auto";
case SERVICE_DEMAND_START:
return "demand";
case SERVICE_DISABLED:
return "disabled";
default:
return QString("start type %1").arg(startType);
}
}
void logServiceState(const QString& name) {
SC_HANDLE scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT);
if (scm == nullptr) {
WindowsUtils::windowsLog("Failed to open SCManager");
return;
}
auto scmGuard = qScopeGuard([&] { CloseServiceHandle(scm); });
SC_HANDLE service = OpenService(scm, (const wchar_t*)name.utf16(),
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
if (service == nullptr) {
WindowsUtils::windowsLog("Failed to open the service " + name);
return;
}
auto serviceGuard = qScopeGuard([&] { CloseServiceHandle(service); });
SERVICE_STATUS status;
QString state = QueryServiceStatus(service, &status)
? serviceStateName(status.dwCurrentState)
: QString("unknown state");
DWORD required = 0;
QueryServiceConfig(service, nullptr, 0, &required);
QByteArray buffer(required, 0);
auto* config = reinterpret_cast<LPQUERY_SERVICE_CONFIG>(buffer.data());
QString startType =
config != nullptr && QueryServiceConfig(service, config, required, &required)
? serviceStartTypeName(config->dwStartType)
: QString("unknown start type");
logger.debug() << name << "is" << state << "with start type" << startType;
}
void logWintunDevices() {
const wchar_t* enumerator = L"SWD\\WINTUN";
ULONG length = 0;
if (CM_Get_Device_ID_List_SizeW(&length, enumerator,
CM_GETIDLIST_FILTER_ENUMERATOR) != CR_SUCCESS) {
logger.warning() << "Failed to size the Wintun device list";
return;
}
if (length == 0) {
logger.debug() << "No Wintun devices are registered";
return;
}
QVector<wchar_t> buffer(length, 0);
if (CM_Get_Device_ID_ListW(enumerator, buffer.data(), length,
CM_GETIDLIST_FILTER_ENUMERATOR) != CR_SUCCESS) {
logger.warning() << "Failed to enumerate the Wintun devices";
return;
}
bool found = false;
for (const wchar_t* id = buffer.constData(); *id != 0; id += wcslen(id) + 1) {
found = true;
const QString deviceId = QString::fromWCharArray(id);
DEVINST device = 0;
if (CM_Locate_DevNodeW(&device, const_cast<wchar_t*>(id),
CM_LOCATE_DEVNODE_PHANTOM) != CR_SUCCESS) {
logger.debug() << "Wintun device" << deviceId << "cannot be located";
continue;
}
ULONG status = 0;
ULONG problem = 0;
if (CM_Get_DevNode_Status(&status, &problem, device, 0) != CR_SUCCESS) {
logger.debug() << "Wintun device" << deviceId << "has no status";
continue;
}
logger.debug() << "Wintun device" << deviceId << "status"
<< QString::number(status, 16) << "problem code"
<< QString::number(problem, 16);
}
if (!found) {
logger.debug() << "No Wintun devices are registered";
}
}
} // namespace
// static
void WindowsUtils::logNetworkStackDiagnostics() {
logServiceState("NetSetupSvc");
logWintunDevices();
}
+2
View File
@@ -16,6 +16,8 @@ class WindowsUtils final {
// Returns the major version of Windows
static QString windowsVersion();
static void logNetworkStackDiagnostics();
// Force an application crash for testing
static void forceCrash();
};
+13
View File
@@ -2,6 +2,10 @@
#include "ipc.h"
#include <QProcess>
#ifdef Q_OS_WIN
#include "platforms/windows/windowsutils.h"
#endif
#ifndef Q_OS_IOS
IpcServerProcess::IpcServerProcess(QObject *parent) :
@@ -20,6 +24,15 @@ IpcServerProcess::IpcServerProcess(QObject *parent) :
qDebug() << "IpcServerProcess errorOccurred " << error;
});
#ifdef Q_OS_WIN
connect(m_process.data(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
[&](int exitCode, QProcess::ExitStatus){
if (exitCode != 0 && m_program == amnezia::PermittedProcess::Tun2Socks) {
WindowsUtils::logNetworkStackDiagnostics();
}
});
#endif
}
IpcServerProcess::~IpcServerProcess()
+1
View File
@@ -181,6 +181,7 @@ if(WIN32)
gdi32
Advapi32
Kernel32
cfgmgr32
qt6keychain
)