ResourceWatcherFSM.cpp 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289
  1. #include "stdafx.h"
  2. #include "ResourceWatcherFSM.h"
  3. #include "DeviceBaseClass.h"
  4. #include <string.h>
  5. #include <string>
  6. #include <assert.h>
  7. #include <algorithm>
  8. #include "fileutil.h"
  9. #include <ctime>
  10. #include "CommEntityUtil.hpp"
  11. #include "SpUtility.h"
  12. #include "RestfulFunc.h"
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include "ResourceWatcher_UserCode.h"
  16. #ifdef RVC_OS_LINUX
  17. #include <vector>
  18. #include <dirent.h>
  19. #include <sstream>
  20. #include <fstream>
  21. #include <iostream>
  22. #include "publicFunExport.h"
  23. #include "toolkit.h"
  24. #include "iniutil.h"
  25. #include "osutil.h"
  26. #else
  27. #include <intrin.h>
  28. #include <ShlObj.h>
  29. #include <ShellAPI.h>
  30. #include <Pdh.h>
  31. #include <io.h>
  32. #include <direct.h>
  33. #include "memutil.h"
  34. #include "array.h"
  35. #include <Windows.h>
  36. #include <wintrust.h>
  37. #include <direct.h>
  38. #include <Mscat.h>
  39. #include <Softpub.h>
  40. #include <wlanapi.h>
  41. #include <Netlistmgr.h> //网络检测添加
  42. #include <psapi.h>
  43. #include <tlhelp32.h>
  44. #include "Mmdeviceapi.h"
  45. #include "Propidl.h"
  46. #include "Functiondiscoverykeys_devpkey.h"
  47. #pragma comment(lib, "pdh.lib")
  48. #pragma comment(lib,"winmm.lib" )
  49. #pragma comment(lib, "shell32.lib")
  50. #pragma comment(lib, "Wintrust.lib")
  51. #pragma comment(lib, "crypt32.lib")
  52. #pragma comment(lib, "wlanapi.lib")
  53. #endif
  54. //硬件信息搜集参数
  55. #define DEFAULT_HARDWARE_CHECK_TIME 60 * 1000 //CPU、内存扫描默认间隔,1分钟
  56. #define TIMER_HARDWARE_CHECK 2
  57. //硬盘扫描
  58. #define DEFAULT_DISK_CHECK_TIME 4 * 60 * 60 * 1000 //硬盘默认4小时扫描一次
  59. #define TIMER_DISK_CHECK 3
  60. //保留版本数目
  61. #define DEFAULT_VERSION_SAVED_COUNT 5
  62. #define MAX_VERSION_PATH 256
  63. //一天的秒数,用于计算文件时间
  64. const int SECONDS_OF_DAY = 60 * 60 * 24;
  65. const int VIDEO_DEFAULT_BACKDAYS = 30;
  66. #ifdef RVC_OS_LINUX
  67. #define PROCESS_ITEM 14 //进程CPU信息读取位置参数
  68. const int MAX_MAINLINK_CHECK_TIME = 5000;
  69. const int TIMER_MAINLINK_CHECK = 4;
  70. #else
  71. const int TIMER_ID_CLEARVIDEO_ENHANCE = 1;
  72. const int THOUSAND = 1024;
  73. const int MILLION = 1048576;
  74. #endif // RVC_OS_LINUX
  75. static int hardwareCheckTime = 60 * 1000; //初始化硬件检测间隔
  76. static int hardwareCheckFlag = 1;
  77. static int cpuWarnTime = 0;
  78. static int cpuWarnThreshold = 10;
  79. static int memWarnTime = 0;
  80. static int memWarnThreshold = 10; //初始化CUP、内存告警阈值次数
  81. static int diskCheckTime = 4 * 60 * 60 * 1000; //初始化硬盘检测间隔
  82. static int diskCheckFlag = 1;
  83. #define DIV (1024 * 1024)
  84. #define DAY_DIV (24 * 60 * 60)
  85. #define HOURS_DIV (60 * 60)
  86. #define MINUS_DIV (60)
  87. #ifndef RVC_OS_LINUX
  88. #define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
  89. #define SafeDeleteArraySize(pData) { if(pData){delete []pData;pData=NULL;} }
  90. #endif // !RVC_OS_LINUX
  91. template<class T>
  92. class TimerOutHelper : public ITimerListener
  93. {
  94. public:
  95. typedef void (T::* FuncTimer)(void* pUserdata);
  96. TimerOutHelper(T* p, FuncTimer pTimerFunc, void* pData, bool bDeleteSelf = false)
  97. : m_pObject(p), m_pUserData(pData), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf)
  98. {
  99. }
  100. virtual void OnTimeout(DWORD dwTimerID)
  101. {
  102. (m_pObject->*m_pTimer)(m_pUserData);
  103. if (m_bDeleteSelf)
  104. delete this;
  105. }
  106. private:
  107. void* m_pUserData;
  108. T* m_pObject;
  109. FuncTimer m_pTimer;
  110. bool m_bDeleteSelf;
  111. };
  112. ResourceWatcherFSM::ResourceWatcherFSM(void)
  113. :m_strTerminalNo(true),
  114. m_bFirstRunAfterBoot(FALSE),
  115. m_cpuTop(0)
  116. {
  117. #ifdef RVC_OS_WIN
  118. m_forceStartupWithExeFlag = 0;
  119. m_iNonSignedTotal = 0;
  120. m_bNeedForceDiskCheck = false;
  121. m_DoneDetectAutostart = true;
  122. #endif // RVC_OS_WIN
  123. }
  124. ResourceWatcherFSM::~ResourceWatcherFSM(void)
  125. {
  126. }
  127. void ResourceWatcherFSM::s0_on_entry()
  128. {
  129. LOG_FUNCTION();
  130. #if defined(RVC_OS_WIN)
  131. this->PostEventFIFO(new RunEvent());
  132. BOOL fInstallBySetup(FALSE);
  133. ErrorCodeEnum rc = DetectVTMInstalledBySetup(fInstallBySetup);
  134. if (Error_Succeed == rc && !fInstallBySetup) {
  135. GetEntityBase()->GetFunction()->PostThreadPoolTask(new CreateLinkTask(this));
  136. }
  137. else {
  138. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("detect install type return %s, setup type: %d", SpStrError(rc), fInstallBySetup);
  139. }
  140. #endif //RVC_OS_WIN
  141. }
  142. unsigned int ResourceWatcherFSM::s0_on_event(FSMEvent* e)
  143. {
  144. LOG_FUNCTION();
  145. unsigned int unRes = 0;
  146. switch (e->iEvt)
  147. {
  148. case USER_EVT_RUN:
  149. {
  150. e->SetHandled();
  151. }
  152. break;
  153. default:
  154. {
  155. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unexpecetd Event(%d)", e->iEvt);
  156. }
  157. break;
  158. }
  159. return unRes;
  160. }
  161. void ResourceWatcherFSM::s0_on_exit()
  162. {
  163. }
  164. void ResourceWatcherFSM::s1_on_entry()
  165. {
  166. LOG_FUNCTION();
  167. }
  168. unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
  169. {
  170. LOG_FUNCTION();
  171. unsigned int unRes = 0;
  172. e->SetHandled();
  173. return unRes;
  174. }
  175. void ResourceWatcherFSM::s1_on_exit()
  176. {
  177. }
  178. void ResourceWatcherFSM::s2_on_entry()
  179. {
  180. LOG_FUNCTION();
  181. }
  182. unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
  183. {
  184. LOG_FUNCTION();
  185. unsigned int unRes = 0;
  186. switch (e->iEvt)
  187. {
  188. case USER_EVT_RUN:
  189. {
  190. e->SetHandled();
  191. }
  192. break;
  193. }
  194. return unRes;
  195. }
  196. void ResourceWatcherFSM::s2_on_exit()
  197. {
  198. }
  199. void ResourceWatcherFSM::s3_on_entry()
  200. {
  201. LOG_FUNCTION();
  202. }
  203. unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
  204. {
  205. unsigned int unRes = 0;
  206. switch (e->iEvt)
  207. {
  208. case USER_EVT_RUN:
  209. {
  210. e->SetHandled();
  211. }
  212. break;
  213. }
  214. return unRes;
  215. }
  216. void ResourceWatcherFSM::s3_on_exit()
  217. {
  218. }
  219. #ifdef RVC_OS_LINUX
  220. bool ResourceWatcherFSM::GetMonitorInfo(CSimpleStringA& outInfo)
  221. {
  222. std::string sucContent, failedContent;
  223. CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
  224. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  225. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  226. std::string msg = SP::Utility::ToTrim(sucContent);
  227. SP::Utility::replaceInPlace(msg, "\n", "|");
  228. outInfo = msg.c_str();
  229. return ret;
  230. }
  231. #endif // RVC_OS_LINUX
  232. //首页状态变化时触发的功能
  233. void ResourceWatcherFSM::TriggerAtStatusChanged(bool bMStatus)
  234. {
  235. if (firstMpage)//首次进入首页
  236. {
  237. firstMpage = false;
  238. CSmartPointer<IConfigInfo> spRunConfig;
  239. CSmartPointer<IConfigInfo> spCtSettingConfig;
  240. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  241. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  242. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckTime", hardwareCheckTime);
  243. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckFlag", hardwareCheckFlag);
  244. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "DiskCheckTime", diskCheckTime);
  245. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "DiskCheckFlag", diskCheckFlag);
  246. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "CpuTooHighPercent", m_cpuHighPercent);
  247. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "CpuWarnThreshold", cpuWarnThreshold);
  248. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MemoryTooHighPercent", m_memHighPercent);
  249. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MemWarnThreshold", memWarnThreshold);
  250. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardDiskTooHighPercent", m_diskHighPercent);
  251. spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "VerifySignature", m_iVerify);
  252. #if defined(RVC_OS_WIN)
  253. if (m_iVerify == 1) {//文件签名校验
  254. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Verify digitsign...");
  255. VerifyDigitSignTask* task = new VerifyDigitSignTask(this);
  256. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  257. }
  258. #endif //RVC_OS_WIN
  259. if (hardwareCheckTime <= 0) { //非法数值情况下设置为默认一分钟
  260. hardwareCheckTime = DEFAULT_HARDWARE_CHECK_TIME;
  261. }
  262. void* pTmpData = NULL;
  263. ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
  264. GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, hardwareCheckTime);
  265. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set Hardware Timer!");
  266. if (diskCheckFlag > 0) {
  267. GetSystemDiskStatus(); //仅启动时检测一次硬盘状态即可
  268. }
  269. if (diskCheckTime <= 0) {
  270. diskCheckTime = DEFAULT_DISK_CHECK_TIME;
  271. }
  272. void* pTmpData2 = NULL;
  273. ITimerListener* pListener2 = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::DiskCheckTimer, pTmpData2);
  274. GetEntityBase()->GetFunction()->SetTimer(TIMER_DISK_CHECK, pListener2, diskCheckTime);
  275. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set DISK CHECK Timer!");
  276. //集中配置额外加的清理逻辑
  277. CenterSettingDeleteTask* centerSettingDeleteTask = new CenterSettingDeleteTask(this);
  278. GetEntityBase()->GetFunction()->PostThreadPoolTask(centerSettingDeleteTask);
  279. //终端默认的自动清理逻辑
  280. AutoDeleteFilesTask* autoDeleteTask = new AutoDeleteFilesTask(this);
  281. GetEntityBase()->GetFunction()->PostThreadPoolTask(autoDeleteTask);
  282. #if defined(RVC_OS_LINUX)
  283. if (m_bFirstRunAfterBoot) {
  284. UINT sysVer = 0;
  285. UploadSysVersionInfo(sysVer);
  286. ConfirmWindowEffectHasBeenOpen();
  287. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fetch os version: %u", sysVer);
  288. if (1031 < sysVer) {
  289. ConfirmDDEClipboardDisable();
  290. ConfirmNotificationCenterDisable();
  291. }
  292. else {
  293. RecoverDDEClipboardEnable();
  294. }
  295. GetEntityBase()->GetFunction()->PostThreadPoolTask(new DetectSoftwareInstallStatusTask(this));
  296. GetEntityBase()->GetFunction()->PostThreadPoolTask(new UploadMonitorInfoTask(this));
  297. AlarmSystemBasicInfo();
  298. }
  299. #endif //RVC_OS_LINUX
  300. }
  301. }
  302. ErrorCodeEnum ResourceWatcherFSM::OnInit()
  303. {
  304. firstMpage = true; //是否首次进入首页
  305. ErrorCodeEnum erroCode = Error_Succeed;
  306. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Complied at: %s %s", __DATE__, __TIME__);
  307. CSmartPointer<IConfigInfo> spRunConfig;
  308. CSmartPointer<IConfigInfo> spCtSettingConfig;
  309. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  310. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  311. erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(m_RvcSysinfo);
  312. m_strTerminalNo = m_RvcSysinfo.strTerminalID;
  313. m_bFirstRunAfterBoot = DetectIsFirstRunAtBoot();
  314. if (m_bFirstRunAfterBoot) {
  315. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("First time to run after system boot.");
  316. }
  317. if (m_bFirstRunAfterBoot) {
  318. #if defined(RVC_OS_WIN)
  319. //GetSystemMetrics (SM_CMONITORS) 计数仅显示可见的显示器
  320. const int screenNums = GetSystemMetrics(SM_CMONITORS);
  321. const int aimScreenNums4Stand2S = 2;
  322. const int aimScreenNums4Other = 1;
  323. if (0 == m_RvcSysinfo.strMachineType.Compare("RVC.Stand2S", true) && screenNums != aimScreenNums4Stand2S) {
  324. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_LACK_OF_MONITOR
  325. , CSimpleStringA::Format("{\"subject\":\"screen_count\",\"machine_type\":\"%s\",\"expect\":%d,\"actual\":%d}"
  326. , m_RvcSysinfo.strMachineType.GetData(), aimScreenNums4Stand2S, screenNums));
  327. }
  328. else if (0 != m_RvcSysinfo.strMachineType.Compare("RVC.Stand2S", true) && screenNums != aimScreenNums4Other) {
  329. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_LACK_OF_MONITOR
  330. , CSimpleStringA::Format("{\"subject\":\"screen_count\",\"machine_type\":\"%s\",\"expect\":%d,\"actual\":%d}"
  331. , m_RvcSysinfo.strMachineType.GetData(), aimScreenNums4Other, screenNums));
  332. }
  333. #endif //RVC_OS_WIN
  334. }
  335. spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "DisplayCnt", m_iNonSignedDisplay);
  336. if (m_iNonSignedDisplay <= 0)
  337. m_iNonSignedDisplay = 10;
  338. spRunConfig->ReadConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  339. return Error_Succeed;
  340. }
  341. ErrorCodeEnum ResourceWatcherFSM::OnExit()
  342. {
  343. #ifdef RVC_OS_LINUX
  344. GetEntityBase()->GetFunction()->KillTimer(TIMER_HARDWARE_CHECK);
  345. #endif // RVC_OS_LINUX
  346. return Error_Succeed;
  347. }
  348. void ResourceWatcherFSM::AfterInit()
  349. {
  350. #if defined(RVC_OS_WIN)
  351. if (m_bFirstRunAfterBoot) {
  352. DetectAutoStartupCover();
  353. DetectWallpaperAndWarn();
  354. ClearDesktopFileTask* task = new ClearDesktopFileTask(this);
  355. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  356. }
  357. DetectVersionHasChangedAndWarnCover();
  358. #endif //RVC_OS_WIN
  359. }
  360. void ResourceWatcherFSM::LinkDetect(int detectType, const char* url, bool& status, unsigned int& delay, int warnFlag)
  361. {
  362. string tUrl = url;
  363. string host = "http://";
  364. int flag = 0;
  365. unsigned int tInterval = 0;
  366. string msg;
  367. if (tUrl.find("http") == string::npos) {
  368. tUrl = host + tUrl;
  369. }
  370. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Check url:[%s].", tUrl.c_str());
  371. ULLINT begin, end;
  372. begin = SP::Module::Comm::RVCGetTickCount();
  373. int curFlag = HttpProbe(tUrl, msg, 5);
  374. end = SP::Module::Comm::RVCGetTickCount();
  375. tInterval = end - begin;
  376. if (curFlag > 0 && curFlag < 400) {
  377. flag = true;
  378. }
  379. else {
  380. flag = false;
  381. }
  382. if (flag == false) {
  383. status = false;
  384. }
  385. else {
  386. status = true;
  387. }
  388. delay = tInterval > 0 ? tInterval:1;
  389. }
  390. ErrorCodeEnum ResourceWatcherFSM::BizLinkDetect(
  391. SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
  392. {
  393. LOG_FUNCTION();
  394. ErrorCodeEnum ec = Error_Succeed;
  395. int detectType = ctx->Req.protocol;
  396. CSimpleStringA url = ctx->Req.bizLink;
  397. bool linkStatus = false;
  398. unsigned int delay = 0;
  399. LinkDetect(detectType, url.GetData(), linkStatus, delay);
  400. ctx->Ans.bizLinkStatus = linkStatus;
  401. ctx->Ans.bizLinkDelayMS = delay;
  402. ctx->Ans.intParam = 0;
  403. CSimpleStringA warn;
  404. if (!linkStatus) {
  405. warn = CSimpleStringA::Format("BizLink disconnected[%s].", url.GetData());
  406. }
  407. else
  408. {
  409. warn = CSimpleStringA::Format("BizLink connected[%s], Delay time [%d]ms.", url.GetData(), delay);
  410. }
  411. LogWarn(Severity_Low, Error_Param, LOG_WARN_BIZLINK_CONNECT_CHECK, warn.GetData());
  412. if (ctx != NULL) {
  413. ctx->Answer(ec);
  414. }
  415. return ec;
  416. }
  417. //通过集中配置额外执行的清理策略
  418. void ResourceWatcherFSM::CenterSettingDelete()
  419. {
  420. string p;
  421. CSmartPointer<IConfigInfo> spCtSettingConfig;
  422. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  423. CSimpleStringA upPath(""), tempPath(""), tPath(""), upgradePath("");
  424. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "DocumentCleanPath", tempPath);
  425. if (tempPath.GetLength() == 0) {
  426. return;
  427. }
  428. ErrorCodeEnum erroCode = Error_Succeed;
  429. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  430. CSmartPointer<IConfigInfo> spConfigRun;
  431. //判断是否需要被清理
  432. erroCode = pFunc->OpenConfig(Config_Run, spConfigRun);
  433. if (erroCode != Error_Succeed) {
  434. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Open Run Config failed");
  435. return;
  436. }
  437. int nLastTaskTime = 0;
  438. int nLstFlag = 0;
  439. bool bFailFlag = false;
  440. CSimpleStringA optFileName("");
  441. UINT64 utVersion = 0;
  442. spConfigRun->ReadConfigValueHexInt("DeleteDocumentTask", "OptVer", utVersion);
  443. spConfigRun->ReadConfigValue("DeleteDocumentTask", "DocumentName", optFileName);
  444. spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
  445. spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastTime", nLastTaskTime);
  446. CVersion optVer(utVersion);
  447. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  448. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
  449. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  450. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  451. (LPCTSTR)optVer.ToString(), nLstFlag);
  452. if (optVer.IsValid() && optVer == m_RvcSysinfo.InstallVersion && !nLstFlag && optFileName == tempPath)
  453. {
  454. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Certain document cleaning has been done before.");
  455. return;
  456. }
  457. //执行清理逻辑
  458. upPath = tempPath;
  459. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  460. nFileCount = ProcessFileDelete(upPath.GetData(), nDelSuc, nDelFail, false);
  461. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Process result(%s): count(%d), suc(%d), failed(%d).", upPath.GetData(), nFileCount, nDelSuc, nDelFail);
  462. if (nDelFail != 0) {
  463. bFailFlag = true;
  464. //break;
  465. }
  466. nLstFlag = bFailFlag ? 1 : 0;
  467. spConfigRun->WriteConfigValueHexInt("DeleteDocumentTask", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  468. spConfigRun->WriteConfigValue("DeleteDocumentTask", "DocumentName", tempPath);
  469. spConfigRun->WriteConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
  470. spConfigRun->WriteConfigValue("DeleteDocumentTask", "LastTime",
  471. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  472. if (!bFailFlag)
  473. {
  474. LogWarn(Severity_Low, Error_Debug, LOG_WARN_FILE_DELETE_SUC, CSimpleStringA::Format("Delete files in [%s] success", tempPath.GetData()));
  475. }
  476. }
  477. time_t ResourceWatcherFSM::GetPathTimeSeconds(const char* inPath)
  478. {
  479. if (!inPath)
  480. {
  481. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetPathFileDays PATH = NULL.", inPath);
  482. return 0;
  483. }
  484. time_t lCreateTime = 0;
  485. //int reTimes = 0;
  486. #ifdef RVC_OS_WIN
  487. struct _finddata_t fileinfo;//文件信息读取结构
  488. string p;
  489. long hFile = _findfirst(inPath, &fileinfo);
  490. if (hFile == -1L)
  491. {
  492. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get [%s] fileinfo failed. GLE = %u.", inPath, GetLastError());
  493. return 0;
  494. }
  495. lCreateTime = fileinfo.time_write; //文件最后修改时间
  496. _findclose(hFile);
  497. #else
  498. struct stat stFile;
  499. if (stat(inPath, &stFile) == -1)
  500. {
  501. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] Failed to get file stats. GLE=%d.", inPath, GetLastError());
  502. return 0;
  503. }
  504. lCreateTime = stFile.st_mtime; //文件状态最后修改时间
  505. #endif // RVC_OS_WIN
  506. //reTimes = lCreateTime; //文件时间
  507. return lCreateTime;
  508. }
  509. //所有文件删除功能都用这个函数来处理
  510. //bool delDir:控制是否将目录也一并删除,false 保留目录, true 删除目录
  511. //int saveBackDay:保存多少天内的文件, 默认参数,默认值为0,即不保存。(delDir = true时,该参数强制为0)
  512. int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt, bool delDir, unsigned int saveBackDay)
  513. {
  514. if (delDir == true) //若要删除目录,则不保留任何文件
  515. {
  516. saveBackDay = 0;
  517. }
  518. int fileCnt = 0;
  519. char* searchFilePath = new char[MAX_PATH];
  520. char* tempFilePath = new char[MAX_PATH];
  521. if (searchFilePath == NULL || tempFilePath == NULL)
  522. {
  523. if (searchFilePath) delete[] searchFilePath;
  524. if (tempFilePath) delete[] tempFilePath;
  525. searchFilePath = NULL;
  526. tempFilePath = NULL;
  527. return fileCnt;
  528. }
  529. ZeroMemory(searchFilePath, MAX_PATH);
  530. ZeroMemory(tempFilePath, MAX_PATH);
  531. #ifdef RVC_OS_LINUX
  532. int fileLength = strlen(lpszPath);
  533. struct stat st;
  534. if (stat(lpszPath, &st) == -1)
  535. {
  536. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] Failed to get file stats.", lpszPath);
  537. nDelSucCnt++;
  538. return fileCnt;
  539. }
  540. if (!S_ISDIR(st.st_mode))
  541. {//单文件处理
  542. if (saveBackDay != 0)
  543. {
  544. time_t lSystemTime;
  545. time(&lSystemTime);
  546. time_t fileTime = GetPathTimeSeconds(lpszPath); //获取文件的最后改动时间
  547. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  548. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  549. {
  550. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Files 存留天数[%d], 删除阈值[%u],无需清理.", (int)delDays, saveBackDay);
  551. return fileCnt;
  552. }
  553. }
  554. if (RemoveFileA(lpszPath) == true) {
  555. nDelSucCnt++;
  556. fileCnt++;
  557. }
  558. else {
  559. nDelFailedCnt++;
  560. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno);
  561. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno));
  562. }
  563. if (searchFilePath) delete[] searchFilePath;
  564. if (tempFilePath) delete[] tempFilePath;
  565. searchFilePath = NULL;
  566. tempFilePath = NULL;
  567. return fileCnt;
  568. }
  569. DIR* d = opendir(lpszPath);
  570. if (!d) {
  571. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("opendir failed: %d.", errno);
  572. if (searchFilePath) delete[] searchFilePath;
  573. if (tempFilePath) delete[] tempFilePath;
  574. searchFilePath = NULL;
  575. tempFilePath = NULL;
  576. nDelFailedCnt++;
  577. return fileCnt;
  578. }
  579. struct dirent* dp = NULL;
  580. while ((dp = readdir(d)) != NULL) {
  581. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  582. continue;
  583. }
  584. strcpy(tempFilePath, lpszPath);
  585. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  586. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  587. continue;
  588. }
  589. strcat(tempFilePath, "/");
  590. strcat(tempFilePath, dp->d_name);
  591. stat(tempFilePath, &st);
  592. if (saveBackDay != 0)
  593. {
  594. time_t lSystemTime;
  595. time(&lSystemTime);
  596. time_t fileTime = GetPathTimeSeconds(tempFilePath); //获取文件的最后改动时间
  597. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  598. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  599. {
  600. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Dir[%s], 存留天数[%d], 删除阈值[%u],无需清理.", tempFilePath, (int)delDays, saveBackDay);
  601. continue;
  602. }
  603. }
  604. int tDelSucCnt = 0, tDelFailedCnt = 0;
  605. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt, true); //子目录要清理
  606. if (tDelFailedCnt != 0) {
  607. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")("rm(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno);
  608. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("rm(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno));
  609. nDelSucCnt += tDelSucCnt;
  610. nDelFailedCnt += tDelFailedCnt;
  611. return fileCnt;
  612. }
  613. nDelSucCnt += tDelSucCnt;
  614. }
  615. closedir(d);
  616. #else
  617. CSimpleStringA inPath = lpszPath;
  618. inPath.Append("\\*"); // "D:aaa\bbb\ccc\* " 匹配目录下的所有文件和文件夹
  619. int fileLength = inPath.GetLength();
  620. WIN32_FIND_DATA wfd;
  621. HANDLE hFind;
  622. hFind = FindFirstFile(inPath.GetData(), &wfd);
  623. //单文件操作
  624. if (hFind == INVALID_HANDLE_VALUE) // 非文件夹 (inPath "D:aaa\bbb\ccc\* "格式的情况下,如果前面是文件,会找不到匹配)
  625. {
  626. if (saveBackDay != 0)
  627. {
  628. //读取文件时间
  629. time_t lSystemTime;
  630. time(&lSystemTime);
  631. time_t fileTime = GetPathTimeSeconds(lpszPath); //获取文件的最后改动时间
  632. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  633. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  634. {
  635. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("存留天数[%d], 删除阈值[%u],无需清理.", (int)delDays, saveBackDay);
  636. return fileCnt;
  637. }
  638. }
  639. if (DeleteFile(lpszPath) == true)
  640. {
  641. nDelSucCnt++;
  642. fileCnt++;
  643. }
  644. else
  645. {
  646. nDelFailedCnt++;
  647. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")
  648. ("Delete [%s] failed, GLE = %u.", lpszPath, GetLastError());
  649. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("RemoveFileA [%s] failed, GLE = %u.", lpszPath, errno));
  650. }
  651. if (searchFilePath) delete[] searchFilePath;
  652. if (tempFilePath) delete[] tempFilePath;
  653. searchFilePath = NULL;
  654. tempFilePath = NULL;
  655. return fileCnt;
  656. }
  657. //文件夹操作
  658. do
  659. {
  660. if (wfd.cFileName[0] != '.')
  661. {
  662. strcpy_s(tempFilePath, MAX_PATH, inPath.GetData());
  663. tempFilePath[fileLength - 1] = '\0';
  664. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH)
  665. {
  666. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  667. }
  668. else
  669. {
  670. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName); //"D:aaa\bbb\ccc\fileName"
  671. if (saveBackDay != 0)
  672. {
  673. time_t lSystemTime;
  674. time(&lSystemTime);
  675. time_t fileTime = GetPathTimeSeconds(tempFilePath); //获取文件的最后改动时间
  676. if (fileTime == 0)
  677. {
  678. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get file time (%s) failed. skip clean", (LPCTSTR)tempFilePath);
  679. nDelFailedCnt++;
  680. continue;
  681. }
  682. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  683. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  684. {
  685. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Dir[%s], 存留天数[%d], 删除阈值[%u],无需清理.", tempFilePath, (int)delDays, saveBackDay);
  686. continue;
  687. }
  688. }
  689. int tDelSucCnt = 0, tDelFailedCnt = 0;
  690. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt, true); //子目录要删除
  691. if (tDelFailedCnt != 0)
  692. {
  693. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")
  694. ("rm(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, GetLastError());
  695. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("RemoveFileA [%s] failed, GLE = %u.", (LPCTSTR)tempFilePath, errno));
  696. nDelFailedCnt += tDelFailedCnt;
  697. return fileCnt;
  698. }
  699. nDelFailedCnt += tDelFailedCnt;
  700. nDelSucCnt += tDelSucCnt;
  701. }
  702. }
  703. } while (FindNextFileA(hFind, &wfd));
  704. FindClose(hFind);
  705. #endif // RVC_OS_LINUX
  706. if (delDir) //删除目录
  707. {
  708. #ifdef RVC_OS_WIN
  709. RemoveDirectoryA(lpszPath);
  710. #else
  711. RemoveDirRecursive(lpszPath);
  712. #endif
  713. }
  714. if (searchFilePath) delete[] searchFilePath;
  715. if (tempFilePath) delete[] tempFilePath;
  716. searchFilePath = NULL;
  717. tempFilePath = NULL;
  718. return fileCnt;
  719. }
  720. //终端默认执行的终端清理策略
  721. void ResourceWatcherFSM::AutoDeleteFiles()
  722. {
  723. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  724. CSmartPointer<IConfigInfo> spConfig;
  725. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  726. //判断是否升级完毕,未完成升级不进行删除任务
  727. CSimpleStringA strRunInfo, strStartTime;
  728. if (m_pEntity->GetFunction()->GetPath("RunInfo", strRunInfo) == Error_Succeed) {
  729. strStartTime = strRunInfo + SPLIT_SLASH_STR + "runcfg" + SPLIT_SLASH_STR + "starttime.dat";
  730. if (!ExistsFileA(strStartTime.GetData())) {
  731. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade prpcess done, try to delete version files.");//完成升级过程,通过
  732. }
  733. else
  734. {
  735. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,should not delete files.");
  736. return;//升级未完成,不进行删除
  737. }
  738. }
  739. else
  740. {
  741. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path error, should not version files.");
  742. return;//失败,继续等待
  743. }
  744. //清理版本相关文件
  745. DeleteVersionPackage();
  746. //清理录像文件
  747. DeleteVideoFiles();
  748. return;
  749. }
  750. //终端升级后会执行版本清理功能 包含dump和 upgaraded清理
  751. BOOL ResourceWatcherFSM::DeleteVersionPackage()
  752. {
  753. ErrorCodeEnum erroCode = Error_Succeed;
  754. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  755. CSmartPointer<IConfigInfo> spConfigRun;
  756. CSmartPointer<IConfigInfo> spConfig;
  757. CSystemStaticInfo info;
  758. if (pFunc->GetSystemStaticInfo(info) != Error_Succeed) {
  759. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get system static info error");
  760. return FALSE;
  761. }
  762. //清理执行成功与否的判断变量
  763. int nLastTaskTime = 0;
  764. int nLstFailed = 0;
  765. int nDelCount = 0;
  766. UINT64 utVersion = 0;
  767. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  768. pFunc->OpenConfig(Config_Run, spConfigRun);
  769. spConfigRun->ReadConfigValueHexInt("VersionClear", "OptVer", utVersion);
  770. spConfigRun->ReadConfigValueInt("VersionClear", "DelVerCnt", nDelCount);
  771. spConfigRun->ReadConfigValueInt("VersionClear", "LastCondi", nLstFailed); //失败标志
  772. spConfigRun->ReadConfigValueInt("VersionClear", "LastTime", nLastTaskTime);
  773. CVersion optVer(utVersion);
  774. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  775. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastFailed: %d",
  776. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  777. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  778. (LPCTSTR)optVer.ToString(), nLstFailed);
  779. //判断是否需要执行清理任务,若此版本之前成功清理过则不再继续执行后续操作
  780. if (optVer.IsValid() && optVer == info.InstallVersion && !nLstFailed) {
  781. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("VersionPackage cleaning has been done before.");
  782. return TRUE;
  783. }
  784. //--------------------------------------------------------------------------------------------
  785. //版本清理中默认进行upgrade清理
  786. int closeUpgradeClear = 0;
  787. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseUpgradeClear", closeUpgradeClear);
  788. if (!closeUpgradeClear)
  789. {
  790. //删除rvc/Upgraded目录下的文件
  791. CSimpleStringA upPath;
  792. ErrorCodeEnum upError = pFunc->GetPath("Upgraded", upPath);
  793. if (Error_Succeed != upError) {
  794. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Try to clean Upgraded Dir. But get Upgraded path error = %u.", upError);
  795. return FALSE;
  796. }
  797. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  798. nFileCount = ProcessFileDelete(upPath.GetData(), nDelSuc, nDelFail, false);
  799. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete [Upgraded] result(%s): count(%d), suc(%d), failed(%d).", upPath.GetData(), nFileCount, nDelSuc, nDelFail);
  800. }
  801. //--------------------------------------------------------------------------------------------
  802. //版本清理中默认进行dump清理
  803. int closeDmpClear = 0;
  804. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseDmpClear", closeDmpClear);
  805. if (!closeDmpClear)
  806. { //执行删除流程rvc/dmp
  807. CSimpleStringA dmpPath;
  808. ErrorCodeEnum dmpError = pFunc->GetPath("Temp", dmpPath);
  809. if (Error_Succeed != dmpError) {
  810. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Try to clean Dump Dir. But get Temp path error = %u.", dmpError);
  811. return FALSE;
  812. }
  813. #ifdef RVC_OS_LINUX
  814. dmpPath = dmpPath + SPLIT_SLASH_STR + ".." + SPLIT_SLASH_STR + "dmp"; // +"/../dmp"
  815. #else
  816. dmpPath = dmpPath + CSimpleStringA::Format("\\..\\dmp");
  817. #endif // RVC_OS_LINUX
  818. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  819. nFileCount = ProcessFileDelete(dmpPath.GetData(), nDelSuc, nDelFail, false);
  820. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete [Dump] result(%s): count(%d), suc(%d), failed(%d).", dmpPath.GetData(), nFileCount, nDelSuc, nDelFail);
  821. }
  822. //--------------------------------------------------------------------------------------------
  823. //清理ver文件夹
  824. int closeVerClear = 0;
  825. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseVerClear", closeVerClear);
  826. if (!closeVerClear)
  827. {
  828. int verSaved = DEFAULT_VERSION_SAVED_COUNT;
  829. int tmpSaved = 0;
  830. vector<CVersion> intallInfoVects;
  831. vector<string> files;
  832. spConfig->ReadConfigValueInt("ResourceWatcher", "VerSaveCnt", tmpSaved);
  833. if (tmpSaved > DEFAULT_VERSION_SAVED_COUNT) {
  834. verSaved = tmpSaved;
  835. }
  836. //获取当前目录下的文件夹名称, 将符合命名规则的终端版本名称push_back
  837. CSimpleStringA csPath, verPath;
  838. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  839. if (Error_Succeed == Error) {
  840. if (csPath.IsNullOrEmpty()) {
  841. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get currVer path is null");
  842. return FALSE;
  843. }
  844. else
  845. {
  846. verPath = csPath; //csPath在后面被用了,还需要个存储version路径变量
  847. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CUR VERSION PATH = %s.", csPath.GetData());
  848. }
  849. }
  850. else
  851. {
  852. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get Ver path error = %u.", Error);
  853. return FALSE;
  854. }
  855. //判断哪些是版本文件夹
  856. #ifdef RVC_OS_LINUX
  857. DIR* dp;
  858. struct dirent* dirp;
  859. //过滤非目标版本文件夹
  860. if ((dp = opendir(csPath.GetData())) != NULL) {
  861. while ((dirp = readdir(dp)) != NULL) {
  862. //files.push_back(string(dirp->d_name));
  863. CInstallInfo verInfo = {};
  864. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  865. int n = sscanf(dirp->d_name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  866. if (n != 4)
  867. {
  868. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
  869. continue;
  870. }
  871. else {
  872. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  873. if (verName.IsValid() && verName < info.InstallVersion) //对高于自身版本的文件不予删除
  874. {
  875. intallInfoVects.push_back(verName);
  876. }
  877. else {
  878. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
  879. }
  880. }
  881. }
  882. closedir(dp);
  883. }
  884. #else
  885. long hFile = 0;
  886. struct _finddata_t fileinfo;//文件信息读取结构
  887. string p;
  888. if ((hFile = _findfirst(p.assign(string(csPath.GetData())).append("\\*").c_str(), &fileinfo)) != -1) {
  889. do {
  890. CInstallInfo verInfo = {};
  891. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  892. int n = sscanf(fileinfo.name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  893. if (n != 4)
  894. {
  895. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
  896. continue;
  897. }
  898. else {
  899. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  900. if (verName.IsValid() && verName < info.InstallVersion)
  901. {
  902. intallInfoVects.push_back(verName);
  903. }
  904. else {
  905. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
  906. }
  907. }
  908. } while (_findnext(hFile, &fileinfo) == 0);
  909. _findclose(hFile);
  910. }
  911. #endif // RVC_OS_LINUX
  912. int nPackCount = intallInfoVects.size();
  913. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Install Package's count: %d", nPackCount);
  914. bool bFailFlag = false;
  915. int nDelVersionCnt = 0;
  916. std::string tInfo("");
  917. //执行版本删除流程
  918. if (nPackCount != 0) {
  919. int nSavedCount = 0;
  920. sort(intallInfoVects.begin(), intallInfoVects.end());
  921. vector<CVersion>::reverse_iterator riter = intallInfoVects.rbegin();
  922. while (riter != intallInfoVects.rend()) {
  923. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("InstallPackage Info: %s", (LPCTSTR)(*riter).ToString());
  924. if (++nSavedCount <= verSaved) {
  925. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Save above version");
  926. riter++;
  927. continue;
  928. }
  929. CSimpleStringA tVerPath;
  930. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  931. #ifdef RVC_OS_LINUX
  932. tVerPath = verPath + SPLIT_SLASH_STR + (*riter).ToString();
  933. #else
  934. tVerPath = verPath + "\\" + (*riter).ToString();
  935. #endif // RVC_OS_LINUX
  936. nFileCount = ProcessFileDelete(tVerPath.GetData(), nDelSuc, nDelFail, true); //版本文件夹连目录一起清理
  937. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete Version result(%s): count(%d), suc(%d), failed(%d).",
  938. tVerPath.GetData(), nFileCount, nDelSuc, nDelFail);
  939. if (nDelFail)
  940. {
  941. bFailFlag = true;
  942. }
  943. else
  944. {
  945. nDelVersionCnt++;
  946. tInfo = tInfo + "|" + std::string((*riter).ToString().GetData());
  947. }
  948. riter++;
  949. }
  950. }
  951. nLstFailed = bFailFlag ? 1 : 0;
  952. spConfigRun->WriteConfigValueHexInt("VersionClear", "OptVer", info.InstallVersion.GetVersion64());
  953. spConfigRun->WriteConfigValueInt("VersionClear", "DelVerCnt", nDelCount + nDelVersionCnt);
  954. spConfigRun->WriteConfigValueInt("VersionClear", "LastCondi", nLstFailed);
  955. spConfigRun->WriteConfigValue("VersionClear", "LastTime",
  956. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  957. if (nDelVersionCnt > 0) {
  958. std::string warn = "Delete Vesion file count : " + std::to_string((long long)nDelVersionCnt) + ". ----- " + tInfo + ".";
  959. LogWarn(Severity_Low, Error_Debug, LOG_WARN_VER_DELETE, CSimpleStringA::Format("%s", warn.c_str()));
  960. }
  961. }
  962. return TRUE;
  963. }
  964. void ResourceWatcherFSM::DeleteVideoFiles()
  965. {
  966. int backDays = 0, closeVideoClear = 0;
  967. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  968. CSmartPointer<IConfigInfo> spConfig;
  969. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  970. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseVideoClear", closeVideoClear);
  971. if (closeVideoClear)
  972. {
  973. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CenterSetting no need video clear.");
  974. return;
  975. }
  976. spConfig->ReadConfigValueInt("ResourceWatcher", "VideoBackDays", backDays);
  977. if (backDays <= 0)
  978. {
  979. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("video default backdays:30 days.");
  980. backDays = VIDEO_DEFAULT_BACKDAYS;
  981. }
  982. CSimpleStringA videoPath, verPath;
  983. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("LocalVideo", videoPath); //获取Video路径
  984. if (Error_Succeed == Error) {
  985. if (videoPath.IsNullOrEmpty()) {
  986. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get LocalVideo path NULL");
  987. return;
  988. }
  989. else
  990. {
  991. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("VIDEO PATH = %s.", videoPath.GetData());
  992. }
  993. }
  994. else
  995. {
  996. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get LocalVideo error. error = %u.", Error);
  997. return;
  998. }
  999. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  1000. nFileCount = ProcessFileDelete(videoPath.GetData(), nDelSuc, nDelFail, false, backDays);
  1001. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete [Video] result(%s): count(%d), suc(%d), failed(%d).", videoPath.GetData(), nFileCount, nDelSuc, nDelFail);
  1002. }
  1003. void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType,
  1004. CSmartPointer<ITransactionContext> pTransactionContext)
  1005. {
  1006. if (Test_ShakeHand == eTestType)
  1007. {
  1008. pTransactionContext->SendAnswer(Error_Succeed);
  1009. }
  1010. }
  1011. void ResourceWatcherFSM::HardwareInfoTimer(void* pData)
  1012. {
  1013. if (hardwareCheckFlag > 0) {
  1014. GetSystemCPUStatus();
  1015. GetSystemMemoryStatus();
  1016. }
  1017. GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, hardwareCheckTime);
  1018. }
  1019. void ResourceWatcherFSM::DiskCheckTimer(void* pData)
  1020. {
  1021. if (diskCheckFlag > 0) {
  1022. GetSystemDiskStatus();
  1023. }
  1024. GetEntityBase()->GetFunction()->ResetTimer(TIMER_DISK_CHECK, diskCheckTime);
  1025. }
  1026. ErrorCodeEnum ResourceWatcherFSM::CheckNetType(
  1027. SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
  1028. {
  1029. ErrorCodeEnum ec = Error_Succeed;
  1030. int netType = 0; //默认未知
  1031. #ifdef RVC_OS_LINUX
  1032. int i = 0;
  1033. int sockfd;
  1034. struct ifconf ifconf;
  1035. struct ifreq* ifreq;
  1036. char buf[1024];
  1037. //初始化ifconf
  1038. ifconf.ifc_len = 1024;
  1039. ifconf.ifc_buf = buf;
  1040. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  1041. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("socket error");
  1042. }
  1043. //获取所有接口信息
  1044. ioctl(sockfd, SIOCGIFCONF, &ifconf);
  1045. //逐个获取Ip地址
  1046. int size = ifconf.ifc_len / sizeof(struct ifreq);
  1047. ifreq = (struct ifreq*)buf;
  1048. string netName(ifreq->ifr_name);
  1049. if (size == 1 && netName == "lo") //只有逻辑地址 -- 网线被拔出
  1050. {
  1051. netType = 1;
  1052. }
  1053. else
  1054. {
  1055. for (i = size; i > 0; i--) {
  1056. string netName(ifreq->ifr_name); //有其他网卡 -- 有线
  1057. if (netName != "lo") {
  1058. netType = 2;
  1059. }
  1060. ifreq++;
  1061. }
  1062. }
  1063. #else
  1064. CoInitialize(NULL);
  1065. // 通过NLA接口获取网络状态
  1066. IUnknown* pUnknown = NULL;
  1067. bool bOnline = true;//是否在线
  1068. HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
  1069. IID_IUnknown, (void**)&pUnknown);
  1070. if (SUCCEEDED(Result)) {
  1071. INetworkListManager* pNetworkListManager = NULL;
  1072. if (pUnknown)
  1073. Result = pUnknown->QueryInterface(IID_INetworkListManager, (void
  1074. **)&pNetworkListManager);
  1075. if (SUCCEEDED(Result)) {
  1076. VARIANT_BOOL IsConnect = VARIANT_FALSE;
  1077. if (pNetworkListManager) {
  1078. //Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect); //检测互联网连接
  1079. Result = pNetworkListManager->get_IsConnected(&IsConnect); //检测本地网络
  1080. }
  1081. if (SUCCEEDED(Result)) {
  1082. bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
  1083. }
  1084. }
  1085. if (pNetworkListManager)
  1086. pNetworkListManager->Release();
  1087. }
  1088. if (pUnknown)
  1089. pUnknown->Release();
  1090. if (bOnline == true) {
  1091. netType = 2;
  1092. }
  1093. else
  1094. {
  1095. netType = 1;
  1096. }
  1097. #endif // RVC_OS_LINUX
  1098. if (ctx != NULL) {
  1099. ctx->Ans.netType = netType;
  1100. ctx->Answer(ec);
  1101. }
  1102. return ec;
  1103. }
  1104. ErrorCodeEnum ResourceWatcherFSM::GetBizLinks(
  1105. SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
  1106. {
  1107. LOG_FUNCTION();
  1108. ErrorCodeEnum ec = Error_Succeed;
  1109. int filter = ctx->Req.filter; //后续过滤使用
  1110. CAutoArray<CSimpleStringA> bizLinks;
  1111. CAutoArray<CSimpleStringA> bizNames;
  1112. CSmartPointer<IConfigInfo> spCtSettingConfig;
  1113. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  1114. if (filter == 0) //用户管理桌面业务网址
  1115. {
  1116. CSimpleStringA mLink(""), adLink(""), tLink("");
  1117. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
  1118. if (mLink.GetLength() != 0) {
  1119. CSimpleStringA tName = CSimpleStringA("主站点");
  1120. bizNames.Append(&tName, 0, 1);
  1121. bizLinks.Append(&mLink, 0, 1);
  1122. }
  1123. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrAd", adLink);
  1124. if (adLink.GetLength() != 0) {
  1125. CSimpleStringA tName = CSimpleStringA("广告站点");
  1126. bizNames.Append(&tName, 0, 1);
  1127. bizLinks.Append(&adLink, 0, 1);
  1128. }
  1129. int bizCnt = 0;
  1130. CSimpleStringA info(""), getLink("");
  1131. do {// 主站点|www.test.com
  1132. bizCnt++;
  1133. CSimpleStringA chineseName("");
  1134. CSimpleStringA url("");
  1135. getLink = CSimpleStringA("DesktopDetectUrl").Append(std::to_string(bizCnt).c_str());
  1136. spCtSettingConfig->ReadConfigValue("ResourceWatcher", getLink.GetData(), info);
  1137. if (info.GetLength() != 0) {
  1138. CAutoArray<CSimpleStringA> arr = info.Split('|');
  1139. int len = arr.GetCount();
  1140. if (len != 2) {
  1141. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s]Not Detect Url", info.GetData());
  1142. }
  1143. else
  1144. {
  1145. chineseName = arr[0];
  1146. url = arr[1];
  1147. bizNames.Append(&chineseName, 0, 1);
  1148. bizLinks.Append(&url, 0, 1);
  1149. }
  1150. }
  1151. } while (info.GetLength() != 0);
  1152. }
  1153. else if (filter == 1) //错误页集中配置、准入网址
  1154. {
  1155. int bizCnt = 0;
  1156. CSimpleStringA info(""), getLink("");
  1157. do {// 准入服务|AccessAuth|accessUrl
  1158. bizCnt++;
  1159. CSimpleStringA chineseName(""), entityName(""), key("");
  1160. CSimpleStringA url("");
  1161. getLink = CSimpleStringA("ErrPageDetectUrl").Append(std::to_string(bizCnt).c_str());
  1162. spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getLink, info);
  1163. if (info.GetLength() != 0) {
  1164. CAutoArray<CSimpleStringA> arr = info.Split('|');
  1165. int len = arr.GetCount();
  1166. if (len != 3) {
  1167. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s]Not errPage Check config info.", info.GetData());
  1168. }
  1169. else
  1170. {
  1171. chineseName = arr[0];
  1172. entityName = arr[1];
  1173. key = arr[2];
  1174. spCtSettingConfig->ReadConfigValue(entityName.GetData(), key.GetData(), url);
  1175. if (url.GetLength() != 0) {
  1176. bizNames.Append(&chineseName, 0, 1);
  1177. bizLinks.Append(&url, 0, 1);
  1178. }
  1179. else
  1180. {
  1181. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Get errPage detecet url failed. EntityName:(%s), Key:(%s).",
  1182. entityName.GetData(), key.GetData());
  1183. }
  1184. }
  1185. }
  1186. } while (info.GetLength() != 0);
  1187. }
  1188. ctx->Ans.bizLinks = bizLinks;
  1189. ctx->Ans.bizNames = bizNames;
  1190. if (ctx != NULL) {
  1191. ctx->Answer(ec);
  1192. }
  1193. return ec;
  1194. }
  1195. #ifdef _MSC_VER
  1196. bool ResourceWatcherFSM::CreateLinkFile(const CSimpleStringA& szStartAppPath, const CSimpleStringA& szAddCmdLine,
  1197. const CSimpleStringA& szDestLnkPath, const CSimpleStringA& szIconPath)
  1198. {
  1199. HRESULT hr = CoInitialize(NULL);
  1200. bool bRet = false;
  1201. if (SUCCEEDED(hr))
  1202. {
  1203. IShellLink* pShellLink;
  1204. hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pShellLink);
  1205. if (SUCCEEDED(hr))
  1206. {
  1207. pShellLink->SetPath(szStartAppPath);
  1208. string strTmp = szStartAppPath;
  1209. int nStart = strTmp.find_last_of("/\\");
  1210. pShellLink->SetWorkingDirectory(strTmp.substr(0, nStart).c_str());
  1211. pShellLink->SetArguments(szAddCmdLine);
  1212. if (szIconPath)
  1213. {
  1214. pShellLink->SetIconLocation(szIconPath, 0);
  1215. }
  1216. IPersistFile* pPersistFile;
  1217. hr = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile);
  1218. if (SUCCEEDED(hr))
  1219. {
  1220. hr = pPersistFile->Save(CSimpleStringA2W(szDestLnkPath).GetData(), FALSE);
  1221. if (SUCCEEDED(hr))
  1222. {
  1223. bRet = true;
  1224. }
  1225. pPersistFile->Release();
  1226. }
  1227. pShellLink->Release();
  1228. }
  1229. CoUninitialize();
  1230. }
  1231. return bRet;
  1232. }
  1233. void ResourceWatcherFSM::CreateLink(const CSimpleStringA& exePath, const CSimpleStringA& csVersion)
  1234. {
  1235. LPITEMIDLIST lp;
  1236. SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &lp);
  1237. CHAR lstr[100] = "";
  1238. SHGetPathFromIDList(lp, lstr);
  1239. CSimpleStringA s = lstr;
  1240. s += "\\可视柜台.lnk";
  1241. CSimpleStringA icoPath;
  1242. ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", icoPath);
  1243. icoPath = icoPath + "\\" + csVersion.GetData() + "\\bin\\VTM.ico";
  1244. if (!CreateLinkFile(exePath, "", s, icoPath))
  1245. {
  1246. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile DESKTOP fail");
  1247. }
  1248. SHGetSpecialFolderLocation(0, CSIDL_PROGRAMS, &lp);
  1249. memset(lstr, 0, strlen(lstr));
  1250. SHGetPathFromIDList(lp, lstr);
  1251. s = lstr;
  1252. s += "\\可视柜台.lnk";
  1253. if (!CreateLinkFile(exePath, "", s, icoPath))
  1254. {
  1255. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile CSIDL_PROGRAMS fail");
  1256. }
  1257. }
  1258. bool ResourceWatcherFSM::CopyExeToRoot(const CSimpleStringA& csVersion)
  1259. {
  1260. CSimpleStringA rootVerPath, exePath;
  1261. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  1262. exePath = rootVerPath + "\\VTM.exe";
  1263. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("exePath:%s", exePath.GetData());
  1264. if (rc == Error_Succeed)
  1265. {
  1266. CSimpleStringA srcExePath, csPath = rootVerPath;
  1267. srcExePath = rootVerPath + "\\" + csVersion.GetData() + "\\bin\\VTM.exe";
  1268. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("srcExePath:%s exePath:%s", srcExePath.GetData(), exePath.GetData());
  1269. if (!ExistsFileA(srcExePath)) {
  1270. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s is not exist!", srcExePath.GetData());
  1271. return false;
  1272. }
  1273. if (!CopyFileA(srcExePath.GetData(), exePath.GetData(), FALSE))
  1274. {
  1275. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CopyFileA Fail error :%d ", GetLastError());
  1276. return false;
  1277. }
  1278. }
  1279. else {
  1280. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetPath 4 RootVer failed: %s", SpStrError(rc));
  1281. return false;
  1282. }
  1283. return true;
  1284. }
  1285. bool ResourceWatcherFSM::GetVtmVersionFromActiveTxt(CSimpleStringA& csVersion)
  1286. {
  1287. bool bRet = false;
  1288. CSimpleStringA rootVerPath;
  1289. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
  1290. if (rc != Error_Succeed) {
  1291. LogWarn(Severity_Middle, Error_Exception, LOG_RESOURCEWATCHER_OPEN_ACTIVE_FAIL, "testActive fail , get RootVer path is failed");
  1292. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A06")("testActive fail , get RootVer path is failed!");
  1293. return false;
  1294. }
  1295. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s\\active.txt", rootVerPath.GetData());
  1296. FILE* pFile = fopen(strActiveFile.GetData(), "rb+");
  1297. if (pFile != NULL)
  1298. {
  1299. char szTemp[256] = {};
  1300. char szVersion[32] = {};
  1301. int n = fread(szTemp, 1, 256, pFile);
  1302. strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
  1303. csVersion = szVersion;
  1304. fclose(pFile);
  1305. bRet = true;
  1306. }
  1307. else
  1308. {
  1309. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open active.txt failed.");
  1310. bRet = false;
  1311. }
  1312. return bRet;
  1313. }
  1314. bool ResourceWatcherFSM::GetRegValue(HKEY hKey, LPCTSTR lpcszParam,
  1315. CHAR* pSzValue, DWORD* pDwSizeOfSz)
  1316. {
  1317. DWORD dwType = REG_SZ;
  1318. TCHAR szValue[MAX_PATH + 1] = { 0 };
  1319. DWORD dwSize = MAX_PATH * sizeof(CHAR);
  1320. LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, pDwSizeOfSz);
  1321. if (lResult == ERROR_SUCCESS) {
  1322. strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
  1323. return true;
  1324. }
  1325. else {
  1326. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"%s\" error, result=%ld.", lpcszParam, lResult);
  1327. return false;
  1328. }
  1329. }
  1330. void ResourceWatcherFSM::DetectAutoStartupCover()
  1331. {
  1332. const int nStartupType = DetectAutoStartupType();
  1333. ErrorCodeEnum rc = Error_InvalidState;
  1334. const int setType = InitialAutoStartupSetType();
  1335. bool toCheckAndDelteAutostartFile(false);
  1336. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("current startup type:%d, aim start type:%d", nStartupType, setType);
  1337. switch (setType)
  1338. {
  1339. case 1://将VBS改成EXE,前提是VBS必须已在注册表
  1340. if (nStartupType == 1) {
  1341. rc = ChangeAutoStartupWithExe();
  1342. }
  1343. break;
  1344. case 2: //设置使用EXE注册表自启动
  1345. if (nStartupType == 1 || nStartupType == 0 || nStartupType == 3) {
  1346. rc = ChangeAutoStartupWithExe();
  1347. if (rc == Error_Succeed && nStartupType == 3) {
  1348. toCheckAndDelteAutostartFile = true;
  1349. }
  1350. }
  1351. break;
  1352. case 5: //设置使用EXE注册表自启动(涵盖所有类型)
  1353. if (nStartupType == 1 || nStartupType == 0 || nStartupType == 3 || nStartupType == 4) {
  1354. rc = ChangeAutoStartupWithExe();
  1355. if (rc == Error_Succeed && (nStartupType == 3 || nStartupType == 4)) {
  1356. toCheckAndDelteAutostartFile = true;
  1357. }
  1358. }
  1359. break;
  1360. case 3: //不设置开机自启动
  1361. if (nStartupType == 1 || nStartupType == 2) {
  1362. rc = ChangeAutoStartupWithExe(false, true);
  1363. }
  1364. else if (nStartupType == 3 || nStartupType == 4) {
  1365. toCheckAndDelteAutostartFile = true;
  1366. }
  1367. break;
  1368. case 4: //恢复VBS启动(防止EXE启动失败)
  1369. if (nStartupType == 2 || nStartupType == 0) {
  1370. rc = ChangeAutoStartupWithExe(true);
  1371. }
  1372. break;
  1373. default:
  1374. break;
  1375. }
  1376. if (toCheckAndDelteAutostartFile) {
  1377. CSimpleStringA strLnkPath(true);
  1378. bool scriptTypeOrNot;
  1379. if (IsHasSetAutoStartupByFolder(strLnkPath, scriptTypeOrNot) && !strLnkPath.IsNullOrEmpty()) {
  1380. BOOL rmRet = RemoveFileA(strLnkPath);
  1381. if (!rmRet && ExistsFileA(strLnkPath)) {
  1382. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("remove auto start lnk file failed: %s, GLE=%u", strLnkPath.GetData(), GetLastError());
  1383. }
  1384. else {
  1385. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("remove auto start lnk file: %s", strLnkPath.GetData());
  1386. }
  1387. }
  1388. }
  1389. }
  1390. static int Is32R64Platform()
  1391. {
  1392. static int isWow64 = -1;
  1393. typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  1394. if (isWow64 == -1) {
  1395. BOOL bIsWow64 = FALSE;
  1396. LPFN_ISWOW64PROCESS fnIsWow64Process =
  1397. (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  1398. if (NULL != fnIsWow64Process) {
  1399. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
  1400. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("detect is running with 64bit or not failed: %u", GetLastError());
  1401. return -1;
  1402. }
  1403. else
  1404. {
  1405. isWow64 = bIsWow64 ? 1 : 0;
  1406. }
  1407. }
  1408. }
  1409. return isWow64;
  1410. }
  1411. int ResourceWatcherFSM::DetectAutoStartupType()
  1412. {
  1413. LOG_FUNCTION();
  1414. int vbsType = -1;
  1415. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  1416. if (Is32R64Platform() != 0) {
  1417. dwFlag |= KEY_WOW64_64KEY;
  1418. }
  1419. bool explorerSet = false;
  1420. CSimpleStringA regeditValue(true);
  1421. HKEY hKey;
  1422. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  1423. TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"),
  1424. 0, dwFlag, &hKey);
  1425. if (lResult == ERROR_SUCCESS) {
  1426. DWORD dwType = REG_SZ;
  1427. DWORD dwSize = MAX_PATH * sizeof(TCHAR);
  1428. TCHAR szValue[MAX_PATH + 1] = { 0 };
  1429. memset(szValue, '\0', MAX_PATH + 1);
  1430. lResult = RegQueryValueEx(hKey, "Shell", NULL, &dwType, (LPBYTE)szValue, &dwSize);
  1431. if (lResult == ERROR_SUCCESS) {
  1432. std::string strValue(szValue);
  1433. regeditValue = szValue;
  1434. strValue = SP::Utility::ToLower(strValue);
  1435. CSimpleStringA value(strValue.c_str());
  1436. if (value.IsStartWith("wscript", true) && value.IsEndWith(".vbs", true)) {
  1437. LogWarn(Severity_Low, Error_Debug, LOG_WARN_AUTO_STARTUP_FROM_REGIST, value);
  1438. vbsType = 1;
  1439. }
  1440. else if (value.IsEndWith("vtm.exe", true)) {
  1441. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_EXE, value);
  1442. vbsType = 2;
  1443. }
  1444. else if (value.Compare("explorer.exe") == 0) {
  1445. vbsType = 0;
  1446. explorerSet = true;
  1447. }
  1448. else {
  1449. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_UNKNOWN, value);
  1450. vbsType = 0;
  1451. }
  1452. }
  1453. else {
  1454. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
  1455. CSimpleStringA::Format("RegQueryValueEx error returned %u, GLE=%u.", lResult, GetLastError()));
  1456. }
  1457. }
  1458. else {
  1459. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
  1460. CSimpleStringA::Format("RegOpenKeyEx error, GLE=%u.", GetLastError()));
  1461. }
  1462. RegCloseKey(hKey);
  1463. if (vbsType == 0 || vbsType == -1) {
  1464. CSimpleStringA strLnkPath(true);
  1465. bool scriptType = false;
  1466. if (IsHasSetAutoStartupByFolder(strLnkPath, scriptType)) {
  1467. if (!scriptType) {
  1468. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_STARTMENU_FROMSETUP, strLnkPath);
  1469. vbsType = 3;
  1470. }
  1471. else {
  1472. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_STARTMENU_FROMSCRIPT, strLnkPath);
  1473. vbsType = 4;
  1474. }
  1475. }
  1476. else if (vbsType == 0 && explorerSet) {
  1477. LogWarn(Severity_Low, Error_Debug, LOG_WARN_NOT_AUTO_STARTUP_FROM_REGIST, regeditValue);
  1478. }
  1479. }
  1480. return vbsType;
  1481. }
  1482. ErrorCodeEnum ResourceWatcherFSM::ChangeAutoStartupWithExe(bool resetVBS, bool resetExplorer)
  1483. {
  1484. const char* exploreExe = "explorer.exe";
  1485. ErrorCodeEnum result(Error_Succeed);
  1486. CSimpleStringA exePath(true);
  1487. if (resetExplorer) {
  1488. exePath = exploreExe;
  1489. }
  1490. else
  1491. {
  1492. result = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
  1493. if (exePath.IsNullOrEmpty() || result != Error_Succeed) {
  1494. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")("Get RootVer path failed: %d", result);
  1495. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED, CSimpleStringA::Format("Get RootVer path failed: %d", result));
  1496. return Error_Unexpect;
  1497. }
  1498. if (!resetVBS)
  1499. exePath.Append("\\VTM.exe");
  1500. else
  1501. exePath.Append("\\spexplorerfast.vbs");
  1502. if (!ExistsFileA(exePath)) {
  1503. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")("[%s] is not existed!", exePath.GetData());
  1504. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED, CSimpleStringA::Format("[%s] is not existed!", exePath.GetData()));
  1505. return Error_NotExist;
  1506. }
  1507. }
  1508. DWORD dwFlag = KEY_WRITE;
  1509. if (Is32R64Platform() != 0) {
  1510. dwFlag |= KEY_WOW64_64KEY;
  1511. }
  1512. HKEY hKey;
  1513. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  1514. TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), 0, dwFlag, &hKey);
  1515. if (lResult == ERROR_SUCCESS) {
  1516. lResult = RegSetValueExA(hKey, "Shell", 0, REG_SZ, (const BYTE*)exePath.GetData(), exePath.GetLength());
  1517. if (lResult == ERROR_SUCCESS) {
  1518. LogWarn(Severity_Low, Error_Debug, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_SUCC
  1519. , CSimpleStringA::Format("RegSetValueExA for Shell with %s succ!", exePath.GetData()));
  1520. result = Error_Succeed;
  1521. }
  1522. else
  1523. {
  1524. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")
  1525. ("RegSetValueExA for Shell with %s failed: %d", exePath.GetData(), lResult);
  1526. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
  1527. , CSimpleStringA::Format("RegSetValueExA for Shell with %s failed: %d", exePath.GetData(), lResult));
  1528. result = Error_Unexpect;
  1529. }
  1530. }
  1531. else
  1532. {
  1533. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")
  1534. ("RegOpenKeyEx for write %s failed: %d", exePath.GetData(), lResult);
  1535. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
  1536. , CSimpleStringA::Format("RegOpenKeyEx for write %s failed: %d", exePath.GetData(), lResult));
  1537. result = Error_Unexpect;
  1538. }
  1539. RegCloseKey(hKey);
  1540. return result;
  1541. }
  1542. int ResourceWatcherFSM::InitialAutoStartupSetType()
  1543. {
  1544. int ret = 0;
  1545. CSmartPointer<IConfigInfo> spConfig;
  1546. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  1547. int value(0);
  1548. spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "AutoStartCMD", value);
  1549. if (value != 0) {
  1550. ret = value;
  1551. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get AutoStartCMD from CS: %d", ret);
  1552. }
  1553. return ret;
  1554. }
  1555. BOOL ResourceWatcherFSM::IsHasSetAutoStartupByFolder(CSimpleStringA& strPath, bool& scriptsType)
  1556. {
  1557. BOOL result(FALSE);
  1558. strPath.Clear();
  1559. scriptsType = false;
  1560. const char* STARTUP_DIR_FULL_PATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp";
  1561. const char* STRATUP_FILENAME_FROM_SCRIPTS = "spexplorerauto.lnk";
  1562. #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
  1563. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(ST测试).lnk";
  1564. #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
  1565. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(UAT测试).lnk";
  1566. #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
  1567. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
  1568. #elif defined(DEVOPS_ON_DEV)/*DevOps流水线编译,Dev环境*/
  1569. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(开发).lnk";
  1570. #else/*本地编译等非DevOps环境编译的版本*/
  1571. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
  1572. #endif
  1573. if (!ExistsDirA(STARTUP_DIR_FULL_PATH)) {
  1574. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] dir is not exist!", STARTUP_DIR_FULL_PATH);
  1575. return result;
  1576. }
  1577. strPath = STARTUP_DIR_FULL_PATH;
  1578. strPath += "\\";
  1579. strPath += CMB_LINK_FILE_NAME;
  1580. if (ExistsFileA(strPath)) {
  1581. result = TRUE;
  1582. }
  1583. else {
  1584. auto arr = fileutil_get_sub_files(STARTUP_DIR_FULL_PATH);
  1585. if (arr != NULL) {
  1586. for (int i = 0; i < arr->nelts; ++i) {
  1587. char* file = ARRAY_IDX(arr, i, char*);
  1588. char* filename = strrchr(file, '\\');
  1589. if (filename != NULL) { filename += 1; }
  1590. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("autostartup[%s]", filename);
  1591. if (filename != NULL/* && strcmp(filename, CMB_LINK_FILE_NAME) == 0*/) {
  1592. CSimpleStringA strfilename(filename);
  1593. if (strfilename.IsStartWith("招商银行可视柜台") && strfilename.IsEndWith(".lnk")) {
  1594. strPath = file;
  1595. result = TRUE;
  1596. break;
  1597. }
  1598. }
  1599. }
  1600. toolkit_array_free2(arr);
  1601. }
  1602. }
  1603. if (!result) {
  1604. CSimpleStringA fullStartFileNameFromScripts(STARTUP_DIR_FULL_PATH);
  1605. fullStartFileNameFromScripts += "\\";
  1606. fullStartFileNameFromScripts += STRATUP_FILENAME_FROM_SCRIPTS;
  1607. if (ExistsFileA(fullStartFileNameFromScripts)) {
  1608. strPath = fullStartFileNameFromScripts;
  1609. scriptsType = true;
  1610. result = TRUE;
  1611. }
  1612. else {
  1613. // Get and display the user name.
  1614. const DWORD INFO_BUFFER_SIZE = 2048;
  1615. char infoBuf[INFO_BUFFER_SIZE];
  1616. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  1617. DWORD bufCharCount = INFO_BUFFER_SIZE;
  1618. if (!GetUserName(infoBuf, &bufCharCount)) {
  1619. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetUserName failed, GLE=%u", GetLastError());
  1620. }
  1621. else {
  1622. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("User name:%s", infoBuf);
  1623. fullStartFileNameFromScripts = CSimpleStringA::Format("C:\\Users\\%s\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup", infoBuf);
  1624. fullStartFileNameFromScripts += "\\";
  1625. fullStartFileNameFromScripts += STRATUP_FILENAME_FROM_SCRIPTS;
  1626. if (ExistsFileA(fullStartFileNameFromScripts)) {
  1627. scriptsType = true;
  1628. strPath = fullStartFileNameFromScripts;
  1629. result = TRUE;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. return result;
  1635. }
  1636. void ResourceWatcherFSM::DetectVersionHasChangedAndWarn()
  1637. {
  1638. CSmartPointer<IConfigInfo> spRunConfig;
  1639. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  1640. UINT64 utVersion = 0;
  1641. spRunConfig->ReadConfigValueHexInt("VersionMonitor", "LastVer", utVersion);
  1642. CVersion lastVer(utVersion);
  1643. if (lastVer.IsValid() && lastVer > m_RvcSysinfo.InstallVersion) {
  1644. CSimpleStringA rootVerPath;
  1645. CSimpleStringA warnInfo = CSimpleStringA::Format("version changed from %s to %s", lastVer.ToString().GetData(), m_RvcSysinfo.InstallVersion.ToString().GetData());
  1646. GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  1647. CSimpleStringA csPath = rootVerPath + SPLIT_SLASH_STR + "active.txt";
  1648. if (!ExistsFileA(csPath)) {
  1649. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A0A").setAPI(__FUNCTION__)
  1650. ("%s: active.txt not exist!", warnInfo.GetData());
  1651. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt not exist!", warnInfo.GetData()));
  1652. }
  1653. else
  1654. {
  1655. CSimpleFileComponent activeFileInfo;
  1656. HANDLE hFile = CreateFileA(
  1657. csPath,
  1658. GENERIC_READ,
  1659. FILE_SHARE_READ,
  1660. NULL,
  1661. OPEN_EXISTING,
  1662. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
  1663. NULL);
  1664. if (hFile == INVALID_HANDLE_VALUE) {
  1665. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A0A").setAPI(__FUNCTION__)
  1666. ("%s: active.txt open failed %u", warnInfo.GetData(), GetLastError());
  1667. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt open failed %u", warnInfo.GetData(), GetLastError()));
  1668. }
  1669. else
  1670. {
  1671. GetFileTime(hFile, (LPFILETIME)&activeFileInfo.mftCreate,
  1672. (LPFILETIME)&activeFileInfo.mftAccess, (LPFILETIME)&activeFileInfo.mftModified);
  1673. CloseHandle(hFile);
  1674. char szFormat1[128] = { 0 };
  1675. GetTimeFormatStr(szFormat1, 128, (FILETIME*)&activeFileInfo.mftCreate);
  1676. char szFormat2[128] = { 0 };
  1677. GetTimeFormatStr(szFormat2, 128, (FILETIME*)&activeFileInfo.mftAccess);
  1678. char szFormat3[128] = { 0 };
  1679. GetTimeFormatStr(szFormat3, 128, (FILETIME*)&activeFileInfo.mftModified);
  1680. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A0A").setAPI(__FUNCTION__)
  1681. ("%s: active.txt create at %s, access at %s, modified at %s", warnInfo.GetData(), szFormat1, szFormat2, szFormat3);
  1682. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format(
  1683. "%s: active.txt create at %s, access at %s, modified at %s", warnInfo.GetData(), szFormat1, szFormat2, szFormat3));
  1684. }
  1685. }
  1686. }
  1687. if (!lastVer.IsValid() || lastVer != m_RvcSysinfo.InstallVersion) {
  1688. spRunConfig->WriteConfigValueHexInt("VersionMonitor", "LastVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  1689. }
  1690. }
  1691. void ResourceWatcherFSM::DetectDestopFileAndWarn(bool bClear, CSimpleStringA& strFileSaveList)
  1692. {
  1693. const DWORD INFO_BUFFER_SIZE = 2048;
  1694. char infoBuf[INFO_BUFFER_SIZE];
  1695. DWORD bufCharCount = INFO_BUFFER_SIZE;
  1696. char sys_disk = '\0';
  1697. bufCharCount = INFO_BUFFER_SIZE;
  1698. if (!GetComputerName(infoBuf, &bufCharCount))
  1699. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetComputerName failed, GLE=%u", GetLastError());
  1700. else DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Computer name: %s", infoBuf);
  1701. // Get and display the user name.
  1702. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  1703. bufCharCount = INFO_BUFFER_SIZE;
  1704. if (!GetUserName(infoBuf, &bufCharCount)) {
  1705. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetUserName failed, GLE=%u", GetLastError());
  1706. }
  1707. else
  1708. {
  1709. CSimpleStringA filelist(true);
  1710. int dirCount(0), fileCount(0);
  1711. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("User name: %s", infoBuf);
  1712. CSimpleStringA desktopFullPath = CSimpleStringA::Format("C:\\Users\\%s\\Desktop", infoBuf);
  1713. CSimpleStringA desktopPublicPath("C:\\Users\\Public\\Desktop");
  1714. CAutoArray<CSimpleStringA> desktopPaths;
  1715. desktopPaths.Init(2);
  1716. desktopPaths[0] = desktopFullPath;
  1717. desktopPaths[1] = desktopPublicPath;
  1718. for (int k = 0; k < desktopPaths.GetCount(); ++k) {
  1719. CSimpleStringA& curPath = desktopPaths[k];
  1720. auto arr = fileutil_get_sub_files(curPath);
  1721. if (arr != NULL) {
  1722. for (int i = 0; i < arr->nelts; ++i) {
  1723. char* file = ARRAY_IDX(arr, i, char*);
  1724. char* filename = strrchr(file, '\\');
  1725. if (filename != NULL) { filename += 1; }
  1726. else { filename = file; }
  1727. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("filename:%s", filename);
  1728. bool toRecord = true;
  1729. if (bClear) {
  1730. std::string strLowFileName = SP::Utility::ToLower(std::string(filename));
  1731. if (strFileSaveList.IsNullOrEmpty() || strFileSaveList.IndexOf(strLowFileName.c_str()) == -1) {
  1732. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("delete desktop file:%s", filename);
  1733. RemoveFileA(file);
  1734. if (!ExistsFileA(file)) {
  1735. toRecord = false;
  1736. }
  1737. }
  1738. else {
  1739. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("skip to delete: %s", filename);
  1740. }
  1741. }
  1742. if (toRecord) {
  1743. fileCount++;
  1744. if (!filelist.IsNullOrEmpty()) {
  1745. filelist += "|";
  1746. }
  1747. filelist += filename;
  1748. }
  1749. }
  1750. if (arr->nelts > 0) {
  1751. filelist += ";";
  1752. }
  1753. toolkit_array_free2(arr);
  1754. }
  1755. arr = fileutil_get_sub_dirs(curPath);
  1756. if (arr != NULL) {
  1757. for (int i = 0; i < arr->nelts; ++i) {
  1758. char* dir = ARRAY_IDX(arr, i, char*);
  1759. char* dirname = strrchr(dir, '\\');
  1760. if (dirname != NULL) { dirname += 1; }
  1761. else { dirname = dir; }
  1762. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("dir name:%s", dirname);
  1763. bool toRecord = true;
  1764. if (bClear) {
  1765. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("remove desktop dir:%s", dirname);
  1766. RemoveDirRecursiveA(dir);
  1767. if (!ExistsDirA(dir)) {
  1768. toRecord = false;
  1769. }
  1770. }
  1771. if (toRecord) {
  1772. dirCount++;
  1773. if (!filelist.IsNullOrEmpty() && i != 0) {
  1774. filelist += "|";
  1775. }
  1776. filelist += dirname;
  1777. }
  1778. }
  1779. if (arr->nelts > 0) {
  1780. filelist += ";";
  1781. }
  1782. toolkit_array_free2(arr);
  1783. }
  1784. }
  1785. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DESKTOP_FILESTATUS
  1786. ,CSimpleStringA::Format("{\"subject\":\"desktop_file\",\"clear_flag\":\"%d\",\"username\":\"%s\",\"file_count\":%d,\"dir_count\":%d,\"content\":\"%s\"}"
  1787. , bClear ? 1 : 0, infoBuf, fileCount, dirCount, filelist.GetLength() < 950 ? filelist.GetData() : (filelist.SubString(0, 950) + "....").GetData()));
  1788. }
  1789. }
  1790. ErrorCodeEnum ResourceWatcherFSM::DetectVTMInstalledBySetup(BOOL& fYes)
  1791. {
  1792. HKEY key;
  1793. ErrorCodeEnum result(Error_Succeed);
  1794. fYes = FALSE;
  1795. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{123BBC1D-8555-4E90-96CA-70E678FF5C24}_is1";
  1796. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
  1797. if (ERROR_SUCCESS == lResult) {
  1798. fYes = TRUE;
  1799. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
  1800. LogWarn(Severity_Low, Error_Debug, LOG_INFO_INSTALL_BY_SETUP, "Intalled by Setup");
  1801. }
  1802. else if (ERROR_FILE_NOT_FOUND == lResult)
  1803. {
  1804. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
  1805. fYes = FALSE;
  1806. }
  1807. else
  1808. {
  1809. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegOpenKeyEx For{123BBC1D-8555-4E90-96CA-70E678FF5C24} error, Result=%ld.", lResult);
  1810. fYes = FALSE;
  1811. result = Error_Unexpect;
  1812. }
  1813. RegCloseKey(key);
  1814. return result;
  1815. }
  1816. bool ResourceWatcherFSM::RegRdVtmVersion(CSimpleStringA& VTMpath, CSimpleStringA& vtmVersion)
  1817. {
  1818. bool bRet = false;
  1819. HKEY key;
  1820. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\VTM";
  1821. CSimpleStringA regParaPath = "path";
  1822. CSimpleStringA regParaVersion = "version";
  1823. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
  1824. char arrVTMpath[MAX_PATH] = { 0 }, arrVTMversion[MAX_PATH] = { 0 };
  1825. if (ERROR_SUCCESS == lResult)
  1826. {
  1827. DWORD dwValue = MAX_PATH * sizeof(CHAR);
  1828. bool res1 = GetRegValue(key, regParaPath, arrVTMpath, &dwValue);
  1829. if (res1) {
  1830. bRet = true;
  1831. VTMpath = arrVTMpath;
  1832. }
  1833. else {
  1834. bRet = false;
  1835. RegCloseKey(key);
  1836. return bRet;
  1837. }
  1838. dwValue = MAX_PATH * sizeof(CHAR);
  1839. bool res2 = GetRegValue(key, regParaVersion, arrVTMversion, &dwValue);
  1840. if (res2) {
  1841. bRet = true;
  1842. vtmVersion = arrVTMversion;
  1843. }
  1844. else {
  1845. bRet = false;
  1846. RegCloseKey(key);
  1847. return bRet;
  1848. }
  1849. }
  1850. else
  1851. {
  1852. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
  1853. bRet = false;
  1854. }
  1855. RegCloseKey(key);
  1856. return bRet;
  1857. }
  1858. bool ResourceWatcherFSM::RegWtVtmPath()
  1859. {
  1860. bool bRet = true;
  1861. HKEY key;
  1862. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
  1863. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
  1864. {
  1865. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
  1866. bRet = false;
  1867. }
  1868. DWORD dwDisposition;
  1869. regPath += "\\VTM";
  1870. if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
  1871. REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
  1872. {
  1873. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
  1874. bRet = false;
  1875. }
  1876. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
  1877. {
  1878. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  1879. bRet = false;
  1880. }
  1881. CSimpleStringA para = "path";
  1882. CSimpleStringA exePath;
  1883. ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
  1884. if (Error_Succeed == Error)
  1885. {
  1886. exePath += "\\VTM.exe";
  1887. if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)exePath.GetData(), MAX_PATH))
  1888. {
  1889. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set path value failed");
  1890. bRet = false;
  1891. }
  1892. }
  1893. else
  1894. {
  1895. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get path of VTM.exe failed.");
  1896. }
  1897. ::RegCloseKey(key);
  1898. return bRet;
  1899. }
  1900. bool ResourceWatcherFSM::RegWtVtmVersion()
  1901. {
  1902. bool bRet = true;
  1903. HKEY key;
  1904. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
  1905. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
  1906. {
  1907. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
  1908. bRet = false;
  1909. }
  1910. DWORD dwDisposition;
  1911. regPath += "\\VTM";
  1912. if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
  1913. REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
  1914. {
  1915. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
  1916. bRet = false;
  1917. }
  1918. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
  1919. {
  1920. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  1921. bRet = false;
  1922. }
  1923. CSimpleStringA para = "version";
  1924. CSimpleStringA csVersion;
  1925. if (GetVtmVersionFromActiveTxt(csVersion))
  1926. {
  1927. //RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH);
  1928. if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH))
  1929. {
  1930. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  1931. bRet = false;
  1932. }
  1933. }
  1934. else
  1935. {
  1936. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get version of VTM.exe failed.");
  1937. }
  1938. ::RegCloseKey(key);
  1939. return bRet;
  1940. }
  1941. bool ResourceWatcherFSM::RegOperation()
  1942. {
  1943. bool bRet = true;
  1944. CSimpleStringA csVersion, VtmRegPath, VtmRegVersion;
  1945. bool bGetActive = GetVtmVersionFromActiveTxt(csVersion);
  1946. bool bRegRead = RegRdVtmVersion(VtmRegPath, VtmRegVersion);
  1947. CSimpleStringA rootVerPath, exePath;
  1948. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  1949. exePath = rootVerPath + "\\VTM.exe";
  1950. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("csVersion :%s ,VtmRegVersion:%s ", csVersion.GetData(), VtmRegVersion.GetData());
  1951. if (!ExistsFileA(exePath) || !bGetActive || !bRegRead || (0 != VtmRegVersion.Compare(csVersion, true)))
  1952. {
  1953. if (!ExistsFileA(exePath) && !CopyExeToRoot(csVersion))
  1954. {
  1955. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Copy VTM.exe to version root fail.");
  1956. bRet = false;
  1957. }
  1958. else
  1959. {
  1960. if (!RegWtVtmPath())
  1961. {
  1962. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmPath failed.");
  1963. }
  1964. if (!RegWtVtmVersion())
  1965. {
  1966. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmVersion failed.");
  1967. }
  1968. CreateLink(exePath, csVersion);
  1969. }
  1970. }
  1971. return bRet;
  1972. }
  1973. bool ResourceWatcherFSM::UpdateExe()
  1974. {
  1975. int updateExe = 0;
  1976. CSmartPointer<IConfigInfo> spCtSettingConfig;
  1977. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  1978. spCtSettingConfig->ReadConfigValueInt("NonExclusive", "UpdateExe", updateExe);
  1979. if (updateExe == 1)
  1980. return true;
  1981. return false;
  1982. }
  1983. void ResourceWatcherFSM::VerifySignature()
  1984. {
  1985. LOG_FUNCTION();
  1986. CSimpleStringA strMsg(true);
  1987. char* buffer = new char[MAX_PATH];
  1988. getcwd(buffer, MAX_PATH);
  1989. strcat(buffer, "\\*");
  1990. DWORD elapsed = 0;
  1991. DWORD dwStart = GetTickCount();
  1992. DWORD dwEnd = GetTickCount();
  1993. VerifySignature(buffer);
  1994. if (m_nonSignedFiles.size() > 0)
  1995. {
  1996. CSimpleStringA fileList = "";
  1997. for (size_t i = 0; i < m_nonSignedFiles.size(); i++)
  1998. {
  1999. fileList += GetFileName(m_nonSignedFiles[i]);
  2000. if (i < m_nonSignedFiles.size() - 1)
  2001. fileList += ",";
  2002. }
  2003. int toDisplay = m_iNonSignedTotal < m_iNonSignedDisplay ? m_iNonSignedTotal : m_iNonSignedDisplay;
  2004. strMsg = CSimpleStringA::Format("共有%d个文件未签名,其中%d个为:%s.",
  2005. m_iNonSignedTotal, toDisplay, fileList.GetData());
  2006. }
  2007. dwEnd = GetTickCount();
  2008. elapsed = dwEnd - dwStart;
  2009. strMsg = strMsg + CSimpleStringA::Format("签名耗时:%dms", elapsed);
  2010. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_FILE_NOT_TRUSTED, (LPCTSTR)strMsg);
  2011. delete buffer;
  2012. }
  2013. void ResourceWatcherFSM::VerifySignature(const CSimpleStringA& filePath)
  2014. {
  2015. HANDLE hFind = NULL;
  2016. WIN32_FIND_DATA fileInfo;
  2017. DWORD64 dwSize = 0;
  2018. hFind = FindFirstFile(filePath, &fileInfo);
  2019. if (hFind == INVALID_HANDLE_VALUE)
  2020. return;
  2021. string strDirPath = filePath;
  2022. do
  2023. {
  2024. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  2025. {
  2026. if (!strcmp(fileInfo.cFileName, ".") || !strcmp(fileInfo.cFileName, ".."))
  2027. {
  2028. //Do nothing for "." and ".." folders
  2029. }
  2030. else
  2031. {
  2032. strDirPath.insert(strDirPath.find("*"), string(fileInfo.cFileName) + "\\");
  2033. VerifySignature(strDirPath.c_str());
  2034. strDirPath = filePath;
  2035. }
  2036. }
  2037. else
  2038. {
  2039. CSimpleStringA fileName = fileInfo.cFileName;
  2040. string strFileName = fileName;
  2041. string strFilePath;
  2042. if(strFileName.empty()
  2043. || (strFileName.rfind(".dll") != strFileName.length() - 4
  2044. && strFileName.rfind(".exe") != strFileName.length() - 4))
  2045. continue;
  2046. strFilePath = strDirPath;
  2047. strFilePath.replace(strFilePath.find("*"), strFilePath.length(), string(fileInfo.cFileName));
  2048. if (!RetrieveDigitalSignatureInfo(strFilePath.c_str()))
  2049. {
  2050. if (m_iNonSignedTotal < m_iNonSignedDisplay)
  2051. {
  2052. m_nonSignedFiles.push_back(strFilePath.c_str());
  2053. }
  2054. m_iNonSignedTotal++;
  2055. }
  2056. }
  2057. } while (FindNextFile(hFind, &fileInfo));
  2058. FindClose(hFind);
  2059. }
  2060. void ResourceWatcherFSM::DetectAndClearDesktopFile()
  2061. {
  2062. #if defined(RVC_OS_WIN)
  2063. CSmartPointer<IConfigInfo> spCtSettingConfig;
  2064. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  2065. int clearDesktopFlag(0);
  2066. CSimpleStringA strFileWhiteSheet(true);
  2067. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "ClearDesktopSwitch", clearDesktopFlag);
  2068. if (!!clearDesktopFlag) {
  2069. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DesktopWhiteSheet", strFileWhiteSheet);
  2070. if (!strFileWhiteSheet.IsNullOrEmpty()) {
  2071. std::string strLowFileName = SP::Utility::ToLower(std::string(strFileWhiteSheet.GetData()));
  2072. strFileWhiteSheet = strLowFileName.c_str();
  2073. }
  2074. }
  2075. DetectDestopFileAndWarn(!!clearDesktopFlag, strFileWhiteSheet);
  2076. #endif //RVC_OS_WIN
  2077. }
  2078. CSimpleStringA ResourceWatcherFSM::GetFileName(const CSimpleStringA& filePath)
  2079. {
  2080. CSimpleStringA tmp = filePath;
  2081. auto arrPath = tmp.Split('\\');
  2082. int size = arrPath.GetCount();
  2083. return arrPath[size - 1];
  2084. }
  2085. bool ResourceWatcherFSM::RetrieveDigitalSignatureInfo(const char* pFilePath)
  2086. {
  2087. HCERTSTORE hStore = NULL;
  2088. HCRYPTMSG hMsg = NULL;
  2089. WCHAR* wpFilePath = NULL;
  2090. int len = ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, NULL, 0);
  2091. if (len > 0) {
  2092. wpFilePath = new wchar_t[len + 1];
  2093. std::memset(wpFilePath, 0, (len + 1) * sizeof(wchar_t));
  2094. ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, &wpFilePath[0], len);
  2095. }
  2096. if (CryptQueryObject(CERT_QUERY_OBJECT_FILE,
  2097. wpFilePath,
  2098. CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
  2099. CERT_QUERY_FORMAT_FLAG_BINARY,
  2100. 0,
  2101. NULL,
  2102. NULL,
  2103. NULL,
  2104. &hStore,
  2105. &hMsg,
  2106. NULL))
  2107. {
  2108. DWORD dwCountSigners = 0;
  2109. DWORD dwcbSz = sizeof(dwCountSigners);
  2110. if (CryptMsgGetParam(hMsg, CMSG_SIGNER_COUNT_PARAM, 0, &dwCountSigners, &dwcbSz))
  2111. {
  2112. if (dwCountSigners != 0)
  2113. {
  2114. dwcbSz = 0;
  2115. CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwcbSz);
  2116. if (dwcbSz)
  2117. {
  2118. PCMSG_SIGNER_INFO pSignerInfo = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwcbSz];
  2119. if (pSignerInfo)
  2120. {
  2121. DWORD dwcbSz2 = dwcbSz;
  2122. if (CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, pSignerInfo, &dwcbSz) &&
  2123. dwcbSz == dwcbSz2)
  2124. {
  2125. if (VerifyFirstCertificate(hStore, pSignerInfo)
  2126. || VerifyOtherCertificate(pSignerInfo))
  2127. return true;
  2128. }
  2129. delete[] pSignerInfo;
  2130. pSignerInfo = NULL;
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. if (hStore != NULL)
  2137. {
  2138. CertCloseStore(hStore, 0);
  2139. hStore = NULL;
  2140. }
  2141. if (hMsg != NULL)
  2142. {
  2143. CryptMsgClose(hMsg);
  2144. hMsg = NULL;
  2145. }
  2146. return false;
  2147. }
  2148. bool ResourceWatcherFSM::VerifyFirstCertificate(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo)
  2149. {
  2150. CERT_INFO ci = { 0 };
  2151. ci.Issuer = pSignerInfo->Issuer;
  2152. ci.SerialNumber = pSignerInfo->SerialNumber;
  2153. PCCERT_CONTEXT pCertContext = NULL;
  2154. int c = 0;
  2155. bool ret = false;
  2156. for (;; c++)
  2157. {
  2158. pCertContext = CertFindCertificateInStore(hStore,
  2159. ENCODING, 0, CERT_FIND_SUBJECT_CERT,
  2160. (PVOID)&ci, pCertContext);
  2161. if (!pCertContext)
  2162. {
  2163. break;
  2164. }
  2165. DWORD dwcbSz;
  2166. char* pBuff;
  2167. dwcbSz = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
  2168. if (dwcbSz != 0)
  2169. {
  2170. pBuff = new (std::nothrow) char[dwcbSz];
  2171. if (pBuff)
  2172. {
  2173. if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, pBuff, dwcbSz) == dwcbSz)
  2174. {
  2175. if (!strcmp(pBuff, "China Merchants Bank Co., Ltd") || !strcmp(pBuff, "Microsoft Corporation"))
  2176. ret = true;
  2177. }
  2178. delete[] pBuff;
  2179. pBuff = NULL;
  2180. }
  2181. }
  2182. }
  2183. if (pCertContext)
  2184. {
  2185. CertFreeCertificateContext(pCertContext);
  2186. pCertContext = NULL;
  2187. }
  2188. return ret;
  2189. }
  2190. bool ResourceWatcherFSM::VerifyOtherCertificate(PCMSG_SIGNER_INFO pSignerInfo)
  2191. {
  2192. int ret = false;
  2193. for (DWORD a = 0; a < pSignerInfo->UnauthAttrs.cAttr; a++)
  2194. {
  2195. #ifndef szOID_NESTED_SIGNATURE
  2196. #define szOID_NESTED_SIGNATURE "1.3.6.1.4.1.311.2.4.1"
  2197. #endif
  2198. if (pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId &&
  2199. lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId, szOID_NESTED_SIGNATURE) == 0)
  2200. {
  2201. HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, 0, NULL, NULL, NULL);
  2202. if (hMsg)
  2203. {
  2204. if (::CryptMsgUpdate(hMsg,
  2205. pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData,
  2206. pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData,
  2207. TRUE))
  2208. {
  2209. DWORD dwSignerInfo = 0;
  2210. ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
  2211. if (dwSignerInfo != 0)
  2212. {
  2213. PCMSG_SIGNER_INFO pSignerInfo2 = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwSignerInfo];
  2214. if (pSignerInfo2)
  2215. {
  2216. if (::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM,
  2217. 0, (PVOID)pSignerInfo2, &dwSignerInfo))
  2218. {
  2219. CRYPT_DATA_BLOB c7Data;
  2220. c7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData;
  2221. c7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData;
  2222. //ret = FindAppropriateStoreAndVerifyFirstCertificate(pSignerInfo2, &c7Data);
  2223. HCERTSTORE hStore = NULL;
  2224. hStore = CertOpenStore(CERT_STORE_PROV_PKCS7, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, &c7Data);
  2225. ret = hStore && VerifyFirstCertificate(hStore, pSignerInfo2);
  2226. if (hStore)
  2227. {
  2228. ::CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
  2229. hStore = NULL;
  2230. }
  2231. }
  2232. delete[] pSignerInfo2;
  2233. pSignerInfo2 = NULL;
  2234. }
  2235. }
  2236. }
  2237. ::CryptMsgClose(hMsg);
  2238. }
  2239. }
  2240. }
  2241. return ret;
  2242. }
  2243. long long GetDirSizeFsm(string dirPath)
  2244. {
  2245. long long fileLen = 0;
  2246. long hFile = 0;
  2247. //文件信息
  2248. struct _finddata_t fileinfo;
  2249. string p;
  2250. if ((hFile = _findfirst(p.assign(dirPath).append("\\*").c_str(), &fileinfo)) != -1)
  2251. {
  2252. do
  2253. {
  2254. //如果是目录,迭代之
  2255. //如果不是,加入列表
  2256. if ((fileinfo.attrib & _A_SUBDIR))
  2257. {
  2258. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2259. fileLen += GetDirSizeFsm(p.assign(dirPath).append("\\").append(fileinfo.name));
  2260. }
  2261. else
  2262. {
  2263. fileLen += fileinfo.size;
  2264. }
  2265. } while (_findnext(hFile, &fileinfo) == 0);
  2266. _findclose(hFile);
  2267. }
  2268. return fileLen;
  2269. }
  2270. struct CmpByValueFromBiggest //从最大的排起
  2271. {
  2272. bool operator()(const pair<string, long>& l, const pair<string, long>& r) {
  2273. return l.second > r.second;
  2274. }
  2275. };
  2276. //unordered_map<string, long> fileSpace;
  2277. unordered_map<string, long> fileIncreasedSpace;
  2278. vector<pair<string, long>> sortFileIncreasedSpace;
  2279. unordered_map<string, long> fileSpace;
  2280. vector<pair<string, long>> sortFileSpace;
  2281. static bool spaceLock = false;
  2282. void ResourceWatcherFSM::CheckDiskFileSpace()
  2283. {
  2284. if (spaceLock)
  2285. {
  2286. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("当前已有硬盘扫描进行中,跳过。");
  2287. return;
  2288. }
  2289. else
  2290. {
  2291. spaceLock = true; //加锁
  2292. }
  2293. CSmartPointer<IConfigInfo> spConfigRun;
  2294. CSmartPointer<IConfigInfo> spCtSettingConfig;
  2295. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2296. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  2297. int lastDiskUsed = 0;
  2298. unsigned long long lastVer = 0;
  2299. int spaceIncrease = 0; //硬盘增长阈值
  2300. spConfigRun->ReadConfigValueHexInt("SpaceInfo", "OptVer", lastVer);
  2301. spConfigRun->ReadConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", lastDiskUsed);
  2302. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "DiskUsedIncreaseInt(GB)", spaceIncrease);
  2303. if (spaceIncrease == 0)
  2304. {
  2305. spaceIncrease = 5; //默认阈值5GB
  2306. }
  2307. if (!m_bNeedForceDiskCheck) //是否需要强制全盘扫描 - 硬盘使用过高是会强制
  2308. {
  2309. if (lastVer == m_RvcSysinfo.InstallVersion.GetVersion64())
  2310. {
  2311. if (lastDiskUsed != 0 && ((int)(GetDiskUsedByte() / (1024 * 1024 * 1024)) - lastDiskUsed) < spaceIncrease) //增长值判定
  2312. {
  2313. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("硬盘空间增长未超过阈值,无需扫描。");
  2314. if (spaceLock)
  2315. {
  2316. spaceLock = false; //释放锁
  2317. }
  2318. return;
  2319. }
  2320. else
  2321. {
  2322. //降低磁盘扫描频率
  2323. SYSTEMTIME localTime;
  2324. GetLocalTime(&localTime);
  2325. if (m_diskLastWarnHour != localTime.wHour)
  2326. {
  2327. m_diskLastWarnHour = localTime.wHour;
  2328. CSmartPointer<IConfigInfo> spConfigRun;
  2329. ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2330. if (eErr == Error_Succeed) {
  2331. spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  2332. }
  2333. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("硬盘增长超过阈值,重点目录扫描!");
  2334. }
  2335. else
  2336. {
  2337. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("磁盘增长最近1小时已扫描一次,暂不扫描。");
  2338. if (spaceLock)
  2339. {
  2340. spaceLock = false; //释放锁
  2341. }
  2342. return;
  2343. }
  2344. }
  2345. }
  2346. else
  2347. {
  2348. spConfigRun->WriteConfigValueHexInt("SpaceInfo", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  2349. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("新版本,重点目录扫描");
  2350. }
  2351. }
  2352. else
  2353. {
  2354. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("强制扫描。");
  2355. }
  2356. string path = "D:";
  2357. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("扫描D盘。");
  2358. long long fileLen = 0;
  2359. long hFile = 0;
  2360. //文件信息
  2361. struct _finddata_t fileinfo;
  2362. string p;
  2363. if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
  2364. {
  2365. do
  2366. {
  2367. //如果是目录,迭代之
  2368. //如果不是,加入列表
  2369. if ((fileinfo.attrib & _A_SUBDIR))
  2370. {
  2371. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2372. fileLen = GetDirSizeFsm(p.assign(path).append("\\").append(fileinfo.name));
  2373. else
  2374. {
  2375. continue;
  2376. }
  2377. }
  2378. else
  2379. {
  2380. fileLen = fileinfo.size;
  2381. }
  2382. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  2383. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  2384. {
  2385. DOUBLE len = (DOUBLE)fileLen / 1024;
  2386. resLen = CSimpleStringA::Format("%.2f KB", len);
  2387. }
  2388. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  2389. {
  2390. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  2391. resLen = CSimpleStringA::Format("%.2f MB", len);
  2392. }
  2393. else if (fileLen >= (1024 * 1024 * 1024))
  2394. {
  2395. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  2396. resLen = CSimpleStringA::Format("%.2f GB", len);
  2397. }
  2398. CSimpleStringA oldLenStr("");
  2399. long oldLen = 0;
  2400. spConfigRun->ReadConfigValue("SpaceInfo",
  2401. p.assign(path).append("\\").append(fileinfo.name).c_str(), oldLenStr);
  2402. oldLen = atol(oldLenStr.GetData());
  2403. fileIncreasedSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  2404. fileSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  2405. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  2406. p.assign(path).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  2407. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2408. {
  2409. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\").append(fileinfo.name).c_str(),
  2410. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  2411. }
  2412. } while (_findnext(hFile, &fileinfo) == 0);
  2413. _findclose(hFile);
  2414. }
  2415. //获取version目录下的文件夹大小
  2416. CSimpleStringA csPath;
  2417. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  2418. fileLen = 0;
  2419. hFile = 0;
  2420. p = "";
  2421. if ((hFile = _findfirst(p.assign(csPath.GetData()).append("\\*").c_str(), &fileinfo)) != -1)
  2422. {
  2423. do
  2424. {
  2425. //如果是目录,迭代之
  2426. //如果不是,加入列表
  2427. if ((fileinfo.attrib & _A_SUBDIR))
  2428. {
  2429. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2430. fileLen = GetDirSizeFsm(p.assign(csPath.GetData()).append("\\").append(fileinfo.name));
  2431. else
  2432. {
  2433. continue;
  2434. }
  2435. }
  2436. else
  2437. {
  2438. fileLen = fileinfo.size;
  2439. }
  2440. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  2441. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  2442. {
  2443. DOUBLE len = (DOUBLE)fileLen / 1024;
  2444. resLen = CSimpleStringA::Format("%.2f KB", len);
  2445. }
  2446. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  2447. {
  2448. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  2449. resLen = CSimpleStringA::Format("%.2f MB", len);
  2450. }
  2451. else if (fileLen >= (1024 * 1024 * 1024))
  2452. {
  2453. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  2454. resLen = CSimpleStringA::Format("%.2f GB", len);
  2455. }
  2456. CSimpleStringA oldLenStr(""); //MB
  2457. long oldLen = 0;
  2458. spConfigRun->ReadConfigValue("SpaceInfo",
  2459. p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), oldLenStr);
  2460. oldLen = atol(oldLenStr.GetData());
  2461. fileIncreasedSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  2462. fileSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  2463. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  2464. p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  2465. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2466. {
  2467. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(),
  2468. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  2469. }
  2470. } while (_findnext(hFile, &fileinfo) == 0);
  2471. _findclose(hFile);
  2472. }
  2473. //获取rvc目录下的文件夹大小
  2474. fileLen = 0;
  2475. hFile = 0;
  2476. p = "";
  2477. if ((hFile = _findfirst(p.assign(path).append("\\rvc\\*").c_str(), &fileinfo)) != -1)
  2478. {
  2479. do
  2480. {
  2481. //如果是目录,迭代之
  2482. //如果不是,加入列表
  2483. if ((fileinfo.attrib & _A_SUBDIR))
  2484. {
  2485. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2486. fileLen = GetDirSizeFsm(p.assign(path).append("\\rvc\\").append(fileinfo.name));
  2487. else
  2488. {
  2489. continue;
  2490. }
  2491. }
  2492. else
  2493. {
  2494. fileLen = fileinfo.size;
  2495. }
  2496. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  2497. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  2498. {
  2499. DOUBLE len = (DOUBLE)fileLen / 1024;
  2500. resLen = CSimpleStringA::Format("%.2f KB", len);
  2501. }
  2502. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  2503. {
  2504. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  2505. resLen = CSimpleStringA::Format("%.2f MB", len);
  2506. }
  2507. else if (fileLen >= (1024 * 1024 * 1024))
  2508. {
  2509. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  2510. resLen = CSimpleStringA::Format("%.2f GB", len);
  2511. }
  2512. CSimpleStringA oldLenStr("");
  2513. long oldLen = 0;
  2514. spConfigRun->ReadConfigValue("SpaceInfo",
  2515. p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), oldLenStr);
  2516. oldLen = atol(oldLenStr.GetData());
  2517. fileIncreasedSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  2518. fileSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  2519. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  2520. p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), resLen.GetData());
  2521. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2522. {
  2523. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(),
  2524. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  2525. }
  2526. } while (_findnext(hFile, &fileinfo) == 0);
  2527. _findclose(hFile);
  2528. }
  2529. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2530. {
  2531. //写入硬盘量
  2532. spConfigRun->WriteConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", GetDiskUsedByte() / (1024 * 1024 * 1024));
  2533. if (spaceLock)
  2534. {
  2535. spaceLock = false; //释放锁
  2536. }
  2537. return; //新版本无需上报文件信息,更新完运行时文件后即可结束
  2538. }
  2539. //获取增量最大的前十文件夹信息
  2540. sortFileIncreasedSpace = vector<pair<string, long>>(fileIncreasedSpace.begin(), fileIncreasedSpace.end());
  2541. sort(sortFileIncreasedSpace.begin(), sortFileIncreasedSpace.end(), CmpByValueFromBiggest());
  2542. int topFileNum = sortFileIncreasedSpace.size();
  2543. if (topFileNum > 10)
  2544. {
  2545. topFileNum = 10;
  2546. }
  2547. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("变化最大的%d个文件夹信息。", topFileNum);
  2548. fileLen = 0;
  2549. for (int i = 0; i < topFileNum; i++)
  2550. {
  2551. fileLen = sortFileIncreasedSpace[i].second;
  2552. if (fileLen == 0) break;
  2553. CSimpleStringA warn1 = CSimpleStringA::Format("TOP %d: [%s], 增量[%ld]MB",
  2554. i + 1, sortFileIncreasedSpace[i].first.c_str(), sortFileIncreasedSpace[i].second);
  2555. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPINCREASED_SPACE, warn1.GetData());
  2556. }
  2557. if (m_bNeedForceDiskCheck)
  2558. {
  2559. //获取空间占用最大前十文件夹信息
  2560. sortFileSpace = vector<pair<string, long>>(fileSpace.begin(), fileSpace.end());
  2561. sort(sortFileSpace.begin(), sortFileSpace.end(), CmpByValueFromBiggest());
  2562. int topFileSize = sortFileSpace.size();
  2563. if (topFileSize > 10)
  2564. {
  2565. topFileSize = 10;
  2566. }
  2567. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("空间占用最大的%d个文件夹信息。", topFileSize);
  2568. fileLen = 0;
  2569. for (int i = 0; i < topFileSize; i++)
  2570. {
  2571. fileLen = sortFileSpace[i].second;
  2572. if (fileLen == 0) break;
  2573. CSimpleStringA warn2 = CSimpleStringA::Format("空间占用排名 %d: [%s], 大小[%ld]MB",
  2574. i + 1, sortFileSpace[i].first.c_str(), sortFileSpace[i].second);
  2575. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warn2.GetData());
  2576. }
  2577. m_bNeedForceDiskCheck = false;
  2578. }
  2579. if (spaceLock)
  2580. {
  2581. spaceLock = false; //释放锁
  2582. }
  2583. }
  2584. void ResourceWatcherFSM::GetSystemDiskStatus()
  2585. {
  2586. if (m_diskHighPercent <= 0)
  2587. {
  2588. m_diskHighPercent = 90; //默认硬盘告警百分比90%
  2589. }
  2590. ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
  2591. BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
  2592. if (ret == 0)
  2593. {
  2594. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
  2595. return;
  2596. }
  2597. CSimpleStringA csBinPath;
  2598. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
  2599. DWORD dwAvFree = ulAvailFree.QuadPart / MILLION;
  2600. DWORD dwTotal = ulTotalBytes.QuadPart / MILLION;
  2601. DWORD dwTotalFree = ulTotalFree.QuadPart / MILLION;
  2602. int ratio = dwTotalFree * 100 / dwTotal;
  2603. if ((100 - ratio) > m_diskHighPercent)
  2604. {
  2605. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The disk has %d MB(%d%%) available.\n", dwTotalFree, ratio);
  2606. string test(csBinPath.GetData());
  2607. char diskMessage[1024];
  2608. sprintf(diskMessage, "{\"Disk\":\"%c:\",\"total\":\"%0.2f GByte\",\"free ratio\":\"%d%%\"}",
  2609. csBinPath.GetData()[0], (double)dwTotal / 1024, ratio);
  2610. //oilyang@20200526 根据wq建议,降低磁盘空间偏少的告警频率
  2611. //SYSTEMTIME localTime;
  2612. //GetLocalTime(&localTime);
  2613. //if (m_diskLastWarnHour != localTime.wHour) //需要告警时才强制全盘扫描
  2614. //{
  2615. // m_diskLastWarnHour = localTime.wHour;
  2616. // CSmartPointer<IConfigInfo> spConfigRun;
  2617. // ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2618. // if (eErr == Error_Succeed) {
  2619. // spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  2620. // }
  2621. // //LogWarn(Severity_Low, Error_Resource, LOG_EVT_SELFCHECK_HARDDISK_TOO_HIGH, "Harddisk free space is few.");
  2622. // LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, diskMessage);
  2623. // m_bNeedForceDiskCheck = true;
  2624. //}
  2625. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, diskMessage);
  2626. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A05").setAPI("DiskUsedCheck")(diskMessage);
  2627. m_bNeedForceDiskCheck = true;
  2628. }
  2629. else
  2630. {
  2631. m_bNeedForceDiskCheck = false;
  2632. }
  2633. CheckDiskFileSpaceTask* task4 = new CheckDiskFileSpaceTask(this);
  2634. GetEntityBase()->GetFunction()->PostThreadPoolTask(task4);
  2635. }
  2636. ULONGLONG ResourceWatcherFSM::GetDiskUsedByte()
  2637. {
  2638. ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
  2639. BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
  2640. if (ret == 0)
  2641. {
  2642. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
  2643. return -1;
  2644. }
  2645. CSimpleStringA csBinPath;
  2646. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
  2647. return ulTotalBytes.QuadPart - ulTotalFree.QuadPart;
  2648. }
  2649. __int64 Filetime2Int64(const FILETIME& ftime)
  2650. {
  2651. LARGE_INTEGER li;
  2652. li.LowPart = ftime.dwLowDateTime;
  2653. li.HighPart = ftime.dwHighDateTime;
  2654. return li.QuadPart;
  2655. }
  2656. __int64 CompareFileTime2(const FILETIME& preTime, const FILETIME& nowTime)
  2657. {
  2658. return Filetime2Int64(nowTime) - Filetime2Int64(preTime);
  2659. }
  2660. unordered_map<int, long long> oldProcessTime;
  2661. unordered_map<int, long long> newProcessTime;
  2662. unordered_map<int, CSimpleStringA> processName;
  2663. unordered_map<int, double> processCpu;
  2664. bool cmp(const pair<int, double>& a, const pair<int, double>& b) {
  2665. return a.second > b.second;
  2666. }
  2667. void ResourceWatcherFSM::GetSystemCPUStatus()
  2668. {
  2669. oldProcessTime.clear();
  2670. newProcessTime.clear();
  2671. processName.clear();
  2672. processCpu.clear();
  2673. FILETIME preIdleTime;
  2674. FILETIME preKernelTime;
  2675. FILETIME preUserTime;
  2676. FILETIME preProcCreateTime;
  2677. FILETIME preProcExitTime;
  2678. FILETIME preProcKernelTime;
  2679. FILETIME preProcUserTime;
  2680. GetSystemTimes(&preIdleTime, &preKernelTime, &preUserTime);
  2681. PROCESSENTRY32 pe32Old;
  2682. pe32Old.dwSize = sizeof(pe32Old);
  2683. //获得系统进程快照的句柄
  2684. HANDLE hProcessSnapOld = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  2685. if (hProcessSnapOld == INVALID_HANDLE_VALUE)
  2686. {
  2687. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  2688. return;
  2689. }
  2690. //首先获得第一个进程
  2691. BOOL bProcessOld = Process32First(hProcessSnapOld, &pe32Old);
  2692. //循环获得所有进程
  2693. while (bProcessOld)
  2694. {
  2695. //进程名和进程ID
  2696. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32Old.th32ProcessID);
  2697. GetProcessTimes(hProcess, &preProcCreateTime, &preProcExitTime, &preProcKernelTime, &preProcUserTime);
  2698. oldProcessTime[pe32Old.th32ProcessID] = Filetime2Int64(preProcKernelTime) + Filetime2Int64(preProcUserTime);
  2699. bProcessOld = Process32Next(hProcessSnapOld, &pe32Old);
  2700. }
  2701. CloseHandle(hProcessSnapOld);
  2702. // 等待一段时间
  2703. Sleep(100); // 100毫秒
  2704. ULONGLONG deltaTime = 100 * 1000000; // 100毫秒转换为纳秒
  2705. FILETIME idleTime;
  2706. FILETIME kernelTime;
  2707. FILETIME userTime;
  2708. FILETIME ProcCreateTime;
  2709. FILETIME ProcExitTime;
  2710. FILETIME procKernelTime;
  2711. FILETIME procUserTime;
  2712. GetSystemTimes(&idleTime, &kernelTime, &userTime);
  2713. PROCESSENTRY32 pe32New;
  2714. pe32New.dwSize = sizeof(pe32New);
  2715. //获得系统进程快照的句柄
  2716. HANDLE hProcessSnapNew = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  2717. if (hProcessSnapNew == INVALID_HANDLE_VALUE)
  2718. {
  2719. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  2720. return;
  2721. }
  2722. //首先获得第一个进程
  2723. BOOL bProcessNew = Process32First(hProcessSnapNew, &pe32New);
  2724. //循环获得所有进程
  2725. while (bProcessNew)
  2726. {
  2727. //进程名和进程ID
  2728. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32New.th32ProcessID);
  2729. GetProcessTimes(hProcess, &ProcCreateTime, &ProcExitTime, &procKernelTime, &procUserTime);
  2730. newProcessTime[pe32New.th32ProcessID] = Filetime2Int64(procKernelTime) + Filetime2Int64(procUserTime);
  2731. processName[pe32New.th32ProcessID] = CSimpleStringA(pe32New.szExeFile);
  2732. bProcessNew = Process32Next(hProcessSnapNew, &pe32New);
  2733. }
  2734. CloseHandle(hProcessSnapNew);
  2735. auto idle = CompareFileTime2(preIdleTime, idleTime);
  2736. auto kernel = CompareFileTime2(preKernelTime, kernelTime);
  2737. auto user = CompareFileTime2(preUserTime, userTime);
  2738. if (kernel + user == 0)
  2739. return;
  2740. CSystemRunInfo runInfo = { 0 };
  2741. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  2742. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
  2743. {
  2744. runInfo.strRunningEntityNames[i];
  2745. CEntityRunInfo entityInfo = { 0 };
  2746. GetEntityBase()->GetFunction()->GetEntityRunInfo(runInfo.strRunningEntityNames[i].GetData(), entityInfo);
  2747. processName[entityInfo.dwProcessID] = runInfo.strRunningEntityNames[i];
  2748. }
  2749. unordered_map<int, long long>::iterator it;
  2750. for (it = newProcessTime.begin(); it != newProcessTime.end(); ++it)
  2751. {
  2752. int tPid = it->first;
  2753. //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
  2754. if (oldProcessTime.find(tPid) == oldProcessTime.end())
  2755. {
  2756. continue;
  2757. }
  2758. // 转换为百分比
  2759. double tRatio = 100.0 * (newProcessTime[tPid] - oldProcessTime[tPid]) / deltaTime;
  2760. if (tRatio > 0.0);
  2761. {
  2762. processCpu[tPid] = tRatio;
  2763. }
  2764. }
  2765. vector<pair<int, double>> vec(processCpu.begin(), processCpu.end());
  2766. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  2767. int len = min(10, vec.size());
  2768. CSimpleStringA procWarn = "";
  2769. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  2770. {
  2771. procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.2f", vec[i].second) + "%\"";
  2772. }
  2773. double cpuRatio = 100.0 * (kernel + user - idle) / (kernel + user);
  2774. if (m_cpuHighPercent <= 0)
  2775. {
  2776. m_cpuHighPercent = 80; //默认告警百分比80%
  2777. }
  2778. if (cpuWarnThreshold <= 0)
  2779. {
  2780. cpuWarnThreshold = 10; //默认满10次告一次警
  2781. }
  2782. if (cpuRatio > (double)m_cpuHighPercent)
  2783. {
  2784. cpuWarnTime = cpuWarnTime % cpuWarnThreshold;
  2785. if (cpuWarnTime == 0) //每达到一次阈值告警一次
  2786. {
  2787. CSimpleStringA warn = CSimpleStringA::Format("{\"type\":\"cpu\", \"total_used\":\" %.2f", cpuRatio);
  2788. warn = warn + "%\"" + procWarn + "}";
  2789. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, warn.GetData());
  2790. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A03").setAPI("CpuUsedCheck")(warn.GetData());
  2791. if (cpuRatio > 98) //cpu极端异常情况
  2792. {
  2793. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_ERROR, warn.GetData());
  2794. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A02")(warn.GetData());
  2795. }
  2796. }
  2797. cpuWarnTime++;
  2798. }
  2799. }
  2800. unsigned long long convert_time_format(const FILETIME* ftime)
  2801. {
  2802. LARGE_INTEGER li;
  2803. li.LowPart = ftime->dwLowDateTime;
  2804. li.HighPart = ftime->dwHighDateTime;
  2805. return li.QuadPart;
  2806. }
  2807. /// 时间转换
  2808. static uint64_t file_time_2_utc(const FILETIME* ftime)
  2809. {
  2810. LARGE_INTEGER li;
  2811. li.LowPart = ftime->dwLowDateTime;
  2812. li.HighPart = ftime->dwHighDateTime;
  2813. return li.QuadPart;
  2814. }
  2815. /// 获得CPU的核数
  2816. static int get_processor_number()
  2817. {
  2818. SYSTEM_INFO info;
  2819. GetSystemInfo(&info);
  2820. return (int)info.dwNumberOfProcessors;
  2821. }
  2822. int ResourceWatcherFSM::GetCpuUsageRatio(int pid)
  2823. {
  2824. //cpu数量
  2825. static int processor_count_ = -1;
  2826. //上一次的时间
  2827. static int64_t last_time_ = 0;
  2828. static int64_t last_system_time_ = 0;
  2829. FILETIME now;
  2830. FILETIME creation_time;
  2831. FILETIME exit_time;
  2832. FILETIME kernel_time;
  2833. FILETIME user_time;
  2834. int64_t system_time;
  2835. int64_t time;
  2836. int64_t system_time_delta;
  2837. int64_t time_delta;
  2838. int cpu = -1;
  2839. if (processor_count_ == -1)
  2840. {
  2841. processor_count_ = get_processor_number();
  2842. }
  2843. GetSystemTimeAsFileTime(&now);
  2844. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
  2845. if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
  2846. {
  2847. return -1;
  2848. }
  2849. system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time))
  2850. / processor_count_;
  2851. time = file_time_2_utc(&now);
  2852. if ((last_system_time_ == 0) || (last_time_ == 0))
  2853. {
  2854. last_system_time_ = system_time;
  2855. last_time_ = time;
  2856. return -1;
  2857. }
  2858. system_time_delta = system_time - last_system_time_;
  2859. time_delta = time - last_time_;
  2860. if (time_delta == 0)
  2861. return -1;
  2862. cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta);
  2863. last_system_time_ = system_time;
  2864. last_time_ = time;
  2865. return cpu;
  2866. }
  2867. double GetMemoryUsageGB(int pid)
  2868. {
  2869. #ifdef WIN32
  2870. DWORDLONG mem = 0, vmem = 0;
  2871. PROCESS_MEMORY_COUNTERS pmc;
  2872. // get process hanlde by pid
  2873. HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  2874. if (GetProcessMemoryInfo(process, &pmc, sizeof(pmc)))
  2875. {
  2876. mem = pmc.WorkingSetSize;
  2877. vmem = pmc.PagefileUsage;
  2878. }
  2879. CloseHandle(process);
  2880. // use GetCurrentProcess() can get current process and no need to close handle
  2881. // convert mem from B to GB
  2882. double memGB = mem / (1024.0 * 1024.0 * 1024.0);
  2883. return memGB;
  2884. #else
  2885. char file_name[64] = { 0 };
  2886. FILE* fd;
  2887. char line_buff[512] = { 0 };
  2888. sprintf(file_name, "/proc/%d/status", pid);
  2889. fd = fopen(file_name, "r");
  2890. if (nullptr == fd)
  2891. return 0;
  2892. char name[64];
  2893. int vmrss = 0;
  2894. for (int i = 0; i < VMRSS_LINE - 1; i++)
  2895. fgets(line_buff, sizeof(line_buff), fd);
  2896. fgets(line_buff, sizeof(line_buff), fd);
  2897. sscanf(line_buff, "%s %d", name, &vmrss);
  2898. fclose(fd);
  2899. // cnvert VmRSS from KB to MB
  2900. return vmrss / 1024.0;
  2901. #endif
  2902. }
  2903. unordered_map<int, double> processMem;
  2904. void ResourceWatcherFSM::GetSystemMemoryStatus()
  2905. {
  2906. MEMORYSTATUSEX statex;
  2907. statex.dwLength = sizeof(statex);
  2908. GlobalMemoryStatusEx(&statex);
  2909. double totalMem = statex.ullTotalPhys / (1024.0 * 1024.0 * 1024.0); //GB
  2910. unordered_map<int, CSimpleStringA>::iterator it;
  2911. for (it = processName.begin(); it != processName.end(); ++it)
  2912. {
  2913. int tPid = it->first;
  2914. double tmp = GetMemoryUsageGB(it->first);
  2915. if (tmp > 0.0 && tmp < 100)
  2916. {
  2917. processMem[tPid] = 100 * (tmp / totalMem);
  2918. }
  2919. }
  2920. //return;
  2921. vector<pair<int, double>> vec(processMem.begin(), processMem.end());
  2922. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  2923. int len = min(10, vec.size());
  2924. CSimpleStringA procWarn = "";
  2925. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  2926. {
  2927. procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.1f", vec[i].second) + "%\"";
  2928. }
  2929. if (m_memHighPercent <= 0)
  2930. {
  2931. m_memHighPercent = 80; //默认告警百分比80%
  2932. }
  2933. if (memWarnThreshold <= 0)
  2934. {
  2935. memWarnThreshold = 10; //默认告警阈值10次
  2936. }
  2937. if (statex.dwMemoryLoad > m_memHighPercent)
  2938. {
  2939. memWarnTime = memWarnTime % memWarnThreshold;
  2940. if (memWarnTime == 0) //每达到阈值告警一次
  2941. {
  2942. CSimpleStringA warn = CSimpleStringA::Format("{\"type\":\"mem\", \"total\":\"%.1f GByte\",\"total_used\":\" %d%%\"", totalMem, statex.dwMemoryLoad);
  2943. warn = warn + procWarn + "}";
  2944. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, warn.GetData());
  2945. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A04").setAPI("MemUsedCheck")(warn.GetData());
  2946. }
  2947. memWarnTime++;
  2948. }
  2949. }
  2950. int ResourceWatcherFSM::IsWifiConnected()
  2951. {
  2952. DWORD service_ver;
  2953. HANDLE handle = NULL;
  2954. int result = -1;
  2955. DWORD err = WlanOpenHandle(WLAN_API_VERSION, NULL, &service_ver, &handle);
  2956. if (err != 0) {
  2957. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("open wlan handle failed %d", err);
  2958. return result;
  2959. }
  2960. PWLAN_INTERFACE_INFO_LIST info_list = NULL;
  2961. PWLAN_INTERFACE_INFO interface_info = NULL;
  2962. err = WlanEnumInterfaces(handle, NULL, &info_list);
  2963. if (err != ERROR_SUCCESS) {
  2964. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Enum wlan interface failed %d", err);
  2965. WlanCloseHandle(handle, NULL);
  2966. return -1;
  2967. }
  2968. const int count = info_list->dwNumberOfItems;
  2969. for (int i = 0; i < count; ++i) {
  2970. interface_info = &info_list->InterfaceInfo[i];
  2971. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("wireless interface name: %s", SP::Module::Util::W2S(interface_info->strInterfaceDescription).c_str());
  2972. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("state: %d", interface_info->isState);
  2973. if (interface_info->isState == wlan_interface_state_connected) {
  2974. result = 1;
  2975. }
  2976. DWORD radio_state_info_size = sizeof(WLAN_RADIO_STATE);
  2977. PWLAN_RADIO_STATE radio_state_info_ptr = NULL;
  2978. WLAN_OPCODE_VALUE_TYPE op_code = wlan_opcode_value_type_invalid;
  2979. err = WlanQueryInterface(handle, &interface_info->InterfaceGuid, wlan_intf_opcode_radio_state,
  2980. NULL, &radio_state_info_size, (PVOID*)&radio_state_info_ptr, &op_code);
  2981. if (err != ERROR_SUCCESS) {
  2982. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("WlanQueryInterface failed %d", err);
  2983. }
  2984. else
  2985. {
  2986. const uint32_t count_of_phys = radio_state_info_ptr->dwNumberOfPhys;
  2987. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of valid PHYs: %d", count_of_phys);
  2988. if (count_of_phys > 0 && result == -1) {
  2989. if (dot11_radio_state_on == radio_state_info_ptr->PhyRadioState[0].dot11SoftwareRadioState) {
  2990. result = 0;
  2991. }
  2992. else
  2993. {
  2994. /*
  2995. for (int j = 0; j < count_of_phys; ++j) {
  2996. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("software radio state: %d, %d", j , radio_state_info_ptr->PhyRadioState[j].dot11SoftwareRadioState);
  2997. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("hardware radio state: %d, %d", j, radio_state_info_ptr->PhyRadioState[j].dot11HardwareRadioState);
  2998. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("**********************");
  2999. }
  3000. */
  3001. }
  3002. }
  3003. }
  3004. }
  3005. if (info_list != NULL) {
  3006. WlanFreeMemory(info_list);
  3007. }
  3008. WlanCloseHandle(handle, NULL);
  3009. return result;
  3010. }
  3011. void ResourceWatcherFSM::DetectWallpaperAndWarn()
  3012. {
  3013. int vbsType = -1;
  3014. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  3015. if (Is32R64Platform() != 0) {
  3016. dwFlag |= KEY_WOW64_64KEY;
  3017. }
  3018. bool explorerSet = false;
  3019. CSimpleStringA regeditValue(true);
  3020. HKEY hKey;
  3021. LONG lResult = RegOpenKeyEx(HKEY_CURRENT_USER,"Control Panel\\Desktop", 0, dwFlag, &hKey);
  3022. if (lResult == ERROR_SUCCESS) {
  3023. DWORD dwType = REG_SZ;
  3024. DWORD dwSize = MAX_PATH * sizeof(TCHAR);
  3025. TCHAR szValue[MAX_PATH + 1] = { 0 };
  3026. memset(szValue, '\0', MAX_PATH + 1);
  3027. lResult = RegQueryValueEx(hKey, "Wallpaper", NULL, &dwType, (LPBYTE)szValue, &dwSize);
  3028. if (lResult == ERROR_SUCCESS) {
  3029. CSimpleStringA strMsg = CSimpleStringA::Format("{\"subject\":\"wallpaper_path\",\"value\":\"%s\"}", szValue);
  3030. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DESKTOP_WALLPAPER_PATH, strMsg);
  3031. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("WallpaperSettings")(strMsg.GetData());
  3032. }
  3033. else {
  3034. CSimpleStringA strMsg = CSimpleStringA::Format("{\"subject\":\"wallpaper_path\",\"error\":\"RegQueryValueEx for Wallpaper returned %u, GLE=%u\"}", lResult, GetLastError());
  3035. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_DESKTOP_WALLPAPER_PATH_FETCHFAILE, strMsg);
  3036. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("WallpaperSettings").setResultCode("RTA5A0E")(strMsg.GetData());
  3037. }
  3038. }
  3039. else {
  3040. CSimpleStringA strMsg = CSimpleStringA::Format("{\"subject\":\"wallpaper_path\",\"error\":\"RegOpenKeyEx for Desktop returned %u, GLE=%u\"}", lResult, GetLastError());
  3041. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_DESKTOP_WALLPAPER_PATH_FETCHFAILE, strMsg);
  3042. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("WallpaperSettings").setResultCode("RTA5A0E")(strMsg.GetData());
  3043. }
  3044. RegCloseKey(hKey);
  3045. }
  3046. #endif // _MSC_VER end硬件资源监控相关系统功能 CPU、内存、硬盘、网络wifi
  3047. #ifdef RVC_OS_LINUX
  3048. static bool spaceLock = false;
  3049. void ResourceWatcherFSM::CheckDiskFileSpace()
  3050. {
  3051. if (spaceLock)
  3052. {
  3053. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("当前已有硬盘扫描进行中,跳过。");
  3054. return;
  3055. }
  3056. else
  3057. {
  3058. spaceLock = true; //加锁
  3059. }
  3060. //获取opt文件夹下的文件占用信息
  3061. FILE* fp = NULL;
  3062. CSimpleStringA cmd = "du -h -s /opt/* | sort -rn | head";
  3063. if ((fp = popen(cmd.GetData(), "r")) == NULL) {
  3064. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("popen failed:%d", GetLastError());
  3065. return;
  3066. }
  3067. char buf[1024] = { 0 };
  3068. CSimpleStringA warnMsg(true);
  3069. while (fgets(buf, sizeof(buf), fp))
  3070. {
  3071. warnMsg = warnMsg + "|" + buf;
  3072. }
  3073. if (warnMsg.GetLength() > 0)
  3074. {
  3075. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warnMsg.GetData()); //告警opt下的文件夹
  3076. }
  3077. pclose(fp);
  3078. //获取opt/rvc文件夹下的文件占用信息
  3079. FILE* fp2 = NULL;
  3080. CSimpleStringA cmd2 = "du -h -s /opt/rvc/* | sort -rn | head";
  3081. if ((fp2 = popen(cmd2.GetData(), "r")) == NULL) {
  3082. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("popen failed:%d", GetLastError());
  3083. return;
  3084. }
  3085. CSimpleStringA warnMsg2(true);
  3086. char buf2[1024] = { 0 };
  3087. while (fgets(buf2, sizeof(buf2), fp2))
  3088. {
  3089. warnMsg2 = warnMsg2 + "|" + buf2;
  3090. }
  3091. if (warnMsg2.GetLength() > 0)
  3092. {
  3093. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warnMsg2.GetData()); //告警opt/rvc下的文件夹
  3094. }
  3095. pclose(fp2);
  3096. if (spaceLock)
  3097. {
  3098. spaceLock = false; //释放锁
  3099. }
  3100. }
  3101. #endif // RVC_OS_LINUX
  3102. ErrorCodeEnum ResourceWatcherFSM::CatchSystemBasicInfo(SystemBasicInfo& info)
  3103. {
  3104. #if defined(RVC_OS_WIN)
  3105. ///**TODO(Gifur@10/10/2023): 待实现 */
  3106. return Error_NotImpl;
  3107. #else
  3108. CSimpleStringA runCfgPath;
  3109. ErrorCodeEnum errCode = GetEntityBase()->GetFunction()->GetPath("RunCfg", runCfgPath);
  3110. if (runCfgPath.IsNullOrEmpty()) return Error_Null;
  3111. CSimpleStringA storeFilePath = runCfgPath + SPLIT_SLASH_STR + "SMBIOSData.txt";
  3112. if (!ExistsFileA(storeFilePath)) {
  3113. RemoveFileA(storeFilePath);
  3114. }
  3115. std::string succStr, errStr;
  3116. std::string runStr("dmidecode -t system > ");
  3117. runStr += storeFilePath.GetData();
  3118. if (!SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3119. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("execute '%s' failed!", runStr.c_str());
  3120. if (!ExistsFileA(storeFilePath)) {
  3121. RemoveFileA(storeFilePath);
  3122. }
  3123. return Error_Unexpect;
  3124. }
  3125. do {
  3126. std::string succStr, errStr;
  3127. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Manufacturer\"){print$2}' ");
  3128. runStr += storeFilePath.GetData();
  3129. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3130. info.strManufacturer = SP::Utility::ToTrim(succStr).c_str();
  3131. }
  3132. else
  3133. {
  3134. succStr = "";
  3135. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Manufacturer' failed!");
  3136. }
  3137. } while (false);
  3138. do {
  3139. std::string succStr, errStr;
  3140. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Product Name\"){print$2}' ");
  3141. runStr += storeFilePath.GetData();
  3142. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3143. info.strProductName = SP::Utility::ToTrim(succStr).c_str();
  3144. }
  3145. else
  3146. {
  3147. succStr = "";
  3148. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Product Name' failed!");
  3149. }
  3150. } while (false);
  3151. do {
  3152. std::string succStr, errStr;
  3153. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Serial Number\"){print$2}' ");
  3154. runStr += storeFilePath.GetData();
  3155. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3156. info.strSerialNumber = SP::Utility::ToTrim(succStr).c_str();
  3157. }
  3158. else
  3159. {
  3160. succStr = "";
  3161. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Serial Number' failed!");
  3162. }
  3163. } while (false);
  3164. if (!ExistsFileA(storeFilePath)) {
  3165. RemoveFileA(storeFilePath);
  3166. }
  3167. return Error_Succeed;
  3168. #endif //RVC_OS_WIN
  3169. }
  3170. void ResourceWatcherFSM::AlarmSystemBasicInfo()
  3171. {
  3172. SystemBasicInfo info;
  3173. if (Error_Succeed == CatchSystemBasicInfo(info)) {
  3174. CSimpleStringA strResult("{");
  3175. if (!info.strManufacturer.IsNullOrEmpty()) {
  3176. strResult += CSimpleStringA::Format("\"Manufacturer\":\"%s\"", info.strManufacturer.GetData());
  3177. }
  3178. if (!info.strProductName.IsNullOrEmpty()) {
  3179. if (strResult.GetLength() > 1) {
  3180. strResult += ", ";
  3181. }
  3182. strResult += CSimpleStringA::Format("\"Product Name\":\"%s\"", info.strProductName.GetData());
  3183. }
  3184. if (!info.strSerialNumber.IsNullOrEmpty()) {
  3185. if (strResult.GetLength() > 1) {
  3186. strResult += ", ";
  3187. }
  3188. strResult += CSimpleStringA::Format("\"Serial Number\":\"%s\"", info.strSerialNumber.GetData());
  3189. }
  3190. strResult += "}";
  3191. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DEVICE_SMBIOS_GET, strResult);
  3192. }
  3193. }
  3194. BOOL ResourceWatcherFSM::DetectIsFirstRunAtBoot()
  3195. {
  3196. const BOOL bSet = SP::Module::Comm::IsFirsRunAppAfterSystemBoot(GetEntityBase(), LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT);
  3197. if (bSet) {
  3198. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
  3199. if (eRet != Error_Succeed) {
  3200. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
  3201. }
  3202. }
  3203. else {
  3204. GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
  3205. }
  3206. return bSet;
  3207. }
  3208. #ifdef RVC_OS_LINUX
  3209. void ResourceWatcherFSM::UploadMonitorSettings()
  3210. {
  3211. CSmartPointer<IConfigInfo> spCtSettingConfig;
  3212. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  3213. int nSwitchOff(0);
  3214. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenOFF", nSwitchOff);
  3215. if (!!nSwitchOff) {
  3216. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Cancel monitor change listen!");
  3217. if (m_bFirstRunAfterBoot) {
  3218. CSimpleStringA value(true);
  3219. bool res = GetMonitorInfo(value);
  3220. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  3221. }
  3222. }
  3223. else
  3224. {
  3225. int nInterval(10000);
  3226. int nValue(0);
  3227. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenInterval", nValue);
  3228. if (nValue >= 10000) {
  3229. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Update monitor listen interval from %d to %d", nInterval, nValue);
  3230. nInterval = nValue;
  3231. }
  3232. CSimpleStringA strLastMonitor(true);
  3233. bool readFromCfgFalg(true);
  3234. CSmartPointer<IConfigInfo> spRunConfig;
  3235. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  3236. spRunConfig->ReadConfigValue("MonitorAttribute", "LastInfo", strLastMonitor);
  3237. do
  3238. {
  3239. CSimpleStringA value(true);
  3240. bool res = GetMonitorInfo(value);
  3241. if (!value.IsNullOrEmpty() && (strLastMonitor.IsNullOrEmpty() || (strLastMonitor.Compare(value) != 0))) {
  3242. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  3243. CSmartPointer<IConfigInfo> spRunConfig;
  3244. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  3245. spRunConfig->WriteConfigValue("MonitorAttribute", "LastInfo", value);
  3246. strLastMonitor = value;
  3247. if (readFromCfgFalg) {
  3248. readFromCfgFalg = false;
  3249. }
  3250. }
  3251. else if (readFromCfgFalg && !strLastMonitor.IsNullOrEmpty() && strLastMonitor.Compare(value) == 0)
  3252. {
  3253. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  3254. readFromCfgFalg = false;
  3255. }
  3256. Sleep(nInterval);
  3257. } while (true);
  3258. }
  3259. }
  3260. void ResourceWatcherFSM::DetectSoftwareInstallStatus()
  3261. {
  3262. CSmartPointer<IConfigInfo> spCtSettingConfig;
  3263. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  3264. CSimpleStringA strSoftwaresNames[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
  3265. CSimpleStringA strSoftwaresVers[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
  3266. int nNameCounts = 0;
  3267. for (int i = 0; i < MAX_SOFTWARE_INSTALLED_DETECT_COUNT; i++) {
  3268. strSoftwaresNames[i] = "";
  3269. strSoftwaresVers[i] = "";
  3270. CSimpleStringA item = CSimpleStringA::Format("SoftwareInstallDetect%d", i);
  3271. CSimpleStringA value(true);
  3272. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), item, value);
  3273. if (value.IsNullOrEmpty()) {
  3274. break;
  3275. }
  3276. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CenterSettings:[%s]", value.GetData());
  3277. if (value.IndexOf("#") != -1) {
  3278. /** CSimpleString会带Trim操作,在这里不适用 [Gifur@202485]*/
  3279. auto items = SP::Utility::Split(std::string(value.GetData()), '#');
  3280. strSoftwaresNames[i] = items[0].c_str();
  3281. strSoftwaresVers[i] = items[1].c_str();
  3282. }
  3283. else
  3284. {
  3285. strSoftwaresNames[i] = value;
  3286. }
  3287. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect SoftDetect from CentralSetting, %d: [%s],[%s],[%s]"
  3288. , i, item.GetData(), strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData());
  3289. nNameCounts++;
  3290. }
  3291. if (nNameCounts > 0) {
  3292. for (int i = 0; i < nNameCounts; ++i) {
  3293. CSimpleStringA runItem = CSimpleStringA::Format("dpkg -l | grep \"%s\" | awk '{print $3}'", strSoftwaresNames[i].GetData());
  3294. std::string additional("");
  3295. std::string succStr, errStr;
  3296. std::string runStr(runItem.GetData());
  3297. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3298. if (succStr.empty()) {
  3299. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"not installed\",\"detect_flag\":0}", strSoftwaresNames[i].GetData());
  3300. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i, strMsg);
  3301. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus")(strMsg.GetData());
  3302. }
  3303. else
  3304. {
  3305. succStr = SP::Utility::ToTrim(succStr);
  3306. if (strSoftwaresVers[i].IsNullOrEmpty() || strSoftwaresVers[i].Compare(succStr.c_str()) == 0) {
  3307. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\",\"detect_flag\":1}"
  3308. , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData());
  3309. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_BASE + i, strMsg);
  3310. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus")(strMsg.GetData());
  3311. }
  3312. else
  3313. {
  3314. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\", \"expected\":\"%s\",\"detect_flag\":0}"
  3315. , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData());
  3316. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i, strMsg);
  3317. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus")(strMsg.GetData());
  3318. }
  3319. }
  3320. }
  3321. else
  3322. {
  3323. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"detect failed\", \"expected\":\"%s\",\"detect_flag\":0}"
  3324. , strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData());
  3325. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_STATUS_FAILED, strMsg);
  3326. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus").setResultCode("RTA5A0D")(strMsg.GetData());
  3327. }
  3328. }
  3329. }
  3330. }
  3331. UINT ResourceWatcherFSM::GetSystemDisplayVersion(CSimpleStringA& strVersion)
  3332. {
  3333. UINT result = 0;
  3334. const char filePath[] = "/etc/os-version";
  3335. strVersion.Clear();
  3336. char tmp[33];
  3337. memset(tmp, 0, 33);
  3338. inifile_read_str_s("Version", "MajorVersion", "unknown", tmp, 32, filePath);
  3339. strVersion = tmp;
  3340. strVersion += ".";
  3341. memset(tmp, 0, 33);
  3342. inifile_read_str_s("Version", "MinorVersion", "unknown", tmp, 32, filePath);
  3343. strVersion += tmp;
  3344. strVersion += ".";
  3345. result = atoi(tmp);
  3346. memset(tmp, 0, 33);
  3347. inifile_read_str_s("Version", "OsBuild", "unknown", tmp, 32, filePath);
  3348. strVersion += tmp;
  3349. return result;
  3350. }
  3351. void ResourceWatcherFSM::UploadSysVersionInfo(UINT& ver)
  3352. {
  3353. std::map<std::string, std::string> srcData;
  3354. CSimpleStringA osver;
  3355. ver = GetSystemDisplayVersion(osver);
  3356. srcData.insert(std::make_pair("os-version", osver)); ////当前操作系统版本(系统信息)
  3357. tk_utsname_t t;
  3358. osutil_uname(&t);
  3359. srcData.insert(std::make_pair("sysname", t.sysname)); ////当前操作系统名
  3360. srcData.insert(std::make_pair("release", t.release)); ////当前发布级别
  3361. srcData.insert(std::make_pair("version", t.version)); ////当前发布版本
  3362. srcData.insert(std::make_pair("machine", t.machine)); ////当前硬件体系类型
  3363. do {
  3364. std::string sucContent, failedContent;
  3365. std::string cmd("cat /proc/cpuinfo |grep \"model name\" | awk 'NR==1'");
  3366. bool ret = SP::Module::Util::ShellExecute(cmd, sucContent, failedContent);
  3367. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", cmd.c_str(), sucContent.c_str(), failedContent.c_str());
  3368. auto elems = SP::Utility::Split(sucContent, ':');
  3369. if (elems.size() > 1) {
  3370. sucContent = SP::Utility::ToTrim(elems[1]);
  3371. }
  3372. srcData.insert(std::make_pair("cpu-type", sucContent));
  3373. } while (false);
  3374. auto ret = generateJsonStr(srcData);
  3375. LogWarn(Severity_Low, Error_Hardware, LOG_RESOURCEWATCHER_SYSTEMINFO, ret.second.c_str());
  3376. }
  3377. string ResourceWatcherFSM::MemoryProcessStatus()
  3378. {
  3379. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  3380. ErrorCodeEnum erroCode = Error_Unexpect;
  3381. int memTop = 10; //10个进程
  3382. map<string, string> nameProcess;
  3383. CSystemRunInfo runInfo = { 0 };
  3384. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3385. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++)
  3386. {
  3387. string entityName = runInfo.strRunningEntityNames[i].GetData();
  3388. CEntityRunInfo entityInfo = { 0 };
  3389. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  3390. nameProcess[to_string(entityInfo.dwProcessID)] = entityName;
  3391. }
  3392. FILE* fp;
  3393. char buffer[2048];
  3394. string cmd = "ps c -eo pid,%mem,rss,command | sort -k3 -rn | head -" + to_string(memTop);
  3395. fp = popen(cmd.c_str(), "r");
  3396. int i = 0;
  3397. string s;
  3398. string str[4];
  3399. //mem
  3400. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("MEM TOP %d PROCESS!", memTop);
  3401. string topMessage = "";
  3402. while (i < memTop)
  3403. {
  3404. fgets(buffer, sizeof(buffer), fp);
  3405. s = buffer;
  3406. istringstream is(s);
  3407. is >> str[0] >> str[1] >> str[2] >> str[3];
  3408. double temp;
  3409. stringstream ss1;
  3410. ss1 << str[2];
  3411. ss1 >> temp;
  3412. temp = temp / (1024 * 1024);
  3413. stringstream ss2;
  3414. ss2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << temp;
  3415. str[2] = ss2.str();
  3416. if (nameProcess.find(str[0]) != nameProcess.end())
  3417. {
  3418. str[3] = nameProcess[str[0]];
  3419. }
  3420. topMessage = topMessage + "\"" + str[3] + "\"" + ":" + "\"" + str[1] + "%\"";
  3421. if (i != memTop - 1)
  3422. {
  3423. topMessage += ",";
  3424. }
  3425. ++i;
  3426. }
  3427. topMessage += "}";
  3428. pclose(fp);
  3429. return topMessage;
  3430. }
  3431. long ResourceWatcherFSM::GetCPURunTime(CPUInfo* cpu) //获取CPU的当前信息,同时返回CPU使用时间
  3432. {
  3433. FILE* fd;
  3434. char buff[1024] = { 0 };
  3435. CPUInfo* cpuInfo = cpu;
  3436. fd = fopen("/proc/stat", "r");
  3437. if (!fd) {
  3438. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read CPU Info FAILED!");
  3439. return -1;
  3440. }
  3441. fgets(buff, sizeof(buff), fd);
  3442. char name[64] = { 0 };
  3443. sscanf(buff, "%s %u %u %u %u %u %u %u",
  3444. cpuInfo->name, &cpuInfo->user, &cpuInfo->nice, &cpuInfo->system, &cpuInfo->idle, &cpuInfo->lowait, &cpuInfo->irq, &cpuInfo->softirq);
  3445. fclose(fd);
  3446. return (cpuInfo->user + cpuInfo->nice + cpuInfo->system + cpuInfo->idle + cpuInfo->lowait + cpuInfo->irq + cpuInfo->softirq);
  3447. }
  3448. long ResourceWatcherFSM::ReadProcCPURunTime(DWORD pid, ProcCPUInfo* pInfo) { //根据pid读取进程占用的CPU时间
  3449. char file_name[64] = { 0 };
  3450. FILE* fd;
  3451. char line_buff[1024] = { 0 };
  3452. sprintf(file_name, "/proc/%d/stat", pid);
  3453. fd = fopen(file_name, "r");
  3454. if (nullptr == fd) {
  3455. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read PROCESS[%d] CPU Info FAILED!", pid);
  3456. return -1;
  3457. }
  3458. fgets(line_buff, sizeof(line_buff), fd);
  3459. sscanf(line_buff, "%u %s", &pInfo->pid, pInfo->pname);
  3460. const char* q = GetItems(line_buff, PROCESS_ITEM);
  3461. sscanf(q, "%ld %ld %ld %ld", &pInfo->utime, &pInfo->stime, &pInfo->cutime, &pInfo->cstime);
  3462. fclose(fd);
  3463. return (pInfo->utime + pInfo->stime + pInfo->cutime + pInfo->cstime);
  3464. }
  3465. //获取第N项开始的指针
  3466. const char* ResourceWatcherFSM::GetItems(const char* buffer, unsigned int item) {
  3467. const char* p = buffer;
  3468. int len = strlen(buffer);
  3469. int count = 0;
  3470. for (int i = 0; i < len; i++) {
  3471. if (' ' == *p) {
  3472. count++;
  3473. if (count == item - 1) {
  3474. p++;
  3475. break;
  3476. }
  3477. }
  3478. p++;
  3479. }
  3480. return p;
  3481. }
  3482. bool cmp(const pair<DWORD, DOUBLE>& a, const pair<DWORD, DOUBLE>& b) {
  3483. return a.second > b.second;
  3484. }
  3485. /* -----------------------
  3486. 根据先后两个时间的CPU信息,
  3487. 计算CPU的总占用量和各个进程的占用量
  3488. ----------------------- */
  3489. void ResourceWatcherFSM::GetSystemCPUStatus()
  3490. {
  3491. //int cpu_num = sysconf(_SC_NPROCESSORS_CONF); //CPU核数
  3492. CPUInfo* cpuOld = new CPUInfo;
  3493. CPUInfo* cpuNew = new CPUInfo;
  3494. const char* tPath = "/proc";
  3495. map<DWORD, string> nameProcess; // <pid, 进程名>
  3496. map<DWORD, DOUBLE> usageProcess; // <pid, CPU占用率>
  3497. long oldTotalTime = GetCPURunTime(cpuOld); //旧CPU运行总时间
  3498. if (oldTotalTime == -1)
  3499. {
  3500. return;
  3501. }
  3502. map<DWORD, long> oldProcCPUTime; // <pid, 旧时刻进程的CPU占用时间>
  3503. struct dirent* oldDirp;
  3504. DIR* oldDp = opendir(tPath);
  3505. if (oldDp != NULL) {
  3506. while ((oldDirp = readdir(oldDp)) != NULL) { //获取旧时刻 每一个进程的pid、CPU运行时间、进程名
  3507. string fileName = oldDirp->d_name;
  3508. BOOL isPid = TRUE;
  3509. for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
  3510. {
  3511. if (!isdigit(fileName[i]))
  3512. {
  3513. isPid = FALSE;
  3514. break;
  3515. }
  3516. }
  3517. if (!isPid) continue;
  3518. DWORD pid;
  3519. long oldTime;
  3520. ProcCPUInfo* oldProcCPU = new ProcCPUInfo;
  3521. sscanf(oldDirp->d_name, "%d", &pid); //读取文件夹名
  3522. oldTime = ReadProcCPURunTime(pid, oldProcCPU);
  3523. if (oldTime == -1)
  3524. {
  3525. return;
  3526. }
  3527. oldProcCPUTime[pid] = oldTime;
  3528. nameProcess[pid] = oldProcCPU->pname;
  3529. delete oldProcCPU;
  3530. }
  3531. closedir(oldDp);
  3532. }
  3533. sleep(1);
  3534. long newTotalTime = GetCPURunTime(cpuNew); //新CPU运行总时间
  3535. if (newTotalTime == -1)
  3536. {
  3537. return;
  3538. }
  3539. map<DWORD, long> newProcCPUTime; // <pid, 新时刻进程的CPU占用时间>
  3540. struct dirent* newDirp;
  3541. DIR* newDp = opendir(tPath);
  3542. if (newDp != NULL) {
  3543. while ((newDirp = readdir(newDp)) != NULL) { //获取新时刻 每一个进程的pid、CPU运行时间、进程名
  3544. string fileName = newDirp->d_name;
  3545. BOOL isPid = TRUE;
  3546. for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
  3547. {
  3548. if (!isdigit(fileName[i]))
  3549. {
  3550. isPid = FALSE;
  3551. break;
  3552. }
  3553. }
  3554. if (!isPid) continue;
  3555. DWORD pid;
  3556. long newTime;
  3557. ProcCPUInfo* newProcCPU = new ProcCPUInfo;
  3558. sscanf(newDirp->d_name, "%d", &pid); //读取文件夹名
  3559. newTime = ReadProcCPURunTime(pid, newProcCPU);
  3560. if (newTime == -1)
  3561. {
  3562. return;
  3563. }
  3564. newProcCPUTime[pid] = newTime;
  3565. string tName = newProcCPU->pname;
  3566. tName.erase(tName.begin());
  3567. tName.erase(tName.begin() + (tName.length() - 1));
  3568. nameProcess[pid] = tName;
  3569. delete newProcCPU;
  3570. }
  3571. closedir(newDp);
  3572. }
  3573. map<DWORD, long>::iterator it;
  3574. for (it = newProcCPUTime.begin(); it != newProcCPUTime.end(); ++it)
  3575. {
  3576. DWORD tPid = it->first;
  3577. //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
  3578. DOUBLE tRatio = 100.0 * (newProcCPUTime[tPid] - oldProcCPUTime[tPid]) / (newTotalTime - oldTotalTime);
  3579. usageProcess[tPid] = tRatio;
  3580. }
  3581. CSystemRunInfo runInfo = { 0 };
  3582. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3583. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
  3584. {
  3585. string entityName = runInfo.strRunningEntityNames[i].GetData();
  3586. CEntityRunInfo entityInfo = { 0 };
  3587. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  3588. nameProcess[entityInfo.dwProcessID] = entityName;
  3589. }
  3590. vector<pair<DWORD, DOUBLE>> vec(usageProcess.begin(), usageProcess.end());
  3591. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  3592. int cpuTop = 10;
  3593. int len = MIN(cpuTop, vec.size()); //确认要展示的进程数量
  3594. string procWarn = "";
  3595. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  3596. {
  3597. char* tUsage = new char[20];
  3598. sprintf(tUsage, "%.2lf", vec[i].second);
  3599. procWarn = procWarn + ",\"" + nameProcess[vec[i].first] + "\":\"" + string(tUsage) + "%\"";
  3600. delete tUsage;
  3601. }
  3602. unsigned long oldInfo, newInfo;
  3603. double cUsedRate = 0;
  3604. //第一次(用户+优先级+系统+空闲)的时间
  3605. //oldInfo = (unsigned long)(cpuOld->user + cpuOld->nice + cpuOld->system + cpuOld->idle + cpuOld->lowait + cpuOld->irq + cpuOld->softirq);
  3606. //第二次(用户+优先级+系统+空闲)的时间
  3607. //newInfo = (unsigned long)(cpuNew->user + cpuNew->nice + cpuNew->system + cpuNew->idle + cpuNew->lowait + cpuNew->irq + cpuNew->softirq);
  3608. double totalTime = newTotalTime - oldTotalTime;
  3609. double freeTime = cpuNew->idle - cpuOld->idle;
  3610. cUsedRate = (totalTime - freeTime) / totalTime;
  3611. if (m_cpuHighPercent <= 0)
  3612. {
  3613. m_cpuHighPercent = 80; //默认告警百分比80%
  3614. }
  3615. if (cpuWarnThreshold <= 0)
  3616. {
  3617. cpuWarnThreshold = 10; //默认满10次告一次警
  3618. }
  3619. if ((cUsedRate * 100) > m_cpuHighPercent)
  3620. {
  3621. cpuWarnTime = cpuWarnTime % cpuWarnThreshold;
  3622. if (cpuWarnTime == 0) //每达到一次阈值告警一次
  3623. {
  3624. stringstream tss;
  3625. tss << std::setiosflags(std::ios::fixed) << std::setprecision(2) << cUsedRate * 100;
  3626. string warn = "{ \"total_used\":\"" + tss.str() + "%\"" + procWarn + "}";
  3627. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  3628. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A03").setAPI("CpuUsedCheck")(warn.c_str());
  3629. }
  3630. cpuWarnTime++;
  3631. }
  3632. delete cpuNew;
  3633. delete cpuOld;
  3634. }
  3635. void ResourceWatcherFSM::GetSystemMemoryStatus()
  3636. {
  3637. MemInfo* memInfo = new MemInfo();
  3638. FILE* fd;
  3639. char buff[256];
  3640. fd = fopen("/proc/meminfo", "r");
  3641. if (!fd) {
  3642. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read Memory INFO FAILED!");
  3643. return;
  3644. }
  3645. fgets(buff, sizeof(buff), fd);
  3646. sscanf(buff, "%s %lu ", memInfo->infoName1, &memInfo->memTotal);
  3647. fgets(buff, sizeof(buff), fd);
  3648. sscanf(buff, "%s %lu ", memInfo->infoName2, &memInfo->memFree);
  3649. fgets(buff, sizeof(buff), fd);
  3650. sscanf(buff, "%s %lu ", memInfo->infoName3, &memInfo->memAvail);
  3651. fclose(fd);
  3652. double mUsedRate = 0;
  3653. mUsedRate = (double)(memInfo->memTotal - memInfo->memAvail) / (double)memInfo->memTotal;
  3654. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3655. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  3656. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE];
  3657. ByteSprintf(szResult, (double)(memInfo->memTotal) * 1024, 'G'); // 内存信息在 /proc/meminfo 中的单位为 KB
  3658. ByteSprintf(szResult2, (double)(memInfo->memFree) * 1024, 'G');
  3659. ByteSprintf(szResult3, (double)(memInfo->memAvail) * 1024, 'G');
  3660. if (m_memHighPercent <= 0)
  3661. {
  3662. m_memHighPercent = 80; //默认告警百分比80%
  3663. }
  3664. if (memWarnThreshold <= 0)
  3665. {
  3666. memWarnThreshold = 10; //默认告警阈值10次
  3667. }
  3668. if ((mUsedRate * 100) > m_memHighPercent)
  3669. {
  3670. memWarnTime = memWarnTime % memWarnThreshold;
  3671. if (memWarnTime == 0) //每达到阈值告警一次
  3672. {
  3673. char usedResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3674. ByteSprintf(usedResult, (double)(memInfo->memTotal) * 1024 * mUsedRate, 'G');
  3675. stringstream ss1;
  3676. ss1 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << mUsedRate * 100;
  3677. string warn = "{ \"total\":\"" + string(szResult) + "\"," +
  3678. "\"used\":\"" + ss1.str() + "%\"," + MemoryProcessStatus();
  3679. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  3680. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A04").setAPI("MemUsedCheck")(warn.c_str());
  3681. }
  3682. memWarnTime++;
  3683. }
  3684. }
  3685. void ResourceWatcherFSM::GetDiskStatusFrom(LPCTSTR path)
  3686. {
  3687. if (m_diskHighPercent <= 0)
  3688. {
  3689. m_diskHighPercent = 90; //默认硬盘告警百分比90%
  3690. }
  3691. unsigned long long uiTotalBytes;
  3692. unsigned long long uiFreeDiskBytes;
  3693. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3694. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  3695. BOOL readFlag = DiskInfo::GetDiskSpace(path, uiTotalBytes, uiFreeDiskBytes);
  3696. double dUsedRate = 1 - (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  3697. ByteSprintf(szResult, (double)uiTotalBytes);
  3698. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  3699. if (readFlag && (dUsedRate * 100 < m_diskHighPercent)) {
  3700. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.", path, szResult, szResult2, dUsedRate * 100);
  3701. }
  3702. else
  3703. {
  3704. CSimpleStringA warnStr = CSimpleStringA::Format("\"Disk\":\"%s\",\"total\":\"%s\",\"free\":\"%s\",\"used rate\":\"%.1lf%%\"",
  3705. path, szResult, szResult2, dUsedRate * 100);
  3706. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, warnStr.GetData());
  3707. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A05").setAPI("DiskUsedCheck")(warnStr.GetData());
  3708. CheckDiskFileSpaceTask* task4 = new CheckDiskFileSpaceTask(this);
  3709. GetEntityBase()->GetFunction()->PostThreadPoolTask(task4);
  3710. }
  3711. }
  3712. void ResourceWatcherFSM::GetSystemDiskStatus()
  3713. {
  3714. GetDiskStatusFrom("/");
  3715. }
  3716. void ResourceWatcherFSM::switchWindowsEffect(const char* cfgFilePath, bool enable)
  3717. {
  3718. char tmp[33];
  3719. memset(tmp, 0, 33);
  3720. inifile_read_str_s("Compositing", "Enabled", "", tmp, 32, cfgFilePath);
  3721. if (strlen(tmp) == 0 || stricmp(tmp, "false") == 0) {
  3722. if (enable) {
  3723. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "true");
  3724. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_ON, "to active window effect");
  3725. }
  3726. }
  3727. else if (stricmp(tmp, "true") == 0) {
  3728. if (!enable) {
  3729. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "false");
  3730. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_OFF, "to inactive window effect");
  3731. }
  3732. }
  3733. }
  3734. void ResourceWatcherFSM::RecoverDDEClipboardEnable()
  3735. {
  3736. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  3737. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  3738. if (!ExistsFileA(clipboardPath.c_str()) && ExistsFileA(clipboardPathBak.c_str())) {
  3739. fileutil_copy_file(clipboardPath.c_str(), clipboardPathBak.c_str());
  3740. //fileutil_delete_file(clipboardPathBak.c_str());
  3741. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_CLIPBOARD_RECOVER_ENABLE, "recover clipboard succ.");
  3742. }
  3743. else {
  3744. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s exists.", clipboardPath.c_str());
  3745. }
  3746. }
  3747. void ResourceWatcherFSM::ConfirmDDEClipboardDisable()
  3748. {
  3749. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  3750. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  3751. char* clipboards[] = { "dde-clipboard", "dde-clipboardloader" };
  3752. if (!ExistsFileA(clipboardPath.c_str())) {
  3753. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There are no any %s files.", clipboardPath.c_str());
  3754. if (ExistsFileA(clipboardPathBak.c_str())) {
  3755. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s exists.", clipboardPathBak.c_str());
  3756. }
  3757. return;
  3758. }
  3759. if (0 != fileutil_copy_file(clipboardPathBak.c_str(), clipboardPath.c_str())) {
  3760. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove clipboard failed");
  3761. }
  3762. else {
  3763. fileutil_delete_file(clipboardPath.c_str());
  3764. osutil_terminate_related_process(clipboards, array_size(clipboards), 0);
  3765. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_SUCC, "remove clipboard succ.");
  3766. }
  3767. }
  3768. void ResourceWatcherFSM::ConfirmNotificationCenterDisable()
  3769. {
  3770. const char* osd_file_path = "/usr/lib/deepin-daemon/dde-osd";
  3771. const char* osd_bak_file_path = "/usr/lib/deepin-daemon/dde-osd.bak";
  3772. CSmartPointer<IConfigInfo> spConfig;
  3773. GetEntityBase()->GetFunction()->OpenConfig(Config_Cache, spConfig);
  3774. int flag = 0;
  3775. spConfig->ReadConfigValueInt("UOSFeatures", "NotifyCenterSupport", flag);
  3776. if (flag == 1) {
  3777. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("allow the dde-osd process alive.");
  3778. if (!ExistsFileA(osd_file_path) && ExistsFileA(osd_bak_file_path)) {
  3779. fileutil_copy_file(osd_file_path, osd_bak_file_path);
  3780. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_OSD_RECOVER_ENABLE, "recover dde osd succ.");
  3781. }
  3782. }
  3783. else {
  3784. if (ExistsFileA(osd_file_path) && !ExistsFileA(osd_bak_file_path)) {
  3785. char* relates[] = { "dde-osd" };
  3786. if (0 != fileutil_copy_file(osd_bak_file_path, osd_file_path)) {
  3787. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove dde osd failed");
  3788. }
  3789. else {
  3790. osutil_terminate_related_process(relates, array_size(relates), 0);
  3791. fileutil_delete_file(osd_file_path);
  3792. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_OSD_REMOVE_SUCC, "remove dde osd succ.");
  3793. }
  3794. }
  3795. }
  3796. }
  3797. void ResourceWatcherFSM::ConfirmWindowEffectHasBeenOpen()
  3798. {
  3799. array_header_t* arr;
  3800. arr = fileutil_get_sub_dirs_a("/home");
  3801. if (arr) {
  3802. int i;
  3803. for (i = 0; i < arr->nelts; ++i) {
  3804. char szDestSubDir[256] = { 0 };
  3805. char* dir = ARRAY_IDX(arr, i, char*);
  3806. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("sub dir: %s", dir);
  3807. strcpy(szDestSubDir, dir);
  3808. strcat(szDestSubDir, SPLIT_SLASH_STR);
  3809. strcat(szDestSubDir, ".config/kwinrc");
  3810. if (ExistsFileA(szDestSubDir)) {
  3811. switchWindowsEffect(szDestSubDir, true);
  3812. }
  3813. }
  3814. toolkit_array_free2(arr);
  3815. }
  3816. }
  3817. #endif // RVC_OS_LINUX