ZaStoGram_desktop/Telegram/SourceFiles/core/update_checker.cpp
loop-uh f32a6c3364 Update trust: the fork has its own v2 update key chain
Clients merged with upstream 7.4.x accept only v2 (TDUP) update packages,
verified against trust data compiled into the client. Telegram own root key
does not trust the fork signatures, so every update built since the merge was
rejected ("unsupported update format (missing v2 magic)").

- Resources/update: the fork root public key, a manifest that authorizes one
  Ed25519 release key for the stable and beta channels, and the root
  signature of that manifest. Private keys live outside the repository.
- build/zastogram/update_keys.py: generates the keys, issues and checks the
  manifest, installs the release key on the build VM, backs the keys up.
- Dev builds (build id dev-N) verify packages against a running version one
  step lower, because dev-N releases share one AppVersion. The signature is
  still mandatory and a lower base version is still rejected.
- Tests: test_update_verify (fork manifest shape, dev version rule) and the
  release guard test_update_keys.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:52:12 +00:00

3035 lines
83 KiB
C++

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information see the local LEGAL file.
*/
#include "core/update_checker.h"
#include "platform/platform_specific.h"
#include "base/platform/base_platform_info.h"
#include "base/platform/base_platform_file_utilities.h"
#include "base/timer.h"
#include "base/bytes.h"
#include "base/unixtime.h"
#include "storage/localstorage.h"
#include "core/application.h"
#include "core/changelogs.h"
#include "core/click_handler_types.h"
#include "core/update_channel.h"
#include "core/update_keys.h"
#include "core/update_unpack.h"
#include "core/update_verify.h"
#include "core/version.h"
#include "core/zsg_build.h"
#include "core/zsg_mirrors.h"
#include "data/data_channel.h"
#include "data/data_session.h"
#include "mainwindow.h"
#include "main/main_account.h"
#include "main/main_session.h"
#include "main/main_domain.h"
#include "info/info_memento.h"
#include "info/info_controller.h"
#include "window/window_controller.h"
#include "window/window_session_controller.h"
#include "settings/sections/settings_advanced.h"
#include "settings/settings_intro.h"
#include "test/test_agent.h"
#include "ui/layers/box_content.h"
#include <QtCore/QDataStream>
#include <QtNetwork/QHostInfo>
#include <QtNetwork/QNetworkProxy>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QFileSystemWatcher>
#include <ksandbox.h>
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
#include "base/platform/linux/base_linux_xdp_utilities.h"
#include "platform/linux/update_install_linux.h"
#include <flatpakportal/flatpakportal.hpp>
#elif defined Q_OS_MACOS // !Q_OS_WIN && !Q_OS_MACOS
#include "platform/mac/update_install_mac.h"
#else // Q_OS_MACOS
#include "platform/win/update_install_win.h"
#endif // Q_OS_WIN
extern "C" {
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/err.h>
} // extern "C"
#ifndef Q_OS_WIN
#include <unistd.h>
#endif // !Q_OS_WIN
namespace Core {
namespace {
constexpr auto kUpdateCheckTimeout = 6 * crl::time(1000);
// A stalled download is told apart from a slow one by this silence.
constexpr auto kUpdaterStallTimeout = 20 * crl::time(1000);
// The whole check, with every mirror: the mirrors are raced, so a name that
// is dropped silently must not eat the time the working ones need.
constexpr auto kUpdateCheckBudget = 40 * crl::time(1000);
// The entry pages are asked once the first routes had their chance: most
// checks end sooner and never need them.
constexpr auto kEntryDelay = crl::time(2500);
constexpr auto kMirrorStagger = crl::time(1500);
constexpr auto kLoaderSilence = 5 * 1000;
constexpr auto kMaxResponseSize = 1024 * 1024;
// The same releases are mirrored to GitHub, whose names are not filtered where
// the git ones are: it is the first route and the git mirrors back it up.
constexpr auto kZaStoGramGithubApi =
"https://api.github.com/repos/zapret-discordyoutube/"
"ZaStoGram_desktop/releases?per_page=6"_cs;
constexpr auto kZaStoGramForgejoDownload =
"https://vsnvsnhkgr.zapret.moe/zastogram/ZaStoGram_desktop/"
"releases/download/%1/%2"_cs;
constexpr auto kZaStoGramReleasesApi =
"https://vsnvsnhkgr.zapret.moe/api/v1/repos/"
"zastogram/ZaStoGram_desktop/releases"
"?draft=false&pre-release=true&limit=1"_cs;
// Alpha and canary builds are published far more often than the eight hours
// a stable build waits, so they ask every ten to fifteen minutes instead.
constexpr auto kFrequentUpdateDelayConstPart = 600;
constexpr auto kFrequentUpdateDelayRandPart = 300;
// tdata/version marker for installed v2 canary packages, holding the full
// 64-bit (base << 32 | counter) version. 0x7FFFFFFF is the alpha marker.
constexpr auto kVersionFileCanaryMarker = quint32(0x7FFFFFFE);
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
constexpr auto kFlatpakPortalService = "org.freedesktop.portal.Flatpak";
constexpr auto kFlatpakPortalObjectPath = "/org/freedesktop/portal/Flatpak";
constexpr auto kFlatpakUpdated = "/app/.updated"_cs;
#endif // !Q_OS_WIN && !Q_OS_MACOS
#ifdef TDESKTOP_DISABLE_AUTOUPDATE
bool UpdaterIsDisabled = true;
#else // TDESKTOP_DISABLE_AUTOUPDATE
bool UpdaterIsDisabled = false;
#endif // TDESKTOP_DISABLE_AUTOUPDATE
std::weak_ptr<Updater> UpdaterInstance;
using Progress = UpdateChecker::Progress;
using State = UpdateChecker::State;
#ifdef Q_OS_WIN
using VersionInt = DWORD;
using VersionChar = WCHAR;
#else // Q_OS_WIN
using VersionInt = int;
using VersionChar = wchar_t;
#endif // Q_OS_WIN
using Loader = MTP::AbstractDedicatedLoader;
std::optional<uint64> ZaStoGramDevBuildNumber() {
static const auto Expression = QRegularExpression(
u"^dev-(\\d+)(?:\\D.*)?$"_q,
QRegularExpression::CaseInsensitiveOption);
const auto match = Expression.match(ZsgBuildId.utf16());
if (!match.hasMatch()) {
return std::nullopt;
}
return match.captured(1).toULongLong();
}
bool IsZaStoGramDevBuild() {
return ZaStoGramDevBuildNumber().has_value();
}
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
using namespace gi::repository;
namespace GObject = gi::repository::GObject;
#endif // !Q_OS_WIN && !Q_OS_MACOS
struct BIODeleter {
void operator()(BIO *value) {
BIO_free(value);
}
};
inline auto MakeBIO(const void *buf, int len) {
return std::unique_ptr<BIO, BIODeleter>{
BIO_new_mem_buf(buf, len),
};
}
class Checker : public base::has_weak_ptr {
public:
Checker(bool testing);
virtual void start() = 0;
virtual bool poll() const;
rpl::producer<std::shared_ptr<Loader>> ready() const;
rpl::producer<> failed() const;
rpl::lifetime &lifetime();
virtual ~Checker() = default;
protected:
bool testing() const;
void done(std::shared_ptr<Loader> result);
void fail();
private:
bool _testing = false;
rpl::event_stream<std::shared_ptr<Loader>> _ready;
rpl::event_stream<> _failed;
rpl::lifetime _lifetime;
};
struct Implementation {
std::unique_ptr<Checker> checker;
std::shared_ptr<Loader> loader;
bool failed = false;
};
class HttpChecker : public Checker {
public:
HttpChecker(bool testing);
void start() override;
~HttpChecker();
private:
enum class ResponseType {
UpdateMap,
DevReleases,
};
void request(const QUrl &url, ResponseType type);
struct Attempt {
QString host;
bool direct = false;
bool github = false;
};
void startNext();
void sendTo(const Attempt &attempt);
void attemptFailed();
void requestEntryNames();
void addAttempts(const QStringList &hosts, bool github = false);
[[nodiscard]] int attemptsCount() const;
[[nodiscard]] QString mirrored(const QString &url) const;
void gotResponse(
not_null<QNetworkReply*> reply,
const Attempt &attempt,
crl::time started);
void clearSentRequest();
bool handleResponse(const QByteArray &response);
bool handleDevReleases(const QByteArray &response);
std::optional<QString> parseOldResponse(
const QByteArray &response) const;
std::optional<QString> parseResponse(const QByteArray &response) const;
QString validateLatestUrl(
uint64 availableVersion,
bool isAvailableAlpha,
QString url) const;
std::unique_ptr<QNetworkAccessManager> _manager;
std::unique_ptr<QNetworkAccessManager> _directManager;
std::vector<QNetworkReply*> _replies;
ResponseType _responseType = ResponseType::UpdateMap;
QUrl _baseUrl;
std::vector<Attempt> _attempts;
QString _answeredHost;
bool _answeredDirect = false;
bool _answeredGithub = false;
int _nextHost = 0;
base::Timer _staggerTimer;
base::Timer _entryTimer;
bool _proxied = false;
enum class EntryState {
None,
Pending,
Done,
};
EntryState _entryState = EntryState::None;
};
class HttpLoaderActor;
class HttpLoader : public Loader {
public:
HttpLoader(
const QString &url,
const QString &fallbackUrl = QString(),
bool direct = false);
~HttpLoader();
private:
void startLoading() override;
friend class HttpLoaderActor;
QString _url;
QString _fallbackUrl;
bool _direct = false;
std::unique_ptr<QThread> _thread;
HttpLoaderActor *_actor = nullptr;
};
class HttpLoaderActor : public QObject {
public:
HttpLoaderActor(
not_null<HttpLoader*> parent,
not_null<QThread*> thread,
const QStringList &urls,
bool direct);
private:
void start();
void sendRequest();
bool tryNextHost();
void gotMetaData();
void partFinished(qint64 got, qint64 total);
void partFailed(QNetworkReply::NetworkError e);
not_null<HttpLoader*> _parent;
QStringList _urls;
int _urlIndex = 0;
QNetworkAccessManager _manager;
std::unique_ptr<QNetworkReply> _reply;
};
class MtpChecker : public Checker {
public:
MtpChecker(base::weak_ptr<Main::Session> session, bool testing);
void start() override;
private:
using FileLocation = MTP::DedicatedLoader::Location;
using Checker::fail;
Fn<void(const MTP::Error &error)> failHandler();
void gotMessage(const MTPmessages_Messages &result);
std::optional<FileLocation> parseMessage(
const MTPmessages_Messages &result) const;
std::optional<FileLocation> parseText(const QByteArray &text) const;
FileLocation validateLatestLocation(
uint64 availableVersion,
const FileLocation &location) const;
void startCanary();
void requestCanaryMetadata(
const MTPInputChannel &channel,
int messageId,
bool fallbackToPinned);
void requestCanaryPinnedFallback(const MTPInputChannel &channel);
void gotCanaryMessage(
const MTPInputChannel &channel,
const MTPmessages_Messages &result,
int messageId,
bool fallbackToPinned);
void parseCanaryMetadata(
const MTPInputChannel &channel,
const QByteArray &text);
MTP::WeakInstance _mtp;
};
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
class FlatpakChecker : public Checker {
public:
FlatpakChecker(bool testing);
void start() override;
bool poll() const override;
~FlatpakChecker();
private:
FlatpakPortal::Flatpak _interface;
FlatpakPortal::FlatpakUpdateMonitor _monitor;
QFileSystemWatcher _watcher;
ulong _updateAvailableSignal = 0;
};
class FlatpakLoader : public Loader {
public:
FlatpakLoader(FlatpakPortal::FlatpakUpdateMonitor monitor);
~FlatpakLoader();
private:
void startLoading() override;
FlatpakPortal::FlatpakUpdateMonitor _monitor;
ulong _progressSignal = 0;
};
#endif // !Q_OS_WIN && !Q_OS_MACOS
std::shared_ptr<Updater> GetUpdaterInstance() {
if (const auto result = UpdaterInstance.lock()) {
return result;
}
const auto result = std::make_shared<Updater>();
UpdaterInstance = result;
return result;
}
[[nodiscard]] base::weak_ptr<Main::Session> LookupCanaryPrivateSession(
base::weak_ptr<Main::Session> fallback) {
if (BuildUpdateChannel != Updates::Channel::CanaryPrivate
|| !CanaryPrivateChannelId
|| !IsAppLaunched()
|| !App().domain().started()) {
return fallback;
}
for (const auto &[index, account] : App().domain().accounts()) {
if (const auto session = account->maybeSession()) {
const auto channel = session->data().channelLoaded(
ChannelId(BareId(CanaryPrivateChannelId)));
if (channel && channel->amIn()) {
return base::make_weak(session);
}
}
}
return fallback;
}
QString UpdatesFolder() {
return cWorkingDir() + u"tupdates"_q;
}
void ClearAll() {
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
if (!KSandbox::isInside()) {
auto error = QString();
if (!Platform::ClearUpdateData(cWorkingDir(), error)) {
LOG(("Update Error: %1").arg(error));
}
return;
}
#endif // !Q_OS_WIN && !Q_OS_MACOS
base::Platform::DeleteDirectory(UpdatesFolder());
}
QString FindUpdateFile() {
QDir updates(UpdatesFolder());
if (!updates.exists()) {
return QString();
}
const auto list = updates.entryInfoList(QDir::Files);
for (const auto &info : list) {
// ZaStoGram downloads classical v1 packages from Forgejo releases
// (tupdate*, tx64upd*, tarm64upd*), so the v1 names stay accepted.
static const auto RegExp = QRegularExpression(
"^("
"tupdate|"
"tx64upd|"
"tarm64upd|"
"tmacupd|"
"tarmacupd|"
"tlinuxupd|"
")\\d+(_[a-z\\d]+)?$",
QRegularExpression::CaseInsensitiveOption
);
static const auto RegExpV2 = QRegularExpression(
"^td-update-(win|mac|linux)-(x86|x64|arm)-\\d+"
"(-beta|-canary-\\d+(-private)?)?$",
QRegularExpression::CaseInsensitiveOption
);
if (RegExp.match(info.fileName()).hasMatch()
|| RegExpV2.match(info.fileName()).hasMatch()) {
return info.absoluteFilePath();
}
}
return QString();
}
[[nodiscard]] std::optional<Updates::Manifest> HeldManifest() {
auto error = QString();
auto result = Updates::ParseVerifiedManifest(
Updates::EmbeddedManifest(),
Updates::EmbeddedManifestSignature(),
Updates::RootPublicKeyPem(),
&error);
if (!result) {
LOG(("Update Error: Bad embedded manifest: %1").arg(error));
}
auto manifest = QByteArray();
auto signature = QByteArray();
if (Local::readUpdateManifest(&manifest, &signature)) {
auto persisted = Updates::ParseVerifiedManifest(
manifest,
signature,
Updates::RootPublicKeyPem());
if (persisted && (!result || persisted->version > result->version)) {
result = std::move(persisted);
}
}
return result;
}
void AdoptManifest(const Updates::Manifest &manifest) {
const auto held = HeldManifest();
if (!held || manifest.version > held->version) {
LOG(("Update Info: Adopting manifest version %1."
).arg(manifest.version));
Local::writeUpdateManifest(manifest.bytes, manifest.signature);
}
}
QString ExtractFilename(const QString &url) {
const auto expression = QRegularExpression(u"/([^/\\?]+)(\\?|$)"_q);
if (const auto match = expression.match(url); match.hasMatch()) {
return match.captured(1).replace(
QRegularExpression(u"[^a-zA-Z0-9_\\-]"_q),
QString());
}
return QString();
}
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
enum class ManifestAdoption {
Queued,
Immediate,
};
[[nodiscard]] bool WriteUpdateReadyFile(const QString &readyFilePath) {
QFile readyFile(readyFilePath);
if (readyFile.open(QIODevice::WriteOnly)) {
if (readyFile.write("1", 1)) {
readyFile.close();
} else {
LOG(("Update Error: cant write ready file '%1'").arg(readyFilePath));
return false;
}
} else {
LOG(("Update Error: cant create ready file '%1'").arg(readyFilePath));
return false;
}
return true;
}
[[nodiscard]] std::optional<Updates::VerifiedUpdate> VerifyUpdateV2(
const QByteArray &content,
ManifestAdoption adoption) {
// The expected target follows the feed key, not the build: an x64
// build under Rosetta asks for armac and must accept that package.
const auto target = Updates::TargetFromPlatformKey(
Platform::AutoUpdateKey().toLatin1());
if (!target) {
LOG(("Update Error: No v2 target for platform key '%1'."
).arg(Platform::AutoUpdateKey()));
return std::nullopt;
}
// The full verification happens before any decompression, so no
// unauthenticated bytes ever reach the LZMA or QDataStream parsers.
auto error = QString();
auto verified = Updates::VerifyUpdate(
content,
BuildUpdateChannel,
AppBetaVersion || cInstallBetaVersion(),
*target,
IsZaStoGramDevBuild()
? Updates::DevRunningVersion(RunningUpdateVersion())
: RunningUpdateVersion(),
HeldManifest(),
Updates::RootPublicKeyPem(),
base::unixtime::now(),
&error);
if (!verified) {
LOG(("Update Error: v2 update rejected: %1").arg(error));
return std::nullopt;
}
if (verified->adoptManifest) {
if (adoption == ManifestAdoption::Immediate) {
AdoptManifest(verified->manifest);
} else {
crl::on_main([manifest = verified->manifest] {
AdoptManifest(manifest);
});
}
}
return verified;
}
#if defined Q_OS_MACOS || defined Q_OS_WIN
[[nodiscard]] bool VerifyKeptUpdate(
const QByteArray &content,
Platform::UpdateInstallMode mode,
ManifestAdoption adoption) {
if (!VerifyUpdateV2(content, adoption)) {
return false;
}
#ifdef Q_OS_WIN
if (mode == Platform::UpdateInstallMode::Protected) {
auto error = QString();
if (!Platform::ValidateProtectedUpdate(
content,
cInstallBetaVersion(),
error)) {
LOG(("Update Error: %1").arg(error));
return false;
}
}
#endif // Q_OS_WIN
return true;
}
#endif // Q_OS_MACOS || Q_OS_WIN
[[nodiscard]] bool UnpackUpdateV2(
const QString &filepath,
const QByteArray &content,
ManifestAdoption adoption) {
const auto verified = VerifyUpdateV2(content, adoption);
if (!verified) {
return false;
}
const auto tempDirPath = cWorkingDir() + u"tupdates/temp"_q;
const auto readyFilePath = cWorkingDir() + u"tupdates/temp/ready"_q;
base::Platform::DeleteDirectory(tempDirPath);
QDir tempDir(tempDirPath);
if (tempDir.exists() || QFile(readyFilePath).exists()) {
LOG(("Update Error: cant clear tupdates/temp dir!"));
return false;
}
auto error = QString();
const auto uncompressed = Updates::DecompressUpdatePayload(
*verified,
&error);
if (!uncompressed) {
LOG(("Update Error: %1").arg(error));
return false;
}
tempDir.mkdir(tempDir.absolutePath());
const auto canary
= (verified->envelope.channel == Updates::Channel::CanaryPublic)
|| (verified->envelope.channel == Updates::Channel::CanaryPrivate);
if (!Updates::ExtractUpdateFiles(
*uncompressed,
verified->envelope.version,
tempDirPath,
&error)) {
LOG(("Update Error: %1").arg(error));
return false;
}
if (!WriteUpdateVersionFile(
tempDirPath,
Updates::UpdateVersionBase(verified->envelope.version),
canary ? verified->envelope.version : 0)) {
return false;
}
if (!WriteUpdateReadyFile(readyFilePath)) {
return false;
}
QFile(filepath).remove();
return true;
}
// ZaStoGram releases are signed by Packer with the fork's own RSA keys
// (UpdatesPublicKey / UpdatesPublicBetaKey in config.h) in the classical v1
// layout: [128 bytes RSA signature][20 bytes SHA1][payload]. The payload and
// the inner file list are the same as in the v2 envelope, so after the
// signature check the v2 hardened decompression and extraction are reused.
[[nodiscard]] bool UnpackUpdateV1(
const QString &filepath,
const QByteArray &compressed) {
const int32 hSigLen = 128, hShaLen = 20;
if (compressed.size() <= hSigLen + hShaLen) {
LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
return false;
}
uchar sha1Buffer[20];
bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressed.size() - hSigLen - hShaLen, sha1Buffer), hShaLen);
if (!goodSha1) {
LOG(("Update Error: bad SHA1 hash of update file!"));
return false;
}
RSA *pbKey = [] {
const auto bio = MakeBIO(
const_cast<char*>(
AppBetaVersion
? UpdatesPublicBetaKey
: UpdatesPublicKey),
-1);
return PEM_read_bio_RSAPublicKey(bio.get(), 0, 0, 0);
}();
if (!pbKey) {
LOG(("Update Error: cant read public rsa key!"));
return false;
}
if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
RSA_free(pbKey);
// try other public key, if we update from beta to stable or vice versa
pbKey = [] {
const auto bio = MakeBIO(
const_cast<char*>(
AppBetaVersion
? UpdatesPublicKey
: UpdatesPublicBetaKey),
-1);
return PEM_read_bio_RSAPublicKey(bio.get(), 0, 0, 0);
}();
if (!pbKey) {
LOG(("Update Error: cant read public rsa key!"));
return false;
}
if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
RSA_free(pbKey);
LOG(("Update Error: bad RSA signature of update file!"));
return false;
}
}
RSA_free(pbKey);
// The bytes after the signature and the hash are authenticated now.
auto authenticated = Updates::VerifiedUpdate();
authenticated.envelope.payload = compressed.mid(hSigLen + hShaLen);
auto error = QString();
const auto uncompressed = Updates::DecompressUpdatePayload(
authenticated,
&error);
if (!uncompressed) {
LOG(("Update Error: %1").arg(error));
return false;
}
quint32 version = 0;
{
QDataStream stream(*uncompressed);
stream.setVersion(QDataStream::Qt_5_1);
stream >> version;
if (stream.status() != QDataStream::Ok) {
LOG(("Update Error: cant read version from downloaded stream, status: %1").arg(stream.status()));
return false;
}
}
if (version == 0x7FFFFFFF) { // alpha version
LOG(("Update Error: legacy alpha update is not supported."));
return false;
} else if (int32(version) < AppVersion
|| (int32(version) == AppVersion && !IsZaStoGramDevBuild())) {
LOG(("Update Error: downloaded version %1 is not greater, than mine %2").arg(version).arg(AppVersion));
return false;
}
QString tempDirPath = cWorkingDir() + u"tupdates/temp"_q, readyFilePath = cWorkingDir() + u"tupdates/temp/ready"_q;
base::Platform::DeleteDirectory(tempDirPath);
QDir tempDir(tempDirPath);
if (tempDir.exists() || QFile(readyFilePath).exists()) {
LOG(("Update Error: cant clear tupdates/temp dir!"));
return false;
}
tempDir.mkdir(tempDir.absolutePath());
if (!Updates::ExtractUpdateFiles(
*uncompressed,
Updates::MakeUpdateVersion(version, 0),
tempDirPath,
&error)) {
LOG(("Update Error: %1").arg(error));
return false;
}
if (!WriteUpdateVersionFile(tempDirPath, version, 0)) {
return false;
}
if (!WriteUpdateReadyFile(readyFilePath)) {
return false;
}
QFile(filepath).remove();
return true;
}
#endif // !TDESKTOP_DISABLE_AUTOUPDATE
bool UnpackUpdate(const QString &filepath) {
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
if (filepath.isEmpty()) {
return true;
}
#if defined Q_OS_MACOS || defined Q_OS_WIN
auto error = QString();
const auto mode = Platform::GetUpdateInstallMode(
cExeDir() + cExeName(),
error);
if (mode == Platform::UpdateInstallMode::Refused) {
LOG(("Update Error: %1").arg(error));
return false;
}
const auto content = Platform::ReadUpdatePackage(filepath, error);
if (!content) {
LOG(("Update Error: %1").arg(error));
return false;
} else if (!Updates::IsV2UpdateFile(*content)) {
LOG(("Update Error: unsupported update format (missing v2 magic)."));
return false;
} else if (!VerifyKeptUpdate(*content, mode, ManifestAdoption::Queued)) {
return false;
}
const auto ready = Platform::ReadyUpdatePackagePath(cWorkingDir());
QFile::remove(ready);
if (!QFile::rename(filepath, ready)) {
LOG(("Update Error: could not keep the verified update package."));
return false;
}
return true;
#else // Q_OS_MACOS || Q_OS_WIN
auto error = QString();
const auto mode = KSandbox::isInside()
? Platform::UpdateInstallMode::Writable
: Platform::GetUpdateInstallMode(cExeDir() + cExeName(), error);
if (mode == Platform::UpdateInstallMode::Refused) {
LOG(("Update Error: %1").arg(error));
return false;
}
const auto content = Platform::ReadUpdatePackage(filepath, error);
if (!content) {
LOG(("Update Error: %1").arg(error));
return false;
} else if (mode == Platform::UpdateInstallMode::Protected) {
if (!Platform::PrepareProtectedUpdate(
cWorkingDir(),
filepath,
*content,
cInstallBetaVersion(),
error)) {
LOG(("Update Error: %1").arg(error));
return false;
}
return true;
}
const auto &compressed = *content;
if (Updates::IsV2UpdateFile(compressed)) {
if (UnpackUpdateV2(
filepath,
compressed,
ManifestAdoption::Queued)) {
return true;
} else if (BuildIsCanary) {
return false;
}
LOG(("Update Info: trying v1 unpacking for a file with v2 magic."));
} else if (BuildIsCanary) {
LOG(("Update Error: canary builds accept only v2 updates."));
return false;
}
return UnpackUpdateV1(filepath, compressed);
#endif // !Q_OS_MACOS && !Q_OS_WIN
#else // !TDESKTOP_DISABLE_AUTOUPDATE
return false;
#endif // TDESKTOP_DISABLE_AUTOUPDATE
}
template <typename Callback>
bool ParseCommonMap(
const QByteArray &json,
bool testing,
Callback &&callback) {
auto error = QJsonParseError{ 0, QJsonParseError::NoError };
const auto document = QJsonDocument::fromJson(json, &error);
if (error.error != QJsonParseError::NoError) {
LOG(("Update Error: MTP failed to parse JSON, error: %1"
).arg(error.errorString()));
return false;
} else if (!document.isObject()) {
LOG(("Update Error: MTP not an object received in JSON."));
return false;
}
const auto platforms = document.object();
const auto platform = Platform::AutoUpdateKey();
const auto it = platforms.constFind(platform);
if (it == platforms.constEnd()) {
LOG(("Update Error: MTP platform '%1' not found in response."
).arg(platform));
return false;
} else if (!(*it).isObject()) {
LOG(("Update Error: MTP not an object found for platform '%1'."
).arg(platform));
return false;
}
const auto types = (*it).toObject();
const auto list = [&]() -> std::vector<QString> {
if (cAlphaVersion()) {
return { "alpha", "beta", "stable" };
} else if (cInstallBetaVersion()) {
return { "beta", "stable" };
}
return { "stable" };
}();
auto bestIsAvailableAlpha = false;
auto bestAvailableVersion = 0ULL;
for (const auto &type : list) {
const auto it = types.constFind(type);
if (it == types.constEnd()) {
continue;
} else if (!(*it).isObject()) {
LOG(("Update Error: Not an object found for '%1:%2'."
).arg(platform).arg(type));
return false;
}
const auto map = (*it).toObject();
const auto key = testing ? "testing" : "released";
const auto version = map.constFind(key);
if (version == map.constEnd()) {
continue;
}
const auto isAvailableAlpha = (type == "alpha");
const auto availableVersion = [&] {
if ((*version).isString()) {
const auto string = (*version).toString();
if (const auto index = string.indexOf(':'); index > 0) {
return base::StringViewMid(string, 0, index).toULongLong();
}
return string.toULongLong();
} else if ((*version).isDouble()) {
return uint64(base::SafeRound((*version).toDouble()));
}
return 0ULL;
}();
if (!availableVersion) {
LOG(("Update Error: Version is not valid for '%1:%2:%3'."
).arg(platform).arg(type).arg(key));
return false;
}
const auto compare = isAvailableAlpha
? availableVersion
: availableVersion * 1000;
const auto bestCompare = bestIsAvailableAlpha
? bestAvailableVersion
: bestAvailableVersion * 1000;
if (compare > bestCompare) {
bestAvailableVersion = availableVersion;
bestIsAvailableAlpha = isAvailableAlpha;
if (!callback(availableVersion, isAvailableAlpha, map)) {
return false;
}
}
}
if (!bestAvailableVersion) {
LOG(("Update Error: No valid entry found for platform '%1'."
).arg(platform));
return false;
}
return true;
}
Checker::Checker(bool testing) : _testing(testing) {
}
rpl::producer<std::shared_ptr<Loader>> Checker::ready() const {
return _ready.events();
}
rpl::producer<> Checker::failed() const {
return _failed.events();
}
bool Checker::poll() const {
return true;
}
bool Checker::testing() const {
return _testing;
}
void Checker::done(std::shared_ptr<Loader> result) {
_ready.fire(std::move(result));
}
void Checker::fail() {
_failed.fire({});
}
rpl::lifetime &Checker::lifetime() {
return _lifetime;
}
HttpChecker::HttpChecker(bool testing)
: Checker(testing)
, _staggerTimer([=] { startNext(); })
, _entryTimer([=] { requestEntryNames(); }) {
}
void HttpChecker::start() {
if (IsZaStoGramDevBuild()) {
DEBUG_LOG(("Update Info: requesting ZaStoGram dev releases"));
request(
QUrl(kZaStoGramReleasesApi.utf16()),
ResponseType::DevReleases);
return;
}
const auto updaterVersion = Platform::AutoUpdateVersion();
const auto path = Local::readAutoupdatePrefix()
+ qstr("/current")
+ (updaterVersion > 1 ? QString::number(updaterVersion) : QString());
DEBUG_LOG(("Update Info: requesting update state"));
request(QUrl(path), ResponseType::UpdateMap);
}
void HttpChecker::request(const QUrl &url, ResponseType type) {
_responseType = type;
_baseUrl = url;
_nextHost = 0;
_answeredGithub = false;
_entryTimer.cancel();
_attempts.clear();
// git.zapret.moe is dropped by name in some countries, while the same
// Forgejo answers on its mirrors. They are raced: the next one starts
// after a short stagger or as soon as the previous one fails, and the
// first valid answer wins. When every known name is out, the names
// handed out now come from the entry pages (requestEntryNames).
const auto mirrored = Core::ZsgMirrors::IsGitHost(url.host());
_entryState = mirrored ? EntryState::None : EntryState::Done;
// The app-wide proxy (a Telegram-only SOCKS5 from the free catalog, a
// system PAC) also applies to these requests and may silently swallow
// them, while a browser on the same machine goes straight out. So the
// same hosts are also tried directly, after the proxied ones.
_proxied = (QNetworkProxy::applicationProxy().type()
!= QNetworkProxy::NoProxy)
|| QNetworkProxyFactory::usesSystemConfiguration();
if (mirrored) {
addAttempts(
Core::ZsgMirrors::Hosts(),
type == ResponseType::DevReleases);
_entryTimer.callOnce(kEntryDelay);
} else {
_attempts.push_back({ QString(), false });
}
LOG(("Update Info: checking through %1 route(s), proxy: %2, hosts: %3"
).arg(_attempts.size()
).arg(_proxied ? u"app/system"_q : u"none"_q
).arg(Core::ZsgMirrors::Hosts().join(',')));
for (const auto &host : Core::ZsgMirrors::Hosts()) {
QHostInfo::lookupHost(host, [=](const QHostInfo &info) {
auto addresses = QStringList();
for (const auto &address : info.addresses()) {
addresses.push_back(address.toString());
}
LOG(("Update Info: DNS %1 -> %2 (%3)"
).arg(host
).arg(addresses.join(','), info.errorString()));
});
}
_manager = std::make_unique<QNetworkAccessManager>();
_directManager = std::make_unique<QNetworkAccessManager>();
_directManager->setProxy(QNetworkProxy::NoProxy);
startNext();
}
int HttpChecker::attemptsCount() const {
return int(_attempts.size());
}
void HttpChecker::addAttempts(const QStringList &hosts, bool github) {
const auto add = [&](bool direct) {
if (github) {
_attempts.push_back({ QString(), direct, true });
}
for (const auto &host : hosts) {
_attempts.push_back({ host, direct, false });
}
};
add(false);
if (_proxied) {
add(true);
}
}
// The entry pages are asked a little after the first routes started, and
// at once when every known name has failed: the new names still fit into
// the check budget. Names already tried are not repeated. The check waits
// for every page: Apps Script is slow, and it is the one that always
// carries the live names.
void HttpChecker::requestEntryNames() {
_entryTimer.cancel();
if (_entryState != EntryState::None) {
return;
}
_entryState = EntryState::Pending;
auto tried = QStringList();
for (const auto &attempt : _attempts) {
if (!attempt.host.isEmpty() && !tried.contains(attempt.host)) {
tried.push_back(attempt.host);
}
}
LOG(("Update Info: asking the entry pages for new mirror names"));
const auto weak = base::make_weak(this);
Core::ZsgMirrors::FetchEntryNames(tried, [=](
QStringList fresh,
bool last) {
const auto strong = weak.get();
if (!strong || strong->_entryState != EntryState::Pending) {
return; // the check already ended: an answer, a failure or a new request
}
if (last) {
strong->_entryState = EntryState::Done;
}
LOG(("Update Info: entry pages gave %1%2"
).arg(fresh.join(',')
).arg(last ? u" (all answered)"_q : QString()));
if (!fresh.isEmpty()) {
strong->addAttempts(fresh);
strong->startNext();
}
if (last
&& strong->_replies.empty()
&& strong->_nextHost >= strong->attemptsCount()) {
strong->clearSentRequest();
strong->fail();
}
});
}
void HttpChecker::startNext() {
_staggerTimer.cancel();
if (_nextHost >= attemptsCount()) {
requestEntryNames();
return;
}
const auto attempt = _attempts[_nextHost];
++_nextHost;
sendTo(attempt);
if (_nextHost < attemptsCount()) {
_staggerTimer.callOnce(kMirrorStagger);
}
}
QString HttpChecker::mirrored(const QString &url) const {
return _answeredHost.isEmpty()
? url
: Core::ZsgMirrors::WithHost(url, _answeredHost);
}
void HttpChecker::sendTo(const Attempt &attempt) {
const auto url = attempt.github
? QUrl(kZaStoGramGithubApi.utf16())
: attempt.host.isEmpty()
? _baseUrl
: Core::ZsgMirrors::WithHost(_baseUrl, attempt.host);
auto request = QNetworkRequest(url);
// Qt's HTTP/2 backend does not apply the read-buffer limit.
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, false);
request.setTransferTimeout(int(kUpdateCheckTimeout));
if (_responseType == ResponseType::DevReleases) {
request.setRawHeader("Accept", "application/json");
request.setRawHeader("User-Agent", "ZaStoGram-Desktop-Updater");
}
const auto started = crl::now();
const auto reply = (attempt.direct ? _directManager : _manager)->get(
request);
_replies.push_back(reply);
reply->setReadBufferSize(kMaxResponseSize);
reply->connect(reply, &QNetworkReply::readyRead, [=, queued = false]() mutable {
if (queued || reply->bytesAvailable() < kMaxResponseSize) {
return;
}
queued = true;
crl::on_main(this, [=] {
gotResponse(reply, attempt, started);
});
});
// "finished" also comes after an error, one handler covers both.
reply->connect(reply, &QNetworkReply::finished, [=] {
gotResponse(reply, attempt, started);
});
}
void HttpChecker::attemptFailed() {
if (_nextHost < attemptsCount()) {
startNext();
} else if (_entryState == EntryState::None) {
requestEntryNames();
} else if (_replies.empty() && _entryState == EntryState::Done) {
clearSentRequest();
fail();
}
}
void HttpChecker::gotResponse(
not_null<QNetworkReply*> reply,
const Attempt &attempt,
crl::time started) {
const auto i = std::find(_replies.begin(), _replies.end(), reply.get());
if (i == _replies.end()) {
return;
}
_replies.erase(i);
const auto ok = (reply->error() == QNetworkReply::NoError);
const auto status = reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute).toInt();
const auto response = ok ? reply->read(kMaxResponseSize) : QByteArray();
const auto host = attempt.host;
LOG(("Update Info: %1%2 -> %3 (%4), http %5, %6 bytes, %7 ms"
).arg(attempt.github ? u"github"_q : host
).arg(attempt.direct ? u" [direct]"_q : QString()
).arg(int(reply->error())
).arg(reply->errorString()
).arg(status
).arg(response.size()
).arg(crl::now() - started));
reply->disconnect(reply, &QNetworkReply::finished, nullptr, nullptr);
reply->deleteLater();
if (!ok) {
attemptFailed();
return;
}
cSetLastUpdateCheck(base::unixtime::now());
if (response.size() >= kMaxResponseSize) {
LOG(("Update Error: update response is too large: %1")
.arg(response.size()));
attemptFailed();
return;
}
_answeredHost = host;
_answeredDirect = attempt.direct;
_answeredGithub = attempt.github;
const auto weak = base::make_weak(this);
const auto handled = (_responseType == ResponseType::DevReleases)
? handleDevReleases(response)
: handleResponse(response);
if (!handled) {
LOG(("Update Error: Bad update map size: %1").arg(response.size()));
if (const auto strong = weak.get()) {
strong->_answeredHost = QString();
strong->attemptFailed();
}
return;
}
// done() may have destroyed this checker already.
if (const auto strong = weak.get()) {
strong->clearSentRequest();
}
if (!host.isEmpty()) {
Core::ZsgMirrors::RememberGood(host);
}
}
bool HttpChecker::handleDevReleases(const QByteArray &response) {
auto error = QJsonParseError{ 0, QJsonParseError::NoError };
const auto document = QJsonDocument::fromJson(response, &error);
if (error.error != QJsonParseError::NoError || !document.isArray()) {
LOG(("Update Error: bad Forgejo releases response: %1")
.arg(error.errorString()));
return false;
}
const auto current = ZaStoGramDevBuildNumber().value_or(0);
auto best = current;
auto bestUrl = QString();
auto bestFallback = QString();
static const auto TagExpression = QRegularExpression(u"^dev-(\\d+)$"_q);
const auto packagePrefix = [&] {
const auto platform = Platform::AutoUpdateKey();
if (platform == "win") {
return u"tupdate"_q;
} else if (platform == "win64") {
return u"tx64upd"_q;
} else if (platform == "winarm") {
return u"tarm64upd"_q;
}
return QString();
}();
if (packagePrefix.isEmpty()) {
LOG(("Update Error: unsupported ZaStoGram dev update platform."));
return false;
}
for (const auto &value : document.array()) {
if (!value.isObject()) {
continue;
}
const auto release = value.toObject();
if (!release.value("prerelease").toBool()
|| release.value("draft").toBool()) {
continue;
}
const auto match = TagExpression.match(
release.value("tag_name").toString());
if (!match.hasMatch()) {
continue;
}
const auto build = match.captured(1).toULongLong();
if (build <= best) {
continue;
}
auto hasManifest = false;
auto packageVersion = 0ULL;
auto packageUrl = QString();
auto packageName = QString();
const auto packageExpression = QRegularExpression(
u"^%1(\\d+)_dev%2$"_q.arg(packagePrefix).arg(build));
for (const auto &assetValue : release.value("assets").toArray()) {
const auto asset = assetValue.toObject();
const auto name = asset.value("name").toString();
if (name == "current4") {
hasManifest = true;
} else if (const auto package = packageExpression.match(name);
package.hasMatch()) {
packageVersion = package.captured(1).toULongLong();
packageUrl = asset.value("browser_download_url").toString();
packageName = name;
}
}
if (hasManifest
&& packageVersion >= uint64(AppVersion)
&& !packageUrl.isEmpty()) {
best = build;
bestUrl = packageUrl;
// A package found on GitHub can also be fetched from the git
// mirrors when GitHub's file host is the one that is cut.
bestFallback = _answeredGithub
? QString(kZaStoGramForgejoDownload.utf16()).arg(
QString("dev-%1").arg(build),
packageName)
: QString();
}
}
if (bestUrl.isEmpty()) {
done(nullptr);
return true;
}
DEBUG_LOG(("Update Info: found ZaStoGram dev build %1").arg(best));
done(std::make_shared<HttpLoader>(
mirrored(bestUrl),
bestFallback,
_answeredDirect));
return true;
}
bool HttpChecker::handleResponse(const QByteArray &response) {
const auto handle = [&](const QString &url) {
done(url.isEmpty()
? nullptr
: std::make_shared<HttpLoader>(
mirrored(url),
QString(),
_answeredDirect));
return true;
};
if (const auto url = parseOldResponse(response)) {
return handle(*url);
} else if (const auto url = parseResponse(response)) {
return handle(*url);
}
return false;
}
void HttpChecker::clearSentRequest() {
_staggerTimer.cancel();
_entryTimer.cancel();
_entryState = EntryState::Done;
_nextHost = attemptsCount();
for (const auto reply : base::take(_replies)) {
reply->disconnect(reply, &QNetworkReply::finished, nullptr, nullptr);
reply->abort();
reply->disconnect();
reply->deleteLater();
}
if (const auto manager = _manager.release()) {
manager->deleteLater();
}
if (const auto manager = _directManager.release()) {
manager->deleteLater();
}
}
std::optional<QString> HttpChecker::parseOldResponse(
const QByteArray &response) const {
const auto string = QString::fromLatin1(response);
const auto old = QRegularExpression(
u"^\\s*(\\d+)\\s*:\\s*([\\x21-\\x7f]+)\\s*$"_q
).match(string);
if (!old.hasMatch()) {
return std::nullopt;
}
const auto availableVersion = old.captured(1).toULongLong();
const auto url = old.captured(2);
const auto isAvailableAlpha = url.startsWith(qstr("beta_"));
return validateLatestUrl(
availableVersion,
isAvailableAlpha,
isAvailableAlpha ? url.mid(5) + "_{signature}" : url);
}
std::optional<QString> HttpChecker::parseResponse(
const QByteArray &response) const {
auto bestAvailableVersion = 0ULL;
auto bestIsAvailableAlpha = false;
auto bestLink = QString();
const auto accumulate = [&](
uint64 version,
bool isAlpha,
const QJsonObject &map) {
bestAvailableVersion = version;
bestIsAvailableAlpha = isAlpha;
const auto link = map.constFind("link");
if (link == map.constEnd()) {
LOG(("Update Error: Link not found for version %1."
).arg(version));
return false;
} else if (!(*link).isString()) {
LOG(("Update Error: Link is not a string for version %1."
).arg(version));
return false;
}
bestLink = (*link).toString();
return true;
};
const auto result = ParseCommonMap(response, testing(), accumulate);
if (!result) {
return std::nullopt;
}
return validateLatestUrl(
bestAvailableVersion,
bestIsAvailableAlpha,
Local::readAutoupdatePrefix() + bestLink);
}
QString HttpChecker::validateLatestUrl(
uint64 availableVersion,
bool isAvailableAlpha,
QString url) const {
const auto myVersion = isAvailableAlpha
? cAlphaVersion()
: uint64(AppVersion);
const auto validVersion = (cAlphaVersion() || !isAvailableAlpha);
if (!validVersion || availableVersion <= myVersion) {
return QString();
}
const auto versionUrl = url.replace(
"{version}",
QString::number(availableVersion));
const auto finalUrl = isAvailableAlpha
? QString(versionUrl).replace(
"{signature}",
countAlphaVersionSignature(availableVersion))
: versionUrl;
return finalUrl;
}
HttpChecker::~HttpChecker() {
clearSentRequest();
}
HttpLoader::HttpLoader(
const QString &url,
const QString &fallbackUrl,
bool direct)
: Loader(UpdatesFolder() + '/' + ExtractFilename(url), kChunkSize)
, _url(url)
, _fallbackUrl(fallbackUrl)
, _direct(direct) {
}
void HttpLoader::startLoading() {
LOG(("Update Info: Loading using HTTP from '%1'.").arg(_url));
// The address the check was answered with goes first, then the same file
// on every other git mirror, then the fallback file with its mirrors.
auto urls = QStringList(_url);
const auto addMirrors = [&](const QString &url) {
if (!Core::ZsgMirrors::IsGitHost(QUrl(url).host())) {
if (!urls.contains(url)) {
urls.push_back(url);
}
return;
}
for (const auto &host : Core::ZsgMirrors::Hosts()) {
const auto mirror = Core::ZsgMirrors::WithHost(url, host);
if (!urls.contains(mirror)) {
urls.push_back(mirror);
}
}
};
addMirrors(_url);
if (!_fallbackUrl.isEmpty()) {
addMirrors(_fallbackUrl);
}
_thread = std::make_unique<QThread>();
_actor = new HttpLoaderActor(this, _thread.get(), urls, _direct);
_thread->start();
}
HttpLoader::~HttpLoader() {
if (const auto thread = base::take(_thread)) {
if (const auto actor = base::take(_actor)) {
QObject::connect(
thread.get(),
&QThread::finished,
actor,
&QObject::deleteLater);
}
thread->quit();
thread->wait();
}
}
HttpLoaderActor::HttpLoaderActor(
not_null<HttpLoader*> parent,
not_null<QThread*> thread,
const QStringList &urls,
bool direct)
: _parent(parent)
, _urls(urls) {
if (direct) {
_manager.setProxy(QNetworkProxy::NoProxy);
}
moveToThread(thread);
_manager.moveToThread(thread);
connect(thread, &QThread::started, this, [=] { start(); });
}
void HttpLoaderActor::start() {
sendRequest();
}
bool HttpLoaderActor::tryNextHost() {
if (_urlIndex + 1 >= _urls.size()) {
return false;
}
++_urlIndex;
LOG(("Update Info: trying to continue from '%1'.").arg(_urls[_urlIndex]));
if (const auto old = _reply.release()) {
old->disconnect(this);
old->abort();
old->deleteLater();
}
sendRequest();
return true;
}
void HttpLoaderActor::sendRequest() {
auto request = QNetworkRequest(QUrl(_urls[_urlIndex]));
// A name dropped by a filter never answers and never errors: give up
// on it after a short silence so the next mirror can resume the file.
request.setTransferTimeout(kLoaderSilence);
// GitHub hands its files over through a redirect to another host.
request.setAttribute(
QNetworkRequest::RedirectPolicyAttribute,
QNetworkRequest::NoLessSafeRedirectPolicy);
const auto rangeHeaderValue = "bytes="
+ QByteArray::number(_parent->alreadySize())
+ "-";
request.setRawHeader("Range", rangeHeaderValue);
request.setAttribute(
QNetworkRequest::HttpPipeliningAllowedAttribute,
true);
_reply.reset(_manager.get(request));
connect(
_reply.get(),
&QNetworkReply::downloadProgress,
this,
&HttpLoaderActor::partFinished);
connect(
_reply.get(),
&QNetworkReply::errorOccurred,
this,
&HttpLoaderActor::partFailed);
connect(
_reply.get(),
&QNetworkReply::metaDataChanged,
this,
&HttpLoaderActor::gotMetaData);
}
void HttpLoaderActor::gotMetaData() {
const auto pairs = _reply->rawHeaderPairs();
for (const auto &pair : pairs) {
if (QString::fromUtf8(pair.first).toLower() == "content-range") {
const auto m = QRegularExpression(u"/(\\d+)([^\\d]|$)"_q).match(QString::fromUtf8(pair.second));
if (m.hasMatch()) {
_parent->writeChunk({}, m.captured(1).toLongLong());
}
}
}
}
void HttpLoaderActor::partFinished(qint64 got, qint64 total) {
if (!_reply) return;
const auto statusCode = _reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute);
if (statusCode.isValid()) {
const auto status = statusCode.toInt();
if (status != 200 && status != 206 && status != 416) {
LOG(("Update Error: "
"Bad HTTP status received in partFinished(): %1"
).arg(status));
if (!tryNextHost()) {
_parent->threadSafeFailed();
}
return;
}
}
DEBUG_LOG(("Update Info: part %1 of %2").arg(got).arg(total));
const auto data = _reply->readAll();
_parent->writeChunk(bytes::make_span(data), total);
}
void HttpLoaderActor::partFailed(QNetworkReply::NetworkError e) {
if (!_reply) return;
const auto statusCode = _reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute);
_reply.release()->deleteLater();
if (statusCode.isValid()) {
const auto status = statusCode.toInt();
if (status == 416) { // Requested range not satisfiable
_parent->writeChunk({}, _parent->alreadySize());
return;
}
}
LOG(("Update Error: failed to download part after %1, error %2"
).arg(_parent->alreadySize()
).arg(e));
if (!tryNextHost()) {
_parent->threadSafeFailed();
}
}
MtpChecker::MtpChecker(
base::weak_ptr<Main::Session> session,
bool testing)
: Checker(testing)
, _mtp(session) {
}
void MtpChecker::start() {
if (!_mtp.valid()) {
LOG(("Update Info: MTP is unavailable."));
crl::on_main(this, [=] { fail(); });
return;
}
if (BuildIsCanary) {
startCanary();
return;
}
const auto updaterVersion = Platform::AutoUpdateVersion();
const auto feed = "tdhbcfeed"
+ (updaterVersion > 1 ? QString::number(updaterVersion) : QString());
MTP::ResolveChannel(&_mtp, feed, [=](
const MTPInputChannel &channel) {
_mtp.send(
MTPmessages_GetHistory(
MTP_inputPeerChannel(
channel.c_inputChannel().vchannel_id(),
channel.c_inputChannel().vaccess_hash()),
MTP_int(0), // offset_id
MTP_int(0), // offset_date
MTP_int(0), // add_offset
MTP_int(1), // limit
MTP_int(0), // max_id
MTP_int(0), // min_id
MTP_long(0)), // hash
[=](const MTPmessages_Messages &result) { gotMessage(result); },
failHandler());
}, [=] { fail(); });
}
void MtpChecker::gotMessage(const MTPmessages_Messages &result) {
const auto location = parseMessage(result);
if (!location) {
fail();
return;
} else if (location->username.isEmpty()) {
done(nullptr);
return;
}
const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) {
if (loader) {
done(std::move(loader));
} else {
fail();
}
};
MTP::StartDedicatedLoader(&_mtp, *location, UpdatesFolder(), ready);
}
auto MtpChecker::parseMessage(const MTPmessages_Messages &result) const
-> std::optional<FileLocation> {
const auto message = MTP::GetMessagesElement(result);
if (!message || message->type() != mtpc_message) {
LOG(("Update Error: MTP feed message not found."));
return std::nullopt;
}
return parseText(message->c_message().vmessage().v);
}
auto MtpChecker::parseText(const QByteArray &text) const
-> std::optional<FileLocation> {
auto bestAvailableVersion = 0ULL;
auto bestLocation = FileLocation();
const auto accumulate = [&](
uint64 version,
bool isAlpha,
const QJsonObject &map) {
if (isAlpha) {
LOG(("Update Error: MTP closed alpha found."));
return false;
}
bestAvailableVersion = version;
const auto key = testing() ? "testing" : "released";
const auto entry = map.constFind(key);
if (entry == map.constEnd()) {
LOG(("Update Error: MTP entry not found for version %1."
).arg(version));
return false;
} else if (!(*entry).isString()) {
LOG(("Update Error: MTP entry is not a string for version %1."
).arg(version));
return false;
}
const auto full = (*entry).toString();
const auto start = full.indexOf(':');
const auto post = full.indexOf('#');
if (start <= 0 || post < start) {
LOG(("Update Error: MTP entry '%1' is bad for version %2."
).arg(full
).arg(version));
return false;
}
bestLocation.username = full.mid(start + 1, post - start - 1);
bestLocation.postId = base::StringViewMid(full, post + 1).toInt();
if (bestLocation.username.isEmpty() || !bestLocation.postId) {
LOG(("Update Error: MTP entry '%1' is bad for version %2."
).arg(full
).arg(version));
return false;
}
return true;
};
const auto result = ParseCommonMap(text, testing(), accumulate);
if (!result) {
return std::nullopt;
}
return validateLatestLocation(bestAvailableVersion, bestLocation);
}
auto MtpChecker::validateLatestLocation(
uint64 availableVersion,
const FileLocation &location) const -> FileLocation {
const auto myVersion = uint64(AppVersion);
return (availableVersion <= myVersion) ? FileLocation() : location;
}
void MtpChecker::startCanary() {
if (!CanaryMetadataMessageId) {
LOG(("Update Error: Canary metadata message id is not set."));
crl::on_main(this, [=] { fail(); });
return;
}
// The branches are compile-time: the private one exists only in a
// build that has a real channel id, so no other build compiles a
// channelLoaded() whose result the optimizer can fold to nullptr and
// then report as a null 'this' at the inputChannel() call below.
if constexpr (BuildUpdateChannel == Updates::Channel::CanaryPublic) {
const auto username = QString::fromLatin1(
CanaryPublicChannelUsername);
if (username.isEmpty()) {
LOG(("Update Error: Canary channel username is not set."));
crl::on_main(this, [=] { fail(); });
return;
}
MTP::ResolveChannel(&_mtp, username, [=](
const MTPInputChannel &channel) {
requestCanaryMetadata(channel, CanaryMetadataMessageId, true);
}, [=] { fail(); });
} else if constexpr (CanaryPrivateChannelId != 0) {
// Membership is enrollment for the private canary channel, so it
// is located by numeric id and cached access hash on this
// session, never through a username resolve.
const auto session = _mtp.session().get();
const auto channel = session
? session->data().channelLoaded(
ChannelId(BareId(CanaryPrivateChannelId)))
: nullptr;
if (!channel || !channel->amIn()) {
LOG(("Update Error: Canary private channel is not available."));
crl::on_main(this, [=] { fail(); });
return;
}
requestCanaryMetadata(
channel->inputChannel(),
CanaryMetadataMessageId,
true);
} else {
LOG(("Update Error: Canary private channel id is not set."));
crl::on_main(this, [=] { fail(); });
}
}
void MtpChecker::requestCanaryMetadata(
const MTPInputChannel &channel,
int messageId,
bool fallbackToPinned) {
_mtp.send(
MTPchannels_GetMessages(
channel,
MTP_vector<MTPInputMessage>(
1,
MTP_inputMessageID(MTP_int(messageId)))),
[=](const MTPmessages_Messages &result) {
gotCanaryMessage(channel, result, messageId, fallbackToPinned);
},
failHandler());
}
void MtpChecker::requestCanaryPinnedFallback(const MTPInputChannel &channel) {
_mtp.send(
MTPchannels_GetFullChannel(channel),
[=](const MTPmessages_ChatFull &result) {
const auto pinnedId = result.data().vfull_chat().match([](
const MTPDchannelFull &data) {
return data.vpinned_msg_id().value_or_empty();
}, [](const auto &) {
return 0;
});
if (!pinnedId) {
LOG(("Update Error: Canary pinned message not found."));
fail();
return;
}
requestCanaryMetadata(channel, pinnedId, false);
},
failHandler());
}
void MtpChecker::gotCanaryMessage(
const MTPInputChannel &channel,
const MTPmessages_Messages &result,
int messageId,
bool fallbackToPinned) {
const auto message = MTP::GetMessagesElement(result, messageId);
if (!message || message->type() != mtpc_message) {
if (fallbackToPinned) {
requestCanaryPinnedFallback(channel);
} else {
LOG(("Update Error: Canary metadata message not found."));
fail();
}
return;
}
parseCanaryMetadata(channel, message->c_message().vmessage().v);
}
void MtpChecker::parseCanaryMetadata(
const MTPInputChannel &channel,
const QByteArray &text) {
auto parseError = QJsonParseError();
const auto document = QJsonDocument::fromJson(text, &parseError);
if (parseError.error != QJsonParseError::NoError
|| !document.isObject()) {
LOG(("Update Error: Could not parse canary metadata JSON."));
fail();
return;
}
const auto object = document.object();
if (object.value(u"format"_q).toDouble() != 1.) {
LOG(("Update Error: Unknown canary metadata format."));
fail();
return;
}
const auto decode = [](const QJsonValue &value) {
if (!value.isString()) {
return QByteArray();
}
const auto decoded = QByteArray::fromBase64Encoding(
value.toString().toLatin1(),
QByteArray::AbortOnBase64DecodingErrors);
return decoded ? decoded.decoded : QByteArray();
};
const auto manifest = decode(object.value(u"manifest"_q));
const auto manifestSig = decode(object.value(u"manifest_sig"_q));
if (!manifest.isEmpty() && !manifestSig.isEmpty()) {
auto error = QString();
if (auto parsed = Updates::ParseVerifiedManifest(
manifest,
manifestSig,
Updates::RootPublicKeyPem(),
&error)) {
AdoptManifest(*parsed);
} else {
LOG(("Update Error: Bad canary metadata manifest: %1").arg(error));
}
}
const auto channels = object.value(u"channels"_q).toObject();
const auto platform = Platform::AutoUpdateKey();
auto bestVersion = quint64(0);
auto bestPostId = 0;
const auto readU32 = [](const QJsonValue &value, quint32 *result) {
const auto number = value.toDouble();
if (!(number >= 0.) || !(number <= 4294967295.)) {
return false;
}
*result = quint32(number);
return (double(*result) == number);
};
const auto consider = [&](const QByteArray &name) {
const auto entry = channels.value(QLatin1String(name)).toObject();
if (entry.isEmpty()) {
return;
}
auto base = quint32(0);
auto counter = quint32(0);
auto postId = quint32(0);
if (!readU32(entry.value(u"base"_q), &base)
|| !base
|| !readU32(entry.value(u"counter"_q), &counter)
|| !readU32(
entry.value(u"posts"_q).toObject().value(platform),
&postId)
|| !postId
|| postId > quint32(0x7FFFFFFF)) {
return;
}
const auto version = Updates::MakeUpdateVersion(base, counter);
if (version > bestVersion) {
bestVersion = version;
bestPostId = int(postId);
}
};
consider(Updates::ChannelName(BuildUpdateChannel));
if (BuildUpdateChannel == Updates::Channel::CanaryPublic) {
// Dormancy rescue: a stale public canary channel may point to a
// newer stable or beta release. Package verification still
// enforces the strictly-greater-base channel policy on whatever
// is downloaded.
consider(Updates::ChannelName(Updates::Channel::Stable));
consider(Updates::ChannelName(Updates::Channel::Beta));
}
if (!bestVersion || bestVersion <= RunningUpdateVersion()) {
done(nullptr);
return;
}
auto location = FileLocation();
location.channelId = uint64(channel.c_inputChannel().vchannel_id().v);
location.accessHash = uint64(channel.c_inputChannel().vaccess_hash().v);
location.postId = bestPostId;
const auto ready = [=](std::unique_ptr<MTP::DedicatedLoader> loader) {
if (loader) {
done(std::move(loader));
} else {
fail();
}
};
MTP::StartDedicatedLoader(&_mtp, location, UpdatesFolder(), ready);
}
Fn<void(const MTP::Error &error)> MtpChecker::failHandler() {
return [=](const MTP::Error &error) {
LOG(("Update Error: MTP check failed with '%1'"
).arg(QString::number(error.code()) + ':' + error.type()));
fail();
};
}
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
FlatpakChecker::FlatpakChecker(bool testing)
: Checker(testing)
, _watcher({u"/app"_q}) {
FlatpakPortal::FlatpakProxy::new_for_bus(
Gio::BusType::SESSION_,
Gio::DBusProxyFlags::NONE_,
kFlatpakPortalService,
kFlatpakPortalObjectPath,
crl::guard(this, [=](GObject::Object, Gio::AsyncResult res) {
auto result = FlatpakPortal::FlatpakProxy::new_for_bus_finish(res);
if (!result) {
Gio::DBusErrorNS_::strip_remote_error(result.error());
LOG(("Update Error: %1").arg(result.error().message_().c_str()));
return;
}
_interface = *result;
_interface.call_create_update_monitor(
GLib::Variant::new_array(
GLib::VariantType::new_("{sv}"),
{}),
[=](GObject::Object, Gio::AsyncResult res) {
const auto result = _interface.call_create_update_monitor_finish(
res);
if (!result) {
Gio::DBusErrorNS_::strip_remote_error(result.error());
LOG(("Update Error: %1").arg(
result.error().message_().c_str()));
fail();
return;
}
FlatpakPortal::FlatpakUpdateMonitorProxy::new_for_bus(
Gio::BusType::SESSION_,
Gio::DBusProxyFlags::NONE_,
kFlatpakPortalService,
std::get<1>(*result),
crl::guard(this, [=](GObject::Object, Gio::AsyncResult res) {
using FlatpakPortal::FlatpakUpdateMonitorProxy;
auto result = FlatpakUpdateMonitorProxy::new_for_bus_finish(
res);
if (!result) {
Gio::DBusErrorNS_::strip_remote_error(result.error());
LOG(("Update Error: %1").arg(
result.error().message_().c_str()));
fail();
return;
}
_monitor = *result;
_updateAvailableSignal
= _monitor.signal_update_available().connect([=](
FlatpakPortal::FlatpakUpdateMonitor,
GLib::Variant updateInfo) {
done(std::make_shared<FlatpakLoader>(_monitor));
});
}));
});
}));
QObject::connect(
&_watcher,
&QFileSystemWatcher::directoryChanged,
[=](const QString &path) {
start();
});
}
void FlatpakChecker::start() {
if (QFileInfo::exists(kFlatpakUpdated.utf16())) {
done(std::make_shared<FlatpakLoader>(_monitor));
}
}
bool FlatpakChecker::poll() const {
return false;
}
FlatpakChecker::~FlatpakChecker() {
if (_monitor) {
_monitor.disconnect(_updateAvailableSignal);
_monitor.call_close(nullptr);
}
}
FlatpakLoader::FlatpakLoader(FlatpakPortal::FlatpakUpdateMonitor monitor)
: Loader({}, kChunkSize)
, _monitor(monitor) {
if (!_monitor) {
return;
}
_progressSignal = _monitor.signal_progress().connect([=](
FlatpakPortal::FlatpakUpdateMonitor,
GLib::Variant info) {
auto dict = GLib::VariantDict::new_(info);
switch (dict.lookup_value("status").get_uint32()) {
case 0: {
const auto n_ops = dict.lookup_value("n_ops").get_uint32();
const auto op = dict.lookup_value("op").get_uint32();
const auto progress = dict.lookup_value("progress").get_uint32();
threadSafeProgress({
int64(
std::round((op + (progress / 100.)) / n_ops * 104857600)),
104857600,
true,
});
} break;
case 1:
case 2: threadSafeReady(); break;
case 3: {
LOG(("Update Error: %1").arg(
dict.lookup_value("error_message").get_string(
nullptr).c_str()));
threadSafeFailed();
} break;
}
});
}
void FlatpakLoader::startLoading() {
if (QFileInfo::exists(kFlatpakUpdated.utf16())) {
threadSafeReady();
}
if (!_monitor) {
return;
}
_monitor.call_update(
base::Platform::XDP::ParentWindowID(),
GLib::Variant::new_array(
GLib::VariantType::new_("{sv}"),
{}),
crl::guard(this, [=](GObject::Object, Gio::AsyncResult res) {
const auto result = _monitor.call_close_finish(res);
if (!result) {
Gio::DBusErrorNS_::strip_remote_error(result.error());
LOG(("Update Error: %1").arg(
result.error().message_().c_str()));
threadSafeFailed();
}
}));
}
FlatpakLoader::~FlatpakLoader() {
if (_monitor) {
_monitor.disconnect(_progressSignal);
}
}
#endif // !Q_OS_WIN && !Q_OS_MACOS
} // namespace
bool UpdaterDisabled() {
return UpdaterIsDisabled;
}
void SetUpdaterDisabledAtStartup() {
Expects(UpdaterInstance.lock() == nullptr);
UpdaterIsDisabled = true;
}
bool WriteUpdateVersionFile(
const QString &directory,
quint32 version,
quint64 canaryVersion) {
// create tdata/version file
QDir().mkpath(directory + u"/tdata"_q);
std::wstring versionString = FormatVersionDisplay(version).toStdWString();
const auto versionNum = canaryVersion
? VersionInt(kVersionFileCanaryMarker)
: VersionInt(version);
const auto versionLen = VersionInt(versionString.size() * sizeof(VersionChar));
VersionChar versionStr[32];
memcpy(versionStr, versionString.c_str(), versionLen);
QFile fVersion(directory + u"/tdata/version"_q);
if (!fVersion.open(QIODevice::WriteOnly)) {
LOG(("Update Error: cant write version file '%1'").arg(directory + u"/version"_q));
return false;
}
fVersion.write((const char*)&versionNum, sizeof(VersionInt));
if (canaryVersion) {
fVersion.write((const char*)&canaryVersion, sizeof(quint64));
} else {
fVersion.write((const char*)&versionLen, sizeof(VersionInt));
fVersion.write((const char*)&versionStr[0], versionLen);
}
fVersion.close();
return true;
}
class Updater : public base::has_weak_ptr {
public:
Updater();
rpl::producer<> checking() const;
rpl::producer<> isLatest() const;
rpl::producer<Progress> progress() const;
rpl::producer<> failed() const;
rpl::producer<> ready() const;
void start(bool forceWait);
void stop();
void test();
State state() const;
int already() const;
int size() const;
bool percent() const;
void setMtproto(base::weak_ptr<Main::Session> session);
~Updater();
private:
enum class Action {
Waiting,
Checking,
Loading,
Unpacking,
Ready,
};
void check();
void startImplementation(
not_null<Implementation*> which,
std::unique_ptr<Checker> checker);
bool tryLoaders();
void handleTimeout();
void checkerDone(
not_null<Implementation*> which,
std::shared_ptr<Loader> loader);
void checkerFail(not_null<Implementation*> which);
void finalize(QString filepath);
void unpackDone(bool ready);
void reportChecking();
void reportProgress(Progress progress);
void reportLatest();
void reportFailed();
void reportReady();
void scheduleNext();
bool _testing = false;
Action _action = Action::Waiting;
base::Timer _timer;
base::Timer _retryTimer;
rpl::event_stream<> _checking;
rpl::event_stream<> _isLatest;
rpl::event_stream<Progress> _progress;
rpl::event_stream<> _failed;
rpl::event_stream<> _ready;
Implementation _httpImplementation;
Implementation _mtpImplementation;
Implementation _flatpakImplementation;
std::shared_ptr<Loader> _activeLoader;
bool _usingMtprotoLoader = (cAlphaVersion() != 0);
base::weak_ptr<Main::Session> _session;
};
Updater::Updater()
: _timer([=] { check(); })
, _retryTimer([=] { handleTimeout(); }) {
}
rpl::producer<> Updater::checking() const {
return _checking.events();
}
rpl::producer<> Updater::isLatest() const {
return _isLatest.events();
}
auto Updater::progress() const
-> rpl::producer<Progress> {
return _progress.events();
}
rpl::producer<> Updater::failed() const {
return _failed.events();
}
rpl::producer<> Updater::ready() const {
return _ready.events();
}
void Updater::check() {
start(false);
}
void Updater::reportReady() {
stop();
_action = Action::Ready;
if (!Quitting()) {
cSetLastUpdateCheck(base::unixtime::now());
Local::writeSettings();
}
_ready.fire({});
}
void Updater::reportFailed() {
const auto flatpakWaiting = KSandbox::isFlatpak()
&& (_action == Action::Waiting);
if (_action != Action::Checking
&& _action != Action::Loading
&& _action != Action::Unpacking
&& !flatpakWaiting) {
return;
}
LOG(("Update Info: the update check ended with a failure."));
scheduleNext();
_failed.fire({});
}
void Updater::reportLatest() {
const auto flatpakWaiting = KSandbox::isFlatpak()
&& (_action == Action::Waiting);
if (_action != Action::Checking && !flatpakWaiting) {
return;
}
if (const auto update = FindUpdateFile(); !update.isEmpty()) {
QFile(update).remove();
}
LOG(("Update Info: the latest version is installed."));
scheduleNext();
_isLatest.fire({});
}
void Updater::reportChecking() {
_action = Action::Checking;
_retryTimer.callOnce(kUpdateCheckBudget);
_checking.fire({});
}
void Updater::reportProgress(Progress progress) {
if (_action != Action::Loading) {
return;
}
_retryTimer.callOnce(kUpdaterStallTimeout);
_progress.fire(std::move(progress));
}
void Updater::scheduleNext() {
stop();
if (!Quitting()) {
cSetLastUpdateCheck(base::unixtime::now());
Local::writeSettings();
start(true);
}
}
auto Updater::state() const -> State {
if (_action == Action::Ready) {
return State::Ready;
} else if (_action == Action::Loading) {
return State::Download;
}
return State::None;
}
int Updater::size() const {
return _activeLoader ? _activeLoader->totalSize() : 0;
}
int Updater::already() const {
return _activeLoader ? _activeLoader->alreadySize() : 0;
}
bool Updater::percent() const {
return _activeLoader ? _activeLoader->preferPercent() : 0;
}
void Updater::stop() {
_timer.cancel();
_retryTimer.cancel();
_httpImplementation = Implementation();
_mtpImplementation = Implementation();
_flatpakImplementation = Implementation{
std::move(_flatpakImplementation.checker)
};
_activeLoader = nullptr;
_action = Action::Waiting;
}
void Updater::start(bool forceWait) {
if (cExeName().isEmpty()) {
return;
}
_timer.cancel();
if (_action == Action::Checking && !_retryTimer.isActive()) {
LOG(("Update Info: the check had no timer, ending it."));
handleTimeout();
}
if (!cAutoUpdate()
|| _action != Action::Waiting
|| Test::SuppressUpdateChecks()) {
return;
}
_retryTimer.cancel();
const auto frequent = cAlphaVersion() || BuildIsCanary;
const auto constDelay = frequent
? kFrequentUpdateDelayConstPart
: UpdateDelayConstPart;
const auto randDelay = frequent
? kFrequentUpdateDelayRandPart
: UpdateDelayRandPart;
const auto updateInSecs = cLastUpdateCheck()
+ constDelay
+ int(rand() % randDelay)
- base::unixtime::now();
auto sendRequest = (updateInSecs <= 0)
|| (updateInSecs > constDelay + randDelay);
if (!sendRequest && !forceWait) {
if (!FindUpdateFile().isEmpty()) {
sendRequest = true;
}
}
if (cManyInstance() && !Logs::DebugEnabled()) {
// Only main instance is updating.
return;
}
if (KSandbox::isFlatpak()) {
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
if (!_flatpakImplementation.checker) {
startImplementation(
&_flatpakImplementation,
std::make_unique<FlatpakChecker>(_testing));
}
#endif // !Q_OS_WIN && !Q_OS_MACOS
} else if (sendRequest) {
reportChecking();
startImplementation(
&_httpImplementation,
std::make_unique<HttpChecker>(_testing));
// Updates come only from our Forgejo releases, never from
// the official Telegram update channel.
startImplementation(&_mtpImplementation, nullptr);
} else {
_timer.callOnce((updateInSecs + 5) * crl::time(1000));
}
}
void Updater::startImplementation(
not_null<Implementation*> which,
std::unique_ptr<Checker> checker) {
if (!checker) {
class EmptyChecker : public Checker {
public:
EmptyChecker() : Checker(false) {
}
void start() override {
crl::on_main(this, [=] { fail(); });
}
};
checker = std::make_unique<EmptyChecker>();
}
checker->ready(
) | rpl::on_next([=](std::shared_ptr<Loader> &&loader) {
checkerDone(which, std::move(loader));
}, checker->lifetime());
checker->failed(
) | rpl::on_next([=] {
checkerFail(which);
}, checker->lifetime());
*which = Implementation{ std::move(checker) };
crl::on_main(which->checker.get(), [=] {
which->checker->start();
});
}
void Updater::checkerDone(
not_null<Implementation*> which,
std::shared_ptr<Loader> loader) {
if (which->checker->poll()) which->checker = nullptr;
which->loader = std::move(loader);
tryLoaders();
}
void Updater::checkerFail(not_null<Implementation*> which) {
which->checker = nullptr;
which->failed = true;
tryLoaders();
}
void Updater::test() {
_testing = true;
cSetLastUpdateCheck(0);
start(false);
}
void Updater::setMtproto(base::weak_ptr<Main::Session> session) {
_session = session;
}
void Updater::handleTimeout() {
LOG(("Update Info: timeout in state %1 (http: %2, mtp: %3)"
).arg(int(_action)
).arg(_httpImplementation.checker ? u"waiting"_q : u"done"_q
).arg(_mtpImplementation.checker ? u"waiting"_q : u"done"_q));
if (_action == Action::Checking) {
const auto reset = [&](Implementation &which) {
if (base::take(which.checker)) {
which.failed = true;
}
};
reset(_httpImplementation);
reset(_mtpImplementation);
tryLoaders();
} else if (_action == Action::Loading) {
reportFailed();
}
}
bool Updater::tryLoaders() {
if (_httpImplementation.checker || _mtpImplementation.checker) {
// Some checkers didn't finish yet.
return true;
}
_retryTimer.cancel();
const auto tryOne = [&](Implementation &which) {
_activeLoader = std::move(which.loader);
if (const auto loader = _activeLoader.get()) {
_action = Action::Loading;
loader->progress(
) | rpl::on_next([=](Progress progress) {
reportProgress(std::move(progress));
}, loader->lifetime());
loader->ready(
) | rpl::on_next([=](QString &&filepath) {
finalize(std::move(filepath));
}, loader->lifetime());
loader->failed(
) | rpl::on_next([=] {
reportFailed();
}, loader->lifetime());
_retryTimer.callOnce(kUpdaterStallTimeout);
// The settings page says "Checking" until the first progress
// arrives, and through a slow mirror it takes a while.
_progress.fire(Progress{
loader->alreadySize(),
loader->totalSize(),
loader->preferPercent(),
});
loader->wipeFolder();
loader->start();
} else {
reportLatest();
}
};
if (KSandbox::isFlatpak()) {
if (_flatpakImplementation.failed) {
reportFailed();
return false;
} else {
tryOne(_flatpakImplementation);
}
} else if (_mtpImplementation.failed && _httpImplementation.failed) {
reportFailed();
return false;
} else if (!_mtpImplementation.loader) {
tryOne(_httpImplementation);
} else if (!_httpImplementation.loader) {
tryOne(_mtpImplementation);
} else {
tryOne(_usingMtprotoLoader
? _mtpImplementation
: _httpImplementation);
_usingMtprotoLoader = !_usingMtprotoLoader;
}
return true;
}
void Updater::finalize(QString filepath) {
if (_action != Action::Loading) {
return;
}
_retryTimer.cancel();
_activeLoader = nullptr;
_action = Action::Unpacking;
crl::async([=] {
const auto ready = UnpackUpdate(filepath);
crl::on_main([=] {
GetUpdaterInstance()->unpackDone(ready);
});
});
}
void Updater::unpackDone(bool ready) {
if (ready) {
reportReady();
} else {
ClearAll();
reportFailed();
}
}
Updater::~Updater() {
stop();
}
UpdateChecker::UpdateChecker()
: _updater(GetUpdaterInstance()) {
if (IsAppLaunched() && Core::App().domain().started()) {
if (const auto session = Core::App().activeAccount().maybeSession()) {
_updater->setMtproto(session);
}
}
}
rpl::producer<> UpdateChecker::checking() const {
return _updater->checking();
}
rpl::producer<> UpdateChecker::isLatest() const {
return _updater->isLatest();
}
auto UpdateChecker::progress() const
-> rpl::producer<Progress> {
return _updater->progress();
}
rpl::producer<> UpdateChecker::failed() const {
return _updater->failed();
}
rpl::producer<> UpdateChecker::ready() const {
return _updater->ready();
}
void UpdateChecker::start(bool forceWait) {
_updater->start(forceWait);
}
void UpdateChecker::test() {
_updater->test();
}
void UpdateChecker::setMtproto(base::weak_ptr<Main::Session> session) {
_updater->setMtproto(session);
}
void UpdateChecker::stop() {
_updater->stop();
}
auto UpdateChecker::state() const
-> State {
return _updater->state();
}
int UpdateChecker::already() const {
return _updater->already();
}
int UpdateChecker::size() const {
return _updater->size();
}
bool UpdateChecker::percent() const {
return _updater->percent();
}
//QString winapiErrorWrap() {
// WCHAR errMsg[2048];
// DWORD errorCode = GetLastError();
// LPTSTR errorText = NULL, errorTextDefault = L"(Unknown error)";
// FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, 0, 0);
// if (!errorText) {
// errorText = errorTextDefault;
// }
// StringCbPrintf(errMsg, sizeof(errMsg), L"Error code: %d, error message: %s", errorCode, errorText);
// if (errorText != errorTextDefault) {
// LocalFree(errorText);
// }
// return QString::fromWCharArray(errMsg);
//}
namespace {
#if !defined TDESKTOP_DISABLE_AUTOUPDATE || (!defined Q_OS_WIN && !defined Q_OS_MACOS)
[[nodiscard]] bool PromoteReadyUpdater() {
QString readyFilePath = cWorkingDir() + u"tupdates/temp/ready"_q, readyPath = cWorkingDir() + u"tupdates/temp"_q;
if (!QFile(readyFilePath).exists() || cExeName().isEmpty()) {
if (QDir(cWorkingDir() + u"tupdates/ready"_q).exists() || QDir(cWorkingDir() + u"tupdates/temp"_q).exists()) {
ClearAll();
}
return false;
}
// check ready version
QString versionPath = readyPath + u"/tdata/version"_q;
{
QFile fVersion(versionPath);
if (!fVersion.open(QIODevice::ReadOnly)) {
LOG(("Update Error: cant read version file '%1'").arg(versionPath));
ClearAll();
return false;
}
auto versionNum = VersionInt();
if (fVersion.read((char*)&versionNum, sizeof(VersionInt)) != sizeof(VersionInt)) {
LOG(("Update Error: cant read version from file '%1'").arg(versionPath));
ClearAll();
return false;
}
if (versionNum == 0x7FFFFFFF) { // alpha version
LOG(("Update Error: legacy alpha update is not supported."));
ClearAll();
return false;
} else if (versionNum == kVersionFileCanaryMarker) {
quint64 canaryVersion = 0;
if (fVersion.read((char*)&canaryVersion, sizeof(quint64)) != sizeof(quint64)) {
LOG(("Update Error: cant read canary version from file '%1'").arg(versionPath));
ClearAll();
return false;
}
if (!BuildIsCanary || canaryVersion <= RunningUpdateVersion()) {
LOG(("Update Error: cant install canary version %1 having version %2").arg(canaryVersion).arg(RunningUpdateVersion()));
ClearAll();
return false;
}
} else if (BuildUpdateChannel == Updates::Channel::CanaryPrivate) {
LOG(("Update Error: cant install a non-canary version %1 on a private canary").arg(versionNum));
ClearAll();
return false;
} else if (versionNum < AppVersion
|| (versionNum == AppVersion && !IsZaStoGramDevBuild())) {
LOG(("Update Error: cant install version %1 having version %2").arg(versionNum).arg(AppVersion));
ClearAll();
return false;
}
fVersion.close();
}
#ifdef Q_OS_WIN
QString curUpdater = (cExeDir() + u"Updater.exe"_q);
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Updater.exe"_q);
#elif defined Q_OS_MACOS // Q_OS_WIN
QString curUpdater = (cExeDir() + cExeName() + u"/Contents/Frameworks/Updater"_q);
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Telegram.app/Contents/Frameworks/Updater"_q);
#else // Q_OS_MACOS
QString curUpdater = (cExeDir() + u"Updater"_q);
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Updater"_q);
#endif // else for Q_OS_WIN || Q_OS_MACOS
if (!updater.exists()) {
QFileInfo current(curUpdater);
if (!current.exists()) {
ClearAll();
return false;
}
#if !defined Q_OS_WIN && !defined Q_OS_MACOS
if (!KSandbox::isInside()) {
if (!current.isFile() || !current.isExecutable()) {
ClearAll();
return false;
}
return true;
}
#endif // !Q_OS_WIN && !Q_OS_MACOS
if (!QFile(current.absoluteFilePath()).copy(updater.absoluteFilePath())) {
ClearAll();
return false;
}
}
#ifdef Q_OS_WIN
if (CopyFile(updater.absoluteFilePath().toStdWString().c_str(), curUpdater.toStdWString().c_str(), FALSE) == FALSE) {
const auto errorCode = GetLastError();
LOG(("Update Error: could not copy '%1' to '%2', error code: %3"
).arg(updater.absoluteFilePath()).arg(curUpdater).arg(errorCode));
ClearAll();
return false;
}
if (DeleteFile(updater.absoluteFilePath().toStdWString().c_str()) == FALSE) {
ClearAll();
return false;
}
#elif defined Q_OS_MACOS // Q_OS_WIN
QDir().mkpath(QFileInfo(curUpdater).absolutePath());
DEBUG_LOG(("Update Info: moving %1 to %2...").arg(updater.absoluteFilePath()).arg(curUpdater));
if (!objc_moveFile(updater.absoluteFilePath(), curUpdater)) {
ClearAll();
return false;
}
#else // Q_OS_MACOS
if (QFile::exists(curUpdater)
&& unlink(QFile::encodeName(curUpdater).constData())) {
DEBUG_LOG(("Update Error: could not unlink current Updater."));
ClearAll();
return false;
}
if (!linuxMoveFile(QFile::encodeName(updater.absoluteFilePath()).constData(), QFile::encodeName(curUpdater).constData())) {
DEBUG_LOG(("Update Error: could not copy new Updater."));
ClearAll();
return false;
}
#endif // else for Q_OS_WIN || Q_OS_MACOS
#ifdef Q_OS_MACOS
base::Platform::RemoveQuarantine(QFileInfo(curUpdater).absolutePath());
base::Platform::RemoveQuarantine(updater.absolutePath());
#endif // Q_OS_MACOS
return true;
}
#endif // !TDESKTOP_DISABLE_AUTOUPDATE || (!Q_OS_WIN && !Q_OS_MACOS)
#if (defined Q_OS_MACOS || defined Q_OS_WIN) && !defined TDESKTOP_DISABLE_AUTOUPDATE
[[nodiscard]] bool CheckKeptUpdatePackage() {
const auto working = cWorkingDir();
if (!Platform::ReadyUpdatePackagePresent(working)) {
const auto temp = QFileInfo(working + u"tupdates/temp"_q);
const auto legacy = QFileInfo(working + u"tupdates/ready"_q);
if (temp.exists()
|| temp.isSymLink()
|| legacy.exists()
|| legacy.isSymLink()) {
ClearAll(); // an unpacked tree never installs without its package
}
return false;
}
auto error = QString();
const auto mode = Platform::GetUpdateInstallMode(
cExeDir() + cExeName(),
error);
const auto content = (mode != Platform::UpdateInstallMode::Refused)
? Platform::ReadUpdatePackage(
Platform::ReadyUpdatePackagePath(working),
error)
: std::nullopt;
if (!content) {
LOG(("Update Error: %1").arg(error));
ClearAll();
return false;
} else if (!VerifyKeptUpdate(*content, mode, ManifestAdoption::Immediate)) {
ClearAll();
return false;
}
return true;
}
#endif // (Q_OS_MACOS || Q_OS_WIN) && !TDESKTOP_DISABLE_AUTOUPDATE
} // namespace
bool checkReadyUpdate() {
#if defined Q_OS_MACOS || defined Q_OS_WIN
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
return CheckKeptUpdatePackage();
#else // !TDESKTOP_DISABLE_AUTOUPDATE
return false;
#endif // TDESKTOP_DISABLE_AUTOUPDATE
#else // Q_OS_MACOS || Q_OS_WIN
if (!KSandbox::isInside()) {
const auto packagePresent = Platform::ReadyUpdatePackagePresent(
cWorkingDir());
const auto temp = QFileInfo(cWorkingDir() + u"tupdates/temp"_q);
const auto legacy = QFileInfo(cWorkingDir() + u"tupdates/ready"_q);
if (!packagePresent
&& !temp.exists() && !temp.isSymLink()
&& !legacy.exists() && !legacy.isSymLink()) {
return false;
}
auto error = QString();
const auto reject = [&] {
LOG(("Update Error: %1").arg(error));
ClearAll();
return false;
};
const auto mode = Platform::GetUpdateInstallMode(
cExeDir() + cExeName(),
error);
if (mode == Platform::UpdateInstallMode::Refused) {
return reject();
} else if (packagePresent) {
if (!Platform::ClearUpdateData(cWorkingDir(), error, true)) {
return reject();
}
const auto package = Platform::ReadyUpdatePackagePath(cWorkingDir());
const auto content = Platform::ReadUpdatePackage(package, error);
if (!content) {
return reject();
} else if (mode == Platform::UpdateInstallMode::Protected) {
if (!Platform::ValidateProtectedUpdate(
*content,
cInstallBetaVersion(),
error)) {
return reject();
}
return true;
}
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
if (!UnpackUpdateV2(
package,
*content,
ManifestAdoption::Immediate)
|| (Platform::ReadyUpdatePackagePresent(cWorkingDir())
&& !QFile::remove(package))) {
error = u"Could not unpack and retire the ready update package."_q;
return reject();
}
#endif // !TDESKTOP_DISABLE_AUTOUPDATE
} else if (mode == Platform::UpdateInstallMode::Protected) {
error = u"An unpacked update cannot be installed with privilege."_q;
return reject();
}
}
return PromoteReadyUpdater();
#endif // !Q_OS_MACOS && !Q_OS_WIN
}
#if defined Q_OS_MACOS || defined Q_OS_WIN
ReadyUpdateInstall prepareReadyUpdate() {
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
const auto working = cWorkingDir();
const auto package = Platform::ReadyUpdatePackagePath(working);
auto error = QString();
const auto mode = Platform::GetUpdateInstallMode(
cExeDir() + cExeName(),
error);
const auto content = (mode != Platform::UpdateInstallMode::Refused
&& Platform::ReadyUpdatePackagePresent(working))
? Platform::ReadUpdatePackage(package, error)
: std::nullopt;
if (!content) {
LOG(("Update Error: %1").arg(error.isEmpty()
? u"No update package is kept for installation."_q
: error));
ClearAll();
return ReadyUpdateInstall::Failed;
}
#ifdef Q_OS_WIN
if (mode == Platform::UpdateInstallMode::Protected) {
if (!VerifyKeptUpdate(*content, mode, ManifestAdoption::Immediate)) {
ClearAll();
return ReadyUpdateInstall::Failed;
}
return ReadyUpdateInstall::Protected;
}
#endif // Q_OS_WIN
if (!UnpackUpdateV2(package, *content, ManifestAdoption::Immediate)
|| Platform::ReadyUpdatePackagePresent(working)) {
LOG(("Update Error: could not unpack and retire the kept update package."));
ClearAll();
return ReadyUpdateInstall::Failed;
}
return PromoteReadyUpdater()
? ReadyUpdateInstall::Unpacked
: ReadyUpdateInstall::Failed;
#else // !TDESKTOP_DISABLE_AUTOUPDATE
return ReadyUpdateInstall::Failed;
#endif // TDESKTOP_DISABLE_AUTOUPDATE
}
#endif // Q_OS_MACOS || Q_OS_WIN
void UpdateApplication() {
if (UpdaterDisabled()) {
const auto url = [&] {
#ifdef OS_WIN_STORE
return "https://www.microsoft.com/en-us/store/p/telegram-desktop/9nztwsqntd0s";
#elif defined OS_MAC_STORE // OS_WIN_STORE
return "https://itunes.apple.com/ae/app/telegram-desktop/id946399090";
#else // OS_WIN_STORE || OS_MAC_STORE
if (KSandbox::isFlatpak()) {
return "https://flathub.org/apps/details/org.telegram.desktop";
} else if (KSandbox::isSnap()) {
return "https://snapcraft.io/telegram-desktop";
}
return "https://desktop.telegram.org";
#endif // OS_WIN_STORE || OS_MAC_STORE
}();
UrlClickHandler::Open(url);
} else {
cSetAutoUpdate(true);
const auto window = Core::IsAppLaunched()
? Core::App().activePrimaryWindow()
: nullptr;
if (window) {
if (const auto controller = window->sessionController()) {
controller->showSection(
std::make_shared<Info::Memento>(
Info::Settings::Tag{ controller->session().user() },
::Settings::AdvancedId()),
Window::SectionShow());
} else {
window->widget()->showSpecialLayer(
Box<::Settings::LayerWidget>(window),
anim::type::normal);
}
window->widget()->showFromTray();
}
cSetLastUpdateCheck(0);
Core::UpdateChecker().start();
}
}
QString countAlphaVersionSignature(uint64 version) { // duplicated in packer.cpp
if (cAlphaPrivateKey().isEmpty()) {
LOG(("Error: Trying to count alpha version signature without alpha private key!"));
return QString();
}
QByteArray signedData = (qstr("TelegramBeta_") + QString::number(version, 16).toLower()).toUtf8();
static const int32 shaSize = 20, keySize = 128;
uchar sha1Buffer[shaSize];
hashSha1(signedData.constData(), signedData.size(), sha1Buffer); // count sha1
uint32 siglen = 0;
RSA *prKey = [] {
const auto bio = MakeBIO(
const_cast<char*>(cAlphaPrivateKey().constData()),
-1);
return PEM_read_bio_RSAPrivateKey(bio.get(), 0, 0, 0);
}();
if (!prKey) {
LOG(("Error: Could not read alpha private key!"));
return QString();
}
if (RSA_size(prKey) != keySize) {
LOG(("Error: Bad alpha private key size: %1").arg(RSA_size(prKey)));
RSA_free(prKey);
return QString();
}
QByteArray signature;
signature.resize(keySize);
if (RSA_sign(NID_sha1, (const uchar*)(sha1Buffer), shaSize, (uchar*)(signature.data()), &siglen, prKey) != 1) { // count signature
LOG(("Error: Counting alpha version signature failed!"));
RSA_free(prKey);
return QString();
}
RSA_free(prKey);
if (siglen != keySize) {
LOG(("Error: Bad alpha version signature length: %1").arg(siglen));
return QString();
}
signature = signature.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
signature = signature.replace('-', '8').replace('_', 'B');
return QString::fromUtf8(signature.mid(19, 32));
}
} // namespace Core