bool WindowsProcessInOut::createOutputFile() { SAFE_CLOSE_HANDLE_AND_RESET(outputFileHandle_); if (outputFileName_.empty())//如果文件名为空,表示不需要此句柄 return true; SECURITY_ATTRIBUTES saAttr = {0}; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; outputFileHandle_ = CreateFileW(outputFileName_.c_str(), GENERIC_WRITE, FILE_SHARE_READ, &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == outputFileHandle_) { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); OJString msg(GetOJString("[process] - createOutputFile - can't create output file: ")); msg += outputFileName_; logger->logError(msg); outputFileHandle_ = NULL; } return outputFileHandle_ != NULL; }
virtual DWORD OnStart() { if (m_pLogger == NULL || m_hExited == NULL) { Stop(); return ERROR_SUCCESS; } m_pLogger->SetLogFileName(SERVICE_NAME); m_pLogger->SetAddDateBefore(false); m_pLogger->WriteLog(LM_INFO, TEXT("=============================")); m_pLogger->SetAddDateBefore(true); if (OneInstance()) { Stop(); return ERROR_SUCCESS; } if ((m_hThread = (HANDLE)_beginthreadex(NULL, 0, WorkThread, this, 0, NULL)) == NULL) { Stop(); return ERROR_SUCCESS; } return ERROR_SUCCESS; }
bool PoolSimVector::apply (PoolSimVector::Values requests, ILogger& logger) { if (requests.size() != _pools.size()) { // both vectors need to have same size logger.fatal("Invalid number %d of pool requests (%d pools defined)\n", requests.size(), _pools.size()); return false; } // now do real alloc for(int i=0; i<_pools.size(); i++) { int r = requests[i]; if (r != 0) { if (_pools[i]->mayAlloc(requests[i])) { // allocation in range, do it _pools[i]->alloc(requests[i]); logger.log("POOL", "pool %s/%d: request %d, now %d\n", _pools[i]->getName(), i, r, _pools[i]->getAllocated()); } else { // overflow or underflow if (r>0) { logger.log("POOL", "pool %s/%d: overflow %d\n", _pools[i]->getName(), i, r); } else { logger.log("POOL", "pool %s/%d: underflow %d\n", _pools[i]->getName(), i, r); } } } } return true; }
bool CI8DeskSvr::StartRemoteControl() { stdex::tString strFilePath = utility::GetAppPath() + _T("WinVNC\\"); SetDllDirectory(strFilePath.c_str()); strFilePath += TEXT("WinVNC.dll"); m_hRemoteCtrl = LoadLibrary(strFilePath.c_str()); if (m_hRemoteCtrl == NULL) return false; typedef BOOL (WINAPI* PFNSTARTVNC)(); PFNSTARTVNC pfnStartVNC = GetProcAddress(m_hRemoteCtrl, "_StartVNC@0"); if (pfnStartVNC == NULL) return false; try { pfnStartVNC(); } catch(...) { m_pLogger->WriteLog(LM_INFO, TEXT("加载远程控制客户端失败。\r\n")); BOOL (WINAPI* pfnStopVNC)(); pfnStopVNC = GetProcAddress(m_hRemoteCtrl, "_StopVNC@0"); if (pfnStopVNC == NULL) return false; pfnStopVNC(); } m_pLogger->WriteLog(LM_INFO, TEXT("加载远程控制客户端成功。\r\n")); return true; }
bool JudgeTask::compile() { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); logger->logTrace(OJStr("[JudgeTask] start compile...")); CompilerPtr compiler = CompilerFactory::create(Input.Language); compiler->run(codeFile_, exeFile_, compileFile_); if(compiler->isAccept()) { output_.Result = AppConfig::JudgeCode::Accept; } else if(compiler->isSystemError()) { output_.Result = AppConfig::JudgeCode::SystemError; } else if(compiler->isCompileError()) { output_.Result = AppConfig::JudgeCode::CompileError; std::vector<OJChar_t> buffer; if(FileTool::ReadFile(buffer, compileFile_) && !buffer.empty()) { output_.CompileError = &buffer[0]; } } return compiler->isAccept(); }
bool RemoveFile(const OJString &filename) { if (IsFileExist(filename)) { fs::path fullpath(filename); sys::error_code err; bool res = fs::remove(fullpath, err); if (!(sys::errc::success == err)) { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); OJString msg(GetOJString("[filetool] - IMUST::RemoveFile - remove failed: ")); msg += filename; msg += GetOJString(" - "); msg += String2OJString(err.message()); logger->logError(msg); return false; } return res; } return true; }
bool JudgeTask::match() { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); logger->logTrace(OJStr("[JudgeTask] start match...")); MatcherPtr matcher = MatcherFactory::create(false, OJStr("")); matcher->run(answerOutputFile_, userOutputFile_); if(matcher->isAccept()) { output_.Result = AppConfig::JudgeCode::Accept; } else if(matcher->isPresentError()) { output_.Result = AppConfig::JudgeCode::PresentError; } else if(matcher->isWrongAnswer()) { output_.Result = AppConfig::JudgeCode::WrongAnswer; } else if(matcher->isSystemError()) { output_.Result = AppConfig::JudgeCode::SystemError; } return matcher->isAccept(); }
bool MakeDir(const OJString &path) { if (!IsDirExist(path)) { fs::path fullpath(path); sys::error_code err; bool res = fs::create_directory(fullpath, err); if (!(sys::errc::success == err)) { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); OJString msg(GetOJString("[filetool] - IMUST::MakeDir - make dir failed: ")); msg += path; msg += GetOJString(" - "); msg += String2OJString(err.message()); logger->logError(msg); return false; } return res; } return true; }
IPluginObject *Factory::CreateObject(ISystem *pSys, const char *identifier) { ILogger *pLogger = pSys->GetLogger("Enigma.Factory"); IPluginObject *pObject = NULL; pLogger->Debug("Trying '%s'", identifier); // if (!strcmp(identifier, "enigma.Starfield")) { // pObject = dynamic_cast<IPluginObject *>(new TestTriangleGenerator()); // } if (!strcmp(identifier, "enigma.RenderTVBox")) { pObject = dynamic_cast<IPluginObject *>(new EnigmaTVBox()); } if (!strcmp(identifier, "enigma.Starfield")) { pObject = dynamic_cast<IPluginObject *>(new Starfield()); } if (!strcmp(identifier, "enigma.RayTracer")) { pObject = dynamic_cast<IPluginObject *>(new RayTracer()); } if (!strcmp(identifier, "enigma.RayTracer.Sphere")) { pObject = dynamic_cast<IPluginObject *>(new Sphere()); } if (pObject != NULL) { pLogger->Debug("Ok"); } else pLogger->Debug("Failed"); return pObject; }
ILogger *Logger::GetLogger(const char *name) { ILogger *pLogger = NULL; LoggerInstance *pInstance; ILoggerList::iterator it; Initialize(); it = loggers.begin(); while(it != loggers.end()) { pInstance = (LoggerInstance *)*it; pLogger = pInstance->pLogger; if (!strcmp(pLogger->GetName(), name)) { return pLogger; } it++; } // Have to create a new logger pLogger = (ILogger *)new Logger(name); pInstance = new LoggerInstance(pLogger); // TODO: Support for exclude list loggers.push_back(pInstance); return pLogger; }
void BusinessAction::saveRecord() { ILogger* logger = this->getLogger(); if (logger) { ILoggerRecord* record = this->generateRecord(); logger->addRecord(record); } }
bool CCliMgr::UnInitialize() { if (m_pLogger) { m_pLogger->WriteLog(LM_INFO, TEXT("Plug UnInitialize")); m_pLogger->SetAddDateBefore(false); m_pLogger->WriteLog(LM_INFO, TEXT("=========================================================\r\n\r\n")); } return true; }
Stat operator()(const std::string& name, unsigned iterations, ILogger& logger, TF&& functor, TArgs&&... args) { Stat stat; if(m_startlog_enabled) logger.logStart(name, iterations); stat = bench(iterations, functor, std::forward(args)...); if(m_endlog_enabled) logger.logEnd(name, iterations, stat); return stat; }
IPluginObject *CurveFactory::CreateObject(ISystem *pSys, const char *identifier) { ILogger *pLogger = pSys->GetLogger("StdCurve.Factory");//Logger::GetLogger("StdCurve.Factory"); IPluginObject *pObject = NULL; pLogger->Debug("Trying '%s'", identifier); if (!strcmp(identifier,"Animation.GenericCurve")) { pObject = dynamic_cast<IPluginObject *> (new YaptCurveFacade()); } if (!strcmp(identifier,"Animation.Key")) { pObject = dynamic_cast<IPluginObject *> (new GenericCurveKey()); } if (!strcmp(identifier,"Animation.VectorKey")) { pObject = dynamic_cast<IPluginObject *> (new VectorCurveKey()); } if (!strcmp(identifier,"Animation.ExpSolver")) { pObject = dynamic_cast<IPluginObject *> (new YaptExpSolverFacade()); } if (!strcmp(identifier,"Animation.Expression")) { pObject = dynamic_cast<IPluginObject *> (new YaptExpSolverFacade()); } if (!strcmp(identifier,"Animation.VectorExpression")) { pObject = dynamic_cast<IPluginObject *> (new YaptVecExpSolverFacade()); } if (!strcmp(identifier,"Numeric.VectorMux")) { pObject = dynamic_cast<IPluginObject *> (new VectorMux()); } if (!strcmp(identifier,"Numeric.IntMinMax")) { pObject = dynamic_cast<IPluginObject *> (new IntMinMax()); } if (!strcmp(identifier,"Numeric.FloatToInt")) { pObject = dynamic_cast<IPluginObject *> (new FloatToInt()); } if (!strcmp(identifier,"Numeric.VectorElement")) { pObject = dynamic_cast<IPluginObject *> (new VectorElement()); } if (pObject != NULL) { pLogger->Debug("Ok"); } else pLogger->Debug("Failed"); return pObject; }
void JudgeThread::operator()() { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); OJString infoBuffer; FormatString(infoBuffer, OJStr("work/%d"), id_); FileTool::MakeDir(infoBuffer); FormatString(infoBuffer, OJStr("[JudgeThread][%d]start..."), id_); logger->logTrace(infoBuffer); while (!g_sigExit) { IMUST::TaskPtr pTask; //从任务队列取任务 workingTaskMgr_->lock(); if(workingTaskMgr_->hasTask()) { pTask = workingTaskMgr_->popTask(); } workingTaskMgr_->unlock(); if(!pTask)//没有任务 { OJSleep(1000); continue; } pTask->init(id_); if(!pTask->run()) { FormatString(infoBuffer, OJStr("[JudgeThread][%d]System Error!Judge thread will exit!"), id_); logger->logError(infoBuffer); break; } //添加到完成队列 finisheTaskMgr_->lock(); finisheTaskMgr_->addTask(pTask); finisheTaskMgr_->unlock(); OJSleep(10);//防止线程过度繁忙 } FormatString(infoBuffer, OJStr("[JudgeThread][%d]end."), id_); logger->logTrace(infoBuffer); }
bool JudgeTask::excute() { ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); logger->logTrace(OJStr("[JudgeTask] start excute...")); OJString infoBuffer; if(!FileTool::IsFileExist(exeFile_)) { FormatString(infoBuffer, OJStr("[JudgeTask] not found exe file! %s."), exeFile_); logger->logError(infoBuffer); output_.Result = AppConfig::JudgeCode::SystemError; return false; } ExcuterPtr excuter = ExcuterFactory::create(Input.Language); excuter->run(exeFile_, answerInputFile_, userOutputFile_, Input.LimitTime, Input.LimitMemory); if(excuter->isAccept()) { output_.Result = AppConfig::JudgeCode::Accept; } else if(excuter->isSystemError()) { output_.Result = AppConfig::JudgeCode::SystemError; } else if(excuter->isOutputOutOfLimited()) { output_.Result = AppConfig::JudgeCode::OutputLimited; } else if(excuter->isTimeOutOfLimited()) { output_.Result = AppConfig::JudgeCode::TimeLimitExceed; } else if(excuter->isMemoryOutOfLimited()) { output_.Result = AppConfig::JudgeCode::MemoryLimitExceed; } else if(excuter->isRuntimeError()) { output_.Result = AppConfig::JudgeCode::RuntimeError; } output_.RunTime = excuter->getRunTime(); output_.RunMemory = excuter->getRunMemory(); return excuter->isAccept(); }
void CCliMgr::KillProcess(LPCTSTR lpszSvrName) { DWORD aProcesses[1024] = {0}, cbNeeded = 0, cProcesses = 0, MemSize = 0; if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded )) { DWORD dwError = GetLastError(); _com_error Error(dwError); m_pLogger->WriteLog(LM_INFO, TEXT("GetSysProcess (EnumProcess) Error:%d:%s"), dwError, Error.ErrorMessage()); return; } cProcesses = cbNeeded / sizeof(DWORD); tstring sModName = lpszSvrName; for (DWORD idx=0; idx<cProcesses; idx++) { TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>"); HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ|PROCESS_TERMINATE, FALSE, aProcesses[idx]); if (NULL != hProcess) { if (0 == GetModuleFileNameEx(hProcess, NULL, szProcessName, MAX_PATH)) { CloseHandle( hProcess ); continue; } string strProcName = ProcessImagePath(szProcessName); if (stricmp(sModName.c_str(), strProcName.c_str()) == 0) { TerminateProcess(hProcess,0); CloseHandle( hProcess ); return ; } CloseHandle( hProcess ); } } }
virtual DWORD OnStop() { ReportStatusToSCM(SERVICE_STOP_PENDING); if (m_hThread != NULL && m_hThread != NULL) { SetEvent(m_hExited); WaitForSingleObject(m_hThread, INFINITE); CloseHandle(m_hThread); m_hThread = NULL; } if (m_pLogger) { m_pLogger->WriteLog(LM_INFO, TEXT("%s: stoped."), GetSvrName()); m_pLogger->SetAddDateBefore(false); m_pLogger->WriteLog(LM_INFO, TEXT("=============================\r\n\r\n")); } KillService(TEXT("DNAService.exe")); return ERROR_SUCCESS; }
bool DBManager::run() { assert(sqlDriver_->valid() && "[DBManager]sql driver not valid!"); ILogger *logger = LoggerFactory::getLogger(LoggerId::AppInitLoggerId); if(!readTasks()) { logger->logError(GetOJString("[DBManager]read task faild!") + sqlDriver_->getErrorString()); return false; } if(!writeFinishedTask()) { logger->logError(GetOJString("[DBManager]write task faild!") + sqlDriver_->getErrorString()); return false; } return true; }
void CI8DeskSvr::FreeRemoteCtrlPlug() { if (m_hRemoteCtrl != NULL) { BOOL (WINAPI* pfnStopVNC)(); pfnStopVNC = GetProcAddress(m_hRemoteCtrl, "StopVNC"); if (pfnStopVNC != NULL) pfnStopVNC(); FreeLibrary(m_hRemoteCtrl); } m_hRemoteCtrl = NULL; m_pLogger->WriteLog(LM_INFO, TEXT("释放远程控制客户端成功。")); }
BOOL CCliMgr::RunProcess(LPCSTR lpImage, LPCSTR lpPara) { if(!lpImage) { return FALSE; } HANDLE hToken; if(!GetTokenByName(hToken, "explorer.exe")) { m_pLogger->WriteLog(LM_INFO, TEXT("OpenProcessToken Faile!")); return FALSE; } STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; si.cb= sizeof(STARTUPINFO); si.lpDesktop = TEXT("winsta0\\default"); LPVOID lpEnv = NULL; CreateEnvironmentBlock(&lpEnv, hToken, FALSE); BOOL bResult = CreateProcessAsUser(hToken, NULL, (LPSTR)lpPara, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, lpEnv, NULL, &si, &pi); CloseHandle(hToken); m_pLogger->WriteLog(LM_INFO, TEXT("%s."),lpPara); if(bResult) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); m_pLogger->WriteLog(LM_INFO, TEXT("CreateProcessAsUser ok.")); } else { DWORD ir = GetLastError(); m_pLogger->WriteLog(LM_INFO, TEXT("CreateProcessAsUser false.")); } if (lpEnv) DestroyEnvironmentBlock(lpEnv); return bResult; }
void YaptCurveFacade::PostInitialize(ISystem *ySys, IPluginObjectInstance *pInstance) { ILogger *pLogger = ySys->GetLogger("YaptCurveFacade");//Logger::GetLogger("YaptCurveFacade"); pLogger->Debug("PostInitialize"); if (pCurve != NULL) { pLogger->Debug("Dispose curve - not implemented, leaking memory"); } // 'unknown' not supported (it's pointless) so just add '1' to the incoming type pCurve = Curve::CreateCurve(kCurveClass(curveType->v->int_val+1), channels->v->int_val); IDocNode *pNode = pInstance->GetDocumentNode(); int nChildren = pNode->GetNumChildren(kNodeType_ObjectInstance); pLogger->Debug("Assigning keys from children (num childs = '%d')",nChildren); int i; pLogger->Enter(); for (i=0;i<nChildren;i++) { // IPluginObjectInstance *pObject = pDoc->GetChildAt(pInstance, i, kNodeType_ObjectInstance); IDocNode *pChildNode = pNode->GetChildAt(i, kNodeType_ObjectInstance); IPluginObjectInstance *pObject = dynamic_cast<IPluginObjectInstance *>(pChildNode->GetNodeObject()); GenericCurveKey *pCurveKey = dynamic_cast<GenericCurveKey *> (pObject->GetExtObject()); if (pCurveKey != NULL) { Key *pKey = pCurveKey->GetKey(); if (pKey != NULL) { pKey->t *= tScale->v->float_val; pCurve->AddKey(pKey); pLogger->Debug("Added key '%d' at t=%f",i,pKey->t); } else { pLogger->Debug("Key is NULL!"); exit(1); } } else { pLogger->Error("Unsupported child type, Animation curves only supports 'GenericKey' derivates"); } } pLogger->Leave(); }
ElementTree::ElementPtr stop_service(Session &session, ILogger &logger, const StringDict ¶ms) { string transaction_eid = params.get("transaction_id", ""); if (transaction_eid.size() < 4 || transaction_eid.size() > 64) throw ApiResult(mk_resp("bad_transaction")); Payment payment(EMPTY_DATAOBJ); try { payment = query<Payment>(session).for_update() .filter_by(Payment::c.trans_number == transaction_eid).one(); } catch (const NoDataFound &) { throw ApiResult(mk_resp("bad_transaction")); } if (payment.payment_ts == Value() || payment.cancel_ts != Value()) throw ApiResult(mk_resp("bad_transaction")); Order order = query<Order>(session).for_update() .filter_by(Order::c.id == payment.order->id).one(); if (order.ticket_number != Value()) throw ApiResult(mk_resp("bad_transaction")); int existing_cnt = order.receipts.size(); ElementTree::ElementPtr resp = mk_resp("success"); if (existing_cnt) { YB_ASSERT(existing_cnt == 1); resp->add_json("delta_amount", money2str( order.receipts.begin()->amount)); throw ApiResult(resp); } DateTime now_ts = now(); if (now_ts >= order.paid_until_ts) { resp->add_json("delta_amount", money2str(Decimal(0))); throw ApiResult(resp); } int total_secs_left = (int)datetime_diff(now_ts, order.paid_until_ts) - 1; int duration_left = (total_secs_left / (15 * 60)) * 15; // rounded minutes Decimal price_per_minute = order.paid_amount / Decimal(datetime_diff( order.start_ts, order.paid_until_ts) / 60); Decimal delta_amount = (duration_left * price_per_minute).round(2); logger.debug("total_seconds_left=" + to_string(total_secs_left) + " duration_left=" + to_string(duration_left) + " price=" + money2str(price_per_minute) + " delta=" + money2str(delta_amount)); create_account_receipt(session, order.user_eid, order, delta_amount); resp->add_json("delta_amount", money2str(delta_amount)); return resp; }
void CCliMgr::StopService(LPCTSTR lpszSvrName) { SC_HANDLE schSCManager; SERVICE_STATUS svcStatus; BOOL success; schSCManager = OpenSCManager( NULL, // machine (NULL == local) NULL, // database (NULL == default) SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE // access required ); if (schSCManager == NULL) return ; //打开服务 SC_HANDLE hService = ::OpenService(schSCManager, lpszSvrName, SERVICE_ALL_ACCESS); if (hService != NULL) { success = QueryServiceStatus(hService,&svcStatus); if (!success) { return; } if (svcStatus.dwCurrentState == SERVICE_RUNNING) { success = ControlService( hService, // handle to service SERVICE_CONTROL_STOP, // control code &svcStatus // pointer to service status structure ); if (!success) { DWORD dwError = GetLastError(); _com_error Error(dwError); m_pLogger->WriteLog(LM_INFO, TEXT("Stop Service:%s Erorr:%d:%s"),lpszSvrName, dwError, (LPCTSTR)Error.ErrorMessage()); } } ::CloseServiceHandle(hService); } ::CloseServiceHandle(schSCManager); return ; }
ElementTree::ElementPtr get_service_info(Session &session, ILogger &logger, const StringDict ¶ms) { string service_descr_str = params["service_descr"]; string user_eid = params.get("user_id", ""); if (user_eid.empty()) throw ApiResult(mk_resp("not_available", "invalid_user_id")); StringDict service_descr = json2dict(service_descr_str); logger.debug("service_descr: " + dict2str(service_descr)); Product parking; try { string parking_name = service_descr["parking_id"]; parking = query<Product>(session) .filter_by(Product::c.name == parking_name).one(); } catch (const NoDataFound &) { throw ApiResult(mk_resp("not_available", "invalid_parking_id")); } Decimal price, hours; Order order(get_hours_and_price(session, logger, service_descr, parking, false, hours, price)); ElementTree::ElementPtr resp = mk_resp("success"); resp->add_json("price", money2str(price)); ElementTree::ElementPtr info = resp->add_json_dict("info"); info->add_json("available_places", parking.places_avail.value()); if (!order.is_empty()) { info->add_json("start_ts", timestamp2str(datetime2timestamp(order.start_ts))); if (service_descr.has("user_ticket")) info->add_json("paid_duration", Decimal(datetime_diff(order.start_ts, order.paid_until_ts) / 60).round()); } else { info->add_json("start_ts", timestamp2str(datetime2timestamp(now()))); } info->add_json("duration", (hours * 60).round()); info->add_json("balance", money2str( get_account_balance(session, user_eid))); throw ApiResult(resp); }
bool CCliMgr::Initialize(IPlugMgr* pPlugMgr) { if (pPlugMgr == NULL || (m_pLogger = pPlugMgr->CreateLogger()) == NULL) return false; m_pPlugMgr = pPlugMgr; m_Hy.SetLogger(m_pLogger); m_pLogger->SetLogFileName(CLIMGR_PLUG_NAME); m_pLogger->SetAddDateBefore(false); m_pLogger->WriteLog(LM_INFO, TEXT("=========================================================")); m_pLogger->SetAddDateBefore(true); m_pLogger->WriteLog(LM_INFO, TEXT("Plug Initialize")); if (!m_Hy.IsInitialize()) { m_pLogger->WriteLog(LM_INFO, TEXT("HY Initialize Fail.")); return false; } return true; }
bool CCliMgr::ExecCmd(LPSTR pOutData, int nOutLen, LPSTR& pInData, int& nInLen, bool bNeedAck /* = true */) { ICommunication* pICommunication = m_pPlugMgr->GetCommunication(); CAutoLock<ICommunication> lock(pICommunication); if (!pICommunication->ExecCmd(pOutData, nOutLen, pInData, nInLen, bNeedAck)) return false; if (!bNeedAck) return true; CPackageHelper in(pInData); DWORD dwStatus = in.popDWORD(); if (dwStatus == CMD_RET_FAIL) { char szError[4096] = {0}; in.popString(szError); m_pLogger->WriteLog(LM_INFO, "Exec Cmd Error:%s", szError); CoTaskMemFree(pInData); pInData = NULL; nInLen = 0; return false; } return true; }
void CCliMgr::GetSysProcess() { DWORD aProcesses[1024] = {0}, cbNeeded = 0, cProcesses = 0, MemSize = 0; if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded )) { DWORD dwError = GetLastError(); _com_error Error(dwError); m_pLogger->WriteLog(LM_INFO, TEXT("GetSysProcess (EnumProcess) Error:%d:%s"), dwError, Error.ErrorMessage()); return; } cProcesses = cbNeeded / sizeof(DWORD); m_pLogger->WriteLog(LM_INFO, TEXT("Process Num:%d"), cProcesses); CMarkup xml; xml.SetDoc("<?xml version=\"1.0\" encoding=\"gb2312\"?>\r\n"); xml.AddElem("ProcessLst"); xml.IntoElem(); for (DWORD idx=0; idx<cProcesses; idx++) { TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>"); HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, aProcesses[idx]); if (NULL == hProcess) continue; else { if (0 == GetModuleFileNameEx(hProcess, NULL, szProcessName, MAX_PATH)) { CloseHandle( hProcess ); continue; } PROCESS_MEMORY_COUNTERS pmc = {0}; pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS); if ( ::GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) { MemSize = pmc.WorkingSetSize; } CloseHandle( hProcess ); } string strProcName = ProcessImagePath(szProcessName); TCHAR buf[MAX_PATH] = {0}; _stprintf(buf, TEXT("%s %d (PID: %u)\r\n"), szProcessName,MemSize, aProcesses[idx]); xml.AddElem("Process"); xml.AddAttrib("Name", strProcName); xml.AddAttrib("Pid", aProcesses[idx]); xml.AddAttrib("Memory", MemSize); m_pLogger->WriteLog(LM_INFO, buf); } xml.OutOfElem(); string data=xml.GetDoc(); char *pData = NULL; int nSize = data.size() +1024; char* buf= new char[nSize]; _packageheader* pheader = (_packageheader*)buf; InitPackage(pheader, CMD_GAME_CLIENTTOCON); CPackageHelper out(buf); out.pushDWORD(Ctrl_ViewProcInfo); out.pushString(data.c_str(), data.size()); pheader->Length = out.GetOffset(); if (!ExecCmd(buf, pheader->Length, pData, nSize,false)) m_pLogger->WriteLog(LM_INFO, "Report Ctrl_ViewProcInfo Fail."); else { m_pLogger->WriteLog(LM_INFO, "Report Ctrl_ViewProcInfo Success."); CoTaskMemFree(pData); } delete []buf; }
void CCliMgr::GetSysService() { SC_HANDLE schManager = OpenSCManager(NULL, NULL, SERVICE_QUERY_STATUS); if (schManager == NULL) { DWORD dwError = GetLastError(); _com_error Error(dwError); m_pLogger->WriteLog(LM_INFO, TEXT("GetSysService-OpenSCManager Error:%d:%s"), dwError, Error.ErrorMessage()); return ; } DWORD dwSize = 0, dwCount = 0; LPENUM_SERVICE_STATUS st = (LPENUM_SERVICE_STATUS)LocalAlloc(LPTR, 64*1024); LPQUERY_SERVICE_CONFIG sc = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, 4 * 1024); if (!EnumServicesStatus(schManager, SERVICE_TYPE_ALL, SERVICE_ACTIVE, st, 1024*64, &dwSize, &dwCount, NULL)) { DWORD dwError = GetLastError(); _com_error Error(dwError); m_pLogger->WriteLog(LM_INFO, TEXT("EnumServicesStatus Error:%d:%s"), dwError, Error.ErrorMessage()); } CMarkup xml; xml.SetDoc("<?xml version=\"1.0\" encoding=\"gb2312\"?>\r\n"); xml.AddElem("ServiceLst"); xml.IntoElem(); for (DWORD idx=0; idx<dwCount; idx++) { SC_HANDLE hService = ::OpenService(schManager,st[idx].lpServiceName,SERVICE_QUERY_CONFIG); if(hService) { DWORD dwSize = 0; ::QueryServiceConfig(hService, sc, 4 * 1024, &dwSize); CloseServiceHandle(hService); } if (st[idx].ServiceStatus.dwCurrentState == SERVICE_RUNNING) { TCHAR buf[MAX_PATH] = {0}; _stprintf(buf, TEXT("%s %s %s)\r\n"), st[idx].lpServiceName, sc->lpBinaryPathName, st[idx].lpDisplayName); string strProcName = ProcessImagePath(sc->lpBinaryPathName); xml.AddElem("Service"); xml.AddAttrib("Name", st[idx].lpServiceName); xml.AddAttrib("Application", strProcName.c_str()); xml.AddAttrib("DisplayName", st[idx].lpDisplayName); m_pLogger->WriteLog(LM_INFO, buf); } } xml.OutOfElem(); string data=xml.GetDoc(); char *pData = NULL; int nSize = data.size() + 1024; char* buf= new char[nSize]; _packageheader* pheader = (_packageheader*)buf; InitPackage(pheader, CMD_GAME_CLIENTTOCON); CPackageHelper out(buf); out.pushDWORD(Ctrl_ViewSviInfo); out.pushString(data.c_str(), data.size()); pheader->Length = out.GetOffset(); if (!ExecCmd(buf, pheader->Length, pData, nSize, false)) m_pLogger->WriteLog(LM_INFO, "Report Ctrl_ViewSviInfo Fail."); else { m_pLogger->WriteLog(LM_INFO, "Report Ctrl_ViewSviInfo Success."); CoTaskMemFree(pData); } delete []buf; LocalFree(st); LocalFree(sc); CloseServiceHandle(schManager); }
tstring CCliMgr::GetWmiInfo( LPCTSTR lpszClass,LPCTSTR lpszField) { tstring SysInfo,strtmp; HRESULT ret; ret = CoInitialize(NULL); ret = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0 ); if (ret == S_OK || ret== RPC_E_TOO_LATE ) { IWbemLocator * pIWbemLocator = NULL; IWbemServices * pWbemServices = NULL; IEnumWbemClassObject * pEnumObject = NULL; BSTR bstrNamespace = (L"root\\cimv2");// 通过 IWbemLocator 和 IWbemServices 这两个 COM 接口访问 WMI, 获取系统信息 if(CoCreateInstance (CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_IUnknown ,(void**)&pIWbemLocator) == S_OK) { if(pIWbemLocator->ConnectServer( bstrNamespace, // Namespace NULL, // Userid NULL, // PW NULL, // Locale 0, // flags NULL, // Authority NULL, // Context &pWbemServices ) == S_OK) { HRESULT hRes; _bstr_t strQuery = (L"Select * from Win32_OperatingSystem"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned); if(hRes == S_OK) { strtmp = "操作系统的名称: "+_getWmiInfo(pClassObject,"Caption")+"\r\n"; SysInfo = SysInfo + strtmp; } if (pClassObject != NULL) pClassObject->Release(); } } strQuery = (L"Select * from Win32_DiskDrive"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned); if(hRes == S_OK) { strtmp = "硬盘的Model: "+_getWmiInfo(pClassObject,"Model")+"\r\n"; SysInfo = SysInfo + strtmp; m_pLogger->WriteLog(LM_INFO, TEXT("硬盘的Model: %s"),_getWmiInfo(pClassObject,"Model").c_str()); } if (pClassObject != NULL) pClassObject->Release(); } } strQuery = (L"Select * from Win32_LogicalDisk"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { while( pEnumObject->Next( WBEM_INFINITE, uCount, &pClassObject, &uReturned) == S_OK ) { if (atoi(_getWmiInfo(pClassObject,"DriveType").c_str()) != 3) continue; tstring str; str =_getWmiInfo(pClassObject,"Name"); strtmp = "盘符: " +str+" "; m_pLogger->WriteLog(LM_INFO, TEXT("盘符: %s"),str.c_str()); tstring drv; drv += toupper(str[0]); if(m_Hy.IsDriverProtected((char *)drv.c_str())) { strtmp = strtmp+ "还原状态: 保护 "; m_pLogger->WriteLog(LM_INFO, TEXT("还原状态: 保护 ")); } else { strtmp = strtmp+ "还原状态: 未保护 "; m_pLogger->WriteLog(LM_INFO, TEXT("还原状态: 未保护 ")); } strtmp = strtmp+ " 剩余空间: "+_getWmiInfo(pClassObject,"FreeSpace")+"\r\n"; SysInfo = SysInfo + strtmp; m_pLogger->WriteLog(LM_INFO, TEXT("剩余空间: %s"),_getWmiInfo(pClassObject,"FreeSpace").c_str()); } if (pClassObject != NULL) pClassObject->Release(); } } strQuery = (L"Select * from Win32_processor"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned); if(hRes == S_OK) { strtmp = "处理器的制造厂商: "+_getWmiInfo(pClassObject,"Manufacturer") + "\r\n"; strtmp = strtmp + "处理器的名称: "+_getWmiInfo(pClassObject,"Caption") + "\r\n"; SysInfo = SysInfo + strtmp; m_pLogger->WriteLog(LM_INFO, TEXT("处理器的制造厂商: %s"),_getWmiInfo(pClassObject,"Manufacturer").c_str()); m_pLogger->WriteLog(LM_INFO, TEXT("处理器的名称: %s"),_getWmiInfo(pClassObject,"Caption").c_str()); } if (pClassObject != NULL) pClassObject->Release(); } } strQuery = (L"Select * from Win32_LogicalMemoryConfiguration"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned); if(hRes == S_OK) { strtmp = "物理内存大小: "+_getWmiInfo(pClassObject,"TotalPhysicalMemory") + "\r\n"; strtmp = strtmp + "页面文件大小: "+_getWmiInfo(pClassObject,"TotalPageFileSpace") + "\r\n"; strtmp = strtmp + "虚拟内存大小: "+_getWmiInfo(pClassObject,"TotalVirtualMemory") + "\r\n"; SysInfo = SysInfo + strtmp; m_pLogger->WriteLog(LM_INFO, TEXT("物理内存大小: %s"),_getWmiInfo(pClassObject,"TotalPhysicalMemory").c_str()); m_pLogger->WriteLog(LM_INFO, TEXT("页面文件大小: %s"),_getWmiInfo(pClassObject,"TotalPageFileSpace").c_str()); m_pLogger->WriteLog(LM_INFO, TEXT("虚拟内存大小: %s"),_getWmiInfo(pClassObject,"TotalVirtualMemory").c_str()); } if (pClassObject != NULL) pClassObject->Release(); } } strQuery = (L"Select * from Win32_VideoController"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned); if(hRes == S_OK) { strtmp = "显卡名称: "+_getWmiInfo(pClassObject,"Name") + "\r\n"; SysInfo = SysInfo + strtmp; m_pLogger->WriteLog(LM_INFO, TEXT("显卡名称: %s"),_getWmiInfo(pClassObject,"Name").c_str()); } if (pClassObject != NULL) pClassObject->Release(); } } strQuery = (L"Select * from Win32_NetworkAdapter where (Netconnectionstatus = 2)"); hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject); if(hRes == S_OK) { ULONG uCount = 1, uReturned; IWbemClassObject * pClassObject = NULL; hRes = pEnumObject->Reset(); if(hRes == S_OK) { while( pEnumObject->Next( WBEM_INFINITE, uCount, &pClassObject, &uReturned) == S_OK ) { tstring str; str =_getWmiInfo(pClassObject,"MACAddress"); if (!str.empty()) { str =_getWmiInfo(pClassObject,"PNPDeviceID"); size_t pos = str.find("PCI",0); if (pos != tstring::npos) { tstring str = _getWmiInfo(pClassObject,"Caption"); size_t pos = str.find(']'); if (pos != tstring::npos) str = str.substr(pos+1); strtmp = "网卡名称: "+str + "\r\n"; SysInfo = SysInfo + strtmp; m_pLogger->WriteLog(LM_INFO, "网卡名称: %s" , str.c_str()) ; } } } if (pClassObject != NULL) pClassObject->Release(); } } } } if (pIWbemLocator) pIWbemLocator->Release(); if (pWbemServices) pWbemServices->Release(); if (pEnumObject) pEnumObject->Release(); } CoUninitialize(); if (!SysInfo.empty()) { m_SysInfo = SysInfo; } return SysInfo; }