EventLog.cpp 25 KB

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