mod_ResourceWatcher.cpp 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678
  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. #define SafeDeleteArraySize(pData) { if(pData){delete []pData;pData=NULL;} }
  46. void ResourceWatcherServiceSession::Handle_GetDevInfo(
  47. SpReqAnsContext<ResourceWatcherService_GetDevInfo_Req, ResourceWatcherService_GetDevInfo_Ans>::Pointer ctx)
  48. {
  49. DbgToBeidou(ctx->link, __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_GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
  68. {
  69. DbgToBeidou(ctx->link, __FUNCTION__)();
  70. m_pEntity->GetThirdPartyInstallState(ctx);
  71. }
  72. void ResourceWatcherServiceSession::Handle_InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  73. {
  74. DbgToBeidou(ctx->link, __FUNCTION__)();
  75. m_pEntity->InstallThirdPartyProgram(ctx);
  76. }
  77. void ResourceWatcherServiceSession::Handle_UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
  78. {
  79. DbgToBeidou(ctx->link, __FUNCTION__)();
  80. m_pEntity->UninstallThirdPartyProgram(ctx);
  81. }
  82. void ResourceWatcherServiceSession::Handle_RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
  83. {
  84. DbgToBeidou(ctx->link, __FUNCTION__)();
  85. m_pEntity->RestartThirdPartyProgram(ctx);
  86. }
  87. void ResourceWatcherServiceSession::Handle_ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
  88. {
  89. DbgToBeidou(ctx->link, __FUNCTION__)();
  90. m_pEntity->ProcessDetectThirdPartyProgram(ctx);
  91. }
  92. void ResourceWatcherServiceSession::Handle_FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
  93. {
  94. DbgToBeidou(ctx->link, __FUNCTION__)();
  95. m_pEntity->FilesClean(ctx);
  96. }
  97. void ResourceWatcherServiceSession::Handle_FetchSystemSnapshot(SpReqAnsContext<ResourceWatcherService_FetchSystemSnapshot_Req, ResourceWatcherService_FetchSystemSnapshot_Ans>::Pointer ctx)
  98. {
  99. DbgToBeidou(ctx->link, __FUNCTION__)();
  100. m_pEntity->FetchSystemSnapshot(ctx);
  101. }
  102. void ResourceWatcherServiceSession::Handle_OperateFile
  103. (SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  104. ResourceWatcherService_OperateFile_Ans>::Pointer ctx)
  105. {
  106. DbgToBeidou(ctx->link, __FUNCTION__)();
  107. m_pEntity->OperateFile(ctx);
  108. }
  109. struct SogouRunVersionInfo
  110. {
  111. CSimpleStringA strInstallDir;
  112. CSimpleStringA strVersion;
  113. SogouRunVersionInfo() :strInstallDir(true), strVersion(true) {}
  114. CSimpleStringA ToString() const
  115. {
  116. CSimpleStringA result(true);
  117. if (!strInstallDir.IsNullOrEmpty()) {
  118. result += strInstallDir;
  119. result += "#";
  120. }
  121. if (!strVersion.IsNullOrEmpty()) {
  122. result += strVersion;
  123. }
  124. return result;
  125. }
  126. CVersion ConvertVersion()
  127. {
  128. CVersion installVer;
  129. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  130. int n = sscanf(strVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  131. if (n != 4) {
  132. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not sogou version.[%s]", strVersion.GetData());
  133. }
  134. else {
  135. installVer = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
  136. }
  137. return installVer;
  138. }
  139. //true: 普通调用版本输入法,false: SDK版本输入法
  140. bool IsTSFVersion()
  141. {
  142. #if defined(_MSC_VER)
  143. CVersion standardVer = CVersion(2, 6, 1, 1967); //对比版本为2.6.1.1967
  144. #else
  145. CVersion standardVer = CVersion(2, 6, 4, 355); //对比版本为2.4.6.355
  146. #endif //_MSC_VER
  147. return (ConvertVersion() >= standardVer);
  148. }
  149. };
  150. struct SogouInstallStateInfo
  151. {
  152. DWORD dwInstalledStatus;
  153. CSimpleStringA strInstallDate;
  154. SogouInstallStateInfo() :dwInstalledStatus(-1), strInstallDate(true) {}
  155. CSimpleStringA ToString() const
  156. {
  157. CSimpleStringA result(true);
  158. if (!strInstallDate.IsNullOrEmpty()) {
  159. result += GetInstallTime().ToTimeString().GetData();
  160. result += "#";
  161. }
  162. result += CSimpleStringA::Format("%u", dwInstalledStatus);
  163. return result;
  164. }
  165. CSmallDateTime GetInstallTime() const
  166. {
  167. if (!strInstallDate.IsNullOrEmpty()) {
  168. DWORD dwSecsSince1970(0);
  169. sscanf_s(strInstallDate.GetData(), "%u", &dwSecsSince1970);
  170. dwSecsSince1970 -= 946656000; // 2000-1970
  171. return CSmallDateTime(dwSecsSince1970);
  172. }
  173. return CSmallDateTime::BeginTime;
  174. }
  175. };
  176. struct SogouInstallInfo
  177. {
  178. SogouInstallStateInfo state;
  179. SogouRunVersionInfo program;
  180. CSimpleStringA Stringfy() const
  181. {
  182. return (state.ToString() + "||" + program.ToString());
  183. }
  184. bool IsInstalledSuccess() const
  185. {
  186. return (state.dwInstalledStatus == 0);
  187. }
  188. };
  189. #if defined(RVC_OS_LINUX)
  190. std::string TryToGetSogouVersionEx()
  191. {
  192. std::string succStr, errStr;
  193. std::string runStr("cat /opt/sogouimebs/files/share/sogou-version");
  194. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  195. if (succStr.empty()) {
  196. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cat sogou version return empty!");
  197. }
  198. else {
  199. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("cat sogou version returned: %s", succStr.c_str());
  200. return succStr;
  201. }
  202. }
  203. else {
  204. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("execute cmd failed: %s", errStr.c_str());
  205. }
  206. return "";
  207. }
  208. #else
  209. static inline bool Is64BitPlatform()
  210. {
  211. SYSTEM_INFO si;
  212. GetNativeSystemInfo(&si);
  213. return (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64
  214. || si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64);
  215. }
  216. static int Is32R64Platform()
  217. {
  218. static int isWow64 = -1;
  219. typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  220. if (isWow64 == -1) {
  221. BOOL bIsWow64 = FALSE;
  222. LPFN_ISWOW64PROCESS fnIsWow64Process =
  223. (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  224. if (NULL != fnIsWow64Process) {
  225. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
  226. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("detect is running with 64bit or not failed: %u", GetLastError());
  227. return -1;
  228. }
  229. else {
  230. isWow64 = bIsWow64 ? 1 : 0;
  231. }
  232. }
  233. }
  234. return isWow64;
  235. }
  236. static bool GetRegistValue(HKEY hKey, LPCTSTR lpcszParam, DWORD* pDwValue, CHAR* pSzValue, const DWORD* pDwSizeOfSz)
  237. {
  238. if (pDwValue != NULL) {
  239. DWORD dwType = REG_DWORD;
  240. DWORD dwValue = 0;
  241. DWORD dwSize = sizeof(DWORD);
  242. LONG lResult = RegQueryValueExA(hKey, lpcszParam, NULL, &dwType, (LPBYTE)&dwValue, &dwSize);
  243. if (lResult == ERROR_SUCCESS) {
  244. *pDwValue = dwValue;
  245. return true;
  246. }
  247. else {
  248. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"%s\" error, result=%ld.", lpcszParam, lResult);
  249. return false;
  250. }
  251. }
  252. else if (pSzValue != NULL) {
  253. DWORD dwType = REG_SZ;
  254. DWORD dwSize = MAX_PATH * sizeof(CHAR);
  255. TCHAR szValue[MAX_PATH + 1] = { 0 };
  256. LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, &dwSize);
  257. if (lResult == ERROR_SUCCESS) {
  258. strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
  259. return true;
  260. }
  261. else {
  262. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"InstallTime\" error, result=%ld.", lResult);
  263. return false;
  264. }
  265. }
  266. return false;
  267. }
  268. static LONG GetSogouInstallState(SogouInstallStateInfo& info)
  269. {
  270. HKEY hKey;
  271. LONG lResult = -1;
  272. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  273. lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\SogouPCIme", 0, dwFlag, &hKey);
  274. if (lResult == ERROR_SUCCESS) {
  275. DWORD dwValue = (DWORD)-1;
  276. const bool res1 = GetRegistValue(hKey, "InstallFlag", &dwValue, NULL, NULL);
  277. if (res1) {
  278. info.dwInstalledStatus = dwValue;
  279. }
  280. TCHAR szValue[MAX_PATH + 1] = { 0 };
  281. DWORD dwLength = MAX_PATH;
  282. //1970 0x83AA7E80
  283. const bool res2 = GetRegistValue(hKey, "InstallTime", NULL, szValue, &dwLength);
  284. if (res2) {
  285. info.strInstallDate = szValue;
  286. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("InstallTime: %s", info.GetInstallTime().ToTimeString().GetData());
  287. }
  288. if (res1 && res2) {
  289. lResult = 0;
  290. }
  291. else {
  292. lResult = -1;
  293. }
  294. }
  295. else {
  296. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
  297. }
  298. RegCloseKey(hKey);
  299. return lResult;
  300. }
  301. static LONG GetSogouExecuteInfo(SogouRunVersionInfo& info, BOOL f32bit = TRUE)
  302. {
  303. HKEY hKey;
  304. LONG lResult = -1;
  305. PVOID oldValue = NULL;
  306. Wow64DisableWow64FsRedirection(&oldValue);
  307. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  308. lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, f32bit ? "SOFTWARE\\SogouPCIme" : "SOFTWARE\\WOW6432Node\\SogouPCIme", 0, dwFlag, &hKey);
  309. if (lResult == ERROR_SUCCESS) {
  310. TCHAR szVersion[MAX_PATH + 1] = { 0 }, szDefault[MAX_PATH + 1] = { 0 };
  311. DWORD dwLength = MAX_PATH;
  312. const bool res1 = GetRegistValue(hKey, "Version", NULL, szVersion, &dwLength);
  313. if (res1) info.strVersion = szVersion;
  314. const bool res2 = GetRegistValue(hKey, "", NULL, szDefault, &dwLength);
  315. if (res2) info.strInstallDir = szDefault;
  316. if (res1 && res2) {
  317. lResult = 0;
  318. }
  319. else {
  320. lResult = -1;
  321. }
  322. }
  323. else {
  324. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx(32bit=%d) error, Result=%ld.", __FUNCTION__, f32bit, lResult);
  325. }
  326. RegCloseKey(hKey);
  327. Wow64RevertWow64FsRedirection(oldValue);
  328. return lResult;
  329. }
  330. #endif //RVC_OS_LINUX
  331. ErrorCodeEnum GetSogouInstallInfo(SogouInstallInfo& info)
  332. {
  333. #if defined(RVC_OS_LINUX)
  334. info.state.dwInstalledStatus = Sogou_GetInstallStatus();
  335. info.state.strInstallDate = Sogou_GetInstallTime();
  336. info.program.strInstallDir = Sogou_GetInstallPath();
  337. info.program.strVersion = Sogou_GetVersion();
  338. if (info.program.strVersion.IsNullOrEmpty()) {
  339. info.program.strVersion = TryToGetSogouVersionEx().c_str();
  340. }
  341. const int maxTimes = 3;
  342. int curTimes = 0;
  343. while (info.state.dwInstalledStatus == 0 && info.program.strVersion.IsNullOrEmpty() && curTimes < maxTimes) {
  344. Sleep(1000);
  345. info.program.strVersion = Sogou_GetVersion();
  346. if (info.program.strVersion.IsNullOrEmpty()) {
  347. info.program.strVersion = TryToGetSogouVersionEx().c_str();
  348. }
  349. curTimes++;
  350. }
  351. #else
  352. GetSogouInstallState(info.state);
  353. BOOL is32Bit = Is64BitPlatform() ? FALSE : TRUE;
  354. if (ERROR_FILE_NOT_FOUND == GetSogouExecuteInfo(info.program, is32Bit))
  355. GetSogouExecuteInfo(info.program, !is32Bit);
  356. #endif //RVC_OS_LINUX
  357. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%d, %s, %s, %s"
  358. , info.state.dwInstalledStatus, info.state.strInstallDate.GetData()
  359. , info.program.strInstallDir.GetData(), info.program.strVersion.GetData());
  360. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("InstallTime: %s", info.state.GetInstallTime().ToTimeString().GetData());
  361. return info.IsInstalledSuccess() ? Error_Succeed : Error_InvalidState;
  362. }
  363. ErrorCodeEnum SetFileExecutePriviledge(LPCTSTR lpcszDirOrFilePath)
  364. {
  365. #if defined(RVC_OS_WIN)
  366. ErrorCodeEnum result(Error_NotSupport);
  367. #else
  368. ErrorCodeEnum result(Error_Succeed);
  369. if (ExistsDirA(lpcszDirOrFilePath)) {
  370. do {
  371. array_header_t* subs;
  372. subs = fileutil_get_sub_dirs_a(lpcszDirOrFilePath);
  373. if (subs) {
  374. for (int i = 0; i < subs->nelts; ++i) {
  375. char* dir = ARRAY_IDX(subs, i, char*);
  376. const char* dirname = &dir[strlen(lpcszDirOrFilePath) + 1];
  377. ErrorCodeEnum tmpResult = SetFileExecutePriviledge(dir);
  378. if (tmpResult != Error_Succeed) {
  379. toolkit_array_free2(subs);
  380. return tmpResult;
  381. }
  382. }
  383. }
  384. } while (false);
  385. do {
  386. array_header_t* subs;
  387. subs = fileutil_get_sub_files_a(lpcszDirOrFilePath);
  388. if (subs) {
  389. for (int i = 0; i < subs->nelts; ++i) {
  390. char* path = ARRAY_IDX(subs, i, char*);
  391. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  392. if (chmod(path, f_attrib) != 0) {
  393. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("chmod file priviledge failed, %s, %d", path, errno);
  394. toolkit_array_free2(subs);
  395. return Error_Unexpect;
  396. }
  397. }
  398. toolkit_array_free2(subs);
  399. }
  400. } while (false);
  401. }
  402. else if (ExistsFileA(lpcszDirOrFilePath)) {
  403. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  404. if (chmod(lpcszDirOrFilePath, f_attrib) != 0) {
  405. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("chmod file priviledge failed, %s, %d", lpcszDirOrFilePath, errno);
  406. return Error_Unexpect;
  407. }
  408. }
  409. else {
  410. result = Error_InvalidState;
  411. }
  412. #endif //RVC_OS_WIN
  413. return result;
  414. }
  415. void ResourceWatcherEntity::InstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req, ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  416. {
  417. ErrorCodeEnum result(Error_Succeed);
  418. ErrorCodeEnum tmpResult(Error_Succeed);
  419. CSimpleStringA tmpMsg(true);
  420. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2);
  421. 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));
  422. bool sogouInstalled = false;
  423. const bool doTryRestart = (ctx->Req.reserved1 != 1);
  424. if (ctx->Req.type == 1)
  425. {
  426. //安装搜狗输入法
  427. CSmartPointer<InstallSogouTask> sogouInstall = new InstallSogouTask(this);
  428. sogouInstall->ctx = ctx;
  429. GetFunction()->PostThreadPoolTask(sogouInstall.GetRawPointer());
  430. return;
  431. }
  432. else if (ctx->Req.type == 2) {//安装花了钱的字体
  433. #if defined(RVC_OS_WIN)
  434. tmpResult = Error_NotSupport;
  435. #else
  436. CSimpleStringA strAdDataDirPath(true);
  437. tmpResult = GetFunction()->GetPath("Ad", strAdDataDirPath);
  438. if (strAdDataDirPath.IsNullOrEmpty()) {
  439. strAdDataDirPath = "/opt/rvc/adData";
  440. }
  441. if (strAdDataDirPath.IsNullOrEmpty()) {
  442. tmpResult = Error_Unexpect;
  443. tmpMsg = "获取安装包路径Ad失败";
  444. }
  445. else {
  446. CSimpleStringA strInstallPkgPath = strAdDataDirPath + SPLIT_SLASH_STR "HYQiHei";
  447. if (!ExistsDirA(strInstallPkgPath)) {
  448. tmpMsg = CSimpleStringA::Format("%s 文件夹不存在", strInstallPkgPath.GetData());
  449. tmpResult = Error_NotExist;
  450. }
  451. else {
  452. CSimpleStringA strRunIniFilePath = strInstallPkgPath + SPLIT_SLASH_STR + "Run.ini";
  453. if (ExistsFileA(strRunIniFilePath)) {
  454. char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
  455. CSimpleStringA strInstallScriptFile(strInstallPkgPath + SPLIT_SLASH_STR + p);
  456. toolkit_free(p);
  457. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RunScript file: %s", strInstallScriptFile.GetData());
  458. if (ExistsFileA(strInstallScriptFile)) {
  459. do {
  460. char app[MAX_PATH] = { '\0' };
  461. tk_process_t* process = NULL;
  462. tk_process_option_t option;
  463. option.exit_cb = NULL;
  464. option.file = NULL;
  465. option.flags = 0;
  466. sprintf(app, "bash %s", strInstallScriptFile.GetData());
  467. option.params = app;
  468. const int res = process_spawn(&option, &process);
  469. if (0 == res) {
  470. FREE(process);
  471. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("execute {%s} suc", strInstallScriptFile.GetData());
  472. }
  473. else {
  474. tmpMsg = CSimpleStringA::Format("执行 %s 失败:%s", strInstallScriptFile.GetData(), toolkit_strerror(res));
  475. tmpResult = Error_Process;
  476. }
  477. } while (false);
  478. }
  479. else {
  480. tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
  481. tmpResult = Error_NotExist;
  482. }
  483. }
  484. else {
  485. tmpMsg = CSimpleStringA::Format("%s 文件不存在", strRunIniFilePath.GetData());
  486. tmpResult = Error_NotExist;
  487. }
  488. }
  489. }
  490. if (tmpResult == Error_Succeed) {
  491. ///**TODO(Gifur@10/21/2021): 二次校验 */
  492. }
  493. #endif //RVC_OS_WIN
  494. }
  495. else {
  496. result = Error_NotSupport;
  497. }
  498. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM) ("用户桌面安装:%s. result:%d.", tmpMsg.GetData(), tmpResult);
  499. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_INSTALL_THIRDPARTY,
  500. CSimpleStringA::Format("用户桌面安装:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  501. ctx->Ans.result = tmpResult;
  502. ctx->Ans.msg = tmpMsg;
  503. ctx->Answer(result);
  504. return;
  505. }
  506. void ResourceWatcherEntity::UninstallSogou(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
  507. {
  508. ErrorCodeEnum result(Error_Succeed);
  509. ErrorCodeEnum tmpResult(Error_Succeed);
  510. CSimpleStringA tmpMsg(true);
  511. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("to uninstall sogou input...");
  512. #if defined(RVC_OS_LINUX)
  513. CSimpleStringA strUninstallScriptFile(true);
  514. SogouInstallInfo info;
  515. do {
  516. ErrorCodeEnum ecGet = GetSogouInstallInfo(info);
  517. if (info.program.IsTSFVersion()) {
  518. CSimpleStringA shellScriptPath;
  519. GetFunction()->GetPath("Base", shellScriptPath);
  520. shellScriptPath += SPLIT_SLASH_STR;
  521. shellScriptPath += "res" SPLIT_SLASH_STR "RunScript" SPLIT_SLASH_STR;
  522. strUninstallScriptFile = shellScriptPath + "uninstall_tfs_sogouimebs.sh";
  523. if (!ExistsFileA(strUninstallScriptFile)) {
  524. tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strUninstallScriptFile.GetData());
  525. tmpResult = Error_InvalidState;
  526. break;
  527. }
  528. char app[MAX_PATH] = { '\0' };
  529. sprintf(app, "bash %s", strUninstallScriptFile.GetData());
  530. tmpResult = RunShellScript(app);
  531. if (tmpResult != 0) {
  532. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  533. }
  534. else {
  535. Sleep(300);
  536. }
  537. }
  538. else {
  539. CSimpleStringA strInstallPkgPath;
  540. tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
  541. if (tmpResult == Error_Succeed) {
  542. tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
  543. if (tmpResult != Error_Succeed) {
  544. tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
  545. tmpResult = Error_NoPrivilege;
  546. break;
  547. }
  548. const CSimpleStringA strShutdownScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "shutdown_service.sh";
  549. strUninstallScriptFile = strInstallPkgPath + SPLIT_SLASH_STR + "uninstall_sogouime.sh";
  550. if (!ExistsFileA(strShutdownScriptFile)) {
  551. tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strShutdownScriptFile.GetData());
  552. tmpResult = Error_InvalidState;
  553. break;
  554. }
  555. if (!ExistsFileA(strUninstallScriptFile)) {
  556. tmpMsg = CSimpleStringA::Format("%s 文件不存在!", strUninstallScriptFile.GetData());
  557. tmpResult = Error_InvalidState;
  558. break;
  559. }
  560. char app[MAX_PATH] = { '\0' };
  561. sprintf(app, "bash %s", strShutdownScriptFile.GetData());
  562. tmpResult = RunShellScript(app);
  563. if (tmpResult != 0) {
  564. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  565. }
  566. else {
  567. Sleep(300);
  568. sprintf(app, "bash %s", strUninstallScriptFile.GetData());
  569. tmpResult = RunShellScript(app);
  570. if (tmpResult != 0) {
  571. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  572. }
  573. else {
  574. Sleep(100);
  575. }
  576. }
  577. }
  578. else {
  579. tmpMsg = CSimpleStringA::Format(" 指定位置 [Ad] 找不到输入法安装包");
  580. tmpResult = Error_InvalidState;
  581. break;
  582. }
  583. }
  584. } while (false);
  585. #else
  586. SogouInstallInfo info;
  587. GetSogouInstallInfo(info);
  588. CSimpleStringA uninPath = info.program.strInstallDir + "\\" + info.program.strVersion + "\\Uninstall.exe";
  589. int startFlag = WinExec(uninPath.GetData(), SW_SHOWNORMAL);
  590. if (startFlag > 31) {
  591. tmpMsg = CSimpleStringA::Format("已执行搜狗卸载程序!路径:%s。", uninPath.GetData());
  592. }
  593. else {
  594. tmpMsg = CSimpleStringA::Format("执行搜狗卸载程序异常!路径:%s。", uninPath.GetData());
  595. tmpResult = Error_Unexpect;
  596. }
  597. #endif //RVC_OS_LINUX
  598. ctx->Ans.result = tmpResult;
  599. ctx->Ans.msg = tmpMsg;
  600. ctx->Answer(result);
  601. }
  602. void ResourceWatcherEntity::UninstallThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_UninstallThirdPartyProgram_Req, ResourceWatcherService_UninstallThirdPartyProgram_Ans>::Pointer ctx)
  603. {
  604. ErrorCodeEnum result(Error_Succeed);
  605. ErrorCodeEnum tmpResult(Error_Succeed);
  606. CSimpleStringA tmpMsg(true);
  607. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_UNINSTALL_THIRDPARTYPROGRAM,
  608. CSimpleStringA::Format("UninstallThirdPartyProgram: ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2));
  609. if (ctx->Req.type == 1) {
  610. //卸载搜狗输入法
  611. #if defined(RVC_OS_LINUX)
  612. UninstallSogouTask* sogouUninstall = new UninstallSogouTask(this);
  613. sogouUninstall->ctx = ctx;
  614. GetFunction()->PostThreadPoolTask(sogouUninstall);
  615. return;
  616. #else
  617. UninstallSogou(ctx);
  618. #endif //RVC_OS_LINUX
  619. }
  620. else {
  621. tmpMsg = CSimpleStringA::Format("接口调用参数错误");
  622. result = Error_NotSupport;
  623. }
  624. ctx->Ans.result = tmpResult;
  625. ctx->Ans.msg = tmpMsg;
  626. ctx->Answer(result);
  627. return;
  628. }
  629. void ResourceWatcherEntity::RestartThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_RestartThirdPartyProgram_Req, ResourceWatcherService_RestartThirdPartyProgram_Ans>::Pointer ctx)
  630. {
  631. ErrorCodeEnum result(Error_Succeed);
  632. ErrorCodeEnum tmpResult(Error_Succeed);
  633. CSimpleStringA tmpMsg(true);
  634. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_RESTART_THIRDPARTYPROGRAM,
  635. CSimpleStringA::Format("RestartThirdPartyProgram: ctx-req context: %d, %d, %d", ctx->Req.type, ctx->Req.reserved1, ctx->Req.reserved2));
  636. if (ctx->Req.type == 1)
  637. {
  638. SogouInstallInfo info;
  639. GetSogouInstallInfo(info);
  640. if (!info.program.IsTSFVersion())
  641. {
  642. //重启搜狗输入法
  643. #if defined(RVC_OS_WIN)
  644. CSimpleStringA csBinPath;
  645. ErrorCodeEnum eErrPath = GetFunction()->GetPath("Bin", csBinPath);
  646. CSimpleStringA startPath = csBinPath + "\\spScript\\SogouServStarter.bat";
  647. if (eErrPath != Error_Succeed) {
  648. tmpResult = Error_NotExist;
  649. tmpMsg = "获取重启脚本路径失败。";
  650. }
  651. else if (!ExistsFileA(startPath)) {
  652. tmpResult = Error_NotExist;
  653. tmpMsg = CSimpleStringA::Format("搜狗重启脚本不存在。");
  654. }
  655. else {
  656. CAutoArray<CSimpleStringA> pName(2);
  657. pName[0] = "SogouImeMon.exe";
  658. pName[1] = "SogouImeWebSrv.exe";
  659. if (!KillProcessFromName(pName[0]) || !KillProcessFromName(pName[1])) {
  660. tmpMsg = CSimpleStringA::Format("杀死当前搜狗进程失败。");
  661. tmpResult = Error_Unexpect;
  662. }
  663. else {
  664. STARTUPINFO si = { sizeof(si) };
  665. PROCESS_INFORMATION pi;
  666. si.dwFlags = STARTF_USESHOWWINDOW;
  667. si.wShowWindow = TRUE;
  668. char* cmdline = const_cast<LPSTR>(startPath.GetData());
  669. BOOL bRet = ::CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
  670. WaitForSingleObject(pi.hProcess, INFINITE);
  671. std::string res = DoCheckCertainProcessStatus(pName);
  672. if (res.size() > 0) {
  673. tmpMsg = CSimpleStringA::Format("已成功重启搜狗输入法进程!路径:%s。", startPath.GetData());
  674. }
  675. else {
  676. tmpMsg = CSimpleStringA::Format("重启搜狗进程失败!路径:%s。", startPath.GetData());
  677. tmpResult = Error_Unexpect;
  678. }
  679. }
  680. }
  681. #else
  682. static int old_process_id[2] = { -1, -1 };
  683. char* relate_processes[2] = { "sogouImeWebSrv", "sogouImeService" };
  684. int count = 3;
  685. alive_process_info processes[3];
  686. memset(processes, 0, sizeof(processes));
  687. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
  688. CAutoArray<CSimpleStringA> msgs(array_size(relate_processes));
  689. int cnt(0);
  690. for (int i = 0; i < array_size(relate_processes); ++i) {
  691. int k = -1;
  692. for (int j = 0; j < count; ++j) {
  693. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  694. k = j;
  695. break;
  696. }
  697. }
  698. if (k != -1) {
  699. cnt++;
  700. old_process_id[k] = processes[k].pid;
  701. std::string sucContent, failedContent;
  702. CSimpleStringA strCmd = CSimpleStringA::Format("kill -9 %d", old_process_id[k]);
  703. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  704. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  705. }
  706. }
  707. int cnt2(0);
  708. if (cnt > 0) {
  709. ///**TODO(Gifur@7/5/2022): 待优化处理 */
  710. Sleep(2000);
  711. int newCount = 3;
  712. int notSame = 0;
  713. vector<CSimpleStringA> tKillmsg;
  714. alive_process_info newProcesses[3];
  715. memset(newProcesses, 0, sizeof(newProcesses));
  716. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &newCount, newProcesses);
  717. for (int i = 0; i < array_size(relate_processes); ++i) {
  718. int k = -1;
  719. for (int j = 0; j < count; ++j) {
  720. if (strcmp(newProcesses[j].name, relate_processes[i]) == 0 && newProcesses[j].pid > 0) {
  721. k = j;
  722. break;
  723. }
  724. }
  725. if (k != -1) {
  726. cnt2++;
  727. if (newProcesses[k].pid != old_process_id[k]) {
  728. notSame++;
  729. }
  730. else {
  731. tmpResult = Error_Unexpect;
  732. CSimpleStringA tmsg = CSimpleStringA::Format("{杀死当前搜狗进程[%s]失败,pid[%d]。}",
  733. newProcesses[k].name, newProcesses[k].pid);
  734. tKillmsg.push_back(tmsg);
  735. }
  736. }
  737. }
  738. if (cnt2 == 0) {
  739. tmpMsg = "已杀死搜狗进程。但重启搜狗进程失败,请确认守护进程正常运行。";
  740. tmpResult = Error_Unexpect;
  741. }
  742. else {
  743. if (tKillmsg.size() != 0) {
  744. for (int i = 0; i < tKillmsg.size(); ++i) {
  745. tmpMsg += tKillmsg[i];
  746. }
  747. }
  748. else {
  749. tmpMsg = "已成功重启搜狗输入法进程。";
  750. }
  751. }
  752. }
  753. else {
  754. tmpMsg = "当前系统无搜狗进程,请确认已安装搜狗输入法,并重启计算机以尝试启动搜狗输入法!";
  755. tmpResult = Error_Unexpect;
  756. }
  757. #endif //RVC_OS_WIN
  758. }
  759. else
  760. {
  761. tmpResult = Error_NotSupport;
  762. tmpMsg = CSimpleStringA::Format("新搜狗版本,不支持重启功能");
  763. }
  764. }
  765. else
  766. {
  767. tmpResult = Error_Param;
  768. tmpMsg = CSimpleStringA::Format("接口调用参数错误。");
  769. }
  770. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM) ("用户桌面重启:%s. result:%d.", tmpMsg.GetData(), tmpResult);
  771. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHE_RESTART_THIRDPARTYPROGRAM,
  772. CSimpleStringA::Format("用户桌面重启:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  773. ctx->Ans.result = tmpResult;
  774. ctx->Ans.msg = tmpMsg;
  775. ctx->Answer(result);
  776. return;
  777. }
  778. void ResourceWatcherEntity::ProcessDetectThirdPartyProgram(SpReqAnsContext<ResourceWatcherService_ProcessDetectThirdPartyProgram_Req, ResourceWatcherService_ProcessDetectThirdPartyProgram_Ans>::Pointer ctx)
  779. {
  780. ErrorCodeEnum result(Error_Succeed);
  781. ErrorCodeEnum tmpResult(Error_Succeed);
  782. CSimpleStringA tmpMsg(true);
  783. std::string res("");
  784. if (ctx->Req.type == 1) {//检测搜狗输入法进程
  785. CAutoArray<CSimpleStringA> pName(2);
  786. #if defined(RVC_OS_WIN)
  787. pName[0] = "SogouImeMon.exe";
  788. pName[1] = "SogouImeWebSrv.exe";
  789. #else
  790. pName[0] = "sogouImeWebSrv";
  791. pName[1] = "sogouImeService";
  792. #endif //RVC_OS_WIN
  793. res = DoCheckCertainProcessStatus(pName);
  794. if (res.length() == 0) {
  795. tmpResult = Error_Failed;
  796. tmpMsg = "当前系统无搜狗进程";
  797. }
  798. else {
  799. tmpMsg = CSimpleStringA::Format("%s", res.c_str());
  800. }
  801. }
  802. ctx->Ans.result = tmpResult;
  803. ctx->Ans.msg = tmpMsg;
  804. ctx->Answer(result);
  805. return;
  806. }
  807. ErrorCodeEnum ResourceWatcherEntity::ReportSogouInstallState()
  808. {
  809. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  810. CSmartPointer<IConfigInfo> spConfig;
  811. ErrorCodeEnum err = spFunction->OpenConfig(Config_Run, spConfig);
  812. BOOL fNeedAlarm = TRUE;
  813. SogouInstallInfo info;
  814. GetSogouInstallInfo(info);
  815. CSimpleStringA strLastRecord(true);
  816. err = spConfig->ReadConfigValue("SogouInput", "LastInstalledRecord", strLastRecord);
  817. if (strLastRecord.IsNullOrEmpty() || info.Stringfy().Compare(strLastRecord) != 0) {
  818. spConfig->WriteConfigValue("SogouInput", "LastInstalledRecord", info.Stringfy());
  819. fNeedAlarm = TRUE;
  820. }
  821. else {
  822. //Report info per day.
  823. int nLastRecordTime = 0;
  824. err = spConfig->ReadConfigValueInt("SogouInput", "LastReportTime", nLastRecordTime);
  825. SYSTEMTIME stTaskTime = CSmallDateTime(nLastRecordTime).ToSystemTime();
  826. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Last Sogou install check time: %04d-%02d-%02d %02d:%02d:%02d",
  827. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  828. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  829. SYSTEMTIME stNow = {};
  830. GetLocalTime(&stNow);
  831. if (nLastRecordTime > 0 && stTaskTime.wYear == stNow.wYear
  832. && stTaskTime.wMonth == stNow.wMonth && stTaskTime.wDay == stNow.wDay) {
  833. //The Same Day
  834. fNeedAlarm = FALSE;
  835. }
  836. else {
  837. fNeedAlarm = TRUE;
  838. }
  839. }
  840. if (fNeedAlarm) {
  841. const DWORD dwUserCode = info.IsInstalledSuccess() ? LOG_ERR_SOGOU_INPUT_INSTALLED : LOG_ERR_SOGOU_INPUT_NOTINSTALLED;
  842. LogWarn(Severity_Low, Error_DataCheck, dwUserCode, info.Stringfy());
  843. //json上送,方便业务组解析
  844. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SogouVerStatus")("{\"install\":%d,\"program\":\"%s\",\"version\":\"%s\",\"installTime\":\"%s\"}",
  845. info.state.dwInstalledStatus, info.program.strInstallDir.GetData(),
  846. info.program.strVersion.GetData(), info.state.GetInstallTime().ToTimeString().GetData());
  847. spConfig->WriteConfigValue("SogouInput", "LastReportTime", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  848. }
  849. return Error_Succeed;
  850. }
  851. #if defined(RVC_OS_LINUX)
  852. /** No use for now [Gifur@2023109]*/
  853. std::vector<std::string> ResourceWatcherEntity::GetUserNameList(bool bExcludeRoot)
  854. {
  855. std::vector<std::string> results;
  856. array_header_t* arr;
  857. arr = fileutil_get_sub_dirs_a("/home");
  858. if (arr) {
  859. int i;
  860. for (i = 0; i < arr->nelts; ++i) {
  861. char szDestSubDir[256] = { 0 };
  862. char* dir = ARRAY_IDX(arr, i, char*);
  863. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("sub dir: %s", dir);
  864. strcpy(szDestSubDir, dir);
  865. strcat(szDestSubDir, SPLIT_SLASH_STR);
  866. strcat(szDestSubDir, ".config/kwinrc");
  867. if (ExistsFileA(szDestSubDir)) {
  868. std::string strUserName((const char*)&dir[strlen("/home/")]);
  869. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("username:%s", strUserName.c_str());
  870. if (strUserName.compare("root") != 0 || !bExcludeRoot) {
  871. results.push_back(strUserName);
  872. }
  873. }
  874. }
  875. toolkit_array_free2(arr);
  876. }
  877. return results;
  878. }
  879. #else
  880. void ResourceWatcherEntity::ReadFileContent()
  881. {
  882. vector<CSimpleStringA> msg;
  883. CSmartPointer<IConfigInfo> spCtSettingConfig;
  884. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  885. int fileCnt = 0;
  886. CSimpleStringA info("");
  887. do {
  888. fileCnt++;
  889. CSimpleStringA getFilename = CSimpleStringA::Format("ReadFileContentPath%d", fileCnt);
  890. CSimpleStringA path(""), part(""), key("");
  891. spCtSettingConfig->ReadConfigValue("ResourceWatcher", getFilename.GetData(), info);
  892. if (info.GetLength() == 0) {
  893. break;
  894. }
  895. CAutoArray<CSimpleStringA> arr = info.Split('|');
  896. int len = arr.GetCount();
  897. if (len != 3) {
  898. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Wrong ReadFile path config.");
  899. break;
  900. }
  901. path = arr[0];
  902. part = arr[1];
  903. key = arr[2];
  904. char szValue[MAX_PATH + 1] = _T("");
  905. long vLength = GetPrivateProfileString(part.GetData(), key.GetData(), "", szValue, 1024, path.GetData());
  906. CSimpleStringA tMsg = CSimpleStringA::Format("Read file [%s], Part = [%s], [%s] = [%s]",
  907. path.GetData(), part.GetData(), key.GetData(), szValue);
  908. msg.push_back(tMsg);
  909. } while (info.GetLength() != 0);
  910. if (msg.size() != 0) {
  911. CSimpleStringA fRes("|");
  912. for (int i = 0; i < msg.size(); ++i) {
  913. fRes = fRes + msg[i] + "|";
  914. }
  915. LogWarn(Severity_Low, Error_Debug, LOG_WARN_GET_FILE_CONTENT, fRes.GetData());
  916. }
  917. }
  918. long long GetDirSize(string dirPath)
  919. {
  920. long long fileLen = 0;
  921. long hFile = 0;
  922. //文件信息
  923. struct _finddata_t fileinfo;
  924. string p;
  925. if ((hFile = _findfirst(p.assign(dirPath).append("\\*").c_str(), &fileinfo)) != -1) {
  926. do {
  927. //如果是目录,迭代之
  928. //如果不是,加入列表
  929. if ((fileinfo.attrib & _A_SUBDIR)) {
  930. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  931. fileLen += GetDirSize(p.assign(dirPath).append("\\").append(fileinfo.name));
  932. }
  933. else {
  934. fileLen += fileinfo.size;
  935. }
  936. } while (_findnext(hFile, &fileinfo) == 0);
  937. _findclose(hFile);
  938. }
  939. return fileLen;
  940. }
  941. void ResourceWatcherEntity::ReadFileInfo()
  942. {
  943. //读取文件大小 修改时间
  944. vector<CSimpleStringA> msg;
  945. CSmartPointer<IConfigInfo> spCtSettingConfig;
  946. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  947. CSimpleStringA path("");
  948. int fileCnt = 0;
  949. do {
  950. fileCnt++;
  951. CSimpleStringA getFilename = CSimpleStringA::Format("ReadFileInfoPath%d", fileCnt);
  952. spCtSettingConfig->ReadConfigValue("ResourceWatcher", getFilename.GetData(), path);
  953. if (path.GetLength() == 0) {
  954. break;
  955. }
  956. time_t lCreateTime, lModifyTime;
  957. long long lFileLen;
  958. struct _finddata_t fileinfo;//文件信息读取结构
  959. long hFile = -1;
  960. hFile = _findfirst(path.GetData(), &fileinfo);
  961. if (hFile == -1) {
  962. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Get path [%s] file info failed.", path.GetData());
  963. continue;
  964. }
  965. _findclose(hFile);
  966. lCreateTime = fileinfo.time_create;
  967. lModifyTime = fileinfo.time_write;
  968. if ((fileinfo.attrib & _A_SUBDIR)) {
  969. lFileLen = GetDirSize(string(path.GetData()));
  970. }
  971. else {
  972. lFileLen = fileinfo.size;
  973. }
  974. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", lFileLen);
  975. if (lFileLen >= 1024 && lFileLen < (1024 * 1024)) {
  976. DOUBLE len = (DOUBLE)lFileLen / 1024;
  977. resLen = CSimpleStringA::Format("%.2f KB", len);
  978. }
  979. else if (lFileLen >= (1024 * 1024) && lFileLen < (1024 * 1024 * 1024)) {
  980. DOUBLE len = (DOUBLE)lFileLen / (1024 * 1024);
  981. resLen = CSimpleStringA::Format("%.2f MB", len);
  982. }
  983. else if (lFileLen >= (1024 * 1024 * 1024)) {
  984. DOUBLE len = (DOUBLE)lFileLen / (1024 * 1024 * 1024);
  985. resLen = CSimpleStringA::Format("%.2f GB", len);
  986. }
  987. tm* localCreate, * localWrite; //本地时间
  988. char bufCreate[128] = { 0 };
  989. char bufWrite[128] = { 0 };
  990. //所有的localtime返回的指针指向同一个static变量,非线程安全,后续的localtime结果会覆盖之前的
  991. localCreate = localtime(&lCreateTime); //转为本地时间
  992. strftime(bufCreate, 64, "%Y-%m-%d %H:%M:%S", localCreate);
  993. localWrite = localtime(&lModifyTime);
  994. strftime(bufWrite, 64, "%Y-%m-%d %H:%M:%S", localWrite);
  995. CSimpleStringA tMsg = CSimpleStringA::Format("文件[%s], 大小[%s], 创建时间 [%s], 最近修改时间[%s]",
  996. path.GetData(), resLen.GetData(), bufCreate, bufWrite);
  997. msg.push_back(tMsg);
  998. } while (path.GetLength() != 0);
  999. if (msg.size() > 0) {
  1000. CSimpleStringA fRes("|");
  1001. for (int i = 0; i < msg.size(); i++) {
  1002. fRes = fRes + msg[i] + "|";
  1003. }
  1004. LogWarn(Severity_Low, Error_Debug, LOG_WARN_READ_FILE_INFO, fRes.GetData());
  1005. }
  1006. return;
  1007. }
  1008. void ResourceWatcherEntity::ChcekDiskFileSpace()
  1009. {
  1010. CSimpleStringA path = "D:";
  1011. long long fileLen = 0;
  1012. long hFile = 0;
  1013. //文件信息
  1014. struct _finddata_t fileinfo;
  1015. string p;
  1016. if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
  1017. do {
  1018. //如果是目录,迭代之
  1019. //如果不是,加入列表
  1020. if ((fileinfo.attrib & _A_SUBDIR)) {
  1021. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  1022. fileLen = GetDirSize(p.assign(path).append("\\").append(fileinfo.name));
  1023. }
  1024. else {
  1025. fileLen = fileinfo.size;
  1026. }
  1027. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  1028. if (fileLen >= 1024 && fileLen < (1024 * 1024)) {
  1029. DOUBLE len = (DOUBLE)fileLen / 1024;
  1030. resLen = CSimpleStringA::Format("%.2f KB", len);
  1031. }
  1032. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024)) {
  1033. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  1034. resLen = CSimpleStringA::Format("%.2f MB", len);
  1035. }
  1036. else if (fileLen >= (1024 * 1024 * 1024)) {
  1037. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  1038. resLen = CSimpleStringA::Format("%.2f GB", len);
  1039. }
  1040. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]", p.assign(path).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  1041. } while (_findnext(hFile, &fileinfo) == 0);
  1042. _findclose(hFile);
  1043. }
  1044. }
  1045. BOOL ResourceWatcherEntity::KillProcessFromName(const CSimpleStringA& strProcessName)
  1046. {
  1047. #if defined(RVC_OS_WIN)
  1048. //创建进程快照(TH32CS_SNAPPROCESS表示创建所有进程的快照)
  1049. HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  1050. PROCESSENTRY32 pe;
  1051. pe.dwSize = sizeof(PROCESSENTRY32);
  1052. if (!Process32First(hSnapShot, &pe)) {
  1053. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("获取进程快照失败。");
  1054. return FALSE;
  1055. }
  1056. while (Process32Next(hSnapShot, &pe)) {
  1057. //pe.szExeFile获取当前进程的可执行文件名称
  1058. CSimpleStringA scTmp = pe.szExeFile;
  1059. if (!scTmp.Compare(strProcessName)) {
  1060. DWORD dwProcessID = pe.th32ProcessID;
  1061. HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID);
  1062. BOOL killed = ::TerminateProcess(hProcess, 0);
  1063. CloseHandle(hProcess);
  1064. if (killed) {
  1065. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SUCCESS! Kill process [%s], pid [%d].", strProcessName.GetData(), dwProcessID);
  1066. }
  1067. else {
  1068. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("FAILED! Kill process [%s], pid [%d].", strProcessName.GetData(), dwProcessID);
  1069. }
  1070. return killed;
  1071. }
  1072. }
  1073. return TRUE;
  1074. #else
  1075. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("It's not supported %s", __FUNCTION__);
  1076. return FALSE;
  1077. #endif //RVC_OS_WIN
  1078. }
  1079. #endif //RVC_OS_LINUX
  1080. void ResourceWatcherEntity::DoCheckSogouProcessStatus()
  1081. {
  1082. #if defined(RVC_OS_WIN)
  1083. if (lastUpgradeInstallTime != 0 && lastUpgradeSwitchTime != 0 && lastUpgradeInstallTime < lastUpgradeSwitchTime) //完整记录了上一次升级的时间
  1084. {
  1085. if (sogouChangeTime.size() != 0) {
  1086. for (int i = 0; i < sogouChangeWarn.size(); i++) {
  1087. if (newestSogouInstall) //搜狗升级
  1088. {
  1089. //正常不用告警
  1090. /* LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, (sogouChangeWarn[i] + "搜狗升级切换1").GetData());
  1091. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR040250A01Z102")("搜狗升级切换1");*/
  1092. }
  1093. else //非搜狗升级导致的退出
  1094. {
  1095. LogWarn(Severity_Middle, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, (sogouChangeWarn[i] + "异常切换1").GetData());
  1096. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR040250A01Z103").setResultCode("RTA5A08")("搜狗异常切换1");
  1097. }
  1098. }
  1099. sogouChangeTime.clear();
  1100. sogouChangeWarn.clear();
  1101. lastUpgradeInstallTime = 0;
  1102. lastUpgradeSwitchTime = 0;
  1103. newestSogouInstall = false;
  1104. return;
  1105. }
  1106. }
  1107. bool fCheck = false;
  1108. CAutoArray<CSimpleStringA> pName(2);
  1109. pName[0] = "SogouImeMon.exe";
  1110. pName[1] = "SogouImeWebSrv.exe";
  1111. int pSize = pName.GetCount();
  1112. static int old_process_id[2] = { -1, -1 };
  1113. static int firstCheck[2] = { -1, -1 };
  1114. CAutoArray<CSimpleStringA> msgs;
  1115. for (int i = 0; i < pSize; ++i) {
  1116. /*old_process_id.push_back(-1);*/
  1117. CSimpleStringA temp("");
  1118. msgs.Append(&temp, 0, 1);
  1119. }
  1120. int cnt(0);
  1121. PROCESSENTRY32 pe32;
  1122. pe32.dwSize = sizeof(pe32);
  1123. //获得系统进程快照的句柄
  1124. HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  1125. if (hProcessSnap == INVALID_HANDLE_VALUE) {
  1126. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  1127. return;
  1128. }
  1129. for (int i = 0; i < pSize; ++i) {
  1130. int position = -1;
  1131. BOOL bProcess = Process32First(hProcessSnap, &pe32);
  1132. while (bProcess) {
  1133. if (strcmp(pe32.szExeFile, pName[i].GetData()) == 0) {
  1134. position = 1;
  1135. break;
  1136. }
  1137. bProcess = Process32Next(hProcessSnap, &pe32);
  1138. }
  1139. if (position != -1 && old_process_id[i] == -1) {
  1140. if (firstCheck[i] == -1) {
  1141. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Sougou first check!");
  1142. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
  1143. , pName[i].GetData(), pe32.th32ProcessID);
  1144. firstCheck[i] = 1;
  1145. fCheck = true;
  1146. sogouProcessRun = 1;
  1147. }
  1148. old_process_id[i] = pe32.th32ProcessID;
  1149. }
  1150. else if (position != -1 && (pe32.th32ProcessID != old_process_id[i])) {
  1151. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1152. , pName[i].GetData(), old_process_id[i], pe32.th32ProcessID);
  1153. old_process_id[i] = pe32.th32ProcessID;
  1154. }
  1155. else if (position == -1 && old_process_id[i] > 0) {
  1156. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1157. , pName[i].GetData(), old_process_id[i], 0);
  1158. old_process_id[i] = 0;
  1159. }
  1160. }
  1161. std::string uploadInfo("");
  1162. if (cnt > 0) {
  1163. if (cnt > 1) {
  1164. uploadInfo = "{";
  1165. }
  1166. for (int i = 0; i < cnt; ++i) {
  1167. if (i != 0) {
  1168. uploadInfo += ",";
  1169. }
  1170. uploadInfo += msgs[i].GetData();
  1171. }
  1172. if (cnt > 1) {
  1173. uploadInfo += "}";
  1174. }
  1175. if (fCheck) //首次检测
  1176. {
  1177. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_FIRSTCHECK, uploadInfo.c_str()); //第一次检测
  1178. lastUpgradeInstallTime = 0;
  1179. lastUpgradeSwitchTime = 0;
  1180. newestSogouInstall = false;
  1181. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR040250A01Z101")("搜狗首次检测");
  1182. }
  1183. else if (newestSogouInstall) {
  1184. //LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, (uploadInfo + "搜狗升级切换2").c_str()); //升级安装导致的进程切换视为正常退出
  1185. lastUpgradeInstallTime = 0;
  1186. lastUpgradeSwitchTime = 0;
  1187. newestSogouInstall = false;
  1188. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR040250A01Z102")("搜狗升级切换2");
  1189. }
  1190. else if (time(0) <= lastSogouChangeEndTime) //lastSogouChangeEndTime为状态'I'结束后的60秒
  1191. {
  1192. //LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, (uploadInfo + "搜狗升级切换3").c_str()); //升级安装导致的进程切换视为正常退出
  1193. lastUpgradeInstallTime = 0;
  1194. lastUpgradeSwitchTime = 0;
  1195. newestSogouInstall = false;
  1196. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR040250A01Z102")("搜狗升级切换3");
  1197. }
  1198. else {
  1199. if (lastUpgradeInstallTime == 0 && lastUpgradeSwitchTime == 0)//非升级时段
  1200. {
  1201. LogWarn(Severity_Middle, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, (uploadInfo + "异常切换3").c_str()); //其他情况下的进程切换视为异常退出
  1202. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode("QLR040250A01Z103").setResultCode("RTA5A08")("搜狗异常切换3");
  1203. }
  1204. else //升级时段,'I'安装中,但是还没有'S'切换时,出现了搜狗进程切换
  1205. {
  1206. sogouChangeWarn.push_back(CSimpleStringA(uploadInfo.c_str()));
  1207. sogouChangeTime.push_back(time(0));
  1208. }
  1209. }
  1210. }
  1211. else {
  1212. SogouInstallInfo info;
  1213. GetSogouInstallInfo(info);
  1214. if (!info.program.IsTSFVersion()) //如果是旧版本搜狗,则检测是否启动
  1215. {
  1216. if (sogouProcessRun == 0)//进程未运行
  1217. {
  1218. LogWarn(Severity_Middle, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, "搜狗进程未启动!");
  1219. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setLogCode("QLR040250A01Z101").setResultCode("RTA5A01")("搜狗未启动!");
  1220. sogouProcessRun = -1; //进程未启动告警一次即可
  1221. }
  1222. }
  1223. }
  1224. CloseHandle(hProcessSnap);
  1225. #else
  1226. static int old_process_id[2] = { -1, -1 };
  1227. char* relate_processes[2] = { "sogouImeWebSrv", "sogouImeService" };
  1228. int count = 3;
  1229. alive_process_info processes[3];
  1230. memset(processes, 0, sizeof(processes));
  1231. osutil_detect_unique_app(relate_processes, array_size(relate_processes), &count, processes);
  1232. CAutoArray<CSimpleStringA> msgs(array_size(relate_processes));
  1233. int cnt(0);
  1234. for (int i = 0; i < array_size(relate_processes); ++i) {
  1235. int k = -1;
  1236. for (int j = 0; j < count; ++j) {
  1237. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  1238. k = j;
  1239. break;
  1240. }
  1241. }
  1242. if (k != -1 && old_process_id[i] == -1) {
  1243. old_process_id[i] = processes[k].pid;
  1244. }
  1245. else if (k != -1 && (processes[k].pid != old_process_id[i])) {
  1246. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1247. , relate_processes[i], old_process_id[i], processes[k].pid);
  1248. old_process_id[i] = processes[k].pid;
  1249. }
  1250. else if (k == -1 && old_process_id[i] != 0) {
  1251. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1252. , relate_processes[i], old_process_id[i], 0);
  1253. old_process_id[i] = 0;
  1254. }
  1255. }
  1256. if (cnt > 0) {
  1257. std::string uploadInfo("");
  1258. if (cnt > 1) {
  1259. uploadInfo = "{";
  1260. }
  1261. for (int i = 0; i < cnt; ++i) {
  1262. if (i != 0) {
  1263. uploadInfo += ",";
  1264. }
  1265. uploadInfo += msgs[i].GetData();
  1266. }
  1267. if (cnt > 1) {
  1268. uploadInfo += "}";
  1269. }
  1270. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_SOGOU_PROCESS_STATUS_CHANGE, uploadInfo.c_str());
  1271. }
  1272. #endif //RVC_OS_WIN
  1273. }
  1274. #if defined(RVC_OS_LINUX)
  1275. ErrorCodeEnum ResourceWatcherEntity::GetSogouPkgDirPath(CSimpleStringA& strPkgPath)
  1276. {
  1277. CSimpleStringA strAdDataDirPath(true);
  1278. CSimpleStringA strInstallPkgPath(true);
  1279. ErrorCodeEnum result = GetFunction()->GetPath("Ad", strAdDataDirPath);
  1280. if (strAdDataDirPath.IsNullOrEmpty()) {
  1281. strAdDataDirPath = "/opt/rvc/adData";
  1282. }
  1283. if (strAdDataDirPath.IsNullOrEmpty()) {
  1284. return Error_Unexpect;
  1285. }
  1286. array_header_t* subs;
  1287. subs = fileutil_get_sub_dirs_a(strAdDataDirPath);
  1288. if (subs) {
  1289. for (int i = 0; i < subs->nelts; ++i) {
  1290. char* dir = ARRAY_IDX(subs, i, char*);
  1291. const char* dirname = &dir[strAdDataDirPath.GetLength() + 1];
  1292. if (CSimpleStringA(dirname).IsStartWith("sogou", true) || CSimpleStringA(dirname).IsStartWith("uos-sogou", true)) {
  1293. if (strInstallPkgPath.IsNullOrEmpty()) {
  1294. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("found it: %s", dir);
  1295. strInstallPkgPath = dir;
  1296. }
  1297. else if (strInstallPkgPath.Compare(dir) < 0) {
  1298. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("replace %s with %s", (LPCTSTR)strInstallPkgPath, dir);
  1299. strInstallPkgPath = dir;
  1300. }
  1301. }
  1302. }
  1303. toolkit_array_free2(subs);
  1304. }
  1305. if (strInstallPkgPath.IsNullOrEmpty()) {
  1306. return Error_NotExist;
  1307. }
  1308. strPkgPath = strInstallPkgPath;
  1309. return Error_Succeed;
  1310. }
  1311. #endif //RVC_OS_LINUX
  1312. ErrorCodeEnum ResourceWatcherEntity::RunShellScript(LPCTSTR cmdline)
  1313. {
  1314. #if defined(RVC_OS_WIN)
  1315. return Error_NotSupport;
  1316. #else
  1317. char app[MAX_PATH] = { '\0' };
  1318. char szldPath[1024] = { '\0' };
  1319. size_t szldLen = 1023;
  1320. tk_process_t* process = NULL;
  1321. tk_process_option_t option;
  1322. const int ldRet = toolkit_getenv("LD_LIBRARY_PATH", szldPath, &szldLen);
  1323. if (ldRet == 0) {
  1324. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get library path: %s", szldPath);
  1325. toolkit_unsetenv("LD_LIBRARY_PATH");
  1326. }
  1327. else {
  1328. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetEnv of LD_LIBRARY_PATH failed: %s", toolkit_strerror(ldRet));
  1329. }
  1330. option.exit_cb = NULL;
  1331. option.file = NULL;
  1332. option.flags = 0;
  1333. option.params = (char*)cmdline;
  1334. const int res = process_spawn(&option, &process);
  1335. if (ldRet == 0) {
  1336. toolkit_setenv("LD_LIBRARY_PATH", szldPath);
  1337. }
  1338. if (0 == res) {
  1339. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("execute {%s}, pid: %d, and wait ...", cmdline, process->pid);
  1340. int status;
  1341. while (process->pid > 0 && waitpid(process->pid, &status, 0) < 0) {
  1342. if (errno != EINTR) {
  1343. status = -1;
  1344. break;
  1345. }
  1346. }
  1347. if (WIFEXITED(status)) {
  1348. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("normal terminal. exit status: %d", WEXITSTATUS(status));
  1349. }
  1350. else if (WIFSIGNALED(status)) {
  1351. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("abnormal terminal, signal: %d", WTERMSIG(status));
  1352. }
  1353. else if (WIFSTOPPED(status)) {
  1354. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cihild stop, signal: %d", WSTOPSIG(status));
  1355. }
  1356. FREE(process);
  1357. return Error_Succeed;
  1358. }
  1359. else {
  1360. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("execute {%s} failed: %d", cmdline, res);
  1361. return Error_Unexpect;
  1362. }
  1363. #endif //RVC_OS_WIN
  1364. }
  1365. std::string ResourceWatcherEntity::DoCheckCertainProcessStatus(const CAutoArray<CSimpleStringA>& pName)
  1366. {
  1367. const int pSize = pName.GetCount();
  1368. vector<int> old_process_id;
  1369. CAutoArray<CSimpleStringA> msgs;
  1370. #if defined(RVC_OS_WIN)
  1371. for (int i = 0; i < pSize; ++i) {
  1372. old_process_id.push_back(-1);
  1373. CSimpleStringA temp("");
  1374. msgs.Append(&temp, 0, 1);
  1375. }
  1376. int cnt(0);
  1377. PROCESSENTRY32 pe32;
  1378. pe32.dwSize = sizeof(pe32);
  1379. HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  1380. if (hProcessSnap == INVALID_HANDLE_VALUE) {
  1381. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  1382. return "";
  1383. }
  1384. for (int i = 0; i < pSize; ++i) {
  1385. int position = -1;
  1386. BOOL bProcess = Process32First(hProcessSnap, &pe32);
  1387. while (bProcess) {
  1388. if (strcmp(pe32.szExeFile, pName[i].GetData()) == 0) {
  1389. position = 1;
  1390. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("pname: %s, pid: %d.", pe32.szExeFile, pe32.th32ProcessID);
  1391. break;
  1392. }
  1393. bProcess = Process32Next(hProcessSnap, &pe32);
  1394. }
  1395. if (position != -1 && old_process_id[i] == -1) {
  1396. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
  1397. , pName[i].GetData(), pe32.th32ProcessID);
  1398. old_process_id[i] = pe32.th32ProcessID;
  1399. }
  1400. else if (position != -1 && (pe32.th32ProcessID != old_process_id[i])) {
  1401. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1402. , pName[i].GetData(), old_process_id[i], pe32.th32ProcessID);
  1403. old_process_id[i] = pe32.th32ProcessID;
  1404. }
  1405. else if (position == -1 && old_process_id[i] > 0) {
  1406. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1407. , pName[i].GetData(), old_process_id[i], 0);
  1408. old_process_id[i] = 0;
  1409. }
  1410. }
  1411. CloseHandle(hProcessSnap);
  1412. #else
  1413. alive_process_info* processes = new alive_process_info[pSize];
  1414. char** relate_processes = new char* [pSize];
  1415. int count = pSize;
  1416. for (int i = 0; i < pSize; ++i) {
  1417. old_process_id.push_back(-1);
  1418. CSimpleStringA temp("");
  1419. msgs.Append(&temp, 0, 1);
  1420. relate_processes[i] = const_cast<char*>(pName[i].GetData());
  1421. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("relate_process name: %s.", relate_processes[i]);
  1422. }
  1423. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("COUNT = %d!", count);
  1424. osutil_detect_unique_app(relate_processes, pSize, &count, processes);
  1425. int cnt(0);
  1426. for (int i = 0; i < pSize; ++i) {
  1427. int k = -1;
  1428. for (int j = 0; j < count; ++j) {
  1429. if (strcmp(processes[j].name, relate_processes[i]) == 0) {
  1430. k = j;
  1431. break;
  1432. }
  1433. }
  1434. if (k != -1 && old_process_id[i] == -1) {
  1435. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"pid\":%d}"
  1436. , relate_processes[i], processes[k].pid);
  1437. old_process_id[i] = processes[k].pid;
  1438. }
  1439. else if (k != -1 && (processes[k].pid != old_process_id[i])) {
  1440. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1441. , relate_processes[i], old_process_id[i], processes[k].pid);
  1442. old_process_id[i] = processes[k].pid;
  1443. }
  1444. else if (k == -1 && old_process_id[i] != 0) {
  1445. msgs[cnt++] = CSimpleStringA::Format("{\"name\":\"%s\", \"prev\":%d, \"pid\":%d}"
  1446. , relate_processes[i], old_process_id[i], 0);
  1447. old_process_id[i] = 0;
  1448. }
  1449. }
  1450. #endif //RVC_OS_WIN
  1451. std::string uploadInfo("");
  1452. if (cnt > 0) {
  1453. if (cnt > 1) {
  1454. uploadInfo = "{";
  1455. }
  1456. for (int i = 0; i < cnt; ++i) {
  1457. if (i != 0) {
  1458. uploadInfo += ",";
  1459. }
  1460. uploadInfo += msgs[i].GetData();
  1461. }
  1462. if (cnt > 1) {
  1463. uploadInfo += "}";
  1464. }
  1465. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s", uploadInfo.c_str());
  1466. }
  1467. return uploadInfo;
  1468. }
  1469. //检测安全软件进程:亚信、联软、锐眼
  1470. void ResourceWatcherEntity::SecProcCheck()
  1471. {
  1472. //默认检测windows, 若后续需要在UOS检测,则通过集中配置读取修改名称
  1473. CSimpleStringA yaXin = "NTRtScan.exe"; //亚信
  1474. CSimpleStringA lianRuan = "UniAccessAgent.exe"; //联软
  1475. CSimpleStringA ruiYan = "RuiYan.exe"; //锐眼
  1476. #ifdef RVC_OS_LINUX
  1477. CSmartPointer<IConfigInfo> spCtSettingConfig;
  1478. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  1479. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "YaXinProcUOS", yaXin);
  1480. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "LianRuanProcUOS", lianRuan);
  1481. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "RuiYanProcUOS", ruiYan);
  1482. #endif // RVC_OS_WIN
  1483. CAutoArray<CSimpleStringA> tArray(&yaXin, 1);
  1484. //Dbg("Security check name:%s.Size = %d.", tArray[0].GetData(), tArray.GetCount());
  1485. if (yaXin.GetLength() != 0)
  1486. {
  1487. string yaXinRe = DoCheckCertainProcessStatus(tArray);
  1488. if (!yaXinRe.empty())
  1489. {
  1490. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SUEPROCCHECK_YAXIN, yaXinRe.c_str());
  1491. }
  1492. }
  1493. if (lianRuan.GetLength() != 0)
  1494. {
  1495. tArray[0] = lianRuan;
  1496. string lianRuanRe = DoCheckCertainProcessStatus(tArray);
  1497. if (!lianRuanRe.empty())
  1498. {
  1499. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SUEPROCCHECK_LIANRUAN, lianRuanRe.c_str());
  1500. }
  1501. }
  1502. if (ruiYan.GetLength() != 0)
  1503. {
  1504. tArray[0] = ruiYan;
  1505. string ruiYanRe = DoCheckCertainProcessStatus(tArray);
  1506. if (!ruiYanRe.empty())
  1507. {
  1508. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SUEPROCCHECK_RUIYAN, ruiYanRe.c_str());
  1509. }
  1510. }
  1511. }
  1512. bool ResourceWatcherEntity::is_str_utf8(const char* str)
  1513. {
  1514. unsigned int nBytes = 0;//UFT8可用1-6个字节编码,ASCII用一个字节
  1515. unsigned char chr = *str;
  1516. bool bAllAscii = true;
  1517. for (unsigned int i = 0; str[i] != '\0'; ++i) {
  1518. chr = *(str + i);
  1519. //判断是否ASCII编码,如果不是,说明有可能是UTF8,ASCII用7位编码,最高位标记为0,0xxxxxxx
  1520. if (nBytes == 0 && (chr & 0x80) != 0) {
  1521. bAllAscii = false;
  1522. }
  1523. if (nBytes == 0) {
  1524. //如果不是ASCII码,应该是多字节符,计算字节数
  1525. if (chr >= 0x80) {
  1526. if (chr >= 0xFC && chr <= 0xFD) {
  1527. nBytes = 6;
  1528. }
  1529. else if (chr >= 0xF8) {
  1530. nBytes = 5;
  1531. }
  1532. else if (chr >= 0xF0) {
  1533. nBytes = 4;
  1534. }
  1535. else if (chr >= 0xE0) {
  1536. nBytes = 3;
  1537. }
  1538. else if (chr >= 0xC0) {
  1539. nBytes = 2;
  1540. }
  1541. else {
  1542. return false;
  1543. }
  1544. nBytes--;
  1545. }
  1546. }
  1547. else {
  1548. if ((chr & 0xC0) != 0x80) {
  1549. return false;
  1550. }
  1551. nBytes--;
  1552. }
  1553. }
  1554. if (nBytes != 0) {
  1555. return false;
  1556. }
  1557. if (bAllAscii) { //如果全部都是ASCII, 也是UTF8
  1558. return true;
  1559. }
  1560. return true;
  1561. }
  1562. ErrorCodeEnum ResourceWatcherEntity::UnzipPack(const char* unZipPackName)
  1563. {
  1564. CSimpleStringA strDownloadsPath;
  1565. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  1566. ErrorCodeEnum rc = spFunction->GetPath("Downloads", strDownloadsPath);
  1567. if (rc != Error_Succeed) {
  1568. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,get Downloads Path is fail");
  1569. return Error_Unexpect;
  1570. }
  1571. CSimpleStringA strTempPath;
  1572. ErrorCodeEnum rc2 = GetFunction()->GetPath("Temp", strTempPath);
  1573. assert(rc2 == Error_Succeed);
  1574. CSimpleStringA strUnzipDir;
  1575. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strTempPath.GetData(), unZipPackName);
  1576. if (strUnzipDir.IsEndWith(".zip") || strUnzipDir.IsEndWith(".cab")) {
  1577. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  1578. }
  1579. // 如目标目录存在,则先删除
  1580. if (ExistsDirA(strUnzipDir)) {
  1581. if (!RemoveDirRecursiveA(strUnzipDir)) {
  1582. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("remove old unzip dir [%s] fail", strUnzipDir.GetData()));
  1583. return Error_NotExist;
  1584. }
  1585. }
  1586. // 创建临时解压目录
  1587. CreateDirA(strUnzipDir.GetData(), true);
  1588. if (!ExistsDirA(strUnzipDir)) {
  1589. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,create temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), GetLastError());
  1590. return Error_Unexpect;
  1591. }
  1592. CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  1593. //升级包是否存在
  1594. if (!ExistsFileA(strZipFile)) {
  1595. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
  1596. return Error_NotExist;
  1597. }
  1598. #if defined(RVC_OS_LINUX)
  1599. string zipFileStr = strZipFile.GetData();
  1600. string zipTempDir = strUnzipDir.GetData();
  1601. if (UnZipToDir(zipFileStr, zipTempDir) != 0) {
  1602. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("unzip pack [%s] fail", zipFileStr.c_str()));
  1603. return Error_NotExist;
  1604. }
  1605. #else
  1606. // 设定解压临时目录
  1607. char szOldPath[MAX_PATH] = {};
  1608. GetCurrentDirectoryA(MAX_PATH, szOldPath);
  1609. //设置当前目录为主目录
  1610. if (!SetCurrentDirectoryA(strUnzipDir.GetData())) {
  1611. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,SetCurrentDirectoryA dir [%s] fail,err=%d", strUnzipDir.GetData(), GetLastError());
  1612. return Error_Unexpect;
  1613. }
  1614. // 解压
  1615. HZIP hz = OpenZip((void*)(const char*)strZipFile, 0, ZIP_FILENAME);
  1616. if (hz == 0) {
  1617. SetCurrentDirectoryA(szOldPath);
  1618. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("open zip file [%s] fail", unZipPackName).GetData());
  1619. return Error_Unexpect;
  1620. }
  1621. ZIPENTRY ze;
  1622. ZRESULT zrc = GetZipItemA(hz, -1, &ze);
  1623. if (zrc == ZR_OK) {
  1624. int numitems = ze.index;
  1625. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("zip entry count is %d", ze.index);
  1626. for (int i = 0; i < numitems; i++) {
  1627. zrc = GetZipItemA(hz, i, &ze);
  1628. if (zrc == ZR_OK) {
  1629. //兼容压缩包里面中文名称是utf8编码
  1630. if (is_str_utf8(ze.name)) {
  1631. char* pGBK = SP::Module::Util::ConvertUtf8ToGBK((const char*)ze.name);
  1632. zrc = UnzipItem(hz, i, pGBK, 0, ZIP_FILENAME);
  1633. if (zrc == ZR_OK) {
  1634. delete[] pGBK;
  1635. }
  1636. else {
  1637. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip [%s] UTF8 item fail,result=0x%X", pGBK, (int)zrc);
  1638. delete[] pGBK;
  1639. break;
  1640. }
  1641. }
  1642. else {
  1643. zrc = UnzipItem(hz, i, ze.name, 0, ZIP_FILENAME);
  1644. if (zrc != ZR_OK) {
  1645. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip [%s] GBK item fail,result=0x%X", ze.name, (int)zrc);
  1646. break;
  1647. }
  1648. }
  1649. }
  1650. else {
  1651. //出错,退出
  1652. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip GetZipItemA [%d] item fail,fail=0x%X", i, (int)zrc);
  1653. break;
  1654. }
  1655. }
  1656. CloseZip(hz);
  1657. }
  1658. else {
  1659. CloseZip(hz);
  1660. }
  1661. // 恢复当前目录
  1662. SetCurrentDirectoryA(szOldPath);
  1663. if (zrc != ZR_OK) {
  1664. return Error_Exception;
  1665. }
  1666. #endif //RVC_OS_LINUX
  1667. return Error_Succeed;
  1668. }
  1669. ErrorCodeEnum ResourceWatcherEntity::DeleteUnzipDir()
  1670. {
  1671. CSimpleStringA strDownloadsPath;
  1672. CSmartPointer<IEntityFunction> spFunction = GetFunction();
  1673. ErrorCodeEnum rc = spFunction->GetPath("Downloads", strDownloadsPath);
  1674. if (rc != Error_Succeed) {
  1675. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir is fail,get Downloads Path is fail");
  1676. return Error_Unexpect;
  1677. }
  1678. CSimpleStringA sogouTest = "sogoutest";
  1679. CSimpleStringA strUnzipDir = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), sogouTest.GetData());
  1680. //解压去除了.zip后缀
  1681. if (strUnzipDir.IsEndWith(".zip")) {
  1682. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  1683. }
  1684. // 解压目录是否存在,存在则删除
  1685. if (ExistsDirA(strUnzipDir.GetData())) {
  1686. if (!RemoveDirRecursiveA(strUnzipDir.GetData())) {
  1687. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), (int)GetLastError());
  1688. return Error_Unexpect;
  1689. }
  1690. else {
  1691. return Error_Succeed;
  1692. }
  1693. }
  1694. return Error_Succeed;
  1695. }
  1696. void ResourceWatcherEntity::GetThirdPartyInstallState(SpReqAnsContext<ResourceWatcherService_GetThirdPartyInstallState_Req, ResourceWatcherService_GetThirdPartyInstallState_Ans>::Pointer ctx)
  1697. {
  1698. ErrorCodeEnum result(Error_Succeed);
  1699. if (ctx->Req.mode == 1) {//查看搜狗输入法安装状态
  1700. SogouInstallInfo info;
  1701. GetSogouInstallInfo(info);
  1702. ctx->Ans.status = info.IsInstalledSuccess() ? 1 : 0;
  1703. ctx->Ans.path = info.program.strInstallDir;
  1704. ctx->Ans.version = info.program.strVersion;
  1705. ctx->Ans.reserverd1 = info.state.GetInstallTime().ToTimeString();
  1706. ctx->Ans.reserverd2 = "";
  1707. ctx->Ans.reserverd3 = info.program.IsTSFVersion() ? 1 : 0;
  1708. ctx->Ans.reserverd4 = 0;
  1709. }
  1710. else if (ctx->Req.mode == 2) { //检测字体的安装状态
  1711. #if defined(_MSC_VER)
  1712. result = Error_NotImpl;
  1713. #else
  1714. CSimpleStringA strFontDir("/usr/share/fonts/truetype");
  1715. CSimpleStringA strRVCTTFsDir(strFontDir + SPLIT_SLASH_STR + "RVCTTFs");
  1716. if (!ExistsDirA(strRVCTTFsDir)) {
  1717. ctx->Ans.status = 0;
  1718. ctx->Ans.reserverd1 = CSimpleStringA::Format("%s 文件夹不存在", (LPCTSTR)strRVCTTFsDir);
  1719. }
  1720. else {
  1721. CSimpleStringA ttf1 = strRVCTTFsDir + SPLIT_SLASH_STR + "HYQiHei-55S.ttf";
  1722. CSimpleStringA ttf2 = strRVCTTFsDir + SPLIT_SLASH_STR + "HYQiHei-65S.ttf";
  1723. CSimpleStringA ttfdir = strRVCTTFsDir + SPLIT_SLASH_STR + "fonts.dir";
  1724. CSimpleStringA ttfscale = strRVCTTFsDir + SPLIT_SLASH_STR + "fonts.scale";
  1725. CSimpleStringA ttfuuid = strRVCTTFsDir + SPLIT_SLASH_STR + ".uuid";
  1726. int existCheck = 0;
  1727. if (!ExistsFileA(ttf1)) {
  1728. existCheck |= 1;
  1729. }
  1730. if (!ExistsFileA(ttf2)) {
  1731. existCheck |= 2;
  1732. }
  1733. if (!ExistsFileA(ttfdir)) {
  1734. existCheck |= 4;
  1735. }
  1736. if (!ExistsFileA(ttfscale)) {
  1737. existCheck |= 8;
  1738. }
  1739. if (!ExistsFileA(ttfuuid)) {
  1740. existCheck |= 16;
  1741. }
  1742. if (existCheck != 0) {
  1743. ctx->Ans.status = 0;
  1744. ctx->Ans.reserverd1 = CSimpleStringA::Format("安装文件不存在:0x%X", existCheck);
  1745. }
  1746. else {
  1747. ctx->Ans.status = 1;
  1748. ctx->Ans.reserverd1 = "";
  1749. ctx->Ans.path = strRVCTTFsDir;
  1750. ctx->Ans.version = "";
  1751. }
  1752. }
  1753. #endif //_MSC_VER
  1754. }
  1755. else if (ctx->Req.mode == 3) { //自定义安装
  1756. #if defined(RVC_OS_WIN)
  1757. result = Error_NotSupport;
  1758. #else
  1759. if (ctx->Req.reserverd3.IsNullOrEmpty()) {
  1760. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("the req rerverd3 is empty.");
  1761. result = Error_Param;
  1762. }
  1763. else {
  1764. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to check %s 's install status...", ctx->Req.reserverd3.GetData());
  1765. CSimpleStringA strSoftwareName(ctx->Req.reserverd3);
  1766. CSimpleStringA strSoftwareVersion(ctx->Req.reserverd4);
  1767. CSimpleStringA runItem = CSimpleStringA::Format("dpkg -l | grep %s | awk '{print $3}'", strSoftwareName.GetData());
  1768. std::string additional("");
  1769. std::string succStr, errStr;
  1770. std::string runStr(runItem.GetData());
  1771. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  1772. if (succStr.empty()) {
  1773. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s is not installed", strSoftwareName.GetData());
  1774. ctx->Ans.status = 0;
  1775. }
  1776. else {
  1777. succStr = SP::Utility::ToTrim(succStr);
  1778. if (strSoftwareVersion.IsNullOrEmpty() || strSoftwareVersion.Compare(succStr.c_str()) == 0) {
  1779. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s is installed, version: %s", strSoftwareName.GetData(), succStr.c_str());
  1780. ctx->Ans.status = 1;
  1781. }
  1782. else {
  1783. ctx->Ans.status = 2;
  1784. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s is installed, but the version<%s> is not the dream one<%s>"
  1785. , strSoftwareName.GetData(), succStr.c_str(), strSoftwareVersion.GetData());
  1786. ctx->Ans.reserverd1 = succStr.c_str();
  1787. }
  1788. }
  1789. }
  1790. else {
  1791. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Execute <%s> failed.", runItem.GetData());
  1792. result = Error_Process;
  1793. }
  1794. }
  1795. #endif //RVC_OS_WIN
  1796. }
  1797. else {
  1798. result = Error_NotSupport;
  1799. }
  1800. ctx->Answer(result);
  1801. return;
  1802. }
  1803. CSimpleStringA ResourceWatcherEntity::GetFilePathWithDir(CSimpleStringA dir, CSimpleStringA fileName)
  1804. {
  1805. CSimpleStringA tmpPath(""), filePath("");
  1806. #ifdef RVC_OS_LINUX
  1807. struct stat st;
  1808. if (stat(dir, &st) == -1)
  1809. {
  1810. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s] Failed to get file stats.", dir.GetData());
  1811. return "";
  1812. }
  1813. if (!S_ISDIR(st.st_mode))
  1814. {
  1815. return "";
  1816. }
  1817. DIR* dp;
  1818. struct dirent* dirp;
  1819. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to open dir %s", dir.GetData());
  1820. if ((dp = opendir(dir.GetData())) != NULL)
  1821. {
  1822. while ((dirp = readdir(dp)) != NULL)
  1823. {
  1824. if ((!strcmp(dirp->d_name, ".")) || (!strcmp(dirp->d_name, ".."))) {
  1825. continue;
  1826. }
  1827. CSimpleStringA tmpName(dirp->d_name);
  1828. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
  1829. if (tmpName == fileName)
  1830. {
  1831. filePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1832. break;
  1833. }
  1834. tmpPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1835. filePath = GetFilePathWithDir(tmpPath, fileName);
  1836. if (!filePath.IsNullOrEmpty())
  1837. {
  1838. break;
  1839. }
  1840. }
  1841. closedir(dp);
  1842. if (filePath.IsNullOrEmpty())
  1843. {
  1844. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Can't find file[%s] under path [%s].",fileName.GetData(), dir.GetData());
  1845. }
  1846. return filePath;
  1847. }
  1848. else
  1849. {
  1850. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Open dir [%s] failed.", dir.GetData());
  1851. return "";
  1852. }
  1853. #else
  1854. CSimpleStringA inPath = dir;
  1855. inPath.Append("\\*"); // "D:aaa\bbb\ccc\* " 匹配目录下的所有文件和文件夹
  1856. int fileLength = inPath.GetLength();
  1857. WIN32_FIND_DATA wfd;
  1858. HANDLE hFind;
  1859. hFind = FindFirstFile(inPath.GetData(), &wfd);
  1860. //单文件操作
  1861. if (hFind == INVALID_HANDLE_VALUE) // 非文件夹 (inPath "D:aaa\bbb\ccc\* "格式的情况下,如果前面是文件,会找不到匹配)
  1862. {
  1863. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s] is NOT dir.", dir.GetData());
  1864. return "";
  1865. }
  1866. //文件夹操作
  1867. do
  1868. {
  1869. if ((!strcmp(wfd.cFileName, ".")) || (!strcmp(wfd.cFileName, ".."))) {
  1870. continue;
  1871. }
  1872. CSimpleStringA tmpName(wfd.cFileName);
  1873. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
  1874. if (tmpName == fileName)
  1875. {
  1876. filePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1877. break;
  1878. }
  1879. tmpPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", dir.GetData(), tmpName.GetData());
  1880. filePath = GetFilePathWithDir(tmpPath, fileName);
  1881. if (!filePath.IsNullOrEmpty())
  1882. {
  1883. break;
  1884. }
  1885. } while (FindNextFileA(hFind, &wfd));
  1886. FindClose(hFind);
  1887. if (filePath.IsNullOrEmpty())
  1888. {
  1889. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Can't find file[%s] under path [%s].", fileName.GetData(), dir.GetData());
  1890. }
  1891. return filePath;
  1892. #endif // RVC_OS_LINUX
  1893. }
  1894. void ResourceWatcherEntity::InstallSogou(SpReqAnsContext<ResourceWatcherService_InstallThirdPartyProgram_Req,
  1895. ResourceWatcherService_InstallThirdPartyProgram_Ans>::Pointer ctx)
  1896. {
  1897. ErrorCodeEnum result(Error_Succeed);
  1898. ErrorCodeEnum tmpResult(Error_Succeed);
  1899. CSimpleStringA tmpMsg(true);
  1900. CSimpleStringA tmpPath(true);
  1901. DWORD warnCode = LOG_RESOURCEWATCHE_INSTALL_THIRDPARTY; //RTA映射
  1902. CSimpleStringA newSogouPath(true);
  1903. CSimpleStringA strDownloadDirPath(true);
  1904. GetFunction()->GetPath("Downloads", strDownloadDirPath);
  1905. CSimpleStringA strTempDirPath(true);
  1906. GetFunction()->GetPath("Temp", strTempDirPath);
  1907. #if defined(RVC_OS_LINUX)
  1908. bool sogouInstalled = false;
  1909. const bool doTryRestart = (ctx->Req.reserved1 != 1);
  1910. SogouInstallInfo info;
  1911. //安装搜狗输入法
  1912. bool zipFind = false;
  1913. time_t newestWrite = 0;
  1914. if (strDownloadDirPath.IsNullOrEmpty()) {
  1915. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("downloads path is invalid, maybe in config mode");
  1916. tmpResult = Error_Unexpect;
  1917. tmpMsg = CSimpleStringA::Format("搜狗安装包目录[Downloads]不存在!");
  1918. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1919. }
  1920. else {
  1921. DIR* dp;
  1922. struct dirent* dirp;
  1923. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to open dir %s", strDownloadDirPath.GetData());
  1924. if ((dp = opendir(strDownloadDirPath.GetData())) != NULL) {
  1925. while ((dirp = readdir(dp)) != NULL) {
  1926. CSimpleStringA tmpName(dirp->d_name);
  1927. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("name:%s", tmpName.GetData());
  1928. if ((tmpName.IsStartWith("sogou", true) || tmpName.IsStartWith("uos-sogou", true))
  1929. && tmpName.IsEndWith(".zip", true)) {
  1930. struct stat buf;
  1931. memset(&buf, 0x00, sizeof(buf));
  1932. CSimpleStringA strFullPathName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadDirPath.GetData(), dirp->d_name);
  1933. const int ret = stat(strFullPathName.GetData(), &buf);
  1934. if (ret != 0) {
  1935. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("获取文件[%s]状态信息出错。", tmpName.GetData());
  1936. }
  1937. else if (buf.st_mtim.tv_sec > newestWrite) {
  1938. newestWrite = buf.st_mtim.tv_sec;
  1939. newSogouPath = CSimpleStringA(tmpName.GetData());
  1940. zipFind = true;
  1941. }
  1942. }
  1943. }
  1944. closedir(dp);
  1945. if (!zipFind) {
  1946. tmpResult = Error_NotExist;
  1947. tmpMsg = CSimpleStringA::Format("在路径[%s]下未找到搜狗安装包!", strDownloadDirPath.GetData());
  1948. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1949. }
  1950. }
  1951. else {
  1952. tmpResult = Error_NotExist;
  1953. tmpMsg = CSimpleStringA::Format("打开[Downloads]目录失败!");
  1954. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1955. }
  1956. }
  1957. CSimpleStringA strInstallPkgPath(true);
  1958. if (zipFind) {
  1959. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to unzip pack %s", newSogouPath.GetData());
  1960. if (UnzipPack(newSogouPath) != Error_Succeed) {
  1961. tmpResult = Error_Unexpect;
  1962. tmpMsg = CSimpleStringA::Format("解压搜狗安装包失败!");
  1963. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1964. }
  1965. else {
  1966. newSogouPath = newSogouPath.SubString(0, newSogouPath.GetLength() - 4);
  1967. strInstallPkgPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",
  1968. strTempDirPath.GetData(), newSogouPath.GetData());
  1969. }
  1970. }
  1971. else {
  1972. tmpResult = GetSogouPkgDirPath(strInstallPkgPath);
  1973. if (tmpResult != Error_Succeed) {
  1974. tmpMsg = CSimpleStringA::Format(" 指定位置 [Ad] 找不到输入法安装包");
  1975. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  1976. }
  1977. }
  1978. CSimpleStringA strInstallScriptFile;
  1979. CSimpleStringA strRunIniFilePath;
  1980. CSimpleStringA strResultLogFilePath;
  1981. const bool doNotStartup(true); //安装后是否启动搜狗输入法服务,据搜狗反馈,不能通过root权限启动Sogou输入法
  1982. if (tmpResult == Error_Succeed) {
  1983. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to install sogou input... %s", strInstallPkgPath.GetData());
  1984. tmpResult = SetFileExecutePriviledge(strInstallPkgPath);
  1985. if (tmpResult != Error_Succeed) {
  1986. tmpMsg = CSimpleStringA::Format("%s 修改文件夹权限失败", strInstallPkgPath.GetData());
  1987. tmpResult = Error_NotExist;
  1988. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  1989. }
  1990. else {
  1991. strRunIniFilePath = GetFilePathWithDir(strInstallPkgPath, "Run.ini");
  1992. if (ExistsFileA(strRunIniFilePath)) {
  1993. char* p = inifile_read_str(strRunIniFilePath, "Action", "ToRun", "");
  1994. strInstallScriptFile = GetFilePathWithDir(strInstallPkgPath, p);
  1995. FREE(p);
  1996. }
  1997. else {
  1998. strInstallScriptFile = GetFilePathWithDir(strInstallPkgPath, "install_sogouime.sh");
  1999. }
  2000. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("install script file: %s", strInstallScriptFile.GetData());
  2001. if (ExistsFileA(strInstallScriptFile)) {
  2002. char app[MAX_PATH] = { '\0' };
  2003. sprintf(app, "bash %s", strInstallScriptFile.GetData());
  2004. tmpResult = RunShellScript(app);
  2005. if (tmpResult != 0) {
  2006. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  2007. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2008. }
  2009. else if (!doNotStartup) {
  2010. CSimpleStringA strStartupScriptFile = GetFilePathWithDir(strInstallPkgPath, "startup_service.sh");
  2011. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("startup script file: %s", strStartupScriptFile.GetData());
  2012. if (!ExistsFileA(strStartupScriptFile)) {
  2013. tmpMsg = CSimpleStringA::Format("%s 启动脚本文件不存在,请重启设备再次验证", strStartupScriptFile.GetData());
  2014. tmpResult = Error_NotExist;
  2015. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2016. }
  2017. else {
  2018. Sleep(1000);
  2019. do {
  2020. sprintf(app, "bash %s", strStartupScriptFile.GetData());
  2021. tmpResult = RunShellScript(app);
  2022. if (tmpResult != 0) {
  2023. tmpMsg = CSimpleStringA::Format("执行 '%s' 失败", app);
  2024. tmpResult = Error_Process;
  2025. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2026. }
  2027. } while (false);
  2028. }
  2029. }
  2030. }
  2031. else {
  2032. tmpMsg = CSimpleStringA::Format("%s 执行文件不存在", strInstallScriptFile.GetData());
  2033. tmpResult = Error_NotExist;
  2034. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2035. }
  2036. }
  2037. }
  2038. if (tmpResult == Error_Succeed) {
  2039. Sleep(1500);
  2040. strResultLogFilePath = GetFilePathWithDir(strInstallPkgPath, "result.log");
  2041. do {
  2042. const int maxTimes = 5;
  2043. int curTimes = 0;
  2044. while (!ExistsFileA(strResultLogFilePath) && curTimes < maxTimes) {
  2045. Sleep(1500);
  2046. curTimes++;
  2047. }
  2048. } while (false);
  2049. if (!ExistsFileA(strResultLogFilePath)) {
  2050. tmpResult = Error_NotExist;
  2051. tmpMsg = CSimpleStringA::Format("安装成功标志文件不存在!");
  2052. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2053. }
  2054. else {
  2055. FILE* pResultLog = fopen(strResultLogFilePath, "r");
  2056. if (pResultLog == NULL) {
  2057. tmpResult = Error_IO;
  2058. tmpMsg = CSimpleStringA::Format("打开安装成功标志文件失败!%s", strerror(errno));
  2059. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2060. }
  2061. else {
  2062. char szTmp[1024] = { '\0' };
  2063. int nRead = fread(szTmp, 1, sizeof(szTmp), pResultLog);
  2064. int installResult(-1);
  2065. char installMsg[256] = { '\0' };
  2066. sscanf(szTmp, "result=%d&msg=%s", &installResult, installMsg);
  2067. fclose(pResultLog);
  2068. if (installResult != 0) {
  2069. tmpResult = Error_Unexpect;
  2070. tmpMsg = CSimpleStringA::Format("安装状态错误:%s", szTmp);;
  2071. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2072. }
  2073. else {
  2074. GetSogouInstallInfo(info);
  2075. if (!info.IsInstalledSuccess()) {
  2076. tmpResult = Error_FailVerify;
  2077. tmpMsg = CSimpleStringA::Format("搜狗检测安装状态失败!");
  2078. }
  2079. else {
  2080. ctx->Ans.path = info.program.strInstallDir;
  2081. ctx->Ans.reserverd1 = info.program.strVersion;
  2082. ctx->Ans.reserverd2 = info.state.GetInstallTime().ToTimeString();
  2083. //ctx->Ans.reserverd3 = info.program.IsTSFVersion() ? 1 : 0;
  2084. //ctx->Ans.reserverd4 = 0;
  2085. if (doTryRestart) {
  2086. tmpMsg = CSimpleStringA::Format(" 从[%s]安装搜狗输入法成功。", strInstallPkgPath.GetData());
  2087. }
  2088. sogouInstalled = true;
  2089. }
  2090. }
  2091. }
  2092. }
  2093. }
  2094. LogWarn(Severity_Low, Error_Debug, warnCode,
  2095. CSimpleStringA::Format("用户桌面重装搜狗:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  2096. ctx->Ans.result = tmpResult;
  2097. ctx->Ans.msg = tmpMsg;
  2098. ctx->Answer(tmpResult, warnCode);
  2099. #else
  2100. //win-sogou 包名
  2101. bool zipFind = false;
  2102. struct _finddata_t fileinfo;//文件信息读取结构
  2103. long hFile = -1;
  2104. time_t newestWrite = 0;
  2105. if (strDownloadDirPath.IsNullOrEmpty()) {
  2106. tmpResult = Error_Unexpect;
  2107. tmpMsg = CSimpleStringA::Format("搜狗安装包目录[Downloads]不存在!");
  2108. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  2109. }
  2110. else {
  2111. CSimpleStringA tmpDownloads(strDownloadDirPath.GetData());
  2112. hFile = _findfirst(tmpDownloads.Append("\\*").GetData(), &fileinfo);
  2113. if (hFile != -1) {
  2114. do {
  2115. CSimpleStringA tmpName(fileinfo.name);
  2116. if ((tmpName.IsStartWith("sogou", true) || tmpName.IsStartWith("win-sogou", true) || tmpName.IsStartWith("Sys-Win-sogou", true))
  2117. && tmpName.IsEndWith(".zip", true) && fileinfo.time_write > newestWrite) {
  2118. newestWrite = fileinfo.time_write;
  2119. newSogouPath = CSimpleStringA(tmpName.GetData());
  2120. zipFind = true;
  2121. }
  2122. } while (_findnext(hFile, &fileinfo) == 0);
  2123. _findclose(hFile);
  2124. if (zipFind) {
  2125. if (UnzipPack(newSogouPath.GetData()) != Error_Succeed) {
  2126. tmpResult = Error_Unexpect;
  2127. tmpMsg = CSimpleStringA::Format("解压搜狗安装包失败!");
  2128. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2129. }
  2130. else {
  2131. newSogouPath = newSogouPath.SubString(0, newSogouPath.GetLength() - 4);
  2132. CSimpleStringA tmpStrInstallDirPath = CSimpleStringA::Format("%s\\%s",
  2133. strTempDirPath.GetData(), newSogouPath.GetData()); //D:RVC\temp\sogou.xxxxx
  2134. CSimpleStringA strInstallDirPath("");
  2135. CSimpleStringA strResultLogFilePath("");
  2136. strInstallDirPath = GetFilePathWithDir(tmpStrInstallDirPath, "install_sogouime.bat") + " force";
  2137. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("开始安装");
  2138. STARTUPINFO si = { sizeof(si) };
  2139. PROCESS_INFORMATION pi;
  2140. si.dwFlags = STARTF_USESHOWWINDOW;
  2141. si.wShowWindow = TRUE;
  2142. char* cmdline = const_cast<LPSTR>(strInstallDirPath.GetData());
  2143. BOOL bRet = ::CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
  2144. WaitForSingleObject(pi.hProcess, INFINITE);
  2145. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("结束后台安装流程");
  2146. strResultLogFilePath = GetFilePathWithDir(tmpStrInstallDirPath, "result.log");
  2147. if (strResultLogFilePath.IsNullOrEmpty() || strInstallDirPath.IsNullOrEmpty()) {
  2148. tmpResult = Error_NotExist;
  2149. tmpMsg = CSimpleStringA::Format("进入安装目录失败!路径为空!");
  2150. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2151. }
  2152. else if (!ExistsFileA(strResultLogFilePath)) {
  2153. tmpResult = Error_NotExist;
  2154. tmpMsg = CSimpleStringA::Format("安装成功标志文件不存在!路径[%s]", strResultLogFilePath.GetData());
  2155. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2156. }
  2157. else {
  2158. FILE* pResultLog = fopen(strResultLogFilePath, "r");
  2159. if (pResultLog == NULL) {
  2160. tmpResult = Error_IO;
  2161. tmpMsg = CSimpleStringA::Format("打开安装成功标志文件失败!%s", strerror(errno));
  2162. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2163. }
  2164. else {
  2165. char szTmp[1024] = { '\0' };
  2166. int nRead = fread(szTmp, 1, sizeof(szTmp), pResultLog);
  2167. CSimpleStringA tInstallRe = szTmp;
  2168. fclose(pResultLog);
  2169. CSimpleStringA installResult = "-1";
  2170. CSimpleStringA installMsg;
  2171. auto arr = tInstallRe.Split('&');
  2172. if (arr.GetCount() != 2) {
  2173. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetSysUpgradeResult")("GetSysUpgradeResult read result log format fail");
  2174. tmpMsg = "read result.log format fail,eg result=0&msg=install ok";
  2175. }
  2176. for (int i = 0; i < arr.GetCount(); i++) {
  2177. auto arr2 = arr[i].Split('=');
  2178. if (arr2.GetCount() == 2) {
  2179. if (stricmp(arr2[0], "result") == 0)
  2180. installResult = arr2[1];
  2181. else if (stricmp(arr2[0], "msg") == 0)
  2182. installMsg = arr2[1];
  2183. }
  2184. }
  2185. if (installResult != CSimpleStringA::Format("0")) {
  2186. tmpResult = Error_Unexpect;
  2187. tmpMsg = CSimpleStringA::Format("安装状态错误:%s", szTmp);
  2188. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2189. }
  2190. else {
  2191. SogouInstallInfo info;
  2192. if (GetSogouInstallInfo(info) != Error_Succeed) {
  2193. tmpResult = Error_FailVerify;
  2194. tmpMsg = CSimpleStringA::Format("搜狗安装状态失败!");
  2195. warnCode = LOG_RESOURCEWATCHE_INSTALL_SOGOU_FAILED;
  2196. }
  2197. else {
  2198. ctx->Ans.path = info.program.strInstallDir;
  2199. ctx->Ans.reserverd1 = info.program.strVersion;
  2200. ctx->Ans.reserverd2 = info.state.GetInstallTime().ToTimeString();
  2201. }
  2202. }
  2203. }
  2204. }
  2205. if (tmpResult == Error_Succeed) {
  2206. tmpMsg = CSimpleStringA::Format("已成功安装搜狗输入法!");
  2207. }
  2208. }
  2209. }
  2210. else {
  2211. tmpResult = Error_NotExist;
  2212. tmpMsg = CSimpleStringA::Format("在路径[%s]下未找到搜狗安装包!", strDownloadDirPath.GetData());
  2213. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  2214. }
  2215. }
  2216. else {
  2217. tmpResult = Error_NotExist;
  2218. tmpMsg = CSimpleStringA::Format("搜狗打开[Downloads]目录失败!");
  2219. warnCode = LOG_RESOURCEWATCHE_SOGOU_FINDPKG_FAILED;
  2220. }
  2221. }
  2222. LogWarn(Severity_Low, Error_Debug, warnCode,
  2223. CSimpleStringA::Format("用户桌面重装搜狗:%s. result:%d.", tmpMsg.GetData(), tmpResult));
  2224. ctx->Ans.result = tmpResult;
  2225. ctx->Ans.msg = tmpMsg;
  2226. ctx->Answer(tmpResult, warnCode);
  2227. return;
  2228. #endif //RVC_OS_LINUX
  2229. }
  2230. void ResourceWatcherEntity::CheckProcessStatus()
  2231. {
  2232. vector<string> msg;
  2233. CSmartPointer<IConfigInfo> spCtSettingConfig;
  2234. GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  2235. CSimpleStringA getProcess(""), tName("");
  2236. int procCnt = 0;
  2237. #if defined(RVC_OS_LINUX)
  2238. do {
  2239. procCnt++;
  2240. getProcess = CSimpleStringA::Format("ProcessNameUOS%d", procCnt);
  2241. spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getProcess, tName);
  2242. if (!tName.IsNullOrEmpty()) {
  2243. std::string succStr, errStr;
  2244. std::string runStr("pgrep -d '|' ");
  2245. runStr += tName.GetData();
  2246. CSimpleStringA tMsg(true);
  2247. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  2248. if (succStr.empty()) {
  2249. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": 0}", tName.GetData());
  2250. }
  2251. else {
  2252. succStr = SP::Utility::ToTrim(succStr);
  2253. if (succStr.find('|') != std::string::npos) {
  2254. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": %s}", tName.GetData(), succStr.c_str());
  2255. }
  2256. else {
  2257. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": \"%s\"}", tName.GetData(), succStr.c_str());
  2258. }
  2259. }
  2260. }
  2261. else {
  2262. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": -1}", tName.GetData());
  2263. }
  2264. msg.push_back(tMsg.GetData());
  2265. }
  2266. } while (!tName.IsNullOrEmpty());
  2267. #else
  2268. do {
  2269. procCnt++;
  2270. getProcess = CSimpleStringA::Format("ProcessName%d", procCnt);
  2271. spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getProcess, tName);
  2272. if (tName.GetLength() != 0) {
  2273. CAutoArray<CSimpleStringA> tArray;
  2274. tArray.Append(&tName, 0, 1);
  2275. string tMsg = DoCheckCertainProcessStatus(tArray);
  2276. if (tMsg.size() == 0) {
  2277. tMsg = CSimpleStringA::Format("{ \"name\":\"%s\", \"pid\": 0}", tName.GetData());
  2278. }
  2279. msg.push_back(tMsg);
  2280. }
  2281. } while (tName.GetLength() != 0);
  2282. #endif //RVC_OS_LINUX
  2283. if (msg.size() != 0) {
  2284. CSimpleStringA res(true);
  2285. if (msg.size() == 1) {
  2286. res = msg[0].c_str();
  2287. }
  2288. else {
  2289. res = "{";
  2290. for (int i = 0; i < msg.size(); ++i) {
  2291. if (i != 0) { res += ","; }
  2292. res = res + msg[i].c_str();
  2293. }
  2294. res += "}";
  2295. }
  2296. LogWarn(Severity_Low, Error_Debug, LOG_WARN_PROCESS_STATUS, res);
  2297. }
  2298. }
  2299. void ResourceWatcherEntity::FilesClean(SpReqAnsContext<ResourceWatcherService_FilesClean_Req, ResourceWatcherService_FilesClean_Ans>::Pointer ctx)
  2300. {
  2301. ErrorCodeEnum result(Error_Succeed);
  2302. ErrorCodeEnum tmpResult(Error_Succeed);
  2303. CSimpleStringA tmpMsg(true);
  2304. if (ctx->Req.type == 1)//清理浏览器缓存
  2305. {
  2306. BrowserCacheClean browserCacheClean;
  2307. browserCacheClean.needClean = 1;
  2308. SpSendBroadcast(GetFunction(),
  2309. SP_MSG_OF(BrowserCacheClean), SP_MSG_SIG_OF(BrowserCacheClean), browserCacheClean);
  2310. tmpMsg = "已发送重启命令";
  2311. }
  2312. else {
  2313. tmpResult = Error_NotExist;
  2314. tmpMsg = "非法的调用参数";
  2315. }
  2316. ctx->Ans.result = tmpResult;
  2317. ctx->Ans.msg = tmpMsg;
  2318. ctx->Answer(result);
  2319. }
  2320. void ResourceWatcherEntity::OnUpgradeStateEvent(const char* pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, UpgradeManager::UpgradeStateEvent& evt)
  2321. {
  2322. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OnUpgradeStateEvent, cInstallState:%c, strNewVersion:%s.", evt.cInstallState, evt.strNewVersion.GetData());
  2323. CSimpleStringA packName = evt.strPackName;
  2324. if (evt.cInstallState == 'I') {
  2325. lastUpgradeInstallTime = time(0);
  2326. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("lastUpgradeInstallTime = %lld.", lastUpgradeInstallTime);
  2327. }
  2328. if (evt.cInstallState == 'S' || evt.cInstallState == 'C') {
  2329. lastUpgradeSwitchTime = time(0);
  2330. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("lastUpgradeSwitchTime = %lld.", lastUpgradeSwitchTime);
  2331. if (evt.strNewVersion.GetLength() == 0) {
  2332. newestSogouInstall = true;
  2333. lastSogouChangeEndTime = lastUpgradeSwitchTime + 60;
  2334. }
  2335. DoCheckSogouProcessStatus();
  2336. }
  2337. }
  2338. void ResourceWatcherEntity::FetchSystemSnapshot(
  2339. SpReqAnsContext<ResourceWatcherService_FetchSystemSnapshot_Req, ResourceWatcherService_FetchSystemSnapshot_Ans>::Pointer ctx)
  2340. {
  2341. CSimpleStringA info(true);
  2342. if (ctx->Req.type == 1) {
  2343. #if defined(RVC_OS_WIN)
  2344. ctx->Answer(Error_NotSupport);
  2345. #else
  2346. const bool ret = m_fsm.GetMonitorInfo(info);
  2347. if (ret) {
  2348. ctx->Ans.result = 0;
  2349. ctx->Ans.msg = info;
  2350. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS_GET, info);
  2351. }
  2352. else {
  2353. ctx->Ans.result = -1;
  2354. ctx->Ans.msg = "调用 GetMonitorInfo 接口失败";
  2355. }
  2356. ctx->Answer(Error_Succeed);
  2357. #endif //RVC_OS_WIN
  2358. }
  2359. else if (ctx->Req.type == 2) { /** 有无安装新版浏览器 [Gifur@20221219]*/
  2360. #if defined(_MSC_VER)
  2361. ctx->Answer(Error_NotSupport);
  2362. #else
  2363. const std::string execute_newbrowser_path = "/usr/share/browser/browser";
  2364. const std::string execute_oldbrowser_path = "/usr/share/uosbrowser/uosbrowser";
  2365. int result(0);
  2366. std::string additional("");
  2367. std::string succStr, errStr;
  2368. std::string runStr("dpkg -l | grep org.deepin.browser | awk '{print $3}'");
  2369. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  2370. if (succStr.empty()) {
  2371. if (ExistsFileA(execute_oldbrowser_path.c_str())) {
  2372. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s exists!", execute_oldbrowser_path.c_str());
  2373. result = 1;
  2374. }
  2375. else {
  2376. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s not exists!", execute_oldbrowser_path.c_str());
  2377. }
  2378. }
  2379. else {
  2380. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("new browser version: %s", succStr.c_str());
  2381. additional = succStr;
  2382. if (!ExistsFileA(execute_newbrowser_path.c_str())) {
  2383. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s not exists!", execute_newbrowser_path.c_str());
  2384. }
  2385. result = 2;
  2386. }
  2387. ctx->Ans.result = result;
  2388. ctx->Ans.msg = additional.c_str();
  2389. ctx->Answer(Error_Succeed);
  2390. }
  2391. else {
  2392. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("execute '%s' failed!", runStr.c_str());
  2393. ctx->Answer(Error_Process);
  2394. }
  2395. #endif //_MSC_VER
  2396. }
  2397. else {
  2398. ctx->Answer(Error_NotSupport);
  2399. }
  2400. }
  2401. #if defined(RVC_OS_WIN)
  2402. SP_BEGIN_ENTITY_MAP()
  2403. SP_ENTITY(ResourceWatcherEntity)
  2404. SP_END_ENTITY_MAP()
  2405. #else
  2406. ResourceWatcherEntity cur;
  2407. class SpEntityModuleStub : public ModuleBase
  2408. {
  2409. public:
  2410. SpEntityModuleStub()
  2411. {
  2412. try {
  2413. //ResourceWatcherEntity* cur = new ResourceWatcherEntity();
  2414. // 内存分配成功
  2415. m_pEntityArray[m_nEntityCount++] = dynamic_cast<CEntityBase*>(&cur);
  2416. }
  2417. catch (const std::bad_alloc& e) {
  2418. // 内存分配失败,捕获异常
  2419. Dbg("ResourceWatcher Error: Memory allocation failed for ResourceWatcherEntity. %s", e.what());
  2420. // 处理错误
  2421. }
  2422. catch (...) {
  2423. Dbg("ResourceWatcher Error: other for ResourceWatcherEntity");
  2424. }
  2425. Dbg("ResourceWatcher SpEntityModuleStub end");
  2426. }
  2427. };
  2428. SpEntityModuleStub g_ModuleInst;
  2429. extern "C" void __attribute__((constructor)) SoMain() {
  2430. g_ModuleInst.DllMain(NULL, DLL_PROCESS_ATTACH, NULL);
  2431. }
  2432. #endif