EventLogW.cpp 25 KB

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