forked from gurnec/HashCheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashCheckCommon.c
417 lines (342 loc) · 11.3 KB
/
HashCheckCommon.c
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
/**
* HashCheck Shell Extension
* Copyright (C) Kai Liu. All rights reserved.
*
* Please refer to readme.txt for information about this source code.
* Please refer to license.txt for details about distribution and modification.
**/
#include "globals.h"
#include "HashCheckCommon.h"
#include "GetHighMSB.h"
HANDLE __fastcall CreateThreadCRT( PVOID pThreadProc, PVOID pvParam )
{
if (!pThreadProc)
{
// If we have a NULL pThreadProc, then we are starting a worker thread,
// and there is some initialization that we need to take care of...
PCOMMONCONTEXT pcmnctx = pvParam;
pcmnctx->status = ACTIVE;
pcmnctx->cSentMsgs = 0;
pcmnctx->cHandledMsgs = 0;
pcmnctx->hWndPBTotal = GetDlgItem(pcmnctx->hWnd, IDC_PROG_TOTAL);
pcmnctx->hWndPBFile = GetDlgItem(pcmnctx->hWnd, IDC_PROG_FILE);
pThreadProc = WorkerThreadStartup;
}
return((HANDLE)_beginthreadex(
NULL,
BASE_STACK_SIZE,
pThreadProc,
pvParam,
0,
NULL
));
}
HANDLE __fastcall OpenFileForReading( PCTSTR pszPath )
{
return(CreateFile(
pszPath,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL
));
}
VOID __fastcall NormalizeString( PTSTR psz )
{
if (!psz) return;
while (*psz)
{
switch (*psz)
{
case TEXT('\r'):
*psz = TEXT('\n');
break;
case TEXT('\t'):
case TEXT('"'):
case TEXT('*'):
*psz = TEXT(' ');
break;
case TEXT('/'):
*psz = TEXT('\\');
break;
}
++psz;
}
}
VOID WINAPI SetControlText( HWND hWnd, UINT uCtrlID, UINT uStringID )
{
TCHAR szBuffer[MAX_STRINGMSG];
LoadString(g_hModThisDll, uStringID, szBuffer, countof(szBuffer));
SetDlgItemText(hWnd, uCtrlID, szBuffer);
}
VOID WINAPI EnableControl( HWND hWnd, UINT uCtrlID, BOOL bEnable )
{
HWND hWndControl = GetDlgItem(hWnd, uCtrlID);
ShowWindow(hWndControl, (bEnable) ? SW_SHOW : SW_HIDE);
EnableWindow(hWndControl, bEnable);
}
VOID WINAPI FormatFractionalResults( PTSTR pszFormat, PTSTR pszBuffer, UINT uPart, UINT uTotal )
{
// pszFormat must be at least MAX_STRINGRES TCHARs long
// pszBuffer must be at least MAX_STRINGMSG TCHARs long
if (*pszFormat == 0)
{
LoadString(
g_hModThisDll,
(uTotal == 1) ? IDS_HP_RESULT_FMT : IDS_HP_RESULTS_FMT,
pszFormat,
MAX_STRINGRES
);
}
if (*pszFormat != TEXT('!'))
wnsprintf(pszBuffer, MAX_STRINGMSG, pszFormat, uPart, uTotal);
else
wnsprintf(pszBuffer, MAX_STRINGMSG, pszFormat + 1, uTotal, uPart);
}
VOID WINAPI SetProgressBarPause( PCOMMONCONTEXT pcmnctx, WPARAM iState )
{
// For Windows Classic, we can change the color to indicate a pause
COLORREF clrProgress = (iState == PBST_NORMAL) ? CLR_DEFAULT : RGB(0xFF, 0x80, 0x00);
SendMessage(pcmnctx->hWndPBTotal, PBM_SETBARCOLOR, 0, clrProgress);
SendMessage(pcmnctx->hWndPBFile, PBM_SETBARCOLOR, 0, clrProgress);
// Toggle the marquee animation if applicable
if (pcmnctx->dwFlags & HCF_MARQUEE)
SendMessage(pcmnctx->hWndPBTotal, PBM_SETMARQUEE, iState == PBST_NORMAL, MARQUEE_INTERVAL);
if (g_uWinVer >= 0x0600)
{
// If this is Vista, we can also set the state
SendMessage(pcmnctx->hWndPBTotal, PBM_SETSTATE, iState, 0);
SendMessage(pcmnctx->hWndPBFile, PBM_SETSTATE, iState, 0);
// Vista's progress bar is buggy--if you pause it while it is animating,
// the color will not change (but it will stop animating), so it may
// be necessary to send another PBM_SETSTATE to get it right
SetTimer(pcmnctx->hWnd, TIMER_ID_PAUSE, 750, NULL);
}
}
VOID WINAPI WorkerThreadTogglePause( PCOMMONCONTEXT pcmnctx )
{
if (pcmnctx->status == ACTIVE)
{
if (SuspendThread(pcmnctx->hThread) != THREAD_SUSPEND_ERROR)
{
pcmnctx->status = PAUSED;
if (!(pcmnctx->dwFlags & HCF_EXIT_PENDING))
{
SetControlText(pcmnctx->hWnd, IDC_PAUSE, IDS_HC_RESUME);
SetProgressBarPause(pcmnctx, PBST_PAUSED);
}
}
}
else if (pcmnctx->status == PAUSED)
{
DWORD dwResult;
do
{
dwResult = ResumeThread(pcmnctx->hThread);
} while (dwResult != THREAD_SUSPEND_ERROR && dwResult > 1);
pcmnctx->status = ACTIVE;
if (!(pcmnctx->dwFlags & HCF_EXIT_PENDING))
{
SetControlText(pcmnctx->hWnd, IDC_PAUSE, IDS_HC_PAUSE);
SetProgressBarPause(pcmnctx, PBST_NORMAL);
}
}
}
VOID WINAPI WorkerThreadStop( PCOMMONCONTEXT pcmnctx )
{
if (pcmnctx->status == INACTIVE || pcmnctx->status == CLEANUP_COMPLETED)
return;
// If the thread is paused, unpause it
if (pcmnctx->status == PAUSED)
WorkerThreadTogglePause(pcmnctx);
// Signal cancellation
pcmnctx->status = CANCEL_REQUESTED;
// Disable the control buttons
if (!(pcmnctx->dwFlags & HCF_EXIT_PENDING))
{
EnableWindow(GetDlgItem(pcmnctx->hWnd, IDC_PAUSE), FALSE);
EnableWindow(GetDlgItem(pcmnctx->hWnd, IDC_STOP), FALSE);
}
}
VOID WINAPI WorkerThreadCleanup( PCOMMONCONTEXT pcmnctx )
{
if (pcmnctx->status == CLEANUP_COMPLETED)
return;
// There are only two times this function gets called:
// Case 1: The worker thread has exited on its own, and this function
// was invoked in response to the thread's exit notification.
// Case 2: A forced abort was requested (app exit, system shutdown, etc.),
// where this is called right after calling WorkerThreadStop to signal the
// thread to exit.
if (pcmnctx->hThread)
{
if (pcmnctx->status != INACTIVE)
{
// Forced abort, where the thread has been told to stop but has not yet
// stopped: wait for the thread, but nuke it if it appears to be hanged.
if (WaitForSingleObject(pcmnctx->hThread, 10000) == WAIT_TIMEOUT)
TerminateThread(pcmnctx->hThread, 0);
}
CloseHandle(pcmnctx->hThread);
}
pcmnctx->status = CLEANUP_COMPLETED;
if (!(pcmnctx->dwFlags & HCF_EXIT_PENDING))
{
static const UINT16 arCtrls[] =
{
IDC_PROG_TOTAL,
IDC_PROG_FILE,
IDC_PAUSE,
IDC_STOP
};
UINT i;
for (i = 0; i < countof(arCtrls); ++i)
EnableControl(pcmnctx->hWnd, arCtrls[i], FALSE);
}
}
DWORD WINAPI WorkerThreadStartup( PCOMMONCONTEXT pcmnctx )
{
// Exchange the WORKERTHREADEXTRA member
PFNWORKERMAIN pfnWorkerMain = pcmnctx->ex.pfnWorkerMain;
pcmnctx->ex.pvBuffer = VirtualAlloc(NULL, READ_BUFFER_SIZE, MEM_COMMIT, PAGE_READWRITE);
if (pcmnctx->ex.pvBuffer)
{
pfnWorkerMain(pcmnctx);
VirtualFree(pcmnctx->ex.pvBuffer, 0, MEM_RELEASE);
}
pcmnctx->status = INACTIVE;
if (!(pcmnctx->dwFlags & HCF_EXIT_PENDING))
PostMessage(pcmnctx->hWnd, HM_WORKERTHREAD_DONE, (WPARAM)pcmnctx, 0);
return(0);
}
VOID WINAPI WorkerThreadHashFile( PCOMMONCONTEXT pcmnctx, PCTSTR pszPath, PBOOL pbSuccess,
PWHCTXEX pwhctx, PWHRESULTEX pwhres, PFILESIZE pFileSize )
{
#define GETMSB(ui64) (LODWORD(ui64 >> uShiftBits))
HANDLE hFile;
*pbSuccess = FALSE;
// If the worker thread is working so fast that the UI cannot catch up,
// pause for a bit to let things settle down
while (pcmnctx->cSentMsgs > pcmnctx->cHandledMsgs + 50)
{
Sleep(50);
if (pcmnctx->status == CANCEL_REQUESTED)
return;
}
// Indicate that we want lower-case results (TODO: make this an option)
pwhctx->uCaseMode = WHFMT_LOWERCASE;
if ((hFile = OpenFileForReading(pszPath)) != INVALID_HANDLE_VALUE)
{
ULONGLONG cbFileSize, cbFileRead = 0;
DWORD cbBufferRead;
UINT uShiftBits;
UINT8 cInner = 0;
if (GetFileSizeEx(hFile, (PLARGE_INTEGER)&cbFileSize))
{
// The progress bar is updates only once every 4 buffer reads; if
// the file is small enough that it requires only one such cycle,
// then do not bother with updating the progress bar; this improves
// performance when working with large numbers of small files
BOOL bUpdateProgress = cbFileSize >= READ_BUFFER_SIZE * 4;
// Get the shift factor for the file size; unless the file is 2GiB
// or larger in size, this will always be zero
if ( (uShiftBits = GetHighMSB((PULARGE_INTEGER)&cbFileSize)) ||
((INT)LODWORD(cbFileSize) < 0) )
{
// The progress bar expects a signed integer, so we need to
// ensure that the highest bit is never set
++uShiftBits;
}
// Initialize the file progress bar
if (bUpdateProgress)
PostMessage(pcmnctx->hWndPBFile, PBM_SETRANGE32, 0, GETMSB(cbFileSize));
// If the caller provides a way to return the file size, then set
// the file size and send a SETSIZE notification
if (pFileSize)
{
pFileSize->ui64 = cbFileSize;
StrFormatKBSize(cbFileSize, pFileSize->sz, countof(pFileSize->sz));
PostMessage(pcmnctx->hWnd, HM_WORKERTHREAD_SETSIZE, (WPARAM)pcmnctx, (LPARAM)pFileSize);
}
// Finally, read the file and calculate the checksum; the
// progress bar is updated only once every 4 buffer reads (512K)
WHInitEx(pwhctx);
do // Outer loop: keep going until the end
{
do // Inner loop: break every 4 cycles or if the end is reached
{
if (pcmnctx->status == CANCEL_REQUESTED)
{
CloseHandle(hFile);
return;
}
ReadFile(hFile, pcmnctx->ex.pvBuffer, READ_BUFFER_SIZE, &cbBufferRead, NULL);
WHUpdateEx(pwhctx, pcmnctx->ex.pvBuffer, cbBufferRead);
cbFileRead += cbBufferRead;
} while (cbBufferRead == READ_BUFFER_SIZE && (++cInner & 0x03));
if (bUpdateProgress)
PostMessage(pcmnctx->hWndPBFile, PBM_SETPOS, GETMSB(cbFileRead), 0);
} while (cbBufferRead == READ_BUFFER_SIZE);
WHFinishEx(pwhctx, pwhres);
if (cbFileRead == cbFileSize)
*pbSuccess = TRUE;
if (bUpdateProgress)
PostMessage(pcmnctx->hWndPBFile, PBM_SETPOS, 0, 0);
}
CloseHandle(hFile);
}
}
__forceinline HANDLE WINAPI GetActCtx( HMODULE hModule, PCTSTR pszResourceName )
{
// Wraps away the silliness of CreateActCtx, including the fact that
// it will fail if you do not provide a valid path string even if you
// supply a valid module handle, which is quite silly since the path is
// just going to get translated into a module handle anyway by the API.
ACTCTX ctx;
TCHAR szModule[MAX_PATH << 1];
GetModuleFileName(hModule, szModule, countof(szModule));
ctx.cbSize = sizeof(ctx);
ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
ctx.lpSource = szModule;
ctx.lpResourceName = pszResourceName;
ctx.hModule = hModule;
return(CreateActCtx(&ctx));
}
ULONG_PTR WINAPI ActivateManifest( BOOL bActivate )
{
if (!g_bActCtxCreated)
{
g_bActCtxCreated = TRUE;
g_hActCtx = GetActCtx(g_hModThisDll, MAKEINTRESOURCE(IDR_RT_MANIFEST));
}
if (g_hActCtx != INVALID_HANDLE_VALUE)
{
ULONG_PTR uCookie;
if (!bActivate)
return(1); // Just indicate that we have a good g_hActCtx
else if (ActivateActCtx(g_hActCtx, &uCookie))
return(uCookie);
}
// We can assume that zero is never a valid cookie value...
// * http://support.microsoft.com/kb/830033
// * http://blogs.msdn.com/jonwis/archive/2006/01/12/512405.aspx
return(0);
}
ULONG_PTR __fastcall HostAddRef( )
{
LPUNKNOWN pUnknown;
if (SHGetInstanceExplorer(&pUnknown) == S_OK)
return((ULONG_PTR)pUnknown);
else
return(0);
}
VOID __fastcall HostRelease( ULONG_PTR uCookie )
{
if (uCookie)
{
LPUNKNOWN pUnknown = (LPUNKNOWN)uCookie;
pUnknown->lpVtbl->Release(pUnknown);
}
}