ResourceWatcherFSM.cpp 335 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369
  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 <stdio.h>
  12. #include <stdlib.h>
  13. #include "ResourceWatcher_UserCode.h"
  14. #ifdef RVC_OS_LINUX
  15. #include <vector>
  16. #include <dirent.h>
  17. #include <sstream>
  18. #include <fstream>
  19. #include <iostream>
  20. #include "publicFunExport.h"
  21. #include "toolkit.h"
  22. #include "iniutil.h"
  23. #include "osutil.h"
  24. #include "SpUtility.h"
  25. #include "RestfulFunc.h"
  26. #else
  27. #include <intrin.h>
  28. #include <ShlObj.h>
  29. #include <Pdh.h>
  30. #include <io.h>
  31. #include <direct.h>
  32. #include "memutil.h"
  33. #include "array.h"
  34. #include <Windows.h>
  35. #include <wintrust.h>
  36. #include <direct.h>
  37. #include <Mscat.h>
  38. #include <Softpub.h>
  39. #include <wlanapi.h>
  40. #include <Netlistmgr.h> //网络检测添加
  41. #include <psapi.h>
  42. #include <tlhelp32.h>
  43. #include "Mmdeviceapi.h"
  44. #include "PolicyConfig.h"
  45. #include "Propidl.h"
  46. #include "Functiondiscoverykeys_devpkey.h"
  47. #include "NetConfigCommon.h"
  48. #include "NetworkInfo.h"
  49. #include "NetworkProbe.h"
  50. #include "MbnEventImpl.h"
  51. #include "Event.h"
  52. #include "..\mod_chromium\Chromium_client_g.h" //启动浏览器接口
  53. using namespace Chromium;
  54. #pragma comment(lib, "pdh.lib")
  55. #pragma comment(lib,"winmm.lib" )
  56. #pragma comment(lib, "shell32.lib")
  57. #pragma comment(lib, "Wintrust.lib")
  58. #pragma comment(lib, "crypt32.lib")
  59. #pragma comment(lib, "wlanapi.lib")
  60. #endif
  61. //硬件信息搜集参数
  62. const int MAX_HARDWARE_CHECK_TIME = 5000;
  63. const int TIMER_HARDWARE_CHECK = 2;
  64. //保留版本数目
  65. const int DEFAULT_VERSION_SAVED_COUNT = 5;
  66. const int MAX_VERSION_PATH = 256;
  67. const int DEFAULT_DAY_OF_BACKWARD = 90;
  68. const int MAX_DAY_OF_BACKWARD = 365;
  69. const char* DEFAULT_DELETE_FILE_SUFFIX = "*";
  70. LPCTSTR UPLOAD_VIDEO_PATH = "UploadVideo";
  71. CRITICAL_SECTION g_csVideoMoreClear;
  72. const int AD0_DAY_OF_BACKWARD = 7;
  73. const int TIMER_INTERVAL_CLEARVIDEO_ENHANCE = 60 * 1000;
  74. #ifdef RVC_OS_LINUX
  75. #define PROCESS_ITEM 14 //进程CPU信息读取位置参数
  76. const int MAX_MAINLINK_CHECK_TIME = 5000;
  77. const int TIMER_MAINLINK_CHECK = 4;
  78. static BOOL lastLinkStatus = true; //记录上次检测的连通状态,广播用 true:连通 false:不通
  79. #else
  80. const int TIMER_ID_CLEARVIDEO_ENHANCE = 1;
  81. static int mainDetectFlag = 0;
  82. static int hardwareCheckTime = 5000;
  83. static int hardwareCheckFlag = 1;
  84. static int batteryCheckTime = 2;
  85. const int MAX_AYSNC_TIMEOUT = 60000;
  86. const int MAX_CHECK_TIME = 60000;
  87. const int MAX_CPU_CHECK_TIME = 5000;
  88. const int TIMER_ID_CHECK = 0;
  89. const int TIMER_CPU_CHECK = 1;
  90. const int THOUSAND = 1024;
  91. const int MILLION = 1048576;
  92. #endif // RVC_OS_LINUX
  93. #define MAX_VOLUME_COUNT 26
  94. #define BUFSIZE 512
  95. static BOOL sBDiskValStatus[MAX_VOLUME_COUNT + 1] = { FALSE };
  96. #define MAX_SUBFILES_COUNT 1000
  97. #define DIV (1024 * 1024)
  98. #define DAY_DIV (24 * 60 * 60)
  99. #define HOURS_DIV (60 * 60)
  100. #define MINUS_DIV (60)
  101. const char* SystemElapsedQuery = "\\System\\System Up Time";
  102. #ifndef RVC_OS_LINUX
  103. #define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
  104. #define SafeDeleteArraySize(pData) { if(pData){delete []pData;pData=NULL;} }
  105. #endif // !RVC_OS_LINUX
  106. template<class T>
  107. class TimerOutHelper : public ITimerListener
  108. {
  109. public:
  110. typedef void (T::* FuncTimer)(void* pUserdata);
  111. TimerOutHelper(T* p, FuncTimer pTimerFunc, void* pData, bool bDeleteSelf = false)
  112. : m_pObject(p), m_pUserData(pData), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf)
  113. {
  114. }
  115. virtual void OnTimeout(DWORD dwTimerID)
  116. {
  117. (m_pObject->*m_pTimer)(m_pUserData);
  118. if (m_bDeleteSelf)
  119. delete this;
  120. }
  121. private:
  122. void* m_pUserData;
  123. T* m_pObject;
  124. FuncTimer m_pTimer;
  125. bool m_bDeleteSelf;
  126. };
  127. #ifdef RVC_OS_LINUX
  128. ResourceWatcherFSM::ResourceWatcherFSM(void)
  129. :m_IsPadDevice(FALSE),
  130. m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD),
  131. m_csUploadVideoPath(true),
  132. m_bReadyFlag(false),
  133. m_bVideoClearReady(false),
  134. m_nMinSavedDay(DEFAULT_SAVE_DATE_COUNT),
  135. m_highPart(0),
  136. m_lowPart(0),
  137. m_strTerminalNo(true),
  138. m_strDefaultDns(true),
  139. m_strBackupDns(true),
  140. m_nEnableSetDns(0),
  141. m_bFirstRunAfterBoot(FALSE),
  142. m_bGetStatusRotate(FALSE),
  143. m_csDelFileSuffix(true),
  144. m_failDelCnt(0),
  145. m_bIsConfigMode(FALSE)
  146. {
  147. mAllVideoFileSizeCal = 0;
  148. mMaxFileSize = 0;
  149. mUiCalibration = 0;
  150. mUiRequireBytes = 0;
  151. mftAd0RemoveTime = 0;
  152. }
  153. #else
  154. ResourceWatcherFSM::ResourceWatcherFSM(void)
  155. :m_IsPadDevice(TRUE),
  156. m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD),
  157. m_csUploadVideoPath(""),
  158. m_bReadyFlag(false),
  159. m_bVideoClearReady(false),
  160. m_nMinSavedDay(DEFAULT_SAVE_DATE_COUNT),
  161. m_highPart(0),
  162. m_lowPart(0),
  163. m_strTerminalNo(true),
  164. m_fProbeDone(true),
  165. m_DoneDetectAutostart(true),
  166. m_forceStartupWithExeFlag(0),
  167. m_bIsVerified(false),
  168. m_iNonSignedTotal(0),
  169. checkActiveBefore(FALSE),
  170. m_cardswiperStatus(-1)
  171. {
  172. mUiRequireBytes.QuadPart = 0ui64;
  173. mUiCalibration.QuadPart = 0ui64;
  174. m_strDefaultDns = NULL;
  175. m_strBackupDns = NULL;
  176. m_nEnableSetDns = 0;
  177. m_nProbeIndex = 0;
  178. memset(m_strProbeAddress, 0, sizeof(CSimpleStringA) * MAX_NETWORK_PROBE_COUNT);
  179. }
  180. #endif // RVC_OS_LINUX
  181. ResourceWatcherFSM::~ResourceWatcherFSM(void)
  182. {
  183. }
  184. #ifdef RVC_OS_LINUX
  185. void ResourceWatcherFSM::ClearVideoQueue()
  186. {
  187. while (!m_VideoFiles.empty()) {
  188. TmpFileInfo* pNodeInfo = m_VideoFiles.top();
  189. m_VideoFiles.pop();
  190. if (pNodeInfo != NULL) {
  191. delete pNodeInfo;
  192. }
  193. }
  194. memset(szMaxSizeFilePath, 0, sizeof(szMaxSizeFilePath));
  195. mAllVideoFileSizeCal = 0;
  196. mMaxFileSize = 0;
  197. mUiRequireBytes = 0;
  198. VideoDailyRecord.clear();
  199. }
  200. void ResourceWatcherFSM::PrintVideEmurateResult()
  201. {
  202. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  203. ByteSprintf(szResult, (double)mMaxFileSize);
  204. Dbg("Max Video file: %s size: %s", szMaxSizeFilePath, szResult);
  205. Dbg("mAllVideoFileSizeCal : %llu Bytes", mAllVideoFileSizeCal);
  206. ByteSprintf(szResult, (double)mAllVideoFileSizeCal);
  207. Dbg("Totally(size: %d) directory size: %s", m_VideoFiles.size(), szResult);
  208. }
  209. #endif // RVC_OS_LINUX
  210. void ResourceWatcherFSM::s0_on_entry()
  211. {
  212. LOG_FUNCTION();
  213. #ifdef RVC_OS_LINUX
  214. if (!m_bIsConfigMode) {
  215. this->PostEventFIFO(new RunEvent());
  216. GetCpuType(NULL);
  217. }
  218. else {
  219. Dbg("in config mode, do nothing about clear job");
  220. }
  221. #else
  222. this->PostEventFIFO(new RunEvent());
  223. GetCpuType(NULL);
  224. SetDnsServer();
  225. GetEntityBase()->GetFunction()->PostThreadPoolTask(new ClearCenterSettingFilesTask(this));
  226. BOOL fInstallBySetup(FALSE);
  227. if (Error_Succeed == DetectVTMInstalledBySetup(fInstallBySetup) && !fInstallBySetup) {
  228. GetEntityBase()->GetFunction()->PostThreadPoolTask(new CreateLinkTask(this));
  229. }
  230. #endif // RVC_OS_LINUX
  231. }
  232. unsigned int ResourceWatcherFSM::s0_on_event(FSMEvent* e)
  233. {
  234. LOG_FUNCTION();
  235. unsigned int unRes = 0;
  236. switch (e->iEvt)
  237. {
  238. case USER_EVT_RUN:
  239. {
  240. if (m_IsPadDevice)
  241. {
  242. GetCardSwiperTask* task = new GetCardSwiperTask(this);
  243. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  244. }
  245. #ifdef RVC_OS_LINUX
  246. RunTask* videoTask = new RunTask(this);
  247. videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
  248. GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
  249. #else
  250. ClearVideoFilesTask* videoTask = new ClearVideoFilesTask(this);
  251. videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
  252. GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
  253. ClearAd0Task* ad0Task = new ClearAd0Task(this);
  254. GetEntityBase()->GetFunction()->PostThreadPoolTask(ad0Task);
  255. #endif // RVC_OS_LINUX
  256. e->SetHandled();
  257. }
  258. break;
  259. case USER_EVT_FETCH:
  260. {
  261. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  262. fetchEvt->ctx->Answer(Error_InvalidState);
  263. e->SetHandled();
  264. }
  265. break;
  266. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  267. {
  268. m_bGetStatusRotate = FALSE;
  269. e->SetHandled();
  270. }
  271. break;
  272. default:
  273. {
  274. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unexpecetd Event(%d)", e->iEvt);
  275. }
  276. break;
  277. }
  278. return unRes;
  279. }
  280. void ResourceWatcherFSM::s0_on_exit()
  281. {
  282. }
  283. void ResourceWatcherFSM::s1_on_entry()
  284. {
  285. LOG_FUNCTION();
  286. }
  287. unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
  288. {
  289. LOG_FUNCTION();
  290. unsigned int unRes = 0;
  291. switch (e->iEvt)
  292. {
  293. case USER_EVT_FETCH:
  294. {
  295. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  296. if (m_IsPadDevice)
  297. {
  298. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  299. fetchEvt->ctx->Answer(Error_Succeed);
  300. }
  301. else
  302. {
  303. fetchEvt->ctx->Answer(Error_InvalidState);
  304. }
  305. e->SetHandled();
  306. }
  307. break;
  308. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  309. {
  310. m_bGetStatusRotate = FALSE;
  311. e->SetHandled();
  312. }
  313. break;
  314. case USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED:
  315. {
  316. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s::There are %d file(s), successfully delete %d file(s) in path %s", __FUNCTION__,
  317. e->param2, e->param1, (LPCTSTR)m_csUploadVideoPath);
  318. if (m_failDelCnt != 0)
  319. {
  320. CSimpleStringA strMsg = CSimpleStringA::Format("There are %d matched files should be deleted", m_failDelCnt);
  321. LogWarn(Severity_Middle, Error_Unexpect, 0, (LPCTSTR)strMsg);
  322. }
  323. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  324. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  325. }
  326. e->SetHandled();
  327. break;
  328. #ifndef RVC_OS_LINUX
  329. case EVT_TIMER:
  330. {
  331. if (e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
  332. {
  333. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  334. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  335. }
  336. }
  337. e->SetHandled();
  338. break;
  339. #endif // !RVC_OS_LINUX
  340. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  341. e->SetHandled();
  342. break;
  343. case USER_EVT_VERSION_CLEAR_FINISHED:
  344. e->SetHandled();
  345. break;
  346. default:
  347. {
  348. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Unexpecetd Event(%d)", e->iEvt);
  349. }
  350. break;
  351. }
  352. return unRes;
  353. }
  354. void ResourceWatcherFSM::s1_on_exit()
  355. {
  356. }
  357. void ResourceWatcherFSM::s2_on_entry()
  358. {
  359. LOG_FUNCTION();
  360. }
  361. unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
  362. {
  363. LOG_FUNCTION();
  364. unsigned int unRes = 0;
  365. switch (e->iEvt)
  366. {
  367. case USER_EVT_RUN:
  368. {
  369. e->SetHandled();
  370. }
  371. break;
  372. case USER_EVT_FETCH:
  373. {
  374. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  375. if (m_IsPadDevice)
  376. {
  377. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  378. fetchEvt->ctx->Answer(Error_Succeed);
  379. }
  380. else
  381. {
  382. fetchEvt->ctx->Answer(Error_InvalidState);
  383. }
  384. e->SetHandled();
  385. }
  386. break;
  387. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  388. {
  389. m_bGetStatusRotate = FALSE;
  390. e->SetHandled();
  391. }
  392. break;
  393. #ifndef RVC_OS_LINUX
  394. case EVT_TIMER:
  395. {
  396. if (e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
  397. {
  398. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  399. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  400. }
  401. }
  402. e->SetHandled();
  403. break;
  404. #endif // !RVC_OS_LINUX
  405. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  406. {
  407. }
  408. e->SetHandled();
  409. break;
  410. }
  411. return unRes;
  412. }
  413. void ResourceWatcherFSM::s2_on_exit()
  414. {
  415. }
  416. void ResourceWatcherFSM::s3_on_entry()
  417. {
  418. LOG_FUNCTION();
  419. m_bVideoClearReady = true;
  420. }
  421. unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
  422. {
  423. unsigned int unRes = 0;
  424. switch (e->iEvt)
  425. {
  426. case USER_EVT_RUN:
  427. {
  428. e->SetHandled();
  429. }
  430. break;
  431. case USER_EVT_FETCH:
  432. {
  433. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  434. if (m_IsPadDevice)
  435. {
  436. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  437. fetchEvt->ctx->Answer(Error_Succeed);
  438. }
  439. else
  440. {
  441. fetchEvt->ctx->Answer(Error_InvalidState);
  442. }
  443. e->SetHandled();
  444. }
  445. break;
  446. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  447. {
  448. m_bGetStatusRotate = FALSE;
  449. e->SetHandled();
  450. }
  451. break;
  452. #ifndef RVC_OS_LINUX
  453. case EVT_TIMER:
  454. {
  455. if (e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
  456. {
  457. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  458. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  459. }
  460. }
  461. e->SetHandled();
  462. break;
  463. #endif // !RVC_OS_LINUX
  464. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE:
  465. {
  466. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  467. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  468. }
  469. e->SetHandled();
  470. break;
  471. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  472. {
  473. }
  474. e->SetHandled();
  475. break;
  476. case USER_EVT_FILE_OPERAT:
  477. {
  478. OperateFileEvent* theEvt = dynamic_cast<OperateFileEvent*>(e);
  479. OperateFileTask* theTask = new OperateFileTask(this, theEvt->m_ctx);
  480. GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
  481. }
  482. e->SetHandled();
  483. break;
  484. case USER_EVT_FILE_OPERAT_FINISHED:
  485. {
  486. }
  487. e->SetHandled();
  488. break;
  489. case USER_EVT_GET_EVENTLOG:
  490. {
  491. GetEventLogEvent* theEvt = dynamic_cast<GetEventLogEvent*>(e);
  492. #ifdef RVC_OS_LINUX
  493. theEvt->m_ctx->Answer(Error_NotSupport);
  494. #else
  495. GetEventLogTask* theTask = new GetEventLogTask(this, theEvt->m_ctx);
  496. GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
  497. #endif // RVC_OS_LINUX
  498. }
  499. e->SetHandled();
  500. break;
  501. case USER_EVT_GET_EVENTLOG_FINISHED:
  502. {
  503. }
  504. e->SetHandled();
  505. break;
  506. }
  507. return unRes;
  508. }
  509. void ResourceWatcherFSM::s3_on_exit()
  510. {
  511. m_bVideoClearReady = false;
  512. }
  513. #ifdef RVC_OS_LINUX
  514. bool ResourceWatcherFSM::GetMonitorInfo(CSimpleStringA& outInfo)
  515. {
  516. std::string sucContent, failedContent;
  517. CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
  518. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  519. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  520. std::string msg = SP::Utility::ToTrim(sucContent);
  521. SP::Utility::replaceInPlace(msg, "\n", "|");
  522. outInfo = msg.c_str();
  523. return ret;
  524. }
  525. void ResourceWatcherFSM::readVideoStoreData()
  526. {
  527. CSmartPointer<IConfigInfo> spCtSettingConfig;
  528. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  529. // From CenterSetting --Josephus at 10:02:10 201759
  530. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "BackwardDays", m_nDayOfBackward);
  531. if (m_nDayOfBackward <= 0) {
  532. m_nDayOfBackward = 90;
  533. } else {
  534. Dbg("Detect BackwardDays from CentralSetting %d", m_nDayOfBackward);
  535. }
  536. if (m_nDayOfBackward <= 0 || m_nDayOfBackward > MAX_DAY_OF_BACKWARD) {
  537. Dbg("Detect BackwardDays(%d) is illegal and Set default %d", m_nDayOfBackward, DEFAULT_DAY_OF_BACKWARD);
  538. m_nDayOfBackward = DEFAULT_DAY_OF_BACKWARD;
  539. }
  540. int minSavedDay = 0;
  541. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MinSavedDays", minSavedDay);
  542. if (minSavedDay >= 1 && minSavedDay < DEFAULT_SAVE_DATE_COUNT) {
  543. m_nMinSavedDay = minSavedDay;
  544. Dbg("Detect MinSavedDays from CentralSetting %d", m_nMinSavedDay);
  545. }
  546. }
  547. #endif // RVC_OS_LINUX
  548. ErrorCodeEnum ResourceWatcherFSM::OnInit()
  549. {
  550. #ifdef RVC_OS_LINUX
  551. LOG_FUNCTION();
  552. ErrorCodeEnum erroCode = Error_Succeed;
  553. CSimpleStringA strtermState;
  554. GetEntityBase()->GetFunction()->GetSysVar("TerminalStage", strtermState);
  555. if (strtermState.IsStartWith("Z=")) {
  556. Dbg("in config mode");
  557. m_bIsConfigMode = TRUE;
  558. }
  559. CSystemStaticInfo sysInfo;
  560. erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
  561. if (erroCode != Error_Succeed) {
  562. Dbg("Get System Static info failed: %s.", SpStrError(erroCode));
  563. return Error_Unexpect;
  564. }
  565. Dbg("%s, %s", sysInfo.strMachineType.GetData(), sysInfo.strTerminalID.GetData());
  566. m_strTerminalNo = sysInfo.strTerminalID;
  567. if (!sysInfo.strMachineType.IsNullOrEmpty() && !sysInfo.strMachineType.Compare("RVC.Pad", true)) {
  568. m_IsPadDevice = TRUE;
  569. }
  570. m_bFirstRunAfterBoot = DetectIsFirstRunAtBoot();
  571. Dbg("to initialize critical section...");
  572. InitializeCriticalSection(&g_csVideoMoreClear);
  573. CSmartPointer<IConfigInfo> spConfig;
  574. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  575. cpuTop = 0;
  576. erroCode = spConfig->ReadConfigValueInt("TOPProcess", "cpu", cpuTop); //读取需要监控的CPU进程个数
  577. if (erroCode != Error_Succeed) {
  578. Dbg("Get CPU TOP NUM failed: %s.", SpStrError(erroCode));
  579. }
  580. if (cpuTop == 0) {
  581. cpuTop = 10; //From static config
  582. } else if (cpuTop == -1) {
  583. Dbg("No need for TOP PROCESS!");
  584. cpuTop = 0;
  585. }
  586. if (!m_bIsConfigMode) {
  587. erroCode = GetEntityBase()->GetFunction()->GetPath("LocalVideo", m_csUploadVideoPath);
  588. if (erroCode != Error_Succeed || m_csUploadVideoPath.IsNullOrEmpty()) {
  589. return Error_NotInit;
  590. }
  591. InitialVolumes();
  592. InitBlackList();
  593. readVideoStoreData();
  594. m_bReadyFlag = IsNeedToFirstClear();
  595. Dbg("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)"
  596. , (LPCTSTR)m_csUploadVideoPath, m_nDayOfBackward, !m_bReadyFlag);
  597. void* pTmpData = NULL;
  598. ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
  599. GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, MAX_HARDWARE_CHECK_TIME);
  600. Dbg("Set Hardware Timer!");
  601. }
  602. return Error_Succeed;
  603. #else
  604. #ifdef WIDE_CONDITION
  605. setlocale(LC_ALL, "chs");
  606. #endif
  607. ErrorCodeEnum erroCode = Error_Succeed;
  608. CSimpleStringA csMacroPath;
  609. CSimpleStringA csLstExecTime;
  610. CSmartPointer<IConfigInfo> spRunConfig;
  611. CSmartPointer<IConfigInfo> spCtSettingConfig;
  612. BOOL bDesk2S = FALSE;
  613. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Complied at: %s %s", __DATE__, __TIME__);
  614. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  615. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  616. erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(m_RvcSysinfo);
  617. m_strTerminalNo = m_RvcSysinfo.strTerminalID;
  618. m_xIdlePre = m_xKernelPre = m_xUserPre = 0; //CPU计算使用
  619. isNeedForceDiskCheck = false;
  620. if (m_RvcSysinfo.strMachineType.Compare("RVC.Pad", true))
  621. {
  622. m_IsPadDevice = FALSE;
  623. }
  624. if (!m_RvcSysinfo.strMachineType.Compare("RVC.Desk2S", true)) {
  625. bDesk2S = TRUE;
  626. }
  627. if (IsHasSetAutoStartupByFolder()) {
  628. /** 因为安装时已经设置为开机自启动了,所以要把注册表的开机自启动取消掉(如果有) Gifur@20221017]*/
  629. m_forceStartupWithExeFlag = 3;
  630. }
  631. else {
  632. InitialAutoStartupSetType();
  633. }
  634. DWORD vc = InitialVolumes();
  635. InitBlackSheet();
  636. spConfig->ReadConfigValue("Video", "Path", csMacroPath);
  637. if (csMacroPath.GetLength() < 1)
  638. {
  639. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Read VideoPath from local config failed");
  640. return Error_NotInit;
  641. }
  642. else
  643. {
  644. erroCode = ExpandDir((LPCTSTR)csMacroPath, m_csUploadVideoPath);
  645. if (erroCode == Error_Succeed)
  646. {
  647. if (m_csUploadVideoPath.GetLength() > 0)
  648. {
  649. m_bReadyFlag = true;
  650. }
  651. else
  652. {
  653. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ExpandDir returned empty string.");
  654. }
  655. }
  656. else
  657. {
  658. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ExpandDir failed.");
  659. }
  660. }
  661. if (!m_bReadyFlag)
  662. {
  663. return Error_NotInit;
  664. }
  665. // From CenterSetting --Josephus at 10:02:10 201759
  666. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "BackwardDays", m_nDayOfBackward);
  667. if (m_nDayOfBackward <= 0)
  668. {
  669. spConfig->ReadConfigValueInt("Video", "BackwardDays", m_nDayOfBackward);
  670. }
  671. if (m_nDayOfBackward <= 0 || m_nDayOfBackward > MAX_DAY_OF_BACKWARD)
  672. {
  673. m_nDayOfBackward = DEFAULT_DAY_OF_BACKWARD;
  674. }
  675. int minSavedDay = 0;
  676. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MinSavedDays", minSavedDay);
  677. if (minSavedDay >= 1 && minSavedDay < DEFAULT_SAVE_DATE_COUNT)
  678. {
  679. m_nMinSavedDay = minSavedDay;
  680. }
  681. //TODO:完全移除
  682. if (FALSE && 0 != m_RvcSysinfo.strMachineType.Compare("RVC.PAD", true)) {
  683. //huchen add for set dns
  684. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DefaultDns", m_strDefaultDns);
  685. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "BackupDns", m_strBackupDns);
  686. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "EnableSetDns", m_nEnableSetDns);
  687. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect Dns from CentralSetting EnableSetDns: %d Default: %s, Backup: %s.", m_nEnableSetDns, m_strDefaultDns.GetData(), m_strBackupDns.GetData());
  688. }
  689. //huchen add for network probe
  690. for (int i = 0; i < MAX_NETWORK_PROBE_COUNT; i++) {
  691. char address_index[10] = { 0 };
  692. itoa(i, address_index, 10);
  693. std::string str_address = "NetProbeAddress";
  694. str_address += address_index;
  695. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), str_address.c_str(), m_strProbeAddress[i]);
  696. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect NetProbe from CentralSetting NetProbeAddress, %d: %s,%s.", i, str_address.c_str(), m_strProbeAddress[i].GetData());
  697. if (m_strProbeAddress[i].GetLength() == 0) {
  698. break;
  699. }
  700. else if (m_fProbeDone) {
  701. m_fProbeDone = false;
  702. }
  703. }
  704. IsNeedToFirstClear();
  705. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)",
  706. (LPCTSTR)m_csUploadVideoPath, m_nDayOfBackward, !m_bReadyFlag);
  707. InitializeCriticalSection(&g_csVideoMoreClear);
  708. InitialCPUMarkInfor();
  709. {
  710. CSystemRunInfo runInfo = { 0 };
  711. erroCode = GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  712. if (erroCode == ERROR_SUCCESS) {
  713. }
  714. BOOL bSet = FALSE;
  715. CBootInfo bootInfo = { 0 };
  716. CSmallDateTime dateTime;
  717. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
  718. erroCode = GetEntityBase()->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
  719. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
  720. CSmallDateTime systemBootTime;
  721. BOOL bRet = GetSystemBootTime(systemBootTime);
  722. BOOL bRequiredSet = FALSE;
  723. if (bRet && systemBootTime > bootInfo.tmStart) {
  724. bSet = TRUE;
  725. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
  726. if (eRet != Error_Succeed) {
  727. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
  728. }
  729. ///*TODO(80374374@10/17/2022): */
  730. m_DoneDetectAutostart = false;
  731. std::map<std::string, std::string> srcData;
  732. CSimpleStringA strData = CSimpleStringA::Format("{\"AppLastStartTime\":\"%s\",\"AppStartTime\":\"%s\",\"OSStartTime\":\"%s\"}"
  733. , (LPCTSTR)bootInfo.tmStart.ToTimeString(), (LPCTSTR)runInfo.tmStart.ToTimeString(), systemBootTime.ToTimeString().GetData());
  734. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT, strData.GetData());
  735. }
  736. if (bDesk2S) {
  737. int nLastTaskTime(0);
  738. spRunConfig->ReadConfigValueInt("Device", "SetAudioOutput", nLastTaskTime);
  739. CSmallDateTime lastSetTime(nLastTaskTime);
  740. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RunConfig SetAudioOutput time : %s", (LPCTSTR)lastSetTime.ToTimeString());
  741. if (systemBootTime > lastSetTime) {
  742. bRequiredSet = TRUE;
  743. }
  744. }
  745. if (bRequiredSet) {
  746. bRet = SetDefaultAudioDevice();
  747. if (bRet) {
  748. spRunConfig->WriteConfigValue("Device", "SetAudioOutput",
  749. (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  750. }
  751. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("set default audio returned: %d", bRet);
  752. if (!bRet) {
  753. LogWarn(Severity_High, Error_AudioOut, 0, "Set default video output failed!!");
  754. }
  755. }
  756. if (!bSet) {
  757. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
  758. }
  759. else {
  760. if (!curUserName.IsNullOrEmpty()) {
  761. DetectDestopFileAndWarn(curUserName);
  762. }
  763. if (0 == m_RvcSysinfo.strMachineType.Compare("RVC.Stand2S", true)) {
  764. const int aimScreenNums = 2;
  765. const int screenNums = GetSystemMetrics(SM_CMONITORS);
  766. if (screenNums != 2) {
  767. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_LACK_OF_MONITOR
  768. , CSimpleStringA::Format("lack of monitor! current: %d, aim: %d", screenNums, aimScreenNums));
  769. }
  770. }
  771. }
  772. }
  773. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MainDetectFlag", mainDetectFlag);
  774. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckTime", hardwareCheckTime);
  775. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckFlag", hardwareCheckFlag);
  776. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "CpuTooHighPercent", m_cpuHighPercent);
  777. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MemoryTooHighPercent", m_memHighPercent);
  778. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardDiskTooHighPercent", m_diskHighPercent);
  779. if (hardwareCheckTime < MAX_HARDWARE_CHECK_TIME)
  780. {
  781. hardwareCheckTime = MAX_HARDWARE_CHECK_TIME;
  782. }
  783. void* pTmpData = NULL;
  784. ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
  785. GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, hardwareCheckTime);
  786. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set Hardware Timer!");
  787. m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  788. spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "VerifySignature", m_iVerify);
  789. spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "DisplayCnt", m_iNonSignedDisplay);
  790. if (m_iNonSignedDisplay <= 0)
  791. m_iNonSignedDisplay = 10;
  792. if (m_iVerify == 1)
  793. {
  794. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Verify digitsign...");
  795. VerifyDigitSignTask* task = new VerifyDigitSignTask(this);
  796. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  797. }
  798. terminalShowFlag = false;
  799. lastACLineStatus = -1;
  800. lastBatteryPercent = -1;
  801. lastNetStatus = -1;
  802. terminalStatusSwitch = 0; //默认关闭
  803. tmpMessageWindFlag = false;
  804. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "TerminalStatusSwitch", terminalStatusSwitch);
  805. if (m_RvcSysinfo.strMachineType == "RVC.CardPrinter")
  806. {
  807. CSmartPointer<IConfigInfo> spCtSettingConfig;
  808. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  809. CSimpleStringA tType("");
  810. spCtSettingConfig->ReadConfigValue("Chromium", "WebMask_RVC.CardPrinter", tType);
  811. if (tType == CSimpleStringA::Format("with_browser"))
  812. {
  813. isNeedShowTerminalStatus = false;
  814. }
  815. else
  816. {
  817. isNeedShowTerminalStatus = true;
  818. }
  819. }
  820. else
  821. {
  822. isNeedShowTerminalStatus = true;
  823. }
  824. CSmartPointer<IConfigInfo> spConfigRun;
  825. ErrorCodeEnum err = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  826. if (err == Error_Succeed) {
  827. spConfigRun->ReadConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  828. }
  829. return Error_Succeed;
  830. #endif // RVC_OS_LINUX
  831. }
  832. ErrorCodeEnum ResourceWatcherFSM::OnExit()
  833. {
  834. #ifdef RVC_OS_LINUX
  835. GetEntityBase()->GetFunction()->KillTimer(TIMER_HARDWARE_CHECK);
  836. #endif // RVC_OS_LINUX
  837. ClearVideoQueue();
  838. DeleteCriticalSection(&g_csVideoMoreClear);
  839. return Error_Succeed;
  840. }
  841. #ifdef RVC_OS_LINUX
  842. void ResourceWatcherFSM::AfterInit()
  843. {
  844. CSmartPointer<IConfigInfo> spCtSettingConfig;
  845. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  846. //huchen add for set dns
  847. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DefaultDns", m_strDefaultDns);
  848. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "BackupDns", m_strBackupDns);
  849. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "EnableSetDns", m_nEnableSetDns);
  850. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect Dns from CentralSetting EnableSetDns: %d Default: %s, Backup: %s.",
  851. m_nEnableSetDns, m_strDefaultDns.GetData(), m_strBackupDns.GetData());
  852. if (m_bFirstRunAfterBoot) {
  853. UINT sysVer = 0;
  854. UploadSysVersionInfo(sysVer);
  855. ConfirmWindowEffectHasBeenOpen();
  856. ConfirmDNSConfigHasSet();
  857. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fetch os version: %u", sysVer);
  858. if (1031 < sysVer) {
  859. ConfirmDDEClipboardDisable();
  860. ConfirmNotificationCenterDisable();
  861. } else {
  862. RecoverDDEClipboardEnable();
  863. }
  864. GetEntityBase()->GetFunction()->PostThreadPoolTask(new DetectSoftwareInstallStatusTask(this));
  865. GetEntityBase()->GetFunction()->PostThreadPoolTask(new UploadMonitorInfoTask(this));
  866. }
  867. ///**TODO(Gifur@8/10/2023): 联调完成后把它挪到开机时第一次启动时才执行 */
  868. AlarmSystemBasicInfo();
  869. }
  870. #else
  871. int ResourceWatcherFSM::NetProbe() {
  872. int i = m_nProbeIndex;
  873. if (i < MAX_NETWORK_PROBE_COUNT) {
  874. if (m_strProbeAddress[i].GetLength() == 0) {
  875. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("NetProbeAddress index: %d is null.", i);
  876. return -1;
  877. }
  878. CAutoArray<CSimpleStringA> strContent = m_strProbeAddress[i].Split(',');
  879. if (strContent.GetCount() < 2)
  880. {
  881. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address 参数个数错误.");
  882. m_nProbeIndex++;
  883. return 0;
  884. }
  885. if (strContent[0].Compare("http") == 0) {
  886. http_probe((char*)strContent[1].GetData(), 5 * 1000, i);
  887. }
  888. else if (strContent[0].Compare("tcp") == 0) {
  889. if (strContent.GetCount() < 3)
  890. {
  891. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address TCP 参数个数错误.");
  892. m_nProbeIndex++;
  893. return 0;
  894. }
  895. if (isdigit(strContent[2][0])) {
  896. tcp_probe((char*)strContent[1].GetData(), atoi(strContent[2]), i);
  897. }
  898. }
  899. else if (strContent[0].Compare("udp") == 0) {
  900. if (strContent.GetCount() < 3)
  901. {
  902. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address UDP 参数个数错误.");
  903. m_nProbeIndex++;
  904. return 0;
  905. }
  906. if (isdigit(strContent[2][0])) {
  907. udp_probe((char*)strContent[1].GetData(), atoi(strContent[2]), 5 * 1000, i);
  908. }
  909. }
  910. else {
  911. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address 参数类型错误");
  912. }
  913. }
  914. m_nProbeIndex++;
  915. return 0;
  916. }
  917. int ResourceWatcherFSM::SetDnsServer()
  918. {
  919. if (!m_nEnableSetDns) {
  920. return 0;
  921. }
  922. if ((m_strDefaultDns.GetLength() == 0) || (m_strBackupDns.GetLength() == 0)) {
  923. return 0;
  924. }
  925. //get dns
  926. char print_buffer[1024];
  927. DWORD before_time = GetTickCount();
  928. auto netcards_info = NetCardInfo::GetNetworkInfo();
  929. DWORD now_time = GetTickCount();
  930. std::vector<std::shared_ptr<NetCardInfo>>::iterator it;
  931. std::string print_msg = "Get Dns Success ! Cust: ";
  932. std::ostringstream os;
  933. os << now_time - before_time;
  934. print_msg += os.str();
  935. for (it = netcards_info.begin(); it != netcards_info.end(); ++it) {
  936. print_msg += "default_dns:";
  937. print_msg += (*it)->GetNetCardInfo().default_dns.c_str();
  938. print_msg += " backup_dns:";
  939. print_msg += (*it)->GetNetCardInfo().backup_dns.c_str();
  940. print_msg += ", ";
  941. }
  942. print_msg += "cfg_default_dns:";
  943. print_msg += m_strDefaultDns.GetData();
  944. print_msg += " cfg_bak_dns:";
  945. print_msg += m_strBackupDns.GetData();
  946. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_GET_DNS_CUST, print_msg.c_str());
  947. //set or delete dns
  948. before_time = now_time;
  949. bool set_result = false;
  950. bool delete_dns = false;
  951. bool had_set = false;
  952. std::vector<int> error_codes;
  953. if ((strcmp("0.0.0.0", m_strDefaultDns.GetData()) == 0) && (strcmp("0.0.0.0", m_strBackupDns.GetData()) == 0)) {
  954. delete_dns = true;
  955. }
  956. for (it = netcards_info.begin(); it != netcards_info.end(); ++it) {
  957. char buffer[1024];
  958. (*it)->show(buffer, 1024);
  959. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetDnsServer, NetworkInfo: %s", buffer);
  960. string::size_type idx = (*it)->GetNetCardInfo().ip.find(":");
  961. if (idx != string::npos) {
  962. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDnsServer, ip is ipv6, skip.");
  963. continue;
  964. }
  965. idx = (*it)->GetNetCardInfo().default_dns.find(":");
  966. if (idx != string::npos) {
  967. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDnsServer, default dns is ipv6, skip.");
  968. continue;
  969. }
  970. idx = (*it)->GetNetCardInfo().backup_dns.find(":");
  971. if (idx != string::npos) {
  972. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDnsServer, backup dns is ipv6, skip.");
  973. continue;
  974. }
  975. //delete dns
  976. if (delete_dns) {
  977. if ((*it)->SetAutoDns()) {
  978. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete Dns Success.");
  979. set_result = true;
  980. }
  981. else {
  982. int error_code = (*it)->get_last_error_code();
  983. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Delete Dns Failed. error_code: %d", error_code);
  984. error_codes.push_back(error_code);
  985. }
  986. continue;
  987. }
  988. //set dns
  989. if ((strcmp((*it)->GetNetCardInfo().default_dns.c_str(), m_strDefaultDns.GetData()) != 0) ||
  990. (strcmp((*it)->GetNetCardInfo().backup_dns.c_str(), m_strBackupDns.GetData()) != 0)) {
  991. if ((*it)->SetDns(m_strDefaultDns.GetData(), m_strBackupDns.GetData())) {
  992. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set Dns Success.");
  993. set_result = true;
  994. }
  995. else {
  996. int error_code = (*it)->get_last_error_code();
  997. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Set Dns Failed. error_code: %d", error_code);
  998. error_codes.push_back(error_code);
  999. }
  1000. }
  1001. else {
  1002. had_set = true;
  1003. }
  1004. }
  1005. //print set dns result
  1006. if (!had_set) {
  1007. now_time = GetTickCount();
  1008. if (delete_dns) {
  1009. if (set_result) {
  1010. _snprintf(print_buffer, 1024, "Delete Dns Success ! Cust: %d", now_time - before_time);
  1011. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_DELETE_DNS_CUST, print_buffer);
  1012. }
  1013. else {
  1014. //_snprintf(print_buffer, 1024, "Delete Dns Failed ! Cust: %d", now_time - before_time);
  1015. std::string print_msg = "Delete Dns Failed ! Cust: ";
  1016. std::ostringstream os;
  1017. os << now_time - before_time;
  1018. print_msg += os.str();
  1019. std::vector<int>::iterator it;
  1020. print_msg += "error_codes: ";
  1021. for (it = error_codes.begin(); it != error_codes.end(); ++it) {
  1022. std::ostringstream os;
  1023. os << *it;
  1024. print_msg += os.str();
  1025. print_msg += ", ";
  1026. }
  1027. LogWarn(Severity_High, Error_Unexpect, LOG_ERR_DELETE_DNS_FAILED, print_msg.c_str());
  1028. }
  1029. }
  1030. else {
  1031. if (set_result) {
  1032. _snprintf(print_buffer, 1024, "Set Dns Success ! Cust: %d", now_time - before_time);
  1033. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_SET_DNS_CUST, print_buffer);
  1034. }
  1035. else {
  1036. //_snprintf(print_buffer, 1024, "Set Dns Failed ! Cust: %d", now_time - before_time);
  1037. std::string print_msg = "Set Dns Failed ! Cust: ";
  1038. std::ostringstream os;
  1039. os << now_time - before_time;
  1040. print_msg += os.str();
  1041. std::vector<int>::iterator it;
  1042. print_msg += "error_codes: ";
  1043. for (it = error_codes.begin(); it != error_codes.end(); ++it) {
  1044. std::ostringstream os;
  1045. os << *it;
  1046. print_msg += os.str();
  1047. print_msg += ", ";
  1048. }
  1049. LogWarn(Severity_High, Error_Unexpect, LOG_ERR_SET_DNS_FAILED, print_msg.c_str());
  1050. }
  1051. }
  1052. }
  1053. return 0;
  1054. }
  1055. #endif // RVC_OS_LINUX
  1056. int ResourceWatcherFSM::GetCardSwiperStatus()
  1057. {
  1058. LOG_FUNCTION();
  1059. ErrorCodeEnum errorCode = Error_Succeed;
  1060. CardSwiperClient* client = NULL;
  1061. CardSwiperService_QueryConnInfo_Req req;
  1062. CardSwiperService_QueryConnInfo_Ans ans;
  1063. QueryCardSwiper cardswiperStatus;
  1064. BOOL bConnected = FALSE;
  1065. // [Josephus in 7:05:25 2016/9/6]
  1066. int lastStatus = m_cardswiperStatus;
  1067. int errorTimes1 = 0, errorTimes2 = 0, errorTimes3 = 0;
  1068. int sleepTime = 1500;
  1069. const int errorMaxTimes = 2;
  1070. m_bGetStatusRotate = TRUE;
  1071. while (m_bGetStatusRotate)
  1072. {
  1073. if (client == NULL)
  1074. {
  1075. client = new CardSwiperClient(GetEntityBase());
  1076. }
  1077. if (!bConnected)
  1078. {
  1079. errorCode = client->Connect();
  1080. if (errorCode != Error_Succeed)
  1081. {
  1082. if (errorTimes1 < errorMaxTimes)
  1083. {
  1084. errorTimes1++;
  1085. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Connect to CardSwiper failed %s", SpStrError(errorCode));
  1086. Sleep(500);
  1087. continue;
  1088. }
  1089. else
  1090. {
  1091. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Connect to CardSwiper failed...");
  1092. // [Josephus in 16:15:37 2016/3/28]
  1093. bConnected = FALSE;
  1094. client->SafeDelete();
  1095. client = NULL;
  1096. m_cardswiperStatus = 0;
  1097. goto BroadCastPoint;
  1098. }
  1099. }
  1100. else
  1101. {
  1102. bConnected = TRUE;
  1103. errorTimes3 = errorTimes2 = 0;
  1104. }
  1105. }
  1106. errorCode = client->QueryConnInfo(req, ans, 3000);
  1107. if (errorCode != Error_Succeed)
  1108. {
  1109. if (errorTimes2 < errorMaxTimes)
  1110. {
  1111. errorTimes2++;
  1112. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get CardSwiper status failed with code %s", SpStrError(errorCode));
  1113. Sleep(500);
  1114. continue;
  1115. }
  1116. else
  1117. {
  1118. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get CardSwiper status failed...");
  1119. bConnected = FALSE;
  1120. client->GetFunction()->CloseSession();
  1121. client = NULL;
  1122. m_cardswiperStatus = 0;
  1123. }
  1124. }
  1125. else
  1126. {
  1127. errorTimes1 = errorTimes2 = errorTimes3 = 0;
  1128. m_cardswiperStatus = ans.connect;
  1129. }
  1130. BroadCastPoint:
  1131. if (lastStatus != m_cardswiperStatus)
  1132. {
  1133. cardswiperStatus.status = m_cardswiperStatus;
  1134. SpSendBroadcast(GetEntityBase()->GetFunction(),
  1135. SP_MSG_OF(QueryCardSwiper), SP_MSG_SIG_OF(QueryCardSwiper), cardswiperStatus);
  1136. lastStatus = m_cardswiperStatus;
  1137. }
  1138. break;
  1139. }
  1140. if (client)
  1141. {
  1142. #ifdef RVC_OS_LINUX
  1143. if (bConnected)
  1144. {
  1145. client->GetFunction()->CloseSession();
  1146. }
  1147. else
  1148. {
  1149. client->SafeDelete();
  1150. }
  1151. #else
  1152. client->SafeDelete();
  1153. #endif // RVC_OS_LINUX
  1154. client = NULL;
  1155. }
  1156. return 0;
  1157. }
  1158. #ifdef RVC_OS_LINUX
  1159. void ResourceWatcherFSM::AppendVideoSizeTogether()
  1160. {
  1161. Dbg("Add UploadFile size together...");
  1162. unsigned long long uiAdditionBytes;
  1163. CalculateWillUploadDirSize(uiAdditionBytes);
  1164. mAllVideoFileSizeCal += uiAdditionBytes;
  1165. diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
  1166. }
  1167. void ResourceWatcherFSM::CalculateFreeDiskNeeded()
  1168. {
  1169. const_map_cu_iter citer = VideoDailyRecord.cbegin();
  1170. UINT uCount = 0;
  1171. while (citer != VideoDailyRecord.cend()) {
  1172. Dbg("date[%d]: %d", (citer->first), citer->second);
  1173. uCount += citer->second;
  1174. citer++;
  1175. }
  1176. Dbg("count %d and video file size#%d", uCount, m_VideoFiles.size());
  1177. diskInfo.CalAverRequreSpaceEachDay(mAllVideoFileSizeCal,
  1178. uCount, VideoDailyRecord.size(),
  1179. BASE_AVAILALBE_DATE_COUNT, mUiRequireBytes);
  1180. }
  1181. void ResourceWatcherFSM::RecordFreeDiskNeededToRunCfg()
  1182. {
  1183. CSmartPointer<IConfigInfo> spConfigRun;
  1184. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1185. spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes);
  1186. spConfigRun->WriteConfigValue("LastClearTime", "Video", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  1187. m_bReadyFlag = false;
  1188. }
  1189. void ResourceWatcherFSM::GetFreeDiskNeededFromRunCfg()
  1190. {
  1191. CSmartPointer<IConfigInfo> spConfigRun;
  1192. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1193. UINT64 value(0);
  1194. spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", value);
  1195. mUiRequireBytes = value;
  1196. Dbg("Retrieve from runcfg about required bytes: %llu", value);
  1197. }
  1198. #endif // RVC_OS_LINUX
  1199. int ResourceWatcherFSM::CleanVideoFiles(int& newDeletedFilesNum, int initFlag)
  1200. {
  1201. #ifdef RVC_OS_LINUX
  1202. ClearVideoQueue();
  1203. newDeletedFilesNum = 0;
  1204. CSimpleStringA filePath = m_csUploadVideoPath;
  1205. Dbg("(InitFlag:%d) filePath %s", initFlag, (LPCTSTR)filePath);
  1206. newDeletedFilesNum = 0;
  1207. m_failDelCnt = 0;
  1208. const int nRet = RemoveExpireVideoFileAndRecord((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
  1209. PrintVideEmurateResult();
  1210. Dbg("nRet: %d, new Deleted Files Num:%d, video counts:%d", nRet, newDeletedFilesNum, m_VideoFiles.size());
  1211. LOG_ASSERT(nRet - newDeletedFilesNum == m_VideoFiles.size());
  1212. if (!!initFlag) {
  1213. AppendVideoSizeTogether();
  1214. CalculateFreeDiskNeeded();
  1215. RecordFreeDiskNeededToRunCfg();
  1216. }
  1217. else {
  1218. GetFreeDiskNeededFromRunCfg();
  1219. }
  1220. return nRet;
  1221. #else
  1222. ClearVideoQueue();
  1223. CSimpleStringA filePath = m_csUploadVideoPath + "\\*";
  1224. newDeletedFilesNum = 0;
  1225. m_failDelCnt = 0;
  1226. int nRet = ProcessVideoFile((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
  1227. PrintResult();
  1228. assert(nRet - newDeletedFilesNum == m_VideoFiles.size());
  1229. CSmartPointer<IConfigInfo> spConfigRun;
  1230. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1231. if (initFlag == 1)
  1232. {
  1233. ULARGE_INTEGER uiAdditionBytes;
  1234. CalCulateUploadFileAddition(uiAdditionBytes);
  1235. uiAllVideoFileSizeCal.QuadPart += uiAdditionBytes.QuadPart;
  1236. diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
  1237. const_map_cu_iter citer = VideoDailyRecord.cbegin();
  1238. UINT uCount = 0;
  1239. while (citer != VideoDailyRecord.cend())
  1240. {
  1241. uCount += citer->second;
  1242. citer++;
  1243. }
  1244. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("uCount#%d, size#%d", uCount, m_VideoFiles.size());
  1245. diskInfo.CalAverRequreSpaceEachDay(uiAllVideoFileSizeCal,
  1246. uCount,
  1247. VideoDailyRecord.size(),
  1248. BASE_AVAILALBE_DATE_COUNT,
  1249. mUiRequireBytes);
  1250. FILETIME ftCurTime;
  1251. GetSystemTimeAsFileTime(&ftCurTime);
  1252. SYSTEMTIME stUTC, stLocal;
  1253. FileTimeToSystemTime(&ftCurTime, &stUTC);
  1254. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  1255. int nYear = stLocal.wYear;
  1256. int nMonth = stLocal.wMonth;
  1257. int nDay = stLocal.wDay;
  1258. char displayTime[MAX_PATH] = { 0 };
  1259. GetTimeString(displayTime, MAX_PATH, &ftCurTime);
  1260. CSimpleStringA csRecord = displayTime;
  1261. #if 1
  1262. spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
  1263. spConfigRun->WriteConfigValueInt("Video", "FilesNum", nRet);
  1264. spConfigRun->WriteConfigValueInt("Video", "Deleted", newDeletedFilesNum);
  1265. spConfigRun->WriteConfigValueInt("Video", "FailedDel", m_failDelCnt);
  1266. spConfigRun->WriteConfigValue("Video", "LastTime", csRecord);
  1267. spConfigRun->WriteConfigValueInt("Video", "Year", nYear);
  1268. spConfigRun->WriteConfigValueInt("Video", "Month", nMonth);
  1269. spConfigRun->WriteConfigValueInt("Video", "Day", nDay);
  1270. m_bReadyFlag = false;
  1271. #endif
  1272. }
  1273. else
  1274. {
  1275. ErrorCodeEnum erroCode = spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes",
  1276. mUiRequireBytes.QuadPart);
  1277. if (erroCode != Error_Succeed)
  1278. {
  1279. LogWarn(Severity_Middle, Error_Unexpect, 0, "Get RequiredBytes failed !");
  1280. mUiRequireBytes.QuadPart = 0ui64;
  1281. }
  1282. }
  1283. return nRet;
  1284. #endif // RVC_OS_LINUX
  1285. }
  1286. #ifdef RVC_OS_LINUX
  1287. void ResourceWatcherFSM::CalculateBackTime(time_t* ftResultTime, int days)
  1288. {
  1289. time_t ftCurTime = time(NULL);//获取当前时间
  1290. time_t ftBackTime = ftCurTime - (60 * 60 * 24 * days);
  1291. *ftResultTime = ftBackTime;
  1292. return;
  1293. }
  1294. BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(unsigned long long& uiBytesCal)
  1295. {
  1296. uiBytesCal = 0;
  1297. BOOL bRet = FALSE;
  1298. CSimpleStringA uploadVideoPath;
  1299. CSimpleStringA tmpValue;
  1300. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
  1301. if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
  1302. if (ec == Error_Succeed) {
  1303. Dbg("UploadVideo path: %s", (LPCTSTR)uploadVideoPath);
  1304. uiBytesCal = 0;
  1305. const int nFileCnt = CalculateAllVideoSize(uploadVideoPath, &uiBytesCal);
  1306. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1307. ByteSprintf(szResult, (double)uiBytesCal);
  1308. Dbg("Result: Files(%d), Size: %s", nFileCnt, szResult);
  1309. }
  1310. return (ec == Error_Succeed);
  1311. }
  1312. int ResourceWatcherFSM::RemoveExpireVideoFileAndRecord(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag)
  1313. {
  1314. int fileCnt = 0;
  1315. int fileLength = strlen(dirName);
  1316. // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
  1317. char searchFilePath[MAX_PATH] = { 0 };
  1318. char tempFilePath[MAX_PATH] = { 0 };
  1319. char displayTime[MAX_PATH] = { 0 };
  1320. time_t tmp_time;
  1321. CalculateBackTime(&tmp_time, m_nDayOfBackward);
  1322. deletedFileCnt = deleteFailedCnt = 0;
  1323. GetTimeFormatStr(displayTime, MAX_PATH, &tmp_time);
  1324. Dbg("video backtrace time: %s", displayTime);
  1325. struct stat st;
  1326. if (stat(dirName, &st) < 0 || !S_ISDIR(st.st_mode)) {
  1327. return 0;
  1328. }
  1329. DIR* d = opendir(dirName);
  1330. if (!d) {
  1331. return 0;
  1332. }
  1333. struct dirent* dp = NULL;
  1334. while ((dp = readdir(d)) != NULL) {
  1335. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1336. continue;
  1337. }
  1338. strcpy(tempFilePath, dirName);
  1339. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1340. Dbg("filePath is too long for current.");
  1341. continue;
  1342. }
  1343. strcat(tempFilePath, "/");
  1344. strcat(tempFilePath, dp->d_name);
  1345. if (-1 == stat(tempFilePath, &st)) {
  1346. Dbg("stat video file: %s error: %d", tempFilePath, errno);
  1347. continue;
  1348. }
  1349. const bool isdir = !!(S_ISDIR(st.st_mode));
  1350. if (isdir) {
  1351. fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  1352. }
  1353. else {
  1354. if (nFlag == 1 && st.st_mtime < tmp_time) {
  1355. GetTimeFormatStr(displayTime, MAX_PATH, &st.st_mtime);
  1356. if (RemoveFileA(tempFilePath)) {
  1357. deletedFileCnt++;
  1358. Dbg("Delete matched %s(%s) suc.", dp->d_name, displayTime);
  1359. }
  1360. else {
  1361. deleteFailedCnt++;
  1362. Dbg("Delete matched %s(%s) failed: %d", dp->d_name, displayTime, errno);
  1363. }
  1364. }
  1365. RecordVideoFileInfomation(tempFilePath, &st);
  1366. fileCnt++;
  1367. }
  1368. }
  1369. closedir(d);
  1370. return fileCnt;
  1371. }
  1372. void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, struct stat* pWfdata)
  1373. {
  1374. m_VideoFiles.push(new TmpFileInfo(lpFilePath, pWfdata->st_mtime, pWfdata->st_size));
  1375. mAllVideoFileSizeCal += pWfdata->st_size;
  1376. if (mMaxFileSize < pWfdata->st_size) {
  1377. strcpy(szMaxSizeFilePath, lpFilePath);
  1378. mMaxFileSize = pWfdata->st_size;
  1379. }
  1380. SyncUpdateVideoCreateDaily(&pWfdata->st_mtime, 1);
  1381. }
  1382. #else
  1383. void ResourceWatcherFSM::CalculateBackTime(PFILETIME ftResultTime, int days)
  1384. {
  1385. //Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
  1386. FILETIME ftCurTime, ftBackTime;
  1387. GetSystemTimeAsFileTime(&ftCurTime);
  1388. ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
  1389. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  1390. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  1391. if (days > 0)
  1392. {
  1393. uliOffset.QuadPart = UInt32x32To64(days * 24 * 60 * 60, 1e7);
  1394. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  1395. }
  1396. else
  1397. {
  1398. uliOffset.QuadPart = UInt32x32To64(-1 * days * 24 * 60 * 60, 1e7);
  1399. uliBackTime.QuadPart = uliCurTime.QuadPart + uliOffset.QuadPart;
  1400. }
  1401. ftBackTime.dwHighDateTime = uliBackTime.HighPart;
  1402. ftBackTime.dwLowDateTime = uliBackTime.LowPart;
  1403. *ftResultTime = ftBackTime;
  1404. return;
  1405. }
  1406. void ResourceWatcherFSM::GetTimeString(LPTSTR lpszString, DWORD dwSize, FILETIME* ftWrite)
  1407. {
  1408. SYSTEMTIME stUTC, stLocal;
  1409. // Convert the last-write time to local time.
  1410. FileTimeToSystemTime(ftWrite, &stUTC);
  1411. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  1412. // Build a string showing the date and time.
  1413. sprintf_s(lpszString, dwSize, "%02d/%02d/%d %02d:%02d:%02d",
  1414. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1415. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  1416. return;
  1417. }
  1418. int ResourceWatcherFSM::ProcessVideoFile(
  1419. LPCTSTR dirName
  1420. , int& deletedFileCnt
  1421. , int& deleteFailedCnt
  1422. , const int nFlag)
  1423. {
  1424. int fileCnt = 0;
  1425. int fileLength = strlen(dirName);
  1426. // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
  1427. char searchFilePath[MAX_PATH] = { 0 };
  1428. char tempFilePath[MAX_PATH] = { 0 };
  1429. char displayTime[MAX_PATH] = { 0 };
  1430. WIN32_FIND_DATA foundFileData;
  1431. HANDLE hFind;
  1432. FILETIME ftRemoveTime;
  1433. CalculateBackTime(&ftRemoveTime, m_nDayOfBackward);
  1434. GetTimeString(displayTime, MAX_PATH, &ftRemoveTime);
  1435. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The date backward to delete: %s", displayTime);
  1436. hFind = FindFirstFile(dirName, &foundFileData);
  1437. if (hFind == INVALID_HANDLE_VALUE)
  1438. {
  1439. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM) ("FindFirstFile failed (%u)", GetLastError());
  1440. return 0;
  1441. }
  1442. if ((foundFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  1443. {
  1444. if (/*foundFileData.cFileName[0] != '.'*/FALSE)
  1445. {
  1446. strcpy_s(tempFilePath, dirName);
  1447. tempFilePath[fileLength - 1] = '\0';
  1448. if (strlen(tempFilePath) + strlen(foundFileData.cFileName) + 3 >= MAX_PATH)
  1449. {
  1450. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  1451. }
  1452. else
  1453. {
  1454. strcat_s(tempFilePath, foundFileData.cFileName);
  1455. strcat_s(tempFilePath, "\\*");
  1456. fileCnt += ProcessVideoFile((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  1457. }
  1458. }
  1459. }
  1460. else
  1461. {
  1462. strcpy_s(searchFilePath, dirName);
  1463. searchFilePath[fileLength - 1] = '\0';
  1464. strcat_s(searchFilePath, foundFileData.cFileName);
  1465. if (nFlag == 1 && CompareVideoFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0)
  1466. {
  1467. GetTimeString(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
  1468. if (DeleteFile(searchFilePath) != 0)
  1469. {
  1470. deletedFileCnt++;
  1471. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete matched %s(%s) suc.", foundFileData.cFileName, displayTime);
  1472. }
  1473. else
  1474. {
  1475. deleteFailedCnt++;
  1476. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete matched %s(%s) failed(%d).", foundFileData.cFileName, displayTime, GetLastError());
  1477. CalCulateFileInfo(searchFilePath, &foundFileData);
  1478. }
  1479. }
  1480. else
  1481. {
  1482. CalCulateFileInfo(searchFilePath, &foundFileData);
  1483. }
  1484. fileCnt++;
  1485. }
  1486. while (FindNextFile(hFind, &foundFileData))
  1487. {
  1488. if ((foundFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  1489. {
  1490. if (/*foundFileData.cFileName[0] != '.'*/FALSE)
  1491. {
  1492. strcpy_s(tempFilePath, dirName);
  1493. tempFilePath[fileLength - 1] = '\0';
  1494. strcat_s(tempFilePath, foundFileData.cFileName);
  1495. strcat_s(tempFilePath, "\\*");
  1496. fileCnt += ProcessVideoFile((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  1497. }
  1498. }
  1499. else
  1500. {
  1501. strcpy_s(searchFilePath, dirName);
  1502. searchFilePath[fileLength - 1] = '\0';
  1503. strcat_s(searchFilePath, foundFileData.cFileName);
  1504. if (nFlag == 1 && CompareVideoFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0)
  1505. {
  1506. GetTimeString(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
  1507. if (DeleteFile(searchFilePath) != 0)
  1508. {
  1509. deletedFileCnt++;
  1510. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete matched %s(%s) suc.", foundFileData.cFileName, displayTime);
  1511. }
  1512. else
  1513. {
  1514. deleteFailedCnt++;
  1515. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Delete matched %s(%s) failed(%d).",
  1516. foundFileData.cFileName, displayTime, GetLastError());
  1517. CalCulateFileInfo(searchFilePath, &foundFileData);
  1518. }
  1519. }
  1520. else
  1521. {
  1522. CalCulateFileInfo(searchFilePath, &foundFileData);
  1523. }
  1524. fileCnt++;
  1525. }
  1526. }
  1527. FindClose(hFind);
  1528. return fileCnt;
  1529. }
  1530. BOOL ResourceWatcherFSM::GetCPUBrand(CSimpleStringA& csCpuBrand)
  1531. {
  1532. char CPUBrandString[0x40];
  1533. int CPUInfo[4] = { -1 };
  1534. unsigned nExIds;
  1535. // Calling __cpuid with 0x80000000 as the InfoType argument
  1536. // gets the number of valid extended IDs.
  1537. __cpuid(CPUInfo, 0x80000000);
  1538. nExIds = CPUInfo[0];
  1539. memset(CPUBrandString, 0, sizeof(CPUBrandString));
  1540. if (nExIds >= 0x80000004)
  1541. {
  1542. __cpuid(CPUInfo, 0x80000002);
  1543. memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
  1544. __cpuid(CPUInfo, 0x80000003);
  1545. memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
  1546. __cpuid(CPUInfo, 0x80000004);
  1547. memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
  1548. // Display all the information in user-friendly format.
  1549. csCpuBrand = CPUBrandString;
  1550. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CPU Brand String: %s", (LPCTSTR)csCpuBrand);
  1551. return TRUE;
  1552. }
  1553. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Current device is not supported for getting cpu brand 0x%08x.", nExIds);
  1554. return FALSE;
  1555. }
  1556. void ResourceWatcherFSM::InitialCPUMarkInfor()
  1557. {
  1558. m_highPart = 4000;
  1559. m_lowPart = 2000;
  1560. Dbg("hight:%d > value >low:%d.", m_highPart, m_lowPart);
  1561. return;
  1562. }
  1563. #endif // RVC_OS_LINUX
  1564. void ResourceWatcherFSM::ClearMoreVideoFiles()
  1565. {
  1566. #ifdef RVC_OS_LINUX
  1567. EnterCriticalSection(&g_csVideoMoreClear);
  1568. ErrorCodeEnum erroCode = Error_Succeed;
  1569. BOOL bOK = FALSE;
  1570. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
  1571. CSmartPointer<IConfigInfo> spConfigRun;
  1572. ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1573. if (m_VideoFiles.empty() || mUiRequireBytes == 0) {
  1574. int reseved = 0;
  1575. int nRes = CleanVideoFiles(reseved, IsNeedToFirstClear() ? 1 : 0);
  1576. if (nRes - reseved == 0) {
  1577. Dbg("There are no any video files in facts.");
  1578. //SetSysValAndBroadcast(0, "There are no any video files in facts.");
  1579. LeaveCriticalSection(&g_csVideoMoreClear);
  1580. return;
  1581. }
  1582. }
  1583. int CurRank = 3; //default
  1584. int BfRank = 0;
  1585. if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
  1586. BfRank = 0;
  1587. }
  1588. if (BfRank > 0) {
  1589. unsigned long long uiTotalBytes;
  1590. unsigned long long uiFreeDiskBytes;
  1591. if (!DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
  1592. LeaveCriticalSection(&g_csVideoMoreClear);
  1593. return;
  1594. }
  1595. //对比上次,剩余的可用磁盘空间更小了。
  1596. if (mUiCalibration >= uiFreeDiskBytes) {
  1597. Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
  1598. CurRank = BfRank == 4 ? 1 : BfRank;
  1599. }
  1600. mUiCalibration = uiFreeDiskBytes;
  1601. }
  1602. const int InitialRank = CurRank;
  1603. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1604. int nEnoughLevel = 0;
  1605. unsigned long long uiFactor;
  1606. char displayTime[MAX_PATH] = { 0 };
  1607. time_t ftSavedTime;
  1608. CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
  1609. GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
  1610. Dbg("It's SavedTime backtrace: %s", displayTime);
  1611. do {
  1612. uiFactor = DEFAULT_AVAILALBE_DATE_COUNT; // 7天
  1613. if (CurRank == 2) uiFactor = LESS_AVAILALBE_DATE_COUNT; // 3天
  1614. else if (CurRank == 1) uiFactor = LEAST_AVAILALBE_DATE_COUNT; // 1天
  1615. const unsigned long long uiSpaceRequired = mUiRequireBytes * uiFactor;
  1616. ByteSprintf(szResult, (double)uiSpaceRequired);
  1617. Dbg("Required free disk size: %s, current rank: %d", szResult, CurRank);
  1618. unsigned long long uiMoreSpaceRealRequired(0);
  1619. unsigned long long uiAdjustment(0);
  1620. if (diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_csUploadVideoPath, uiSpaceRequired, uiAdjustment, &uiMoreSpaceRealRequired)
  1621. && uiMoreSpaceRealRequired) {
  1622. unsigned long long uiNewFreeBytes(0);
  1623. UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
  1624. BOOL bTrackBackStop = FALSE;
  1625. Dbg("the more space required: %llu.", uiMoreSpaceRealRequired);
  1626. while (!m_VideoFiles.empty() && uiNewFreeBytes < uiMoreSpaceRealRequired) {
  1627. TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
  1628. if (pCurFileInfo != NULL) {
  1629. GetTimeFormatStr(displayTime, MAX_PATH, &(pCurFileInfo->mftEditTime));
  1630. if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
  1631. Dbg("stop at %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
  1632. bTrackBackStop = TRUE;
  1633. break;
  1634. }
  1635. if (RemoveFileA(pCurFileInfo->msFileName.c_str()) != 0) {
  1636. uiNewFreeBytes += pCurFileInfo->ftSize;
  1637. uDeletedCnt++;
  1638. Dbg("Delete suc: %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
  1639. SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
  1640. }
  1641. else {
  1642. Dbg("[DelFail] File(%s) %d", pCurFileInfo->msFileName.c_str(), errno);
  1643. uFailedDeleteCnt++;
  1644. }
  1645. }
  1646. m_VideoFiles.pop();
  1647. if (pCurFileInfo != NULL) delete pCurFileInfo;
  1648. }
  1649. char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1650. char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1651. ByteSprintf(szOutput, (double)uiNewFreeBytes);
  1652. ByteSprintf(szOutput2, (double)uiMoreSpaceRealRequired);
  1653. Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
  1654. CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
  1655. if (uiNewFreeBytes >= uiMoreSpaceRealRequired) {
  1656. break;
  1657. }
  1658. else {
  1659. --CurRank;
  1660. }
  1661. #ifdef WITH_DEBUG
  1662. UINT uCount = 0;
  1663. for (const_map_cu_iter citer = VideoDailyRecord.cbegin(); citer != VideoDailyRecord.cend(); citer++) { uCount += citer->second; }
  1664. Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
  1665. #endif
  1666. }
  1667. else if (InitialRank > CurRank) {
  1668. break;
  1669. }
  1670. else {
  1671. LeaveCriticalSection(&g_csVideoMoreClear);
  1672. return;
  1673. }
  1674. } while (CurRank > 0);
  1675. if (CurRank < 3) {
  1676. unsigned long long uiTotalBytes;
  1677. unsigned long long uiFreeDiskBytes;
  1678. if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
  1679. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  1680. ByteSprintf(szResult, (double)uiTotalBytes);
  1681. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  1682. double dFreeRate = (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  1683. sprintf(szResult3, "[Disk# %s] total: %s, free: %s, rate: %.1lf%%.",
  1684. m_csUploadVideoPath.GetData(), szResult, szResult2, dFreeRate * 100);
  1685. mUiCalibration = uiFreeDiskBytes;
  1686. }
  1687. else {
  1688. strcpy(szResult3, "It's not enough disk space for recording video !");
  1689. }
  1690. }
  1691. else {
  1692. strcpy(szResult3, "Disk space is enough for recording.");
  1693. }
  1694. if (CurRank == 0) { CurRank = 4; }
  1695. if (BfRank != CurRank) {
  1696. erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
  1697. }
  1698. SetSysValAndBroadcast(CurRank, szResult3);
  1699. LeaveCriticalSection(&g_csVideoMoreClear);
  1700. return;
  1701. #else
  1702. EnterCriticalSection(&g_csVideoMoreClear);
  1703. ErrorCodeEnum erroCode = Error_Succeed;
  1704. BOOL bOK = FALSE;
  1705. CSmartPointer<IConfigInfo> spConfigRun;
  1706. ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1707. if (m_VideoFiles.empty())
  1708. {
  1709. int reseved = 0;
  1710. IsNeedToFirstClear();
  1711. int nRes = ClearVideoFiles(reseved, m_bReadyFlag ? 1 : 0);
  1712. if (nRes - reseved == 0)
  1713. {
  1714. SetSysValAndBroadcast(0, "There are no any video files in facts.");
  1715. LeaveCriticalSection(&g_csVideoMoreClear);
  1716. return;
  1717. }
  1718. }
  1719. if (mUiRequireBytes.QuadPart == 0ui64)
  1720. {//更新记录运行时,并等待下一次的自检执行。
  1721. int reseved = 0;
  1722. ClearVideoFiles(reseved);
  1723. LeaveCriticalSection(&g_csVideoMoreClear);
  1724. return;
  1725. }
  1726. ULARGE_INTEGER uiSpaceRequired;
  1727. ULARGE_INTEGER uiSpaceRealRequired;
  1728. ULARGE_INTEGER uiFactor;
  1729. int CurRank = 3;
  1730. int BfRank = 0;
  1731. if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0)
  1732. BfRank = 0;
  1733. if (BfRank > 0)
  1734. {
  1735. ULARGE_INTEGER uiTotalBytes;
  1736. ULARGE_INTEGER uiFreeDiskBytes;
  1737. if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes))
  1738. {
  1739. //对比上次,剩余的可用磁盘空间更小了。
  1740. if (mUiCalibration.QuadPart >= uiFreeDiskBytes.QuadPart)
  1741. {
  1742. CurRank = BfRank;
  1743. }
  1744. mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
  1745. }
  1746. }
  1747. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1748. int nEnoughLevel = 0;
  1749. do
  1750. {
  1751. uiFactor.QuadPart = 0;
  1752. switch (CurRank)
  1753. {
  1754. case 3:
  1755. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
  1756. break;
  1757. case 2:
  1758. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LESS_AVAILALBE_DATE_COUNT;
  1759. break;
  1760. case 1:
  1761. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LEAST_AVAILALBE_DATE_COUNT;
  1762. break;
  1763. default:
  1764. CurRank = 3;
  1765. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
  1766. }
  1767. ByteSprintf(szResult, (double)uiSpaceRequired.QuadPart);
  1768. if (bOK = diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_csUploadVideoPath,
  1769. uiSpaceRequired, uiFactor, &uiSpaceRealRequired))
  1770. {
  1771. if (uiSpaceRealRequired.QuadPart == 0)
  1772. {
  1773. break;
  1774. }
  1775. char displayTime[MAX_PATH] = { 0 };
  1776. FILETIME ftSavedTime;
  1777. //TODO: 暂时设置为至少保存两星期的录像文件,如果一天都不保留,那么 m_VideoFiles 要做即时更新 。2017-5-10
  1778. CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
  1779. GetTimeString(displayTime, MAX_PATH, &ftSavedTime);
  1780. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SavedTime backtrace: %s", displayTime);
  1781. ULARGE_INTEGER uiFreeBytes;
  1782. uiFreeBytes.QuadPart = 0;
  1783. UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
  1784. BOOL bTrackBackStop = FALSE;
  1785. while (!m_VideoFiles.empty() && uiFreeBytes.QuadPart < uiSpaceRealRequired.QuadPart)
  1786. {
  1787. TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
  1788. if (pCurFileInfo != NULL)
  1789. {
  1790. SYSTEMTIME stUTC, stLocal;
  1791. FileTimeToSystemTime(&(pCurFileInfo->mftEditTime), &stUTC);
  1792. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  1793. if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0)
  1794. {
  1795. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("yet %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
  1796. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1797. stLocal.wHour, stLocal.wMinute);
  1798. bTrackBackStop = TRUE;
  1799. break;
  1800. }
  1801. if (DeleteFile(pCurFileInfo->msFileName.c_str()) != 0)
  1802. {
  1803. ULARGE_INTEGER tmpBytes;
  1804. tmpBytes.HighPart = pCurFileInfo->mDwFileSizeHeight;
  1805. tmpBytes.LowPart = pCurFileInfo->mDwFileSizeLow;
  1806. uiFreeBytes.QuadPart += tmpBytes.QuadPart;
  1807. uDeletedCnt++;
  1808. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete suc: %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
  1809. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1810. stLocal.wHour, stLocal.wMinute);
  1811. UINT uDate = stLocal.wYear * 10000 + stLocal.wMonth * 100 + stLocal.wDay;
  1812. VideoDailyRecord[uDate]--;
  1813. }
  1814. else
  1815. {
  1816. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[DelFail] File(%s) %u", pCurFileInfo->msFileName.c_str(), GetLastError());
  1817. uFailedDeleteCnt++;
  1818. }
  1819. }
  1820. m_VideoFiles.pop();
  1821. if (pCurFileInfo != NULL) delete pCurFileInfo;
  1822. }
  1823. char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1824. char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1825. ByteSprintf(szOutput, (double)uiFreeBytes.QuadPart);
  1826. ByteSprintf(szOutput2, (double)uiSpaceRealRequired.QuadPart);
  1827. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
  1828. CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
  1829. if (uiFreeBytes.QuadPart >= uiSpaceRealRequired.QuadPart)
  1830. {
  1831. break;
  1832. }
  1833. --CurRank;
  1834. #if 1
  1835. UINT uCount = 0;
  1836. for (const_map_cu_iter citer = VideoDailyRecord.cbegin();
  1837. citer != VideoDailyRecord.cend(); citer++)
  1838. {
  1839. uCount += citer->second;
  1840. }
  1841. #endif
  1842. }
  1843. else
  1844. {
  1845. LogWarn(Severity_Middle, Error_Unexpect, 0, "IsNeedToDoClearJobEx invoked failed !");
  1846. LeaveCriticalSection(&g_csVideoMoreClear);
  1847. return;
  1848. }
  1849. } while (CurRank > 0);
  1850. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
  1851. if (CurRank < 3)
  1852. {
  1853. ULARGE_INTEGER uiTotalBytes;
  1854. ULARGE_INTEGER uiFreeDiskBytes;
  1855. if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes))
  1856. {
  1857. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  1858. ByteSprintf(szResult, (double)uiTotalBytes.QuadPart);
  1859. ByteSprintf(szResult2, (double)uiFreeDiskBytes.QuadPart);
  1860. double dFreeRate = (uiFreeDiskBytes.QuadPart * kConversion[3]) / (uiTotalBytes.QuadPart * kConversion[3]);
  1861. sprintf_s(szResult3, "[Disk# %c:\\] total: %s, free: %s, rate: %.1lf%%.",
  1862. m_csUploadVideoPath[0], szResult, szResult2, dFreeRate * 100);
  1863. mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
  1864. }
  1865. else
  1866. {
  1867. strcpy_s(szResult3, "It's not enough disk space for recording video !");
  1868. }
  1869. if (CurRank == 0)
  1870. {
  1871. CurRank = 4;
  1872. }
  1873. }
  1874. else
  1875. {
  1876. strcpy_s(szResult3, "Disk space is enough for recording.");
  1877. }
  1878. if (BfRank != CurRank)
  1879. {
  1880. erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
  1881. }
  1882. SetSysValAndBroadcast(CurRank, szResult3);
  1883. LeaveCriticalSection(&g_csVideoMoreClear);
  1884. return;
  1885. #endif // RVC_OS_LINUX
  1886. }
  1887. #ifdef RVC_OS_LINUX
  1888. BOOL ResourceWatcherFSM::RemoveDuplicateCenterSettingFiles()
  1889. {
  1890. LOG_FUNCTION();
  1891. ErrorCodeEnum erroCode = Error_Succeed;
  1892. CSmartPointer<IConfigInfo> spConfigRun;
  1893. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1894. if (erroCode != Error_Succeed) {
  1895. Dbg("OpenConfig of 'Config_Run' failed 0x%x(%d).", erroCode, erroCode);
  1896. return FALSE;
  1897. }
  1898. int nLastTaskTime(0);
  1899. spConfigRun->ReadConfigValueInt("LastClearTime", "CenterSetting", nLastTaskTime);
  1900. if (IsTodayDone(nLastTaskTime)) {
  1901. return TRUE;
  1902. }
  1903. CSimpleStringA ssFilePath(true);
  1904. erroCode = GetEntityBase()->GetFunction()->GetPath("cfg", ssFilePath);
  1905. if (erroCode != Error_Succeed || ssFilePath.IsNullOrEmpty()) {
  1906. Dbg("Get path of 'cfg' failed 0x%x(%d).", erroCode, erroCode);
  1907. return FALSE;
  1908. }
  1909. Dbg("filePath %s", (LPCTSTR)ssFilePath);
  1910. int nDelSuc = 0;
  1911. int nDelFailed = 0;
  1912. int nfileSum = ClearSpecifieFile(DFT_CenterSetting, ssFilePath, nDelSuc, nDelFailed);
  1913. Dbg("#CenterSetting#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  1914. spConfigRun->WriteConfigValue("LastClearTime", "CenterSetting", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  1915. return TRUE;
  1916. }
  1917. int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt)
  1918. {
  1919. LOG_FUNCTION();
  1920. int nRes;
  1921. int nfileCnt = 0;
  1922. int fileLength = strlen(dirName);
  1923. char searchFilePath[MAX_PATH] = { 0 };
  1924. char tempFilePath[MAX_PATH] = { 0 };
  1925. char displayTime[MAX_PATH] = { 0 };
  1926. struct stat st;
  1927. if (stat(dirName, &st) < 0) {
  1928. Dbg("stat for %s failed: %d %s", dirName, errno, strerror(errno));
  1929. return -2;
  1930. }
  1931. if (!S_ISDIR(st.st_mode)) {
  1932. Dbg(" %s is not directory", dirName);
  1933. return -2;
  1934. }
  1935. DIR* d = opendir(dirName);
  1936. if (!d) {
  1937. return -3;
  1938. }
  1939. struct dirent* dp = NULL;
  1940. while ((dp = readdir(d)) != NULL) {
  1941. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1942. continue;
  1943. }
  1944. strcpy(tempFilePath, dirName);
  1945. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1946. Dbg("filePath is too long for current.");
  1947. continue;
  1948. }
  1949. strcat(tempFilePath, "/");
  1950. strcat(tempFilePath, dp->d_name);
  1951. Dbg("fileName: %s", dp->d_name);
  1952. struct stat stFile;
  1953. stat(tempFilePath, &stFile);
  1954. const bool isdir = !!(S_ISDIR(stFile.st_mode));
  1955. if (isdir && fileType != DFT_CenterSetting) {
  1956. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  1957. if (nRes >= 0) nfileCnt += nRes;
  1958. }
  1959. else if (!isdir) {
  1960. if (fileType != DFT_Ad0 || (CompareVideoFileTime(&mftAd0RemoveTime, &stFile.st_mtime) >= 0)) {
  1961. nRes = RemoveSpecifiedFile(fileType, tempFilePath, dp->d_name);
  1962. }
  1963. else {
  1964. nRes = 0;
  1965. }
  1966. if (nRes == -1) deleteFailedCnt++;
  1967. else if (nRes == 1) deletedFileCnt++;
  1968. nfileCnt++;
  1969. }
  1970. }
  1971. closedir(d);
  1972. return nfileCnt;
  1973. }
  1974. int ResourceWatcherFSM::RemoveSpecifiedFile(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
  1975. {
  1976. CSimpleStringA ssFileName = szFileName;
  1977. if (ssFileName.IsNullOrEmpty()) return FALSE;
  1978. if ((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
  1979. || fileType == DFT_Ad0
  1980. ) {
  1981. if (RemoveFileA(szFilePath)) {
  1982. Dbg("%s delete suc.", szFileName);
  1983. return 1;
  1984. }
  1985. Dbg("%s delete failed %d.", szFileName, GetLastError());
  1986. return -1;
  1987. }
  1988. return 0;
  1989. }
  1990. #else
  1991. BOOL ResourceWatcherFSM::ExecuteClearTask()
  1992. {
  1993. ErrorCodeEnum erroCode = Error_Succeed;
  1994. CSmartPointer<IConfigInfo> spConfigRun;
  1995. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1996. CSimpleStringA ssCurTarget = "CenterSetting";
  1997. CSimpleStringA ssLasTarget = "";
  1998. int nLastTaskTime(0);
  1999. int nFailedNum(0);
  2000. spConfigRun->ReadConfigValue("ClearTask", "Target", ssLasTarget);
  2001. spConfigRun->ReadConfigValueInt("ClearTask", "LastTime", nLastTaskTime);
  2002. spConfigRun->ReadConfigValueInt("ClearTask", "FailedNum", nFailedNum);
  2003. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  2004. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Last clear time: %04d-%02d-%02d %02d:%02d:%02d",
  2005. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  2006. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  2007. SYSTEMTIME stNow = {};
  2008. GetLocalTime(&stNow);
  2009. if (nLastTaskTime > 0
  2010. /*&& ssCurTarget.Compare(ssLasTarget, true) == 0*/
  2011. && stTaskTime.wYear == stNow.wYear
  2012. && stTaskTime.wMonth == stNow.wMonth && stTaskTime.wDay == stNow.wDay
  2013. && nFailedNum == 0)
  2014. {
  2015. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ClearTask has been executed today, last clear time: %s",
  2016. (const char*)CSmallDateTime(nLastTaskTime).ToTimeString());
  2017. return TRUE;
  2018. }
  2019. CSimpleStringA ssFilePath = "";
  2020. erroCode = GetEntityBase()->GetFunction()->GetPath("cfg", ssFilePath);
  2021. if (erroCode != Error_Succeed || ssFilePath.IsNullOrEmpty())
  2022. {
  2023. return FALSE;
  2024. }
  2025. ssFilePath = ssFilePath + "\\*";
  2026. int nDelSuc = 0;
  2027. int nDelFailed = 0;
  2028. int nfileSum = ClearSpecifieFile(DFT_CenterSetting, (LPCTSTR)ssFilePath, nDelSuc, nDelFailed);
  2029. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  2030. spConfigRun->WriteConfigValue("ClearTask", "Target", (LPCTSTR)ssCurTarget);
  2031. spConfigRun->WriteConfigValue("ClearTask", "LastTime",
  2032. (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  2033. spConfigRun->WriteConfigValueInt("ClearTask", "TargetNum", nDelSuc + nDelFailed);
  2034. spConfigRun->WriteConfigValueInt("ClearTask", "FailedNum", nDelFailed);
  2035. return TRUE;
  2036. }
  2037. int ResourceWatcherFSM::ClearSpecifieFile(
  2038. DealFileType fileType,
  2039. LPCTSTR dirName,
  2040. int& deletedFileCnt,
  2041. int& deleteFailedCnt)
  2042. {
  2043. int nRes;
  2044. int nfileCnt = 0;
  2045. int fileLength = strlen(dirName);
  2046. char searchFilePath[MAX_PATH] = { 0 };
  2047. char tempFilePath[MAX_PATH] = { 0 };
  2048. char displayTime[MAX_PATH] = { 0 };
  2049. WIN32_FIND_DATA fndFileData;
  2050. HANDLE hFind;
  2051. hFind = FindFirstFile(dirName, &fndFileData);
  2052. if (hFind == INVALID_HANDLE_VALUE)
  2053. {
  2054. return -2;
  2055. }
  2056. if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  2057. {
  2058. if (fndFileData.cFileName[0] != '.')
  2059. {
  2060. memset(tempFilePath, 0, sizeof(tempFilePath));
  2061. strcpy_s(tempFilePath, dirName);
  2062. tempFilePath[fileLength - 1] = '\0';
  2063. if (strlen(tempFilePath) + strlen(fndFileData.cFileName) + 3 >= MAX_PATH)
  2064. {
  2065. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  2066. }
  2067. else
  2068. {
  2069. strcat_s(tempFilePath, fndFileData.cFileName);
  2070. strcat_s(tempFilePath, "\\*");
  2071. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  2072. if (nRes >= 0) nfileCnt += nRes;
  2073. }
  2074. }
  2075. }
  2076. else
  2077. {
  2078. memset((void*)searchFilePath, 0, MAX_PATH);
  2079. strcpy_s(searchFilePath, dirName);
  2080. searchFilePath[fileLength - 1] = '\0';
  2081. strcat_s(searchFilePath, fndFileData.cFileName);
  2082. if (fileType == DFT_Ad0) {
  2083. if (CompareFileTime(&m_ftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
  2084. nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
  2085. }
  2086. else {
  2087. nRes = 0;
  2088. }
  2089. }
  2090. else {
  2091. nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
  2092. }
  2093. if (nRes == -1) deleteFailedCnt++;
  2094. else if (nRes == 1) deletedFileCnt++;
  2095. nfileCnt++;
  2096. }
  2097. while (FindNextFile(hFind, &fndFileData))
  2098. {
  2099. if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  2100. {
  2101. if (fndFileData.cFileName[0] != '.')
  2102. {
  2103. memset(tempFilePath, 0, sizeof(tempFilePath));
  2104. strcpy_s(tempFilePath, dirName);
  2105. tempFilePath[fileLength - 1] = '\0';
  2106. strcat_s(tempFilePath, fndFileData.cFileName);
  2107. strcat_s(tempFilePath, "\\*");
  2108. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  2109. if (nRes >= 0) nfileCnt += nRes;
  2110. }
  2111. }
  2112. else
  2113. {
  2114. memset((void*)searchFilePath, 0, MAX_PATH);
  2115. strcpy_s(searchFilePath, dirName);
  2116. searchFilePath[fileLength - 1] = '\0';
  2117. strcat_s(searchFilePath, fndFileData.cFileName);
  2118. if (fileType == DFT_Ad0) {
  2119. if (CompareFileTime(&m_ftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
  2120. nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
  2121. }
  2122. else {
  2123. nRes = 0;
  2124. }
  2125. }
  2126. else {
  2127. nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
  2128. }
  2129. if (nRes == -1) deleteFailedCnt++;
  2130. else if (nRes == 1) deletedFileCnt++;
  2131. nfileCnt++;
  2132. }
  2133. }
  2134. FindClose(hFind);
  2135. return nfileCnt;
  2136. }
  2137. int ResourceWatcherFSM::DoSomethingWith(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
  2138. {
  2139. CSimpleStringA ssFileName = szFileName;
  2140. if (ssFileName.GetLength() <= 0)
  2141. return FALSE;
  2142. if ((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
  2143. ||
  2144. fileType == DFT_Ad0
  2145. ) {
  2146. if (DeleteFile(szFilePath) != 0)
  2147. {
  2148. return 1;
  2149. }
  2150. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s delete failed %d.", szFileName, GetLastError());
  2151. return -1;
  2152. }
  2153. return 0;
  2154. }
  2155. #endif // RVC_OS_LINUX
  2156. bool ResourceWatcherFSM::IsNeedToFirstClear()
  2157. {
  2158. #ifdef RVC_OS_LINUX
  2159. int nLastTaskTime(0);
  2160. CSmartPointer<IConfigInfo> spRunConfig;
  2161. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  2162. spRunConfig->ReadConfigValueInt("LastClearTime", "Video", nLastTaskTime);
  2163. return !IsTodayDone(nLastTaskTime);
  2164. #else
  2165. m_bReadyFlag = true;
  2166. CSimpleStringA csLstExecTime;
  2167. CSmartPointer<IConfigInfo> spRunConfig;
  2168. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  2169. spRunConfig->ReadConfigValue("Video", "LastTime", csLstExecTime);
  2170. if (csLstExecTime.GetLength() > 1)
  2171. {
  2172. int nYear = 0, nMonth = 0, nDay = 0;
  2173. spRunConfig->ReadConfigValueInt("Video", "Year", nYear);
  2174. spRunConfig->ReadConfigValueInt("Video", "Month", nMonth);
  2175. spRunConfig->ReadConfigValueInt("Video", "Day", nDay);
  2176. if (nYear != 0 && nMonth != 0 && nDay != 0)
  2177. {
  2178. SYSTEMTIME stUTC, stLocal;
  2179. GetSystemTime(&stUTC);
  2180. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  2181. if (nYear == stLocal.wYear && nMonth == stLocal.wMonth && nDay == stLocal.wDay)
  2182. {
  2183. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Video Clear job has been done today in %s", (LPCTSTR)csLstExecTime);
  2184. m_bReadyFlag = false;
  2185. }
  2186. }
  2187. }
  2188. return m_bReadyFlag;
  2189. #endif // RVC_OS_LINUX
  2190. }
  2191. int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt)
  2192. {
  2193. #ifdef RVC_OS_LINUX
  2194. int fileCnt = 0;
  2195. int fileLength = strlen(lpszPath);
  2196. char* searchFilePath = new char[MAX_PATH];
  2197. char* tempFilePath = new char[MAX_PATH];
  2198. if (searchFilePath == NULL || tempFilePath == NULL) {
  2199. if (searchFilePath) delete[] searchFilePath;
  2200. if (tempFilePath) delete[] tempFilePath;
  2201. return fileCnt;
  2202. }
  2203. ZeroMemory(searchFilePath, MAX_PATH);
  2204. ZeroMemory(tempFilePath, MAX_PATH);
  2205. struct stat st;
  2206. if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
  2207. if (searchFilePath) delete[] searchFilePath;
  2208. if (tempFilePath) delete[] tempFilePath;
  2209. Dbg("stat failed or is not dir.");
  2210. return fileCnt;
  2211. }
  2212. DIR* d = opendir(lpszPath);
  2213. if (!d) {
  2214. if (searchFilePath) delete[] searchFilePath;
  2215. if (tempFilePath) delete[] tempFilePath;
  2216. Dbg("opendir failed: %d", errno);
  2217. return fileCnt;
  2218. }
  2219. struct dirent* dp = NULL;
  2220. while ((dp = readdir(d)) != NULL) {
  2221. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  2222. continue;
  2223. }
  2224. strcpy(tempFilePath, lpszPath);
  2225. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  2226. Dbg("filePath is too long for current.");
  2227. continue;
  2228. }
  2229. strcat(tempFilePath, "/");
  2230. strcat(tempFilePath, dp->d_name);
  2231. stat(tempFilePath, &st);
  2232. bool isdir = !!(S_ISDIR(st.st_mode));
  2233. if (isdir) {
  2234. int tDelSucCnt = 0, tDelFailedCnt = 0;
  2235. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
  2236. if (tDelFailedCnt == 0 && rmdir(tempFilePath) != 0) {
  2237. Dbg("rmdir(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno);
  2238. nDelFailedCnt++;
  2239. }
  2240. nDelFailedCnt += tDelFailedCnt;
  2241. nDelSucCnt += tDelSucCnt;
  2242. }
  2243. else {
  2244. if (RemoveFileA(tempFilePath)) {
  2245. nDelSucCnt++;
  2246. Dbg("Delete [%s] suc.", dp->d_name);
  2247. }
  2248. else {
  2249. nDelFailedCnt++;
  2250. Dbg("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno);
  2251. }
  2252. fileCnt++;
  2253. }
  2254. }
  2255. closedir(d);
  2256. if (searchFilePath) delete[] searchFilePath;
  2257. if (tempFilePath) delete[] tempFilePath;
  2258. searchFilePath = NULL;
  2259. tempFilePath = NULL;
  2260. return fileCnt;
  2261. #else
  2262. int fileCnt = 0;
  2263. int fileLength = strlen(lpszPath);
  2264. WIN32_FIND_DATA wfd;
  2265. HANDLE hFind;
  2266. hFind = FindFirstFile(lpszPath, &wfd);
  2267. if (hFind == INVALID_HANDLE_VALUE)
  2268. {
  2269. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("FindFirstFile failed GLE = %u.", GetLastError());
  2270. return 0;
  2271. }
  2272. char* searchFilePath = new char[MAX_PATH];
  2273. char* tempFilePath = new char[MAX_PATH];
  2274. if (searchFilePath == NULL || tempFilePath == NULL)
  2275. {
  2276. if (searchFilePath) delete[] searchFilePath;
  2277. if (tempFilePath) delete[] tempFilePath;
  2278. searchFilePath = NULL;
  2279. tempFilePath = NULL;
  2280. return fileCnt;
  2281. }
  2282. ZeroMemory(searchFilePath, MAX_PATH);
  2283. ZeroMemory(tempFilePath, MAX_PATH);
  2284. do
  2285. {
  2286. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  2287. {
  2288. if (wfd.cFileName[0] != '.')
  2289. {
  2290. strcpy_s(tempFilePath, MAX_PATH, lpszPath);
  2291. tempFilePath[fileLength - 1] = '\0';
  2292. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH)
  2293. {
  2294. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  2295. }
  2296. else
  2297. {
  2298. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
  2299. CSimpleStringA tmpPath = tempFilePath;
  2300. strcat_s(tempFilePath, MAX_PATH, "\\*");
  2301. int tDelSucCnt = 0, tDelFailedCnt = 0;
  2302. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
  2303. if (tDelFailedCnt == 0 && !RemoveDirectoryA(tmpPath))
  2304. {
  2305. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RemoveDirectoryA(%s) failed, GLE = %u.", (LPCTSTR)tmpPath, GetLastError());
  2306. nDelFailedCnt++;
  2307. }
  2308. nDelFailedCnt += tDelFailedCnt;
  2309. nDelSucCnt += tDelSucCnt;
  2310. }
  2311. }
  2312. }
  2313. else
  2314. {
  2315. strcpy_s(searchFilePath, MAX_PATH, lpszPath);
  2316. searchFilePath[fileLength - 1] = '\0';
  2317. strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
  2318. if (DeleteFile(searchFilePath) != 0)
  2319. {
  2320. nDelSucCnt++;
  2321. }
  2322. else
  2323. {
  2324. nDelFailedCnt++;
  2325. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Delete [%s] failed, GLE = %u.", wfd.cFileName, GetLastError());
  2326. }
  2327. fileCnt++;
  2328. }
  2329. } while (FindNextFileA(hFind, &wfd));
  2330. FindClose(hFind);
  2331. if (searchFilePath) delete[] searchFilePath;
  2332. if (tempFilePath) delete[] tempFilePath;
  2333. searchFilePath = NULL;
  2334. tempFilePath = NULL;
  2335. return fileCnt;
  2336. #endif // RVC_OS_LINUX
  2337. }
  2338. BOOL ResourceWatcherFSM::DeleteVersionPackage()
  2339. {
  2340. BOOL bRet = FALSE;
  2341. ErrorCodeEnum erroCode = Error_Succeed;
  2342. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  2343. CSmartPointer<IConfigInfo> spConfigRun;
  2344. CSmartPointer<IConfigInfo> spConfig;
  2345. CSystemStaticInfo info;
  2346. if (pFunc->GetSystemStaticInfo(info) != Error_Succeed) {
  2347. LogError(Severity_Middle, erroCode, 0, "Get system static info error");
  2348. return FALSE;
  2349. }
  2350. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Current version: %s", (LPCTSTR)info.InstallVersion.ToString());
  2351. //判断是否需要被清理
  2352. int nLastTaskTime = 0;
  2353. int nLstFlag = 0;
  2354. int nDelCount = 0;
  2355. UINT64 utVersion = 0;
  2356. int verSaved = DEFAULT_VERSION_SAVED_COUNT;
  2357. int tmpSaved = 0;
  2358. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  2359. spConfig->ReadConfigValueInt("VersionSaved", "default", tmpSaved);
  2360. if (tmpSaved > DEFAULT_VERSION_SAVED_COUNT) {
  2361. verSaved = tmpSaved;
  2362. }
  2363. pFunc->OpenConfig(Config_Run, spConfigRun);
  2364. spConfigRun->ReadConfigValueHexInt("VersionClear", "OptVer", utVersion);
  2365. spConfigRun->ReadConfigValueInt("VersionClear", "DelVerCnt", nDelCount);
  2366. spConfigRun->ReadConfigValueInt("VersionClear", "LastCondi", nLstFlag);
  2367. spConfigRun->ReadConfigValueInt("VersionClear", "LastTime", nLastTaskTime);
  2368. CVersion optVer(utVersion);
  2369. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  2370. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
  2371. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  2372. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  2373. (LPCTSTR)optVer.ToString(), nLstFlag);
  2374. //判断是否需要被清理
  2375. if (optVer.IsValid() && optVer == info.InstallVersion && !nLstFlag) {
  2376. Dbg("VersionPackage cleaning has been done before.");
  2377. return TRUE;
  2378. }
  2379. CSimpleStringA strRunInfo, strStartTime;
  2380. if (m_pEntity->GetFunction()->GetPath("RunInfo", strRunInfo) == Error_Succeed) {
  2381. strStartTime = strRunInfo + SPLIT_SLASH_STR + "runcfg" + SPLIT_SLASH_STR + "starttime.dat";
  2382. if (!ExistsFileA(strStartTime.GetData())) {
  2383. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade prpcess done, try to delete version files.");//完成升级过程,通过
  2384. } else {
  2385. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,should not delete version files.");
  2386. return FALSE;//升级未完成,不进行删除
  2387. }
  2388. } else {
  2389. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path is error, should not delete version files.");
  2390. return FALSE;//失败,继续等待
  2391. }
  2392. //获取当前目录下的文件夹名称, 将符合命名规则的终端版本名称push_back
  2393. CSimpleStringA csPath;
  2394. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  2395. if (Error_Succeed == Error) {
  2396. if (csPath.IsNullOrEmpty()) {
  2397. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get currVer path is null");
  2398. return FALSE;
  2399. } else {
  2400. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CUR VERSION PATH = %s.", csPath.GetData());
  2401. }
  2402. } else {
  2403. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get Ver path error");
  2404. return FALSE;
  2405. }
  2406. vector<CVersion> intallInfoVects;
  2407. vector<string> files;
  2408. CSimpleStringA upPath;
  2409. ErrorCodeEnum upError = pFunc->GetPath("Upgraded", upPath);
  2410. if (Error_Succeed != upError) {
  2411. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get Upgraded path error");
  2412. return FALSE;
  2413. }
  2414. #ifdef RVC_OS_LINUX
  2415. DIR* dp;
  2416. struct dirent* dirp;
  2417. if ((dp = opendir(csPath.GetData())) != NULL) {
  2418. while ((dirp = readdir(dp)) != NULL) {
  2419. //files.push_back(string(dirp->d_name));
  2420. CInstallInfo verInfo = {};
  2421. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  2422. int n = sscanf(dirp->d_name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  2423. if (n != 4)
  2424. {
  2425. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
  2426. continue;
  2427. }
  2428. else {
  2429. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  2430. if (verName.IsValid() && verName < info.InstallVersion) //对高于自身版本的文件不予删除
  2431. {
  2432. intallInfoVects.push_back(verName);
  2433. }
  2434. else {
  2435. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
  2436. }
  2437. }
  2438. }
  2439. closedir(dp);
  2440. }
  2441. //删除rvc/Upgraded目录下的文件
  2442. DIR* updp;
  2443. struct dirent* updirp;
  2444. if ((updp = opendir(upPath.GetData())) != NULL) {
  2445. while ((updirp = readdir(updp)) != NULL) {
  2446. char szPath[MAX_VERSION_PATH] = { 0 };
  2447. strcat(szPath, upPath.GetData());
  2448. CSimpleStringA tmpDirPath = szPath;
  2449. strcat(szPath, SPLIT_SLASH_STR);
  2450. strcat(szPath, updirp->d_name);
  2451. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("operating Upgrade path: [%s][%s]", (LPCTSTR)tmpDirPath, szPath);
  2452. RemoveFileA(szPath);
  2453. }
  2454. closedir(updp);
  2455. }
  2456. #else
  2457. long hFile = 0;
  2458. struct _finddata_t fileinfo;//文件信息读取结构
  2459. string p;
  2460. if ((hFile = _findfirst(p.assign(string(csPath.GetData())).append("\\*").c_str(), &fileinfo)) != -1) {
  2461. do {
  2462. CInstallInfo verInfo = {};
  2463. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  2464. int n = sscanf(fileinfo.name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  2465. if (n != 4)
  2466. {
  2467. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
  2468. continue;
  2469. }
  2470. else {
  2471. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  2472. if (verName.IsValid() && verName < info.InstallVersion)
  2473. {
  2474. intallInfoVects.push_back(verName);
  2475. }
  2476. else {
  2477. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
  2478. }
  2479. }
  2480. } while (_findnext(hFile, &fileinfo) == 0);
  2481. _findclose(hFile);
  2482. }
  2483. //删除rvc/Upgraded目录下的文件
  2484. struct _finddata_t upfileinfo;
  2485. long upFile = 0;
  2486. if ((upFile = _findfirst(p.assign(string(upPath.GetData())).append("\\*").c_str(), &upfileinfo)) != -1) {
  2487. do {
  2488. char szPath[MAX_VERSION_PATH] = { 0 };
  2489. strcat_s(szPath, upPath.GetData());
  2490. CSimpleStringA tmpDirPath = szPath;
  2491. strcat_s(szPath, SPLIT_SLASH_STR);
  2492. strcat_s(szPath, upfileinfo.name);
  2493. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("operating Upgrade path: [%s][%s]", (LPCTSTR)tmpDirPath, szPath);
  2494. RemoveFileA(szPath);
  2495. } while (_findnext(upFile, &upfileinfo) == 0);
  2496. _findclose(upFile);
  2497. }
  2498. #endif // RVC_OS_LINUX
  2499. int nPackCount = intallInfoVects.size();
  2500. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Install Package's count: %d", nPackCount);
  2501. bool bFailFlag = false;
  2502. int nDelVersionCnt = 0;
  2503. std::string tInfo("");
  2504. if (nPackCount != 0) {
  2505. int nSavedCount = 0;
  2506. sort(intallInfoVects.begin(), intallInfoVects.end());
  2507. vector<CVersion>::reverse_iterator riter = intallInfoVects.rbegin();
  2508. while (riter != intallInfoVects.rend()) {
  2509. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("InstallPackage Info: %s", (LPCTSTR)(*riter).ToString());
  2510. if (++nSavedCount <= verSaved) {
  2511. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Save above version");
  2512. riter++;
  2513. continue;
  2514. }
  2515. if (!DeleteSpecificeVersionDir(*riter)) bFailFlag = true;
  2516. else {
  2517. nDelVersionCnt++;
  2518. tInfo = tInfo + "|" + std::string((*riter).ToString().GetData());
  2519. }
  2520. riter++;
  2521. }
  2522. }
  2523. nLstFlag = bFailFlag ? 1 : 0;
  2524. spConfigRun->WriteConfigValueHexInt("VersionClear", "OptVer", info.InstallVersion.GetVersion64());
  2525. spConfigRun->WriteConfigValueInt("VersionClear", "DelVerCnt", nDelCount + nDelVersionCnt);
  2526. spConfigRun->WriteConfigValueInt("VersionClear", "LastCondi", nLstFlag);
  2527. spConfigRun->WriteConfigValue("VersionClear", "LastTime",
  2528. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  2529. if (nDelVersionCnt > 0) {
  2530. std::string warn = "Delete Vesion file count : " + std::to_string((long long)nDelVersionCnt) + ". ----- " + tInfo + ".";
  2531. LogWarn(Severity_Low, Error_Debug, LOG_WARN_VER_DELETE, CSimpleStringA::Format("%s", warn.c_str()));
  2532. }
  2533. return TRUE;
  2534. }
  2535. BOOL ResourceWatcherFSM::DeleteSpecificeVersionDir(CVersion version)
  2536. {
  2537. #ifdef RVC_OS_LINUX
  2538. ErrorCodeEnum erroCode = Error_Unexpect;
  2539. CSimpleStringA strPath;
  2540. if (GetEntityBase()->GetFunction()->GetPath("RootVer", strPath) != Error_Succeed)
  2541. return FALSE;
  2542. strPath = strPath + SPLIT_SLASH_STR + version.ToString();
  2543. if (!ExistsDirA(strPath)) {
  2544. Dbg("Directory(%s) Not Existed, Maybe delete before !!", strPath.GetData());
  2545. return TRUE;
  2546. }
  2547. CSimpleStringA tmpDirPath = strPath;
  2548. Dbg("operating version path: [%s][%s]", (LPCTSTR)tmpDirPath, (LPCTSTR)strPath);
  2549. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  2550. nFileCount = ProcessFileDelete((LPCTSTR)tmpDirPath, nDelSuc, nDelFail);
  2551. Dbg("Process result(%s): count(%d), suc(%d), failed(%d).", tmpDirPath.GetData(), nFileCount, nDelSuc, nDelFail);
  2552. if (nDelFail != 0 || rmdir(tmpDirPath) != 0) {
  2553. Dbg("Unexpect condition happen: (%d)", nDelFail);
  2554. return FALSE;
  2555. }
  2556. return TRUE;
  2557. #else
  2558. ErrorCodeEnum erroCode = Error_Unexpect;
  2559. char szPath[MAX_VERSION_PATH] = { 0 };
  2560. ZeroMemory(szPath, MAX_VERSION_PATH);
  2561. DWORD dwLen = GetModuleFileNameA(NULL, szPath, MAX_VERSION_PATH);
  2562. if (dwLen != 0)
  2563. {
  2564. char* pch = strstr(szPath, "\\bin");
  2565. if (pch != NULL)
  2566. {
  2567. pch[0] = '\0';
  2568. CSimpleStringA strPath = szPath;
  2569. pch = strrchr(szPath, '\\');
  2570. if (pch != NULL)
  2571. {
  2572. pch[1] = '\0';
  2573. strcat_s(szPath, (LPCTSTR)version.ToString());
  2574. if (!ExistsDirA(szPath))
  2575. {
  2576. return TRUE;
  2577. }
  2578. CSimpleStringA tmpDirPath = szPath;
  2579. strcat_s(szPath, "\\*");
  2580. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  2581. nFileCount = ProcessFileDelete(szPath, nDelSuc, nDelFail);
  2582. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Process result(%s): count(%d), suc(%d), failed(%d).", szPath, nFileCount, nDelSuc, nDelFail);
  2583. if (nDelFail != 0 || !RemoveDirectoryA(tmpDirPath))
  2584. {
  2585. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unexpect condition happen: (%d)(%u).", nDelFail, GetLastError());
  2586. return FALSE;
  2587. }
  2588. erroCode = Error_Succeed;
  2589. }
  2590. }
  2591. }
  2592. else
  2593. {
  2594. LogWarn(Severity_Middle, Error_Unexpect, 0, "GetModuleFileNameA failed !");
  2595. }
  2596. return (erroCode == Error_Succeed);
  2597. #endif // RVC_OS_LINUX
  2598. }
  2599. #ifdef RVC_OS_LINUX
  2600. int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, unsigned long long* puliSpaceBytes)
  2601. {
  2602. int fileCnt = 0;
  2603. int fileLength = strlen(lpszPath);
  2604. char* searchFilePath = new char[MAX_PATH];
  2605. char* tempFilePath = new char[MAX_PATH];
  2606. if (searchFilePath == NULL || tempFilePath == NULL) {
  2607. if (searchFilePath) delete[] searchFilePath;
  2608. if (tempFilePath) delete[] tempFilePath;
  2609. return fileCnt;
  2610. }
  2611. ZeroMemory(searchFilePath, MAX_PATH);
  2612. ZeroMemory(tempFilePath, MAX_PATH);
  2613. struct stat st;
  2614. if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
  2615. if (searchFilePath) delete[] searchFilePath;
  2616. if (tempFilePath) delete[] tempFilePath;
  2617. return fileCnt;
  2618. }
  2619. DIR* d = opendir(lpszPath);
  2620. if (!d) {
  2621. if (searchFilePath) delete[] searchFilePath;
  2622. if (tempFilePath) delete[] tempFilePath;
  2623. return fileCnt;
  2624. }
  2625. struct dirent* dp = NULL;
  2626. while ((dp = readdir(d)) != NULL) {
  2627. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  2628. continue;
  2629. }
  2630. strcpy(tempFilePath, lpszPath);
  2631. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  2632. Dbg("filePath is too long for current.");
  2633. continue;
  2634. }
  2635. strcat(tempFilePath, "/");
  2636. strcat(tempFilePath, dp->d_name);
  2637. stat(tempFilePath, &st);
  2638. const bool isdir = !!(S_ISDIR(st.st_mode));
  2639. if (isdir) {
  2640. fileCnt += CalculateAllVideoSize((LPCTSTR)tempFilePath, puliSpaceBytes);
  2641. }
  2642. else {
  2643. *puliSpaceBytes += st.st_size;
  2644. SyncUpdateVideoCreateDaily(&st.st_mtime, 1);
  2645. fileCnt++;
  2646. }
  2647. }
  2648. closedir(d);
  2649. if (searchFilePath) delete[] searchFilePath;
  2650. if (tempFilePath) delete[] tempFilePath;
  2651. return fileCnt;
  2652. }
  2653. #endif // RVC_OS_LINUX
  2654. void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType,
  2655. CSmartPointer<ITransactionContext> pTransactionContext)
  2656. {
  2657. #ifdef RVC_OS_LINUX
  2658. static uint32_t times = 0;
  2659. pTransactionContext->SendAnswer(Error_Succeed);
  2660. times++;
  2661. if (m_bVideoClearReady && times > 60 * 2) { //2 hour per times
  2662. times = 0;
  2663. PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
  2664. }
  2665. #else
  2666. pTransactionContext->SendAnswer(Error_Succeed);
  2667. if (m_bVideoClearReady)
  2668. {
  2669. PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
  2670. }
  2671. #endif // RVC_OS_LINUX
  2672. }
  2673. #ifndef RVC_OS_LINUX
  2674. void ResourceWatcherFSM::ToCheckNetProbe()
  2675. {
  2676. if (!m_fProbeDone) {
  2677. m_fProbeDone = true;
  2678. GetEntityBase()->GetFunction()->PostThreadPoolTask(new NetProbeTask(this));
  2679. }
  2680. }
  2681. #endif // !RVC_OS_LINUX
  2682. void ResourceWatcherFSM::SetSysValAndBroadcast(DWORD dwVal, LPCTSTR lpszMessage)
  2683. {
  2684. static DWORD dwOldVal = (DWORD)-1;
  2685. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  2686. CSimpleStringA csVPStatus = VIDEO_SPACE_UNKNOWN;
  2687. CSimpleStringA csNewVPSatus = VIDEO_SPACE_UNKNOWN;
  2688. spFunction->GetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csVPStatus);
  2689. if (dwVal == 4)
  2690. {
  2691. csNewVPSatus = VIDEO_SPACE_INSUFF_FATAL;
  2692. LogWarn(Severity_High, Error_TooSmallBuffer, LOG_ERR_RES_VIDEO_INSUFFICIENT, lpszMessage);
  2693. }
  2694. else if (dwVal == 2)
  2695. {
  2696. csNewVPSatus = VIDEO_SPACE_INSUFF_LITTLE;
  2697. if (dwVal != dwOldVal)
  2698. LogWarn(Severity_Middle, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
  2699. }
  2700. else if (dwVal == 1)
  2701. {
  2702. csNewVPSatus = VIDEO_SPACE_INSUFF_LESS;
  2703. if (dwVal != dwOldVal)
  2704. LogWarn(Severity_Low, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
  2705. }
  2706. else if (dwVal == 3)
  2707. {
  2708. csNewVPSatus = VIDEO_SPACE_SUFFICIENT;
  2709. if (dwVal != dwOldVal)
  2710. LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
  2711. }
  2712. else if (dwVal == 0)
  2713. {
  2714. if (dwVal != dwOldVal)
  2715. LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
  2716. }
  2717. if (csNewVPSatus != csVPStatus)
  2718. {
  2719. ErrorCodeEnum eRet = spFunction->SetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csNewVPSatus);
  2720. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetSysVar(%s) from '%s' to '%s' returned %d",
  2721. SYSVAR_DISKSTATEUS_FOR_VIDEO
  2722. , (LPCTSTR)csVPStatus
  2723. , (LPCTSTR)csNewVPSatus
  2724. , eRet);
  2725. }
  2726. dwOldVal = dwVal;
  2727. }
  2728. BOOL ResourceWatcherFSM::InitialFileEntity(LPCTSTR lpszPath, DWORD& dwFileCnt, const DWORD dwFilterAttributes)
  2729. {
  2730. LOG_FUNCTION();
  2731. if (lpszPath == NULL)
  2732. {
  2733. SetLastError(ERROR_INVALID_PARAMETER);
  2734. LogWarn(Severity_Middle, Error_Param, ERROR_INVALID_PARAMETER, "Null file path !");
  2735. return FALSE;
  2736. }
  2737. #ifdef _MSC_VER
  2738. HANDLE hFile = CreateFileA(
  2739. lpszPath,
  2740. GENERIC_READ,
  2741. FILE_SHARE_READ,
  2742. NULL,
  2743. OPEN_EXISTING,
  2744. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
  2745. NULL);
  2746. if (hFile == INVALID_HANDLE_VALUE)
  2747. {
  2748. return FALSE;
  2749. }
  2750. #endif // _MSC_VER
  2751. m_FileEntry.SubFiles.Clear();
  2752. m_FileEntry.FileNamesBuffer.Clear();
  2753. m_FileEntry.Current.Clear();
  2754. DWORD dwLocate;
  2755. Append(m_FileEntry.FileNamesBuffer, (PBYTE)lpszPath, strlen(lpszPath), dwLocate);
  2756. m_FileEntry.Current.mNameOffset = dwLocate;
  2757. m_FileEntry.Current.mNameLength = strlen(lpszPath);
  2758. #ifdef _MSC_VER
  2759. GetFileTime(hFile, (LPFILETIME)&m_FileEntry.Current.mftCreate,
  2760. (LPFILETIME)&m_FileEntry.Current.mftAccess, (LPFILETIME)&m_FileEntry.Current.mftModified);
  2761. CloseHandle(hFile);
  2762. hFile = NULL;
  2763. m_FileEntry.Current.mAttributes = GetFileAttributesA(lpszPath);
  2764. m_FileEntry.Current.mFileSize = 0;
  2765. DWORD dwDir = 0, dwFile = 0;
  2766. GetSubFileInfors(&m_FileEntry, dwDir, dwFile, dwFilterAttributes);
  2767. DisplayFileEntities(&m_FileEntry);
  2768. dwFileCnt = dwDir + dwFile;
  2769. #else
  2770. struct stat st;
  2771. if (stat(lpszPath, &st) < 0) {
  2772. Dbg("stat %s failed.", lpszPath);
  2773. return FALSE;
  2774. }
  2775. //GetFileTime
  2776. m_FileEntry.Current.mftCreate = st.st_ctime;
  2777. m_FileEntry.Current.mftAccess = st.st_atime;
  2778. m_FileEntry.Current.mftModified = st.st_mtime;
  2779. m_FileEntry.Current.mAttributes = 0;
  2780. //GetFileAttributesA
  2781. if (S_ISDIR(st.st_mode)) {
  2782. m_FileEntry.Current.mFileSize = 0;
  2783. m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_DIRECTORY;
  2784. }
  2785. else {
  2786. m_FileEntry.Current.mFileSize = st.st_size;
  2787. }
  2788. if (m_FileEntry.Current.mAttributes == 0)
  2789. m_FileEntry.Current.mAttributes = FILE_ATTRIBUTE_ARCHIVE;
  2790. if (!(st.st_mode & S_IWUSR))
  2791. m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_READONLY;
  2792. DWORD dwDir = 0, dwFile = 0;
  2793. GetSubFileInfors(&m_FileEntry, dwDir, dwFile, dwFilterAttributes);
  2794. Dbg("Flag: dwDir:%u, dwFile: %u", dwDir, dwFile);
  2795. DisplayFileEntities(&m_FileEntry);
  2796. dwFileCnt = dwDir + dwFile;
  2797. m_FileEntry.Current.mFileSize = dwFileCnt;
  2798. #endif // _MSC_VER
  2799. return TRUE;
  2800. }
  2801. DWORD ResourceWatcherFSM::InitialVolumes()
  2802. {
  2803. UINT uCount = 0;
  2804. #ifdef _MSC_VER
  2805. if (!sBDiskValStatus[MAX_VOLUME_COUNT])
  2806. {
  2807. CHAR szDrivers[BUFSIZE] = { 0 };
  2808. CHAR szVolumeName[MAX_PATH] = { 0 };
  2809. CHAR szFileSysName[MAX_PATH] = { 0 };
  2810. BOOL bRet = GetLogicalDriveStringsA(BUFSIZE - 1, szDrivers);
  2811. if (bRet)
  2812. {
  2813. int nDriNum = 0;
  2814. for (CHAR* pTemp = szDrivers; *pTemp != '\0'; pTemp += 4)
  2815. {
  2816. if (*pTemp >= 'a' && *pTemp <= 'z') *pTemp -= 32;
  2817. nDriNum = *pTemp - 'A';
  2818. sBDiskValStatus[nDriNum] = FALSE;
  2819. if (DRIVE_FIXED == GetDriveType(pTemp))
  2820. {
  2821. DWORD dwMaxCompLen, dwFileSystemFlags;
  2822. bRet = GetVolumeInformation(pTemp, szVolumeName, MAX_PATH, NULL,
  2823. &dwMaxCompLen, &dwFileSystemFlags, szFileSysName, MAX_PATH);
  2824. sBDiskValStatus[nDriNum] = TRUE;
  2825. uCount++;
  2826. }
  2827. }
  2828. }
  2829. if (uCount > 0)
  2830. {
  2831. sBDiskValStatus[MAX_VOLUME_COUNT] = TRUE;
  2832. }
  2833. }
  2834. m_FileEntry.SubFiles.Clear();
  2835. m_FileEntry.FileNamesBuffer.Clear();
  2836. m_FileEntry.Current.Clear();
  2837. uCount = 0;
  2838. ULARGE_INTEGER uiTotalBytes, uiTotalFreeBytes;
  2839. if (sBDiskValStatus[MAX_VOLUME_COUNT])
  2840. {
  2841. m_FileEntry.Current.mLevel = -2; //mark parent of volume -2-level
  2842. char szVolume[8] = { 0 };
  2843. for (int i = 0; i < MAX_VOLUME_COUNT; ++i)
  2844. {
  2845. if (sBDiskValStatus[i])
  2846. {
  2847. szVolume[0] = i + 'A';
  2848. szVolume[1] = ':';
  2849. szVolume[2] = '\0';
  2850. CSimpleFileComponent volume;
  2851. if (DiskInfo::GetDiskSpace(szVolume, uiTotalBytes, uiTotalFreeBytes))
  2852. {
  2853. volume.mFileSize = uiTotalFreeBytes.QuadPart;
  2854. }
  2855. volume.mLevel = 0;
  2856. DWORD dwNameLen = strlen(szVolume);
  2857. Append(m_FileEntry.FileNamesBuffer, (PBYTE)szVolume, dwNameLen, volume.mNameOffset);
  2858. volume.mNameLength = dwNameLen;
  2859. volume.mAttributes = 0;
  2860. m_FileEntry.SubFiles.Append(&volume, 0, 1);
  2861. uCount++;
  2862. }
  2863. }
  2864. }
  2865. DisplayFileEntities(&m_FileEntry);
  2866. #endif // _MSC_VER
  2867. return uCount;
  2868. }
  2869. ErrorCodeEnum ResourceWatcherFSM::GetCpuType(
  2870. SpReqAnsContext<ResourceWatcherService_GetCpuType_Req,
  2871. ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
  2872. {
  2873. ErrorCodeEnum ec = Error_Succeed;
  2874. ec = Error_NotSupport;
  2875. LogWarn(Severity_Middle, ec, 0, CSimpleStringA::Format("%s is not supported!", __FUNCTION__));
  2876. if (ctx != NULL) {
  2877. ctx->Answer(ec);
  2878. }
  2879. return ec;
  2880. }
  2881. void ResourceWatcherFSM::HardwareInfoTimer(void* pData)
  2882. {
  2883. #ifdef RVC_OS_LINUX
  2884. GetSystemCPUStatus();
  2885. GetSystemMemoryStatus();
  2886. GetSystemDiskStatus();
  2887. GetOperationDiskStatus();
  2888. GetMainLinkStatus();
  2889. GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, MAX_HARDWARE_CHECK_TIME * 2);
  2890. #else
  2891. if (mainDetectFlag > 0)
  2892. {
  2893. GetMainLinkStatus();
  2894. }
  2895. CSystemStaticInfo info;
  2896. GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  2897. if (info.strMachineType == "RVC.PAD")
  2898. {
  2899. GetBatteryStatus();
  2900. }
  2901. if (hardwareCheckFlag > 0)
  2902. {
  2903. GetSystemCPUStatus();
  2904. GetSystemMemoryStatus();
  2905. GetSystemDiskStatus();
  2906. }
  2907. GetNetStatus();
  2908. GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, hardwareCheckTime);
  2909. #endif // RVC_OS_LINUX
  2910. }
  2911. void ResourceWatcherFSM::LinkDetect(int detectType, const char* url, bool& status, uint& delay)
  2912. {
  2913. #ifdef RVC_OS_LINUX
  2914. timeval begin, end;
  2915. uint tInterval = 0;
  2916. bool flag = false;
  2917. string tUrl = url;
  2918. string host = "http://";
  2919. if (tUrl.find("http") == string::npos)
  2920. {
  2921. tUrl = host + tUrl;
  2922. }
  2923. char tmpUrl[1024] = { 0 };
  2924. strcpy(tmpUrl, tUrl.c_str());
  2925. Dbg("Check url:[%s].", url);
  2926. gettimeofday(&begin, NULL);
  2927. string msg;
  2928. int curFlag = HttpProbe(tmpUrl, msg, 5);
  2929. gettimeofday(&end, NULL);
  2930. tInterval = (end.tv_sec - begin.tv_sec) * 1000 + (end.tv_usec - begin.tv_usec) / 1000;
  2931. if (curFlag > 0 && curFlag < 400)
  2932. {
  2933. status = true;
  2934. }
  2935. else
  2936. {
  2937. status = false;
  2938. }
  2939. delay = tInterval;
  2940. #else
  2941. int flag = 0;
  2942. DWORD start, finish;
  2943. string tUrl = url;
  2944. string host = "http://";
  2945. if (tUrl.find("http") == string::npos)
  2946. {
  2947. tUrl = host + tUrl;
  2948. }
  2949. char tmpUrl[MAX_PATH] = { 0 };
  2950. strcpy_s(tmpUrl, tUrl.c_str());
  2951. start = timeGetTime();
  2952. flag = http_probe(tmpUrl, 5000, 0, warnFlag);
  2953. finish = timeGetTime();
  2954. unsigned int tInterval = finish - start;
  2955. if (flag == false)
  2956. {
  2957. status = false;
  2958. }
  2959. else
  2960. {
  2961. status = true;
  2962. }
  2963. delay = tInterval;
  2964. #endif // RVC_OS_LINUX
  2965. }
  2966. ErrorCodeEnum ResourceWatcherFSM::BizLinkDetect(
  2967. SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
  2968. {
  2969. LOG_FUNCTION();
  2970. ErrorCodeEnum ec = Error_Succeed;
  2971. int detectType = ctx->Req.protocol;
  2972. CSimpleStringA url = ctx->Req.bizLink;
  2973. bool linkStatus = false;
  2974. uint delay = 0;
  2975. LinkDetect(detectType, url.GetData(), linkStatus, delay);
  2976. ctx->Ans.bizLinkStatus = linkStatus;
  2977. ctx->Ans.bizLinkDelayMS = delay;
  2978. ctx->Ans.intParam = 0;
  2979. #ifdef _MSC_VER
  2980. CSimpleStringA warn;
  2981. if (!linkStatus)
  2982. {
  2983. warn = CSimpleStringA::Format("BizLink disconnected[%s].", url.GetData());
  2984. }
  2985. else
  2986. {
  2987. warn = CSimpleStringA::Format("BizLink connected[%s], Delay time [%d]ms.", url.GetData(), delay);
  2988. }
  2989. LogWarn(Severity_Low, Error_Param, LOG_WARN_BIZLINK_CONNECT_CHECK, warn.GetData());
  2990. #endif // _MSC_VER
  2991. if (ctx != NULL) {
  2992. ctx->Answer(ec);
  2993. }
  2994. return ec;
  2995. }
  2996. #ifdef _MSC_VER
  2997. #define CNNTYPE_UNKONWN 0 //0:未知
  2998. #define CNNTYPE_LAN 1 //网线已连接
  2999. #define CNNTYPE_LAN_DISCONNECT 2 //网线未连接(行内PAD,本应连接网线的)
  3000. #define CNNTYPE_DONGLE_CNTED 3 //外接卡托已连接(这种情况几乎没有)
  3001. #define CNNTYPE_DONGLE_DISCONNECT 4 //外接卡托未连接(这种情况几乎没有)
  3002. #define CNNTYPE_LTE_CNTED 5 //5:LTE设备,处于已连接状态
  3003. #define CNNTYPE_LTE_DISCONNECT 6 //LTE设备,处于未连接状态
  3004. #define CNNTYPE_MIFI_WIFI_SIM 7 //MIFI连接模式,WIFI已连接,SIM卡已连接
  3005. #define CNNTYPE_MIFI_WIFI_CNTED 8 //MIFI连接模式,WIFI已连接,SIM卡未连接
  3006. #define CNNTYPE_MIFI_WIFI_DISCONNECT 9 //MIFI连接模式,WIFI未连接
  3007. #define CNNTYPE_WIFI_CONNECT 10 //WIFI已连接(非MIFI模式,手工连接等其他场景)
  3008. #define CNNTYPE_NO_ANY_CONNECT 11 //无任何其他内容连接
  3009. #endif // _MSC_VER
  3010. ErrorCodeEnum ResourceWatcherFSM::CheckNetType(
  3011. SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
  3012. {
  3013. #ifdef RVC_OS_LINUX
  3014. ErrorCodeEnum ec = Error_Succeed;
  3015. int netType = 0; //默认未知
  3016. CSimpleStringA tmpVendor(""), tmpDevSN(""), tmpDLLVersion("");
  3017. GetEntityBase()->GetFunction()->GetSysVar("FWBVendor", tmpVendor);
  3018. GetEntityBase()->GetFunction()->GetSysVar("FWBDevSN", tmpDevSN);
  3019. GetEntityBase()->GetFunction()->GetSysVar("FWBVersion", tmpDLLVersion);
  3020. if (tmpDLLVersion.GetLength() < 2)
  3021. tmpDLLVersion = "8.1";
  3022. if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2)
  3023. {
  3024. Dbg("This is fwb device.");
  3025. }
  3026. else
  3027. {
  3028. int i = 0;
  3029. int sockfd;
  3030. struct ifconf ifconf;
  3031. struct ifreq* ifreq;
  3032. char buf[1024];
  3033. //初始化ifconf
  3034. ifconf.ifc_len = 1024;
  3035. ifconf.ifc_buf = buf;
  3036. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  3037. {
  3038. perror("socket error");
  3039. exit(1);
  3040. }
  3041. //获取所有接口信息
  3042. ioctl(sockfd, SIOCGIFCONF, &ifconf);
  3043. //逐个获取Ip地址
  3044. int size = ifconf.ifc_len / sizeof(struct ifreq);
  3045. ifreq = (struct ifreq*)buf;
  3046. string netName(ifreq->ifr_name);
  3047. if (size == 1 && netName == "lo") //只有逻辑地址 -- 网线被拔出
  3048. {
  3049. netType = 1;
  3050. }
  3051. else
  3052. {
  3053. for (i = size; i > 0; i--)
  3054. {
  3055. string netName(ifreq->ifr_name); //有其他网卡 -- 有线
  3056. if (netName != "lo")
  3057. {
  3058. netType = 2;
  3059. }
  3060. ifreq++;
  3061. }
  3062. }
  3063. ctx->Ans.netType = netType;
  3064. }
  3065. if (ctx != NULL) {
  3066. ctx->Answer(ec);
  3067. }
  3068. return ec;
  3069. #else
  3070. ErrorCodeEnum ec = Error_Succeed;
  3071. int netType = 0; //默认未知
  3072. CSystemStaticInfo info;
  3073. GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  3074. if (info.strMachineType.Compare("RVC.PAD") == 0) //PAD机型
  3075. {
  3076. CMbnImplHelper mbnHelper;
  3077. ResetDongleInfos();
  3078. const int nMBN = mbnHelper.EnumerateInterfaces();
  3079. const int cnt = g_DongleInfos.GetCount();
  3080. for (int i = 0; i < cnt; ++i) {
  3081. if (g_DongleInfos[i].state == MBD_ACTIVATION_CONNECTED) {
  3082. netType = 4; //移动网络
  3083. }
  3084. }
  3085. if (netType == 0 && 1 == IsWifiConnected()) {
  3086. netType = 3; //无线网络
  3087. }
  3088. if (netType == 0) {
  3089. if (SP::Module::Net::CheckLANConnectStatus()) {
  3090. netType = 2; //有线
  3091. }
  3092. else {
  3093. netType = 1; //未连接
  3094. }
  3095. }
  3096. }
  3097. else //大机、低柜、卡库
  3098. {
  3099. CoInitialize(NULL);
  3100. // 通过NLA接口获取网络状态
  3101. IUnknown* pUnknown = NULL;
  3102. BOOL bOnline = TRUE;//是否在线
  3103. HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
  3104. IID_IUnknown, (void**)&pUnknown);
  3105. if (SUCCEEDED(Result))
  3106. {
  3107. INetworkListManager* pNetworkListManager = NULL;
  3108. if (pUnknown)
  3109. Result = pUnknown->QueryInterface(IID_INetworkListManager, (void
  3110. **)&pNetworkListManager);
  3111. if (SUCCEEDED(Result))
  3112. {
  3113. VARIANT_BOOL IsConnect = VARIANT_FALSE;
  3114. if (pNetworkListManager)
  3115. {
  3116. //Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect); //检测互联网连接
  3117. Result = pNetworkListManager->get_IsConnected(&IsConnect); //检测本地网络
  3118. }
  3119. if (SUCCEEDED(Result))
  3120. {
  3121. bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
  3122. }
  3123. }
  3124. if (pNetworkListManager)
  3125. pNetworkListManager->Release();
  3126. }
  3127. if (pUnknown)
  3128. pUnknown->Release();
  3129. if (bOnline == true)
  3130. {
  3131. netType = 2;
  3132. }
  3133. else
  3134. {
  3135. netType = 1;
  3136. }
  3137. }
  3138. ctx->Ans.netType = netType;
  3139. if (ctx != NULL) {
  3140. ctx->Answer(ec);
  3141. }
  3142. return ec;
  3143. #endif // RVC_OS_LINUX
  3144. }
  3145. #ifdef _MSC_VER
  3146. void ResourceWatcherFSM::GetNetStatus()
  3147. {
  3148. ErrorCodeEnum ec = Error_Succeed;
  3149. int netType = 0; //默认未知
  3150. CSystemStaticInfo info;
  3151. GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  3152. if (info.strMachineType.Compare("RVC.PAD") == 0) //PAD机型
  3153. {
  3154. CMbnImplHelper mbnHelper;
  3155. ResetDongleInfos();
  3156. const int nMBN = mbnHelper.EnumerateInterfaces();
  3157. const int cnt = g_DongleInfos.GetCount();
  3158. for (int i = 0; i < cnt; ++i) {
  3159. if (g_DongleInfos[i].state == MBD_ACTIVATION_CONNECTED) {
  3160. netType = 4; //移动网络
  3161. }
  3162. }
  3163. if (netType == 0 && 1 == IsWifiConnected()) {
  3164. netType = 3; //无线网络
  3165. }
  3166. if (netType == 0) {
  3167. if (SP::Module::Net::CheckLANConnectStatus()) {
  3168. netType = 2; //有线
  3169. }
  3170. else {
  3171. netType = 1; //未连接
  3172. }
  3173. }
  3174. }
  3175. else //大机、低柜、卡库
  3176. {
  3177. CoInitialize(NULL);
  3178. // 通过NLA接口获取网络状态
  3179. IUnknown* pUnknown = NULL;
  3180. BOOL bOnline = TRUE;//是否在线
  3181. HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
  3182. IID_IUnknown, (void**)&pUnknown);
  3183. if (SUCCEEDED(Result))
  3184. {
  3185. INetworkListManager* pNetworkListManager = NULL;
  3186. if (pUnknown)
  3187. Result = pUnknown->QueryInterface(IID_INetworkListManager, (void
  3188. **)&pNetworkListManager);
  3189. if (SUCCEEDED(Result))
  3190. {
  3191. VARIANT_BOOL IsConnect = VARIANT_FALSE;
  3192. if (pNetworkListManager)
  3193. {
  3194. //Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect); //检测互联网连接
  3195. Result = pNetworkListManager->get_IsConnected(&IsConnect); //检测本地网络
  3196. }
  3197. if (SUCCEEDED(Result))
  3198. {
  3199. bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
  3200. }
  3201. }
  3202. if (pNetworkListManager)
  3203. pNetworkListManager->Release();
  3204. }
  3205. if (pUnknown)
  3206. pUnknown->Release();
  3207. if (bOnline == true)
  3208. {
  3209. netType = 2;
  3210. }
  3211. else
  3212. {
  3213. netType = 1;
  3214. }
  3215. }
  3216. NetStatus netStatus;
  3217. netStatus.status = netType;
  3218. if (netType != lastNetStatus)
  3219. {
  3220. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("netStatus.status: %d.", netStatus.status);
  3221. SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(NetStatus), SP_MSG_SIG_OF(NetStatus), netStatus);
  3222. lastNetStatus = netType;
  3223. }
  3224. }
  3225. #endif // _MSC_VER
  3226. ErrorCodeEnum ResourceWatcherFSM::GetBizLinks(
  3227. SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
  3228. {
  3229. LOG_FUNCTION();
  3230. ErrorCodeEnum ec = Error_Succeed;
  3231. int filter = ctx->Req.filter; //后续过滤使用
  3232. CAutoArray<CSimpleStringA> bizLinks;
  3233. CAutoArray<CSimpleStringA> bizNames;
  3234. CSmartPointer<IConfigInfo> spCtSettingConfig;
  3235. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  3236. CSimpleStringA mLink(""), adLink(""), tLink("");
  3237. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
  3238. if (mLink.GetLength() != 0)
  3239. {
  3240. CSimpleStringA tName = CSimpleStringA("主站点");
  3241. bizNames.Append(&tName, 0, 1);
  3242. bizLinks.Append(&mLink, 0, 1);
  3243. }
  3244. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrAd", adLink);
  3245. if (adLink.GetLength() != 0)
  3246. {
  3247. CSimpleStringA tName = CSimpleStringA("广告站点");
  3248. bizNames.Append(&tName, 0, 1);
  3249. bizLinks.Append(&adLink, 0, 1);
  3250. }
  3251. int bizCnt = 0;
  3252. CSimpleStringA getLink("");
  3253. do
  3254. {
  3255. bizCnt++;
  3256. getLink = CSimpleStringA("UserBizLink").Append(std::to_string(bizCnt).c_str());
  3257. spCtSettingConfig->ReadConfigValue("Chromium", (LPCTSTR)getLink, tLink);
  3258. if (tLink.GetLength() != 0)
  3259. {
  3260. CSimpleStringA tName = CSimpleStringA("业务站点").Append(std::to_string(bizCnt).c_str());
  3261. bizNames.Append(&tName, 0, 1);
  3262. bizLinks.Append(&tLink, 0, 1);
  3263. }
  3264. } while (tLink.GetLength() != 0);
  3265. ctx->Ans.bizLinks = bizLinks;
  3266. ctx->Ans.bizNames = bizNames;
  3267. if (ctx != NULL) {
  3268. ctx->Answer(ec);
  3269. }
  3270. return ec;
  3271. }
  3272. void ResourceWatcherFSM::GetMainLinkStatus()
  3273. {
  3274. ErrorCodeEnum errorCode = Error_Succeed;
  3275. CSmartPointer<IConfigInfo> spCtSettingConfig;
  3276. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  3277. ErrorCodeEnum erroCode = Error_Unexpect;
  3278. CSimpleStringA mLink("");
  3279. erroCode = spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
  3280. if (mLink.GetLength() == 0)
  3281. {
  3282. return;
  3283. }
  3284. MainLinkDetect mainDetect;
  3285. const char* mainLink = mLink.GetData();
  3286. bool curStatus = false;
  3287. uint delay = 0;
  3288. LinkDetect(0, mainLink, curStatus, delay);
  3289. #ifdef RVC_OS_LINUX
  3290. if (!curStatus)
  3291. {
  3292. Dbg("Main Link disconnected [%s].", mainLink);
  3293. }
  3294. mainDetect.mainLinkStatus = curStatus;
  3295. mainDetect.reversed1 = 0;
  3296. mainDetect.reversed2 = "";
  3297. if (curStatus != lastLinkStatus || !curStatus)
  3298. {
  3299. SpSendBroadcast(GetEntityBase()->GetFunction(),
  3300. SP_MSG_OF(MainLinkDetect), SP_MSG_SIG_OF(MainLinkDetect), mainDetect);
  3301. lastLinkStatus = curStatus;
  3302. }
  3303. #else
  3304. if (!curStatus)
  3305. {
  3306. std::string warn = "Main Link disconnected [" + std::string(mainLink) + "].";
  3307. LogWarn(Severity_Middle, Error_Param, LOG_WARN_MAINLINK_CONNECT_FAILED, CSimpleStringA::Format("%s", warn.c_str()));
  3308. }
  3309. mainDetect.mainLinkStatus = curStatus;
  3310. mainDetect.reversed1 = 0;
  3311. mainDetect.reversed2 = "";
  3312. SpSendBroadcast(GetEntityBase()->GetFunction(),
  3313. SP_MSG_OF(MainLinkDetect), SP_MSG_SIG_OF(MainLinkDetect), mainDetect);
  3314. #endif // RVC_OS_LINUX
  3315. }
  3316. #ifdef _MSC_VER
  3317. void ResourceWatcherFSM::CalCulateFileInfo(LPCTSTR lpFilePath, PWIN32_FIND_DATA pWfdata)
  3318. {
  3319. m_VideoFiles.push(new TmpFileInfo(lpFilePath,
  3320. &(pWfdata->ftLastWriteTime),
  3321. pWfdata->nFileSizeHigh, pWfdata->nFileSizeLow));
  3322. ULARGE_INTEGER uiTemp;
  3323. uiTemp.HighPart = pWfdata->nFileSizeHigh;
  3324. uiTemp.LowPart = pWfdata->nFileSizeLow;
  3325. uiAllVideoFileSizeCal.QuadPart += uiTemp.QuadPart;
  3326. if (uiMaxFileSize.QuadPart < uiTemp.QuadPart)
  3327. {
  3328. strcpy_s(szMaxSizeFilePath, lpFilePath);
  3329. uiMaxFileSize.QuadPart = uiTemp.QuadPart;
  3330. }
  3331. SYSTEMTIME stUTC, stLocal;
  3332. FileTimeToSystemTime(&(pWfdata->ftLastWriteTime), &stUTC);
  3333. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  3334. UINT uDate = stLocal.wYear * 10000 + stLocal.wMonth * 100 + stLocal.wDay;
  3335. VideoDailyRecord[uDate]++;
  3336. }
  3337. BOOL ResourceWatcherFSM::CalCulateUploadFileAddition(ULARGE_INTEGER& uiBytesCal)
  3338. {
  3339. uiBytesCal.QuadPart = 0;
  3340. BOOL bRet = FALSE;
  3341. ErrorCodeEnum ec = Error_Unexpect;
  3342. CSimpleStringA uploadVideoPath;
  3343. ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
  3344. if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
  3345. if (ec == Error_Succeed)
  3346. {
  3347. CSimpleStringA filePath = uploadVideoPath + "\\*";
  3348. ULARGE_INTEGER uliSpaceSize;
  3349. uliSpaceSize.QuadPart = 0;
  3350. int nFileCnt = ProcessFileSpaceCalculation(filePath, &uliSpaceSize);
  3351. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3352. ByteSprintf(szResult, (double)uliSpaceSize.QuadPart);
  3353. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Result: Files(%d), Size(%s).", nFileCnt, szResult);
  3354. uiBytesCal.QuadPart = uliSpaceSize.QuadPart;
  3355. }
  3356. return (ec == Error_Succeed);
  3357. }
  3358. int ResourceWatcherFSM::ProcessFileSpaceCalculation(LPCTSTR lpszPath, PULARGE_INTEGER puliSpaceBytes)
  3359. {
  3360. int fileCnt = 0;
  3361. int fileLength = strlen(lpszPath);
  3362. char* searchFilePath = new char[MAX_PATH];
  3363. char* tempFilePath = new char[MAX_PATH];
  3364. if (searchFilePath == NULL || tempFilePath == NULL)
  3365. {
  3366. if (searchFilePath) delete[] searchFilePath;
  3367. if (tempFilePath) delete[] tempFilePath;
  3368. return fileCnt;
  3369. }
  3370. ZeroMemory(searchFilePath, MAX_PATH);
  3371. ZeroMemory(tempFilePath, MAX_PATH);
  3372. WIN32_FIND_DATA wfd;
  3373. HANDLE hFind;
  3374. hFind = FindFirstFile(lpszPath, &wfd);
  3375. if (hFind == INVALID_HANDLE_VALUE)
  3376. {
  3377. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FindFirstFile failed GLE = %u.", GetLastError());
  3378. if (searchFilePath) delete[] searchFilePath;
  3379. if (tempFilePath) delete[] tempFilePath;
  3380. return 0;
  3381. }
  3382. do
  3383. {
  3384. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  3385. {
  3386. if (wfd.cFileName[0] != '.')
  3387. {
  3388. strcpy_s(tempFilePath, MAX_PATH, lpszPath);
  3389. tempFilePath[fileLength - 1] = '\0';
  3390. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH)
  3391. {
  3392. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  3393. }
  3394. else
  3395. {
  3396. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
  3397. strcat_s(tempFilePath, MAX_PATH, "\\*");
  3398. fileCnt += ProcessFileSpaceCalculation((LPCTSTR)tempFilePath, puliSpaceBytes);
  3399. }
  3400. }
  3401. }
  3402. else
  3403. {
  3404. strcpy_s(searchFilePath, MAX_PATH, lpszPath);
  3405. searchFilePath[fileLength - 1] = '\0';
  3406. strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
  3407. ULARGE_INTEGER uiTemp;
  3408. uiTemp.HighPart = wfd.nFileSizeHigh;
  3409. uiTemp.LowPart = wfd.nFileSizeLow;
  3410. puliSpaceBytes->QuadPart += uiTemp.QuadPart;
  3411. SYSTEMTIME stUTC, stLocal;
  3412. FileTimeToSystemTime(&wfd.ftLastWriteTime, &stUTC);
  3413. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  3414. UINT uDate = stLocal.wYear * 10000 + stLocal.wMonth * 100 + stLocal.wDay;
  3415. VideoDailyRecord[uDate]++;
  3416. fileCnt++;
  3417. }
  3418. } while (FindNextFileA(hFind, &wfd));
  3419. FindClose(hFind);
  3420. if (searchFilePath) delete[] searchFilePath;
  3421. if (tempFilePath) delete[] tempFilePath;
  3422. return fileCnt;
  3423. }
  3424. int ResourceWatcherFSM::MonitorRSAMachineKeysDir()
  3425. {
  3426. LPCTSTR cszRSAKeysMonitor = "RSAKeysMonitor";
  3427. LPCTSTR cszRSAKeyFiles = "RSAKeyFiles";
  3428. LPCTSTR cszLostKeyFiles = "LostKeyFiles";
  3429. CSmartPointer<IConfigInfo> spRunConfig;
  3430. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  3431. int nRun_ExistedKeyCount = 0, nRun_LostKeyCount;
  3432. CSimpleStringA strRun_RecentLostKeyName;
  3433. int nRun_LostTimeStamp = 0;
  3434. struct KeyFileElement {
  3435. KeyFileElement() :fn(true) { ft.ftCreateTime = 0; }
  3436. explicit KeyFileElement(LPCTSTR ftName, const ULONGLONG& filetime)
  3437. :fn(ftName) {
  3438. ft.ftCreateTime = filetime;
  3439. }
  3440. explicit KeyFileElement(LPCTSTR ftName, const DWORD& now)
  3441. :fn(ftName) {
  3442. ft.dwHappenTime = now; ft.dwReserved = 0;
  3443. }
  3444. CSimpleStringA fn;
  3445. //ULONGLONG ft;
  3446. typedef union _RELATE_TIME {
  3447. struct {
  3448. DWORD dwHappenTime;
  3449. DWORD dwReserved;
  3450. };
  3451. ULONGLONG ftCreateTime;
  3452. }RELATETIME;
  3453. RELATETIME ft;
  3454. bool operator <(const KeyFileElement& rhs) { return rhs.ft.ftCreateTime < ft.ftCreateTime; }
  3455. bool operator == (const KeyFileElement& rhs) const { return rhs.fn == fn; }
  3456. bool operator == (const KeyFileElement& rhs) { return rhs.fn == fn; }
  3457. bool operator != (const KeyFileElement& rhs) const { return rhs.fn != fn; }
  3458. bool operator != (const KeyFileElement& rhs) { return rhs.fn != fn; }
  3459. };
  3460. vector<KeyFileElement> vtHistoryKeys;
  3461. vector<KeyFileElement> vtLostKeys;
  3462. spRunConfig->ReadConfigValueInt(cszRSAKeysMonitor, "ExistedKeyFileCount", nRun_ExistedKeyCount);
  3463. spRunConfig->ReadConfigValueInt(cszRSAKeysMonitor, "LostKeyFileCount", nRun_LostKeyCount);
  3464. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There are %d file(s) existed last runtime.", nRun_ExistedKeyCount);
  3465. for (int i = 0; i < nRun_ExistedKeyCount; ++i)
  3466. {
  3467. CSimpleStringA strKeyDescript;
  3468. spRunConfig->ReadConfigValue(cszRSAKeyFiles, CSimpleStringA::Format("%d", i + 1), strKeyDescript);
  3469. CAutoArray<CSimpleStringA> strContent = strKeyDescript.Split(',');
  3470. if (strContent.GetCount() == 2)
  3471. {
  3472. ULONGLONG ulCreateTime;
  3473. sscanf_s(strContent[1], "%I64u", &ulCreateTime);
  3474. vtHistoryKeys.push_back(KeyFileElement(strContent[0], ulCreateTime));
  3475. }
  3476. }
  3477. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("There are %d file(s) lost in history record", nRun_LostKeyCount);
  3478. for (int i = 0; i < nRun_LostKeyCount; ++i)
  3479. {
  3480. CSimpleStringA strKeyDescript;
  3481. spRunConfig->ReadConfigValue(cszLostKeyFiles, CSimpleStringA::Format("%d", i + 1), strKeyDescript);
  3482. CAutoArray<CSimpleStringA> strContent = strKeyDescript.Split(',');
  3483. if (strContent.GetCount() >= 2)
  3484. {
  3485. DWORD dwLostTime;
  3486. sscanf_s(strContent[1], "0x%08X", &dwLostTime);
  3487. vtLostKeys.push_back(KeyFileElement(strContent[0], dwLostTime));
  3488. if (dwLostTime == (DWORD)-1)
  3489. {
  3490. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AlwaysPrint: \"%s\" lost(deleted) when RVC was offline", (LPCTSTR)strContent[0]);
  3491. if (strContent.GetCount() == 3)
  3492. {
  3493. sscanf_s(strContent[2], "0x%08X", &dwLostTime);
  3494. SYSTEMTIME stLostTime = CSmallDateTime(dwLostTime).ToSystemTime();
  3495. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("detected above lost when RVC boot at %04d-%02d-%02d %02d:%02d:%02d",
  3496. stLostTime.wYear, stLostTime.wMonth, stLostTime.wDay,
  3497. stLostTime.wHour, stLostTime.wMinute, stLostTime.wSecond);
  3498. }
  3499. }
  3500. else
  3501. {
  3502. SYSTEMTIME stLostTime = CSmallDateTime(dwLostTime).ToSystemTime();
  3503. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AlwaysPrint: \"%s\" lost(deleted) at %04d-%02d-%02d %02d:%02d:%02d",
  3504. (LPCTSTR)strContent[0],
  3505. stLostTime.wYear, stLostTime.wMonth, stLostTime.wDay,
  3506. stLostTime.wHour, stLostTime.wMinute, stLostTime.wSecond);
  3507. }
  3508. }
  3509. else
  3510. {
  3511. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AlwaysPrint: %s", (LPCTSTR)strKeyDescript);
  3512. }
  3513. }
  3514. int nHistoryKeyCount = (int)vtHistoryKeys.size();
  3515. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Record VS VectorSize(%d VS %d)", nRun_ExistedKeyCount, nHistoryKeyCount);
  3516. //C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
  3517. char szMachineKeysPath[MAX_PATH], szTemp[MAX_PATH];
  3518. DWORD dwError = 0;
  3519. ZeroMemory(szMachineKeysPath, MAX_PATH);
  3520. ZeroMemory(szTemp, MAX_PATH);
  3521. strcpy_s(szMachineKeysPath, "C:\\ProgramData\\Microsoft\\Crypto\\RSA\\MachineKeys");
  3522. if (SHGetSpecialFolderPath(NULL, szTemp, CSIDL_COMMON_APPDATA, FALSE))
  3523. {
  3524. strcat_s(szTemp, "\\Microsoft\\Crypto\\RSA\\MachineKeys");
  3525. strcpy_s(szMachineKeysPath, szTemp);
  3526. }
  3527. else
  3528. {
  3529. dwError = GetLastError();
  3530. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("SHGetSpecialFolderPath failed, GLE=%u", dwError);
  3531. ZeroMemory(szTemp, MAX_PATH);
  3532. if (GetSystemDirectory(szTemp, MAX_PATH))
  3533. {
  3534. szMachineKeysPath[0] = szTemp[0];
  3535. }
  3536. else
  3537. {
  3538. dwError = GetLastError();
  3539. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDirectory failed, GLE=%u", dwError);
  3540. }
  3541. }
  3542. if (!ExistsDirA(szMachineKeysPath))
  3543. {
  3544. LogWarn(Severity_Middle, Error_NoTarget, 0,
  3545. CSimpleStringA::Format("Directory(%s) is not existed !", szMachineKeysPath));
  3546. return -1;
  3547. }
  3548. vector<KeyFileElement> vtCurrentKeys;
  3549. CSimpleStringA strKeyFileSuffix(szMachineKeysPath);
  3550. strKeyFileSuffix += "\\*";
  3551. WIN32_FIND_DATA wfd;
  3552. HANDLE hFind;
  3553. hFind = FindFirstFile(strKeyFileSuffix, &wfd);
  3554. if (hFind == INVALID_HANDLE_VALUE)
  3555. {
  3556. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FindFirstFile(%s) failed GLE = %u.", (LPCTSTR)strKeyFileSuffix, GetLastError());
  3557. return -2;
  3558. }
  3559. ULARGE_INTEGER uiTime;
  3560. do
  3561. {
  3562. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
  3563. {
  3564. uiTime.HighPart = wfd.ftCreationTime.dwHighDateTime;
  3565. uiTime.LowPart = wfd.ftCreationTime.dwLowDateTime;
  3566. vtCurrentKeys.push_back(KeyFileElement(wfd.cFileName, uiTime.QuadPart));
  3567. }
  3568. } while (FindNextFileA(hFind, &wfd));
  3569. FindClose(hFind);
  3570. int nCurKeyCount = (int)vtCurrentKeys.size();
  3571. if (nCurKeyCount)
  3572. sort(vtCurrentKeys.begin(), vtCurrentKeys.end());
  3573. char szFormat[128];
  3574. int shown = 0;
  3575. const int max_shown = 3;
  3576. for (vector<KeyFileElement>::const_iterator cit = vtCurrentKeys.cbegin();
  3577. cit != vtCurrentKeys.cend(); ++cit)
  3578. {
  3579. GetTimeString(szFormat, 128, (PFILETIME) & (cit->ft.ftCreateTime));
  3580. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{\"%s\" - CreateTime: %s}", (LPCTSTR)cit->fn, szFormat);
  3581. if (++shown >= max_shown) break; //Print the front three key files
  3582. }
  3583. int lackCount = 0;
  3584. for (vector<KeyFileElement>::iterator it = vtHistoryKeys.begin();
  3585. it != vtHistoryKeys.end(); ++it)
  3586. {
  3587. if (find(vtCurrentKeys.begin(), vtCurrentKeys.end(), *it) == vtCurrentKeys.end())
  3588. {
  3589. lackCount++;
  3590. if (find(vtLostKeys.begin(), vtLostKeys.end(), *it) == vtLostKeys.end())
  3591. {
  3592. LogEvent(Severity_High, LOG_EVT_RSAKEY_LOST_OFFLINE,
  3593. CSimpleStringA::Format("File{\"%s\"} was removed offline !", (LPCTSTR)it->fn));
  3594. //TODO: USN Journal, found out when it lost
  3595. spRunConfig->WriteConfigValueInt(cszRSAKeysMonitor, "LostKeyFileCount", ++nRun_LostKeyCount);
  3596. CSimpleStringA strKeyDescript(it->fn);
  3597. strKeyDescript += CSimpleStringA::Format(",0x%08X", (DWORD)(-1));
  3598. // Although lost offline, but its responsible to record the discovery time
  3599. // -Josephus@2017619 9:17:11
  3600. strKeyDescript += CSimpleStringA::Format(",0x%08X", (DWORD)CSmallDateTime::GetNow());
  3601. spRunConfig->WriteConfigValue(cszLostKeyFiles, CSimpleStringA::Format("%d",
  3602. nRun_LostKeyCount), strKeyDescript);
  3603. }
  3604. }
  3605. }
  3606. if (lackCount > 0 || nCurKeyCount != nHistoryKeyCount)
  3607. {
  3608. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Update Runcfg about %s, Reason(new lost? %d, cur(%d) vs history(%d)",
  3609. cszRSAKeysMonitor, lackCount, nCurKeyCount, nHistoryKeyCount);
  3610. spRunConfig->WriteConfigValueInt(cszRSAKeysMonitor, "ExistedKeyFileCount", nCurKeyCount);
  3611. int i = 0;
  3612. for (vector<KeyFileElement>::const_iterator cit = vtCurrentKeys.cbegin();
  3613. cit != vtCurrentKeys.cend(); ++cit, ++i)
  3614. {
  3615. CSimpleStringA strKeyDescript(cit->fn);
  3616. strKeyDescript += CSimpleStringA::Format(",%I64u", cit->ft);
  3617. spRunConfig->WriteConfigValue(cszRSAKeyFiles, CSimpleStringA::Format("%d", i + 1), strKeyDescript);
  3618. }
  3619. if (i < nRun_ExistedKeyCount)
  3620. {
  3621. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Clear from %d to %d", i + 1, nRun_ExistedKeyCount);
  3622. do {
  3623. spRunConfig->WriteConfigValue(cszRSAKeyFiles, CSimpleStringA::Format("%d", i + 1), "");
  3624. } while (++i < nRun_ExistedKeyCount);
  3625. }
  3626. }
  3627. HANDLE hFile = CreateFileA(
  3628. szMachineKeysPath,
  3629. FILE_LIST_DIRECTORY,
  3630. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  3631. NULL,
  3632. OPEN_EXISTING,
  3633. FILE_FLAG_BACKUP_SEMANTICS,
  3634. NULL);
  3635. if (hFile == INVALID_HANDLE_VALUE)
  3636. {
  3637. dwError = GetLastError();
  3638. LogWarn(Severity_Middle, Error_Unexpect, dwError,
  3639. CSimpleStringA::Format("CreateFileA(%s) failed, GLE=%u", szMachineKeysPath, dwError));
  3640. return -3;
  3641. }
  3642. const DWORD INFO_BUFFER_SIZE = 2048;
  3643. char chInfoBuf[INFO_BUFFER_SIZE];
  3644. DWORD dwBufSize = INFO_BUFFER_SIZE;
  3645. PFILE_NOTIFY_INFORMATION pFNotifyInfo = (PFILE_NOTIFY_INFORMATION)chInfoBuf;
  3646. DWORD dwRetBytes;
  3647. vtCurrentKeys.clear();
  3648. vtHistoryKeys.clear();
  3649. vtLostKeys.clear();
  3650. do
  3651. {
  3652. ZeroMemory(chInfoBuf, INFO_BUFFER_SIZE);
  3653. BOOL bRet = ReadDirectoryChangesW(hFile
  3654. , &chInfoBuf
  3655. , sizeof(chInfoBuf)
  3656. , FALSE
  3657. , FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_DIR_NAME
  3658. , &dwRetBytes
  3659. , NULL
  3660. , NULL
  3661. );
  3662. if (!bRet)
  3663. {
  3664. dwError = GetLastError();
  3665. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ReadDirectoryChangesW failed, GLE=%u", dwError);
  3666. if (dwError == ERROR_INVALID_FUNCTION)
  3667. {
  3668. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The network redirector or the target file system does not support this operation !");
  3669. }
  3670. else if (dwError == ERROR_NOTIFY_ENUM_DIR)
  3671. {
  3672. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The buffer overflows !");
  3673. }
  3674. continue;
  3675. }
  3676. CSimpleStringW strFileNameW(pFNotifyInfo->FileName, pFNotifyInfo->FileNameLength);
  3677. CSimpleStringA strFileName = CSimpleStringW2A(strFileNameW);
  3678. switch (pFNotifyInfo->Action)
  3679. {
  3680. case FILE_ACTION_ADDED: //0x00000001
  3681. {
  3682. LogEvent(Severity_Low, LOG_EVT_RSAKEY_ADD_RIGHTNOW,
  3683. CSimpleStringA::Format("A file{\"%s\"} is added !", (LPCTSTR)strFileName));
  3684. }
  3685. break;
  3686. case FILE_ACTION_REMOVED: //0x00000002
  3687. {
  3688. spRunConfig->WriteConfigValueInt(cszRSAKeysMonitor, "LostKeyFileCount", ++nRun_LostKeyCount);
  3689. LogEvent(Severity_High, LOG_EVT_RSAKEY_LOST_RIGHTNOW,
  3690. CSimpleStringA::Format("File{\"%s\"} is removed !", (LPCTSTR)strFileName));
  3691. CSimpleStringA strKeyDescript(strFileName);
  3692. strKeyDescript += CSimpleStringA::Format(",0x%08X", (DWORD)CSmallDateTime::GetNow());
  3693. spRunConfig->WriteConfigValue(cszLostKeyFiles, CSimpleStringA::Format("%d",
  3694. nRun_LostKeyCount), strKeyDescript);
  3695. }
  3696. break;
  3697. case FILE_ACTION_MODIFIED: //0x00000003
  3698. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The file was modified: %s", (LPCTSTR)strFileName);
  3699. break;
  3700. case FILE_ACTION_RENAMED_OLD_NAME: //0x00000004
  3701. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There is a file was renamed and this is the old name: %s", (LPCTSTR)strFileName);
  3702. break;
  3703. case FILE_ACTION_RENAMED_NEW_NAME: //0x00000005
  3704. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There is a file was renamed and this is the new name: %s", (LPCTSTR)strFileName);
  3705. break;
  3706. }
  3707. } while (Sleep(1000), TRUE);
  3708. CloseHandle(hFile);
  3709. hFile = NULL;
  3710. return 0;
  3711. }
  3712. #endif // _MSC_VER
  3713. DWORD ResourceWatcherFSM::ProcessFileOperation(
  3714. const SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  3715. ResourceWatcherService_OperateFile_Ans>::Pointer& ctx)
  3716. {
  3717. if (ctx == NULL) return 0;
  3718. ResourceWatcherService_OperateFile_Req& req = ctx->Req;
  3719. ResourceWatcherService_OperateFile_Ans& ans = ctx->Ans;
  3720. {
  3721. ans.header = "";
  3722. ans.attachment1 = 0;
  3723. ans.attachment2 = "";
  3724. ans.fileSize = 0ULL;
  3725. ans.ftCreate = 0ULL;
  3726. ans.ftModified = 0ULL;
  3727. ans.ftAccess = 0ULL;
  3728. ans.fileAttribute = 0U;
  3729. ans.count = 0;
  3730. }
  3731. CSimpleStringA strCurrent(true);
  3732. size_t nCurLen = req.current.GetLength();
  3733. if (!req.current.IsNullOrEmpty())
  3734. {
  3735. CSimpleStringA strTemp = req.current.Trim();
  3736. size_t len = req.current.GetLength();
  3737. while (len > 0 && (strTemp[len - 1] == '\\' || strTemp[len - 1] == '/'))
  3738. {
  3739. strTemp[len - 1] = '\0';
  3740. len--;
  3741. }
  3742. if (len > 0)
  3743. {
  3744. strCurrent = strTemp.Trim();
  3745. nCurLen = strCurrent.GetLength();
  3746. LOG_ASSERT(len == nCurLen);
  3747. }
  3748. }
  3749. BOOL bCurNull = strCurrent.IsNullOrEmpty();
  3750. if (!bCurNull)
  3751. {
  3752. int nRes = FilterFilePathAhead(strCurrent, req.mode);
  3753. if (nRes != 0)
  3754. {
  3755. ans.result = OPT_FILE_RES_FAILED;
  3756. CSimpleStringA strTxt;
  3757. switch (nRes)
  3758. {
  3759. case -1:
  3760. case -2:
  3761. strTxt = "文件路径参数错误。";
  3762. break;
  3763. case -3:
  3764. strTxt = "终端指定磁盘不存在。";
  3765. break;
  3766. case 1:
  3767. strTxt = "操作非法:不允许删除盘符。";
  3768. break;
  3769. case 2:
  3770. strTxt = "请求的操作无权限。";
  3771. break;
  3772. default:
  3773. strTxt = "操作失败,原因未知。";
  3774. break;
  3775. }
  3776. ans.attachment1 = strTxt.GetLength();
  3777. ans.attachment2 = strTxt;
  3778. ctx->Answer(Error_Succeed);
  3779. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Try to (option:%d) [%s] failed (%d): %s", req.mode, (LPCTSTR)strCurrent, nRes, (LPCTSTR)strTxt);
  3780. return nRes;
  3781. }
  3782. }
  3783. FileType type = FT_Unknown;
  3784. IsPathExisted(strCurrent, type);
  3785. int count = 0;
  3786. ans.count = 0;
  3787. ans.result = OPT_FILE_RES_INVALID;
  3788. bool bNeedToRefleshHeader = false;
  3789. bool bNeedToSetCtxEntities = false;
  3790. bool bNeedToRefleshEntity = false;
  3791. int updateLevel = 0;
  3792. switch (ctx->Req.mode)
  3793. {
  3794. case OPT_FILE_CMD_SPREAD: //0
  3795. {
  3796. DWORD dwRes = 0;
  3797. if (!bCurNull && (type == FT_Unknown || type == FT_File))
  3798. {
  3799. ans.result = OPT_FILE_RES_FAILED;
  3800. ans.attachment1 = GetErrorMessage(ans.attachment2, "请求的文件不存在或类型不正确。");
  3801. break;
  3802. }
  3803. DWORD dwFilterAttributes = (DWORD)(ctx->Req.filter1);
  3804. if (bCurNull)
  3805. {
  3806. #if defined(_MSC_VER)
  3807. dwRes = InitialVolumes();
  3808. #else
  3809. if (!InitialFileEntity("/", dwRes, dwFilterAttributes)) {
  3810. ans.result = OPT_FILE_RES_FAILED;
  3811. ans.attachment1 = GetErrorMessage(ans.attachment2, "获取根目录列表失败");
  3812. Dbg("Initial File Entity failed: %s", ans.attachment2.GetData());
  3813. break;
  3814. }
  3815. #endif //_MSC_VER
  3816. }
  3817. else if (!InitialFileEntity(strCurrent, dwRes, dwFilterAttributes))
  3818. {
  3819. ans.result = OPT_FILE_RES_FAILED;
  3820. ans.attachment1 = GetErrorMessage(ans.attachment2, "获取文件列表失败");
  3821. break;
  3822. }
  3823. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("%d VS %d", dwRes, m_FileEntry.SubFiles.GetCount());
  3824. LOG_ASSERT(dwRes == m_FileEntry.SubFiles.GetCount());
  3825. count = dwRes;
  3826. ans.result = OPT_FILE_RES_SUCCESS;
  3827. bNeedToSetCtxEntities = true;
  3828. bNeedToRefleshHeader = true;
  3829. }
  3830. break;
  3831. case OPT_FILE_CMD_EXECUTE://1
  3832. {
  3833. if (type != FT_File)
  3834. {
  3835. ans.result = OPT_FILE_RES_INVALID;
  3836. ans.attachment2 = "非可打开或执行的文件类型(目录或其他)";
  3837. ans.attachment1 = ans.attachment2.GetLength();
  3838. break;
  3839. }
  3840. LPCTSTR lpParam = NULL;
  3841. if (req.attachment1 > 0 && req.attachment2.GetLength() > 0)
  3842. lpParam = req.attachment2;
  3843. #ifdef RVC_OS_LINUX
  3844. const DWORD dwRes = ExecuteFile(strCurrent, lpParam);
  3845. ans.result = dwRes ? OPT_FILE_RES_FAILED : OPT_FILE_RES_SUCCESS;
  3846. if (dwRes) {
  3847. ans.attachment2 = "不支持该操作";
  3848. ans.attachment1 = ans.attachment2.GetLength();
  3849. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  3850. }
  3851. #else
  3852. DWORD dwRes = ExecuteFile(strCurrent, lpParam);
  3853. if (!dwRes)
  3854. {
  3855. ans.result = OPT_FILE_RES_SUCCESS;
  3856. }
  3857. else
  3858. {
  3859. ans.result = OPT_FILE_RES_FAILED;
  3860. {
  3861. ans.attachment1 = GetErrorMessage(ans.attachment2, "执行文件操作失败。");
  3862. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("ExecuteFile failed: %s", (LPCTSTR)ans.attachment2);
  3863. }
  3864. }
  3865. #endif // RVC_OS_LINUX
  3866. }
  3867. break;
  3868. case OPT_FILE_CMD_DELETE: //2
  3869. case OPT_FILE_CMD_CLEAR: //3
  3870. {
  3871. #ifdef _MSC_VER
  3872. if (ctx->Req.mode == OPT_FILE_CMD_DELETE)
  3873. {
  3874. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("Delete flag.");
  3875. }
  3876. #endif // _MSC_VER
  3877. if (type == FT_Unknown)
  3878. {
  3879. ans.result = OPT_FILE_RES_INVALID;
  3880. ans.attachment2 = "所指定的文件不存在。";
  3881. ans.attachment1 = ans.attachment2.GetLength();
  3882. break;
  3883. }
  3884. bool bClear = !!(ctx->Req.mode == OPT_FILE_CMD_CLEAR);
  3885. #ifdef _MSC_VER
  3886. if (type == FT_Volume)
  3887. {
  3888. if (!bClear)
  3889. {
  3890. ans.result = OPT_FILE_RES_INVALID;
  3891. ans.attachment1 = strlen("该操作对卷类型的文件无效。");
  3892. ans.attachment2 = "该操作对卷类型的文件无效。";
  3893. }
  3894. else
  3895. {
  3896. if (ClearDirRecursiveEx(strCurrent))
  3897. {
  3898. ans.result = OPT_FILE_RES_SUCCESS;
  3899. bNeedToRefleshEntity = true;
  3900. }
  3901. else
  3902. {
  3903. ans.attachment1 = strlen("清空卷操作执行失败。");
  3904. ans.attachment2 = "清空卷操作执行失败。";
  3905. ans.result = OPT_FILE_RES_FAILED;
  3906. }
  3907. }
  3908. break;
  3909. }
  3910. #endif // _MSC_VER
  3911. if ((type == FT_Directory && ((!bClear && !RemoveDirRecursiveA(strCurrent))
  3912. || (bClear && !ClearDirRecursiveA(strCurrent))))
  3913. || (type == FT_File && !bClear && !RemoveFileA(strCurrent)))
  3914. {
  3915. ans.attachment1 = GetErrorMessage(ans.attachment2,
  3916. ((!bClear) ? "删除操作执行失败。" : "清空操作执行失败。"));
  3917. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("Delete(%d) or clear file failed: %s", !bClear, ans.attachment2.GetData());
  3918. ans.result = OPT_FILE_RES_FAILED;
  3919. break;
  3920. }
  3921. if (type == FT_File && bClear)
  3922. {//文件内容清理
  3923. //simple implement
  3924. FILE* stream;
  3925. SetLastError(0);
  3926. if ((stream = fopen(strCurrent, "w+")) == NULL)
  3927. {
  3928. ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
  3929. ans.result = OPT_FILE_RES_FAILED;
  3930. break;
  3931. }
  3932. else
  3933. {
  3934. if (fclose(stream))
  3935. {
  3936. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("fclose(%s) failed", (LPCTSTR)strCurrent);
  3937. ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
  3938. ans.result = OPT_FILE_RES_FAILED;
  3939. break;
  3940. }
  3941. }
  3942. }
  3943. ans.result = OPT_FILE_RES_SUCCESS;
  3944. bNeedToRefleshEntity = true;
  3945. if ((!bClear && type != FT_File) || (bClear && type == FT_File)) updateLevel = 1;
  3946. }
  3947. break;
  3948. case OPT_FILE_CMD_CREATE: //4
  3949. {
  3950. if (type != FT_Unknown)
  3951. {
  3952. if ((type == FT_Directory && (req.attribute & 0x10))
  3953. || (type == FT_File && !(req.attribute & 0x10))
  3954. || type == FT_Volume)
  3955. {
  3956. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("Existed file occurs create(%d) ?", type);
  3957. ans.result = OPT_FILE_RES_FAILED;
  3958. ans.attachment1 = strlen("目录或文件已存在。");
  3959. ans.attachment2 = "目录或文件已存在。";
  3960. break;
  3961. }
  3962. }
  3963. BOOL bRet = FALSE;
  3964. int depth = GetPathDepth(strCurrent);
  3965. if (depth <= 0)
  3966. {
  3967. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("Invalid file path(%s)", (LPCTSTR)strCurrent);
  3968. ans.result = OPT_FILE_RES_FAILED;
  3969. ans.attachment1 = strlen("非法文件路径或名称。");
  3970. ans.attachment2 = "非法文件路径或名称。";
  3971. break;
  3972. }
  3973. if (req.attribute & 0x10)
  3974. {
  3975. bRet = CreateDirA(strCurrent, TRUE);
  3976. if (!bRet)
  3977. {
  3978. ans.attachment1 = GetErrorMessage(ans.attachment2, "新建文件夹失败。");
  3979. ans.result = OPT_FILE_RES_FAILED;
  3980. break;
  3981. }
  3982. }
  3983. else
  3984. {
  3985. #ifdef RVC_OS_LINUX
  3986. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  3987. ans.attachment2 = "不支持操作";
  3988. ans.attachment1 = ans.attachment2.GetLength();
  3989. break;
  3990. #else
  3991. if (depth == 1/*根目录下创建文件*/ || CreateParentDirA(strCurrent, TRUE))
  3992. {
  3993. DWORD dwNewAttr = FILE_ATTRIBUTE_NORMAL/* | req.attribute*/;
  3994. HANDLE hNewFile = CreateFileA(strCurrent, GENERIC_WRITE,
  3995. 0, NULL, CREATE_NEW, dwNewAttr, NULL);
  3996. if (hNewFile == INVALID_HANDLE_VALUE)
  3997. {
  3998. ans.attachment1 = GetErrorMessage(ans.attachment2, "创建文件失败。");
  3999. ans.result = OPT_FILE_RES_FAILED;
  4000. break;
  4001. }
  4002. if (req.content.GetLength() >= 0)
  4003. {
  4004. DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
  4005. DWORD dwByteWritten = 0;
  4006. DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
  4007. LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  4008. BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
  4009. dwBytesToWrite, &dwByteWritten, NULL);
  4010. UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  4011. if (!bRes || dwByteWritten != dwBytesToWrite)
  4012. {
  4013. ans.attachment1 = GetErrorMessage(ans.attachment2,
  4014. !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
  4015. CloseHandle(hNewFile);
  4016. DeleteFileA(strCurrent);
  4017. ans.result = OPT_FILE_RES_FAILED;
  4018. break;
  4019. }
  4020. }
  4021. CloseHandle(hNewFile);
  4022. }
  4023. else
  4024. {
  4025. ans.attachment1 = GetErrorMessage(ans.attachment2, "创建目标文件所在目录失败。");
  4026. ans.result = OPT_FILE_RES_FAILED;
  4027. break;
  4028. }
  4029. #endif // RVC_OS_LINUX
  4030. }
  4031. ans.result = OPT_FILE_RES_SUCCESS;
  4032. bNeedToRefleshEntity = true;
  4033. updateLevel = 1;
  4034. }
  4035. break;
  4036. case OPT_FILE_CMD_APPEND: //5
  4037. {
  4038. #ifdef RVC_OS_LINUX
  4039. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  4040. ans.attachment2 = "不支持操作";
  4041. ans.attachment1 = ans.attachment2.GetLength();
  4042. #else
  4043. if (type != FT_File)
  4044. {
  4045. ans.result = OPT_FILE_RES_FAILED;
  4046. ans.attachment1 = strlen("目标文件不存在或非文件类型。");
  4047. ans.attachment2 = "目标文件不存在或非文件类型。";
  4048. break;
  4049. }
  4050. else if (req.content.GetLength() <= 0)
  4051. {
  4052. ans.result = OPT_FILE_RES_FAILED;
  4053. ans.attachment1 = strlen("写入的文件内容不存在。");
  4054. ans.attachment2 = "写入的文件内容不存在。";
  4055. break;
  4056. }
  4057. DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
  4058. DWORD dwByteWritten = 0;
  4059. HANDLE hNewFile = CreateFileA(strCurrent, FILE_APPEND_DATA,
  4060. FILE_SHARE_READ, NULL, /*OPEN_EXISTING*/OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  4061. if (hNewFile == INVALID_HANDLE_VALUE)
  4062. {
  4063. ans.attachment1 = GetErrorMessage(ans.attachment2, "打开文件失败。");
  4064. ans.result = OPT_FILE_RES_FAILED;
  4065. break;
  4066. }
  4067. DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
  4068. LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  4069. BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
  4070. dwBytesToWrite, &dwByteWritten, NULL);
  4071. UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  4072. if (!bRes || dwByteWritten != dwBytesToWrite)
  4073. {
  4074. ans.attachment1 = GetErrorMessage(ans.attachment2,
  4075. !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
  4076. ans.result = OPT_FILE_RES_FAILED;
  4077. CloseHandle(hNewFile);
  4078. DeleteFileA(strCurrent);
  4079. ans.result = OPT_FILE_RES_FAILED;
  4080. break;
  4081. }
  4082. CloseHandle(hNewFile);
  4083. ans.result = OPT_FILE_RES_SUCCESS;
  4084. bNeedToRefleshEntity = true;
  4085. updateLevel = 1;
  4086. #endif // RVC_OS_LINUX
  4087. }
  4088. break;
  4089. case OPT_FILE_CMD_RENAME: //6
  4090. {
  4091. #ifdef RVC_OS_LINUX
  4092. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  4093. ans.attachment2 = "不支持操作";
  4094. ans.attachment1 = ans.attachment2.GetLength();
  4095. #else
  4096. if (type == FT_Unknown || type == FT_Volume)
  4097. {
  4098. ans.result = OPT_FILE_RES_FAILED;
  4099. if (type == FT_Unknown)
  4100. {
  4101. ans.attachment1 = strlen("目标文件不存在。");
  4102. ans.attachment2 = "目标文件不存在。";
  4103. }
  4104. else
  4105. {
  4106. ans.attachment1 = strlen("文件类型(卷)不支持当前操作。");
  4107. ans.attachment2 = "文件类型(卷)不支持当前操作。";
  4108. }
  4109. break;
  4110. }
  4111. req.content = req.content.Trim();
  4112. if (req.content.GetLength() <= 0)
  4113. {
  4114. ans.result = OPT_FILE_RES_FAILED;
  4115. ans.attachment1 = strlen("传入新文件名参数为空。");
  4116. ans.attachment2 = "传入新文件名参数为空。";
  4117. break;
  4118. }
  4119. if (strchr(req.content, '\\') || strchr(req.content, '/'))
  4120. {
  4121. ans.result = OPT_FILE_RES_FAILED;
  4122. ans.attachment1 = strlen("新文件名参数无效。");
  4123. ans.attachment2 = "新文件名参数无效。";
  4124. break;
  4125. }
  4126. const size_t st_len = stCurLength + req.content.GetLength();
  4127. char* path = new char[st_len];
  4128. ZeroMemory(path, st_len);
  4129. int res = 0;
  4130. if (path == NULL)
  4131. {
  4132. LogWarn(Severity_Middle, Error_Resource, 0, "alloc path memory failed");
  4133. }
  4134. else
  4135. {
  4136. int dir_len = 0;
  4137. CSimpleStringA strNewName = req.content;
  4138. if ((dir_len = GetDirSplitPath(strCurrent, 1, path, st_len)) > 0)
  4139. {
  4140. if (!req.attribute && type == FT_File)
  4141. {
  4142. char tmp[MAX_PATH] = { 0 };
  4143. strcpy_s(tmp, strCurrent.GetData() + dir_len + 1);
  4144. char* pos = strrchr(tmp, '.');
  4145. if (pos) { strNewName += pos; }
  4146. }
  4147. strcat_s(path, st_len, "\\");
  4148. strcat_s(path, st_len, strNewName);
  4149. res = rename(strCurrent, path);
  4150. }
  4151. else
  4152. {
  4153. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("GetDirSplitPath failed: %s vs %s", (LPCTSTR)strCurrent, path);
  4154. }
  4155. delete[] path;
  4156. path = NULL;
  4157. }
  4158. if (res)
  4159. {
  4160. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("rename failed: %d", errno);
  4161. ans.result = OPT_FILE_RES_FAILED;
  4162. ans.attachment1 = strlen("重命名操作失败。");
  4163. ans.attachment2 = "重命名操作失败。";
  4164. break;
  4165. }
  4166. ans.result = OPT_FILE_RES_SUCCESS;
  4167. bNeedToRefleshEntity = true;
  4168. updateLevel = 1;
  4169. #endif // RVC_OS_LINUX
  4170. }
  4171. break;
  4172. default:
  4173. {
  4174. LogWarn(Severity_Low, Error_Unexpect, 0,
  4175. CSimpleStringA::Format("Unexpected file operation command : %d", ctx->Req.mode));
  4176. CSimpleStringA strTip = CSimpleStringA::Format("无法识别的操作指令(mode: %d)。", ctx->Req.mode);
  4177. ans.attachment1 = strTip.GetLength();
  4178. ans.attachment2 = strTip;
  4179. }
  4180. break;
  4181. }
  4182. if (ans.result == OPT_FILE_RES_SUCCESS)
  4183. {
  4184. if (bNeedToSetCtxEntities || bNeedToRefleshEntity)
  4185. {
  4186. bool bReInit = true;
  4187. if (bNeedToRefleshEntity)
  4188. {
  4189. DWORD dwCnt = 0;
  4190. CSimpleStringA strHeader = strCurrent;
  4191. if (updateLevel != 0)
  4192. {
  4193. char* pPath = new char[nCurLen + 1];
  4194. if (pPath == NULL) bReInit = false;
  4195. else
  4196. {
  4197. UINT uRes = GetDirSplitPath(strHeader, updateLevel, pPath, nCurLen + 1);
  4198. if (uRes == 0) bReInit = false;
  4199. strHeader = pPath;
  4200. delete[] pPath;
  4201. pPath = NULL;
  4202. }
  4203. }
  4204. if (bReInit)
  4205. {
  4206. bReInit = !!InitialFileEntity(strHeader, dwCnt);
  4207. }
  4208. bNeedToRefleshHeader = true;
  4209. }
  4210. if (bReInit)
  4211. {
  4212. ConveyFileEntityToContext(ctx, bNeedToRefleshHeader);
  4213. }
  4214. }
  4215. }
  4216. ctx->Answer(Error_Succeed);
  4217. return (ans.result);
  4218. }
  4219. DWORD ResourceWatcherFSM::ExecuteFile(LPCTSTR lpszFilePath, LPCTSTR lpParam)
  4220. {
  4221. DWORD dwRes = 0;
  4222. #ifdef _MSC_VER
  4223. SHELLEXECUTEINFOA shell;
  4224. memset(&shell, 0, sizeof(SHELLEXECUTEINFOA));
  4225. shell.cbSize = sizeof(SHELLEXECUTEINFOA);
  4226. shell.lpFile = lpszFilePath;
  4227. shell.lpParameters = lpParam;
  4228. shell.fMask = SEE_MASK_INVOKEIDLIST;
  4229. shell.lpVerb = NULL;
  4230. shell.nShow = SW_SHOWDEFAULT;
  4231. if (!ShellExecuteExA(&shell))
  4232. {
  4233. dwRes = GetLastError();
  4234. int nRes = (int)shell.hInstApp;
  4235. Dbg("GLE=%u, InstApp=%d", dwRes, nRes);
  4236. switch (dwRes) {
  4237. case ERROR_NO_ACE_CONDITION:
  4238. LogWarn(Severity_Middle, Error_MethodNotFound, dwRes,
  4239. CSimpleStringA::Format("Target file(%s) association not available !", lpszFilePath));
  4240. break;
  4241. case ERROR_ACCESS_DENIED:
  4242. LogWarn(Severity_Middle, Error_NoPrivilege, dwRes,
  4243. CSimpleStringA::Format("Target file(%s) not privilege !", lpszFilePath));
  4244. break;
  4245. case ERROR_PATH_NOT_FOUND:
  4246. case ERROR_FILE_NOT_FOUND:
  4247. LogWarn(Severity_Middle, Error_NotExist, dwRes,
  4248. CSimpleStringA::Format("Target file(%s) not existed !", lpszFilePath));
  4249. break;
  4250. case ERROR_DLL_NOT_FOUND:
  4251. LogWarn(Severity_Middle, Error_NotExist, dwRes,
  4252. CSimpleStringA::Format("One of library file for Target(%s) not existed !", lpszFilePath));
  4253. break;
  4254. case ERROR_NOT_ENOUGH_MEMORY:
  4255. LogWarn(Severity_Middle, Error_Resource, dwRes,
  4256. CSimpleStringA::Format("Not enough memory for Target(%s) to perform !", lpszFilePath));
  4257. break;
  4258. case ERROR_SHARING_VIOLATION:
  4259. LogWarn(Severity_Middle, Error_Overflow, dwRes,
  4260. CSimpleStringA::Format("Violation occurred for Target(%s) to share !", lpszFilePath));
  4261. break;
  4262. default:
  4263. LogWarn(Severity_Middle, Error_Unexpect, dwRes,
  4264. CSimpleStringA::Format("Unpected condtion for Target(%s) to execute(%u) !"
  4265. , lpszFilePath, dwRes));
  4266. break;
  4267. }
  4268. }
  4269. #else
  4270. dwRes = 1;
  4271. #endif //_MSC_VER
  4272. return dwRes;
  4273. }
  4274. BOOL ResourceWatcherFSM::ConveyFileEntityToContext(
  4275. const SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  4276. ResourceWatcherService_OperateFile_Ans>::Pointer & ctx
  4277. , BOOL bRefleshHeader /*= FALSE*/, DWORD dwFilterAttributes)
  4278. {
  4279. if (ctx == NULL) return FALSE;
  4280. #ifdef _MSC_VER
  4281. ULARGE_INTEGER ilOffsetSize;
  4282. ilOffsetSize.QuadPart = 0;
  4283. const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
  4284. DWORD dwInheritForbidAttrs = 0UL;
  4285. if (bRefleshHeader) {
  4286. if (m_FileEntry.Current.mNameLength != 0) {
  4287. ilOffsetSize.LowPart = m_FileEntry.Current.mNameOffset;
  4288. ilOffsetSize.HighPart = m_FileEntry.Current.mNameLength;
  4289. GetSubFileName(m_FileEntry.FileNamesBuffer,
  4290. dwBufSize, ctx->Ans.header, &ilOffsetSize);
  4291. ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
  4292. ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
  4293. ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
  4294. ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
  4295. ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
  4296. if (!ctx->Ans.header.IsNullOrEmpty() && ctx->Ans.header.GetLength() > 0) {
  4297. if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
  4298. dwInheritForbidAttrs |= BS_DENY_DELETE;
  4299. Dbg("header-forbit:%s", ctx->Ans.header.GetData());
  4300. }
  4301. }
  4302. }
  4303. }
  4304. int count = m_FileEntry.SubFiles.GetCount();
  4305. int minusCount = 0;
  4306. for (int i = 0; i < count; ++i)
  4307. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
  4308. minusCount++;
  4309. count = count - minusCount;
  4310. ctx->Ans.count = count;
  4311. if (count > 0) {
  4312. if (count >= MAX_SUBFILES_COUNT) {
  4313. Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
  4314. std::vector<CSimpleFileShell> vtFileShells;
  4315. for (int i = 0; i < count; ++i) {
  4316. CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
  4317. vtFileShells.push_back(item);
  4318. }
  4319. sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
  4320. char szFormat[128] = { 0 };
  4321. count = MAX_SUBFILES_COUNT;
  4322. ctx->Ans.count = count;
  4323. ctx->Ans.fileAttributes.Init(count);
  4324. ctx->Ans.fileNames.Init(count);
  4325. ctx->Ans.ftCreates.Init(count);
  4326. ctx->Ans.ftModifieds.Init(count);
  4327. ctx->Ans.ftAccesses.Init(count);
  4328. ctx->Ans.fileSizes.Init(count);
  4329. ctx->Ans.forbidAttributes.Init(count);
  4330. ctx->Ans.reserved1.Init(count);
  4331. ctx->Ans.reserved2.Init(count);
  4332. for (int i = 0; i < count; ++i) {
  4333. CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
  4334. ilOffsetSize.LowPart = component->mNameOffset;
  4335. ilOffsetSize.HighPart = component->mNameLength;
  4336. if (component->mAttributes & dwFilterAttributes) {
  4337. CSimpleStringA strFileName;
  4338. GetSubFileName(m_FileEntry.FileNamesBuffer,
  4339. dwBufSize, strFileName, &ilOffsetSize);
  4340. Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
  4341. continue;
  4342. }
  4343. ctx->Ans.reserved1[i] = 0;
  4344. ctx->Ans.reserved2[i] = "";
  4345. ctx->Ans.fileAttributes[i] = component->mAttributes;
  4346. ctx->Ans.ftCreates[i] = component->mftCreate;
  4347. ctx->Ans.ftModifieds[i] = component->mftModified;
  4348. ctx->Ans.ftAccesses[i] = component->mftAccess;
  4349. ctx->Ans.fileSizes[i] = component->mFileSize;
  4350. //TODO: Need to judge whether need to calculate size of directory.
  4351. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  4352. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  4353. ctx->Ans.forbidAttributes[i] = 0;
  4354. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  4355. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4356. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  4357. CSimpleStringA csFilePath;
  4358. GetFullFilePath(&m_FileEntry, i, csFilePath);
  4359. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  4360. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4361. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  4362. }
  4363. }
  4364. }
  4365. vtFileShells.clear();
  4366. } else {
  4367. ctx->Ans.fileAttributes.Init(count);
  4368. ctx->Ans.fileNames.Init(count);
  4369. ctx->Ans.ftCreates.Init(count);
  4370. ctx->Ans.ftModifieds.Init(count);
  4371. ctx->Ans.ftAccesses.Init(count);
  4372. ctx->Ans.fileSizes.Init(count);
  4373. ctx->Ans.forbidAttributes.Init(count);
  4374. ctx->Ans.reserved1.Init(count);
  4375. ctx->Ans.reserved2.Init(count);
  4376. for (int i = 0; i < count; ++i) {
  4377. ilOffsetSize.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
  4378. ilOffsetSize.HighPart = m_FileEntry.SubFiles[i].mNameLength;
  4379. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
  4380. CSimpleStringA strFileName;
  4381. GetSubFileName(m_FileEntry.FileNamesBuffer,
  4382. dwBufSize, strFileName, &ilOffsetSize);
  4383. Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
  4384. continue;
  4385. }
  4386. ctx->Ans.reserved1[i] = 0;
  4387. ctx->Ans.reserved2[i] = "";
  4388. ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
  4389. ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
  4390. ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
  4391. ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
  4392. ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
  4393. //TODO: Need to judge whether need to calculate size of directory.
  4394. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  4395. ctx->Ans.forbidAttributes[i] = 0;
  4396. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  4397. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  4398. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4399. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  4400. CSimpleStringA csFilePath;
  4401. GetFullFilePath(&m_FileEntry, i, csFilePath);
  4402. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  4403. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4404. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  4405. }
  4406. }
  4407. }
  4408. }
  4409. }
  4410. #else
  4411. ULARGE_INTEGER ilOffsetSize;
  4412. ilOffsetSize.QuadPart = 0;
  4413. const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
  4414. DWORD dwInheritForbidAttrs = 0UL;
  4415. if (bRefleshHeader) {
  4416. if (m_FileEntry.Current.mNameLength != 0) {
  4417. ilOffsetSize.u.LowPart = m_FileEntry.Current.mNameOffset;
  4418. ilOffsetSize.u.HighPart = m_FileEntry.Current.mNameLength;
  4419. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.header, &ilOffsetSize);
  4420. ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
  4421. ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
  4422. ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
  4423. ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
  4424. ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
  4425. if (!ctx->Ans.header.IsNullOrEmpty()) {
  4426. if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
  4427. dwInheritForbidAttrs |= BS_DENY_DELETE;
  4428. Dbg("header-forbit:%s", ctx->Ans.header.GetData());
  4429. }
  4430. }
  4431. }
  4432. }
  4433. int count = m_FileEntry.SubFiles.GetCount();
  4434. int minusCount = 0;
  4435. for (int i = 0; i < count; ++i)
  4436. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
  4437. minusCount++;
  4438. count = count - minusCount;
  4439. ctx->Ans.count = count;
  4440. if (count > 0) {
  4441. if (count >= MAX_SUBFILES_COUNT) {
  4442. Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
  4443. std::vector<CSimpleFileShell> vtFileShells;
  4444. for (int i = 0; i < count; ++i) {
  4445. CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
  4446. vtFileShells.push_back(item);
  4447. }
  4448. sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
  4449. char szFormat[128] = { 0 };
  4450. count = MAX_SUBFILES_COUNT;
  4451. ctx->Ans.count = count;
  4452. ctx->Ans.reserved1.Init(count);
  4453. ctx->Ans.reserved2.Init(count);
  4454. ctx->Ans.fileAttributes.Init(count);
  4455. ctx->Ans.fileNames.Init(count);
  4456. ctx->Ans.ftCreates.Init(count);
  4457. ctx->Ans.ftModifieds.Init(count);
  4458. ctx->Ans.ftAccesses.Init(count);
  4459. ctx->Ans.fileSizes.Init(count);
  4460. ctx->Ans.forbidAttributes.Init(count);
  4461. for (int i = 0; i < count; ++i) {
  4462. CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
  4463. ilOffsetSize.u.LowPart = component->mNameOffset;
  4464. ilOffsetSize.u.HighPart = component->mNameLength;
  4465. if (component->mAttributes & dwFilterAttributes) {
  4466. CSimpleStringA strFileName;
  4467. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, strFileName, &ilOffsetSize);
  4468. Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
  4469. continue;
  4470. }
  4471. ctx->Ans.reserved1[i] = 0;
  4472. ctx->Ans.reserved2[i] = "";
  4473. ctx->Ans.fileAttributes[i] = component->mAttributes;
  4474. ctx->Ans.ftCreates[i] = component->mftCreate;
  4475. ctx->Ans.ftModifieds[i] = component->mftModified;
  4476. ctx->Ans.ftAccesses[i] = component->mftAccess;
  4477. ctx->Ans.fileSizes[i] = component->mFileSize;
  4478. //TODO: Need to judge whether need to calculate size of directory.
  4479. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  4480. ctx->Ans.forbidAttributes[i] = 0;
  4481. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  4482. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  4483. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4484. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  4485. CSimpleStringA csFilePath;
  4486. GetFullFilePath(&m_FileEntry, i, csFilePath);
  4487. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  4488. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4489. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  4490. }
  4491. }
  4492. }
  4493. vtFileShells.clear();
  4494. } else {
  4495. ctx->Ans.fileAttributes.Init(count);
  4496. ctx->Ans.fileNames.Init(count);
  4497. ctx->Ans.ftCreates.Init(count);
  4498. ctx->Ans.ftModifieds.Init(count);
  4499. ctx->Ans.ftAccesses.Init(count);
  4500. ctx->Ans.fileSizes.Init(count);
  4501. ctx->Ans.forbidAttributes.Init(count);
  4502. ctx->Ans.reserved1.Init(count);
  4503. ctx->Ans.reserved2.Init(count);
  4504. for (int i = 0; i < count; ++i) {
  4505. ilOffsetSize.u.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
  4506. ilOffsetSize.u.HighPart = m_FileEntry.SubFiles[i].mNameLength;
  4507. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
  4508. CSimpleStringA strFileName;
  4509. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, strFileName, &ilOffsetSize);
  4510. Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
  4511. continue;
  4512. }
  4513. ctx->Ans.reserved1[i] = 0;
  4514. ctx->Ans.reserved2[i] = "";
  4515. ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
  4516. ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
  4517. ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
  4518. ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
  4519. ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
  4520. //TODO: Need to judge whether need to calculate size of directory.
  4521. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  4522. ctx->Ans.forbidAttributes[i] = 0;
  4523. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  4524. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  4525. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4526. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  4527. CSimpleStringA csFilePath;
  4528. GetFullFilePath(&m_FileEntry, i, csFilePath);
  4529. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  4530. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  4531. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  4532. }
  4533. }
  4534. }
  4535. }
  4536. }
  4537. #endif //_MSC_VER
  4538. //Free action for saving memory.
  4539. m_FileEntry.SubFiles.Clear();
  4540. m_FileEntry.FileNamesBuffer.Clear();
  4541. m_FileEntry.Current.Clear();
  4542. return TRUE;
  4543. }
  4544. int ResourceWatcherFSM::FilterFilePathAhead(LPCTSTR lpszPath, const int option)
  4545. {
  4546. #ifdef RVC_OS_LINUX
  4547. size_t len = strlen(lpszPath);
  4548. if (lpszPath[0] != '/') {
  4549. Dbg("illegal disk format path !");
  4550. return -2;
  4551. }
  4552. char* path = new char[len + 1];
  4553. LOG_ASSERT(path != NULL);
  4554. memset(path, 0, sizeof(char) * (len + 1));
  4555. memcpy(path, lpszPath, len);
  4556. path[len] = '\0';
  4557. int pos = len - 1;
  4558. for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos) {
  4559. ;//
  4560. }
  4561. path[pos + 1] = '\0';
  4562. len = strlen(path);
  4563. if (len < 1) {
  4564. delete[] path;
  4565. return -1;
  4566. }
  4567. else if (len == 1 && option == OPT_FILE_CMD_DELETE) {
  4568. /*disk volumn to delete*/
  4569. delete[] path;
  4570. return 1;
  4571. }
  4572. if (InBlackListOrNot(path, option)) {
  4573. delete[] path;
  4574. return 2;
  4575. }
  4576. delete[] path;
  4577. return 0;
  4578. #else
  4579. if (lpszPath == NULL || strlen(lpszPath) <= 1)
  4580. return -1;
  4581. size_t len = strlen(lpszPath);
  4582. if (!((lpszPath[0] <= 'z' && lpszPath[0] >= 'a') || (lpszPath[0] <= 'Z' && lpszPath[0] >= 'A'))
  4583. || lpszPath[1] != ':')
  4584. {
  4585. return -2;
  4586. }
  4587. {
  4588. char disk = lpszPath[0];
  4589. if (disk >= 'a' && disk <= 'z') disk -= 32;
  4590. int diskNo = disk - 'A';
  4591. if (!sBDiskValStatus[diskNo])
  4592. {
  4593. return -3;
  4594. }
  4595. }
  4596. char* path = new char[len + 1];
  4597. LOG_ASSERT(path != NULL);
  4598. memset(path, 0, sizeof(char) * (len + 1));
  4599. memcpy(path, lpszPath, len);
  4600. path[len] = '\0';
  4601. int pos = len - 1;
  4602. for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos)
  4603. {
  4604. ;//
  4605. }
  4606. path[pos + 1] = '\0';
  4607. len = strlen(path);
  4608. if (len <= 1)
  4609. {
  4610. delete[] path;
  4611. return -1;
  4612. }
  4613. else if (len == 2)
  4614. {
  4615. if (option == 2)
  4616. {
  4617. delete[] path;
  4618. return 1;
  4619. }
  4620. }
  4621. if (InBlackSheet(path, option))
  4622. {
  4623. delete[] path;
  4624. return 2;
  4625. }
  4626. delete[] path;
  4627. return 0;
  4628. #endif // RVC_OS_LINUX
  4629. }
  4630. BOOL ResourceWatcherFSM::InBlackListOrNot(LPCTSTR lpszPath, const int option)
  4631. {
  4632. BOOL bForbidden = FALSE;
  4633. LOG_ASSERT(lpszPath != NULL && strlen(lpszPath) != 0);
  4634. DWORD dwRequredAttr = 0;
  4635. switch (option)
  4636. {
  4637. case OPT_FILE_CMD_SPREAD:
  4638. dwRequredAttr |= BS_DENY_READ;
  4639. break;
  4640. case OPT_FILE_CMD_EXECUTE:
  4641. dwRequredAttr |= BS_DENY_EXECUTE;
  4642. break;
  4643. case OPT_FILE_CMD_CREATE:
  4644. dwRequredAttr |= BS_DENY_CREATE;
  4645. break;
  4646. case OPT_FILE_CMD_DELETE:
  4647. case OPT_FILE_CMD_CLEAR:
  4648. case OPT_FILE_CMD_RENAME:
  4649. dwRequredAttr |= BS_DENY_DELETE;
  4650. break;
  4651. case OPT_FILE_CMD_APPEND:
  4652. dwRequredAttr |= BS_DENY_MODIFY;
  4653. break;
  4654. default:
  4655. return bForbidden;
  4656. break;
  4657. }
  4658. const size_t len = strlen(lpszPath);
  4659. char* temp_path = new char[len + 1];
  4660. if (temp_path == NULL) {
  4661. return bForbidden;
  4662. }
  4663. memset(temp_path, 0, sizeof(char) * (len + 1));
  4664. strcpy_s(temp_path, len + 1, lpszPath);
  4665. for (size_t i = 0; i < len; ++i) {
  4666. if (temp_path[i] == '\\')
  4667. temp_path[i] = '/';
  4668. }
  4669. lpszPath = temp_path;
  4670. for (const_bs_iter cit = m_forbidDirList.cbegin(); cit != m_forbidDirList.cend() && !bForbidden; ++cit)
  4671. {
  4672. const bs_key& path = cit->first;
  4673. const bs_value& resist = cit->second;
  4674. const size_t n = strlen(path.c_str());
  4675. if (dwRequredAttr & resist)
  4676. {
  4677. if (path[0] == '*')
  4678. {
  4679. bForbidden = TRUE;
  4680. break;
  4681. }
  4682. if (!_strnicmp(lpszPath, path.c_str(), min(len, n)))
  4683. {
  4684. if (len > n
  4685. && (lpszPath[n] == '\\' || lpszPath[n] == '/')
  4686. && (resist & BS_DENY_INHERITED))
  4687. {
  4688. bForbidden = TRUE;
  4689. }
  4690. if (len == n)
  4691. {
  4692. bForbidden = TRUE;
  4693. }
  4694. if (len < n)
  4695. {
  4696. FileType ft;
  4697. if (IsPathExisted(path.c_str(), ft))
  4698. {
  4699. bForbidden = TRUE;
  4700. }
  4701. }
  4702. }
  4703. }
  4704. }
  4705. if (temp_path) {
  4706. delete[] temp_path;
  4707. temp_path = NULL;
  4708. }
  4709. return bForbidden;
  4710. }
  4711. void ResourceWatcherFSM::InitBlackList()
  4712. {
  4713. #ifdef RVC_OS_LINUX
  4714. LOG_FUNCTION();
  4715. m_forbidDirList.clear();
  4716. DWORD dwDenyAttr;
  4717. CSimpleStringA strPath;
  4718. if (GetEntityBase()->GetFunction()->GetPath("UploadVideo", strPath) == Error_Succeed) {
  4719. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4720. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4721. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  4722. }
  4723. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4724. if (GetEntityBase()->GetFunction()->GetPath("UploadPhoto", strPath) == Error_Succeed) {
  4725. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4726. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4727. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  4728. }
  4729. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4730. if (GetEntityBase()->GetFunction()->GetPath("Cfg", strPath) == Error_Succeed) {
  4731. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4732. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4733. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  4734. }
  4735. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4736. if (GetEntityBase()->GetFunction()->GetPath("Dep", strPath) == Error_Succeed) {
  4737. dwDenyAttr = BS_DENY_DELETE | BS_DENY_CREATE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  4738. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4739. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  4740. }
  4741. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4742. if (GetEntityBase()->GetFunction()->GetPath("Base", strPath) == Error_Succeed) {
  4743. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4744. dwDenyAttr = BS_DENY_DELETE | BS_DENY_EXECUTE | BS_DENY_INHERITED;
  4745. const size_t len = strPath.GetLength();
  4746. char* path = new char[len + 1];
  4747. //Run Directory
  4748. if (path && (ZeroMemory(path, len + 1), GetDirSplitPath(strPath, 2, path, len + 1) > 0)) {
  4749. //Dbg("Add %s - 0x%X", path, dwDenyAttr);
  4750. //m_forbidDirList[string(path)] = dwDenyAttr;
  4751. }
  4752. if (path) {
  4753. strPath = path;
  4754. delete[] path;
  4755. }
  4756. CSimpleStringA strPathInner;
  4757. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4758. strPathInner = strPath + SPLIT_SLASH_STR + "hardwarecfg";
  4759. dwDenyAttr = BS_DENY_DELETE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  4760. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4761. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  4762. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4763. strPathInner = strPath + SPLIT_SLASH_STR + "runinfo" + SPLIT_SLASH_STR + "kmc";
  4764. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4765. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4766. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  4767. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4768. strPathInner = strPath + SPLIT_SLASH_STR + "version";
  4769. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4770. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4771. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  4772. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4773. dwDenyAttr = BS_DENY_MODIFY;
  4774. strPathInner = strPath + SPLIT_SLASH_STR + "version" + SPLIT_SLASH_STR + "active.txt";
  4775. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4776. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  4777. }
  4778. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  4779. #else
  4780. m_blacksheet.clear();
  4781. #define INFO_BUFFER_SIZE MAX_PATH
  4782. char infoBuf[INFO_BUFFER_SIZE];
  4783. DWORD bufCharCount = INFO_BUFFER_SIZE;
  4784. char sys_disk = '\0';
  4785. bufCharCount = INFO_BUFFER_SIZE;
  4786. if (!GetComputerName(infoBuf, &bufCharCount))
  4787. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetComputerName failed, GLE=%u", GetLastError());
  4788. else DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Computer name: %s", infoBuf);
  4789. // Get and display the user name.
  4790. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  4791. bufCharCount = INFO_BUFFER_SIZE;
  4792. if (!GetUserName(infoBuf, &bufCharCount)) {
  4793. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetUserName failed, GLE=%u", GetLastError());
  4794. curUserName.Clear();
  4795. }
  4796. else {
  4797. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("User name: %s", infoBuf);
  4798. curUserName = infoBuf;
  4799. }
  4800. DWORD dwDenyAttr;
  4801. // All file cannot be executed !! -Josephus@2017612 9:29:01
  4802. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  4803. infoBuf[0] = '*', infoBuf[1] = '\0';
  4804. dwDenyAttr = BS_DENY_EXECUTE | BS_DENY_INHERITED;
  4805. m_blacksheet.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  4806. // Get and display the system directory.
  4807. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  4808. if (!GetSystemDirectory(infoBuf, INFO_BUFFER_SIZE))
  4809. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDirectory failed, GLE=%u", GetLastError());
  4810. else
  4811. {
  4812. dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  4813. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add System Directory: %s - 0x%X", infoBuf, dwDenyAttr);
  4814. m_blacksheet.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  4815. sys_disk = infoBuf[0];
  4816. if (sys_disk >= 'a' && sys_disk <= 'z') sys_disk -= 32;
  4817. int diskNo = sys_disk - 'A';
  4818. LOG_ASSERT(sBDiskValStatus[diskNo]);
  4819. sBDiskValStatus[diskNo] = sBDiskValStatus[diskNo] + 2; //Set system disk flag
  4820. }
  4821. // Get and display the Windows directory.
  4822. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  4823. if (!GetWindowsDirectory(infoBuf, INFO_BUFFER_SIZE))
  4824. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetWindowsDirectory failed, GLE=%u", GetLastError());
  4825. else
  4826. {
  4827. dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  4828. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add Windows Directory: %s - 0x%X", infoBuf, dwDenyAttr);
  4829. m_blacksheet.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  4830. }
  4831. if (sys_disk != '\0')
  4832. {
  4833. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  4834. //////////////////////////////////////////////////////////////////////////
  4835. LOG_ASSERT(INFO_BUFFER_SIZE > 4);
  4836. infoBuf[0] = sys_disk;
  4837. infoBuf[1] = ':';
  4838. infoBuf[2] = '\\';
  4839. infoBuf[3] = '\0';
  4840. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Start to Add system limited path: %d", LIMITED_SYS_COUNT);
  4841. const DWORD dwSysAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  4842. for (int i = 0; i < LIMITED_SYS_COUNT; ++i)
  4843. {
  4844. string strfullPath = infoBuf;
  4845. strfullPath += LIMITED_SYS_PATH(i);
  4846. if (m_blacksheet.find(strfullPath) == m_blacksheet.end())
  4847. {
  4848. m_blacksheet[strfullPath] = dwSysAttr;
  4849. }
  4850. }
  4851. }
  4852. //////////////////////////////////////////////////////////////////////////
  4853. CSimpleStringA strPath;
  4854. if (GetEntityBase()->GetFunction()->GetPath("UploadVideo", strPath) == Error_Succeed)
  4855. {
  4856. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4857. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4858. m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
  4859. }
  4860. if (GetEntityBase()->GetFunction()->GetPath("UploadPhoto", strPath) == Error_Succeed)
  4861. {
  4862. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4863. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4864. m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
  4865. }
  4866. if (GetEntityBase()->GetFunction()->GetPath("Cfg", strPath) == Error_Succeed)
  4867. {
  4868. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4869. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4870. m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
  4871. }
  4872. if (GetEntityBase()->GetFunction()->GetPath("Dep", strPath) == Error_Succeed)
  4873. {
  4874. dwDenyAttr = BS_DENY_DELETE | BS_DENY_CREATE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  4875. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  4876. m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
  4877. }
  4878. if (GetEntityBase()->GetFunction()->GetPath("Base", strPath) == Error_Succeed)
  4879. {
  4880. dwDenyAttr = BS_DENY_DELETE | BS_DENY_EXECUTE | BS_DENY_INHERITED;
  4881. const size_t len = strPath.GetLength();
  4882. char* path = new char[len + 1];
  4883. //Run Directory
  4884. if (path && (ZeroMemory(path, len + 1), GetDirSplitPath(strPath, 2, path, len + 1) > 0))
  4885. {
  4886. }
  4887. if (path)
  4888. {
  4889. strPath = path;
  4890. //
  4891. delete[] path;
  4892. }
  4893. CSimpleStringA strPathInner;
  4894. strPathInner = strPath + "\\hardwarecfg";
  4895. dwDenyAttr = BS_DENY_DELETE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  4896. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4897. m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
  4898. strPathInner = strPath + "\\runinfo\\kmc";
  4899. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4900. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4901. m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
  4902. strPathInner = strPath + "\\version";
  4903. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  4904. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4905. m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
  4906. dwDenyAttr = BS_DENY_MODIFY;
  4907. strPathInner = strPath + "\\version\\active.txt";
  4908. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  4909. m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
  4910. }
  4911. #endif // RVC_OS_LINUX
  4912. }
  4913. #ifdef _MSC_VER
  4914. BOOL ResourceWatcherFSM::ClearDirRecursiveEx(LPCSTR lpDirPath)
  4915. {
  4916. int len = strlen(lpDirPath);
  4917. if (lpDirPath == NULL || len == 0)
  4918. return FALSE;
  4919. if (len + 2 >= MAX_PATH)
  4920. {
  4921. return FALSE;
  4922. }
  4923. char* path = new char[MAX_PATH];
  4924. if (path == NULL) return FALSE;
  4925. memset(path, 0, sizeof(path));
  4926. strcpy_s(path, MAX_PATH, lpDirPath);
  4927. int pos = len - 1;
  4928. for (; pos >= 0 && (path[pos] == '/' || path[pos] == '\\'); --pos)
  4929. path[pos] = '\0';
  4930. path[pos + 1] = '\0';
  4931. strcat_s(path, MAX_PATH, "\\*");
  4932. len = strlen(path);
  4933. char tempFilePath[MAX_PATH];
  4934. ZeroMemory(tempFilePath, MAX_PATH);
  4935. WIN32_FIND_DATA wfd;
  4936. HANDLE hFind;
  4937. hFind = FindFirstFile(path, &wfd);
  4938. if (hFind == INVALID_HANDLE_VALUE)
  4939. {
  4940. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FindFirstFile failed GLE = %u.", GetLastError());
  4941. delete[] path;
  4942. return FALSE;
  4943. }
  4944. BOOL bResult = TRUE;
  4945. do
  4946. {
  4947. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  4948. {
  4949. if (wfd.cFileName[0] != '.')
  4950. {
  4951. strcpy_s(tempFilePath, path);
  4952. tempFilePath[len - 1] = '\0';
  4953. if (len + strlen(wfd.cFileName) > MAX_PATH)
  4954. {
  4955. bResult = FALSE;
  4956. break;
  4957. }
  4958. else
  4959. {
  4960. strcat_s(tempFilePath, wfd.cFileName);
  4961. if (!RemoveDirRecursiveA(tempFilePath))
  4962. {
  4963. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RemoveDirRecursiveA(%s) failed", tempFilePath);
  4964. bResult = FALSE;
  4965. break;
  4966. }
  4967. }
  4968. }
  4969. }
  4970. else
  4971. {
  4972. strcpy_s(tempFilePath, path);
  4973. tempFilePath[len - 1] = '\0';
  4974. strcat_s(tempFilePath, wfd.cFileName);
  4975. if (!RemoveFileA(tempFilePath))
  4976. {
  4977. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RemoveFileA(%s) failed", tempFilePath);
  4978. bResult = FALSE;
  4979. break;
  4980. }
  4981. }
  4982. } while (FindNextFileA(hFind, &wfd));
  4983. FindClose(hFind);
  4984. if (path) delete[] path;
  4985. return bResult;
  4986. }
  4987. DWORD ResourceWatcherFSM::GetEventLog(SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req,
  4988. ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
  4989. {
  4990. LOG_FUNCTION();
  4991. CHAR szEvtFile[MAX_PATH] = { 0 };
  4992. memset(szEvtFile, 0, sizeof(CHAR) * MAX_PATH);
  4993. if (!CombineTheEvtxFileName(m_strTerminalNo, szEvtFile)) {
  4994. ctx->Ans.entries = 0;
  4995. ctx->Ans.information = "初始化事件日志文件名失败";
  4996. ctx->Answer(Error_Succeed);
  4997. if (ExistsFileA(szEvtFile)) {
  4998. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
  4999. }
  5000. return 0;
  5001. }
  5002. EVENTLOGPARAM filterParam = { 0 };
  5003. filterParam.wEventType = ctx->Req.evtLevel == 0x00FF ? 0 : ctx->Req.evtLevel;
  5004. BOOL bResult = TRUE;
  5005. DWORD dwResult = ERROR_SUCCESS;
  5006. if (ctx->Req.duration == DURAITON_CUSTOM) {
  5007. ULONGLONG ullStart = ctx->Req.startTime;
  5008. ULONGLONG ullEnd = ctx->Req.endTime;
  5009. dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
  5010. &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), &ullStart, &ullEnd);
  5011. }
  5012. else {
  5013. dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
  5014. &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), NULL, NULL);
  5015. }
  5016. if (dwResult != ERROR_SUCCESS) {
  5017. ctx->Ans.entries = 0;
  5018. ctx->Ans.information = "时间筛选参数错误";
  5019. ctx->Answer(Error_Succeed);
  5020. return 0;
  5021. }
  5022. if (!ctx->Req.evtSrcEventName.IsNullOrEmpty()) {
  5023. #ifdef WIDE_CONDITION
  5024. CSimpleStringW wSrvEventName = CSimpleStringA2W(ctx->Req.evtSrcEventName);
  5025. wcscpy_s(filterParam.lpszSourceEventName, wSrvEventName);
  5026. #else
  5027. strcpy_s(filterParam.lpszSourceEventName, ctx->Req.evtSrcEventName);
  5028. #endif
  5029. }
  5030. DWORD dwEntries = 0;
  5031. WORD wEventTypeMask = ctx->Req.evtName == 0 ? 0x00FF : ctx->Req.evtName;
  5032. if ((wEventTypeMask & 0x0001) == 0x0001) {
  5033. DWORD dwRes = 0;
  5034. filterParam.fApplication = TRUE;
  5035. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  5036. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve application event log returned: %u",
  5037. bResult ? "Success" : "Failed", dwRes);
  5038. if (bResult) {
  5039. dwEntries += dwRes;
  5040. }
  5041. filterParam.fApplication = FALSE;
  5042. }
  5043. if ((wEventTypeMask & 0x0002) == 0x0002) {
  5044. DWORD dwRes = 0;
  5045. filterParam.fSecurity = TRUE;
  5046. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  5047. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve security event log returned: %u",
  5048. bResult ? "Success" : "Failed", dwRes);
  5049. if (bResult) {
  5050. dwEntries += dwRes;
  5051. }
  5052. filterParam.fSecurity = FALSE;
  5053. }
  5054. if ((wEventTypeMask & 0x0008) == 0x0008) {
  5055. DWORD dwRes = 0;
  5056. filterParam.fSystem = TRUE;
  5057. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  5058. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve system event log returned: %u",
  5059. bResult ? "Success" : "Failed", dwRes);
  5060. if (bResult) {
  5061. dwEntries += dwRes;
  5062. }
  5063. filterParam.fSystem = FALSE;
  5064. }
  5065. if ((wEventTypeMask & 0x0100) == 0x0100) {
  5066. DWORD dwRes = 0;
  5067. filterParam.fCustom = TRUE;
  5068. if (!ctx->Req.cusEvtFileName.IsNullOrEmpty()) {
  5069. #ifdef WIDE_CONDITION
  5070. CSimpleStringW strwFileName = CSimpleStringA2W(ctx->Req.cusEvtFileName);
  5071. wcscpy_s(filterParam.lpszCustomEventName, strwFileName);
  5072. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Custom event log path: %s", ctx->Req.cusEvtFileName);
  5073. #else
  5074. strcpy_s(filterParam.lpszCustomEventName, ctx->Req.cusEvtFileName);
  5075. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Custom event log path: %s", filterParam.lpszCustomEventName);
  5076. #endif
  5077. }
  5078. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  5079. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve custom event log returned: %u",
  5080. bResult ? "Success" : "Failed", dwRes);
  5081. if (bResult) {
  5082. dwEntries += dwRes;
  5083. }
  5084. filterParam.fCustom = FALSE;
  5085. }
  5086. if (dwEntries == 0) {
  5087. ctx->Ans.entries = 0;
  5088. LogWarn(Severity_Middle, Error_Unexpect, 0, "The Count of event log is Zero!");
  5089. ctx->Ans.information = "未找到相关的系统事件日志";
  5090. if (ExistsFileA(szEvtFile)) {
  5091. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
  5092. }
  5093. }
  5094. else {
  5095. ctx->Ans.entries = dwEntries;
  5096. ctx->Ans.evtLogFileName = szEvtFile;
  5097. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Total count of event log: %u", dwEntries);
  5098. }
  5099. ctx->Answer(Error_Succeed);
  5100. return dwEntries;
  5101. }
  5102. //合成生成的系统事件文件名称
  5103. DWORD ResourceWatcherFSM::CombineTheEvtxFileName(LPCTSTR lpszTerminalNo, CHAR szEvtxFileName[])
  5104. {
  5105. CSimpleStringA strPath;
  5106. if (lpszTerminalNo == NULL || strlen(lpszTerminalNo) == 0)
  5107. {
  5108. LogWarn(Severity_Middle, Error_Param, 0, "TerminalNo is nullptr");
  5109. return 0;
  5110. }
  5111. if (GetEntityBase()->GetFunction()->GetPath("Temp", strPath) != Error_Succeed
  5112. || strPath.IsNullOrEmpty())
  5113. {
  5114. LogWarn(Severity_Middle, Error_Unexpect, 0, "GetPath about Temp failed");
  5115. return 0;
  5116. }
  5117. if (!ExistsDirA(strPath)) {
  5118. if (!CreateDirRecursiveA(strPath)) {
  5119. LogWarn(Severity_Middle, Error_Unexpect, 0, "CreateDirRecursiveA failed");
  5120. return 0;
  5121. }
  5122. }
  5123. SYSTEMTIME st, stLocal;
  5124. GetSystemTime(&st);
  5125. SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
  5126. #ifdef WIDE_CONDITION
  5127. WCHAR fileName[MAX_PATH] = { 0 };
  5128. CSimpleStringW strwPath = CSimpleStringA2W(strPath);
  5129. CSimpleStringW lpwszTerminalNo = CSimpleStringA2W(CSimpleStringA(lpszTerminalNo));
  5130. swprintf_s(fileName, L"%ws\\%ws-%d%02d%02d-%02d_%02d_%02d", (LPCWSTR)strwPath, (LPCWSTR)lpwszTerminalNo,
  5131. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  5132. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  5133. wcscat_s(fileName, EXT_EVTLOG_NAME);
  5134. CSimpleStringA lpszFileName = CSimpleStringW2A(CSimpleStringW(fileName));
  5135. strcpy_s(szEvtxFileName, MAX_PATH, lpszFileName);
  5136. return strlen(szEvtxFileName);
  5137. #else
  5138. CHAR fileName[MAX_PATH] = { 0 };
  5139. sprintf_s(fileName, "%s\\%s-%d%02d%02d-%02d_%02d_%02d", (LPCTSTR)strPath, lpszTerminalNo,
  5140. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  5141. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  5142. strcat_s(fileName, EXT_EVTLOG_NAME);
  5143. strcpy_s(szEvtxFileName, MAX_PATH, fileName);
  5144. return strlen(szEvtxFileName);
  5145. #endif
  5146. }
  5147. DWORD ResourceWatcherFSM::CalSpecifiedSecondsFrom1970(const WORD wDuration
  5148. , DWORD* dwStartTime
  5149. , DWORD* dwEndTime
  5150. , const PULONGLONG pStartTime
  5151. , const PULONGLONG pEndTime)
  5152. {
  5153. DWORD status = E_FAIL;
  5154. if (dwStartTime == NULL || dwEndTime == NULL)
  5155. return E_INVALIDARG;
  5156. if (wDuration == DURATION_NONE) {
  5157. *dwStartTime = *dwEndTime = 0;
  5158. return ERROR_SUCCESS;
  5159. }
  5160. ULONGLONG ullTimeStamp = 0;
  5161. ULONGLONG SecsTo1970 = 116444736000000000;
  5162. if (wDuration == DURAITON_CUSTOM) {
  5163. if (pStartTime == NULL || pEndTime == NULL)
  5164. return E_POINTER;
  5165. if (*pStartTime > *pEndTime)
  5166. return E_INVALIDARG;
  5167. ullTimeStamp = (*pStartTime) - SecsTo1970;
  5168. ullTimeStamp /= 10000000ULL;
  5169. *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  5170. ullTimeStamp = (*pEndTime) - SecsTo1970;
  5171. ullTimeStamp /= 10000000ULL;
  5172. *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  5173. return ERROR_SUCCESS;
  5174. }
  5175. SYSTEMTIME st;
  5176. GetSystemTime(&st);
  5177. FILETIME ftCurTime;
  5178. GetSystemTimeAsFileTime(&ftCurTime);
  5179. ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
  5180. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  5181. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  5182. if (wDuration == DURATION_HOUR_ONE) {
  5183. uliOffset.QuadPart = UInt32x32To64(1 * 60 * 60, 1e7);
  5184. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  5185. }
  5186. else if (wDuration == DURATION_HOUR_TWELVE) {
  5187. uliOffset.QuadPart = UInt32x32To64(12 * 60 * 60, 1e7);
  5188. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  5189. }
  5190. else if (wDuration == DURATION_DAY_ONE) {
  5191. uliOffset.QuadPart = UInt32x32To64(24 * 60 * 60, 1e7);
  5192. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  5193. }
  5194. else if (wDuration == DURATION_DAY_SEVENT) {
  5195. uliOffset.QuadPart = UInt32x32To64(7 * 24 * 60 * 60, 1e7);
  5196. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  5197. }
  5198. else if (wDuration == DURATION_MONTH_ONE) {
  5199. uliOffset.QuadPart = UInt32x32To64(30 * 24 * 60 * 60, 1e7);
  5200. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  5201. }
  5202. else {
  5203. return E_INVALIDARG;
  5204. }
  5205. ullTimeStamp = uliBackTime.QuadPart - SecsTo1970;
  5206. ullTimeStamp /= 10000000ULL;
  5207. *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  5208. ullTimeStamp = uliCurTime.QuadPart - SecsTo1970;
  5209. ullTimeStamp /= 10000000ULL;
  5210. *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  5211. {
  5212. FILETIME ftBackTime;
  5213. SYSTEMTIME stUTC, stLocal;
  5214. ftBackTime.dwHighDateTime = uliBackTime.HighPart;
  5215. ftBackTime.dwLowDateTime = uliBackTime.LowPart;
  5216. FileTimeToSystemTime(&ftBackTime, &stUTC);
  5217. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  5218. CHAR szTimeFormat[MAX_PATH] = { 0 };
  5219. // Build a string showing the date and time.
  5220. sprintf_s(szTimeFormat, MAX_PATH, "%02d/%02d/%d %02d:%02d:%02d",
  5221. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  5222. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  5223. printf("Start time statmp: %s\n", szTimeFormat);
  5224. }
  5225. return ERROR_SUCCESS;
  5226. }
  5227. BOOL ResourceWatcherFSM::RetrieveSpecificedEventLogs(const LPEVENTLOGPARAM pEvtLogFilter,
  5228. LPCTSTR lpszEvtFileName, DWORD& dwEntries)
  5229. {
  5230. LOG_FUNCTION();
  5231. CEventLog* pEvtLog = NULL;
  5232. if (pEvtLogFilter->fApplication) {
  5233. pEvtLog = new CEventLog(APPLICATION_LOG);
  5234. }
  5235. else if (pEvtLogFilter->fSystem) {
  5236. pEvtLog = new CEventLog(SYSTEM_LOG);
  5237. }
  5238. else if (pEvtLogFilter->fSecurity) {
  5239. pEvtLog = new CEventLog(SECURITY_LOG);
  5240. #ifdef WIDE_CONDITION
  5241. }
  5242. else if (pEvtLogFilter->fCustom && wcslen(pEvtLogFilter->lpszCustomEventName) > 0) {
  5243. #else
  5244. }
  5245. else if (pEvtLogFilter->fCustom && strlen(pEvtLogFilter->lpszCustomEventName) > 0) {
  5246. #endif
  5247. pEvtLog = new CEventLog(pEvtLogFilter->lpszCustomEventName, TRUE);
  5248. }
  5249. if (pEvtLog == NULL || !pEvtLog->IsInitialized())
  5250. {
  5251. if (pEvtLog)
  5252. delete pEvtLog;
  5253. return FALSE;
  5254. }
  5255. #ifdef WIDE_CONDITION
  5256. CSimpleStringW strwFileName = CSimpleStringA2W(CSimpleStringA(lpszEvtFileName));
  5257. pEvtLog->InitializeLogFile(std::wstring(strwFileName));
  5258. #else
  5259. pEvtLog->InitializeLogFile(std::string(lpszEvtFileName));
  5260. #endif
  5261. dwEntries = pEvtLog->FilterEventLog(pEvtLogFilter->lpszSourceEventName
  5262. , pEvtLogFilter->wEventType
  5263. , pEvtLogFilter->dwEventId
  5264. , pEvtLogFilter->dwTimeBegin
  5265. , pEvtLogFilter->dwTimeEnd);
  5266. if (pEvtLog)
  5267. delete pEvtLog;
  5268. return TRUE;
  5269. }
  5270. #endif // _MSC_VER
  5271. BOOL ResourceWatcherFSM::ClearAd0Folder()
  5272. {
  5273. LOG_FUNCTION();
  5274. ErrorCodeEnum ec;
  5275. CSimpleStringA strAd0Path;
  5276. CSmartPointer<IConfigInfo> spConfigRun;
  5277. int nLastTaskTime(0);
  5278. CSimpleStringA ssFilePath(true);
  5279. ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  5280. spConfigRun->ReadConfigValueInt("LastClearTime", "Ad0Task", nLastTaskTime);
  5281. if (IsTodayDone(nLastTaskTime)) {
  5282. return TRUE;
  5283. }
  5284. ec = GetEntityBase()->GetFunction()->GetPath("Ad0", strAd0Path);
  5285. if (ec != Error_Succeed || strAd0Path.IsNullOrEmpty()) {
  5286. return FALSE;
  5287. }
  5288. if (!ExistsDirA(strAd0Path)) {
  5289. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The Folder is not existed");
  5290. spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
  5291. (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  5292. return TRUE;
  5293. }
  5294. char displayTime[MAX_PATH] = { 0 };
  5295. ZeroMemory(&mftAd0RemoveTime, sizeof(FILETIME));
  5296. CalculateBackTime(&mftAd0RemoveTime, AD0_DAY_OF_BACKWARD);
  5297. GetTimeFormatStr(displayTime, MAX_PATH, &mftAd0RemoveTime);
  5298. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The date backward to delete: %s", displayTime);
  5299. #ifdef RVC_OS_LINUX
  5300. ssFilePath = strAd0Path;
  5301. #else
  5302. ssFilePath = strAd0Path + "\\*";
  5303. #endif // RVC_OS_LINUX
  5304. int nDelSuc = 0;
  5305. int nDelFailed = 0;
  5306. int nfileSum = ClearSpecifieFile(DFT_Ad0, (LPCTSTR)ssFilePath, nDelSuc, nDelFailed);
  5307. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("#Ad0#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  5308. spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
  5309. (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  5310. return TRUE;
  5311. }
  5312. BOOL ResourceWatcherFSM::IsTodayDone(int nRecordTime)
  5313. {
  5314. if (nRecordTime <= 0) {
  5315. return FALSE;
  5316. }
  5317. SYSTEMTIME stNow = {};
  5318. SYSTEMTIME stTaskTime = CSmallDateTime(nRecordTime).ToSystemTime();
  5319. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Last record time: %04d-%02d-%02d %02d:%02d:%02d",
  5320. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  5321. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  5322. #ifdef RVC_OS_LINUX
  5323. stNow = CSmallDateTime::GetNow().ToSystemTime();
  5324. #else
  5325. GetLocalTime(&stNow);
  5326. #endif // RVC_OS_LINUX
  5327. if (stTaskTime.wYear == stNow.wYear
  5328. && stTaskTime.wMonth == stNow.wMonth
  5329. && stTaskTime.wDay == stNow.wDay)
  5330. {
  5331. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("task has been executed today, last clear time: %s",
  5332. (const char*)CSmallDateTime(nRecordTime).ToTimeString());
  5333. return TRUE;
  5334. }
  5335. return FALSE;
  5336. }
  5337. BOOL ResourceWatcherFSM::GetSystemBootTime(CSmallDateTime & systemBootTime)
  5338. {
  5339. #ifdef RVC_OS_LINUX
  5340. DWORD ticks = 0;
  5341. SYSTEMTIME systemTime;
  5342. struct sysinfo info;
  5343. time_t curTime = 0;
  5344. time_t bootTime = 0;
  5345. struct tm* ptm = NULL;
  5346. if (sysinfo(&info)) {
  5347. Dbg("Failed to get sysinfo, errno:%u, reason:%s", errno, strerror(errno));
  5348. return FALSE;
  5349. }
  5350. time(&curTime);
  5351. if (curTime > info.uptime) {
  5352. bootTime = curTime - info.uptime;
  5353. }
  5354. else {
  5355. bootTime = info.uptime - curTime;
  5356. }
  5357. ptm = localtime(&bootTime);
  5358. struct timespec ts;
  5359. if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
  5360. ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
  5361. systemTime.wYear = (WORD)(ptm->tm_year + 1900);
  5362. systemTime.wMonth = (WORD)(ptm->tm_mon + 1);
  5363. systemTime.wDayOfWeek = (WORD)ptm->tm_wday;
  5364. systemTime.wDay = (WORD)ptm->tm_mday;
  5365. systemTime.wHour = (WORD)ptm->tm_hour;
  5366. systemTime.wMinute = (WORD)ptm->tm_min;
  5367. systemTime.wSecond = (WORD)ptm->tm_sec;
  5368. systemTime.wMilliseconds = (WORD)(ticks % 1000);
  5369. systemBootTime.FromSystemTime(systemTime);
  5370. Dbg("OSStartTime: %s", systemBootTime.ToTimeString().GetData());
  5371. return TRUE;
  5372. #else
  5373. PDH_STATUS Status;
  5374. HQUERY Query = NULL;
  5375. HCOUNTER hcElapsedTimeCount;
  5376. BOOL fSuc = FALSE;
  5377. /** 杀毒软件会对附件这几个系统调用函数有所监控,导致有时会耗费5s时间 Gifur@20221019]*/
  5378. Status = PdhOpenQuery(NULL, NULL, &Query);
  5379. PDH_FMT_COUNTERVALUE counterValue;
  5380. if (Status != ERROR_SUCCESS)
  5381. {
  5382. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhOpenQuery failed with status 0x%x.", Status);
  5383. goto Cleanup;
  5384. }
  5385. Status = PdhAddCounter(Query, SystemElapsedQuery, NULL, &hcElapsedTimeCount);
  5386. if (Status != ERROR_SUCCESS)
  5387. {
  5388. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhAddCounter for SystemElapsedQuery failed with status 0x%x.", Status);
  5389. goto Cleanup;
  5390. }
  5391. // 查询性能监视器数据
  5392. Status = PdhCollectQueryData(Query);
  5393. if (Status != ERROR_SUCCESS)
  5394. {
  5395. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhCollectQueryData failed with 0x%x.", Status);
  5396. goto Cleanup;
  5397. }
  5398. Status = PdhGetFormattedCounterValue(hcElapsedTimeCount, PDH_FMT_LARGE, NULL, &counterValue);
  5399. if (Status == ERROR_SUCCESS)
  5400. {
  5401. ULONGLONG ulSinceSeconds = counterValue.largeValue;
  5402. ULONG days = 0, hours = 0, minutes = 0, seconds = 0;
  5403. days = ULONG(ulSinceSeconds / DAY_DIV);
  5404. ulSinceSeconds %= DAY_DIV;
  5405. hours = ULONG(ulSinceSeconds / HOURS_DIV);
  5406. ulSinceSeconds %= HOURS_DIV;
  5407. minutes = ULONG(ulSinceSeconds / MINUS_DIV);
  5408. ulSinceSeconds %= MINUS_DIV;
  5409. seconds = ULONG(ulSinceSeconds);
  5410. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SystemElapseTime: %u:%02u:%02u:%02u", days, hours, minutes, seconds);
  5411. FILETIME ftCurTime, ftStartTime;
  5412. GetSystemTimeAsFileTime(&ftCurTime);
  5413. ULARGE_INTEGER uliCurTime;
  5414. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  5415. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  5416. uliCurTime.QuadPart -= counterValue.largeValue * 1e7;
  5417. ftStartTime.dwHighDateTime = uliCurTime.HighPart;
  5418. ftStartTime.dwLowDateTime = uliCurTime.LowPart;
  5419. SYSTEMTIME stUTC, stLocal;
  5420. FileTimeToSystemTime(&ftStartTime, &stUTC);
  5421. char temp[22];
  5422. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  5423. sprintf_s(temp, 22, "%d-%02d-%02d %02d:%02d:%02d",
  5424. stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  5425. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("OSStartTime: %s", temp);
  5426. systemBootTime.FromSystemTime(stLocal);
  5427. fSuc = TRUE;
  5428. }
  5429. Cleanup:
  5430. Status = PdhRemoveCounter(hcElapsedTimeCount);
  5431. if (Query) {
  5432. PdhCloseQuery(Query);
  5433. }
  5434. return fSuc;
  5435. #endif // RVC_OS_LINUX
  5436. }
  5437. #ifdef _MSC_VER
  5438. HRESULT ResourceWatcherFSM::SetDefaultAudioPlaybackDevice(LPCWSTR devID)
  5439. {
  5440. IPolicyConfigVista* pPolicyConfig;
  5441. ERole reserved = eConsole;
  5442. HRESULT hr = CoCreateInstance(__uuidof(CPolicyConfigVistaClient),
  5443. NULL, CLSCTX_ALL, __uuidof(IPolicyConfigVista), (LPVOID*)&pPolicyConfig);
  5444. if (SUCCEEDED(hr))
  5445. {
  5446. hr = pPolicyConfig->SetDefaultEndpoint(devID, reserved);
  5447. pPolicyConfig->Release();
  5448. }
  5449. return hr;
  5450. }
  5451. BOOL ResourceWatcherFSM::SetDefaultAudioDevice()
  5452. {
  5453. CSmartPointer<IEntityFunction> spFunction = GetEntityBase()->GetFunction();
  5454. CSmartPointer<IConfigInfo> spConfig;
  5455. CSimpleStringA strAudioName;
  5456. BOOL bRet = FALSE;
  5457. ErrorCodeEnum ec = spFunction->OpenConfig(Config_Root, spConfig);
  5458. ec = spConfig->ReadConfigValue("Audio", "handfree_out_dev", strAudioName);
  5459. if (strAudioName.IsNullOrEmpty()) {
  5460. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("handfree_out_dev is nullptr or empty!!");
  5461. return FALSE;
  5462. }
  5463. CSimpleStringW strwAudioName = CSimpleStringA2W(strAudioName);
  5464. HRESULT hr = CoInitialize(NULL);
  5465. if (SUCCEEDED(hr))
  5466. {
  5467. IMMDeviceEnumerator* pEnum = NULL;
  5468. // Create a multimedia device enumerator.
  5469. hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL,
  5470. CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pEnum);
  5471. if (SUCCEEDED(hr))
  5472. {
  5473. //判断是否是默认的音频设备,是就退出
  5474. bool bExit = false;
  5475. IMMDevice* pDefDevice = NULL;
  5476. hr = pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefDevice);
  5477. if (SUCCEEDED(hr))
  5478. {
  5479. IPropertyStore* pStore;
  5480. hr = pDefDevice->OpenPropertyStore(STGM_READ, &pStore);
  5481. if (SUCCEEDED(hr))
  5482. {
  5483. PROPVARIANT friendlyName;
  5484. PropVariantInit(&friendlyName);
  5485. hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
  5486. if (SUCCEEDED(hr))
  5487. {
  5488. CSimpleStringW strTmp = friendlyName.pwszVal;
  5489. if (strTmp.IsStartWith(strwAudioName)) {
  5490. bExit = true;
  5491. }
  5492. PropVariantClear(&friendlyName);
  5493. }
  5494. pStore->Release();
  5495. }
  5496. pDefDevice->Release();
  5497. }
  5498. if (bExit) {
  5499. pEnum->Release();
  5500. return TRUE;
  5501. }
  5502. IMMDeviceCollection* pDevices;
  5503. // Enumerate the output devices.
  5504. hr = pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pDevices);
  5505. if (SUCCEEDED(hr))
  5506. {
  5507. UINT count;
  5508. pDevices->GetCount(&count);
  5509. if (SUCCEEDED(hr))
  5510. {
  5511. for (int i = 0; i < count; i++)
  5512. {
  5513. bool bFind = false;
  5514. IMMDevice* pDevice;
  5515. hr = pDevices->Item(i, &pDevice);
  5516. if (SUCCEEDED(hr))
  5517. {
  5518. LPWSTR wstrID = NULL;
  5519. hr = pDevice->GetId(&wstrID);
  5520. if (SUCCEEDED(hr))
  5521. {
  5522. IPropertyStore* pStore;
  5523. hr = pDevice->OpenPropertyStore(STGM_READ, &pStore);
  5524. if (SUCCEEDED(hr))
  5525. {
  5526. PROPVARIANT friendlyName;
  5527. PropVariantInit(&friendlyName);
  5528. hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
  5529. if (SUCCEEDED(hr))
  5530. {
  5531. // if no options, print the device
  5532. // otherwise, find the selected device and set it to be default
  5533. CSimpleStringW strTmp = friendlyName.pwszVal;
  5534. if (strTmp.IsStartWith(strwAudioName)) {
  5535. bFind = true;
  5536. HRESULT hr = SetDefaultAudioPlaybackDevice(wstrID);
  5537. if (SUCCEEDED(hr)) {
  5538. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("set default audio player succ.");
  5539. bRet = TRUE;
  5540. }
  5541. else {
  5542. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("set default audio player failed");
  5543. }
  5544. }
  5545. PropVariantClear(&friendlyName);
  5546. }
  5547. pStore->Release();
  5548. }
  5549. }
  5550. pDevice->Release();
  5551. }
  5552. if (bFind)
  5553. {
  5554. break;
  5555. }
  5556. }
  5557. }
  5558. pDevices->Release();
  5559. }
  5560. pEnum->Release();
  5561. }
  5562. }
  5563. CoUninitialize();
  5564. return bRet;
  5565. }
  5566. bool ResourceWatcherFSM::CreateLinkFile(const CSimpleStringA& szStartAppPath, const CSimpleStringA& szAddCmdLine,
  5567. const CSimpleStringA& szDestLnkPath, const CSimpleStringA& szIconPath)
  5568. {
  5569. HRESULT hr = CoInitialize(NULL);
  5570. bool bRet = false;
  5571. if (SUCCEEDED(hr))
  5572. {
  5573. IShellLink* pShellLink;
  5574. hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pShellLink);
  5575. if (SUCCEEDED(hr))
  5576. {
  5577. pShellLink->SetPath(szStartAppPath);
  5578. string strTmp = szStartAppPath;
  5579. int nStart = strTmp.find_last_of("/\\");
  5580. pShellLink->SetWorkingDirectory(strTmp.substr(0, nStart).c_str());
  5581. pShellLink->SetArguments(szAddCmdLine);
  5582. if (szIconPath)
  5583. {
  5584. pShellLink->SetIconLocation(szIconPath, 0);
  5585. }
  5586. IPersistFile* pPersistFile;
  5587. hr = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile);
  5588. if (SUCCEEDED(hr))
  5589. {
  5590. hr = pPersistFile->Save(CSimpleStringA2W(szDestLnkPath).GetData(), FALSE);
  5591. if (SUCCEEDED(hr))
  5592. {
  5593. bRet = true;
  5594. }
  5595. pPersistFile->Release();
  5596. }
  5597. pShellLink->Release();
  5598. }
  5599. CoUninitialize();
  5600. }
  5601. return bRet;
  5602. }
  5603. void ResourceWatcherFSM::CreateLink(const CSimpleStringA& exePath)
  5604. {
  5605. LPITEMIDLIST lp;
  5606. SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &lp);
  5607. CHAR lstr[100] = "";
  5608. SHGetPathFromIDList(lp, lstr);
  5609. CSimpleStringA s = lstr;
  5610. s += "\\可视柜台.lnk";
  5611. CSimpleStringA icoPath;
  5612. ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", icoPath);
  5613. CSimpleStringA csPath = icoPath;
  5614. csPath += "\\active.txt";
  5615. FILE* pFile = fopen(csPath, "r");
  5616. if (pFile != NULL)
  5617. {
  5618. char szTemp[256] = {};
  5619. char szVersion[32] = {};
  5620. int n = fread(szTemp, 1, 256, pFile);
  5621. strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
  5622. fclose(pFile);
  5623. icoPath = icoPath + "\\" + szVersion + "\\bin\\VTM_IL.ico";
  5624. if (!CreateLinkFile(exePath, "", s, icoPath))
  5625. {
  5626. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile DESKTOP fail");
  5627. }
  5628. SHGetSpecialFolderLocation(0, CSIDL_PROGRAMS, &lp);
  5629. memset(lstr, 0, strlen(lstr));
  5630. SHGetPathFromIDList(lp, lstr);
  5631. s = lstr;
  5632. s += "\\可视柜台.lnk";
  5633. if (!CreateLinkFile(exePath, "", s, icoPath))
  5634. {
  5635. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile CSIDL_PROGRAMS fail");
  5636. }
  5637. }
  5638. else
  5639. {
  5640. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("open active.txt fail");
  5641. }
  5642. }
  5643. bool isFileExist(const std::string& name)
  5644. {
  5645. if (FILE* file = fopen(name.c_str(), "r")) {
  5646. fclose(file);
  5647. return true;
  5648. }
  5649. else {
  5650. return false;
  5651. }
  5652. }
  5653. bool ResourceWatcherFSM::CopyExeToRoot()
  5654. {
  5655. CSimpleStringA rootVerPath, exePath;
  5656. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  5657. exePath = rootVerPath + "\\VTM.exe";
  5658. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("exePath:%s", exePath.GetData());
  5659. if (rc == Error_Succeed) //&& !ExistsFileA(exePath)
  5660. {
  5661. CSimpleStringA srcExePath, csPath = rootVerPath;
  5662. char szVersion[32] = {};
  5663. csPath += "\\active.txt";
  5664. FILE* pFile = fopen(csPath, "r");
  5665. if (pFile != NULL)
  5666. {
  5667. char szTemp[256] = {};
  5668. int n = fread(szTemp, 1, 256, pFile);
  5669. strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
  5670. fclose(pFile);
  5671. srcExePath = rootVerPath + "\\" + szVersion + "\\bin\\VTM.exe";
  5672. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("srcExePath:%s exePath:%s", srcExePath.GetData(), exePath.GetData());
  5673. if (!CopyFileA(srcExePath.GetData(), exePath.GetData(), FALSE))
  5674. {
  5675. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CopyFileA Fail error :%d ", GetLastError());
  5676. return false;
  5677. }
  5678. }
  5679. else
  5680. {
  5681. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("open active.txt fail");
  5682. return false;
  5683. }
  5684. }
  5685. return true;
  5686. }
  5687. bool ResourceWatcherFSM::GetVtmVersion(CSimpleStringA& csVersion)
  5688. {
  5689. bool bRet = false;
  5690. CSimpleStringA rootVerPath;
  5691. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
  5692. if (rc != Error_Succeed) {
  5693. LogWarn(Severity_Middle, Error_Exception, ERR_WRAN_OPEN_ACTIVE_FAIL, "testActive fail , get RootVer path is fai");
  5694. return false;
  5695. }
  5696. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s\\active.txt", rootVerPath.GetData());
  5697. FILE* pFile = fopen(strActiveFile.GetData(), "rb+");
  5698. if (pFile != NULL)
  5699. {
  5700. char szTemp[256] = {};
  5701. char szVersion[32] = {};
  5702. int n = fread(szTemp, 1, 256, pFile);
  5703. strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
  5704. csVersion = szVersion;
  5705. fclose(pFile);
  5706. bRet = true;
  5707. }
  5708. else
  5709. {
  5710. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open active.txt failed.");
  5711. bRet = false;
  5712. }
  5713. return bRet;
  5714. }
  5715. bool ResourceWatcherFSM::GetRegValue(HKEY hKey, LPCTSTR lpcszParam,
  5716. CHAR* pSzValue, DWORD* pDwSizeOfSz)
  5717. {
  5718. DWORD dwType = REG_SZ;
  5719. TCHAR szValue[MAX_PATH + 1] = { 0 };
  5720. DWORD dwSize = MAX_PATH * sizeof(CHAR);
  5721. LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, pDwSizeOfSz);
  5722. if (lResult == ERROR_SUCCESS) {
  5723. strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
  5724. return true;
  5725. }
  5726. else {
  5727. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"InstallTime\" error, result=%ld.", lResult);
  5728. return false;
  5729. }
  5730. }
  5731. void ResourceWatcherFSM::DetectAutoStartupCover()
  5732. {
  5733. int bStartupByVbs(0);
  5734. DetectAutoStartup(bStartupByVbs);
  5735. if (m_forceStartupWithExeFlag == 1 && bStartupByVbs == 1 && !m_IsPadDevice) {
  5736. ChangeAutoStartupWithExe(); //test succ
  5737. }
  5738. else if (m_forceStartupWithExeFlag == 2 && (bStartupByVbs == 0 || bStartupByVbs == 1) && !m_IsPadDevice) {
  5739. ChangeAutoStartupWithExe(); //test succ || test succ
  5740. }
  5741. else if (m_forceStartupWithExeFlag == 3 && (bStartupByVbs == 1 || bStartupByVbs == 2)) {
  5742. ChangeAutoStartupWithExe(true); //test succ || test succ
  5743. }
  5744. }
  5745. static int Is32R64Platform()
  5746. {
  5747. static int isWow64 = -1;
  5748. typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  5749. if (isWow64 == -1) {
  5750. BOOL bIsWow64 = FALSE;
  5751. LPFN_ISWOW64PROCESS fnIsWow64Process =
  5752. (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  5753. if (NULL != fnIsWow64Process) {
  5754. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
  5755. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("detect is running with 64bit or not failed: %u", GetLastError());
  5756. return -1;
  5757. }
  5758. else {
  5759. isWow64 = bIsWow64 ? 1 : 0;
  5760. }
  5761. }
  5762. }
  5763. return isWow64;
  5764. }
  5765. void ResourceWatcherFSM::DetectAutoStartup(int& vbsType)
  5766. {
  5767. LOG_FUNCTION();
  5768. vbsType = -1;
  5769. if (m_DoneDetectAutostart) {
  5770. vbsType = -2;
  5771. return;
  5772. }
  5773. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  5774. if (Is32R64Platform() != 0) {
  5775. dwFlag |= KEY_WOW64_64KEY;
  5776. }
  5777. HKEY hKey;
  5778. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  5779. TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"),
  5780. 0, dwFlag, &hKey);
  5781. if (lResult == ERROR_SUCCESS) {
  5782. DWORD dwType = REG_SZ;
  5783. DWORD dwSize = MAX_PATH * sizeof(TCHAR);
  5784. TCHAR szValue[MAX_PATH + 1] = { 0 };
  5785. lResult = RegQueryValueEx(hKey, "Shell", NULL, &dwType, (LPBYTE)szValue, &dwSize);
  5786. if (lResult == ERROR_SUCCESS) {
  5787. CSimpleStringA value(szValue);
  5788. if (value.IsNullOrEmpty() || value.Compare("explorer.exe") != 0) {
  5789. if (value.IsEndWith(".vbs", true)) {
  5790. LogWarn(Severity_Low, Error_Debug, LOG_WARN_AUTO_STARTUP_FROM_REGIST, value);
  5791. vbsType = 1;
  5792. }
  5793. else if (value.IsEndWith("VTM.exe", true)) {
  5794. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_EXE, value);
  5795. vbsType = 2;
  5796. }
  5797. }
  5798. else {
  5799. LogWarn(Severity_Low, Error_Debug, LOG_WARN_NOT_AUTO_STARTUP_FROM_REGIST, value);
  5800. if (value.Compare("explorer.exe") == 0) {
  5801. vbsType = 0;
  5802. }
  5803. }
  5804. }
  5805. else {
  5806. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
  5807. CSimpleStringA::Format("RegQueryValueEx error returned %u, GLE=%u.", lResult, GetLastError()));
  5808. }
  5809. }
  5810. else {
  5811. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
  5812. CSimpleStringA::Format("RegOpenKeyEx error, GLE=%u.", GetLastError()));
  5813. }
  5814. RegCloseKey(hKey);
  5815. m_DoneDetectAutostart = true;
  5816. return;
  5817. }
  5818. ErrorCodeEnum ResourceWatcherFSM::ChangeAutoStartupWithExe(bool resetExplorer)
  5819. {
  5820. const char* exploreExe = "explorer.exe";
  5821. ErrorCodeEnum result(Error_Succeed);
  5822. CSimpleStringA exePath(true);
  5823. if (resetExplorer) {
  5824. exePath = exploreExe;
  5825. }
  5826. else {
  5827. result = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
  5828. if (exePath.IsNullOrEmpty() || result != Error_Succeed) {
  5829. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get RootVer path failed: %d", result);
  5830. return Error_Unexpect;
  5831. }
  5832. exePath.Append("\\VTM.exe");
  5833. if (!ExistsFileA(exePath)) {
  5834. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] is not existed!", exePath.GetData());
  5835. return Error_NotExist;
  5836. }
  5837. }
  5838. DWORD dwFlag = KEY_WRITE;
  5839. if (Is32R64Platform() != 0) {
  5840. dwFlag |= KEY_WOW64_64KEY;
  5841. }
  5842. HKEY hKey;
  5843. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  5844. TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), 0, dwFlag, &hKey);
  5845. if (lResult == ERROR_SUCCESS) {
  5846. lResult = RegSetValueExA(hKey, "Shell", 0, REG_SZ, (const BYTE*)exePath.GetData(), exePath.GetLength());
  5847. if (lResult == ERROR_SUCCESS) {
  5848. LogWarn(Severity_Low, Error_Debug, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_SUCC
  5849. , CSimpleStringA::Format("RegSetValueExA for Shell with %s succ!", exePath.GetData()));
  5850. result = Error_Succeed;
  5851. }
  5852. else {
  5853. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
  5854. , CSimpleStringA::Format("RegSetValueExA for Shell with %s failed: %d", exePath.GetData(), lResult));
  5855. result = Error_Unexpect;
  5856. }
  5857. }
  5858. else {
  5859. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
  5860. , CSimpleStringA::Format("RegOpenKeyEx for write %s failed: %d", exePath.GetData(), lResult));
  5861. result = Error_Unexpect;
  5862. }
  5863. RegCloseKey(hKey);
  5864. return result;
  5865. }
  5866. void ResourceWatcherFSM::InitialAutoStartupSetType()
  5867. {
  5868. CSmartPointer<IConfigInfo> spConfig;
  5869. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  5870. int value(0);
  5871. spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "AutoStartCMD", value);
  5872. if (value != 0) {
  5873. m_forceStartupWithExeFlag = value;
  5874. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get AutoStartCMD from CS: %d", m_forceStartupWithExeFlag);
  5875. }
  5876. }
  5877. BOOL ResourceWatcherFSM::IsHasSetAutoStartupByFolder()
  5878. {
  5879. BOOL result(FALSE);
  5880. const char* STARTUP_DIR_FULL_PATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp";
  5881. #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
  5882. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(ST测试).lnk";
  5883. #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
  5884. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(UAT测试).lnk";
  5885. #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
  5886. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
  5887. #elif defined(DEVOPS_ON_DEV)/*DevOps流水线编译,Dev环境*/
  5888. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(开发).lnk";
  5889. #else/*本地编译等非DevOps环境编译的版本*/
  5890. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
  5891. #endif
  5892. if (!ExistsDirA(STARTUP_DIR_FULL_PATH)) {
  5893. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] dir is not exist!", STARTUP_DIR_FULL_PATH);
  5894. return result;
  5895. }
  5896. auto arr = fileutil_get_sub_files(STARTUP_DIR_FULL_PATH);
  5897. if (arr != NULL) {
  5898. for (int i = 0; i < arr->nelts; ++i) {
  5899. char* file = ARRAY_IDX(arr, i, char*);
  5900. char* filename = strrchr(file, '\\');
  5901. if (filename != NULL) { filename += 1; }
  5902. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("autostartup[%s]", filename);
  5903. if (filename != NULL/* && strcmp(filename, CMB_LINK_FILE_NAME) == 0*/) {
  5904. CSimpleStringA strfilename(filename);
  5905. if (strfilename.IsStartWith("招商银行可视柜台") && strfilename.IsEndWith(".lnk")) {
  5906. result = TRUE;
  5907. break;
  5908. }
  5909. }
  5910. }
  5911. toolkit_array_free2(arr);
  5912. }
  5913. return result;
  5914. }
  5915. void ResourceWatcherFSM::DetectVersionHasChangedAndWarn()
  5916. {
  5917. CSmartPointer<IConfigInfo> spRunConfig;
  5918. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  5919. UINT64 utVersion = 0;
  5920. spRunConfig->ReadConfigValueHexInt("VersionMonitor", "LastVer", utVersion);
  5921. CVersion lastVer(utVersion);
  5922. if (lastVer.IsValid() && lastVer > m_RvcSysinfo.InstallVersion) {
  5923. CSimpleStringA rootVerPath;
  5924. CSimpleStringA warnInfo = CSimpleStringA::Format("version changed from %s to %s", lastVer.ToString().GetData(), m_RvcSysinfo.InstallVersion.ToString().GetData());
  5925. GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  5926. CSimpleStringA csPath = rootVerPath + "\\active.txt";
  5927. if (!ExistsFileA(csPath)) {
  5928. LogWarn(Severity_Low, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt not exist!", warnInfo.GetData()));
  5929. }
  5930. else {
  5931. CSimpleFileComponent activeFileInfo;
  5932. HANDLE hFile = CreateFileA(
  5933. csPath,
  5934. GENERIC_READ,
  5935. FILE_SHARE_READ,
  5936. NULL,
  5937. OPEN_EXISTING,
  5938. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
  5939. NULL);
  5940. if (hFile == INVALID_HANDLE_VALUE) {
  5941. LogWarn(Severity_Low, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt open failed %u", warnInfo.GetData(), GetLastError()));
  5942. }
  5943. else {
  5944. GetFileTime(hFile, (LPFILETIME)&activeFileInfo.mftCreate,
  5945. (LPFILETIME)&activeFileInfo.mftAccess, (LPFILETIME)&activeFileInfo.mftModified);
  5946. CloseHandle(hFile);
  5947. char szFormat1[128] = { 0 };
  5948. GetTimeFormatStr(szFormat1, 128, (FILETIME*)&activeFileInfo.mftCreate);
  5949. char szFormat2[128] = { 0 };
  5950. GetTimeFormatStr(szFormat2, 128, (FILETIME*)&activeFileInfo.mftAccess);
  5951. char szFormat3[128] = { 0 };
  5952. GetTimeFormatStr(szFormat3, 128, (FILETIME*)&activeFileInfo.mftModified);
  5953. LogWarn(Severity_Low, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format(
  5954. "%s: active.txt create at %s, access at %s, modified at %s", warnInfo.GetData(), szFormat1, szFormat2, szFormat3));
  5955. }
  5956. }
  5957. }
  5958. if (!lastVer.IsValid() || lastVer != m_RvcSysinfo.InstallVersion) {
  5959. spRunConfig->WriteConfigValueHexInt("VersionMonitor", "LastVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  5960. }
  5961. }
  5962. void ResourceWatcherFSM::DetectDestopFileAndWarn(LPCTSTR curUserName)
  5963. {
  5964. CSimpleStringA desktopFullPath = CSimpleStringA::Format("C:\\Users\\%s\\Desktop", curUserName);
  5965. auto arr = fileutil_get_sub_files(desktopFullPath);
  5966. CSimpleStringA filelist(true);
  5967. int dirCount(0), fileCount(0);
  5968. if (arr != NULL) {
  5969. for (int i = 0; i < arr->nelts; ++i) {
  5970. char* file = ARRAY_IDX(arr, i, char*);
  5971. char* filename = strrchr(file, '\\');
  5972. if (filename != NULL) { filename += 1; }
  5973. else { filename = file; }
  5974. fileCount++;
  5975. if (!filelist.IsNullOrEmpty()) {
  5976. filelist += "|";
  5977. }
  5978. filelist += filename;
  5979. }
  5980. toolkit_array_free2(arr);
  5981. }
  5982. filelist += ";";
  5983. arr = fileutil_get_sub_dirs(desktopFullPath);
  5984. if (arr != NULL) {
  5985. for (int i = 0; i < arr->nelts; ++i) {
  5986. char* dir = ARRAY_IDX(arr, i, char*);
  5987. char* dirname = strrchr(dir, '\\');
  5988. if (dirname != NULL) { dirname += 1; }
  5989. else { dirname = dir; }
  5990. dirCount++;
  5991. if (!filelist.IsNullOrEmpty() && i != 0) {
  5992. filelist += "|";
  5993. }
  5994. filelist += dirname;
  5995. }
  5996. toolkit_array_free2(arr);
  5997. }
  5998. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DESKTOP_FILESTATUS, CSimpleStringA::Format(
  5999. "%s's deskop: file(%d),dir(%d), list:(%s)", curUserName, fileCount, dirCount,
  6000. filelist.GetLength() < 950 ? filelist.GetData() : (filelist.SubString(0, 950) + "....").GetData()));
  6001. }
  6002. ErrorCodeEnum ResourceWatcherFSM::DetectVTMInstalledBySetup(BOOL& fYes)
  6003. {
  6004. HKEY key;
  6005. ErrorCodeEnum result(Error_Succeed);
  6006. fYes = FALSE;
  6007. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{123BBC1D-8555-4E90-96CA-70E678FF5C24}_is1";
  6008. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
  6009. if (ERROR_SUCCESS == lResult) {
  6010. fYes = TRUE;
  6011. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
  6012. LogWarn(Severity_Low, Error_Debug, LOG_INFO_INSTALL_BY_SETUP, "Intalled by Setup");
  6013. }
  6014. else if (ERROR_FILE_NOT_FOUND == lResult) {
  6015. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
  6016. fYes = FALSE;
  6017. }
  6018. else {
  6019. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegOpenKeyEx For{123BBC1D-8555-4E90-96CA-70E678FF5C24} error, Result=%ld.", lResult);
  6020. fYes = FALSE;
  6021. result = Error_Unexpect;
  6022. }
  6023. RegCloseKey(key);
  6024. return result;
  6025. }
  6026. bool ResourceWatcherFSM::RegRdVtmVersion(CSimpleStringA& VTMpath, CSimpleStringA& vtmVersion)
  6027. {
  6028. bool bRet = false;
  6029. HKEY key;
  6030. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\VTM";
  6031. CSimpleStringA regParaPath = "path";
  6032. CSimpleStringA regParaVersion = "version";
  6033. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
  6034. char arrVTMpath[MAX_PATH] = { 0 }, arrVTMversion[MAX_PATH] = { 0 };
  6035. if (ERROR_SUCCESS == lResult)
  6036. {
  6037. DWORD dwValue = MAX_PATH * sizeof(CHAR);
  6038. bool res1 = GetRegValue(key, regParaPath, arrVTMpath, &dwValue);
  6039. if (res1) {
  6040. bRet = true;
  6041. VTMpath = arrVTMpath;
  6042. }
  6043. else {
  6044. bRet = false;
  6045. RegCloseKey(key);
  6046. return bRet;
  6047. }
  6048. dwValue = MAX_PATH * sizeof(CHAR);
  6049. bool res2 = GetRegValue(key, regParaVersion, arrVTMversion, &dwValue);
  6050. if (res2) {
  6051. bRet = true;
  6052. vtmVersion = arrVTMversion;
  6053. }
  6054. else {
  6055. bRet = false;
  6056. RegCloseKey(key);
  6057. return bRet;
  6058. }
  6059. }
  6060. else
  6061. {
  6062. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
  6063. bRet = false;
  6064. }
  6065. RegCloseKey(key);
  6066. return bRet;
  6067. }
  6068. bool ResourceWatcherFSM::RegWtVtmPath()
  6069. {
  6070. bool bRet = true;
  6071. HKEY key;
  6072. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
  6073. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
  6074. {
  6075. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
  6076. bRet = false;
  6077. }
  6078. DWORD dwDisposition;
  6079. regPath += "\\VTM";
  6080. if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
  6081. REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
  6082. {
  6083. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
  6084. bRet = false;
  6085. }
  6086. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
  6087. {
  6088. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  6089. bRet = false;
  6090. }
  6091. CSimpleStringA para = "path";
  6092. CSimpleStringA exePath;
  6093. ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
  6094. if (Error_Succeed == Error)
  6095. {
  6096. exePath += "\\VTM.exe";
  6097. if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)exePath.GetData(), MAX_PATH))
  6098. {
  6099. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set path value failed");
  6100. bRet = false;
  6101. }
  6102. }
  6103. else
  6104. {
  6105. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get path of VTM.exe failed.");
  6106. }
  6107. ::RegCloseKey(key);
  6108. return bRet;
  6109. }
  6110. bool ResourceWatcherFSM::RegWtVtmVersion()
  6111. {
  6112. bool bRet = true;
  6113. HKEY key;
  6114. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
  6115. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
  6116. {
  6117. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
  6118. bRet = false;
  6119. }
  6120. DWORD dwDisposition;
  6121. regPath += "\\VTM";
  6122. if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
  6123. REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
  6124. {
  6125. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
  6126. bRet = false;
  6127. }
  6128. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
  6129. {
  6130. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  6131. bRet = false;
  6132. }
  6133. CSimpleStringA para = "version";
  6134. CSimpleStringA csVersion;
  6135. if (GetVtmVersion(csVersion))
  6136. {
  6137. //RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH);
  6138. if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH))
  6139. {
  6140. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  6141. bRet = false;
  6142. }
  6143. }
  6144. else
  6145. {
  6146. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get version of VTM.exe failed.");
  6147. }
  6148. ::RegCloseKey(key);
  6149. return bRet;
  6150. }
  6151. bool ResourceWatcherFSM::RegOperation()
  6152. {
  6153. bool bRet = true;
  6154. CSimpleStringA csVersion, VtmRegPath, VtmRegVersion;
  6155. bool bGetActive = GetVtmVersion(csVersion);
  6156. bool bRegRead = RegRdVtmVersion(VtmRegPath, VtmRegVersion);
  6157. CSimpleStringA rootVerPath, exePath;
  6158. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  6159. exePath = rootVerPath + "\\VTM.exe";
  6160. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("csVersion :%s ,VtmRegVersion:%s ", csVersion.GetData(), VtmRegVersion.GetData());
  6161. if (!ExistsFileA(exePath) || !bGetActive || !bRegRead || (0 != VtmRegVersion.Compare(csVersion, true)))
  6162. {
  6163. if (!CopyExeToRoot())
  6164. {
  6165. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Copy VTM.exe to version root fail.");
  6166. bRet = false;
  6167. }
  6168. else
  6169. {
  6170. if (!RegWtVtmPath())
  6171. {
  6172. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmPath failed.");
  6173. }
  6174. if (!RegWtVtmVersion())
  6175. {
  6176. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmVersion failed.");
  6177. }
  6178. CreateLink(exePath);
  6179. }
  6180. }
  6181. return bRet;
  6182. }
  6183. bool ResourceWatcherFSM::UpdateExe()
  6184. {
  6185. int updateExe = 0;
  6186. CSmartPointer<IConfigInfo> spCtSettingConfig;
  6187. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  6188. spCtSettingConfig->ReadConfigValueInt("NonExclusive", "UpdateExe", updateExe);
  6189. if (updateExe == 1)
  6190. return true;
  6191. return false;
  6192. }
  6193. void ResourceWatcherFSM::VerifySignature()
  6194. {
  6195. LOG_FUNCTION();
  6196. char* buffer = new char[MAX_PATH];
  6197. getcwd(buffer, MAX_PATH);
  6198. strcat(buffer, "\\*");
  6199. DWORD elapsed = 0;
  6200. DWORD dwStart = GetTickCount();
  6201. DWORD dwEnd = GetTickCount();
  6202. VerifySignature(buffer);
  6203. if (m_nonSignedFiles.size() > 0)
  6204. {
  6205. CSimpleStringA fileList = "";
  6206. for (size_t i = 0; i < m_nonSignedFiles.size(); i++)
  6207. {
  6208. fileList += GetFileName(m_nonSignedFiles[i]);
  6209. if (i < m_nonSignedFiles.size() - 1)
  6210. fileList += ",";
  6211. }
  6212. int toDisplay = m_iNonSignedTotal < m_iNonSignedDisplay ? m_iNonSignedTotal : m_iNonSignedDisplay;
  6213. CSimpleStringA strMsg = CSimpleStringA::Format("共有%d个文件未签名,其中%d个为:%s",
  6214. m_iNonSignedTotal, toDisplay, fileList.GetData());
  6215. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_FILE_NOT_TRUSTED, (LPCTSTR)strMsg);
  6216. }
  6217. dwEnd = GetTickCount();
  6218. elapsed = dwEnd - dwStart;
  6219. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Verifying cost:%dms", elapsed);
  6220. delete buffer;
  6221. }
  6222. void ResourceWatcherFSM::VerifySignature(const CSimpleStringA& filePath)
  6223. {
  6224. HANDLE hFind = NULL;
  6225. WIN32_FIND_DATA fileInfo;
  6226. DWORD64 dwSize = 0;
  6227. hFind = FindFirstFile(filePath, &fileInfo);
  6228. if (hFind == INVALID_HANDLE_VALUE)
  6229. return;
  6230. string strDirPath = filePath;
  6231. do
  6232. {
  6233. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  6234. {
  6235. if (!strcmp(fileInfo.cFileName, ".") || !strcmp(fileInfo.cFileName, ".."))
  6236. {
  6237. //Do nothing for "." and ".." folders
  6238. }
  6239. else
  6240. {
  6241. strDirPath.insert(strDirPath.find("*"), string(fileInfo.cFileName) + "\\");
  6242. VerifySignature(strDirPath.c_str());
  6243. strDirPath = filePath;
  6244. }
  6245. }
  6246. else
  6247. {
  6248. CSimpleStringA fileName = fileInfo.cFileName;
  6249. string strFileName = fileName;
  6250. string strFilePath;
  6251. if (strFileName.find(".dll") == string::npos && strFileName.find(".exe") == string::npos)
  6252. continue;
  6253. strFilePath = strDirPath;
  6254. strFilePath.replace(strFilePath.find("*"), strFilePath.length(), string(fileInfo.cFileName));
  6255. if (!RetrieveDigitalSignatureInfo(strFilePath.c_str()))
  6256. {
  6257. if (m_iNonSignedTotal < m_iNonSignedDisplay)
  6258. {
  6259. m_nonSignedFiles.push_back(strFilePath.c_str());
  6260. }
  6261. m_iNonSignedTotal++;
  6262. }
  6263. }
  6264. } while (FindNextFile(hFind, &fileInfo));
  6265. FindClose(hFind);
  6266. }
  6267. CSimpleStringA ResourceWatcherFSM::GetFileName(const CSimpleStringA& filePath)
  6268. {
  6269. CSimpleStringA tmp = filePath;
  6270. auto arrPath = tmp.Split('\\');
  6271. int size = arrPath.GetCount();
  6272. return arrPath[size - 1];
  6273. }
  6274. bool ResourceWatcherFSM::RetrieveDigitalSignatureInfo(const char* pFilePath)
  6275. {
  6276. HCERTSTORE hStore = NULL;
  6277. HCRYPTMSG hMsg = NULL;
  6278. WCHAR* wpFilePath = NULL;
  6279. int len = ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, NULL, 0);
  6280. if (len > 0) {
  6281. wpFilePath = new wchar_t[len + 1];
  6282. std::memset(wpFilePath, 0, (len + 1) * sizeof(wchar_t));
  6283. ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, &wpFilePath[0], len);
  6284. }
  6285. if (CryptQueryObject(CERT_QUERY_OBJECT_FILE,
  6286. wpFilePath,
  6287. CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
  6288. CERT_QUERY_FORMAT_FLAG_BINARY,
  6289. 0,
  6290. NULL,
  6291. NULL,
  6292. NULL,
  6293. &hStore,
  6294. &hMsg,
  6295. NULL))
  6296. {
  6297. DWORD dwCountSigners = 0;
  6298. DWORD dwcbSz = sizeof(dwCountSigners);
  6299. if (CryptMsgGetParam(hMsg, CMSG_SIGNER_COUNT_PARAM, 0, &dwCountSigners, &dwcbSz))
  6300. {
  6301. if (dwCountSigners != 0)
  6302. {
  6303. dwcbSz = 0;
  6304. CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwcbSz);
  6305. if (dwcbSz)
  6306. {
  6307. PCMSG_SIGNER_INFO pSignerInfo = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwcbSz];
  6308. if (pSignerInfo)
  6309. {
  6310. DWORD dwcbSz2 = dwcbSz;
  6311. if (CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, pSignerInfo, &dwcbSz) &&
  6312. dwcbSz == dwcbSz2)
  6313. {
  6314. if (VerifyFirstCertificate(hStore, pSignerInfo)
  6315. || VerifyOtherCertificate(pSignerInfo))
  6316. return true;
  6317. }
  6318. delete[] pSignerInfo;
  6319. pSignerInfo = NULL;
  6320. }
  6321. }
  6322. }
  6323. }
  6324. }
  6325. if (hStore != NULL)
  6326. {
  6327. CertCloseStore(hStore, 0);
  6328. hStore = NULL;
  6329. }
  6330. if (hMsg != NULL)
  6331. {
  6332. CryptMsgClose(hMsg);
  6333. hMsg = NULL;
  6334. }
  6335. return false;
  6336. }
  6337. bool ResourceWatcherFSM::VerifyFirstCertificate(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo)
  6338. {
  6339. CERT_INFO ci = { 0 };
  6340. ci.Issuer = pSignerInfo->Issuer;
  6341. ci.SerialNumber = pSignerInfo->SerialNumber;
  6342. PCCERT_CONTEXT pCertContext = NULL;
  6343. int c = 0;
  6344. bool ret = false;
  6345. for (;; c++)
  6346. {
  6347. pCertContext = CertFindCertificateInStore(hStore,
  6348. ENCODING, 0, CERT_FIND_SUBJECT_CERT,
  6349. (PVOID)&ci, pCertContext);
  6350. if (!pCertContext)
  6351. {
  6352. break;
  6353. }
  6354. DWORD dwcbSz;
  6355. char* pBuff;
  6356. dwcbSz = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
  6357. if (dwcbSz != 0)
  6358. {
  6359. pBuff = new (std::nothrow) char[dwcbSz];
  6360. if (pBuff)
  6361. {
  6362. if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, pBuff, dwcbSz) == dwcbSz)
  6363. {
  6364. if (!strcmp(pBuff, "China Merchants Bank Co., Ltd"))
  6365. ret = true;
  6366. }
  6367. delete[] pBuff;
  6368. pBuff = NULL;
  6369. }
  6370. }
  6371. }
  6372. if (pCertContext)
  6373. {
  6374. CertFreeCertificateContext(pCertContext);
  6375. pCertContext = NULL;
  6376. }
  6377. return ret;
  6378. }
  6379. bool ResourceWatcherFSM::VerifyOtherCertificate(PCMSG_SIGNER_INFO pSignerInfo)
  6380. {
  6381. int ret = false;
  6382. for (DWORD a = 0; a < pSignerInfo->UnauthAttrs.cAttr; a++)
  6383. {
  6384. #ifndef szOID_NESTED_SIGNATURE
  6385. #define szOID_NESTED_SIGNATURE "1.3.6.1.4.1.311.2.4.1"
  6386. #endif
  6387. if (pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId &&
  6388. lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId, szOID_NESTED_SIGNATURE) == 0)
  6389. {
  6390. HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, 0, NULL, NULL, NULL);
  6391. if (hMsg)
  6392. {
  6393. if (::CryptMsgUpdate(hMsg,
  6394. pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData,
  6395. pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData,
  6396. TRUE))
  6397. {
  6398. DWORD dwSignerInfo = 0;
  6399. ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
  6400. if (dwSignerInfo != 0)
  6401. {
  6402. PCMSG_SIGNER_INFO pSignerInfo2 = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwSignerInfo];
  6403. if (pSignerInfo2)
  6404. {
  6405. if (::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM,
  6406. 0, (PVOID)pSignerInfo2, &dwSignerInfo))
  6407. {
  6408. CRYPT_DATA_BLOB c7Data;
  6409. c7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData;
  6410. c7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData;
  6411. //ret = FindAppropriateStoreAndVerifyFirstCertificate(pSignerInfo2, &c7Data);
  6412. HCERTSTORE hStore = NULL;
  6413. hStore = CertOpenStore(CERT_STORE_PROV_PKCS7, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, &c7Data);
  6414. ret = hStore && VerifyFirstCertificate(hStore, pSignerInfo2);
  6415. if (hStore)
  6416. {
  6417. ::CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
  6418. hStore = NULL;
  6419. }
  6420. }
  6421. delete[] pSignerInfo2;
  6422. pSignerInfo2 = NULL;
  6423. }
  6424. }
  6425. }
  6426. ::CryptMsgClose(hMsg);
  6427. }
  6428. }
  6429. }
  6430. return ret;
  6431. }
  6432. void ResourceWatcherFSM::DeleteFiles()
  6433. {
  6434. string p;
  6435. CSmartPointer<IConfigInfo> spCtSettingConfig;
  6436. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  6437. CSimpleStringA upPath(""), tempPath(""), tPath(""), upgradePath("");
  6438. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "DocumentCleanPath", tempPath);
  6439. if (tempPath.GetLength() == 0)
  6440. {
  6441. return;
  6442. }
  6443. //if (tempPath != CSimpleStringA("Temp") && tempPath != CSimpleStringA("Upgraded")) //目前只支持temp文件夹 和 upgrade文件夹
  6444. //{
  6445. // DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Illegal file path [%s].", tempPath.GetData());
  6446. // return;
  6447. //}
  6448. ErrorCodeEnum erroCode = Error_Succeed;
  6449. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  6450. CSmartPointer<IConfigInfo> spConfigRun;
  6451. //判断是否需要被清理
  6452. erroCode = pFunc->OpenConfig(Config_Run, spConfigRun);
  6453. if (erroCode != Error_Succeed)
  6454. {
  6455. LogWarn(Severity_Middle, erroCode, 0, "Open Run Config failed");
  6456. return;
  6457. }
  6458. int nLastTaskTime = 0;
  6459. int nLstFlag = 0;
  6460. CSimpleStringA optFileName("");
  6461. UINT64 utVersion = 0;
  6462. spConfigRun->ReadConfigValueHexInt("DeleteDocumentTask", "OptVer", utVersion);
  6463. spConfigRun->ReadConfigValue("DeleteDocumentTask", "DocumentName", optFileName);
  6464. spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
  6465. spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastTime", nLastTaskTime);
  6466. CVersion optVer(utVersion);
  6467. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  6468. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
  6469. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  6470. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  6471. (LPCTSTR)optVer.ToString(), nLstFlag);
  6472. SYSTEMTIME stNow = {};
  6473. GetLocalTime(&stNow);
  6474. if (optVer.IsValid() && optVer == m_RvcSysinfo.InstallVersion && !nLstFlag && optFileName == tempPath)
  6475. {
  6476. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Certain document cleaning has been done before.");
  6477. return;
  6478. }
  6479. //这里进行过滤处理,最终获取可以清理的路径
  6480. //GetEntityBase()->GetFunction()->GetPath(tempPath.GetData(), upPath);
  6481. //删除upPath目录下的文件
  6482. struct _finddata_t upfileinfo;
  6483. long upFile = 0;
  6484. bool bFailFlag = false;
  6485. WIN32_FIND_DATA wfd;
  6486. HANDLE hFind;
  6487. upPath = tempPath;
  6488. upPath.Append("\\*");
  6489. hFind = FindFirstFile(upPath.GetData(), &wfd);
  6490. if (hFind != INVALID_HANDLE_VALUE)
  6491. {
  6492. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
  6493. {
  6494. //upPath.Append("\\*");
  6495. //char szPath[256] = { 0 };
  6496. //strcat_s(szPath, upPath.GetData());
  6497. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  6498. //nFileCount = ProcessFileDelete(szPath, nDelSuc, nDelFail);
  6499. nFileCount = ProcessFileDelete(upPath.GetData(), nDelSuc, nDelFail);
  6500. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Process result(%s): count(%d), suc(%d), failed(%d).", upPath.GetData(), nFileCount, nDelSuc, nDelFail);
  6501. if (nDelFail != 0)
  6502. {
  6503. bFailFlag = true;
  6504. //break;
  6505. }
  6506. FindClose(hFind);
  6507. }
  6508. else
  6509. {
  6510. if (DeleteFile(tempPath.GetData()) != 0)
  6511. {
  6512. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("删除文件%s成功。", tempPath.GetData());
  6513. //break;
  6514. }
  6515. else
  6516. {
  6517. bFailFlag = true;
  6518. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("删除文件%s失败。", tempPath.GetData());
  6519. }
  6520. }
  6521. }
  6522. else
  6523. {
  6524. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM) ("FindFirstFile failed (%u)", GetLastError());
  6525. }
  6526. nLstFlag = bFailFlag ? 1 : 0;
  6527. spConfigRun->WriteConfigValueHexInt("DeleteDocumentTask", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  6528. spConfigRun->WriteConfigValue("DeleteDocumentTask", "DocumentName", tempPath);
  6529. spConfigRun->WriteConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
  6530. spConfigRun->WriteConfigValue("DeleteDocumentTask", "LastTime",
  6531. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  6532. if (!bFailFlag)
  6533. {
  6534. //std::string warn = "Delete [%s] success.";
  6535. LogWarn(Severity_Low, Error_Debug, LOG_WARN_DIR_DELETE, CSimpleStringA::Format("Delete files in [%s] success", tempPath.GetData()));
  6536. }
  6537. else {
  6538. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete files in [%s] failed.", tempPath.GetData());
  6539. }
  6540. }
  6541. void ResourceWatcherFSM::ShowTerminalStatusPage()
  6542. {
  6543. ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
  6544. ErrorCodeEnum error = chromiumClient->Connect();
  6545. if (error == Error_Succeed)
  6546. {
  6547. ChromiumSrv_OpenBrowser_Req req;
  6548. ChromiumSrv_OpenBrowser_Ans ans;
  6549. int width = GetSystemMetrics(0);
  6550. auto pFunc = GetEntityBase()->GetFunction();
  6551. CSimpleStringA strPath, statusPagePath, fileStart;
  6552. fileStart = "file:///";
  6553. pFunc->GetPath("Bin", strPath);
  6554. strPath += "\\Chromium\\cefclient.exe";
  6555. pFunc->GetPath("Bin", statusPagePath);
  6556. statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\showStatus.html";
  6557. statusPagePath = fileStart + statusPagePath;
  6558. if (!terminalShowFlag)
  6559. {
  6560. /*CSimpleStringA setting = CSimpleStringA::Format(" --center-size=%d*35 --src-pos=%d*0 --top=-1 --logextend=test", width / 5, width - (width / 5));
  6561. CSimpleStringA cmdLine = strPath + " --url=file:///" + statusPagePath + setting;
  6562. WinExec(cmdLine.GetData(), SW_MINIMIZE);*/
  6563. req.mainUrl = statusPagePath;
  6564. req.type = "SpecialPageFromOtherEntity";
  6565. req.name = "terminalStatus";
  6566. req.param1 = CSimpleStringA::Format("%d*35", width / 5);
  6567. req.param2 = CSimpleStringA::Format("%d*0", width - (width / 5));
  6568. req.top = -1;
  6569. error = chromiumClient->OpenBrowser(req, ans, 10000);
  6570. chromiumClient->GetFunction()->CloseSession();
  6571. ::SetCursorPos(0, 0);
  6572. mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
  6573. if (error != Error_Succeed)
  6574. {
  6575. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] failed.", statusPagePath.GetData());
  6576. }
  6577. else
  6578. {
  6579. terminalShowFlag = true;
  6580. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] success.", statusPagePath.GetData());
  6581. }
  6582. }
  6583. }
  6584. }
  6585. void ResourceWatcherFSM::CloseTerminalStatusPage()
  6586. {
  6587. auto pFunc = GetEntityBase()->GetFunction();
  6588. CSimpleStringA strPath, statusPagePath;
  6589. pFunc->GetPath("Bin", strPath);
  6590. strPath += "\\Chromium\\cefclient.exe";
  6591. ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
  6592. ErrorCodeEnum error = chromiumClient->Connect();
  6593. if (error == Error_Succeed)
  6594. {
  6595. ChromiumSrv_CloseBrowser_Req req;
  6596. ChromiumSrv_CloseBrowser_Ans ans;
  6597. if (terminalShowFlag)
  6598. {
  6599. //CSimpleStringA setting = "--logextend=test";
  6600. //CSimpleStringA cmdLine = strPath + " --kill " + setting;
  6601. //WinExec(cmdLine.GetData(), SW_MINIMIZE);
  6602. req.type = "SpecialPageFromOtherEntity";
  6603. req.name = "terminalStatus";
  6604. error = chromiumClient->CloseBrowser(req, ans, 10000);
  6605. if (error != Error_Succeed)
  6606. {
  6607. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [terminalStatus] failed.");
  6608. }
  6609. else
  6610. {
  6611. terminalShowFlag = false;
  6612. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [terminalStatus] success.");
  6613. }
  6614. }
  6615. }
  6616. }
  6617. void ResourceWatcherFSM::GetBatteryStatus() //0: 默认,电池状态和电量变化时广播, 1:每次调用都广播 2:关闭广播功能
  6618. {
  6619. /*
  6620. ACLineStatus: Byte; {0:电源断电; 1:电源正常; 255:电源状态未知}
  6621. BatteryFlag: Byte; {1:电量充足 >66%; 2:电量低 <33%; 4:电池基本耗尽 <5%; 8:充电; 128:没有电池; 255:电池状态未知}
  6622. 如果出现9的状态,则表示充电中+电量大于66%(8+1);
  6623. 如果不给充电,且电池电量介于高电量和低电量之间,则该值为0;
  6624. 如果在33%~%66%之间,且充电,则为8(0+8)。
  6625. 如果在5% ~ 33%之间,且充电,则为10 (2+8)
  6626. 如果在0% ~ 5%之间,且充电,则为……
  6627. BatteryLifePercent: Byte; {0..100:所剩电量百分数; 255:未知}
  6628. Reserved1: Byte; {保留, 须为 0}
  6629. BatteryLifeTime: DWORD; {电池剩余能量; -1 表示未知}
  6630. BatteryFullLifeTime: DWORD; {电池总能量; -1 表示未知}*/
  6631. SYSTEM_POWER_STATUS powerStatus;
  6632. GetSystemPowerStatus(&powerStatus);
  6633. BatteryStatus batteryStatus;
  6634. CSimpleStringA btFlag; //powerStatus.BatteryFlag;
  6635. CSimpleStringA btPercent; // powerStatus.BatteryLifePercent;
  6636. CSimpleStringA acStatus;
  6637. batteryStatus.status = powerStatus.ACLineStatus;
  6638. batteryStatus.reversed1 = powerStatus.BatteryLifePercent;
  6639. if ((powerStatus.ACLineStatus != lastACLineStatus) || (powerStatus.BatteryLifePercent != lastBatteryPercent))
  6640. {
  6641. lastACLineStatus = powerStatus.ACLineStatus;
  6642. lastBatteryPercent = powerStatus.BatteryLifePercent;
  6643. SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(BatteryStatus), SP_MSG_SIG_OF(BatteryStatus), batteryStatus);
  6644. }
  6645. }
  6646. ErrorCodeEnum ResourceWatcherFSM::CheckBatteryStatus(
  6647. SpReqAnsContext<ResourceWatcherService_CheckBatteryStatus_Req, ResourceWatcherService_CheckBatteryStatus_Ans>::Pointer ctx)
  6648. {
  6649. LOG_FUNCTION();
  6650. ErrorCodeEnum ec = Error_Succeed;
  6651. SYSTEM_POWER_STATUS powerStatus;
  6652. GetSystemPowerStatus(&powerStatus);
  6653. ctx->Ans.status = powerStatus.ACLineStatus;
  6654. ctx->Ans.percent = powerStatus.BatteryLifePercent;
  6655. if (ctx != NULL) {
  6656. ctx->Answer(ec);
  6657. }
  6658. return ec;
  6659. }
  6660. void ResourceWatcherFSM::ClearDumpFiles()
  6661. {
  6662. int deleteSucCnt = 0;
  6663. int deleteFailedCnt = 0;
  6664. int fileCnt = 0;
  6665. CSimpleStringA dmpPath;
  6666. ErrorCodeEnum dmpError = GetEntityBase()->GetFunction()->GetPath("Temp", dmpPath);
  6667. if (Error_Succeed != dmpError) {
  6668. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get Dump path error");
  6669. return;
  6670. }
  6671. dmpPath += CSimpleStringA::Format("\\..\\dmp");
  6672. // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
  6673. char searchFilePath[MAX_PATH] = { 0 };
  6674. char tempFilePath[MAX_PATH] = { 0 };
  6675. char displayTime[MAX_PATH] = { 0 };
  6676. WIN32_FIND_DATA foundFileData;
  6677. HANDLE hFind;
  6678. CSmartPointer<IConfigInfo> spCtSettingConfig;
  6679. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  6680. int backDay = 0;
  6681. ErrorCodeEnum re = spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "DumpClearBackDay", backDay);
  6682. if (backDay < 7 || backDay >365 || re != Error_Succeed)
  6683. {
  6684. backDay = 7; //保留至少七天的dump文件
  6685. }
  6686. FILETIME ftRemoveTime;
  6687. CalculateBackTime(&ftRemoveTime, backDay);
  6688. GetTimeString(displayTime, MAX_PATH, &ftRemoveTime);
  6689. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("The date DUMPFILE backward to delete: %s", displayTime);
  6690. string p;
  6691. hFind = FindFirstFile(p.assign(string(dmpPath.GetData())).append("\\*").c_str(), &foundFileData);
  6692. if (hFind != INVALID_HANDLE_VALUE) {
  6693. do {
  6694. if (CSimpleStringA::Format("%s", &foundFileData.cFileName) == "." || CSimpleStringA::Format("%s", &foundFileData.cFileName) == "..")
  6695. {
  6696. continue;
  6697. }
  6698. if (CompareFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0)
  6699. {
  6700. GetTimeString(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
  6701. //strcpy_s(searchFilePath, (dmpPath + CSimpleStringA::Format("\\%s", &foundFileData.cFileName)).GetData());
  6702. if (DeleteFile((dmpPath + CSimpleStringA::Format("\\%s", &foundFileData.cFileName)).GetData()) != 0)
  6703. {
  6704. deleteSucCnt++;
  6705. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete DUMPFILE matched %s(%s) suc.", foundFileData.cFileName, displayTime);
  6706. }
  6707. else
  6708. {
  6709. deleteFailedCnt++;
  6710. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete DUMPFILE matched %s(%s) failed(%d).", foundFileData.cFileName, displayTime, GetLastError());
  6711. }
  6712. }
  6713. fileCnt++;
  6714. } while (FindNextFile(hFind, &foundFileData));
  6715. FindClose(hFind);
  6716. }
  6717. else
  6718. {
  6719. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM) ("FindFirstFile failed (%u)", GetLastError());
  6720. return;
  6721. }
  6722. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Total [%d] dump files, delete suc[%d], failed[%d].", fileCnt, deleteSucCnt, deleteFailedCnt);
  6723. return;
  6724. }
  6725. void ResourceWatcherFSM::FsmCreateWindow(CSimpleStringA text, int txtsize, int delayMS, int txtx, int txty)
  6726. {
  6727. //if (GetHWnd() != NULL)
  6728. //{
  6729. // //closegraph();
  6730. // CloseWindow(GetHWnd());
  6731. // closegraph();
  6732. // return;
  6733. //}
  6734. //initgraph(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), 0);
  6735. //HWND hwnd = GetHWnd();
  6736. //::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & (~(WS_CAPTION | WS_SYSMENU | WS_SIZEBOX)));
  6737. //::SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) & (~(WS_EX_WINDOWEDGE | WS_EX_DLGMODALFRAME)) | WS_EX_LAYERED | WS_EX_TOOLWINDOW);
  6738. ///*SetWindowPos(hwnd, HWND_TOPMOST, (GetSystemMetrics(SM_CXSCREEN) - getwidth()) / 2, (GetSystemMetrics(SM_CYSCREEN) - getheight()) / 2, getwidth(), getheight(), SWP_SHOWWINDOW
  6739. // | SWP_FRAMECHANGED | SWP_DRAWFRAME);*/
  6740. //SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_SHOWWINDOW
  6741. // | SWP_FRAMECHANGED | SWP_DRAWFRAME);
  6742. //SetLayeredWindowAttributes(hwnd, 0x000000, 0, LWA_COLORKEY);
  6743. //setcolor(RGB(0, 0, 1)); //黑色
  6744. //setbkcolor(RGB(255, 240, 192)); //背景色
  6745. ////line(0, 0, 800, 600);
  6746. ////std::string time = "abc";
  6747. ////const char* a = time.c_str();
  6748. //LOGFONT f;
  6749. //gettextstyle(&f); // 获取当前字体设置
  6750. //f.lfHeight = txtsize; // 设置字体高度;
  6751. //_tcscpy(f.lfFaceName, _T("黑体")); // 设置字体为“黑体”(高版本 VC 推荐使用 _tcscpy_s 函数)
  6752. //f.lfQuality = ANTIALIASED_QUALITY; // 设置输出效果为抗锯齿
  6753. //settextstyle(&f);
  6754. //int width = textwidth(text.GetData());
  6755. //int height = textheight(text.GetData());
  6756. //if (txtx < 0 || txty < 0)
  6757. //{
  6758. // outtextxy((GetSystemMetrics(SM_CXSCREEN) - width) / 2, (GetSystemMetrics(SM_CYSCREEN) - height) / 2, text.GetData());
  6759. //}
  6760. //else
  6761. //{
  6762. // outtextxy(txtx, txty, text.GetData());
  6763. //}
  6764. //if(delayMS > 0)
  6765. //{
  6766. // Sleep(delayMS);
  6767. // CloseWindow(GetHWnd());
  6768. // closegraph();
  6769. //}
  6770. ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
  6771. ErrorCodeEnum error = chromiumClient->Connect();
  6772. if (error == Error_Succeed)
  6773. {
  6774. ChromiumSrv_OpenBrowser_Req req;
  6775. ChromiumSrv_OpenBrowser_Ans ans;
  6776. int width = GetSystemMetrics(0);
  6777. auto pFunc = GetEntityBase()->GetFunction();
  6778. CSimpleStringA strPath, statusPagePath, fileStart;
  6779. fileStart = "file:///";
  6780. pFunc->GetPath("Bin", strPath);
  6781. strPath += "\\Chromium\\cefclient.exe";
  6782. pFunc->GetPath("Bin", statusPagePath);
  6783. if (text == "软件升级安装中,请稍等……")
  6784. {
  6785. statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\installMessage.html";
  6786. req.param1 = CSimpleStringA::Format("750*80");
  6787. }
  6788. else if (text == "升级完成,可视柜台即将重启,请稍等……")
  6789. {
  6790. statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\restartMessage.html";
  6791. req.param1 = CSimpleStringA::Format("1100*80");
  6792. }
  6793. //statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\installMessage.html";
  6794. statusPagePath = fileStart + statusPagePath;
  6795. req.mainUrl = statusPagePath;
  6796. req.type = "SpecialPageFromOtherEntity";
  6797. req.name = "tempMessage";
  6798. //req.param1 = CSimpleStringA::Format("1000*70");
  6799. //req.param2 = CSimpleStringA::Format("%d*0", width - (width / 5));
  6800. req.top = -1;
  6801. error = chromiumClient->OpenBrowser(req, ans, 10000);
  6802. chromiumClient->GetFunction()->CloseSession();
  6803. ::SetCursorPos(0, 0);
  6804. mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
  6805. if (error != Error_Succeed)
  6806. {
  6807. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] failed.", statusPagePath.GetData());
  6808. }
  6809. else
  6810. {
  6811. tmpMessageWindFlag = true;
  6812. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] success.", statusPagePath.GetData());
  6813. }
  6814. }
  6815. if (delayMS > 0)
  6816. {
  6817. Sleep(delayMS);
  6818. ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
  6819. ErrorCodeEnum error = chromiumClient->Connect();
  6820. if (error == Error_Succeed)
  6821. {
  6822. ChromiumSrv_CloseBrowser_Req req;
  6823. ChromiumSrv_CloseBrowser_Ans ans;
  6824. req.type = "SpecialPageFromOtherEntity";
  6825. req.name = "tempMessage";
  6826. error = chromiumClient->CloseBrowser(req, ans, 10000);
  6827. /*auto pFunc = GetEntityBase()->GetFunction();
  6828. CSimpleStringA strPath, statusPagePath;
  6829. pFunc->GetPath("Bin", strPath);
  6830. strPath += "\\Chromium\\cefclient.exe --kill --logextend=tempMessage";
  6831. WinExec(strPath.GetData(), SW_MINIMIZE);
  6832. ::SetCursorPos(0, 0);
  6833. mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);*/
  6834. if (error != Error_Succeed)
  6835. {
  6836. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [tempMessage] failed.");
  6837. }
  6838. else
  6839. {
  6840. tmpMessageWindFlag = false;
  6841. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [tempMessage] success.");
  6842. }
  6843. }
  6844. }
  6845. }
  6846. #endif // _MSC_VER 截止到创建弹窗
  6847. #ifdef _MSC_VER //硬件资源监控相关系统功能 CPU、内存、硬盘、网络wifi
  6848. long long GetDirSizeFsm(string dirPath)
  6849. {
  6850. long long fileLen = 0;
  6851. long hFile = 0;
  6852. //文件信息
  6853. struct _finddata_t fileinfo;
  6854. string p;
  6855. if ((hFile = _findfirst(p.assign(dirPath).append("\\*").c_str(), &fileinfo)) != -1)
  6856. {
  6857. do
  6858. {
  6859. //如果是目录,迭代之
  6860. //如果不是,加入列表
  6861. if ((fileinfo.attrib & _A_SUBDIR))
  6862. {
  6863. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  6864. fileLen += GetDirSizeFsm(p.assign(dirPath).append("\\").append(fileinfo.name));
  6865. }
  6866. else
  6867. {
  6868. fileLen += fileinfo.size;
  6869. }
  6870. } while (_findnext(hFile, &fileinfo) == 0);
  6871. _findclose(hFile);
  6872. }
  6873. return fileLen;
  6874. }
  6875. struct CmpByValueFromBiggest //从最大的排起
  6876. {
  6877. bool operator()(const pair<string, long>& l, const pair<string, long>& r) {
  6878. return l.second > r.second;
  6879. }
  6880. };
  6881. //unordered_map<string, long> fileSpace;
  6882. unordered_map<string, long> fileIncreasedSpace;
  6883. vector<pair<string, long>> sortFileIncreasedSpace;
  6884. unordered_map<string, long> fileSpace;
  6885. vector<pair<string, long>> sortFileSpace;
  6886. static bool spaceLock = false;
  6887. void ResourceWatcherFSM::CheckDiskFileSpace()
  6888. {
  6889. if (spaceLock)
  6890. {
  6891. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("当前已有硬盘扫描进行中,跳过。");
  6892. return;
  6893. }
  6894. else
  6895. {
  6896. spaceLock = true; //加锁
  6897. }
  6898. CSmartPointer<IConfigInfo> spConfigRun;
  6899. CSmartPointer<IConfigInfo> spCtSettingConfig;
  6900. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  6901. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  6902. int lastDiskUsed = 0;
  6903. unsigned long long lastVer = 0;
  6904. int spaceIncrease = 0; //硬盘增长阈值
  6905. spConfigRun->ReadConfigValueHexInt("SpaceInfo", "OptVer", lastVer);
  6906. spConfigRun->ReadConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", lastDiskUsed);
  6907. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "DiskUsedIncreaseInt(GB)", spaceIncrease);
  6908. if (spaceIncrease == 0)
  6909. {
  6910. spaceIncrease = 5; //默认阈值5GB
  6911. }
  6912. if (!isNeedForceDiskCheck) //是否需要强制全盘扫描 - 硬盘使用过高是会强制
  6913. {
  6914. if (lastVer == m_RvcSysinfo.InstallVersion.GetVersion64())
  6915. {
  6916. if (lastDiskUsed != 0 && ((int)(GetDiskUsedByte() / (1024 * 1024 * 1024)) - lastDiskUsed) < spaceIncrease) //增长值判定
  6917. {
  6918. //DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("硬盘空间增长未超过阈值,无需扫描。");
  6919. if (spaceLock)
  6920. {
  6921. spaceLock = false; //释放锁
  6922. }
  6923. return;
  6924. }
  6925. else
  6926. {
  6927. //降低磁盘扫描频率
  6928. SYSTEMTIME localTime;
  6929. GetLocalTime(&localTime);
  6930. if (m_diskLastWarnHour != localTime.wHour)
  6931. {
  6932. m_diskLastWarnHour = localTime.wHour;
  6933. CSmartPointer<IConfigInfo> spConfigRun;
  6934. ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  6935. if (eErr == Error_Succeed) {
  6936. spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  6937. }
  6938. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("硬盘增长超过阈值,重点目录扫描!");
  6939. }
  6940. else
  6941. {
  6942. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("磁盘增长最近1小时已扫描一次,暂不扫描。");
  6943. if (spaceLock)
  6944. {
  6945. spaceLock = false; //释放锁
  6946. }
  6947. return;
  6948. }
  6949. }
  6950. }
  6951. else
  6952. {
  6953. spConfigRun->WriteConfigValueHexInt("SpaceInfo", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  6954. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("新版本,重点目录扫描");
  6955. }
  6956. }
  6957. else
  6958. {
  6959. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("强制扫描。");
  6960. }
  6961. CSystemStaticInfo sysInfo;
  6962. string path("");
  6963. GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
  6964. if (sysInfo.strMachineType == "RVC.PAD")
  6965. {
  6966. path = "C:";
  6967. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("pad设备。扫描C盘。");
  6968. }
  6969. else
  6970. {
  6971. path = "D:";
  6972. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("非pad设备。扫描D盘。");
  6973. }
  6974. if (path.size() == 0)
  6975. {
  6976. if (spaceLock)
  6977. {
  6978. spaceLock = false; //释放锁
  6979. }
  6980. return;
  6981. }
  6982. long long fileLen = 0;
  6983. long hFile = 0;
  6984. //文件信息
  6985. struct _finddata_t fileinfo;
  6986. string p;
  6987. if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
  6988. {
  6989. do
  6990. {
  6991. //如果是目录,迭代之
  6992. //如果不是,加入列表
  6993. if ((fileinfo.attrib & _A_SUBDIR))
  6994. {
  6995. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  6996. fileLen = GetDirSizeFsm(p.assign(path).append("\\").append(fileinfo.name));
  6997. else
  6998. {
  6999. continue;
  7000. }
  7001. }
  7002. else
  7003. {
  7004. fileLen = fileinfo.size;
  7005. }
  7006. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  7007. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  7008. {
  7009. DOUBLE len = (DOUBLE)fileLen / 1024;
  7010. resLen = CSimpleStringA::Format("%.2f KB", len);
  7011. }
  7012. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  7013. {
  7014. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  7015. resLen = CSimpleStringA::Format("%.2f MB", len);
  7016. }
  7017. else if (fileLen >= (1024 * 1024 * 1024))
  7018. {
  7019. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  7020. resLen = CSimpleStringA::Format("%.2f GB", len);
  7021. }
  7022. CSimpleStringA oldLenStr("");
  7023. long oldLen = 0;
  7024. spConfigRun->ReadConfigValue("SpaceInfo",
  7025. p.assign(path).append("\\").append(fileinfo.name).c_str(), oldLenStr);
  7026. oldLen = atol(oldLenStr.GetData());
  7027. fileIncreasedSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  7028. fileSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  7029. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  7030. p.assign(path).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  7031. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  7032. {
  7033. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\").append(fileinfo.name).c_str(),
  7034. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  7035. }
  7036. } while (_findnext(hFile, &fileinfo) == 0);
  7037. _findclose(hFile);
  7038. }
  7039. //获取version目录下的文件夹大小
  7040. CSimpleStringA csPath;
  7041. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  7042. fileLen = 0;
  7043. hFile = 0;
  7044. p = "";
  7045. if ((hFile = _findfirst(p.assign(csPath.GetData()).append("\\*").c_str(), &fileinfo)) != -1)
  7046. {
  7047. do
  7048. {
  7049. //如果是目录,迭代之
  7050. //如果不是,加入列表
  7051. if ((fileinfo.attrib & _A_SUBDIR))
  7052. {
  7053. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  7054. fileLen = GetDirSizeFsm(p.assign(csPath.GetData()).append("\\").append(fileinfo.name));
  7055. else
  7056. {
  7057. continue;
  7058. }
  7059. }
  7060. else
  7061. {
  7062. fileLen = fileinfo.size;
  7063. }
  7064. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  7065. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  7066. {
  7067. DOUBLE len = (DOUBLE)fileLen / 1024;
  7068. resLen = CSimpleStringA::Format("%.2f KB", len);
  7069. }
  7070. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  7071. {
  7072. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  7073. resLen = CSimpleStringA::Format("%.2f MB", len);
  7074. }
  7075. else if (fileLen >= (1024 * 1024 * 1024))
  7076. {
  7077. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  7078. resLen = CSimpleStringA::Format("%.2f GB", len);
  7079. }
  7080. CSimpleStringA oldLenStr(""); //MB
  7081. long oldLen = 0;
  7082. spConfigRun->ReadConfigValue("SpaceInfo",
  7083. p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), oldLenStr);
  7084. oldLen = atol(oldLenStr.GetData());
  7085. fileIncreasedSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  7086. fileSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  7087. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  7088. p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  7089. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  7090. {
  7091. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(),
  7092. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  7093. }
  7094. } while (_findnext(hFile, &fileinfo) == 0);
  7095. _findclose(hFile);
  7096. }
  7097. //获取rvc目录下的文件夹大小
  7098. fileLen = 0;
  7099. hFile = 0;
  7100. p = "";
  7101. if ((hFile = _findfirst(p.assign(path).append("\\rvc\\*").c_str(), &fileinfo)) != -1)
  7102. {
  7103. do
  7104. {
  7105. //如果是目录,迭代之
  7106. //如果不是,加入列表
  7107. if ((fileinfo.attrib & _A_SUBDIR))
  7108. {
  7109. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  7110. fileLen = GetDirSizeFsm(p.assign(path).append("\\rvc\\").append(fileinfo.name));
  7111. else
  7112. {
  7113. continue;
  7114. }
  7115. }
  7116. else
  7117. {
  7118. fileLen = fileinfo.size;
  7119. }
  7120. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  7121. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  7122. {
  7123. DOUBLE len = (DOUBLE)fileLen / 1024;
  7124. resLen = CSimpleStringA::Format("%.2f KB", len);
  7125. }
  7126. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  7127. {
  7128. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  7129. resLen = CSimpleStringA::Format("%.2f MB", len);
  7130. }
  7131. else if (fileLen >= (1024 * 1024 * 1024))
  7132. {
  7133. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  7134. resLen = CSimpleStringA::Format("%.2f GB", len);
  7135. }
  7136. CSimpleStringA oldLenStr("");
  7137. long oldLen = 0;
  7138. spConfigRun->ReadConfigValue("SpaceInfo",
  7139. p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), oldLenStr);
  7140. oldLen = atol(oldLenStr.GetData());
  7141. fileIncreasedSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  7142. fileSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  7143. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  7144. p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), resLen.GetData());
  7145. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  7146. {
  7147. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(),
  7148. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  7149. }
  7150. } while (_findnext(hFile, &fileinfo) == 0);
  7151. _findclose(hFile);
  7152. }
  7153. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  7154. {
  7155. //写入硬盘量
  7156. spConfigRun->WriteConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", GetDiskUsedByte() / (1024 * 1024 * 1024));
  7157. if (spaceLock)
  7158. {
  7159. spaceLock = false; //释放锁
  7160. }
  7161. return; //新版本无需上报文件信息,更新完运行时文件后即可结束
  7162. }
  7163. //获取增量最大的前十文件夹信息
  7164. sortFileIncreasedSpace = vector<pair<string, long>>(fileIncreasedSpace.begin(), fileIncreasedSpace.end());
  7165. sort(sortFileIncreasedSpace.begin(), sortFileIncreasedSpace.end(), CmpByValueFromBiggest());
  7166. int topFileNum = sortFileIncreasedSpace.size();
  7167. if (topFileNum > 10)
  7168. {
  7169. topFileNum = 10;
  7170. }
  7171. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("变化最大的%d个文件夹信息。", topFileNum);
  7172. fileLen = 0;
  7173. for (int i = 0; i < topFileNum; i++)
  7174. {
  7175. fileLen = sortFileIncreasedSpace[i].second;
  7176. if (fileLen == 0) break;
  7177. //Dbg("TOP %d: [%s], 增量[%ld]MB", i + 1, sortFileIncreasedSpace[i].first.c_str(), sortFileIncreasedSpace[i].second);
  7178. CSimpleStringA warn1 = CSimpleStringA::Format("TOP %d: [%s], 增量[%ld]MB",
  7179. i + 1, sortFileIncreasedSpace[i].first.c_str(), sortFileIncreasedSpace[i].second);
  7180. LogWarn(Severity_Middle, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPINCREASED_SPACE, warn1.GetData());
  7181. }
  7182. if (isNeedForceDiskCheck)
  7183. {
  7184. //获取空间占用最大前十文件夹信息
  7185. sortFileSpace = vector<pair<string, long>>(fileSpace.begin(), fileSpace.end());
  7186. sort(sortFileSpace.begin(), sortFileSpace.end(), CmpByValueFromBiggest());
  7187. int topFileSize = sortFileSpace.size();
  7188. if (topFileSize > 10)
  7189. {
  7190. topFileSize = 10;
  7191. }
  7192. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("空间占用最大的%d个文件夹信息。", topFileSize);
  7193. fileLen = 0;
  7194. for (int i = 0; i < topFileSize; i++)
  7195. {
  7196. fileLen = sortFileSpace[i].second;
  7197. if (fileLen == 0) break;
  7198. //Dbg("空间占用排名 %d: [%s], 大小[%ld]MB", i + 1, sortFileSpace[i].first.c_str(), sortFileSpace[i].second);
  7199. CSimpleStringA warn2 = CSimpleStringA::Format("空间占用排名 %d: [%s], 大小[%ld]MB",
  7200. i + 1, sortFileSpace[i].first.c_str(), sortFileSpace[i].second);
  7201. LogWarn(Severity_Middle, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warn2.GetData());
  7202. }
  7203. isNeedForceDiskCheck = false;
  7204. }
  7205. if (spaceLock)
  7206. {
  7207. spaceLock = false; //释放锁
  7208. }
  7209. }
  7210. void ResourceWatcherFSM::GetSystemDiskStatus()
  7211. {
  7212. ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
  7213. BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
  7214. if (ret == 0)
  7215. {
  7216. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
  7217. return;
  7218. }
  7219. CSimpleStringA csBinPath;
  7220. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
  7221. //Dbg("%d,%d,%d",(ulAvailFree.QuadPart/MILLION)*100,ulTotalBytes.QuadPart,(ulTotalBytes.QuadPart/MILLION));
  7222. DWORD dwAvFree = ulAvailFree.QuadPart / MILLION;
  7223. DWORD dwTotal = ulTotalBytes.QuadPart / MILLION;
  7224. DWORD dwTotalFree = ulTotalFree.QuadPart / MILLION;
  7225. int ratio = dwTotalFree * 100 / dwTotal;
  7226. if (m_diskHighPercent <= 0)
  7227. {
  7228. m_diskHighPercent = 90; //默认硬盘告警百分比90%
  7229. }
  7230. if ((100 - ratio) > m_diskHighPercent)
  7231. {
  7232. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("The disk has %d MB(%d%%) available.\n", dwTotalFree, ratio);
  7233. string test(csBinPath.GetData());
  7234. char diskMessage[1024];
  7235. sprintf(diskMessage, "{\"Disk\":\"%c:\",\"total\":\"%0.2f GByte\",\"free ratio\":\"%d%%\"}",
  7236. csBinPath.GetData()[0], (double)dwTotal / 1024, ratio);
  7237. //oilyang@20200526 根据wq建议,降低磁盘空间偏少的告警频率
  7238. SYSTEMTIME localTime;
  7239. GetLocalTime(&localTime);
  7240. if (m_diskLastWarnHour != localTime.wHour) //需要告警时才强制全盘扫描
  7241. {
  7242. m_diskLastWarnHour = localTime.wHour;
  7243. CSmartPointer<IConfigInfo> spConfigRun;
  7244. ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  7245. if (eErr == Error_Succeed) {
  7246. spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  7247. }
  7248. //LogWarn(Severity_Low, Error_Resource, LOG_EVT_SELFCHECK_HARDDISK_TOO_HIGH, "Harddisk free space is few.");
  7249. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, diskMessage);
  7250. isNeedForceDiskCheck = true;
  7251. }
  7252. }
  7253. else
  7254. {
  7255. isNeedForceDiskCheck = false;
  7256. }
  7257. CheckDiskFileSpaceTask* task4 = new CheckDiskFileSpaceTask(this);
  7258. GetEntityBase()->GetFunction()->PostThreadPoolTask(task4);
  7259. }
  7260. ULONGLONG ResourceWatcherFSM::GetDiskUsedByte()
  7261. {
  7262. ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
  7263. BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
  7264. if (ret == 0)
  7265. {
  7266. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
  7267. return -1;
  7268. }
  7269. CSimpleStringA csBinPath;
  7270. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
  7271. //Dbg("%lld,%lld,%lld",ulAvailFree.QuadPart,ulTotalBytes.QuadPart, ulTotalFree.QuadPart);
  7272. //DWORD dwAvFree = ulAvailFree.QuadPart / MILLION;
  7273. //DWORD dwTotal = ulTotalBytes.QuadPart / MILLION;
  7274. //DWORD dwTotalFree = ulTotalFree.QuadPart / MILLION;
  7275. //int ratio = dwTotalFree * 100 / dwTotal;
  7276. return ulTotalBytes.QuadPart - ulTotalFree.QuadPart;
  7277. }
  7278. __int64 Filetime2Int64(const FILETIME& ftime)
  7279. {
  7280. LARGE_INTEGER li;
  7281. li.LowPart = ftime.dwLowDateTime;
  7282. li.HighPart = ftime.dwHighDateTime;
  7283. return li.QuadPart;
  7284. }
  7285. __int64 CompareFileTime2(const FILETIME& preTime, const FILETIME& nowTime)
  7286. {
  7287. return Filetime2Int64(nowTime) - Filetime2Int64(preTime);
  7288. }
  7289. unordered_map<int, long long> oldProcessTime;
  7290. unordered_map<int, long long> newProcessTime;
  7291. unordered_map<int, CSimpleStringA> processName;
  7292. unordered_map<int, double> processCpu;
  7293. bool cmp(const pair<int, double>& a, const pair<int, double>& b) {
  7294. return a.second > b.second;
  7295. }
  7296. void ResourceWatcherFSM::GetSystemCPUStatus()
  7297. {
  7298. FILETIME preIdleTime;
  7299. FILETIME preKernelTime;
  7300. FILETIME preUserTime;
  7301. FILETIME preProcCreateTime;
  7302. FILETIME preProcExitTime;
  7303. FILETIME preProcKernelTime;
  7304. FILETIME preProcUserTime;
  7305. GetSystemTimes(&preIdleTime, &preKernelTime, &preUserTime);
  7306. PROCESSENTRY32 pe32Old;
  7307. pe32Old.dwSize = sizeof(pe32Old);
  7308. //获得系统进程快照的句柄
  7309. HANDLE hProcessSnapOld = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  7310. if (hProcessSnapOld == INVALID_HANDLE_VALUE)
  7311. {
  7312. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  7313. return;
  7314. }
  7315. //首先获得第一个进程
  7316. BOOL bProcessOld = Process32First(hProcessSnapOld, &pe32Old);
  7317. //循环获得所有进程
  7318. while (bProcessOld)
  7319. {
  7320. //进程名和进程ID
  7321. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32Old.th32ProcessID);
  7322. GetProcessTimes(hProcess, &preProcCreateTime, &preProcExitTime, &preProcKernelTime, &preProcUserTime);
  7323. oldProcessTime[pe32Old.th32ProcessID] = Filetime2Int64(preProcKernelTime) + Filetime2Int64(preProcUserTime);
  7324. bProcessOld = Process32Next(hProcessSnapOld, &pe32Old);
  7325. }
  7326. CloseHandle(hProcessSnapOld);
  7327. Sleep(1000);
  7328. FILETIME idleTime;
  7329. FILETIME kernelTime;
  7330. FILETIME userTime;
  7331. FILETIME ProcCreateTime;
  7332. FILETIME ProcExitTime;
  7333. FILETIME procKernelTime;
  7334. FILETIME procUserTime;
  7335. GetSystemTimes(&idleTime, &kernelTime, &userTime);
  7336. PROCESSENTRY32 pe32New;
  7337. pe32New.dwSize = sizeof(pe32New);
  7338. //获得系统进程快照的句柄
  7339. HANDLE hProcessSnapNew = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  7340. if (hProcessSnapNew == INVALID_HANDLE_VALUE)
  7341. {
  7342. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  7343. return;
  7344. }
  7345. //首先获得第一个进程
  7346. BOOL bProcessNew = Process32First(hProcessSnapNew, &pe32New);
  7347. //循环获得所有进程
  7348. while (bProcessNew)
  7349. {
  7350. //进程名和进程ID
  7351. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32New.th32ProcessID);
  7352. GetProcessTimes(hProcess, &ProcCreateTime, &ProcExitTime, &procKernelTime, &procUserTime);
  7353. newProcessTime[pe32New.th32ProcessID] = Filetime2Int64(procKernelTime) + Filetime2Int64(procUserTime);
  7354. processName[pe32New.th32ProcessID] = CSimpleStringA(pe32New.szExeFile);
  7355. bProcessNew = Process32Next(hProcessSnapNew, &pe32New);
  7356. }
  7357. CloseHandle(hProcessSnapNew);
  7358. auto idle = CompareFileTime2(preIdleTime, idleTime);
  7359. auto kernel = CompareFileTime2(preKernelTime, kernelTime);
  7360. auto user = CompareFileTime2(preUserTime, userTime);
  7361. if (kernel + user == 0)
  7362. return;
  7363. CSystemRunInfo runInfo = { 0 };
  7364. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  7365. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
  7366. {
  7367. runInfo.strRunningEntityNames[i];
  7368. CEntityRunInfo entityInfo = { 0 };
  7369. GetEntityBase()->GetFunction()->GetEntityRunInfo(runInfo.strRunningEntityNames[i].GetData(), entityInfo);
  7370. processName[entityInfo.dwProcessID] = runInfo.strRunningEntityNames[i];
  7371. }
  7372. unordered_map<int, long long>::iterator it;
  7373. for (it = newProcessTime.begin(); it != newProcessTime.end(); ++it)
  7374. {
  7375. int tPid = it->first;
  7376. //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
  7377. if (oldProcessTime.find(tPid) == oldProcessTime.end())
  7378. {
  7379. continue;
  7380. }
  7381. double tRatio = 100.0 * (newProcessTime[tPid] - oldProcessTime[tPid]) / (kernel + user);
  7382. if (tRatio > 0.0)
  7383. {
  7384. processCpu[tPid] = tRatio;
  7385. //Dbg("process[%s] CPU[%.2f].", processName[tPid].GetData(), tRatio);
  7386. }
  7387. }
  7388. vector<pair<int, double>> vec(processCpu.begin(), processCpu.end());
  7389. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  7390. int len = min(10, vec.size());
  7391. CSimpleStringA procWarn = "";
  7392. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  7393. {
  7394. procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.2f", vec[i].second) + "%\"";
  7395. }
  7396. double cpuRatio = 100.0 * (kernel + user - idle) / (kernel + user);
  7397. //Dbg("total CPU[%.2f].", cpuRatio);
  7398. if (m_cpuHighPercent <= 0)
  7399. {
  7400. m_cpuHighPercent = 80; //默认告警百分比80%
  7401. }
  7402. if (cpuRatio > (double)m_cpuHighPercent)
  7403. {
  7404. CSimpleStringA warn = CSimpleStringA::Format("{ \"total_used\":\" %.2f", cpuRatio);
  7405. warn = warn + "%\"" + procWarn + "}";
  7406. LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, warn.GetData());
  7407. }
  7408. }
  7409. unsigned long long convert_time_format(const FILETIME* ftime)
  7410. {
  7411. LARGE_INTEGER li;
  7412. li.LowPart = ftime->dwLowDateTime;
  7413. li.HighPart = ftime->dwHighDateTime;
  7414. return li.QuadPart;
  7415. }
  7416. /// 时间转换
  7417. static uint64_t file_time_2_utc(const FILETIME* ftime)
  7418. {
  7419. LARGE_INTEGER li;
  7420. li.LowPart = ftime->dwLowDateTime;
  7421. li.HighPart = ftime->dwHighDateTime;
  7422. return li.QuadPart;
  7423. }
  7424. /// 获得CPU的核数
  7425. static int get_processor_number()
  7426. {
  7427. SYSTEM_INFO info;
  7428. GetSystemInfo(&info);
  7429. return (int)info.dwNumberOfProcessors;
  7430. }
  7431. int ResourceWatcherFSM::GetCpuUsageRatio(int pid)
  7432. {
  7433. //cpu数量
  7434. static int processor_count_ = -1;
  7435. //上一次的时间
  7436. static int64_t last_time_ = 0;
  7437. static int64_t last_system_time_ = 0;
  7438. FILETIME now;
  7439. FILETIME creation_time;
  7440. FILETIME exit_time;
  7441. FILETIME kernel_time;
  7442. FILETIME user_time;
  7443. int64_t system_time;
  7444. int64_t time;
  7445. int64_t system_time_delta;
  7446. int64_t time_delta;
  7447. int cpu = -1;
  7448. if (processor_count_ == -1)
  7449. {
  7450. processor_count_ = get_processor_number();
  7451. }
  7452. GetSystemTimeAsFileTime(&now);
  7453. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
  7454. if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
  7455. {
  7456. return -1;
  7457. }
  7458. system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time))
  7459. / processor_count_;
  7460. time = file_time_2_utc(&now);
  7461. if ((last_system_time_ == 0) || (last_time_ == 0))
  7462. {
  7463. last_system_time_ = system_time;
  7464. last_time_ = time;
  7465. return -1;
  7466. }
  7467. system_time_delta = system_time - last_system_time_;
  7468. time_delta = time - last_time_;
  7469. if (time_delta == 0)
  7470. return -1;
  7471. cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta);
  7472. last_system_time_ = system_time;
  7473. last_time_ = time;
  7474. return cpu;
  7475. }
  7476. double GetMemoryUsageGB(int pid)
  7477. {
  7478. #ifdef WIN32
  7479. DWORDLONG mem = 0, vmem = 0;
  7480. PROCESS_MEMORY_COUNTERS pmc;
  7481. // get process hanlde by pid
  7482. HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  7483. if (GetProcessMemoryInfo(process, &pmc, sizeof(pmc)))
  7484. {
  7485. mem = pmc.WorkingSetSize;
  7486. vmem = pmc.PagefileUsage;
  7487. }
  7488. CloseHandle(process);
  7489. // use GetCurrentProcess() can get current process and no need to close handle
  7490. // convert mem from B to GB
  7491. double memGB = mem / (1024.0 * 1024.0 * 1024.0);
  7492. return memGB;
  7493. #else
  7494. char file_name[64] = { 0 };
  7495. FILE* fd;
  7496. char line_buff[512] = { 0 };
  7497. sprintf(file_name, "/proc/%d/status", pid);
  7498. fd = fopen(file_name, "r");
  7499. if (nullptr == fd)
  7500. return 0;
  7501. char name[64];
  7502. int vmrss = 0;
  7503. for (int i = 0; i < VMRSS_LINE - 1; i++)
  7504. fgets(line_buff, sizeof(line_buff), fd);
  7505. fgets(line_buff, sizeof(line_buff), fd);
  7506. sscanf(line_buff, "%s %d", name, &vmrss);
  7507. fclose(fd);
  7508. // cnvert VmRSS from KB to MB
  7509. return vmrss / 1024.0;
  7510. #endif
  7511. }
  7512. unordered_map<int, double> processMem;
  7513. void ResourceWatcherFSM::GetSystemMemoryStatus()
  7514. {
  7515. // Use to convert bytes to KB
  7516. #define DIV 1024
  7517. // Specify the width of the field in which to print the numbers.
  7518. // The asterisk in the format specifier "%*I64d" takes an integer
  7519. // argument and uses it to pad and right justify the number.
  7520. #define WIDTH 7
  7521. MEMORYSTATUSEX statex;
  7522. statex.dwLength = sizeof(statex);
  7523. GlobalMemoryStatusEx(&statex);
  7524. double totalMem = statex.ullTotalPhys / (1024.0 * 1024.0 * 1024.0); //GB
  7525. unordered_map<int, CSimpleStringA>::iterator it;
  7526. for (it = processName.begin(); it != processName.end(); ++it)
  7527. {
  7528. int tPid = it->first;
  7529. double tmp = GetMemoryUsageGB(it->first);
  7530. if (tmp > 0.0)
  7531. {
  7532. processMem[tPid] = 100 * (tmp / totalMem);
  7533. }
  7534. }
  7535. //return;
  7536. vector<pair<int, double>> vec(processMem.begin(), processMem.end());
  7537. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  7538. int len = min(10, vec.size());
  7539. CSimpleStringA procWarn = "";
  7540. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  7541. {
  7542. procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.1f", vec[i].second) + "%\"";
  7543. }
  7544. if (m_memHighPercent <= 0)
  7545. {
  7546. m_memHighPercent = 80; //默认告警百分比80%
  7547. }
  7548. if (statex.dwMemoryLoad > m_memHighPercent)
  7549. {
  7550. CSimpleStringA warn = CSimpleStringA::Format("{\"total\":\"%.1f GByte\",\"total_used\":\" %d%%\"", totalMem, statex.dwMemoryLoad);
  7551. warn = warn + procWarn + "}";
  7552. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, warn.GetData());
  7553. }
  7554. }
  7555. int ResourceWatcherFSM::IsWifiConnected()
  7556. {
  7557. DWORD service_ver;
  7558. HANDLE handle = NULL;
  7559. int result = -1;
  7560. DWORD err = WlanOpenHandle(WLAN_API_VERSION, NULL, &service_ver, &handle);
  7561. if (err != 0) {
  7562. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("open wlan handle failed %d", err);
  7563. return result;
  7564. }
  7565. PWLAN_INTERFACE_INFO_LIST info_list = NULL;
  7566. PWLAN_INTERFACE_INFO interface_info = NULL;
  7567. err = WlanEnumInterfaces(handle, NULL, &info_list);
  7568. if (err != ERROR_SUCCESS) {
  7569. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Enum wlan interface failed %d", err);
  7570. WlanCloseHandle(handle, NULL);
  7571. return -1;
  7572. }
  7573. const int count = info_list->dwNumberOfItems;
  7574. for (int i = 0; i < count; ++i) {
  7575. interface_info = &info_list->InterfaceInfo[i];
  7576. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("wireless interface name: %s", SP::Module::Util::W2S(interface_info->strInterfaceDescription).c_str());
  7577. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("state: %d", interface_info->isState);
  7578. if (interface_info->isState == wlan_interface_state_connected) {
  7579. result = 1;
  7580. }
  7581. DWORD radio_state_info_size = sizeof(WLAN_RADIO_STATE);
  7582. PWLAN_RADIO_STATE radio_state_info_ptr = NULL;
  7583. WLAN_OPCODE_VALUE_TYPE op_code = wlan_opcode_value_type_invalid;
  7584. err = WlanQueryInterface(handle, &interface_info->InterfaceGuid, wlan_intf_opcode_radio_state,
  7585. NULL, &radio_state_info_size, (PVOID*)&radio_state_info_ptr, &op_code);
  7586. if (err != ERROR_SUCCESS) {
  7587. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("WlanQueryInterface failed %d", err);
  7588. }
  7589. else {
  7590. const uint32_t count_of_phys = radio_state_info_ptr->dwNumberOfPhys;
  7591. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of valid PHYs: %d", count_of_phys);
  7592. if (count_of_phys > 0 && result == -1) {
  7593. if (dot11_radio_state_on == radio_state_info_ptr->PhyRadioState[0].dot11SoftwareRadioState) {
  7594. result = 0;
  7595. }
  7596. else {
  7597. /*
  7598. for (int j = 0; j < count_of_phys; ++j) {
  7599. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("software radio state: %d, %d", j , radio_state_info_ptr->PhyRadioState[j].dot11SoftwareRadioState);
  7600. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("hardware radio state: %d, %d", j, radio_state_info_ptr->PhyRadioState[j].dot11HardwareRadioState);
  7601. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("**********************");
  7602. }
  7603. */
  7604. }
  7605. }
  7606. }
  7607. }
  7608. if (info_list != NULL) {
  7609. WlanFreeMemory(info_list);
  7610. }
  7611. WlanCloseHandle(handle, NULL);
  7612. return result;
  7613. }
  7614. #endif // _MSC_VER end硬件资源监控相关系统功能 CPU、内存、硬盘、网络wifi
  7615. ErrorCodeEnum ResourceWatcherFSM::CatchSystemBasicInfo(SystemBasicInfo& info)
  7616. {
  7617. CSimpleStringA runCfgPath;
  7618. ErrorCodeEnum errCode = GetEntityBase()->GetFunction()->GetPath("RunCfg", runCfgPath);
  7619. if (runCfgPath.IsNullOrEmpty()) return Error_Null;
  7620. CSimpleStringA storeFilePath = runCfgPath + SPLIT_SLASH_STR + "SMBIOSData.txt";
  7621. if (!ExistsFileA(storeFilePath)) {
  7622. RemoveFileA(storeFilePath);
  7623. }
  7624. std::string succStr, errStr;
  7625. std::string runStr("dmidecode -t system > ");
  7626. runStr += storeFilePath.GetData();
  7627. if (!SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  7628. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("execute '%s' failed!", runStr.c_str());
  7629. if (!ExistsFileA(storeFilePath)) {
  7630. RemoveFileA(storeFilePath);
  7631. }
  7632. return Error_Unexpect;
  7633. }
  7634. do
  7635. {
  7636. std::string succStr, errStr;
  7637. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Manufacturer\"){print$2}' ");
  7638. runStr += storeFilePath.GetData();
  7639. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  7640. info.strManufacturer = SP::Utility::ToTrim(succStr).c_str();
  7641. } else {
  7642. succStr = "";
  7643. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Manufacturer' failed!");
  7644. }
  7645. } while (false);
  7646. do {
  7647. std::string succStr, errStr;
  7648. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Product Name\"){print$2}' ");
  7649. runStr += storeFilePath.GetData();
  7650. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  7651. info.strProductName = SP::Utility::ToTrim(succStr).c_str();
  7652. } else {
  7653. succStr = "";
  7654. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Product Name' failed!");
  7655. }
  7656. } while (false);
  7657. do {
  7658. std::string succStr, errStr;
  7659. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Serial Number\"){print$2}' ");
  7660. runStr += storeFilePath.GetData();
  7661. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  7662. info.strSerialNumber = SP::Utility::ToTrim(succStr).c_str();
  7663. } else {
  7664. succStr = "";
  7665. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Serial Number' failed!");
  7666. }
  7667. } while (false);
  7668. if (!ExistsFileA(storeFilePath)) {
  7669. RemoveFileA(storeFilePath);
  7670. }
  7671. return Error_Succeed;
  7672. }
  7673. void ResourceWatcherFSM::AlarmSystemBasicInfo()
  7674. {
  7675. SystemBasicInfo info;
  7676. if (Error_Succeed == CatchSystemBasicInfo(info)) {
  7677. CSimpleStringA strResult("{");
  7678. if (!info.strManufacturer.IsNullOrEmpty()) {
  7679. strResult += CSimpleStringA::Format("\"Manufacturer\":\"%s\"", info.strManufacturer.GetData());
  7680. }
  7681. if (!info.strProductName.IsNullOrEmpty()) {
  7682. if (strResult.GetLength() > 1) {
  7683. strResult += ", ";
  7684. }
  7685. strResult += CSimpleStringA::Format("\"Product Name\":\"%s\"", info.strProductName.GetData());
  7686. }
  7687. if (!info.strSerialNumber.IsNullOrEmpty()) {
  7688. if (strResult.GetLength() > 1) {
  7689. strResult += ", ";
  7690. }
  7691. strResult += CSimpleStringA::Format("\"Serial Number\":\"%s\"", info.strSerialNumber.GetData());
  7692. }
  7693. strResult += "}";
  7694. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DEVICE_SMBIOS_GET, strResult);
  7695. }
  7696. }
  7697. #ifdef RVC_OS_LINUX
  7698. void ResourceWatcherFSM::UploadMonitorSettings()
  7699. {
  7700. CSmartPointer<IConfigInfo> spCtSettingConfig;
  7701. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  7702. int nSwitchOff(0);
  7703. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenOFF", nSwitchOff);
  7704. if (!!nSwitchOff) {
  7705. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Cancel monitor change listen!");
  7706. if (m_bFirstRunAfterBoot) {
  7707. CSimpleStringA value(true);
  7708. bool res = GetMonitorInfo(value);
  7709. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  7710. }
  7711. } else {
  7712. int nInterval(10000);
  7713. int nValue(0);
  7714. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenInterval", nValue);
  7715. if (nValue >= 10000) {
  7716. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Update monitor listen interval from %d to %d", nInterval, nValue);
  7717. nInterval = nValue;
  7718. }
  7719. CSimpleStringA strLastMonitor(true);
  7720. bool readFromCfgFalg(true);
  7721. CSmartPointer<IConfigInfo> spRunConfig;
  7722. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  7723. spRunConfig->ReadConfigValue("MonitorAttribute", "LastInfo", strLastMonitor);
  7724. do
  7725. {
  7726. CSimpleStringA value(true);
  7727. bool res = GetMonitorInfo(value);
  7728. if (!value.IsNullOrEmpty() && (strLastMonitor.IsNullOrEmpty() || (strLastMonitor.Compare(value) != 0))) {
  7729. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  7730. CSmartPointer<IConfigInfo> spRunConfig;
  7731. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  7732. spRunConfig->WriteConfigValue("MonitorAttribute", "LastInfo", value);
  7733. strLastMonitor = value;
  7734. if (readFromCfgFalg) {
  7735. readFromCfgFalg = false;
  7736. }
  7737. } else if (readFromCfgFalg && !strLastMonitor.IsNullOrEmpty() && strLastMonitor.Compare(value) == 0) {
  7738. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  7739. readFromCfgFalg = false;
  7740. }
  7741. Sleep(nInterval);
  7742. } while (true);
  7743. }
  7744. }
  7745. void ResourceWatcherFSM::DetectSoftwareInstallStatus()
  7746. {
  7747. CSmartPointer<IConfigInfo> spCtSettingConfig;
  7748. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  7749. CSimpleStringA strSoftwaresNames[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
  7750. CSimpleStringA strSoftwaresVers[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
  7751. int nNameCounts = 0;
  7752. for (int i = 0; i < MAX_SOFTWARE_INSTALLED_DETECT_COUNT; i++) {
  7753. strSoftwaresNames[i] = "";
  7754. strSoftwaresVers[i] = "";
  7755. CSimpleStringA item = CSimpleStringA::Format("SoftwareInstallDetect%d", i);
  7756. CSimpleStringA value(true);
  7757. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), item, value);
  7758. if (value.IsNullOrEmpty()) {
  7759. break;
  7760. }
  7761. if (value.IndexOf("#") != -1) {
  7762. CAutoArray<CSimpleStringA> items = value.Split('#');
  7763. strSoftwaresNames[i] = items[0];
  7764. strSoftwaresVers[i] = items[1];
  7765. } else {
  7766. strSoftwaresNames[i] = value;
  7767. }
  7768. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect SoftDetect from CentralSetting, %d: %s,%s,%s."
  7769. , i, item.GetData(), strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData());
  7770. nNameCounts++;
  7771. }
  7772. if (nNameCounts > 0) {
  7773. for (int i = 0; i < nNameCounts; ++i) {
  7774. CSimpleStringA runItem = CSimpleStringA::Format("dpkg -l | grep %s | awk '{print $3}'", strSoftwaresNames[i].GetData());
  7775. std::string additional("");
  7776. std::string succStr, errStr;
  7777. std::string runStr(runItem.GetData());
  7778. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  7779. if (succStr.empty()) {
  7780. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i,
  7781. CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"not installed\"}", strSoftwaresNames[i].GetData()));
  7782. } else {
  7783. succStr = SP::Utility::ToTrim(succStr);
  7784. if (strSoftwaresVers[i].IsNullOrEmpty() || strSoftwaresVers[i].Compare(succStr.c_str()) == 0) {
  7785. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_BASE + i,
  7786. CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\"}"
  7787. , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData()));
  7788. } else {
  7789. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i,
  7790. CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\", \"expected\":\"%s\"}"
  7791. , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData()));
  7792. }
  7793. }
  7794. } else {
  7795. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_STATUS_FAILED,
  7796. CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"detect failed\", \"expected\":\"%s\"}"
  7797. , strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData()));
  7798. }
  7799. }
  7800. }
  7801. }
  7802. BOOL ResourceWatcherFSM::DetectIsFirstRunAtBoot()
  7803. {
  7804. CSystemRunInfo runInfo = { 0 };
  7805. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  7806. BOOL bSet = FALSE;
  7807. CBootInfo bootInfo = { 0 };
  7808. CSmallDateTime dateTime;
  7809. Dbg("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
  7810. ErrorCodeEnum erroCode = GetEntityBase()->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
  7811. Dbg("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
  7812. CSmallDateTime systemBootTime;
  7813. BOOL bRet = GetSystemBootTime(systemBootTime);
  7814. if (bRet && systemBootTime > bootInfo.tmStart) {
  7815. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
  7816. if (eRet != Error_Succeed) {
  7817. Dbg("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
  7818. }
  7819. bSet = TRUE;
  7820. std::map<std::string, std::string> srcData;
  7821. srcData.insert(std::make_pair("OSStartTime", systemBootTime.ToTimeString().GetData()));
  7822. srcData.insert(std::make_pair("AppStartTime", (LPCTSTR)runInfo.tmStart.ToTimeString()));
  7823. srcData.insert(std::make_pair("AppLastStartTime", (LPCTSTR)bootInfo.tmStart.ToTimeString()));
  7824. auto ret = generateJsonStr(srcData);
  7825. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT, ret.second.c_str());
  7826. }
  7827. else {
  7828. GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
  7829. bSet = FALSE;
  7830. }
  7831. return bSet;
  7832. }
  7833. UINT ResourceWatcherFSM::GetSystemDisplayVersion(CSimpleStringA& strVersion)
  7834. {
  7835. UINT result = 0;
  7836. const char filePath[] = "/etc/os-version";
  7837. strVersion.Clear();
  7838. char tmp[33];
  7839. memset(tmp, 0, 33);
  7840. inifile_read_str_s("Version", "MajorVersion", "unknown", tmp, 32, filePath);
  7841. strVersion = tmp;
  7842. strVersion += ".";
  7843. memset(tmp, 0, 33);
  7844. inifile_read_str_s("Version", "MinorVersion", "unknown", tmp, 32, filePath);
  7845. strVersion += tmp;
  7846. strVersion += ".";
  7847. result = atoi(tmp);
  7848. memset(tmp, 0, 33);
  7849. inifile_read_str_s("Version", "OsBuild", "unknown", tmp, 32, filePath);
  7850. strVersion += tmp;
  7851. return result;
  7852. }
  7853. void ResourceWatcherFSM::UploadSysVersionInfo(UINT& ver)
  7854. {
  7855. std::map<std::string, std::string> srcData;
  7856. CSimpleStringA osver;
  7857. ver = GetSystemDisplayVersion(osver);
  7858. srcData.insert(std::make_pair("os-version", osver)); ////当前操作系统版本(系统信息)
  7859. tk_utsname_t t;
  7860. osutil_uname(&t);
  7861. srcData.insert(std::make_pair("sysname", t.sysname)); ////当前操作系统名
  7862. srcData.insert(std::make_pair("release", t.release)); ////当前发布级别
  7863. srcData.insert(std::make_pair("version", t.version)); ////当前发布版本
  7864. srcData.insert(std::make_pair("machine", t.machine)); ////当前硬件体系类型
  7865. do {
  7866. std::string sucContent, failedContent;
  7867. std::string cmd("cat /proc/cpuinfo |grep \"model name\" | awk 'NR==1'");
  7868. bool ret = SP::Module::Util::ShellExecute(cmd, sucContent, failedContent);
  7869. Dbg("{%s}:{%s}{%s}", cmd.c_str(), sucContent.c_str(), failedContent.c_str());
  7870. //std::size_t found = sucContent.rfind("\n");
  7871. //if (found != std::string::npos) {
  7872. // sucContent.replace(found, strlen("\n"), "");
  7873. //}
  7874. auto elems = SP::Utility::Split(sucContent, ':');
  7875. if (elems.size() > 1) {
  7876. sucContent = SP::Utility::ToTrim(elems[1]);
  7877. }
  7878. srcData.insert(std::make_pair("cpu-type", sucContent));
  7879. } while (false);
  7880. //#if defined(RVC_OS_LINUX)
  7881. // CSystemStaticInfo sysInfo;
  7882. // ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
  7883. // if (eErr == Error_Succeed) {
  7884. // termInfo["MachineMode"] = (LPCTSTR)sysInfo.strMachineModel;
  7885. // termInfo["MachineSN"] = (LPCTSTR)sysInfo.strMachineSN;
  7886. // }
  7887. //#endif //RVC_OS_LINUX
  7888. auto ret = generateJsonStr(srcData);
  7889. LogWarn(Severity_Low, Error_Hardware, LOG_RESOURCEWATCHER_SYSTEMINFO, ret.second.c_str());
  7890. }
  7891. string ResourceWatcherFSM::MemoryProcessStatus()
  7892. {
  7893. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  7894. CSmartPointer<IConfigInfo> spConfig;
  7895. ErrorCodeEnum erroCode = Error_Unexpect;
  7896. ///*TODO: 不要每次都进来读取配置文件 (80374374@5/17/2023)*/
  7897. spFunction->OpenConfig(Config_CenterSetting, spConfig);
  7898. int memTop = 0;
  7899. erroCode = spConfig->ReadConfigValueInt("TOPProcess", "mem", memTop);
  7900. if (memTop == 0) {
  7901. memTop = 10;
  7902. } else if (memTop == -1) {
  7903. return "";
  7904. }
  7905. map<string, string> nameProcess;
  7906. CSystemRunInfo runInfo = { 0 };
  7907. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  7908. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++)
  7909. {
  7910. string entityName = runInfo.strRunningEntityNames[i].GetData();
  7911. CEntityRunInfo entityInfo = { 0 };
  7912. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  7913. nameProcess[to_string(entityInfo.dwProcessID)] = entityName;
  7914. }
  7915. FILE* fp;
  7916. char buffer[2048];
  7917. string cmd = "ps c -eo pid,%mem,rss,command | sort -k3 -rn | head -" + to_string(memTop);
  7918. fp = popen(cmd.c_str(), "r");
  7919. int i = 0;
  7920. string s;
  7921. string str[4];
  7922. //mem
  7923. Dbg("MEM TOP %d PROCESS!", memTop);
  7924. string topMessage = "";
  7925. while (i < memTop)
  7926. {
  7927. fgets(buffer, sizeof(buffer), fp);
  7928. s = buffer;
  7929. istringstream is(s);
  7930. is >> str[0] >> str[1] >> str[2] >> str[3];
  7931. double temp;
  7932. stringstream ss1;
  7933. ss1 << str[2];
  7934. ss1 >> temp;
  7935. temp = temp / (1024 * 1024);
  7936. stringstream ss2;
  7937. ss2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << temp;
  7938. str[2] = ss2.str();
  7939. if (nameProcess.find(str[0]) != nameProcess.end())
  7940. {
  7941. str[3] = nameProcess[str[0]];
  7942. }
  7943. topMessage = topMessage + "\"" + str[3] + "\"" + ":" + "\"" + str[1] + "%\"";
  7944. if (i != memTop - 1)
  7945. {
  7946. topMessage += ",";
  7947. }
  7948. ++i;
  7949. }
  7950. topMessage += "}";
  7951. pclose(fp);
  7952. return topMessage;
  7953. }
  7954. long ResourceWatcherFSM::GetCPURunTime(CPUInfo* cpu) //获取CPU的当前信息,同时返回CPU使用时间
  7955. {
  7956. FILE* fd;
  7957. char buff[1024] = { 0 };
  7958. CPUInfo* cpuInfo = cpu;
  7959. fd = fopen("/proc/stat", "r");
  7960. if (!fd) {
  7961. Dbg("Read CPU Info FAILED!");
  7962. return -1;
  7963. }
  7964. fgets(buff, sizeof(buff), fd);
  7965. char name[64] = { 0 };
  7966. sscanf(buff, "%s %u %u %u %u %u %u %u",
  7967. cpuInfo->name, &cpuInfo->user, &cpuInfo->nice, &cpuInfo->system, &cpuInfo->idle, &cpuInfo->lowait, &cpuInfo->irq, &cpuInfo->softirq);
  7968. fclose(fd);
  7969. return (cpuInfo->user + cpuInfo->nice + cpuInfo->system + cpuInfo->idle + cpuInfo->lowait + cpuInfo->irq + cpuInfo->softirq);
  7970. }
  7971. long ResourceWatcherFSM::ReadProcCPURunTime(DWORD pid, ProcCPUInfo* pInfo) { //根据pid读取进程占用的CPU时间
  7972. char file_name[64] = { 0 };
  7973. FILE* fd;
  7974. char line_buff[1024] = { 0 };
  7975. sprintf(file_name, "/proc/%d/stat", pid);
  7976. fd = fopen(file_name, "r");
  7977. if (nullptr == fd) {
  7978. Dbg("Read PROCESS[%d] CPU Info FAILED!", pid);
  7979. return -1;
  7980. }
  7981. fgets(line_buff, sizeof(line_buff), fd);
  7982. sscanf(line_buff, "%u %s", &pInfo->pid, pInfo->pname);
  7983. const char* q = GetItems(line_buff, PROCESS_ITEM);
  7984. sscanf(q, "%ld %ld %ld %ld", &pInfo->utime, &pInfo->stime, &pInfo->cutime, &pInfo->cstime);
  7985. fclose(fd);
  7986. return (pInfo->utime + pInfo->stime + pInfo->cutime + pInfo->cstime);
  7987. }
  7988. //获取第N项开始的指针
  7989. const char* ResourceWatcherFSM::GetItems(const char* buffer, unsigned int item) {
  7990. const char* p = buffer;
  7991. int len = strlen(buffer);
  7992. int count = 0;
  7993. for (int i = 0; i < len; i++) {
  7994. if (' ' == *p) {
  7995. count++;
  7996. if (count == item - 1) {
  7997. p++;
  7998. break;
  7999. }
  8000. }
  8001. p++;
  8002. }
  8003. return p;
  8004. }
  8005. bool cmp(const pair<DWORD, DOUBLE>& a, const pair<DWORD, DOUBLE>& b) {
  8006. return a.second > b.second;
  8007. }
  8008. /* -----------------------
  8009. 根据先后两个时间的CPU信息,
  8010. 计算CPU的总占用量和各个进程的占用量
  8011. ----------------------- */
  8012. void ResourceWatcherFSM::GetSystemCPUStatus()
  8013. {
  8014. //int cpu_num = sysconf(_SC_NPROCESSORS_CONF); //CPU核数
  8015. CPUInfo* cpuOld = new CPUInfo;
  8016. CPUInfo* cpuNew = new CPUInfo;
  8017. const char* tPath = "/proc";
  8018. map<DWORD, string> nameProcess; // <pid, 进程名>
  8019. map<DWORD, DOUBLE> usageProcess; // <pid, CPU占用率>
  8020. long oldTotalTime = GetCPURunTime(cpuOld); //旧CPU运行总时间
  8021. if (oldTotalTime == -1)
  8022. {
  8023. return;
  8024. }
  8025. map<DWORD, long> oldProcCPUTime; // <pid, 旧时刻进程的CPU占用时间>
  8026. struct dirent* oldDirp;
  8027. DIR* oldDp = opendir(tPath);
  8028. if (oldDp != NULL) {
  8029. while ((oldDirp = readdir(oldDp)) != NULL) { //获取旧时刻 每一个进程的pid、CPU运行时间、进程名
  8030. string fileName = oldDirp->d_name;
  8031. BOOL isPid = TRUE;
  8032. for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
  8033. {
  8034. if (!isdigit(fileName[i]))
  8035. {
  8036. isPid = FALSE;
  8037. break;
  8038. }
  8039. }
  8040. if (!isPid) continue;
  8041. DWORD pid;
  8042. long oldTime;
  8043. ProcCPUInfo* oldProcCPU = new ProcCPUInfo;
  8044. sscanf(oldDirp->d_name, "%d", &pid); //读取文件夹名
  8045. oldTime = ReadProcCPURunTime(pid, oldProcCPU);
  8046. if (oldTime == -1)
  8047. {
  8048. return;
  8049. }
  8050. oldProcCPUTime[pid] = oldTime;
  8051. nameProcess[pid] = oldProcCPU->pname;
  8052. delete oldProcCPU;
  8053. }
  8054. closedir(oldDp);
  8055. }
  8056. sleep(1);
  8057. long newTotalTime = GetCPURunTime(cpuNew); //新CPU运行总时间
  8058. if (newTotalTime == -1)
  8059. {
  8060. return;
  8061. }
  8062. map<DWORD, long> newProcCPUTime; // <pid, 新时刻进程的CPU占用时间>
  8063. struct dirent* newDirp;
  8064. DIR* newDp = opendir(tPath);
  8065. if (newDp != NULL) {
  8066. while ((newDirp = readdir(newDp)) != NULL) { //获取新时刻 每一个进程的pid、CPU运行时间、进程名
  8067. string fileName = newDirp->d_name;
  8068. BOOL isPid = TRUE;
  8069. for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
  8070. {
  8071. if (!isdigit(fileName[i]))
  8072. {
  8073. isPid = FALSE;
  8074. break;
  8075. }
  8076. }
  8077. if (!isPid) continue;
  8078. DWORD pid;
  8079. long newTime;
  8080. ProcCPUInfo* newProcCPU = new ProcCPUInfo;
  8081. sscanf(newDirp->d_name, "%d", &pid); //读取文件夹名
  8082. newTime = ReadProcCPURunTime(pid, newProcCPU);
  8083. if (newTime == -1)
  8084. {
  8085. return;
  8086. }
  8087. newProcCPUTime[pid] = newTime;
  8088. string tName = newProcCPU->pname;
  8089. tName.erase(tName.begin());
  8090. tName.erase(tName.begin() + (tName.length() - 1));
  8091. nameProcess[pid] = tName;
  8092. delete newProcCPU;
  8093. }
  8094. closedir(newDp);
  8095. }
  8096. map<DWORD, long>::iterator it;
  8097. for (it = newProcCPUTime.begin(); it != newProcCPUTime.end(); ++it)
  8098. {
  8099. DWORD tPid = it->first;
  8100. //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
  8101. DOUBLE tRatio = 100.0 * (newProcCPUTime[tPid] - oldProcCPUTime[tPid]) / (newTotalTime - oldTotalTime);
  8102. usageProcess[tPid] = tRatio;
  8103. }
  8104. CSystemRunInfo runInfo = { 0 };
  8105. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  8106. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
  8107. {
  8108. string entityName = runInfo.strRunningEntityNames[i].GetData();
  8109. CEntityRunInfo entityInfo = { 0 };
  8110. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  8111. nameProcess[entityInfo.dwProcessID] = entityName;
  8112. }
  8113. vector<pair<DWORD, DOUBLE>> vec(usageProcess.begin(), usageProcess.end());
  8114. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  8115. int len = MIN(cpuTop, vec.size());
  8116. Dbg("CPU TOP %d PROCESS!", len);
  8117. string procWarn = "";
  8118. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  8119. {
  8120. char* tUsage = new char[20];
  8121. sprintf(tUsage, "%.2lf", vec[i].second);
  8122. procWarn = procWarn + ",\"" + nameProcess[vec[i].first] + "\":\"" + string(tUsage) + "%\"";
  8123. delete tUsage;
  8124. }
  8125. unsigned long oldInfo, newInfo;
  8126. double cUsedRate = 0;
  8127. //第一次(用户+优先级+系统+空闲)的时间
  8128. //oldInfo = (unsigned long)(cpuOld->user + cpuOld->nice + cpuOld->system + cpuOld->idle + cpuOld->lowait + cpuOld->irq + cpuOld->softirq);
  8129. //第二次(用户+优先级+系统+空闲)的时间
  8130. //newInfo = (unsigned long)(cpuNew->user + cpuNew->nice + cpuNew->system + cpuNew->idle + cpuNew->lowait + cpuNew->irq + cpuNew->softirq);
  8131. double totalTime = newTotalTime - oldTotalTime;
  8132. double freeTime = cpuNew->idle - cpuOld->idle;
  8133. cUsedRate = (totalTime - freeTime) / totalTime;
  8134. if (cUsedRate < 0.8) {
  8135. //Dbg("[CPU] used rate: %.1lf%%.", cUsedRate * 100);
  8136. }
  8137. else {
  8138. stringstream tss;
  8139. tss << std::setiosflags(std::ios::fixed) << std::setprecision(2) << cUsedRate * 100;
  8140. string warn = "{ \"total_used\":\"" + tss.str() + "%\"" + procWarn + "}";
  8141. //Dbg("%s", warn.c_str());
  8142. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  8143. }
  8144. delete cpuNew;
  8145. delete cpuOld;
  8146. }
  8147. void ResourceWatcherFSM::GetSystemMemoryStatus()
  8148. {
  8149. MemInfo* memInfo = new MemInfo();
  8150. FILE* fd;
  8151. char buff[256];
  8152. fd = fopen("/proc/meminfo", "r");
  8153. if (!fd) {
  8154. Dbg("Read Memory INFO FAILED!");
  8155. return;
  8156. }
  8157. fgets(buff, sizeof(buff), fd);
  8158. sscanf(buff, "%s %lu ", memInfo->infoName1, &memInfo->memTotal);
  8159. fgets(buff, sizeof(buff), fd);
  8160. sscanf(buff, "%s %lu ", memInfo->infoName2, &memInfo->memFree);
  8161. fgets(buff, sizeof(buff), fd);
  8162. sscanf(buff, "%s %lu ", memInfo->infoName3, &memInfo->memAvail);
  8163. fclose(fd);
  8164. double mUsedRate = 0;
  8165. mUsedRate = (double)(memInfo->memTotal - memInfo->memAvail) / (double)memInfo->memTotal;
  8166. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  8167. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  8168. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE];
  8169. ByteSprintf(szResult, (double)(memInfo->memTotal) * 1024, 'G'); // 内存信息在 /proc/meminfo 中的单位为 KB
  8170. ByteSprintf(szResult2, (double)(memInfo->memFree) * 1024, 'G');
  8171. ByteSprintf(szResult3, (double)(memInfo->memAvail) * 1024, 'G');
  8172. if (mUsedRate < 0.8) {
  8173. //Dbg("[Memory] total: %s, free: %s, available: %s, [Memory] used rate: %.1lf%%.", szResult, szResult2, szResult3, mUsedRate * 100);
  8174. }
  8175. else {
  8176. /*LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH,
  8177. CSimpleStringA::Format("MEMORY TOO HIGH! -- [Memory] total: %s, free: %s, available: %s, [Memory] used rate: %.1lf%%.",
  8178. szResult, szResult2, szResult3, mUsedRate * 100)
  8179. );*/
  8180. char usedResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  8181. ByteSprintf(usedResult, (double)(memInfo->memTotal) * 1024 * mUsedRate, 'G');
  8182. stringstream ss1;
  8183. ss1 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << mUsedRate * 100;
  8184. string warn = "{ \"total\":\"" + string(szResult) + "\"," +
  8185. "\"used\":\"" + ss1.str() + "%\"," + MemoryProcessStatus();
  8186. Dbg("%s", warn.c_str());
  8187. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  8188. }
  8189. }
  8190. void ResourceWatcherFSM::GetDiskStatusFrom(LPCTSTR path)
  8191. {
  8192. unsigned long long uiTotalBytes;
  8193. unsigned long long uiFreeDiskBytes;
  8194. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  8195. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  8196. BOOL readFlag = DiskInfo::GetDiskSpace(path, uiTotalBytes, uiFreeDiskBytes);
  8197. double dUsedRate = 1 - (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  8198. ByteSprintf(szResult, (double)uiTotalBytes);
  8199. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  8200. if (readFlag && (dUsedRate < 0.9)) {
  8201. //Dbg("[Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.", path, szResult, szResult2, dUsedRate * 100);
  8202. }
  8203. else {
  8204. std::time_t now = std::time(nullptr);
  8205. std::tm* local_time = std::localtime(&now);
  8206. if (m_diskLastWarnHour != local_time->tm_hour)
  8207. {
  8208. m_diskLastWarnHour = local_time->tm_hour;
  8209. CSmartPointer<IConfigInfo> spConfigRun;
  8210. ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  8211. if (eErr == Error_Succeed) {
  8212. spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  8213. }
  8214. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH,
  8215. CSimpleStringA::Format("DISK TOO HIGH! -- [Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.",
  8216. path, szResult, szResult2, dUsedRate * 100));
  8217. }
  8218. }
  8219. }
  8220. void ResourceWatcherFSM::GetSystemDiskStatus()
  8221. {
  8222. GetDiskStatusFrom("/");
  8223. }
  8224. void ResourceWatcherFSM::GetOperationDiskStatus()
  8225. {
  8226. GetDiskStatusFrom(m_csUploadVideoPath);
  8227. }
  8228. void ResourceWatcherFSM::switchWindowsEffect(const char* cfgFilePath, bool enable)
  8229. {
  8230. char tmp[33];
  8231. memset(tmp, 0, 33);
  8232. inifile_read_str_s("Compositing", "Enabled", "", tmp, 32, cfgFilePath);
  8233. if (strlen(tmp) == 0 || stricmp(tmp, "false") == 0) {
  8234. if (enable) {
  8235. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "true");
  8236. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_ON, "to active window effect");
  8237. }
  8238. }
  8239. else if (stricmp(tmp, "true") == 0) {
  8240. if (!enable) {
  8241. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "false");
  8242. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_OFF, "to inactive window effect");
  8243. }
  8244. }
  8245. }
  8246. BOOL ResourceWatcherFSM::readDNSConfigFile(CSimpleStringA& result)
  8247. {
  8248. std::string succStr, errStr;
  8249. if (SP::Module::Util::ShellExecute("cat /etc/resolv.conf", succStr, errStr)) {
  8250. result = succStr.c_str();
  8251. return TRUE;
  8252. }
  8253. else {
  8254. return FALSE;
  8255. }
  8256. }
  8257. void ResourceWatcherFSM::RecoverDDEClipboardEnable()
  8258. {
  8259. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  8260. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  8261. if (!ExistsFileA(clipboardPath.c_str()) && ExistsFileA(clipboardPathBak.c_str())) {
  8262. fileutil_copy_file(clipboardPath.c_str(), clipboardPathBak.c_str());
  8263. //fileutil_delete_file(clipboardPathBak.c_str());
  8264. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_CLIPBOARD_RECOVER_ENABLE, "recover clipboard succ.");
  8265. }
  8266. else {
  8267. Dbg("%s exists.", clipboardPath.c_str());
  8268. }
  8269. }
  8270. void ResourceWatcherFSM::ConfirmDDEClipboardDisable()
  8271. {
  8272. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  8273. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  8274. char* clipboards[] = { "dde-clipboard", "dde-clipboardloader" };
  8275. if (!ExistsFileA(clipboardPath.c_str())) {
  8276. Dbg("There are no any %s files.", clipboardPath.c_str());
  8277. if (ExistsFileA(clipboardPathBak.c_str())) {
  8278. Dbg("%s exists.", clipboardPathBak.c_str());
  8279. }
  8280. return;
  8281. }
  8282. if (0 != fileutil_copy_file(clipboardPathBak.c_str(), clipboardPath.c_str())) {
  8283. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove clipboard failed");
  8284. }
  8285. else {
  8286. fileutil_delete_file(clipboardPath.c_str());
  8287. osutil_terminate_related_process(clipboards, array_size(clipboards));
  8288. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_SUCC, "remove clipboard succ.");
  8289. }
  8290. }
  8291. void ResourceWatcherFSM::ConfirmNotificationCenterDisable()
  8292. {
  8293. const char* osd_file_path = "/usr/lib/deepin-daemon/dde-osd";
  8294. const char* osd_bak_file_path = "/usr/lib/deepin-daemon/dde-osd.bak";
  8295. CSmartPointer<IConfigInfo> spConfig;
  8296. GetEntityBase()->GetFunction()->OpenConfig(Config_Cache, spConfig);
  8297. int flag = 0;
  8298. spConfig->ReadConfigValueInt("UOSFeatures", "NotifyCenterSupport", flag);
  8299. if (flag == 1) {
  8300. Dbg("allow the dde-osd process alive.");
  8301. if (!ExistsFileA(osd_file_path) && ExistsFileA(osd_bak_file_path)) {
  8302. fileutil_copy_file(osd_file_path, osd_bak_file_path);
  8303. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_OSD_RECOVER_ENABLE, "recover dde osd succ.");
  8304. }
  8305. }
  8306. else {
  8307. if (ExistsFileA(osd_file_path) && !ExistsFileA(osd_bak_file_path)) {
  8308. char* relates[] = { "dde-osd" };
  8309. if (0 != fileutil_copy_file(osd_bak_file_path, osd_file_path)) {
  8310. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove dde osd failed");
  8311. }
  8312. else {
  8313. osutil_terminate_related_process(relates, array_size(relates));
  8314. fileutil_delete_file(osd_file_path);
  8315. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_OSD_REMOVE_SUCC, "remove dde osd succ.");
  8316. }
  8317. }
  8318. }
  8319. }
  8320. BOOL ResourceWatcherFSM::SetLocalDNSWithResolv(LPCTSTR dns1, LPCTSTR dns2)
  8321. {
  8322. const char* dnsPath = "/etc/resolv.conf";
  8323. const int res = access(dnsPath, W_OK);
  8324. if (res == 0) {
  8325. CSimpleStringA timeStamp = CSmallDateTime::GetNow().ToTimeString();
  8326. FILE* resolv = fopen(dnsPath, "w+");
  8327. int state = fprintf(resolv, "#Update by VTM %s\nnameserver %s\nnameserver %s\n", timeStamp.GetData(), dns1, dns2);
  8328. fclose(resolv);
  8329. if (state < 0) {
  8330. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_FAILED,
  8331. CSimpleStringA::Format("update dns config for %s|%s failed: err: %d", dns1, dns2, errno));
  8332. return FALSE;
  8333. }
  8334. else {
  8335. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_SUCC,
  8336. CSimpleStringA::Format("update dns with resolv for %s|%s succ!", dns1, dns2));
  8337. return TRUE;
  8338. }
  8339. }
  8340. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_FAILED,
  8341. CSimpleStringA::Format("access dns with resolv failed err: %d, rc:%d", errno, res));
  8342. return FALSE;
  8343. }
  8344. /** 在厂商机器查看了信息,不能以这里面的内容为准 [Gifur@2021910]*/
  8345. BOOL ResourceWatcherFSM::SetLocalDNSWithNetworkManager(LPCTSTR dns1, LPCTSTR dns2)
  8346. {
  8347. BOOL result = FALSE;
  8348. const char* connectDirPath = "/etc/NetworkManager/system-connections";
  8349. array_header_t* arr;
  8350. arr = fileutil_get_sub_files_a(connectDirPath);
  8351. if (arr) {
  8352. do {
  8353. for (int i = 0; i < arr->nelts; ++i) {
  8354. char* dir = ARRAY_IDX(arr, i, char*);
  8355. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  8356. CSimpleStringA::Format("%d: %s", i + 1, dir));
  8357. }
  8358. if (arr->nelts == 0) {
  8359. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  8360. CSimpleStringA::Format("%s: no any sub files", connectDirPath));
  8361. }
  8362. toolkit_array_free2(arr);
  8363. return result;
  8364. } while (false);
  8365. if (arr->nelts != 1) {
  8366. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_SYSCONNECT_DUPLICATE,
  8367. CSimpleStringA::Format("%s: unexpect connects count: %d", connectDirPath, arr->nelts));
  8368. }
  8369. else {
  8370. char szDestPath[256] = { 0 };
  8371. char* dir = ARRAY_IDX(arr, 0, char*);
  8372. strcpy(szDestPath, dir);
  8373. do {
  8374. char value[128];
  8375. inifile_read_str_s("connection", "interface-name", "", value, 127, szDestPath);
  8376. if (strlen(value) == 0) {
  8377. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_CONNECTION_INFO_UNEXPECT,
  8378. CSimpleStringA::Format("get interface name from %s failed.", szDestPath));
  8379. break;
  8380. }
  8381. memset(value, 0, sizeof(value));
  8382. inifile_read_str_s("ipv4", "dns", "", value, 127, szDestPath);
  8383. bool toUpdate = true;
  8384. if (strlen(value) > 0) {
  8385. CSimpleStringA DNSes(value);
  8386. auto arr = DNSes.Split(';');
  8387. int cf1 = 0, cf2 = 0;
  8388. for (int i = 0; i < arr.GetCount(); ++i) {
  8389. if (arr[i].Compare(dns1) == 0) cf1++;
  8390. if (arr[i].Compare(dns2) == 0) cf2++;
  8391. }
  8392. if (cf1 > 0 && cf2 > 0) {
  8393. toUpdate = false;
  8394. Dbg("already exists: %s, needless to update.", value);
  8395. result = TRUE;
  8396. }
  8397. }
  8398. if (toUpdate) {
  8399. CSimpleStringA newLine(dns1);
  8400. if (newLine.Compare(dns2) != 0) {
  8401. newLine += ";";
  8402. newLine += dns2;
  8403. newLine += ";";
  8404. }
  8405. else {
  8406. newLine += ";";
  8407. }
  8408. inifile_write_str(szDestPath, "ipv4", "dns", newLine);
  8409. inifile_write_str(szDestPath, "ipv4", "ignore-auto-dns", "true");
  8410. Dbg("to update services.");
  8411. std::string nor, err;
  8412. SP::Module::Util::ShellExecute("service NetworkManager restart", nor, err);
  8413. Dbg("restart service done!");
  8414. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_NM_SUCC,
  8415. CSimpleStringA::Format("update dns with netwokrMange for %s|%s succ!", dns1, dns2));
  8416. result = TRUE;
  8417. }
  8418. } while (false);
  8419. }
  8420. toolkit_array_free2(arr);
  8421. }
  8422. else {
  8423. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  8424. CSimpleStringA::Format("%s: no such directory or not any sub files", connectDirPath));
  8425. //LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_SYSCONNECT_DUPLICATE,
  8426. // CSimpleStringA::Format("%s: no such directory or not any sub files", connectDirPath));
  8427. }
  8428. return result;
  8429. }
  8430. /*
  8431. * 桌面版本自带的NetworkManage管理服务与Interface的设置有冲突,如果手工改动Interface的配置,则NetworkManage会失效
  8432. * UOS默认使用NetworkMange接管网卡的管理,所以为了适应UOS,此种方式暂不实现
  8433. */
  8434. BOOL ResourceWatcherFSM::SetLocalDNSWithInterfaces(LPCTSTR dns1, LPCTSTR dns2)
  8435. {
  8436. return FALSE;
  8437. }
  8438. void ResourceWatcherFSM::ConfirmDNSConfigHasSet()
  8439. {
  8440. LOG_FUNCTION();
  8441. CSimpleStringA dns1(true), dns2(true);
  8442. #if 1
  8443. CSmartPointer<IConfigInfo> spConfig;
  8444. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  8445. spConfig->ReadConfigValue("DNS", "dns1", dns1);
  8446. spConfig->ReadConfigValue("DNS", "dns2", dns2);
  8447. #else
  8448. dns1 = m_strDefaultDns;
  8449. dns2 = m_strBackupDns;
  8450. if (!m_nEnableSetDns) {
  8451. Dbg("no enable set dns server.");
  8452. return;
  8453. }
  8454. #endif
  8455. if (dns1.IsNullOrEmpty() && dns2.IsNullOrEmpty()) {
  8456. Dbg("not any dns set at entity config.");
  8457. return;
  8458. }
  8459. if (dns2.IsNullOrEmpty()) dns2 = dns1;
  8460. if (dns1.IsNullOrEmpty()) dns1 = dns2;
  8461. CSimpleStringA str;
  8462. readDNSConfigFile(str);
  8463. do {
  8464. std::string a(str.GetData());
  8465. SP::Utility::replaceInPlace(a, "\n", "|");
  8466. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  8467. CSimpleStringA::Format("%s $$ %s|%s", a.c_str(), m_strDefaultDns.GetData(), m_strBackupDns.GetData()));
  8468. } while (false);
  8469. if (dns1.IsNullOrEmpty() && dns2.IsNullOrEmpty()) {
  8470. Dbg("not any dns set at entity config.");
  8471. return;
  8472. }
  8473. if (dns2.IsNullOrEmpty()) dns2 = dns1;
  8474. if (dns1.IsNullOrEmpty()) dns1 = dns2;
  8475. return;
  8476. //////////////////////////////////////////////////////////////////////////
  8477. /** 下面的代码验证暂不可行 [Gifur@202319]*/
  8478. if (!str.IsNullOrEmpty()) {
  8479. CAutoArray<CSimpleStringA> arr = str.Split('\n');
  8480. CSimpleStringA check1("nameserver ");
  8481. CSimpleStringA check2("nameserver ");
  8482. check1 += dns1;
  8483. check2 += dns2;
  8484. int cf1 = 0, cf2 = 0;
  8485. for (int i = 0; i < arr.GetCount(); ++i) {
  8486. if (arr[i].Compare(check1) == 0) cf1++;
  8487. if (arr[i].Compare(check2) == 0) cf2++;
  8488. }
  8489. if (cf1 > 0 && cf2 > 0) {
  8490. Dbg("dns has been config before:");
  8491. Dbg(str);
  8492. return;
  8493. }
  8494. }
  8495. Dbg("to set dns config...");
  8496. SetLocalDNSWithResolv(dns1, dns2);
  8497. //SetLocalDNSWithNetworkManager(dns1, dns2);
  8498. Dbg("set dns config done!");
  8499. }
  8500. void ResourceWatcherFSM::ConfirmWindowEffectHasBeenOpen()
  8501. {
  8502. array_header_t* arr;
  8503. arr = fileutil_get_sub_dirs_a("/home");
  8504. if (arr) {
  8505. int i;
  8506. for (i = 0; i < arr->nelts; ++i) {
  8507. char szDestSubDir[256] = { 0 };
  8508. char* dir = ARRAY_IDX(arr, i, char*);
  8509. Dbg("sub dir: %s", dir);
  8510. strcpy(szDestSubDir, dir);
  8511. strcat(szDestSubDir, SPLIT_SLASH_STR);
  8512. strcat(szDestSubDir, ".config/kwinrc");
  8513. if (ExistsFileA(szDestSubDir)) {
  8514. switchWindowsEffect(szDestSubDir, true);
  8515. }
  8516. }
  8517. toolkit_array_free2(arr);
  8518. }
  8519. }
  8520. #endif // RVC_OS_LINUX