mod_ResourceWatcher.cpp 75 KB

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