Compare commits

...
Author SHA1 Message Date
yp 440fd2f6f5 fix: share failover state across controllers, keep the working proxy per run 2026-10-02 10:00:25 +03:00
yp 93aa3b6247 fix: run libagw calls off the main thread
fix: accept gateway answers without http_status
fix: stop logging server config with private keys
fix: destroy news gateway controller on its own thread
fix: keep agw failover state per environment and gateway
2026-10-01 18:54:59 +03:00
vkamn 2f6bed2853 fix: build fixes 2026-09-30 13:19:18 +08:00
vkamn e48cfabbf0 Merge branch 'dev' of github-amnezia:amnezia-vpn/amnezia-client into HEAD 2026-09-30 11:25:20 +08:00
vkamn d9760bf732 refactor: gateway error code parsing 2026-09-08 19:03:14 +08:00
vkamn a020e7c527 Merge branch 'dev' of github-amnezia:amnezia-vpn/amnezia-client into HEAD 2026-09-08 15:12:14 +08:00
vkamn 28b92fa73c Merge branch 'dev' of github-amnezia:amnezia-vpn/amnezia-client into feat/switch-to-libagw 2026-08-25 15:24:05 +08:00
vkamn cf549e8d54 chore: fix android build with agw 2026-08-24 23:48:31 +08:00
vkamn 9eeed61274 feat: add conanfile for libagw 2026-08-24 22:28:21 +08:00
vkamn 1d5061f2fc feat: use libagw 2026-08-24 17:04:30 +08:00
16 changed files with 733 additions and 770 deletions

No files matched your search

