123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458 |
- // mod_ResourceWatcher.cpp : 定义 DLL 应用程序的导出函数。
- //
- #include "stdafx.h"
- #include "mod_ResourceWatcher.h"
- #include "CommEntityUtil.hpp"
- #include "array.h"
- #include "fileutil.h"
- #include "iniutil.h"
- #include "toolkit.h"
- #include "osutil.h"
- #if defined(RVC_OS_LINUX)
- #include "SogouVersion.h"
- #include <winpr/sysinfo.h>
- #endif //RVC_OS_LINUX
- #include "publicFunExport.h"
- #include <map>
- #include <regex.h>
- struct SogouRunVersionInfo
- {
- CSimpleStringA strInstallDir;
- CSimpleStringA strVersion;
- SogouRunVersionInfo():strInstallDir(true),strVersion(true){}
- CSimpleStringA ToString() const {
- CSimpleStringA result(true);
- if(!strInstallDir.IsNullOrEmpty()) {
- result += strInstallDir;
- result += "#";
- }
- if(!strVersion.IsNullOrEmpty()) {
- result += strVersion;
- }
- return result;
- }
- };
- struct SogouInstallStateInfo
- {
- DWORD dwInstalledStatus;
- CSimpleStringA strInstallDate;
- SogouInstallStateInfo():dwInstalledStatus(-1),strInstallDate(true){}
- CSimpleStringA ToString() const {
- CSimpleStringA result(true);
- if(!strInstallDate.IsNullOrEmpty()) {
- //result += strInstallDate;
- result += GetInstallTime().ToTimeString();
- result += "#";
- }
- result += CSimpleStringA::Format("%u", dwInstalledStatus);
- return result;
- }
- CSmallDateTime GetInstallTime() const {
- if(!strInstallDate.IsNullOrEmpty()) {
- DWORD dwSecsSince1970(0);
- sscanf_s(strInstallDate.GetData(), "%u", &dwSecsSince1970);
- dwSecsSince1970 -= 946656000; // 2000-1970
- return CSmallDateTime(dwSecsSince1970);
- }
- return CSmallDateTime::BeginTime;
- }
- };
- struct SogouInstallInfo
- {
- SogouInstallStateInfo state;
- SogouRunVersionInfo program;
- CSimpleStringA Stringfy() const
- {
- return (state.ToString() + "||" + program.ToString());
- }
- bool IsInstalledSuccess() const {
- return (state.dwInstalledStatus == 0);
- }
- };
- void ResourceWatcherServiceSession::Handle_Fetch(
- SpReqAnsContext<ResourceWatcherService_Fetch_Req, ResourceWatcherService_Fetch_Ans>::Pointer ctx)
- {
- m_pEntity->Fetch(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetDevInfo(
- SpReqAnsContext<ResourceWatcherService_GetDevInfo_Req, ResourceWatcherService_GetDevInfo_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetDevInfo(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetCardSwiper(SpReqAnsContext<ResourceWatcherService_GetCardSwiper_Req, ResourceWatcherService_GetCardSwiper_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetCSwiperStatus(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetCpuType(SpReqAnsContext<ResourceWatcherService_GetCpuType_Req, ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetCPUType(ctx);
- }
- void ResourceWatcherServiceSession::Handle_OperateFile
- (SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
- ResourceWatcherService_OperateFile_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->OperateFile(ctx);
- }
- void ResourceWatcherServiceSession::Handle_ExtractEventLog(
- SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req, ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->RetrieveEventLog(ctx);
- }
- void ResourceWatcherServiceSession::Handle_UpdateDNS(SpReqAnsContext<ResourceWatcherService_UpdateDNS_Req, ResourceWatcherService_UpdateDNS_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->UpdateDNS(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetNetworkInfo(SpReqAnsContext<ResourceWatcherService_GetNetworkInfo_Req, ResourceWatcherService_GetNetworkInfo_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetNetworkInfo(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetThirdPartyInstallState(ctx);
- }
- void ResourceWatcherServiceSession::Handle_InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->InstallThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_BizLinkDetect(SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->BizLinkDetect(ctx);
- }
- void ResourceWatcherServiceSession::Handle_CheckNetType(SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->CheckNetType(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetBizLinks(SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetBizLinks(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetTerminalVersionList(SpReqAnsContext<ResourceWatcherService_GetTerminalVersionList_Req, ResourceWatcherService_GetTerminalVersionList_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->GetTerminalVersionList(ctx);
- }
- void ResourceWatcherServiceSession::Handle_ManipulateVersion(SpReqAnsContext<ResourceWatcherService_ManipulateVersion_Req, ResourceWatcherService_ManipulateVersion_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ManipulateVersion(ctx);
- }
- void ResourceWatcherServiceSession::Handle_UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->UninstallThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->RestartThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- m_pEntity->ProcessDetectThirdPartyProgram(ctx);
- }
- void ResourceWatcherEntity::UpdateDNS(SpReqAnsContext<ResourceWatcherService_UpdateDNS_Req, ResourceWatcherService_UpdateDNS_Ans>::Pointer ctx)
- {
- ctx->Answer(Error_NotImpl);
- }
- void ResourceWatcherEntity::GetNetworkInfo(SpReqAnsContext<ResourceWatcherService_GetNetworkInfo_Req, ResourceWatcherService_GetNetworkInfo_Ans>::Pointer ctx)
- {
- char buf[512];
- toolkit_interface_address_t* info;
- int count, i;
- toolkit_interface_addresses(&info, &count);
- i = count;
- Dbg("Number of interfaces: %d", count);
- if (count <= 0) {
- ctx->Answer(Error_NotExist);
- return;
- }
- int realCount = 0;
- while (i--) {
- toolkit_interface_address_t& interface = info[i];
- if (interface.address.address4.sin_family == AF_INET/* && !interface.is_internal*/) {
- realCount++;
- }
- }
- if (realCount <= 0) {
- ctx->Answer(Error_NotExist);
- return;
- }
- ctx->Ans.status = 0;
- ctx->Ans.current = "";
- ctx->Ans.ips.Init(realCount);
- ctx->Ans.names.Init(realCount);
- ctx->Ans.macs.Init(realCount);
- ctx->Ans.masks.Init(realCount);
- ctx->Ans.gateways.Init(realCount);
- ctx->Ans.dns.Init(realCount);
- int cnt = 0, active = -1;
- for (i = 0; i < count; ++i) {
- toolkit_interface_address_t& interface = info[i];
- if (interface.address.address4.sin_family == AF_INET) {
- ctx->Ans.names[cnt] = interface.name;
- toolkit_ip4_name(&interface.address.address4, buf, sizeof(buf));
- if (strcmp(buf, "127.0.0.1") != 0) active = cnt;
- ctx->Ans.ips[cnt] = buf;
- ctx->Ans.macs[cnt] = "";
- ctx->Ans.masks[cnt] = "";
- ctx->Ans.gateways[cnt] = "";
- ctx->Ans.dns[cnt] = "";
- cnt++;
- }
- }
- toolkit_free_interface_addresses(info, count);
- const char* parent = "/etc/NetworkManager/system-connections";
- array_header_t* subs;
- subs = fileutil_get_sub_files_a(parent);
- if (subs) {
- for (i = 0; i < subs->nelts; ++i) {
- char path[256] = { 0 };
- char* dir = ARRAY_IDX(subs, i, char*);
- char value[128];
- inifile_read_str_s("connection", "interface-name", "", value, 127, dir);
- if (strlen(value) == 0) continue;
- for (int j = 0; j < realCount; ++j) {
- if (ctx->Ans.names[j].Compare(value) == 0) {
- memset(value, 0, sizeof(value));
- inifile_read_str_s("connection", "id", "", value, 127, dir);
- if (strlen(value) > 0) {
- ctx->Ans.names[j] = CSimpleStringA::Format("%s#%s", value, ctx->Ans.names[j].GetData());
- }
- if (active == j) {
- ctx->Ans.current = ctx->Ans.names[j];
- }
- memset(value, 0, sizeof(value));
- inifile_read_str_s("ethernet", "mac-address", "", value, 127, dir);
- ctx->Ans.macs[j] = value;
- memset(value, 0, sizeof(value));
- inifile_read_str_s("ipv4", "dns", "", value, 127, dir);
- ctx->Ans.dns[j] = value;
- break;
- }
- }
- }
- toolkit_array_free2(subs);
- }
- ctx->Answer(Error_Succeed);
- }
- void ResourceWatcherEntity::GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- if (ctx->Req.mode == 1) {//查看搜狗输入法安装状态
- SogouInstallInfo info;
- info.state.dwInstalledStatus = Sogou_GetInstallStatus();
- info.state.strInstallDate = Sogou_GetInstallTime();
- info.program.strInstallDir = Sogou_GetInstallPath();
- info.program.strVersion = Sogou_GetVersion();
- const int maxTimes = 5;
- int curTimes = 0;
- while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
- Sleep(1200);
- info.program.strVersion = Sogou_GetVersion();
- curTimes++;
- }
- Dbg("%d, %s, %s, %s"
- , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
- , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
- Dbg("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
- ctx->Ans.status = info.IsInstalledSuccess() ? 1 : 0;
- ctx->Ans.reserverd1 = info.state.GetInstallTime().ToTimeString();
- ctx->Ans.path = info.program.strInstallDir;
- ctx->Ans.version = info.program.strVersion;
- } else if (ctx->Req.mode == 2) { //检测字体的安装状态
- CSimpleStringA strFontDir("/usr/share/fonts/truetype");
- CSimpleStringA strRVCTTFsDir(strFontDir + SPLIT_SLASH_STR + "RVCTTFs");
- if (!ExistsDirA(strRVCTTFsDir)) {
- ctx->Ans.status = 0;
- ctx->Ans.reserverd1 = CSimpleStringA::Format("%s 文件夹不存在", (LPCTSTR)strRVCTTFsDir);
- } else {
- CSimpleStringA ttf1 = strRVCTTFsDir + SPLIT_SLASH_STR + "HYQiHei-55S.ttf";
- CSimpleStringA ttf2 = strRVCTTFsDir + SPLIT_SLASH_STR + "HYQiHei-65S.ttf";
- CSimpleStringA ttfdir = strRVCTTFsDir + SPLIT_SLASH_STR + "fonts.dir";
- CSimpleStringA ttfscale = strRVCTTFsDir + SPLIT_SLASH_STR + "fonts.scale";
- CSimpleStringA ttfuuid = strRVCTTFsDir + SPLIT_SLASH_STR + ".uuid";
- int existCheck = 0;
- if (!ExistsFileA(ttf1)) {
- existCheck |= 1;
- }
- if (!ExistsFileA(ttf2)) {
- existCheck |= 2;
- }
- if (!ExistsFileA(ttfdir)) {
- existCheck |= 4;
- }
- if (!ExistsFileA(ttfscale)) {
- existCheck |= 8;
- }
- if (!ExistsFileA(ttfuuid)) {
- existCheck |= 16;
- }
- if (existCheck != 0) {
- ctx->Ans.status = 0;
- ctx->Ans.reserverd1 = CSimpleStringA::Format("安装文件不存在:0x%X", existCheck);
- } else {
- ctx->Ans.status = 1;
- ctx->Ans.reserverd1 = "";
- ctx->Ans.path = strRVCTTFsDir;
- ctx->Ans.version = "";
- }
- }
- } else {
- result = Error_NotSupport;
- }
- ctx->Answer(result);
- return;
- }
- ErrorCodeEnum SetFileExecutePriviledge(LPCTSTR lpcszDirOrFilePath)
- {
- ErrorCodeEnum result(Error_Succeed);
- if (ExistsDirA(lpcszDirOrFilePath)) {
- do
- {
- array_header_t* subs;
- subs = fileutil_get_sub_dirs_a(lpcszDirOrFilePath);
- if (subs) {
- for (int i = 0; i < subs->nelts; ++i) {
- char* dir = ARRAY_IDX(subs, i, char*);
- const char* dirname = &dir[strlen(lpcszDirOrFilePath) + 1];
- ErrorCodeEnum tmpResult = SetFileExecutePriviledge(dir);
- if (tmpResult != Error_Succeed) {
- toolkit_array_free2(subs);
- return tmpResult;
- }
- }
- }
- } while (false);
- do {
- array_header_t* subs;
- subs = fileutil_get_sub_files_a(lpcszDirOrFilePath);
- if (subs) {
- for (int i = 0; i < subs->nelts; ++i) {
- char* path = ARRAY_IDX(subs, i, char*);
- mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
- if (chmod(path, f_attrib) != 0) {
- Dbg("chmod file priviledge failed, %s, %d", path, errno);
- toolkit_array_free2(subs);
- return Error_Unexpect;
- }
- }
- toolkit_array_free2(subs);
- }
- } while (false);
- } else if(ExistsFileA(lpcszDirOrFilePath)) {
- mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
- if (chmod(lpcszDirOrFilePath, f_attrib) != 0) {
- Dbg("chmod file priviledge failed, %s, %d", lpcszDirOrFilePath, errno);
- return Error_Unexpect;
- }
- } else {
- result = Error_InvalidState;
- }
- return result;
- }
- void ResourceWatcherEntity::InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.type == 1) {//安装搜狗输入法
- Dbg("to install sogou input...");
- const bool doNotStartup(true); //安装后是否启动搜狗输入法服务,据搜狗反馈,不能通过root权限启动Sogou输入法
- CSimpleStringA strInstallPkgPath;
- tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("指定位置找不到输入法安装包");
- } else {
- tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
- if (tmpResult != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
- tmpResult = Error_NotExist;
- } else {
- CSimpleStringA strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
- if (ExistsFileA(strRunIniFilePath)) {
- char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
- CSimpleStringA strInstallScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + p);
- toolkit_free(p);
- Dbg("install script file: %s", strInstallScriptFile.GetData());
- if (ExistsFileA(strInstallScriptFile)) {
- char app[MAX_PATH] = { '\0' };
- sprintf(app, "bash %s", strInstallScriptFile.GetData());
- tmpResult = RunShellScript(app);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
- } else if(!doNotStartup) {
- CSimpleStringA strStartupScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + "startup_service.sh");
- Dbg("startup script file: %s", strStartupScriptFile.GetData());
- if (!ExistsFileA(strStartupScriptFile)) {
- tmpMsg = CSimpleStringA::Format("%s 启动脚本文件不存在,请重启设备再次验证", strStartupScriptFile.GetData());
- tmpResult = Error_NotExist;
- } else {
- Sleep(1000);
- do {
- char app[MAX_PATH] = { '\0' };
- tk_process_t* process = NULL;
- tk_process_option_t option;
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- #if 0
- auto users = GetUserNameList(true);
- if (users.size() == 1) {
- sprintf(app, "su -m -p -c \"bash %s\" %s", strStartupScriptFile.GetData(), users[0].c_str());
- } else {
- for (auto it = users.cbegin(); it != users.cend(); ++it) {
- Dbg("user:%s", it->c_str());
- }
- sprintf(app, "bash %s", strStartupScriptFile.GetData());
- }
- #else
- sprintf(app, "bash %s", strStartupScriptFile.GetData());
- #endif
- option.params = app;
- const int res = process_spawn(&option, &process);
- if (0 == res) {
- FREE(process);
- Dbg("execute {%s} suc", app);
- } else {
- tmpMsg = CSimpleStringA::Format("执行 '%s' 失败:%s", app, toolkit_strerror(res));
- tmpResult = Error_Process;
- }
- } while (false);
- }
- }
- } else {
- tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
- tmpResult = Error_NotExist;
- }
- } else {
- tmpMsg = CSimpleStringA::Format("%s 文件不存在,请检查安装包完整性", strRunIniFilePath.GetData());
- tmpResult = Error_NotExist;
- }
- }
- }
- if (tmpResult == Error_Succeed) {
- Sleep(1500);
- const CSimpleStringA strResultLogFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "result.log";
- do
- {
- const int maxTimes = 5;
- int curTimes = 0;
- while (!ExistsFileA(strResultLogFilePath) && curTimes < maxTimes) {
- Sleep(1500);
- curTimes++;
- }
- } while (false);
- if (!ExistsFileA(strResultLogFilePath)) {
- tmpResult = Error_NotExist;
- tmpMsg = CSimpleStringA::Format("安装成功标志文件不存在!");
- } else {
- FILE* pResultLog = fopen(strResultLogFilePath, "r");
- if (pResultLog == NULL) {
- tmpResult = Error_IO;
- tmpMsg = CSimpleStringA::Format("打开安装成功标志文件失败!%s", strerror(errno));
- } else {
- char szTmp[1024] = {'\0'};
- int nRead = fread(szTmp, 1, sizeof(szTmp), pResultLog);
- int installResult(-1);
- char installMsg[256] = { '\0' };
- sscanf(szTmp, "result=%d&msg=%s", &installResult, installMsg);
- fclose(pResultLog);
- if (installResult != 0) {
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("%s", szTmp);
- } else {
- SogouInstallInfo info;
- info.state.dwInstalledStatus = Sogou_GetInstallStatus();
- info.state.strInstallDate = Sogou_GetInstallTime();
- info.program.strInstallDir = Sogou_GetInstallPath();
- info.program.strVersion = Sogou_GetVersion();
- const int maxTimes = 5;
- int curTimes = 0;
- while (!doNotStartup && info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
- Sleep(1200);
- info.program.strVersion = Sogou_GetVersion();
- curTimes++;
- }
- Dbg("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
- Dbg("%d, %s, %s, %s"
- , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
- , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
- if (!info.IsInstalledSuccess()) {
- tmpResult = Error_FailVerify;
- tmpMsg = CSimpleStringA::Format("检测安装状态失败!");
- } else {
- ctx->Ans.path = info.program.strInstallDir;
- ctx->Ans.reserverd1 = info.program.strVersion;
- ctx->Ans.reserverd2 = info.state.GetInstallTime().ToTimeString();
- }
- }
- }
- }
- }
- } else if (ctx->Req.type == 2) {//安装花了钱的字体
- Dbg("to install cmb font input...%d", m_bInitMode);
- CSimpleStringA strAdDataDirPath(true);
- tmpResult = GetFunction()->GetPath("Ad", strAdDataDirPath);
- if (strAdDataDirPath.IsNullOrEmpty() && m_bInitMode) {
- strAdDataDirPath = "/opt/rvc/adData";
- }
- if (strAdDataDirPath.IsNullOrEmpty()) {
- tmpResult = Error_Unexpect;
- tmpMsg = "获取安装包路径Ad失败";
- } else {
- CSimpleStringA strInstallPkgPath = strAdDataDirPath + SPLIT_SLASH_STR "HYQiHei";
- if (!ExistsDirA(strInstallPkgPath)) {
- tmpMsg = CSimpleStringA::Format("%s 文件夹不存在", strInstallPkgPath.GetData());
- tmpResult = Error_NotExist;
- } else {
- CSimpleStringA strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
- if (ExistsFileA(strRunIniFilePath)) {
- char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
- CSimpleStringA strInstallScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + p);
- toolkit_free(p);
- Dbg("RunScript file: %s", strInstallScriptFile.GetData());
- if (ExistsFileA(strInstallScriptFile)) {
- do {
- char app[MAX_PATH] = { '\0' };
- tk_process_t* process = NULL;
- tk_process_option_t option;
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- sprintf(app, "bash %s", strInstallScriptFile.GetData());
- option.params = app;
- const int res = process_spawn(&option, &process);
- if (0 == res) {
- FREE(process);
- Dbg("execute {%s} suc", strInstallScriptFile.GetData());
- } else {
- tmpMsg = CSimpleStringA::Format("执行 %s 失败:%s", strInstallScriptFile.GetData(), toolkit_strerror(res));
- tmpResult = Error_Process;
- }
- } while (false);
- } else {
- tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
- tmpResult = Error_NotExist;
- }
- } else {
- tmpMsg = CSimpleStringA::Format("%s 文件不存在", strRunIniFilePath.GetData());
- tmpResult = Error_NotExist;
- }
- }
- }
- if (tmpResult == Error_Succeed) {
- ///**TODO(Gifur@10/21/2021): 二次校验 */
- }
- } else {
- result = Error_NotSupport;
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- return;
- }
- void ResourceWatcherEntity::GetTerminalVersionList(SpReqAnsContext<ResourceWatcherService_GetTerminalVersionList_Req, ResourceWatcherService_GetTerminalVersionList_Ans>::Pointer ctx)
- {
- CSimpleStringA strVersionBaseDir(true);
- GetFunction()->GetPath("RootVer", strVersionBaseDir);
- const CSimpleStringA strActiveFile = strVersionBaseDir + SPLIT_SLASH_STR + "active.txt";
- CSystemStaticInfo staticInfo;
- GetFunction()->GetSystemStaticInfo(staticInfo);
- CSimpleStringA strCurrVer = staticInfo.InstallVersion.ToString();
- Dbg("get current version [%s]", (LPCTSTR)strCurrVer);
- std::vector<std::string> verlist;
- array_header_t* arr;
- arr = fileutil_get_sub_dirs_a(strVersionBaseDir);
- if (arr) {
- do {
- regex_t reg;
- CSimpleStringA strPattern("^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+[\(\)A-Za-z_-]*$");
- int ret = regcomp(®, strPattern, REG_EXTENDED | REG_NOSUB);
- if (ret) {
- char ebuff[256];
- regerror(ret, ®, ebuff, 256);
- Dbg("regex failed: %s", ebuff);
- ctx->Ans.msg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
- ctx->Ans.current = -1;
- break;
- } else {
- for (int i = 0; i < arr->nelts; ++i) {
- char* versionDir = ARRAY_IDX(arr, i, char*);
- char* versionDirName = &versionDir[strVersionBaseDir.GetLength() + 1];
- ret = regexec(®, versionDirName, 0, NULL, 0);
- if (0 == ret) {
- Dbg("filename %s matched!", versionDirName);
- verlist.push_back(std::string(versionDirName));
- }
- }
- }
- } while (false);
- toolkit_array_free2(arr);
- }
- if (!verlist.empty()) {
- const int count = verlist.size();
- ctx->Ans.index.Init(count);
- ctx->Ans.version.Init(count);
- ctx->Ans.remark.Init(count);
- ctx->Ans.type.Init(count);
- ctx->Ans.status.Init(count);
- for (int i = 0; i < count; ++i) {
- ctx->Ans.index[i] = i;
- ctx->Ans.version[i] = verlist[i].c_str();
- if (verlist[i].compare(strCurrVer.GetData()) == 0) {
- ctx->Ans.current = i;
- }
- ctx->Ans.remark[i] = "";
- ctx->Ans.type[i] = ctx->Ans.status[i] = 0;
- }
- }
- ctx->Answer(Error_Succeed);
- }
- namespace
- {
- bool UpdateCurrentVersionName(LPCTSTR filePath, LPCTSTR versionStr, LPCTSTR backupPath)
- {
- if (fileutil_copy_file(backupPath, filePath) != 0) {
- return false;
- }
- FILE* fp = fopen(filePath, "wb+");
- if (fp == NULL) {
- return false;
- }
- bool result(false);
- do
- {
- int ret = fwrite(versionStr, strlen(versionStr), 1, fp);
- if (ret != 1) {
- Dbg("fwrite failed: %d", ret);
- break;
- }
- fflush(fp);
- fclose(fp);
- fp = fopen(filePath, "rb");
- if (fp != NULL) {
- char value[32] = { 0 };
- int ret2 = fread(value, strlen(versionStr), 1, fp);
- if (ret2 == 1) {
- if (strcmp(value, versionStr) == 0)
- Dbg("read agagin the value is the same!");
- else {
- break;
- }
- }
- }
- result = true;
- } while (false);
- fclose(fp);
- if (!result && backupPath) {
- fileutil_copy_file(filePath, backupPath);
- fileutil_delete_file(backupPath);
- }
- if (result && backupPath) {
- fileutil_delete_file(backupPath);
- }
- return result;
- }
- }
- void ResourceWatcherEntity::ManipulateVersion(SpReqAnsContext<ResourceWatcherService_ManipulateVersion_Req, ResourceWatcherService_ManipulateVersion_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- int tmpResult(0);
- CSimpleStringA tmpMsg(true);
- switch (ctx->Req.operation) {
- case 1: //设置为此版本为当前版本
- {
- CSimpleStringA strVersionBaseDir(true);
- GetFunction()->GetPath("RootVer", strVersionBaseDir);
- const CSimpleStringA strActiveFile = strVersionBaseDir + SPLIT_SLASH_STR + "active.txt";
- const CSimpleStringA strActiveFileBackup = strActiveFile + "activebak.txt";
- CSystemStaticInfo staticInfo;
- GetFunction()->GetSystemStaticInfo(staticInfo);
- CSimpleStringA strCurrVer = staticInfo.InstallVersion.ToString();
- Dbg("get current version [%s]", (LPCTSTR)strCurrVer);
- if (!UpdateCurrentVersionName(strActiveFile, ctx->Req.value, strActiveFileBackup)) {
- tmpResult = Error_Unexpect;
- tmpMsg = "切换版本失败";
- }
- }
- break;
- case 2: //删除此版本
- {
- CSimpleStringA strVersionBaseDir(true);
- GetFunction()->GetPath("RootVer", strVersionBaseDir);
- const CSimpleStringA strVersionDirPath = strVersionBaseDir + SPLIT_SLASH_STR + ctx->Req.value;
- if (ExistsDirA(strVersionDirPath)) {
- if (!RemoveDirRecursiveA(strVersionDirPath)) {
- tmpResult = Error_Unexpect;
- tmpMsg = "删除版本失败";
- }
- }
- }
- break;
- default:
- result = Error_NotSupport;
- break;
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- }
- void ResourceWatcherEntity::UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.type == 1) {
- Dbg("to uninstall sogou input...");
- CSimpleStringA strInstallPkgPath;
- tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
- if (tmpResult == Error_Succeed) {
- do
- {
- tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
- if (tmpResult != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
- tmpResult = Error_NoPrivilege;
- break;
- }
- const CSimpleStringA strShutdownScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "shutdown_service.sh";
- const CSimpleStringA strUninstallScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "uninstall_sogouime.sh";
- if (!ExistsFileA(strShutdownScriptFile)) {
- tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strShutdownScriptFile.GetData());
- tmpResult = Error_InvalidState;
- break;
- }
- if (!ExistsFileA(strUninstallScriptFile)) {
- tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strUninstallScriptFile.GetData());
- tmpResult = Error_InvalidState;
- break;
- }
- char app[MAX_PATH] = { '\0' };
- sprintf(app, "bash %s", strShutdownScriptFile.GetData());
- tmpResult = RunShellScript(app);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
- } else {
- Sleep(300);
- sprintf(app, "bash %s", strUninstallScriptFile.GetData());
- tmpResult = RunShellScript(app);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
- } else {
- Sleep(100);
- }
- }
- } while (false);
- }
- } else {
- result = Error_NotSupport;
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- return;
- }
- void ResourceWatcherEntity::RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- int restartRe = false;
- CSimpleStringA tmpMsg(true);
- std::string res("");
- if (ctx->Req.type == 1) {//重启搜狗输入法
- //CSimpleStringA csBinPath;
- //ErrorCodeEnum eErrPath = GetFunction()->GetPath("Bin", csBinPath);
- //if (eErrPath != Error_Succeed)
- //{
- // //Dbg("GetBasePath failed (%d).", eErrPath));
- // tmpMsg = "GetBasePath failed.";
- //}
- //else
- //{
- // CSimpleStringA startPath = CSimpleStringA::Format("%s\\spScript\\SogouServStarter.bat", csBinPath.GetData());
- // int startFlag = WinExec(startPath.GetData(), SW_SHOWNORMAL);
- // if (startFlag > 31)
- // {
- // tmpMsg = CSimpleStringA::Format("已执行搜狗启动脚本!路径:%s。", startPath.GetData());
- // restartRe = 1;
- // }
- // else
- // {
- // tmpMsg = CSimpleStringA::Format("执行启动脚本异常!路径:%s。", startPath.GetData());
- // restartRe = 0;
- // }
- //}
- }
- ctx->Ans.result = restartRe;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- return;
- }
- void ResourceWatcherEntity::ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- int procDetectRe = false;
- CSimpleStringA tmpMsg(true);
- std::string res("");
- if (ctx->Req.type == 1) {//检测搜狗输入法进程
- CAutoArray<CSimpleStringA> pName(2);
- pName[0] = "SogouImeMon.exe";
- pName[1] = "SogouImeWebSrv.exe";
- res = DoCheckCertainProcessStatus(pName);
- if (res.length() == 0)
- {
- procDetectRe = false;
- tmpMsg = "Can't find Sogou Process.";
- }
- else
- {
- procDetectRe = true;
- tmpMsg = CSimpleStringA::Format("%s", res.c_str());
- }
- }
- ctx->Ans.result = procDetectRe;
- ctx->Ans.msg = tmpMsg;
- result = tmpResult;
- ctx->Answer(result);
- return;
- }
- #if defined(RVC_OS_WIN)
- //1: 32bit process running at 64bit platform
- //0:
- static int Is32R64Platform()
- {
- static int isWow64 = -1;
- typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
- if (isWow64 == -1) {
- BOOL bIsWow64 = FALSE;
- LPFN_ISWOW64PROCESS fnIsWow64Process =
- (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
- if (NULL != fnIsWow64Process) {
- if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
- Dbg("detect is running with 64bit or not failed: %u", GetLastError());
- return -1;
- } else {
- isWow64 = bIsWow64 ? 1 : 0;
- }
- }
- }
- return isWow64;
- }
- static bool GetRegistValue(HKEY hKey, LPCTSTR lpcszParam,
- DWORD* pDwValue, CHAR* pSzValue, const DWORD* pDwSizeOfSz)
- {
- if (pDwValue != NULL) {
- DWORD dwType = REG_DWORD;
- DWORD dwValue = 0;
- DWORD dwSize = sizeof(DWORD);
- LONG lResult = RegQueryValueExA(hKey, lpcszParam, NULL, &dwType, (LPBYTE)&dwValue, &dwSize);
- if (lResult == ERROR_SUCCESS) {
- Dbg("Value of \"%s\": %d", lpcszParam, dwValue);
- *pDwValue = dwValue;
- return true;
- } else {
- Dbg("RegQueryValueEx for \"%s\" error, result=%ld.", lpcszParam, lResult);
- return false;
- }
- } else if (pSzValue != NULL) {
- DWORD dwType = REG_SZ;
- DWORD dwSize = MAX_PATH * sizeof(CHAR);
- TCHAR szValue[MAX_PATH + 1] = { 0 };
- LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, &dwSize);
- if (lResult == ERROR_SUCCESS) {
- Dbg("Value of \"%s\": %s", lpcszParam, szValue);
- strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
- return true;
- } else {
- Dbg("RegQueryValueEx for \"InstallTime\" error, result=%ld.", lResult);
- return false;
- }
- }
- Dbg("invalid param for \"%s\"", lpcszParam);
- return false;
- }
- static LONG GetSogouInstallState(SogouInstallStateInfo& info)
- {
- HKEY hKey;
- LONG lResult = -1;
- DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
- lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\SogouPCIme", 0, dwFlag, &hKey);
- if (lResult == ERROR_SUCCESS) {
- DWORD dwValue = (DWORD)-1;
- const bool res1 = GetRegistValue(hKey, "InstallFlag", &dwValue, NULL, NULL);
- if (res1) {
- info.dwInstalledStatus = dwValue;
- }
- TCHAR szValue[MAX_PATH + 1] = { 0 };
- DWORD dwLength = MAX_PATH;
- //1970 0x83AA7E80
- const bool res2 = GetRegistValue(hKey, "InstallTime", NULL, szValue, &dwLength);
- if (res2) {
- info.strInstallDate = szValue;
- Dbg("InstallTime: %s", info.GetInstallTime().ToTimeString().GetData());
- }
- if (res1 && res2) {
- lResult = 0;
- } else {
- lResult = -1;
- }
- } else {
- Dbg("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
- }
- RegCloseKey(hKey);
- return lResult;
- }
- static LONG GetSogouExecuteInfo(SogouRunVersionInfo& info, BOOL f32bit = TRUE)
- {
- HKEY hKey;
- LONG lResult = -1;
- PVOID oldValue = NULL;
- Wow64DisableWow64FsRedirection(&oldValue);
- DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
- lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- f32bit ? "SOFTWARE\\SogouPCIme" : "SOFTWARE\\WOW6432Node\\SogouPCIme", 0, dwFlag, &hKey);
- if (lResult == ERROR_SUCCESS) {
- TCHAR szVersion[MAX_PATH + 1] = { 0 }, szDefault[MAX_PATH + 1] = { 0 };
- DWORD dwLength = MAX_PATH;
- const bool res1 = GetRegistValue(hKey, "Version", NULL, szVersion, &dwLength);
- if (res1) info.strVersion = szVersion;
- const bool res2 = GetRegistValue(hKey, "", NULL, szDefault, &dwLength);
- if (res2) info.strInstallDir = szDefault;
- if (res1 && res2) {
- lResult = 0;
- } else {
- lResult = -1;
- }
- } else {
- Dbg("%s::RegOpenKeyEx(32bit=%d) error, Result=%ld.", __FUNCTION__, f32bit, lResult);
- }
- RegCloseKey(hKey);
- Wow64RevertWow64FsRedirection(oldValue);
- return lResult;
- }
- #endif //RVC_OS_WIN
- ErrorCodeEnum ResourceWatcherEntity::DoCheckInstallStateJob()
- {
- LOG_FUNCTION();
- CSmartPointer<IEntityFunction> spFunction = GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum err = spFunction->OpenConfig(Config_Run, spConfig);
- BOOL fNeedAlarm = TRUE;
- SogouInstallInfo info;
- #if defined(RVC_OS_WIN)
- GetSogouInstallState(info.state);
- BOOL is32Bit = Is64BitPlatform() ? FALSE : TRUE;
- if (ERROR_FILE_NOT_FOUND == GetSogouExecuteInfo(info.program, is32Bit))
- GetSogouExecuteInfo(info.program, !is32Bit);
- #else
- info.state.dwInstalledStatus = Sogou_GetInstallStatus();
- info.state.strInstallDate = Sogou_GetInstallTime();
- info.program.strInstallDir = Sogou_GetInstallPath();
- info.program.strVersion = Sogou_GetVersion();
- /** 重试获取版本号 [Gifur@2022224]*/
- const int maxTimes = 3;
- int curTimes = 0;
- while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
- Sleep(1500);
- info.program.strVersion = Sogou_GetVersion();
- curTimes++;
- }
- Dbg("%d, %s, %s, %s"
- , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
- , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
- Dbg("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
- #endif //RVC_OS_WIN
- CSimpleStringA strLastRecord(true);
- err = spConfig->ReadConfigValue("SogouInput", "LastInstalledRecord", strLastRecord);
- if (strLastRecord.IsNullOrEmpty() || info.Stringfy().Compare(strLastRecord) != 0) {
- spConfig->WriteConfigValue("SogouInput", "LastInstalledRecord", info.Stringfy());
- fNeedAlarm = TRUE;
- } else {
- //Report info per day.
- int nLastRecordTime = 0;
- err = spConfig->ReadConfigValueInt("SogouInput", "LastReportTime", nLastRecordTime);
- SYSTEMTIME stTaskTime = CSmallDateTime(nLastRecordTime).ToSystemTime();
- Dbg("Last Sogou install check time: %04d-%02d-%02d %02d:%02d:%02d",
- stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
- stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
- SYSTEMTIME stNow = {};
- GetLocalTime(&stNow);
- if (nLastRecordTime > 0 && stTaskTime.wYear == stNow.wYear
- && stTaskTime.wMonth == stNow.wMonth && stTaskTime.wDay == stNow.wDay) {
- //The Same Day
- fNeedAlarm = FALSE;
- } else {
- fNeedAlarm = TRUE;
- }
- }
- if (fNeedAlarm) {
- const DWORD dwUserCode = info.IsInstalledSuccess() ? LOG_ERR_SOGOU_INPUT_INSTALLED : LOG_ERR_SOGOU_INPUT_NOTINSTALLED;
- LogWarn(Severity_Middle, Error_DataCheck, dwUserCode, info.Stringfy());
- spConfig->WriteConfigValue("SogouInput", "LastReportTime",
- CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- } else {
- Dbg("Do not Report.");
- }
- return Error_Succeed;
- }
- void ResourceWatcherEntity::DoCheckSogouProcessStatus()
- {
- static int old_process_id[2] = { -1, -1 };
- char* relate_processes[2] = {"sogouImeWebSrv", "sogouImeService"};
- int count = 3;
- alive_process_info processes[3];
- memset(processes, 0, sizeof(processes));
- osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
- CAutoArray<CSimpleStringA> msgs(array_size(relate_processes));
- int cnt(0);
- for (int i = 0; i < array_size(relate_processes); ++i) {
- int k = -1;
- for (int j = 0; j < count; ++j) {
- if (strcmp(processes[j].name, relate_processes[i]) == 0) {
- k = j;
- break;
- }
- }
- if (k != -1 && old_process_id[i] == -1) {
- old_process_id[i] = processes[k].pid;
- } else if (k != -1 && (processes[k].pid != old_process_id[i])) {
- msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
- , relate_processes[i], old_process_id[i], processes[k].pid);
- old_process_id[i] = processes[k].pid;
- } else if(k == -1 && old_process_id[i] != 0) {
- msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
- , relate_processes[i], old_process_id[i], 0);
- old_process_id[i] = 0;
- }
- }
- if (cnt > 0) {
- std::string uploadInfo("");
- if (cnt > 1) {
- uploadInfo = "{";
- }
- for (int i = 0; i < cnt; ++i) {
- if (i != 0) {
- uploadInfo += ",";
- }
- uploadInfo += msgs[i].GetData();
- }
- if (cnt > 1) {
- uploadInfo += "}";
- }
- LogWarn(Severity_Middle, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, uploadInfo.c_str());
- }
- }
- //# all available outputs
- //OUTPUTS = $(xrandr | awk '$2 ~ /connected/ {print $1}')
- //echo outputs : $OUTPUTS
- //# get info from xrandr
- //XRANDR = `xrandr`
- //
- //connectedOutputs = $(echo "$XRANDR" | grep " connected" | sed - e "s/\([A-Z0-9]\+\) connected.*/\1/")
- //activeOutput = $(echo "$XRANDR" | grep - e " connected [^(]" | sed - e "s/\([A-Z0-9]\+\) connected.*/\1/")
- //connected = $(echo $connectedOutputs | wc - w)
- //echo connectedOutputs : ${ connectedOutputs }
- //echo activeOutput : ${ activeOutput }
- //echo connected : ${ connected }
- ErrorCodeEnum ResourceWatcherEntity::ConfigMonitorSetting(const UOS::MonitorInfo& config)
- {
- ErrorCodeEnum result(Error_Succeed);
- CSimpleStringA strExecute("xrandr");
- //Get monitor info
- do {
- std::string sucContent, failedContent;
- CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
- bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
- Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
- } while (false);
- do {
- std::string sucContent, failedContent;
- CSimpleStringA strCmd("xrandr |awk '$2 ~ /connected/ {print $1}'");
- bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
- Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
- } while (false);
- CSimpleStringA strCmd(strExecute);
- if (!config.name.empty()) {
- strCmd += CSimpleStringA::Format(" --output %s", config.name.c_str());
- //Set resolution
- if (config.nResolutionX != 0 && config.nResolutionY != 0) {
- CSimpleStringA tmp = CSimpleStringA::Format(" --mode %dx%d", config.nResolutionX, config.nResolutionY);
- strCmd += tmp;
- }
- if (config.refreshRate != 0) {
- CSimpleStringA tmp = CSimpleStringA::Format(" --rate %d", config.refreshRate);
- strCmd += tmp;
- }
- //set primary
- if (config.isPrimary) {
- strCmd += " --primary";
- } else if (config.posDirecttion != -1 && !config.other.empty()) {
- CSimpleStringA posDir(true);
- switch (config.posDirecttion) {
- case 0:
- posDir = "--same-as";
- case 1:
- posDir = "--above";
- break;
- case 2:
- posDir = "--right-of";
- break;
- case 3:
- posDir = "--above";
- break;
- case 4:
- posDir = "--left-of";
- break;
- default:
- result = Error_Param;
- break;
- }
- if (result == Error_Succeed) {
- CSimpleStringA tmp = CSimpleStringA::Format(" %s %s", posDir.GetData(), config.other.c_str());
- strCmd += tmp;
- }
- }
- }
- do
- {
- std::string sucContent, failedContent;
- bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
- Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
- } while (false);
- do {
- std::string sucContent, failedContent;
- strCmd = strExecute;
- bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
- Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
- } while (false);
- return result;
- }
- std::vector<std::string> ResourceWatcherEntity::GetUserNameList(bool bExcludeRoot)
- {
- std::vector<std::string> results;
- array_header_t* arr;
- arr = fileutil_get_sub_dirs_a("/home");
- if (arr) {
- int i;
- for (i = 0; i < arr->nelts; ++i) {
- char szDestSubDir[256] = { 0 };
- char* dir = ARRAY_IDX(arr, i, char*);
- Dbg("sub dir: %s", dir);
- strcpy(szDestSubDir, dir);
- strcat(szDestSubDir, SPLIT_SLASH_STR);
- strcat(szDestSubDir, ".config/kwinrc");
- if (ExistsFileA(szDestSubDir)) {
- std::string strUserName((const char*)&dir[strlen("/home/")]);
- Dbg("username:%s", strUserName.c_str());
- if (strUserName.compare("root") != 0 || !bExcludeRoot) {
- results.push_back(strUserName);
- }
- }
- }
- toolkit_array_free2(arr);
- }
- return results;
- }
- ErrorCodeEnum ResourceWatcherEntity::GetSogouPkgDirPath(CSimpleStringA& strPkgPath)
- {
- CSimpleStringA strAdDataDirPath(true);
- CSimpleStringA strInstallPkgPath(true);
- ErrorCodeEnum result = GetFunction()->GetPath("Ad", strAdDataDirPath);
- if (strAdDataDirPath.IsNullOrEmpty() && m_bInitMode) {
- strAdDataDirPath = "/opt/rvc/adData";
- }
- if (strAdDataDirPath.IsNullOrEmpty()) {
- return Error_Unexpect;
- }
- array_header_t* subs;
- subs = fileutil_get_sub_dirs_a(strAdDataDirPath);
- if (subs) {
- for (int i = 0; i < subs->nelts; ++i) {
- char* dir = ARRAY_IDX(subs, i, char*);
- const char* dirname = &dir[strAdDataDirPath.GetLength() + 1];
- if (CSimpleStringA(dirname).IsStartWith("sogou", true)) {
- if (strInstallPkgPath.IsNullOrEmpty()) {
- Dbg("found it: %s", dir);
- strInstallPkgPath = dir;
- } else if (strInstallPkgPath.Compare(dir) < 0) {
- Dbg("replace %s with %s", (LPCTSTR)strInstallPkgPath, dir);
- strInstallPkgPath = dir;
- }
- }
- }
- toolkit_array_free2(subs);
- }
- if (strInstallPkgPath.IsNullOrEmpty()) {
- return Error_NotExist;
- }
- strPkgPath = strInstallPkgPath;
- return Error_Succeed;
- }
- ErrorCodeEnum ResourceWatcherEntity::RunShellScript(LPCTSTR cmdline)
- {
- char app[MAX_PATH] = { '\0' };
- tk_process_t* process = NULL;
- tk_process_option_t option;
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- option.params = (char*)cmdline;
- const int res = process_spawn(&option, &process);
- if (0 == res) {
- Dbg("execute {%s}, pid: %d", cmdline, process->pid);
- FREE(process);
- return Error_Succeed;
- } else {
- Dbg("execute {%s} failed: %d", cmdline, res);
- return Error_Unexpect;
- }
- }
- void ResourceWatcherEntity::OnSysVarEvent(const char* pszKey, const char* pszValue, const char* pszOldValue, const char* pszEntityName)
- {
- Dbg("OnSysVarEvent pszKey = %s, pszValue = %s", pszKey, pszValue);
- if ((_strnicmp(pszKey, "UIState", strlen("UIState")) == 0)) {
- if (_strnicmp(pszValue, "M", strlen("M")) == 0) {
- ClearVersionTask* task = new ClearVersionTask(&m_fsm);
- GetFunction()->PostThreadPoolTask(task);
- }
- }
- }
- std::string ResourceWatcherEntity::DoCheckCertainProcessStatus(const CAutoArray<CSimpleStringA>& pName)
- {
- int pSize = pName.GetCount();
- /*static int old_process_id[pSize];
- memset(old_process_id, -1, sizeof(old_process_id));*/
- vector<int> old_process_id;
- CAutoArray<CSimpleStringA> msgs;
- alive_process_info* processes = new alive_process_info[pSize];
- char** relate_processes = new char* [pSize];
- int count = pSize;
- for (int i = 0; i < pSize; ++i)
- {
- old_process_id.push_back(-1);
- CSimpleStringA temp("");
- msgs.Append(&temp, 0, 1);
- relate_processes[i] = const_cast<char*>(pName[i].GetData());
- Dbg("relate_process name: %s.", relate_processes[i]);
- }
- Dbg("COUNT = %d!", count);
- osutil_detect_unique_app(relate_processes, pSize, &count, processes);
- int cnt(0);
- for (int i = 0; i < pSize; ++i) {
- int k = -1;
- for (int j = 0; j < count; ++j) {
- if (strcmp(processes[j].name, relate_processes[i]) == 0) {
- k = j;
- break;
- }
- }
- if (k != -1 && old_process_id[i] == -1) {
- msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
- , relate_processes[i], processes[k].pid);
- old_process_id[i] = processes[k].pid;
- }
- else if (k != -1 && (processes[k].pid != old_process_id[i])) {
- msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
- , relate_processes[i], old_process_id[i], processes[k].pid);
- old_process_id[i] = processes[k].pid;
- }
- else if (k == -1 && old_process_id[i] != 0) {
- msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
- , relate_processes[i], old_process_id[i], 0);
- old_process_id[i] = 0;
- }
- }
- std::string uploadInfo("");
- if (cnt > 0) {
- if (cnt > 1) {
- uploadInfo = "{";
- }
- for (int i = 0; i < cnt; ++i) {
- if (i != 0) {
- uploadInfo += ",";
- }
- uploadInfo += msgs[i].GetData();
- }
- if (cnt > 1) {
- uploadInfo += "}";
- }
- }
- return uploadInfo;
- }
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(ResourceWatcherEntity)
- SP_END_ENTITY_MAP()
|