1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023 |
- #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)(EntityResource::getLink().upgradeLink())->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]*/
- ///**TODO(Gifur@8/7/2023): 支持信创单屏版本 */
- 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()
|