-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUpdateManager.cpp
executable file
·418 lines (340 loc) · 10.7 KB
/
UpdateManager.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
#include "StdAfx.h"
#include ".\updatemanager.h"
//#include ".\MinakortWebUpload.h"
#include ".\Resource.h"
#include ".\UpdateDialog.h"
#include ".\defines.h"
#include ".\Utility.h"
#include ".\HttpStream.h"
#pragma comment(lib, "version.lib")
const int FILE_ERROR = 2;
const int OLD_CLIENT = 3;
const int BINARY_ERROR = 4;
const int REGISTRATION_ERROR = 5;
/*
Automatic update should not be performed on a url supplied over an internet connection.
That would make it easier to redirect the download to a malicious site.
*/
extern int ReleaseVersion;
static const LPTSTR UpdatePath = _T("public/minakortcontrolsupdate.aspx");
static const UINT UpdateServerPort = 80;
static const UINT UpdateManagerVersion= 1;
static const LPTSTR UPDATEMANAGER_AGENT = _T("MinakortControlsUpdateManager");
UpdateManager::UpdateManager(void)
{
}
UpdateManager::~UpdateManager(void)
{
}
const CString UpdateManager::GetVersionsQueryString()
{
CString q, t;
BOOL b;
q.AppendFormat(_T("updateManagerVersion=%u&controlReleaseVersion=%u"), UpdateManagerVersion, ReleaseVersion);
SYSTEM_INFO system;
//TODO: Should use GetNativeSystemInfo, but that isn't available before Windows XP.
::GetSystemInfo(&system);
q.AppendFormat(_T("&processorArchitecture=%u"), (unsigned)system.wProcessorArchitecture);
OSVERSIONINFO version;
ZeroMemory(&version, sizeof(version));
version.dwOSVersionInfoSize = sizeof(version);
b = ::GetVersionEx(&version);
if(version.dwPlatformId == VER_PLATFORM_WIN32_NT)
t = _T("nt");
else if(version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
t = _T("95");
else t = _T("unknown");
q += _T("&platform=");
q += t;
q.AppendFormat(_T("&winmajor=%u&winminor=%u&winCsd="), version.dwMajorVersion, version.dwMinorVersion);
q.Append(EscapeUrl(version.szCSDVersion));
q += _T("&gdiplusver=");
t = _T("0.0");
DWORD size = ::GetFileVersionInfoSize(_T("gdiplus.dll"), NULL);
while(size != 0)
{
LPVOID gdiver = new byte[size];
b = ::GetFileVersionInfo(_T("gdiplus.dll"), 0, size, gdiver);
if(!b) break;
VS_FIXEDFILEINFO* vsinfo;unsigned len;
b = ::VerQueryValue(gdiver, _T("\\"), (void**)&vsinfo, &len);
if(!b) break;
t.Format(_T("%u.%u"), vsinfo->dwFileVersionMS, vsinfo->dwFileVersionLS);
delete[] gdiver;
break;
}
q += t;
q += _T("&admin=");
q += Utility::IsUserAdmin()?_T("True"):_T("False");
DWORD mfc71 = ::GetFileVersionInfoSize(_T("mfc71.dll"), NULL);
q += mfc71?_T("&mfc71=True"):_T("&mfc71=False");
return q;
}
HANDLE CreateTempFile(CString& file)
{
TCHAR t;
DWORD len = ::GetTempPath(0, &t);
CString path;
path.ReleaseBuffer(::GetTempPath(len, path.GetBuffer(len)));
::GetTempFileName(path, _T("update"), 0, file.GetBuffer(MAX_PATH));
file.ReleaseBuffer();
DWORD flags = 0;//FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE;
HANDLE handle = ::CreateFile(file, GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_ALWAYS,flags,0);
return handle;
}
CString GetBinaryPath(bool adminInstall)
{
CString path;
if(adminInstall)
{
HRESULT hr = SHGetFolderPath(NULL,
CSIDL_PROGRAM_FILES,
NULL,
0,
path.GetBuffer(MAX_PATH));
path.ReleaseBuffer();
path += _T("\\");
if(SUCCEEDED(hr))
path += _T("Minakort\\");
else
throw FILE_ERROR;
}
else
{
HRESULT hr = SHGetFolderPath(NULL,
CSIDL_LOCAL_APPDATA,
NULL,
0,
path.GetBuffer(MAX_PATH));
path.ReleaseBuffer();
path += _T("\\");
if(SUCCEEDED(hr))
{
path += _T("Minakort");
if(!::PathFileExists(path) && !::CreateDirectory(path, NULL))
throw FILE_ERROR;
path += _T("\\Binaries\\");
}
else
throw FILE_ERROR;
}
if(!::PathFileExists(path) && !::CreateDirectory(path, NULL))
throw FILE_ERROR;
return path;
}
//__declspec(dllexport) HRESULT GetClsid(LPCWSTR className, GUID* guid)
//{
// if(guid)
// memset(guid, sizeof(GUID), 0x00);
//
// if(!guid || !className)
// return E_INVALIDARG;
//
// if(wcscmp(className, L"CMinakortWebUpload") == 0)
// {
// *guid = __uuidof(CMinakortWebUpload);
// return S_OK;
// }
// return E_FAIL;
//}
typedef HRESULT (*comvoid)();
typedef HRESULT (*regfunc)(int oldVersion, int oldUpdateManagerVersion, bool administratorInstall);
//typedef HRESULT (*getGuidFunc)(LPCWSTR className, GUID* guid);
struct UpdateProcPrm
{
UpdateManager* mgr;
UpdateDialog* dlg;
CEvent* finishedEvent;
HRESULT result;
// GUID uploadClsid;
};
HRESULT UpdateManager::StartUpdate(/*GUID *newClsID*/)
{
UpdateDialog dlg;
CEvent finishedEvent;
UpdateProcPrm prm;
prm.dlg = &dlg;
prm.finishedEvent = &finishedEvent;
prm.mgr = this;
prm.result = E_FAIL;
CWinThread* thread = ::AfxBeginThread(UpdateProc, &prm, THREAD_PRIORITY_BELOW_NORMAL, 0, 0, 0);
dlg.DoModal();
finishedEvent.Lock();
//if(newClsID)
// memcpy(newClsID, &prm.uploadClsid, sizeof(GUID));
return prm.result;
}
UINT UpdateManager::UpdateProc(LPVOID threadParameter)
{
UpdateProcPrm* prm = static_cast<UpdateProcPrm*>(threadParameter);
HANDLE tempFile = 0;
CString tempFileName = _T("");
HMODULE newmod = 0;
BOOL success = FALSE;
HRESULT error = S_OK;
CString errorMessage = _T("");
try
{
bool administratorInstall = Utility::IsUserAdmin()?true:false;
CString queryString = CString(APP_DIR) + UpdatePath;
queryString += CString(_T("?")) + GetVersionsQueryString();
CInternetSession session(UPDATEMANAGER_AGENT);
CHttpConnection* connection = session.GetHttpConnection(SERVER_ADDRESS, 0, UpdateServerPort, 0, 0);
HttpStream s(connection, queryString);
s.StartReading();
tempFile = CreateTempFile(tempFileName);
if(!tempFile)
throw FILE_ERROR;
if(s.Read<int>() != UpdateManagerVersion)
throw OLD_CLIENT;
DWORD responseCode = s.Read<DWORD>();
//Read message
CStringW message = s.ReadStringW();
if(message.GetLength() > 0)
MessageBox(prm->dlg->GetSafeHwnd(), CW2T(message), R2T(IDS_UPDATE_SERVERMESSAGECAPTION), MB_ICONINFORMATION);
//Read file count
int files = s.Read<int>();
//Read total bytes count
int totalBytes = s.Read<int>();
prm->dlg->SetJobBytes(totalBytes);
UINT totalFinishedBytes=0;
for(int currentFile=0;currentFile<files;currentFile++)
{
//Read require registration
char requireRegistration = s.Read<char>();
//Read file name
CString fileName = CW2T(s.ReadStringW());
//Read file size
UINT fileSize = s.Read<UINT>();
UINT readBytes = 0;
while(readBytes < fileSize)
{
DWORD read, toRead;
byte buf[16*1024];
toRead = min(fileSize-readBytes, sizeof(buf));
read = s.ReadBuffer(buf, toRead);
if(read == 0)
throw CONNECTION_ERROR;
readBytes += read;
totalFinishedBytes += read;
if(!::WriteFile(tempFile, buf, read, &toRead, NULL))
throw FILE_ERROR;
if(toRead != read)
throw FILE_ERROR;
prm->dlg->SetFinishedBytes(totalFinishedBytes);
}
::CloseHandle(tempFile);
tempFile = 0;
//move the file to "program files\minakort" or "~\Local settings\minakort\binaries"
CString permanentPath = GetBinaryPath(administratorInstall);
::SetCurrentDirectory(permanentPath); //So that download libraries will be found by windows.
//if targetFile already exists, move it to a temp name
if(::PathFileExists(permanentPath + fileName))
{
//Try to delete it first:
if(!::DeleteFile(permanentPath + fileName))
{
CString tmp;
tmp.Format(_T("old_%u"), ::GetTickCount);
::MoveFile(permanentPath + fileName, permanentPath + tmp + fileName);
//TODO: set a delete on the file upon reboot.
}
}
permanentPath += fileName;
if(!::MoveFile(tempFileName, permanentPath))
throw FILE_ERROR;
tempFileName.Empty();
newmod = ::LoadLibrary(permanentPath);
if(!newmod)
throw BINARY_ERROR;
//OverrideClassesRoot has no effect on Win95, which is ok, since we're allways admins there annyways.
if(!administratorInstall)
Utility::OverrideClassesRoot(HKEY_CURRENT_USER, _T("Software\\Classes"));
regfunc prereg = (regfunc)::GetProcAddress(newmod, ("UpdatedPreregInstall"));
comvoid reg = (comvoid)::GetProcAddress(newmod, ("DllRegisterServer"));
regfunc postreg = (regfunc)::GetProcAddress(newmod, ("UpdatedPostregInstall"));
// getGuidFunc getGuid = (getGuidFunc)::GetProcAddress(newmod, _T("GetClsid"));
if(!reg && requireRegistration)
throw BINARY_ERROR;
HRESULT hr = S_OK;
if(prereg)
hr = prereg(ReleaseVersion, UpdateManagerVersion, administratorInstall);
if(reg)
hr = reg();
if(FAILED(hr))
throw REGISTRATION_ERROR;
if(postreg)
hr = postreg(ReleaseVersion, UpdateManagerVersion, administratorInstall);
// if(getGuid)
// hr = getGuid(L"CMinakortWebUpload", &prm->uploadClsid);
if(newmod)
::FreeLibrary(newmod);
newmod = 0;
}
//TODO: selfdelete.
//Begin by moving this dll, to a temp path, and then delete it on reboot.
success = TRUE;
error = S_OK;
}
catch(CInternetException* exc)
{
error = 0-CONNECTION_ERROR;
exc->GetErrorMessage(errorMessage.GetBuffer(1000), 1000);
errorMessage.ReleaseBuffer();
exc->Delete();
}
catch(CException* exc)
{
error = E_FAIL;
exc->GetErrorMessage(errorMessage.GetBuffer(1000), 1000);
errorMessage.ReleaseBuffer();
exc->Delete();
}
catch(int errNum)
{
error = 0-errNum; //TODO: create a real hresult
switch(errNum)
{
case CONNECTION_ERROR:
errorMessage = R2T(IDS_UPDATEERROR_COMM);
break;
case FILE_ERROR:
errorMessage = R2T(IDS_UPDATEERROR_FILE);
break;
case OLD_CLIENT:
errorMessage = R2T(IDS_UPDATEERROR_OLDCLIENT);
break;
case BINARY_ERROR:
errorMessage = R2T(IDS_UPDATEERROR_BINARY);
break;
case REGISTRATION_ERROR:
errorMessage = R2T(IDS_UPDATEERROR_REG);
break;
default:
errorMessage = R2T(IDS_UPDATEERROR_UNKNOWN);
}
}
catch(...)
{
errorMessage = R2T(IDS_UPDATEERROR_UNKNOWN);
error = E_FAIL;
}
if(tempFile)
::CloseHandle(tempFile);
if(newmod)
::FreeLibrary(newmod);
if(tempFileName.GetLength())
::DeleteFile(tempFileName);
if(FAILED(error))
{
::MessageBox(prm->dlg->GetSafeHwnd(), CString(R2T(IDS_UPDATE_INSTALLATIONFAILED)) + errorMessage, R2T(IDS_UPDATE_INSTALLINGCAPTION), MB_ICONERROR|MB_OK);
}
else
{
::MessageBox(prm->dlg->GetSafeHwnd(), R2T(IDS_UPDATE_INSTALLATIONFINISHED), R2T(IDS_UPDATE_INSTALLINGCAPTION), MB_OK|MB_ICONINFORMATION);
}
prm->result = error;
prm->dlg->EndDialog(IDOK);
prm->finishedEvent->SetEvent();
return error;
}