mod_ResourceWatcher.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  1. // mod_ResourceWatcher.cpp : 定义 DLL 应用程序的导出函数。
  2. //
  3. #include "stdafx.h"
  4. #include "mod_ResourceWatcher.h"
  5. #include "CommEntityUtil.hpp"
  6. #include "array.h"
  7. #include "fileutil.h"
  8. #include "iniutil.h"
  9. #include "toolkit.h"
  10. #include "osutil.h"
  11. #if defined(RVC_OS_LINUX)
  12. #include "SogouVersion.h"
  13. #include <winpr/sysinfo.h>
  14. #endif //RVC_OS_LINUX
  15. #include "XUnZipZilb.h"
  16. #include "publicFunExport.h"
  17. #include <map>
  18. #include <regex.h>
  19. #include "../mod_healthmanager/HealthManager_client_g.h"
  20. using namespace HealthManager;
  21. struct SogouRunVersionInfo
  22. {
  23. CSimpleStringA strInstallDir;
  24. CSimpleStringA strVersion;
  25. SogouRunVersionInfo():strInstallDir(true),strVersion(true){}
  26. CSimpleStringA ToString() const {
  27. CSimpleStringA result(true);
  28. if(!strInstallDir.IsNullOrEmpty()) {
  29. result += strInstallDir;
  30. result += "#";
  31. }
  32. if(!strVersion.IsNullOrEmpty()) {
  33. result += strVersion;
  34. }
  35. return result;
  36. }
  37. };
  38. struct SogouInstallStateInfo
  39. {
  40. DWORD dwInstalledStatus;
  41. CSimpleStringA strInstallDate;
  42. SogouInstallStateInfo():dwInstalledStatus(-1),strInstallDate(true){}
  43. CSimpleStringA ToString() const {
  44. CSimpleStringA result(true);
  45. if(!strInstallDate.IsNullOrEmpty()) {
  46. //result += strInstallDate;
  47. result += GetInstallTime().ToTimeString();
  48. result += "#";
  49. }
  50. result += CSimpleStringA::Format("%u", dwInstalledStatus);
  51. return result;
  52. }
  53. CSmallDateTime GetInstallTime() const {
  54. if(!strInstallDate.IsNullOrEmpty()) {
  55. DWORD dwSecsSince1970(0);
  56. sscanf_s(strInstallDate.GetData(), "%u", &dwSecsSince1970);
  57. dwSecsSince1970 -= 946656000; // 2000-1970
  58. return CSmallDateTime(dwSecsSince1970);
  59. }
  60. return CSmallDateTime::BeginTime;
  61. }
  62. };
  63. struct SogouInstallInfo
  64. {
  65. SogouInstallStateInfo state;
  66. SogouRunVersionInfo program;
  67. CSimpleStringA Stringfy() const
  68. {
  69. return (state.ToString() + "||" + program.ToString());
  70. }
  71. bool IsInstalledSuccess() const {
  72. return (state.dwInstalledStatus == 0);
  73. }
  74. };
  75. void ResourceWatcherServiceSession::Handle_Fetch(
  76. SpReqAnsContext<ResourceWatcherService_Fetch_Req, ResourceWatcherService_Fetch_Ans>::Pointer ctx)
  77. {
  78. m_pEntity->Fetch(ctx);
  79. }
  80. void ResourceWatcherServiceSession::Handle_GetDevInfo(
  81. SpReqAnsContext<ResourceWatcherService_GetDevInfo_Req, ResourceWatcherService_GetDevInfo_Ans>::Pointer ctx)
  82. {
  83. LOG_FUNCTION();
  84. m_pEntity->GetDevInfo(ctx);
  85. }
  86. void ResourceWatcherServiceSession::Handle_GetCardSwiper(SpReqAnsContext<ResourceWatcherService_GetCardSwiper_Req, ResourceWatcherService_GetCardSwiper_Ans>::Pointer ctx)
  87. {
  88. LOG_FUNCTION();
  89. m_pEntity->GetCSwiperStatus(ctx);
  90. }
  91. void ResourceWatcherServiceSession::Handle_GetCpuType(SpReqAnsContext<ResourceWatcherService_GetCpuType_Req, ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
  92. {
  93. LOG_FUNCTION();
  94. m_pEntity->GetCPUType(ctx);
  95. }
  96. void ResourceWatcherServiceSession::Handle_OperateFile
  97. (SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  98. ResourceWatcherService_OperateFile_Ans>::Pointer ctx)
  99. {
  100. LOG_FUNCTION();
  101. m_pEntity->OperateFile(ctx);
  102. }
  103. void ResourceWatcherServiceSession::Handle_ExtractEventLog(
  104. SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req, ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
  105. {
  106. LOG_FUNCTION();
  107. m_pEntity->RetrieveEventLog(ctx);
  108. }
  109. void ResourceWatcherServiceSession::Handle_UpdateDNS(SpReqAnsContext<ResourceWatcherService_UpdateDNS_Req, ResourceWatcherService_UpdateDNS_Ans>::Pointer ctx)
  110. {
  111. LOG_FUNCTION();
  112. m_pEntity->UpdateDNS(ctx);
  113. }
  114. void ResourceWatcherServiceSession::Handle_GetNetworkInfo(SpReqAnsContext<ResourceWatcherService_GetNetworkInfo_Req, ResourceWatcherService_GetNetworkInfo_Ans>::Pointer ctx)
  115. {
  116. LOG_FUNCTION();
  117. m_pEntity->GetNetworkInfo(ctx);
  118. }
  119. void ResourceWatcherServiceSession::Handle_GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
  120. {
  121. LOG_FUNCTION();
  122. m_pEntity->GetThirdPartyInstallState(ctx);
  123. }
  124. void ResourceWatcherServiceSession::Handle_InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  125. {
  126. LOG_FUNCTION();
  127. m_pEntity->InstallThirdPartyProgram(ctx);
  128. }
  129. void ResourceWatcherServiceSession::Handle_BizLinkDetect(SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
  130. {
  131. LOG_FUNCTION();
  132. m_pEntity->BizLinkDetect(ctx);
  133. }
  134. void ResourceWatcherServiceSession::Handle_CheckNetType(SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
  135. {
  136. LOG_FUNCTION();
  137. m_pEntity->CheckNetType(ctx);
  138. }
  139. void ResourceWatcherServiceSession::Handle_GetBizLinks(SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
  140. {
  141. LOG_FUNCTION();
  142. m_pEntity->GetBizLinks(ctx);
  143. }
  144. void ResourceWatcherServiceSession::Handle_GetTerminalVersionList(SpReqAnsContext<ResourceWatcherService_GetTerminalVersionList_Req, ResourceWatcherService_GetTerminalVersionList_Ans>::Pointer ctx)
  145. {
  146. LOG_FUNCTION();
  147. m_pEntity->GetTerminalVersionList(ctx);
  148. }
  149. void ResourceWatcherServiceSession::Handle_ManipulateVersion(SpReqAnsContext<ResourceWatcherService_ManipulateVersion_Req, ResourceWatcherService_ManipulateVersion_Ans>::Pointer ctx)
  150. {
  151. LOG_FUNCTION();
  152. m_pEntity->ManipulateVersion(ctx);
  153. }
  154. void ResourceWatcherServiceSession::Handle_UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
  155. {
  156. LOG_FUNCTION();
  157. m_pEntity->UninstallThirdPartyProgram(ctx);
  158. }
  159. void ResourceWatcherServiceSession::Handle_RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
  160. {
  161. LOG_FUNCTION();
  162. m_pEntity->RestartThirdPartyProgram(ctx);
  163. }
  164. void ResourceWatcherServiceSession::Handle_ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
  165. {
  166. LOG_FUNCTION();
  167. m_pEntity->ProcessDetectThirdPartyProgram(ctx);
  168. }
  169. void ResourceWatcherServiceSession::Handle_FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
  170. {
  171. LOG_FUNCTION();
  172. m_pEntity->FilesClean(ctx);
  173. }
  174. void ResourceWatcherEntity::UpdateDNS(SpReqAnsContext<ResourceWatcherService_UpdateDNS_Req, ResourceWatcherService_UpdateDNS_Ans>::Pointer ctx)
  175. {
  176. ctx->Answer(Error_NotImpl);
  177. }
  178. void ResourceWatcherEntity::GetNetworkInfo(SpReqAnsContext<ResourceWatcherService_GetNetworkInfo_Req, ResourceWatcherService_GetNetworkInfo_Ans>::Pointer ctx)
  179. {
  180. char buf[512];
  181. toolkit_interface_address_t* info;
  182. int count, i;
  183. toolkit_interface_addresses(&info, &count);
  184. i = count;
  185. Dbg("Number of interfaces: %d", count);
  186. if (count <= 0) {
  187. ctx->Answer(Error_NotExist);
  188. return;
  189. }
  190. int realCount = 0;
  191. while (i--) {
  192. toolkit_interface_address_t& interface = info[i];
  193. if (interface.address.address4.sin_family == AF_INET/* && !interface.is_internal*/) {
  194. realCount++;
  195. }
  196. }
  197. if (realCount <= 0) {
  198. ctx->Answer(Error_NotExist);
  199. return;
  200. }
  201. ctx->Ans.status = 0;
  202. ctx->Ans.current = "";
  203. ctx->Ans.ips.Init(realCount);
  204. ctx->Ans.names.Init(realCount);
  205. ctx->Ans.macs.Init(realCount);
  206. ctx->Ans.masks.Init(realCount);
  207. ctx->Ans.gateways.Init(realCount);
  208. ctx->Ans.dns.Init(realCount);
  209. int cnt = 0, active = -1;
  210. for (i = 0; i < count; ++i) {
  211. toolkit_interface_address_t& interface = info[i];
  212. if (interface.address.address4.sin_family == AF_INET) {
  213. ctx->Ans.names[cnt] = interface.name;
  214. toolkit_ip4_name(&interface.address.address4, buf, sizeof(buf));
  215. if (strcmp(buf, "127.0.0.1") != 0) active = cnt;
  216. ctx->Ans.ips[cnt] = buf;
  217. ctx->Ans.macs[cnt] = "";
  218. ctx->Ans.masks[cnt] = "";
  219. ctx->Ans.gateways[cnt] = "";
  220. ctx->Ans.dns[cnt] = "";
  221. cnt++;
  222. }
  223. }
  224. toolkit_free_interface_addresses(info, count);
  225. const char* parent = "/etc/NetworkManager/system-connections";
  226. array_header_t* subs;
  227. subs = fileutil_get_sub_files_a(parent);
  228. if (subs) {
  229. for (i = 0; i < subs->nelts; ++i) {
  230. char path[256] = { 0 };
  231. char* dir = ARRAY_IDX(subs, i, char*);
  232. char value[128];
  233. inifile_read_str_s("connection", "interface-name", "", value, 127, dir);
  234. if (strlen(value) == 0) continue;
  235. for (int j = 0; j < realCount; ++j) {
  236. if (ctx->Ans.names[j].Compare(value) == 0) {
  237. memset(value, 0, sizeof(value));
  238. inifile_read_str_s("connection", "id", "", value, 127, dir);
  239. if (strlen(value) > 0) {
  240. ctx->Ans.names[j] = CSimpleStringA::Format("%s#%s", value, ctx->Ans.names[j].GetData());
  241. }
  242. if (active == j) {
  243. ctx->Ans.current = ctx->Ans.names[j];
  244. }
  245. memset(value, 0, sizeof(value));
  246. inifile_read_str_s("ethernet", "mac-address", "", value, 127, dir);
  247. ctx->Ans.macs[j] = value;
  248. memset(value, 0, sizeof(value));
  249. inifile_read_str_s("ipv4", "dns", "", value, 127, dir);
  250. ctx->Ans.dns[j] = value;
  251. break;
  252. }
  253. }
  254. }
  255. toolkit_array_free2(subs);
  256. }
  257. ctx->Answer(Error_Succeed);
  258. }
  259. void ResourceWatcherEntity::GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
  260. {
  261. ErrorCodeEnum result(Error_Succeed);
  262. if (ctx->Req.mode == 1) {//查看搜狗输入法安装状态
  263. SogouInstallInfo info;
  264. info.state.dwInstalledStatus = Sogou_GetInstallStatus();
  265. info.state.strInstallDate = Sogou_GetInstallTime();
  266. info.program.strInstallDir = Sogou_GetInstallPath();
  267. info.program.strVersion = Sogou_GetVersion();
  268. const int maxTimes = 5;
  269. int curTimes = 0;
  270. while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
  271. Sleep(1200);
  272. info.program.strVersion = Sogou_GetVersion();
  273. curTimes++;
  274. }
  275. Dbg("%d, %s, %s, %s"
  276. , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
  277. , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
  278. Dbg("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
  279. ctx->Ans.status = info.IsInstalledSuccess() ? 1 : 0;
  280. ctx->Ans.reserverd1 = info.state.GetInstallTime().ToTimeString();
  281. ctx->Ans.path = info.program.strInstallDir;
  282. ctx->Ans.version = info.program.strVersion;
  283. } else if (ctx->Req.mode == 2) { //检测字体的安装状态
  284. CSimpleStringA strFontDir("/usr/share/fonts/truetype");
  285. CSimpleStringA strRVCTTFsDir(strFontDir + SPLIT_SLASH_STR + "RVCTTFs");
  286. if (!ExistsDirA(strRVCTTFsDir)) {
  287. ctx->Ans.status = 0;
  288. ctx->Ans.reserverd1 = CSimpleStringA::Format("%s 文件夹不存在", (LPCTSTR)strRVCTTFsDir);
  289. } else {
  290. CSimpleStringA ttf1 = strRVCTTFsDir + SPLIT_SLASH_STR + "HYQiHei-55S.ttf";
  291. CSimpleStringA ttf2 = strRVCTTFsDir + SPLIT_SLASH_STR + "HYQiHei-65S.ttf";
  292. CSimpleStringA ttfdir = strRVCTTFsDir + SPLIT_SLASH_STR + "fonts.dir";
  293. CSimpleStringA ttfscale = strRVCTTFsDir + SPLIT_SLASH_STR + "fonts.scale";
  294. CSimpleStringA ttfuuid = strRVCTTFsDir + SPLIT_SLASH_STR + ".uuid";
  295. int existCheck = 0;
  296. if (!ExistsFileA(ttf1)) {
  297. existCheck |= 1;
  298. }
  299. if (!ExistsFileA(ttf2)) {
  300. existCheck |= 2;
  301. }
  302. if (!ExistsFileA(ttfdir)) {
  303. existCheck |= 4;
  304. }
  305. if (!ExistsFileA(ttfscale)) {
  306. existCheck |= 8;
  307. }
  308. if (!ExistsFileA(ttfuuid)) {
  309. existCheck |= 16;
  310. }
  311. if (existCheck != 0) {
  312. ctx->Ans.status = 0;
  313. ctx->Ans.reserverd1 = CSimpleStringA::Format("安装文件不存在:0x%X", existCheck);
  314. } else {
  315. ctx->Ans.status = 1;
  316. ctx->Ans.reserverd1 = "";
  317. ctx->Ans.path = strRVCTTFsDir;
  318. ctx->Ans.version = "";
  319. }
  320. }
  321. } else {
  322. result = Error_NotSupport;
  323. }
  324. ctx->Answer(result);
  325. return;
  326. }
  327. ErrorCodeEnum SetFileExecutePriviledge(LPCTSTR lpcszDirOrFilePath)
  328. {
  329. ErrorCodeEnum result(Error_Succeed);
  330. if (ExistsDirA(lpcszDirOrFilePath)) {
  331. do
  332. {
  333. array_header_t* subs;
  334. subs = fileutil_get_sub_dirs_a(lpcszDirOrFilePath);
  335. if (subs) {
  336. for (int i = 0; i < subs->nelts; ++i) {
  337. char* dir = ARRAY_IDX(subs, i, char*);
  338. const char* dirname = &dir[strlen(lpcszDirOrFilePath) + 1];
  339. ErrorCodeEnum tmpResult = SetFileExecutePriviledge(dir);
  340. if (tmpResult != Error_Succeed) {
  341. toolkit_array_free2(subs);
  342. return tmpResult;
  343. }
  344. }
  345. }
  346. } while (false);
  347. do {
  348. array_header_t* subs;
  349. subs = fileutil_get_sub_files_a(lpcszDirOrFilePath);
  350. if (subs) {
  351. for (int i = 0; i < subs->nelts; ++i) {
  352. char* path = ARRAY_IDX(subs, i, char*);
  353. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  354. if (chmod(path, f_attrib) != 0) {
  355. Dbg("chmod file priviledge failed, %s, %d", path, errno);
  356. toolkit_array_free2(subs);
  357. return Error_Unexpect;
  358. }
  359. }
  360. toolkit_array_free2(subs);
  361. }
  362. } while (false);
  363. } else if(ExistsFileA(lpcszDirOrFilePath)) {
  364. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  365. if (chmod(lpcszDirOrFilePath, f_attrib) != 0) {
  366. Dbg("chmod file priviledge failed, %s, %d", lpcszDirOrFilePath, errno);
  367. return Error_Unexpect;
  368. }
  369. } else {
  370. result = Error_InvalidState;
  371. }
  372. return result;
  373. }
  374. ErrorCodeEnum ResourceWatcherEntity::GetUnzipTempDir(CSimpleStringA& strUnzipDir)
  375. {
  376. CSimpleStringA strDownloadsPath;
  377. auto rc = GetFunction()->GetPath("Downloads", strDownloadsPath);
  378. assert(rc == Error_Succeed);
  379. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strDownloadsPath, strUnzipDir);
  380. if (strUnzipDir.IsEndWith(".zip") || strUnzipDir.IsEndWith(".cab"))
  381. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  382. return Error_Succeed;
  383. }
  384. ErrorCodeEnum ResourceWatcherEntity::UnzipPack(const char* unZipPackName)
  385. {
  386. CSimpleStringA strDownloadsPath;
  387. auto rc = GetFunction()->GetPath("Downloads", strDownloadsPath);
  388. assert(rc == Error_Succeed);
  389. CSimpleStringA strTempPath;
  390. CSmartPointer<IEntityFunction> spFunction2 = GetFunction();
  391. ErrorCodeEnum rc2 = spFunction2->GetPath("Temp", strTempPath);
  392. assert(rc2 == Error_Succeed);
  393. CSimpleStringA strUnzipPath;
  394. strUnzipPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strTempPath.GetData(), unZipPackName);
  395. if (strUnzipPath.IsEndWith(".zip") || strUnzipPath.IsEndWith(".cab"))
  396. {
  397. strUnzipPath = strUnzipPath.SubString(0, strUnzipPath.GetLength() - 4);
  398. }
  399. // 如目标目录存在,则先删除
  400. if (ExistsDirA(strUnzipPath))
  401. {
  402. if (!RemoveDirRecursiveA(strUnzipPath)) {
  403. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("remove old unzip dir [%s] fail", strUnzipPath.GetData()));
  404. return Error_NotExist;
  405. }
  406. }
  407. // 创建临时解压目录
  408. CreateDirA(strUnzipPath.GetData(), false);
  409. // 解压
  410. CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  411. string zipFileStr = strZipFile.GetData();
  412. string zipTempDir = strUnzipPath.GetData();
  413. if (!ExistsFileA(strZipFile.GetData()))
  414. {
  415. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("pack [%s] not exists", unZipPackName));
  416. return Error_NotExist;
  417. }
  418. if (UnZipToDir(zipFileStr, zipTempDir) != 0)
  419. {
  420. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("unzip pack [%s] fail", unZipPackName));
  421. return Error_NotExist;
  422. }
  423. return Error_Succeed;
  424. }
  425. void ResourceWatcherEntity::InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  426. {
  427. ErrorCodeEnum result(Error_Succeed);
  428. ErrorCodeEnum tmpResult(Error_Succeed);
  429. CSimpleStringA tmpMsg(true);
  430. bool sogouInstalled = false;
  431. if (ctx->Req.type == 1) {//安装搜狗输入法
  432. bool zipFind = false;
  433. time_t newestWrite = 0;
  434. CSimpleStringA newSogouPath(true);
  435. CSimpleStringA strDownloadDirPath(true);
  436. GetFunction()->GetPath("Downloads", strDownloadDirPath);
  437. CSimpleStringA strTempDirPath(true);
  438. GetFunction()->GetPath("Temp", strTempDirPath);
  439. if (strDownloadDirPath.IsNullOrEmpty()) {
  440. tmpResult = Error_Unexpect;
  441. tmpMsg = CSimpleStringA::Format("搜狗安装包目录[Downloads]不存在!");
  442. }
  443. else
  444. {
  445. DIR* dp;
  446. struct dirent* dirp;
  447. if ((dp = opendir(strDownloadDirPath.GetData())) != NULL)
  448. {
  449. while ((dirp = readdir(dp)) != NULL)
  450. {
  451. CSimpleStringA tmpName(dirp->d_name);
  452. struct stat buf;
  453. int ret = 0;
  454. memset(&buf, 0x00, sizeof(buf));
  455. ret = stat(CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadDirPath.GetData(), dirp->d_name).GetData(), &buf);
  456. if (tmpName.IsStartWith("uos-sogou", true) && tmpName.IsEndWith(".zip", true) && buf.st_mtim.tv_sec > newestWrite)
  457. {
  458. if (ret != 0)
  459. {
  460. Dbg("获取文件[%s]状态信息出错。\n", tmpName.GetData());
  461. }
  462. else
  463. {
  464. newestWrite = buf.st_mtim.tv_sec;
  465. newSogouPath = CSimpleStringA(tmpName.GetData());
  466. zipFind = true;
  467. }
  468. }
  469. }
  470. if(!zipFind)
  471. {
  472. tmpResult = Error_NotExist;
  473. tmpMsg = CSimpleStringA::Format("在路径[%s]下未找到搜狗安装包!", strDownloadDirPath.GetData());
  474. }
  475. }
  476. else
  477. {
  478. tmpResult = Error_NotExist;
  479. tmpMsg = CSimpleStringA::Format("打开[Downloads]目录失败!");
  480. }
  481. }
  482. CSimpleStringA strInstallPkgPath;
  483. if (zipFind)
  484. {
  485. if (UnzipPack(newSogouPath.GetData()) != Error_Succeed)
  486. {
  487. tmpResult = Error_Unexpect;
  488. tmpMsg = CSimpleStringA::Format("解压搜狗安装包失败!");
  489. }
  490. else
  491. {
  492. newSogouPath = newSogouPath.SubString(0, newSogouPath.GetLength() - 4);
  493. strInstallPkgPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",
  494. strTempDirPath.GetData(), newSogouPath.GetData());
  495. }
  496. }
  497. else
  498. {
  499. tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
  500. if (tmpResult != 0) {
  501. tmpMsg = tmpMsg + CSimpleStringA::Format(" 指定位置[%s]找不到输入法安装包", strInstallPkgPath.GetData());
  502. }
  503. }
  504. Dbg("to install sogou input...");
  505. const bool doNotStartup(true); //安装后是否启动搜狗输入法服务,据搜狗反馈,不能通过root权限启动Sogou输入法
  506. if(tmpResult == Error_Succeed)
  507. {
  508. tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
  509. if (tmpResult != Error_Succeed) {
  510. tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
  511. tmpResult = Error_NotExist;
  512. }
  513. else {
  514. CSimpleStringA strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
  515. if (ExistsFileA(strRunIniFilePath)) {
  516. char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
  517. CSimpleStringA strInstallScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + p);
  518. toolkit_free(p);
  519. Dbg("install script file: %s", strInstallScriptFile.GetData());
  520. if (ExistsFileA(strInstallScriptFile)) {
  521. char app[MAX_PATH] = { '\0' };
  522. sprintf(app, "bash %s", strInstallScriptFile.GetData());
  523. tmpResult = RunShellScript(app);
  524. if (tmpResult != 0) {
  525. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  526. }
  527. else if (!doNotStartup) {
  528. CSimpleStringA strStartupScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + "startup_service.sh");
  529. Dbg("startup script file: %s", strStartupScriptFile.GetData());
  530. if (!ExistsFileA(strStartupScriptFile)) {
  531. tmpMsg = CSimpleStringA::Format("%s 启动脚本文件不存在,请重启设备再次验证", strStartupScriptFile.GetData());
  532. tmpResult = Error_NotExist;
  533. }
  534. else {
  535. Sleep(1000);
  536. do {
  537. char app[MAX_PATH] = { '\0' };
  538. tk_process_t* process = NULL;
  539. tk_process_option_t option;
  540. option.exit_cb = NULL;
  541. option.file = NULL;
  542. option.flags = 0;
  543. #if 0
  544. auto users = GetUserNameList(true);
  545. if (users.size() == 1) {
  546. sprintf(app, "su -m -p -c \"bash %s\" %s", strStartupScriptFile.GetData(), users[0].c_str());
  547. }
  548. else {
  549. for (auto it = users.cbegin(); it != users.cend(); ++it) {
  550. Dbg("user:%s", it->c_str());
  551. }
  552. sprintf(app, "bash %s", strStartupScriptFile.GetData());
  553. }
  554. #else
  555. sprintf(app, "bash %s", strStartupScriptFile.GetData());
  556. #endif
  557. option.params = app;
  558. const int res = process_spawn(&option, &process);
  559. if (0 == res) {
  560. FREE(process);
  561. Dbg("execute {%s} suc", app);
  562. }
  563. else {
  564. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败:%s", app, toolkit_strerror(res));
  565. tmpResult = Error_Process;
  566. }
  567. } while (false);
  568. }
  569. }
  570. }
  571. else {
  572. tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
  573. tmpResult = Error_NotExist;
  574. }
  575. }
  576. else {
  577. tmpMsg = CSimpleStringA::Format("%s 文件不存在,请检查安装包完整性", strRunIniFilePath.GetData());
  578. tmpResult = Error_NotExist;
  579. }
  580. }
  581. }
  582. if (tmpResult == Error_Succeed) {
  583. Sleep(1500);
  584. const CSimpleStringA strResultLogFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "result.log";
  585. do
  586. {
  587. const int maxTimes = 5;
  588. int curTimes = 0;
  589. while (!ExistsFileA(strResultLogFilePath) && curTimes < maxTimes) {
  590. Sleep(1500);
  591. curTimes++;
  592. }
  593. } while (false);
  594. if (!ExistsFileA(strResultLogFilePath)) {
  595. tmpResult = Error_NotExist;
  596. tmpMsg = CSimpleStringA::Format("安装成功标志文件不存在!");
  597. }
  598. else {
  599. FILE* pResultLog = fopen(strResultLogFilePath, "r");
  600. if (pResultLog == NULL) {
  601. tmpResult = Error_IO;
  602. tmpMsg = CSimpleStringA::Format("打开安装成功标志文件失败!%s", strerror(errno));
  603. }
  604. else {
  605. char szTmp[1024] = { '\0' };
  606. int nRead = fread(szTmp, 1, sizeof(szTmp), pResultLog);
  607. int installResult(-1);
  608. char installMsg[256] = { '\0' };
  609. sscanf(szTmp, "result=%d&msg=%s", &installResult, installMsg);
  610. fclose(pResultLog);
  611. if (installResult != 0) {
  612. tmpResult = Error_Unexpect;
  613. tmpMsg = CSimpleStringA::Format("%s", szTmp);
  614. }
  615. else {
  616. SogouInstallInfo info;
  617. info.state.dwInstalledStatus = Sogou_GetInstallStatus();
  618. info.state.strInstallDate = Sogou_GetInstallTime();
  619. info.program.strInstallDir = Sogou_GetInstallPath();
  620. info.program.strVersion = Sogou_GetVersion();
  621. const int maxTimes = 5;
  622. int curTimes = 0;
  623. while (!doNotStartup && info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
  624. Sleep(1200);
  625. info.program.strVersion = Sogou_GetVersion();
  626. curTimes++;
  627. }
  628. Dbg("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
  629. Dbg("%d, %s, %s, %s"
  630. , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
  631. , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
  632. if (!info.IsInstalledSuccess()) {
  633. tmpResult = Error_FailVerify;
  634. tmpMsg = CSimpleStringA::Format("检测安装状态失败!");
  635. }
  636. else {
  637. ctx->Ans.path = info.program.strInstallDir;
  638. ctx->Ans.reserverd1 = info.program.strVersion;
  639. ctx->Ans.reserverd2 = info.state.GetInstallTime().ToTimeString();
  640. tmpMsg = tmpMsg + CSimpleStringA::Format(" 从[%s]安装搜狗输入法成功,设备即将重启。", strInstallPkgPath.GetData());
  641. sogouInstalled = true;
  642. }
  643. }
  644. }
  645. }
  646. }
  647. } else if (ctx->Req.type == 2) {//安装花了钱的字体
  648. Dbg("to install cmb font input...%d", m_bInitMode);
  649. CSimpleStringA strAdDataDirPath(true);
  650. tmpResult = GetFunction()->GetPath("Ad", strAdDataDirPath);
  651. if (strAdDataDirPath.IsNullOrEmpty() && m_bInitMode) {
  652. strAdDataDirPath = "/opt/rvc/adData";
  653. }
  654. if (strAdDataDirPath.IsNullOrEmpty()) {
  655. tmpResult = Error_Unexpect;
  656. tmpMsg = "获取安装包路径Ad失败";
  657. } else {
  658. CSimpleStringA strInstallPkgPath = strAdDataDirPath + SPLIT_SLASH_STR "HYQiHei";
  659. if (!ExistsDirA(strInstallPkgPath)) {
  660. tmpMsg = CSimpleStringA::Format("%s 文件夹不存在", strInstallPkgPath.GetData());
  661. tmpResult = Error_NotExist;
  662. } else {
  663. CSimpleStringA strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
  664. if (ExistsFileA(strRunIniFilePath)) {
  665. char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
  666. CSimpleStringA strInstallScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + p);
  667. toolkit_free(p);
  668. Dbg("RunScript file: %s", strInstallScriptFile.GetData());
  669. if (ExistsFileA(strInstallScriptFile)) {
  670. do {
  671. char app[MAX_PATH] = { '\0' };
  672. tk_process_t* process = NULL;
  673. tk_process_option_t option;
  674. option.exit_cb = NULL;
  675. option.file = NULL;
  676. option.flags = 0;
  677. sprintf(app, "bash %s", strInstallScriptFile.GetData());
  678. option.params = app;
  679. const int res = process_spawn(&option, &process);
  680. if (0 == res) {
  681. FREE(process);
  682. Dbg("execute {%s} suc", strInstallScriptFile.GetData());
  683. } else {
  684. tmpMsg = CSimpleStringA::Format("执行 %s 失败:%s", strInstallScriptFile.GetData(), toolkit_strerror(res));
  685. tmpResult = Error_Process;
  686. }
  687. } while (false);
  688. } else {
  689. tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
  690. tmpResult = Error_NotExist;
  691. }
  692. } else {
  693. tmpMsg = CSimpleStringA::Format("%s 文件不存在", strRunIniFilePath.GetData());
  694. tmpResult = Error_NotExist;
  695. }
  696. }
  697. }
  698. if (tmpResult == Error_Succeed) {
  699. ///**TODO(Gifur@10/21/2021): 二次校验 */
  700. }
  701. } else {
  702. result = Error_NotSupport;
  703. }
  704. ctx->Ans.result = tmpResult;
  705. ctx->Ans.msg = tmpMsg;
  706. ctx->Answer(result);
  707. if (sogouInstalled)
  708. {
  709. HealthManagerService_ClientBase* m_pRWClient = new HealthManagerService_ClientBase(this);
  710. ErrorCodeEnum eErr = m_pRWClient->Connect();
  711. if (eErr != Error_Succeed) {
  712. Dbg("HealthManager connected failed.");
  713. m_pRWClient->SafeDelete();
  714. m_pRWClient = NULL;
  715. }
  716. else
  717. {
  718. HealthManagerService_ControlTerminalLife_Req detReq;
  719. HealthManagerService_ControlTerminalLife_Ans detAns;
  720. detReq.cmdType = 4;
  721. detReq.reason = 0;
  722. eErr = m_pRWClient->ControlTerminalLife(detReq, detAns, 3000);
  723. if (eErr == Error_Succeed)
  724. {
  725. // 系统重启事件
  726. LogWarn(Severity_Middle, Error_Succeed, Event_Req_OS_Restart, "搜狗安装成功, 设备即将重启。");
  727. }
  728. else
  729. {
  730. LogWarn(Severity_Middle, Error_Unexpect, 0, "调用健康实体重启设备失败!");
  731. }
  732. }
  733. }
  734. return;
  735. }
  736. void ResourceWatcherEntity::GetTerminalVersionList(SpReqAnsContext<ResourceWatcherService_GetTerminalVersionList_Req, ResourceWatcherService_GetTerminalVersionList_Ans>::Pointer ctx)
  737. {
  738. CSimpleStringA strVersionBaseDir(true);
  739. GetFunction()->GetPath("RootVer", strVersionBaseDir);
  740. const CSimpleStringA strActiveFile = strVersionBaseDir + SPLIT_SLASH_STR + "active.txt";
  741. CSystemStaticInfo staticInfo;
  742. GetFunction()->GetSystemStaticInfo(staticInfo);
  743. CSimpleStringA strCurrVer = staticInfo.InstallVersion.ToString();
  744. Dbg("get current version [%s]", (LPCTSTR)strCurrVer);
  745. std::vector<std::string> verlist;
  746. array_header_t* arr;
  747. arr = fileutil_get_sub_dirs_a(strVersionBaseDir);
  748. if (arr) {
  749. do {
  750. regex_t reg;
  751. CSimpleStringA strPattern("^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+[\(\)A-Za-z_-]*$");
  752. int ret = regcomp(&reg, strPattern, REG_EXTENDED | REG_NOSUB);
  753. if (ret) {
  754. char ebuff[256];
  755. regerror(ret, &reg, ebuff, 256);
  756. Dbg("regex failed: %s", ebuff);
  757. ctx->Ans.msg = CSimpleStringA::Format("内部错误:REGEX %s", ebuff);
  758. ctx->Ans.current = -1;
  759. break;
  760. } else {
  761. for (int i = 0; i < arr->nelts; ++i) {
  762. char* versionDir = ARRAY_IDX(arr, i, char*);
  763. char* versionDirName = &versionDir[strVersionBaseDir.GetLength() + 1];
  764. ret = regexec(&reg, versionDirName, 0, NULL, 0);
  765. if (0 == ret) {
  766. Dbg("filename %s matched!", versionDirName);
  767. verlist.push_back(std::string(versionDirName));
  768. }
  769. }
  770. }
  771. } while (false);
  772. toolkit_array_free2(arr);
  773. }
  774. if (!verlist.empty()) {
  775. const int count = verlist.size();
  776. ctx->Ans.index.Init(count);
  777. ctx->Ans.version.Init(count);
  778. ctx->Ans.remark.Init(count);
  779. ctx->Ans.type.Init(count);
  780. ctx->Ans.status.Init(count);
  781. for (int i = 0; i < count; ++i) {
  782. ctx->Ans.index[i] = i;
  783. ctx->Ans.version[i] = verlist[i].c_str();
  784. if (verlist[i].compare(strCurrVer.GetData()) == 0) {
  785. ctx->Ans.current = i;
  786. }
  787. ctx->Ans.remark[i] = "";
  788. ctx->Ans.type[i] = ctx->Ans.status[i] = 0;
  789. }
  790. }
  791. ctx->Answer(Error_Succeed);
  792. }
  793. namespace
  794. {
  795. bool UpdateCurrentVersionName(LPCTSTR filePath, LPCTSTR versionStr, LPCTSTR backupPath)
  796. {
  797. if (fileutil_copy_file(backupPath, filePath) != 0) {
  798. return false;
  799. }
  800. FILE* fp = fopen(filePath, "wb+");
  801. if (fp == NULL) {
  802. return false;
  803. }
  804. bool result(false);
  805. do
  806. {
  807. int ret = fwrite(versionStr, strlen(versionStr), 1, fp);
  808. if (ret != 1) {
  809. Dbg("fwrite failed: %d", ret);
  810. break;
  811. }
  812. fflush(fp);
  813. fclose(fp);
  814. fp = fopen(filePath, "rb");
  815. if (fp != NULL) {
  816. char value[32] = { 0 };
  817. int ret2 = fread(value, strlen(versionStr), 1, fp);
  818. if (ret2 == 1) {
  819. if (strcmp(value, versionStr) == 0)
  820. Dbg("read agagin the value is the same!");
  821. else {
  822. break;
  823. }
  824. }
  825. }
  826. result = true;
  827. } while (false);
  828. fclose(fp);
  829. if (!result && backupPath) {
  830. fileutil_copy_file(filePath, backupPath);
  831. fileutil_delete_file(backupPath);
  832. }
  833. if (result && backupPath) {
  834. fileutil_delete_file(backupPath);
  835. }
  836. return result;
  837. }
  838. }
  839. void ResourceWatcherEntity::ManipulateVersion(SpReqAnsContext<ResourceWatcherService_ManipulateVersion_Req, ResourceWatcherService_ManipulateVersion_Ans>::Pointer ctx)
  840. {
  841. ErrorCodeEnum result(Error_Succeed);
  842. int tmpResult(0);
  843. CSimpleStringA tmpMsg(true);
  844. switch (ctx->Req.operation) {
  845. case 1: //设置为此版本为当前版本
  846. {
  847. CSimpleStringA strVersionBaseDir(true);
  848. GetFunction()->GetPath("RootVer", strVersionBaseDir);
  849. const CSimpleStringA strActiveFile = strVersionBaseDir + SPLIT_SLASH_STR + "active.txt";
  850. const CSimpleStringA strActiveFileBackup = strActiveFile + "activebak.txt";
  851. CSystemStaticInfo staticInfo;
  852. GetFunction()->GetSystemStaticInfo(staticInfo);
  853. CSimpleStringA strCurrVer = staticInfo.InstallVersion.ToString();
  854. Dbg("get current version [%s]", (LPCTSTR)strCurrVer);
  855. if (!UpdateCurrentVersionName(strActiveFile, ctx->Req.value, strActiveFileBackup)) {
  856. tmpResult = Error_Unexpect;
  857. tmpMsg = "切换版本失败";
  858. } else {
  859. LogWarn(Severity_Low, Error_IO, LOG_RESOURCEWATCHE_CHANGE_CURRENT_VERSION,
  860. CSimpleStringA::Format("changed version from %s to %s", strCurrVer.GetData(), ctx->Req.value.GetData()));
  861. }
  862. }
  863. break;
  864. case 2: //删除此版本
  865. {
  866. CSimpleStringA strVersionBaseDir(true);
  867. GetFunction()->GetPath("RootVer", strVersionBaseDir);
  868. const CSimpleStringA strVersionDirPath = strVersionBaseDir + SPLIT_SLASH_STR + ctx->Req.value;
  869. if (ExistsDirA(strVersionDirPath)) {
  870. if (!RemoveDirRecursiveA(strVersionDirPath)) {
  871. tmpResult = Error_Unexpect;
  872. tmpMsg = "删除版本失败";
  873. } else {
  874. LogWarn(Severity_Low, Error_IO, LOG_RESOURCEWATCHE_DELETE_VERSION,
  875. CSimpleStringA::Format("delete version %s", ctx->Req.value.GetData()));
  876. }
  877. }
  878. }
  879. break;
  880. default:
  881. result = Error_NotSupport;
  882. break;
  883. }
  884. ctx->Ans.result = tmpResult;
  885. ctx->Ans.msg = tmpMsg;
  886. ctx->Answer(result);
  887. }
  888. void ResourceWatcherEntity::UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
  889. {
  890. ErrorCodeEnum result(Error_Succeed);
  891. ErrorCodeEnum tmpResult(Error_Succeed);
  892. CSimpleStringA tmpMsg(true);
  893. if (ctx->Req.type == 1) {
  894. Dbg("to uninstall sogou input...");
  895. CSimpleStringA strInstallPkgPath;
  896. tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
  897. if (tmpResult == Error_Succeed) {
  898. do
  899. {
  900. tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
  901. if (tmpResult != Error_Succeed) {
  902. tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
  903. tmpResult = Error_NoPrivilege;
  904. break;
  905. }
  906. const CSimpleStringA strShutdownScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "shutdown_service.sh";
  907. const CSimpleStringA strUninstallScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "uninstall_sogouime.sh";
  908. if (!ExistsFileA(strShutdownScriptFile)) {
  909. tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strShutdownScriptFile.GetData());
  910. tmpResult = Error_InvalidState;
  911. break;
  912. }
  913. if (!ExistsFileA(strUninstallScriptFile)) {
  914. tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strUninstallScriptFile.GetData());
  915. tmpResult = Error_InvalidState;
  916. break;
  917. }
  918. char app[MAX_PATH] = { '\0' };
  919. sprintf(app, "bash %s", strShutdownScriptFile.GetData());
  920. tmpResult = RunShellScript(app);
  921. if (tmpResult != 0) {
  922. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  923. } else {
  924. Sleep(300);
  925. sprintf(app, "bash %s", strUninstallScriptFile.GetData());
  926. tmpResult = RunShellScript(app);
  927. if (tmpResult != 0) {
  928. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  929. } else {
  930. Sleep(100);
  931. }
  932. }
  933. } while (false);
  934. }
  935. } else {
  936. result = Error_NotSupport;
  937. }
  938. ctx->Ans.result = tmpResult;
  939. ctx->Ans.msg = tmpMsg;
  940. ctx->Answer(result);
  941. return;
  942. }
  943. void ResourceWatcherEntity::RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
  944. {
  945. ErrorCodeEnum result(Error_Succeed);
  946. ErrorCodeEnum tmpResult(Error_Succeed);
  947. CSimpleStringA tmpMsg(true);
  948. if (ctx->Req.type == 1)
  949. {//重启搜狗输入法
  950. static int old_process_id[2] = { -1, -1 };
  951. char* relate_processes[2] = { "sogouImeWebSrv", "sogouImeService" };
  952. int count = 3;
  953. alive_process_info processes[3];
  954. memset(processes, 0, sizeof(processes));
  955. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
  956. CAutoArray<CSimpleStringA> msgs(array_size(relate_processes));
  957. int cnt(0);
  958. for (int i = 0; i < array_size(relate_processes); ++i)
  959. {
  960. int k = -1;
  961. for (int j = 0; j < count; ++j) {
  962. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  963. k = j;
  964. break;
  965. }
  966. }
  967. if (k != -1)
  968. {
  969. cnt++;
  970. old_process_id[k] = processes[k].pid;
  971. std::string sucContent, failedContent;
  972. CSimpleStringA strCmd = CSimpleStringA::Format("kill -9 %d", old_process_id[k]);
  973. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  974. Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  975. }
  976. }
  977. if (cnt > 0)
  978. {
  979. Sleep(2000);
  980. int newCount = 3;
  981. int notSame = 0;
  982. vector<CSimpleStringA> tKillmsg;
  983. alive_process_info newProcesses[3];
  984. memset(newProcesses, 0, sizeof(newProcesses));
  985. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &newCount, newProcesses);
  986. for (int i = 0; i < array_size(relate_processes); ++i)
  987. {
  988. int k = -1;
  989. for (int j = 0; j < count; ++j) {
  990. if (strcmp(newProcesses[j].name, relate_processes[i]) == 0) {
  991. k = j;
  992. break;
  993. }
  994. }
  995. if (k != -1)
  996. {
  997. if (newProcesses[k].pid != old_process_id[k])
  998. {
  999. notSame++;
  1000. }
  1001. else
  1002. {
  1003. tmpResult = Error_Unexpect;
  1004. CSimpleStringA tmsg = CSimpleStringA::Format("{杀死当前搜狗进程[%s]失败,pid[%d]。}",
  1005. newProcesses[k].name, newProcesses[k].pid);
  1006. tKillmsg.push_back(tmsg);
  1007. }
  1008. }
  1009. }
  1010. if (tKillmsg.size() != 0)
  1011. {
  1012. for (int i = 0; i < tKillmsg.size(); ++i)
  1013. {
  1014. tmpMsg += tKillmsg[i];
  1015. }
  1016. }
  1017. else
  1018. {
  1019. tmpMsg = "已成功重启搜狗输入法进程。";
  1020. }
  1021. }
  1022. else
  1023. {
  1024. tmpMsg = "当前系统无搜狗进程,请确认已安装搜狗输入法,并重启计算机以尝试启动搜狗输入法!";
  1025. tmpResult = Error_Unexpect;
  1026. }
  1027. }
  1028. else
  1029. {
  1030. tmpResult = Error_NotSupport;
  1031. tmpMsg = CSimpleStringA::Format("接口调用参数错误。");
  1032. }
  1033. ctx->Ans.result = tmpResult;
  1034. ctx->Ans.msg = tmpMsg;
  1035. ctx->Answer(result);
  1036. return;
  1037. }
  1038. void ResourceWatcherEntity::ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
  1039. {
  1040. ErrorCodeEnum result(Error_Succeed);
  1041. ErrorCodeEnum tmpResult(Error_Succeed);
  1042. CSimpleStringA tmpMsg(true);
  1043. std::string res("");
  1044. if (ctx->Req.type == 1) {//检测搜狗输入法进程
  1045. CAutoArray<CSimpleStringA> pName(2);
  1046. pName[0] = "sogouImeWebSrv";
  1047. pName[1] = "sogouImeService";
  1048. res = DoCheckCertainProcessStatus(pName);
  1049. if (res.length() == 0)
  1050. {
  1051. tmpResult = Error_Failed;
  1052. tmpMsg = "Can't find Sogou Process.";
  1053. }
  1054. else
  1055. {
  1056. tmpMsg = CSimpleStringA::Format("%s", res.c_str());
  1057. }
  1058. }
  1059. ctx->Ans.result = tmpResult;
  1060. ctx->Ans.msg = tmpMsg;
  1061. ctx->Answer(result);
  1062. return;
  1063. }
  1064. #if defined(RVC_OS_WIN)
  1065. //1: 32bit process running at 64bit platform
  1066. //0:
  1067. static int Is32R64Platform()
  1068. {
  1069. static int isWow64 = -1;
  1070. typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  1071. if (isWow64 == -1) {
  1072. BOOL bIsWow64 = FALSE;
  1073. LPFN_ISWOW64PROCESS fnIsWow64Process =
  1074. (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  1075. if (NULL != fnIsWow64Process) {
  1076. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
  1077. Dbg("detect is running with 64bit or not failed: %u", GetLastError());
  1078. return -1;
  1079. } else {
  1080. isWow64 = bIsWow64 ? 1 : 0;
  1081. }
  1082. }
  1083. }
  1084. return isWow64;
  1085. }
  1086. static bool GetRegistValue(HKEY hKey, LPCTSTR lpcszParam,
  1087. DWORD* pDwValue, CHAR* pSzValue, const DWORD* pDwSizeOfSz)
  1088. {
  1089. if (pDwValue != NULL) {
  1090. DWORD dwType = REG_DWORD;
  1091. DWORD dwValue = 0;
  1092. DWORD dwSize = sizeof(DWORD);
  1093. LONG lResult = RegQueryValueExA(hKey, lpcszParam, NULL, &dwType, (LPBYTE)&dwValue, &dwSize);
  1094. if (lResult == ERROR_SUCCESS) {
  1095. Dbg("Value of \"%s\": %d", lpcszParam, dwValue);
  1096. *pDwValue = dwValue;
  1097. return true;
  1098. } else {
  1099. Dbg("RegQueryValueEx for \"%s\" error, result=%ld.", lpcszParam, lResult);
  1100. return false;
  1101. }
  1102. } else if (pSzValue != NULL) {
  1103. DWORD dwType = REG_SZ;
  1104. DWORD dwSize = MAX_PATH * sizeof(CHAR);
  1105. TCHAR szValue[MAX_PATH + 1] = { 0 };
  1106. LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, &dwSize);
  1107. if (lResult == ERROR_SUCCESS) {
  1108. Dbg("Value of \"%s\": %s", lpcszParam, szValue);
  1109. strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
  1110. return true;
  1111. } else {
  1112. Dbg("RegQueryValueEx for \"InstallTime\" error, result=%ld.", lResult);
  1113. return false;
  1114. }
  1115. }
  1116. Dbg("invalid param for \"%s\"", lpcszParam);
  1117. return false;
  1118. }
  1119. static LONG GetSogouInstallState(SogouInstallStateInfo& info)
  1120. {
  1121. HKEY hKey;
  1122. LONG lResult = -1;
  1123. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  1124. lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\SogouPCIme", 0, dwFlag, &hKey);
  1125. if (lResult == ERROR_SUCCESS) {
  1126. DWORD dwValue = (DWORD)-1;
  1127. const bool res1 = GetRegistValue(hKey, "InstallFlag", &dwValue, NULL, NULL);
  1128. if (res1) {
  1129. info.dwInstalledStatus = dwValue;
  1130. }
  1131. TCHAR szValue[MAX_PATH + 1] = { 0 };
  1132. DWORD dwLength = MAX_PATH;
  1133. //1970 0x83AA7E80
  1134. const bool res2 = GetRegistValue(hKey, "InstallTime", NULL, szValue, &dwLength);
  1135. if (res2) {
  1136. info.strInstallDate = szValue;
  1137. Dbg("InstallTime: %s", info.GetInstallTime().ToTimeString().GetData());
  1138. }
  1139. if (res1 && res2) {
  1140. lResult = 0;
  1141. } else {
  1142. lResult = -1;
  1143. }
  1144. } else {
  1145. Dbg("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
  1146. }
  1147. RegCloseKey(hKey);
  1148. return lResult;
  1149. }
  1150. static LONG GetSogouExecuteInfo(SogouRunVersionInfo& info, BOOL f32bit = TRUE)
  1151. {
  1152. HKEY hKey;
  1153. LONG lResult = -1;
  1154. PVOID oldValue = NULL;
  1155. Wow64DisableWow64FsRedirection(&oldValue);
  1156. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  1157. lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  1158. f32bit ? "SOFTWARE\\SogouPCIme" : "SOFTWARE\\WOW6432Node\\SogouPCIme", 0, dwFlag, &hKey);
  1159. if (lResult == ERROR_SUCCESS) {
  1160. TCHAR szVersion[MAX_PATH + 1] = { 0 }, szDefault[MAX_PATH + 1] = { 0 };
  1161. DWORD dwLength = MAX_PATH;
  1162. const bool res1 = GetRegistValue(hKey, "Version", NULL, szVersion, &dwLength);
  1163. if (res1) info.strVersion = szVersion;
  1164. const bool res2 = GetRegistValue(hKey, "", NULL, szDefault, &dwLength);
  1165. if (res2) info.strInstallDir = szDefault;
  1166. if (res1 && res2) {
  1167. lResult = 0;
  1168. } else {
  1169. lResult = -1;
  1170. }
  1171. } else {
  1172. Dbg("%s::RegOpenKeyEx(32bit=%d) error, Result=%ld.", __FUNCTION__, f32bit, lResult);
  1173. }
  1174. RegCloseKey(hKey);
  1175. Wow64RevertWow64FsRedirection(oldValue);
  1176. return lResult;
  1177. }
  1178. #endif //RVC_OS_WIN
  1179. ErrorCodeEnum ResourceWatcherEntity::DoCheckInstallStateJob()
  1180. {
  1181. LOG_FUNCTION();
  1182. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  1183. CSmartPointer<IConfigInfo> spConfig;
  1184. ErrorCodeEnum err = spFunction->OpenConfig(Config_Run, spConfig);
  1185. BOOL fNeedAlarm = TRUE;
  1186. SogouInstallInfo info;
  1187. #if defined(RVC_OS_WIN)
  1188. GetSogouInstallState(info.state);
  1189. BOOL is32Bit = Is64BitPlatform() ? FALSE : TRUE;
  1190. if (ERROR_FILE_NOT_FOUND == GetSogouExecuteInfo(info.program, is32Bit))
  1191. GetSogouExecuteInfo(info.program, !is32Bit);
  1192. #else
  1193. info.state.dwInstalledStatus = Sogou_GetInstallStatus();
  1194. info.state.strInstallDate = Sogou_GetInstallTime();
  1195. info.program.strInstallDir = Sogou_GetInstallPath();
  1196. info.program.strVersion = Sogou_GetVersion();
  1197. /** 重试获取版本号 [Gifur@2022224]*/
  1198. const int maxTimes = 3;
  1199. int curTimes = 0;
  1200. while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
  1201. Sleep(1500);
  1202. info.program.strVersion = Sogou_GetVersion();
  1203. curTimes++;
  1204. }
  1205. Dbg("%d, %s, %s, %s"
  1206. , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
  1207. , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
  1208. Dbg("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
  1209. #endif //RVC_OS_WIN
  1210. CSimpleStringA strLastRecord(true);
  1211. err = spConfig->ReadConfigValue("SogouInput", "LastInstalledRecord", strLastRecord);
  1212. if (strLastRecord.IsNullOrEmpty() || info.Stringfy().Compare(strLastRecord) != 0) {
  1213. spConfig->WriteConfigValue("SogouInput", "LastInstalledRecord", info.Stringfy());
  1214. fNeedAlarm = TRUE;
  1215. } else {
  1216. //Report info per day.
  1217. int nLastRecordTime = 0;
  1218. err = spConfig->ReadConfigValueInt("SogouInput", "LastReportTime", nLastRecordTime);
  1219. SYSTEMTIME stTaskTime = CSmallDateTime(nLastRecordTime).ToSystemTime();
  1220. Dbg("Last Sogou install check time: %04d-%02d-%02d %02d:%02d:%02d",
  1221. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  1222. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  1223. SYSTEMTIME stNow = {};
  1224. GetLocalTime(&stNow);
  1225. if (nLastRecordTime > 0 && stTaskTime.wYear == stNow.wYear
  1226. && stTaskTime.wMonth == stNow.wMonth && stTaskTime.wDay == stNow.wDay) {
  1227. //The Same Day
  1228. fNeedAlarm = FALSE;
  1229. } else {
  1230. fNeedAlarm = TRUE;
  1231. }
  1232. }
  1233. if (fNeedAlarm) {
  1234. const DWORD dwUserCode = info.IsInstalledSuccess() ? LOG_ERR_SOGOU_INPUT_INSTALLED : LOG_ERR_SOGOU_INPUT_NOTINSTALLED;
  1235. LogWarn(Severity_Middle, Error_DataCheck, dwUserCode, info.Stringfy());
  1236. spConfig->WriteConfigValue("SogouInput", "LastReportTime",
  1237. CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  1238. } else {
  1239. Dbg("Do not Report.");
  1240. }
  1241. return Error_Succeed;
  1242. }
  1243. void ResourceWatcherEntity::DoCheckSogouProcessStatus()
  1244. {
  1245. static int old_process_id[2] = { -1, -1 };
  1246. char* relate_processes[2] = {"sogouImeWebSrv", "sogouImeService"};
  1247. int count = 3;
  1248. alive_process_info processes[3];
  1249. memset(processes, 0, sizeof(processes));
  1250. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
  1251. CAutoArray<CSimpleStringA> msgs(array_size(relate_processes));
  1252. int cnt(0);
  1253. for (int i = 0; i < array_size(relate_processes); ++i) {
  1254. int k = -1;
  1255. for (int j = 0; j < count; ++j) {
  1256. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  1257. k = j;
  1258. break;
  1259. }
  1260. }
  1261. if (k != -1 && old_process_id[i] == -1) {
  1262. old_process_id[i] = processes[k].pid;
  1263. } else if (k != -1 && (processes[k].pid != old_process_id[i])) {
  1264. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1265. , relate_processes[i], old_process_id[i], processes[k].pid);
  1266. old_process_id[i] = processes[k].pid;
  1267. } else if(k == -1 && old_process_id[i] != 0) {
  1268. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1269. , relate_processes[i], old_process_id[i], 0);
  1270. old_process_id[i] = 0;
  1271. }
  1272. }
  1273. if (cnt > 0) {
  1274. std::string uploadInfo("");
  1275. if (cnt > 1) {
  1276. uploadInfo = "{";
  1277. }
  1278. for (int i = 0; i < cnt; ++i) {
  1279. if (i != 0) {
  1280. uploadInfo += ",";
  1281. }
  1282. uploadInfo += msgs[i].GetData();
  1283. }
  1284. if (cnt > 1) {
  1285. uploadInfo += "}";
  1286. }
  1287. LogWarn(Severity_Middle, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, uploadInfo.c_str());
  1288. }
  1289. }
  1290. //# all available outputs
  1291. //OUTPUTS = $(xrandr | awk '$2 ~ /connected/ {print $1}')
  1292. //echo outputs : $OUTPUTS
  1293. //# get info from xrandr
  1294. //XRANDR = `xrandr`
  1295. //
  1296. //connectedOutputs = $(echo "$XRANDR" | grep " connected" | sed - e "s/\([A-Z0-9]\+\) connected.*/\1/")
  1297. //activeOutput = $(echo "$XRANDR" | grep - e " connected [^(]" | sed - e "s/\([A-Z0-9]\+\) connected.*/\1/")
  1298. //connected = $(echo $connectedOutputs | wc - w)
  1299. //echo connectedOutputs : ${ connectedOutputs }
  1300. //echo activeOutput : ${ activeOutput }
  1301. //echo connected : ${ connected }
  1302. ErrorCodeEnum ResourceWatcherEntity::ConfigMonitorSetting(const UOS::MonitorInfo& config)
  1303. {
  1304. ErrorCodeEnum result(Error_Succeed);
  1305. CSimpleStringA strExecute("xrandr");
  1306. //Get monitor info
  1307. do {
  1308. std::string sucContent, failedContent;
  1309. CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
  1310. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  1311. Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  1312. } while (false);
  1313. do {
  1314. std::string sucContent, failedContent;
  1315. CSimpleStringA strCmd("xrandr |awk '$2 ~ /connected/ {print $1}'");
  1316. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  1317. Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  1318. } while (false);
  1319. CSimpleStringA strCmd(strExecute);
  1320. if (!config.name.empty()) {
  1321. strCmd += CSimpleStringA::Format(" --output %s", config.name.c_str());
  1322. //Set resolution
  1323. if (config.nResolutionX != 0 && config.nResolutionY != 0) {
  1324. CSimpleStringA tmp = CSimpleStringA::Format(" --mode %dx%d", config.nResolutionX, config.nResolutionY);
  1325. strCmd += tmp;
  1326. }
  1327. if (config.refreshRate != 0) {
  1328. CSimpleStringA tmp = CSimpleStringA::Format(" --rate %d", config.refreshRate);
  1329. strCmd += tmp;
  1330. }
  1331. //set primary
  1332. if (config.isPrimary) {
  1333. strCmd += " --primary";
  1334. } else if (config.posDirecttion != -1 && !config.other.empty()) {
  1335. CSimpleStringA posDir(true);
  1336. switch (config.posDirecttion) {
  1337. case 0:
  1338. posDir = "--same-as";
  1339. case 1:
  1340. posDir = "--above";
  1341. break;
  1342. case 2:
  1343. posDir = "--right-of";
  1344. break;
  1345. case 3:
  1346. posDir = "--above";
  1347. break;
  1348. case 4:
  1349. posDir = "--left-of";
  1350. break;
  1351. default:
  1352. result = Error_Param;
  1353. break;
  1354. }
  1355. if (result == Error_Succeed) {
  1356. CSimpleStringA tmp = CSimpleStringA::Format(" %s %s", posDir.GetData(), config.other.c_str());
  1357. strCmd += tmp;
  1358. }
  1359. }
  1360. }
  1361. do
  1362. {
  1363. std::string sucContent, failedContent;
  1364. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  1365. Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  1366. } while (false);
  1367. do {
  1368. std::string sucContent, failedContent;
  1369. strCmd = strExecute;
  1370. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  1371. Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  1372. } while (false);
  1373. return result;
  1374. }
  1375. std::vector<std::string> ResourceWatcherEntity::GetUserNameList(bool bExcludeRoot)
  1376. {
  1377. std::vector<std::string> results;
  1378. array_header_t* arr;
  1379. arr = fileutil_get_sub_dirs_a("/home");
  1380. if (arr) {
  1381. int i;
  1382. for (i = 0; i < arr->nelts; ++i) {
  1383. char szDestSubDir[256] = { 0 };
  1384. char* dir = ARRAY_IDX(arr, i, char*);
  1385. Dbg("sub dir: %s", dir);
  1386. strcpy(szDestSubDir, dir);
  1387. strcat(szDestSubDir, SPLIT_SLASH_STR);
  1388. strcat(szDestSubDir, ".config/kwinrc");
  1389. if (ExistsFileA(szDestSubDir)) {
  1390. std::string strUserName((const char*)&dir[strlen("/home/")]);
  1391. Dbg("username:%s", strUserName.c_str());
  1392. if (strUserName.compare("root") != 0 || !bExcludeRoot) {
  1393. results.push_back(strUserName);
  1394. }
  1395. }
  1396. }
  1397. toolkit_array_free2(arr);
  1398. }
  1399. return results;
  1400. }
  1401. ErrorCodeEnum ResourceWatcherEntity::GetSogouPkgDirPath(CSimpleStringA& strPkgPath)
  1402. {
  1403. CSimpleStringA strAdDataDirPath(true);
  1404. CSimpleStringA strInstallPkgPath(true);
  1405. ErrorCodeEnum result = GetFunction()->GetPath("Ad", strAdDataDirPath);
  1406. if (strAdDataDirPath.IsNullOrEmpty() && m_bInitMode) {
  1407. strAdDataDirPath = "/opt/rvc/adData";
  1408. }
  1409. if (strAdDataDirPath.IsNullOrEmpty()) {
  1410. return Error_Unexpect;
  1411. }
  1412. array_header_t* subs;
  1413. subs = fileutil_get_sub_dirs_a(strAdDataDirPath);
  1414. if (subs) {
  1415. for (int i = 0; i < subs->nelts; ++i) {
  1416. char* dir = ARRAY_IDX(subs, i, char*);
  1417. const char* dirname = &dir[strAdDataDirPath.GetLength() + 1];
  1418. if (CSimpleStringA(dirname).IsStartWith("sogou", true)) {
  1419. if (strInstallPkgPath.IsNullOrEmpty()) {
  1420. Dbg("found it: %s", dir);
  1421. strInstallPkgPath = dir;
  1422. } else if (strInstallPkgPath.Compare(dir) < 0) {
  1423. Dbg("replace %s with %s", (LPCTSTR)strInstallPkgPath, dir);
  1424. strInstallPkgPath = dir;
  1425. }
  1426. }
  1427. }
  1428. toolkit_array_free2(subs);
  1429. }
  1430. if (strInstallPkgPath.IsNullOrEmpty()) {
  1431. return Error_NotExist;
  1432. }
  1433. strPkgPath = strInstallPkgPath;
  1434. return Error_Succeed;
  1435. }
  1436. ErrorCodeEnum ResourceWatcherEntity::RunShellScript(LPCTSTR cmdline)
  1437. {
  1438. char app[MAX_PATH] = { '\0' };
  1439. tk_process_t* process = NULL;
  1440. tk_process_option_t option;
  1441. option.exit_cb = NULL;
  1442. option.file = NULL;
  1443. option.flags = 0;
  1444. option.params = (char*)cmdline;
  1445. const int res = process_spawn(&option, &process);
  1446. if (0 == res) {
  1447. Dbg("execute {%s}, pid: %d", cmdline, process->pid);
  1448. FREE(process);
  1449. return Error_Succeed;
  1450. } else {
  1451. Dbg("execute {%s} failed: %d", cmdline, res);
  1452. return Error_Unexpect;
  1453. }
  1454. }
  1455. void ResourceWatcherEntity::OnSysVarEvent(const char* pszKey, const char* pszValue, const char* pszOldValue, const char* pszEntityName)
  1456. {
  1457. Dbg("OnSysVarEvent pszKey = %s, pszValue = %s", pszKey, pszValue);
  1458. if ((_strnicmp(pszKey, "UIState", strlen("UIState")) == 0)) {
  1459. if (_strnicmp(pszValue, "M", strlen("M")) == 0) {
  1460. ClearVersionTask* task = new ClearVersionTask(&m_fsm);
  1461. GetFunction()->PostThreadPoolTask(task);
  1462. }
  1463. }
  1464. }
  1465. }
  1466. std::string ResourceWatcherEntity::DoCheckCertainProcessStatus(const CAutoArray<CSimpleStringA>& pName)
  1467. {
  1468. int pSize = pName.GetCount();
  1469. /*static int old_process_id[pSize];
  1470. memset(old_process_id, -1, sizeof(old_process_id));*/
  1471. vector<int> old_process_id;
  1472. CAutoArray<CSimpleStringA> msgs;
  1473. alive_process_info* processes = new alive_process_info[pSize];
  1474. char** relate_processes = new char* [pSize];
  1475. int count = pSize;
  1476. for (int i = 0; i < pSize; ++i)
  1477. {
  1478. old_process_id.push_back(-1);
  1479. CSimpleStringA temp("");
  1480. msgs.Append(&temp, 0, 1);
  1481. relate_processes[i] = const_cast<char*>(pName[i].GetData());
  1482. Dbg("relate_process name: %s.", relate_processes[i]);
  1483. }
  1484. Dbg("COUNT = %d!", count);
  1485. osutil_detect_unique_app(relate_processes, pSize, &count, processes);
  1486. int cnt(0);
  1487. for (int i = 0; i < pSize; ++i) {
  1488. int k = -1;
  1489. for (int j = 0; j < count; ++j) {
  1490. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  1491. k = j;
  1492. break;
  1493. }
  1494. }
  1495. if (k != -1 && old_process_id[i] == -1) {
  1496. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
  1497. , relate_processes[i], processes[k].pid);
  1498. old_process_id[i] = processes[k].pid;
  1499. }
  1500. else if (k != -1 && (processes[k].pid != old_process_id[i])) {
  1501. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1502. , relate_processes[i], old_process_id[i], processes[k].pid);
  1503. old_process_id[i] = processes[k].pid;
  1504. }
  1505. else if (k == -1 && old_process_id[i] != 0) {
  1506. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1507. , relate_processes[i], old_process_id[i], 0);
  1508. old_process_id[i] = 0;
  1509. }
  1510. }
  1511. std::string uploadInfo("");
  1512. if (cnt > 0) {
  1513. if (cnt > 1) {
  1514. uploadInfo = "{";
  1515. }
  1516. for (int i = 0; i < cnt; ++i) {
  1517. if (i != 0) {
  1518. uploadInfo += ",";
  1519. }
  1520. uploadInfo += msgs[i].GetData();
  1521. }
  1522. if (cnt > 1) {
  1523. uploadInfo += "}";
  1524. }
  1525. }
  1526. return uploadInfo;
  1527. void ResourceWatcherEntity::FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
  1528. {
  1529. ErrorCodeEnum result(Error_Succeed);
  1530. ErrorCodeEnum tmpResult(Error_Succeed);
  1531. CSimpleStringA tmpMsg(true);
  1532. if (ctx->Req.type == 1)//清理浏览器缓存
  1533. {
  1534. BrowserCacheClean browserCacheClean;
  1535. browserCacheClean.needClean = 1;
  1536. SpSendBroadcast(GetFunction(),
  1537. SP_MSG_OF(BrowserCacheClean), SP_MSG_SIG_OF(BrowserCacheClean), browserCacheClean);
  1538. tmpMsg = "已发送重启命令";
  1539. }
  1540. else
  1541. {
  1542. tmpResult = Error_NotExist;
  1543. tmpMsg = "非法的调用参数";
  1544. }
  1545. ctx->Ans.result = tmpResult;
  1546. ctx->Ans.msg = tmpMsg;
  1547. ctx->Answer(result);
  1548. }
  1549. SP_BEGIN_ENTITY_MAP()
  1550. SP_ENTITY(ResourceWatcherEntity)
  1551. SP_END_ENTITY_MAP()