+4
View File
@@ -43,11 +43,15 @@ endif()
find_package(Qt6 REQUIRED COMPONENTS ${PACKAGES})
find_package(OpenSSL REQUIRED)
# Gateway transport (envelope crypto, HTTP, proxy failover) — Go library.
find_package(libagw REQUIRED)
set(LIBS ${LIBS}
Qt6::Core Qt6::Gui
Qt6::Network Qt6::Xml Qt6::RemoteObjects
Qt6::Quick Qt6::Svg Qt6::QuickControls2
Qt6::Core5Compat Qt6::Concurrent
amnezia::libagw
)
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
+2
View File
@@ -59,6 +59,8 @@ find_package(openvpn-pt-android REQUIRED)
set(LIBS ${LIBS} amnezia::openvpn-pt-android)
set_property(TARGET ${PROJECT} APPEND PROPERTY QT_ANDROID_EXTRA_LIBS ${OPENVPN_PT_ANDROID_LIBCK_OVPN_PLUGIN_PATH})
set_property(TARGET ${PROJECT} APPEND PROPERTY QT_ANDROID_EXTRA_LIBS ${LIBAGW_LIBRARY_PATH})
set(APP_ANDROID_PACKAGE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/android)
if(APP_ANDROID_MAX_SDK)
@@ -76,12 +76,11 @@ QFuture<QPair<ErrorCode, QJsonArray>> NewsController::fetchNews()
return QtFuture::makeReadyFuture(qMakePair(ErrorCode::NoError, QJsonArray()));
}
auto gatewayController = QSharedPointer<GatewayController>::create(
m_appSettingsRepository->getGatewayEndpoint(),
m_appSettingsRepository->isDevGatewayEnv(),
apiDefs::requestTimeoutMsecs,
m_appSettingsRepository->isStrictKillSwitchEnabled(),
m_appSettingsRepository);
QSharedPointer<GatewayController> gatewayController(
new GatewayController(m_appSettingsRepository->getGatewayEndpoint(), m_appSettingsRepository->isDevGatewayEnv(),
apiDefs::requestTimeoutMsecs, m_appSettingsRepository->isStrictKillSwitchEnabled(),
m_appSettingsRepository),
&QObject::deleteLater);
// both country codes and service types are arrays here, one entry per gateway stack the user has
const QJsonObject payload = GatewayPayloadBuilder(m_appSettingsRepository)
File diff suppressed because it is too large. Load diff
+27 -44
View File
@@ -1,23 +1,24 @@
#ifndef GATEWAYCONTROLLER_H
#define GATEWAYCONTROLLER_H
#include <QByteArray>
#include <QFuture>
#include <QNetworkReply>
#include <QJsonObject>
#include <QObject>
#include <QPair>
#include <QPromise>
#include <QSharedPointer>
#include <QString>
#include "core/utils/errorCodes.h"
#include "core/utils/routeModes.h"
#include "core/utils/commonStructs.h"
#ifdef Q_OS_IOS
#include "platforms/ios/ios_controller.h"
#endif
#include "agw.h"
class SecureAppSettingsRepository;
// Thin Qt facade over the libagw transport: the envelope crypto, HTTP and
// proxy failover live in the Go library; this class
// keeps the historical GatewayController API for the existing call sites and
// wires the host-side concerns (killswitch exceptions, iOS inet access, state
// persistence) into the library callbacks.
class GatewayController : public QObject
{
Q_OBJECT
@@ -26,51 +27,33 @@ public:
explicit GatewayController(const QString &gatewayEndpoint, const bool isDevEnvironment, const int requestTimeoutMsecs,
const bool isStrictKillSwitchEnabled, SecureAppSettingsRepository *appSettingsRepository,
QObject *parent = nullptr);
~GatewayController() override;
// Blocks like the old implementation did: pumps a local event loop
// (ExcludeUserInputEvents) until the request completes, so UI-thread
// callers keep their behaviour.
amnezia::ErrorCode post(const QString &endpoint, const QJsonObject apiPayload, QByteArray &responseBody);
// Runs the request on a worker thread. The controller must outlive the
// returned future (call sites hold it in a QSharedPointer).
QFuture<QPair<amnezia::ErrorCode, QByteArray>> postAsync(const QString &endpoint, const QJsonObject apiPayload);
// Internal: invoked from the library's on_before_request callback,
// marshalled to this object's thread. Public only for the C trampoline.
void handleBeforeRequest(const QString &host);
private:
struct EncryptedRequestData
{
QNetworkRequest request;
QByteArray requestBody;
QByteArray key;
QByteArray iv;
QByteArray salt;
amnezia::ErrorCode errorCode;
};
QPair<amnezia::ErrorCode, QByteArray> executePost(const QString &endpoint, const QJsonObject &apiPayload);
static amnezia::ErrorCode mapResultCode(const int code, const QByteArray &responseBody);
void persistState();
struct DecryptionResult
{
QByteArray decryptedBody;
bool isDecryptionSuccessful;
};
EncryptedRequestData prepareRequest(const QString &endpoint, const QJsonObject &apiPayload);
DecryptionResult tryDecryptResponseBody(const QByteArray &encryptedResponseBody, QNetworkReply::NetworkError replyError,
const QByteArray &key, const QByteArray &iv, const QByteArray &salt);
QStringList getProxyUrls(const QString &serviceType, const QString &userCountryCode);
bool shouldBypassProxy(const QNetworkReply::NetworkError &replyError, const QByteArray &decryptedResponseBody, bool isDecryptionSuccessful);
void bypassProxy(const QString &endpoint, const QString &serviceType, const QString &userCountryCode,
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,
const QString &proxyUrlsCacheKey, 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 &, bool, const QList<QSslError> &, QNetworkReply::NetworkError, const QString &, int)> onComplete);
int m_requestTimeoutMsecs;
QString m_gatewayEndpoint;
bool m_isDevEnvironment = false;
bool m_isStrictKillSwitchEnabled = false;
SecureAppSettingsRepository *m_appSettingsRepository = nullptr;
inline static QString m_proxyUrl;
agw_client_handle m_client = 0;
bool m_publicKeyMissing = false;
QJsonObject m_baseState;
QString m_stateKey;
};
#endif // GATEWAYCONTROLLER_H
@@ -324,6 +324,26 @@ void SecureAppSettingsRepository::writeGatewayProxyUrls(const QString &cacheKey,
setValue(QStringLiteral("Conf/proxyUrls/") + cacheKey, proxyUrlsEncrypted);
}
QStringList SecureAppSettingsRepository::legacyGatewayProxyListKeys() const
{
const QString prefix = QStringLiteral("Conf/proxyUrls/");
QStringList result;
for (const QString &key : m_settings->keys(prefix + QStringLiteral("service_"))) {
result.append(key.mid(prefix.size()));
}
return result;
}
QByteArray SecureAppSettingsRepository::readLegacyGatewayProxyList(const QString &cacheKey) const
{
return value(QStringLiteral("Conf/proxyUrls/") + cacheKey).toByteArray();
}
void SecureAppSettingsRepository::removeLegacyGatewayProxyList(const QString &cacheKey)
{
m_settings->remove(QStringLiteral("Conf/proxyUrls/") + cacheKey);
}
bool SecureAppSettingsRepository::isKillSwitchEnabled() const
{
return value("Conf/killSwitchEnabled", true).toBool();
@@ -65,6 +65,9 @@ public:
void toggleDevGatewayEnv(bool enabled);
QByteArray readGatewayProxyUrls(const QString &cacheKey) const;
void writeGatewayProxyUrls(const QString &cacheKey, const QByteArray &proxyUrlsEncrypted);
QStringList legacyGatewayProxyListKeys() const;
QByteArray readLegacyGatewayProxyList(const QString &cacheKey) const;
void removeLegacyGatewayProxyList(const QString &cacheKey);
bool isKillSwitchEnabled() const;
void setKillSwitchEnabled(bool enabled);
+52 -67
View File
@@ -111,9 +111,7 @@ bool apiUtils::isSubscriptionExpiringSoon(const QString &subscriptionEndDate, in
return endDate <= nowUtc.addDays(withinDays);
}
amnezia::ErrorCode apiUtils::checkNetworkReplyErrors(const QList<QSslError> &sslErrors, const QString &replyErrorString,
const QNetworkReply::NetworkError &replyError, const int httpStatusCode,
const QByteArray &responseBody)
amnezia::ErrorCode apiUtils::checkApiResponseErrors(const QByteArray &responseBody)
{
const int httpStatusCodeConflict = 409;
const int httpStatusCodeNotFound = 404;
@@ -123,76 +121,63 @@ amnezia::ErrorCode apiUtils::checkNetworkReplyErrors(const QList<QSslError> &ssl
const int httpStatusCodeRequestTimeout = 408;
const int httpStatusCodeUnprocessableEntity = 422;
if (!sslErrors.empty()) {
qDebug().noquote() << sslErrors;
return amnezia::ErrorCode::ApiConfigSslError;
}
if (replyError == QNetworkReply::NetworkError::OperationCanceledError
|| replyError == QNetworkReply::NetworkError::TimeoutError) {
qDebug() << replyError;
return amnezia::ErrorCode::ApiConfigTimeoutError;
}
if (replyError == QNetworkReply::NetworkError::OperationNotImplementedError) {
qDebug() << replyError;
return amnezia::ErrorCode::ApiUpdateRequestError;
if (responseBody.isEmpty()) {
return amnezia::ErrorCode::ApiConfigDecryptionError;
}
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseBody);
if (jsonDoc.isObject()) {
QJsonObject jsonObj = jsonDoc.object();
const int httpStatusFromBody = jsonObj.value(QStringLiteral("http_status")).toInt(-1);
if (httpStatusFromBody == httpStatusCodeTooManyRequests) {
return amnezia::ErrorCode::ApiRateLimitError;
}
if (httpStatusFromBody == httpStatusCodeConflict) {
if (apiErrorMessageFromJson(jsonObj).contains(trialAlreadyUsedMessage, Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiTrialAlreadyUsedError;
}
return amnezia::ErrorCode::ApiConfigLimitError;
}
if (httpStatusFromBody == httpStatusCodeNotFound) {
return amnezia::ErrorCode::ApiNotFoundError;
}
if (httpStatusFromBody == httpStatusCodeRequestTimeout) {
return amnezia::ErrorCode::ApiConfigTimeoutError;
}
if (httpStatusFromBody == httpStatusCodeNotImplemented) {
return amnezia::ErrorCode::ApiUpdateRequestError;
}
if (httpStatusFromBody == httpStatusCodeUnprocessableEntity) {
if (apiErrorMessageFromJson(jsonObj) == unprocessableSubscriptionMessage) {
return amnezia::ErrorCode::ApiSubscriptionExpiredError;
}
return amnezia::ErrorCode::ApiConfigDownloadError;
}
if (httpStatusFromBody == httpStatusCodePaymentRequired) {
const QString message = apiErrorMessageFromJson(jsonObj);
if (message.contains(QLatin1String("refresh_captcha"), Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiCaptchaRefreshError;
}
if (message.contains(QLatin1String("invalid_captcha"), Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiCaptchaInvalidError;
}
if (jsonObj.contains(QStringLiteral("captcha_id")) || jsonObj.contains(QStringLiteral("captcha_image"))
|| message.compare(QLatin1String("rate_limit_exceeded"), Qt::CaseInsensitive) == 0
|| message.contains(QLatin1String("rate_limit_exceeded"), Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiCaptchaRequiredError;
}
return amnezia::ErrorCode::ApiSubscriptionNotActiveError;
}
if (httpStatusFromBody >= 300) {
return amnezia::ErrorCode::ApiConfigDownloadError;
}
}
if (replyError == QNetworkReply::NoError) {
if (!jsonDoc.isObject()) {
return amnezia::ErrorCode::NoError;
}
qDebug() << "something went wrong";
return amnezia::ErrorCode::ApiConfigDownloadError;
QJsonObject jsonObj = jsonDoc.object();
const int httpStatusFromBody = jsonObj.value(QStringLiteral("http_status")).toInt(-1);
if (httpStatusFromBody == httpStatusCodeTooManyRequests) {
return amnezia::ErrorCode::ApiRateLimitError;
}
if (httpStatusFromBody == httpStatusCodeConflict) {
if (apiErrorMessageFromJson(jsonObj).contains(trialAlreadyUsedMessage, Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiTrialAlreadyUsedError;
}
return amnezia::ErrorCode::ApiConfigLimitError;
}
if (httpStatusFromBody == httpStatusCodeNotFound) {
return amnezia::ErrorCode::ApiNotFoundError;
}
if (httpStatusFromBody == httpStatusCodeRequestTimeout) {
return amnezia::ErrorCode::ApiConfigTimeoutError;
}
if (httpStatusFromBody == httpStatusCodeNotImplemented) {
return amnezia::ErrorCode::ApiUpdateRequestError;
}
if (httpStatusFromBody == httpStatusCodeUnprocessableEntity) {
if (apiErrorMessageFromJson(jsonObj) == unprocessableSubscriptionMessage) {
return amnezia::ErrorCode::ApiSubscriptionExpiredError;
}
return amnezia::ErrorCode::ApiConfigDownloadError;
}
if (httpStatusFromBody == httpStatusCodePaymentRequired) {
const QString message = apiErrorMessageFromJson(jsonObj);
if (message.contains(QLatin1String("refresh_captcha"), Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiCaptchaRefreshError;
}
if (message.contains(QLatin1String("invalid_captcha"), Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiCaptchaInvalidError;
}
if (jsonObj.contains(QStringLiteral("captcha_id")) || jsonObj.contains(QStringLiteral("captcha_image"))
|| message.compare(QLatin1String("rate_limit_exceeded"), Qt::CaseInsensitive) == 0
|| message.contains(QLatin1String("rate_limit_exceeded"), Qt::CaseInsensitive)) {
return amnezia::ErrorCode::ApiCaptchaRequiredError;
}
return amnezia::ErrorCode::ApiSubscriptionNotActiveError;
}
if (httpStatusFromBody >= 300) {
return amnezia::ErrorCode::ApiConfigDownloadError;
}
return amnezia::ErrorCode::NoError;
}
bool apiUtils::isPremiumServer(const QJsonObject &serverConfigObject)
+1 -3
View File
@@ -29,9 +29,7 @@ namespace apiUtils
bool isPremiumServer(const QJsonObject &serverConfigObject);
amnezia::ErrorCode checkNetworkReplyErrors(const QList<QSslError> &sslErrors, const QString &replyErrorString,
const QNetworkReply::NetworkError &replyError, const int httpStatusCode,
const QByteArray &responseBody);
amnezia::ErrorCode checkApiResponseErrors(const QByteArray &responseBody);
QString getPremiumV2VpnKey(const QJsonObject &serverConfigObject);
}
+43 -4
View File
@@ -31,7 +31,7 @@ SecureQSettings::SecureQSettings(const QString &organization, const QString &app
// convert settings to encrypted for if updated to >= 2.1.0
if (encryptionRequired() && !encrypted) {
for (const QString &key : m_settings.allKeys()) {
if (encryptedKeys.contains(key)) {
if (isEncryptedKey(key)) {
const QVariant &val = value(key);
setValue(key, val);
}
@@ -88,7 +88,7 @@ void SecureQSettings::setValue(const QString &key, const QVariant &value)
{
QMutexLocker locker(&m_mutex);
if (encryptionRequired() && encryptedKeys.contains(key)) {
if (encryptionRequired() && isEncryptedKey(key)) {
if (!getEncKey().isEmpty() && !getEncIv().isEmpty()) {
QByteArray decryptedValue;
{
@@ -118,6 +118,45 @@ void SecureQSettings::remove(const QString &key)
m_cache.remove(key);
}
QStringList SecureQSettings::keys(const QString &prefix) const
{
QMutexLocker locker(&m_mutex);
QStringList result;
for (const QString &key : m_settings.allKeys()) {
if (key.startsWith(prefix)) {
result.append(key);
}
}
return result;
}
bool SecureQSettings::isEncryptedKey(const QString &key) const
{
if (encryptedKeys.contains(key)) {
return true;
}
for (const QString &prefix : m_encryptedKeyPrefixes) {
if (key.startsWith(prefix)) {
return true;
}
}
return false;
}
bool SecureQSettings::isBackupExcluded(const QString &key) const
{
if (key == "Conf/installationUuid") {
return true;
}
for (const QString &prefix : m_fieldsNotToBackup) {
if (key.startsWith(prefix)) {
return true;
}
}
return false;
}
QByteArray SecureQSettings::backupAppConfig() const
{
QMutexLocker locker(&m_mutex);
@@ -127,7 +166,7 @@ QByteArray SecureQSettings::backupAppConfig() const
const auto needToBackup = [this](const auto &key) {
for (const auto &item : m_fieldsToBackup)
{
if (key == "Conf/installationUuid")
if (isBackupExcluded(key))
{
return false;
}
@@ -163,7 +202,7 @@ bool SecureQSettings::restoreAppConfig(const QByteArray &json)
return false;
for (const QString &key : cfg.keys()) {
if (key == "Conf/installationUuid") {
if (isBackupExcluded(key)) {
continue;
}
+9
View File
@@ -20,6 +20,7 @@ public:
QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const;
void setValue(const QString &key, const QVariant &value);
void remove(const QString &key);
QStringList keys(const QString &prefix) const;
QByteArray backupAppConfig() const;
bool restoreAppConfig(const QByteArray &json);
@@ -43,10 +44,18 @@ private:
mutable QHash<QString, QVariant> m_cache;
QStringList encryptedKeys; // encode only key listed here
QStringList m_encryptedKeyPrefixes = {
"Conf/proxyUrls/",
};
bool isEncryptedKey(const QString &key) const;
// only this fields need for backup
QStringList m_fieldsToBackup = {
"Conf/", "Servers/",
};
QStringList m_fieldsNotToBackup = {
"Conf/proxyUrls/",
};
bool isBackupExcluded(const QString &key) const;
mutable QByteArray m_key;
mutable QByteArray m_iv;
+20
View File
@@ -2,6 +2,24 @@ find_package(Qt6 REQUIRED COMPONENTS Test)
include(CTest)
function(amnezia_copy_runtime_dlls)
if(NOT WIN32)
return()
endif()
get_property(_targets DIRECTORY PROPERTY BUILDSYSTEM_TARGETS)
foreach(_target ${_targets})
get_target_property(_type ${_target} TYPE)
if(_type STREQUAL "EXECUTABLE")
add_custom_command(TARGET ${_target} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<FILTER:$<TARGET_RUNTIME_DLLS:${_target}>,EXCLUDE,/Qt6[^/]*\\.dll$>"
"$<TARGET_FILE_DIR:${_target}>"
COMMAND_EXPAND_LISTS
)
endif()
endforeach()
endfunction()
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
@@ -415,3 +433,5 @@ endif()
# Android tests are executed on-device via androidtestrunner in CI (see .github/workflows/tests.yml).
# CTest cannot run Android binaries on the host machine, so no add_test() entries are registered here.
amnezia_copy_runtime_dlls()
+2
View File
@@ -18,3 +18,5 @@ target_link_libraries(test_ui_news_model_and_controller PRIVATE
add_test(NAME UiApiServicesModelAndControllerTest COMMAND test_ui_api_services_model_and_controller)
add_test(NAME UiNewsModelAndControllerTest COMMAND test_ui_news_model_and_controller)
amnezia_copy_runtime_dlls()
@@ -29,3 +29,4 @@ add_test(NAME AdminSelfHostedExportTest COMMAND test_admin_self_hosted_export)
add_test(NAME SelfHostedServerSetupTest COMMAND test_self_hosted_server_setup)
add_test(NAME MultipleExportsTest COMMAND test_multiple_exports)
amnezia_copy_runtime_dlls()
+2
View File
@@ -14,6 +14,8 @@ class AmneziaVPN(ConanFile):
def requirements(self):
os = str(self.settings.os)
self.requires("libagw/1.0.2")
has_ne = os == "iOS" or (os == "Macos" and self.options.macos_ne)
has_service = os == "Windows" or os == "Linux" or (os == "Macos" and not has_ne)
+178
View File
@@ -0,0 +1,178 @@
from conan import ConanFile
from conan.tools.files import copy, chdir
from conan.tools.layout import basic_layout
from conan.errors import ConanInvalidConfiguration
from conan.tools.gnu import AutotoolsToolchain
from conan.tools.apple import XCRun, is_apple_os
from conan.tools.apple.apple import _to_apple_arch
from conan.tools.env import Environment
from conan.tools.scm import Git
import os
import shlex
class Libagw(ConanFile):
name = "libagw"
version = "1.0.2"
settings = "os", "arch", "compiler"
_arch_map = {
"x86": "386",
"x86_64": "amd64",
"armv7": "arm",
"armv8": "arm64"
}
@property
def _goos(self):
return {
"Linux": "linux",
"Android": "android",
"iOS": "ios",
"Macos": "darwin",
"Windows": "windows"
}.get(str(self.settings.os))
@property
def _archs(self):
return str(self.settings.arch).split("|")
@property
def _is_multiarch(self):
return len(self._archs) > 1
@property
def _is_windows(self):
return str(self.settings.os).startswith("Windows")
@property
def _is_android(self):
return str(self.settings.os) == "Android"
def config_options(self):
# Windows: MSVC cannot link a Go c-archive (LNK1223 — it rejects the
# gcc-generated .pdata contributions), so it gets a DLL plus an import lib.
# Android: go has no c-archive buildmode there at all.
shared = self._is_windows or self._is_android
self.package_type = "shared-library" if shared else "static-library"
def configure(self):
self.settings.rm_safe("compiler.libcxx")
self.settings.rm_safe("compiler.cppstd")
if self._is_windows:
# mingw-builds is being used on Windows
del self.settings.compiler
def layout(self):
basic_layout(self)
def build_requirements(self):
# 1.23 line: go>=1.24 has an android/arm futex_time64 regression
# (golang/go#77930), the same reason openvpn-pt-android pins it.
self.tool_requires("go/1.23.12")
if self._is_windows:
self.win_bash = True
if not self.conf.get("tools.microsoft.bash:path", check_type=str):
self.tool_requires("msys2/cci.latest")
self.tool_requires("mingw-builds/15.1.0")
def validate(self):
if not self._goos or not all(arch in self._arch_map for arch in self._archs):
raise ConanInvalidConfiguration(
f"{self.name} v{self.version} does not support {self.settings.os} {self.settings.arch}"
)
if self._is_multiarch and not is_apple_os(self):
raise ConanInvalidConfiguration(
f"{self.name} v{self.version} does not support multiarch builds"
)
def source(self):
git = Git(self)
git.clone(url="https://github.com/amnezia-vpn/libagw.git", target=".",
args=["--branch", f"v{self.version}"])
def generate(self):
tc = AutotoolsToolchain(self)
tc.apple_arch_flag = None
env = tc.environment()
env.define("GOPATH", os.path.join(self.build_folder, "gopath"))
env.define("GOMODCACHE", os.path.join(self.build_folder, "gopath", "pkg", "mod"))
env.define("GOCACHE", os.path.join(self.build_folder, "gocache"))
env.define("GOOS", self._goos)
env.define("CGO_ENABLED", "1")
self._ldflags = tc.ldflags
self._cflags = tc.cflags
tc.generate(env)
def _go_build(self, output, buildmode, goarch, cflags, ldflags, goldflags=""):
env = Environment()
env.define("GOARCH", goarch)
env.define("CGO_CFLAGS", " ".join(cflags))
env.define("CGO_LDFLAGS", " ".join(ldflags))
go_ldflags = " ".join(filter(None, ["-s -w", goldflags]))
with env.vars(self).apply():
self.run(f'go build -buildmode={buildmode} -ldflags="{go_ldflags}" '
f'-o {shlex.quote(output)} ./archive')
def build(self):
with chdir(self, self.source_folder):
for arch in self._archs:
build_dir = os.path.join(self.build_folder, "slices", arch) if self._is_multiarch else self.build_folder
if self._is_windows:
build_dir = build_dir.replace("\\", "/")
goarch = self._arch_map.get(arch)
cflags = list(self._cflags)
ldflags = list(self._ldflags)
if is_apple_os(self):
cflags.append(f"-arch {_to_apple_arch(arch)}")
ldflags.append(f"-arch {_to_apple_arch(arch)}")
if self._is_windows:
dll = f"{build_dir}/agw.dll"
self._go_build(dll, "c-shared", goarch, cflags, ldflags)
# An import lib MSVC accepts: gendef reads the DLL exports,
# dlltool turns them into agw.lib.
with chdir(self, build_dir):
self.run("gendef agw.dll")
self.run("dlltool -d agw.def -l agw.lib -D agw.dll")
elif self._is_android:
# Without an explicit soname the DT_NEEDED entry picks up the
# full build path, which does not exist on the device.
self._go_build(os.path.join(build_dir, "libagw.so"), "c-shared", goarch, cflags, ldflags,
goldflags="-extldflags=-Wl,-soname,libagw.so")
else:
self._go_build(os.path.join(build_dir, "libagw.a"), "c-archive", goarch, cflags, ldflags)
if is_apple_os(self) and self._is_multiarch:
lipo = XCRun(self).find("lipo")
archives = [os.path.join(self.build_folder, "slices", arch, "libagw.a") for arch in self._archs]
output = os.path.join(self.build_folder, "libagw.a")
self.run("{} -create -output {} {}".format(
shlex.quote(lipo),
shlex.quote(output),
shlex.join(archives)
))
def package(self):
headers = os.path.join(self.source_folder, "cabi")
copy(self, "agw.h", src=headers, dst=os.path.join(self.package_folder, "include"), keep_path=False)
copy(self, "agw_types.h", src=headers, dst=os.path.join(self.package_folder, "include"), keep_path=False)
copy(self, "libagw.a", src=self.build_folder, dst=os.path.join(self.package_folder, "lib"),
keep_path=False, excludes=["slices/*"])
copy(self, "libagw.so", src=self.build_folder, dst=os.path.join(self.package_folder, "lib"), keep_path=False)
copy(self, "agw.lib", src=self.build_folder, dst=os.path.join(self.package_folder, "lib"), keep_path=False)
copy(self, "agw.dll", src=self.build_folder, dst=os.path.join(self.package_folder, "bin"), keep_path=False)
def package_info(self):
self.cpp_info.set_property("cmake_target_name", "amnezia::libagw")
self.cpp_info.libs = ["agw"]
if is_apple_os(self):
# Go's crypto/x509 reads the system trust store.
self.cpp_info.frameworks = ["CoreFoundation", "Security"]
elif self._is_android:
self.cpp_info.system_libs = ["log"]
elif str(self.settings.os) == "Linux":
self.cpp_info.system_libs = ["pthread"]