123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369 |
- #include "stdafx.h"
- #include "ResourceWatcherFSM.h"
- #include "DeviceBaseClass.h"
- #include <string.h>
- #include <string>
- #include <assert.h>
- #include <algorithm>
- #include "fileutil.h"
- #include <ctime>
- #include "CommEntityUtil.hpp"
- #include <stdio.h>
- #include <stdlib.h>
- #include "ResourceWatcher_UserCode.h"
- #ifdef RVC_OS_LINUX
- #include <vector>
- #include <dirent.h>
- #include <sstream>
- #include <fstream>
- #include <iostream>
- #include "publicFunExport.h"
- #include "toolkit.h"
- #include "iniutil.h"
- #include "osutil.h"
- #include "SpUtility.h"
- #include "RestfulFunc.h"
- #else
- #include <intrin.h>
- #include <ShlObj.h>
- #include <Pdh.h>
- #include <io.h>
- #include <direct.h>
- #include "memutil.h"
- #include "array.h"
- #include <Windows.h>
- #include <wintrust.h>
- #include <direct.h>
- #include <Mscat.h>
- #include <Softpub.h>
- #include <wlanapi.h>
- #include <Netlistmgr.h> //网络检测添加
- #include <psapi.h>
- #include <tlhelp32.h>
- #include "Mmdeviceapi.h"
- #include "PolicyConfig.h"
- #include "Propidl.h"
- #include "Functiondiscoverykeys_devpkey.h"
- #include "NetConfigCommon.h"
- #include "NetworkInfo.h"
- #include "NetworkProbe.h"
- #include "MbnEventImpl.h"
- #include "Event.h"
- #include "..\mod_chromium\Chromium_client_g.h" //启动浏览器接口
- using namespace Chromium;
- #pragma comment(lib, "pdh.lib")
- #pragma comment(lib,"winmm.lib" )
- #pragma comment(lib, "shell32.lib")
- #pragma comment(lib, "Wintrust.lib")
- #pragma comment(lib, "crypt32.lib")
- #pragma comment(lib, "wlanapi.lib")
- #endif
- //硬件信息搜集参数
- const int MAX_HARDWARE_CHECK_TIME = 5000;
- const int TIMER_HARDWARE_CHECK = 2;
- //保留版本数目
- const int DEFAULT_VERSION_SAVED_COUNT = 5;
- const int MAX_VERSION_PATH = 256;
- const int DEFAULT_DAY_OF_BACKWARD = 90;
- const int MAX_DAY_OF_BACKWARD = 365;
- const char* DEFAULT_DELETE_FILE_SUFFIX = "*";
- LPCTSTR UPLOAD_VIDEO_PATH = "UploadVideo";
- CRITICAL_SECTION g_csVideoMoreClear;
- const int AD0_DAY_OF_BACKWARD = 7;
- const int TIMER_INTERVAL_CLEARVIDEO_ENHANCE = 60 * 1000;
- #ifdef RVC_OS_LINUX
- #define PROCESS_ITEM 14 //进程CPU信息读取位置参数
- const int MAX_MAINLINK_CHECK_TIME = 5000;
- const int TIMER_MAINLINK_CHECK = 4;
- static BOOL lastLinkStatus = true; //记录上次检测的连通状态,广播用 true:连通 false:不通
- #else
- const int TIMER_ID_CLEARVIDEO_ENHANCE = 1;
- static int mainDetectFlag = 0;
- static int hardwareCheckTime = 5000;
- static int hardwareCheckFlag = 1;
- static int batteryCheckTime = 2;
- const int MAX_AYSNC_TIMEOUT = 60000;
- const int MAX_CHECK_TIME = 60000;
- const int MAX_CPU_CHECK_TIME = 5000;
- const int TIMER_ID_CHECK = 0;
- const int TIMER_CPU_CHECK = 1;
- const int THOUSAND = 1024;
- const int MILLION = 1048576;
- #endif // RVC_OS_LINUX
- #define MAX_VOLUME_COUNT 26
- #define BUFSIZE 512
- static BOOL sBDiskValStatus[MAX_VOLUME_COUNT + 1] = { FALSE };
- #define MAX_SUBFILES_COUNT 1000
- #define DIV (1024 * 1024)
- #define DAY_DIV (24 * 60 * 60)
- #define HOURS_DIV (60 * 60)
- #define MINUS_DIV (60)
- const char* SystemElapsedQuery = "\\System\\System Up Time";
- #ifndef RVC_OS_LINUX
- #define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
- #define SafeDeleteArraySize(pData) { if(pData){delete []pData;pData=NULL;} }
- #endif // !RVC_OS_LINUX
- template<class T>
- class TimerOutHelper : public ITimerListener
- {
- public:
- typedef void (T::* FuncTimer)(void* pUserdata);
- TimerOutHelper(T* p, FuncTimer pTimerFunc, void* pData, bool bDeleteSelf = false)
- : m_pObject(p), m_pUserData(pData), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf)
- {
- }
- virtual void OnTimeout(DWORD dwTimerID)
- {
- (m_pObject->*m_pTimer)(m_pUserData);
- if (m_bDeleteSelf)
- delete this;
- }
- private:
- void* m_pUserData;
- T* m_pObject;
- FuncTimer m_pTimer;
- bool m_bDeleteSelf;
- };
- #ifdef RVC_OS_LINUX
- ResourceWatcherFSM::ResourceWatcherFSM(void)
- :m_IsPadDevice(FALSE),
- m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD),
- m_csUploadVideoPath(true),
- m_bReadyFlag(false),
- m_bVideoClearReady(false),
- m_nMinSavedDay(DEFAULT_SAVE_DATE_COUNT),
- m_highPart(0),
- m_lowPart(0),
- m_strTerminalNo(true),
- m_strDefaultDns(true),
- m_strBackupDns(true),
- m_nEnableSetDns(0),
- m_bFirstRunAfterBoot(FALSE),
- m_bGetStatusRotate(FALSE),
- m_csDelFileSuffix(true),
- m_failDelCnt(0),
- m_bIsConfigMode(FALSE)
- {
- mAllVideoFileSizeCal = 0;
- mMaxFileSize = 0;
- mUiCalibration = 0;
- mUiRequireBytes = 0;
- mftAd0RemoveTime = 0;
- }
- #else
- ResourceWatcherFSM::ResourceWatcherFSM(void)
- :m_IsPadDevice(TRUE),
- m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD),
- m_csUploadVideoPath(""),
- m_bReadyFlag(false),
- m_bVideoClearReady(false),
- m_nMinSavedDay(DEFAULT_SAVE_DATE_COUNT),
- m_highPart(0),
- m_lowPart(0),
- m_strTerminalNo(true),
- m_fProbeDone(true),
- m_DoneDetectAutostart(true),
- m_forceStartupWithExeFlag(0),
- m_bIsVerified(false),
- m_iNonSignedTotal(0),
- checkActiveBefore(FALSE),
- m_cardswiperStatus(-1)
- {
- mUiRequireBytes.QuadPart = 0ui64;
- mUiCalibration.QuadPart = 0ui64;
- m_strDefaultDns = NULL;
- m_strBackupDns = NULL;
- m_nEnableSetDns = 0;
- m_nProbeIndex = 0;
- memset(m_strProbeAddress, 0, sizeof(CSimpleStringA) * MAX_NETWORK_PROBE_COUNT);
- }
- #endif // RVC_OS_LINUX
- ResourceWatcherFSM::~ResourceWatcherFSM(void)
- {
- }
- #ifdef RVC_OS_LINUX
- void ResourceWatcherFSM::ClearVideoQueue()
- {
- while (!m_VideoFiles.empty()) {
- TmpFileInfo* pNodeInfo = m_VideoFiles.top();
- m_VideoFiles.pop();
- if (pNodeInfo != NULL) {
- delete pNodeInfo;
- }
- }
- memset(szMaxSizeFilePath, 0, sizeof(szMaxSizeFilePath));
- mAllVideoFileSizeCal = 0;
- mMaxFileSize = 0;
- mUiRequireBytes = 0;
- VideoDailyRecord.clear();
- }
- void ResourceWatcherFSM::PrintVideEmurateResult()
- {
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(szResult, (double)mMaxFileSize);
- Dbg("Max Video file: %s size: %s", szMaxSizeFilePath, szResult);
- Dbg("mAllVideoFileSizeCal : %llu Bytes", mAllVideoFileSizeCal);
- ByteSprintf(szResult, (double)mAllVideoFileSizeCal);
- Dbg("Totally(size: %d) directory size: %s", m_VideoFiles.size(), szResult);
- }
- #endif // RVC_OS_LINUX
- void ResourceWatcherFSM::s0_on_entry()
- {
- LOG_FUNCTION();
- #ifdef RVC_OS_LINUX
- if (!m_bIsConfigMode) {
- this->PostEventFIFO(new RunEvent());
- GetCpuType(NULL);
- }
- else {
- Dbg("in config mode, do nothing about clear job");
- }
- #else
- this->PostEventFIFO(new RunEvent());
- GetCpuType(NULL);
- SetDnsServer();
- GetEntityBase()->GetFunction()->PostThreadPoolTask(new ClearCenterSettingFilesTask(this));
- BOOL fInstallBySetup(FALSE);
- if (Error_Succeed == DetectVTMInstalledBySetup(fInstallBySetup) && !fInstallBySetup) {
- GetEntityBase()->GetFunction()->PostThreadPoolTask(new CreateLinkTask(this));
- }
- #endif // RVC_OS_LINUX
- }
- unsigned int ResourceWatcherFSM::s0_on_event(FSMEvent* e)
- {
- LOG_FUNCTION();
- unsigned int unRes = 0;
- switch (e->iEvt)
- {
- case USER_EVT_RUN:
- {
- if (m_IsPadDevice)
- {
- GetCardSwiperTask* task = new GetCardSwiperTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- #ifdef RVC_OS_LINUX
- RunTask* videoTask = new RunTask(this);
- videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
- #else
- ClearVideoFilesTask* videoTask = new ClearVideoFilesTask(this);
- videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
- ClearAd0Task* ad0Task = new ClearAd0Task(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(ad0Task);
- #endif // RVC_OS_LINUX
- e->SetHandled();
- }
- break;
- case USER_EVT_FETCH:
- {
- FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
- fetchEvt->ctx->Answer(Error_InvalidState);
- e->SetHandled();
- }
- break;
- case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
- {
- m_bGetStatusRotate = FALSE;
- e->SetHandled();
- }
- break;
- default:
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unexpecetd Event(%d)", e->iEvt);
- }
- break;
- }
- return unRes;
- }
- void ResourceWatcherFSM::s0_on_exit()
- {
- }
- void ResourceWatcherFSM::s1_on_entry()
- {
- LOG_FUNCTION();
- }
- unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
- {
- LOG_FUNCTION();
- unsigned int unRes = 0;
- switch (e->iEvt)
- {
- case USER_EVT_FETCH:
- {
- FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
- if (m_IsPadDevice)
- {
- fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
- fetchEvt->ctx->Answer(Error_Succeed);
- }
- else
- {
- fetchEvt->ctx->Answer(Error_InvalidState);
- }
- e->SetHandled();
- }
- break;
- case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
- {
- m_bGetStatusRotate = FALSE;
- e->SetHandled();
- }
- break;
- case USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s::There are %d file(s), successfully delete %d file(s) in path %s", __FUNCTION__,
- e->param2, e->param1, (LPCTSTR)m_csUploadVideoPath);
- if (m_failDelCnt != 0)
- {
- CSimpleStringA strMsg = CSimpleStringA::Format("There are %d matched files should be deleted", m_failDelCnt);
- LogWarn(Severity_Middle, Error_Unexpect, 0, (LPCTSTR)strMsg);
- }
- ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- e->SetHandled();
- break;
- #ifndef RVC_OS_LINUX
- case EVT_TIMER:
- {
- if (e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
- {
- ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- }
- e->SetHandled();
- break;
- #endif // !RVC_OS_LINUX
- case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
- e->SetHandled();
- break;
- case USER_EVT_VERSION_CLEAR_FINISHED:
- e->SetHandled();
- break;
- default:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Unexpecetd Event(%d)", e->iEvt);
- }
- break;
- }
- return unRes;
- }
- void ResourceWatcherFSM::s1_on_exit()
- {
- }
- void ResourceWatcherFSM::s2_on_entry()
- {
- LOG_FUNCTION();
- }
- unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
- {
- LOG_FUNCTION();
- unsigned int unRes = 0;
- switch (e->iEvt)
- {
- case USER_EVT_RUN:
- {
- e->SetHandled();
- }
- break;
- case USER_EVT_FETCH:
- {
- FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
- if (m_IsPadDevice)
- {
- fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
- fetchEvt->ctx->Answer(Error_Succeed);
- }
- else
- {
- fetchEvt->ctx->Answer(Error_InvalidState);
- }
- e->SetHandled();
- }
- break;
- case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
- {
- m_bGetStatusRotate = FALSE;
- e->SetHandled();
- }
- break;
- #ifndef RVC_OS_LINUX
- case EVT_TIMER:
- {
- if (e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
- {
- ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- }
- e->SetHandled();
- break;
- #endif // !RVC_OS_LINUX
- case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
- {
- }
- e->SetHandled();
- break;
- }
- return unRes;
- }
- void ResourceWatcherFSM::s2_on_exit()
- {
- }
- void ResourceWatcherFSM::s3_on_entry()
- {
- LOG_FUNCTION();
- m_bVideoClearReady = true;
- }
- unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
- {
- unsigned int unRes = 0;
- switch (e->iEvt)
- {
- case USER_EVT_RUN:
- {
- e->SetHandled();
- }
- break;
- case USER_EVT_FETCH:
- {
- FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
- if (m_IsPadDevice)
- {
- fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
- fetchEvt->ctx->Answer(Error_Succeed);
- }
- else
- {
- fetchEvt->ctx->Answer(Error_InvalidState);
- }
- e->SetHandled();
- }
- break;
- case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
- {
- m_bGetStatusRotate = FALSE;
- e->SetHandled();
- }
- break;
- #ifndef RVC_OS_LINUX
- case EVT_TIMER:
- {
- if (e->param1 == TIMER_ID_CLEARVIDEO_ENHANCE)
- {
- ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- }
- e->SetHandled();
- break;
- #endif // !RVC_OS_LINUX
- case USER_EVT_CLEAR_VIDEOFILE_ENHANCE:
- {
- ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- e->SetHandled();
- break;
- case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
- {
- }
- e->SetHandled();
- break;
- case USER_EVT_FILE_OPERAT:
- {
- OperateFileEvent* theEvt = dynamic_cast<OperateFileEvent*>(e);
- OperateFileTask* theTask = new OperateFileTask(this, theEvt->m_ctx);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
- }
- e->SetHandled();
- break;
- case USER_EVT_FILE_OPERAT_FINISHED:
- {
- }
- e->SetHandled();
- break;
- case USER_EVT_GET_EVENTLOG:
- {
- GetEventLogEvent* theEvt = dynamic_cast<GetEventLogEvent*>(e);
- #ifdef RVC_OS_LINUX
- theEvt->m_ctx->Answer(Error_NotSupport);
- #else
- GetEventLogTask* theTask = new GetEventLogTask(this, theEvt->m_ctx);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
- #endif // RVC_OS_LINUX
- }
- e->SetHandled();
- break;
- case USER_EVT_GET_EVENTLOG_FINISHED:
- {
- }
- e->SetHandled();
- break;
- }
- return unRes;
- }
- void ResourceWatcherFSM::s3_on_exit()
- {
- m_bVideoClearReady = false;
- }
- #ifdef RVC_OS_LINUX
- bool ResourceWatcherFSM::GetMonitorInfo(CSimpleStringA& outInfo)
- {
- std::string sucContent, failedContent;
- CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
- bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
- std::string msg = SP::Utility::ToTrim(sucContent);
- SP::Utility::replaceInPlace(msg, "\n", "|");
- outInfo = msg.c_str();
- return ret;
- }
- void ResourceWatcherFSM::readVideoStoreData()
- {
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- // From CenterSetting --Josephus at 10:02:10 201759
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "BackwardDays", m_nDayOfBackward);
- if (m_nDayOfBackward <= 0) {
- m_nDayOfBackward = 90;
- } else {
- Dbg("Detect BackwardDays from CentralSetting %d", m_nDayOfBackward);
- }
- if (m_nDayOfBackward <= 0 || m_nDayOfBackward > MAX_DAY_OF_BACKWARD) {
- Dbg("Detect BackwardDays(%d) is illegal and Set default %d", m_nDayOfBackward, DEFAULT_DAY_OF_BACKWARD);
- m_nDayOfBackward = DEFAULT_DAY_OF_BACKWARD;
- }
- int minSavedDay = 0;
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MinSavedDays", minSavedDay);
- if (minSavedDay >= 1 && minSavedDay < DEFAULT_SAVE_DATE_COUNT) {
- m_nMinSavedDay = minSavedDay;
- Dbg("Detect MinSavedDays from CentralSetting %d", m_nMinSavedDay);
- }
- }
- #endif // RVC_OS_LINUX
- ErrorCodeEnum ResourceWatcherFSM::OnInit()
- {
- #ifdef RVC_OS_LINUX
- LOG_FUNCTION();
- ErrorCodeEnum erroCode = Error_Succeed;
- CSimpleStringA strtermState;
- GetEntityBase()->GetFunction()->GetSysVar("TerminalStage", strtermState);
- if (strtermState.IsStartWith("Z=")) {
- Dbg("in config mode");
- m_bIsConfigMode = TRUE;
- }
- CSystemStaticInfo sysInfo;
- erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
- if (erroCode != Error_Succeed) {
- Dbg("Get System Static info failed: %s.", SpStrError(erroCode));
- return Error_Unexpect;
- }
- Dbg("%s, %s", sysInfo.strMachineType.GetData(), sysInfo.strTerminalID.GetData());
- m_strTerminalNo = sysInfo.strTerminalID;
- if (!sysInfo.strMachineType.IsNullOrEmpty() && !sysInfo.strMachineType.Compare("RVC.Pad", true)) {
- m_IsPadDevice = TRUE;
- }
- m_bFirstRunAfterBoot = DetectIsFirstRunAtBoot();
- Dbg("to initialize critical section...");
- InitializeCriticalSection(&g_csVideoMoreClear);
- CSmartPointer<IConfigInfo> spConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- cpuTop = 0;
- erroCode = spConfig->ReadConfigValueInt("TOPProcess", "cpu", cpuTop); //读取需要监控的CPU进程个数
- if (erroCode != Error_Succeed) {
- Dbg("Get CPU TOP NUM failed: %s.", SpStrError(erroCode));
- }
- if (cpuTop == 0) {
- cpuTop = 10; //From static config
- } else if (cpuTop == -1) {
- Dbg("No need for TOP PROCESS!");
- cpuTop = 0;
- }
- if (!m_bIsConfigMode) {
- erroCode = GetEntityBase()->GetFunction()->GetPath("LocalVideo", m_csUploadVideoPath);
- if (erroCode != Error_Succeed || m_csUploadVideoPath.IsNullOrEmpty()) {
- return Error_NotInit;
- }
- InitialVolumes();
- InitBlackList();
- readVideoStoreData();
- m_bReadyFlag = IsNeedToFirstClear();
- Dbg("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)"
- , (LPCTSTR)m_csUploadVideoPath, m_nDayOfBackward, !m_bReadyFlag);
- void* pTmpData = NULL;
- ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
- GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, MAX_HARDWARE_CHECK_TIME);
- Dbg("Set Hardware Timer!");
- }
- return Error_Succeed;
- #else
- #ifdef WIDE_CONDITION
- setlocale(LC_ALL, "chs");
- #endif
- ErrorCodeEnum erroCode = Error_Succeed;
- CSimpleStringA csMacroPath;
- CSimpleStringA csLstExecTime;
- CSmartPointer<IConfigInfo> spRunConfig;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- BOOL bDesk2S = FALSE;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Complied at: %s %s", __DATE__, __TIME__);
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(m_RvcSysinfo);
- m_strTerminalNo = m_RvcSysinfo.strTerminalID;
- m_xIdlePre = m_xKernelPre = m_xUserPre = 0; //CPU计算使用
- isNeedForceDiskCheck = false;
- if (m_RvcSysinfo.strMachineType.Compare("RVC.Pad", true))
- {
- m_IsPadDevice = FALSE;
- }
- if (!m_RvcSysinfo.strMachineType.Compare("RVC.Desk2S", true)) {
- bDesk2S = TRUE;
- }
- if (IsHasSetAutoStartupByFolder()) {
- /** 因为安装时已经设置为开机自启动了,所以要把注册表的开机自启动取消掉(如果有) Gifur@20221017]*/
- m_forceStartupWithExeFlag = 3;
- }
- else {
- InitialAutoStartupSetType();
- }
- DWORD vc = InitialVolumes();
- InitBlackSheet();
- spConfig->ReadConfigValue("Video", "Path", csMacroPath);
- if (csMacroPath.GetLength() < 1)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Read VideoPath from local config failed");
- return Error_NotInit;
- }
- else
- {
- erroCode = ExpandDir((LPCTSTR)csMacroPath, m_csUploadVideoPath);
- if (erroCode == Error_Succeed)
- {
- if (m_csUploadVideoPath.GetLength() > 0)
- {
- m_bReadyFlag = true;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ExpandDir returned empty string.");
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ExpandDir failed.");
- }
- }
- if (!m_bReadyFlag)
- {
- return Error_NotInit;
- }
- // From CenterSetting --Josephus at 10:02:10 201759
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "BackwardDays", m_nDayOfBackward);
- if (m_nDayOfBackward <= 0)
- {
- spConfig->ReadConfigValueInt("Video", "BackwardDays", m_nDayOfBackward);
- }
- if (m_nDayOfBackward <= 0 || m_nDayOfBackward > MAX_DAY_OF_BACKWARD)
- {
- m_nDayOfBackward = DEFAULT_DAY_OF_BACKWARD;
- }
- int minSavedDay = 0;
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MinSavedDays", minSavedDay);
- if (minSavedDay >= 1 && minSavedDay < DEFAULT_SAVE_DATE_COUNT)
- {
- m_nMinSavedDay = minSavedDay;
- }
- //TODO:完全移除
- if (FALSE && 0 != m_RvcSysinfo.strMachineType.Compare("RVC.PAD", true)) {
- //huchen add for set dns
- spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DefaultDns", m_strDefaultDns);
- spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "BackupDns", m_strBackupDns);
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "EnableSetDns", m_nEnableSetDns);
- 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());
- }
- //huchen add for network probe
- for (int i = 0; i < MAX_NETWORK_PROBE_COUNT; i++) {
- char address_index[10] = { 0 };
- itoa(i, address_index, 10);
- std::string str_address = "NetProbeAddress";
- str_address += address_index;
- spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), str_address.c_str(), m_strProbeAddress[i]);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect NetProbe from CentralSetting NetProbeAddress, %d: %s,%s.", i, str_address.c_str(), m_strProbeAddress[i].GetData());
- if (m_strProbeAddress[i].GetLength() == 0) {
- break;
- }
- else if (m_fProbeDone) {
- m_fProbeDone = false;
- }
- }
- IsNeedToFirstClear();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)",
- (LPCTSTR)m_csUploadVideoPath, m_nDayOfBackward, !m_bReadyFlag);
- InitializeCriticalSection(&g_csVideoMoreClear);
- InitialCPUMarkInfor();
- {
- CSystemRunInfo runInfo = { 0 };
- erroCode = GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
- if (erroCode == ERROR_SUCCESS) {
- }
- BOOL bSet = FALSE;
- CBootInfo bootInfo = { 0 };
- CSmallDateTime dateTime;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
- erroCode = GetEntityBase()->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
- CSmallDateTime systemBootTime;
- BOOL bRet = GetSystemBootTime(systemBootTime);
- BOOL bRequiredSet = FALSE;
- if (bRet && systemBootTime > bootInfo.tmStart) {
- bSet = TRUE;
- ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
- if (eRet != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
- }
- ///*TODO(80374374@10/17/2022): */
- m_DoneDetectAutostart = false;
- std::map<std::string, std::string> srcData;
- CSimpleStringA strData = CSimpleStringA::Format("{\"AppLastStartTime\":\"%s\",\"AppStartTime\":\"%s\",\"OSStartTime\":\"%s\"}"
- , (LPCTSTR)bootInfo.tmStart.ToTimeString(), (LPCTSTR)runInfo.tmStart.ToTimeString(), systemBootTime.ToTimeString().GetData());
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT, strData.GetData());
- }
- if (bDesk2S) {
- int nLastTaskTime(0);
- spRunConfig->ReadConfigValueInt("Device", "SetAudioOutput", nLastTaskTime);
- CSmallDateTime lastSetTime(nLastTaskTime);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RunConfig SetAudioOutput time : %s", (LPCTSTR)lastSetTime.ToTimeString());
- if (systemBootTime > lastSetTime) {
- bRequiredSet = TRUE;
- }
- }
- if (bRequiredSet) {
- bRet = SetDefaultAudioDevice();
- if (bRet) {
- spRunConfig->WriteConfigValue("Device", "SetAudioOutput",
- (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("set default audio returned: %d", bRet);
- if (!bRet) {
- LogWarn(Severity_High, Error_AudioOut, 0, "Set default video output failed!!");
- }
- }
- if (!bSet) {
- ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
- }
- else {
- if (!curUserName.IsNullOrEmpty()) {
- DetectDestopFileAndWarn(curUserName);
- }
- if (0 == m_RvcSysinfo.strMachineType.Compare("RVC.Stand2S", true)) {
- const int aimScreenNums = 2;
- const int screenNums = GetSystemMetrics(SM_CMONITORS);
- if (screenNums != 2) {
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_LACK_OF_MONITOR
- , CSimpleStringA::Format("lack of monitor! current: %d, aim: %d", screenNums, aimScreenNums));
- }
- }
- }
- }
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MainDetectFlag", mainDetectFlag);
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckTime", hardwareCheckTime);
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckFlag", hardwareCheckFlag);
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "CpuTooHighPercent", m_cpuHighPercent);
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MemoryTooHighPercent", m_memHighPercent);
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardDiskTooHighPercent", m_diskHighPercent);
- if (hardwareCheckTime < MAX_HARDWARE_CHECK_TIME)
- {
- hardwareCheckTime = MAX_HARDWARE_CHECK_TIME;
- }
- void* pTmpData = NULL;
- ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
- GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, hardwareCheckTime);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set Hardware Timer!");
- m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "VerifySignature", m_iVerify);
- spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "DisplayCnt", m_iNonSignedDisplay);
- if (m_iNonSignedDisplay <= 0)
- m_iNonSignedDisplay = 10;
- if (m_iVerify == 1)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Verify digitsign...");
- VerifyDigitSignTask* task = new VerifyDigitSignTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- terminalShowFlag = false;
- lastACLineStatus = -1;
- lastBatteryPercent = -1;
- lastNetStatus = -1;
- terminalStatusSwitch = 0; //默认关闭
- tmpMessageWindFlag = false;
- spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "TerminalStatusSwitch", terminalStatusSwitch);
- if (m_RvcSysinfo.strMachineType == "RVC.CardPrinter")
- {
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- CSimpleStringA tType("");
- spCtSettingConfig->ReadConfigValue("Chromium", "WebMask_RVC.CardPrinter", tType);
- if (tType == CSimpleStringA::Format("with_browser"))
- {
- isNeedShowTerminalStatus = false;
- }
- else
- {
- isNeedShowTerminalStatus = true;
- }
- }
- else
- {
- isNeedShowTerminalStatus = true;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum err = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (err == Error_Succeed) {
- spConfigRun->ReadConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
- }
- return Error_Succeed;
- #endif // RVC_OS_LINUX
- }
- ErrorCodeEnum ResourceWatcherFSM::OnExit()
- {
- #ifdef RVC_OS_LINUX
- GetEntityBase()->GetFunction()->KillTimer(TIMER_HARDWARE_CHECK);
- #endif // RVC_OS_LINUX
- ClearVideoQueue();
- DeleteCriticalSection(&g_csVideoMoreClear);
- return Error_Succeed;
- }
- #ifdef RVC_OS_LINUX
- void ResourceWatcherFSM::AfterInit()
- {
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- //huchen add for set dns
- spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DefaultDns", m_strDefaultDns);
- spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "BackupDns", m_strBackupDns);
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "EnableSetDns", m_nEnableSetDns);
- 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());
- if (m_bFirstRunAfterBoot) {
- UINT sysVer = 0;
- UploadSysVersionInfo(sysVer);
- ConfirmWindowEffectHasBeenOpen();
- ConfirmDNSConfigHasSet();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fetch os version: %u", sysVer);
- if (1031 < sysVer) {
- ConfirmDDEClipboardDisable();
- ConfirmNotificationCenterDisable();
- } else {
- RecoverDDEClipboardEnable();
- }
- GetEntityBase()->GetFunction()->PostThreadPoolTask(new DetectSoftwareInstallStatusTask(this));
- GetEntityBase()->GetFunction()->PostThreadPoolTask(new UploadMonitorInfoTask(this));
- }
- ///**TODO(Gifur@8/10/2023): 联调完成后把它挪到开机时第一次启动时才执行 */
- AlarmSystemBasicInfo();
- }
- #else
- int ResourceWatcherFSM::NetProbe() {
- int i = m_nProbeIndex;
- if (i < MAX_NETWORK_PROBE_COUNT) {
- if (m_strProbeAddress[i].GetLength() == 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("NetProbeAddress index: %d is null.", i);
- return -1;
- }
- CAutoArray<CSimpleStringA> strContent = m_strProbeAddress[i].Split(',');
- if (strContent.GetCount() < 2)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address 参数个数错误.");
- m_nProbeIndex++;
- return 0;
- }
- if (strContent[0].Compare("http") == 0) {
- http_probe((char*)strContent[1].GetData(), 5 * 1000, i);
- }
- else if (strContent[0].Compare("tcp") == 0) {
- if (strContent.GetCount() < 3)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address TCP 参数个数错误.");
- m_nProbeIndex++;
- return 0;
- }
- if (isdigit(strContent[2][0])) {
- tcp_probe((char*)strContent[1].GetData(), atoi(strContent[2]), i);
- }
- }
- else if (strContent[0].Compare("udp") == 0) {
- if (strContent.GetCount() < 3)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address UDP 参数个数错误.");
- m_nProbeIndex++;
- return 0;
- }
- if (isdigit(strContent[2][0])) {
- udp_probe((char*)strContent[1].GetData(), atoi(strContent[2]), 5 * 1000, i);
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("net probe address 参数类型错误");
- }
- }
- m_nProbeIndex++;
- return 0;
- }
- int ResourceWatcherFSM::SetDnsServer()
- {
- if (!m_nEnableSetDns) {
- return 0;
- }
- if ((m_strDefaultDns.GetLength() == 0) || (m_strBackupDns.GetLength() == 0)) {
- return 0;
- }
- //get dns
- char print_buffer[1024];
- DWORD before_time = GetTickCount();
- auto netcards_info = NetCardInfo::GetNetworkInfo();
- DWORD now_time = GetTickCount();
- std::vector<std::shared_ptr<NetCardInfo>>::iterator it;
- std::string print_msg = "Get Dns Success ! Cust: ";
- std::ostringstream os;
- os << now_time - before_time;
- print_msg += os.str();
- for (it = netcards_info.begin(); it != netcards_info.end(); ++it) {
- print_msg += "default_dns:";
- print_msg += (*it)->GetNetCardInfo().default_dns.c_str();
- print_msg += " backup_dns:";
- print_msg += (*it)->GetNetCardInfo().backup_dns.c_str();
- print_msg += ", ";
- }
- print_msg += "cfg_default_dns:";
- print_msg += m_strDefaultDns.GetData();
- print_msg += " cfg_bak_dns:";
- print_msg += m_strBackupDns.GetData();
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_GET_DNS_CUST, print_msg.c_str());
- //set or delete dns
- before_time = now_time;
- bool set_result = false;
- bool delete_dns = false;
- bool had_set = false;
- std::vector<int> error_codes;
- if ((strcmp("0.0.0.0", m_strDefaultDns.GetData()) == 0) && (strcmp("0.0.0.0", m_strBackupDns.GetData()) == 0)) {
- delete_dns = true;
- }
- for (it = netcards_info.begin(); it != netcards_info.end(); ++it) {
- char buffer[1024];
- (*it)->show(buffer, 1024);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetDnsServer, NetworkInfo: %s", buffer);
- string::size_type idx = (*it)->GetNetCardInfo().ip.find(":");
- if (idx != string::npos) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDnsServer, ip is ipv6, skip.");
- continue;
- }
- idx = (*it)->GetNetCardInfo().default_dns.find(":");
- if (idx != string::npos) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDnsServer, default dns is ipv6, skip.");
- continue;
- }
- idx = (*it)->GetNetCardInfo().backup_dns.find(":");
- if (idx != string::npos) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDnsServer, backup dns is ipv6, skip.");
- continue;
- }
- //delete dns
- if (delete_dns) {
- if ((*it)->SetAutoDns()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete Dns Success.");
- set_result = true;
- }
- else {
- int error_code = (*it)->get_last_error_code();
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Delete Dns Failed. error_code: %d", error_code);
- error_codes.push_back(error_code);
- }
- continue;
- }
- //set dns
- if ((strcmp((*it)->GetNetCardInfo().default_dns.c_str(), m_strDefaultDns.GetData()) != 0) ||
- (strcmp((*it)->GetNetCardInfo().backup_dns.c_str(), m_strBackupDns.GetData()) != 0)) {
- if ((*it)->SetDns(m_strDefaultDns.GetData(), m_strBackupDns.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set Dns Success.");
- set_result = true;
- }
- else {
- int error_code = (*it)->get_last_error_code();
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Set Dns Failed. error_code: %d", error_code);
- error_codes.push_back(error_code);
- }
- }
- else {
- had_set = true;
- }
- }
- //print set dns result
- if (!had_set) {
- now_time = GetTickCount();
- if (delete_dns) {
- if (set_result) {
- _snprintf(print_buffer, 1024, "Delete Dns Success ! Cust: %d", now_time - before_time);
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_DELETE_DNS_CUST, print_buffer);
- }
- else {
- //_snprintf(print_buffer, 1024, "Delete Dns Failed ! Cust: %d", now_time - before_time);
- std::string print_msg = "Delete Dns Failed ! Cust: ";
- std::ostringstream os;
- os << now_time - before_time;
- print_msg += os.str();
- std::vector<int>::iterator it;
- print_msg += "error_codes: ";
- for (it = error_codes.begin(); it != error_codes.end(); ++it) {
- std::ostringstream os;
- os << *it;
- print_msg += os.str();
- print_msg += ", ";
- }
- LogWarn(Severity_High, Error_Unexpect, LOG_ERR_DELETE_DNS_FAILED, print_msg.c_str());
- }
- }
- else {
- if (set_result) {
- _snprintf(print_buffer, 1024, "Set Dns Success ! Cust: %d", now_time - before_time);
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_SET_DNS_CUST, print_buffer);
- }
- else {
- //_snprintf(print_buffer, 1024, "Set Dns Failed ! Cust: %d", now_time - before_time);
- std::string print_msg = "Set Dns Failed ! Cust: ";
- std::ostringstream os;
- os << now_time - before_time;
- print_msg += os.str();
- std::vector<int>::iterator it;
- print_msg += "error_codes: ";
- for (it = error_codes.begin(); it != error_codes.end(); ++it) {
- std::ostringstream os;
- os << *it;
- print_msg += os.str();
- print_msg += ", ";
- }
- LogWarn(Severity_High, Error_Unexpect, LOG_ERR_SET_DNS_FAILED, print_msg.c_str());
- }
- }
- }
- return 0;
- }
- #endif // RVC_OS_LINUX
- int ResourceWatcherFSM::GetCardSwiperStatus()
- {
- LOG_FUNCTION();
- ErrorCodeEnum errorCode = Error_Succeed;
- CardSwiperClient* client = NULL;
- CardSwiperService_QueryConnInfo_Req req;
- CardSwiperService_QueryConnInfo_Ans ans;
- QueryCardSwiper cardswiperStatus;
- BOOL bConnected = FALSE;
- // [Josephus in 7:05:25 2016/9/6]
- int lastStatus = m_cardswiperStatus;
- int errorTimes1 = 0, errorTimes2 = 0, errorTimes3 = 0;
- int sleepTime = 1500;
- const int errorMaxTimes = 2;
- m_bGetStatusRotate = TRUE;
- while (m_bGetStatusRotate)
- {
- if (client == NULL)
- {
- client = new CardSwiperClient(GetEntityBase());
- }
- if (!bConnected)
- {
- errorCode = client->Connect();
- if (errorCode != Error_Succeed)
- {
- if (errorTimes1 < errorMaxTimes)
- {
- errorTimes1++;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Connect to CardSwiper failed %s", SpStrError(errorCode));
- Sleep(500);
- continue;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Connect to CardSwiper failed...");
- // [Josephus in 16:15:37 2016/3/28]
- bConnected = FALSE;
- client->SafeDelete();
- client = NULL;
- m_cardswiperStatus = 0;
- goto BroadCastPoint;
- }
- }
- else
- {
- bConnected = TRUE;
- errorTimes3 = errorTimes2 = 0;
- }
- }
- errorCode = client->QueryConnInfo(req, ans, 3000);
- if (errorCode != Error_Succeed)
- {
- if (errorTimes2 < errorMaxTimes)
- {
- errorTimes2++;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get CardSwiper status failed with code %s", SpStrError(errorCode));
- Sleep(500);
- continue;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get CardSwiper status failed...");
- bConnected = FALSE;
- client->GetFunction()->CloseSession();
- client = NULL;
- m_cardswiperStatus = 0;
- }
- }
- else
- {
- errorTimes1 = errorTimes2 = errorTimes3 = 0;
- m_cardswiperStatus = ans.connect;
- }
- BroadCastPoint:
- if (lastStatus != m_cardswiperStatus)
- {
- cardswiperStatus.status = m_cardswiperStatus;
- SpSendBroadcast(GetEntityBase()->GetFunction(),
- SP_MSG_OF(QueryCardSwiper), SP_MSG_SIG_OF(QueryCardSwiper), cardswiperStatus);
- lastStatus = m_cardswiperStatus;
- }
- break;
- }
- if (client)
- {
- #ifdef RVC_OS_LINUX
- if (bConnected)
- {
- client->GetFunction()->CloseSession();
- }
- else
- {
- client->SafeDelete();
- }
- #else
- client->SafeDelete();
- #endif // RVC_OS_LINUX
- client = NULL;
- }
- return 0;
- }
- #ifdef RVC_OS_LINUX
- void ResourceWatcherFSM::AppendVideoSizeTogether()
- {
- Dbg("Add UploadFile size together...");
- unsigned long long uiAdditionBytes;
- CalculateWillUploadDirSize(uiAdditionBytes);
- mAllVideoFileSizeCal += uiAdditionBytes;
- diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
- }
- void ResourceWatcherFSM::CalculateFreeDiskNeeded()
- {
- const_map_cu_iter citer = VideoDailyRecord.cbegin();
- UINT uCount = 0;
- while (citer != VideoDailyRecord.cend()) {
- Dbg("date[%d]: %d", (citer->first), citer->second);
- uCount += citer->second;
- citer++;
- }
- Dbg("count %d and video file size#%d", uCount, m_VideoFiles.size());
- diskInfo.CalAverRequreSpaceEachDay(mAllVideoFileSizeCal,
- uCount, VideoDailyRecord.size(),
- BASE_AVAILALBE_DATE_COUNT, mUiRequireBytes);
- }
- void ResourceWatcherFSM::RecordFreeDiskNeededToRunCfg()
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes);
- spConfigRun->WriteConfigValue("LastClearTime", "Video", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- m_bReadyFlag = false;
- }
- void ResourceWatcherFSM::GetFreeDiskNeededFromRunCfg()
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- UINT64 value(0);
- spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", value);
- mUiRequireBytes = value;
- Dbg("Retrieve from runcfg about required bytes: %llu", value);
- }
- #endif // RVC_OS_LINUX
- int ResourceWatcherFSM::CleanVideoFiles(int& newDeletedFilesNum, int initFlag)
- {
- #ifdef RVC_OS_LINUX
- ClearVideoQueue();
- newDeletedFilesNum = 0;
- CSimpleStringA filePath = m_csUploadVideoPath;
- Dbg("(InitFlag:%d) filePath %s", initFlag, (LPCTSTR)filePath);
- newDeletedFilesNum = 0;
- m_failDelCnt = 0;
- const int nRet = RemoveExpireVideoFileAndRecord((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
- PrintVideEmurateResult();
- Dbg("nRet: %d, new Deleted Files Num:%d, video counts:%d", nRet, newDeletedFilesNum, m_VideoFiles.size());
- LOG_ASSERT(nRet - newDeletedFilesNum == m_VideoFiles.size());
- if (!!initFlag) {
- AppendVideoSizeTogether();
- CalculateFreeDiskNeeded();
- RecordFreeDiskNeededToRunCfg();
- }
- else {
- GetFreeDiskNeededFromRunCfg();
- }
- return nRet;
- #else
- ClearVideoQueue();
- CSimpleStringA filePath = m_csUploadVideoPath + "\\*";
- newDeletedFilesNum = 0;
- m_failDelCnt = 0;
- int nRet = ProcessVideoFile((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
- PrintResult();
- assert(nRet - newDeletedFilesNum == m_VideoFiles.size());
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (initFlag == 1)
- {
- ULARGE_INTEGER uiAdditionBytes;
- CalCulateUploadFileAddition(uiAdditionBytes);
- uiAllVideoFileSizeCal.QuadPart += uiAdditionBytes.QuadPart;
- diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
- const_map_cu_iter citer = VideoDailyRecord.cbegin();
- UINT uCount = 0;
- while (citer != VideoDailyRecord.cend())
- {
- uCount += citer->second;
- citer++;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("uCount#%d, size#%d", uCount, m_VideoFiles.size());
- diskInfo.CalAverRequreSpaceEachDay(uiAllVideoFileSizeCal,
- uCount,
- VideoDailyRecord.size(),
- BASE_AVAILALBE_DATE_COUNT,
- mUiRequireBytes);
- FILETIME ftCurTime;
- GetSystemTimeAsFileTime(&ftCurTime);
- SYSTEMTIME stUTC, stLocal;
- FileTimeToSystemTime(&ftCurTime, &stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- int nYear = stLocal.wYear;
- int nMonth = stLocal.wMonth;
- int nDay = stLocal.wDay;
- char displayTime[MAX_PATH] = { 0 };
- GetTimeString(displayTime, MAX_PATH, &ftCurTime);
- CSimpleStringA csRecord = displayTime;
- #if 1
- spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
- spConfigRun->WriteConfigValueInt("Video", "FilesNum", nRet);
- spConfigRun->WriteConfigValueInt("Video", "Deleted", newDeletedFilesNum);
- spConfigRun->WriteConfigValueInt("Video", "FailedDel", m_failDelCnt);
- spConfigRun->WriteConfigValue("Video", "LastTime", csRecord);
- spConfigRun->WriteConfigValueInt("Video", "Year", nYear);
- spConfigRun->WriteConfigValueInt("Video", "Month", nMonth);
- spConfigRun->WriteConfigValueInt("Video", "Day", nDay);
- m_bReadyFlag = false;
- #endif
- }
- else
- {
- ErrorCodeEnum erroCode = spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes",
- mUiRequireBytes.QuadPart);
- if (erroCode != Error_Succeed)
- {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "Get RequiredBytes failed !");
- mUiRequireBytes.QuadPart = 0ui64;
- }
- }
- return nRet;
- #endif // RVC_OS_LINUX
- }
- #ifdef RVC_OS_LINUX
- void ResourceWatcherFSM::CalculateBackTime(time_t* ftResultTime, int days)
- {
- time_t ftCurTime = time(NULL);//获取当前时间
- time_t ftBackTime = ftCurTime - (60 * 60 * 24 * days);
- *ftResultTime = ftBackTime;
- return;
- }
- BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(unsigned long long& uiBytesCal)
- {
- uiBytesCal = 0;
- BOOL bRet = FALSE;
- CSimpleStringA uploadVideoPath;
- CSimpleStringA tmpValue;
- ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
- if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
- if (ec == Error_Succeed) {
- Dbg("UploadVideo path: %s", (LPCTSTR)uploadVideoPath);
- uiBytesCal = 0;
- const int nFileCnt = CalculateAllVideoSize(uploadVideoPath, &uiBytesCal);
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(szResult, (double)uiBytesCal);
- Dbg("Result: Files(%d), Size: %s", nFileCnt, szResult);
- }
- return (ec == Error_Succeed);
- }
- int ResourceWatcherFSM::RemoveExpireVideoFileAndRecord(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag)
- {
- int fileCnt = 0;
- int fileLength = strlen(dirName);
- // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
- char searchFilePath[MAX_PATH] = { 0 };
- char tempFilePath[MAX_PATH] = { 0 };
- char displayTime[MAX_PATH] = { 0 };
- time_t tmp_time;
- CalculateBackTime(&tmp_time, m_nDayOfBackward);
- deletedFileCnt = deleteFailedCnt = 0;
- GetTimeFormatStr(displayTime, MAX_PATH, &tmp_time);
- Dbg("video backtrace time: %s", displayTime);
- struct stat st;
- if (stat(dirName, &st) < 0 || !S_ISDIR(st.st_mode)) {
- return 0;
- }
- DIR* d = opendir(dirName);
- if (!d) {
- return 0;
- }
- struct dirent* dp = NULL;
- while ((dp = readdir(d)) != NULL) {
- if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
- continue;
- }
- strcpy(tempFilePath, dirName);
- if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
- Dbg("filePath is too long for current.");
- continue;
- }
- strcat(tempFilePath, "/");
- strcat(tempFilePath, dp->d_name);
- if (-1 == stat(tempFilePath, &st)) {
- Dbg("stat video file: %s error: %d", tempFilePath, errno);
- continue;
- }
- const bool isdir = !!(S_ISDIR(st.st_mode));
- if (isdir) {
- fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
- }
- else {
- if (nFlag == 1 && st.st_mtime < tmp_time) {
- GetTimeFormatStr(displayTime, MAX_PATH, &st.st_mtime);
- if (RemoveFileA(tempFilePath)) {
- deletedFileCnt++;
- Dbg("Delete matched %s(%s) suc.", dp->d_name, displayTime);
- }
- else {
- deleteFailedCnt++;
- Dbg("Delete matched %s(%s) failed: %d", dp->d_name, displayTime, errno);
- }
- }
- RecordVideoFileInfomation(tempFilePath, &st);
- fileCnt++;
- }
- }
- closedir(d);
- return fileCnt;
- }
- void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, struct stat* pWfdata)
- {
- m_VideoFiles.push(new TmpFileInfo(lpFilePath, pWfdata->st_mtime, pWfdata->st_size));
- mAllVideoFileSizeCal += pWfdata->st_size;
- if (mMaxFileSize < pWfdata->st_size) {
- strcpy(szMaxSizeFilePath, lpFilePath);
- mMaxFileSize = pWfdata->st_size;
- }
- SyncUpdateVideoCreateDaily(&pWfdata->st_mtime, 1);
- }
- #else
- void ResourceWatcherFSM::CalculateBackTime(PFILETIME ftResultTime, int days)
- {
- //Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
- FILETIME ftCurTime, ftBackTime;
- GetSystemTimeAsFileTime(&ftCurTime);
- ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
- uliCurTime.HighPart = ftCurTime.dwHighDateTime;
- uliCurTime.LowPart = ftCurTime.dwLowDateTime;
- if (days > 0)
- {
- uliOffset.QuadPart = UInt32x32To64(days * 24 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
- }
- else
- {
- uliOffset.QuadPart = UInt32x32To64(-1 * days * 24 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart + uliOffset.QuadPart;
- }
- ftBackTime.dwHighDateTime = uliBackTime.HighPart;
- ftBackTime.dwLowDateTime = uliBackTime.LowPart;
- *ftResultTime = ftBackTime;
- return;
- }
- void ResourceWatcherFSM::GetTimeString(LPTSTR lpszString, DWORD dwSize, FILETIME* ftWrite)
- {
- SYSTEMTIME stUTC, stLocal;
- // Convert the last-write time to local time.
- FileTimeToSystemTime(ftWrite, &stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- // Build a string showing the date and time.
- sprintf_s(lpszString, dwSize, "%02d/%02d/%d %02d:%02d:%02d",
- stLocal.wMonth, stLocal.wDay, stLocal.wYear,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- return;
- }
- int ResourceWatcherFSM::ProcessVideoFile(
- LPCTSTR dirName
- , int& deletedFileCnt
- , int& deleteFailedCnt
- , const int nFlag)
- {
- int fileCnt = 0;
- int fileLength = strlen(dirName);
- // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
- char searchFilePath[MAX_PATH] = { 0 };
- char tempFilePath[MAX_PATH] = { 0 };
- char displayTime[MAX_PATH] = { 0 };
- WIN32_FIND_DATA foundFileData;
- HANDLE hFind;
- FILETIME ftRemoveTime;
- CalculateBackTime(&ftRemoveTime, m_nDayOfBackward);
- GetTimeString(displayTime, MAX_PATH, &ftRemoveTime);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The date backward to delete: %s", displayTime);
- hFind = FindFirstFile(dirName, &foundFileData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM) ("FindFirstFile failed (%u)", GetLastError());
- return 0;
- }
- if ((foundFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (/*foundFileData.cFileName[0] != '.'*/FALSE)
- {
- strcpy_s(tempFilePath, dirName);
- tempFilePath[fileLength - 1] = '\0';
- if (strlen(tempFilePath) + strlen(foundFileData.cFileName) + 3 >= MAX_PATH)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
- }
- else
- {
- strcat_s(tempFilePath, foundFileData.cFileName);
- strcat_s(tempFilePath, "\\*");
- fileCnt += ProcessVideoFile((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
- }
- }
- }
- else
- {
- strcpy_s(searchFilePath, dirName);
- searchFilePath[fileLength - 1] = '\0';
- strcat_s(searchFilePath, foundFileData.cFileName);
- if (nFlag == 1 && CompareVideoFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0)
- {
- GetTimeString(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
- if (DeleteFile(searchFilePath) != 0)
- {
- deletedFileCnt++;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete matched %s(%s) suc.", foundFileData.cFileName, displayTime);
- }
- else
- {
- deleteFailedCnt++;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete matched %s(%s) failed(%d).", foundFileData.cFileName, displayTime, GetLastError());
- CalCulateFileInfo(searchFilePath, &foundFileData);
- }
- }
- else
- {
- CalCulateFileInfo(searchFilePath, &foundFileData);
- }
- fileCnt++;
- }
- while (FindNextFile(hFind, &foundFileData))
- {
- if ((foundFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (/*foundFileData.cFileName[0] != '.'*/FALSE)
- {
- strcpy_s(tempFilePath, dirName);
- tempFilePath[fileLength - 1] = '\0';
- strcat_s(tempFilePath, foundFileData.cFileName);
- strcat_s(tempFilePath, "\\*");
- fileCnt += ProcessVideoFile((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
- }
- }
- else
- {
- strcpy_s(searchFilePath, dirName);
- searchFilePath[fileLength - 1] = '\0';
- strcat_s(searchFilePath, foundFileData.cFileName);
- if (nFlag == 1 && CompareVideoFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0)
- {
- GetTimeString(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
- if (DeleteFile(searchFilePath) != 0)
- {
- deletedFileCnt++;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete matched %s(%s) suc.", foundFileData.cFileName, displayTime);
- }
- else
- {
- deleteFailedCnt++;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Delete matched %s(%s) failed(%d).",
- foundFileData.cFileName, displayTime, GetLastError());
- CalCulateFileInfo(searchFilePath, &foundFileData);
- }
- }
- else
- {
- CalCulateFileInfo(searchFilePath, &foundFileData);
- }
- fileCnt++;
- }
- }
- FindClose(hFind);
- return fileCnt;
- }
- BOOL ResourceWatcherFSM::GetCPUBrand(CSimpleStringA& csCpuBrand)
- {
- char CPUBrandString[0x40];
- int CPUInfo[4] = { -1 };
- unsigned nExIds;
- // Calling __cpuid with 0x80000000 as the InfoType argument
- // gets the number of valid extended IDs.
- __cpuid(CPUInfo, 0x80000000);
- nExIds = CPUInfo[0];
- memset(CPUBrandString, 0, sizeof(CPUBrandString));
- if (nExIds >= 0x80000004)
- {
- __cpuid(CPUInfo, 0x80000002);
- memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
- __cpuid(CPUInfo, 0x80000003);
- memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
- __cpuid(CPUInfo, 0x80000004);
- memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
- // Display all the information in user-friendly format.
- csCpuBrand = CPUBrandString;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CPU Brand String: %s", (LPCTSTR)csCpuBrand);
- return TRUE;
- }
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Current device is not supported for getting cpu brand 0x%08x.", nExIds);
- return FALSE;
- }
- void ResourceWatcherFSM::InitialCPUMarkInfor()
- {
- m_highPart = 4000;
- m_lowPart = 2000;
- Dbg("hight:%d > value >low:%d.", m_highPart, m_lowPart);
- return;
- }
- #endif // RVC_OS_LINUX
- void ResourceWatcherFSM::ClearMoreVideoFiles()
- {
- #ifdef RVC_OS_LINUX
- EnterCriticalSection(&g_csVideoMoreClear);
- ErrorCodeEnum erroCode = Error_Succeed;
- BOOL bOK = FALSE;
- char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (m_VideoFiles.empty() || mUiRequireBytes == 0) {
- int reseved = 0;
- int nRes = CleanVideoFiles(reseved, IsNeedToFirstClear() ? 1 : 0);
- if (nRes - reseved == 0) {
- Dbg("There are no any video files in facts.");
- //SetSysValAndBroadcast(0, "There are no any video files in facts.");
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- }
- }
- int CurRank = 3; //default
- int BfRank = 0;
- if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
- BfRank = 0;
- }
- if (BfRank > 0) {
- unsigned long long uiTotalBytes;
- unsigned long long uiFreeDiskBytes;
- if (!DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- }
- //对比上次,剩余的可用磁盘空间更小了。
- if (mUiCalibration >= uiFreeDiskBytes) {
- Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
- CurRank = BfRank == 4 ? 1 : BfRank;
- }
- mUiCalibration = uiFreeDiskBytes;
- }
- const int InitialRank = CurRank;
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- int nEnoughLevel = 0;
- unsigned long long uiFactor;
- char displayTime[MAX_PATH] = { 0 };
- time_t ftSavedTime;
- CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
- GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
- Dbg("It's SavedTime backtrace: %s", displayTime);
- do {
- uiFactor = DEFAULT_AVAILALBE_DATE_COUNT; // 7天
- if (CurRank == 2) uiFactor = LESS_AVAILALBE_DATE_COUNT; // 3天
- else if (CurRank == 1) uiFactor = LEAST_AVAILALBE_DATE_COUNT; // 1天
- const unsigned long long uiSpaceRequired = mUiRequireBytes * uiFactor;
- ByteSprintf(szResult, (double)uiSpaceRequired);
- Dbg("Required free disk size: %s, current rank: %d", szResult, CurRank);
- unsigned long long uiMoreSpaceRealRequired(0);
- unsigned long long uiAdjustment(0);
- if (diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_csUploadVideoPath, uiSpaceRequired, uiAdjustment, &uiMoreSpaceRealRequired)
- && uiMoreSpaceRealRequired) {
- unsigned long long uiNewFreeBytes(0);
- UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
- BOOL bTrackBackStop = FALSE;
- Dbg("the more space required: %llu.", uiMoreSpaceRealRequired);
- while (!m_VideoFiles.empty() && uiNewFreeBytes < uiMoreSpaceRealRequired) {
- TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
- if (pCurFileInfo != NULL) {
- GetTimeFormatStr(displayTime, MAX_PATH, &(pCurFileInfo->mftEditTime));
- if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
- Dbg("stop at %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
- bTrackBackStop = TRUE;
- break;
- }
- if (RemoveFileA(pCurFileInfo->msFileName.c_str()) != 0) {
- uiNewFreeBytes += pCurFileInfo->ftSize;
- uDeletedCnt++;
- Dbg("Delete suc: %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
- SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
- }
- else {
- Dbg("[DelFail] File(%s) %d", pCurFileInfo->msFileName.c_str(), errno);
- uFailedDeleteCnt++;
- }
- }
- m_VideoFiles.pop();
- if (pCurFileInfo != NULL) delete pCurFileInfo;
- }
- char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
- char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
- ByteSprintf(szOutput, (double)uiNewFreeBytes);
- ByteSprintf(szOutput2, (double)uiMoreSpaceRealRequired);
- Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
- CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
- if (uiNewFreeBytes >= uiMoreSpaceRealRequired) {
- break;
- }
- else {
- --CurRank;
- }
- #ifdef WITH_DEBUG
- UINT uCount = 0;
- for (const_map_cu_iter citer = VideoDailyRecord.cbegin(); citer != VideoDailyRecord.cend(); citer++) { uCount += citer->second; }
- Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
- #endif
- }
- else if (InitialRank > CurRank) {
- break;
- }
- else {
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- }
- } while (CurRank > 0);
- if (CurRank < 3) {
- unsigned long long uiTotalBytes;
- unsigned long long uiFreeDiskBytes;
- if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes)) {
- char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(szResult, (double)uiTotalBytes);
- ByteSprintf(szResult2, (double)uiFreeDiskBytes);
- double dFreeRate = (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
- sprintf(szResult3, "[Disk# %s] total: %s, free: %s, rate: %.1lf%%.",
- m_csUploadVideoPath.GetData(), szResult, szResult2, dFreeRate * 100);
- mUiCalibration = uiFreeDiskBytes;
- }
- else {
- strcpy(szResult3, "It's not enough disk space for recording video !");
- }
- }
- else {
- strcpy(szResult3, "Disk space is enough for recording.");
- }
- if (CurRank == 0) { CurRank = 4; }
- if (BfRank != CurRank) {
- erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
- }
- SetSysValAndBroadcast(CurRank, szResult3);
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- #else
- EnterCriticalSection(&g_csVideoMoreClear);
- ErrorCodeEnum erroCode = Error_Succeed;
- BOOL bOK = FALSE;
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (m_VideoFiles.empty())
- {
- int reseved = 0;
- IsNeedToFirstClear();
- int nRes = ClearVideoFiles(reseved, m_bReadyFlag ? 1 : 0);
- if (nRes - reseved == 0)
- {
- SetSysValAndBroadcast(0, "There are no any video files in facts.");
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- }
- }
- if (mUiRequireBytes.QuadPart == 0ui64)
- {//更新记录运行时,并等待下一次的自检执行。
- int reseved = 0;
- ClearVideoFiles(reseved);
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- }
- ULARGE_INTEGER uiSpaceRequired;
- ULARGE_INTEGER uiSpaceRealRequired;
- ULARGE_INTEGER uiFactor;
- int CurRank = 3;
- int BfRank = 0;
- if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0)
- BfRank = 0;
- if (BfRank > 0)
- {
- ULARGE_INTEGER uiTotalBytes;
- ULARGE_INTEGER uiFreeDiskBytes;
- if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes))
- {
- //对比上次,剩余的可用磁盘空间更小了。
- if (mUiCalibration.QuadPart >= uiFreeDiskBytes.QuadPart)
- {
- CurRank = BfRank;
- }
- mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
- }
- }
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- int nEnoughLevel = 0;
- do
- {
- uiFactor.QuadPart = 0;
- switch (CurRank)
- {
- case 3:
- uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
- break;
- case 2:
- uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LESS_AVAILALBE_DATE_COUNT;
- break;
- case 1:
- uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LEAST_AVAILALBE_DATE_COUNT;
- break;
- default:
- CurRank = 3;
- uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
- }
- ByteSprintf(szResult, (double)uiSpaceRequired.QuadPart);
- if (bOK = diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_csUploadVideoPath,
- uiSpaceRequired, uiFactor, &uiSpaceRealRequired))
- {
- if (uiSpaceRealRequired.QuadPart == 0)
- {
- break;
- }
- char displayTime[MAX_PATH] = { 0 };
- FILETIME ftSavedTime;
- //TODO: 暂时设置为至少保存两星期的录像文件,如果一天都不保留,那么 m_VideoFiles 要做即时更新 。2017-5-10
- CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
- GetTimeString(displayTime, MAX_PATH, &ftSavedTime);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SavedTime backtrace: %s", displayTime);
- ULARGE_INTEGER uiFreeBytes;
- uiFreeBytes.QuadPart = 0;
- UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
- BOOL bTrackBackStop = FALSE;
- while (!m_VideoFiles.empty() && uiFreeBytes.QuadPart < uiSpaceRealRequired.QuadPart)
- {
- TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
- if (pCurFileInfo != NULL)
- {
- SYSTEMTIME stUTC, stLocal;
- FileTimeToSystemTime(&(pCurFileInfo->mftEditTime), &stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("yet %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
- stLocal.wMonth, stLocal.wDay, stLocal.wYear,
- stLocal.wHour, stLocal.wMinute);
- bTrackBackStop = TRUE;
- break;
- }
- if (DeleteFile(pCurFileInfo->msFileName.c_str()) != 0)
- {
- ULARGE_INTEGER tmpBytes;
- tmpBytes.HighPart = pCurFileInfo->mDwFileSizeHeight;
- tmpBytes.LowPart = pCurFileInfo->mDwFileSizeLow;
- uiFreeBytes.QuadPart += tmpBytes.QuadPart;
- uDeletedCnt++;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Delete suc: %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
- stLocal.wMonth, stLocal.wDay, stLocal.wYear,
- stLocal.wHour, stLocal.wMinute);
- UINT uDate = stLocal.wYear * 10000 + stLocal.wMonth * 100 + stLocal.wDay;
- VideoDailyRecord[uDate]--;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[DelFail] File(%s) %u", pCurFileInfo->msFileName.c_str(), GetLastError());
- uFailedDeleteCnt++;
- }
- }
- m_VideoFiles.pop();
- if (pCurFileInfo != NULL) delete pCurFileInfo;
- }
- char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
- char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
- ByteSprintf(szOutput, (double)uiFreeBytes.QuadPart);
- ByteSprintf(szOutput2, (double)uiSpaceRealRequired.QuadPart);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
- CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
- if (uiFreeBytes.QuadPart >= uiSpaceRealRequired.QuadPart)
- {
- break;
- }
- --CurRank;
- #if 1
- UINT uCount = 0;
- for (const_map_cu_iter citer = VideoDailyRecord.cbegin();
- citer != VideoDailyRecord.cend(); citer++)
- {
- uCount += citer->second;
- }
- #endif
- }
- else
- {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "IsNeedToDoClearJobEx invoked failed !");
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- }
- } while (CurRank > 0);
- char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
- if (CurRank < 3)
- {
- ULARGE_INTEGER uiTotalBytes;
- ULARGE_INTEGER uiFreeDiskBytes;
- if (DiskInfo::GetDiskSpace((LPCTSTR)m_csUploadVideoPath, uiTotalBytes, uiFreeDiskBytes))
- {
- char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(szResult, (double)uiTotalBytes.QuadPart);
- ByteSprintf(szResult2, (double)uiFreeDiskBytes.QuadPart);
- double dFreeRate = (uiFreeDiskBytes.QuadPart * kConversion[3]) / (uiTotalBytes.QuadPart * kConversion[3]);
- sprintf_s(szResult3, "[Disk# %c:\\] total: %s, free: %s, rate: %.1lf%%.",
- m_csUploadVideoPath[0], szResult, szResult2, dFreeRate * 100);
- mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
- }
- else
- {
- strcpy_s(szResult3, "It's not enough disk space for recording video !");
- }
- if (CurRank == 0)
- {
- CurRank = 4;
- }
- }
- else
- {
- strcpy_s(szResult3, "Disk space is enough for recording.");
- }
- if (BfRank != CurRank)
- {
- erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
- }
- SetSysValAndBroadcast(CurRank, szResult3);
- LeaveCriticalSection(&g_csVideoMoreClear);
- return;
- #endif // RVC_OS_LINUX
- }
- #ifdef RVC_OS_LINUX
- BOOL ResourceWatcherFSM::RemoveDuplicateCenterSettingFiles()
- {
- LOG_FUNCTION();
- ErrorCodeEnum erroCode = Error_Succeed;
- CSmartPointer<IConfigInfo> spConfigRun;
- erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (erroCode != Error_Succeed) {
- Dbg("OpenConfig of 'Config_Run' failed 0x%x(%d).", erroCode, erroCode);
- return FALSE;
- }
- int nLastTaskTime(0);
- spConfigRun->ReadConfigValueInt("LastClearTime", "CenterSetting", nLastTaskTime);
- if (IsTodayDone(nLastTaskTime)) {
- return TRUE;
- }
- CSimpleStringA ssFilePath(true);
- erroCode = GetEntityBase()->GetFunction()->GetPath("cfg", ssFilePath);
- if (erroCode != Error_Succeed || ssFilePath.IsNullOrEmpty()) {
- Dbg("Get path of 'cfg' failed 0x%x(%d).", erroCode, erroCode);
- return FALSE;
- }
- Dbg("filePath %s", (LPCTSTR)ssFilePath);
- int nDelSuc = 0;
- int nDelFailed = 0;
- int nfileSum = ClearSpecifieFile(DFT_CenterSetting, ssFilePath, nDelSuc, nDelFailed);
- Dbg("#CenterSetting#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
- spConfigRun->WriteConfigValue("LastClearTime", "CenterSetting", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- return TRUE;
- }
- int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt)
- {
- LOG_FUNCTION();
- int nRes;
- int nfileCnt = 0;
- int fileLength = strlen(dirName);
- char searchFilePath[MAX_PATH] = { 0 };
- char tempFilePath[MAX_PATH] = { 0 };
- char displayTime[MAX_PATH] = { 0 };
- struct stat st;
- if (stat(dirName, &st) < 0) {
- Dbg("stat for %s failed: %d %s", dirName, errno, strerror(errno));
- return -2;
- }
- if (!S_ISDIR(st.st_mode)) {
- Dbg(" %s is not directory", dirName);
- return -2;
- }
- DIR* d = opendir(dirName);
- if (!d) {
- return -3;
- }
- struct dirent* dp = NULL;
- while ((dp = readdir(d)) != NULL) {
- if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
- continue;
- }
- strcpy(tempFilePath, dirName);
- if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
- Dbg("filePath is too long for current.");
- continue;
- }
- strcat(tempFilePath, "/");
- strcat(tempFilePath, dp->d_name);
- Dbg("fileName: %s", dp->d_name);
- struct stat stFile;
- stat(tempFilePath, &stFile);
- const bool isdir = !!(S_ISDIR(stFile.st_mode));
- if (isdir && fileType != DFT_CenterSetting) {
- int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
- if (nRes >= 0) nfileCnt += nRes;
- }
- else if (!isdir) {
- if (fileType != DFT_Ad0 || (CompareVideoFileTime(&mftAd0RemoveTime, &stFile.st_mtime) >= 0)) {
- nRes = RemoveSpecifiedFile(fileType, tempFilePath, dp->d_name);
- }
- else {
- nRes = 0;
- }
- if (nRes == -1) deleteFailedCnt++;
- else if (nRes == 1) deletedFileCnt++;
- nfileCnt++;
- }
- }
- closedir(d);
- return nfileCnt;
- }
- int ResourceWatcherFSM::RemoveSpecifiedFile(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
- {
- CSimpleStringA ssFileName = szFileName;
- if (ssFileName.IsNullOrEmpty()) return FALSE;
- if ((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
- || fileType == DFT_Ad0
- ) {
- if (RemoveFileA(szFilePath)) {
- Dbg("%s delete suc.", szFileName);
- return 1;
- }
- Dbg("%s delete failed %d.", szFileName, GetLastError());
- return -1;
- }
- return 0;
- }
- #else
- BOOL ResourceWatcherFSM::ExecuteClearTask()
- {
- ErrorCodeEnum erroCode = Error_Succeed;
- CSmartPointer<IConfigInfo> spConfigRun;
- erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA ssCurTarget = "CenterSetting";
- CSimpleStringA ssLasTarget = "";
- int nLastTaskTime(0);
- int nFailedNum(0);
- spConfigRun->ReadConfigValue("ClearTask", "Target", ssLasTarget);
- spConfigRun->ReadConfigValueInt("ClearTask", "LastTime", nLastTaskTime);
- spConfigRun->ReadConfigValueInt("ClearTask", "FailedNum", nFailedNum);
- SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Last clear time: %04d-%02d-%02d %02d:%02d:%02d",
- stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
- stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
- SYSTEMTIME stNow = {};
- GetLocalTime(&stNow);
- if (nLastTaskTime > 0
- /*&& ssCurTarget.Compare(ssLasTarget, true) == 0*/
- && stTaskTime.wYear == stNow.wYear
- && stTaskTime.wMonth == stNow.wMonth && stTaskTime.wDay == stNow.wDay
- && nFailedNum == 0)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ClearTask has been executed today, last clear time: %s",
- (const char*)CSmallDateTime(nLastTaskTime).ToTimeString());
- return TRUE;
- }
- CSimpleStringA ssFilePath = "";
- erroCode = GetEntityBase()->GetFunction()->GetPath("cfg", ssFilePath);
- if (erroCode != Error_Succeed || ssFilePath.IsNullOrEmpty())
- {
- return FALSE;
- }
- ssFilePath = ssFilePath + "\\*";
- int nDelSuc = 0;
- int nDelFailed = 0;
- int nfileSum = ClearSpecifieFile(DFT_CenterSetting, (LPCTSTR)ssFilePath, nDelSuc, nDelFailed);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
- spConfigRun->WriteConfigValue("ClearTask", "Target", (LPCTSTR)ssCurTarget);
- spConfigRun->WriteConfigValue("ClearTask", "LastTime",
- (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- spConfigRun->WriteConfigValueInt("ClearTask", "TargetNum", nDelSuc + nDelFailed);
- spConfigRun->WriteConfigValueInt("ClearTask", "FailedNum", nDelFailed);
- return TRUE;
- }
- int ResourceWatcherFSM::ClearSpecifieFile(
- DealFileType fileType,
- LPCTSTR dirName,
- int& deletedFileCnt,
- int& deleteFailedCnt)
- {
- int nRes;
- int nfileCnt = 0;
- int fileLength = strlen(dirName);
- char searchFilePath[MAX_PATH] = { 0 };
- char tempFilePath[MAX_PATH] = { 0 };
- char displayTime[MAX_PATH] = { 0 };
- WIN32_FIND_DATA fndFileData;
- HANDLE hFind;
- hFind = FindFirstFile(dirName, &fndFileData);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- return -2;
- }
- if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (fndFileData.cFileName[0] != '.')
- {
- memset(tempFilePath, 0, sizeof(tempFilePath));
- strcpy_s(tempFilePath, dirName);
- tempFilePath[fileLength - 1] = '\0';
- if (strlen(tempFilePath) + strlen(fndFileData.cFileName) + 3 >= MAX_PATH)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
- }
- else
- {
- strcat_s(tempFilePath, fndFileData.cFileName);
- strcat_s(tempFilePath, "\\*");
- int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
- if (nRes >= 0) nfileCnt += nRes;
- }
- }
- }
- else
- {
- memset((void*)searchFilePath, 0, MAX_PATH);
- strcpy_s(searchFilePath, dirName);
- searchFilePath[fileLength - 1] = '\0';
- strcat_s(searchFilePath, fndFileData.cFileName);
- if (fileType == DFT_Ad0) {
- if (CompareFileTime(&m_ftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
- nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
- }
- else {
- nRes = 0;
- }
- }
- else {
- nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
- }
- if (nRes == -1) deleteFailedCnt++;
- else if (nRes == 1) deletedFileCnt++;
- nfileCnt++;
- }
- while (FindNextFile(hFind, &fndFileData))
- {
- if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (fndFileData.cFileName[0] != '.')
- {
- memset(tempFilePath, 0, sizeof(tempFilePath));
- strcpy_s(tempFilePath, dirName);
- tempFilePath[fileLength - 1] = '\0';
- strcat_s(tempFilePath, fndFileData.cFileName);
- strcat_s(tempFilePath, "\\*");
- int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
- if (nRes >= 0) nfileCnt += nRes;
- }
- }
- else
- {
- memset((void*)searchFilePath, 0, MAX_PATH);
- strcpy_s(searchFilePath, dirName);
- searchFilePath[fileLength - 1] = '\0';
- strcat_s(searchFilePath, fndFileData.cFileName);
- if (fileType == DFT_Ad0) {
- if (CompareFileTime(&m_ftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
- nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
- }
- else {
- nRes = 0;
- }
- }
- else {
- nRes = DoSomethingWith(fileType, searchFilePath, fndFileData.cFileName);
- }
- if (nRes == -1) deleteFailedCnt++;
- else if (nRes == 1) deletedFileCnt++;
- nfileCnt++;
- }
- }
- FindClose(hFind);
- return nfileCnt;
- }
- int ResourceWatcherFSM::DoSomethingWith(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
- {
- CSimpleStringA ssFileName = szFileName;
- if (ssFileName.GetLength() <= 0)
- return FALSE;
- if ((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
- ||
- fileType == DFT_Ad0
- ) {
- if (DeleteFile(szFilePath) != 0)
- {
- return 1;
- }
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s delete failed %d.", szFileName, GetLastError());
- return -1;
- }
- return 0;
- }
- #endif // RVC_OS_LINUX
- bool ResourceWatcherFSM::IsNeedToFirstClear()
- {
- #ifdef RVC_OS_LINUX
- int nLastTaskTime(0);
- CSmartPointer<IConfigInfo> spRunConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- spRunConfig->ReadConfigValueInt("LastClearTime", "Video", nLastTaskTime);
- return !IsTodayDone(nLastTaskTime);
- #else
- m_bReadyFlag = true;
- CSimpleStringA csLstExecTime;
- CSmartPointer<IConfigInfo> spRunConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- spRunConfig->ReadConfigValue("Video", "LastTime", csLstExecTime);
- if (csLstExecTime.GetLength() > 1)
- {
- int nYear = 0, nMonth = 0, nDay = 0;
- spRunConfig->ReadConfigValueInt("Video", "Year", nYear);
- spRunConfig->ReadConfigValueInt("Video", "Month", nMonth);
- spRunConfig->ReadConfigValueInt("Video", "Day", nDay);
- if (nYear != 0 && nMonth != 0 && nDay != 0)
- {
- SYSTEMTIME stUTC, stLocal;
- GetSystemTime(&stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- if (nYear == stLocal.wYear && nMonth == stLocal.wMonth && nDay == stLocal.wDay)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Video Clear job has been done today in %s", (LPCTSTR)csLstExecTime);
- m_bReadyFlag = false;
- }
- }
- }
- return m_bReadyFlag;
- #endif // RVC_OS_LINUX
- }
- int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt)
- {
- #ifdef RVC_OS_LINUX
- int fileCnt = 0;
- int fileLength = strlen(lpszPath);
- char* searchFilePath = new char[MAX_PATH];
- char* tempFilePath = new char[MAX_PATH];
- if (searchFilePath == NULL || tempFilePath == NULL) {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- ZeroMemory(searchFilePath, MAX_PATH);
- ZeroMemory(tempFilePath, MAX_PATH);
- struct stat st;
- if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- Dbg("stat failed or is not dir.");
- return fileCnt;
- }
- DIR* d = opendir(lpszPath);
- if (!d) {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- Dbg("opendir failed: %d", errno);
- return fileCnt;
- }
- struct dirent* dp = NULL;
- while ((dp = readdir(d)) != NULL) {
- if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
- continue;
- }
- strcpy(tempFilePath, lpszPath);
- if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
- Dbg("filePath is too long for current.");
- continue;
- }
- strcat(tempFilePath, "/");
- strcat(tempFilePath, dp->d_name);
- stat(tempFilePath, &st);
- bool isdir = !!(S_ISDIR(st.st_mode));
- if (isdir) {
- int tDelSucCnt = 0, tDelFailedCnt = 0;
- fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
- if (tDelFailedCnt == 0 && rmdir(tempFilePath) != 0) {
- Dbg("rmdir(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno);
- nDelFailedCnt++;
- }
- nDelFailedCnt += tDelFailedCnt;
- nDelSucCnt += tDelSucCnt;
- }
- else {
- if (RemoveFileA(tempFilePath)) {
- nDelSucCnt++;
- Dbg("Delete [%s] suc.", dp->d_name);
- }
- else {
- nDelFailedCnt++;
- Dbg("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno);
- }
- fileCnt++;
- }
- }
- closedir(d);
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- searchFilePath = NULL;
- tempFilePath = NULL;
- return fileCnt;
- #else
- int fileCnt = 0;
- int fileLength = strlen(lpszPath);
- WIN32_FIND_DATA wfd;
- HANDLE hFind;
- hFind = FindFirstFile(lpszPath, &wfd);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("FindFirstFile failed GLE = %u.", GetLastError());
- return 0;
- }
- char* searchFilePath = new char[MAX_PATH];
- char* tempFilePath = new char[MAX_PATH];
- if (searchFilePath == NULL || tempFilePath == NULL)
- {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- searchFilePath = NULL;
- tempFilePath = NULL;
- return fileCnt;
- }
- ZeroMemory(searchFilePath, MAX_PATH);
- ZeroMemory(tempFilePath, MAX_PATH);
- do
- {
- if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (wfd.cFileName[0] != '.')
- {
- strcpy_s(tempFilePath, MAX_PATH, lpszPath);
- tempFilePath[fileLength - 1] = '\0';
- if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
- }
- else
- {
- strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
- CSimpleStringA tmpPath = tempFilePath;
- strcat_s(tempFilePath, MAX_PATH, "\\*");
- int tDelSucCnt = 0, tDelFailedCnt = 0;
- fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
- if (tDelFailedCnt == 0 && !RemoveDirectoryA(tmpPath))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RemoveDirectoryA(%s) failed, GLE = %u.", (LPCTSTR)tmpPath, GetLastError());
- nDelFailedCnt++;
- }
- nDelFailedCnt += tDelFailedCnt;
- nDelSucCnt += tDelSucCnt;
- }
- }
- }
- else
- {
- strcpy_s(searchFilePath, MAX_PATH, lpszPath);
- searchFilePath[fileLength - 1] = '\0';
- strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
- if (DeleteFile(searchFilePath) != 0)
- {
- nDelSucCnt++;
- }
- else
- {
- nDelFailedCnt++;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Delete [%s] failed, GLE = %u.", wfd.cFileName, GetLastError());
- }
- fileCnt++;
- }
- } while (FindNextFileA(hFind, &wfd));
- FindClose(hFind);
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- searchFilePath = NULL;
- tempFilePath = NULL;
- return fileCnt;
- #endif // RVC_OS_LINUX
- }
- BOOL ResourceWatcherFSM::DeleteVersionPackage()
- {
- BOOL bRet = FALSE;
- ErrorCodeEnum erroCode = Error_Succeed;
- CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfigRun;
- CSmartPointer<IConfigInfo> spConfig;
- CSystemStaticInfo info;
- if (pFunc->GetSystemStaticInfo(info) != Error_Succeed) {
- LogError(Severity_Middle, erroCode, 0, "Get system static info error");
- return FALSE;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Current version: %s", (LPCTSTR)info.InstallVersion.ToString());
- //判断是否需要被清理
- int nLastTaskTime = 0;
- int nLstFlag = 0;
- int nDelCount = 0;
- UINT64 utVersion = 0;
- int verSaved = DEFAULT_VERSION_SAVED_COUNT;
- int tmpSaved = 0;
- pFunc->OpenConfig(Config_CenterSetting, spConfig);
- spConfig->ReadConfigValueInt("VersionSaved", "default", tmpSaved);
- if (tmpSaved > DEFAULT_VERSION_SAVED_COUNT) {
- verSaved = tmpSaved;
- }
- pFunc->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->ReadConfigValueHexInt("VersionClear", "OptVer", utVersion);
- spConfigRun->ReadConfigValueInt("VersionClear", "DelVerCnt", nDelCount);
- spConfigRun->ReadConfigValueInt("VersionClear", "LastCondi", nLstFlag);
- spConfigRun->ReadConfigValueInt("VersionClear", "LastTime", nLastTaskTime);
- CVersion optVer(utVersion);
- SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
- stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
- stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
- (LPCTSTR)optVer.ToString(), nLstFlag);
- //判断是否需要被清理
- if (optVer.IsValid() && optVer == info.InstallVersion && !nLstFlag) {
- Dbg("VersionPackage cleaning has been done before.");
- return TRUE;
- }
- CSimpleStringA strRunInfo, strStartTime;
- if (m_pEntity->GetFunction()->GetPath("RunInfo", strRunInfo) == Error_Succeed) {
- strStartTime = strRunInfo + SPLIT_SLASH_STR + "runcfg" + SPLIT_SLASH_STR + "starttime.dat";
- if (!ExistsFileA(strStartTime.GetData())) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade prpcess done, try to delete version files.");//完成升级过程,通过
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,should not delete version files.");
- return FALSE;//升级未完成,不进行删除
- }
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path is error, should not delete version files.");
- return FALSE;//失败,继续等待
- }
- //获取当前目录下的文件夹名称, 将符合命名规则的终端版本名称push_back
- CSimpleStringA csPath;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
- if (Error_Succeed == Error) {
- if (csPath.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get currVer path is null");
- return FALSE;
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CUR VERSION PATH = %s.", csPath.GetData());
- }
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get Ver path error");
- return FALSE;
- }
- vector<CVersion> intallInfoVects;
- vector<string> files;
- CSimpleStringA upPath;
- ErrorCodeEnum upError = pFunc->GetPath("Upgraded", upPath);
- if (Error_Succeed != upError) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get Upgraded path error");
- return FALSE;
- }
- #ifdef RVC_OS_LINUX
- DIR* dp;
- struct dirent* dirp;
- if ((dp = opendir(csPath.GetData())) != NULL) {
- while ((dirp = readdir(dp)) != NULL) {
- //files.push_back(string(dirp->d_name));
- CInstallInfo verInfo = {};
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(dirp->d_name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
- continue;
- }
- else {
- CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
- if (verName.IsValid() && verName < info.InstallVersion) //对高于自身版本的文件不予删除
- {
- intallInfoVects.push_back(verName);
- }
- else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
- }
- }
- }
- closedir(dp);
- }
- //删除rvc/Upgraded目录下的文件
- DIR* updp;
- struct dirent* updirp;
- if ((updp = opendir(upPath.GetData())) != NULL) {
- while ((updirp = readdir(updp)) != NULL) {
- char szPath[MAX_VERSION_PATH] = { 0 };
- strcat(szPath, upPath.GetData());
- CSimpleStringA tmpDirPath = szPath;
- strcat(szPath, SPLIT_SLASH_STR);
- strcat(szPath, updirp->d_name);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("operating Upgrade path: [%s][%s]", (LPCTSTR)tmpDirPath, szPath);
- RemoveFileA(szPath);
- }
- closedir(updp);
- }
- #else
- long hFile = 0;
- struct _finddata_t fileinfo;//文件信息读取结构
- string p;
- if ((hFile = _findfirst(p.assign(string(csPath.GetData())).append("\\*").c_str(), &fileinfo)) != -1) {
- do {
- CInstallInfo verInfo = {};
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(fileinfo.name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
- continue;
- }
- else {
- CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
- if (verName.IsValid() && verName < info.InstallVersion)
- {
- intallInfoVects.push_back(verName);
- }
- else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
- }
- }
- } while (_findnext(hFile, &fileinfo) == 0);
- _findclose(hFile);
- }
- //删除rvc/Upgraded目录下的文件
- struct _finddata_t upfileinfo;
- long upFile = 0;
- if ((upFile = _findfirst(p.assign(string(upPath.GetData())).append("\\*").c_str(), &upfileinfo)) != -1) {
- do {
- char szPath[MAX_VERSION_PATH] = { 0 };
- strcat_s(szPath, upPath.GetData());
- CSimpleStringA tmpDirPath = szPath;
- strcat_s(szPath, SPLIT_SLASH_STR);
- strcat_s(szPath, upfileinfo.name);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("operating Upgrade path: [%s][%s]", (LPCTSTR)tmpDirPath, szPath);
- RemoveFileA(szPath);
- } while (_findnext(upFile, &upfileinfo) == 0);
- _findclose(upFile);
- }
- #endif // RVC_OS_LINUX
- int nPackCount = intallInfoVects.size();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Install Package's count: %d", nPackCount);
- bool bFailFlag = false;
- int nDelVersionCnt = 0;
- std::string tInfo("");
- if (nPackCount != 0) {
- int nSavedCount = 0;
- sort(intallInfoVects.begin(), intallInfoVects.end());
- vector<CVersion>::reverse_iterator riter = intallInfoVects.rbegin();
- while (riter != intallInfoVects.rend()) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("InstallPackage Info: %s", (LPCTSTR)(*riter).ToString());
- if (++nSavedCount <= verSaved) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Save above version");
- riter++;
- continue;
- }
- if (!DeleteSpecificeVersionDir(*riter)) bFailFlag = true;
- else {
- nDelVersionCnt++;
- tInfo = tInfo + "|" + std::string((*riter).ToString().GetData());
- }
- riter++;
- }
- }
- nLstFlag = bFailFlag ? 1 : 0;
- spConfigRun->WriteConfigValueHexInt("VersionClear", "OptVer", info.InstallVersion.GetVersion64());
- spConfigRun->WriteConfigValueInt("VersionClear", "DelVerCnt", nDelCount + nDelVersionCnt);
- spConfigRun->WriteConfigValueInt("VersionClear", "LastCondi", nLstFlag);
- spConfigRun->WriteConfigValue("VersionClear", "LastTime",
- (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- if (nDelVersionCnt > 0) {
- std::string warn = "Delete Vesion file count : " + std::to_string((long long)nDelVersionCnt) + ". ----- " + tInfo + ".";
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_VER_DELETE, CSimpleStringA::Format("%s", warn.c_str()));
- }
- return TRUE;
- }
- BOOL ResourceWatcherFSM::DeleteSpecificeVersionDir(CVersion version)
- {
- #ifdef RVC_OS_LINUX
- ErrorCodeEnum erroCode = Error_Unexpect;
- CSimpleStringA strPath;
- if (GetEntityBase()->GetFunction()->GetPath("RootVer", strPath) != Error_Succeed)
- return FALSE;
- strPath = strPath + SPLIT_SLASH_STR + version.ToString();
- if (!ExistsDirA(strPath)) {
- Dbg("Directory(%s) Not Existed, Maybe delete before !!", strPath.GetData());
- return TRUE;
- }
- CSimpleStringA tmpDirPath = strPath;
- Dbg("operating version path: [%s][%s]", (LPCTSTR)tmpDirPath, (LPCTSTR)strPath);
- int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
- nFileCount = ProcessFileDelete((LPCTSTR)tmpDirPath, nDelSuc, nDelFail);
- Dbg("Process result(%s): count(%d), suc(%d), failed(%d).", tmpDirPath.GetData(), nFileCount, nDelSuc, nDelFail);
- if (nDelFail != 0 || rmdir(tmpDirPath) != 0) {
- Dbg("Unexpect condition happen: (%d)", nDelFail);
- return FALSE;
- }
- return TRUE;
- #else
- ErrorCodeEnum erroCode = Error_Unexpect;
- char szPath[MAX_VERSION_PATH] = { 0 };
- ZeroMemory(szPath, MAX_VERSION_PATH);
- DWORD dwLen = GetModuleFileNameA(NULL, szPath, MAX_VERSION_PATH);
- if (dwLen != 0)
- {
- char* pch = strstr(szPath, "\\bin");
- if (pch != NULL)
- {
- pch[0] = '\0';
- CSimpleStringA strPath = szPath;
- pch = strrchr(szPath, '\\');
- if (pch != NULL)
- {
- pch[1] = '\0';
- strcat_s(szPath, (LPCTSTR)version.ToString());
- if (!ExistsDirA(szPath))
- {
- return TRUE;
- }
- CSimpleStringA tmpDirPath = szPath;
- strcat_s(szPath, "\\*");
- int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
- nFileCount = ProcessFileDelete(szPath, nDelSuc, nDelFail);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Process result(%s): count(%d), suc(%d), failed(%d).", szPath, nFileCount, nDelSuc, nDelFail);
- if (nDelFail != 0 || !RemoveDirectoryA(tmpDirPath))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unexpect condition happen: (%d)(%u).", nDelFail, GetLastError());
- return FALSE;
- }
- erroCode = Error_Succeed;
- }
- }
- }
- else
- {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "GetModuleFileNameA failed !");
- }
- return (erroCode == Error_Succeed);
- #endif // RVC_OS_LINUX
- }
- #ifdef RVC_OS_LINUX
- int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, unsigned long long* puliSpaceBytes)
- {
- int fileCnt = 0;
- int fileLength = strlen(lpszPath);
- char* searchFilePath = new char[MAX_PATH];
- char* tempFilePath = new char[MAX_PATH];
- if (searchFilePath == NULL || tempFilePath == NULL) {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- ZeroMemory(searchFilePath, MAX_PATH);
- ZeroMemory(tempFilePath, MAX_PATH);
- struct stat st;
- if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- DIR* d = opendir(lpszPath);
- if (!d) {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- struct dirent* dp = NULL;
- while ((dp = readdir(d)) != NULL) {
- if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
- continue;
- }
- strcpy(tempFilePath, lpszPath);
- if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
- Dbg("filePath is too long for current.");
- continue;
- }
- strcat(tempFilePath, "/");
- strcat(tempFilePath, dp->d_name);
- stat(tempFilePath, &st);
- const bool isdir = !!(S_ISDIR(st.st_mode));
- if (isdir) {
- fileCnt += CalculateAllVideoSize((LPCTSTR)tempFilePath, puliSpaceBytes);
- }
- else {
- *puliSpaceBytes += st.st_size;
- SyncUpdateVideoCreateDaily(&st.st_mtime, 1);
- fileCnt++;
- }
- }
- closedir(d);
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- #endif // RVC_OS_LINUX
- void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType,
- CSmartPointer<ITransactionContext> pTransactionContext)
- {
- #ifdef RVC_OS_LINUX
- static uint32_t times = 0;
- pTransactionContext->SendAnswer(Error_Succeed);
- times++;
- if (m_bVideoClearReady && times > 60 * 2) { //2 hour per times
- times = 0;
- PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
- }
- #else
- pTransactionContext->SendAnswer(Error_Succeed);
- if (m_bVideoClearReady)
- {
- PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
- }
- #endif // RVC_OS_LINUX
- }
- #ifndef RVC_OS_LINUX
- void ResourceWatcherFSM::ToCheckNetProbe()
- {
- if (!m_fProbeDone) {
- m_fProbeDone = true;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(new NetProbeTask(this));
- }
- }
- #endif // !RVC_OS_LINUX
- void ResourceWatcherFSM::SetSysValAndBroadcast(DWORD dwVal, LPCTSTR lpszMessage)
- {
- static DWORD dwOldVal = (DWORD)-1;
- CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
- CSimpleStringA csVPStatus = VIDEO_SPACE_UNKNOWN;
- CSimpleStringA csNewVPSatus = VIDEO_SPACE_UNKNOWN;
- spFunction->GetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csVPStatus);
- if (dwVal == 4)
- {
- csNewVPSatus = VIDEO_SPACE_INSUFF_FATAL;
- LogWarn(Severity_High, Error_TooSmallBuffer, LOG_ERR_RES_VIDEO_INSUFFICIENT, lpszMessage);
- }
- else if (dwVal == 2)
- {
- csNewVPSatus = VIDEO_SPACE_INSUFF_LITTLE;
- if (dwVal != dwOldVal)
- LogWarn(Severity_Middle, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
- }
- else if (dwVal == 1)
- {
- csNewVPSatus = VIDEO_SPACE_INSUFF_LESS;
- if (dwVal != dwOldVal)
- LogWarn(Severity_Low, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
- }
- else if (dwVal == 3)
- {
- csNewVPSatus = VIDEO_SPACE_SUFFICIENT;
- if (dwVal != dwOldVal)
- LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
- }
- else if (dwVal == 0)
- {
- if (dwVal != dwOldVal)
- LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
- }
- if (csNewVPSatus != csVPStatus)
- {
- ErrorCodeEnum eRet = spFunction->SetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csNewVPSatus);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetSysVar(%s) from '%s' to '%s' returned %d",
- SYSVAR_DISKSTATEUS_FOR_VIDEO
- , (LPCTSTR)csVPStatus
- , (LPCTSTR)csNewVPSatus
- , eRet);
- }
- dwOldVal = dwVal;
- }
- BOOL ResourceWatcherFSM::InitialFileEntity(LPCTSTR lpszPath, DWORD& dwFileCnt, const DWORD dwFilterAttributes)
- {
- LOG_FUNCTION();
- if (lpszPath == NULL)
- {
- SetLastError(ERROR_INVALID_PARAMETER);
- LogWarn(Severity_Middle, Error_Param, ERROR_INVALID_PARAMETER, "Null file path !");
- return FALSE;
- }
- #ifdef _MSC_VER
- HANDLE hFile = CreateFileA(
- lpszPath,
- GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
- if (hFile == INVALID_HANDLE_VALUE)
- {
- return FALSE;
- }
- #endif // _MSC_VER
- m_FileEntry.SubFiles.Clear();
- m_FileEntry.FileNamesBuffer.Clear();
- m_FileEntry.Current.Clear();
- DWORD dwLocate;
- Append(m_FileEntry.FileNamesBuffer, (PBYTE)lpszPath, strlen(lpszPath), dwLocate);
- m_FileEntry.Current.mNameOffset = dwLocate;
- m_FileEntry.Current.mNameLength = strlen(lpszPath);
- #ifdef _MSC_VER
- GetFileTime(hFile, (LPFILETIME)&m_FileEntry.Current.mftCreate,
- (LPFILETIME)&m_FileEntry.Current.mftAccess, (LPFILETIME)&m_FileEntry.Current.mftModified);
- CloseHandle(hFile);
- hFile = NULL;
- m_FileEntry.Current.mAttributes = GetFileAttributesA(lpszPath);
- m_FileEntry.Current.mFileSize = 0;
- DWORD dwDir = 0, dwFile = 0;
- GetSubFileInfors(&m_FileEntry, dwDir, dwFile, dwFilterAttributes);
- DisplayFileEntities(&m_FileEntry);
- dwFileCnt = dwDir + dwFile;
- #else
- struct stat st;
- if (stat(lpszPath, &st) < 0) {
- Dbg("stat %s failed.", lpszPath);
- return FALSE;
- }
- //GetFileTime
- m_FileEntry.Current.mftCreate = st.st_ctime;
- m_FileEntry.Current.mftAccess = st.st_atime;
- m_FileEntry.Current.mftModified = st.st_mtime;
- m_FileEntry.Current.mAttributes = 0;
- //GetFileAttributesA
- if (S_ISDIR(st.st_mode)) {
- m_FileEntry.Current.mFileSize = 0;
- m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_DIRECTORY;
- }
- else {
- m_FileEntry.Current.mFileSize = st.st_size;
- }
- if (m_FileEntry.Current.mAttributes == 0)
- m_FileEntry.Current.mAttributes = FILE_ATTRIBUTE_ARCHIVE;
- if (!(st.st_mode & S_IWUSR))
- m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_READONLY;
- DWORD dwDir = 0, dwFile = 0;
- GetSubFileInfors(&m_FileEntry, dwDir, dwFile, dwFilterAttributes);
- Dbg("Flag: dwDir:%u, dwFile: %u", dwDir, dwFile);
- DisplayFileEntities(&m_FileEntry);
- dwFileCnt = dwDir + dwFile;
- m_FileEntry.Current.mFileSize = dwFileCnt;
- #endif // _MSC_VER
- return TRUE;
- }
- DWORD ResourceWatcherFSM::InitialVolumes()
- {
- UINT uCount = 0;
- #ifdef _MSC_VER
- if (!sBDiskValStatus[MAX_VOLUME_COUNT])
- {
- CHAR szDrivers[BUFSIZE] = { 0 };
- CHAR szVolumeName[MAX_PATH] = { 0 };
- CHAR szFileSysName[MAX_PATH] = { 0 };
- BOOL bRet = GetLogicalDriveStringsA(BUFSIZE - 1, szDrivers);
- if (bRet)
- {
- int nDriNum = 0;
- for (CHAR* pTemp = szDrivers; *pTemp != '\0'; pTemp += 4)
- {
- if (*pTemp >= 'a' && *pTemp <= 'z') *pTemp -= 32;
- nDriNum = *pTemp - 'A';
- sBDiskValStatus[nDriNum] = FALSE;
- if (DRIVE_FIXED == GetDriveType(pTemp))
- {
- DWORD dwMaxCompLen, dwFileSystemFlags;
- bRet = GetVolumeInformation(pTemp, szVolumeName, MAX_PATH, NULL,
- &dwMaxCompLen, &dwFileSystemFlags, szFileSysName, MAX_PATH);
- sBDiskValStatus[nDriNum] = TRUE;
- uCount++;
- }
- }
- }
- if (uCount > 0)
- {
- sBDiskValStatus[MAX_VOLUME_COUNT] = TRUE;
- }
- }
- m_FileEntry.SubFiles.Clear();
- m_FileEntry.FileNamesBuffer.Clear();
- m_FileEntry.Current.Clear();
- uCount = 0;
- ULARGE_INTEGER uiTotalBytes, uiTotalFreeBytes;
- if (sBDiskValStatus[MAX_VOLUME_COUNT])
- {
- m_FileEntry.Current.mLevel = -2; //mark parent of volume -2-level
- char szVolume[8] = { 0 };
- for (int i = 0; i < MAX_VOLUME_COUNT; ++i)
- {
- if (sBDiskValStatus[i])
- {
- szVolume[0] = i + 'A';
- szVolume[1] = ':';
- szVolume[2] = '\0';
- CSimpleFileComponent volume;
- if (DiskInfo::GetDiskSpace(szVolume, uiTotalBytes, uiTotalFreeBytes))
- {
- volume.mFileSize = uiTotalFreeBytes.QuadPart;
- }
- volume.mLevel = 0;
- DWORD dwNameLen = strlen(szVolume);
- Append(m_FileEntry.FileNamesBuffer, (PBYTE)szVolume, dwNameLen, volume.mNameOffset);
- volume.mNameLength = dwNameLen;
- volume.mAttributes = 0;
- m_FileEntry.SubFiles.Append(&volume, 0, 1);
- uCount++;
- }
- }
- }
- DisplayFileEntities(&m_FileEntry);
- #endif // _MSC_VER
- return uCount;
- }
- ErrorCodeEnum ResourceWatcherFSM::GetCpuType(
- SpReqAnsContext<ResourceWatcherService_GetCpuType_Req,
- ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
- {
- ErrorCodeEnum ec = Error_Succeed;
- ec = Error_NotSupport;
- LogWarn(Severity_Middle, ec, 0, CSimpleStringA::Format("%s is not supported!", __FUNCTION__));
- if (ctx != NULL) {
- ctx->Answer(ec);
- }
- return ec;
- }
- void ResourceWatcherFSM::HardwareInfoTimer(void* pData)
- {
- #ifdef RVC_OS_LINUX
- GetSystemCPUStatus();
- GetSystemMemoryStatus();
- GetSystemDiskStatus();
- GetOperationDiskStatus();
- GetMainLinkStatus();
- GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, MAX_HARDWARE_CHECK_TIME * 2);
- #else
- if (mainDetectFlag > 0)
- {
- GetMainLinkStatus();
- }
- CSystemStaticInfo info;
- GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (info.strMachineType == "RVC.PAD")
- {
- GetBatteryStatus();
- }
- if (hardwareCheckFlag > 0)
- {
- GetSystemCPUStatus();
- GetSystemMemoryStatus();
- GetSystemDiskStatus();
- }
- GetNetStatus();
- GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, hardwareCheckTime);
- #endif // RVC_OS_LINUX
- }
- void ResourceWatcherFSM::LinkDetect(int detectType, const char* url, bool& status, uint& delay)
- {
- #ifdef RVC_OS_LINUX
- timeval begin, end;
- uint tInterval = 0;
- bool flag = false;
- string tUrl = url;
- string host = "http://";
- if (tUrl.find("http") == string::npos)
- {
- tUrl = host + tUrl;
- }
- char tmpUrl[1024] = { 0 };
- strcpy(tmpUrl, tUrl.c_str());
- Dbg("Check url:[%s].", url);
- gettimeofday(&begin, NULL);
- string msg;
- int curFlag = HttpProbe(tmpUrl, msg, 5);
- gettimeofday(&end, NULL);
- tInterval = (end.tv_sec - begin.tv_sec) * 1000 + (end.tv_usec - begin.tv_usec) / 1000;
- if (curFlag > 0 && curFlag < 400)
- {
- status = true;
- }
- else
- {
- status = false;
- }
- delay = tInterval;
- #else
- int flag = 0;
- DWORD start, finish;
- string tUrl = url;
- string host = "http://";
- if (tUrl.find("http") == string::npos)
- {
- tUrl = host + tUrl;
- }
- char tmpUrl[MAX_PATH] = { 0 };
- strcpy_s(tmpUrl, tUrl.c_str());
- start = timeGetTime();
- flag = http_probe(tmpUrl, 5000, 0, warnFlag);
- finish = timeGetTime();
- unsigned int tInterval = finish - start;
- if (flag == false)
- {
- status = false;
- }
- else
- {
- status = true;
- }
- delay = tInterval;
- #endif // RVC_OS_LINUX
- }
- ErrorCodeEnum ResourceWatcherFSM::BizLinkDetect(
- SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- ErrorCodeEnum ec = Error_Succeed;
- int detectType = ctx->Req.protocol;
- CSimpleStringA url = ctx->Req.bizLink;
- bool linkStatus = false;
- uint delay = 0;
- LinkDetect(detectType, url.GetData(), linkStatus, delay);
- ctx->Ans.bizLinkStatus = linkStatus;
- ctx->Ans.bizLinkDelayMS = delay;
- ctx->Ans.intParam = 0;
- #ifdef _MSC_VER
- CSimpleStringA warn;
- if (!linkStatus)
- {
- warn = CSimpleStringA::Format("BizLink disconnected[%s].", url.GetData());
- }
- else
- {
- warn = CSimpleStringA::Format("BizLink connected[%s], Delay time [%d]ms.", url.GetData(), delay);
- }
- LogWarn(Severity_Low, Error_Param, LOG_WARN_BIZLINK_CONNECT_CHECK, warn.GetData());
- #endif // _MSC_VER
- if (ctx != NULL) {
- ctx->Answer(ec);
- }
- return ec;
- }
- #ifdef _MSC_VER
- #define CNNTYPE_UNKONWN 0 //0:未知
- #define CNNTYPE_LAN 1 //网线已连接
- #define CNNTYPE_LAN_DISCONNECT 2 //网线未连接(行内PAD,本应连接网线的)
- #define CNNTYPE_DONGLE_CNTED 3 //外接卡托已连接(这种情况几乎没有)
- #define CNNTYPE_DONGLE_DISCONNECT 4 //外接卡托未连接(这种情况几乎没有)
- #define CNNTYPE_LTE_CNTED 5 //5:LTE设备,处于已连接状态
- #define CNNTYPE_LTE_DISCONNECT 6 //LTE设备,处于未连接状态
- #define CNNTYPE_MIFI_WIFI_SIM 7 //MIFI连接模式,WIFI已连接,SIM卡已连接
- #define CNNTYPE_MIFI_WIFI_CNTED 8 //MIFI连接模式,WIFI已连接,SIM卡未连接
- #define CNNTYPE_MIFI_WIFI_DISCONNECT 9 //MIFI连接模式,WIFI未连接
- #define CNNTYPE_WIFI_CONNECT 10 //WIFI已连接(非MIFI模式,手工连接等其他场景)
- #define CNNTYPE_NO_ANY_CONNECT 11 //无任何其他内容连接
- #endif // _MSC_VER
- ErrorCodeEnum ResourceWatcherFSM::CheckNetType(
- SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
- {
- #ifdef RVC_OS_LINUX
- ErrorCodeEnum ec = Error_Succeed;
- int netType = 0; //默认未知
- CSimpleStringA tmpVendor(""), tmpDevSN(""), tmpDLLVersion("");
- GetEntityBase()->GetFunction()->GetSysVar("FWBVendor", tmpVendor);
- GetEntityBase()->GetFunction()->GetSysVar("FWBDevSN", tmpDevSN);
- GetEntityBase()->GetFunction()->GetSysVar("FWBVersion", tmpDLLVersion);
- if (tmpDLLVersion.GetLength() < 2)
- tmpDLLVersion = "8.1";
- if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2)
- {
- Dbg("This is fwb device.");
- }
- else
- {
- int i = 0;
- int sockfd;
- struct ifconf ifconf;
- struct ifreq* ifreq;
- char buf[1024];
- //初始化ifconf
- ifconf.ifc_len = 1024;
- ifconf.ifc_buf = buf;
- if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
- {
- perror("socket error");
- exit(1);
- }
- //获取所有接口信息
- ioctl(sockfd, SIOCGIFCONF, &ifconf);
- //逐个获取Ip地址
- int size = ifconf.ifc_len / sizeof(struct ifreq);
- ifreq = (struct ifreq*)buf;
- string netName(ifreq->ifr_name);
- if (size == 1 && netName == "lo") //只有逻辑地址 -- 网线被拔出
- {
- netType = 1;
- }
- else
- {
- for (i = size; i > 0; i--)
- {
- string netName(ifreq->ifr_name); //有其他网卡 -- 有线
- if (netName != "lo")
- {
- netType = 2;
- }
- ifreq++;
- }
- }
- ctx->Ans.netType = netType;
- }
- if (ctx != NULL) {
- ctx->Answer(ec);
- }
- return ec;
- #else
- ErrorCodeEnum ec = Error_Succeed;
- int netType = 0; //默认未知
- CSystemStaticInfo info;
- GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (info.strMachineType.Compare("RVC.PAD") == 0) //PAD机型
- {
- CMbnImplHelper mbnHelper;
- ResetDongleInfos();
- const int nMBN = mbnHelper.EnumerateInterfaces();
- const int cnt = g_DongleInfos.GetCount();
- for (int i = 0; i < cnt; ++i) {
- if (g_DongleInfos[i].state == MBD_ACTIVATION_CONNECTED) {
- netType = 4; //移动网络
- }
- }
- if (netType == 0 && 1 == IsWifiConnected()) {
- netType = 3; //无线网络
- }
- if (netType == 0) {
- if (SP::Module::Net::CheckLANConnectStatus()) {
- netType = 2; //有线
- }
- else {
- netType = 1; //未连接
- }
- }
- }
- else //大机、低柜、卡库
- {
- CoInitialize(NULL);
- // 通过NLA接口获取网络状态
- IUnknown* pUnknown = NULL;
- BOOL bOnline = TRUE;//是否在线
- HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
- IID_IUnknown, (void**)&pUnknown);
- if (SUCCEEDED(Result))
- {
- INetworkListManager* pNetworkListManager = NULL;
- if (pUnknown)
- Result = pUnknown->QueryInterface(IID_INetworkListManager, (void
- **)&pNetworkListManager);
- if (SUCCEEDED(Result))
- {
- VARIANT_BOOL IsConnect = VARIANT_FALSE;
- if (pNetworkListManager)
- {
- //Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect); //检测互联网连接
- Result = pNetworkListManager->get_IsConnected(&IsConnect); //检测本地网络
- }
- if (SUCCEEDED(Result))
- {
- bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
- }
- }
- if (pNetworkListManager)
- pNetworkListManager->Release();
- }
- if (pUnknown)
- pUnknown->Release();
- if (bOnline == true)
- {
- netType = 2;
- }
- else
- {
- netType = 1;
- }
- }
- ctx->Ans.netType = netType;
- if (ctx != NULL) {
- ctx->Answer(ec);
- }
- return ec;
- #endif // RVC_OS_LINUX
- }
- #ifdef _MSC_VER
- void ResourceWatcherFSM::GetNetStatus()
- {
- ErrorCodeEnum ec = Error_Succeed;
- int netType = 0; //默认未知
- CSystemStaticInfo info;
- GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (info.strMachineType.Compare("RVC.PAD") == 0) //PAD机型
- {
- CMbnImplHelper mbnHelper;
- ResetDongleInfos();
- const int nMBN = mbnHelper.EnumerateInterfaces();
- const int cnt = g_DongleInfos.GetCount();
- for (int i = 0; i < cnt; ++i) {
- if (g_DongleInfos[i].state == MBD_ACTIVATION_CONNECTED) {
- netType = 4; //移动网络
- }
- }
- if (netType == 0 && 1 == IsWifiConnected()) {
- netType = 3; //无线网络
- }
- if (netType == 0) {
- if (SP::Module::Net::CheckLANConnectStatus()) {
- netType = 2; //有线
- }
- else {
- netType = 1; //未连接
- }
- }
- }
- else //大机、低柜、卡库
- {
- CoInitialize(NULL);
- // 通过NLA接口获取网络状态
- IUnknown* pUnknown = NULL;
- BOOL bOnline = TRUE;//是否在线
- HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
- IID_IUnknown, (void**)&pUnknown);
- if (SUCCEEDED(Result))
- {
- INetworkListManager* pNetworkListManager = NULL;
- if (pUnknown)
- Result = pUnknown->QueryInterface(IID_INetworkListManager, (void
- **)&pNetworkListManager);
- if (SUCCEEDED(Result))
- {
- VARIANT_BOOL IsConnect = VARIANT_FALSE;
- if (pNetworkListManager)
- {
- //Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect); //检测互联网连接
- Result = pNetworkListManager->get_IsConnected(&IsConnect); //检测本地网络
- }
- if (SUCCEEDED(Result))
- {
- bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
- }
- }
- if (pNetworkListManager)
- pNetworkListManager->Release();
- }
- if (pUnknown)
- pUnknown->Release();
- if (bOnline == true)
- {
- netType = 2;
- }
- else
- {
- netType = 1;
- }
- }
- NetStatus netStatus;
- netStatus.status = netType;
- if (netType != lastNetStatus)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("netStatus.status: %d.", netStatus.status);
- SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(NetStatus), SP_MSG_SIG_OF(NetStatus), netStatus);
- lastNetStatus = netType;
- }
- }
- #endif // _MSC_VER
- ErrorCodeEnum ResourceWatcherFSM::GetBizLinks(
- SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- ErrorCodeEnum ec = Error_Succeed;
- int filter = ctx->Req.filter; //后续过滤使用
- CAutoArray<CSimpleStringA> bizLinks;
- CAutoArray<CSimpleStringA> bizNames;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- CSimpleStringA mLink(""), adLink(""), tLink("");
- spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
- if (mLink.GetLength() != 0)
- {
- CSimpleStringA tName = CSimpleStringA("主站点");
- bizNames.Append(&tName, 0, 1);
- bizLinks.Append(&mLink, 0, 1);
- }
- spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrAd", adLink);
- if (adLink.GetLength() != 0)
- {
- CSimpleStringA tName = CSimpleStringA("广告站点");
- bizNames.Append(&tName, 0, 1);
- bizLinks.Append(&adLink, 0, 1);
- }
- int bizCnt = 0;
- CSimpleStringA getLink("");
- do
- {
- bizCnt++;
- getLink = CSimpleStringA("UserBizLink").Append(std::to_string(bizCnt).c_str());
- spCtSettingConfig->ReadConfigValue("Chromium", (LPCTSTR)getLink, tLink);
- if (tLink.GetLength() != 0)
- {
- CSimpleStringA tName = CSimpleStringA("业务站点").Append(std::to_string(bizCnt).c_str());
- bizNames.Append(&tName, 0, 1);
- bizLinks.Append(&tLink, 0, 1);
- }
- } while (tLink.GetLength() != 0);
- ctx->Ans.bizLinks = bizLinks;
- ctx->Ans.bizNames = bizNames;
- if (ctx != NULL) {
- ctx->Answer(ec);
- }
- return ec;
- }
- void ResourceWatcherFSM::GetMainLinkStatus()
- {
- ErrorCodeEnum errorCode = Error_Succeed;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- ErrorCodeEnum erroCode = Error_Unexpect;
- CSimpleStringA mLink("");
- erroCode = spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
- if (mLink.GetLength() == 0)
- {
- return;
- }
- MainLinkDetect mainDetect;
- const char* mainLink = mLink.GetData();
- bool curStatus = false;
- uint delay = 0;
- LinkDetect(0, mainLink, curStatus, delay);
- #ifdef RVC_OS_LINUX
- if (!curStatus)
- {
- Dbg("Main Link disconnected [%s].", mainLink);
- }
- mainDetect.mainLinkStatus = curStatus;
- mainDetect.reversed1 = 0;
- mainDetect.reversed2 = "";
- if (curStatus != lastLinkStatus || !curStatus)
- {
- SpSendBroadcast(GetEntityBase()->GetFunction(),
- SP_MSG_OF(MainLinkDetect), SP_MSG_SIG_OF(MainLinkDetect), mainDetect);
- lastLinkStatus = curStatus;
- }
- #else
- if (!curStatus)
- {
- std::string warn = "Main Link disconnected [" + std::string(mainLink) + "].";
- LogWarn(Severity_Middle, Error_Param, LOG_WARN_MAINLINK_CONNECT_FAILED, CSimpleStringA::Format("%s", warn.c_str()));
- }
- mainDetect.mainLinkStatus = curStatus;
- mainDetect.reversed1 = 0;
- mainDetect.reversed2 = "";
- SpSendBroadcast(GetEntityBase()->GetFunction(),
- SP_MSG_OF(MainLinkDetect), SP_MSG_SIG_OF(MainLinkDetect), mainDetect);
- #endif // RVC_OS_LINUX
- }
- #ifdef _MSC_VER
- void ResourceWatcherFSM::CalCulateFileInfo(LPCTSTR lpFilePath, PWIN32_FIND_DATA pWfdata)
- {
- m_VideoFiles.push(new TmpFileInfo(lpFilePath,
- &(pWfdata->ftLastWriteTime),
- pWfdata->nFileSizeHigh, pWfdata->nFileSizeLow));
- ULARGE_INTEGER uiTemp;
- uiTemp.HighPart = pWfdata->nFileSizeHigh;
- uiTemp.LowPart = pWfdata->nFileSizeLow;
- uiAllVideoFileSizeCal.QuadPart += uiTemp.QuadPart;
- if (uiMaxFileSize.QuadPart < uiTemp.QuadPart)
- {
- strcpy_s(szMaxSizeFilePath, lpFilePath);
- uiMaxFileSize.QuadPart = uiTemp.QuadPart;
- }
- SYSTEMTIME stUTC, stLocal;
- FileTimeToSystemTime(&(pWfdata->ftLastWriteTime), &stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- UINT uDate = stLocal.wYear * 10000 + stLocal.wMonth * 100 + stLocal.wDay;
- VideoDailyRecord[uDate]++;
- }
- BOOL ResourceWatcherFSM::CalCulateUploadFileAddition(ULARGE_INTEGER& uiBytesCal)
- {
- uiBytesCal.QuadPart = 0;
- BOOL bRet = FALSE;
- ErrorCodeEnum ec = Error_Unexpect;
- CSimpleStringA uploadVideoPath;
- ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
- if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
- if (ec == Error_Succeed)
- {
- CSimpleStringA filePath = uploadVideoPath + "\\*";
- ULARGE_INTEGER uliSpaceSize;
- uliSpaceSize.QuadPart = 0;
- int nFileCnt = ProcessFileSpaceCalculation(filePath, &uliSpaceSize);
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(szResult, (double)uliSpaceSize.QuadPart);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Result: Files(%d), Size(%s).", nFileCnt, szResult);
- uiBytesCal.QuadPart = uliSpaceSize.QuadPart;
- }
- return (ec == Error_Succeed);
- }
- int ResourceWatcherFSM::ProcessFileSpaceCalculation(LPCTSTR lpszPath, PULARGE_INTEGER puliSpaceBytes)
- {
- int fileCnt = 0;
- int fileLength = strlen(lpszPath);
- char* searchFilePath = new char[MAX_PATH];
- char* tempFilePath = new char[MAX_PATH];
- if (searchFilePath == NULL || tempFilePath == NULL)
- {
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- ZeroMemory(searchFilePath, MAX_PATH);
- ZeroMemory(tempFilePath, MAX_PATH);
- WIN32_FIND_DATA wfd;
- HANDLE hFind;
- hFind = FindFirstFile(lpszPath, &wfd);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FindFirstFile failed GLE = %u.", GetLastError());
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return 0;
- }
- do
- {
- if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (wfd.cFileName[0] != '.')
- {
- strcpy_s(tempFilePath, MAX_PATH, lpszPath);
- tempFilePath[fileLength - 1] = '\0';
- if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
- }
- else
- {
- strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
- strcat_s(tempFilePath, MAX_PATH, "\\*");
- fileCnt += ProcessFileSpaceCalculation((LPCTSTR)tempFilePath, puliSpaceBytes);
- }
- }
- }
- else
- {
- strcpy_s(searchFilePath, MAX_PATH, lpszPath);
- searchFilePath[fileLength - 1] = '\0';
- strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
- ULARGE_INTEGER uiTemp;
- uiTemp.HighPart = wfd.nFileSizeHigh;
- uiTemp.LowPart = wfd.nFileSizeLow;
- puliSpaceBytes->QuadPart += uiTemp.QuadPart;
- SYSTEMTIME stUTC, stLocal;
- FileTimeToSystemTime(&wfd.ftLastWriteTime, &stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- UINT uDate = stLocal.wYear * 10000 + stLocal.wMonth * 100 + stLocal.wDay;
- VideoDailyRecord[uDate]++;
- fileCnt++;
- }
- } while (FindNextFileA(hFind, &wfd));
- FindClose(hFind);
- if (searchFilePath) delete[] searchFilePath;
- if (tempFilePath) delete[] tempFilePath;
- return fileCnt;
- }
- int ResourceWatcherFSM::MonitorRSAMachineKeysDir()
- {
- LPCTSTR cszRSAKeysMonitor = "RSAKeysMonitor";
- LPCTSTR cszRSAKeyFiles = "RSAKeyFiles";
- LPCTSTR cszLostKeyFiles = "LostKeyFiles";
- CSmartPointer<IConfigInfo> spRunConfig;
- ErrorCodeEnum ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- int nRun_ExistedKeyCount = 0, nRun_LostKeyCount;
- CSimpleStringA strRun_RecentLostKeyName;
- int nRun_LostTimeStamp = 0;
- struct KeyFileElement {
- KeyFileElement() :fn(true) { ft.ftCreateTime = 0; }
- explicit KeyFileElement(LPCTSTR ftName, const ULONGLONG& filetime)
- :fn(ftName) {
- ft.ftCreateTime = filetime;
- }
- explicit KeyFileElement(LPCTSTR ftName, const DWORD& now)
- :fn(ftName) {
- ft.dwHappenTime = now; ft.dwReserved = 0;
- }
- CSimpleStringA fn;
- //ULONGLONG ft;
- typedef union _RELATE_TIME {
- struct {
- DWORD dwHappenTime;
- DWORD dwReserved;
- };
- ULONGLONG ftCreateTime;
- }RELATETIME;
- RELATETIME ft;
- bool operator <(const KeyFileElement& rhs) { return rhs.ft.ftCreateTime < ft.ftCreateTime; }
- bool operator == (const KeyFileElement& rhs) const { return rhs.fn == fn; }
- bool operator == (const KeyFileElement& rhs) { return rhs.fn == fn; }
- bool operator != (const KeyFileElement& rhs) const { return rhs.fn != fn; }
- bool operator != (const KeyFileElement& rhs) { return rhs.fn != fn; }
- };
- vector<KeyFileElement> vtHistoryKeys;
- vector<KeyFileElement> vtLostKeys;
- spRunConfig->ReadConfigValueInt(cszRSAKeysMonitor, "ExistedKeyFileCount", nRun_ExistedKeyCount);
- spRunConfig->ReadConfigValueInt(cszRSAKeysMonitor, "LostKeyFileCount", nRun_LostKeyCount);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There are %d file(s) existed last runtime.", nRun_ExistedKeyCount);
- for (int i = 0; i < nRun_ExistedKeyCount; ++i)
- {
- CSimpleStringA strKeyDescript;
- spRunConfig->ReadConfigValue(cszRSAKeyFiles, CSimpleStringA::Format("%d", i + 1), strKeyDescript);
- CAutoArray<CSimpleStringA> strContent = strKeyDescript.Split(',');
- if (strContent.GetCount() == 2)
- {
- ULONGLONG ulCreateTime;
- sscanf_s(strContent[1], "%I64u", &ulCreateTime);
- vtHistoryKeys.push_back(KeyFileElement(strContent[0], ulCreateTime));
- }
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("There are %d file(s) lost in history record", nRun_LostKeyCount);
- for (int i = 0; i < nRun_LostKeyCount; ++i)
- {
- CSimpleStringA strKeyDescript;
- spRunConfig->ReadConfigValue(cszLostKeyFiles, CSimpleStringA::Format("%d", i + 1), strKeyDescript);
- CAutoArray<CSimpleStringA> strContent = strKeyDescript.Split(',');
- if (strContent.GetCount() >= 2)
- {
- DWORD dwLostTime;
- sscanf_s(strContent[1], "0x%08X", &dwLostTime);
- vtLostKeys.push_back(KeyFileElement(strContent[0], dwLostTime));
- if (dwLostTime == (DWORD)-1)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AlwaysPrint: \"%s\" lost(deleted) when RVC was offline", (LPCTSTR)strContent[0]);
- if (strContent.GetCount() == 3)
- {
- sscanf_s(strContent[2], "0x%08X", &dwLostTime);
- SYSTEMTIME stLostTime = CSmallDateTime(dwLostTime).ToSystemTime();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("detected above lost when RVC boot at %04d-%02d-%02d %02d:%02d:%02d",
- stLostTime.wYear, stLostTime.wMonth, stLostTime.wDay,
- stLostTime.wHour, stLostTime.wMinute, stLostTime.wSecond);
- }
- }
- else
- {
- SYSTEMTIME stLostTime = CSmallDateTime(dwLostTime).ToSystemTime();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AlwaysPrint: \"%s\" lost(deleted) at %04d-%02d-%02d %02d:%02d:%02d",
- (LPCTSTR)strContent[0],
- stLostTime.wYear, stLostTime.wMonth, stLostTime.wDay,
- stLostTime.wHour, stLostTime.wMinute, stLostTime.wSecond);
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AlwaysPrint: %s", (LPCTSTR)strKeyDescript);
- }
- }
- int nHistoryKeyCount = (int)vtHistoryKeys.size();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Record VS VectorSize(%d VS %d)", nRun_ExistedKeyCount, nHistoryKeyCount);
- //C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
- char szMachineKeysPath[MAX_PATH], szTemp[MAX_PATH];
- DWORD dwError = 0;
- ZeroMemory(szMachineKeysPath, MAX_PATH);
- ZeroMemory(szTemp, MAX_PATH);
- strcpy_s(szMachineKeysPath, "C:\\ProgramData\\Microsoft\\Crypto\\RSA\\MachineKeys");
- if (SHGetSpecialFolderPath(NULL, szTemp, CSIDL_COMMON_APPDATA, FALSE))
- {
- strcat_s(szTemp, "\\Microsoft\\Crypto\\RSA\\MachineKeys");
- strcpy_s(szMachineKeysPath, szTemp);
- }
- else
- {
- dwError = GetLastError();
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("SHGetSpecialFolderPath failed, GLE=%u", dwError);
- ZeroMemory(szTemp, MAX_PATH);
- if (GetSystemDirectory(szTemp, MAX_PATH))
- {
- szMachineKeysPath[0] = szTemp[0];
- }
- else
- {
- dwError = GetLastError();
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDirectory failed, GLE=%u", dwError);
- }
- }
- if (!ExistsDirA(szMachineKeysPath))
- {
- LogWarn(Severity_Middle, Error_NoTarget, 0,
- CSimpleStringA::Format("Directory(%s) is not existed !", szMachineKeysPath));
- return -1;
- }
- vector<KeyFileElement> vtCurrentKeys;
- CSimpleStringA strKeyFileSuffix(szMachineKeysPath);
- strKeyFileSuffix += "\\*";
- WIN32_FIND_DATA wfd;
- HANDLE hFind;
- hFind = FindFirstFile(strKeyFileSuffix, &wfd);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FindFirstFile(%s) failed GLE = %u.", (LPCTSTR)strKeyFileSuffix, GetLastError());
- return -2;
- }
- ULARGE_INTEGER uiTime;
- do
- {
- if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
- {
- uiTime.HighPart = wfd.ftCreationTime.dwHighDateTime;
- uiTime.LowPart = wfd.ftCreationTime.dwLowDateTime;
- vtCurrentKeys.push_back(KeyFileElement(wfd.cFileName, uiTime.QuadPart));
- }
- } while (FindNextFileA(hFind, &wfd));
- FindClose(hFind);
- int nCurKeyCount = (int)vtCurrentKeys.size();
- if (nCurKeyCount)
- sort(vtCurrentKeys.begin(), vtCurrentKeys.end());
- char szFormat[128];
- int shown = 0;
- const int max_shown = 3;
- for (vector<KeyFileElement>::const_iterator cit = vtCurrentKeys.cbegin();
- cit != vtCurrentKeys.cend(); ++cit)
- {
- GetTimeString(szFormat, 128, (PFILETIME) & (cit->ft.ftCreateTime));
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{\"%s\" - CreateTime: %s}", (LPCTSTR)cit->fn, szFormat);
- if (++shown >= max_shown) break; //Print the front three key files
- }
- int lackCount = 0;
- for (vector<KeyFileElement>::iterator it = vtHistoryKeys.begin();
- it != vtHistoryKeys.end(); ++it)
- {
- if (find(vtCurrentKeys.begin(), vtCurrentKeys.end(), *it) == vtCurrentKeys.end())
- {
- lackCount++;
- if (find(vtLostKeys.begin(), vtLostKeys.end(), *it) == vtLostKeys.end())
- {
- LogEvent(Severity_High, LOG_EVT_RSAKEY_LOST_OFFLINE,
- CSimpleStringA::Format("File{\"%s\"} was removed offline !", (LPCTSTR)it->fn));
- //TODO: USN Journal, found out when it lost
- spRunConfig->WriteConfigValueInt(cszRSAKeysMonitor, "LostKeyFileCount", ++nRun_LostKeyCount);
- CSimpleStringA strKeyDescript(it->fn);
- strKeyDescript += CSimpleStringA::Format(",0x%08X", (DWORD)(-1));
- // Although lost offline, but its responsible to record the discovery time
- // -Josephus@2017619 9:17:11
- strKeyDescript += CSimpleStringA::Format(",0x%08X", (DWORD)CSmallDateTime::GetNow());
- spRunConfig->WriteConfigValue(cszLostKeyFiles, CSimpleStringA::Format("%d",
- nRun_LostKeyCount), strKeyDescript);
- }
- }
- }
- if (lackCount > 0 || nCurKeyCount != nHistoryKeyCount)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Update Runcfg about %s, Reason(new lost? %d, cur(%d) vs history(%d)",
- cszRSAKeysMonitor, lackCount, nCurKeyCount, nHistoryKeyCount);
- spRunConfig->WriteConfigValueInt(cszRSAKeysMonitor, "ExistedKeyFileCount", nCurKeyCount);
- int i = 0;
- for (vector<KeyFileElement>::const_iterator cit = vtCurrentKeys.cbegin();
- cit != vtCurrentKeys.cend(); ++cit, ++i)
- {
- CSimpleStringA strKeyDescript(cit->fn);
- strKeyDescript += CSimpleStringA::Format(",%I64u", cit->ft);
- spRunConfig->WriteConfigValue(cszRSAKeyFiles, CSimpleStringA::Format("%d", i + 1), strKeyDescript);
- }
- if (i < nRun_ExistedKeyCount)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Clear from %d to %d", i + 1, nRun_ExistedKeyCount);
- do {
- spRunConfig->WriteConfigValue(cszRSAKeyFiles, CSimpleStringA::Format("%d", i + 1), "");
- } while (++i < nRun_ExistedKeyCount);
- }
- }
- HANDLE hFile = CreateFileA(
- szMachineKeysPath,
- FILE_LIST_DIRECTORY,
- FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
- if (hFile == INVALID_HANDLE_VALUE)
- {
- dwError = GetLastError();
- LogWarn(Severity_Middle, Error_Unexpect, dwError,
- CSimpleStringA::Format("CreateFileA(%s) failed, GLE=%u", szMachineKeysPath, dwError));
- return -3;
- }
- const DWORD INFO_BUFFER_SIZE = 2048;
- char chInfoBuf[INFO_BUFFER_SIZE];
- DWORD dwBufSize = INFO_BUFFER_SIZE;
- PFILE_NOTIFY_INFORMATION pFNotifyInfo = (PFILE_NOTIFY_INFORMATION)chInfoBuf;
- DWORD dwRetBytes;
- vtCurrentKeys.clear();
- vtHistoryKeys.clear();
- vtLostKeys.clear();
- do
- {
- ZeroMemory(chInfoBuf, INFO_BUFFER_SIZE);
- BOOL bRet = ReadDirectoryChangesW(hFile
- , &chInfoBuf
- , sizeof(chInfoBuf)
- , FALSE
- , FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_DIR_NAME
- , &dwRetBytes
- , NULL
- , NULL
- );
- if (!bRet)
- {
- dwError = GetLastError();
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ReadDirectoryChangesW failed, GLE=%u", dwError);
- if (dwError == ERROR_INVALID_FUNCTION)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The network redirector or the target file system does not support this operation !");
- }
- else if (dwError == ERROR_NOTIFY_ENUM_DIR)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The buffer overflows !");
- }
- continue;
- }
- CSimpleStringW strFileNameW(pFNotifyInfo->FileName, pFNotifyInfo->FileNameLength);
- CSimpleStringA strFileName = CSimpleStringW2A(strFileNameW);
- switch (pFNotifyInfo->Action)
- {
- case FILE_ACTION_ADDED: //0x00000001
- {
- LogEvent(Severity_Low, LOG_EVT_RSAKEY_ADD_RIGHTNOW,
- CSimpleStringA::Format("A file{\"%s\"} is added !", (LPCTSTR)strFileName));
- }
- break;
- case FILE_ACTION_REMOVED: //0x00000002
- {
- spRunConfig->WriteConfigValueInt(cszRSAKeysMonitor, "LostKeyFileCount", ++nRun_LostKeyCount);
- LogEvent(Severity_High, LOG_EVT_RSAKEY_LOST_RIGHTNOW,
- CSimpleStringA::Format("File{\"%s\"} is removed !", (LPCTSTR)strFileName));
- CSimpleStringA strKeyDescript(strFileName);
- strKeyDescript += CSimpleStringA::Format(",0x%08X", (DWORD)CSmallDateTime::GetNow());
- spRunConfig->WriteConfigValue(cszLostKeyFiles, CSimpleStringA::Format("%d",
- nRun_LostKeyCount), strKeyDescript);
- }
- break;
- case FILE_ACTION_MODIFIED: //0x00000003
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The file was modified: %s", (LPCTSTR)strFileName);
- break;
- case FILE_ACTION_RENAMED_OLD_NAME: //0x00000004
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There is a file was renamed and this is the old name: %s", (LPCTSTR)strFileName);
- break;
- case FILE_ACTION_RENAMED_NEW_NAME: //0x00000005
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There is a file was renamed and this is the new name: %s", (LPCTSTR)strFileName);
- break;
- }
- } while (Sleep(1000), TRUE);
- CloseHandle(hFile);
- hFile = NULL;
- return 0;
- }
- #endif // _MSC_VER
- DWORD ResourceWatcherFSM::ProcessFileOperation(
- const SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
- ResourceWatcherService_OperateFile_Ans>::Pointer& ctx)
- {
- if (ctx == NULL) return 0;
- ResourceWatcherService_OperateFile_Req& req = ctx->Req;
- ResourceWatcherService_OperateFile_Ans& ans = ctx->Ans;
- {
- ans.header = "";
- ans.attachment1 = 0;
- ans.attachment2 = "";
- ans.fileSize = 0ULL;
- ans.ftCreate = 0ULL;
- ans.ftModified = 0ULL;
- ans.ftAccess = 0ULL;
- ans.fileAttribute = 0U;
- ans.count = 0;
- }
- CSimpleStringA strCurrent(true);
- size_t nCurLen = req.current.GetLength();
- if (!req.current.IsNullOrEmpty())
- {
- CSimpleStringA strTemp = req.current.Trim();
- size_t len = req.current.GetLength();
- while (len > 0 && (strTemp[len - 1] == '\\' || strTemp[len - 1] == '/'))
- {
- strTemp[len - 1] = '\0';
- len--;
- }
- if (len > 0)
- {
- strCurrent = strTemp.Trim();
- nCurLen = strCurrent.GetLength();
- LOG_ASSERT(len == nCurLen);
- }
- }
- BOOL bCurNull = strCurrent.IsNullOrEmpty();
- if (!bCurNull)
- {
- int nRes = FilterFilePathAhead(strCurrent, req.mode);
- if (nRes != 0)
- {
- ans.result = OPT_FILE_RES_FAILED;
- CSimpleStringA strTxt;
- switch (nRes)
- {
- case -1:
- case -2:
- strTxt = "文件路径参数错误。";
- break;
- case -3:
- strTxt = "终端指定磁盘不存在。";
- break;
- case 1:
- strTxt = "操作非法:不允许删除盘符。";
- break;
- case 2:
- strTxt = "请求的操作无权限。";
- break;
- default:
- strTxt = "操作失败,原因未知。";
- break;
- }
- ans.attachment1 = strTxt.GetLength();
- ans.attachment2 = strTxt;
- ctx->Answer(Error_Succeed);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Try to (option:%d) [%s] failed (%d): %s", req.mode, (LPCTSTR)strCurrent, nRes, (LPCTSTR)strTxt);
- return nRes;
- }
- }
- FileType type = FT_Unknown;
- IsPathExisted(strCurrent, type);
- int count = 0;
- ans.count = 0;
- ans.result = OPT_FILE_RES_INVALID;
- bool bNeedToRefleshHeader = false;
- bool bNeedToSetCtxEntities = false;
- bool bNeedToRefleshEntity = false;
- int updateLevel = 0;
- switch (ctx->Req.mode)
- {
- case OPT_FILE_CMD_SPREAD: //0
- {
- DWORD dwRes = 0;
- if (!bCurNull && (type == FT_Unknown || type == FT_File))
- {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = GetErrorMessage(ans.attachment2, "请求的文件不存在或类型不正确。");
- break;
- }
- DWORD dwFilterAttributes = (DWORD)(ctx->Req.filter1);
- if (bCurNull)
- {
- #if defined(_MSC_VER)
- dwRes = InitialVolumes();
- #else
- if (!InitialFileEntity("/", dwRes, dwFilterAttributes)) {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = GetErrorMessage(ans.attachment2, "获取根目录列表失败");
- Dbg("Initial File Entity failed: %s", ans.attachment2.GetData());
- break;
- }
- #endif //_MSC_VER
- }
- else if (!InitialFileEntity(strCurrent, dwRes, dwFilterAttributes))
- {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = GetErrorMessage(ans.attachment2, "获取文件列表失败");
- break;
- }
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("%d VS %d", dwRes, m_FileEntry.SubFiles.GetCount());
- LOG_ASSERT(dwRes == m_FileEntry.SubFiles.GetCount());
- count = dwRes;
- ans.result = OPT_FILE_RES_SUCCESS;
- bNeedToSetCtxEntities = true;
- bNeedToRefleshHeader = true;
- }
- break;
- case OPT_FILE_CMD_EXECUTE://1
- {
- if (type != FT_File)
- {
- ans.result = OPT_FILE_RES_INVALID;
- ans.attachment2 = "非可打开或执行的文件类型(目录或其他)";
- ans.attachment1 = ans.attachment2.GetLength();
- break;
- }
- LPCTSTR lpParam = NULL;
- if (req.attachment1 > 0 && req.attachment2.GetLength() > 0)
- lpParam = req.attachment2;
- #ifdef RVC_OS_LINUX
- const DWORD dwRes = ExecuteFile(strCurrent, lpParam);
- ans.result = dwRes ? OPT_FILE_RES_FAILED : OPT_FILE_RES_SUCCESS;
- if (dwRes) {
- ans.attachment2 = "不支持该操作";
- ans.attachment1 = ans.attachment2.GetLength();
- ans.result = OPT_FILE_RES_NOT_SUPPORT;
- }
- #else
- DWORD dwRes = ExecuteFile(strCurrent, lpParam);
- if (!dwRes)
- {
- ans.result = OPT_FILE_RES_SUCCESS;
- }
- else
- {
- ans.result = OPT_FILE_RES_FAILED;
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2, "执行文件操作失败。");
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("ExecuteFile failed: %s", (LPCTSTR)ans.attachment2);
- }
- }
- #endif // RVC_OS_LINUX
- }
- break;
- case OPT_FILE_CMD_DELETE: //2
- case OPT_FILE_CMD_CLEAR: //3
- {
- #ifdef _MSC_VER
- if (ctx->Req.mode == OPT_FILE_CMD_DELETE)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("Delete flag.");
- }
- #endif // _MSC_VER
- if (type == FT_Unknown)
- {
- ans.result = OPT_FILE_RES_INVALID;
- ans.attachment2 = "所指定的文件不存在。";
- ans.attachment1 = ans.attachment2.GetLength();
- break;
- }
- bool bClear = !!(ctx->Req.mode == OPT_FILE_CMD_CLEAR);
- #ifdef _MSC_VER
- if (type == FT_Volume)
- {
- if (!bClear)
- {
- ans.result = OPT_FILE_RES_INVALID;
- ans.attachment1 = strlen("该操作对卷类型的文件无效。");
- ans.attachment2 = "该操作对卷类型的文件无效。";
- }
- else
- {
- if (ClearDirRecursiveEx(strCurrent))
- {
- ans.result = OPT_FILE_RES_SUCCESS;
- bNeedToRefleshEntity = true;
- }
- else
- {
- ans.attachment1 = strlen("清空卷操作执行失败。");
- ans.attachment2 = "清空卷操作执行失败。";
- ans.result = OPT_FILE_RES_FAILED;
- }
- }
- break;
- }
- #endif // _MSC_VER
- if ((type == FT_Directory && ((!bClear && !RemoveDirRecursiveA(strCurrent))
- || (bClear && !ClearDirRecursiveA(strCurrent))))
- || (type == FT_File && !bClear && !RemoveFileA(strCurrent)))
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2,
- ((!bClear) ? "删除操作执行失败。" : "清空操作执行失败。"));
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("Delete(%d) or clear file failed: %s", !bClear, ans.attachment2.GetData());
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- if (type == FT_File && bClear)
- {//文件内容清理
- //simple implement
- FILE* stream;
- SetLastError(0);
- if ((stream = fopen(strCurrent, "w+")) == NULL)
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- else
- {
- if (fclose(stream))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("fclose(%s) failed", (LPCTSTR)strCurrent);
- ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- }
- }
- ans.result = OPT_FILE_RES_SUCCESS;
- bNeedToRefleshEntity = true;
- if ((!bClear && type != FT_File) || (bClear && type == FT_File)) updateLevel = 1;
- }
- break;
- case OPT_FILE_CMD_CREATE: //4
- {
- if (type != FT_Unknown)
- {
- if ((type == FT_Directory && (req.attribute & 0x10))
- || (type == FT_File && !(req.attribute & 0x10))
- || type == FT_Volume)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_USER)("Existed file occurs create(%d) ?", type);
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("目录或文件已存在。");
- ans.attachment2 = "目录或文件已存在。";
- break;
- }
- }
- BOOL bRet = FALSE;
- int depth = GetPathDepth(strCurrent);
- if (depth <= 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("Invalid file path(%s)", (LPCTSTR)strCurrent);
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("非法文件路径或名称。");
- ans.attachment2 = "非法文件路径或名称。";
- break;
- }
- if (req.attribute & 0x10)
- {
- bRet = CreateDirA(strCurrent, TRUE);
- if (!bRet)
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2, "新建文件夹失败。");
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- }
- else
- {
- #ifdef RVC_OS_LINUX
- ans.result = OPT_FILE_RES_NOT_SUPPORT;
- ans.attachment2 = "不支持操作";
- ans.attachment1 = ans.attachment2.GetLength();
- break;
- #else
- if (depth == 1/*根目录下创建文件*/ || CreateParentDirA(strCurrent, TRUE))
- {
- DWORD dwNewAttr = FILE_ATTRIBUTE_NORMAL/* | req.attribute*/;
- HANDLE hNewFile = CreateFileA(strCurrent, GENERIC_WRITE,
- 0, NULL, CREATE_NEW, dwNewAttr, NULL);
- if (hNewFile == INVALID_HANDLE_VALUE)
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2, "创建文件失败。");
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- if (req.content.GetLength() >= 0)
- {
- DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
- DWORD dwByteWritten = 0;
- DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
- LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
- BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
- dwBytesToWrite, &dwByteWritten, NULL);
- UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
- if (!bRes || dwByteWritten != dwBytesToWrite)
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2,
- !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
- CloseHandle(hNewFile);
- DeleteFileA(strCurrent);
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- }
- CloseHandle(hNewFile);
- }
- else
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2, "创建目标文件所在目录失败。");
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- #endif // RVC_OS_LINUX
- }
- ans.result = OPT_FILE_RES_SUCCESS;
- bNeedToRefleshEntity = true;
- updateLevel = 1;
- }
- break;
- case OPT_FILE_CMD_APPEND: //5
- {
- #ifdef RVC_OS_LINUX
- ans.result = OPT_FILE_RES_NOT_SUPPORT;
- ans.attachment2 = "不支持操作";
- ans.attachment1 = ans.attachment2.GetLength();
- #else
- if (type != FT_File)
- {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("目标文件不存在或非文件类型。");
- ans.attachment2 = "目标文件不存在或非文件类型。";
- break;
- }
- else if (req.content.GetLength() <= 0)
- {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("写入的文件内容不存在。");
- ans.attachment2 = "写入的文件内容不存在。";
- break;
- }
- DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
- DWORD dwByteWritten = 0;
- HANDLE hNewFile = CreateFileA(strCurrent, FILE_APPEND_DATA,
- FILE_SHARE_READ, NULL, /*OPEN_EXISTING*/OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
- if (hNewFile == INVALID_HANDLE_VALUE)
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2, "打开文件失败。");
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
- LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
- BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
- dwBytesToWrite, &dwByteWritten, NULL);
- UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
- if (!bRes || dwByteWritten != dwBytesToWrite)
- {
- ans.attachment1 = GetErrorMessage(ans.attachment2,
- !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
- ans.result = OPT_FILE_RES_FAILED;
- CloseHandle(hNewFile);
- DeleteFileA(strCurrent);
- ans.result = OPT_FILE_RES_FAILED;
- break;
- }
- CloseHandle(hNewFile);
- ans.result = OPT_FILE_RES_SUCCESS;
- bNeedToRefleshEntity = true;
- updateLevel = 1;
- #endif // RVC_OS_LINUX
- }
- break;
- case OPT_FILE_CMD_RENAME: //6
- {
- #ifdef RVC_OS_LINUX
- ans.result = OPT_FILE_RES_NOT_SUPPORT;
- ans.attachment2 = "不支持操作";
- ans.attachment1 = ans.attachment2.GetLength();
- #else
- if (type == FT_Unknown || type == FT_Volume)
- {
- ans.result = OPT_FILE_RES_FAILED;
- if (type == FT_Unknown)
- {
- ans.attachment1 = strlen("目标文件不存在。");
- ans.attachment2 = "目标文件不存在。";
- }
- else
- {
- ans.attachment1 = strlen("文件类型(卷)不支持当前操作。");
- ans.attachment2 = "文件类型(卷)不支持当前操作。";
- }
- break;
- }
- req.content = req.content.Trim();
- if (req.content.GetLength() <= 0)
- {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("传入新文件名参数为空。");
- ans.attachment2 = "传入新文件名参数为空。";
- break;
- }
- if (strchr(req.content, '\\') || strchr(req.content, '/'))
- {
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("新文件名参数无效。");
- ans.attachment2 = "新文件名参数无效。";
- break;
- }
- const size_t st_len = stCurLength + req.content.GetLength();
- char* path = new char[st_len];
- ZeroMemory(path, st_len);
- int res = 0;
- if (path == NULL)
- {
- LogWarn(Severity_Middle, Error_Resource, 0, "alloc path memory failed");
- }
- else
- {
- int dir_len = 0;
- CSimpleStringA strNewName = req.content;
- if ((dir_len = GetDirSplitPath(strCurrent, 1, path, st_len)) > 0)
- {
- if (!req.attribute && type == FT_File)
- {
- char tmp[MAX_PATH] = { 0 };
- strcpy_s(tmp, strCurrent.GetData() + dir_len + 1);
- char* pos = strrchr(tmp, '.');
- if (pos) { strNewName += pos; }
- }
- strcat_s(path, st_len, "\\");
- strcat_s(path, st_len, strNewName);
- res = rename(strCurrent, path);
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("GetDirSplitPath failed: %s vs %s", (LPCTSTR)strCurrent, path);
- }
- delete[] path;
- path = NULL;
- }
- if (res)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("rename failed: %d", errno);
- ans.result = OPT_FILE_RES_FAILED;
- ans.attachment1 = strlen("重命名操作失败。");
- ans.attachment2 = "重命名操作失败。";
- break;
- }
- ans.result = OPT_FILE_RES_SUCCESS;
- bNeedToRefleshEntity = true;
- updateLevel = 1;
- #endif // RVC_OS_LINUX
- }
- break;
- default:
- {
- LogWarn(Severity_Low, Error_Unexpect, 0,
- CSimpleStringA::Format("Unexpected file operation command : %d", ctx->Req.mode));
- CSimpleStringA strTip = CSimpleStringA::Format("无法识别的操作指令(mode: %d)。", ctx->Req.mode);
- ans.attachment1 = strTip.GetLength();
- ans.attachment2 = strTip;
- }
- break;
- }
- if (ans.result == OPT_FILE_RES_SUCCESS)
- {
- if (bNeedToSetCtxEntities || bNeedToRefleshEntity)
- {
- bool bReInit = true;
- if (bNeedToRefleshEntity)
- {
- DWORD dwCnt = 0;
- CSimpleStringA strHeader = strCurrent;
- if (updateLevel != 0)
- {
- char* pPath = new char[nCurLen + 1];
- if (pPath == NULL) bReInit = false;
- else
- {
- UINT uRes = GetDirSplitPath(strHeader, updateLevel, pPath, nCurLen + 1);
- if (uRes == 0) bReInit = false;
- strHeader = pPath;
- delete[] pPath;
- pPath = NULL;
- }
- }
- if (bReInit)
- {
- bReInit = !!InitialFileEntity(strHeader, dwCnt);
- }
- bNeedToRefleshHeader = true;
- }
- if (bReInit)
- {
- ConveyFileEntityToContext(ctx, bNeedToRefleshHeader);
- }
- }
- }
- ctx->Answer(Error_Succeed);
- return (ans.result);
- }
- DWORD ResourceWatcherFSM::ExecuteFile(LPCTSTR lpszFilePath, LPCTSTR lpParam)
- {
- DWORD dwRes = 0;
- #ifdef _MSC_VER
- SHELLEXECUTEINFOA shell;
- memset(&shell, 0, sizeof(SHELLEXECUTEINFOA));
- shell.cbSize = sizeof(SHELLEXECUTEINFOA);
- shell.lpFile = lpszFilePath;
- shell.lpParameters = lpParam;
- shell.fMask = SEE_MASK_INVOKEIDLIST;
- shell.lpVerb = NULL;
- shell.nShow = SW_SHOWDEFAULT;
- if (!ShellExecuteExA(&shell))
- {
- dwRes = GetLastError();
- int nRes = (int)shell.hInstApp;
- Dbg("GLE=%u, InstApp=%d", dwRes, nRes);
- switch (dwRes) {
- case ERROR_NO_ACE_CONDITION:
- LogWarn(Severity_Middle, Error_MethodNotFound, dwRes,
- CSimpleStringA::Format("Target file(%s) association not available !", lpszFilePath));
- break;
- case ERROR_ACCESS_DENIED:
- LogWarn(Severity_Middle, Error_NoPrivilege, dwRes,
- CSimpleStringA::Format("Target file(%s) not privilege !", lpszFilePath));
- break;
- case ERROR_PATH_NOT_FOUND:
- case ERROR_FILE_NOT_FOUND:
- LogWarn(Severity_Middle, Error_NotExist, dwRes,
- CSimpleStringA::Format("Target file(%s) not existed !", lpszFilePath));
- break;
- case ERROR_DLL_NOT_FOUND:
- LogWarn(Severity_Middle, Error_NotExist, dwRes,
- CSimpleStringA::Format("One of library file for Target(%s) not existed !", lpszFilePath));
- break;
- case ERROR_NOT_ENOUGH_MEMORY:
- LogWarn(Severity_Middle, Error_Resource, dwRes,
- CSimpleStringA::Format("Not enough memory for Target(%s) to perform !", lpszFilePath));
- break;
- case ERROR_SHARING_VIOLATION:
- LogWarn(Severity_Middle, Error_Overflow, dwRes,
- CSimpleStringA::Format("Violation occurred for Target(%s) to share !", lpszFilePath));
- break;
- default:
- LogWarn(Severity_Middle, Error_Unexpect, dwRes,
- CSimpleStringA::Format("Unpected condtion for Target(%s) to execute(%u) !"
- , lpszFilePath, dwRes));
- break;
- }
- }
- #else
- dwRes = 1;
- #endif //_MSC_VER
- return dwRes;
- }
- BOOL ResourceWatcherFSM::ConveyFileEntityToContext(
- const SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
- ResourceWatcherService_OperateFile_Ans>::Pointer & ctx
- , BOOL bRefleshHeader /*= FALSE*/, DWORD dwFilterAttributes)
- {
- if (ctx == NULL) return FALSE;
- #ifdef _MSC_VER
- ULARGE_INTEGER ilOffsetSize;
- ilOffsetSize.QuadPart = 0;
- const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
- DWORD dwInheritForbidAttrs = 0UL;
- if (bRefleshHeader) {
- if (m_FileEntry.Current.mNameLength != 0) {
- ilOffsetSize.LowPart = m_FileEntry.Current.mNameOffset;
- ilOffsetSize.HighPart = m_FileEntry.Current.mNameLength;
- GetSubFileName(m_FileEntry.FileNamesBuffer,
- dwBufSize, ctx->Ans.header, &ilOffsetSize);
- ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
- ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
- ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
- ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
- ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
- if (!ctx->Ans.header.IsNullOrEmpty() && ctx->Ans.header.GetLength() > 0) {
- if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
- dwInheritForbidAttrs |= BS_DENY_DELETE;
- Dbg("header-forbit:%s", ctx->Ans.header.GetData());
- }
- }
- }
- }
- int count = m_FileEntry.SubFiles.GetCount();
- int minusCount = 0;
- for (int i = 0; i < count; ++i)
- if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
- minusCount++;
- count = count - minusCount;
- ctx->Ans.count = count;
- if (count > 0) {
- if (count >= MAX_SUBFILES_COUNT) {
- Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
- std::vector<CSimpleFileShell> vtFileShells;
- for (int i = 0; i < count; ++i) {
- CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
- vtFileShells.push_back(item);
- }
- sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
- char szFormat[128] = { 0 };
- count = MAX_SUBFILES_COUNT;
- ctx->Ans.count = count;
- ctx->Ans.fileAttributes.Init(count);
- ctx->Ans.fileNames.Init(count);
- ctx->Ans.ftCreates.Init(count);
- ctx->Ans.ftModifieds.Init(count);
- ctx->Ans.ftAccesses.Init(count);
- ctx->Ans.fileSizes.Init(count);
- ctx->Ans.forbidAttributes.Init(count);
- ctx->Ans.reserved1.Init(count);
- ctx->Ans.reserved2.Init(count);
- for (int i = 0; i < count; ++i) {
- CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
- ilOffsetSize.LowPart = component->mNameOffset;
- ilOffsetSize.HighPart = component->mNameLength;
- if (component->mAttributes & dwFilterAttributes) {
- CSimpleStringA strFileName;
- GetSubFileName(m_FileEntry.FileNamesBuffer,
- dwBufSize, strFileName, &ilOffsetSize);
- Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
- continue;
- }
- ctx->Ans.reserved1[i] = 0;
- ctx->Ans.reserved2[i] = "";
- ctx->Ans.fileAttributes[i] = component->mAttributes;
- ctx->Ans.ftCreates[i] = component->mftCreate;
- ctx->Ans.ftModifieds[i] = component->mftModified;
- ctx->Ans.ftAccesses[i] = component->mftAccess;
- ctx->Ans.fileSizes[i] = component->mFileSize;
- //TODO: Need to judge whether need to calculate size of directory.
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
- Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
- ctx->Ans.forbidAttributes[i] = 0;
- if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
- CSimpleStringA csFilePath;
- GetFullFilePath(&m_FileEntry, i, csFilePath);
- if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
- }
- }
- }
- vtFileShells.clear();
- } else {
- ctx->Ans.fileAttributes.Init(count);
- ctx->Ans.fileNames.Init(count);
- ctx->Ans.ftCreates.Init(count);
- ctx->Ans.ftModifieds.Init(count);
- ctx->Ans.ftAccesses.Init(count);
- ctx->Ans.fileSizes.Init(count);
- ctx->Ans.forbidAttributes.Init(count);
- ctx->Ans.reserved1.Init(count);
- ctx->Ans.reserved2.Init(count);
- for (int i = 0; i < count; ++i) {
- ilOffsetSize.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
- ilOffsetSize.HighPart = m_FileEntry.SubFiles[i].mNameLength;
- if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
- CSimpleStringA strFileName;
- GetSubFileName(m_FileEntry.FileNamesBuffer,
- dwBufSize, strFileName, &ilOffsetSize);
- Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
- continue;
- }
- ctx->Ans.reserved1[i] = 0;
- ctx->Ans.reserved2[i] = "";
- ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
- ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
- ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
- ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
- ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
- //TODO: Need to judge whether need to calculate size of directory.
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
- ctx->Ans.forbidAttributes[i] = 0;
- Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
- if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
- CSimpleStringA csFilePath;
- GetFullFilePath(&m_FileEntry, i, csFilePath);
- if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
- }
- }
- }
- }
- }
- #else
- ULARGE_INTEGER ilOffsetSize;
- ilOffsetSize.QuadPart = 0;
- const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
- DWORD dwInheritForbidAttrs = 0UL;
- if (bRefleshHeader) {
- if (m_FileEntry.Current.mNameLength != 0) {
- ilOffsetSize.u.LowPart = m_FileEntry.Current.mNameOffset;
- ilOffsetSize.u.HighPart = m_FileEntry.Current.mNameLength;
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.header, &ilOffsetSize);
- ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
- ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
- ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
- ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
- ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
- if (!ctx->Ans.header.IsNullOrEmpty()) {
- if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
- dwInheritForbidAttrs |= BS_DENY_DELETE;
- Dbg("header-forbit:%s", ctx->Ans.header.GetData());
- }
- }
- }
- }
- int count = m_FileEntry.SubFiles.GetCount();
- int minusCount = 0;
- for (int i = 0; i < count; ++i)
- if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
- minusCount++;
- count = count - minusCount;
- ctx->Ans.count = count;
- if (count > 0) {
- if (count >= MAX_SUBFILES_COUNT) {
- Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
- std::vector<CSimpleFileShell> vtFileShells;
- for (int i = 0; i < count; ++i) {
- CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
- vtFileShells.push_back(item);
- }
- sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
- char szFormat[128] = { 0 };
- count = MAX_SUBFILES_COUNT;
- ctx->Ans.count = count;
- ctx->Ans.reserved1.Init(count);
- ctx->Ans.reserved2.Init(count);
- ctx->Ans.fileAttributes.Init(count);
- ctx->Ans.fileNames.Init(count);
- ctx->Ans.ftCreates.Init(count);
- ctx->Ans.ftModifieds.Init(count);
- ctx->Ans.ftAccesses.Init(count);
- ctx->Ans.fileSizes.Init(count);
- ctx->Ans.forbidAttributes.Init(count);
- for (int i = 0; i < count; ++i) {
- CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
- ilOffsetSize.u.LowPart = component->mNameOffset;
- ilOffsetSize.u.HighPart = component->mNameLength;
- if (component->mAttributes & dwFilterAttributes) {
- CSimpleStringA strFileName;
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, strFileName, &ilOffsetSize);
- Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
- continue;
- }
- ctx->Ans.reserved1[i] = 0;
- ctx->Ans.reserved2[i] = "";
- ctx->Ans.fileAttributes[i] = component->mAttributes;
- ctx->Ans.ftCreates[i] = component->mftCreate;
- ctx->Ans.ftModifieds[i] = component->mftModified;
- ctx->Ans.ftAccesses[i] = component->mftAccess;
- ctx->Ans.fileSizes[i] = component->mFileSize;
- //TODO: Need to judge whether need to calculate size of directory.
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
- ctx->Ans.forbidAttributes[i] = 0;
- Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
- if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
- CSimpleStringA csFilePath;
- GetFullFilePath(&m_FileEntry, i, csFilePath);
- if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
- }
- }
- }
- vtFileShells.clear();
- } else {
- ctx->Ans.fileAttributes.Init(count);
- ctx->Ans.fileNames.Init(count);
- ctx->Ans.ftCreates.Init(count);
- ctx->Ans.ftModifieds.Init(count);
- ctx->Ans.ftAccesses.Init(count);
- ctx->Ans.fileSizes.Init(count);
- ctx->Ans.forbidAttributes.Init(count);
- ctx->Ans.reserved1.Init(count);
- ctx->Ans.reserved2.Init(count);
- for (int i = 0; i < count; ++i) {
- ilOffsetSize.u.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
- ilOffsetSize.u.HighPart = m_FileEntry.SubFiles[i].mNameLength;
- if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
- CSimpleStringA strFileName;
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, strFileName, &ilOffsetSize);
- Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
- continue;
- }
- ctx->Ans.reserved1[i] = 0;
- ctx->Ans.reserved2[i] = "";
- ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
- ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
- ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
- ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
- ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
- //TODO: Need to judge whether need to calculate size of directory.
- GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
- ctx->Ans.forbidAttributes[i] = 0;
- Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
- if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
- CSimpleStringA csFilePath;
- GetFullFilePath(&m_FileEntry, i, csFilePath);
- if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
- ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
- Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
- }
- }
- }
- }
- }
- #endif //_MSC_VER
- //Free action for saving memory.
- m_FileEntry.SubFiles.Clear();
- m_FileEntry.FileNamesBuffer.Clear();
- m_FileEntry.Current.Clear();
- return TRUE;
- }
- int ResourceWatcherFSM::FilterFilePathAhead(LPCTSTR lpszPath, const int option)
- {
- #ifdef RVC_OS_LINUX
- size_t len = strlen(lpszPath);
- if (lpszPath[0] != '/') {
- Dbg("illegal disk format path !");
- return -2;
- }
- char* path = new char[len + 1];
- LOG_ASSERT(path != NULL);
- memset(path, 0, sizeof(char) * (len + 1));
- memcpy(path, lpszPath, len);
- path[len] = '\0';
- int pos = len - 1;
- for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos) {
- ;//
- }
- path[pos + 1] = '\0';
- len = strlen(path);
- if (len < 1) {
- delete[] path;
- return -1;
- }
- else if (len == 1 && option == OPT_FILE_CMD_DELETE) {
- /*disk volumn to delete*/
- delete[] path;
- return 1;
- }
- if (InBlackListOrNot(path, option)) {
- delete[] path;
- return 2;
- }
- delete[] path;
- return 0;
- #else
- if (lpszPath == NULL || strlen(lpszPath) <= 1)
- return -1;
- size_t len = strlen(lpszPath);
- if (!((lpszPath[0] <= 'z' && lpszPath[0] >= 'a') || (lpszPath[0] <= 'Z' && lpszPath[0] >= 'A'))
- || lpszPath[1] != ':')
- {
- return -2;
- }
- {
- char disk = lpszPath[0];
- if (disk >= 'a' && disk <= 'z') disk -= 32;
- int diskNo = disk - 'A';
- if (!sBDiskValStatus[diskNo])
- {
- return -3;
- }
- }
- char* path = new char[len + 1];
- LOG_ASSERT(path != NULL);
- memset(path, 0, sizeof(char) * (len + 1));
- memcpy(path, lpszPath, len);
- path[len] = '\0';
- int pos = len - 1;
- for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos)
- {
- ;//
- }
- path[pos + 1] = '\0';
- len = strlen(path);
- if (len <= 1)
- {
- delete[] path;
- return -1;
- }
- else if (len == 2)
- {
- if (option == 2)
- {
- delete[] path;
- return 1;
- }
- }
- if (InBlackSheet(path, option))
- {
- delete[] path;
- return 2;
- }
- delete[] path;
- return 0;
- #endif // RVC_OS_LINUX
- }
- BOOL ResourceWatcherFSM::InBlackListOrNot(LPCTSTR lpszPath, const int option)
- {
- BOOL bForbidden = FALSE;
- LOG_ASSERT(lpszPath != NULL && strlen(lpszPath) != 0);
- DWORD dwRequredAttr = 0;
- switch (option)
- {
- case OPT_FILE_CMD_SPREAD:
- dwRequredAttr |= BS_DENY_READ;
- break;
- case OPT_FILE_CMD_EXECUTE:
- dwRequredAttr |= BS_DENY_EXECUTE;
- break;
- case OPT_FILE_CMD_CREATE:
- dwRequredAttr |= BS_DENY_CREATE;
- break;
- case OPT_FILE_CMD_DELETE:
- case OPT_FILE_CMD_CLEAR:
- case OPT_FILE_CMD_RENAME:
- dwRequredAttr |= BS_DENY_DELETE;
- break;
- case OPT_FILE_CMD_APPEND:
- dwRequredAttr |= BS_DENY_MODIFY;
- break;
- default:
- return bForbidden;
- break;
- }
- const size_t len = strlen(lpszPath);
- char* temp_path = new char[len + 1];
- if (temp_path == NULL) {
- return bForbidden;
- }
- memset(temp_path, 0, sizeof(char) * (len + 1));
- strcpy_s(temp_path, len + 1, lpszPath);
- for (size_t i = 0; i < len; ++i) {
- if (temp_path[i] == '\\')
- temp_path[i] = '/';
- }
- lpszPath = temp_path;
- for (const_bs_iter cit = m_forbidDirList.cbegin(); cit != m_forbidDirList.cend() && !bForbidden; ++cit)
- {
- const bs_key& path = cit->first;
- const bs_value& resist = cit->second;
- const size_t n = strlen(path.c_str());
- if (dwRequredAttr & resist)
- {
- if (path[0] == '*')
- {
- bForbidden = TRUE;
- break;
- }
- if (!_strnicmp(lpszPath, path.c_str(), min(len, n)))
- {
- if (len > n
- && (lpszPath[n] == '\\' || lpszPath[n] == '/')
- && (resist & BS_DENY_INHERITED))
- {
- bForbidden = TRUE;
- }
- if (len == n)
- {
- bForbidden = TRUE;
- }
- if (len < n)
- {
- FileType ft;
- if (IsPathExisted(path.c_str(), ft))
- {
- bForbidden = TRUE;
- }
- }
- }
- }
- }
- if (temp_path) {
- delete[] temp_path;
- temp_path = NULL;
- }
- return bForbidden;
- }
- void ResourceWatcherFSM::InitBlackList()
- {
- #ifdef RVC_OS_LINUX
- LOG_FUNCTION();
- m_forbidDirList.clear();
- DWORD dwDenyAttr;
- CSimpleStringA strPath;
- if (GetEntityBase()->GetFunction()->GetPath("UploadVideo", strPath) == Error_Succeed) {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
- }
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- if (GetEntityBase()->GetFunction()->GetPath("UploadPhoto", strPath) == Error_Succeed) {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
- }
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- if (GetEntityBase()->GetFunction()->GetPath("Cfg", strPath) == Error_Succeed) {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
- }
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- if (GetEntityBase()->GetFunction()->GetPath("Dep", strPath) == Error_Succeed) {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_CREATE | BS_DENY_MODIFY | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
- }
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- if (GetEntityBase()->GetFunction()->GetPath("Base", strPath) == Error_Succeed) {
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_EXECUTE | BS_DENY_INHERITED;
- const size_t len = strPath.GetLength();
- char* path = new char[len + 1];
- //Run Directory
- if (path && (ZeroMemory(path, len + 1), GetDirSplitPath(strPath, 2, path, len + 1) > 0)) {
- //Dbg("Add %s - 0x%X", path, dwDenyAttr);
- //m_forbidDirList[string(path)] = dwDenyAttr;
- }
- if (path) {
- strPath = path;
- delete[] path;
- }
- CSimpleStringA strPathInner;
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- strPathInner = strPath + SPLIT_SLASH_STR + "hardwarecfg";
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_MODIFY | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- strPathInner = strPath + SPLIT_SLASH_STR + "runinfo" + SPLIT_SLASH_STR + "kmc";
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- strPathInner = strPath + SPLIT_SLASH_STR + "version";
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- dwDenyAttr = BS_DENY_MODIFY;
- strPathInner = strPath + SPLIT_SLASH_STR + "version" + SPLIT_SLASH_STR + "active.txt";
- Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
- }
- Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
- #else
- m_blacksheet.clear();
- #define INFO_BUFFER_SIZE MAX_PATH
- char infoBuf[INFO_BUFFER_SIZE];
- DWORD bufCharCount = INFO_BUFFER_SIZE;
- char sys_disk = '\0';
- bufCharCount = INFO_BUFFER_SIZE;
- if (!GetComputerName(infoBuf, &bufCharCount))
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetComputerName failed, GLE=%u", GetLastError());
- else DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Computer name: %s", infoBuf);
- // Get and display the user name.
- ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
- bufCharCount = INFO_BUFFER_SIZE;
- if (!GetUserName(infoBuf, &bufCharCount)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetUserName failed, GLE=%u", GetLastError());
- curUserName.Clear();
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("User name: %s", infoBuf);
- curUserName = infoBuf;
- }
- DWORD dwDenyAttr;
- // All file cannot be executed !! -Josephus@2017612 9:29:01
- ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
- infoBuf[0] = '*', infoBuf[1] = '\0';
- dwDenyAttr = BS_DENY_EXECUTE | BS_DENY_INHERITED;
- m_blacksheet.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
- // Get and display the system directory.
- ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
- if (!GetSystemDirectory(infoBuf, INFO_BUFFER_SIZE))
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDirectory failed, GLE=%u", GetLastError());
- else
- {
- dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add System Directory: %s - 0x%X", infoBuf, dwDenyAttr);
- m_blacksheet.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
- sys_disk = infoBuf[0];
- if (sys_disk >= 'a' && sys_disk <= 'z') sys_disk -= 32;
- int diskNo = sys_disk - 'A';
- LOG_ASSERT(sBDiskValStatus[diskNo]);
- sBDiskValStatus[diskNo] = sBDiskValStatus[diskNo] + 2; //Set system disk flag
- }
- // Get and display the Windows directory.
- ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
- if (!GetWindowsDirectory(infoBuf, INFO_BUFFER_SIZE))
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetWindowsDirectory failed, GLE=%u", GetLastError());
- else
- {
- dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add Windows Directory: %s - 0x%X", infoBuf, dwDenyAttr);
- m_blacksheet.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
- }
- if (sys_disk != '\0')
- {
- ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
- //////////////////////////////////////////////////////////////////////////
- LOG_ASSERT(INFO_BUFFER_SIZE > 4);
- infoBuf[0] = sys_disk;
- infoBuf[1] = ':';
- infoBuf[2] = '\\';
- infoBuf[3] = '\0';
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Start to Add system limited path: %d", LIMITED_SYS_COUNT);
- const DWORD dwSysAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
- for (int i = 0; i < LIMITED_SYS_COUNT; ++i)
- {
- string strfullPath = infoBuf;
- strfullPath += LIMITED_SYS_PATH(i);
- if (m_blacksheet.find(strfullPath) == m_blacksheet.end())
- {
- m_blacksheet[strfullPath] = dwSysAttr;
- }
- }
- }
- //////////////////////////////////////////////////////////////////////////
- CSimpleStringA strPath;
- if (GetEntityBase()->GetFunction()->GetPath("UploadVideo", strPath) == Error_Succeed)
- {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
- }
- if (GetEntityBase()->GetFunction()->GetPath("UploadPhoto", strPath) == Error_Succeed)
- {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
- }
- if (GetEntityBase()->GetFunction()->GetPath("Cfg", strPath) == Error_Succeed)
- {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
- }
- if (GetEntityBase()->GetFunction()->GetPath("Dep", strPath) == Error_Succeed)
- {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_CREATE | BS_DENY_MODIFY | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
- m_blacksheet[string(strPath.GetData())] = dwDenyAttr;
- }
- if (GetEntityBase()->GetFunction()->GetPath("Base", strPath) == Error_Succeed)
- {
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_EXECUTE | BS_DENY_INHERITED;
- const size_t len = strPath.GetLength();
- char* path = new char[len + 1];
- //Run Directory
- if (path && (ZeroMemory(path, len + 1), GetDirSplitPath(strPath, 2, path, len + 1) > 0))
- {
- }
- if (path)
- {
- strPath = path;
- //
- delete[] path;
- }
- CSimpleStringA strPathInner;
- strPathInner = strPath + "\\hardwarecfg";
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_MODIFY | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
- strPathInner = strPath + "\\runinfo\\kmc";
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
- strPathInner = strPath + "\\version";
- dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
- dwDenyAttr = BS_DENY_MODIFY;
- strPathInner = strPath + "\\version\\active.txt";
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
- m_blacksheet[string(strPathInner.GetData())] = dwDenyAttr;
- }
- #endif // RVC_OS_LINUX
- }
- #ifdef _MSC_VER
- BOOL ResourceWatcherFSM::ClearDirRecursiveEx(LPCSTR lpDirPath)
- {
- int len = strlen(lpDirPath);
- if (lpDirPath == NULL || len == 0)
- return FALSE;
- if (len + 2 >= MAX_PATH)
- {
- return FALSE;
- }
- char* path = new char[MAX_PATH];
- if (path == NULL) return FALSE;
- memset(path, 0, sizeof(path));
- strcpy_s(path, MAX_PATH, lpDirPath);
- int pos = len - 1;
- for (; pos >= 0 && (path[pos] == '/' || path[pos] == '\\'); --pos)
- path[pos] = '\0';
- path[pos + 1] = '\0';
- strcat_s(path, MAX_PATH, "\\*");
- len = strlen(path);
- char tempFilePath[MAX_PATH];
- ZeroMemory(tempFilePath, MAX_PATH);
- WIN32_FIND_DATA wfd;
- HANDLE hFind;
- hFind = FindFirstFile(path, &wfd);
- if (hFind == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FindFirstFile failed GLE = %u.", GetLastError());
- delete[] path;
- return FALSE;
- }
- BOOL bResult = TRUE;
- do
- {
- if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- if (wfd.cFileName[0] != '.')
- {
- strcpy_s(tempFilePath, path);
- tempFilePath[len - 1] = '\0';
- if (len + strlen(wfd.cFileName) > MAX_PATH)
- {
- bResult = FALSE;
- break;
- }
- else
- {
- strcat_s(tempFilePath, wfd.cFileName);
- if (!RemoveDirRecursiveA(tempFilePath))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RemoveDirRecursiveA(%s) failed", tempFilePath);
- bResult = FALSE;
- break;
- }
- }
- }
- }
- else
- {
- strcpy_s(tempFilePath, path);
- tempFilePath[len - 1] = '\0';
- strcat_s(tempFilePath, wfd.cFileName);
- if (!RemoveFileA(tempFilePath))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RemoveFileA(%s) failed", tempFilePath);
- bResult = FALSE;
- break;
- }
- }
- } while (FindNextFileA(hFind, &wfd));
- FindClose(hFind);
- if (path) delete[] path;
- return bResult;
- }
- DWORD ResourceWatcherFSM::GetEventLog(SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req,
- ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- CHAR szEvtFile[MAX_PATH] = { 0 };
- memset(szEvtFile, 0, sizeof(CHAR) * MAX_PATH);
- if (!CombineTheEvtxFileName(m_strTerminalNo, szEvtFile)) {
- ctx->Ans.entries = 0;
- ctx->Ans.information = "初始化事件日志文件名失败";
- ctx->Answer(Error_Succeed);
- if (ExistsFileA(szEvtFile)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
- }
- return 0;
- }
- EVENTLOGPARAM filterParam = { 0 };
- filterParam.wEventType = ctx->Req.evtLevel == 0x00FF ? 0 : ctx->Req.evtLevel;
- BOOL bResult = TRUE;
- DWORD dwResult = ERROR_SUCCESS;
- if (ctx->Req.duration == DURAITON_CUSTOM) {
- ULONGLONG ullStart = ctx->Req.startTime;
- ULONGLONG ullEnd = ctx->Req.endTime;
- dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
- &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), &ullStart, &ullEnd);
- }
- else {
- dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
- &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), NULL, NULL);
- }
- if (dwResult != ERROR_SUCCESS) {
- ctx->Ans.entries = 0;
- ctx->Ans.information = "时间筛选参数错误";
- ctx->Answer(Error_Succeed);
- return 0;
- }
- if (!ctx->Req.evtSrcEventName.IsNullOrEmpty()) {
- #ifdef WIDE_CONDITION
- CSimpleStringW wSrvEventName = CSimpleStringA2W(ctx->Req.evtSrcEventName);
- wcscpy_s(filterParam.lpszSourceEventName, wSrvEventName);
- #else
- strcpy_s(filterParam.lpszSourceEventName, ctx->Req.evtSrcEventName);
- #endif
- }
- DWORD dwEntries = 0;
- WORD wEventTypeMask = ctx->Req.evtName == 0 ? 0x00FF : ctx->Req.evtName;
- if ((wEventTypeMask & 0x0001) == 0x0001) {
- DWORD dwRes = 0;
- filterParam.fApplication = TRUE;
- bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve application event log returned: %u",
- bResult ? "Success" : "Failed", dwRes);
- if (bResult) {
- dwEntries += dwRes;
- }
- filterParam.fApplication = FALSE;
- }
- if ((wEventTypeMask & 0x0002) == 0x0002) {
- DWORD dwRes = 0;
- filterParam.fSecurity = TRUE;
- bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve security event log returned: %u",
- bResult ? "Success" : "Failed", dwRes);
- if (bResult) {
- dwEntries += dwRes;
- }
- filterParam.fSecurity = FALSE;
- }
- if ((wEventTypeMask & 0x0008) == 0x0008) {
- DWORD dwRes = 0;
- filterParam.fSystem = TRUE;
- bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve system event log returned: %u",
- bResult ? "Success" : "Failed", dwRes);
- if (bResult) {
- dwEntries += dwRes;
- }
- filterParam.fSystem = FALSE;
- }
- if ((wEventTypeMask & 0x0100) == 0x0100) {
- DWORD dwRes = 0;
- filterParam.fCustom = TRUE;
- if (!ctx->Req.cusEvtFileName.IsNullOrEmpty()) {
- #ifdef WIDE_CONDITION
- CSimpleStringW strwFileName = CSimpleStringA2W(ctx->Req.cusEvtFileName);
- wcscpy_s(filterParam.lpszCustomEventName, strwFileName);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Custom event log path: %s", ctx->Req.cusEvtFileName);
- #else
- strcpy_s(filterParam.lpszCustomEventName, ctx->Req.cusEvtFileName);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Custom event log path: %s", filterParam.lpszCustomEventName);
- #endif
- }
- bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s]Retrieve custom event log returned: %u",
- bResult ? "Success" : "Failed", dwRes);
- if (bResult) {
- dwEntries += dwRes;
- }
- filterParam.fCustom = FALSE;
- }
- if (dwEntries == 0) {
- ctx->Ans.entries = 0;
- LogWarn(Severity_Middle, Error_Unexpect, 0, "The Count of event log is Zero!");
- ctx->Ans.information = "未找到相关的系统事件日志";
- if (ExistsFileA(szEvtFile)) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
- }
- }
- else {
- ctx->Ans.entries = dwEntries;
- ctx->Ans.evtLogFileName = szEvtFile;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Total count of event log: %u", dwEntries);
- }
- ctx->Answer(Error_Succeed);
- return dwEntries;
- }
- //合成生成的系统事件文件名称
- DWORD ResourceWatcherFSM::CombineTheEvtxFileName(LPCTSTR lpszTerminalNo, CHAR szEvtxFileName[])
- {
- CSimpleStringA strPath;
- if (lpszTerminalNo == NULL || strlen(lpszTerminalNo) == 0)
- {
- LogWarn(Severity_Middle, Error_Param, 0, "TerminalNo is nullptr");
- return 0;
- }
- if (GetEntityBase()->GetFunction()->GetPath("Temp", strPath) != Error_Succeed
- || strPath.IsNullOrEmpty())
- {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "GetPath about Temp failed");
- return 0;
- }
- if (!ExistsDirA(strPath)) {
- if (!CreateDirRecursiveA(strPath)) {
- LogWarn(Severity_Middle, Error_Unexpect, 0, "CreateDirRecursiveA failed");
- return 0;
- }
- }
- SYSTEMTIME st, stLocal;
- GetSystemTime(&st);
- SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
- #ifdef WIDE_CONDITION
- WCHAR fileName[MAX_PATH] = { 0 };
- CSimpleStringW strwPath = CSimpleStringA2W(strPath);
- CSimpleStringW lpwszTerminalNo = CSimpleStringA2W(CSimpleStringA(lpszTerminalNo));
- swprintf_s(fileName, L"%ws\\%ws-%d%02d%02d-%02d_%02d_%02d", (LPCWSTR)strwPath, (LPCWSTR)lpwszTerminalNo,
- stLocal.wYear, stLocal.wMonth, stLocal.wDay,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- wcscat_s(fileName, EXT_EVTLOG_NAME);
- CSimpleStringA lpszFileName = CSimpleStringW2A(CSimpleStringW(fileName));
- strcpy_s(szEvtxFileName, MAX_PATH, lpszFileName);
- return strlen(szEvtxFileName);
- #else
- CHAR fileName[MAX_PATH] = { 0 };
- sprintf_s(fileName, "%s\\%s-%d%02d%02d-%02d_%02d_%02d", (LPCTSTR)strPath, lpszTerminalNo,
- stLocal.wYear, stLocal.wMonth, stLocal.wDay,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- strcat_s(fileName, EXT_EVTLOG_NAME);
- strcpy_s(szEvtxFileName, MAX_PATH, fileName);
- return strlen(szEvtxFileName);
- #endif
- }
- DWORD ResourceWatcherFSM::CalSpecifiedSecondsFrom1970(const WORD wDuration
- , DWORD* dwStartTime
- , DWORD* dwEndTime
- , const PULONGLONG pStartTime
- , const PULONGLONG pEndTime)
- {
- DWORD status = E_FAIL;
- if (dwStartTime == NULL || dwEndTime == NULL)
- return E_INVALIDARG;
- if (wDuration == DURATION_NONE) {
- *dwStartTime = *dwEndTime = 0;
- return ERROR_SUCCESS;
- }
- ULONGLONG ullTimeStamp = 0;
- ULONGLONG SecsTo1970 = 116444736000000000;
- if (wDuration == DURAITON_CUSTOM) {
- if (pStartTime == NULL || pEndTime == NULL)
- return E_POINTER;
- if (*pStartTime > *pEndTime)
- return E_INVALIDARG;
- ullTimeStamp = (*pStartTime) - SecsTo1970;
- ullTimeStamp /= 10000000ULL;
- *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
- ullTimeStamp = (*pEndTime) - SecsTo1970;
- ullTimeStamp /= 10000000ULL;
- *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
- return ERROR_SUCCESS;
- }
- SYSTEMTIME st;
- GetSystemTime(&st);
- FILETIME ftCurTime;
- GetSystemTimeAsFileTime(&ftCurTime);
- ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
- uliCurTime.HighPart = ftCurTime.dwHighDateTime;
- uliCurTime.LowPart = ftCurTime.dwLowDateTime;
- if (wDuration == DURATION_HOUR_ONE) {
- uliOffset.QuadPart = UInt32x32To64(1 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
- }
- else if (wDuration == DURATION_HOUR_TWELVE) {
- uliOffset.QuadPart = UInt32x32To64(12 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
- }
- else if (wDuration == DURATION_DAY_ONE) {
- uliOffset.QuadPart = UInt32x32To64(24 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
- }
- else if (wDuration == DURATION_DAY_SEVENT) {
- uliOffset.QuadPart = UInt32x32To64(7 * 24 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
- }
- else if (wDuration == DURATION_MONTH_ONE) {
- uliOffset.QuadPart = UInt32x32To64(30 * 24 * 60 * 60, 1e7);
- uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
- }
- else {
- return E_INVALIDARG;
- }
- ullTimeStamp = uliBackTime.QuadPart - SecsTo1970;
- ullTimeStamp /= 10000000ULL;
- *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
- ullTimeStamp = uliCurTime.QuadPart - SecsTo1970;
- ullTimeStamp /= 10000000ULL;
- *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
- {
- FILETIME ftBackTime;
- SYSTEMTIME stUTC, stLocal;
- ftBackTime.dwHighDateTime = uliBackTime.HighPart;
- ftBackTime.dwLowDateTime = uliBackTime.LowPart;
- FileTimeToSystemTime(&ftBackTime, &stUTC);
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- CHAR szTimeFormat[MAX_PATH] = { 0 };
- // Build a string showing the date and time.
- sprintf_s(szTimeFormat, MAX_PATH, "%02d/%02d/%d %02d:%02d:%02d",
- stLocal.wMonth, stLocal.wDay, stLocal.wYear,
- stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- printf("Start time statmp: %s\n", szTimeFormat);
- }
- return ERROR_SUCCESS;
- }
- BOOL ResourceWatcherFSM::RetrieveSpecificedEventLogs(const LPEVENTLOGPARAM pEvtLogFilter,
- LPCTSTR lpszEvtFileName, DWORD& dwEntries)
- {
- LOG_FUNCTION();
- CEventLog* pEvtLog = NULL;
- if (pEvtLogFilter->fApplication) {
- pEvtLog = new CEventLog(APPLICATION_LOG);
- }
- else if (pEvtLogFilter->fSystem) {
- pEvtLog = new CEventLog(SYSTEM_LOG);
- }
- else if (pEvtLogFilter->fSecurity) {
- pEvtLog = new CEventLog(SECURITY_LOG);
- #ifdef WIDE_CONDITION
- }
- else if (pEvtLogFilter->fCustom && wcslen(pEvtLogFilter->lpszCustomEventName) > 0) {
- #else
- }
- else if (pEvtLogFilter->fCustom && strlen(pEvtLogFilter->lpszCustomEventName) > 0) {
- #endif
- pEvtLog = new CEventLog(pEvtLogFilter->lpszCustomEventName, TRUE);
- }
- if (pEvtLog == NULL || !pEvtLog->IsInitialized())
- {
- if (pEvtLog)
- delete pEvtLog;
- return FALSE;
- }
- #ifdef WIDE_CONDITION
- CSimpleStringW strwFileName = CSimpleStringA2W(CSimpleStringA(lpszEvtFileName));
- pEvtLog->InitializeLogFile(std::wstring(strwFileName));
- #else
- pEvtLog->InitializeLogFile(std::string(lpszEvtFileName));
- #endif
- dwEntries = pEvtLog->FilterEventLog(pEvtLogFilter->lpszSourceEventName
- , pEvtLogFilter->wEventType
- , pEvtLogFilter->dwEventId
- , pEvtLogFilter->dwTimeBegin
- , pEvtLogFilter->dwTimeEnd);
- if (pEvtLog)
- delete pEvtLog;
- return TRUE;
- }
- #endif // _MSC_VER
- BOOL ResourceWatcherFSM::ClearAd0Folder()
- {
- LOG_FUNCTION();
- ErrorCodeEnum ec;
- CSimpleStringA strAd0Path;
- CSmartPointer<IConfigInfo> spConfigRun;
- int nLastTaskTime(0);
- CSimpleStringA ssFilePath(true);
- ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->ReadConfigValueInt("LastClearTime", "Ad0Task", nLastTaskTime);
- if (IsTodayDone(nLastTaskTime)) {
- return TRUE;
- }
- ec = GetEntityBase()->GetFunction()->GetPath("Ad0", strAd0Path);
- if (ec != Error_Succeed || strAd0Path.IsNullOrEmpty()) {
- return FALSE;
- }
- if (!ExistsDirA(strAd0Path)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("The Folder is not existed");
- spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
- (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- return TRUE;
- }
-
- char displayTime[MAX_PATH] = { 0 };
- ZeroMemory(&mftAd0RemoveTime, sizeof(FILETIME));
- CalculateBackTime(&mftAd0RemoveTime, AD0_DAY_OF_BACKWARD);
- GetTimeFormatStr(displayTime, MAX_PATH, &mftAd0RemoveTime);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The date backward to delete: %s", displayTime);
- #ifdef RVC_OS_LINUX
- ssFilePath = strAd0Path;
- #else
- ssFilePath = strAd0Path + "\\*";
- #endif // RVC_OS_LINUX
- int nDelSuc = 0;
- int nDelFailed = 0;
- int nfileSum = ClearSpecifieFile(DFT_Ad0, (LPCTSTR)ssFilePath, nDelSuc, nDelFailed);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("#Ad0#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
-
- spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
- (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- return TRUE;
- }
- BOOL ResourceWatcherFSM::IsTodayDone(int nRecordTime)
- {
- if (nRecordTime <= 0) {
- return FALSE;
- }
- SYSTEMTIME stNow = {};
- SYSTEMTIME stTaskTime = CSmallDateTime(nRecordTime).ToSystemTime();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Last record time: %04d-%02d-%02d %02d:%02d:%02d",
- stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
- stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
- #ifdef RVC_OS_LINUX
- stNow = CSmallDateTime::GetNow().ToSystemTime();
- #else
- GetLocalTime(&stNow);
- #endif // RVC_OS_LINUX
- if (stTaskTime.wYear == stNow.wYear
- && stTaskTime.wMonth == stNow.wMonth
- && stTaskTime.wDay == stNow.wDay)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("task has been executed today, last clear time: %s",
- (const char*)CSmallDateTime(nRecordTime).ToTimeString());
- return TRUE;
- }
- return FALSE;
- }
- BOOL ResourceWatcherFSM::GetSystemBootTime(CSmallDateTime & systemBootTime)
- {
- #ifdef RVC_OS_LINUX
- DWORD ticks = 0;
- SYSTEMTIME systemTime;
- struct sysinfo info;
- time_t curTime = 0;
- time_t bootTime = 0;
- struct tm* ptm = NULL;
- if (sysinfo(&info)) {
- Dbg("Failed to get sysinfo, errno:%u, reason:%s", errno, strerror(errno));
- return FALSE;
- }
- time(&curTime);
- if (curTime > info.uptime) {
- bootTime = curTime - info.uptime;
- }
- else {
- bootTime = info.uptime - curTime;
- }
- ptm = localtime(&bootTime);
- struct timespec ts;
- if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
- ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
- systemTime.wYear = (WORD)(ptm->tm_year + 1900);
- systemTime.wMonth = (WORD)(ptm->tm_mon + 1);
- systemTime.wDayOfWeek = (WORD)ptm->tm_wday;
- systemTime.wDay = (WORD)ptm->tm_mday;
- systemTime.wHour = (WORD)ptm->tm_hour;
- systemTime.wMinute = (WORD)ptm->tm_min;
- systemTime.wSecond = (WORD)ptm->tm_sec;
- systemTime.wMilliseconds = (WORD)(ticks % 1000);
- systemBootTime.FromSystemTime(systemTime);
- Dbg("OSStartTime: %s", systemBootTime.ToTimeString().GetData());
- return TRUE;
- #else
- PDH_STATUS Status;
- HQUERY Query = NULL;
- HCOUNTER hcElapsedTimeCount;
- BOOL fSuc = FALSE;
- /** 杀毒软件会对附件这几个系统调用函数有所监控,导致有时会耗费5s时间 Gifur@20221019]*/
- Status = PdhOpenQuery(NULL, NULL, &Query);
- PDH_FMT_COUNTERVALUE counterValue;
- if (Status != ERROR_SUCCESS)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhOpenQuery failed with status 0x%x.", Status);
- goto Cleanup;
- }
- Status = PdhAddCounter(Query, SystemElapsedQuery, NULL, &hcElapsedTimeCount);
- if (Status != ERROR_SUCCESS)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhAddCounter for SystemElapsedQuery failed with status 0x%x.", Status);
- goto Cleanup;
- }
- // 查询性能监视器数据
- Status = PdhCollectQueryData(Query);
- if (Status != ERROR_SUCCESS)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("PdhCollectQueryData failed with 0x%x.", Status);
- goto Cleanup;
- }
- Status = PdhGetFormattedCounterValue(hcElapsedTimeCount, PDH_FMT_LARGE, NULL, &counterValue);
- if (Status == ERROR_SUCCESS)
- {
- ULONGLONG ulSinceSeconds = counterValue.largeValue;
- ULONG days = 0, hours = 0, minutes = 0, seconds = 0;
- days = ULONG(ulSinceSeconds / DAY_DIV);
- ulSinceSeconds %= DAY_DIV;
- hours = ULONG(ulSinceSeconds / HOURS_DIV);
- ulSinceSeconds %= HOURS_DIV;
- minutes = ULONG(ulSinceSeconds / MINUS_DIV);
- ulSinceSeconds %= MINUS_DIV;
- seconds = ULONG(ulSinceSeconds);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SystemElapseTime: %u:%02u:%02u:%02u", days, hours, minutes, seconds);
- FILETIME ftCurTime, ftStartTime;
- GetSystemTimeAsFileTime(&ftCurTime);
- ULARGE_INTEGER uliCurTime;
- uliCurTime.HighPart = ftCurTime.dwHighDateTime;
- uliCurTime.LowPart = ftCurTime.dwLowDateTime;
- uliCurTime.QuadPart -= counterValue.largeValue * 1e7;
- ftStartTime.dwHighDateTime = uliCurTime.HighPart;
- ftStartTime.dwLowDateTime = uliCurTime.LowPart;
- SYSTEMTIME stUTC, stLocal;
- FileTimeToSystemTime(&ftStartTime, &stUTC);
- char temp[22];
- SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
- sprintf_s(temp, 22, "%d-%02d-%02d %02d:%02d:%02d",
- stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("OSStartTime: %s", temp);
- systemBootTime.FromSystemTime(stLocal);
- fSuc = TRUE;
- }
- Cleanup:
- Status = PdhRemoveCounter(hcElapsedTimeCount);
- if (Query) {
- PdhCloseQuery(Query);
- }
- return fSuc;
- #endif // RVC_OS_LINUX
- }
- #ifdef _MSC_VER
- HRESULT ResourceWatcherFSM::SetDefaultAudioPlaybackDevice(LPCWSTR devID)
- {
- IPolicyConfigVista* pPolicyConfig;
- ERole reserved = eConsole;
- HRESULT hr = CoCreateInstance(__uuidof(CPolicyConfigVistaClient),
- NULL, CLSCTX_ALL, __uuidof(IPolicyConfigVista), (LPVOID*)&pPolicyConfig);
- if (SUCCEEDED(hr))
- {
- hr = pPolicyConfig->SetDefaultEndpoint(devID, reserved);
- pPolicyConfig->Release();
- }
- return hr;
- }
- BOOL ResourceWatcherFSM::SetDefaultAudioDevice()
- {
- CSmartPointer<IEntityFunction> spFunction = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- CSimpleStringA strAudioName;
- BOOL bRet = FALSE;
- ErrorCodeEnum ec = spFunction->OpenConfig(Config_Root, spConfig);
- ec = spConfig->ReadConfigValue("Audio", "handfree_out_dev", strAudioName);
- if (strAudioName.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("handfree_out_dev is nullptr or empty!!");
- return FALSE;
- }
- CSimpleStringW strwAudioName = CSimpleStringA2W(strAudioName);
- HRESULT hr = CoInitialize(NULL);
- if (SUCCEEDED(hr))
- {
- IMMDeviceEnumerator* pEnum = NULL;
- // Create a multimedia device enumerator.
- hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL,
- CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pEnum);
- if (SUCCEEDED(hr))
- {
- //判断是否是默认的音频设备,是就退出
- bool bExit = false;
- IMMDevice* pDefDevice = NULL;
- hr = pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefDevice);
- if (SUCCEEDED(hr))
- {
- IPropertyStore* pStore;
- hr = pDefDevice->OpenPropertyStore(STGM_READ, &pStore);
- if (SUCCEEDED(hr))
- {
- PROPVARIANT friendlyName;
- PropVariantInit(&friendlyName);
- hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
- if (SUCCEEDED(hr))
- {
- CSimpleStringW strTmp = friendlyName.pwszVal;
- if (strTmp.IsStartWith(strwAudioName)) {
- bExit = true;
- }
- PropVariantClear(&friendlyName);
- }
- pStore->Release();
- }
- pDefDevice->Release();
- }
- if (bExit) {
- pEnum->Release();
- return TRUE;
- }
- IMMDeviceCollection* pDevices;
- // Enumerate the output devices.
- hr = pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pDevices);
- if (SUCCEEDED(hr))
- {
- UINT count;
- pDevices->GetCount(&count);
- if (SUCCEEDED(hr))
- {
- for (int i = 0; i < count; i++)
- {
- bool bFind = false;
- IMMDevice* pDevice;
- hr = pDevices->Item(i, &pDevice);
- if (SUCCEEDED(hr))
- {
- LPWSTR wstrID = NULL;
- hr = pDevice->GetId(&wstrID);
- if (SUCCEEDED(hr))
- {
- IPropertyStore* pStore;
- hr = pDevice->OpenPropertyStore(STGM_READ, &pStore);
- if (SUCCEEDED(hr))
- {
- PROPVARIANT friendlyName;
- PropVariantInit(&friendlyName);
- hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
- if (SUCCEEDED(hr))
- {
- // if no options, print the device
- // otherwise, find the selected device and set it to be default
- CSimpleStringW strTmp = friendlyName.pwszVal;
- if (strTmp.IsStartWith(strwAudioName)) {
- bFind = true;
- HRESULT hr = SetDefaultAudioPlaybackDevice(wstrID);
- if (SUCCEEDED(hr)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("set default audio player succ.");
- bRet = TRUE;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("set default audio player failed");
- }
- }
- PropVariantClear(&friendlyName);
- }
- pStore->Release();
- }
- }
- pDevice->Release();
- }
- if (bFind)
- {
- break;
- }
- }
- }
- pDevices->Release();
- }
- pEnum->Release();
- }
- }
- CoUninitialize();
- return bRet;
- }
- bool ResourceWatcherFSM::CreateLinkFile(const CSimpleStringA& szStartAppPath, const CSimpleStringA& szAddCmdLine,
- const CSimpleStringA& szDestLnkPath, const CSimpleStringA& szIconPath)
- {
- HRESULT hr = CoInitialize(NULL);
- bool bRet = false;
- if (SUCCEEDED(hr))
- {
- IShellLink* pShellLink;
- hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pShellLink);
- if (SUCCEEDED(hr))
- {
- pShellLink->SetPath(szStartAppPath);
- string strTmp = szStartAppPath;
- int nStart = strTmp.find_last_of("/\\");
- pShellLink->SetWorkingDirectory(strTmp.substr(0, nStart).c_str());
- pShellLink->SetArguments(szAddCmdLine);
- if (szIconPath)
- {
- pShellLink->SetIconLocation(szIconPath, 0);
- }
- IPersistFile* pPersistFile;
- hr = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile);
- if (SUCCEEDED(hr))
- {
- hr = pPersistFile->Save(CSimpleStringA2W(szDestLnkPath).GetData(), FALSE);
- if (SUCCEEDED(hr))
- {
- bRet = true;
- }
- pPersistFile->Release();
- }
- pShellLink->Release();
- }
- CoUninitialize();
- }
- return bRet;
- }
- void ResourceWatcherFSM::CreateLink(const CSimpleStringA& exePath)
- {
- LPITEMIDLIST lp;
- SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &lp);
- CHAR lstr[100] = "";
- SHGetPathFromIDList(lp, lstr);
- CSimpleStringA s = lstr;
- s += "\\可视柜台.lnk";
- CSimpleStringA icoPath;
- ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", icoPath);
- CSimpleStringA csPath = icoPath;
- csPath += "\\active.txt";
- FILE* pFile = fopen(csPath, "r");
- if (pFile != NULL)
- {
- char szTemp[256] = {};
- char szVersion[32] = {};
- int n = fread(szTemp, 1, 256, pFile);
- strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
- fclose(pFile);
- icoPath = icoPath + "\\" + szVersion + "\\bin\\VTM_IL.ico";
- if (!CreateLinkFile(exePath, "", s, icoPath))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile DESKTOP fail");
- }
- SHGetSpecialFolderLocation(0, CSIDL_PROGRAMS, &lp);
- memset(lstr, 0, strlen(lstr));
- SHGetPathFromIDList(lp, lstr);
- s = lstr;
- s += "\\可视柜台.lnk";
- if (!CreateLinkFile(exePath, "", s, icoPath))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile CSIDL_PROGRAMS fail");
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("open active.txt fail");
- }
- }
- bool isFileExist(const std::string& name)
- {
- if (FILE* file = fopen(name.c_str(), "r")) {
- fclose(file);
- return true;
- }
- else {
- return false;
- }
- }
- bool ResourceWatcherFSM::CopyExeToRoot()
- {
- CSimpleStringA rootVerPath, exePath;
- ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
- exePath = rootVerPath + "\\VTM.exe";
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("exePath:%s", exePath.GetData());
- if (rc == Error_Succeed) //&& !ExistsFileA(exePath)
- {
- CSimpleStringA srcExePath, csPath = rootVerPath;
- char szVersion[32] = {};
- csPath += "\\active.txt";
- FILE* pFile = fopen(csPath, "r");
- if (pFile != NULL)
- {
- char szTemp[256] = {};
- int n = fread(szTemp, 1, 256, pFile);
- strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
- fclose(pFile);
- srcExePath = rootVerPath + "\\" + szVersion + "\\bin\\VTM.exe";
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("srcExePath:%s exePath:%s", srcExePath.GetData(), exePath.GetData());
- if (!CopyFileA(srcExePath.GetData(), exePath.GetData(), FALSE))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CopyFileA Fail error :%d ", GetLastError());
- return false;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("open active.txt fail");
- return false;
- }
- }
- return true;
- }
- bool ResourceWatcherFSM::GetVtmVersion(CSimpleStringA& csVersion)
- {
- bool bRet = false;
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- LogWarn(Severity_Middle, Error_Exception, ERR_WRAN_OPEN_ACTIVE_FAIL, "testActive fail , get RootVer path is fai");
- return false;
- }
- CSimpleStringA strActiveFile = CSimpleStringA::Format("%s\\active.txt", rootVerPath.GetData());
- FILE* pFile = fopen(strActiveFile.GetData(), "rb+");
- if (pFile != NULL)
- {
- char szTemp[256] = {};
- char szVersion[32] = {};
- int n = fread(szTemp, 1, 256, pFile);
- strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
- csVersion = szVersion;
- fclose(pFile);
- bRet = true;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open active.txt failed.");
- bRet = false;
- }
- return bRet;
- }
- bool ResourceWatcherFSM::GetRegValue(HKEY hKey, LPCTSTR lpcszParam,
- CHAR* pSzValue, DWORD* pDwSizeOfSz)
- {
- DWORD dwType = REG_SZ;
- TCHAR szValue[MAX_PATH + 1] = { 0 };
- DWORD dwSize = MAX_PATH * sizeof(CHAR);
- LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, pDwSizeOfSz);
- if (lResult == ERROR_SUCCESS) {
- strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
- return true;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"InstallTime\" error, result=%ld.", lResult);
- return false;
- }
- }
- void ResourceWatcherFSM::DetectAutoStartupCover()
- {
- int bStartupByVbs(0);
- DetectAutoStartup(bStartupByVbs);
- if (m_forceStartupWithExeFlag == 1 && bStartupByVbs == 1 && !m_IsPadDevice) {
- ChangeAutoStartupWithExe(); //test succ
- }
- else if (m_forceStartupWithExeFlag == 2 && (bStartupByVbs == 0 || bStartupByVbs == 1) && !m_IsPadDevice) {
- ChangeAutoStartupWithExe(); //test succ || test succ
- }
- else if (m_forceStartupWithExeFlag == 3 && (bStartupByVbs == 1 || bStartupByVbs == 2)) {
- ChangeAutoStartupWithExe(true); //test succ || test succ
- }
- }
- static int Is32R64Platform()
- {
- static int isWow64 = -1;
- typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
- if (isWow64 == -1) {
- BOOL bIsWow64 = FALSE;
- LPFN_ISWOW64PROCESS fnIsWow64Process =
- (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
- if (NULL != fnIsWow64Process) {
- if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("detect is running with 64bit or not failed: %u", GetLastError());
- return -1;
- }
- else {
- isWow64 = bIsWow64 ? 1 : 0;
- }
- }
- }
- return isWow64;
- }
- void ResourceWatcherFSM::DetectAutoStartup(int& vbsType)
- {
- LOG_FUNCTION();
- vbsType = -1;
- if (m_DoneDetectAutostart) {
- vbsType = -2;
- return;
- }
- DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
- if (Is32R64Platform() != 0) {
- dwFlag |= KEY_WOW64_64KEY;
- }
- HKEY hKey;
- LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"),
- 0, dwFlag, &hKey);
- if (lResult == ERROR_SUCCESS) {
- DWORD dwType = REG_SZ;
- DWORD dwSize = MAX_PATH * sizeof(TCHAR);
- TCHAR szValue[MAX_PATH + 1] = { 0 };
- lResult = RegQueryValueEx(hKey, "Shell", NULL, &dwType, (LPBYTE)szValue, &dwSize);
- if (lResult == ERROR_SUCCESS) {
- CSimpleStringA value(szValue);
- if (value.IsNullOrEmpty() || value.Compare("explorer.exe") != 0) {
- if (value.IsEndWith(".vbs", true)) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_AUTO_STARTUP_FROM_REGIST, value);
- vbsType = 1;
- }
- else if (value.IsEndWith("VTM.exe", true)) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_EXE, value);
- vbsType = 2;
- }
- }
- else {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_NOT_AUTO_STARTUP_FROM_REGIST, value);
- if (value.Compare("explorer.exe") == 0) {
- vbsType = 0;
- }
- }
- }
- else {
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
- CSimpleStringA::Format("RegQueryValueEx error returned %u, GLE=%u.", lResult, GetLastError()));
- }
- }
- else {
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
- CSimpleStringA::Format("RegOpenKeyEx error, GLE=%u.", GetLastError()));
- }
- RegCloseKey(hKey);
- m_DoneDetectAutostart = true;
- return;
- }
- ErrorCodeEnum ResourceWatcherFSM::ChangeAutoStartupWithExe(bool resetExplorer)
- {
- const char* exploreExe = "explorer.exe";
- ErrorCodeEnum result(Error_Succeed);
- CSimpleStringA exePath(true);
- if (resetExplorer) {
- exePath = exploreExe;
- }
- else {
- result = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
- if (exePath.IsNullOrEmpty() || result != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get RootVer path failed: %d", result);
- return Error_Unexpect;
- }
- exePath.Append("\\VTM.exe");
- if (!ExistsFileA(exePath)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] is not existed!", exePath.GetData());
- return Error_NotExist;
- }
- }
- DWORD dwFlag = KEY_WRITE;
- if (Is32R64Platform() != 0) {
- dwFlag |= KEY_WOW64_64KEY;
- }
- HKEY hKey;
- LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), 0, dwFlag, &hKey);
- if (lResult == ERROR_SUCCESS) {
- lResult = RegSetValueExA(hKey, "Shell", 0, REG_SZ, (const BYTE*)exePath.GetData(), exePath.GetLength());
- if (lResult == ERROR_SUCCESS) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_SUCC
- , CSimpleStringA::Format("RegSetValueExA for Shell with %s succ!", exePath.GetData()));
- result = Error_Succeed;
- }
- else {
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
- , CSimpleStringA::Format("RegSetValueExA for Shell with %s failed: %d", exePath.GetData(), lResult));
- result = Error_Unexpect;
- }
- }
- else {
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
- , CSimpleStringA::Format("RegOpenKeyEx for write %s failed: %d", exePath.GetData(), lResult));
- result = Error_Unexpect;
- }
- RegCloseKey(hKey);
- return result;
- }
- void ResourceWatcherFSM::InitialAutoStartupSetType()
- {
- CSmartPointer<IConfigInfo> spConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- int value(0);
- spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "AutoStartCMD", value);
- if (value != 0) {
- m_forceStartupWithExeFlag = value;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get AutoStartCMD from CS: %d", m_forceStartupWithExeFlag);
- }
- }
- BOOL ResourceWatcherFSM::IsHasSetAutoStartupByFolder()
- {
- BOOL result(FALSE);
- const char* STARTUP_DIR_FULL_PATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp";
- #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
- const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(ST测试).lnk";
- #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
- const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(UAT测试).lnk";
- #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
- const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
- #elif defined(DEVOPS_ON_DEV)/*DevOps流水线编译,Dev环境*/
- const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(开发).lnk";
- #else/*本地编译等非DevOps环境编译的版本*/
- const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
- #endif
- if (!ExistsDirA(STARTUP_DIR_FULL_PATH)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] dir is not exist!", STARTUP_DIR_FULL_PATH);
- return result;
- }
- auto arr = fileutil_get_sub_files(STARTUP_DIR_FULL_PATH);
- if (arr != NULL) {
- for (int i = 0; i < arr->nelts; ++i) {
- char* file = ARRAY_IDX(arr, i, char*);
- char* filename = strrchr(file, '\\');
- if (filename != NULL) { filename += 1; }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("autostartup[%s]", filename);
- if (filename != NULL/* && strcmp(filename, CMB_LINK_FILE_NAME) == 0*/) {
- CSimpleStringA strfilename(filename);
- if (strfilename.IsStartWith("招商银行可视柜台") && strfilename.IsEndWith(".lnk")) {
- result = TRUE;
- break;
- }
- }
- }
- toolkit_array_free2(arr);
- }
- return result;
- }
- void ResourceWatcherFSM::DetectVersionHasChangedAndWarn()
- {
- CSmartPointer<IConfigInfo> spRunConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- UINT64 utVersion = 0;
- spRunConfig->ReadConfigValueHexInt("VersionMonitor", "LastVer", utVersion);
- CVersion lastVer(utVersion);
- if (lastVer.IsValid() && lastVer > m_RvcSysinfo.InstallVersion) {
- CSimpleStringA rootVerPath;
- CSimpleStringA warnInfo = CSimpleStringA::Format("version changed from %s to %s", lastVer.ToString().GetData(), m_RvcSysinfo.InstallVersion.ToString().GetData());
- GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
- CSimpleStringA csPath = rootVerPath + "\\active.txt";
- if (!ExistsFileA(csPath)) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt not exist!", warnInfo.GetData()));
- }
- else {
- CSimpleFileComponent activeFileInfo;
- HANDLE hFile = CreateFileA(
- csPath,
- GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
- if (hFile == INVALID_HANDLE_VALUE) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt open failed %u", warnInfo.GetData(), GetLastError()));
- }
- else {
- GetFileTime(hFile, (LPFILETIME)&activeFileInfo.mftCreate,
- (LPFILETIME)&activeFileInfo.mftAccess, (LPFILETIME)&activeFileInfo.mftModified);
- CloseHandle(hFile);
- char szFormat1[128] = { 0 };
- GetTimeFormatStr(szFormat1, 128, (FILETIME*)&activeFileInfo.mftCreate);
- char szFormat2[128] = { 0 };
- GetTimeFormatStr(szFormat2, 128, (FILETIME*)&activeFileInfo.mftAccess);
- char szFormat3[128] = { 0 };
- GetTimeFormatStr(szFormat3, 128, (FILETIME*)&activeFileInfo.mftModified);
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format(
- "%s: active.txt create at %s, access at %s, modified at %s", warnInfo.GetData(), szFormat1, szFormat2, szFormat3));
- }
- }
- }
- if (!lastVer.IsValid() || lastVer != m_RvcSysinfo.InstallVersion) {
- spRunConfig->WriteConfigValueHexInt("VersionMonitor", "LastVer", m_RvcSysinfo.InstallVersion.GetVersion64());
- }
- }
- void ResourceWatcherFSM::DetectDestopFileAndWarn(LPCTSTR curUserName)
- {
- CSimpleStringA desktopFullPath = CSimpleStringA::Format("C:\\Users\\%s\\Desktop", curUserName);
- auto arr = fileutil_get_sub_files(desktopFullPath);
- CSimpleStringA filelist(true);
- int dirCount(0), fileCount(0);
- if (arr != NULL) {
- for (int i = 0; i < arr->nelts; ++i) {
- char* file = ARRAY_IDX(arr, i, char*);
- char* filename = strrchr(file, '\\');
- if (filename != NULL) { filename += 1; }
- else { filename = file; }
- fileCount++;
- if (!filelist.IsNullOrEmpty()) {
- filelist += "|";
- }
- filelist += filename;
- }
- toolkit_array_free2(arr);
- }
- filelist += ";";
- arr = fileutil_get_sub_dirs(desktopFullPath);
- if (arr != NULL) {
- for (int i = 0; i < arr->nelts; ++i) {
- char* dir = ARRAY_IDX(arr, i, char*);
- char* dirname = strrchr(dir, '\\');
- if (dirname != NULL) { dirname += 1; }
- else { dirname = dir; }
- dirCount++;
- if (!filelist.IsNullOrEmpty() && i != 0) {
- filelist += "|";
- }
- filelist += dirname;
- }
- toolkit_array_free2(arr);
- }
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_DESKTOP_FILESTATUS, CSimpleStringA::Format(
- "%s's deskop: file(%d),dir(%d), list:(%s)", curUserName, fileCount, dirCount,
- filelist.GetLength() < 950 ? filelist.GetData() : (filelist.SubString(0, 950) + "....").GetData()));
- }
- ErrorCodeEnum ResourceWatcherFSM::DetectVTMInstalledBySetup(BOOL& fYes)
- {
- HKEY key;
- ErrorCodeEnum result(Error_Succeed);
- fYes = FALSE;
- CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{123BBC1D-8555-4E90-96CA-70E678FF5C24}_is1";
- LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
- if (ERROR_SUCCESS == lResult) {
- fYes = TRUE;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_INSTALL_BY_SETUP, "Intalled by Setup");
- }
- else if (ERROR_FILE_NOT_FOUND == lResult) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
- fYes = FALSE;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegOpenKeyEx For{123BBC1D-8555-4E90-96CA-70E678FF5C24} error, Result=%ld.", lResult);
- fYes = FALSE;
- result = Error_Unexpect;
- }
- RegCloseKey(key);
- return result;
- }
- bool ResourceWatcherFSM::RegRdVtmVersion(CSimpleStringA& VTMpath, CSimpleStringA& vtmVersion)
- {
- bool bRet = false;
- HKEY key;
- CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\VTM";
- CSimpleStringA regParaPath = "path";
- CSimpleStringA regParaVersion = "version";
- LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
- char arrVTMpath[MAX_PATH] = { 0 }, arrVTMversion[MAX_PATH] = { 0 };
- if (ERROR_SUCCESS == lResult)
- {
- DWORD dwValue = MAX_PATH * sizeof(CHAR);
- bool res1 = GetRegValue(key, regParaPath, arrVTMpath, &dwValue);
- if (res1) {
- bRet = true;
- VTMpath = arrVTMpath;
- }
- else {
- bRet = false;
- RegCloseKey(key);
- return bRet;
- }
- dwValue = MAX_PATH * sizeof(CHAR);
- bool res2 = GetRegValue(key, regParaVersion, arrVTMversion, &dwValue);
- if (res2) {
- bRet = true;
- vtmVersion = arrVTMversion;
- }
- else {
- bRet = false;
- RegCloseKey(key);
- return bRet;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
- bRet = false;
- }
- RegCloseKey(key);
- return bRet;
- }
- bool ResourceWatcherFSM::RegWtVtmPath()
- {
- bool bRet = true;
- HKEY key;
- CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
- if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
- bRet = false;
- }
- DWORD dwDisposition;
- regPath += "\\VTM";
- if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
- REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
- bRet = false;
- }
- if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
- bRet = false;
- }
- CSimpleStringA para = "path";
- CSimpleStringA exePath;
- ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
- if (Error_Succeed == Error)
- {
- exePath += "\\VTM.exe";
- if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)exePath.GetData(), MAX_PATH))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set path value failed");
- bRet = false;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get path of VTM.exe failed.");
- }
- ::RegCloseKey(key);
- return bRet;
- }
- bool ResourceWatcherFSM::RegWtVtmVersion()
- {
- bool bRet = true;
- HKEY key;
- CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
- if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
- bRet = false;
- }
- DWORD dwDisposition;
- regPath += "\\VTM";
- if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
- REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
- bRet = false;
- }
- if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
- bRet = false;
- }
- CSimpleStringA para = "version";
- CSimpleStringA csVersion;
- if (GetVtmVersion(csVersion))
- {
- //RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH);
- if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
- bRet = false;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get version of VTM.exe failed.");
- }
- ::RegCloseKey(key);
- return bRet;
- }
- bool ResourceWatcherFSM::RegOperation()
- {
- bool bRet = true;
- CSimpleStringA csVersion, VtmRegPath, VtmRegVersion;
- bool bGetActive = GetVtmVersion(csVersion);
- bool bRegRead = RegRdVtmVersion(VtmRegPath, VtmRegVersion);
- CSimpleStringA rootVerPath, exePath;
- ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
- exePath = rootVerPath + "\\VTM.exe";
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("csVersion :%s ,VtmRegVersion:%s ", csVersion.GetData(), VtmRegVersion.GetData());
- if (!ExistsFileA(exePath) || !bGetActive || !bRegRead || (0 != VtmRegVersion.Compare(csVersion, true)))
- {
- if (!CopyExeToRoot())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Copy VTM.exe to version root fail.");
- bRet = false;
- }
- else
- {
- if (!RegWtVtmPath())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmPath failed.");
- }
- if (!RegWtVtmVersion())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmVersion failed.");
- }
- CreateLink(exePath);
- }
- }
- return bRet;
- }
- bool ResourceWatcherFSM::UpdateExe()
- {
- int updateExe = 0;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- spCtSettingConfig->ReadConfigValueInt("NonExclusive", "UpdateExe", updateExe);
- if (updateExe == 1)
- return true;
- return false;
- }
- void ResourceWatcherFSM::VerifySignature()
- {
- LOG_FUNCTION();
- char* buffer = new char[MAX_PATH];
- getcwd(buffer, MAX_PATH);
- strcat(buffer, "\\*");
- DWORD elapsed = 0;
- DWORD dwStart = GetTickCount();
- DWORD dwEnd = GetTickCount();
- VerifySignature(buffer);
- if (m_nonSignedFiles.size() > 0)
- {
- CSimpleStringA fileList = "";
- for (size_t i = 0; i < m_nonSignedFiles.size(); i++)
- {
- fileList += GetFileName(m_nonSignedFiles[i]);
- if (i < m_nonSignedFiles.size() - 1)
- fileList += ",";
- }
- int toDisplay = m_iNonSignedTotal < m_iNonSignedDisplay ? m_iNonSignedTotal : m_iNonSignedDisplay;
- CSimpleStringA strMsg = CSimpleStringA::Format("共有%d个文件未签名,其中%d个为:%s",
- m_iNonSignedTotal, toDisplay, fileList.GetData());
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_FILE_NOT_TRUSTED, (LPCTSTR)strMsg);
- }
- dwEnd = GetTickCount();
- elapsed = dwEnd - dwStart;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Verifying cost:%dms", elapsed);
- delete buffer;
- }
- void ResourceWatcherFSM::VerifySignature(const CSimpleStringA& filePath)
- {
- HANDLE hFind = NULL;
- WIN32_FIND_DATA fileInfo;
- DWORD64 dwSize = 0;
- hFind = FindFirstFile(filePath, &fileInfo);
- if (hFind == INVALID_HANDLE_VALUE)
- return;
- string strDirPath = filePath;
- do
- {
- if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
- {
- if (!strcmp(fileInfo.cFileName, ".") || !strcmp(fileInfo.cFileName, ".."))
- {
- //Do nothing for "." and ".." folders
- }
- else
- {
- strDirPath.insert(strDirPath.find("*"), string(fileInfo.cFileName) + "\\");
- VerifySignature(strDirPath.c_str());
- strDirPath = filePath;
- }
- }
- else
- {
- CSimpleStringA fileName = fileInfo.cFileName;
- string strFileName = fileName;
- string strFilePath;
- if (strFileName.find(".dll") == string::npos && strFileName.find(".exe") == string::npos)
- continue;
- strFilePath = strDirPath;
- strFilePath.replace(strFilePath.find("*"), strFilePath.length(), string(fileInfo.cFileName));
- if (!RetrieveDigitalSignatureInfo(strFilePath.c_str()))
- {
- if (m_iNonSignedTotal < m_iNonSignedDisplay)
- {
- m_nonSignedFiles.push_back(strFilePath.c_str());
- }
- m_iNonSignedTotal++;
- }
- }
- } while (FindNextFile(hFind, &fileInfo));
- FindClose(hFind);
- }
- CSimpleStringA ResourceWatcherFSM::GetFileName(const CSimpleStringA& filePath)
- {
- CSimpleStringA tmp = filePath;
- auto arrPath = tmp.Split('\\');
- int size = arrPath.GetCount();
- return arrPath[size - 1];
- }
- bool ResourceWatcherFSM::RetrieveDigitalSignatureInfo(const char* pFilePath)
- {
- HCERTSTORE hStore = NULL;
- HCRYPTMSG hMsg = NULL;
- WCHAR* wpFilePath = NULL;
- int len = ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, NULL, 0);
- if (len > 0) {
- wpFilePath = new wchar_t[len + 1];
- std::memset(wpFilePath, 0, (len + 1) * sizeof(wchar_t));
- ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, &wpFilePath[0], len);
- }
- if (CryptQueryObject(CERT_QUERY_OBJECT_FILE,
- wpFilePath,
- CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
- CERT_QUERY_FORMAT_FLAG_BINARY,
- 0,
- NULL,
- NULL,
- NULL,
- &hStore,
- &hMsg,
- NULL))
- {
- DWORD dwCountSigners = 0;
- DWORD dwcbSz = sizeof(dwCountSigners);
- if (CryptMsgGetParam(hMsg, CMSG_SIGNER_COUNT_PARAM, 0, &dwCountSigners, &dwcbSz))
- {
- if (dwCountSigners != 0)
- {
- dwcbSz = 0;
- CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwcbSz);
- if (dwcbSz)
- {
- PCMSG_SIGNER_INFO pSignerInfo = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwcbSz];
- if (pSignerInfo)
- {
- DWORD dwcbSz2 = dwcbSz;
- if (CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, pSignerInfo, &dwcbSz) &&
- dwcbSz == dwcbSz2)
- {
- if (VerifyFirstCertificate(hStore, pSignerInfo)
- || VerifyOtherCertificate(pSignerInfo))
- return true;
- }
- delete[] pSignerInfo;
- pSignerInfo = NULL;
- }
- }
- }
- }
- }
- if (hStore != NULL)
- {
- CertCloseStore(hStore, 0);
- hStore = NULL;
- }
- if (hMsg != NULL)
- {
- CryptMsgClose(hMsg);
- hMsg = NULL;
- }
- return false;
- }
- bool ResourceWatcherFSM::VerifyFirstCertificate(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo)
- {
- CERT_INFO ci = { 0 };
- ci.Issuer = pSignerInfo->Issuer;
- ci.SerialNumber = pSignerInfo->SerialNumber;
- PCCERT_CONTEXT pCertContext = NULL;
- int c = 0;
- bool ret = false;
- for (;; c++)
- {
- pCertContext = CertFindCertificateInStore(hStore,
- ENCODING, 0, CERT_FIND_SUBJECT_CERT,
- (PVOID)&ci, pCertContext);
- if (!pCertContext)
- {
- break;
- }
- DWORD dwcbSz;
- char* pBuff;
- dwcbSz = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
- if (dwcbSz != 0)
- {
- pBuff = new (std::nothrow) char[dwcbSz];
- if (pBuff)
- {
- if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, pBuff, dwcbSz) == dwcbSz)
- {
- if (!strcmp(pBuff, "China Merchants Bank Co., Ltd"))
- ret = true;
- }
- delete[] pBuff;
- pBuff = NULL;
- }
- }
- }
- if (pCertContext)
- {
- CertFreeCertificateContext(pCertContext);
- pCertContext = NULL;
- }
- return ret;
- }
- bool ResourceWatcherFSM::VerifyOtherCertificate(PCMSG_SIGNER_INFO pSignerInfo)
- {
- int ret = false;
- for (DWORD a = 0; a < pSignerInfo->UnauthAttrs.cAttr; a++)
- {
- #ifndef szOID_NESTED_SIGNATURE
- #define szOID_NESTED_SIGNATURE "1.3.6.1.4.1.311.2.4.1"
- #endif
- if (pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId &&
- lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId, szOID_NESTED_SIGNATURE) == 0)
- {
- HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, 0, NULL, NULL, NULL);
- if (hMsg)
- {
- if (::CryptMsgUpdate(hMsg,
- pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData,
- pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData,
- TRUE))
- {
- DWORD dwSignerInfo = 0;
- ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
- if (dwSignerInfo != 0)
- {
- PCMSG_SIGNER_INFO pSignerInfo2 = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwSignerInfo];
- if (pSignerInfo2)
- {
- if (::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM,
- 0, (PVOID)pSignerInfo2, &dwSignerInfo))
- {
- CRYPT_DATA_BLOB c7Data;
- c7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData;
- c7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData;
- //ret = FindAppropriateStoreAndVerifyFirstCertificate(pSignerInfo2, &c7Data);
- HCERTSTORE hStore = NULL;
- hStore = CertOpenStore(CERT_STORE_PROV_PKCS7, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, &c7Data);
- ret = hStore && VerifyFirstCertificate(hStore, pSignerInfo2);
- if (hStore)
- {
- ::CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
- hStore = NULL;
- }
- }
- delete[] pSignerInfo2;
- pSignerInfo2 = NULL;
- }
- }
- }
- ::CryptMsgClose(hMsg);
- }
- }
- }
- return ret;
- }
- void ResourceWatcherFSM::DeleteFiles()
- {
- string p;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- CSimpleStringA upPath(""), tempPath(""), tPath(""), upgradePath("");
- spCtSettingConfig->ReadConfigValue("ResourceWatcher", "DocumentCleanPath", tempPath);
- if (tempPath.GetLength() == 0)
- {
- return;
- }
- //if (tempPath != CSimpleStringA("Temp") && tempPath != CSimpleStringA("Upgraded")) //目前只支持temp文件夹 和 upgrade文件夹
- //{
- // DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Illegal file path [%s].", tempPath.GetData());
- // return;
- //}
- ErrorCodeEnum erroCode = Error_Succeed;
- CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfigRun;
- //判断是否需要被清理
- erroCode = pFunc->OpenConfig(Config_Run, spConfigRun);
- if (erroCode != Error_Succeed)
- {
- LogWarn(Severity_Middle, erroCode, 0, "Open Run Config failed");
- return;
- }
- int nLastTaskTime = 0;
- int nLstFlag = 0;
- CSimpleStringA optFileName("");
- UINT64 utVersion = 0;
- spConfigRun->ReadConfigValueHexInt("DeleteDocumentTask", "OptVer", utVersion);
- spConfigRun->ReadConfigValue("DeleteDocumentTask", "DocumentName", optFileName);
- spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
- spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastTime", nLastTaskTime);
- CVersion optVer(utVersion);
- SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
- stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
- stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
- (LPCTSTR)optVer.ToString(), nLstFlag);
- SYSTEMTIME stNow = {};
- GetLocalTime(&stNow);
- if (optVer.IsValid() && optVer == m_RvcSysinfo.InstallVersion && !nLstFlag && optFileName == tempPath)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Certain document cleaning has been done before.");
- return;
- }
- //这里进行过滤处理,最终获取可以清理的路径
- //GetEntityBase()->GetFunction()->GetPath(tempPath.GetData(), upPath);
- //删除upPath目录下的文件
- struct _finddata_t upfileinfo;
- long upFile = 0;
- bool bFailFlag = false;
- WIN32_FIND_DATA wfd;
- HANDLE hFind;
- upPath = tempPath;
- upPath.Append("\\*");
- hFind = FindFirstFile(upPath.GetData(), &wfd);
- if (hFind != INVALID_HANDLE_VALUE)
- {
- if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
- {
- //upPath.Append("\\*");
- //char szPath[256] = { 0 };
- //strcat_s(szPath, upPath.GetData());
- int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
- //nFileCount = ProcessFileDelete(szPath, nDelSuc, nDelFail);
- nFileCount = ProcessFileDelete(upPath.GetData(), nDelSuc, nDelFail);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Process result(%s): count(%d), suc(%d), failed(%d).", upPath.GetData(), nFileCount, nDelSuc, nDelFail);
- if (nDelFail != 0)
- {
- bFailFlag = true;
- //break;
- }
- FindClose(hFind);
- }
- else
- {
- if (DeleteFile(tempPath.GetData()) != 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("删除文件%s成功。", tempPath.GetData());
- //break;
- }
- else
- {
- bFailFlag = true;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("删除文件%s失败。", tempPath.GetData());
- }
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM) ("FindFirstFile failed (%u)", GetLastError());
- }
- nLstFlag = bFailFlag ? 1 : 0;
- spConfigRun->WriteConfigValueHexInt("DeleteDocumentTask", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
- spConfigRun->WriteConfigValue("DeleteDocumentTask", "DocumentName", tempPath);
- spConfigRun->WriteConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
- spConfigRun->WriteConfigValue("DeleteDocumentTask", "LastTime",
- (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
- if (!bFailFlag)
- {
- //std::string warn = "Delete [%s] success.";
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_DIR_DELETE, CSimpleStringA::Format("Delete files in [%s] success", tempPath.GetData()));
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete files in [%s] failed.", tempPath.GetData());
- }
- }
- void ResourceWatcherFSM::ShowTerminalStatusPage()
- {
- ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
- ErrorCodeEnum error = chromiumClient->Connect();
- if (error == Error_Succeed)
- {
- ChromiumSrv_OpenBrowser_Req req;
- ChromiumSrv_OpenBrowser_Ans ans;
- int width = GetSystemMetrics(0);
- auto pFunc = GetEntityBase()->GetFunction();
- CSimpleStringA strPath, statusPagePath, fileStart;
- fileStart = "file:///";
- pFunc->GetPath("Bin", strPath);
- strPath += "\\Chromium\\cefclient.exe";
- pFunc->GetPath("Bin", statusPagePath);
- statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\showStatus.html";
- statusPagePath = fileStart + statusPagePath;
- if (!terminalShowFlag)
- {
- /*CSimpleStringA setting = CSimpleStringA::Format(" --center-size=%d*35 --src-pos=%d*0 --top=-1 --logextend=test", width / 5, width - (width / 5));
- CSimpleStringA cmdLine = strPath + " --url=file:///" + statusPagePath + setting;
- WinExec(cmdLine.GetData(), SW_MINIMIZE);*/
- req.mainUrl = statusPagePath;
- req.type = "SpecialPageFromOtherEntity";
- req.name = "terminalStatus";
- req.param1 = CSimpleStringA::Format("%d*35", width / 5);
- req.param2 = CSimpleStringA::Format("%d*0", width - (width / 5));
- req.top = -1;
- error = chromiumClient->OpenBrowser(req, ans, 10000);
- chromiumClient->GetFunction()->CloseSession();
- ::SetCursorPos(0, 0);
- mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
- if (error != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] failed.", statusPagePath.GetData());
- }
- else
- {
- terminalShowFlag = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] success.", statusPagePath.GetData());
- }
- }
- }
- }
- void ResourceWatcherFSM::CloseTerminalStatusPage()
- {
- auto pFunc = GetEntityBase()->GetFunction();
- CSimpleStringA strPath, statusPagePath;
- pFunc->GetPath("Bin", strPath);
- strPath += "\\Chromium\\cefclient.exe";
- ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
- ErrorCodeEnum error = chromiumClient->Connect();
- if (error == Error_Succeed)
- {
- ChromiumSrv_CloseBrowser_Req req;
- ChromiumSrv_CloseBrowser_Ans ans;
- if (terminalShowFlag)
- {
- //CSimpleStringA setting = "--logextend=test";
- //CSimpleStringA cmdLine = strPath + " --kill " + setting;
- //WinExec(cmdLine.GetData(), SW_MINIMIZE);
- req.type = "SpecialPageFromOtherEntity";
- req.name = "terminalStatus";
- error = chromiumClient->CloseBrowser(req, ans, 10000);
- if (error != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [terminalStatus] failed.");
- }
- else
- {
- terminalShowFlag = false;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [terminalStatus] success.");
- }
- }
- }
- }
- void ResourceWatcherFSM::GetBatteryStatus() //0: 默认,电池状态和电量变化时广播, 1:每次调用都广播 2:关闭广播功能
- {
- /*
- ACLineStatus: Byte; {0:电源断电; 1:电源正常; 255:电源状态未知}
- BatteryFlag: Byte; {1:电量充足 >66%; 2:电量低 <33%; 4:电池基本耗尽 <5%; 8:充电; 128:没有电池; 255:电池状态未知}
- 如果出现9的状态,则表示充电中+电量大于66%(8+1);
- 如果不给充电,且电池电量介于高电量和低电量之间,则该值为0;
- 如果在33%~%66%之间,且充电,则为8(0+8)。
- 如果在5% ~ 33%之间,且充电,则为10 (2+8)
- 如果在0% ~ 5%之间,且充电,则为……
- BatteryLifePercent: Byte; {0..100:所剩电量百分数; 255:未知}
- Reserved1: Byte; {保留, 须为 0}
- BatteryLifeTime: DWORD; {电池剩余能量; -1 表示未知}
- BatteryFullLifeTime: DWORD; {电池总能量; -1 表示未知}*/
- SYSTEM_POWER_STATUS powerStatus;
- GetSystemPowerStatus(&powerStatus);
- BatteryStatus batteryStatus;
- CSimpleStringA btFlag; //powerStatus.BatteryFlag;
- CSimpleStringA btPercent; // powerStatus.BatteryLifePercent;
- CSimpleStringA acStatus;
- batteryStatus.status = powerStatus.ACLineStatus;
- batteryStatus.reversed1 = powerStatus.BatteryLifePercent;
- if ((powerStatus.ACLineStatus != lastACLineStatus) || (powerStatus.BatteryLifePercent != lastBatteryPercent))
- {
- lastACLineStatus = powerStatus.ACLineStatus;
- lastBatteryPercent = powerStatus.BatteryLifePercent;
- SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(BatteryStatus), SP_MSG_SIG_OF(BatteryStatus), batteryStatus);
- }
- }
- ErrorCodeEnum ResourceWatcherFSM::CheckBatteryStatus(
- SpReqAnsContext<ResourceWatcherService_CheckBatteryStatus_Req, ResourceWatcherService_CheckBatteryStatus_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- ErrorCodeEnum ec = Error_Succeed;
- SYSTEM_POWER_STATUS powerStatus;
- GetSystemPowerStatus(&powerStatus);
- ctx->Ans.status = powerStatus.ACLineStatus;
- ctx->Ans.percent = powerStatus.BatteryLifePercent;
- if (ctx != NULL) {
- ctx->Answer(ec);
- }
- return ec;
- }
- void ResourceWatcherFSM::ClearDumpFiles()
- {
- int deleteSucCnt = 0;
- int deleteFailedCnt = 0;
- int fileCnt = 0;
- CSimpleStringA dmpPath;
- ErrorCodeEnum dmpError = GetEntityBase()->GetFunction()->GetPath("Temp", dmpPath);
- if (Error_Succeed != dmpError) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get Dump path error");
- return;
- }
- dmpPath += CSimpleStringA::Format("\\..\\dmp");
- // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
- char searchFilePath[MAX_PATH] = { 0 };
- char tempFilePath[MAX_PATH] = { 0 };
- char displayTime[MAX_PATH] = { 0 };
- WIN32_FIND_DATA foundFileData;
- HANDLE hFind;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- int backDay = 0;
- ErrorCodeEnum re = spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "DumpClearBackDay", backDay);
- if (backDay < 7 || backDay >365 || re != Error_Succeed)
- {
- backDay = 7; //保留至少七天的dump文件
- }
- FILETIME ftRemoveTime;
- CalculateBackTime(&ftRemoveTime, backDay);
- GetTimeString(displayTime, MAX_PATH, &ftRemoveTime);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("The date DUMPFILE backward to delete: %s", displayTime);
- string p;
- hFind = FindFirstFile(p.assign(string(dmpPath.GetData())).append("\\*").c_str(), &foundFileData);
- if (hFind != INVALID_HANDLE_VALUE) {
- do {
- if (CSimpleStringA::Format("%s", &foundFileData.cFileName) == "." || CSimpleStringA::Format("%s", &foundFileData.cFileName) == "..")
- {
- continue;
- }
- if (CompareFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0)
- {
- GetTimeString(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
- //strcpy_s(searchFilePath, (dmpPath + CSimpleStringA::Format("\\%s", &foundFileData.cFileName)).GetData());
- if (DeleteFile((dmpPath + CSimpleStringA::Format("\\%s", &foundFileData.cFileName)).GetData()) != 0)
- {
- deleteSucCnt++;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete DUMPFILE matched %s(%s) suc.", foundFileData.cFileName, displayTime);
- }
- else
- {
- deleteFailedCnt++;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete DUMPFILE matched %s(%s) failed(%d).", foundFileData.cFileName, displayTime, GetLastError());
- }
- }
- fileCnt++;
- } while (FindNextFile(hFind, &foundFileData));
- FindClose(hFind);
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM) ("FindFirstFile failed (%u)", GetLastError());
- return;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Total [%d] dump files, delete suc[%d], failed[%d].", fileCnt, deleteSucCnt, deleteFailedCnt);
- return;
- }
- void ResourceWatcherFSM::FsmCreateWindow(CSimpleStringA text, int txtsize, int delayMS, int txtx, int txty)
- {
- //if (GetHWnd() != NULL)
- //{
- // //closegraph();
- // CloseWindow(GetHWnd());
- // closegraph();
- // return;
- //}
- //initgraph(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), 0);
- //HWND hwnd = GetHWnd();
- //::SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & (~(WS_CAPTION | WS_SYSMENU | WS_SIZEBOX)));
- //::SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) & (~(WS_EX_WINDOWEDGE | WS_EX_DLGMODALFRAME)) | WS_EX_LAYERED | WS_EX_TOOLWINDOW);
- ///*SetWindowPos(hwnd, HWND_TOPMOST, (GetSystemMetrics(SM_CXSCREEN) - getwidth()) / 2, (GetSystemMetrics(SM_CYSCREEN) - getheight()) / 2, getwidth(), getheight(), SWP_SHOWWINDOW
- // | SWP_FRAMECHANGED | SWP_DRAWFRAME);*/
- //SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_SHOWWINDOW
- // | SWP_FRAMECHANGED | SWP_DRAWFRAME);
- //SetLayeredWindowAttributes(hwnd, 0x000000, 0, LWA_COLORKEY);
- //setcolor(RGB(0, 0, 1)); //黑色
- //setbkcolor(RGB(255, 240, 192)); //背景色
- ////line(0, 0, 800, 600);
- ////std::string time = "abc";
- ////const char* a = time.c_str();
- //LOGFONT f;
- //gettextstyle(&f); // 获取当前字体设置
- //f.lfHeight = txtsize; // 设置字体高度;
- //_tcscpy(f.lfFaceName, _T("黑体")); // 设置字体为“黑体”(高版本 VC 推荐使用 _tcscpy_s 函数)
- //f.lfQuality = ANTIALIASED_QUALITY; // 设置输出效果为抗锯齿
- //settextstyle(&f);
- //int width = textwidth(text.GetData());
- //int height = textheight(text.GetData());
- //if (txtx < 0 || txty < 0)
- //{
- // outtextxy((GetSystemMetrics(SM_CXSCREEN) - width) / 2, (GetSystemMetrics(SM_CYSCREEN) - height) / 2, text.GetData());
- //}
- //else
- //{
- // outtextxy(txtx, txty, text.GetData());
- //}
- //if(delayMS > 0)
- //{
- // Sleep(delayMS);
- // CloseWindow(GetHWnd());
- // closegraph();
- //}
- ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
- ErrorCodeEnum error = chromiumClient->Connect();
- if (error == Error_Succeed)
- {
- ChromiumSrv_OpenBrowser_Req req;
- ChromiumSrv_OpenBrowser_Ans ans;
- int width = GetSystemMetrics(0);
- auto pFunc = GetEntityBase()->GetFunction();
- CSimpleStringA strPath, statusPagePath, fileStart;
- fileStart = "file:///";
- pFunc->GetPath("Bin", strPath);
- strPath += "\\Chromium\\cefclient.exe";
- pFunc->GetPath("Bin", statusPagePath);
- if (text == "软件升级安装中,请稍等……")
- {
- statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\installMessage.html";
- req.param1 = CSimpleStringA::Format("750*80");
- }
- else if (text == "升级完成,可视柜台即将重启,请稍等……")
- {
- statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\restartMessage.html";
- req.param1 = CSimpleStringA::Format("1100*80");
- }
- //statusPagePath += "\\..\\res\\ManagerDesktop\\H5Page\\installMessage.html";
- statusPagePath = fileStart + statusPagePath;
- req.mainUrl = statusPagePath;
- req.type = "SpecialPageFromOtherEntity";
- req.name = "tempMessage";
- //req.param1 = CSimpleStringA::Format("1000*70");
- //req.param2 = CSimpleStringA::Format("%d*0", width - (width / 5));
- req.top = -1;
- error = chromiumClient->OpenBrowser(req, ans, 10000);
- chromiumClient->GetFunction()->CloseSession();
- ::SetCursorPos(0, 0);
- mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
- if (error != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] failed.", statusPagePath.GetData());
- }
- else
- {
- tmpMessageWindFlag = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Start chromium page [%s] success.", statusPagePath.GetData());
- }
- }
- if (delayMS > 0)
- {
- Sleep(delayMS);
- ChromiumSrv_ClientBase* chromiumClient = new ChromiumSrv_ClientBase(GetEntityBase());
- ErrorCodeEnum error = chromiumClient->Connect();
- if (error == Error_Succeed)
- {
- ChromiumSrv_CloseBrowser_Req req;
- ChromiumSrv_CloseBrowser_Ans ans;
- req.type = "SpecialPageFromOtherEntity";
- req.name = "tempMessage";
- error = chromiumClient->CloseBrowser(req, ans, 10000);
- /*auto pFunc = GetEntityBase()->GetFunction();
- CSimpleStringA strPath, statusPagePath;
- pFunc->GetPath("Bin", strPath);
- strPath += "\\Chromium\\cefclient.exe --kill --logextend=tempMessage";
- WinExec(strPath.GetData(), SW_MINIMIZE);
- ::SetCursorPos(0, 0);
- mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);*/
- if (error != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [tempMessage] failed.");
- }
- else
- {
- tmpMessageWindFlag = false;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close chromium page [tempMessage] success.");
- }
- }
- }
- }
- #endif // _MSC_VER 截止到创建弹窗
- #ifdef _MSC_VER //硬件资源监控相关系统功能 CPU、内存、硬盘、网络wifi
- long long GetDirSizeFsm(string dirPath)
- {
- long long fileLen = 0;
- long hFile = 0;
- //文件信息
- struct _finddata_t fileinfo;
- string p;
- if ((hFile = _findfirst(p.assign(dirPath).append("\\*").c_str(), &fileinfo)) != -1)
- {
- do
- {
- //如果是目录,迭代之
- //如果不是,加入列表
- if ((fileinfo.attrib & _A_SUBDIR))
- {
- if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
- fileLen += GetDirSizeFsm(p.assign(dirPath).append("\\").append(fileinfo.name));
- }
- else
- {
- fileLen += fileinfo.size;
- }
- } while (_findnext(hFile, &fileinfo) == 0);
- _findclose(hFile);
- }
- return fileLen;
- }
- struct CmpByValueFromBiggest //从最大的排起
- {
- bool operator()(const pair<string, long>& l, const pair<string, long>& r) {
- return l.second > r.second;
- }
- };
- //unordered_map<string, long> fileSpace;
- unordered_map<string, long> fileIncreasedSpace;
- vector<pair<string, long>> sortFileIncreasedSpace;
- unordered_map<string, long> fileSpace;
- vector<pair<string, long>> sortFileSpace;
- static bool spaceLock = false;
- void ResourceWatcherFSM::CheckDiskFileSpace()
- {
- if (spaceLock)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("当前已有硬盘扫描进行中,跳过。");
- return;
- }
- else
- {
- spaceLock = true; //加锁
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- int lastDiskUsed = 0;
- unsigned long long lastVer = 0;
- int spaceIncrease = 0; //硬盘增长阈值
- spConfigRun->ReadConfigValueHexInt("SpaceInfo", "OptVer", lastVer);
- spConfigRun->ReadConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", lastDiskUsed);
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "DiskUsedIncreaseInt(GB)", spaceIncrease);
- if (spaceIncrease == 0)
- {
- spaceIncrease = 5; //默认阈值5GB
- }
- if (!isNeedForceDiskCheck) //是否需要强制全盘扫描 - 硬盘使用过高是会强制
- {
- if (lastVer == m_RvcSysinfo.InstallVersion.GetVersion64())
- {
- if (lastDiskUsed != 0 && ((int)(GetDiskUsedByte() / (1024 * 1024 * 1024)) - lastDiskUsed) < spaceIncrease) //增长值判定
- {
- //DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("硬盘空间增长未超过阈值,无需扫描。");
- if (spaceLock)
- {
- spaceLock = false; //释放锁
- }
- return;
- }
- else
- {
- //降低磁盘扫描频率
- SYSTEMTIME localTime;
- GetLocalTime(&localTime);
- if (m_diskLastWarnHour != localTime.wHour)
- {
- m_diskLastWarnHour = localTime.wHour;
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr == Error_Succeed) {
- spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
- }
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("硬盘增长超过阈值,重点目录扫描!");
- }
- else
- {
- //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("磁盘增长最近1小时已扫描一次,暂不扫描。");
- if (spaceLock)
- {
- spaceLock = false; //释放锁
- }
- return;
- }
- }
- }
- else
- {
- spConfigRun->WriteConfigValueHexInt("SpaceInfo", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("新版本,重点目录扫描");
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("强制扫描。");
- }
- CSystemStaticInfo sysInfo;
- string path("");
- GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
- if (sysInfo.strMachineType == "RVC.PAD")
- {
- path = "C:";
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("pad设备。扫描C盘。");
- }
- else
- {
- path = "D:";
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("非pad设备。扫描D盘。");
- }
- if (path.size() == 0)
- {
- if (spaceLock)
- {
- spaceLock = false; //释放锁
- }
- return;
- }
- long long fileLen = 0;
- long hFile = 0;
- //文件信息
- struct _finddata_t fileinfo;
- string p;
- if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
- {
- do
- {
- //如果是目录,迭代之
- //如果不是,加入列表
- if ((fileinfo.attrib & _A_SUBDIR))
- {
- if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
- fileLen = GetDirSizeFsm(p.assign(path).append("\\").append(fileinfo.name));
- else
- {
- continue;
- }
- }
- else
- {
- fileLen = fileinfo.size;
- }
- CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
- if (fileLen >= 1024 && fileLen < (1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / 1024;
- resLen = CSimpleStringA::Format("%.2f KB", len);
- }
- else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
- resLen = CSimpleStringA::Format("%.2f MB", len);
- }
- else if (fileLen >= (1024 * 1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
- resLen = CSimpleStringA::Format("%.2f GB", len);
- }
- CSimpleStringA oldLenStr("");
- long oldLen = 0;
- spConfigRun->ReadConfigValue("SpaceInfo",
- p.assign(path).append("\\").append(fileinfo.name).c_str(), oldLenStr);
- oldLen = atol(oldLenStr.GetData());
- fileIncreasedSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
- fileSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
- p.assign(path).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
- if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
- {
- spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\").append(fileinfo.name).c_str(),
- CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
- }
- } while (_findnext(hFile, &fileinfo) == 0);
- _findclose(hFile);
- }
- //获取version目录下的文件夹大小
- CSimpleStringA csPath;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
- fileLen = 0;
- hFile = 0;
- p = "";
- if ((hFile = _findfirst(p.assign(csPath.GetData()).append("\\*").c_str(), &fileinfo)) != -1)
- {
- do
- {
- //如果是目录,迭代之
- //如果不是,加入列表
- if ((fileinfo.attrib & _A_SUBDIR))
- {
- if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
- fileLen = GetDirSizeFsm(p.assign(csPath.GetData()).append("\\").append(fileinfo.name));
- else
- {
- continue;
- }
- }
- else
- {
- fileLen = fileinfo.size;
- }
- CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
- if (fileLen >= 1024 && fileLen < (1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / 1024;
- resLen = CSimpleStringA::Format("%.2f KB", len);
- }
- else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
- resLen = CSimpleStringA::Format("%.2f MB", len);
- }
- else if (fileLen >= (1024 * 1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
- resLen = CSimpleStringA::Format("%.2f GB", len);
- }
- CSimpleStringA oldLenStr(""); //MB
- long oldLen = 0;
- spConfigRun->ReadConfigValue("SpaceInfo",
- p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), oldLenStr);
- oldLen = atol(oldLenStr.GetData());
- fileIncreasedSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
- fileSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
- p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
- if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
- {
- spConfigRun->WriteConfigValue("SpaceInfo", p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(),
- CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
- }
- } while (_findnext(hFile, &fileinfo) == 0);
- _findclose(hFile);
- }
- //获取rvc目录下的文件夹大小
- fileLen = 0;
- hFile = 0;
- p = "";
- if ((hFile = _findfirst(p.assign(path).append("\\rvc\\*").c_str(), &fileinfo)) != -1)
- {
- do
- {
- //如果是目录,迭代之
- //如果不是,加入列表
- if ((fileinfo.attrib & _A_SUBDIR))
- {
- if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
- fileLen = GetDirSizeFsm(p.assign(path).append("\\rvc\\").append(fileinfo.name));
- else
- {
- continue;
- }
- }
- else
- {
- fileLen = fileinfo.size;
- }
- CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
- if (fileLen >= 1024 && fileLen < (1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / 1024;
- resLen = CSimpleStringA::Format("%.2f KB", len);
- }
- else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
- resLen = CSimpleStringA::Format("%.2f MB", len);
- }
- else if (fileLen >= (1024 * 1024 * 1024))
- {
- DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
- resLen = CSimpleStringA::Format("%.2f GB", len);
- }
- CSimpleStringA oldLenStr("");
- long oldLen = 0;
- spConfigRun->ReadConfigValue("SpaceInfo",
- p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), oldLenStr);
- oldLen = atol(oldLenStr.GetData());
- fileIncreasedSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
- fileSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
- p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), resLen.GetData());
- if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
- {
- spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(),
- CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
- }
- } while (_findnext(hFile, &fileinfo) == 0);
- _findclose(hFile);
- }
- if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
- {
- //写入硬盘量
- spConfigRun->WriteConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", GetDiskUsedByte() / (1024 * 1024 * 1024));
- if (spaceLock)
- {
- spaceLock = false; //释放锁
- }
- return; //新版本无需上报文件信息,更新完运行时文件后即可结束
- }
- //获取增量最大的前十文件夹信息
- sortFileIncreasedSpace = vector<pair<string, long>>(fileIncreasedSpace.begin(), fileIncreasedSpace.end());
- sort(sortFileIncreasedSpace.begin(), sortFileIncreasedSpace.end(), CmpByValueFromBiggest());
- int topFileNum = sortFileIncreasedSpace.size();
- if (topFileNum > 10)
- {
- topFileNum = 10;
- }
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("变化最大的%d个文件夹信息。", topFileNum);
- fileLen = 0;
- for (int i = 0; i < topFileNum; i++)
- {
- fileLen = sortFileIncreasedSpace[i].second;
- if (fileLen == 0) break;
- //Dbg("TOP %d: [%s], 增量[%ld]MB", i + 1, sortFileIncreasedSpace[i].first.c_str(), sortFileIncreasedSpace[i].second);
- CSimpleStringA warn1 = CSimpleStringA::Format("TOP %d: [%s], 增量[%ld]MB",
- i + 1, sortFileIncreasedSpace[i].first.c_str(), sortFileIncreasedSpace[i].second);
- LogWarn(Severity_Middle, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPINCREASED_SPACE, warn1.GetData());
- }
- if (isNeedForceDiskCheck)
- {
- //获取空间占用最大前十文件夹信息
- sortFileSpace = vector<pair<string, long>>(fileSpace.begin(), fileSpace.end());
- sort(sortFileSpace.begin(), sortFileSpace.end(), CmpByValueFromBiggest());
- int topFileSize = sortFileSpace.size();
- if (topFileSize > 10)
- {
- topFileSize = 10;
- }
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("空间占用最大的%d个文件夹信息。", topFileSize);
- fileLen = 0;
- for (int i = 0; i < topFileSize; i++)
- {
- fileLen = sortFileSpace[i].second;
- if (fileLen == 0) break;
- //Dbg("空间占用排名 %d: [%s], 大小[%ld]MB", i + 1, sortFileSpace[i].first.c_str(), sortFileSpace[i].second);
- CSimpleStringA warn2 = CSimpleStringA::Format("空间占用排名 %d: [%s], 大小[%ld]MB",
- i + 1, sortFileSpace[i].first.c_str(), sortFileSpace[i].second);
- LogWarn(Severity_Middle, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warn2.GetData());
- }
- isNeedForceDiskCheck = false;
- }
- if (spaceLock)
- {
- spaceLock = false; //释放锁
- }
- }
- void ResourceWatcherFSM::GetSystemDiskStatus()
- {
- ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
- BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
- if (ret == 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
- return;
- }
- CSimpleStringA csBinPath;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
- //Dbg("%d,%d,%d",(ulAvailFree.QuadPart/MILLION)*100,ulTotalBytes.QuadPart,(ulTotalBytes.QuadPart/MILLION));
- DWORD dwAvFree = ulAvailFree.QuadPart / MILLION;
- DWORD dwTotal = ulTotalBytes.QuadPart / MILLION;
- DWORD dwTotalFree = ulTotalFree.QuadPart / MILLION;
- int ratio = dwTotalFree * 100 / dwTotal;
- if (m_diskHighPercent <= 0)
- {
- m_diskHighPercent = 90; //默认硬盘告警百分比90%
- }
- if ((100 - ratio) > m_diskHighPercent)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("The disk has %d MB(%d%%) available.\n", dwTotalFree, ratio);
- string test(csBinPath.GetData());
- char diskMessage[1024];
- sprintf(diskMessage, "{\"Disk\":\"%c:\",\"total\":\"%0.2f GByte\",\"free ratio\":\"%d%%\"}",
- csBinPath.GetData()[0], (double)dwTotal / 1024, ratio);
- //oilyang@20200526 根据wq建议,降低磁盘空间偏少的告警频率
- SYSTEMTIME localTime;
- GetLocalTime(&localTime);
- if (m_diskLastWarnHour != localTime.wHour) //需要告警时才强制全盘扫描
- {
- m_diskLastWarnHour = localTime.wHour;
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr == Error_Succeed) {
- spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
- }
- //LogWarn(Severity_Low, Error_Resource, LOG_EVT_SELFCHECK_HARDDISK_TOO_HIGH, "Harddisk free space is few.");
- LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, diskMessage);
- isNeedForceDiskCheck = true;
- }
- }
- else
- {
- isNeedForceDiskCheck = false;
- }
- CheckDiskFileSpaceTask* task4 = new CheckDiskFileSpaceTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task4);
- }
- ULONGLONG ResourceWatcherFSM::GetDiskUsedByte()
- {
- ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
- BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
- if (ret == 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
- return -1;
- }
- CSimpleStringA csBinPath;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
- //Dbg("%lld,%lld,%lld",ulAvailFree.QuadPart,ulTotalBytes.QuadPart, ulTotalFree.QuadPart);
- //DWORD dwAvFree = ulAvailFree.QuadPart / MILLION;
- //DWORD dwTotal = ulTotalBytes.QuadPart / MILLION;
- //DWORD dwTotalFree = ulTotalFree.QuadPart / MILLION;
- //int ratio = dwTotalFree * 100 / dwTotal;
- return ulTotalBytes.QuadPart - ulTotalFree.QuadPart;
- }
- __int64 Filetime2Int64(const FILETIME& ftime)
- {
- LARGE_INTEGER li;
- li.LowPart = ftime.dwLowDateTime;
- li.HighPart = ftime.dwHighDateTime;
- return li.QuadPart;
- }
- __int64 CompareFileTime2(const FILETIME& preTime, const FILETIME& nowTime)
- {
- return Filetime2Int64(nowTime) - Filetime2Int64(preTime);
- }
- unordered_map<int, long long> oldProcessTime;
- unordered_map<int, long long> newProcessTime;
- unordered_map<int, CSimpleStringA> processName;
- unordered_map<int, double> processCpu;
- bool cmp(const pair<int, double>& a, const pair<int, double>& b) {
- return a.second > b.second;
- }
- void ResourceWatcherFSM::GetSystemCPUStatus()
- {
- FILETIME preIdleTime;
- FILETIME preKernelTime;
- FILETIME preUserTime;
- FILETIME preProcCreateTime;
- FILETIME preProcExitTime;
- FILETIME preProcKernelTime;
- FILETIME preProcUserTime;
- GetSystemTimes(&preIdleTime, &preKernelTime, &preUserTime);
- PROCESSENTRY32 pe32Old;
- pe32Old.dwSize = sizeof(pe32Old);
- //获得系统进程快照的句柄
- HANDLE hProcessSnapOld = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- if (hProcessSnapOld == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
- return;
- }
- //首先获得第一个进程
- BOOL bProcessOld = Process32First(hProcessSnapOld, &pe32Old);
- //循环获得所有进程
- while (bProcessOld)
- {
- //进程名和进程ID
- HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32Old.th32ProcessID);
- GetProcessTimes(hProcess, &preProcCreateTime, &preProcExitTime, &preProcKernelTime, &preProcUserTime);
- oldProcessTime[pe32Old.th32ProcessID] = Filetime2Int64(preProcKernelTime) + Filetime2Int64(preProcUserTime);
- bProcessOld = Process32Next(hProcessSnapOld, &pe32Old);
- }
- CloseHandle(hProcessSnapOld);
- Sleep(1000);
- FILETIME idleTime;
- FILETIME kernelTime;
- FILETIME userTime;
- FILETIME ProcCreateTime;
- FILETIME ProcExitTime;
- FILETIME procKernelTime;
- FILETIME procUserTime;
- GetSystemTimes(&idleTime, &kernelTime, &userTime);
- PROCESSENTRY32 pe32New;
- pe32New.dwSize = sizeof(pe32New);
- //获得系统进程快照的句柄
- HANDLE hProcessSnapNew = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- if (hProcessSnapNew == INVALID_HANDLE_VALUE)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
- return;
- }
- //首先获得第一个进程
- BOOL bProcessNew = Process32First(hProcessSnapNew, &pe32New);
- //循环获得所有进程
- while (bProcessNew)
- {
- //进程名和进程ID
- HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32New.th32ProcessID);
- GetProcessTimes(hProcess, &ProcCreateTime, &ProcExitTime, &procKernelTime, &procUserTime);
- newProcessTime[pe32New.th32ProcessID] = Filetime2Int64(procKernelTime) + Filetime2Int64(procUserTime);
- processName[pe32New.th32ProcessID] = CSimpleStringA(pe32New.szExeFile);
- bProcessNew = Process32Next(hProcessSnapNew, &pe32New);
- }
- CloseHandle(hProcessSnapNew);
- auto idle = CompareFileTime2(preIdleTime, idleTime);
- auto kernel = CompareFileTime2(preKernelTime, kernelTime);
- auto user = CompareFileTime2(preUserTime, userTime);
- if (kernel + user == 0)
- return;
- CSystemRunInfo runInfo = { 0 };
- GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
- for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
- {
- runInfo.strRunningEntityNames[i];
- CEntityRunInfo entityInfo = { 0 };
- GetEntityBase()->GetFunction()->GetEntityRunInfo(runInfo.strRunningEntityNames[i].GetData(), entityInfo);
- processName[entityInfo.dwProcessID] = runInfo.strRunningEntityNames[i];
- }
- unordered_map<int, long long>::iterator it;
- for (it = newProcessTime.begin(); it != newProcessTime.end(); ++it)
- {
- int tPid = it->first;
- //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
- if (oldProcessTime.find(tPid) == oldProcessTime.end())
- {
- continue;
- }
- double tRatio = 100.0 * (newProcessTime[tPid] - oldProcessTime[tPid]) / (kernel + user);
- if (tRatio > 0.0)
- {
- processCpu[tPid] = tRatio;
- //Dbg("process[%s] CPU[%.2f].", processName[tPid].GetData(), tRatio);
- }
- }
- vector<pair<int, double>> vec(processCpu.begin(), processCpu.end());
- sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
- int len = min(10, vec.size());
- CSimpleStringA procWarn = "";
- for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
- {
- procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.2f", vec[i].second) + "%\"";
- }
- double cpuRatio = 100.0 * (kernel + user - idle) / (kernel + user);
- //Dbg("total CPU[%.2f].", cpuRatio);
- if (m_cpuHighPercent <= 0)
- {
- m_cpuHighPercent = 80; //默认告警百分比80%
- }
- if (cpuRatio > (double)m_cpuHighPercent)
- {
- CSimpleStringA warn = CSimpleStringA::Format("{ \"total_used\":\" %.2f", cpuRatio);
- warn = warn + "%\"" + procWarn + "}";
- LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, warn.GetData());
- }
- }
- unsigned long long convert_time_format(const FILETIME* ftime)
- {
- LARGE_INTEGER li;
- li.LowPart = ftime->dwLowDateTime;
- li.HighPart = ftime->dwHighDateTime;
- return li.QuadPart;
- }
- /// 时间转换
- static uint64_t file_time_2_utc(const FILETIME* ftime)
- {
- LARGE_INTEGER li;
- li.LowPart = ftime->dwLowDateTime;
- li.HighPart = ftime->dwHighDateTime;
- return li.QuadPart;
- }
- /// 获得CPU的核数
- static int get_processor_number()
- {
- SYSTEM_INFO info;
- GetSystemInfo(&info);
- return (int)info.dwNumberOfProcessors;
- }
- int ResourceWatcherFSM::GetCpuUsageRatio(int pid)
- {
- //cpu数量
- static int processor_count_ = -1;
- //上一次的时间
- static int64_t last_time_ = 0;
- static int64_t last_system_time_ = 0;
- FILETIME now;
- FILETIME creation_time;
- FILETIME exit_time;
- FILETIME kernel_time;
- FILETIME user_time;
- int64_t system_time;
- int64_t time;
- int64_t system_time_delta;
- int64_t time_delta;
- int cpu = -1;
- if (processor_count_ == -1)
- {
- processor_count_ = get_processor_number();
- }
- GetSystemTimeAsFileTime(&now);
- HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
- if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
- {
- return -1;
- }
- system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time))
- / processor_count_;
- time = file_time_2_utc(&now);
- if ((last_system_time_ == 0) || (last_time_ == 0))
- {
- last_system_time_ = system_time;
- last_time_ = time;
- return -1;
- }
- system_time_delta = system_time - last_system_time_;
- time_delta = time - last_time_;
- if (time_delta == 0)
- return -1;
- cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta);
- last_system_time_ = system_time;
- last_time_ = time;
- return cpu;
- }
- double GetMemoryUsageGB(int pid)
- {
- #ifdef WIN32
- DWORDLONG mem = 0, vmem = 0;
- PROCESS_MEMORY_COUNTERS pmc;
- // get process hanlde by pid
- HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
- if (GetProcessMemoryInfo(process, &pmc, sizeof(pmc)))
- {
- mem = pmc.WorkingSetSize;
- vmem = pmc.PagefileUsage;
- }
- CloseHandle(process);
- // use GetCurrentProcess() can get current process and no need to close handle
- // convert mem from B to GB
- double memGB = mem / (1024.0 * 1024.0 * 1024.0);
- return memGB;
- #else
- char file_name[64] = { 0 };
- FILE* fd;
- char line_buff[512] = { 0 };
- sprintf(file_name, "/proc/%d/status", pid);
- fd = fopen(file_name, "r");
- if (nullptr == fd)
- return 0;
- char name[64];
- int vmrss = 0;
- for (int i = 0; i < VMRSS_LINE - 1; i++)
- fgets(line_buff, sizeof(line_buff), fd);
- fgets(line_buff, sizeof(line_buff), fd);
- sscanf(line_buff, "%s %d", name, &vmrss);
- fclose(fd);
- // cnvert VmRSS from KB to MB
- return vmrss / 1024.0;
- #endif
- }
- unordered_map<int, double> processMem;
- void ResourceWatcherFSM::GetSystemMemoryStatus()
- {
- // Use to convert bytes to KB
- #define DIV 1024
- // Specify the width of the field in which to print the numbers.
- // The asterisk in the format specifier "%*I64d" takes an integer
- // argument and uses it to pad and right justify the number.
- #define WIDTH 7
- MEMORYSTATUSEX statex;
- statex.dwLength = sizeof(statex);
- GlobalMemoryStatusEx(&statex);
- double totalMem = statex.ullTotalPhys / (1024.0 * 1024.0 * 1024.0); //GB
- unordered_map<int, CSimpleStringA>::iterator it;
- for (it = processName.begin(); it != processName.end(); ++it)
- {
- int tPid = it->first;
- double tmp = GetMemoryUsageGB(it->first);
- if (tmp > 0.0)
- {
- processMem[tPid] = 100 * (tmp / totalMem);
- }
- }
- //return;
- vector<pair<int, double>> vec(processMem.begin(), processMem.end());
- sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
- int len = min(10, vec.size());
- CSimpleStringA procWarn = "";
- for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
- {
- procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.1f", vec[i].second) + "%\"";
- }
- if (m_memHighPercent <= 0)
- {
- m_memHighPercent = 80; //默认告警百分比80%
- }
- if (statex.dwMemoryLoad > m_memHighPercent)
- {
- CSimpleStringA warn = CSimpleStringA::Format("{\"total\":\"%.1f GByte\",\"total_used\":\" %d%%\"", totalMem, statex.dwMemoryLoad);
- warn = warn + procWarn + "}";
- LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, warn.GetData());
- }
- }
- int ResourceWatcherFSM::IsWifiConnected()
- {
- DWORD service_ver;
- HANDLE handle = NULL;
- int result = -1;
- DWORD err = WlanOpenHandle(WLAN_API_VERSION, NULL, &service_ver, &handle);
- if (err != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("open wlan handle failed %d", err);
- return result;
- }
- PWLAN_INTERFACE_INFO_LIST info_list = NULL;
- PWLAN_INTERFACE_INFO interface_info = NULL;
- err = WlanEnumInterfaces(handle, NULL, &info_list);
- if (err != ERROR_SUCCESS) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Enum wlan interface failed %d", err);
- WlanCloseHandle(handle, NULL);
- return -1;
- }
- const int count = info_list->dwNumberOfItems;
- for (int i = 0; i < count; ++i) {
- interface_info = &info_list->InterfaceInfo[i];
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("wireless interface name: %s", SP::Module::Util::W2S(interface_info->strInterfaceDescription).c_str());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("state: %d", interface_info->isState);
- if (interface_info->isState == wlan_interface_state_connected) {
- result = 1;
- }
- DWORD radio_state_info_size = sizeof(WLAN_RADIO_STATE);
- PWLAN_RADIO_STATE radio_state_info_ptr = NULL;
- WLAN_OPCODE_VALUE_TYPE op_code = wlan_opcode_value_type_invalid;
- err = WlanQueryInterface(handle, &interface_info->InterfaceGuid, wlan_intf_opcode_radio_state,
- NULL, &radio_state_info_size, (PVOID*)&radio_state_info_ptr, &op_code);
- if (err != ERROR_SUCCESS) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("WlanQueryInterface failed %d", err);
- }
- else {
- const uint32_t count_of_phys = radio_state_info_ptr->dwNumberOfPhys;
- //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of valid PHYs: %d", count_of_phys);
- if (count_of_phys > 0 && result == -1) {
- if (dot11_radio_state_on == radio_state_info_ptr->PhyRadioState[0].dot11SoftwareRadioState) {
- result = 0;
- }
- else {
- /*
- for (int j = 0; j < count_of_phys; ++j) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("software radio state: %d, %d", j , radio_state_info_ptr->PhyRadioState[j].dot11SoftwareRadioState);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("hardware radio state: %d, %d", j, radio_state_info_ptr->PhyRadioState[j].dot11HardwareRadioState);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("**********************");
- }
- */
- }
- }
- }
- }
- if (info_list != NULL) {
- WlanFreeMemory(info_list);
- }
- WlanCloseHandle(handle, NULL);
- return result;
- }
- #endif // _MSC_VER end硬件资源监控相关系统功能 CPU、内存、硬盘、网络wifi
- ErrorCodeEnum ResourceWatcherFSM::CatchSystemBasicInfo(SystemBasicInfo& info)
- {
- CSimpleStringA runCfgPath;
- ErrorCodeEnum errCode = GetEntityBase()->GetFunction()->GetPath("RunCfg", runCfgPath);
- if (runCfgPath.IsNullOrEmpty()) return Error_Null;
- CSimpleStringA storeFilePath = runCfgPath + SPLIT_SLASH_STR + "SMBIOSData.txt";
- if (!ExistsFileA(storeFilePath)) {
- RemoveFileA(storeFilePath);
- }
- std::string succStr, errStr;
- std::string runStr("dmidecode -t system > ");
- runStr += storeFilePath.GetData();
- if (!SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("execute '%s' failed!", runStr.c_str());
- if (!ExistsFileA(storeFilePath)) {
- RemoveFileA(storeFilePath);
- }
- return Error_Unexpect;
- }
- do
- {
- std::string succStr, errStr;
- std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Manufacturer\"){print$2}' ");
- runStr += storeFilePath.GetData();
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- info.strManufacturer = SP::Utility::ToTrim(succStr).c_str();
- } else {
- succStr = "";
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Manufacturer' failed!");
- }
- } while (false);
- do {
- std::string succStr, errStr;
- std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Product Name\"){print$2}' ");
- runStr += storeFilePath.GetData();
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- info.strProductName = SP::Utility::ToTrim(succStr).c_str();
- } else {
- succStr = "";
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Product Name' failed!");
- }
- } while (false);
- do {
- std::string succStr, errStr;
- std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Serial Number\"){print$2}' ");
- runStr += storeFilePath.GetData();
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- info.strSerialNumber = SP::Utility::ToTrim(succStr).c_str();
- } else {
- succStr = "";
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Serial Number' failed!");
- }
- } while (false);
- if (!ExistsFileA(storeFilePath)) {
- RemoveFileA(storeFilePath);
- }
- return Error_Succeed;
-
- }
- void ResourceWatcherFSM::AlarmSystemBasicInfo()
- {
- SystemBasicInfo info;
- if (Error_Succeed == CatchSystemBasicInfo(info)) {
- CSimpleStringA strResult("{");
- if (!info.strManufacturer.IsNullOrEmpty()) {
- strResult += CSimpleStringA::Format("\"Manufacturer\":\"%s\"", info.strManufacturer.GetData());
- }
- if (!info.strProductName.IsNullOrEmpty()) {
- if (strResult.GetLength() > 1) {
- strResult += ", ";
- }
- strResult += CSimpleStringA::Format("\"Product Name\":\"%s\"", info.strProductName.GetData());
- }
- if (!info.strSerialNumber.IsNullOrEmpty()) {
- if (strResult.GetLength() > 1) {
- strResult += ", ";
- }
- strResult += CSimpleStringA::Format("\"Serial Number\":\"%s\"", info.strSerialNumber.GetData());
- }
- strResult += "}";
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_DEVICE_SMBIOS_GET, strResult);
- }
- }
- #ifdef RVC_OS_LINUX
- void ResourceWatcherFSM::UploadMonitorSettings()
- {
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- int nSwitchOff(0);
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenOFF", nSwitchOff);
- if (!!nSwitchOff) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Cancel monitor change listen!");
- if (m_bFirstRunAfterBoot) {
- CSimpleStringA value(true);
- bool res = GetMonitorInfo(value);
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
- }
- } else {
- int nInterval(10000);
- int nValue(0);
- spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenInterval", nValue);
- if (nValue >= 10000) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Update monitor listen interval from %d to %d", nInterval, nValue);
- nInterval = nValue;
- }
- CSimpleStringA strLastMonitor(true);
- bool readFromCfgFalg(true);
- CSmartPointer<IConfigInfo> spRunConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- spRunConfig->ReadConfigValue("MonitorAttribute", "LastInfo", strLastMonitor);
- do
- {
- CSimpleStringA value(true);
- bool res = GetMonitorInfo(value);
- if (!value.IsNullOrEmpty() && (strLastMonitor.IsNullOrEmpty() || (strLastMonitor.Compare(value) != 0))) {
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
- CSmartPointer<IConfigInfo> spRunConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
- spRunConfig->WriteConfigValue("MonitorAttribute", "LastInfo", value);
- strLastMonitor = value;
- if (readFromCfgFalg) {
- readFromCfgFalg = false;
- }
- } else if (readFromCfgFalg && !strLastMonitor.IsNullOrEmpty() && strLastMonitor.Compare(value) == 0) {
- LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
- readFromCfgFalg = false;
- }
- Sleep(nInterval);
- } while (true);
- }
- }
- void ResourceWatcherFSM::DetectSoftwareInstallStatus()
- {
- CSmartPointer<IConfigInfo> spCtSettingConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
- CSimpleStringA strSoftwaresNames[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
- CSimpleStringA strSoftwaresVers[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
- int nNameCounts = 0;
- for (int i = 0; i < MAX_SOFTWARE_INSTALLED_DETECT_COUNT; i++) {
- strSoftwaresNames[i] = "";
- strSoftwaresVers[i] = "";
- CSimpleStringA item = CSimpleStringA::Format("SoftwareInstallDetect%d", i);
- CSimpleStringA value(true);
- spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), item, value);
- if (value.IsNullOrEmpty()) {
- break;
- }
- if (value.IndexOf("#") != -1) {
- CAutoArray<CSimpleStringA> items = value.Split('#');
- strSoftwaresNames[i] = items[0];
- strSoftwaresVers[i] = items[1];
- } else {
- strSoftwaresNames[i] = value;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect SoftDetect from CentralSetting, %d: %s,%s,%s."
- , i, item.GetData(), strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData());
- nNameCounts++;
- }
- if (nNameCounts > 0) {
- for (int i = 0; i < nNameCounts; ++i) {
- CSimpleStringA runItem = CSimpleStringA::Format("dpkg -l | grep %s | awk '{print $3}'", strSoftwaresNames[i].GetData());
- std::string additional("");
- std::string succStr, errStr;
- std::string runStr(runItem.GetData());
- if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
- if (succStr.empty()) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i,
- CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"not installed\"}", strSoftwaresNames[i].GetData()));
- } else {
- succStr = SP::Utility::ToTrim(succStr);
- if (strSoftwaresVers[i].IsNullOrEmpty() || strSoftwaresVers[i].Compare(succStr.c_str()) == 0) {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_BASE + i,
- CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\"}"
- , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData()));
- } else {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i,
- CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\", \"expected\":\"%s\"}"
- , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData()));
- }
- }
- } else {
- LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_STATUS_FAILED,
- CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"detect failed\", \"expected\":\"%s\"}"
- , strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData()));
- }
- }
- }
- }
- BOOL ResourceWatcherFSM::DetectIsFirstRunAtBoot()
- {
- CSystemRunInfo runInfo = { 0 };
- GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
- BOOL bSet = FALSE;
- CBootInfo bootInfo = { 0 };
- CSmallDateTime dateTime;
- Dbg("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
- ErrorCodeEnum erroCode = GetEntityBase()->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
- Dbg("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
- CSmallDateTime systemBootTime;
- BOOL bRet = GetSystemBootTime(systemBootTime);
- if (bRet && systemBootTime > bootInfo.tmStart) {
- ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
- if (eRet != Error_Succeed) {
- Dbg("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
- }
- bSet = TRUE;
- std::map<std::string, std::string> srcData;
- srcData.insert(std::make_pair("OSStartTime", systemBootTime.ToTimeString().GetData()));
- srcData.insert(std::make_pair("AppStartTime", (LPCTSTR)runInfo.tmStart.ToTimeString()));
- srcData.insert(std::make_pair("AppLastStartTime", (LPCTSTR)bootInfo.tmStart.ToTimeString()));
- auto ret = generateJsonStr(srcData);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT, ret.second.c_str());
- }
- else {
- GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
- bSet = FALSE;
- }
- return bSet;
- }
- UINT ResourceWatcherFSM::GetSystemDisplayVersion(CSimpleStringA& strVersion)
- {
- UINT result = 0;
- const char filePath[] = "/etc/os-version";
- strVersion.Clear();
- char tmp[33];
- memset(tmp, 0, 33);
- inifile_read_str_s("Version", "MajorVersion", "unknown", tmp, 32, filePath);
- strVersion = tmp;
- strVersion += ".";
- memset(tmp, 0, 33);
- inifile_read_str_s("Version", "MinorVersion", "unknown", tmp, 32, filePath);
- strVersion += tmp;
- strVersion += ".";
- result = atoi(tmp);
- memset(tmp, 0, 33);
- inifile_read_str_s("Version", "OsBuild", "unknown", tmp, 32, filePath);
- strVersion += tmp;
- return result;
- }
- void ResourceWatcherFSM::UploadSysVersionInfo(UINT& ver)
- {
- std::map<std::string, std::string> srcData;
- CSimpleStringA osver;
- ver = GetSystemDisplayVersion(osver);
- srcData.insert(std::make_pair("os-version", osver)); ////当前操作系统版本(系统信息)
- tk_utsname_t t;
- osutil_uname(&t);
- srcData.insert(std::make_pair("sysname", t.sysname)); ////当前操作系统名
- srcData.insert(std::make_pair("release", t.release)); ////当前发布级别
- srcData.insert(std::make_pair("version", t.version)); ////当前发布版本
- srcData.insert(std::make_pair("machine", t.machine)); ////当前硬件体系类型
- do {
- std::string sucContent, failedContent;
- std::string cmd("cat /proc/cpuinfo |grep \"model name\" | awk 'NR==1'");
- bool ret = SP::Module::Util::ShellExecute(cmd, sucContent, failedContent);
- Dbg("{%s}:{%s}{%s}", cmd.c_str(), sucContent.c_str(), failedContent.c_str());
- //std::size_t found = sucContent.rfind("\n");
- //if (found != std::string::npos) {
- // sucContent.replace(found, strlen("\n"), "");
- //}
- auto elems = SP::Utility::Split(sucContent, ':');
- if (elems.size() > 1) {
- sucContent = SP::Utility::ToTrim(elems[1]);
- }
- srcData.insert(std::make_pair("cpu-type", sucContent));
- } while (false);
- //#if defined(RVC_OS_LINUX)
- // CSystemStaticInfo sysInfo;
- // ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
- // if (eErr == Error_Succeed) {
- // termInfo["MachineMode"] = (LPCTSTR)sysInfo.strMachineModel;
- // termInfo["MachineSN"] = (LPCTSTR)sysInfo.strMachineSN;
- // }
- //#endif //RVC_OS_LINUX
- auto ret = generateJsonStr(srcData);
- LogWarn(Severity_Low, Error_Hardware, LOG_RESOURCEWATCHER_SYSTEMINFO, ret.second.c_str());
- }
- string ResourceWatcherFSM::MemoryProcessStatus()
- {
- CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum erroCode = Error_Unexpect;
- ///*TODO: 不要每次都进来读取配置文件 (80374374@5/17/2023)*/
- spFunction->OpenConfig(Config_CenterSetting, spConfig);
- int memTop = 0;
- erroCode = spConfig->ReadConfigValueInt("TOPProcess", "mem", memTop);
- if (memTop == 0) {
- memTop = 10;
- } else if (memTop == -1) {
- return "";
- }
- map<string, string> nameProcess;
- CSystemRunInfo runInfo = { 0 };
- GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
- for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++)
- {
- string entityName = runInfo.strRunningEntityNames[i].GetData();
- CEntityRunInfo entityInfo = { 0 };
- GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
- nameProcess[to_string(entityInfo.dwProcessID)] = entityName;
- }
- FILE* fp;
- char buffer[2048];
- string cmd = "ps c -eo pid,%mem,rss,command | sort -k3 -rn | head -" + to_string(memTop);
- fp = popen(cmd.c_str(), "r");
- int i = 0;
- string s;
- string str[4];
- //mem
- Dbg("MEM TOP %d PROCESS!", memTop);
- string topMessage = "";
- while (i < memTop)
- {
- fgets(buffer, sizeof(buffer), fp);
- s = buffer;
- istringstream is(s);
- is >> str[0] >> str[1] >> str[2] >> str[3];
- double temp;
- stringstream ss1;
- ss1 << str[2];
- ss1 >> temp;
- temp = temp / (1024 * 1024);
- stringstream ss2;
- ss2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << temp;
- str[2] = ss2.str();
- if (nameProcess.find(str[0]) != nameProcess.end())
- {
- str[3] = nameProcess[str[0]];
- }
- topMessage = topMessage + "\"" + str[3] + "\"" + ":" + "\"" + str[1] + "%\"";
-
- if (i != memTop - 1)
- {
- topMessage += ",";
- }
- ++i;
- }
- topMessage += "}";
- pclose(fp);
- return topMessage;
- }
- long ResourceWatcherFSM::GetCPURunTime(CPUInfo* cpu) //获取CPU的当前信息,同时返回CPU使用时间
- {
- FILE* fd;
- char buff[1024] = { 0 };
- CPUInfo* cpuInfo = cpu;
- fd = fopen("/proc/stat", "r");
- if (!fd) {
- Dbg("Read CPU Info FAILED!");
- return -1;
- }
- fgets(buff, sizeof(buff), fd);
- char name[64] = { 0 };
- sscanf(buff, "%s %u %u %u %u %u %u %u",
- cpuInfo->name, &cpuInfo->user, &cpuInfo->nice, &cpuInfo->system, &cpuInfo->idle, &cpuInfo->lowait, &cpuInfo->irq, &cpuInfo->softirq);
- fclose(fd);
- return (cpuInfo->user + cpuInfo->nice + cpuInfo->system + cpuInfo->idle + cpuInfo->lowait + cpuInfo->irq + cpuInfo->softirq);
- }
- long ResourceWatcherFSM::ReadProcCPURunTime(DWORD pid, ProcCPUInfo* pInfo) { //根据pid读取进程占用的CPU时间
- char file_name[64] = { 0 };
- FILE* fd;
- char line_buff[1024] = { 0 };
- sprintf(file_name, "/proc/%d/stat", pid);
- fd = fopen(file_name, "r");
- if (nullptr == fd) {
- Dbg("Read PROCESS[%d] CPU Info FAILED!", pid);
- return -1;
- }
- fgets(line_buff, sizeof(line_buff), fd);
- sscanf(line_buff, "%u %s", &pInfo->pid, pInfo->pname);
- const char* q = GetItems(line_buff, PROCESS_ITEM);
- sscanf(q, "%ld %ld %ld %ld", &pInfo->utime, &pInfo->stime, &pInfo->cutime, &pInfo->cstime);
- fclose(fd);
- return (pInfo->utime + pInfo->stime + pInfo->cutime + pInfo->cstime);
- }
- //获取第N项开始的指针
- const char* ResourceWatcherFSM::GetItems(const char* buffer, unsigned int item) {
- const char* p = buffer;
- int len = strlen(buffer);
- int count = 0;
- for (int i = 0; i < len; i++) {
- if (' ' == *p) {
- count++;
- if (count == item - 1) {
- p++;
- break;
- }
- }
- p++;
- }
- return p;
- }
- bool cmp(const pair<DWORD, DOUBLE>& a, const pair<DWORD, DOUBLE>& b) {
- return a.second > b.second;
- }
- /* -----------------------
- 根据先后两个时间的CPU信息,
- 计算CPU的总占用量和各个进程的占用量
- ----------------------- */
- void ResourceWatcherFSM::GetSystemCPUStatus()
- {
- //int cpu_num = sysconf(_SC_NPROCESSORS_CONF); //CPU核数
- CPUInfo* cpuOld = new CPUInfo;
- CPUInfo* cpuNew = new CPUInfo;
- const char* tPath = "/proc";
- map<DWORD, string> nameProcess; // <pid, 进程名>
- map<DWORD, DOUBLE> usageProcess; // <pid, CPU占用率>
- long oldTotalTime = GetCPURunTime(cpuOld); //旧CPU运行总时间
- if (oldTotalTime == -1)
- {
- return;
- }
- map<DWORD, long> oldProcCPUTime; // <pid, 旧时刻进程的CPU占用时间>
- struct dirent* oldDirp;
- DIR* oldDp = opendir(tPath);
- if (oldDp != NULL) {
- while ((oldDirp = readdir(oldDp)) != NULL) { //获取旧时刻 每一个进程的pid、CPU运行时间、进程名
- string fileName = oldDirp->d_name;
- BOOL isPid = TRUE;
- for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
- {
- if (!isdigit(fileName[i]))
- {
- isPid = FALSE;
- break;
- }
- }
- if (!isPid) continue;
- DWORD pid;
- long oldTime;
- ProcCPUInfo* oldProcCPU = new ProcCPUInfo;
- sscanf(oldDirp->d_name, "%d", &pid); //读取文件夹名
- oldTime = ReadProcCPURunTime(pid, oldProcCPU);
- if (oldTime == -1)
- {
- return;
- }
- oldProcCPUTime[pid] = oldTime;
- nameProcess[pid] = oldProcCPU->pname;
- delete oldProcCPU;
- }
- closedir(oldDp);
- }
- sleep(1);
- long newTotalTime = GetCPURunTime(cpuNew); //新CPU运行总时间
- if (newTotalTime == -1)
- {
- return;
- }
- map<DWORD, long> newProcCPUTime; // <pid, 新时刻进程的CPU占用时间>
- struct dirent* newDirp;
- DIR* newDp = opendir(tPath);
- if (newDp != NULL) {
- while ((newDirp = readdir(newDp)) != NULL) { //获取新时刻 每一个进程的pid、CPU运行时间、进程名
- string fileName = newDirp->d_name;
- BOOL isPid = TRUE;
- for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
- {
- if (!isdigit(fileName[i]))
- {
- isPid = FALSE;
- break;
- }
- }
- if (!isPid) continue;
- DWORD pid;
- long newTime;
- ProcCPUInfo* newProcCPU = new ProcCPUInfo;
- sscanf(newDirp->d_name, "%d", &pid); //读取文件夹名
- newTime = ReadProcCPURunTime(pid, newProcCPU);
- if (newTime == -1)
- {
- return;
- }
- newProcCPUTime[pid] = newTime;
- string tName = newProcCPU->pname;
- tName.erase(tName.begin());
- tName.erase(tName.begin() + (tName.length() - 1));
- nameProcess[pid] = tName;
- delete newProcCPU;
- }
- closedir(newDp);
- }
- map<DWORD, long>::iterator it;
- for (it = newProcCPUTime.begin(); it != newProcCPUTime.end(); ++it)
- {
- DWORD tPid = it->first;
- //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
- DOUBLE tRatio = 100.0 * (newProcCPUTime[tPid] - oldProcCPUTime[tPid]) / (newTotalTime - oldTotalTime);
- usageProcess[tPid] = tRatio;
- }
- CSystemRunInfo runInfo = { 0 };
- GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
- for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
- {
- string entityName = runInfo.strRunningEntityNames[i].GetData();
- CEntityRunInfo entityInfo = { 0 };
- GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
- nameProcess[entityInfo.dwProcessID] = entityName;
- }
- vector<pair<DWORD, DOUBLE>> vec(usageProcess.begin(), usageProcess.end());
- sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
- int len = MIN(cpuTop, vec.size());
- Dbg("CPU TOP %d PROCESS!", len);
- string procWarn = "";
- for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
- {
- char* tUsage = new char[20];
- sprintf(tUsage, "%.2lf", vec[i].second);
- procWarn = procWarn + ",\"" + nameProcess[vec[i].first] + "\":\"" + string(tUsage) + "%\"";
- delete tUsage;
- }
- unsigned long oldInfo, newInfo;
- double cUsedRate = 0;
- //第一次(用户+优先级+系统+空闲)的时间
- //oldInfo = (unsigned long)(cpuOld->user + cpuOld->nice + cpuOld->system + cpuOld->idle + cpuOld->lowait + cpuOld->irq + cpuOld->softirq);
- //第二次(用户+优先级+系统+空闲)的时间
- //newInfo = (unsigned long)(cpuNew->user + cpuNew->nice + cpuNew->system + cpuNew->idle + cpuNew->lowait + cpuNew->irq + cpuNew->softirq);
- double totalTime = newTotalTime - oldTotalTime;
- double freeTime = cpuNew->idle - cpuOld->idle;
- cUsedRate = (totalTime - freeTime) / totalTime;
- if (cUsedRate < 0.8) {
- //Dbg("[CPU] used rate: %.1lf%%.", cUsedRate * 100);
- }
- else {
- stringstream tss;
- tss << std::setiosflags(std::ios::fixed) << std::setprecision(2) << cUsedRate * 100;
- string warn = "{ \"total_used\":\"" + tss.str() + "%\"" + procWarn + "}";
- //Dbg("%s", warn.c_str());
- LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
- }
- delete cpuNew;
- delete cpuOld;
- }
- void ResourceWatcherFSM::GetSystemMemoryStatus()
- {
- MemInfo* memInfo = new MemInfo();
- FILE* fd;
- char buff[256];
- fd = fopen("/proc/meminfo", "r");
- if (!fd) {
- Dbg("Read Memory INFO FAILED!");
- return;
- }
- fgets(buff, sizeof(buff), fd);
- sscanf(buff, "%s %lu ", memInfo->infoName1, &memInfo->memTotal);
- fgets(buff, sizeof(buff), fd);
- sscanf(buff, "%s %lu ", memInfo->infoName2, &memInfo->memFree);
- fgets(buff, sizeof(buff), fd);
- sscanf(buff, "%s %lu ", memInfo->infoName3, &memInfo->memAvail);
- fclose(fd);
- double mUsedRate = 0;
- mUsedRate = (double)(memInfo->memTotal - memInfo->memAvail) / (double)memInfo->memTotal;
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
- char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(szResult, (double)(memInfo->memTotal) * 1024, 'G'); // 内存信息在 /proc/meminfo 中的单位为 KB
- ByteSprintf(szResult2, (double)(memInfo->memFree) * 1024, 'G');
- ByteSprintf(szResult3, (double)(memInfo->memAvail) * 1024, 'G');
- if (mUsedRate < 0.8) {
- //Dbg("[Memory] total: %s, free: %s, available: %s, [Memory] used rate: %.1lf%%.", szResult, szResult2, szResult3, mUsedRate * 100);
- }
- else {
- /*LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH,
- CSimpleStringA::Format("MEMORY TOO HIGH! -- [Memory] total: %s, free: %s, available: %s, [Memory] used rate: %.1lf%%.",
- szResult, szResult2, szResult3, mUsedRate * 100)
- );*/
- char usedResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- ByteSprintf(usedResult, (double)(memInfo->memTotal) * 1024 * mUsedRate, 'G');
- stringstream ss1;
- ss1 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << mUsedRate * 100;
- string warn = "{ \"total\":\"" + string(szResult) + "\"," +
- "\"used\":\"" + ss1.str() + "%\"," + MemoryProcessStatus();
- Dbg("%s", warn.c_str());
- LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
- }
- }
- void ResourceWatcherFSM::GetDiskStatusFrom(LPCTSTR path)
- {
- unsigned long long uiTotalBytes;
- unsigned long long uiFreeDiskBytes;
- char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
- char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
- BOOL readFlag = DiskInfo::GetDiskSpace(path, uiTotalBytes, uiFreeDiskBytes);
- double dUsedRate = 1 - (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
- ByteSprintf(szResult, (double)uiTotalBytes);
- ByteSprintf(szResult2, (double)uiFreeDiskBytes);
- if (readFlag && (dUsedRate < 0.9)) {
- //Dbg("[Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.", path, szResult, szResult2, dUsedRate * 100);
- }
- else {
- std::time_t now = std::time(nullptr);
- std::tm* local_time = std::localtime(&now);
- if (m_diskLastWarnHour != local_time->tm_hour)
- {
- m_diskLastWarnHour = local_time->tm_hour;
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if (eErr == Error_Succeed) {
- spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
- }
- LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH,
- CSimpleStringA::Format("DISK TOO HIGH! -- [Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.",
- path, szResult, szResult2, dUsedRate * 100));
- }
- }
- }
- void ResourceWatcherFSM::GetSystemDiskStatus()
- {
- GetDiskStatusFrom("/");
- }
- void ResourceWatcherFSM::GetOperationDiskStatus()
- {
- GetDiskStatusFrom(m_csUploadVideoPath);
- }
- void ResourceWatcherFSM::switchWindowsEffect(const char* cfgFilePath, bool enable)
- {
- char tmp[33];
- memset(tmp, 0, 33);
- inifile_read_str_s("Compositing", "Enabled", "", tmp, 32, cfgFilePath);
- if (strlen(tmp) == 0 || stricmp(tmp, "false") == 0) {
- if (enable) {
- inifile_write_str(cfgFilePath, "Compositing", "Enabled", "true");
- LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_ON, "to active window effect");
- }
- }
- else if (stricmp(tmp, "true") == 0) {
- if (!enable) {
- inifile_write_str(cfgFilePath, "Compositing", "Enabled", "false");
- LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_OFF, "to inactive window effect");
- }
- }
- }
- BOOL ResourceWatcherFSM::readDNSConfigFile(CSimpleStringA& result)
- {
- std::string succStr, errStr;
- if (SP::Module::Util::ShellExecute("cat /etc/resolv.conf", succStr, errStr)) {
- result = succStr.c_str();
- return TRUE;
- }
- else {
- return FALSE;
- }
- }
- void ResourceWatcherFSM::RecoverDDEClipboardEnable()
- {
- const std::string clipboardPath = "/usr/bin/dde-clipboard";
- const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
- if (!ExistsFileA(clipboardPath.c_str()) && ExistsFileA(clipboardPathBak.c_str())) {
- fileutil_copy_file(clipboardPath.c_str(), clipboardPathBak.c_str());
- //fileutil_delete_file(clipboardPathBak.c_str());
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_CLIPBOARD_RECOVER_ENABLE, "recover clipboard succ.");
- }
- else {
- Dbg("%s exists.", clipboardPath.c_str());
- }
- }
- void ResourceWatcherFSM::ConfirmDDEClipboardDisable()
- {
- const std::string clipboardPath = "/usr/bin/dde-clipboard";
- const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
- char* clipboards[] = { "dde-clipboard", "dde-clipboardloader" };
- if (!ExistsFileA(clipboardPath.c_str())) {
- Dbg("There are no any %s files.", clipboardPath.c_str());
- if (ExistsFileA(clipboardPathBak.c_str())) {
- Dbg("%s exists.", clipboardPathBak.c_str());
- }
- return;
- }
- if (0 != fileutil_copy_file(clipboardPathBak.c_str(), clipboardPath.c_str())) {
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove clipboard failed");
- }
- else {
- fileutil_delete_file(clipboardPath.c_str());
- osutil_terminate_related_process(clipboards, array_size(clipboards));
- LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_SUCC, "remove clipboard succ.");
- }
- }
- void ResourceWatcherFSM::ConfirmNotificationCenterDisable()
- {
- const char* osd_file_path = "/usr/lib/deepin-daemon/dde-osd";
- const char* osd_bak_file_path = "/usr/lib/deepin-daemon/dde-osd.bak";
- CSmartPointer<IConfigInfo> spConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Cache, spConfig);
- int flag = 0;
- spConfig->ReadConfigValueInt("UOSFeatures", "NotifyCenterSupport", flag);
- if (flag == 1) {
- Dbg("allow the dde-osd process alive.");
- if (!ExistsFileA(osd_file_path) && ExistsFileA(osd_bak_file_path)) {
- fileutil_copy_file(osd_file_path, osd_bak_file_path);
- LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_OSD_RECOVER_ENABLE, "recover dde osd succ.");
- }
- }
- else {
- if (ExistsFileA(osd_file_path) && !ExistsFileA(osd_bak_file_path)) {
- char* relates[] = { "dde-osd" };
- if (0 != fileutil_copy_file(osd_bak_file_path, osd_file_path)) {
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove dde osd failed");
- }
- else {
- osutil_terminate_related_process(relates, array_size(relates));
- fileutil_delete_file(osd_file_path);
- LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_OSD_REMOVE_SUCC, "remove dde osd succ.");
- }
- }
- }
- }
- BOOL ResourceWatcherFSM::SetLocalDNSWithResolv(LPCTSTR dns1, LPCTSTR dns2)
- {
- const char* dnsPath = "/etc/resolv.conf";
- const int res = access(dnsPath, W_OK);
- if (res == 0) {
- CSimpleStringA timeStamp = CSmallDateTime::GetNow().ToTimeString();
- FILE* resolv = fopen(dnsPath, "w+");
- int state = fprintf(resolv, "#Update by VTM %s\nnameserver %s\nnameserver %s\n", timeStamp.GetData(), dns1, dns2);
- fclose(resolv);
- if (state < 0) {
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_FAILED,
- CSimpleStringA::Format("update dns config for %s|%s failed: err: %d", dns1, dns2, errno));
- return FALSE;
- }
- else {
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_SUCC,
- CSimpleStringA::Format("update dns with resolv for %s|%s succ!", dns1, dns2));
- return TRUE;
- }
- }
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_FAILED,
- CSimpleStringA::Format("access dns with resolv failed err: %d, rc:%d", errno, res));
- return FALSE;
- }
- /** 在厂商机器查看了信息,不能以这里面的内容为准 [Gifur@2021910]*/
- BOOL ResourceWatcherFSM::SetLocalDNSWithNetworkManager(LPCTSTR dns1, LPCTSTR dns2)
- {
- BOOL result = FALSE;
- const char* connectDirPath = "/etc/NetworkManager/system-connections";
- array_header_t* arr;
- arr = fileutil_get_sub_files_a(connectDirPath);
- if (arr) {
- do {
- for (int i = 0; i < arr->nelts; ++i) {
- char* dir = ARRAY_IDX(arr, i, char*);
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
- CSimpleStringA::Format("%d: %s", i + 1, dir));
- }
- if (arr->nelts == 0) {
- LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
- CSimpleStringA::Format("%s: no any sub files", connectDirPath));
- }
- toolkit_array_free2(arr);
- return result;
- } while (false);
- if (arr->nelts != 1) {
- LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_SYSCONNECT_DUPLICATE,
- CSimpleStringA::Format("%s: unexpect connects count: %d", connectDirPath, arr->nelts));
- }
- else {
- char szDestPath[256] = { 0 };
- char* dir = ARRAY_IDX(arr, 0, char*);
- strcpy(szDestPath, dir);
- do {
- char value[128];
- inifile_read_str_s("connection", "interface-name", "", value, 127, szDestPath);
- if (strlen(value) == 0) {
- LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_CONNECTION_INFO_UNEXPECT,
- CSimpleStringA::Format("get interface name from %s failed.", szDestPath));
- break;
- }
- memset(value, 0, sizeof(value));
- inifile_read_str_s("ipv4", "dns", "", value, 127, szDestPath);
- bool toUpdate = true;
- if (strlen(value) > 0) {
- CSimpleStringA DNSes(value);
- auto arr = DNSes.Split(';');
- int cf1 = 0, cf2 = 0;
- for (int i = 0; i < arr.GetCount(); ++i) {
- if (arr[i].Compare(dns1) == 0) cf1++;
- if (arr[i].Compare(dns2) == 0) cf2++;
- }
- if (cf1 > 0 && cf2 > 0) {
- toUpdate = false;
- Dbg("already exists: %s, needless to update.", value);
- result = TRUE;
- }
- }
- if (toUpdate) {
- CSimpleStringA newLine(dns1);
- if (newLine.Compare(dns2) != 0) {
- newLine += ";";
- newLine += dns2;
- newLine += ";";
- }
- else {
- newLine += ";";
- }
- inifile_write_str(szDestPath, "ipv4", "dns", newLine);
- inifile_write_str(szDestPath, "ipv4", "ignore-auto-dns", "true");
- Dbg("to update services.");
- std::string nor, err;
- SP::Module::Util::ShellExecute("service NetworkManager restart", nor, err);
- Dbg("restart service done!");
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_NM_SUCC,
- CSimpleStringA::Format("update dns with netwokrMange for %s|%s succ!", dns1, dns2));
- result = TRUE;
- }
- } while (false);
- }
- toolkit_array_free2(arr);
- }
- else {
- LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
- CSimpleStringA::Format("%s: no such directory or not any sub files", connectDirPath));
- //LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_SYSCONNECT_DUPLICATE,
- // CSimpleStringA::Format("%s: no such directory or not any sub files", connectDirPath));
- }
- return result;
- }
- /*
- * 桌面版本自带的NetworkManage管理服务与Interface的设置有冲突,如果手工改动Interface的配置,则NetworkManage会失效
- * UOS默认使用NetworkMange接管网卡的管理,所以为了适应UOS,此种方式暂不实现
- */
- BOOL ResourceWatcherFSM::SetLocalDNSWithInterfaces(LPCTSTR dns1, LPCTSTR dns2)
- {
- return FALSE;
- }
- void ResourceWatcherFSM::ConfirmDNSConfigHasSet()
- {
- LOG_FUNCTION();
- CSimpleStringA dns1(true), dns2(true);
- #if 1
- CSmartPointer<IConfigInfo> spConfig;
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- spConfig->ReadConfigValue("DNS", "dns1", dns1);
- spConfig->ReadConfigValue("DNS", "dns2", dns2);
- #else
- dns1 = m_strDefaultDns;
- dns2 = m_strBackupDns;
- if (!m_nEnableSetDns) {
- Dbg("no enable set dns server.");
- return;
- }
- #endif
- if (dns1.IsNullOrEmpty() && dns2.IsNullOrEmpty()) {
- Dbg("not any dns set at entity config.");
- return;
- }
- if (dns2.IsNullOrEmpty()) dns2 = dns1;
- if (dns1.IsNullOrEmpty()) dns1 = dns2;
- CSimpleStringA str;
- readDNSConfigFile(str);
- do {
- std::string a(str.GetData());
- SP::Utility::replaceInPlace(a, "\n", "|");
- LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
- CSimpleStringA::Format("%s $$ %s|%s", a.c_str(), m_strDefaultDns.GetData(), m_strBackupDns.GetData()));
- } while (false);
- if (dns1.IsNullOrEmpty() && dns2.IsNullOrEmpty()) {
- Dbg("not any dns set at entity config.");
- return;
- }
- if (dns2.IsNullOrEmpty()) dns2 = dns1;
- if (dns1.IsNullOrEmpty()) dns1 = dns2;
- return;
- //////////////////////////////////////////////////////////////////////////
- /** 下面的代码验证暂不可行 [Gifur@202319]*/
- if (!str.IsNullOrEmpty()) {
- CAutoArray<CSimpleStringA> arr = str.Split('\n');
- CSimpleStringA check1("nameserver ");
- CSimpleStringA check2("nameserver ");
- check1 += dns1;
- check2 += dns2;
- int cf1 = 0, cf2 = 0;
- for (int i = 0; i < arr.GetCount(); ++i) {
- if (arr[i].Compare(check1) == 0) cf1++;
- if (arr[i].Compare(check2) == 0) cf2++;
- }
- if (cf1 > 0 && cf2 > 0) {
- Dbg("dns has been config before:");
- Dbg(str);
- return;
- }
- }
- Dbg("to set dns config...");
- SetLocalDNSWithResolv(dns1, dns2);
- //SetLocalDNSWithNetworkManager(dns1, dns2);
- Dbg("set dns config done!");
- }
- void ResourceWatcherFSM::ConfirmWindowEffectHasBeenOpen()
- {
- array_header_t* arr;
- arr = fileutil_get_sub_dirs_a("/home");
- if (arr) {
- int i;
- for (i = 0; i < arr->nelts; ++i) {
- char szDestSubDir[256] = { 0 };
- char* dir = ARRAY_IDX(arr, i, char*);
- Dbg("sub dir: %s", dir);
- strcpy(szDestSubDir, dir);
- strcat(szDestSubDir, SPLIT_SLASH_STR);
- strcat(szDestSubDir, ".config/kwinrc");
- if (ExistsFileA(szDestSubDir)) {
- switchWindowsEffect(szDestSubDir, true);
- }
- }
- toolkit_array_free2(arr);
- }
- }
- #endif // RVC_OS_LINUX
|