mod_ResourceWatcher.cpp 77 KB

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