1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
|
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#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 "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/settings_advanced.h"
#include "settings/settings_intro.h"
#include "ui/layers/box_content.h"
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <ksandbox.h>
extern "C" {
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/err.h>
} // extern "C"
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
#if defined Q_OS_WIN && !defined DESKTOP_APP_USE_PACKAGED // use Lzma SDK for win
#include <LzmaLib.h>
#else // Q_OS_WIN && !DESKTOP_APP_USE_PACKAGED
#include <lzma.h>
#endif // else of Q_OS_WIN && !DESKTOP_APP_USE_PACKAGED
#endif // !TDESKTOP_DISABLE_AUTOUPDATE
#ifdef Q_OS_UNIX
#include <unistd.h>
#endif // Q_OS_UNIX
namespace Core {
namespace {
constexpr auto kUpdaterTimeout = 10 * crl::time(1000);
constexpr auto kMaxResponseSize = 1024 * 1024;
#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;
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;
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:
void gotResponse();
void gotFailure(QNetworkReply::NetworkError e);
void clearSentRequest();
bool handleResponse(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;
QNetworkReply *_reply = nullptr;
};
class HttpLoaderActor;
class HttpLoader : public Loader {
public:
HttpLoader(const QString &url);
~HttpLoader();
private:
void startLoading() override;
friend class HttpLoaderActor;
QString _url;
std::unique_ptr<QThread> _thread;
HttpLoaderActor *_actor = nullptr;
};
class HttpLoaderActor : public QObject {
public:
HttpLoaderActor(
not_null<HttpLoader*> parent,
not_null<QThread*> thread,
const QString &url);
private:
void start();
void sendRequest();
void gotMetaData();
void partFinished(qint64 got, qint64 total);
void partFailed(QNetworkReply::NetworkError e);
not_null<HttpLoader*> _parent;
QString _url;
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;
MTP::WeakInstance _mtp;
};
std::shared_ptr<Updater> GetUpdaterInstance() {
if (const auto result = UpdaterInstance.lock()) {
return result;
}
const auto result = std::make_shared<Updater>();
UpdaterInstance = result;
return result;
}
QString UpdatesFolder() {
return cWorkingDir() + u"tupdates"_q;
}
void ClearAll() {
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) {
if (QRegularExpression(
"^("
"tupdate|"
"tx64upd|"
"tmacupd|"
"tarmacupd|"
"tlinuxupd|"
")\\d+(_[a-z\\d]+)?$",
QRegularExpression::CaseInsensitiveOption
).match(info.fileName()).hasMatch()) {
return info.absoluteFilePath();
}
}
return QString();
}
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();
}
bool UnpackUpdate(const QString &filepath) {
#ifndef TDESKTOP_DISABLE_AUTOUPDATE
QFile input(filepath);
if (!input.open(QIODevice::ReadOnly)) {
LOG(("Update Error: cant read updates file!"));
return false;
}
#if defined Q_OS_WIN && !defined DESKTOP_APP_USE_PACKAGED // use Lzma SDK for win
const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else // Q_OS_WIN && !DESKTOP_APP_USE_PACKAGED
const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif // Q_OS_WIN && !DESKTOP_APP_USE_PACKAGED
QByteArray compressed = input.readAll();
int32 compressedLen = compressed.size() - hSize;
if (compressedLen <= 0) {
LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
return false;
}
input.close();
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;
}
uchar sha1Buffer[20];
bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, 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);
QByteArray uncompressed;
int32 uncompressedLen;
memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
uncompressed.resize(uncompressedLen);
size_t resultLen = uncompressed.size();
#if defined Q_OS_WIN && !defined DESKTOP_APP_USE_PACKAGED // use Lzma SDK for win
SizeT srcLen = compressedLen;
int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
if (uncompressRes != SZ_OK) {
LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
return false;
}
#else // Q_OS_WIN && !DESKTOP_APP_USE_PACKAGED
lzma_stream stream = LZMA_STREAM_INIT;
lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
if (ret != LZMA_OK) {
const char *msg;
switch (ret) {
case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
default: msg = "Unknown error, possibly a bug"; break;
}
LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
return false;
}
stream.avail_in = compressedLen;
stream.next_in = (uint8_t*)(compressed.constData() + hSize);
stream.avail_out = resultLen;
stream.next_out = (uint8_t*)uncompressed.data();
lzma_ret res = lzma_code(&stream, LZMA_FINISH);
if (stream.avail_in) {
LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
return false;
} else if (stream.avail_out) {
LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen));
return false;
}
lzma_end(&stream);
if (res != LZMA_OK && res != LZMA_STREAM_END) {
const char *msg;
switch (res) {
case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
default: msg = "Unknown error, possibly a bug"; break;
}
LOG(("Error in decompression: %1 (error code %2)").arg(msg).arg(res));
return false;
}
#endif // Q_OS_WIN && !DESKTOP_APP_USE_PACKAGED
tempDir.mkdir(tempDir.absolutePath());
quint32 version;
{
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;
}
quint64 alphaVersion = 0;
if (version == 0x7FFFFFFF) { // alpha version
stream >> alphaVersion;
if (stream.status() != QDataStream::Ok) {
LOG(("Update Error: cant read alpha version from downloaded stream, status: %1").arg(stream.status()));
return false;
}
if (!cAlphaVersion() || alphaVersion <= cAlphaVersion()) {
LOG(("Update Error: downloaded alpha version %1 is not greater, than mine %2").arg(alphaVersion).arg(cAlphaVersion()));
return false;
}
} else if (int32(version) <= AppVersion) {
LOG(("Update Error: downloaded version %1 is not greater, than mine %2").arg(version).arg(AppVersion));
return false;
}
quint32 filesCount;
stream >> filesCount;
if (stream.status() != QDataStream::Ok) {
LOG(("Update Error: cant read files count from downloaded stream, status: %1").arg(stream.status()));
return false;
}
if (!filesCount) {
LOG(("Update Error: update is empty!"));
return false;
}
for (uint32 i = 0; i < filesCount; ++i) {
QString relativeName;
quint32 fileSize;
QByteArray fileInnerData;
bool executable = false;
stream >> relativeName >> fileSize >> fileInnerData;
#ifdef Q_OS_UNIX
stream >> executable;
#endif // Q_OS_UNIX
if (stream.status() != QDataStream::Ok) {
LOG(("Update Error: cant read file from downloaded stream, status: %1").arg(stream.status()));
return false;
}
if (fileSize != quint32(fileInnerData.size())) {
LOG(("Update Error: bad file size %1 not matching data size %2").arg(fileSize).arg(fileInnerData.size()));
return false;
}
QFile f(tempDirPath + '/' + relativeName);
if (!QDir().mkpath(QFileInfo(f).absolutePath())) {
LOG(("Update Error: cant mkpath for file '%1'").arg(tempDirPath + '/' + relativeName));
return false;
}
if (!f.open(QIODevice::WriteOnly)) {
LOG(("Update Error: cant open file '%1' for writing").arg(tempDirPath + '/' + relativeName));
return false;
}
auto writtenBytes = f.write(fileInnerData);
if (writtenBytes != fileSize) {
f.close();
LOG(("Update Error: cant write file '%1', desiredSize: %2, write result: %3").arg(tempDirPath + '/' + relativeName).arg(fileSize).arg(writtenBytes));
return false;
}
f.close();
if (executable) {
QFileDevice::Permissions p = f.permissions();
p |= QFileDevice::ExeOwner | QFileDevice::ExeUser | QFileDevice::ExeGroup | QFileDevice::ExeOther;
f.setPermissions(p);
}
}
// create tdata/version file
tempDir.mkdir(QDir(tempDirPath + u"/tdata"_q).absolutePath());
std::wstring versionString = FormatVersionDisplay(version).toStdWString();
const auto versionNum = VersionInt(version);
const auto versionLen = VersionInt(versionString.size() * sizeof(VersionChar));
VersionChar versionStr[32];
memcpy(versionStr, versionString.c_str(), versionLen);
QFile fVersion(tempDirPath + u"/tdata/version"_q);
if (!fVersion.open(QIODevice::WriteOnly)) {
LOG(("Update Error: cant write version file '%1'").arg(tempDirPath + u"/version"_q));
return false;
}
fVersion.write((const char*)&versionNum, sizeof(VersionInt));
if (versionNum == 0x7FFFFFFF) { // alpha version
fVersion.write((const char*)&alphaVersion, sizeof(quint64));
} else {
fVersion.write((const char*)&versionLen, sizeof(VersionInt));
fVersion.write((const char*)&versionStr[0], versionLen);
}
fVersion.close();
}
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;
}
input.remove();
return true;
#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::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) {
}
void HttpChecker::start() {
const auto updaterVersion = Platform::AutoUpdateVersion();
const auto path = Local::readAutoupdatePrefix()
+ qstr("/current")
+ (updaterVersion > 1 ? QString::number(updaterVersion) : QString());
auto url = QUrl(path);
DEBUG_LOG(("Update Info: requesting update state"));
const auto request = QNetworkRequest(url);
_manager = std::make_unique<QNetworkAccessManager>();
_reply = _manager->get(request);
_reply->connect(_reply, &QNetworkReply::finished, [=] {
gotResponse();
});
_reply->connect(_reply, &QNetworkReply::errorOccurred, [=](auto e) {
gotFailure(e);
});
}
void HttpChecker::gotResponse() {
if (!_reply) {
return;
}
cSetLastUpdateCheck(base::unixtime::now());
const auto response = _reply->readAll();
clearSentRequest();
if (response.size() >= kMaxResponseSize || !handleResponse(response)) {
LOG(("Update Error: Bad update map size: %1").arg(response.size()));
gotFailure(QNetworkReply::UnknownContentError);
}
}
bool HttpChecker::handleResponse(const QByteArray &response) {
const auto handle = [&](const QString &url) {
done(url.isEmpty() ? nullptr : std::make_shared<HttpLoader>(url));
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() {
const auto reply = base::take(_reply);
if (!reply) {
return;
}
reply->disconnect(reply, &QNetworkReply::finished, nullptr, nullptr);
reply->disconnect(reply, &QNetworkReply::errorOccurred, nullptr, nullptr);
reply->abort();
reply->deleteLater();
_manager = nullptr;
}
void HttpChecker::gotFailure(QNetworkReply::NetworkError e) {
LOG(("Update Error: "
"could not get current version %1").arg(e));
if (const auto reply = base::take(_reply)) {
reply->deleteLater();
}
fail();
}
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)
: Loader(UpdatesFolder() + '/' + ExtractFilename(url), kChunkSize)
, _url(url) {
}
void HttpLoader::startLoading() {
LOG(("Update Info: Loading using HTTP from '%1'.").arg(_url));
_thread = std::make_unique<QThread>();
_actor = new HttpLoaderActor(this, _thread.get(), _url);
_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 QString &url)
: _parent(parent) {
_url = url;
moveToThread(thread);
_manager.moveToThread(thread);
connect(thread, &QThread::started, this, [=] { start(); });
}
void HttpLoaderActor::start() {
sendRequest();
}
void HttpLoaderActor::sendRequest() {
auto request = QNetworkRequest(_url);
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).toInt());
}
}
}
}
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));
_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));
_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;
}
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;
}
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();
};
}
} // namespace
bool UpdaterDisabled() {
return UpdaterIsDisabled;
}
void SetUpdaterDisabledAtStartup() {
Expects(UpdaterInstance.lock() == nullptr);
UpdaterIsDisabled = 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;
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 handleChecking();
void handleProgress();
void handleLatest();
void handleFailed();
void handleReady();
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;
std::shared_ptr<Loader> _activeLoader;
bool _usingMtprotoLoader = (cAlphaVersion() != 0);
base::weak_ptr<Main::Session> _session;
rpl::lifetime _lifetime;
};
Updater::Updater()
: _timer([=] { check(); })
, _retryTimer([=] { handleTimeout(); }) {
checking() | rpl::start_with_next([=] {
handleChecking();
}, _lifetime);
progress() | rpl::start_with_next([=] {
handleProgress();
}, _lifetime);
failed() | rpl::start_with_next([=] {
handleFailed();
}, _lifetime);
ready() | rpl::start_with_next([=] {
handleReady();
}, _lifetime);
isLatest() | rpl::start_with_next([=] {
handleLatest();
}, _lifetime);
}
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::handleReady() {
stop();
_action = Action::Ready;
if (!Quitting()) {
cSetLastUpdateCheck(base::unixtime::now());
Local::writeSettings();
}
}
void Updater::handleFailed() {
scheduleNext();
}
void Updater::handleLatest() {
if (const auto update = FindUpdateFile(); !update.isEmpty()) {
QFile(update).remove();
}
scheduleNext();
}
void Updater::handleChecking() {
_action = Action::Checking;
_retryTimer.callOnce(kUpdaterTimeout);
}
void Updater::handleProgress() {
_retryTimer.callOnce(kUpdaterTimeout);
}
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;
}
void Updater::stop() {
_httpImplementation = Implementation();
_mtpImplementation = Implementation();
_activeLoader = nullptr;
_action = Action::Waiting;
}
void Updater::start(bool forceWait) {
if (cExeName().isEmpty()) {
return;
}
_timer.cancel();
if (!cAutoUpdate() || _action != Action::Waiting) {
return;
}
_retryTimer.cancel();
const auto constDelay = cAlphaVersion() ? 600 : UpdateDelayConstPart;
const auto randDelay = cAlphaVersion() ? 300 : 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 (sendRequest) {
startImplementation(
&_httpImplementation,
std::make_unique<HttpChecker>(_testing));
startImplementation(
&_mtpImplementation,
std::make_unique<MtpChecker>(_session, _testing));
_checking.fire({});
} 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::start_with_next([=](std::shared_ptr<Loader> &&loader) {
checkerDone(which, std::move(loader));
}, checker->lifetime());
checker->failed(
) | rpl::start_with_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) {
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() {
if (_action == Action::Checking) {
const auto reset = [&](Implementation &which) {
if (base::take(which.checker)) {
which.failed = true;
}
};
reset(_httpImplementation);
reset(_mtpImplementation);
if (!tryLoaders()) {
cSetLastUpdateCheck(0);
_timer.callOnce(kUpdaterTimeout);
}
} else if (_action == Action::Loading) {
_failed.fire({});
}
}
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::start_to_stream(_progress, loader->lifetime());
loader->ready(
) | rpl::start_with_next([=](QString &&filepath) {
finalize(std::move(filepath));
}, loader->lifetime());
loader->failed(
) | rpl::start_with_next([=] {
_failed.fire({});
}, loader->lifetime());
_retryTimer.callOnce(kUpdaterTimeout);
loader->wipeFolder();
loader->start();
} else {
_isLatest.fire({});
}
};
if (_mtpImplementation.failed && _httpImplementation.failed) {
_failed.fire({});
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) {
_ready.fire({});
} else {
ClearAll();
_failed.fire({});
}
}
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();
}
//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);
//}
bool checkReadyUpdate() {
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
quint64 alphaVersion = 0;
if (fVersion.read((char*)&alphaVersion, sizeof(quint64)) != sizeof(quint64)) {
LOG(("Update Error: cant read alpha version from file '%1'").arg(versionPath));
ClearAll();
return false;
}
if (!cAlphaVersion() || alphaVersion <= cAlphaVersion()) {
LOG(("Update Error: cant install alpha version %1 having alpha version %2").arg(alphaVersion).arg(cAlphaVersion()));
ClearAll();
return false;
}
} else if (versionNum <= AppVersion) {
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_MAC // Q_OS_WIN
QString curUpdater = (cExeDir() + cExeName() + u"/Contents/Frameworks/Updater"_q);
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Telegram.app/Contents/Frameworks/Updater"_q);
#elif defined Q_OS_UNIX // Q_OS_MAC
QString curUpdater = (cExeDir() + u"Updater"_q);
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Updater"_q);
#endif // Q_OS_UNIX
if (!updater.exists()) {
QFileInfo current(curUpdater);
if (!current.exists()) {
ClearAll();
return false;
}
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) {
DWORD errorCode = GetLastError();
if (errorCode == ERROR_ACCESS_DENIED) { // we are in write-protected dir, like Program Files
cSetWriteProtected(true);
return true;
} else {
ClearAll();
return false;
}
}
if (DeleteFile(updater.absoluteFilePath().toStdWString().c_str()) == FALSE) {
ClearAll();
return false;
}
#elif defined Q_OS_MAC // 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;
}
#elif defined Q_OS_UNIX // Q_OS_MAC
// if the files in the directory are owned by user, while the directory is not,
// update will still fail since it's not possible to remove files
if (QFile::exists(curUpdater)
&& unlink(QFile::encodeName(curUpdater).constData())) {
if (errno == EACCES) {
DEBUG_LOG(("Update Info: "
"could not unlink current Updater, access denied."));
cSetWriteProtected(true);
return true;
} else {
DEBUG_LOG(("Update Error: could not unlink current Updater."));
ClearAll();
return false;
}
}
if (!linuxMoveFile(QFile::encodeName(updater.absoluteFilePath()).constData(), QFile::encodeName(curUpdater).constData())) {
if (errno == EACCES) {
DEBUG_LOG(("Update Info: "
"could not copy new Updater, access denied."));
cSetWriteProtected(true);
return true;
} else {
DEBUG_LOG(("Update Error: could not copy new Updater."));
ClearAll();
return false;
}
}
#endif // Q_OS_UNIX
#ifdef Q_OS_MAC
base::Platform::RemoveQuarantine(QFileInfo(curUpdater).absolutePath());
base::Platform::RemoveQuarantine(updater.absolutePath());
#endif // Q_OS_MAC
return true;
}
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::Advanced::Id()),
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
|