123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022 |
- #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"
- #include "ResourceWatcher_UserCode.h"
- #if defined(RVC_OS_LINUX)
- #include "SogouVersion.h"
- #include <winpr/sysinfo.h>
- #include <sys/wait.h>
- #include <errno.h>
- #endif //RVC_OS_LINUX
- #include "XUnZipZilb.h"
- #include "publicFunExport.h"
- #include <map>
- #include <regex.h>
- #include "../mod_healthmanager/HealthManager_client_g.h"
- using namespace HealthManager;
- void ResourceWatcherServiceSession::Handle_Fetch(
- SpReqAnsContext<ResourceWatcherService_Fetch_Req, ResourceWatcherService_Fetch_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->Fetch(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetDevInfo(
- SpReqAnsContext<ResourceWatcherService_GetDevInfo_Req, ResourceWatcherService_GetDevInfo_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetDevInfo(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetCardSwiper(SpReqAnsContext<ResourceWatcherService_GetCardSwiper_Req, ResourceWatcherService_GetCardSwiper_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetCSwiperStatus(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetCpuType(SpReqAnsContext<ResourceWatcherService_GetCpuType_Req, ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetCPUType(ctx);
- }
- void ResourceWatcherServiceSession::Handle_OperateFile
- (SpReqAnsContext<ResourceWatcherService_OperateFile_Req, ResourceWatcherService_OperateFile_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->OperateFile(ctx);
- }
- void ResourceWatcherServiceSession::Handle_ExtractEventLog(
- SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req, ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->RetrieveEventLog(ctx);
- }
- void ResourceWatcherServiceSession::Handle_BizLinkDetect(SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->BizLinkDetect(ctx);
- }
- void ResourceWatcherServiceSession::Handle_CheckNetType(SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->CheckNetType(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetBizLinks(SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetBizLinks(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetThirdPartyInstallState(ctx);
- }
- void ResourceWatcherServiceSession::Handle_InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->InstallThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->UninstallThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->RestartThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->ProcessDetectThirdPartyProgram(ctx);
- }
- void ResourceWatcherServiceSession::Handle_FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->FilesClean(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetTerminalVersionList(SpReqAnsContext<ResourceWatcherService_GetTerminalVersionList_Req, ResourceWatcherService_GetTerminalVersionList_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetTerminalVersionList(ctx);
- }
- void ResourceWatcherServiceSession::Handle_ManipulateVersion(SpReqAnsContext<ResourceWatcherService_ManipulateVersion_Req, ResourceWatcherService_ManipulateVersion_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->ManipulateVersion(ctx);
- }
- void ResourceWatcherServiceSession::Handle_FetchSystemSnapshot(SpReqAnsContext<ResourceWatcherService_FetchSystemSnapshot_Req, ResourceWatcherService_FetchSystemSnapshot_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->FetchSystemSnapshot(ctx);
- }
- void ResourceWatcherServiceSession::Handle_UpdateDNS(SpReqAnsContext<ResourceWatcherService_UpdateDNS_Req, ResourceWatcherService_UpdateDNS_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->UpdateDNS(ctx);
- }
- void ResourceWatcherServiceSession::Handle_GetNetworkInfo(SpReqAnsContext<ResourceWatcherService_GetNetworkInfo_Req, ResourceWatcherService_GetNetworkInfo_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetNetworkInfo(ctx);
- }
- 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;
- }
- CVersion ConvertVersion()
- {
- CVersion installVer;
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(strVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not sogou version.[%s]", strVersion.GetData());
- } else {
- installVer = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
- }
- return installVer;
- }
- //true: 普通调用版本输入法,false: SDK版本输入法
- bool IsTSFVersion()
- {
- #if defined(_MSC_VER)
- CVersion standardVer = CVersion(2, 6, 1, 1967); //对比版本为2.6.1.1967
- #else
- CVersion standardVer = CVersion(2, 6, 4, 355); //对比版本为2.4.6.355
- #endif //_MSC_VER
-
- return (ConvertVersion() >= standardVer);
- }
- };
- 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().GetData();
- 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);
- }
- };
- std::string TryToGetSogouVersionEx()
- {
- std::string succStr, errStr;
- std::string runStr("cat /opt/sogouimebs/files/share/sogou-version");
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- if (succStr.empty()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cat sogou version return empty!");
- } else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("cat sogou version returned: %s", succStr.c_str());
- return succStr;
- }
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("execute cmd failed: %s", errStr.c_str());
- }
- return "";
- }
- ErrorCodeEnum GetSogouInstallInfo(SogouInstallInfo& info)
- {
- info.state.dwInstalledStatus = Sogou_GetInstallStatus();
- info.state.strInstallDate = Sogou_GetInstallTime();
- info.program.strInstallDir = Sogou_GetInstallPath();
- info.program.strVersion = Sogou_GetVersion();
- if (info.program.strVersion.IsNullOrEmpty()) {
- info.program.strVersion = TryToGetSogouVersionEx().c_str();
- }
- const int maxTimes = 3;
- int curTimes = 0;
- while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
- Sleep(1000);
- info.program.strVersion = Sogou_GetVersion();
- if (info.program.strVersion.IsNullOrEmpty()) {
- info.program.strVersion = TryToGetSogouVersionEx().c_str();
- }
- curTimes++;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%d, %s, %s, %s"
- , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
- , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
- return info.IsInstalledSuccess() ? Error_Succeed : Error_InvalidState;
- }
- 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;
- GetSogouInstallInfo(info);
- ctx->Ans.status = info.IsInstalledSuccess() ? 1 : 0;
- ctx->Ans.path = info.program.strInstallDir;
- ctx->Ans.version = info.program.strVersion;
- ctx->Ans.reserverd1 = info.state.GetInstallTime().ToTimeString();
- ctx->Ans.reserverd2 = "";
- ctx->Ans.reserverd3 = info.program.IsTSFVersion() ? 1 : 0;
- ctx->Ans.reserverd4 = 0;
- } 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 if (ctx->Req.mode == 3) { //自定义安装
- if (ctx->Req.reserverd3.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("the req rerverd3 is empty.");
- result = Error_Param;
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to check %s 's install status...", ctx->Req.reserverd3.GetData());
- CSimpleStringA strSoftwareName(ctx->Req.reserverd3);
- CSimpleStringA strSoftwareVersion(ctx->Req.reserverd4);
- CSimpleStringA runItem = CSimpleStringA::Format("dpkg -l | grep %s | awk '{print $3}'", strSoftwareName.GetData());
- std::string additional("");
- std::string succStr, errStr;
- std::string runStr(runItem.GetData());
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- if (succStr.empty()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s is not installed", strSoftwareName.GetData());
- ctx->Ans.status = 0;
- } else {
- succStr = SP::Utility::ToTrim(succStr);
- if (strSoftwareVersion.IsNullOrEmpty() || strSoftwareVersion.Compare(succStr.c_str()) == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s is installed, version: %s", strSoftwareName.GetData(), succStr.c_str());
- ctx->Ans.status = 1;
- } else {
- ctx->Ans.status = 2;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s is installed, but the version<%s> is not the dream one<%s>"
- , strSoftwareName.GetData(), succStr.c_str(), strSoftwareVersion.GetData());
- ctx->Ans.reserverd1 = succStr.c_str();
- }
- }
- } else {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Execute <%s> failed.", runItem.GetData());
- result = Error_Process;
- }
- }
- } 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;
- }
- ErrorCodeEnum ResourceWatcherEntity::GetUnzipTempDir(CSimpleStringA& strUnzipDir)
- {
- CSimpleStringA strDownloadsPath;
- auto rc = GetFunction()->GetPath("Downloads", strDownloadsPath);
- assert(rc == Error_Succeed);
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strDownloadsPath, strUnzipDir);
- if (strUnzipDir.IsEndWith(".zip") || strUnzipDir.IsEndWith(".cab"))
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- return Error_Succeed;
- }
- ErrorCodeEnum ResourceWatcherEntity::UnzipPack(const char* unZipPackName)
- {
- CSimpleStringA strDownloadsPath;
- auto rc = GetFunction()->GetPath("Downloads", strDownloadsPath);
- assert(rc == Error_Succeed);
- CSimpleStringA strTempPath;
- ErrorCodeEnum rc2 = GetFunction()->GetPath("Temp", strTempPath);
- assert(rc2 == Error_Succeed);
- CSimpleStringA strUnzipPath;
- strUnzipPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strTempPath.GetData(), unZipPackName);
- if (strUnzipPath.IsEndWith(".zip") || strUnzipPath.IsEndWith(".cab"))
- {
- strUnzipPath = strUnzipPath.SubString(0, strUnzipPath.GetLength() - 4);
- }
- // 如目标目录存在,则先删除
- if (ExistsDirA(strUnzipPath))
- {
- if (!RemoveDirRecursiveA(strUnzipPath)) {
- LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("remove old unzip dir [%s] fail", strUnzipPath.GetData()));
- return Error_NotExist;
- }
- }
- // 创建临时解压目录
- CreateDirA(strUnzipPath.GetData(), false);
- // 解压
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
- string zipFileStr = strZipFile.GetData();
- string zipTempDir = strUnzipPath.GetData();
- if (!ExistsFileA(strZipFile.GetData())) {
- LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("pack [%s] not exists", strZipFile.GetData()));
- return Error_NotExist;
- }
- if (UnZipToDir(zipFileStr, zipTempDir) != 0) {
- LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("unzip pack [%s] fail", zipFileStr.c_str()));
- return Error_NotExist;
- }
- return Error_Succeed;
- }
- void ResourceWatcherEntity::InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_INSTALL_THIRDPARTY, CSimpleStringA::Format("InstallThirdPartyProgram: ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2));
- bool sogouInstalled = false;
- const bool doTryRestart = (ctx->Req.reserved1 != 1);
- if (ctx->Req.type == 1)
- {
- //安装搜狗输入法
- CSmartPointer<InstallSogouTask> sogouInstall = new InstallSogouTask(this);
- sogouInstall->ctx = ctx;
- GetFunction()->PostThreadPoolTask(sogouInstall.GetRawPointer());
- return;
- } 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;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM) ("用户桌面安装:%s. result:%d.", tmpMsg.GetData(), tmpResult);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_INSTALL_THIRDPARTY,
- CSimpleStringA::Format("用户桌面安装:%s. result:%d.", tmpMsg.GetData(), tmpResult));
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- return;
- }
- void ResourceWatcherEntity::InstallSogou(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req,
- ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- bool sogouInstalled = false;
- const bool doTryRestart = (ctx->Req.reserved1 != 1);
- SogouInstallInfo info;
- //安装搜狗输入法
- bool zipFind = false;
- time_t newestWrite = 0;
- CSimpleStringA newSogouPath(true);
- CSimpleStringA strDownloadDirPath(true);
- GetFunction()->GetPath("Downloads", strDownloadDirPath);
- CSimpleStringA strTempDirPath(true);
- GetFunction()->GetPath("Temp", strTempDirPath);
- if (strDownloadDirPath.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("downloads path is invalid, maybe in config mode");
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("搜狗安装包目录[Downloads]不存在!");
- }
- else {
- DIR* dp;
- struct dirent* dirp;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to open dir %s", strDownloadDirPath.GetData());
- if ((dp = opendir(strDownloadDirPath.GetData())) != NULL)
- {
- while ((dirp = readdir(dp)) != NULL)
- {
- CSimpleStringA tmpName(dirp->d_name);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
- if ((tmpName.IsStartWith("sogou", true) || tmpName.IsStartWith("uos-sogou", true))
- && tmpName.IsEndWith(".zip", true)) {
- struct stat buf;
- memset(&buf, 0x00, sizeof(buf));
- CSimpleStringA strFullPathName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadDirPath.GetData(), dirp->d_name);
- const int ret = stat(strFullPathName.GetData(), &buf);
- if (ret != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("获取文件[%s]状态信息出错。", tmpName.GetData());
- }
- else if (buf.st_mtim.tv_sec > newestWrite) {
- newestWrite = buf.st_mtim.tv_sec;
- newSogouPath = CSimpleStringA(tmpName.GetData());
- zipFind = true;
- }
- }
- }
- closedir(dp);
- if (!zipFind)
- {
- tmpResult = Error_NotExist;
- tmpMsg = CSimpleStringA::Format("在路径[%s]下未找到搜狗安装包!", strDownloadDirPath.GetData());
- }
- }
- else
- {
- tmpResult = Error_NotExist;
- tmpMsg = CSimpleStringA::Format("打开[Downloads]目录失败!");
- }
- }
- CSimpleStringA strInstallPkgPath(true);
- if (zipFind)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to unzip pack %s", newSogouPath.GetData());
- if (UnzipPack(newSogouPath) != Error_Succeed)
- {
- tmpResult = Error_Unexpect;
- tmpMsg = CSimpleStringA::Format("解压搜狗安装包失败!");
- }
- else
- {
- newSogouPath = newSogouPath.SubString(0, newSogouPath.GetLength() - 4);
- strInstallPkgPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",
- strTempDirPath.GetData(), newSogouPath.GetData());
-
- /** 下载下来的包出现两层目录的情况 [陈纪林@2023814]*/
- DIR* dp1;
- struct dirent* dirp1;
- if ((dp1 = opendir(strInstallPkgPath.GetData())) != NULL) {
- while ((dirp1 = readdir(dp1)) != NULL)
- {
- CSimpleStringA tmpName(dirp1->d_name);
- if (tmpName.IsStartWith("sogou", true) || tmpName.IsStartWith("uos-sogou", true))
- {
- strInstallPkgPath = strInstallPkgPath + SPLIT_SLASH_STR + tmpName;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("安装目录:%s.", strInstallPkgPath.GetData());
- }
- }
- closedir(dp1);
- }
-
- }
- }
- else
- {
- tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
- if (tmpResult != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format(" 指定位置 [Ad] 找不到输入法安装包");
- }
- }
- CSimpleStringA strInstallScriptFile;
- CSimpleStringA strRunIniFilePath;
- CSimpleStringA strResultLogFilePath;
- const bool doNotStartup(true); //安装后是否启动搜狗输入法服务,据搜狗反馈,不能通过root权限启动Sogou输入法
- if (tmpResult == Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to install sogou input... %s", strInstallPkgPath.GetData());
- tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
- if (tmpResult != Error_Succeed) {
- tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
- tmpResult = Error_NotExist;
- } else {
- strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
- strResultLogFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "result.log";
- if (ExistsFileA(strRunIniFilePath)) {
- char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
- strInstallScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + p;
- FREE(p);
- } else {
- strInstallScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "install_sogouime.sh";
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("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");
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("startup script file: %s", strStartupScriptFile.GetData());
- if (!ExistsFileA(strStartupScriptFile)) {
- tmpMsg = CSimpleStringA::Format("%s 启动脚本文件不存在,请重启设备再次验证", strStartupScriptFile.GetData());
- tmpResult = Error_NotExist;
- } else {
- Sleep(1000);
- do {
- sprintf(app, "bash %s", strStartupScriptFile.GetData());
- tmpResult = RunShellScript(app);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
- tmpResult = Error_Process;
- }
- } while (false);
- }
- }
- } else {
- tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
- tmpResult = Error_NotExist;
- }
- }
- }
- if (tmpResult == Error_Succeed) {
- Sleep(1500);
- 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 {
- GetSogouInstallInfo(info);
- 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();
- //ctx->Ans.reserverd3 = info.program.IsTSFVersion() ? 1 : 0;
- //ctx->Ans.reserverd4 = 0;
- if (doTryRestart) {
- tmpMsg = CSimpleStringA::Format(" 从[%s]安装搜狗输入法成功。", strInstallPkgPath.GetData());
- }
- sogouInstalled = true;
- }
- }
- }
- }
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM) ("用户桌面重装搜狗:%s. result:%d.", tmpMsg.GetData(), tmpResult);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_INSTALL_THIRDPARTY,
- CSimpleStringA::Format("用户桌面重装搜狗:%s. result:%d.", tmpMsg.GetData(), tmpResult));
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- if (sogouInstalled && doTryRestart && !info.program.IsTSFVersion()) {
- HealthManagerService_ClientBase* m_pRWClient = new HealthManagerService_ClientBase(this);
- ErrorCodeEnum eErr = m_pRWClient->Connect();
- if (eErr != Error_Succeed) {
- Dbg("HealthManager connected failed.");
- m_pRWClient->SafeDelete();
- m_pRWClient = NULL;
- } else {
- HealthManagerService_ControlTerminalLife_Req detReq;
- HealthManagerService_ControlTerminalLife_Ans detAns;
- detReq.cmdType = 4;
- detReq.reason = 0;
- eErr = m_pRWClient->ControlTerminalLife(detReq, detAns, 3000);
- if (eErr == Error_Succeed) {
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_RESTARTPC_AFTER_INSTALLED_SOGOUINPUT, "Ask HealthManagerService for restarting PC succ after installing sogouinput");
- } else {
- LogWarn(Severity_Middle, Error_Unexpect, 0, CSimpleStringA::Format("HealthManagerService::ControlTerminalLife failed: %s", SpStrError(eErr)));
- }
- m_pRWClient->GetFunction()->CloseSession();
- m_pRWClient = NULL;
- }
- }
- }
- void ResourceWatcherEntity::UninstallSogou(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to uninstall sogou input...");
- CSimpleStringA strUninstallScriptFile(true);
- SogouInstallInfo info;
- do {
- ErrorCodeEnum ecGet = GetSogouInstallInfo(info);
- if (info.program.IsTSFVersion()) {
- CSimpleStringA shellScriptPath;
- GetFunction()->GetPath("Base", shellScriptPath);
- shellScriptPath += SPLIT_SLASH_STR;
- shellScriptPath += "res" SPLIT_SLASH_STR "RunScript" SPLIT_SLASH_STR;
- strUninstallScriptFile = shellScriptPath + "uninstall_tfs_sogouimebs.sh";
- if (!ExistsFileA(strUninstallScriptFile)) {
- tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strUninstallScriptFile.GetData());
- tmpResult = Error_InvalidState;
- break;
- }
- char app[MAX_PATH] = { '\0' };
- sprintf(app, "bash %s", strUninstallScriptFile.GetData());
- tmpResult = RunShellScript(app);
- if (tmpResult != 0) {
- tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
- } else {
- Sleep(300);
- }
- } else {
- CSimpleStringA strInstallPkgPath;
- tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
- if (tmpResult == Error_Succeed) {
- 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";
- 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);
- }
- }
- } else {
- tmpMsg = CSimpleStringA::Format(" 指定位置 [Ad] 找不到输入法安装包");
- tmpResult = Error_InvalidState;
- break;
- }
- }
- } while (false);
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- }
- 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 = "切换版本失败";
- } else {
- LogWarn(Severity_Low, Error_IO, LOG_RESOURCEWATCHE_CHANGE_CURRENT_VERSION,
- CSimpleStringA::Format("changed version from %s to %s", strCurrVer.GetData(), ctx->Req.value.GetData()));
- }
- }
- 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 = "删除版本失败";
- } else {
- LogWarn(Severity_Low, Error_IO, LOG_RESOURCEWATCHE_DELETE_VERSION,
- CSimpleStringA::Format("delete version %s", ctx->Req.value.GetData()));
- }
- }
- }
- 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);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_UNINSTALL_THIRDPARTYPROGRAM,
- CSimpleStringA::Format("UninstallThirdPartyProgram: ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2));
- if (ctx->Req.type == 1) {
- //安装搜狗输入法
- UninstallSogouTask* sogouUninstall = new UninstallSogouTask(this);
- sogouUninstall->ctx = ctx;
- GetFunction()->PostThreadPoolTask(sogouUninstall);
- return;
- } 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);
- CSimpleStringA tmpMsg(true);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_RESTART_THIRDPARTYPROGRAM,
- CSimpleStringA::Format("RestartThirdPartyProgram: ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2));
- if (ctx->Req.type == 1)
- {
- SogouInstallInfo info;
- GetSogouInstallInfo(info);
- if (!info.program.IsTSFVersion())
- {
- //重启搜狗输入法
- 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) {
- cnt++;
- old_process_id[k] = processes[k].pid;
- std::string sucContent, failedContent;
- CSimpleStringA strCmd = CSimpleStringA::Format("kill -9 %d", old_process_id[k]);
- bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
- }
- }
- int cnt2(0);
- if (cnt > 0)
- {
- ///**TODO(Gifur@7/5/2022): 待优化处理 */
- Sleep(2000);
- int newCount = 3;
- int notSame = 0;
- vector<CSimpleStringA> tKillmsg;
- alive_process_info newProcesses[3];
- memset(newProcesses, 0, sizeof(newProcesses));
- osutil_detect_unique_app(relate_processes, array_size(relate_processes), &newCount, newProcesses);
- for (int i = 0; i < array_size(relate_processes); ++i) {
- int k = -1;
- for (int j = 0; j < count; ++j) {
- if (strcmp(newProcesses[j].name, relate_processes[i]) == 0 && newProcesses[j].pid > 0) {
- k = j;
- break;
- }
- }
- if (k != -1) {
- cnt2++;
- if (newProcesses[k].pid != old_process_id[k]) {
- notSame++;
- } else {
- tmpResult = Error_Unexpect;
- CSimpleStringA tmsg = CSimpleStringA::Format("{杀死当前搜狗进程[%s]失败,pid[%d]。}",
- newProcesses[k].name, newProcesses[k].pid);
- tKillmsg.push_back(tmsg);
- }
- }
- }
- if (cnt2 == 0)
- {
- tmpMsg = "已杀死搜狗进程。但重启搜狗进程失败,请确认守护进程正常运行。";
- tmpResult = Error_Unexpect;
- }
- else {
- if (tKillmsg.size() != 0) {
- for (int i = 0; i < tKillmsg.size(); ++i) {
- tmpMsg += tKillmsg[i];
- }
- } else {
- tmpMsg = "已成功重启搜狗输入法进程。";
- }
- }
- }
- else
- {
- tmpMsg = "当前系统无搜狗进程,请确认已安装搜狗输入法,并重启计算机以尝试启动搜狗输入法!";
- tmpResult = Error_Unexpect;
- }
- }
- else
- {
- tmpResult = Error_NotSupport;
- tmpMsg = CSimpleStringA::Format("新搜狗版本,不支持重启功能。");
- }
- }
- else
- {
- tmpResult = Error_Param;
- tmpMsg = CSimpleStringA::Format("接口调用参数错误。");
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM) ("用户桌面重启:%s. result:%d.", tmpMsg.GetData(), tmpResult);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_RESTART_THIRDPARTYPROGRAM,
- CSimpleStringA::Format("用户桌面重启:%s. result:%d.", tmpMsg.GetData(), tmpResult));
- ctx->Ans.result = tmpResult;
- 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);
- CSimpleStringA tmpMsg(true);
- std::string res("");
- if (ctx->Req.type == 1) {//检测搜狗输入法进程
- CAutoArray<CSimpleStringA> pName(2);
- pName[0] = "sogouImeWebSrv";
- pName[1] = "sogouImeService";
- res = DoCheckCertainProcessStatus(pName);
- if (res.length() == 0)
- {
- tmpResult = Error_Failed;
- tmpMsg = "当前系统无搜狗进程";
- }
- else
- {
- tmpMsg = CSimpleStringA::Format("%s", res.c_str());
- }
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- return;
- }
- void ResourceWatcherEntity::CheckProcessStatus()
- {
- vector<string> msg;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- CSimpleStringA getProcess(""), tName("");
- int procCnt = 0;
- do {
- procCnt++;
- getProcess = CSimpleStringA::Format("ProcessNameUOS%d", procCnt);
- spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getProcess, tName);
- if (!tName.IsNullOrEmpty()) {
- std::string succStr, errStr;
- std::string runStr("pgrep -d '|' ");
- runStr += tName.GetData();
- CSimpleStringA tMsg(true);
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- if (succStr.empty()) {
- tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": 0}", tName.GetData());
- } else {
- succStr = SP::Utility::ToTrim(succStr);
- if (succStr.find('|') != std::string::npos) {
- tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": %s}", tName.GetData(), succStr.c_str());
- } else {
- tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": \"%s\"}", tName.GetData(), succStr.c_str());
- }
- }
- } else {
- tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": -1}", tName.GetData());
- }
- msg.push_back(tMsg.GetData());
- }
- } while (!tName.IsNullOrEmpty());
- if (msg.size() != 0) {
- CSimpleStringA res(true);
- if (msg.size() == 1) {
- res = msg[0].c_str();
- } else {
- res = "{";
- for (int i = 0; i < msg.size(); ++i) {
- if (i != 0) { res += ","; }
- res = res + msg[i].c_str();
- }
- res += "}";
- }
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_PROCESS_STATUS, res);
- }
- }
- #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
- GetSogouInstallInfo(info);
- #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_Low, 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_Low, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, uploadInfo.c_str());
- }
- }
- 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) || CSimpleStringA(dirname).IsStartWith("uos-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' };
- char szldPath[1024] = { '\0' };
- size_t szldLen = 1023;
- tk_process_t* process = NULL;
- tk_process_option_t option;
- const int ldRet = toolkit_getenv("LD_LIBRARY_PATH", szldPath, &szldLen);
- if (ldRet == 0) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get library path: %s", szldPath);
- toolkit_unsetenv("LD_LIBRARY_PATH");
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetEnv of LD_LIBRARY_PATH failed: %s", toolkit_strerror(ldRet));
- }
- option.exit_cb = NULL;
- option.file = NULL;
- option.flags = 0;
- option.params = (char*)cmdline;
- const int res = process_spawn(&option, &process);
- if (ldRet == 0) {
- toolkit_setenv("LD_LIBRARY_PATH", szldPath);
- }
- if (0 == res) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("execute {%s}, pid: %d, and wait ...", cmdline, process->pid);
- int status;
- while (process->pid > 0 && waitpid(process->pid, &status, 0) < 0) {
- if (errno != EINTR) {
- status = -1;
- break;
- }
- }
- if (WIFEXITED(status)) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("normal terminal. exit status: %d", WEXITSTATUS(status));
- } else if (WIFSIGNALED(status)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("abnormal terminal, signal: %d", WTERMSIG(status));
- } else if (WIFSTOPPED(status)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cihild stop, signal: %d", WSTOPSIG(status));
- }
- FREE(process);
- return Error_Succeed;
- } else {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("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) {
- ///**TODO(Gifur@8/11/2023): 不要每一次进入首页都进行版本清理,没必要 */
- ClearVersionTask* task = new ClearVersionTask(&m_fsm);
- GetFunction()->PostThreadPoolTask(task);
- }
- }
- }
- std::string ResourceWatcherEntity::DoCheckCertainProcessStatus(const CAutoArray<CSimpleStringA>& pName)
- {
- const int pSize = pName.GetCount();
- 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());
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("relate_process name: %s.", relate_processes[i]);
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("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;
- }
- void ResourceWatcherEntity::FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
- {
- ErrorCodeEnum result(Error_Succeed);
- ErrorCodeEnum tmpResult(Error_Succeed);
- CSimpleStringA tmpMsg(true);
- if (ctx->Req.type == 1)//清理浏览器缓存
- {
- BrowserCacheClean browserCacheClean;
- browserCacheClean.needClean = 1;
- SpSendBroadcast(GetFunction(),
- SP_MSG_OF(BrowserCacheClean), SP_MSG_SIG_OF(BrowserCacheClean), browserCacheClean);
- tmpMsg = "已发送重启命令";
- }
- else
- {
- tmpResult = Error_NotExist;
- tmpMsg = "非法的调用参数";
- }
- ctx->Ans.result = tmpResult;
- ctx->Ans.msg = tmpMsg;
- ctx->Answer(result);
- }
- void ResourceWatcherEntity::FetchSystemSnapshot(
- SpReqAnsContext<ResourceWatcherService_FetchSystemSnapshot_Req, ResourceWatcherService_FetchSystemSnapshot_Ans>::Pointer ctx)
- {
- CSimpleStringA info(true);
- if (ctx->Req.type == 1) {
- const bool ret = m_fsm.GetMonitorInfo(info);
- if (ret) {
- ctx->Ans.result = 0;
- ctx->Ans.msg = info;
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS_GET, info);
- } else {
- ctx->Ans.result = -1;
- ctx->Ans.msg = "调用 GetMonitorInfo 接口失败";
- }
- ctx->Answer(Error_Succeed);
- } else if (ctx->Req.type == 2) { /** 有无安装新版浏览器 [Gifur@20221219]*/
- const std::string execute_newbrowser_path = "/usr/share/browser/browser";
- const std::string execute_oldbrowser_path = "/usr/share/uosbrowser/uosbrowser";
- int result(0);
- std::string additional("");
- std::string succStr, errStr;
- std::string runStr("dpkg -l | grep org.deepin.browser | awk '{print $3}'");
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- if (succStr.empty()) {
- if (ExistsFileA(execute_oldbrowser_path.c_str())) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s exists!", execute_oldbrowser_path.c_str());
- result = 1;
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s not exists!", execute_oldbrowser_path.c_str());
- }
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("new browser version: %s", succStr.c_str());
- additional = succStr;
- if (!ExistsFileA(execute_newbrowser_path.c_str())) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s not exists!", execute_newbrowser_path.c_str());
- }
- result = 2;
- }
- ctx->Ans.result = result;
- ctx->Ans.msg = additional.c_str();
- ctx->Answer(Error_Succeed);
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("execute '%s' failed!", runStr.c_str());
- ctx->Answer(Error_Process);
- }
- } else {
- ctx->Answer(Error_NotSupport);
- }
- }
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(ResourceWatcherEntity)
- SP_END_ENTITY_MAP()
|