forked from rainmeter/rainmeter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUpdateCheck.cpp
601 lines (512 loc) · 16.3 KB
/
UpdateCheck.cpp
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
/* Copyright (C) 2017 Rainmeter Project Developers
*
* This Source Code Form is subject to the terms of the GNU General Public
* License; either version 2 of the License, or (at your option) any later
* version. If a copy of the GPL was not distributed with this file, You can
* obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */
#include "StdAfx.h"
#include "../Common/FileUtil.h"
#include "../Common/Platform.h"
#include "../Common/StringUtil.h"
#include "../Common/Version.h"
#include "Rainmeter.h"
#include "System.h"
#include "TrayIcon.h"
#include "UpdateCheck.h"
#include "Util.h"
#include "../Version.h"
#include <sstream>
#include <iomanip>
#include <bcrypt.h>
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0L)
namespace {
// To test a local |status.json| file, set |LOCAL_STATUS_FILE| to your local |status.json| file.
// Example: L"C:\\Rainmeter\\status.json"
// Remember to set this back to an empty string before committing any changes to this file!!
std::wstring LOCAL_STATUS_FILE = L"";
void ShowError(WCHAR* description)
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_INTERNET_EXTENDED_ERROR)
{
WCHAR szBuffer[1024] = { 0 };
DWORD dwError = 0UL, dwLen = _countof(szBuffer);
LPCWSTR error = L"Unknown Error";
if (InternetGetLastResponseInfo(&dwError, szBuffer, &dwLen))
{
error = szBuffer;
dwErr = dwError;
}
LogErrorF(L"(%s) %s (ErrorCode=%i)", description, error, dwErr);
}
else
{
LPVOID lpMsgBuf = nullptr;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK,
GetModuleHandle(L"wininet"),
dwErr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
nullptr);
LPCWSTR error = lpMsgBuf ? (WCHAR*)lpMsgBuf : L"Unknown error";
LogErrorF(L"(%s) %s (ErrorCode=%i)", description, error, dwErr);
if (lpMsgBuf) LocalFree(lpMsgBuf);
}
}
} // namespace
LPCWSTR Updater::s_UpdateURL = L"http://rainmeter.github.io/rainmeter/status.json";
Updater::Updater() :
m_Status(nullptr),
m_DownloadInstaller(true)
{
if (!LOCAL_STATUS_FILE.empty())
{
if (_wcsnicmp(LOCAL_STATUS_FILE.c_str(), L"file://", 7) != 0)
{
LOCAL_STATUS_FILE.insert(0, L"file://");
}
s_UpdateURL = LOCAL_STATUS_FILE.c_str();
}
}
Updater::~Updater()
{
}
Updater& Updater::GetInstance()
{
static Updater s_Updater;
return s_Updater;
}
void Updater::CheckForUpdates(bool download)
{
m_DownloadInstaller = download;
_beginthread(GetStatus, 0, this);
}
void Updater::GetLanguageStatus()
{
const bool debug = GetRainmeter().GetDebug();
if (debug)
{
LogDebug(L"------------------------------");
LogDebug(L"* Checking language status:");
}
if (m_Status.is_null() || m_Status.is_discarded())
{
if (debug)
{
LogError(L">>Status file: Invalid (may not have been downloaded)");
LogDebug(L"------------------------------");
}
return;
}
bool obsolete = false;
const auto lcid = (unsigned)GetRainmeter().GetResourceLCID();
const auto& lang = m_Status["language"];
if (lang.is_null() || lang.empty() ||
!lang.is_structured() || !lang.is_array())
{
if (debug)
{
LogDebug(L">>Status file: Invalid (possibly corrupt?)");
LogDebug(L"------------------------------");
}
return;
}
for (auto& it = lang.cbegin(); it != lang.cend(); ++it)
{
const auto& id = it.value()["id"];
if (id.is_number_unsigned() && id.get<unsigned>() == lcid)
{
if (debug) LogDebugF(L" Language ID found: %u", lcid);
const auto& obs = it.value()["obsolete"];
if (obs.is_boolean())
{
obsolete = obs.get<bool>();
if (debug) LogDebugF(L" Language status: %s", obsolete ? L"Obsolete" : L"Current");
}
break;
}
}
GetRainmeter().SetLanguageStatus(obsolete);
if (debug) LogDebug(L"------------------------------");
}
void Updater::GetStatus(void* pParam)
{
auto updater = (Updater*)pParam;
const bool debug = GetRainmeter().GetDebug();
if (debug)
{
LogDebug(L"------------------------------");
LogDebug(L"* Checking for status updates:");
}
// Download the status file |status.json|
std::string data;
if (!DownloadStatusFile(data) || data.empty())
{
if (debug) ShowError(L">>Status file: Download failed");
return;
}
if (debug) LogDebug(L" Downloading status file: Success!");
json status = json::parse(data, nullptr, false);
if (status.is_null() || status.is_discarded())
{
if (debug) LogError(L">>Status file: Invalid status file");
return;
}
if (debug) LogDebug(L" Parsing status file: Success!");
CheckVersion(status, updater->m_DownloadInstaller);
updater->m_Status = std::move(status);
updater->GetLanguageStatus();
}
bool Updater::DownloadStatusFile(std::string& data)
{
LPCWSTR url = Updater::s_UpdateURL;
if (_wcsnicmp(url, L"file://", 7) == 0) // Local file
{
WCHAR path[MAX_PATH] = { 0 };
DWORD pathLength = _countof(path);
HRESULT hr = PathCreateFromUrl(url, path, &pathLength, 0UL);
if (FAILED(hr))
{
return false;
}
size_t fileSize = 0ULL;
BYTE* buffer = FileUtil::ReadFullFile(path, &fileSize).release();
data = (char*)buffer;
free(buffer);
buffer = nullptr;
return true;
}
HINTERNET hRootHandle = InternetOpen(L"Rainmeter", INTERNET_OPEN_TYPE_PRECONFIG, nullptr, nullptr, 0UL);
if (!hRootHandle) return false;
HINTERNET hUrlDump = InternetOpenUrl(hRootHandle, url, nullptr, 0UL, INTERNET_FLAG_RESYNCHRONIZE, 0UL);
if (!hUrlDump)
{
InternetCloseHandle(hRootHandle);
return false;
}
// The |status.json| file should be UTF-8 (or ANSI) encoded, however, allocate the buffer
// with 3 extra bytes for triple null termination in case the encoding changes.
const DWORD CHUNK_SIZE = 8192UL;
DWORD bufferSize = CHUNK_SIZE;
BYTE* buffer = (BYTE*)malloc(bufferSize + 3UL);
DWORD dataSize = 0UL;
// Read the data.
do
{
DWORD readSize = 0UL;
if (!InternetReadFile(hUrlDump, buffer + dataSize, bufferSize - dataSize, &readSize))
{
free(buffer);
buffer = nullptr;
InternetCloseHandle(hUrlDump);
InternetCloseHandle(hRootHandle);
return false;
}
else if (readSize == 0UL)
{
// All data read.
break;
}
dataSize += readSize;
bufferSize += CHUNK_SIZE;
BYTE* oldBuffer = buffer;
if ((buffer = (BYTE*)realloc(buffer, bufferSize + 3UL)) == nullptr)
{
free(oldBuffer); // In case realloc fails
oldBuffer = nullptr;
InternetCloseHandle(hUrlDump);
InternetCloseHandle(hRootHandle);
return false;
}
} while (true);
InternetCloseHandle(hUrlDump);
InternetCloseHandle(hRootHandle);
// Triple null terminate the buffer.
buffer[dataSize] = 0;
buffer[dataSize + 1] = 0;
buffer[dataSize + 2] = 0;
data = (char*)buffer;
free(buffer);
buffer = nullptr;
return true;
}
void Updater::CheckVersion(json& status, bool downloadNewVersion)
{
const bool debug = GetRainmeter().GetDebug();
std::wstring buffer;
auto getStatusValue = [&buffer](json& key) -> bool
{
buffer.clear();
if (!key.empty())
{
std::string value = key.get<std::string>();
if (!value.empty())
{
buffer = StringUtil::Widen(value);
return true;
}
}
return false;
};
// Get "release version" from the status file
if (!getStatusValue(status["release"]["version"]))
{
if (debug)
{
buffer = StringUtil::Widen(status["release"].dump());
LogErrorF(L">>Status File: Parsing error: release:%s", buffer.c_str());
}
return;
}
VersionHelper::Version availableVersion = { buffer };
if (!availableVersion.IsValid())
{
if (debug) LogErrorF(L">>Status File: Invalid \"version\": %s", buffer.c_str());
return;
}
if (debug) LogDebugF(L" Status file version: %s", buffer.c_str());
// Get "Rainmeter version"
VersionHelper::Version rainmeterVersion = { APPVERSION };
if (!rainmeterVersion.IsValid())
{
if (debug) LogErrorF(L">>Status File: Invalid Rainmeter version: %s", APPVERSION); // Probably never reach this
return;
}
if (availableVersion > rainmeterVersion)
{
const bool isDevBuild = []()
{
if (!LOCAL_STATUS_FILE.empty()) return true;
return RAINMETER_VERSION == 0;
} ();
// Get "minimum Windows version" from the status file
if (!getStatusValue(status["release"]["minimum_windows"]["version"]))
{
if (debug)
{
buffer = StringUtil::Widen(status["release"]["minimum_windows"].dump());
LogErrorF(L">>Status File: Error parsing \"version\": minimum_windows:%s", buffer.c_str());
}
return;
}
VersionHelper::Version statusWinVer = { buffer };
if (!statusWinVer.IsValid())
{
if (debug) LogErrorF(L">>Status File: Invalid \"minimum_windows\" version: %s", buffer.c_str()); // Probably never reach this
return;
}
// Get the user's Windows version
VersionHelper::Version systemWinVer = { GetPlatform().GetRawVersion() };
if (!systemWinVer.IsValid())
{
if (debug) LogErrorF(L">>Status File: Invalid system version: %s", systemWinVer.Get().c_str());
return;
}
// Check if the new Rainmeter version requires a Windows version that is newer than the user's installed version
if (statusWinVer > systemWinVer)
{
if (!getStatusValue(status["release"]["minimum_windows"]["name"]))
{
if (debug)
{
buffer = StringUtil::Widen(status["release"]["minimum_windows"].dump());
LogErrorF(L">>Status File: Error parsing \"name\": minimum_windows:%s", buffer.c_str());
}
buffer = L"Windows build"; // For error message below
}
LogNoticeF(
L"* A new version of Rainmeter is available, however, your system does not meet the minimum required Windows version."
L" Rainmeter %s requires \"%s (%s)\" or higher.",
availableVersion.Get().c_str(),
buffer.c_str(),
statusWinVer.Get().c_str());
return;
}
if (!isDevBuild)
{
LogNotice(L"* New Rainmeter version available!");
GetRainmeter().SetNewVersion();
}
const bool downloadedNewVersion = [&]()
{
if (isDevBuild) return false;
if (downloadNewVersion) return DownloadNewVersion(status);
return false;
} ();
WCHAR tmp[32] = { 0 };
LPCWSTR dataFile = GetRainmeter().GetDataFile().c_str();
GetPrivateProfileString(L"Rainmeter", L"LastCheck", L"0", tmp, _countof(tmp), dataFile);
// Show tray notification only once per new version
VersionHelper::Version lastVersion = { tmp };
if (!lastVersion.IsValid())
{
lastVersion.Set(L"0"); // "LastCheck" probably doesn't exist yet.
}
buffer = availableVersion.Get();
if (availableVersion > lastVersion)
{
WritePrivateProfileString(L"Rainmeter", L"LastCheck", buffer.c_str(), dataFile);
if (!isDevBuild && !downloadedNewVersion)
{
GetRainmeter().GetTrayIcon()->ShowUpdateNotification(buffer.c_str());
}
}
if (!isDevBuild && downloadedNewVersion)
{
GetRainmeter().GetTrayIcon()->ShowInstallUpdateNotification(buffer.c_str());
}
}
}
bool Updater::DownloadNewVersion(json& status)
{
const bool debug = GetRainmeter().GetDebug();
std::string download_url;
if (!status["release"]["download_url"].empty())
{
download_url = status["release"]["download_url"].get<std::string>();
}
if (download_url.empty())
{
if (debug) LogError(L">>Status file: Parsing \"download_url\" failed");
return false;
}
std::string download_sha256;
if (!status["release"]["download_sha256"].empty())
{
download_sha256 = status["release"]["download_sha256"].get<std::string>();
}
if (download_sha256.empty())
{
if (debug) LogError(L">>Status file: Parsing \"download_sha256\" failed");
return false;
}
const std::wstring url = StringUtil::Widen(download_url);
const std::wstring sha = StringUtil::Widen(download_sha256);
std::wstring path = GetRainmeter().GetSettingsPath();
path += L"Updates\\";
std::wstring filename = url;
std::wstring::size_type pos = filename.rfind(L'/');
if (pos == std::wstring::npos)
{
if (debug) LogError(L">>Status file: Invalid \"download_url\"");
return false;
}
filename = filename.substr(pos + 1);
const std::wstring fullPath = path + filename;
if (PathFileExists(fullPath.c_str()))
{
if (VerifyInstaller(path, filename, sha, true))
{
GetRainmeter().SetDownloadedNewVersion();
return true;
}
DeleteFile(fullPath.c_str());
}
CreateDirectory(path.c_str(), nullptr);
// Download the installer
HRESULT resultCoInitialize = CoInitialize(nullptr);
auto cleanup = [&](bool ret) -> bool
{
if (SUCCEEDED(resultCoInitialize))
{
CoUninitialize();
}
return ret;
};
HRESULT result = URLDownloadToFile(nullptr, url.c_str(), fullPath.c_str(), 0UL, nullptr);
if (result != S_OK)
{
LogErrorF(L">>New installer download failed (res=0x%08X, COM=0x%08X): %s",
result, resultCoInitialize, url.c_str());
return cleanup(false);
}
if (VerifyInstaller(path, filename, sha, true))
{
if (debug)
{
LogDebug(L" Downloading new installer: Success!");
LogDebug(L" Verifying installer integrity: Success!");
LogDebugF(L" Installer location: %s", fullPath.c_str());
}
GetRainmeter().SetDownloadedNewVersion();
return cleanup(true);
}
// Installer not verified, remove file and |Updates| folder
DeleteFile(fullPath.c_str());
System::RemoveFolder(path);
return cleanup(false);
}
bool Updater::VerifyInstaller(const std::wstring& path, const std::wstring& filename, const std::wstring& sha256, bool writeToDataFile)
{
const bool debug = GetRainmeter().GetDebug();
const std::wstring fullpath = path + filename;
if (!PathFileExists(fullpath.c_str()))
{
if (debug) LogErrorF(L">>Verify installer: Installer file does not exist");
return false;
}
// Dump installer contents into byte array
size_t fileSize = 0ULL;
BYTE* buffer = FileUtil::ReadFullFile(fullpath, &fileSize).release();
NTSTATUS status = 0L;
BCRYPT_ALG_HANDLE provider = nullptr;
BCRYPT_HASH_HANDLE hashHandle = nullptr;
PBYTE hash = nullptr;
DWORD hashLength = 0UL;
DWORD resultLength = 0UL;
auto cleanup = [&](LPCWSTR func, bool ret) -> bool
{
free(buffer);
buffer = nullptr;
if (!ret && func && debug) LogErrorF(L">>Verify installer error (%s): 0x%08x (%lu)", func, status, status);
if (hash) HeapFree(GetProcessHeap(), 0UL, hash);
if (hashHandle) BCryptDestroyHash(hashHandle);
if (provider) BCryptCloseAlgorithmProvider(provider, 0UL);
return ret;
};
status = BCryptOpenAlgorithmProvider(&provider, BCRYPT_SHA256_ALGORITHM, nullptr, 0UL);
if (!NT_SUCCESS(status)) return cleanup(L"OpenProvider", false);
status = BCryptGetProperty(provider, BCRYPT_HASH_LENGTH, (PBYTE)&hashLength, sizeof(hashLength), &resultLength, 0UL);
if (!NT_SUCCESS(status)) return cleanup(L"GetProperty", false);
hash = (PBYTE)HeapAlloc(GetProcessHeap(), 0UL, hashLength);
if (!hash)
{
status = STATUS_NO_MEMORY;
return cleanup(L"No Memory", false);
}
status = BCryptCreateHash(provider, &hashHandle, nullptr, 0UL, nullptr, 0UL, 0UL);
if (!NT_SUCCESS(status)) return cleanup(L"CreateHash", false);
status = BCryptHashData(hashHandle, buffer, (ULONG)fileSize, 0UL);
if (!NT_SUCCESS(status)) return cleanup(L"HashData", false);
status = BCryptFinishHash(hashHandle, hash, hashLength, 0UL);
if (!NT_SUCCESS(status)) return cleanup(L"FinishHash", false);
// Convert the hash to a hex string
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (DWORD i = 0UL; i < hashLength; ++i)
{
ss << std::setw(2) << static_cast<int>(hash[i]);
}
std::wstring hashStr = StringUtil::Widen(ss.str());
cleanup(nullptr, true);
bool isVerified = _wcsicmp(sha256.c_str(), hashStr.c_str()) == 0;
if (isVerified && writeToDataFile)
{
LPCWSTR dataFile = GetRainmeter().GetDataFile().c_str();
WritePrivateProfileString(L"Rainmeter", L"InstallerName", filename.c_str(), dataFile);
WritePrivateProfileString(L"Rainmeter", L"InstallerSha256", sha256.c_str(), dataFile);
}
if (!isVerified && debug)
{
LogError(L">>Verify installer error: Hashes do not match!");
LogErrorF(L">>>Status file SHA256 hash: %s", sha256.c_str());
LogErrorF(L">>>Installer file SHA256 hash: %s", hashStr.c_str());
}
return isVerified;
}