EventLog.cpp 25 KB

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