123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814 |
- #include "stdafx.h"
- #include "EventLog.h"
- #include "Spbase.h"
- unsigned char _ctype[] = {0x00, /* EOF */
- _C,_C,_C,_C,_C,_C,_C,_C, /* 0-7 */
- _C,_C|_S,_C|_S,_C|_S,_C|_S,_C|_S,_C,_C, /* 8-15 */
- _C,_C,_C,_C,_C,_C,_C,_C, /* 16-23 */
- _C,_C,_C,_C,_C,_C,_C,_C, /* 24-31 */
- _S|_SP,_P,_P,_P,_P,_P,_P,_P, /* 32-39 */
- _P,_P,_P,_P,_P,_P,_P,_P, /* 40-47 */
- _D,_D,_D,_D,_D,_D,_D,_D, /* 48-55 */
- _D,_D,_P,_P,_P,_P,_P,_P, /* 56-63 */
- _P,_U|_X,_U|_X,_U|_X,_U|_X,_U|_X,_U|_X,_U, /* 64-71 */
- _U,_U,_U,_U,_U,_U,_U,_U, /* 72-79 */
- _U,_U,_U,_U,_U,_U,_U,_U, /* 80-87 */
- _U,_U,_U,_P,_P,_P,_P,_P, /* 88-95 */
- _P,_L|_X,_L|_X,_L|_X,_L|_X,_L|_X,_L|_X,_L, /* 96-103 */
- _L,_L,_L,_L,_L,_L,_L,_L, /* 104-111 */
- _L,_L,_L,_L,_L,_L,_L,_L, /* 112-119 */
- _L,_L,_L,_P,_P,_P,_P,_C, /* 120-127 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 128-143 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 144-159 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 160-175 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 176-191 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 192-207 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 208-223 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 224-239 */
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* 240-255 */
- // If the message string contains parameter insertion strings (for example, %%4096),
- // you must perform the parameter substitution yourself. To get the parameter message
- // string, call FormatMessage with the message identifier found in the parameter insertion
- // string (for example, 4096 is the message identifier if the parameter insertion string
- // is %%4096). You then substitute the parameter insertion string in the message
- // string with the actual parameter message string.
- DWORD CEventLog::ApplyParameterStringsToMessage(
- HMODULE hModule,
- CONST LPCTSTR pMessage, LPTSTR& pFinalMessage)
- {
- DWORD status = ERROR_SUCCESS;
- DWORD dwParameterCount = 0; // Number of insertion strings found in pMessage
- size_t cbBuffer = 0; // Size of the buffer in bytes
- size_t cchBuffer = 0; // Size of the buffer in characters
- size_t cchParameters = 0; // Number of characters in all the parameter strings
- size_t cch = 0;
- DWORD i = 0;
- LPTSTR* pStartingAddresses = NULL; // Array of pointers to the beginning of each parameter string in pMessage
- LPTSTR* pEndingAddresses = NULL; // Array of pointers to the end of each parameter string in pMessage
- DWORD* pParameterIDs = NULL; // Array of parameter identifiers found in pMessage
- LPTSTR* pParameters = NULL; // Array of the actual parameter strings
- LPTSTR pTempMessage = (LPTSTR)pMessage;
- LPTSTR pTempFinalMessage = NULL;
- // Determine the number of parameter insertion strings in pMessage.
- while (pTempMessage = strchr(pTempMessage, '%'))
- {
- pTempMessage++;
- if(isdigit(*pTempMessage))
- {
- dwParameterCount++;
- }
- }
- // If there are no parameter insertion strings in pMessage, return.
- if (0 == dwParameterCount)
- {
- pFinalMessage = NULL;
- goto cleanup;
- }
- // Allocate an array of pointers that will contain the beginning address
- // of each parameter insertion string.
- cbBuffer = sizeof(LPTSTR) * dwParameterCount;
- pStartingAddresses = (LPTSTR*)malloc(cbBuffer);
- if (NULL == pStartingAddresses)
- {
- //!!printf("Failed to allocate memory for pStartingAddresses.\n");
- status = ERROR_OUTOFMEMORY;
- goto cleanup;
- }
- RtlZeroMemory(pStartingAddresses, cbBuffer);
- // Allocate an array of pointers that will contain the ending address (one
- // character past the of the identifier) of the each parameter insertion string.
- pEndingAddresses = (LPTSTR*)malloc(cbBuffer);
- if (NULL == pEndingAddresses)
- {
- //!!printf("Failed to allocate memory for pEndingAddresses.\n");
- status = ERROR_OUTOFMEMORY;
- goto cleanup;
- }
- RtlZeroMemory(pEndingAddresses, cbBuffer);
- // Allocate an array of pointers that will contain pointers to the actual
- // parameter strings.
- pParameters = (LPTSTR*)malloc(cbBuffer);
- if (NULL == pParameters)
- {
- //!!printf("Failed to allocate memory for pEndingAddresses.\n");
- status = ERROR_OUTOFMEMORY;
- goto cleanup;
- }
- RtlZeroMemory(pParameters, cbBuffer);
- // Allocate an array of DWORDs that will contain the message identifier
- // for each parameter.
- pParameterIDs = (DWORD*)malloc(cbBuffer);
- if (NULL == pParameterIDs)
- {
- //!!printf("Failed to allocate memory for pParameterIDs.\n");
- status = ERROR_OUTOFMEMORY;
- goto cleanup;
- }
- RtlZeroMemory(pParameterIDs, cbBuffer);
- // Find each parameter in pMessage and get the pointer to the
- // beginning of the insertion string, the end of the insertion string,
- // and the message identifier of the parameter.
- pTempMessage = (LPTSTR)pMessage;
- while (pTempMessage = strchr(pTempMessage, '%'))
- {
- if (isdigit(*(pTempMessage+1)))
- {
- pStartingAddresses[i] = pTempMessage;
- pTempMessage++;
- pParameterIDs[i] = (DWORD)atoi(pTempMessage);
- while (isdigit(*++pTempMessage))
- ;
- pEndingAddresses[i] = pTempMessage;
- i++;
- }
- else
- {
- pTempMessage++;
- }
- }
- // For each parameter, use the message identifier to get the
- // actual parameter string.
- for (DWORD i = 0; i < dwParameterCount; i++)
- {
- pParameters[i] = GetMessageString(hModule, pParameterIDs[i], 0, NULL);
- if (NULL == pParameters[i])
- {
- //!!printf("GetMessageString could not find parameter string for insert %lu.\n", i);
- status = ERROR_INVALID_PARAMETER;
- goto cleanup;
- }
- cchParameters += strlen(pParameters[i]);
- }
- // Allocate enough memory for pFinalMessage based on the length of pMessage
- // and the length of each parameter string. The pFinalMessage buffer will contain
- // the completed parameter substitution.
- pTempMessage = (LPTSTR)pMessage;
- cbBuffer = (strlen(pMessage) + cchParameters + 1) * sizeof(CHAR);
- pFinalMessage = (LPTSTR)malloc(cbBuffer);
- if (NULL == pFinalMessage)
- {
- //!!printf("Failed to allocate memory for pFinalMessage.\n");
- status = ERROR_OUTOFMEMORY;
- goto cleanup;
- }
- RtlZeroMemory(pFinalMessage, cbBuffer);
- cchBuffer = cbBuffer / sizeof(CHAR);
- pTempFinalMessage = pFinalMessage;
- // Build the final message string.
- for (DWORD i = 0; i < dwParameterCount; i++)
- {
- // Append the segment from pMessage. In the first iteration, this is "8 " and in the
- // second iteration, this is " = 2 ".
- strncpy_s(pTempFinalMessage, cchBuffer, pTempMessage, cch = (pStartingAddresses[i] - pTempMessage));
- pTempMessage = pEndingAddresses[i];
- cchBuffer -= cch;
- // Append the parameter string. In the first iteration, this is "quarts" and in the
- // second iteration, this is "gallons"
- pTempFinalMessage += cch;
- strcpy_s(pTempFinalMessage, cchBuffer, pParameters[i]);
- cchBuffer -= cch = strlen(pParameters[i]);
- pTempFinalMessage += cch;
- }
- // Append the last segment from pMessage, which is ".".
- strcpy_s(pTempFinalMessage, cchBuffer, pTempMessage);
- cleanup:
- if (ERROR_SUCCESS != status)
- pFinalMessage = (LPTSTR)pMessage;
- if (pStartingAddresses)
- free(pStartingAddresses);
- if (pEndingAddresses)
- free(pEndingAddresses);
- if (pParameterIDs)
- free(pParameterIDs);
- for (DWORD i = 0; i < dwParameterCount; i++)
- {
- if (pParameters[i])
- LocalFree(pParameters[i]);
- }
- return status;
- }
- CEventLog::CEventLog(void)
- :m_hEventLog(NULL)
- ,pOutFile(NULL)
- {
- memset(m_szSourceName, 0, sizeof(CHAR)*MAX_PATH);
- }
- CEventLog::CEventLog(LPCTSTR lpSrcName)
- :m_hEventLog(NULL)
- ,pOutFile(NULL)
- {
- memset(m_szSourceName, 0, sizeof(CHAR)*MAX_PATH);
- Initialize(lpSrcName);
- }
- CEventLog::~CEventLog(void)
- {
- if (m_hEventLog)
- CloseEventLog(m_hEventLog);
- if(pOutFile)
- delete pOutFile;
- }
- HRESULT CEventLog::Initialize(LPCTSTR lpSrcName)
- {
- HRESULT hr = NOERROR;
- m_hEventLog = OpenEventLog(NULL, lpSrcName);
- if(m_hEventLog == NULL)
- {
- hr = HRESULT_FROM_WIN32(GetLastError());
- }
- else
- {
- memset(m_szSourceName, 0, sizeof(CHAR)*MAX_PATH);
- strcpy_s(m_szSourceName, lpSrcName);
- }
- return hr;
- }
- DWORD CEventLog::FilterEventLog(
- LPCTSTR lpszSourceName,
- WORD wEventType,
- DWORD dwEventID,
- DWORD dwStartTime,
- DWORD dwEndTime)
- {
- if(m_hEventLog == NULL)
- return 0;
- DWORD dwEntries = 0;
- BOOL bEnough = FALSE;
- DWORD dwStartTick = GetTickCount();
- if(pOutFile) {
- SYSTEMTIME st, stLocal;
- GetSystemTime(&st);
- SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
- CHAR strTimeInfo[MAX_PATH] = {0};
- sprintf_s(strTimeInfo, "生成时间:%d\\%02d\\%02d %02d:%02d:%02d.%03d",
- stLocal.wYear, stLocal.wMonth, stLocal.wDay,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond, stLocal.wMilliseconds);
- pOutFile->WriteEventLogEntry(std::string(strTimeInfo));
- std::string strTitle;
- strTitle.append("级别\t日期和时间\t来源\t事件 ID\t任务类别\t事件内容\r\n");
- pOutFile->WriteEventLogEntry(strTitle);
- }
- DWORD status = ERROR_SUCCESS;
- DWORD dwBytesToRead = 0;
- DWORD dwBytesRead = 0;
- DWORD dwMinimumBytesToRead = 0;
- PBYTE pBuffer = NULL;
- PBYTE pTemp = NULL;
- dwBytesToRead = MAX_RECORD_BUFFER_SIZE;
- pBuffer = (PBYTE)malloc(dwBytesToRead);
- if (NULL == pBuffer)
- {
- //!!printf("Failed to allocate the initial memory for the record buffer.");
- return 0;
- }
- while (ERROR_SUCCESS == status && !bEnough)
- {
- if (!ReadEventLog(m_hEventLog, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ,
- 0, pBuffer, dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
- {
- status = GetLastError();
- if (ERROR_INSUFFICIENT_BUFFER == status)
- {
- status = ERROR_SUCCESS;
- pTemp = (PBYTE)realloc(pBuffer, dwMinimumBytesToRead);
- if (NULL == pTemp)
- {
- //!!printf("Failed to reallocate the memory for the record buffer (%d bytes).\n",dwMinimumBytesToRead);
- return 0;
- }
- pBuffer = pTemp;
- dwBytesToRead = dwMinimumBytesToRead;
- }
- else
- {
- if (ERROR_HANDLE_EOF != status)
- {
- //!!printf("ReadEventLog failed with %lu.\n", status);
- if (pBuffer) {
- free(pBuffer);
- pBuffer = NULL;
- }
- return 0;
- }
- }
- }
- else
- {
- PBYTE pRecord = pBuffer;
- PBYTE pEndOfRecords = pBuffer + dwBytesRead;
- LPTSTR pMessage = NULL;
- LPTSTR pFinalMessage = NULL;
- CHAR TimeStamp[MAX_TIMESTAMP_LEN];
-
- while (pRecord < pEndOfRecords)
- {
- PEVENTLOGRECORD pELR = (PEVENTLOGRECORD)pRecord;
- BOOL bAcceptance = TRUE;
- if(bAcceptance && lpszSourceName != NULL && strlen(lpszSourceName) > 0) {
- bAcceptance = !strcmp(lpszSourceName, (LPCSTR)(pRecord + sizeof(EVENTLOGRECORD)));
- }
- if(bAcceptance && wEventType != 0) {
- bAcceptance = (wEventType & pELR->EventType);
- }
- if(bAcceptance && dwEventID != 0) {
- bAcceptance = (dwEventID == (pELR->EventID & 0xFFFF));
- }
- if(bAcceptance && dwStartTime != 0 && (dwStartTime <= dwEndTime)) {
- bAcceptance = (dwStartTime <= pELR->TimeGenerated && pELR->TimeGenerated <= dwEndTime);
- if(!bAcceptance && pELR->TimeGenerated < dwStartTime)
- bEnough = TRUE;
- }
- if(bAcceptance)
- {
- dwEntries++;
- std::ostringstream ostr;
- if((pELR->EventID & 0xFFFF) == 4625
- && !strcmp("Microsoft-Windows-Security-Auditing",
- (LPCSTR)(pRecord + sizeof(EVENTLOGRECORD)))) {
- //!!printf("Here !");
- }
- //!!printf("EventType: %s ", pEventTypeNames[GetEventTypeName(pELR->EventType)]);
- ostr << pEventTypeNames[GetEventTypeName(pELR->EventType)] << "\t";
- SYSTEMTIME stTime;
- GetTimestamp(pELR->TimeGenerated, &stTime, TimeStamp);
- Dbg("%s ", TimeStamp);
- ostr << TimeStamp << "\t";
- ////!!printf("RecordNumber: %8lu ", pELR->RecordNumber);
- Dbg("Source: %s ", (LPCSTR)(pRecord + sizeof(EVENTLOGRECORD)));
- ostr << (LPCSTR)(pRecord + sizeof(EVENTLOGRECORD)) << "\t";
- Dbg("EventID: %8d ", pELR->EventID & 0xFFFF);
- ostr << std::setw(8) << (pELR->EventID & 0xFFFF);
- CHAR szKeyName[MAX_PATH + 1];
- CHAR szExeFile[MAX_PATH + 1];
- CHAR szExeFilePath[MAX_PATH + 1];
- sprintf(szKeyName, REG_FULLFILL_KEY, m_szSourceName,
- (LPCSTR)(pRecord + sizeof(EVENTLOGRECORD)));
- HKEY hKey = NULL;
- DWORD dwMaxPath = MAX_PATH + 1;
- DWORD dwType;
- HMODULE hModule = NULL;
- if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0L, KEY_READ, &hKey) == NOERROR)
- {
- if(RegQueryValueEx(hKey, EVENT_MESSAGE_FILE,
- 0, &dwType, (LPBYTE)szExeFile, &dwMaxPath) == NOERROR)
- {
- if(ExpandEnvironmentStrings(szExeFile, szExeFilePath, MAX_PATH + 1) == 0)
- strcpy_s(szExeFilePath, szExeFile);
- hModule = GetMessageResources(szExeFilePath);
- if(hModule)
- {
- Dbg("GetMessageString about category");
- LPTSTR pMessage = GetMessageString(hModule, pELR->EventCategory, 0, NULL);
- if (pMessage)
- {
- //!!printf("EventCategory: %s ", pMessage);
- ostr << "\t" << pMessage;
- LocalFree(pMessage);
- pMessage = NULL;
- }
- Dbg("GetMessageString about EventMessage");
- pMessage = GetMessageString(hModule, pELR->EventID,
- pELR->NumStrings, (LPTSTR)(pRecord + pELR->StringOffset));
- if (pMessage)
- {
- DWORD status = ApplyParameterStringsToMessage(hModule,
- pMessage, pFinalMessage);
- //!!printf("\nEventMessage: %s ", (pFinalMessage) ? pFinalMessage : pMessage);
- std::string strTemp(
- (pFinalMessage) ? (LPCTSTR)pFinalMessage : (LPCTSTR)pMessage);
- ostr << "\t" << strTemp;
- LocalFree(pMessage);
- if(pFinalMessage && pFinalMessage != pMessage) {
- free(pFinalMessage);
- pFinalMessage = NULL;
- }
- pMessage = NULL;
- pFinalMessage = NULL;
- }
- Dbg("Finished routine");
- }
- }
- }
- if (/*pELR->DataLength > 0*/FALSE)
- {
- PBYTE pData = NULL;
- PBYTE pStrings = NULL;
- UINT uStringOffset;
- CHAR* szExpandedString;
- pData = (PBYTE)malloc(pELR->DataLength*sizeof(BYTE));
- pStrings = (PBYTE)malloc(pELR->DataOffset-pELR->StringOffset * sizeof(BYTE));
- DWORD dwExpandStringLen = pELR->DataOffset-pELR->StringOffset + 1024;
- szExpandedString = (CHAR*)malloc((dwExpandStringLen)*sizeof(CHAR));
- if(pData == NULL || pStrings == NULL || szExpandedString == NULL)
- {
- //!!printf("Failed to reallocate the memory for the event data.\n");
- if(pData) free(pData);
- if(pStrings) free(pStrings);
- if(szExpandedString) free(szExpandedString);
- if (pBuffer) free(pBuffer);
- return 0;
- }
- memcpy(pData, pRecord + pELR->DataOffset, pELR->DataLength);
- memcpy(pStrings,(PBYTE)pELR + pELR->StringOffset, pELR->DataOffset-pELR->StringOffset);
- UINT x, uStepOfString = 0;
- for(x=0; x<pELR->NumStrings; ++x)
- {
- if(x == 0)
- {
- strcpy_s(szExpandedString, dwExpandStringLen, (CHAR*)pStrings+uStepOfString);
- if(x < (UINT)pELR->NumStrings - 1)
- strcat_s(szExpandedString, dwExpandStringLen, ",");
- }
- else
- {
- strcat_s(szExpandedString, dwExpandStringLen, (CHAR*)pStrings + uStepOfString);
- }
- uStepOfString = strlen((CHAR*)pStrings+uStepOfString) + 1;
- }
- if(hModule)
- {
- CHAR** _sz = (CHAR**)malloc((pELR->NumStrings)*sizeof(CHAR*));
- uStringOffset = 0;
- DWORD dwZlen = 0;
- register UINT z;
- for(z=0; z<pELR->NumStrings; ++z)
- {
- dwZlen = strlen((CHAR*)pStrings+uStringOffset) + 1;
- _sz[z] = (CHAR*)malloc((dwZlen)* sizeof(CHAR));
- if(_sz[z] != NULL)
- {
- strcpy_s(_sz[z], dwZlen, (CHAR*)pStrings + uStringOffset);
- uStringOffset += strlen((CHAR *)pStrings + uStringOffset) + 1;
- }
- }
- LPVOID lpszBuffer = 0;
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_HMODULE |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_ARGUMENT_ARRAY,
- hModule, pELR->EventID, 0, (LPTSTR)&lpszBuffer, 1024,
- _sz
- );
- for(z=0; _sz != NULL && z<pELR->NumStrings; ++z)
- {
- if(_sz[z] != NULL)
- {
- free(_sz[z]);
- _sz[z] = NULL;
- }
- }
- if(_sz != NULL)
- {
- free(_sz);
- _sz = NULL;
- }
- if(lpszBuffer)
- {
- strcpy_s(szExpandedString, dwExpandStringLen, (CHAR *)lpszBuffer);
- uStringOffset = strlen(szExpandedString);
- }
- if(lpszBuffer)
- {
- LocalFree(lpszBuffer);
- }
- }
- //!!printf("\nEventData: %s", szExpandedString);
- if(szExpandedString) free(szExpandedString);
- if(pData) free(pData);
- if(pStrings) free(pStrings);
- }
- if(hKey)
- {
- RegCloseKey(hKey);
- hKey = NULL;
- }
- if(hModule != NULL)
- {
- FreeLibrary(hModule);
- hModule = NULL;
- }
- if(pOutFile)
- pOutFile->WriteEventLogEntry(ostr.str());
- //!!printf("\n");
- }
- if(bEnough) {
- //!!printf("Discover its enough, abort and break !\n");
- break;
- }
- pRecord += pELR->Length;
- }
- }
- }
- if(pBuffer) {
- free(pBuffer);
- pBuffer = NULL;
- }
- if(pOutFile) {
- CHAR strTimeInfo[MAX_PATH] = {0};
- DWORD dwDuration = GetTickCount() - dwStartTick;
- DWORD dwSplit = dwDuration / 1000; //s
- if(dwDuration / 1000 / 60 > 60) {
- DWORD dwSplit2 = dwSplit / 60 / 60;
- sprintf_s(strTimeInfo, "\r\n\t耗时:%d h:%02d m:%02d s .%03d ms",
- dwSplit2, (dwSplit - dwSplit2 * 60 * 60) % 60, dwSplit % 60, dwDuration % 1000);
- }else if(dwDuration / 1000 > 60) {
- sprintf_s(strTimeInfo, "\r\n\t耗时:%02d m:%02d s .%03d ms",
- dwSplit/60, dwSplit%60, dwDuration % 1000);
- }else {
- sprintf_s(strTimeInfo, "\r\n\t耗时:%02d s .%03d ms", dwSplit, dwDuration % 1000);
- }
- pOutFile->WriteEventLogEntry(std::string(strTimeInfo));
- memset(strTimeInfo, 0, sizeof(strTimeInfo));
- sprintf_s(strTimeInfo, "\t共记录 %u 条 %s 事件日志\r\n", dwEntries, m_szSourceName);
- pOutFile->WriteEventLogEntry(std::string(strTimeInfo));
-
- pOutFile->WriteEventLogEntry(std::string("\t筛选条件:"));
- if(lpszSourceName != NULL && strlen(lpszSourceName) > 0) {
- pOutFile->WriteEventLogEntry(std::string("\t来源: ") + lpszSourceName);
- }
- if(wEventType != 0) {
- std::string strEventType("\t类型:");
- if(wEventType & EVENTLOG_ERROR_TYPE) {
- strEventType.append(" ");
- strEventType.append(pEventTypeNames[0]);
- }
- if(wEventType & EVENTLOG_WARNING_TYPE) {
- strEventType.append(" ");
- strEventType.append(pEventTypeNames[1]);
- }
- if(wEventType & EVENTLOG_INFORMATION_TYPE) {
- strEventType.append(" ");
- strEventType.append(pEventTypeNames[2]);
- }
- if(wEventType & EVENTLOG_AUDIT_SUCCESS) {
- strEventType.append(" ");
- strEventType.append(pEventTypeNames[3]);
- }
- if(wEventType & EVENTLOG_AUDIT_FAILURE) {
- strEventType.append(" ");
- strEventType.append(pEventTypeNames[4]);
- }
- pOutFile->WriteEventLogEntry(strEventType);
- }
- if(dwEventID != 0) {
- CHAR szEventID[20] = {0};
- sprintf_s(szEventID, "%u", dwEventID);
- pOutFile->WriteEventLogEntry(std::string("\t事件 ID: ") + szEventID);
- }
- if(dwStartTime != 0 && (dwStartTime <= dwEndTime)) {
- CHAR TimeStart[MAX_TIMESTAMP_LEN];
- CHAR TimeEnd[MAX_TIMESTAMP_LEN];
- SYSTEMTIME stTime;
- GetTimestamp(dwStartTime, &stTime, TimeStart);
- GetTimestamp(dwEndTime, &stTime, TimeEnd);
- pOutFile->WriteEventLogEntry(std::string("\t记录时间: ") + TimeStart + " - " + TimeEnd);
- }
- pOutFile->WriteEventLogEntry("\r\n");
- }
- return dwEntries;
- }
- // Get the last record number in the log file and read it.
- // This positions the cursor, so that we can begin reading
- // new records when the service notifies us that new records were
- // written to the log file.
- DWORD CEventLog::SeekToLastRecord()
- {
- DWORD status = ERROR_SUCCESS;
- DWORD dwLastRecordNumber = 0;
- PBYTE pRecord = NULL;
- status = GetLastRecordNumber(&dwLastRecordNumber);
- if (ERROR_SUCCESS != status)
- {
- //!!printf("GetLastRecordNumber failed.\n");
- goto cleanup;
- }
- status = ReadSingleRecord(pRecord, dwLastRecordNumber, EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ);
- if (ERROR_SUCCESS != status)
- {
- //!!printf("ReadRecord failed seeking to record %lu.\n", dwLastRecordNumber);
- goto cleanup;
- }
- cleanup:
- if (pRecord)
- free(pRecord);
- return status;
- }
- // Get the record number to the last record in the log file.
- DWORD CEventLog::GetLastRecordNumber(DWORD* pdwRecordNumber)
- {
- DWORD status = ERROR_SUCCESS;
- DWORD OldestRecordNumber = 0;
- DWORD NumberOfRecords = 0;
- if (!GetOldestEventLogRecord(m_hEventLog, &OldestRecordNumber))
- {
- //!!printf("GetOldestEventLogRecord failed with %lu.\n", status = GetLastError());
- goto cleanup;
- }
- if (!GetNumberOfEventLogRecords(m_hEventLog, &NumberOfRecords))
- {
- //!!printf("GetOldestEventLogRecord failed with %lu.\n", status = GetLastError());
- goto cleanup;
- }
- *pdwRecordNumber = OldestRecordNumber + NumberOfRecords - 1;
- cleanup:
- return status;
- }
- // Read a single record from the event log.
- DWORD CEventLog::ReadSingleRecord(PBYTE & pBuffer, DWORD dwRecordNumber, DWORD dwReadFlags)
- {
- DWORD status = ERROR_SUCCESS;
- DWORD dwBytesToRead = sizeof(EVENTLOGRECORD);
- DWORD dwBytesRead = 0;
- DWORD dwMinimumBytesToRead = 0;
- PBYTE pTemp = NULL;
- // The initial size of the buffer is not big enough to read a record, but ReadEventLog
- // requires a valid pointer. The ReadEventLog function will fail and return the required
- // buffer size; reallocate the buffer to the required size.
- pBuffer= (PBYTE)malloc(sizeof(EVENTLOGRECORD));
- // Get the required buffer size, reallocate the buffer and then read the event record.
- if (!ReadEventLog(m_hEventLog, dwReadFlags, dwRecordNumber, pBuffer,
- dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
- {
- status = GetLastError();
- if (ERROR_INSUFFICIENT_BUFFER == status)
- {
- status = ERROR_SUCCESS;
- pTemp = (PBYTE)realloc(pBuffer, dwMinimumBytesToRead);
- if (NULL == pTemp)
- {
- //!!printf("Failed to reallocate memory for the record buffer (%d bytes).\n", dwMinimumBytesToRead);
- goto cleanup;
- }
- pBuffer = pTemp;
- dwBytesToRead = dwMinimumBytesToRead;
- if (!ReadEventLog(m_hEventLog, dwReadFlags,
- dwRecordNumber, pBuffer, dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
- {
- //!!printf("Second ReadEventLog failed with %lu.\n", status = GetLastError());
- goto cleanup;
- }
- }
- else
- {
- if (ERROR_HANDLE_EOF != status)
- {
- //!!printf("ReadEventLog failed with %lu.\n", status);
- goto cleanup;
- }
- }
- }
- cleanup:
- return status;
- }
- // Formats the specified message. If the message uses inserts, build
- // the argument list to pass to FormatMessage.
- LPTSTR CEventLog::GetMessageString(HMODULE hModule, DWORD MessageId, DWORD argc, LPTSTR argv)
- {
- LPTSTR pMessage = NULL;
- DWORD dwFormatFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE
- | FORMAT_MESSAGE_ALLOCATE_BUFFER;
- DWORD_PTR* pArgs = NULL;
- LPTSTR pString = argv;
- // The insertion strings appended to the end of the event record
- // are an array of strings; however, FormatMessage requires
- // an array of addresses. Create an array of DWORD_PTRs based on
- // the count of strings. Assign the address of each string
- // to an element in the array (maintaining the same order).
- if (argc > 0)
- {
- pArgs = (DWORD_PTR*)malloc(sizeof(DWORD_PTR) * argc);
- if (pArgs)
- {
- dwFormatFlags |= FORMAT_MESSAGE_ARGUMENT_ARRAY;
- for (DWORD i = 0; i < argc; i++)
- {
- pArgs[i] = (DWORD_PTR)pString;
- pString += strlen(pString) + 1;
- }
- }
- else
- {
- dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
- //!!printf("Failed to allocate memory for the insert string array.\n");
- }
- }
- if (!FormatMessage(dwFormatFlags, hModule, MessageId,
- 0, (LPTSTR)&pMessage, 0, (va_list*)pArgs))
- {
- //!!printf("Format message failed with %lu\n", GetLastError());
- }
- if (pArgs)
- free(pArgs);
- if(pMessage != NULL)
- {
- size_t MsgLen = strlen((LPCTSTR)pMessage);
- if(MsgLen > 0) {
- if(MsgLen >= 2 && pMessage[MsgLen-1] == '\n' && pMessage[MsgLen-2] == '\r') pMessage[MsgLen-2] = '\0';
- if(MsgLen >= 1 && pMessage[MsgLen-1] == '\n') pMessage[MsgLen-1] = '\0';
- }
- }
- return pMessage;
- }
- void CEventLog::GetTimestamp(const DWORD Time, PSYSTEMTIME stTime, CHAR DisplayString[])
- {
- ULONGLONG ullTimeStamp = 0;
- ULONGLONG SecsTo1970 = 116444736000000000;
- SYSTEMTIME st;
- FILETIME ft, ftLocal;
- ullTimeStamp = Int32x32To64(Time, 10000000) + SecsTo1970;
- ft.dwHighDateTime = (DWORD)((ullTimeStamp >> 32) & 0xFFFFFFFF);
- ft.dwLowDateTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
- FileTimeToLocalFileTime(&ft, &ftLocal);
- FileTimeToSystemTime(&ftLocal, &st);
- StringCchPrintf(DisplayString, MAX_TIMESTAMP_LEN, "%04d/%02d/%02d %.2d:%.2d:%.2d",
- st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
-
- if(stTime != NULL) {
- //SystemTimeToTzSpecificLocalTime(NULL, &st, stTime);
- *stTime = st;
- }
- return;
- }
|