static HRESULT UnregisterAddin(const std::wstring& clsid) { HRESULT hr = S_OK; ATL::CRegKey key; //delete BHO LSTATUS lStatus = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(clsid.c_str()); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } //delete HKCR lStatus = key.Open(HKEY_CLASSES_ROOT, L"CLSID"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(clsid.c_str()); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } return hr; }
BOOL CMailMsg::DetectMailClient(WTL::CString& sMailClientName) { ATL::CRegKey regKey; TCHAR buf[1024] = _T(""); ULONG buf_size = 0; LONG lResult; lResult = regKey.Open(HKEY_CURRENT_USER, _T("SOFTWARE\\Clients\\Mail"), KEY_READ); if(lResult!=ERROR_SUCCESS) { lResult = regKey.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Clients\\Mail"), KEY_READ); } if(lResult==ERROR_SUCCESS) { buf_size = 1023; #pragma warning(disable:4996) LONG result = regKey.QueryValue(buf, _T(""), &buf_size); #pragma warning(default:4996) if(result==ERROR_SUCCESS) { sMailClientName = buf; return TRUE; } regKey.Close(); } else { sMailClientName = "Not Detected"; } return FALSE; }
/// Loads a list of message IDs that should be passed on to the AOIA application void LoadMessageFilter(HKEY hKeyParent, LPCTSTR lpszKeyName) { g_messageFilter.empty(); ATL::CRegKey reg; if (reg.Open(hKeyParent, lpszKeyName, KEY_READ) == ERROR_SUCCESS) { TCHAR subkey[256]; DWORD skLength = 256; DWORD dw; int index = 0; while (true) { if (reg.EnumKey(index, subkey, &skLength) == ERROR_SUCCESS) { index++; if (reg.QueryDWORDValue(subkey, dw) == ERROR_SUCCESS) { g_messageFilter.insert(dw); } } else { break; } } } else { LOG("Unable to open key: " << lpszKeyName) } }
BOOL AddinHelper::TodayNotDo(const wchar_t* szValueName) { DWORD dwLastUTC = 0; BOOL bCando = FALSE; ATL::CRegKey key; if (key.Open(HKEY_CURRENT_USER, REGEDITPATH) == ERROR_SUCCESS) { bCando = TRUE; if(key.QueryDWORDValue(szValueName, dwLastUTC) == ERROR_SUCCESS) { __time64_t tTime = (__time64_t)dwLastUTC; tm* pTm = _localtime64(&tTime); LONG nLastDay = pTm->tm_mday; LONG nLastMonth = pTm->tm_mon; LONG nLastYear = pTm->tm_year; __time64_t lCurTime; _time64( &lCurTime); tm* pTmc = _localtime64(&lCurTime); LONG nCurDay = pTmc->tm_mday; LONG nCurMonth = pTmc->tm_mon; LONG nCurYear = pTmc->tm_year; TSDEBUG4CXX("TodayHasDo check time pTmc = "<<nCurYear<<nCurMonth<<nCurDay<<", pTm = "<<nLastYear<<nLastMonth<<nLastDay); if (nCurDay == nLastDay && nCurMonth == nLastMonth && nCurYear == nLastYear){ bCando = FALSE; } else{ bCando = TRUE; } } key.Close(); } return bCando; }
static HRESULT UnregisterAddin(const std::wstring& clsid) { HRESULT hr = S_OK; ATL::CRegKey key; //delete IconOverlay LSTATUS lStatus = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ShellIconOverlayIdentifiers"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(L" DeskUpdateRemind"); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } //delete CopyHook lStatus = key.Open(HKEY_CLASSES_ROOT, L"Directory\\shellex\\CopyHookHandlers"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(L"AYBSharing"); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } //delete BHO //lStatus = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects"); //if (lStatus == ERROR_SUCCESS) { // lStatus = key.RecurseDeleteKey(clsid.c_str()); // key.Close(); //} //if (lStatus != ERROR_SUCCESS) { // hr = HRESULT_FROM_WIN32(lStatus); //} //delete HKCR lStatus = key.Open(HKEY_CLASSES_ROOT, L"CLSID"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(clsid.c_str()); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } return hr; }
bool RegistryHelper::writeValue(const LPTSTR valueName, std::wstring const& value) const { ATL::CRegKey regKey; return (ERROR_SUCCESS == regKey.Open(key_, keyName_, KEY_WRITE) || ERROR_SUCCESS == regKey.Create(key_, keyName_, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE)) && ERROR_SUCCESS == regKey.SetStringValue(valueName, value.c_str()); }
bool GetGreenShiledExeFilePath(wchar_t* buffer, std::size_t bufferLength) { ATL::CRegKey key; if(key.Open(HKEY_LOCAL_MACHINE, L"Software\\ADClean", KEY_QUERY_VALUE) != ERROR_SUCCESS) { return false; } ULONG size = bufferLength; return key.QueryStringValue(L"Path", buffer, &size) == ERROR_SUCCESS; }
BOOL CNTEventLogSource::Uninstall(LPCTSTR lpszLogName, LPCTSTR lpszSourceName) { //Validate our parameters ATLASSUME(lpszLogName != NULL); ATLASSERT(_tcslen(lpszLogName)); ATLASSUME(lpszSourceName != NULL); ATLASSERT(_tcslen(lpszSourceName)); //Remove the settings from the registry TCHAR szSubKey[4096]; _stprintf_s(szSubKey, sizeof(szSubKey)/sizeof(TCHAR), _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s"), lpszLogName, lpszSourceName); long nSuccess = RegDeleteKey(HKEY_LOCAL_MACHINE, szSubKey); if (nSuccess != ERROR_SUCCESS) //If we cannot delete this registry key, then abort this function before we go any further { SetLastError(nSuccess); //Make the last error value available to our callers return FALSE; } //Remove ourself from the "Sources" registry key _stprintf_s(szSubKey, sizeof(szSubKey)/sizeof(TCHAR), _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s"), lpszLogName); ATL::CRegKey appKey; if (appKey.Open(HKEY_LOCAL_MACHINE, szSubKey, KEY_WRITE | KEY_READ) == ERROR_SUCCESS) { CNTServiceStringArray sources; if (GetStringArrayFromRegistry(appKey, _T("Sources"), sources)) { //If our name is in the array then remove it BOOL bFoundMyself = FALSE; #ifdef CNTSERVICE_MFC_EXTENSIONS for (int i=0; i<sources.GetSize() && !bFoundMyself; i++) { bFoundMyself = (sources.GetAt(i) == lpszSourceName); if (bFoundMyself) { sources.RemoveAt(i); } } #else CNTServiceStringArray::iterator iterFind = std::find(sources.begin(), sources.end(), lpszSourceName); bFoundMyself = (iterFind != sources.end()); if (bFoundMyself) sources.erase(iterFind); #endif if (bFoundMyself) SetStringArrayIntoRegistry(appKey, _T("Sources"), sources); } } return TRUE; }
std::wstring RegistryHelper::readValue(const LPTSTR valueName) const { ATL::CRegKey regKey; unsigned long valSize = 0; std::wstring value; if (!( ERROR_SUCCESS == regKey.Open(key_, keyName_, KEY_READ) && ERROR_SUCCESS == regKey.QueryStringValue(valueName, NULL, &valSize) && valSize > 0 && (value.resize(valSize), ERROR_SUCCESS == regKey.QueryStringValue(valueName, (LPTSTR)value.data(), &valSize)) )) value.clear(); else value.resize(valSize - 1); return value; }
RegData AddinHelper::QueryRegVal(HKEY hkey, LPCTSTR lpszKeyName, LPCTSTR lpszValuename, REGSAM flag) { ATL::CRegKey key; HRESULT hr; RegData rd; if ((hr = key.Open(hkey, lpszKeyName, flag)) == ERROR_SUCCESS) { TCHAR tszValue[MAX_PATH] = {0}; ULONG lLen = MAX_PATH; DWORD dwInfo; if (key.QueryStringValue(lpszValuename, tszValue, &lLen) == ERROR_SUCCESS){ std::wstring wstrInfo = tszValue; rd.strData = wstrInfo; } else if((key.QueryDWORDValue(lpszValuename, dwInfo) == ERROR_SUCCESS)){ rd.dwData = dwInfo; } key.Close(); } return rd; }
bool IsPDFPrinterInstalled(std::tstring& stReason) { const _bstr_t c_sAmynuProgId = _T("CDIntfEx.CDIntfEx"); try { CLSID clsid = {0}; HRESULT hr = CLSIDFromProgID(c_sAmynuProgId, &clsid); if (S_OK != hr) throw Workshare::Com::ComException(_T("PDF converter not installed."), hr); ATL::CRegKey printerRegistry; const TCHAR c_sRegistryKey[] = _T("Software\\Microsoft\\Windows NT\\CurrentVersion\\Devices\0"); LONG lResult = printerRegistry.Open(HKEY_CURRENT_USER, c_sRegistryKey, KEY_READ); if(ERROR_SUCCESS != lResult) { CStdString sMessage; sMessage.Format(_T("Failed to open the key \"%s\" for reading the configured PDF printer"), c_sRegistryKey); throw Workshare::System::SystemException(_T("Failed to open the registry to read the configured PDF printer"), lResult); } TCHAR szData[MAX_PATH]; ULONG ulSize(sizeof(szData)/sizeof(szData[0])); lResult = printerRegistry.QueryStringValue(c_sPDFDriverName, szData, &ulSize); if(ERROR_SUCCESS != lResult) { CStdString sMessage; sMessage.Format(_T("The PDF converter is not correctly installed. The printer \"%s\" needs to be installed. Rerun the installation of the PDF printer."), c_sPDFDriverName); throw Workshare::System::SystemException(sMessage.c_str(), lResult); } } catch(const Workshare::Exception& e) { stReason = e.Message; return false; } catch(...) { unexpected(); } return true; }
DWORD AddinHelper::GetIntervalTime() const { TSAUTO(); DWORD dwResult = 3600; std::wstring subKey = L"Software\\"; subKey += this->m_productName; subKey += L"Host"; if (this->m_isService) { DWORD dwSessionId = ::WTSGetActiveConsoleSessionId(); HANDLE hUserToken = NULL; if(!::WTSQueryUserToken(dwSessionId, &hUserToken)) { TSERROR4CXX("WTSQueryUserToken fail. Error: " << ::GetLastError()); return dwResult; } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseUserToken(hUserToken, ::CloseHandle); TOKEN_ELEVATION_TYPE tokenElevationType; DWORD dwSize = sizeof(TOKEN_ELEVATION_TYPE); if(!::GetTokenInformation(hUserToken, TokenElevationType, &tokenElevationType, dwSize, &dwSize)) { TSERROR4CXX("GetTokenInformation TokenElevationType fail." << ::GetLastError()); return dwResult; } HANDLE hDuplicateToken = NULL; if(tokenElevationType == TokenElevationTypeLimited) { TOKEN_LINKED_TOKEN linkedToken; dwSize = sizeof(TOKEN_LINKED_TOKEN); if (!::GetTokenInformation(hUserToken, TokenLinkedToken, &linkedToken, dwSize, &dwSize)) { TSERROR4CXX("GetTokenInformation TokenLinkedToken fail. Error: " << ::GetLastError()); return dwResult; } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseLinkedToken(linkedToken.LinkedToken, ::CloseHandle); if(!::DuplicateTokenEx(linkedToken.LinkedToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hDuplicateToken)) { TSERROR4CXX("DuplicateTokenEx fail. Error: " << ::GetLastError()); return dwResult; } } else { if(!::DuplicateTokenEx(hUserToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hDuplicateToken)) { TSERROR4CXX("DuplicateTokenEx fail. Error: " << ::GetLastError()); return dwResult; } } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseDuplicateToken(hDuplicateToken, ::CloseHandle); TCHAR szUsername[MAX_PATH]; DWORD dwUsernameLen = MAX_PATH; PROFILEINFO pi; std::memset(&pi, 0, sizeof(PROFILEINFO)); pi.dwSize = sizeof(PROFILEINFO); if(!ImpersonateLoggedOnUser(hDuplicateToken)) { TSERROR4CXX("ImpersonateLoggedOnUser failed."); return dwResult; } DWORD dwUserNameLength = MAX_PATH; if(!::GetUserName(szUsername, &dwUserNameLength)) { TSERROR4CXX("GetUserName failed."); ::RevertToSelf(); return dwResult; } ::RevertToSelf(); pi.lpUserName = szUsername; pi.dwFlags = 1; if(!::LoadUserProfile(hDuplicateToken, &pi)) { TSERROR4CXX("LoadUserProfile failed."); return dwResult; } do { ATL::CRegKey key; if (key.Open((HKEY)pi.hProfile, subKey.c_str()) != ERROR_SUCCESS) { break; } DWORD dwInterval = 0; if(key.QueryDWORDValue(L"interval", dwInterval)!= ERROR_SUCCESS) { break; } dwResult = dwInterval; } while(false); ::UnloadUserProfile(hDuplicateToken, pi.hProfile); } else { ATL::CRegKey key; TSERROR4CXX("GetIntervalTime subKey: " << subKey.c_str()); if(key.Open(HKEY_CURRENT_USER, subKey.c_str()) != ERROR_SUCCESS) { return dwResult; } DWORD dwInterval = 0; if(key.QueryDWORDValue(L"interval", dwInterval)!= ERROR_SUCCESS) { return dwResult; } dwResult = dwInterval; TSERROR4CXX("GetIntervalTime dwInterval: " << dwInterval); } if (dwResult < 600) { dwResult = 600; } return dwResult; }
HRESULT UninstallService() { TSAUTO(); ATL::CRegKey key; LSTATUS lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost"); if(lRegResult == ERROR_SUCCESS) { lRegResult = key.DeleteValue(L"ADCleanService"); if(lRegResult != ERROR_SUCCESS) { TSWARN4CXX("Failed to delete reg value. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost\\ADCleanService. Error: " << lRegResult); } key.Close(); } else { TSWARN4CXX("Failed to open reg key. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost. Error: " << lRegResult); } lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\ADCleanService"); if(lRegResult == ERROR_SUCCESS) { lRegResult = key.RecurseDeleteKey(L"Parameters"); if(lRegResult != ERROR_SUCCESS) { TSWARN4CXX("Failed to delete reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters. Error: " << lRegResult); } key.Close(); } else { TSWARN4CXX("Failed to open reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService. Error: " << lRegResult); } SC_HANDLE schSCManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if(schSCManager == NULL) { DWORD dwOpenError = ::GetLastError(); TSERROR4CXX("OpenSCManager failed. Error: " << dwOpenError); return HRESULT_FROM_WIN32(dwOpenError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseSCManagerHandle(schSCManager, ::CloseServiceHandle); SC_HANDLE schService = ::OpenService(schSCManager, szServiceName, DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS); if(schService == NULL) { DWORD dwOpenError = ::GetLastError(); TSERROR4CXX("OpenSCManager failed. Error: " << dwOpenError); return HRESULT_FROM_WIN32(dwOpenError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseServiceHandle(schService, ::CloseServiceHandle); SERVICE_STATUS_PROCESS ssp; DWORD dwBytesNeeded = 0; if(!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { DWORD dwQueryServiceStatus = ::GetLastError(); TSERROR4CXX("QueryServiceStatusEx failed. Error: " << dwQueryServiceStatus); return HRESULT_FROM_WIN32(dwQueryServiceStatus); } if(ssp.dwCurrentState != SERVICE_STOPPED) { DWORD dwStartTime = GetTickCount(); DWORD dwTimeout = 30000; while (ssp.dwCurrentState == SERVICE_STOP_PENDING) { DWORD dwWaitTime = ssp.dwWaitHint / 10; if( dwWaitTime < 1000 ) dwWaitTime = 1000; else if ( dwWaitTime > 10000 ) dwWaitTime = 10000; Sleep(dwWaitTime); if(!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { DWORD dwQueryServiceStatus = ::GetLastError(); TSERROR4CXX("QueryServiceStatusEx failed. Error: " << dwQueryServiceStatus); return HRESULT_FROM_WIN32(dwQueryServiceStatus); } if(ssp.dwCurrentState == SERVICE_STOPPED) { TSINFO4CXX("Service Stop Success."); goto AfterStopLabel; } if(GetTickCount() - dwStartTime > dwTimeout) { TSERROR4CXX("Wait for service stop timeout."); return E_FAIL; } } if(!ControlService(schService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp)) { DWORD dwControlServiceError = ::GetLastError(); TSERROR4CXX("ControlService failed. Error: " << dwControlServiceError); return HRESULT_FROM_WIN32(dwControlServiceError); } while ( ssp.dwCurrentState != SERVICE_STOPPED ) { DWORD dwWaitTime = ssp.dwWaitHint; if( dwWaitTime < 1000 ) dwWaitTime = 1000; else if ( dwWaitTime > 10000 ) dwWaitTime = 10000; Sleep(dwWaitTime); if(!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { DWORD dwQueryServiceStatus = ::GetLastError(); TSERROR4CXX("QueryServiceStatusEx failed. Error: " << dwQueryServiceStatus); return HRESULT_FROM_WIN32(dwQueryServiceStatus); } if(ssp.dwCurrentState == SERVICE_STOPPED) { TSINFO4CXX("Service Stop Success."); break; } if(GetTickCount() - dwStartTime > dwTimeout ) { TSERROR4CXX("Wait timed out"); return E_FAIL; } } } AfterStopLabel: if(::DeleteService(schService)) { TSERROR4CXX("DeleteService success"); return S_OK; } else { DWORD dwDeleteError = ::GetLastError(); TSERROR4CXX("DeleteService failed. Error: " << dwDeleteError); return HRESULT_FROM_WIN32(dwDeleteError); } }
void AddinHelper::LaunchExe() { TSDEBUG4CXX("LaunchExe , enter Now = "<<::GetTickCount()); BOOL bFirst = TodayNotDo(); if (bFirst){ SendState::Send("explorerplugin_startup", "explorerplugin"); } else{ SendState::Send("explorerplugin_timer", "explorerplugin"); } //判断地域标志 DWORD dwLastUTC = 0; DWORD dwZoneAllow = 0; BOOL bCando = FALSE; ATL::CRegKey key; if (!bFirst && key.Open(HKEY_CURRENT_USER, REGEDITPATH) == ERROR_SUCCESS) { bCando = TRUE; if (key.QueryDWORDValue(ZONESWITCH, dwZoneAllow) != ERROR_SUCCESS || dwZoneAllow != 1){ bCando = FALSE; } else if(key.QueryDWORDValue(LASTLAUNCHUTC, dwLastUTC) == ERROR_SUCCESS) { __time64_t tTime = (__time64_t)dwLastUTC; tm* pTm = _localtime64(&tTime); LONG nLastDay = pTm->tm_mday; LONG nLastMonth = pTm->tm_mon; LONG nLastYear = pTm->tm_year; __time64_t lCurTime; _time64( &lCurTime); tm* pTmc = _localtime64(&lCurTime); LONG nCurDay = pTmc->tm_mday; LONG nCurMonth = pTmc->tm_mon; LONG nCurYear = pTmc->tm_year; TSDEBUG4CXX("check time pTmc = "<<nCurYear<<nCurMonth<<nCurDay<<", pTm = "<<nLastYear<<nLastMonth<<nLastDay); if (nCurDay == nLastDay && nCurMonth == nLastMonth && nCurYear == nLastYear){ bCando = FALSE; } else{ bCando = TRUE; } } key.Close(); } TSDEBUG4CXX("LaunchExe , bCando = "<<bCando); if (!bFirst && !bCando){ return; } if (!bFirst && IsStartUp()){ return; } RegData rd = QueryRegVal(HKEY_LOCAL_MACHINE, REGEDITPATH, _T("Path"), KEY_READ | KEY_WOW64_32KEY); TSDEBUG4CXX("LaunchExe rd.strData = "<<rd.strData.c_str()); if (rd.strData == L"" || !PathFileExists(rd.strData.c_str())){ return; } TCHAR* tszProName = PathFindFileName(rd.strData.c_str()); if (!bFirst && QueryProcessExist(tszProName)){ TSDEBUG4CXX("LaunchExe process exist "<<tszProName); return; } SHELLEXECUTEINFO sei; std::memset(&sei, 0, sizeof(SHELLEXECUTEINFO)); sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.lpFile = rd.strData.c_str(); sei.lpParameters = L"/sstartfrom explorerplugin /embedding"; sei.nShow = SW_SHOWNORMAL; ShellExecuteEx(&sei); TSDEBUG4CXX("LaunchExe rd.strData.c_str() = "<<rd.strData.c_str()); if (bFirst){ ATL::CRegKey key; if (key.Open(HKEY_CURRENT_USER, REGEDITPATH) == ERROR_SUCCESS) { __time64_t lCurTime; _time64( &lCurTime); key.SetDWORDValue(L"pluginlastutc", lCurTime); key.Close(); } } }
void CFileTypesForm::OnBnClickedButtonReload() { for (DWORD i=0; i<pageCount; i++) { if (pages[i]) { pages[i]->info.Clear(); pages[i]->UpdateTree(); } } DSUtil::FilterTemplates filters; filters.EnumerateAllRegisteredFilters(); // search for registered protocols if (page_protocols) { ATL::CRegKey rkRoot(HKEY_CLASSES_ROOT); // only real protocols => not something like "WMP11.AssocProtocol.MMS" // faster, because i don't need to search in every entry for "Source Filter" TCHAR szName[10] = {0}; DWORD szNameLength = 10; DWORD i = 0; long ret = 0; while (ERROR_NO_MORE_ITEMS != (ret = rkRoot.EnumKey(i++, szName, &szNameLength))) { if (ret != ERROR_SUCCESS) continue; CRegKey rkKey; if(ERROR_SUCCESS == rkKey.Open(HKEY_CLASSES_ROOT, szName, KEY_READ)) { TCHAR szSourceFilterGuid[40] = {0}; DWORD szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("Source Filter"), szSourceFilterGuid, &szLength)) { GraphStudio::PropItem* group = new GraphStudio::PropItem(CString(szName)); CString strClsid = szSourceFilterGuid; GUID clsid = {0}; CLSIDFromString((LPOLESTR)strClsid.GetBuffer(), &clsid); group->AddItem(new GraphStudio::PropItem(_T("CLSID"), CString(szSourceFilterGuid), false)); DSUtil::FilterTemplate ft; if (filters.FindTemplateByCLSID(clsid, &ft)) { group->AddItem(new GraphStudio::PropItem(_T("Name"), CString(ft.name), false)); group->AddItem(new GraphStudio::PropItem(_T("File"), CString(ft.file), false)); } // last Change of this key FILETIME timeMod = {0}; if (ERROR_SUCCESS == RegQueryInfoKey(rkKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &timeMod)) group->AddItem(new GraphStudio::PropItem(_T("Modified"), CTime(timeMod))); page_protocols->info.AddItem(group); } } rkKey.Close(); szNameLength = 10; } page_protocols->UpdateTree(); rkRoot.Close(); } // search for registered extensions if (page_extensions) { ATL::CRegKey rkRoot; CString strRoot = _T("Media Type\\Extensions"); if (ERROR_SUCCESS == rkRoot.Open(HKEY_CLASSES_ROOT, strRoot, KEY_READ)) { // {7DF62B50-6843-11D2-9EEB-006008039E37} static const GUID CLSID_StillVideo = {0x7DF62B50, 0x6843, 0x11D2, { 0x9E, 0xEB, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37} }; TCHAR szName[50] = {0}; DWORD szNameLength = 50; DWORD i = 0; while (ERROR_NO_MORE_ITEMS != rkRoot.EnumKey(i++, szName, &szNameLength)) { CString strKey = strRoot; strKey.Append(_T("\\")); strKey.Append(szName); CRegKey rkKey; if(ERROR_SUCCESS == rkKey.Open(HKEY_CLASSES_ROOT, strKey, KEY_READ)) { GraphStudio::PropItem* group = new GraphStudio::PropItem(CString(szName)); TCHAR szGuid[40] = {0}; DWORD szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("Source Filter"), szGuid, &szLength)) { CString strClsid = szGuid; GUID clsid = {0}; CLSIDFromString((LPOLESTR)strClsid.GetBuffer(), &clsid); group->AddItem(new GraphStudio::PropItem(_T("CLSID"), CString(szGuid), false)); DSUtil::FilterTemplate ft; if (filters.FindTemplateByCLSID(clsid, &ft)) { group->AddItem(new GraphStudio::PropItem(_T("Name"), CString(ft.name), false)); group->AddItem(new GraphStudio::PropItem(_T("File"), CString(ft.file), false)); } else if (clsid == CLSID_StillVideo) { group->AddItem(new GraphStudio::PropItem(_T("Name"), _T("Generate Still Video"), false)); } } szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("Media Type"), szGuid, &szLength)) { CString strMT; GUID clsidMT = {0}; CLSIDFromString((LPOLESTR)strMT.GetBuffer(), &clsidMT); GraphStudio::NameGuid(clsidMT,strMT,CgraphstudioApp::g_showGuidsOfKnownTypes); group->AddItem(new GraphStudio::PropItem(_T("MediaType"), strMT, false)); } szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("SubType"), szGuid, &szLength)) { CString strST = szGuid; GUID clsidST = {0}; CLSIDFromString((LPOLESTR)strST.GetBuffer(), &clsidST); GraphStudio::NameGuid(clsidST,strST,CgraphstudioApp::g_showGuidsOfKnownTypes); group->AddItem(new GraphStudio::PropItem(_T("SubType"), strST, false)); } // last Change of this key FILETIME timeMod = {0}; if (ERROR_SUCCESS == RegQueryInfoKey(rkKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &timeMod)) group->AddItem(new GraphStudio::PropItem(_T("Modified"), CTime(timeMod))); page_extensions->info.AddItem(group); } rkKey.Close(); szNameLength = 50; } page_extensions->UpdateTree(); } rkRoot.Close(); } // search for registered byte pattern if (page_bytes) { ATL::CRegKey rkRoot; CString strRoot = _T("Media Type"); if (ERROR_SUCCESS == rkRoot.Open(HKEY_CLASSES_ROOT, strRoot, KEY_READ)) { TCHAR szMTName[40] = {0}; DWORD szMTNameLength = 40; DWORD i = 0; while (ERROR_NO_MORE_ITEMS != rkRoot.EnumKey(i++, szMTName, &szMTNameLength)) { CString strMT = szMTName; GUID clsidMT = {0}; if(NOERROR == CLSIDFromString((LPOLESTR)strMT.GetBuffer(), &clsidMT)) { GraphStudio::NameGuid(clsidMT,strMT,false); CString strKeyMT = strRoot; strKeyMT.Append(_T("\\")); strKeyMT.Append(szMTName); CRegKey rkKeyMT; if(ERROR_SUCCESS == rkKeyMT.Open(HKEY_CLASSES_ROOT, strKeyMT, KEY_READ)) { TCHAR szSTName[40] = {0}; DWORD szSTNameLength = 40; DWORD j = 0; while (ERROR_NO_MORE_ITEMS != rkKeyMT.EnumKey(j++, szSTName, &szSTNameLength)) { CString strST = szSTName; GUID clsidST = {0}; if(NOERROR == CLSIDFromString((LPOLESTR)strST.GetBuffer(), &clsidST)) { GraphStudio::NameGuid(clsidST,strST,false); CString strKeyST = strKeyMT; strKeyST.Append(_T("\\")); strKeyST.Append(szSTName); CRegKey rkKeyST; if(ERROR_SUCCESS == rkKeyST.Open(HKEY_CLASSES_ROOT, strKeyST, KEY_READ)) { TCHAR szGuid[40] = {0}; DWORD szLength = 40; if (ERROR_SUCCESS == rkKeyST.QueryStringValue(_T("Source Filter"), szGuid, &szLength)) { CString groupName = strMT; groupName.Append(_T("\\")); groupName.Append(strST); GraphStudio::PropItem* group = new GraphStudio::PropItem(groupName); CString strClsid = szGuid; GUID clsid = {0}; CLSIDFromString((LPOLESTR)strClsid.GetBuffer(), &clsid); group->AddItem(new GraphStudio::PropItem(_T("CLSID"), CString(szGuid), false)); DSUtil::FilterTemplate ft; if (filters.FindTemplateByCLSID(clsid, &ft)) { group->AddItem(new GraphStudio::PropItem(_T("Name"), CString(ft.name), false)); group->AddItem(new GraphStudio::PropItem(_T("File"), CString(ft.file), false)); } // Enumerate the values TCHAR szValueName[5] = {0}; DWORD szValueNameLength = 5; DWORD dwRegType; DWORD k = 0; long ret = 0; while (ERROR_NO_MORE_ITEMS != (ret = RegEnumValue(rkKeyST, k++, szValueName, &szValueNameLength, NULL, &dwRegType, NULL, NULL))) { if (dwRegType == REG_SZ && ret == ERROR_SUCCESS) { TCHAR szValue[255] = {0}; DWORD szValueLength = 255; if (ERROR_SUCCESS == rkKeyST.QueryStringValue(szValueName, szValue, &szValueLength)) { CString strValue = szValue; CStringArray arValues; DSUtil::Tokenizer(strValue, _T(","), arValues); CString strResultValue; bool lastTokenWasEmpty = false; for (int i=0; i<arValues.GetCount(); i++) { CString strToken = arValues.GetAt(i); strToken = strToken.Trim(); switch (i % 4) { case 0: if (i > 0) strResultValue.Append(_T(" && [")); else strResultValue.Append(_T("[")); strResultValue.Append(strToken); break; case 1: strResultValue.Append(_T(",")); strResultValue.Append(strToken); break; case 2: strResultValue.Append(_T("] => (")); strResultValue.Append(ByteFormatString(strToken)); break; case 3: if (!lastTokenWasEmpty) strResultValue.Append(_T(" = ")); strResultValue.Append(ByteFormatString(strToken)); strResultValue.Append(_T(")")); break; } lastTokenWasEmpty = strToken.IsEmpty(); } group->AddItem(new GraphStudio::PropItem(CString(szValueName), strResultValue, false)); // TODO maybe better format of the byte string } } szValueNameLength = 5; } // last Change of this key FILETIME timeMod = {0}; if (ERROR_SUCCESS == RegQueryInfoKey(rkKeyST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &timeMod)) group->AddItem(new GraphStudio::PropItem(_T("Modified"), CTime(timeMod))); page_bytes->info.AddItem(group); } } rkKeyST.Close(); } szSTNameLength = 40; } } rkKeyMT.Close(); } szMTNameLength = 40; } page_bytes->UpdateTree(); } rkRoot.Close(); } }
void CCrashHandler::GenerateErrorReport(PEXCEPTION_POINTERS pExInfo) { CExceptionReport rpt(pExInfo); CMainDlg mainDlg; CZLib zlib; CString sTempFileName = CUtility::getTempFileName(); unsigned int i; // let client add application specific files to report if (m_lpfnCallback && !m_lpfnCallback(this)) return; //Определеяем, что делать с отчетом DumpType dumpType = Referenced;//По умолчанию сбрасываем только ту память, на которую идут ссылки в стеке ActionType actionType = GUI;//По умолчанию - выводим пользователю диалог CString action, storeFolder, dump; ATL::CRegKey rk; //Читаем из ключа с именем приложения int32_t lRet = rk.Open(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cognitive Technologies Ltd.\\CuneiForm\\PumaCrashRpt\\") + CUtility::getAppName(), KEY_QUERY_VALUE); if(lRet != ERROR_SUCCESS) { //Читаем из дефолтного ключа lRet = rk.Open(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cognitive Technologies Ltd.\\CuneiForm\\PumaCrashRpt\\Default"), KEY_QUERY_VALUE); } if(lRet == ERROR_SUCCESS) { //Читаем дейтсвие uint32_t dwBufLen = 1000; rk.QueryValue(action.GetBuffer(1000), "Action", &dwBufLen); action.ReleaseBuffer(MAX(dwBufLen - 1, 0)); //Читаем папку для автосохранения dwBufLen = 1000; rk.QueryValue(storeFolder.GetBuffer(1000), "StoreFolder", &dwBufLen); storeFolder.ReleaseBuffer(MAX(dwBufLen - 1, 0)); //Читаем тип дампа dwBufLen = 1000; rk.QueryValue(dump.GetBuffer(1000), "DumpType", &dwBufLen); dump.ReleaseBuffer(MAX(dwBufLen - 1, 0)); rk.Close(); if (!action.IsEmpty()) { if (action.CompareNoCase("GUI") == 0) actionType = GUI; else if (action.CompareNoCase("QuietStore") == 0) actionType = QuietStore; else if (action.CompareNoCase("NoAction") == 0) actionType = NoAction; } if (!dump.IsEmpty()) { if (dump.CompareNoCase("Mini") == 0) dumpType = Mini; else if (dump.CompareNoCase("Referenced") == 0) dumpType = Referenced; else if (dump.CompareNoCase("Full") == 0) dumpType = Full; } if (storeFolder.CompareNoCase("Temp folder") == 0) storeFolder = getenv("TEMP"); } if (actionType == NoAction) return; // add crash files to report m_files[rpt.getCrashFile(dumpType)] = CString((const char *)IDS_CRASH_DUMP); m_files[rpt.getCrashLog()] = CString((const char *)IDS_CRASH_LOG); // add symbol files to report for (i = 0; i < (uint)rpt.getNumSymbolFiles(); i++) m_files[(const char *)rpt.getSymbolFile(i)] = CString((const char *)IDS_SYMBOL_FILE); // zip the report if (!zlib.Open(sTempFileName)) return; // add report files to zip TStrStrMap::iterator cur = m_files.begin(); for (i = 0; i < m_files.size(); i++, cur++) zlib.AddFile((*cur).first); zlib.Close(); if (actionType == GUI) { // display main dialog mainDlg.m_pUDFiles = &m_files; //Сохраняем флаги по исключениям с плавающей точкой - кто-то их злобно сбрасывает при показе диалога uint oldFpState = _controlfp(0, 0); if (IDOK == mainDlg.DoModal()) { if (m_sTo.IsEmpty() || !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription)) { SaveReport(rpt, sTempFileName); } } //Восстанавливаем флаги _controlfp(oldFpState, _MCW_DN | _MCW_EM | _MCW_IC | _MCW_RC | _MCW_PC); } else if (actionType == QuietStore) { // Just in-case it already exist ::DeleteFile(storeFolder + '\\' + CUtility::formatSaveFileName() + ".zip"); ::CopyFile(sTempFileName, storeFolder + '\\' + CUtility::formatSaveFileName() + ".zip", TRUE); } DeleteFile(sTempFileName); }
HRESULT CreateGreenShieldService(const wchar_t* szDllPath) { TSAUTO(); SC_HANDLE schSCManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager == NULL) { DWORD dwOpenError = ::GetLastError(); TSERROR4CXX("OpenSCManager failed. Error: " << dwOpenError); return HRESULT_FROM_WIN32(dwOpenError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseSCManagerHandle(schSCManager, ::CloseServiceHandle); const wchar_t* szImagePath = L"%SystemRoot%\\System32\\svchost.exe -k ADCleanService"; SC_HANDLE schService = ::CreateService( schSCManager, szServiceName, szServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_SHARE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szImagePath, NULL, NULL, NULL, NULL, NULL); if(schService == NULL) { DWORD dwCreateError = ::GetLastError(); TSERROR4CXX("CreateService failed. Error: " << dwCreateError); return HRESULT_FROM_WIN32(dwCreateError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseServiceHandle(schService, ::CloseServiceHandle); SERVICE_DESCRIPTION description = { L"广告清道夫实时过滤服务。" }; ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &description); // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ADCleanService ATL::CRegKey key; LONG lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\ADCleanService", KEY_READ); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Filed to open reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } key.Close(); // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ADCleanService\Parameters lRegResult = key.Create(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters"); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to create reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } lRegResult = key.SetStringValue(L"ServiceDll", szDllPath, REG_EXPAND_SZ); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to set reg value. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters\\ServiceDll. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } key.Close(); // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost"); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to open reg key. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } lRegResult = key.SetMultiStringValue(L"ADCleanService", L"ADCleanService\0"); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to set reg value. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost\\ADCleanService. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } // start service ::StartService(schService, 0, NULL); return S_OK; }