mod_ResourceWatcher.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  1. #include "stdafx.h"
  2. #if defined(_MSC_VER)
  3. #include <shellapi.h>
  4. #include <shlobj.h>
  5. #include <wintrust.h>
  6. #include <direct.h>
  7. #include <Mscat.h>
  8. #include <Softpub.h>
  9. #include <windows.h>
  10. #include <tlhelp32.h>
  11. #include "XUnzip.h" //解压文件
  12. #include <io.h>
  13. #include <direct.h>
  14. #include <psapi.h>
  15. #include <sys/stat.h>
  16. #else
  17. #include "SogouVersion.h"
  18. #include <winpr/sysinfo.h>
  19. #include <sys/wait.h>
  20. #include <errno.h>
  21. #include "XUnZipZilb.h"
  22. #include <regex.h>
  23. #endif //_MSC_VER
  24. #include "array.h"
  25. #include "fileutil.h"
  26. #include "iniutil.h"
  27. #include "toolkit.h"
  28. #include "osutil.h"
  29. #include "publicFunExport.h"
  30. #include <map>
  31. #include "SpUtility.h"
  32. #include <time.h>
  33. #include "HealthManager_client_g.h"
  34. #include "CommEntityUtil.hpp"
  35. #include "mod_ResourceWatcher.h"
  36. #include "ResourceWatcher_UserCode.h"
  37. using namespace HealthManager;
  38. void ResourceWatcherServiceSession::Handle_GetDevInfo(
  39. SpReqAnsContext<ResourceWatcherService_GetDevInfo_Req, ResourceWatcherService_GetDevInfo_Ans>::Pointer ctx)
  40. {
  41. DbgToBeidou(ctx->link, __FUNCTION__)();
  42. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(ResourceWatcherService_LogCode_GetDevInfo).setAPI(__FUNCTION__)(__FUNCTION__);
  43. m_pEntity->GetDevInfo(ctx);
  44. }
  45. void ResourceWatcherServiceSession::Handle_BizLinkDetect(SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
  46. {
  47. DbgToBeidou(ctx->link, __FUNCTION__)();
  48. m_pEntity->BizLinkDetect(ctx);
  49. }
  50. void ResourceWatcherServiceSession::Handle_CheckNetType(SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
  51. {
  52. DbgToBeidou(ctx->link, __FUNCTION__)();
  53. m_pEntity->CheckNetType(ctx);
  54. }
  55. void ResourceWatcherServiceSession::Handle_GetBizLinks(SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
  56. {
  57. DbgToBeidou(ctx->link, __FUNCTION__)();
  58. m_pEntity->GetBizLinks(ctx);
  59. }
  60. void ResourceWatcherServiceSession::Handle_InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  61. {
  62. DbgToBeidou(ctx->link, __FUNCTION__)();
  63. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(ResourceWatcherService_LogCode_InstallThirdPartyProgram).setAPI(__FUNCTION__)(__FUNCTION__);
  64. m_pEntity->InstallThirdPartyProgram(ctx);
  65. }
  66. void ResourceWatcherServiceSession::Handle_FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
  67. {
  68. DbgToBeidou(ctx->link, __FUNCTION__)();
  69. m_pEntity->FilesClean(ctx);
  70. }
  71. void ResourceWatcherServiceSession::Handle_FetchSystemSnapshot(SpReqAnsContext<ResourceWatcherService_FetchSystemSnapshot_Req, ResourceWatcherService_FetchSystemSnapshot_Ans>::Pointer ctx)
  72. {
  73. DbgToBeidou(ctx->link, __FUNCTION__)();
  74. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(ResourceWatcherService_LogCode_FetchSystemSnapshot).setAPI(__FUNCTION__)(__FUNCTION__);
  75. m_pEntity->FetchSystemSnapshot(ctx);
  76. }
  77. void ResourceWatcherServiceSession::Handle_CheckIsFileExists(SpReqAnsContext<ResourceWatcherService_CheckIsFileExists_Req, ResourceWatcherService_CheckIsFileExists_Ans>::Pointer ctx)
  78. {
  79. DbgToBeidou(ctx->link, __FUNCTION__)();
  80. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(ResourceWatcherService_LogCode_CheckIsFileExists).setAPI(__FUNCTION__)(__FUNCTION__);
  81. m_pEntity->CheckIsFileExists(ctx);
  82. }
  83. void ResourceWatcherServiceSession::Handle_OperateFile
  84. (SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  85. ResourceWatcherService_OperateFile_Ans>::Pointer ctx)
  86. {
  87. DbgToBeidou(ctx->link, __FUNCTION__)();
  88. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(ResourceWatcherService_LogCode_OperateFile).setAPI(__FUNCTION__)(__FUNCTION__);
  89. m_pEntity->OperateFile(ctx);
  90. }
  91. struct SogouRunVersionInfo
  92. {
  93. CSimpleStringA strInstallDir;
  94. CSimpleStringA strVersion;
  95. SogouRunVersionInfo() :strInstallDir(true), strVersion(true) {}
  96. CSimpleStringA ToString() const
  97. {
  98. CSimpleStringA result(true);
  99. if (!strInstallDir.IsNullOrEmpty()) {
  100. result += strInstallDir;
  101. result += "#";
  102. }
  103. if (!strVersion.IsNullOrEmpty()) {
  104. result += strVersion;
  105. }
  106. return result;
  107. }
  108. CVersion ConvertVersion()
  109. {
  110. CVersion installVer;
  111. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  112. int n = sscanf(strVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  113. if (n != 4) {
  114. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not sogou version.[%s]", strVersion.GetData());
  115. }
  116. else {
  117. installVer = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
  118. }
  119. return installVer;
  120. }
  121. //TODO: CrossPlaform [Gifur@2025730]
  122. //true: 普通调用版本输入法,false: SDK版本输入法
  123. bool IsTSFVersion()
  124. {
  125. #if defined(_MSC_VER)
  126. CVersion standardVer = CVersion(2, 6, 1, 1967); //对比版本为2.6.1.1967
  127. #else
  128. CVersion standardVer = CVersion(2, 6, 4, 355); //对比版本为2.4.6.355
  129. #endif //_MSC_VER
  130. return (ConvertVersion() >= standardVer);
  131. }
  132. };
  133. struct SogouInstallStateInfo
  134. {
  135. DWORD dwInstalledStatus;
  136. CSimpleStringA strInstallDate;
  137. SogouInstallStateInfo() :dwInstalledStatus(-1), strInstallDate(true) {}
  138. CSimpleStringA ToString() const
  139. {
  140. CSimpleStringA result(true);
  141. if (!strInstallDate.IsNullOrEmpty()) {
  142. result += GetInstallTime().ToTimeString().GetData();
  143. result += "#";
  144. }
  145. result += CSimpleStringA::Format("%u", dwInstalledStatus);
  146. return result;
  147. }
  148. CSmallDateTime GetInstallTime() const
  149. {
  150. if (!strInstallDate.IsNullOrEmpty()) {
  151. DWORD dwSecsSince1970(0);
  152. sscanf_s(strInstallDate.GetData(), "%u", &dwSecsSince1970);
  153. dwSecsSince1970 -= 946656000; // 2000-1970
  154. return CSmallDateTime(dwSecsSince1970);
  155. }
  156. return CSmallDateTime::BeginTime;
  157. }
  158. };
  159. struct SogouInstallInfo
  160. {
  161. SogouInstallStateInfo state;
  162. SogouRunVersionInfo program;
  163. CSimpleStringA Stringfy() const
  164. {
  165. return (state.ToString() + "||" + program.ToString());
  166. }
  167. bool IsInstalledSuccess() const
  168. {
  169. return (state.dwInstalledStatus == 0);
  170. }
  171. };
  172. #if defined(RVC_OS_LINUX)
  173. std::string TryToGetSogouVersionEx()
  174. {
  175. std::string succStr, errStr;
  176. std::string runStr("cat /opt/sogouimebs/files/share/sogou-version");
  177. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  178. if (succStr.empty()) {
  179. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cat sogou version return empty!");
  180. }
  181. else {
  182. return succStr;
  183. }
  184. }
  185. else {
  186. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("execute cmd failed: %s", errStr.c_str());
  187. }
  188. return "";
  189. }
  190. #else
  191. static inline bool Is64BitPlatform()
  192. {
  193. SYSTEM_INFO si;
  194. GetNativeSystemInfo(&si);
  195. return (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64
  196. || si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64);
  197. }
  198. //TODO: CrossPlaform [Gifur@2025729]
  199. static int Is32R64Platform()
  200. {
  201. static int isWow64 = -1;
  202. typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  203. if (isWow64 == -1) {
  204. BOOL bIsWow64 = FALSE;
  205. LPFN_ISWOW64PROCESS fnIsWow64Process =
  206. (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  207. if (NULL != fnIsWow64Process) {
  208. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
  209. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("detect is running with 64bit or not failed: %u", GetLastError());
  210. return -1;
  211. }
  212. else {
  213. isWow64 = bIsWow64 ? 1 : 0;
  214. }
  215. }
  216. }
  217. return isWow64;
  218. }
  219. static bool GetRegistValue(HKEY hKey, LPCTSTR lpcszParam, DWORD* pDwValue, CHAR* pSzValue, const DWORD* pDwSizeOfSz)
  220. {
  221. if (pDwValue != NULL) {
  222. DWORD dwType = REG_DWORD;
  223. DWORD dwValue = 0;
  224. DWORD dwSize = sizeof(DWORD);
  225. LONG lResult = RegQueryValueExA(hKey, lpcszParam, NULL, &dwType, (LPBYTE)&dwValue, &dwSize);
  226. if (lResult == ERROR_SUCCESS) {
  227. *pDwValue = dwValue;
  228. return true;
  229. }
  230. else {
  231. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"%s\" error, result=%ld.", lpcszParam, lResult);
  232. return false;
  233. }
  234. }
  235. else if (pSzValue != NULL) {
  236. DWORD dwType = REG_SZ;
  237. DWORD dwSize = MAX_PATH * sizeof(CHAR);
  238. TCHAR szValue[MAX_PATH + 1] = { 0 };
  239. LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, &dwSize);
  240. if (lResult == ERROR_SUCCESS) {
  241. strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
  242. return true;
  243. }
  244. else {
  245. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"InstallTime\" error, result=%ld.", lResult);
  246. return false;
  247. }
  248. }
  249. return false;
  250. }
  251. static LONG GetSogouInstallState(SogouInstallStateInfo& info)
  252. {
  253. HKEY hKey;
  254. LONG lResult = -1;
  255. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  256. lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\SogouPCIme", 0, dwFlag, &hKey);
  257. if (lResult == ERROR_SUCCESS) {
  258. DWORD dwValue = (DWORD)-1;
  259. const bool res1 = GetRegistValue(hKey, "InstallFlag", &dwValue, NULL, NULL);
  260. if (res1) {
  261. info.dwInstalledStatus = dwValue;
  262. }
  263. TCHAR szValue[MAX_PATH + 1] = { 0 };
  264. DWORD dwLength = MAX_PATH;
  265. //1970 0x83AA7E80
  266. const bool res2 = GetRegistValue(hKey, "InstallTime", NULL, szValue, &dwLength);
  267. if (res2) {
  268. info.strInstallDate = szValue;
  269. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("InstallTime: %s", info.GetInstallTime().ToTimeString().GetData());
  270. }
  271. if (res1 && res2) {
  272. lResult = 0;
  273. }
  274. else {
  275. lResult = -1;
  276. }
  277. }
  278. else {
  279. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
  280. }
  281. RegCloseKey(hKey);
  282. return lResult;
  283. }
  284. static LONG GetSogouExecuteInfo(SogouRunVersionInfo& info, BOOL f32bit = TRUE)
  285. {
  286. HKEY hKey;
  287. LONG lResult = -1;
  288. PVOID oldValue = NULL;
  289. Wow64DisableWow64FsRedirection(&oldValue);
  290. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  291. lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, f32bit ? "SOFTWARE\\SogouPCIme" : "SOFTWARE\\WOW6432Node\\SogouPCIme", 0, dwFlag, &hKey);
  292. if (lResult == ERROR_SUCCESS) {
  293. TCHAR szVersion[MAX_PATH + 1] = { 0 }, szDefault[MAX_PATH + 1] = { 0 };
  294. DWORD dwLength = MAX_PATH;
  295. const bool res1 = GetRegistValue(hKey, "Version", NULL, szVersion, &dwLength);
  296. if (res1) info.strVersion = szVersion;
  297. const bool res2 = GetRegistValue(hKey, "", NULL, szDefault, &dwLength);
  298. if (res2) info.strInstallDir = szDefault;
  299. if (res1 && res2) {
  300. lResult = 0;
  301. }
  302. else {
  303. lResult = -1;
  304. }
  305. }
  306. else {
  307. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx(32bit=%d) error, Result=%ld.", __FUNCTION__, f32bit, lResult);
  308. }
  309. RegCloseKey(hKey);
  310. Wow64RevertWow64FsRedirection(oldValue);
  311. return lResult;
  312. }
  313. #endif //RVC_OS_LINUX
  314. ErrorCodeEnum GetSogouInstallInfo(SogouInstallInfo& info)
  315. {
  316. #if defined(RVC_OS_LINUX)
  317. info.state.dwInstalledStatus = Sogou_GetInstallStatus();
  318. info.state.strInstallDate = Sogou_GetInstallTime();
  319. info.program.strInstallDir = Sogou_GetInstallPath();
  320. info.program.strVersion = Sogou_GetVersion();
  321. if (info.program.strVersion.IsNullOrEmpty()) {
  322. info.program.strVersion = TryToGetSogouVersionEx().c_str();
  323. }
  324. const int maxTimes = 3;
  325. int curTimes = 0;
  326. while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
  327. Sleep(1000);
  328. info.program.strVersion = Sogou_GetVersion();
  329. if (info.program.strVersion.IsNullOrEmpty()) {
  330. info.program.strVersion = TryToGetSogouVersionEx().c_str();
  331. }
  332. curTimes++;
  333. }
  334. #else
  335. GetSogouInstallState(info.state);
  336. BOOL is32Bit = Is64BitPlatform() ? FALSE : TRUE;
  337. if (ERROR_FILE_NOT_FOUND == GetSogouExecuteInfo(info.program, is32Bit))
  338. GetSogouExecuteInfo(info.program, !is32Bit);
  339. #endif //RVC_OS_LINUX
  340. return info.IsInstalledSuccess() ? Error_Succeed : Error_InvalidState;
  341. }
  342. ErrorCodeEnum SetFileExecutePriviledge(LPCTSTR lpcszDirOrFilePath)
  343. {
  344. #if defined(RVC_OS_WIN)
  345. ErrorCodeEnum result(Error_NotSupport);
  346. #else
  347. ErrorCodeEnum result(Error_Succeed);
  348. if (ExistsDirA(lpcszDirOrFilePath)) {
  349. do {
  350. array_header_t* subs;
  351. subs = fileutil_get_sub_dirs_a(lpcszDirOrFilePath);
  352. if (subs) {
  353. for (int i = 0; i < subs->nelts; ++i) {
  354. char* dir = ARRAY_IDX(subs, i, char*);
  355. const char* dirname = &dir[strlen(lpcszDirOrFilePath) + 1];
  356. ErrorCodeEnum tmpResult = SetFileExecutePriviledge(dir);
  357. if (tmpResult != Error_Succeed) {
  358. toolkit_array_free2(subs);
  359. return tmpResult;
  360. }
  361. }
  362. }
  363. } while (false);
  364. do {
  365. array_header_t* subs;
  366. subs = fileutil_get_sub_files_a(lpcszDirOrFilePath);
  367. if (subs) {
  368. for (int i = 0; i < subs->nelts; ++i) {
  369. char* path = ARRAY_IDX(subs, i, char*);
  370. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  371. if (chmod(path, f_attrib) != 0) {
  372. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("chmod file priviledge failed, %s, %d", path, errno);
  373. toolkit_array_free2(subs);
  374. return Error_Unexpect;
  375. }
  376. }
  377. toolkit_array_free2(subs);
  378. }
  379. } while (false);
  380. }
  381. else if (ExistsFileA(lpcszDirOrFilePath)) {
  382. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  383. if (chmod(lpcszDirOrFilePath, f_attrib) != 0) {
  384. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("chmod file priviledge failed, %s, %d", lpcszDirOrFilePath, errno);
  385. return Error_Unexpect;
  386. }
  387. }
  388. else {
  389. result = Error_InvalidState;
  390. }
  391. #endif //RVC_OS_WIN
  392. return result;
  393. }
  394. //TODO: CrossPlaform [Gifur@2025730]
  395. static int IsFileExists(const char* pfilename)
  396. {
  397. int iRet = -1;
  398. #ifdef RVC_OS_WIN
  399. if (ExistsFileA(pfilename)) {
  400. iRet = 0;
  401. }
  402. else {
  403. iRet = GetLastError();
  404. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("find file(%s) last error code is %d.", pfilename, iRet);
  405. }
  406. #else
  407. struct stat statbuf;
  408. if (0 == stat(pfilename, &statbuf)) {
  409. iRet = 0;
  410. }
  411. else {
  412. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("find file(%s) errno info is %s.", pfilename, strerror(errno));
  413. iRet = errno;
  414. }
  415. #endif // RVC_OS_WIN
  416. return iRet;
  417. }
  418. void ResourceWatcherEntity::InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  419. {
  420. ErrorCodeEnum result(Error_Succeed);
  421. ErrorCodeEnum tmpResult(Error_Succeed);
  422. CSimpleStringA tmpMsg(true);
  423. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2);
  424. 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));
  425. bool sogouInstalled = false;
  426. const bool doTryRestart = (ctx->Req.reserved1 != 1);
  427. if (ctx->Req.type == 1)
  428. {
  429. //安装搜狗输入法
  430. CSmartPointer<InstallSogouTask> sogouInstall = new InstallSogouTask(this);
  431. sogouInstall->ctx = ctx;
  432. GetFunction()->PostThreadPoolTask(sogouInstall.GetRawPointer());
  433. return;
  434. }
  435. else if (ctx->Req.type == 2) {//安装花了钱的字体
  436. //TODO: 移除 [Gifur@2025730]
  437. #if defined(RVC_OS_WIN)
  438. tmpResult = Error_NotSupport;
  439. #else
  440. CSimpleStringA strAdDataDirPath(true);
  441. tmpResult = GetFunction()->GetPath("Ad", strAdDataDirPath);
  442. if (strAdDataDirPath.IsNullOrEmpty()) {
  443. strAdDataDirPath = "/opt/rvc/adData";
  444. }
  445. if (strAdDataDirPath.IsNullOrEmpty()) {
  446. tmpResult = Error_Unexpect;
  447. tmpMsg = "获取安装包路径Ad失败";
  448. }
  449. else {
  450. CSimpleStringA strInstallPkgPath = strAdDataDirPath + SPLIT_SLASH_STR "HYQiHei";
  451. if (!ExistsDirA(strInstallPkgPath)) {
  452. tmpMsg = CSimpleStringA::Format("%s 文件夹不存在", strInstallPkgPath.GetData());
  453. tmpResult = Error_NotExist;
  454. }
  455. else {
  456. CSimpleStringA strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
  457. if (ExistsFileA(strRunIniFilePath)) {
  458. char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
  459. CSimpleStringA strInstallScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + p);
  460. toolkit_free(p);
  461. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RunScript file: %s", strInstallScriptFile.GetData());
  462. if (ExistsFileA(strInstallScriptFile)) {
  463. do {
  464. char app[MAX_PATH] = { '\0' };
  465. tk_process_t* process = NULL;
  466. tk_process_option_t option;
  467. option.exit_cb = NULL;
  468. option.file = NULL;
  469. option.flags = 0;
  470. sprintf(app, "bash %s", strInstallScriptFile.GetData());
  471. option.params = app;
  472. const int res = process_spawn(&option, &process);
  473. if (0 == res) {
  474. FREE(process);
  475. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("execute {%s} suc", strInstallScriptFile.GetData());
  476. }
  477. else {
  478. tmpMsg = CSimpleStringA::Format("执行 %s 失败:%s", strInstallScriptFile.GetData(), toolkit_strerror(res));
  479. tmpResult = Error_Process;
  480. }
  481. } while (false);
  482. }
  483. else {
  484. tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
  485. tmpResult = Error_NotExist;
  486. }
  487. }
  488. else {
  489. tmpMsg = CSimpleStringA::Format("%s 文件不存在", strRunIniFilePath.GetData());
  490. tmpResult = Error_NotExist;
  491. }
  492. }
  493. }
  494. if (tmpResult == Error_Succeed) {
  495. ///**TODO(Gifur@10/21/2021): 二次校验 */
  496. }
  497. #endif //RVC_OS_WIN
  498. }
  499. else {
  500. result = Error_NotSupport;
  501. }
  502. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM) ("用户桌面安装:%s. result:%d.", tmpMsg.GetData(), tmpResult);
  503. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_INSTALL_THIRDPARTY,
  504. CSimpleStringA::Format("用户桌面安装:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  505. ctx->Ans.result = tmpResult;
  506. ctx->Ans.msg = tmpMsg;
  507. ctx->Answer(result);
  508. return;
  509. }
  510. ErrorCodeEnum ResourceWatcherEntity::ReportSogouInstallState()
  511. {
  512. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  513. CSmartPointer<IConfigInfo> spConfig;
  514. ErrorCodeEnum err = spFunction->OpenConfig(Config_Run, spConfig);
  515. BOOL fNeedAlarm = TRUE;
  516. SogouInstallInfo info;
  517. GetSogouInstallInfo(info);
  518. CSimpleStringA strLastRecord(true);
  519. err = spConfig->ReadConfigValue("SogouInput", "LastInstalledRecord", strLastRecord);
  520. if (strLastRecord.IsNullOrEmpty() || info.Stringfy().Compare(strLastRecord) != 0) {
  521. spConfig->WriteConfigValue("SogouInput", "LastInstalledRecord", info.Stringfy());
  522. fNeedAlarm = TRUE;
  523. }
  524. else {
  525. //Report info per day.
  526. int nLastRecordTime = 0;
  527. err = spConfig->ReadConfigValueInt("SogouInput", "LastReportTime", nLastRecordTime);
  528. SYSTEMTIME stTaskTime = CSmallDateTime(nLastRecordTime).ToSystemTime();
  529. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Last Sogou install check time: %04d-%02d-%02d %02d:%02d:%02d",
  530. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  531. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  532. SYSTEMTIME stNow = {};
  533. GetLocalTime(&stNow);
  534. if (nLastRecordTime > 0 && stTaskTime.wYear == stNow.wYear
  535. && stTaskTime.wMonth == stNow.wMonth && stTaskTime.wDay == stNow.wDay) {
  536. //The Same Day
  537. fNeedAlarm = FALSE;
  538. }
  539. else {
  540. fNeedAlarm = TRUE;
  541. }
  542. }
  543. if (fNeedAlarm) {
  544. const DWORD dwUserCode = info.IsInstalledSuccess() ? LOG_ERR_SOGOU_INPUT_INSTALLED : LOG_ERR_SOGOU_INPUT_NOTINSTALLED;
  545. LogWarn(Severity_Low, Error_DataCheck, dwUserCode, info.Stringfy());
  546. //json上送,方便业务组解析
  547. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SogouVerStatus")("{\"install\":%d,\"program\":\"%s\",\"version\":\"%s\",\"installTime\":\"%s\"}",
  548. info.state.dwInstalledStatus, info.program.strInstallDir.GetData(),
  549. info.program.strVersion.GetData(), info.state.GetInstallTime().ToTimeString().GetData());
  550. spConfig->WriteConfigValue("SogouInput", "LastReportTime", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  551. }
  552. return Error_Succeed;
  553. }
  554. #if defined(RVC_OS_LINUX)
  555. /** No use for now [Gifur@2023109]*/
  556. std::vector<std::string> ResourceWatcherEntity::GetUserNameList(bool bExcludeRoot)
  557. {
  558. std::vector<std::string> results;
  559. array_header_t* arr;
  560. arr = fileutil_get_sub_dirs_a("/home");
  561. if (arr) {
  562. int i;
  563. for (i = 0; i < arr->nelts; ++i) {
  564. char szDestSubDir[256] = { 0 };
  565. char* dir = ARRAY_IDX(arr, i, char*);
  566. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("sub dir: %s", dir);
  567. strcpy(szDestSubDir, dir);
  568. strcat(szDestSubDir, SPLIT_SLASH_STR);
  569. strcat(szDestSubDir, ".config/kwinrc");
  570. if (ExistsFileA(szDestSubDir)) {
  571. std::string strUserName((const char*)&dir[strlen("/home/")]);
  572. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("username:%s", strUserName.c_str());
  573. if (strUserName.compare("root") != 0 || !bExcludeRoot) {
  574. results.push_back(strUserName);
  575. }
  576. }
  577. }
  578. toolkit_array_free2(arr);
  579. }
  580. return results;
  581. }
  582. #else
  583. void ResourceWatcherEntity::ReadFileContent()
  584. {
  585. vector<CSimpleStringA> msg;
  586. CSmartPointer<IConfigInfo> spCtSettingConfig;
  587. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  588. int fileCnt = 0;
  589. CSimpleStringA info("");
  590. do {
  591. fileCnt++;
  592. CSimpleStringA getFilename = CSimpleStringA::Format("ReadFileContentPath%d", fileCnt);
  593. CSimpleStringA path(""), part(""), key("");
  594. spCtSettingConfig->ReadConfigValue("ResourceWatcher", getFilename.GetData(), info);
  595. if (info.GetLength() == 0) {
  596. break;
  597. }
  598. CAutoArray<CSimpleStringA> arr = info.Split('|');
  599. int len = arr.GetCount();
  600. if (len != 3) {
  601. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Wrong ReadFile path config.");
  602. break;
  603. }
  604. path = arr[0];
  605. part = arr[1];
  606. key = arr[2];
  607. char szValue[MAX_PATH + 1] = _T("");
  608. long vLength = GetPrivateProfileString(part.GetData(), key.GetData(), "", szValue, 1024, path.GetData());
  609. CSimpleStringA tMsg = CSimpleStringA::Format("Read file [%s], Part = [%s], [%s] = [%s]",
  610. path.GetData(), part.GetData(), key.GetData(), szValue);
  611. msg.push_back(tMsg);
  612. } while (info.GetLength() != 0);
  613. if (msg.size() != 0) {
  614. CSimpleStringA fRes("|");
  615. for (int i = 0; i < msg.size(); ++i) {
  616. fRes = fRes + msg[i] + "|";
  617. }
  618. LogWarn(Severity_Low, Error_Debug, LOG_WARN_GET_FILE_CONTENT, fRes.GetData());
  619. }
  620. }
  621. long long GetDirSize(string dirPath)
  622. {
  623. long long fileLen = 0;
  624. long hFile = 0;
  625. //文件信息
  626. struct _finddata_t fileinfo;
  627. string p;
  628. if ((hFile = _findfirst(p.assign(dirPath).append("\\*").c_str(), &fileinfo)) != -1) {
  629. do {
  630. //如果是目录,迭代之
  631. //如果不是,加入列表
  632. if ((fileinfo.attrib & _A_SUBDIR)) {
  633. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  634. fileLen += GetDirSize(p.assign(dirPath).append("\\").append(fileinfo.name));
  635. }
  636. else {
  637. fileLen += fileinfo.size;
  638. }
  639. } while (_findnext(hFile, &fileinfo) == 0);
  640. _findclose(hFile);
  641. }
  642. return fileLen;
  643. }
  644. void ResourceWatcherEntity::ReadFileInfo()
  645. {
  646. //读取文件大小 修改时间
  647. vector<CSimpleStringA> msg;
  648. CSmartPointer<IConfigInfo> spCtSettingConfig;
  649. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  650. CSimpleStringA path("");
  651. int fileCnt = 0;
  652. do {
  653. fileCnt++;
  654. CSimpleStringA getFilename = CSimpleStringA::Format("ReadFileInfoPath%d", fileCnt);
  655. spCtSettingConfig->ReadConfigValue("ResourceWatcher", getFilename.GetData(), path);
  656. if (path.GetLength() == 0) {
  657. break;
  658. }
  659. time_t lCreateTime, lModifyTime;
  660. long long lFileLen;
  661. struct _finddata_t fileinfo;//文件信息读取结构
  662. long hFile = -1;
  663. hFile = _findfirst(path.GetData(), &fileinfo);
  664. if (hFile == -1) {
  665. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Get path [%s] file info failed.", path.GetData());
  666. continue;
  667. }
  668. _findclose(hFile);
  669. lCreateTime = fileinfo.time_create;
  670. lModifyTime = fileinfo.time_write;
  671. if ((fileinfo.attrib & _A_SUBDIR)) {
  672. lFileLen = GetDirSize(string(path.GetData()));
  673. }
  674. else {
  675. lFileLen = fileinfo.size;
  676. }
  677. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", lFileLen);
  678. if (lFileLen >= 1024 && lFileLen < (1024 * 1024)) {
  679. DOUBLE len = (DOUBLE)lFileLen / 1024;
  680. resLen = CSimpleStringA::Format("%.2f KB", len);
  681. }
  682. else if (lFileLen >= (1024 * 1024) && lFileLen < (1024 * 1024 * 1024)) {
  683. DOUBLE len = (DOUBLE)lFileLen / (1024 * 1024);
  684. resLen = CSimpleStringA::Format("%.2f MB", len);
  685. }
  686. else if (lFileLen >= (1024 * 1024 * 1024)) {
  687. DOUBLE len = (DOUBLE)lFileLen / (1024 * 1024 * 1024);
  688. resLen = CSimpleStringA::Format("%.2f GB", len);
  689. }
  690. tm* localCreate, * localWrite; //本地时间
  691. char bufCreate[128] = { 0 };
  692. char bufWrite[128] = { 0 };
  693. //所有的localtime返回的指针指向同一个static变量,非线程安全,后续的localtime结果会覆盖之前的
  694. localCreate = localtime(&lCreateTime); //转为本地时间
  695. strftime(bufCreate, 64, "%Y-%m-%d %H:%M:%S", localCreate);
  696. localWrite = localtime(&lModifyTime);
  697. strftime(bufWrite, 64, "%Y-%m-%d %H:%M:%S", localWrite);
  698. CSimpleStringA tMsg = CSimpleStringA::Format("文件[%s], 大小[%s], 创建时间 [%s], 最近修改时间[%s]",
  699. path.GetData(), resLen.GetData(), bufCreate, bufWrite);
  700. msg.push_back(tMsg);
  701. } while (path.GetLength() != 0);
  702. if (msg.size() > 0) {
  703. CSimpleStringA fRes("|");
  704. for (int i = 0; i < msg.size(); i++) {
  705. fRes = fRes + msg[i] + "|";
  706. }
  707. LogWarn(Severity_Low, Error_Debug, LOG_WARN_READ_FILE_INFO, fRes.GetData());
  708. }
  709. return;
  710. }
  711. void ResourceWatcherEntity::ChcekDiskFileSpace()
  712. {
  713. CSimpleStringA path = "D:";
  714. long long fileLen = 0;
  715. long hFile = 0;
  716. //文件信息
  717. struct _finddata_t fileinfo;
  718. string p;
  719. if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
  720. do {
  721. //如果是目录,迭代之
  722. //如果不是,加入列表
  723. if ((fileinfo.attrib & _A_SUBDIR)) {
  724. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  725. fileLen = GetDirSize(p.assign(path).append("\\").append(fileinfo.name));
  726. }
  727. else {
  728. fileLen = fileinfo.size;
  729. }
  730. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  731. if (fileLen >= 1024 && fileLen < (1024 * 1024)) {
  732. DOUBLE len = (DOUBLE)fileLen / 1024;
  733. resLen = CSimpleStringA::Format("%.2f KB", len);
  734. }
  735. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024)) {
  736. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  737. resLen = CSimpleStringA::Format("%.2f MB", len);
  738. }
  739. else if (fileLen >= (1024 * 1024 * 1024)) {
  740. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  741. resLen = CSimpleStringA::Format("%.2f GB", len);
  742. }
  743. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]", p.assign(path).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  744. } while (_findnext(hFile, &fileinfo) == 0);
  745. _findclose(hFile);
  746. }
  747. }
  748. //TODO: CrossPlaform 看是否转移到框架toolkit,太常用了 [Gifur@2025730]
  749. BOOL ResourceWatcherEntity::KillProcessFromName(const CSimpleStringA& strProcessName)
  750. {
  751. #if defined(RVC_OS_WIN)
  752. //创建进程快照(TH32CS_SNAPPROCESS表示创建所有进程的快照)
  753. HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  754. PROCESSENTRY32 pe;
  755. pe.dwSize = sizeof(PROCESSENTRY32);
  756. if (!Process32First(hSnapShot, &pe)) {
  757. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("获取进程快照失败。");
  758. return FALSE;
  759. }
  760. while (Process32Next(hSnapShot, &pe)) {
  761. //pe.szExeFile获取当前进程的可执行文件名称
  762. CSimpleStringA scTmp = pe.szExeFile;
  763. if (!scTmp.Compare(strProcessName)) {
  764. DWORD dwProcessID = pe.th32ProcessID;
  765. HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID);
  766. BOOL killed = ::TerminateProcess(hProcess, 0);
  767. CloseHandle(hProcess);
  768. if (killed) {
  769. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SUCCESS! Kill process [%s], pid [%d].", strProcessName.GetData(), dwProcessID);
  770. }
  771. else {
  772. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("FAILED! Kill process [%s], pid [%d].", strProcessName.GetData(), dwProcessID);
  773. }
  774. return killed;
  775. }
  776. }
  777. return TRUE;
  778. #else
  779. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("It's not supported %s", __FUNCTION__);
  780. return FALSE;
  781. #endif //RVC_OS_WIN
  782. }
  783. #endif //RVC_OS_LINUX
  784. #if defined(RVC_OS_LINUX)
  785. ErrorCodeEnum ResourceWatcherEntity::GetSogouPkgDirPath(CSimpleStringA& strPkgPath)
  786. {
  787. CSimpleStringA strAdDataDirPath(true);
  788. CSimpleStringA strInstallPkgPath(true);
  789. ErrorCodeEnum result = GetFunction()->GetPath("Ad", strAdDataDirPath);
  790. if (strAdDataDirPath.IsNullOrEmpty()) {
  791. strAdDataDirPath = "/opt/rvc/adData";
  792. }
  793. if (strAdDataDirPath.IsNullOrEmpty()) {
  794. return Error_Unexpect;
  795. }
  796. array_header_t* subs;
  797. subs = fileutil_get_sub_dirs_a(strAdDataDirPath);
  798. if (subs) {
  799. for (int i = 0; i < subs->nelts; ++i) {
  800. char* dir = ARRAY_IDX(subs, i, char*);
  801. const char* dirname = &dir[strAdDataDirPath.GetLength() + 1];
  802. if (CSimpleStringA(dirname).IsStartWith("sogou", true) || CSimpleStringA(dirname).IsStartWith("uos-sogou", true)) {
  803. if (strInstallPkgPath.IsNullOrEmpty()) {
  804. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("found it: %s", dir);
  805. strInstallPkgPath = dir;
  806. }
  807. else if (strInstallPkgPath.Compare(dir) < 0) {
  808. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("replace %s with %s", (LPCTSTR)strInstallPkgPath, dir);
  809. strInstallPkgPath = dir;
  810. }
  811. }
  812. }
  813. toolkit_array_free2(subs);
  814. }
  815. if (strInstallPkgPath.IsNullOrEmpty()) {
  816. return Error_NotExist;
  817. }
  818. strPkgPath = strInstallPkgPath;
  819. return Error_Succeed;
  820. }
  821. #endif //RVC_OS_LINUX
  822. //TODO: CrossPlaform [Gifur@2025730]
  823. ErrorCodeEnum ResourceWatcherEntity::RunShellScript(LPCTSTR cmdline)
  824. {
  825. #if defined(RVC_OS_WIN)
  826. return Error_NotSupport;
  827. #else
  828. char app[MAX_PATH] = { '\0' };
  829. char szldPath[1024] = { '\0' };
  830. size_t szldLen = 1023;
  831. tk_process_t* process = NULL;
  832. tk_process_option_t option;
  833. const int ldRet = toolkit_getenv("LD_LIBRARY_PATH", szldPath, &szldLen);
  834. if (ldRet == 0) {
  835. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get library path: %s", szldPath);
  836. toolkit_unsetenv("LD_LIBRARY_PATH");
  837. }
  838. else {
  839. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetEnv of LD_LIBRARY_PATH failed: %s", toolkit_strerror(ldRet));
  840. }
  841. option.exit_cb = NULL;
  842. option.file = NULL;
  843. option.flags = 0;
  844. option.params = (char*)cmdline;
  845. const int res = process_spawn(&option, &process);
  846. if (ldRet == 0) {
  847. toolkit_setenv("LD_LIBRARY_PATH", szldPath);
  848. }
  849. if (0 == res) {
  850. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("execute {%s}, pid: %d, and wait ...", cmdline, process->pid);
  851. int status;
  852. while (process->pid > 0 && waitpid(process->pid, &status, 0) < 0) {
  853. if (errno != EINTR) {
  854. status = -1;
  855. break;
  856. }
  857. }
  858. if (WIFEXITED(status)) {
  859. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("normal terminal. exit status: %d", WEXITSTATUS(status));
  860. }
  861. else if (WIFSIGNALED(status)) {
  862. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("abnormal terminal, signal: %d", WTERMSIG(status));
  863. }
  864. else if (WIFSTOPPED(status)) {
  865. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cihild stop, signal: %d", WSTOPSIG(status));
  866. }
  867. FREE(process);
  868. return Error_Succeed;
  869. }
  870. else {
  871. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("execute {%s} failed: %d", cmdline, res);
  872. return Error_Unexpect;
  873. }
  874. #endif //RVC_OS_WIN
  875. }
  876. std::string ResourceWatcherEntity::DoCheckCertainProcessStatus(const CAutoArray<CSimpleStringA>& pName)
  877. {
  878. const int pSize = pName.GetCount();
  879. vector<int> old_process_id;
  880. CAutoArray<CSimpleStringA> msgs;
  881. #if defined(RVC_OS_WIN)
  882. for (int i = 0; i < pSize; ++i) {
  883. old_process_id.push_back(-1);
  884. CSimpleStringA temp("");
  885. msgs.Append(&temp, 0, 1);
  886. }
  887. int cnt(0);
  888. PROCESSENTRY32 pe32;
  889. pe32.dwSize = sizeof(pe32);
  890. HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  891. if (hProcessSnap == INVALID_HANDLE_VALUE) {
  892. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  893. return "";
  894. }
  895. for (int i = 0; i < pSize; ++i) {
  896. int position = -1;
  897. BOOL bProcess = Process32First(hProcessSnap, &pe32);
  898. while (bProcess) {
  899. if (strcmp(pe32.szExeFile, pName[i].GetData()) == 0) {
  900. position = 1;
  901. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("pname: %s, pid: %d.", pe32.szExeFile, pe32.th32ProcessID);
  902. break;
  903. }
  904. bProcess = Process32Next(hProcessSnap, &pe32);
  905. }
  906. if (position != -1 && old_process_id[i] == -1) {
  907. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
  908. , pName[i].GetData(), pe32.th32ProcessID);
  909. old_process_id[i] = pe32.th32ProcessID;
  910. }
  911. else if (position != -1 && (pe32.th32ProcessID != old_process_id[i])) {
  912. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  913. , pName[i].GetData(), old_process_id[i], pe32.th32ProcessID);
  914. old_process_id[i] = pe32.th32ProcessID;
  915. }
  916. else if (position == -1 && old_process_id[i] > 0) {
  917. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  918. , pName[i].GetData(), old_process_id[i], 0);
  919. old_process_id[i] = 0;
  920. }
  921. }
  922. CloseHandle(hProcessSnap);
  923. #else
  924. alive_process_info* processes = new alive_process_info[pSize];
  925. char** relate_processes = new char* [pSize];
  926. int count = pSize;
  927. for (int i = 0; i < pSize; ++i) {
  928. old_process_id.push_back(-1);
  929. CSimpleStringA temp("");
  930. msgs.Append(&temp, 0, 1);
  931. relate_processes[i] = const_cast<char*>(pName[i].GetData());
  932. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("relate_process name: %s.", relate_processes[i]);
  933. }
  934. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("COUNT = %d!", count);
  935. osutil_detect_unique_app(relate_processes, pSize, &count, processes);
  936. int cnt(0);
  937. for (int i = 0; i < pSize; ++i) {
  938. int k = -1;
  939. for (int j = 0; j < count; ++j) {
  940. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  941. k = j;
  942. break;
  943. }
  944. }
  945. if (k != -1 && old_process_id[i] == -1) {
  946. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
  947. , relate_processes[i], processes[k].pid);
  948. old_process_id[i] = processes[k].pid;
  949. }
  950. else if (k != -1 && (processes[k].pid != old_process_id[i])) {
  951. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  952. , relate_processes[i], old_process_id[i], processes[k].pid);
  953. old_process_id[i] = processes[k].pid;
  954. }
  955. else if (k == -1 && old_process_id[i] != 0) {
  956. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  957. , relate_processes[i], old_process_id[i], 0);
  958. old_process_id[i] = 0;
  959. }
  960. }
  961. #endif //RVC_OS_WIN
  962. std::string uploadInfo("");
  963. if (cnt > 0) {
  964. if (cnt > 1) {
  965. uploadInfo = "{";
  966. }
  967. for (int i = 0; i < cnt; ++i) {
  968. if (i != 0) {
  969. uploadInfo += ",";
  970. }
  971. uploadInfo += msgs[i].GetData();
  972. }
  973. if (cnt > 1) {
  974. uploadInfo += "}";
  975. }
  976. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s", uploadInfo.c_str());
  977. }
  978. return uploadInfo;
  979. }
  980. //检测安全软件进程:亚信、联软、锐眼
  981. void ResourceWatcherEntity::SecProcCheck()
  982. {
  983. //默认检测windows, 若后续需要在UOS检测,则通过集中配置读取修改名称
  984. CSimpleStringA yaXin = "NTRtScan.exe"; //亚信
  985. CSimpleStringA lianRuan = "UniAccessAgent.exe"; //联软
  986. CSimpleStringA ruiYan = "RuiYan.exe"; //锐眼
  987. #ifdef RVC_OS_LINUX
  988. CSmartPointer<IConfigInfo> spCtSettingConfig;
  989. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  990. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "YaXinProcUOS", yaXin);
  991. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "LianRuanProcUOS", lianRuan);
  992. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "RuiYanProcUOS", ruiYan);
  993. #endif // RVC_OS_LINUX
  994. CAutoArray<CSimpleStringA> tArray(&yaXin, 1);
  995. if (yaXin.GetLength() != 0)
  996. {
  997. string yaXinRe = DoCheckCertainProcessStatus(tArray);
  998. if (!yaXinRe.empty())
  999. {
  1000. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SUEPROCCHECK_YAXIN, yaXinRe.c_str());
  1001. }
  1002. }
  1003. if (lianRuan.GetLength() != 0)
  1004. {
  1005. tArray[0] = lianRuan;
  1006. string lianRuanRe = DoCheckCertainProcessStatus(tArray);
  1007. if (!lianRuanRe.empty())
  1008. {
  1009. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SUEPROCCHECK_LIANRUAN, lianRuanRe.c_str());
  1010. }
  1011. }
  1012. if (ruiYan.GetLength() != 0)
  1013. {
  1014. tArray[0] = ruiYan;
  1015. string ruiYanRe = DoCheckCertainProcessStatus(tArray);
  1016. if (!ruiYanRe.empty())
  1017. {
  1018. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SUEPROCCHECK_RUIYAN, ruiYanRe.c_str());
  1019. }
  1020. }
  1021. }
  1022. bool ResourceWatcherEntity::is_str_utf8(const char* str)
  1023. {
  1024. unsigned int nBytes = 0;//UFT8可用1-6个字节编码,ASCII用一个字节
  1025. unsigned char chr = *str;
  1026. bool bAllAscii = true;
  1027. for (unsigned int i = 0; str[i] != '\0'; ++i) {
  1028. chr = *(str + i);
  1029. //判断是否ASCII编码,如果不是,说明有可能是UTF8,ASCII用7位编码,最高位标记为0,0xxxxxxx
  1030. if (nBytes == 0 && (chr & 0x80) != 0) {
  1031. bAllAscii = false;
  1032. }
  1033. if (nBytes == 0) {
  1034. //如果不是ASCII码,应该是多字节符,计算字节数
  1035. if (chr >= 0x80) {
  1036. if (chr >= 0xFC && chr <= 0xFD) {
  1037. nBytes = 6;
  1038. }
  1039. else if (chr >= 0xF8) {
  1040. nBytes = 5;
  1041. }
  1042. else if (chr >= 0xF0) {
  1043. nBytes = 4;
  1044. }
  1045. else if (chr >= 0xE0) {
  1046. nBytes = 3;
  1047. }
  1048. else if (chr >= 0xC0) {
  1049. nBytes = 2;
  1050. }
  1051. else {
  1052. return false;
  1053. }
  1054. nBytes--;
  1055. }
  1056. }
  1057. else {
  1058. if ((chr & 0xC0) != 0x80) {
  1059. return false;
  1060. }
  1061. nBytes--;
  1062. }
  1063. }
  1064. if (nBytes != 0) {
  1065. return false;
  1066. }
  1067. if (bAllAscii) { //如果全部都是ASCII, 也是UTF8
  1068. return true;
  1069. }
  1070. return true;
  1071. }
  1072. ErrorCodeEnum ResourceWatcherEntity::UnzipPack(const char* unZipPackName)
  1073. {
  1074. CSimpleStringA strDownloadsPath;
  1075. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  1076. ErrorCodeEnum rc = spFunction->GetPath("Downloads", strDownloadsPath);
  1077. if (rc != Error_Succeed) {
  1078. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,get Downloads Path is fail");
  1079. return Error_Unexpect;
  1080. }
  1081. CSimpleStringA strTempPath;
  1082. ErrorCodeEnum rc2 = GetFunction()->GetPath("Temp", strTempPath);
  1083. assert(rc2 == Error_Succeed);
  1084. CSimpleStringA strUnzipDir;
  1085. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strTempPath.GetData(), unZipPackName);
  1086. if (strUnzipDir.IsEndWith(".zip") || strUnzipDir.IsEndWith(".cab")) {
  1087. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  1088. }
  1089. // 如目标目录存在,则先删除
  1090. if (ExistsDirA(strUnzipDir)) {
  1091. if (!RemoveDirRecursiveA(strUnzipDir)) {
  1092. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("remove old unzip dir [%s] fail", strUnzipDir.GetData()));
  1093. return Error_NotExist;
  1094. }
  1095. }
  1096. // 创建临时解压目录
  1097. CreateDirA(strUnzipDir.GetData(), true);
  1098. if (!ExistsDirA(strUnzipDir)) {
  1099. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,create temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), GetLastError());
  1100. return Error_Unexpect;
  1101. }
  1102. CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  1103. //升级包是否存在
  1104. if (!ExistsFileA(strZipFile)) {
  1105. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
  1106. return Error_NotExist;
  1107. }
  1108. #if defined(RVC_OS_LINUX)
  1109. string zipFileStr = strZipFile.GetData();
  1110. string zipTempDir = strUnzipDir.GetData();
  1111. if (UnZipToDir(zipFileStr, zipTempDir) != 0) {
  1112. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("unzip pack [%s] fail", zipFileStr.c_str()));
  1113. return Error_NotExist;
  1114. }
  1115. #else
  1116. // 设定解压临时目录
  1117. char szOldPath[MAX_PATH] = {};
  1118. GetCurrentDirectoryA(MAX_PATH, szOldPath);
  1119. //设置当前目录为主目录
  1120. if (!SetCurrentDirectoryA(strUnzipDir.GetData())) {
  1121. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,SetCurrentDirectoryA dir [%s] fail,err=%d", strUnzipDir.GetData(), GetLastError());
  1122. return Error_Unexpect;
  1123. }
  1124. // 解压
  1125. HZIP hz = OpenZip((void*)(const char*)strZipFile, 0, ZIP_FILENAME);
  1126. if (hz == 0) {
  1127. SetCurrentDirectoryA(szOldPath);
  1128. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("open zip file [%s] fail", unZipPackName).GetData());
  1129. return Error_Unexpect;
  1130. }
  1131. ZIPENTRY ze;
  1132. ZRESULT zrc = GetZipItemA(hz, -1, &ze);
  1133. if (zrc == ZR_OK) {
  1134. int numitems = ze.index;
  1135. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("zip entry count is %d", ze.index);
  1136. for (int i = 0; i < numitems; i++) {
  1137. zrc = GetZipItemA(hz, i, &ze);
  1138. if (zrc == ZR_OK) {
  1139. //兼容压缩包里面中文名称是utf8编码
  1140. if (is_str_utf8(ze.name)) {
  1141. char* pGBK = ConvertUtf8ToGBK((const char*)ze.name);
  1142. zrc = UnzipItem(hz, i, pGBK, 0, ZIP_FILENAME);
  1143. if (zrc == ZR_OK) {
  1144. if (pGBK) free(pGBK);
  1145. }
  1146. else {
  1147. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip [%s] UTF8 item fail,result=0x%X", pGBK, (int)zrc);
  1148. if (pGBK) free(pGBK);
  1149. break;
  1150. }
  1151. }
  1152. else {
  1153. zrc = UnzipItem(hz, i, ze.name, 0, ZIP_FILENAME);
  1154. if (zrc != ZR_OK) {
  1155. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip [%s] GBK item fail,result=0x%X", ze.name, (int)zrc);
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. else {
  1161. //出错,退出
  1162. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip GetZipItemA [%d] item fail,fail=0x%X", i, (int)zrc);
  1163. break;
  1164. }
  1165. }
  1166. CloseZip(hz);
  1167. }
  1168. else {
  1169. CloseZip(hz);
  1170. }
  1171. // 恢复当前目录
  1172. SetCurrentDirectoryA(szOldPath);
  1173. if (zrc != ZR_OK) {
  1174. return Error_Exception;
  1175. }
  1176. #endif //RVC_OS_LINUX
  1177. return Error_Succeed;
  1178. }
  1179. ErrorCodeEnum ResourceWatcherEntity::DeleteUnzipDir()
  1180. {
  1181. CSimpleStringA strDownloadsPath;
  1182. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  1183. ErrorCodeEnum rc = spFunction->GetPath("Downloads", strDownloadsPath);
  1184. if (rc != Error_Succeed) {
  1185. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir is fail,get Downloads Path is fail");
  1186. return Error_Unexpect;
  1187. }
  1188. CSimpleStringA sogouTest = "sogoutest";
  1189. CSimpleStringA strUnzipDir = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), sogouTest.GetData());
  1190. //解压去除了.zip后缀
  1191. if (strUnzipDir.IsEndWith(".zip")) {
  1192. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  1193. }
  1194. // 解压目录是否存在,存在则删除
  1195. if (ExistsDirA(strUnzipDir.GetData())) {
  1196. if (!RemoveDirRecursiveA(strUnzipDir.GetData())) {
  1197. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), (int)GetLastError());
  1198. return Error_Unexpect;
  1199. }
  1200. else {
  1201. return Error_Succeed;
  1202. }
  1203. }
  1204. return Error_Succeed;
  1205. }
  1206. CSimpleStringA ResourceWatcherEntity::GetFilePathWithDir(CSimpleStringA dir, CSimpleStringA fileName)
  1207. {
  1208. CSimpleStringA tmpPath(""), filePath("");
  1209. #ifdef RVC_OS_LINUX
  1210. struct stat st;
  1211. if (stat(dir, &st) == -1)
  1212. {
  1213. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s] Failed to get file stats.", dir.GetData());
  1214. return "";
  1215. }
  1216. if (!S_ISDIR(st.st_mode))
  1217. {
  1218. return "";
  1219. }
  1220. DIR* dp;
  1221. struct dirent* dirp;
  1222. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to open dir %s", dir.GetData());
  1223. if ((dp = opendir(dir.GetData())) != NULL)
  1224. {
  1225. while ((dirp = readdir(dp)) != NULL)
  1226. {
  1227. if ((!strcmp(dirp->d_name, ".")) || (!strcmp(dirp->d_name, ".."))) {
  1228. continue;
  1229. }
  1230. CSimpleStringA tmpName(dirp->d_name);
  1231. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
  1232. if (tmpName == fileName)
  1233. {
  1234. filePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1235. break;
  1236. }
  1237. tmpPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1238. filePath = GetFilePathWithDir(tmpPath, fileName);
  1239. if (!filePath.IsNullOrEmpty())
  1240. {
  1241. break;
  1242. }
  1243. }
  1244. closedir(dp);
  1245. if (filePath.IsNullOrEmpty())
  1246. {
  1247. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Can't find file[%s] under path [%s].",fileName.GetData(), dir.GetData());
  1248. }
  1249. return filePath;
  1250. }
  1251. else
  1252. {
  1253. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Open dir [%s] failed.", dir.GetData());
  1254. return "";
  1255. }
  1256. #else
  1257. CSimpleStringA inPath = dir;
  1258. inPath.Append("\\*"); // "D:aaa\bbb\ccc\* " 匹配目录下的所有文件和文件夹
  1259. int fileLength = inPath.GetLength();
  1260. WIN32_FIND_DATA wfd;
  1261. HANDLE hFind;
  1262. hFind = FindFirstFile(inPath.GetData(), &wfd);
  1263. //单文件操作
  1264. if (hFind == INVALID_HANDLE_VALUE) // 非文件夹 (inPath "D:aaa\bbb\ccc\* "格式的情况下,如果前面是文件,会找不到匹配)
  1265. {
  1266. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s] is NOT dir.", dir.GetData());
  1267. return "";
  1268. }
  1269. //文件夹操作
  1270. do
  1271. {
  1272. if ((!strcmp(wfd.cFileName, ".")) || (!strcmp(wfd.cFileName, ".."))) {
  1273. continue;
  1274. }
  1275. CSimpleStringA tmpName(wfd.cFileName);
  1276. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
  1277. if (tmpName == fileName)
  1278. {
  1279. filePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1280. break;
  1281. }
  1282. tmpPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1283. filePath = GetFilePathWithDir(tmpPath, fileName);
  1284. if (!filePath.IsNullOrEmpty())
  1285. {
  1286. break;
  1287. }
  1288. } while (FindNextFileA(hFind, &wfd));
  1289. FindClose(hFind);
  1290. if (filePath.IsNullOrEmpty())
  1291. {
  1292. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Can't find file[%s] under path [%s].", fileName.GetData(), dir.GetData());
  1293. }
  1294. return filePath;
  1295. #endif // RVC_OS_LINUX
  1296. }
  1297. void ResourceWatcherEntity::InstallSogou(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req,
  1298. ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  1299. {
  1300. ErrorCodeEnum result(Error_Succeed);
  1301. ErrorCodeEnum tmpResult(Error_Succeed);
  1302. CSimpleStringA tmpMsg(true);
  1303. CSimpleStringA tmpPath(true);
  1304. DWORD warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_SUC; //RTA映射
  1305. CSimpleStringA newSogouPath(true);
  1306. CSimpleStringA strDownloadDirPath(true);
  1307. GetFunction()->GetPath("Downloads", strDownloadDirPath);
  1308. CSimpleStringA strTempDirPath(true);
  1309. GetFunction()->GetPath("Temp", strTempDirPath);
  1310. #if defined(RVC_OS_LINUX)
  1311. bool sogouInstalled = false;
  1312. const bool doTryRestart = (ctx->Req.reserved1 != 1);
  1313. SogouInstallInfo info;
  1314. //安装搜狗输入法
  1315. bool zipFind = false;
  1316. time_t newestWrite = 0;
  1317. if (strDownloadDirPath.IsNullOrEmpty()) {
  1318. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("downloads path is invalid, maybe in config mode");
  1319. tmpResult = Error_Unexpect;
  1320. tmpMsg = CSimpleStringA::Format("搜狗安装包目录[Downloads]不存在!");
  1321. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1322. }
  1323. else {
  1324. DIR* dp;
  1325. struct dirent* dirp;
  1326. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to open dir %s", strDownloadDirPath.GetData());
  1327. if ((dp = opendir(strDownloadDirPath.GetData())) != NULL) {
  1328. while ((dirp = readdir(dp)) != NULL) {
  1329. CSimpleStringA tmpName(dirp->d_name);
  1330. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
  1331. if ((tmpName.IsStartWith("sogou", true) || tmpName.IsStartWith("uos-sogou", true))
  1332. && tmpName.IsEndWith(".zip", true)) {
  1333. struct stat buf;
  1334. memset(&buf, 0x00, sizeof(buf));
  1335. CSimpleStringA strFullPathName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadDirPath.GetData(), dirp->d_name);
  1336. const int ret = stat(strFullPathName.GetData(), &buf);
  1337. if (ret != 0) {
  1338. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("获取文件[%s]状态信息出错。", tmpName.GetData());
  1339. }
  1340. else if (buf.st_mtim.tv_sec > newestWrite) {
  1341. newestWrite = buf.st_mtim.tv_sec;
  1342. newSogouPath = CSimpleStringA(tmpName.GetData());
  1343. zipFind = true;
  1344. }
  1345. }
  1346. }
  1347. closedir(dp);
  1348. if (!zipFind) {
  1349. tmpResult = Error_NotExist;
  1350. tmpMsg = CSimpleStringA::Format("在路径[%s]下未找到搜狗安装包!", strDownloadDirPath.GetData());
  1351. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1352. }
  1353. }
  1354. else {
  1355. tmpResult = Error_NotExist;
  1356. tmpMsg = CSimpleStringA::Format("打开[Downloads]目录失败!");
  1357. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1358. }
  1359. }
  1360. CSimpleStringA strInstallPkgPath(true);
  1361. if (zipFind) {
  1362. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to unzip pack %s", newSogouPath.GetData());
  1363. if (UnzipPack(newSogouPath) != Error_Succeed) {
  1364. tmpResult = Error_Unexpect;
  1365. tmpMsg = CSimpleStringA::Format("解压搜狗安装包失败!");
  1366. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1367. }
  1368. else {
  1369. newSogouPath = newSogouPath.SubString(0, newSogouPath.GetLength() - 4);
  1370. strInstallPkgPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",
  1371. strTempDirPath.GetData(), newSogouPath.GetData());
  1372. }
  1373. }
  1374. else {
  1375. tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
  1376. if (tmpResult != Error_Succeed) {
  1377. tmpMsg = CSimpleStringA::Format(" 指定位置 [Ad] 找不到输入法安装包");
  1378. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1379. }
  1380. }
  1381. CSimpleStringA strInstallScriptFile;
  1382. CSimpleStringA strRunIniFilePath;
  1383. CSimpleStringA strResultLogFilePath;
  1384. const bool doNotStartup(true); //安装后是否启动搜狗输入法服务,据搜狗反馈,不能通过root权限启动Sogou输入法
  1385. if (tmpResult == Error_Succeed) {
  1386. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to install sogou input... %s", strInstallPkgPath.GetData());
  1387. tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
  1388. if (tmpResult != Error_Succeed) {
  1389. tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
  1390. tmpResult = Error_NotExist;
  1391. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1392. }
  1393. else {
  1394. strRunIniFilePath = GetFilePathWithDir(strInstallPkgPath, "Run.ini");
  1395. if (ExistsFileA(strRunIniFilePath)) {
  1396. char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
  1397. strInstallScriptFile = GetFilePathWithDir(strInstallPkgPath, p);
  1398. FREE(p);
  1399. }
  1400. else {
  1401. strInstallScriptFile = GetFilePathWithDir(strInstallPkgPath, "install_sogouime.sh");
  1402. }
  1403. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("install script file: %s", strInstallScriptFile.GetData());
  1404. if (ExistsFileA(strInstallScriptFile)) {
  1405. char app[MAX_PATH] = { '\0' };
  1406. sprintf(app, "bash %s", strInstallScriptFile.GetData());
  1407. tmpResult = RunShellScript(app);
  1408. if (tmpResult != 0) {
  1409. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  1410. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1411. }
  1412. else if (!doNotStartup) {
  1413. CSimpleStringA strStartupScriptFile = GetFilePathWithDir(strInstallPkgPath, "startup_service.sh");
  1414. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("startup script file: %s", strStartupScriptFile.GetData());
  1415. if (!ExistsFileA(strStartupScriptFile)) {
  1416. tmpMsg = CSimpleStringA::Format("%s 启动脚本文件不存在,请重启设备再次验证", strStartupScriptFile.GetData());
  1417. tmpResult = Error_NotExist;
  1418. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1419. }
  1420. else {
  1421. Sleep(1000);
  1422. do {
  1423. sprintf(app, "bash %s", strStartupScriptFile.GetData());
  1424. tmpResult = RunShellScript(app);
  1425. if (tmpResult != 0) {
  1426. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  1427. tmpResult = Error_Process;
  1428. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1429. }
  1430. } while (false);
  1431. }
  1432. }
  1433. }
  1434. else {
  1435. tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
  1436. tmpResult = Error_NotExist;
  1437. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1438. }
  1439. }
  1440. }
  1441. if (tmpResult == Error_Succeed) {
  1442. Sleep(1500);
  1443. strResultLogFilePath = GetFilePathWithDir(strInstallPkgPath, "result.log");
  1444. do {
  1445. const int maxTimes = 5;
  1446. int curTimes = 0;
  1447. while (!ExistsFileA(strResultLogFilePath) && curTimes < maxTimes) {
  1448. Sleep(1500);
  1449. curTimes++;
  1450. }
  1451. } while (false);
  1452. if (!ExistsFileA(strResultLogFilePath)) {
  1453. tmpResult = Error_NotExist;
  1454. tmpMsg = CSimpleStringA::Format("安装成功标志文件不存在!");
  1455. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1456. }
  1457. else {
  1458. FILE* pResultLog = fopen(strResultLogFilePath, "r");
  1459. if (pResultLog == NULL) {
  1460. tmpResult = Error_IO;
  1461. tmpMsg = CSimpleStringA::Format("打开安装成功标志文件失败!%s", strerror(errno));
  1462. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1463. }
  1464. else {
  1465. char szTmp[1024] = { '\0' };
  1466. int nRead = fread(szTmp, 1, sizeof(szTmp), pResultLog);
  1467. int installResult(-1);
  1468. char installMsg[256] = { '\0' };
  1469. sscanf(szTmp, "result=%d&msg=%s", &installResult, installMsg);
  1470. fclose(pResultLog);
  1471. if (installResult != 0) {
  1472. tmpResult = Error_Unexpect;
  1473. tmpMsg = CSimpleStringA::Format("安装状态错误:%s", szTmp);;
  1474. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1475. }
  1476. else {
  1477. GetSogouInstallInfo(info);
  1478. if (!info.IsInstalledSuccess()) {
  1479. tmpResult = Error_FailVerify;
  1480. tmpMsg = CSimpleStringA::Format("搜狗检测安装状态失败!");
  1481. }
  1482. else {
  1483. ctx->Ans.path = info.program.strInstallDir;
  1484. ctx->Ans.reserverd1 = info.program.strVersion;
  1485. ctx->Ans.reserverd2 = info.state.GetInstallTime().ToTimeString();
  1486. //ctx->Ans.reserverd3 = info.program.IsTSFVersion() ? 1 : 0;
  1487. //ctx->Ans.reserverd4 = 0;
  1488. if (doTryRestart) {
  1489. tmpMsg = CSimpleStringA::Format(" 从[%s]安装搜狗输入法成功。", strInstallPkgPath.GetData());
  1490. }
  1491. sogouInstalled = true;
  1492. }
  1493. }
  1494. }
  1495. }
  1496. }
  1497. LogWarn(Severity_Low, Error_Debug, warnCode,
  1498. CSimpleStringA::Format("用户桌面重装搜狗:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  1499. ctx->Ans.result = tmpResult;
  1500. ctx->Ans.msg = tmpMsg;
  1501. ctx->Answer(tmpResult, warnCode);
  1502. #else
  1503. //win-sogou 包名
  1504. bool zipFind = false;
  1505. struct _finddata_t fileinfo;//文件信息读取结构
  1506. long hFile = -1;
  1507. time_t newestWrite = 0;
  1508. if (strDownloadDirPath.IsNullOrEmpty()) {
  1509. tmpResult = Error_Unexpect;
  1510. tmpMsg = CSimpleStringA::Format("搜狗安装包目录[Downloads]不存在!");
  1511. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1512. }
  1513. else {
  1514. CSimpleStringA tmpDownloads(strDownloadDirPath.GetData());
  1515. hFile = _findfirst(tmpDownloads.Append("\\*").GetData(), &fileinfo);
  1516. if (hFile != -1) {
  1517. do {
  1518. CSimpleStringA tmpName(fileinfo.name);
  1519. if ((tmpName.IsStartWith("sogou", true) || tmpName.IsStartWith("win-sogou", true) || tmpName.IsStartWith("Sys-Win-sogou", true))
  1520. && tmpName.IsEndWith(".zip", true) && fileinfo.time_write > newestWrite) {
  1521. newestWrite = fileinfo.time_write;
  1522. newSogouPath = CSimpleStringA(tmpName.GetData());
  1523. zipFind = true;
  1524. }
  1525. } while (_findnext(hFile, &fileinfo) == 0);
  1526. _findclose(hFile);
  1527. if (zipFind) {
  1528. if (UnzipPack(newSogouPath.GetData()) != Error_Succeed) {
  1529. tmpResult = Error_Unexpect;
  1530. tmpMsg = CSimpleStringA::Format("解压搜狗安装包失败!");
  1531. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1532. }
  1533. else {
  1534. newSogouPath = newSogouPath.SubString(0, newSogouPath.GetLength() - 4);
  1535. CSimpleStringA tmpStrInstallDirPath = CSimpleStringA::Format("%s\\%s",
  1536. strTempDirPath.GetData(), newSogouPath.GetData()); //D:RVC\temp\sogou.xxxxx
  1537. CSimpleStringA strInstallDirPath("");
  1538. CSimpleStringA strResultLogFilePath("");
  1539. strInstallDirPath = GetFilePathWithDir(tmpStrInstallDirPath, "install_sogouime.bat") + " force";
  1540. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("开始安装");
  1541. STARTUPINFO si = { sizeof(si) };
  1542. PROCESS_INFORMATION pi;
  1543. si.dwFlags = STARTF_USESHOWWINDOW;
  1544. si.wShowWindow = TRUE;
  1545. char* cmdline = const_cast<LPSTR>(strInstallDirPath.GetData());
  1546. BOOL bRet = ::CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
  1547. WaitForSingleObject(pi.hProcess, INFINITE);
  1548. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("结束后台安装流程");
  1549. strResultLogFilePath = GetFilePathWithDir(tmpStrInstallDirPath, "result.log");
  1550. if (strResultLogFilePath.IsNullOrEmpty() || strInstallDirPath.IsNullOrEmpty()) {
  1551. tmpResult = Error_NotExist;
  1552. tmpMsg = CSimpleStringA::Format("进入安装目录失败!路径为空!");
  1553. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1554. }
  1555. else if (!ExistsFileA(strResultLogFilePath)) {
  1556. tmpResult = Error_NotExist;
  1557. tmpMsg = CSimpleStringA::Format("安装成功标志文件不存在!路径[%s]", strResultLogFilePath.GetData());
  1558. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1559. }
  1560. else {
  1561. FILE* pResultLog = fopen(strResultLogFilePath, "r");
  1562. if (pResultLog == NULL) {
  1563. tmpResult = Error_IO;
  1564. tmpMsg = CSimpleStringA::Format("打开安装成功标志文件失败!%s", strerror(errno));
  1565. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1566. }
  1567. else {
  1568. char szTmp[1024] = { '\0' };
  1569. int nRead = fread(szTmp, 1, sizeof(szTmp), pResultLog);
  1570. CSimpleStringA tInstallRe = szTmp;
  1571. fclose(pResultLog);
  1572. CSimpleStringA installResult = "-1";
  1573. CSimpleStringA installMsg;
  1574. auto arr = tInstallRe.Split('&');
  1575. if (arr.GetCount() != 2) {
  1576. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read result log format fail");
  1577. tmpMsg = "read result.log format fail,eg result=0&msg=install ok";
  1578. }
  1579. for (int i = 0; i < arr.GetCount(); i++) {
  1580. auto arr2 = arr[i].Split('=');
  1581. if (arr2.GetCount() == 2) {
  1582. if (stricmp(arr2[0], "result") == 0)
  1583. installResult = arr2[1];
  1584. else if (stricmp(arr2[0], "msg") == 0)
  1585. installMsg = arr2[1];
  1586. }
  1587. }
  1588. if (installResult != CSimpleStringA::Format("0")) {
  1589. tmpResult = Error_Unexpect;
  1590. tmpMsg = CSimpleStringA::Format("安装状态错误:%s", szTmp);
  1591. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1592. }
  1593. else {
  1594. SogouInstallInfo info;
  1595. if (GetSogouInstallInfo(info) != Error_Succeed) {
  1596. tmpResult = Error_FailVerify;
  1597. tmpMsg = CSimpleStringA::Format("搜狗安装状态失败!");
  1598. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1599. }
  1600. else {
  1601. ctx->Ans.path = info.program.strInstallDir;
  1602. ctx->Ans.reserverd1 = info.program.strVersion;
  1603. ctx->Ans.reserverd2 = info.state.GetInstallTime().ToTimeString();
  1604. }
  1605. }
  1606. }
  1607. }
  1608. if (tmpResult == Error_Succeed) {
  1609. tmpMsg = CSimpleStringA::Format("已成功安装搜狗输入法!");
  1610. }
  1611. }
  1612. }
  1613. else {
  1614. tmpResult = Error_NotExist;
  1615. tmpMsg = CSimpleStringA::Format("在路径[%s]下未找到搜狗安装包!", strDownloadDirPath.GetData());
  1616. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1617. }
  1618. }
  1619. else {
  1620. tmpResult = Error_NotExist;
  1621. tmpMsg = CSimpleStringA::Format("搜狗打开[Downloads]目录失败!");
  1622. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1623. }
  1624. }
  1625. LogWarn(Severity_Low, Error_Debug, warnCode,
  1626. CSimpleStringA::Format("用户桌面重装搜狗:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  1627. ctx->Ans.result = tmpResult;
  1628. ctx->Ans.msg = tmpMsg;
  1629. ctx->Answer(tmpResult, warnCode);
  1630. return;
  1631. #endif //RVC_OS_LINUX
  1632. }
  1633. void ResourceWatcherEntity::CheckProcessStatus()
  1634. {
  1635. vector<string> msg;
  1636. CSmartPointer<IConfigInfo> spCtSettingConfig;
  1637. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  1638. CSimpleStringA getProcess(""), tName("");
  1639. int procCnt = 0;
  1640. #if defined(RVC_OS_LINUX)
  1641. do {
  1642. procCnt++;
  1643. getProcess = CSimpleStringA::Format("ProcessNameUOS%d", procCnt);
  1644. spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getProcess, tName);
  1645. if (!tName.IsNullOrEmpty()) {
  1646. std::string succStr, errStr;
  1647. std::string runStr("pgrep -d '|' ");
  1648. runStr += tName.GetData();
  1649. CSimpleStringA tMsg(true);
  1650. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  1651. if (succStr.empty()) {
  1652. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": 0}", tName.GetData());
  1653. }
  1654. else {
  1655. succStr = SP::Utility::ToTrim(succStr);
  1656. if (succStr.find('|') != std::string::npos) {
  1657. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": %s}", tName.GetData(), succStr.c_str());
  1658. }
  1659. else {
  1660. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": \"%s\"}", tName.GetData(), succStr.c_str());
  1661. }
  1662. }
  1663. }
  1664. else {
  1665. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": -1}", tName.GetData());
  1666. }
  1667. msg.push_back(tMsg.GetData());
  1668. }
  1669. } while (!tName.IsNullOrEmpty());
  1670. #else
  1671. do {
  1672. procCnt++;
  1673. getProcess = CSimpleStringA::Format("ProcessName%d", procCnt);
  1674. spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getProcess, tName);
  1675. if (tName.GetLength() != 0) {
  1676. CAutoArray<CSimpleStringA> tArray;
  1677. tArray.Append(&tName, 0, 1);
  1678. string tMsg = DoCheckCertainProcessStatus(tArray);
  1679. if (tMsg.size() == 0) {
  1680. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": 0}", tName.GetData());
  1681. }
  1682. msg.push_back(tMsg);
  1683. }
  1684. } while (tName.GetLength() != 0);
  1685. #endif //RVC_OS_LINUX
  1686. if (msg.size() != 0) {
  1687. CSimpleStringA res(true);
  1688. if (msg.size() == 1) {
  1689. res = msg[0].c_str();
  1690. }
  1691. else {
  1692. res = "{";
  1693. for (int i = 0; i < msg.size(); ++i) {
  1694. if (i != 0) { res += ","; }
  1695. res = res + msg[i].c_str();
  1696. }
  1697. res += "}";
  1698. }
  1699. LogWarn(Severity_Low, Error_Debug, LOG_WARN_PROCESS_STATUS, res);
  1700. }
  1701. }
  1702. void ResourceWatcherEntity::FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
  1703. {
  1704. ErrorCodeEnum result(Error_Succeed);
  1705. ErrorCodeEnum tmpResult(Error_Succeed);
  1706. CSimpleStringA tmpMsg(true);
  1707. if (ctx->Req.type == 1)//清理浏览器缓存
  1708. {
  1709. BrowserCacheClean browserCacheClean;
  1710. browserCacheClean.needClean = 1;
  1711. SpSendBroadcast(GetFunction(),
  1712. SP_MSG_OF(BrowserCacheClean), SP_MSG_SIG_OF(BrowserCacheClean), browserCacheClean);
  1713. tmpMsg = "已发送重启命令";
  1714. }
  1715. else {
  1716. tmpResult = Error_NotExist;
  1717. tmpMsg = "非法的调用参数";
  1718. }
  1719. ctx->Ans.result = tmpResult;
  1720. ctx->Ans.msg = tmpMsg;
  1721. ctx->Answer(result);
  1722. }
  1723. void ResourceWatcherEntity::FetchSystemSnapshot(
  1724. SpReqAnsContext<ResourceWatcherService_FetchSystemSnapshot_Req, ResourceWatcherService_FetchSystemSnapshot_Ans>::Pointer ctx)
  1725. {
  1726. CSimpleStringA info(true);
  1727. if (ctx->Req.type == 1) {
  1728. #if defined(RVC_OS_WIN)
  1729. ctx->Answer(Error_NotSupport);
  1730. #else
  1731. const bool ret = m_fsm.GetMonitorInfo(info);
  1732. if (ret) {
  1733. ctx->Ans.result = 0;
  1734. ctx->Ans.msg = info;
  1735. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS_GET, info);
  1736. }
  1737. else {
  1738. ctx->Ans.result = -1;
  1739. ctx->Ans.msg = "调用 GetMonitorInfo 接口失败";
  1740. }
  1741. ctx->Answer(Error_Succeed);
  1742. #endif //RVC_OS_WIN
  1743. }
  1744. else if (ctx->Req.type == 2) { /** 有无安装新版浏览器 [Gifur@20221219]*/
  1745. #if defined(_MSC_VER)
  1746. ctx->Answer(Error_NotSupport);
  1747. #else
  1748. const std::string execute_newbrowser_path = "/usr/share/browser/browser";
  1749. const std::string execute_oldbrowser_path = "/usr/share/uosbrowser/uosbrowser";
  1750. int result(0);
  1751. std::string additional("");
  1752. std::string succStr, errStr;
  1753. std::string runStr("dpkg -l | grep org.deepin.browser | awk '{print $3}'");
  1754. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  1755. if (succStr.empty()) {
  1756. if (ExistsFileA(execute_oldbrowser_path.c_str())) {
  1757. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s exists!", execute_oldbrowser_path.c_str());
  1758. result = 1;
  1759. }
  1760. else {
  1761. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s not exists!", execute_oldbrowser_path.c_str());
  1762. }
  1763. }
  1764. else {
  1765. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("new browser version: %s", succStr.c_str());
  1766. additional = succStr;
  1767. if (!ExistsFileA(execute_newbrowser_path.c_str())) {
  1768. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s not exists!", execute_newbrowser_path.c_str());
  1769. }
  1770. result = 2;
  1771. }
  1772. ctx->Ans.result = result;
  1773. ctx->Ans.msg = additional.c_str();
  1774. ctx->Answer(Error_Succeed);
  1775. }
  1776. else {
  1777. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("execute '%s' failed!", runStr.c_str());
  1778. ctx->Answer(Error_Process);
  1779. }
  1780. #endif //_MSC_VER
  1781. }
  1782. else {
  1783. ctx->Answer(Error_NotSupport);
  1784. }
  1785. }
  1786. int ResourceWatcherEntity::CheckMediaResource(int iFileType, const char* pFileName)
  1787. {
  1788. int iRet = -1;
  1789. CSimpleStringA strRootPath("");
  1790. CSimpleStringA strFileFolder("");
  1791. CSimpleStringA strFilePath("");
  1792. ErrorCodeEnum Error = GetFunction()->GetPath("ADData", strRootPath);
  1793. if (AudioDefaultPath == iFileType) {
  1794. strFileFolder = strRootPath + SPLIT_SLASH_STR + "Audio" + SPLIT_SLASH_STR;
  1795. }
  1796. else {
  1797. strFileFolder = strRootPath + SPLIT_SLASH_STR + "Video" + SPLIT_SLASH_STR;
  1798. }
  1799. strFilePath = strFileFolder + pFileName;
  1800. iRet = IsFileExists(strFilePath.GetData());
  1801. return iRet;
  1802. }
  1803. void ResourceWatcherEntity::CheckIsFileExists(SpReqAnsContext<ResourceWatcherService_CheckIsFileExists_Req, ResourceWatcherService_CheckIsFileExists_Ans>::Pointer ctx)
  1804. {
  1805. int iResult = -1;
  1806. ErrorCodeEnum Error = Error_Succeed;
  1807. DWORD warnCode = 0;
  1808. if (ctx->Req.filename.GetLength() > 0) {
  1809. CSimpleStringA strFileName = CSimpleStringW2A(ctx->Req.filename);
  1810. switch (ctx->Req.filetype) {
  1811. case AbsolutePath:
  1812. iResult = IsFileExists(strFileName.GetData());
  1813. break;
  1814. case AudioDefaultPath:
  1815. case VideoDefaultPath:
  1816. iResult = CheckMediaResource(ctx->Req.filetype, strFileName.GetData());
  1817. break;
  1818. default:
  1819. Error = Error_NotSupport;
  1820. warnCode = LOG_WARN_FILECHECK_NOTSUPPORT_TYPE;
  1821. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("filetype = %d.", ctx->Req.filetype);
  1822. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A10").setAPI(__FUNCTION__)("目前不支持该类型文件检查");
  1823. break;
  1824. }
  1825. }
  1826. else {
  1827. Error = Error_Param;
  1828. warnCode = LOG_WARN_FILECHECK_ERRORPARAM;
  1829. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A11").setAPI(__FUNCTION__)("要检查的文件名为空");
  1830. }
  1831. ctx->Ans.result = iResult;
  1832. if (Error_Succeed == Error) {
  1833. ctx->Answer(Error);
  1834. }
  1835. else {
  1836. ctx->Answer(Error, warnCode);
  1837. }
  1838. }
  1839. #if defined(RVC_OS_WIN)
  1840. SP_BEGIN_ENTITY_MAP()
  1841. SP_ENTITY(ResourceWatcherEntity)
  1842. SP_END_ENTITY_MAP()
  1843. #else
  1844. ResourceWatcherEntity cur;
  1845. class SpEntityModuleStub : public ModuleBase
  1846. {
  1847. public:
  1848. SpEntityModuleStub()
  1849. {
  1850. try {
  1851. //ResourceWatcherEntity* cur = new ResourceWatcherEntity();
  1852. // 内存分配成功
  1853. m_pEntityArray[m_nEntityCount++] = dynamic_cast<CEntityBase*>(&cur);
  1854. }
  1855. catch (const std::bad_alloc& e) {
  1856. // 内存分配失败,捕获异常
  1857. Dbg("ResourceWatcher Error: Memory allocation failed for ResourceWatcherEntity. %s", e.what());
  1858. // 处理错误
  1859. }
  1860. catch (...) {
  1861. Dbg("ResourceWatcher Error: other for ResourceWatcherEntity");
  1862. }
  1863. Dbg("ResourceWatcher SpEntityModuleStub end");
  1864. }
  1865. };
  1866. SpEntityModuleStub g_ModuleInst;
  1867. extern "C" void __attribute__((constructor)) SoMain() {
  1868. g_ModuleInst.DllMain(NULL, DLL_PROCESS_ATTACH, NULL);
  1869. }
  1870. #endif