-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathUpdateRunner.cpp
More file actions
382 lines (301 loc) · 10.6 KB
/
Copy pathUpdateRunner.cpp
File metadata and controls
382 lines (301 loc) · 10.6 KB
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
#include "stdafx.h"
#include "unzip.h"
#include "Resource.h"
#include "UpdateRunner.h"
#include <vector>
void CUpdateRunner::DisplayErrorMessage(CString& errorMessage, wchar_t* logFile)
{
CTaskDialog dlg;
TASKDIALOG_BUTTON buttons[] = {
{ 1, L"Open Setup Log", },
{ 2, L"Close", },
};
// TODO: Something about contacting support?
if (logFile == NULL) {
dlg.SetButtons(&buttons[1], 1, 1);
} else {
dlg.SetButtons(buttons, 2, 1);
}
dlg.SetMainInstructionText(L"Installation has failed");
dlg.SetContentText(errorMessage);
dlg.SetMainIcon(TD_ERROR_ICON);
int nButton;
if (FAILED(dlg.DoModal(::GetActiveWindow(), &nButton))) {
return;
}
if (nButton == 1 && logFile != NULL) {
ShellExecute(NULL, NULL, logFile, NULL, NULL, SW_SHOW);
}
}
HRESULT CUpdateRunner::AreWeInWine()
{
// NB: Behaving differently in Wine is *usually* discouraged
// https://wiki.winehq.org/Developer_FAQ#How_can_I_detect_Wine.3F
HMODULE hntdll = GetModuleHandle(L"ntdll.dll");
if (!hntdll) {
// NB: This can never fail but we'll be pedantic
return E_FAIL;
}
return GetProcAddress(hntdll, "wine_get_version") != NULL ? S_OK : S_FALSE;
}
HRESULT CUpdateRunner::AreWeUACElevated()
{
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken = 0;
HRESULT hr;
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto out;
}
TOKEN_ELEVATION_TYPE elevType;
DWORD dontcare;
if (!GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(TOKEN_ELEVATION_TYPE), &dontcare)) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto out;
}
hr = (elevType == TokenElevationTypeFull ? S_OK : S_FALSE);
out:
if (hToken) {
CloseHandle(hToken);
}
return hr;
}
HRESULT FindDesktopFolderView(REFIID riid, void **ppv)
{
HRESULT hr;
CComPtr<IShellWindows> spShellWindows;
spShellWindows.CoCreateInstance(CLSID_ShellWindows);
CComVariant vtLoc(CSIDL_DESKTOP);
CComVariant vtEmpty;
long lhwnd;
CComPtr<IDispatch> spdisp;
hr = spShellWindows->FindWindowSW(
&vtLoc, &vtEmpty,
SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp);
if (FAILED(hr)) return hr;
CComPtr<IShellBrowser> spBrowser;
hr = CComQIPtr<IServiceProvider>(spdisp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser));
if (FAILED(hr)) return hr;
CComPtr<IShellView> spView;
hr = spBrowser->QueryActiveShellView(&spView);
if (FAILED(hr)) return hr;
hr = spView->QueryInterface(riid, ppv);
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT GetDesktopAutomationObject(REFIID riid, void **ppv)
{
HRESULT hr;
CComPtr<IShellView> spsv;
hr = FindDesktopFolderView(IID_PPV_ARGS(&spsv));
if (FAILED(hr)) return hr;
CComPtr<IDispatch> spdispView;
hr = spsv->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&spdispView));
if (FAILED(hr)) return hr;
return spdispView->QueryInterface(riid, ppv);
}
HRESULT CUpdateRunner::ShellExecuteFromExplorer(LPWSTR pszFile, LPWSTR pszParameters)
{
HRESULT hr;
CComPtr<IShellFolderViewDual> spFolderView;
hr = GetDesktopAutomationObject(IID_PPV_ARGS(&spFolderView));
if (FAILED(hr)) return hr;
CComPtr<IDispatch> spdispShell;
hr = spFolderView->get_Application(&spdispShell);
if (FAILED(hr)) return hr;
return CComQIPtr<IShellDispatch2>(spdispShell)->ShellExecute(
CComBSTR(pszFile),
CComVariant(pszParameters ? pszParameters : L""),
CComVariant(L""),
CComVariant(L""),
CComVariant(SW_SHOWDEFAULT));
}
bool CUpdateRunner::DirectoryExists(wchar_t* szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
bool CUpdateRunner::DirectoryIsWritable(wchar_t * szPath)
{
wchar_t szTempFileName[MAX_PATH];
UINT uRetVal = GetTempFileNameW(szPath, L"Squirrel", 0, szTempFileName);
if (uRetVal == 0) {
return false;
}
DeleteFile(szTempFileName);
return true;
}
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine, bool useFallbackDir)
{
PROCESS_INFORMATION pi = { 0 };
STARTUPINFO si = { 0 };
CResource zipResource;
wchar_t targetDir[MAX_PATH + 1] = { 0 };
wchar_t logFile[MAX_PATH];
std::vector<CString> to_delete;
wchar_t* envSquirrelTemp = _wgetenv(L"SQUIRREL_TEMP");
if (envSquirrelTemp &&
DirectoryExists(envSquirrelTemp) &&
DirectoryIsWritable(envSquirrelTemp) &&
!PathIsUNCW(envSquirrelTemp)) {
_swprintf_c(targetDir, _countof(targetDir) - 1, L"%s", envSquirrelTemp);
goto gotADir;
}
if (!useFallbackDir) {
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, targetDir);
goto gotADir;
}
wchar_t username[512];
wchar_t appDataDir[MAX_PATH];
ULONG unameSize = _countof(username);
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appDataDir);
GetUserName(username, &unameSize);
_swprintf_c(targetDir, _countof(targetDir) - 1, L"%s\\%s", appDataDir, username);
if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
DisplayErrorMessage(CString(err), NULL);
return -1;
}
gotADir:
wcscat_s(targetDir, _countof(targetDir) - 1, L"\\SquirrelTemp");
if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
if (useFallbackDir) {
DisplayErrorMessage(CString(err), NULL);
}
goto failedExtract;
}
const char tempDirValues[] = "\0abcdefghijklmnopqrstuvwxyz";
int tempDirValuesCount = sizeof(tempDirValues) - 1;
bool tempDirCreated = false;
for (int i = 1; i < (tempDirValuesCount * tempDirValuesCount * tempDirValuesCount * tempDirValuesCount); i++) {
int c0 = i % tempDirValuesCount;
int c1 = (i / tempDirValuesCount) % tempDirValuesCount;
int c2 = (i / (tempDirValuesCount * tempDirValuesCount)) % tempDirValuesCount;
int c3 = (i / (tempDirValuesCount * tempDirValuesCount * tempDirValuesCount)) % tempDirValuesCount;
wchar_t tempDir[MAX_PATH] = { 0 };
_swprintf_c(tempDir, _countof(tempDir), L"%s\\temp%c%c%c%c", targetDir, tempDirValues[c3], tempDirValues[c2], tempDirValues[c1], tempDirValues[c0]);
if (CreateDirectory(tempDir, NULL)) {
_swprintf_c(targetDir, _countof(targetDir) - 1, L"%s", tempDir);
tempDirCreated = true;
break;
}
}
if (!tempDirCreated) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
if (useFallbackDir) {
DisplayErrorMessage(CString(err), NULL);
}
goto failedExtract;
}
swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir);
if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
goto failedExtract;
}
DWORD dwSize = zipResource.GetSize();
if (dwSize < 0x100) {
goto failedExtract;
}
BYTE* pData = (BYTE*)zipResource.Lock();
HZIP zipFile = OpenZip(pData, dwSize, NULL);
SetUnzipBaseDir(zipFile, targetDir);
// NB: This library is kind of a disaster
ZRESULT zr;
int index = 0;
do {
ZIPENTRY zentry;
wchar_t targetFile[MAX_PATH];
zr = GetZipItem(zipFile, index, &zentry);
if (zr != ZR_OK && zr != ZR_MORE) {
break;
}
// NB: UnzipItem won't overwrite data, we need to do it ourselves
swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name);
DeleteFile(targetFile);
if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break;
to_delete.push_back(CString(targetFile));
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
// nfi if the zip extract actually worked, check for Update.exe
wchar_t updateExePath[MAX_PATH];
swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe");
if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) {
goto failedExtract;
}
// Run Update.exe
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW;
if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) {
lpCommandLine = L"";
}
wchar_t cmd[MAX_PATH];
swprintf_s(cmd, L"\"%s\" --install . %s", updateExePath, lpCommandLine);
if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) {
goto failedExtract;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD dwExitCode;
if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) {
dwExitCode = (DWORD)-1;
}
if (dwExitCode != 0) {
DisplayErrorMessage(CString(
L"There was an error while installing the application. "
L"Check the setup log for more information and contact the author."), logFile);
}
for (unsigned int i = 0; i < to_delete.size(); i++) {
DeleteFile(to_delete[i]);
}
if (tempDirCreated) {
// Dump Squirrel-Install.log's content out of temp folder before removal
wchar_t tempSquirrelInstallLog[MAX_PATH] = { 0 };
_swprintf_c(tempSquirrelInstallLog, _countof(tempSquirrelInstallLog), L"%s\\Squirrel-Install.log", targetDir);
wchar_t squirrelInstallLog[MAX_PATH] = { 0 };
_swprintf_c(squirrelInstallLog, _countof(squirrelInstallLog), L"%s\\..\\Squirrel-Install.log", targetDir);
if (GetFileAttributes(squirrelInstallLog) == INVALID_FILE_ATTRIBUTES) {
MoveFile(tempSquirrelInstallLog, squirrelInstallLog);
} else {
HANDLE hTempSquirrelInstallLog = CreateFile(tempSquirrelInstallLog, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
HANDLE hSquirrelInstallLog = CreateFile(squirrelInstallLog, FILE_APPEND_DATA | FILE_GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hTempSquirrelInstallLog != INVALID_HANDLE_VALUE && hSquirrelInstallLog != INVALID_HANDLE_VALUE) {
DWORD dwBytesRead;
BYTE copyBuffer[4096];
while (ReadFile(hTempSquirrelInstallLog, copyBuffer, sizeof(copyBuffer), &dwBytesRead, NULL) && dwBytesRead > 0) {
WriteFile(hSquirrelInstallLog, copyBuffer, dwBytesRead, NULL, NULL);
}
}
CloseHandle(hTempSquirrelInstallLog);
CloseHandle(hSquirrelInstallLog);
}
DeleteFile(tempSquirrelInstallLog);
// Remove temporary directory. RemoveDirectory fails even if targetDir is empty at this point
// RemoveDirectory(targetDir);
SHFILEOPSTRUCT sFileOp;
sFileOp.hwnd = NULL;
sFileOp.wFunc = FO_DELETE;
sFileOp.pFrom = targetDir;
sFileOp.pTo = NULL;
sFileOp.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;
sFileOp.fAnyOperationsAborted = FALSE;
sFileOp.lpszProgressTitle = NULL;
sFileOp.hNameMappings = NULL;
SHFileOperation(&sFileOp);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return (int) dwExitCode;
failedExtract:
if (!useFallbackDir) {
// Take another pass at it, using C:\ProgramData instead
return ExtractUpdaterAndRun(lpCommandLine, true);
}
DisplayErrorMessage(CString(L"Failed to extract installer"), NULL);
return (int) dwExitCode;
}