123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844 |
- #include "StdAfx.h"
- #include "EventLogW.h"
- //#include "SpBase.h"
- #include <excpt.h>
- int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep)
- {
- if(code == EXCEPTION_ACCESS_VIOLATION)
- {
- return EXCEPTION_EXECUTE_HANDLER;
- }
- //return EXCEPTION_CONTINUE_SEARCH;
- return EXCEPTION_EXECUTE_HANDLER;
- }
- #ifndef UNICODE
- #define UNICODE
- #endif
- //void PutoutLog(LPCWSTR lpwszMessage) {
- // if(wcslen(lpwszMessage) > 0) {
- // CSimpleStringA strMessage = CSimpleStringW2A(CSimpleStringW(lpwszMessage));
- // Dbg("%s", (LPCTSTR)strMessage);
- // }
- // return;
- //}
- // 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 CEventLogW::ApplyParameterStringsToMessage(
- HMODULE hModule,
- CONST LPCWSTR pMessage, LPWSTR& 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;
- LPWSTR* pStartingAddresses = NULL; // Array of pointers to the beginning of each parameter string in pMessage
- LPWSTR* pEndingAddresses = NULL; // Array of pointers to the end of each parameter string in pMessage
- DWORD* pParameterIDs = NULL; // Array of parameter identifiers found in pMessage
- LPWSTR* pParameters = NULL; // Array of the actual parameter strings
- LPWSTR pTempMessage = (LPWSTR)pMessage;
- LPWSTR pTempFinalMessage = NULL;
- // Determine the number of parameter insertion strings in pMessage.
- while (pTempMessage = wcschr(pTempMessage, L'%'))
- {
- pTempMessage++;
- //if(isdigit(*pTempMessage))
- if ((*pTempMessage) >= L'0' && (*pTempMessage) <= L'9')
- {
- 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(LPWSTR) * dwParameterCount;
- pStartingAddresses = (LPWSTR*)malloc(cbBuffer);
- if (NULL == pStartingAddresses)
- {
- //!!wprintf(L"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 = (LPWSTR*)malloc(cbBuffer);
- if (NULL == pEndingAddresses)
- {
- //!!wprintf(L"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 = (LPWSTR*)malloc(cbBuffer);
- if (NULL == pParameters)
- {
- //!!wprintf(L"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)
- {
- //!!wprintf(L"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 = (LPWSTR)pMessage;
- while (pTempMessage = wcschr(pTempMessage, L'%'))
- {
- if ((*(1 + pTempMessage)) >= L'0' && (*(1 + pTempMessage)) <= L'9')
- {
- pStartingAddresses[i] = pTempMessage;
- pTempMessage++;
- pParameterIDs[i] = (DWORD)_wtoi(pTempMessage);
- while ((*++pTempMessage) >= L'0' && (*pTempMessage) <= L'9')
- ;
- 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])
- {
- //!!wprintf(L"GetMessageString could not find parameter string for insert %lu.\n", i);
- status = ERROR_INVALID_PARAMETER;
- goto cleanup;
- }
- cchParameters += wcslen(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 = (LPWSTR)pMessage;
- cbBuffer = (wcslen(pMessage) + cchParameters + 1) * sizeof(WCHAR);
- pFinalMessage = (LPWSTR)malloc(cbBuffer);
- if (NULL == pFinalMessage)
- {
- //!!wprintf(L"Failed to allocate memory for pFinalMessage.\n");
- status = ERROR_OUTOFMEMORY;
- goto cleanup;
- }
- RtlZeroMemory(pFinalMessage, cbBuffer);
- cchBuffer = cbBuffer / sizeof(WCHAR);
- 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 L"8 " and in the
- // second iteration, this is " = 2 ".
- wcsncpy_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;
- wcscpy_s(pTempFinalMessage, cchBuffer, pParameters[i]);
- cchBuffer -= cch = wcslen(pParameters[i]);
- pTempFinalMessage += cch;
- }
- // Append the last segment from pMessage, which is ".".
- wcscpy_s(pTempFinalMessage, cchBuffer, pTempMessage);
- cleanup:
- if (ERROR_SUCCESS != status)
- //pFinalMessage = (LPWSTR)pMessage;
- pFinalMessage = NULL;
- 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;
- }
- CEventLogW::CEventLogW(void)
- :m_hEventLog(NULL)
- ,pOutFile(NULL)
- {
- memset(m_szSourceName, 0, sizeof(WCHAR)*MAX_PATH);
- }
- CEventLogW::CEventLogW(LPCWSTR lpSrcName, BOOL bCustom)
- :m_hEventLog(NULL)
- ,pOutFile(NULL)
- {
- memset(m_szSourceName, 0, sizeof(WCHAR)*MAX_PATH);
- Initialize(lpSrcName, bCustom);
- }
- CEventLogW::~CEventLogW(void)
- {
- if (m_hEventLog)
- CloseEventLog(m_hEventLog);
- if(pOutFile)
- delete pOutFile;
- }
- HRESULT CEventLogW::Initialize(LPCWSTR lpSrcName, BOOL bCustom)
- {
- HRESULT hr = NOERROR;
- if (bCustom)
- {
- m_hEventLog = OpenBackupEventLogW(NULL, lpSrcName);
- }
- else
- {
- m_hEventLog = OpenEventLogW(NULL, lpSrcName);
- }
- if(m_hEventLog == NULL)
- {
- hr = HRESULT_FROM_WIN32(GetLastError());
- }
- else
- {
- memset(m_szSourceName, 0, sizeof(WCHAR)*MAX_PATH);
- wcscpy_s(m_szSourceName, lpSrcName);
- }
- return hr;
- }
- DWORD CEventLogW::FilterEventLog(
- LPCWSTR 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);
- WCHAR strTimeInfo[MAX_PATH] = {0};
- swprintf_s(strTimeInfo, L"生成时间:%d\\%02d\\%02d %02d:%02d:%02d.%03d\r\n",
- stLocal.wYear, stLocal.wMonth, stLocal.wDay,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond, stLocal.wMilliseconds);
- pOutFile->WriteEventLogEntry(std::wstring(strTimeInfo));
- std::wstring strTitle;
- strTitle.append(L"级别\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)
- {
- //!!wprintf(L"Failed to allocate the initial memory for the record buffer.");
- return 0;
- }
- while (ERROR_SUCCESS == status && !bEnough)
- {
- if (!ReadEventLogW(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)
- {
- //!!wprintf(L"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)
- {
- //!!wprintf(L"ReadEventLogW failed with %lu.\n", status);
- if (pBuffer) {
- free(pBuffer);
- pBuffer = NULL;
- }
- return 0;
- }
- }
- }
- else
- {
- PBYTE pRecord = pBuffer;
- PBYTE pEndOfRecords = pBuffer + dwBytesRead;
- WCHAR TimeStamp[MAX_TIMESTAMP_LEN];
- while (pRecord < pEndOfRecords)
- {
- PEVENTLOGRECORD pELR = (PEVENTLOGRECORD)pRecord;
- BOOL bAcceptance = TRUE;
- if(bAcceptance && lpszSourceName != NULL && wcslen(lpszSourceName) > 0) {
- bAcceptance = !wcscmp(lpszSourceName, (LPCWSTR)(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::wostringstream ostr;
- if((pELR->EventID & 0xFFFF) == 4625
- && !wcscmp(L"Microsoft-Windows-Security-Auditing",
- (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)))) {
- //!!wprintf(L"Here !");
- }
- //!!wprintf(L"EventType: %ls ", pEventTypeNames[GetEventTypeNameW(pELR->EventType)]);
- ostr << pEventTypeNames[GetEventTypeNameW(pELR->EventType)] << L"\t";
- SYSTEMTIME stTime;
- GetTimestamp(pELR->TimeGenerated, &stTime, TimeStamp);
- //!!wprintf(L"%ls ", TimeStamp);
- ostr << TimeStamp << L"\t";
- ////!!wprintf(L"RecordNumber: %8lu ", pELR->RecordNumber);
- //!!wprintf(L"Source: %ls ", (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)));
- ostr << (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)) << L"\t";
- //!!wprintf(L"EventID: %8d ", pELR->EventID & 0xFFFF);
- ostr << std::setw(8) << (pELR->EventID & 0xFFFF);
- WCHAR szKeyName[MAX_PATH + 1];
- WCHAR szExeFile[MAX_PATH + 1];
- WCHAR szExeFilePath[MAX_PATH + 1];
- swprintf(szKeyName, REG_FULLFILL_KEY, m_szSourceName,
- (LPCWSTR)(pRecord + sizeof(EVENTLOGRECORD)));
-
- HKEY hKey = NULL;
- DWORD dwMaxPath = MAX_PATH + 1;
- DWORD dwType;
- HMODULE hModule = NULL;
- if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKeyName, 0L, KEY_READ, &hKey) == NOERROR)
- {
- if(RegQueryValueExW(hKey, EVENT_MESSAGE_FILE,
- NULL, &dwType, (LPBYTE)szExeFile, &dwMaxPath) == NOERROR)
- {
- if(ExpandEnvironmentStringsW(szExeFile, szExeFilePath, MAX_PATH + 1) == 0)
- wcscpy_s(szExeFilePath, szExeFile);
- //WCHAR *current = szExeFilePath, *next;
- //while (current)
- //{
- // next = wcschr(current, L';');
- // if (next)
- // {
- // *next = L'\0';
- // next++;
- // }
- //}
- hModule = GetMessageResources(szExeFilePath);
- if(hModule)
- {
- //!!wprintf(L"GetMessageString about category");
- LPWSTR pMessageCategory = GetMessageString(hModule, pELR->EventCategory, 0, NULL);
- if (pMessageCategory)
- {
- //!!wprintf(L"EventCategory: %ls ", pMessageCategory);
- ostr << L"\t" << pMessageCategory;
- LocalFree(pMessageCategory);
- pMessageCategory = NULL;
- }
- //!!wprintf(L"GetMessageString about EventMessage");
- LPWSTR pMessage = NULL;
- pMessage = GetMessageString(hModule, pELR->EventID,
- pELR->NumStrings, (LPWSTR)(pRecord + pELR->StringOffset));
- if (pMessage)
- {
- LPWSTR pFinalMessage = NULL;
- DWORD status = ApplyParameterStringsToMessage(hModule,
- pMessage, pFinalMessage);
- //!!wprintf(L"\nEventMessage: %ls", (pFinalMessage) ? pFinalMessage : pMessage);
- std::wstring strTemp(
- (pFinalMessage) ? (LPCWSTR)pFinalMessage : (LPCWSTR)pMessage);
- ostr << L"\t" << strTemp;
- if(pFinalMessage && pFinalMessage != pMessage) {
- free(pFinalMessage);
- pFinalMessage = NULL;
- }
- LocalFree(pMessage);
- pMessage = NULL;
- }
- //!!wprintf(L"Finished routine");
- }
- }
- }
- #if 0
- if (/*pELR->DataLength > 0*/FALSE)
- {
- PBYTE pData = NULL;
- PBYTE pStrings = NULL;
- UINT uStringOffset;
- WCHAR* 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 = (WCHAR*)malloc((dwExpandStringLen)*sizeof(WCHAR));
- if(pData == NULL || pStrings == NULL || szExpandedString == NULL)
- {
- //!!wprintf(L"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)
- {
- wcscpy_s(szExpandedString, dwExpandStringLen, (WCHAR*)pStrings+uStepOfString);
- if(x < (UINT)pELR->NumStrings - 1)
- wcscat_s(szExpandedString, dwExpandStringLen, L",");
- }
- else
- {
- wcscat_s(szExpandedString, dwExpandStringLen, (WCHAR*)pStrings + uStepOfString);
- }
- uStepOfString = wcslen((WCHAR*)pStrings+uStepOfString) + 1;
- }
- if(hModule)
- {
- WCHAR** _sz = (WCHAR**)malloc((pELR->NumStrings)*sizeof(WCHAR*));
- uStringOffset = 0;
- DWORD dwZlen = 0;
- register UINT z;
- for(z=0; z<pELR->NumStrings; ++z)
- {
- dwZlen = wcslen((WCHAR*)pStrings+uStringOffset) + 1;
- _sz[z] = (WCHAR*)malloc((dwZlen)* sizeof(WCHAR));
- if(_sz[z] != NULL)
- {
- wcscpy_s(_sz[z], dwZlen, (WCHAR*)pStrings + uStringOffset);
- uStringOffset += wcslen((WCHAR *)pStrings + uStringOffset) + 1;
- }
- }
- LPVOID lpszBuffer = 0;
- FormatMessageW(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_HMODULE |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_ARGUMENT_ARRAY,
- hModule, pELR->EventID, 0, (LPWSTR)&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)
- {
- wcscpy_s(szExpandedString, dwExpandStringLen, (WCHAR *)lpszBuffer);
- uStringOffset = wcslen(szExpandedString);
- }
- if(lpszBuffer)
- {
- LocalFree(lpszBuffer);
- }
- }
- //!!wprintf(L"\nEventData: %ls", szExpandedString);
- if(szExpandedString) free(szExpandedString);
- if(pData) free(pData);
- if(pStrings) free(pStrings);
- }
- #endif
- if(hKey)
- {
- RegCloseKey(hKey);
- hKey = NULL;
- }
- if(hModule != NULL)
- {
- FreeLibrary(hModule);
- hModule = NULL;
- }
- if(pOutFile)
- pOutFile->WriteEventLogEntry(ostr.str());
- //!!wprintf(L"\n");
- }
- if(bEnough) {
- //!!wprintf(L"Discover its enough, abort and break !\n");
- break;
- }
- pRecord += pELR->Length;
- }
- }
- }
- if(pBuffer) {
- free(pBuffer);
- pBuffer = NULL;
- }
- if(pOutFile) {
- WCHAR strTimeInfo[MAX_PATH] = {0};
- DWORD dwDuration = GetTickCount() - dwStartTick;
- DWORD dwSplit = dwDuration / 1000; //s
- if(dwDuration / 1000 / 60 > 60) {
- DWORD dwSplit2 = dwSplit / 60 / 60;
- swprintf_s(strTimeInfo, L"\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) {
- swprintf_s(strTimeInfo, L"\r\n\t耗时:%02d m:%02d s .%03d ms",
- dwSplit/60, dwSplit%60, dwDuration % 1000);
- }else {
- swprintf_s(strTimeInfo, L"\r\n\t耗时:%02d s .%03d ms", dwSplit, dwDuration % 1000);
- }
- pOutFile->WriteEventLogEntry(std::wstring(strTimeInfo));
- memset(strTimeInfo, 0, sizeof(strTimeInfo));
- swprintf_s(strTimeInfo, L"\t共记录 %u 条 %ls 事件日志\r\n", dwEntries, m_szSourceName);
- pOutFile->WriteEventLogEntry(std::wstring(strTimeInfo));
- pOutFile->WriteEventLogEntry(std::wstring(L"\t筛选条件:"));
- if(lpszSourceName != NULL && wcslen(lpszSourceName) > 0) {
- pOutFile->WriteEventLogEntry(std::wstring(L"\t来源: ") + lpszSourceName);
- }
- if(wEventType != 0) {
- std::wstring strEventType(L"\t类型:");
- if(wEventType & EVENTLOG_ERROR_TYPE) {
- strEventType.append(L" ");
- strEventType.append(pEventTypeNames[0]);
- }
- if(wEventType & EVENTLOG_WARNING_TYPE) {
- strEventType.append(L" ");
- strEventType.append(pEventTypeNames[1]);
- }
- if(wEventType & EVENTLOG_INFORMATION_TYPE) {
- strEventType.append(L" ");
- strEventType.append(pEventTypeNames[2]);
- }
- if(wEventType & EVENTLOG_AUDIT_SUCCESS) {
- strEventType.append(L" ");
- strEventType.append(pEventTypeNames[3]);
- }
- if(wEventType & EVENTLOG_AUDIT_FAILURE) {
- strEventType.append(L" ");
- strEventType.append(pEventTypeNames[4]);
- }
- pOutFile->WriteEventLogEntry(strEventType);
- }
- if(dwEventID != 0) {
- WCHAR szEventID[20] = {0};
- swprintf_s(szEventID, L"%u", dwEventID);
- pOutFile->WriteEventLogEntry(std::wstring(L"\t事件 ID: ") + szEventID);
- }
- if(dwStartTime != 0 && (dwStartTime <= dwEndTime)) {
- WCHAR TimeStart[MAX_TIMESTAMP_LEN];
- WCHAR TimeEnd[MAX_TIMESTAMP_LEN];
- SYSTEMTIME stTime;
- GetTimestamp(dwStartTime, &stTime, TimeStart);
- GetTimestamp(dwEndTime, &stTime, TimeEnd);
- pOutFile->WriteEventLogEntry(std::wstring(L"\t记录时间: ") + TimeStart + L" - " + TimeEnd);
- }
- pOutFile->WriteEventLogEntry(L"\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 CEventLogW::SeekToLastRecord()
- {
- DWORD status = ERROR_SUCCESS;
- DWORD dwLastRecordNumber = 0;
- PBYTE pRecord = NULL;
- status = GetLastRecordNumber(&dwLastRecordNumber);
- if (ERROR_SUCCESS != status)
- {
- //!!wprintf(L"GetLastRecordNumber failed.\n");
- goto cleanup;
- }
- status = ReadSingleRecord(pRecord, dwLastRecordNumber, EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ);
- if (ERROR_SUCCESS != status)
- {
- //!!wprintf(L"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 CEventLogW::GetLastRecordNumber(DWORD* pdwRecordNumber)
- {
- DWORD status = ERROR_SUCCESS;
- DWORD OldestRecordNumber = 0;
- DWORD NumberOfRecords = 0;
- if (!GetOldestEventLogRecord(m_hEventLog, &OldestRecordNumber))
- {
- //!!wprintf(L"GetOldestEventLogRecord failed with %lu.\n", status = GetLastError());
- goto cleanup;
- }
- if (!GetNumberOfEventLogRecords(m_hEventLog, &NumberOfRecords))
- {
- //!!wprintf(L"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 CEventLogW::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 (!ReadEventLogW(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)
- {
- //!!wprintf(L"Failed to reallocate memory for the record buffer (%d bytes).\n", dwMinimumBytesToRead);
- goto cleanup;
- }
- pBuffer = pTemp;
- dwBytesToRead = dwMinimumBytesToRead;
- if (!ReadEventLogW(m_hEventLog, dwReadFlags,
- dwRecordNumber, pBuffer, dwBytesToRead, &dwBytesRead, &dwMinimumBytesToRead))
- {
- //!!wprintf(L"Second ReadEventLogW failed with %lu.\n", status = GetLastError());
- goto cleanup;
- }
- }
- else
- {
- if (ERROR_HANDLE_EOF != status)
- {
- //!!wprintf(L"ReadEventLogW 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.
- LPWSTR CEventLogW::GetMessageString(HMODULE hModule, DWORD MessageId, DWORD argc, LPWSTR argv)
- {
- LPWSTR pMessage = NULL;
- DWORD dwFormatFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE
- | FORMAT_MESSAGE_ALLOCATE_BUFFER;
- DWORD_PTR* pArgs = NULL;
- LPWSTR pString = argv;
- DWORD dwRes = ERROR_SUCCESS;
- // 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 += wcslen(pString) + 1;
- }
- }
- else
- {
- dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
- //!!wprintf(L"Failed to allocate memory for the insert string array.\n");
- }
- }
- // if FormatMessageW is called without FORMAT_MESSAGE_IGNORE_INSERTS, the pArgs must contain enough
- // parameters to satisfy all insertion sequences in the message string and they must be of the correct
- // type. stackflow.com/22518746 -Josephus@2017720 11:03:35
- //dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
- DWORD dwCount = 0;
- __try
- {
- dwCount = FormatMessageW(dwFormatFlags, hModule, MessageId,
- 0, (LPWSTR)&pMessage, 0, (va_list*)pArgs);
- }
- __except(filter(GetExceptionCode(), GetExceptionInformation()))
- {
- dwFormatFlags |= FORMAT_MESSAGE_IGNORE_INSERTS;
- dwCount = FormatMessageW(dwFormatFlags, hModule, MessageId,
- 0, (LPWSTR)&pMessage, 0, (va_list*)pArgs);
- }
- if (pArgs)
- free(pArgs);
- if (dwCount == 0)
- {
- //!!wprintf(L"Format message failed with %lu\n", GetLastError());
- }
- //if(pMessage != NULL)
- //{
- // size_t MsgLen = wcslen((LPCWSTR)pMessage);
- // if(MsgLen > 0) {
- // if(MsgLen >= 2 && pMessage[MsgLen-1] == L'\n' && pMessage[MsgLen-2] == L'\r') pMessage[MsgLen-2] = L'\0';
- // if(MsgLen >= 1 && pMessage[MsgLen-1] == L'\n') pMessage[MsgLen-1] = L'\0';
- // }
- //}
- return pMessage;
- }
- void CEventLogW::GetTimestamp(const DWORD Time, PSYSTEMTIME stTime, WCHAR 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);
- StringCchPrintfW(DisplayString, MAX_TIMESTAMP_LEN, L"%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;
- }
|