mod_ResourceWatcher.cpp 77 KB

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