EventLogW.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. #include "StdAfx.h"
  2. #include "EventLogW.h"
  3. #include <excpt.h>
  4. #define _U 0x01 /* upper */
  5. #define _L 0x02 /* lower */
  6. #define _D 0x04 /* digit */
  7. #define _C 0x08 /* cntrl */
  8. #define _P 0x10 /* punct */
  9. #define _S 0x20 /* white space (space/lf/tab) */
  10. #define _X 0x40 /* hex digit */
  11. #define _SP 0x80 /* hard space (0x20) */
  12. extern unsigned char _ctype[];
  13. #define isdigit(c) ((_ctype+1)[c]&(_D))
  14. int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep)
  15. {
  16. if(code == EXCEPTION_ACCESS_VIOLATION)
  17. {
  18. return EXCEPTION_EXECUTE_HANDLER;
  19. }
  20. //return EXCEPTION_CONTINUE_SEARCH;
  21. return EXCEPTION_EXECUTE_HANDLER;
  22. }
  23. #ifndef UNICODE
  24. #define UNICODE
  25. #endif
  26. // If the message string contains parameter insertion strings (for example, %%4096),
  27. // you must perform the parameter substitution yourself. To get the parameter message
  28. // string, call FormatMessage with the message identifier found in the parameter insertion
  29. // string (for example, 4096 is the message identifier if the parameter insertion string
  30. // is %%4096). You then substitute the parameter insertion string in the message
  31. // string with the actual parameter message string.
  32. DWORD CEventLogW::ApplyParameterStringsToMessage(
  33. HMODULE hModule,
  34. CONST LPCWSTR pMessage, LPWSTR& pFinalMessage)
  35. {
  36. DWORD status = ERROR_SUCCESS;
  37. DWORD dwParameterCount = 0; // Number of insertion strings found in pMessage
  38. size_t cbBuffer = 0; // Size of the buffer in bytes
  39. size_t cchBuffer = 0; // Size of the buffer in characters
  40. size_t cchParameters = 0; // Number of characters in all the parameter strings
  41. size_t cch = 0;
  42. DWORD i = 0;
  43. LPWSTR* pStartingAddresses = NULL; // Array of pointers to the beginning of each parameter string in pMessage
  44. LPWSTR* pEndingAddresses = NULL; // Array of pointers to the end of each parameter string in pMessage
  45. DWORD* pParameterIDs = NULL; // Array of parameter identifiers found in pMessage
  46. LPWSTR* pParameters = NULL; // Array of the actual parameter strings
  47. LPWSTR pTempMessage = (LPWSTR)pMessage;
  48. LPWSTR pTempFinalMessage = NULL;
  49. // Determine the number of parameter insertion strings in pMessage.
  50. while (pTempMessage = wcschr(pTempMessage, L'%'))
  51. {
  52. pTempMessage++;
  53. //if(isdigit(*pTempMessage))
  54. if ((*pTempMessage) >= L'0' && (*pTempMessage) <= L'9')
  55. {
  56. dwParameterCount++;
  57. }
  58. }
  59. // If there are no parameter insertion strings in pMessage, return.
  60. if (0 == dwParameterCount)
  61. {
  62. pFinalMessage = NULL;
  63. goto cleanup;
  64. }
  65. // Allocate an array of pointers that will contain the beginning address
  66. // of each parameter insertion string.
  67. cbBuffer = sizeof(LPWSTR) * dwParameterCount;
  68. pStartingAddresses = (LPWSTR*)malloc(cbBuffer);
  69. if (NULL == pStartingAddresses)
  70. {
  71. //!!wprintf(L"Failed to allocate memory for pStartingAddresses.\n");
  72. status = ERROR_OUTOFMEMORY;
  73. goto cleanup;
  74. }
  75. RtlZeroMemory(pStartingAddresses, cbBuffer);
  76. // Allocate an array of pointers that will contain the ending address (one
  77. // character past the of the identifier) of the each parameter insertion string.
  78. pEndingAddresses = (LPWSTR*)malloc(cbBuffer);
  79. if (NULL == pEndingAddresses)
  80. {
  81. //!!wprintf(L"Failed to allocate memory for pEndingAddresses.\n");
  82. status = ERROR_OUTOFMEMORY;
  83. goto cleanup;
  84. }
  85. RtlZeroMemory(pEndingAddresses, cbBuffer);
  86. // Allocate an array of pointers that will contain pointers to the actual
  87. // parameter strings.
  88. pParameters = (LPWSTR*)malloc(cbBuffer);
  89. if (NULL == pParameters)
  90. {
  91. //!!wprintf(L"Failed to allocate memory for pEndingAddresses.\n");
  92. status = ERROR_OUTOFMEMORY;
  93. goto cleanup;
  94. }
  95. RtlZeroMemory(pParameters, cbBuffer);
  96. // Allocate an array of DWORDs that will contain the message identifier
  97. // for each parameter.
  98. pParameterIDs = (DWORD*)malloc(cbBuffer);
  99. if (NULL == pParameterIDs)
  100. {
  101. //!!wprintf(L"Failed to allocate memory for pParameterIDs.\n");
  102. status = ERROR_OUTOFMEMORY;
  103. goto cleanup;
  104. }
  105. RtlZeroMemory(pParameterIDs, cbBuffer);
  106. // Find each parameter in pMessage and get the pointer to the
  107. // beginning of the insertion string, the end of the insertion string,
  108. // and the message identifier of the parameter.
  109. pTempMessage = (LPWSTR)pMessage;
  110. while (pTempMessage = wcschr(pTempMessage, L'%'))
  111. {
  112. if ((*(1 + pTempMessage)) >= L'0' && (*(1 + pTempMessage)) <= L'9')
  113. {
  114. pStartingAddresses[i] = pTempMessage;
  115. pTempMessage++;
  116. pParameterIDs[i] = (DWORD)_wtoi(pTempMessage);
  117. while ((*++pTempMessage) >= L'0' && (*pTempMessage) <= L'9')
  118. ;
  119. pEndingAddresses[i] = pTempMessage;
  120. i++;
  121. }
  122. else
  123. {
  124. pTempMessage++;
  125. }
  126. }
  127. // For each parameter, use the message identifier to get the
  128. // actual parameter string.
  129. for (DWORD i = 0; i < dwParameterCount; i++)
  130. {
  131. pParameters[i] = GetMessageString(hModule, pParameterIDs[i], 0, NULL);
  132. if (NULL == pParameters[i])
  133. {
  134. //!!wprintf(L"GetMessageString could not find parameter string for insert %lu.\n", i);
  135. status = ERROR_INVALID_PARAMETER;
  136. goto cleanup;
  137. }
  138. cchParameters += wcslen(pParameters[i]);
  139. }
  140. // Allocate enough memory for pFinalMessage based on the length of pMessage
  141. // and the length of each parameter string. The pFinalMessage buffer will contain
  142. // the completed parameter substitution.
  143. pTempMessage = (LPWSTR)pMessage;
  144. cbBuffer = (wcslen(pMessage) + cchParameters + 1) * sizeof(WCHAR);
  145. pFinalMessage = (LPWSTR)malloc(cbBuffer);
  146. if (NULL == pFinalMessage)
  147. {
  148. //!!wprintf(L"Failed to allocate memory for pFinalMessage.\n");
  149. status = ERROR_OUTOFMEMORY;
  150. goto cleanup;
  151. }
  152. RtlZeroMemory(pFinalMessage, cbBuffer);
  153. cchBuffer = cbBuffer / sizeof(WCHAR);
  154. pTempFinalMessage = pFinalMessage;
  155. // Build the final message string.
  156. for (DWORD i = 0; i < dwParameterCount; i++)
  157. {
  158. // Append the segment from pMessage. In the first iteration, this is L"8 " and in the
  159. // second iteration, this is " = 2 ".
  160. wcsncpy_s(pTempFinalMessage, cchBuffer, pTempMessage, cch = (pStartingAddresses[i] - pTempMessage));
  161. pTempMessage = pEndingAddresses[i];
  162. cchBuffer -= cch;
  163. // Append the parameter string. In the first iteration, this is "quarts" and in the
  164. // second iteration, this is "gallons"
  165. pTempFinalMessage += cch;
  166. wcscpy_s(pTempFinalMessage, cchBuffer, pParameters[i]);
  167. cchBuffer -= cch = wcslen(pParameters[i]);
  168. pTempFinalMessage += cch;
  169. }
  170. // Append the last segment from pMessage, which is ".".
  171. wcscpy_s(pTempFinalMessage, cchBuffer, pTempMessage);
  172. cleanup:
  173. if (ERROR_SUCCESS != status)
  174. //pFinalMessage = (LPWSTR)pMessage;
  175. pFinalMessage = NULL;
  176. if (pStartingAddresses)
  177. free(pStartingAddresses);
  178. if (pEndingAddresses)
  179. free(pEndingAddresses);
  180. if (pParameterIDs)
  181. free(pParameterIDs);
  182. for (DWORD i = 0; i < dwParameterCount; i++)
  183. {
  184. if (pParameters[i])
  185. LocalFree(pParameters[i]);
  186. }
  187. return status;
  188. }
  189. CEventLogW::CEventLogW(void)
  190. :m_hEventLog(NULL)
  191. ,pOutFile(NULL)
  192. {
  193. memset(m_szSourceName, 0, sizeof(WCHAR)*MAX_PATH);
  194. }
  195. CEventLogW::CEventLogW(LPCWSTR lpSrcName, BOOL bCustom)
  196. :m_hEventLog(NULL)
  197. ,pOutFile(NULL)
  198. {
  199. memset(m_szSourceName, 0, sizeof(WCHAR)*MAX_PATH);
  200. Initialize(lpSrcName, bCustom);
  201. }
  202. CEventLogW::~CEventLogW(void)
  203. {
  204. if (m_hEventLog)
  205. CloseEventLog(m_hEventLog);
  206. if(pOutFile)
  207. delete pOutFile;
  208. }
  209. HRESULT CEventLogW::Initialize(LPCWSTR lpSrcName, BOOL bCustom)
  210. {
  211. HRESULT hr = NOERROR;
  212. if (bCustom)
  213. {
  214. m_hEventLog = OpenBackupEventLogW(NULL, lpSrcName);
  215. }
  216. else
  217. {
  218. m_hEventLog = OpenEventLogW(NULL, lpSrcName);
  219. }
  220. if(m_hEventLog == NULL)
  221. {
  222. hr = HRESULT_FROM_WIN32(GetLastError());
  223. }
  224. else
  225. {
  226. memset(m_szSourceName, 0, sizeof(WCHAR)*MAX_PATH);
  227. wcscpy_s(m_szSourceName, lpSrcName);
  228. }
  229. return hr;
  230. }
  231. DWORD CEventLogW::FilterEventLog(
  232. LPCWSTR lpszSourceName,
  233. WORD wEventType,
  234. DWORD dwEventID,
  235. DWORD dwStartTime,
  236. DWORD dwEndTime)
  237. {
  238. if(m_hEventLog == NULL)
  239. return 0;
  240. DWORD dwEntries = 0;
  241. BOOL bEnough = FALSE;
  242. DWORD dwStartTick = GetTickCount();
  243. if(pOutFile) {
  244. SYSTEMTIME st, stLocal;
  245. GetSystemTime(&st);
  246. SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
  247. WCHAR strTimeInfo[MAX_PATH] = {0};
  248. swprintf_s(strTimeInfo, L"生成时间:%d\\%02d\\%02d %02d:%02d:%02d.%03d\r\n",
  249. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  250. stLocal.wHour, stLocal.wMinute, stLocal.wSecond, stLocal.wMilliseconds);
  251. pOutFile->WriteEventLogEntry(std::wstring(strTimeInfo));
  252. std::wstring strTitle;
  253. strTitle.append(L"级别\t日期和时间\t来源\t事件 ID\t任务类别\t事件内容\r\n");
  254. pOutFile->WriteEventLogEntry(strTitle);
  255. }
  256. DWORD status = ERROR_SUCCESS;
  257. DWORD dwBytesToRead = 0;
  258. DWORD dwBytesRead = 0;
  259. DWORD dwMinimumBytesToRead = 0;
  260. PBYTE pBuffer = NULL;
  261. PBYTE pTemp = NULL;
  262. dwBytesToRead = MAX_RECORD_BUFFER_SIZE;
  263. pBuffer = (PBYTE)malloc(dwBytesToRead);
  264. if (NULL == pBuffer)
  265. {
  266. //!!wprintf(L"Failed to allocate the initial memory for the record buffer.");
  267. return 0;
  268. }
  269. while (ERROR_SUCCESS == status && !bEnough)
  270. {
  271. if (!ReadEventLogW(m_hEventLog, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ,
  272. 0, pBuffer, dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
  273. {
  274. status = GetLastError();
  275. if (ERROR_INSUFFICIENT_BUFFER == status)
  276. {
  277. status = ERROR_SUCCESS;
  278. pTemp = (PBYTE)realloc(pBuffer, dwMinimumBytesToRead);
  279. if (NULL == pTemp)
  280. {
  281. //!!wprintf(L"Failed to reallocate the memory for the record buffer (%d bytes).\n",dwMinimumBytesToRead);
  282. return 0;
  283. }
  284. pBuffer = pTemp;
  285. dwBytesToRead = dwMinimumBytesToRead;
  286. }
  287. else
  288. {
  289. if (ERROR_HANDLE_EOF != status)
  290. {
  291. //!!wprintf(L"ReadEventLogW failed with %lu.\n", status);
  292. if (pBuffer) {
  293. free(pBuffer);
  294. pBuffer = NULL;
  295. }
  296. return 0;
  297. }
  298. }
  299. }
  300. else
  301. {
  302. PBYTE pRecord = pBuffer;
  303. PBYTE pEndOfRecords = pBuffer + dwBytesRead;
  304. WCHAR TimeStamp[MAX_TIMESTAMP_LEN];
  305. while (pRecord < pEndOfRecords)
  306. {
  307. PEVENTLOGRECORD pELR = (PEVENTLOGRECORD)pRecord;
  308. BOOL bAcceptance = TRUE;
  309. if(bAcceptance && lpszSourceName != NULL && wcslen(lpszSourceName) > 0) {
  310. bAcceptance = !wcscmp(lpszSourceName, (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)));
  311. }
  312. if(bAcceptance && wEventType != 0) {
  313. bAcceptance = (wEventType & pELR->EventType);
  314. }
  315. if(bAcceptance && dwEventID != 0) {
  316. bAcceptance = (dwEventID == (pELR->EventID & 0xFFFF));
  317. }
  318. if(bAcceptance && dwStartTime != 0 && (dwStartTime <= dwEndTime)) {
  319. bAcceptance = (dwStartTime <= pELR->TimeGenerated && pELR->TimeGenerated <= dwEndTime);
  320. if(!bAcceptance && pELR->TimeGenerated < dwStartTime)
  321. bEnough = TRUE;
  322. }
  323. if(bAcceptance)
  324. {
  325. dwEntries++;
  326. std::wostringstream ostr;
  327. if((pELR->EventID & 0xFFFF) == 4625
  328. && !wcscmp(L"Microsoft-Windows-Security-Auditing",
  329. (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)))) {
  330. //!!wprintf(L"Here !");
  331. }
  332. //!!wprintf(L"EventType: %ls ", pEventTypeNames[GetEventTypeNameW(pELR->EventType)]);
  333. ostr << pEventTypeNames[GetEventTypeNameW(pELR->EventType)] << L"\t";
  334. SYSTEMTIME stTime;
  335. GetTimestamp(pELR->TimeGenerated, &stTime, TimeStamp);
  336. //!!wprintf(L"%ls ", TimeStamp);
  337. ostr << TimeStamp << L"\t";
  338. ////!!wprintf(L"RecordNumber: %8lu ", pELR->RecordNumber);
  339. //!!wprintf(L"Source: %ls ", (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)));
  340. ostr << (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)) << L"\t";
  341. //!!wprintf(L"EventID: %8d ", pELR->EventID & 0xFFFF);
  342. ostr << std::setw(8) << (pELR->EventID & 0xFFFF);
  343. WCHAR szKeyName[MAX_PATH + 1];
  344. WCHAR szExeFile[MAX_PATH + 1];
  345. WCHAR szExeFilePath[MAX_PATH + 1];
  346. swprintf(szKeyName, REG_FULLFILL_KEY, m_szSourceName,
  347. (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)));
  348. HKEY hKey = NULL;
  349. DWORD dwMaxPath = MAX_PATH + 1;
  350. DWORD dwType;
  351. HMODULE hModule = NULL;
  352. if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKeyName, 0L, KEY_READ, &hKey) == NOERROR)
  353. {
  354. if(RegQueryValueExW(hKey, EVENT_MESSAGE_FILE,
  355. NULL, &dwType, (LPBYTE)szExeFile, &dwMaxPath) == NOERROR)
  356. {
  357. if(ExpandEnvironmentStringsW(szExeFile, szExeFilePath, MAX_PATH + 1) == 0)
  358. wcscpy_s(szExeFilePath, szExeFile);
  359. //WCHAR *current = szExeFilePath, *next;
  360. //while (current)
  361. //{
  362. // next = wcschr(current, L';');
  363. // if (next)
  364. // {
  365. // *next = L'\0';
  366. // next++;
  367. // }
  368. //}
  369. hModule = GetMessageResources(szExeFilePath);
  370. if(hModule)
  371. {
  372. //!!wprintf(L"GetMessageString about category");
  373. LPWSTR pMessageCategory = GetMessageString(hModule, pELR->EventCategory, 0, NULL);
  374. if (pMessageCategory)
  375. {
  376. //!!wprintf(L"EventCategory: %ls ", pMessageCategory);
  377. ostr << L"\t" << pMessageCategory;
  378. LocalFree(pMessageCategory);
  379. pMessageCategory = NULL;
  380. }
  381. //!!wprintf(L"GetMessageString about EventMessage");
  382. LPWSTR pMessage = NULL;
  383. pMessage = GetMessageString(hModule, pELR->EventID,
  384. pELR->NumStrings, (LPWSTR)(pRecord + pELR->StringOffset));
  385. if (pMessage)
  386. {
  387. LPWSTR pFinalMessage = NULL;
  388. DWORD status = ApplyParameterStringsToMessage(hModule,
  389. pMessage, pFinalMessage);
  390. //!!wprintf(L"\nEventMessage: %ls", (pFinalMessage) ? pFinalMessage : pMessage);
  391. std::wstring strTemp(
  392. (pFinalMessage) ? (LPCWSTR)pFinalMessage : (LPCWSTR)pMessage);
  393. ostr << L"\t" << strTemp;
  394. if(pFinalMessage && pFinalMessage != pMessage) {
  395. free(pFinalMessage);
  396. pFinalMessage = NULL;
  397. }
  398. LocalFree(pMessage);
  399. pMessage = NULL;
  400. }
  401. //!!wprintf(L"Finished routine");
  402. }
  403. }
  404. }
  405. #if 0
  406. if (/*pELR->DataLength > 0*/FALSE)
  407. {
  408. PBYTE pData = NULL;
  409. PBYTE pStrings = NULL;
  410. UINT uStringOffset;
  411. WCHAR* szExpandedString;
  412. pData = (PBYTE)malloc(pELR->DataLength*sizeof(BYTE));
  413. pStrings = (PBYTE)malloc(pELR->DataOffset-pELR->StringOffset * sizeof(BYTE));
  414. DWORD dwExpandStringLen = pELR->DataOffset-pELR->StringOffset + 1024;
  415. szExpandedString = (WCHAR*)malloc((dwExpandStringLen)*sizeof(WCHAR));
  416. if(pData == NULL || pStrings == NULL || szExpandedString == NULL)
  417. {
  418. //!!wprintf(L"Failed to reallocate the memory for the event data.\n");
  419. if(pData) free(pData);
  420. if(pStrings) free(pStrings);
  421. if(szExpandedString) free(szExpandedString);
  422. if (pBuffer) free(pBuffer);
  423. return 0;
  424. }
  425. memcpy(pData, pRecord + pELR->DataOffset, pELR->DataLength);
  426. memcpy(pStrings,(PBYTE)pELR + pELR->StringOffset, pELR->DataOffset-pELR->StringOffset);
  427. UINT x, uStepOfString = 0;
  428. for(x=0; x<pELR->NumStrings; ++x)
  429. {
  430. if(x == 0)
  431. {
  432. wcscpy_s(szExpandedString, dwExpandStringLen, (WCHAR*)pStrings+uStepOfString);
  433. if(x < (UINT)pELR->NumStrings - 1)
  434. wcscat_s(szExpandedString, dwExpandStringLen, L",");
  435. }
  436. else
  437. {
  438. wcscat_s(szExpandedString, dwExpandStringLen, (WCHAR*)pStrings + uStepOfString);
  439. }
  440. uStepOfString = wcslen((WCHAR*)pStrings+uStepOfString) + 1;
  441. }
  442. if(hModule)
  443. {
  444. WCHAR** _sz = (WCHAR**)malloc((pELR->NumStrings)*sizeof(WCHAR*));
  445. uStringOffset = 0;
  446. DWORD dwZlen = 0;
  447. register UINT z;
  448. for(z=0; z<pELR->NumStrings; ++z)
  449. {
  450. dwZlen = wcslen((WCHAR*)pStrings+uStringOffset) + 1;
  451. _sz[z] = (WCHAR*)malloc((dwZlen)* sizeof(WCHAR));
  452. if(_sz[z] != NULL)
  453. {
  454. wcscpy_s(_sz[z], dwZlen, (WCHAR*)pStrings + uStringOffset);
  455. uStringOffset += wcslen((WCHAR *)pStrings + uStringOffset) + 1;
  456. }
  457. }
  458. LPVOID lpszBuffer = 0;
  459. FormatMessageW(
  460. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  461. FORMAT_MESSAGE_FROM_HMODULE |
  462. FORMAT_MESSAGE_FROM_SYSTEM |
  463. FORMAT_MESSAGE_ARGUMENT_ARRAY,
  464. hModule, pELR->EventID, 0, (LPWSTR)&lpszBuffer, 1024,
  465. _sz
  466. );
  467. for(z=0; _sz != NULL && z<pELR->NumStrings; ++z)
  468. {
  469. if(_sz[z] != NULL)
  470. {
  471. free(_sz[z]);
  472. _sz[z] = NULL;
  473. }
  474. }
  475. if(_sz != NULL)
  476. {
  477. free(_sz);
  478. _sz = NULL;
  479. }
  480. if(lpszBuffer)
  481. {
  482. wcscpy_s(szExpandedString, dwExpandStringLen, (WCHAR *)lpszBuffer);
  483. uStringOffset = wcslen(szExpandedString);
  484. }
  485. if(lpszBuffer)
  486. {
  487. LocalFree(lpszBuffer);
  488. }
  489. }
  490. //!!wprintf(L"\nEventData: %ls", szExpandedString);
  491. if(szExpandedString) free(szExpandedString);
  492. if(pData) free(pData);
  493. if(pStrings) free(pStrings);
  494. }
  495. #endif
  496. if(hKey)
  497. {
  498. RegCloseKey(hKey);
  499. hKey = NULL;
  500. }
  501. if(hModule != NULL)
  502. {
  503. FreeLibrary(hModule);
  504. hModule = NULL;
  505. }
  506. if(pOutFile)
  507. pOutFile->WriteEventLogEntry(ostr.str());
  508. //!!wprintf(L"\n");
  509. }
  510. if(bEnough) {
  511. //!!wprintf(L"Discover its enough, abort and break !\n");
  512. break;
  513. }
  514. pRecord += pELR->Length;
  515. }
  516. }
  517. }
  518. if(pBuffer) {
  519. free(pBuffer);
  520. pBuffer = NULL;
  521. }
  522. if(pOutFile) {
  523. WCHAR strTimeInfo[MAX_PATH] = {0};
  524. DWORD dwDuration = GetTickCount() - dwStartTick;
  525. DWORD dwSplit = dwDuration / 1000; //s
  526. if(dwDuration / 1000 / 60 > 60) {
  527. DWORD dwSplit2 = dwSplit / 60 / 60;
  528. swprintf_s(strTimeInfo, L"\r\n\t耗时:%d h:%02d m:%02d s .%03d ms",
  529. dwSplit2, (dwSplit - dwSplit2 * 60 * 60) % 60, dwSplit % 60, dwDuration % 1000);
  530. }else if(dwDuration / 1000 > 60) {
  531. swprintf_s(strTimeInfo, L"\r\n\t耗时:%02d m:%02d s .%03d ms",
  532. dwSplit/60, dwSplit%60, dwDuration % 1000);
  533. }else {
  534. swprintf_s(strTimeInfo, L"\r\n\t耗时:%02d s .%03d ms", dwSplit, dwDuration % 1000);
  535. }
  536. pOutFile->WriteEventLogEntry(std::wstring(strTimeInfo));
  537. memset(strTimeInfo, 0, sizeof(strTimeInfo));
  538. swprintf_s(strTimeInfo, L"\t共记录 %u 条 %ls 事件日志\r\n", dwEntries, m_szSourceName);
  539. pOutFile->WriteEventLogEntry(std::wstring(strTimeInfo));
  540. pOutFile->WriteEventLogEntry(std::wstring(L"\t筛选条件:"));
  541. if(lpszSourceName != NULL && wcslen(lpszSourceName) > 0) {
  542. pOutFile->WriteEventLogEntry(std::wstring(L"\t来源: ") + lpszSourceName);
  543. }
  544. if(wEventType != 0) {
  545. std::wstring strEventType(L"\t类型:");
  546. if(wEventType & EVENTLOG_ERROR_TYPE) {
  547. strEventType.append(L" ");
  548. strEventType.append(pEventTypeNames[0]);
  549. }
  550. if(wEventType & EVENTLOG_WARNING_TYPE) {
  551. strEventType.append(L" ");
  552. strEventType.append(pEventTypeNames[1]);
  553. }
  554. if(wEventType & EVENTLOG_INFORMATION_TYPE) {
  555. strEventType.append(L" ");
  556. strEventType.append(pEventTypeNames[2]);
  557. }
  558. if(wEventType & EVENTLOG_AUDIT_SUCCESS) {
  559. strEventType.append(L" ");
  560. strEventType.append(pEventTypeNames[3]);
  561. }
  562. if(wEventType & EVENTLOG_AUDIT_FAILURE) {
  563. strEventType.append(L" ");
  564. strEventType.append(pEventTypeNames[4]);
  565. }
  566. pOutFile->WriteEventLogEntry(strEventType);
  567. }
  568. if(dwEventID != 0) {
  569. WCHAR szEventID[20] = {0};
  570. swprintf_s(szEventID, L"%u", dwEventID);
  571. pOutFile->WriteEventLogEntry(std::wstring(L"\t事件 ID: ") + szEventID);
  572. }
  573. if(dwStartTime != 0 && (dwStartTime <= dwEndTime)) {
  574. WCHAR TimeStart[MAX_TIMESTAMP_LEN];
  575. WCHAR TimeEnd[MAX_TIMESTAMP_LEN];
  576. SYSTEMTIME stTime;
  577. GetTimestamp(dwStartTime, &stTime, TimeStart);
  578. GetTimestamp(dwEndTime, &stTime, TimeEnd);
  579. pOutFile->WriteEventLogEntry(std::wstring(L"\t记录时间: ") + TimeStart + L" - " + TimeEnd);
  580. }
  581. pOutFile->WriteEventLogEntry(L"\r\n");
  582. }
  583. return dwEntries;
  584. }
  585. // Get the last record number in the log file and read it.
  586. // This positions the cursor, so that we can begin reading
  587. // new records when the service notifies us that new records were
  588. // written to the log file.
  589. DWORD CEventLogW::SeekToLastRecord()
  590. {
  591. DWORD status = ERROR_SUCCESS;
  592. DWORD dwLastRecordNumber = 0;
  593. PBYTE pRecord = NULL;
  594. status = GetLastRecordNumber(&dwLastRecordNumber);
  595. if (ERROR_SUCCESS != status)
  596. {
  597. //!!wprintf(L"GetLastRecordNumber failed.\n");
  598. goto cleanup;
  599. }
  600. status = ReadSingleRecord(pRecord, dwLastRecordNumber, EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ);
  601. if (ERROR_SUCCESS != status)
  602. {
  603. //!!wprintf(L"ReadRecord failed seeking to record %lu.\n", dwLastRecordNumber);
  604. goto cleanup;
  605. }
  606. cleanup:
  607. if (pRecord)
  608. free(pRecord);
  609. return status;
  610. }
  611. // Get the record number to the last record in the log file.
  612. DWORD CEventLogW::GetLastRecordNumber(DWORD* pdwRecordNumber)
  613. {
  614. DWORD status = ERROR_SUCCESS;
  615. DWORD OldestRecordNumber = 0;
  616. DWORD NumberOfRecords = 0;
  617. if (!GetOldestEventLogRecord(m_hEventLog, &OldestRecordNumber))
  618. {
  619. //!!wprintf(L"GetOldestEventLogRecord failed with %lu.\n", status = GetLastError());
  620. goto cleanup;
  621. }
  622. if (!GetNumberOfEventLogRecords(m_hEventLog, &NumberOfRecords))
  623. {
  624. //!!wprintf(L"GetOldestEventLogRecord failed with %lu.\n", status = GetLastError());
  625. goto cleanup;
  626. }
  627. *pdwRecordNumber = OldestRecordNumber + NumberOfRecords - 1;
  628. cleanup:
  629. return status;
  630. }
  631. // Read a single record from the event log.
  632. DWORD CEventLogW::ReadSingleRecord(PBYTE & pBuffer, DWORD dwRecordNumber, DWORD dwReadFlags)
  633. {
  634. DWORD status = ERROR_SUCCESS;
  635. DWORD dwBytesToRead = sizeof(EVENTLOGRECORD);
  636. DWORD dwBytesRead = 0;
  637. DWORD dwMinimumBytesToRead = 0;
  638. PBYTE pTemp = NULL;
  639. // The initial size of the buffer is not big enough to read a record, but ReadEventLog
  640. // requires a valid pointer. The ReadEventLog function will fail and return the required
  641. // buffer size; reallocate the buffer to the required size.
  642. pBuffer= (PBYTE)malloc(sizeof(EVENTLOGRECORD));
  643. // Get the required buffer size, reallocate the buffer and then read the event record.
  644. if (!ReadEventLogW(m_hEventLog, dwReadFlags, dwRecordNumber, pBuffer,
  645. dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
  646. {
  647. status = GetLastError();
  648. if (ERROR_INSUFFICIENT_BUFFER == status)
  649. {
  650. status = ERROR_SUCCESS;
  651. pTemp = (PBYTE)realloc(pBuffer, dwMinimumBytesToRead);
  652. if (NULL == pTemp)
  653. {
  654. //!!wprintf(L"Failed to reallocate memory for the record buffer (%d bytes).\n", dwMinimumBytesToRead);
  655. goto cleanup;
  656. }
  657. pBuffer = pTemp;
  658. dwBytesToRead = dwMinimumBytesToRead;
  659. if (!ReadEventLogW(m_hEventLog, dwReadFlags,
  660. dwRecordNumber, pBuffer, dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
  661. {
  662. //!!wprintf(L"Second ReadEventLogW failed with %lu.\n", status = GetLastError());
  663. goto cleanup;
  664. }
  665. }
  666. else
  667. {
  668. if (ERROR_HANDLE_EOF != status)
  669. {
  670. //!!wprintf(L"ReadEventLogW failed with %lu.\n", status);
  671. goto cleanup;
  672. }
  673. }
  674. }
  675. cleanup:
  676. return status;
  677. }
  678. // Formats the specified message. If the message uses inserts, build
  679. // the argument list to pass to FormatMessage.
  680. LPWSTR CEventLogW::GetMessageString(HMODULE hModule, DWORD MessageId, DWORD argc, LPWSTR argv)
  681. {
  682. LPWSTR pMessage = NULL;
  683. DWORD dwFormatFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE
  684. | FORMAT_MESSAGE_ALLOCATE_BUFFER;
  685. DWORD_PTR* pArgs = NULL;
  686. LPWSTR pString = argv;
  687. DWORD dwRes = ERROR_SUCCESS;
  688. // The insertion strings appended to the end of the event record
  689. // are an array of strings; however, FormatMessage requires
  690. // an array of addresses. Create an array of DWORD_PTRs based on
  691. // the count of strings. Assign the address of each string
  692. // to an element in the array (maintaining the same order).
  693. if (argc > 0)
  694. {
  695. pArgs = (DWORD_PTR*)malloc(sizeof(DWORD_PTR) * argc);
  696. if (pArgs)
  697. {
  698. dwFormatFlags |= FORMAT_MESSAGE_ARGUMENT_ARRAY;
  699. for (DWORD i = 0; i < argc; i++)
  700. {
  701. pArgs[i] = (DWORD_PTR)pString;
  702. pString += wcslen(pString) + 1;
  703. }
  704. }
  705. else
  706. {
  707. dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
  708. //!!wprintf(L"Failed to allocate memory for the insert string array.\n");
  709. }
  710. }
  711. // if FormatMessageW is called without FORMAT_MESSAGE_IGNORE_INSERTS, the pArgs must contain enough
  712. // parameters to satisfy all insertion sequences in the message string and they must be of the correct
  713. // type. stackflow.com/22518746 -Josephus@2017720 11:03:35
  714. //dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
  715. DWORD dwCount = 0;
  716. __try
  717. {
  718. dwCount = FormatMessageW(dwFormatFlags, hModule, MessageId,
  719. 0, (LPWSTR)&pMessage, 0, (va_list*)pArgs);
  720. }
  721. __except(filter(GetExceptionCode(), GetExceptionInformation()))
  722. {
  723. dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
  724. dwCount = FormatMessageW(dwFormatFlags, hModule, MessageId,
  725. 0, (LPWSTR)&pMessage, 0, (va_list*)pArgs);
  726. }
  727. if (pArgs)
  728. free(pArgs);
  729. if (dwCount == 0)
  730. {
  731. //!!wprintf(L"Format message failed with %lu\n", GetLastError());
  732. }
  733. //if(pMessage != NULL)
  734. //{
  735. // size_t MsgLen = wcslen((LPCWSTR)pMessage);
  736. // if(MsgLen > 0) {
  737. // if(MsgLen >= 2 && pMessage[MsgLen-1] == L'\n' && pMessage[MsgLen-2] == L'\r') pMessage[MsgLen-2] = L'\0';
  738. // if(MsgLen >= 1 && pMessage[MsgLen-1] == L'\n') pMessage[MsgLen-1] = L'\0';
  739. // }
  740. //}
  741. return pMessage;
  742. }
  743. void CEventLogW::GetTimestamp(const DWORD Time, PSYSTEMTIME stTime, WCHAR DisplayString[])
  744. {
  745. ULONGLONG ullTimeStamp = 0;
  746. ULONGLONG SecsTo1970 = 116444736000000000;
  747. SYSTEMTIME st;
  748. FILETIME ft, ftLocal;
  749. ullTimeStamp = Int32x32To64(Time, 10000000) + SecsTo1970;
  750. ft.dwHighDateTime = (DWORD)((ullTimeStamp >> 32) & 0xFFFFFFFF);
  751. ft.dwLowDateTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  752. FileTimeToLocalFileTime(&ft, &ftLocal);
  753. FileTimeToSystemTime(&ftLocal, &st);
  754. StringCchPrintfW(DisplayString, MAX_TIMESTAMP_LEN, L"%04d/%02d/%02d %.2d:%.2d:%.2d",
  755. st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
  756. if(stTime != NULL) {
  757. //SystemTimeToTzSpecificLocalTime(NULL, &st, stTime);
  758. *stTime = st;
  759. }
  760. return;
  761. }