launcher.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "core/launcher.h"
  8. #include "platform/platform_launcher.h"
  9. #include "platform/platform_specific.h"
  10. #include "base/options.h"
  11. #include "base/platform/base_platform_info.h"
  12. #include "base/platform/base_platform_file_utilities.h"
  13. #include "ui/main_queue_processor.h"
  14. #include "core/crash_reports.h"
  15. #include "core/update_checker.h"
  16. #include "core/sandbox.h"
  17. #include "base/concurrent_timer.h"
  18. #include "base/options.h"
  19. #include <QtCore/QLoggingCategory>
  20. #include <QtCore/QStandardPaths>
  21. namespace Core {
  22. namespace {
  23. uint64 InstallationTag = 0;
  24. base::options::toggle OptionFreeType({
  25. .id = kOptionFreeType,
  26. .name = "FreeType font engine",
  27. .description = "Use the font engine from Linux instead of the system one.",
  28. .scope = base::options::windows | base::options::macos,
  29. .restartRequired = true,
  30. });
  31. class FilteredCommandLineArguments {
  32. public:
  33. FilteredCommandLineArguments(int argc, char **argv);
  34. int &count();
  35. char **values();
  36. private:
  37. static constexpr auto kForwardArgumentCount = 1;
  38. int _count = 0;
  39. std::vector<QByteArray> _owned;
  40. std::vector<char*> _arguments;
  41. void pushArgument(const char *text);
  42. };
  43. FilteredCommandLineArguments::FilteredCommandLineArguments(
  44. int argc,
  45. char **argv) {
  46. // For now just pass only the first argument, the executable path.
  47. for (auto i = 0; i != kForwardArgumentCount; ++i) {
  48. pushArgument(argv[i]);
  49. }
  50. #if defined Q_OS_WIN || defined Q_OS_MAC
  51. if (OptionFreeType.value()) {
  52. pushArgument("-platform");
  53. #ifdef Q_OS_WIN
  54. pushArgument("windows:fontengine=freetype");
  55. #else // Q_OS_WIN
  56. pushArgument("cocoa:fontengine=freetype");
  57. #endif // !Q_OS_WIN
  58. }
  59. #endif // Q_OS_WIN || Q_OS_MAC
  60. pushArgument(nullptr);
  61. }
  62. int &FilteredCommandLineArguments::count() {
  63. _count = _arguments.size() - 1;
  64. return _count;
  65. }
  66. char **FilteredCommandLineArguments::values() {
  67. return _arguments.data();
  68. }
  69. void FilteredCommandLineArguments::pushArgument(const char *text) {
  70. _owned.emplace_back(text);
  71. _arguments.push_back(_owned.back().data());
  72. }
  73. QString DebugModeSettingPath() {
  74. return cWorkingDir() + u"tdata/withdebug"_q;
  75. }
  76. void WriteDebugModeSetting() {
  77. auto file = QFile(DebugModeSettingPath());
  78. if (file.open(QIODevice::WriteOnly)) {
  79. file.write(Logs::DebugEnabled() ? "1" : "0");
  80. }
  81. }
  82. void ComputeDebugMode() {
  83. Logs::SetDebugEnabled(cAlphaVersion() != 0);
  84. const auto debugModeSettingPath = DebugModeSettingPath();
  85. auto file = QFile(debugModeSettingPath);
  86. if (file.exists() && file.open(QIODevice::ReadOnly)) {
  87. Logs::SetDebugEnabled(file.read(1) != "0");
  88. #if defined _DEBUG
  89. } else {
  90. Logs::SetDebugEnabled(true);
  91. #endif
  92. }
  93. if (cDebugMode()) {
  94. Logs::SetDebugEnabled(true);
  95. }
  96. if (Logs::DebugEnabled()) {
  97. QLoggingCategory::setFilterRules("qt.qpa.gl.debug=true");
  98. }
  99. }
  100. void ComputeExternalUpdater() {
  101. auto locations = QStandardPaths::standardLocations(
  102. QStandardPaths::AppDataLocation);
  103. if (locations.isEmpty()) {
  104. locations << QString();
  105. }
  106. locations[0] = QDir::cleanPath(cWorkingDir());
  107. locations << QDir::cleanPath(cExeDir());
  108. for (const auto &location : locations) {
  109. const auto dir = location + u"/externalupdater.d"_q;
  110. for (const auto &info : QDir(dir).entryInfoList(QDir::Files)) {
  111. QFile file(info.absoluteFilePath());
  112. if (file.open(QIODevice::ReadOnly)) {
  113. QTextStream fileStream(&file);
  114. while (!fileStream.atEnd()) {
  115. const auto path = fileStream.readLine();
  116. if (path == (cExeDir() + cExeName())) {
  117. SetUpdaterDisabledAtStartup();
  118. return;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. QString InstallBetaVersionsSettingPath() {
  126. return cWorkingDir() + u"tdata/devversion"_q;
  127. }
  128. void WriteInstallBetaVersionsSetting() {
  129. QFile f(InstallBetaVersionsSettingPath());
  130. if (f.open(QIODevice::WriteOnly)) {
  131. f.write(cInstallBetaVersion() ? "1" : "0");
  132. }
  133. }
  134. void ComputeInstallBetaVersions() {
  135. const auto installBetaSettingPath = InstallBetaVersionsSettingPath();
  136. if (cAlphaVersion()) {
  137. cSetInstallBetaVersion(false);
  138. } else if (QFile::exists(installBetaSettingPath)) {
  139. QFile f(installBetaSettingPath);
  140. if (f.open(QIODevice::ReadOnly)) {
  141. cSetInstallBetaVersion(f.read(1) != "0");
  142. }
  143. } else if (AppBetaVersion) {
  144. WriteInstallBetaVersionsSetting();
  145. }
  146. }
  147. void ComputeInstallationTag() {
  148. InstallationTag = 0;
  149. auto file = QFile(cWorkingDir() + u"tdata/usertag"_q);
  150. if (file.open(QIODevice::ReadOnly)) {
  151. const auto result = file.read(
  152. reinterpret_cast<char*>(&InstallationTag),
  153. sizeof(uint64));
  154. if (result != sizeof(uint64)) {
  155. InstallationTag = 0;
  156. }
  157. file.close();
  158. }
  159. if (!InstallationTag) {
  160. auto generator = std::mt19937(std::random_device()());
  161. auto distribution = std::uniform_int_distribution<uint64>();
  162. do {
  163. InstallationTag = distribution(generator);
  164. } while (!InstallationTag);
  165. if (file.open(QIODevice::WriteOnly)) {
  166. file.write(
  167. reinterpret_cast<char*>(&InstallationTag),
  168. sizeof(uint64));
  169. file.close();
  170. }
  171. }
  172. }
  173. bool MoveLegacyAlphaFolder(const QString &folder, const QString &file) {
  174. const auto was = cExeDir() + folder;
  175. const auto now = cExeDir() + u"TelegramForcePortable"_q;
  176. if (QDir(was).exists() && !QDir(now).exists()) {
  177. const auto oldFile = was + "/tdata/" + file;
  178. const auto newFile = was + "/tdata/alpha";
  179. if (QFile::exists(oldFile) && !QFile::exists(newFile)) {
  180. if (!QFile(oldFile).copy(newFile)) {
  181. LOG(("FATAL: Could not copy '%1' to '%2'").arg(
  182. oldFile,
  183. newFile));
  184. return false;
  185. }
  186. }
  187. if (!QDir().rename(was, now)) {
  188. LOG(("FATAL: Could not rename '%1' to '%2'").arg(was, now));
  189. return false;
  190. }
  191. }
  192. return true;
  193. }
  194. bool MoveLegacyAlphaFolder() {
  195. if (!MoveLegacyAlphaFolder(u"TelegramAlpha_data"_q, u"alpha"_q)
  196. || !MoveLegacyAlphaFolder(u"TelegramBeta_data"_q, u"beta"_q)) {
  197. return false;
  198. }
  199. return true;
  200. }
  201. bool CheckPortableVersionFolder() {
  202. if (!MoveLegacyAlphaFolder()) {
  203. return false;
  204. }
  205. const auto portable = cExeDir() + u"TelegramForcePortable"_q;
  206. QFile key(portable + u"/tdata/alpha"_q);
  207. if (cAlphaVersion()) {
  208. Assert(*AlphaPrivateKey != 0);
  209. cForceWorkingDir(portable);
  210. QDir().mkpath(cWorkingDir() + u"tdata"_q);
  211. cSetAlphaPrivateKey(QByteArray(AlphaPrivateKey));
  212. if (!key.open(QIODevice::WriteOnly)) {
  213. LOG(("FATAL: Could not open '%1' for writing private key!"
  214. ).arg(key.fileName()));
  215. return false;
  216. }
  217. QDataStream dataStream(&key);
  218. dataStream.setVersion(QDataStream::Qt_5_3);
  219. dataStream << quint64(cRealAlphaVersion()) << cAlphaPrivateKey();
  220. return true;
  221. }
  222. if (!QDir(portable).exists()) {
  223. return true;
  224. }
  225. cForceWorkingDir(portable);
  226. if (!key.exists()) {
  227. return true;
  228. }
  229. if (!key.open(QIODevice::ReadOnly)) {
  230. LOG(("FATAL: could not open '%1' for reading private key. "
  231. "Delete it or reinstall private alpha version."
  232. ).arg(key.fileName()));
  233. return false;
  234. }
  235. QDataStream dataStream(&key);
  236. dataStream.setVersion(QDataStream::Qt_5_3);
  237. quint64 v;
  238. QByteArray k;
  239. dataStream >> v >> k;
  240. if (dataStream.status() != QDataStream::Ok || k.isEmpty()) {
  241. LOG(("FATAL: '%1' is corrupted. "
  242. "Delete it or reinstall private alpha version."
  243. ).arg(key.fileName()));
  244. return false;
  245. }
  246. cSetAlphaVersion(AppVersion * 1000ULL);
  247. cSetAlphaPrivateKey(k);
  248. cSetRealAlphaVersion(v);
  249. return true;
  250. }
  251. base::options::toggle OptionFractionalScalingEnabled({
  252. .id = kOptionFractionalScalingEnabled,
  253. .name = "Enable precise High DPI scaling",
  254. .description = "Follow system interface scale settings exactly.",
  255. .scope = base::options::windows | base::options::linux,
  256. .restartRequired = true,
  257. });
  258. } // namespace
  259. const char kOptionFractionalScalingEnabled[] = "fractional-scaling-enabled";
  260. const char kOptionFreeType[] = "freetype";
  261. Launcher *Launcher::InstanceSetter::Instance = nullptr;
  262. std::unique_ptr<Launcher> Launcher::Create(int argc, char *argv[]) {
  263. return std::make_unique<Platform::Launcher>(argc, argv);
  264. }
  265. Launcher::Launcher(int argc, char *argv[])
  266. : _argc(argc)
  267. , _argv(argv)
  268. , _arguments(readArguments(_argc, _argv))
  269. , _baseIntegration(_argc, _argv)
  270. , _initialWorkingDir(QDir::currentPath() + '/') {
  271. crl::toggle_fp_exceptions(true);
  272. base::Integration::Set(&_baseIntegration);
  273. }
  274. Launcher::~Launcher() {
  275. InstanceSetter::Instance = nullptr;
  276. }
  277. void Launcher::init() {
  278. prepareSettings();
  279. initQtMessageLogging();
  280. QApplication::setApplicationName(u"TelegramDesktop"_q);
  281. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  282. // fallback session management is useless for tdesktop since it doesn't have
  283. // any "are you sure you want to close this window?" dialogs
  284. // but it produces bugs like https://github.com/telegramdesktop/tdesktop/issues/5022
  285. // and https://github.com/telegramdesktop/tdesktop/issues/7549
  286. // and https://github.com/telegramdesktop/tdesktop/issues/948
  287. // more info: https://doc.qt.io/qt-5/qguiapplication.html#isFallbackSessionManagementEnabled
  288. QApplication::setFallbackSessionManagementEnabled(false);
  289. #endif // Qt < 6.0.0
  290. initHook();
  291. }
  292. void Launcher::initHighDpi() {
  293. #if QT_VERSION < QT_VERSION_CHECK(6, 2, 0)
  294. qputenv("QT_DPI_ADJUSTMENT_POLICY", "AdjustDpi");
  295. #endif // Qt < 6.2.0
  296. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  297. QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
  298. #endif // Qt < 6.0.0
  299. if (OptionFractionalScalingEnabled.value()) {
  300. QApplication::setHighDpiScaleFactorRoundingPolicy(
  301. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  302. } else {
  303. QApplication::setHighDpiScaleFactorRoundingPolicy(
  304. Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor);
  305. }
  306. }
  307. int Launcher::exec() {
  308. init();
  309. if (cLaunchMode() == LaunchModeFixPrevious) {
  310. return psFixPrevious();
  311. } else if (cLaunchMode() == LaunchModeCleanup) {
  312. return psCleanup();
  313. }
  314. // Must be started before Platform is started.
  315. Logs::start();
  316. base::options::init(cWorkingDir() + "tdata/experimental_options.json");
  317. // Must be called after options are inited.
  318. initHighDpi();
  319. if (Logs::DebugEnabled()) {
  320. const auto openalLogPath = QDir::toNativeSeparators(
  321. cWorkingDir() + u"DebugLogs/last_openal_log.txt"_q);
  322. qputenv("ALSOFT_LOGLEVEL", "3");
  323. #ifdef Q_OS_WIN
  324. _wputenv_s(
  325. L"ALSOFT_LOGFILE",
  326. openalLogPath.toStdWString().c_str());
  327. #else // Q_OS_WIN
  328. qputenv(
  329. "ALSOFT_LOGFILE",
  330. QFile::encodeName(openalLogPath));
  331. #endif // !Q_OS_WIN
  332. }
  333. // Must be started before Sandbox is created.
  334. Platform::start();
  335. ThirdParty::start();
  336. auto result = executeApplication();
  337. DEBUG_LOG(("Telegram finished, result: %1").arg(result));
  338. if (!UpdaterDisabled() && cRestartingUpdate()) {
  339. DEBUG_LOG(("Sandbox Info: executing updater to install update."));
  340. if (!launchUpdater(UpdaterLaunch::PerformUpdate)) {
  341. base::Platform::DeleteDirectory(cWorkingDir() + u"tupdates/temp"_q);
  342. }
  343. } else if (cRestarting()) {
  344. DEBUG_LOG(("Sandbox Info: executing Telegram because of restart."));
  345. launchUpdater(UpdaterLaunch::JustRelaunch);
  346. }
  347. CrashReports::Finish();
  348. ThirdParty::finish();
  349. Platform::finish();
  350. Logs::finish();
  351. return result;
  352. }
  353. bool Launcher::validateCustomWorkingDir() {
  354. if (customWorkingDir()) {
  355. if (_customWorkingDir == cWorkingDir()) {
  356. _customWorkingDir = QString();
  357. return false;
  358. }
  359. cForceWorkingDir(_customWorkingDir);
  360. return true;
  361. }
  362. return false;
  363. }
  364. void Launcher::workingFolderReady() {
  365. srand((unsigned int)time(nullptr));
  366. ComputeDebugMode();
  367. ComputeExternalUpdater();
  368. ComputeInstallBetaVersions();
  369. ComputeInstallationTag();
  370. }
  371. void Launcher::writeDebugModeSetting() {
  372. WriteDebugModeSetting();
  373. }
  374. void Launcher::writeInstallBetaVersionsSetting() {
  375. WriteInstallBetaVersionsSetting();
  376. }
  377. bool Launcher::checkPortableVersionFolder() {
  378. return CheckPortableVersionFolder();
  379. }
  380. QStringList Launcher::readArguments(int argc, char *argv[]) const {
  381. Expects(argc >= 0);
  382. if (const auto native = readArgumentsHook(argc, argv)) {
  383. return *native;
  384. }
  385. auto result = QStringList();
  386. result.reserve(argc);
  387. for (auto i = 0; i != argc; ++i) {
  388. result.push_back(base::FromUtf8Safe(argv[i]));
  389. }
  390. return result;
  391. }
  392. const QStringList &Launcher::arguments() const {
  393. return _arguments;
  394. }
  395. QString Launcher::initialWorkingDir() const {
  396. return _initialWorkingDir;
  397. }
  398. bool Launcher::customWorkingDir() const {
  399. return !_customWorkingDir.isEmpty();
  400. }
  401. void Launcher::prepareSettings() {
  402. auto path = base::Platform::CurrentExecutablePath(_argc, _argv);
  403. LOG(("Executable path before check: %1").arg(path));
  404. if (cExeName().isEmpty()) {
  405. LOG(("WARNING: Could not compute executable path, some features will be disabled."));
  406. }
  407. processArguments();
  408. }
  409. void Launcher::initQtMessageLogging() {
  410. static QtMessageHandler OriginalMessageHandler = nullptr;
  411. OriginalMessageHandler = qInstallMessageHandler([](
  412. QtMsgType type,
  413. const QMessageLogContext &context,
  414. const QString &msg) {
  415. if (OriginalMessageHandler) {
  416. OriginalMessageHandler(type, context, msg);
  417. }
  418. if (Logs::DebugEnabled() || !Logs::started()) {
  419. if (!Logs::WritingEntry()) {
  420. // Sometimes Qt logs something inside our own logging.
  421. LOG((msg));
  422. }
  423. }
  424. });
  425. }
  426. uint64 Launcher::installationTag() const {
  427. return InstallationTag;
  428. }
  429. QByteArray Launcher::instanceHash() const {
  430. static const auto Result = [&] {
  431. QByteArray h(32, 0);
  432. if (customWorkingDir()) {
  433. const auto d = QFile::encodeName(
  434. QDir(cWorkingDir()).absolutePath());
  435. hashMd5Hex(d.constData(), d.size(), h.data());
  436. } else {
  437. const auto f = QFile::encodeName(cExeDir() + cExeName());
  438. hashMd5Hex(f.constData(), f.size(), h.data());
  439. }
  440. return h;
  441. }();
  442. return Result;
  443. }
  444. void Launcher::processArguments() {
  445. enum class KeyFormat {
  446. NoValues,
  447. OneValue,
  448. AllLeftValues,
  449. };
  450. auto parseMap = std::map<QByteArray, KeyFormat> {
  451. { "-debug" , KeyFormat::NoValues },
  452. { "-key" , KeyFormat::OneValue },
  453. { "-autostart" , KeyFormat::NoValues },
  454. { "-fixprevious" , KeyFormat::NoValues },
  455. { "-cleanup" , KeyFormat::NoValues },
  456. { "-noupdate" , KeyFormat::NoValues },
  457. { "-tosettings" , KeyFormat::NoValues },
  458. { "-startintray" , KeyFormat::NoValues },
  459. { "-quit" , KeyFormat::NoValues },
  460. { "-sendpath" , KeyFormat::AllLeftValues },
  461. { "-workdir" , KeyFormat::OneValue },
  462. { "--" , KeyFormat::OneValue },
  463. { "-scale" , KeyFormat::OneValue },
  464. };
  465. auto parseResult = QMap<QByteArray, QStringList>();
  466. auto parsingKey = QByteArray();
  467. auto parsingFormat = KeyFormat::NoValues;
  468. for (const auto &argument : std::as_const(_arguments)) {
  469. switch (parsingFormat) {
  470. case KeyFormat::OneValue: {
  471. parseResult[parsingKey] = QStringList(argument.mid(0, 8192));
  472. parsingFormat = KeyFormat::NoValues;
  473. } break;
  474. case KeyFormat::AllLeftValues: {
  475. parseResult[parsingKey].push_back(argument.mid(0, 8192));
  476. } break;
  477. case KeyFormat::NoValues: {
  478. parsingKey = argument.toLatin1();
  479. auto it = parseMap.find(parsingKey);
  480. if (it != parseMap.end()) {
  481. parsingFormat = it->second;
  482. parseResult[parsingKey] = QStringList();
  483. }
  484. } break;
  485. }
  486. }
  487. static const auto RegExp = QRegularExpression("[^a-z0-9\\-_]");
  488. gDebugMode = parseResult.contains("-debug");
  489. gKeyFile = parseResult
  490. .value("-key", {})
  491. .join(QString())
  492. .toLower()
  493. .replace(RegExp, {});
  494. gLaunchMode = parseResult.contains("-autostart") ? LaunchModeAutoStart
  495. : parseResult.contains("-fixprevious") ? LaunchModeFixPrevious
  496. : parseResult.contains("-cleanup") ? LaunchModeCleanup
  497. : LaunchModeNormal;
  498. gNoStartUpdate = parseResult.contains("-noupdate");
  499. gStartToSettings = parseResult.contains("-tosettings");
  500. gStartInTray = parseResult.contains("-startintray");
  501. gQuit = parseResult.contains("-quit");
  502. gSendPaths = parseResult.value("-sendpath", {});
  503. _customWorkingDir = parseResult.value("-workdir", {}).join(QString());
  504. if (!_customWorkingDir.isEmpty()) {
  505. _customWorkingDir = QDir(_customWorkingDir).absolutePath() + '/';
  506. }
  507. gStartUrl = parseResult.value("--", {}).join(QString());
  508. const auto scaleKey = parseResult.value("-scale", {});
  509. if (scaleKey.size() > 0) {
  510. using namespace style;
  511. const auto value = scaleKey[0].toInt();
  512. gConfigScale = ((value < kScaleMin) || (value > kScaleMax))
  513. ? kScaleAuto
  514. : value;
  515. }
  516. }
  517. int Launcher::executeApplication() {
  518. FilteredCommandLineArguments arguments(_argc, _argv);
  519. Sandbox sandbox(arguments.count(), arguments.values());
  520. Ui::MainQueueProcessor processor;
  521. base::ConcurrentTimerEnvironment environment;
  522. return sandbox.start();
  523. }
  524. } // namespace Core