ZaStoGram_desktop/Telegram/SourceFiles/_other/updater_win.cpp

949 lines
29 KiB
C++

/*
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 "updater.h"
#include "base/platform/win/base_windows_safe_library.h"
#include <exdisp.h>
#include <servprov.h>
#include <shldisp.h>
#include <limits>
#include <memory>
#ifdef ShellExecute
#undef ShellExecute // shellapi.h would rename the IShellDispatch2 method
#endif // ShellExecute
bool _debug = false;
wstring updaterName, updaterDir, updateTo, exeName, customWorkingDir, customKeyFile;
bool equal(const wstring &a, const wstring &b) {
return !_wcsicmp(a.c_str(), b.c_str());
}
wstring FormatUpdateError(const wstring &message, DWORD errorCode) {
auto errorText = LPWSTR(nullptr);
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&errorText),
0,
nullptr);
const auto guard = std::unique_ptr<void, decltype(&LocalFree)>(
errorText,
&LocalFree);
return message + L"\nError code: " + std::to_wstring(errorCode)
+ L"\nError message: " + (errorText ? errorText : L"(Unknown error)");
}
void updateError(const WCHAR *msg, DWORD errorCode) {
const auto text = FormatUpdateError(msg, errorCode);
MessageBox(0, text.c_str(), L"Update error!", MB_ICONERROR);
}
HANDLE _logFile = 0;
void openLog() {
if (!_debug || _logFile) return;
wstring logPath = L"DebugLogs";
if (!CreateDirectory(logPath.c_str(), NULL)) {
DWORD errorCode = GetLastError();
if (errorCode && errorCode != ERROR_ALREADY_EXISTS) {
updateError(L"Failed to create log directory", errorCode);
return;
}
}
SYSTEMTIME stLocalTime;
GetLocalTime(&stLocalTime);
static const int maxFileLen = MAX_PATH * 10;
WCHAR logName[maxFileLen];
wsprintf(logName, L"DebugLogs\\%04d%02d%02d_%02d%02d%02d_upd.txt",
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond);
_logFile = CreateFile(logName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (_logFile == INVALID_HANDLE_VALUE) { // :(
updateError(L"Failed to create log file", GetLastError());
_logFile = 0;
return;
}
}
void closeLog() {
if (!_logFile) return;
CloseHandle(_logFile);
_logFile = 0;
}
void writeLog(const wstring &msg) {
if (!_logFile) return;
wstring full = msg + L'\n';
DWORD written = 0;
BOOL result = WriteFile(_logFile, full.c_str(), full.size() * sizeof(wchar_t), &written, 0);
if (!result) {
updateError((L"Failed to write log entry '" + msg + L"'").c_str(), GetLastError());
closeLog();
return;
}
BOOL flushr = FlushFileBuffers(_logFile);
if (!flushr) {
updateError((L"Failed to flush log on entry '" + msg + L"'").c_str(), GetLastError());
closeLog();
return;
}
}
namespace {
constexpr auto kProcessExitTimeout = DWORD(5000);
bool ParsePositiveInteger(const WCHAR *text, ULONGLONG &result) {
result = 0;
for (; *text; ++text) {
if (*text < L'0' || *text > L'9') {
return false;
}
const auto digit = ULONGLONG(*text - L'0');
if (result > (std::numeric_limits<ULONGLONG>::max() - digit) / 10) {
return false;
}
result = result * 10 + digit;
}
return result != 0;
}
} // namespace
bool ParseUpdateProcess(
const WCHAR *id,
const WCHAR *created,
DWORD &processId,
ULONGLONG &creationTime) {
auto parsedId = ULONGLONG(0);
auto parsedTime = ULONGLONG(0);
if (!ParsePositiveInteger(id, parsedId)
|| parsedId > std::numeric_limits<DWORD>::max()
|| !ParsePositiveInteger(created, parsedTime)) {
return false;
}
processId = DWORD(parsedId);
creationTime = parsedTime;
return true;
}
DWORD FinishUpdateProcess(DWORD processId, ULONGLONG creationTime) {
if (!processId || !creationTime || processId == GetCurrentProcessId()) {
return ERROR_INVALID_PARAMETER;
}
writeLog(L"Waiting for update parent " + std::to_wstring(processId)
+ L" (created " + std::to_wstring(creationTime) + L").");
const auto process = std::unique_ptr<void, decltype(&CloseHandle)>(
OpenProcess(
SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
FALSE,
processId),
&CloseHandle);
if (!process) {
const auto error = GetLastError();
return (error == ERROR_INVALID_PARAMETER) ? ERROR_SUCCESS : error;
}
auto created = FILETIME();
auto exited = FILETIME();
auto kernel = FILETIME();
auto user = FILETIME();
if (!GetProcessTimes(process.get(), &created, &exited, &kernel, &user)) {
return GetLastError();
}
const auto actualTime = (ULONGLONG(created.dwHighDateTime) << 32)
| created.dwLowDateTime;
if (actualTime != creationTime) {
writeLog(L"Update parent already exited; process id was reused.");
return ERROR_SUCCESS;
}
auto wait = WaitForSingleObject(process.get(), kProcessExitTimeout);
if (wait == WAIT_TIMEOUT) {
const auto termination = std::unique_ptr<void, decltype(&CloseHandle)>(
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE,
FALSE,
processId),
&CloseHandle);
if (!termination) {
return GetLastError();
}
if (!GetProcessTimes(
termination.get(),
&created,
&exited,
&kernel,
&user)) {
return GetLastError();
}
const auto terminationTime = (ULONGLONG(created.dwHighDateTime) << 32)
| created.dwLowDateTime;
if (terminationTime != creationTime) {
return ERROR_SUCCESS;
}
writeLog(L"Update parent teardown timed out; terminating it.");
if (!TerminateProcess(termination.get(), ERROR_PROCESS_ABORTED)) {
const auto error = GetLastError();
wait = WaitForSingleObject(process.get(), kProcessExitTimeout);
return (wait == WAIT_OBJECT_0)
? ERROR_SUCCESS
: error;
}
wait = WaitForSingleObject(process.get(), kProcessExitTimeout);
}
return (wait == WAIT_OBJECT_0)
? ERROR_SUCCESS
: (wait == WAIT_TIMEOUT)
? ERROR_TIMEOUT
: GetLastError();
}
// WHY: the parent keeps running while a privileged install copies, and
// Windows cannot overwrite a mapped image or library, only rename it, so a
// shared target moves aside and the leftover goes with the next reboot.
bool ReplaceSharedFile(const wstring &from, const wstring &to) {
const auto fresh = to + L".new";
const auto aside = to + L".old";
DeleteFile(fresh.c_str());
if (!CopyFile(from.c_str(), fresh.c_str(), FALSE)) {
return false;
}
DeleteFile(aside.c_str());
if (!MoveFileEx(to.c_str(), aside.c_str(), MOVEFILE_REPLACE_EXISTING)) {
DeleteFile(fresh.c_str());
return false;
} else if (!MoveFileEx(fresh.c_str(), to.c_str(), 0)) {
MoveFileEx(aside.c_str(), to.c_str(), 0);
DeleteFile(fresh.c_str());
return false;
}
MoveFileEx(aside.c_str(), nullptr, MOVEFILE_DELAY_UNTIL_REBOOT);
return true;
}
void fullClearPath(const wstring &dir) {
WCHAR path[4096];
memcpy(path, dir.c_str(), (dir.size() + 1) * sizeof(WCHAR));
path[dir.size() + 1] = 0;
writeLog(L"Fully clearing path '" + dir + L"'..");
SHFILEOPSTRUCT file_op = {
NULL,
FO_DELETE,
path,
L"",
FOF_NOCONFIRMATION |
FOF_NOERRORUI |
FOF_SILENT,
false,
0,
L""
};
int res = SHFileOperation(&file_op);
if (res) writeLog(L"Error: failed to clear path! :(");
}
void delFolder() {
wstring delPathOld = L"tupdates\\ready", delPath = L"tupdates\\temp", delFolder = L"tupdates";
fullClearPath(delPathOld);
fullClearPath(delPath);
RemoveDirectory(delFolder.c_str());
}
DWORD versionNum = 0, versionLen = 0, readLen = 0;
WCHAR versionStr[32] = { 0 };
bool update() {
writeLog(L"Update started..");
wstring updDir = L"tupdates\\temp", readyFilePath = L"tupdates\\temp\\ready", tdataDir = L"tupdates\\temp\\tdata";
{
HANDLE readyFile = CreateFile(readyFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (readyFile != INVALID_HANDLE_VALUE) {
CloseHandle(readyFile);
} else {
updDir = L"tupdates\\ready"; // old
tdataDir = L"tupdates\\ready\\tdata";
}
}
HANDLE versionFile = CreateFile((tdataDir + L"\\version").c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (versionFile != INVALID_HANDLE_VALUE) {
if (!ReadFile(versionFile, &versionNum, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD)) {
versionNum = 0;
} else {
if (versionNum == 0x7FFFFFFF) { // alpha version
} else if (versionNum == 0x7FFFFFFE) { // v2 canary version
} else if (!ReadFile(versionFile, &versionLen, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD) || versionLen > 63) {
versionNum = 0;
} else if (!ReadFile(versionFile, versionStr, versionLen, &readLen, NULL) || readLen != versionLen) {
versionNum = 0;
}
}
CloseHandle(versionFile);
writeLog(L"Version file read.");
} else {
writeLog(L"Could not open version file to update registry :(");
}
deque<wstring> dirs;
dirs.push_back(updDir);
deque<wstring> from, to, forcedirs;
do {
wstring dir = dirs.front();
dirs.pop_front();
wstring toDir = updateTo;
if (dir.size() > updDir.size() + 1) {
toDir += (dir.substr(updDir.size() + 1) + L"\\");
forcedirs.push_back(toDir);
writeLog(L"Parsing dir '" + toDir + L"' in update tree..");
}
WIN32_FIND_DATA findData;
HANDLE findHandle = FindFirstFileEx((dir + L"\\*").c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, 0, 0);
if (findHandle == INVALID_HANDLE_VALUE) {
DWORD errorCode = GetLastError();
if (errorCode == ERROR_PATH_NOT_FOUND) { // no update is ready
return true;
}
writeLog(L"Error: failed to find update files :(");
updateError(L"Failed to find update files", errorCode);
delFolder();
return false;
}
do {
wstring fname = dir + L"\\" + findData.cFileName;
if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) {
writeLog(L"Skipped 'tdata' path '" + fname + L"'");
} else if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (findData.cFileName != wstring(L".") && findData.cFileName != wstring(L"..")) {
dirs.push_back(fname);
writeLog(L"Added dir '" + fname + L"' in update tree..");
}
} else {
wstring tofname = updateTo + fname.substr(updDir.size() + 1);
if (equal(tofname, updaterName)) { // bad update - has Updater.exe - delete all dir
writeLog(L"Error: bad update, has Updater.exe! '" + tofname + L"' equal '" + updaterName + L"'");
delFolder();
return false;
} else if (equal(tofname, updateTo + L"Telegram.exe") && exeName != L"Telegram.exe") {
wstring fullBinaryPath = updateTo + exeName;
writeLog(L"Target binary found: '" + tofname + L"', changing to '" + fullBinaryPath + L"'");
tofname = fullBinaryPath;
}
if (equal(fname, readyFilePath)) {
writeLog(L"Skipped ready file '" + fname + L"'");
} else {
from.push_back(fname);
to.push_back(tofname);
writeLog(L"Added file '" + fname + L"' to be copied to '" + tofname + L"'");
}
}
} while (FindNextFile(findHandle, &findData));
DWORD errorCode = GetLastError();
if (errorCode && errorCode != ERROR_NO_MORE_FILES) { // everything is found
writeLog(L"Error: failed to find next update file :(");
updateError(L"Failed to find next update file", errorCode);
delFolder();
return false;
}
FindClose(findHandle);
} while (!dirs.empty());
for (size_t i = 0; i < forcedirs.size(); ++i) {
wstring forcedir = forcedirs[i];
writeLog(L"Forcing dir '" + forcedir + L"'..");
if (!forcedir.empty() && !CreateDirectory(forcedir.c_str(), NULL)) {
DWORD errorCode = GetLastError();
if (errorCode && errorCode != ERROR_ALREADY_EXISTS) {
writeLog(L"Error: failed to create dir '" + forcedir + L"'..");
updateError(L"Failed to create directory", errorCode);
delFolder();
return false;
}
writeLog(L"Already exists!");
}
}
for (size_t i = 0; i < from.size(); ++i) {
wstring fname = from[i], tofname = to[i];
BOOL copyResult;
auto movedAside = false;
do {
writeLog(L"Copying file '" + fname + L"' to '" + tofname + L"'..");
int copyTries = 0;
auto errorCode = DWORD(0);
do {
copyResult = CopyFile(fname.c_str(), tofname.c_str(), FALSE);
if (copyResult) {
break;
}
errorCode = GetLastError();
if (errorCode == ERROR_SHARING_VIOLATION
&& !movedAside
&& ReplaceSharedFile(fname, tofname)) {
movedAside = true;
copyResult = TRUE;
writeLog(L"Replaced the shared target aside: " + tofname);
break;
}
++copyTries;
Sleep(100);
} while (copyTries < 100);
if (!copyResult) {
const auto error = FormatUpdateError(
L"Failed to update Telegram :(\nCould not copy:\n"
+ fname + L"\nTo:\n" + tofname,
errorCode);
writeLog(error);
if (MessageBox(
0,
error.c_str(),
L"Update error!",
MB_ICONERROR | MB_RETRYCANCEL) != IDRETRY) {
delFolder();
return false;
}
}
} while (!copyResult);
}
writeLog(L"Update succeed! Clearing folder..");
delFolder();
return true;
}
void updateRegistry() {
if (versionNum && versionNum != 0x7FFFFFFF && versionNum != 0x7FFFFFFE) {
writeLog(L"Updating registry..");
versionStr[versionLen / 2] = 0;
HKEY rkey;
LSTATUS status = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{53F49750-6209-4FBF-9CA8-7A333C87D1ED}_is1", 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &rkey);
if (status == ERROR_SUCCESS) {
writeLog(L"Checking registry install location..");
static const int bufSize = 4096;
DWORD locationType, locationSize = bufSize * 2;
WCHAR locationStr[bufSize], exp[bufSize];
if (RegQueryValueEx(rkey, L"InstallLocation", 0, &locationType, (BYTE*)locationStr, &locationSize) == ERROR_SUCCESS) {
locationSize /= 2;
if (locationStr[locationSize - 1]) {
locationStr[locationSize++] = 0;
}
if (locationType == REG_EXPAND_SZ) {
DWORD copy = ExpandEnvironmentStrings(locationStr, exp, bufSize);
if (copy <= bufSize) {
memcpy(locationStr, exp, copy * sizeof(WCHAR));
}
}
if (locationType == REG_EXPAND_SZ || locationType == REG_SZ) {
if (PathCanonicalize(exp, locationStr)) {
memcpy(locationStr, exp, bufSize * sizeof(WCHAR));
if (GetFullPathName(L".", bufSize, exp, 0) < bufSize) {
wstring installpath = locationStr, mypath = exp;
if (installpath == mypath + L"\\" || true) { // always update reg info, if we found it
WCHAR nameStr[bufSize], dateStr[bufSize], publisherStr[bufSize], icongroupStr[bufSize];
SYSTEMTIME stLocalTime;
GetLocalTime(&stLocalTime);
RegSetValueEx(rkey, L"DisplayVersion", 0, REG_SZ, (const BYTE*)versionStr, ((versionLen / 2) + 1) * sizeof(WCHAR));
wsprintf(nameStr, L"Telegram Desktop");
RegSetValueEx(rkey, L"DisplayName", 0, REG_SZ, (const BYTE*)nameStr, (wcslen(nameStr) + 1) * sizeof(WCHAR));
wsprintf(publisherStr, L"Telegram FZ-LLC");
RegSetValueEx(rkey, L"Publisher", 0, REG_SZ, (const BYTE*)publisherStr, (wcslen(publisherStr) + 1) * sizeof(WCHAR));
wsprintf(icongroupStr, L"Telegram Desktop");
RegSetValueEx(rkey, L"Inno Setup: Icon Group", 0, REG_SZ, (const BYTE*)icongroupStr, (wcslen(icongroupStr) + 1) * sizeof(WCHAR));
wsprintf(dateStr, L"%04d%02d%02d", stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay);
RegSetValueEx(rkey, L"InstallDate", 0, REG_SZ, (const BYTE*)dateStr, (wcslen(dateStr) + 1) * sizeof(WCHAR));
const WCHAR *appURL = L"https://desktop.telegram.org";
RegSetValueEx(rkey, L"HelpLink", 0, REG_SZ, (const BYTE*)appURL, (wcslen(appURL) + 1) * sizeof(WCHAR));
RegSetValueEx(rkey, L"URLInfoAbout", 0, REG_SZ, (const BYTE*)appURL, (wcslen(appURL) + 1) * sizeof(WCHAR));
RegSetValueEx(rkey, L"URLUpdateInfo", 0, REG_SZ, (const BYTE*)appURL, (wcslen(appURL) + 1) * sizeof(WCHAR));
}
}
}
}
}
RegCloseKey(rkey);
}
}
}
namespace {
struct ComReleaser {
void operator()(IUnknown *object) const;
};
struct BstrDeleter {
void operator()(OLECHAR *string) const;
};
template <typename Interface>
using ComPtr = std::unique_ptr<Interface, ComReleaser>;
using Bstr = std::unique_ptr<OLECHAR, BstrDeleter>;
void ComReleaser::operator()(IUnknown *object) const {
object->Release();
}
void BstrDeleter::operator()(OLECHAR *string) const {
SysFreeString(string);
}
template <typename Interface>
[[nodiscard]] ComPtr<Interface> ComQuery(IUnknown *object, REFIID iid) {
auto result = (void*)nullptr;
if (!object
|| FAILED(object->QueryInterface(iid, &result))
|| !result) {
return nullptr;
}
return ComPtr<Interface>(static_cast<Interface*>(result));
}
[[nodiscard]] VARIANT BstrVariant(const Bstr &string) {
auto result = VARIANT();
result.vt = VT_BSTR;
result.bstrVal = string.get();
return result;
}
// WHY: the elevated updater must start the new version with the user's
// token without trusting the user-writable working directory; the desktop
// view's automation object lives in the user's own unelevated explorer.exe.
[[nodiscard]] ComPtr<IShellDispatch2> DesktopShellDispatch() {
auto windowsRaw = (void*)nullptr;
if (FAILED(CoCreateInstance(
CLSID_ShellWindows,
nullptr,
CLSCTX_LOCAL_SERVER,
IID_IShellWindows,
&windowsRaw))
|| !windowsRaw) {
writeLog(L"Error: could not reach the shell windows.");
return nullptr;
}
const auto windows = ComPtr<IShellWindows>(
static_cast<IShellWindows*>(windowsRaw));
auto location = VARIANT();
location.vt = VT_I4;
location.lVal = CSIDL_DESKTOP;
auto root = VARIANT();
root.vt = VT_EMPTY;
auto hwnd = long(0);
auto desktopRaw = (IDispatch*)nullptr;
if (FAILED(windows->FindWindowSW(
&location,
&root,
SWC_DESKTOP,
&hwnd,
SWFO_NEEDDISPATCH,
&desktopRaw))
|| !desktopRaw) {
writeLog(L"Error: could not find the desktop window.");
return nullptr;
}
const auto desktop = ComPtr<IDispatch>(desktopRaw);
const auto provider = ComQuery<IServiceProvider>(
desktop.get(),
IID_IServiceProvider);
auto browserRaw = (void*)nullptr;
if (!provider
|| FAILED(provider->QueryService(
SID_STopLevelBrowser,
IID_IShellBrowser,
&browserRaw))
|| !browserRaw) {
writeLog(L"Error: could not reach the desktop browser.");
return nullptr;
}
const auto browser = ComPtr<IShellBrowser>(
static_cast<IShellBrowser*>(browserRaw));
auto viewRaw = (IShellView*)nullptr;
if (FAILED(browser->QueryActiveShellView(&viewRaw)) || !viewRaw) {
writeLog(L"Error: could not reach the desktop view.");
return nullptr;
}
const auto view = ComPtr<IShellView>(viewRaw);
auto backgroundRaw = (void*)nullptr;
if (FAILED(view->GetItemObject(
SVGIO_BACKGROUND,
IID_IDispatch,
&backgroundRaw))
|| !backgroundRaw) {
writeLog(L"Error: could not reach the desktop automation object.");
return nullptr;
}
const auto background = ComPtr<IDispatch>(
static_cast<IDispatch*>(backgroundRaw));
const auto folderView = ComQuery<IShellFolderViewDual>(
background.get(),
IID_IShellFolderViewDual);
auto applicationRaw = (IDispatch*)nullptr;
if (!folderView
|| FAILED(folderView->get_Application(&applicationRaw))
|| !applicationRaw) {
writeLog(L"Error: could not reach the desktop shell application.");
return nullptr;
}
const auto application = ComPtr<IDispatch>(applicationRaw);
auto result = ComQuery<IShellDispatch2>(
application.get(),
IID_IShellDispatch2);
if (!result) {
writeLog(L"Error: the desktop shell application is not scriptable.");
}
return result;
}
[[nodiscard]] bool LaunchUnelevated(
const wstring &executable,
const wstring &arguments,
const wstring &directory) {
const auto shell = DesktopShellDispatch();
if (!shell) {
return false;
}
const auto file = Bstr(SysAllocString(executable.c_str()));
const auto parameters = Bstr(SysAllocString(arguments.c_str()));
const auto folder = Bstr(SysAllocString(directory.c_str()));
const auto operation = Bstr(SysAllocString(L"open"));
if (!file || !parameters || !folder || !operation) {
writeLog(L"Error: could not allocate the launch strings.");
return false;
}
auto show = VARIANT();
show.vt = VT_I4;
show.lVal = SW_SHOWNORMAL;
const auto result = shell->ShellExecute(
file.get(),
BstrVariant(parameters),
BstrVariant(folder),
BstrVariant(operation),
show);
if (result != S_OK) {
writeLog(FormatUpdateError(
L"The desktop shell did not execute the new version.",
DWORD(result)));
return false;
}
return true;
}
} // namespace
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdParamarg, int cmdShow) {
base::Platform::InitDynamicLibraries();
openLog();
_oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter);
// CAPIHook apiHook("kernel32.dll", "SetUnhandledExceptionFilter", (PROC)RedirectedSetUnhandledExceptionFilter);
writeLog(L"Updaters started..");
auto argsCount = 0;
auto processId = DWORD(0);
auto processCreated = ULONGLONG(0);
auto processArgumentsValid = true;
bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false;
bool justupdate = false, updated = false;
const auto args = CommandLineToArgvW(GetCommandLine(), &argsCount);
const auto argsGuard = std::unique_ptr<void, decltype(&LocalFree)>(
args,
&LocalFree);
if (args) {
for (int i = 1; i < argsCount; ++i) {
writeLog(std::wstring(L"Argument: ") + args[i]);
if (equal(args[i], L"-update")) {
needupdate = true;
} else if (equal(args[i], L"-finishprocess")) {
if (processId
|| i + 2 >= argsCount
|| !ParseUpdateProcess(
args[i + 1],
args[i + 2],
processId,
processCreated)) {
processArgumentsValid = false;
} else {
writeLog(std::wstring(L"Argument: ") + args[++i]);
writeLog(std::wstring(L"Argument: ") + args[++i]);
}
} else if (equal(args[i], L"-autostart")) {
autostart = true;
} else if (equal(args[i], L"-justupdate")) {
justupdate = true;
} else if (equal(args[i], L"-debug")) {
debug = _debug = true;
openLog();
} else if (equal(args[i], L"-startintray")) {
startintray = true;
} else if (equal(args[i], L"-writeprotected") && ++i < argsCount) {
writeLog(std::wstring(L"Argument: ") + args[i]);
writeprotected = true;
updateTo = args[i];
for (int j = 0, l = updateTo.size(); j < l; ++j) {
if (updateTo[j] == L'/') {
updateTo[j] = L'\\';
}
}
} else if (equal(args[i], L"-workdir") && ++i < argsCount) {
writeLog(std::wstring(L"Argument: ") + args[i]);
customWorkingDir = args[i];
} else if (equal(args[i], L"-key") && ++i < argsCount) {
writeLog(std::wstring(L"Argument: ") + args[i]);
customKeyFile = args[i];
} else if (equal(args[i], L"-exename") && ++i < argsCount) {
writeLog(std::wstring(L"Argument: ") + args[i]);
exeName = args[i];
for (int j = 0, l = exeName.size(); j < l; ++j) {
if (exeName[j] == L'/' || exeName[j] == L'\\') {
exeName = L"Telegram.exe";
break;
}
}
}
}
if (exeName.empty()) {
exeName = L"Telegram.exe";
}
if (!processArgumentsValid) {
writeLog(L"Invalid update process arguments; "
L"continuing without process handoff.");
}
if (needupdate) writeLog(L"Need to update!");
if (autostart) writeLog(L"From autostart!");
if (writeprotected) writeLog(L"Write Protected folder!");
if (!customWorkingDir.empty()) writeLog(L"Will pass custom working dir: " + customWorkingDir);
updaterName = args[0];
writeLog(L"Updater name is: " + updaterName);
if (updaterName.size() > 11) {
if (equal(updaterName.substr(updaterName.size() - 11), L"Updater.exe")) {
updaterDir = updaterName.substr(0, updaterName.size() - 11);
writeLog(L"Updater dir is: " + updaterDir);
if (!writeprotected) {
updateTo = updaterDir;
}
writeLog(L"Update to: " + updateTo);
if (needupdate && processId && processArgumentsValid) {
const auto error = FinishUpdateProcess(
processId,
processCreated);
if (error != ERROR_SUCCESS) {
writeLog(FormatUpdateError(
L"Could not finish closing Telegram; continuing with copy retries.",
error));
}
}
if (needupdate && update()) {
updated = true;
updateRegistry();
}
if (writeprotected) { // if we can't clear all tupdates\ready (Updater.exe is there) - clear only version
if (DeleteFile(L"tupdates\\temp\\tdata\\version") || DeleteFile(L"tupdates\\ready\\tdata\\version")) {
writeLog(L"Version file deleted!");
} else {
writeLog(L"Error: could not delete version file");
}
}
} else {
writeLog(L"Error: bad exe name!");
}
} else {
writeLog(L"Error: short exe name!");
}
} else {
writeLog(L"Error: No command line arguments!");
}
wstring targs;
if (autostart) targs += L" -autostart";
if (debug) targs += L" -debug";
if (startintray) targs += L" -startintray";
if (!customWorkingDir.empty()) {
targs += L" -workdir \"" + customWorkingDir + L"\"";
}
if (!customKeyFile.empty()) {
targs += L" -key \"" + customKeyFile + L"\"";
}
writeLog(L"Result arguments: " + targs);
bool executed = justupdate;
if (justupdate) {
writeLog(L"Just updating, the parent relaunches..");
} else if (writeprotected) { // run un-elevated
writeLog(L"Trying to run un-elevated through the desktop shell..");
HRESULT hres = CoInitialize(0);
if (SUCCEEDED(hres)) {
executed = LaunchUnelevated(
updateTo + exeName,
targs.size() ? targs.substr(1) : targs,
updateTo);
if (executed) {
writeLog(L"Executed un-elevated through the desktop shell.");
}
CoUninitialize();
} else {
writeLog(L"Error: Could not initialize COM");
}
}
if (!executed) {
ShellExecuteW(
0,
0,
(updateTo + exeName).c_str(),
(L"-noupdate" + targs).c_str(),
updateTo.empty() ? nullptr : updateTo.c_str(),
SW_SHOWNORMAL);
}
writeLog(L"Closing log and quitting..");
closeLog();
return (needupdate && !updated) ? 1 : 0;
}
static const WCHAR *_programName = L"Telegram Desktop"; // folder in APPDATA, if current path is unavailable for writing
static const WCHAR *_exeName = L"Updater.exe";
LPTOP_LEVEL_EXCEPTION_FILTER _oldWndExceptionFilter = 0;
typedef BOOL (FAR STDAPICALLTYPE *t_miniDumpWriteDump)(
_In_ HANDLE hProcess,
_In_ DWORD ProcessId,
_In_ HANDLE hFile,
_In_ MINIDUMP_TYPE DumpType,
_In_opt_ PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
_In_opt_ PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
_In_opt_ PMINIDUMP_CALLBACK_INFORMATION CallbackParam
);
t_miniDumpWriteDump miniDumpWriteDump = 0;
HANDLE _generateDumpFileAtPath(const WCHAR *path) {
static const int maxFileLen = MAX_PATH * 10;
WCHAR szPath[maxFileLen];
wsprintf(szPath, L"%stdata\\", path);
if (!CreateDirectory(szPath, NULL)) {
if (GetLastError() != ERROR_ALREADY_EXISTS) {
return 0;
}
}
wsprintf(szPath, L"%sdumps\\", path);
if (!CreateDirectory(szPath, NULL)) {
if (GetLastError() != ERROR_ALREADY_EXISTS) {
return 0;
}
}
WCHAR szFileName[maxFileLen];
WCHAR szExeName[maxFileLen];
wcscpy_s(szExeName, _exeName);
WCHAR *dotFrom = wcschr(szExeName, WCHAR(L'.'));
if (dotFrom) {
wsprintf(dotFrom, L"");
}
SYSTEMTIME stLocalTime;
GetLocalTime(&stLocalTime);
wsprintf(
szFileName, L"%s%s-%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szExeName, updaterVersionStr,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
return CreateFile(szFileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
}
void _generateDump(EXCEPTION_POINTERS* pExceptionPointers) {
static const int maxFileLen = MAX_PATH * 10;
closeLog();
HMODULE hDll = LoadLibrary(L"DBGHELP.DLL");
if (!hDll) return;
miniDumpWriteDump = (t_miniDumpWriteDump)GetProcAddress(hDll, "MiniDumpWriteDump");
if (!miniDumpWriteDump) return;
HANDLE hDumpFile = 0;
WCHAR szPath[maxFileLen];
DWORD len = GetModuleFileName(GetModuleHandle(0), szPath, maxFileLen);
if (!len) return;
WCHAR *pathEnd = szPath + len;
if (!_wcsicmp(pathEnd - wcslen(_exeName), _exeName)) {
wsprintf(pathEnd - wcslen(_exeName), L"");
hDumpFile = _generateDumpFileAtPath(szPath);
}
if (!hDumpFile || hDumpFile == INVALID_HANDLE_VALUE) {
WCHAR wstrPath[maxFileLen];
DWORD wstrPathLen = GetEnvironmentVariable(L"APPDATA", wstrPath, maxFileLen);
if (wstrPathLen) {
wsprintf(wstrPath + wstrPathLen, L"\\%s\\", _programName);
hDumpFile = _generateDumpFileAtPath(wstrPath);
}
}
if (!hDumpFile || hDumpFile == INVALID_HANDLE_VALUE) {
return;
}
MINIDUMP_EXCEPTION_INFORMATION ExpParam = {0};
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
miniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpWithDataSegs, &ExpParam, NULL, NULL);
}
LONG CALLBACK _exceptionFilter(EXCEPTION_POINTERS* pExceptionPointers) {
_generateDump(pExceptionPointers);
return _oldWndExceptionFilter ? (*_oldWndExceptionFilter)(pExceptionPointers) : EXCEPTION_CONTINUE_SEARCH;
}
// see http://www.codeproject.com/Articles/154686/SetUnhandledExceptionFilter-and-the-C-C-Runtime-Li
LPTOP_LEVEL_EXCEPTION_FILTER WINAPI RedirectedSetUnhandledExceptionFilter(_In_opt_ LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter) {
// When the CRT calls SetUnhandledExceptionFilter with NULL parameter
// our handler will not get removed.
_oldWndExceptionFilter = lpTopLevelExceptionFilter;
return 0;
}