ResourceWatcherFSM.cpp 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932
  1. #include "stdafx.h"
  2. #include "ResourceWatcherFSM.h"
  3. #include "DeviceBaseClass.h"
  4. #include "publicFunExport.h"
  5. #include <string>
  6. #include <fstream>
  7. #include <iostream>
  8. #include <dirent.h>
  9. #include <vector>
  10. #if defined(RVC_OS_WIN)
  11. #include <intrin.h>
  12. #include <ShlObj.h>
  13. #include <Pdh.h>
  14. #include "shellapi.h"
  15. #include "Mmdeviceapi.h"
  16. #include "Propidl.h"
  17. #include "Functiondiscoverykeys_devpkey.h"
  18. #include "PolicyConfig.h"
  19. #endif //RVC_OS_WIN
  20. #include <assert.h>
  21. #include <algorithm>
  22. #include "toolkit.h"
  23. #include "fileutil.h"
  24. #include "iniutil.h"
  25. #include "osutil.h"
  26. #include "CommEntityUtil.hpp"
  27. #include "SpUtility.h"
  28. //#include "NetworkProbe.h"
  29. #include "RestfulFunc.h"
  30. //硬件信息搜集参数
  31. const int MAX_HARDWARE_CHECK_TIME = 5000;
  32. const int TIMER_HARDWARE_CHECK = 2;
  33. const int MAX_MAINLINK_CHECK_TIME = 5000;
  34. const int TIMER_MAINLINK_CHECK = 4;
  35. const int DEFAULT_DAY_OF_BACKWARD = 90;
  36. const int MAX_DAY_OF_BACKWARD = 365;
  37. const char* DEFAULT_DELETE_FILE_SUFFIX = "*";
  38. LPCTSTR UPLOAD_VIDEO_PATH = "UploadVideo";
  39. const int AD0_DAY_OF_BACKWARD = 7;
  40. const int TIMER_INTERVAL_CLEARVIDEO_ENHANCE = 60 * 1000;
  41. const int MAX_VERSION_PATH = 256;
  42. //保留版本数目
  43. const int DEFAULT_VERSION_SAVED_COUNT = 2;
  44. CRITICAL_SECTION g_csVideoMoreClear;
  45. #define MAX_VOLUME_COUNT 26
  46. #define BUFSIZE 512
  47. static BOOL sBDiskValStatus[MAX_VOLUME_COUNT + 1] = { FALSE };
  48. #define MAX_SUBFILES_COUNT 1000
  49. #define DIV (1024 * 1024)
  50. #define DAY_DIV (24 * 60 * 60)
  51. #define HOURS_DIV (60 * 60)
  52. #define MINUS_DIV (60)
  53. const char* SystemElapsedQuery = "\\System\\System Up Time";
  54. template<class T>
  55. class TimerOutHelper : public ITimerListener
  56. {
  57. public:
  58. typedef void (T::* FuncTimer)(void* pUserdata);
  59. TimerOutHelper(T* p, FuncTimer pTimerFunc, void* pData, bool bDeleteSelf = false)
  60. : m_pObject(p), m_pUserData(pData), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf)
  61. {
  62. }
  63. virtual void OnTimeout(DWORD dwTimerID)
  64. {
  65. (m_pObject->*m_pTimer)(m_pUserData);
  66. if (m_bDeleteSelf)
  67. delete this;
  68. }
  69. private:
  70. void* m_pUserData;
  71. T* m_pObject;
  72. FuncTimer m_pTimer;
  73. bool m_bDeleteSelf;
  74. };
  75. ResourceWatcherFSM::ResourceWatcherFSM(void)
  76. :m_IsPadDevice(FALSE)
  77. , m_bGetStatusRotate(FALSE)
  78. , m_uploadedVideoDirPath(true)
  79. , m_csDelFileSuffix(true)
  80. , m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD)
  81. , m_failDelCnt(0)
  82. , m_bReadyFlag(false)
  83. , m_bVideoClearReady(false)
  84. , m_nMinSavedDay(DEFAULT_SAVE_DATE_COUNT)
  85. , m_highPart(0)
  86. , m_lowPart(0)
  87. , m_strTerminalNo(true)
  88. , m_strDefaultDns(true)
  89. , m_strBackupDns(true)
  90. , m_nEnableSetDns(0)
  91. , m_bFirstRunAfterBoot(FALSE)
  92. , m_bIsConfigMode(FALSE)
  93. {
  94. #if defined(_MSC_VER)
  95. mUiRequireBytes.QuadPart = 0;
  96. mUiCalibration.QuadPart = 0;
  97. #else
  98. mAllVideoFileSizeCal = 0;
  99. mMaxFileSize = 0;
  100. mUiCalibration = 0;
  101. mUiRequireBytes = 0;
  102. mftAd0RemoveTime = 0;
  103. #endif //_MSC_VER
  104. }
  105. ResourceWatcherFSM::~ResourceWatcherFSM(void)
  106. {
  107. }
  108. void ResourceWatcherFSM::ClearVideoQueue()
  109. {
  110. while (!m_VideoFiles.empty()) {
  111. TmpFileInfo* pNodeInfo = m_VideoFiles.top();
  112. m_VideoFiles.pop();
  113. if (pNodeInfo != NULL) {
  114. delete pNodeInfo;
  115. }
  116. }
  117. memset(szMaxSizeFilePath, 0, sizeof(szMaxSizeFilePath));
  118. #if defined(_MSC_VER)
  119. mAllVideoFileSizeCal.QuadPart = 0ui64;
  120. mMaxFileSize.QuadPart = 0ui64;
  121. mUiRequireBytes.QuadPart = 0ui64;
  122. #else
  123. mAllVideoFileSizeCal = 0;
  124. mMaxFileSize = 0;
  125. mUiRequireBytes = 0;
  126. #endif //_MSC_VER
  127. VideoDailyRecord.clear();
  128. }
  129. void ResourceWatcherFSM::PrintVideEmurateResult()
  130. {
  131. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  132. #if defined(_MSC_VER)
  133. ByteSprintf(szResult, (double)mMaxFileSize.QuadPart);
  134. Dbg("Max Video file: %s size: %s", szMaxSizeFilePath, szResult);
  135. Dbg("mAllVideoFileSizeCal.QuadPart : %I64u Bytes", mAllVideoFileSizeCal.QuadPart);
  136. ByteSprintf(szResult, (double)mAllVideoFileSizeCal.QuadPart);
  137. #else
  138. ByteSprintf(szResult, (double)mMaxFileSize);
  139. Dbg("Max Video file: %s size: %s", szMaxSizeFilePath, szResult);
  140. Dbg("mAllVideoFileSizeCal : %llu Bytes", mAllVideoFileSizeCal);
  141. ByteSprintf(szResult, (double)mAllVideoFileSizeCal);
  142. #endif //_MSC_VER
  143. Dbg("Totally(size: %d) directory size: %s", m_VideoFiles.size(), szResult);
  144. }
  145. void ResourceWatcherFSM::s0_on_entry()
  146. {
  147. LOG_FUNCTION();
  148. if (!m_bIsConfigMode) {
  149. this->PostEventFIFO(new RunEvent());
  150. GetCpuType(NULL);
  151. } else {
  152. Dbg("in config mode, do nothing about clear job");
  153. }
  154. }
  155. unsigned int ResourceWatcherFSM::s0_on_event(FSMEvent* e)
  156. {
  157. LOG_FUNCTION();
  158. unsigned int unRes = 0;
  159. switch (e->iEvt) {
  160. case USER_EVT_RUN:
  161. {
  162. if (m_IsPadDevice) {
  163. GetCardSwiperTask* task = new GetCardSwiperTask(this);
  164. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  165. }
  166. #if 0
  167. ClearVideoFilesTask* videoTask = new ClearVideoFilesTask(this);
  168. videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
  169. GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
  170. GetEntityBase()->GetFunction()->PostThreadPoolTask(new ClearCenterSettingFilesTask(this));
  171. GetEntityBase()->GetFunction()->PostThreadPoolTask(new ClearAd0Task(this));
  172. #else
  173. RunTask* videoTask = new RunTask(this);
  174. videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
  175. GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
  176. #endif
  177. e->SetHandled();
  178. }
  179. break;
  180. case USER_EVT_FETCH:
  181. {
  182. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  183. fetchEvt->ctx->Answer(Error_InvalidState);
  184. e->SetHandled();
  185. }
  186. break;
  187. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  188. {
  189. m_bGetStatusRotate = FALSE;
  190. e->SetHandled();
  191. }
  192. break;
  193. default:
  194. {
  195. Dbg("Unexpecetd Event(%d)", e->iEvt);
  196. }
  197. break;
  198. }
  199. return unRes;
  200. }
  201. void ResourceWatcherFSM::s0_on_exit()
  202. {
  203. }
  204. void ResourceWatcherFSM::s1_on_entry()
  205. {
  206. LOG_FUNCTION();
  207. }
  208. unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
  209. {
  210. LOG_FUNCTION();
  211. unsigned int unRes = 0;
  212. switch (e->iEvt) {
  213. case USER_EVT_FETCH:
  214. {
  215. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  216. if (m_IsPadDevice) {
  217. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  218. fetchEvt->ctx->Answer(Error_Succeed);
  219. } else {
  220. Dbg("In Not Pad MachineType, Receive Query CardSwiper Status Event");
  221. fetchEvt->ctx->Answer(Error_NotSupport);
  222. }
  223. e->SetHandled();
  224. }
  225. break;
  226. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  227. {
  228. m_bGetStatusRotate = FALSE;
  229. e->SetHandled();
  230. }
  231. break;
  232. case USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED:
  233. {
  234. Dbg("%s::There are %d file(s), successfully delete %d file(s) in path %s", __FUNCTION__,
  235. e->param2, e->param1, (LPCTSTR)m_uploadedVideoDirPath);
  236. if (m_failDelCnt != 0) {
  237. CSimpleStringA strMsg = CSimpleStringA::Format("There are %d matched files should be deleted", m_failDelCnt);
  238. LogWarn(Severity_Middle, Error_Unexpect, 0, (LPCTSTR)strMsg);
  239. }
  240. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  241. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  242. }
  243. e->SetHandled();
  244. break;
  245. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  246. e->SetHandled();
  247. break;
  248. case USER_EVT_VERSION_CLEAR_FINISHED:
  249. e->SetHandled();
  250. break;
  251. default:
  252. {
  253. Dbg("Unexpecetd Event(%d)", e->iEvt);
  254. }
  255. break;
  256. }
  257. return unRes;
  258. }
  259. void ResourceWatcherFSM::s1_on_exit()
  260. {
  261. }
  262. void ResourceWatcherFSM::s2_on_entry()
  263. {
  264. LOG_FUNCTION();
  265. }
  266. unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
  267. {
  268. LOG_FUNCTION();
  269. unsigned int unRes = 0;
  270. switch (e->iEvt) {
  271. case USER_EVT_RUN:
  272. {
  273. e->SetHandled();
  274. }
  275. break;
  276. case USER_EVT_FETCH:
  277. {
  278. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  279. if (m_IsPadDevice) {
  280. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  281. fetchEvt->ctx->Answer(Error_Succeed);
  282. } else {
  283. Dbg("In Not Pad MachineType, Receive Query CardSwiper Status Event");
  284. fetchEvt->ctx->Answer(Error_NotSupport);
  285. }
  286. e->SetHandled();
  287. }
  288. break;
  289. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  290. {
  291. m_bGetStatusRotate = FALSE;
  292. e->SetHandled();
  293. }
  294. break;
  295. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  296. {
  297. }
  298. e->SetHandled();
  299. break;
  300. }
  301. return unRes;
  302. }
  303. void ResourceWatcherFSM::s2_on_exit()
  304. {
  305. LOG_FUNCTION();
  306. }
  307. void ResourceWatcherFSM::s3_on_entry()
  308. {
  309. LOG_FUNCTION();
  310. m_bVideoClearReady = true;
  311. }
  312. unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
  313. {
  314. LOG_FUNCTION();
  315. unsigned int unRes = 0;
  316. switch (e->iEvt) {
  317. case USER_EVT_RUN:
  318. {
  319. e->SetHandled();
  320. }
  321. break;
  322. case USER_EVT_FETCH:
  323. {
  324. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  325. if (m_IsPadDevice) {
  326. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  327. fetchEvt->ctx->Answer(Error_Succeed);
  328. } else {
  329. Dbg("In Not Pad MachineType, Receive Query CardSwiper Status Event");
  330. fetchEvt->ctx->Answer(Error_NotSupport);
  331. }
  332. e->SetHandled();
  333. }
  334. break;
  335. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  336. {
  337. m_bGetStatusRotate = FALSE;
  338. e->SetHandled();
  339. }
  340. break;
  341. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE:
  342. {
  343. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  344. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  345. }
  346. e->SetHandled();
  347. break;
  348. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  349. {
  350. }
  351. e->SetHandled();
  352. break;
  353. case USER_EVT_FILE_OPERAT:
  354. {
  355. OperateFileEvent* theEvt = dynamic_cast<OperateFileEvent*>(e);
  356. OperateFileTask* theTask = new OperateFileTask(this, theEvt->m_ctx);
  357. GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
  358. }
  359. e->SetHandled();
  360. break;
  361. case USER_EVT_FILE_OPERAT_FINISHED:
  362. {
  363. }
  364. e->SetHandled();
  365. break;
  366. case USER_EVT_GET_EVENTLOG:
  367. {
  368. GetEventLogEvent* theEvt = dynamic_cast<GetEventLogEvent*>(e);
  369. #if defined(_MSC_VER)
  370. GetEventLogTask* theTask = new GetEventLogTask(this, theEvt->m_ctx);
  371. GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
  372. #else
  373. theEvt->m_ctx->Answer(Error_NotSupport);
  374. #endif //_MSC_VER
  375. }
  376. e->SetHandled();
  377. break;
  378. case USER_EVT_GET_EVENTLOG_FINISHED:
  379. {
  380. }
  381. e->SetHandled();
  382. break;
  383. }
  384. return unRes;
  385. }
  386. void ResourceWatcherFSM::s3_on_exit()
  387. {
  388. m_bVideoClearReady = false;
  389. }
  390. void ResourceWatcherFSM::readVideoStoreData()
  391. {
  392. LOG_FUNCTION();
  393. CSmartPointer<IConfigInfo> spCtSettingConfig;
  394. CSmartPointer<IConfigInfo> spConfig;
  395. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  396. GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  397. // From CenterSetting --Josephus at 10:02:10 201759
  398. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "BackwardDays", m_nDayOfBackward);
  399. if (m_nDayOfBackward <= 0) {
  400. spConfig->ReadConfigValueInt("Video", "BackwardDays", m_nDayOfBackward);
  401. } else {
  402. Dbg("Detect BackwardDays from CentralSetting %d", m_nDayOfBackward);
  403. }
  404. if (m_nDayOfBackward <= 0 || m_nDayOfBackward > MAX_DAY_OF_BACKWARD) {
  405. Dbg("Detect BackwardDays(%d) is illegal and Set default %d", m_nDayOfBackward, DEFAULT_DAY_OF_BACKWARD);
  406. m_nDayOfBackward = DEFAULT_DAY_OF_BACKWARD;
  407. }
  408. int minSavedDay = 0;
  409. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MinSavedDays", minSavedDay);
  410. if (minSavedDay >= 1 && minSavedDay < DEFAULT_SAVE_DATE_COUNT) {
  411. m_nMinSavedDay = minSavedDay;
  412. Dbg("Detect MinSavedDays from CentralSetting %d", m_nMinSavedDay);
  413. }
  414. }
  415. ErrorCodeEnum ResourceWatcherFSM::OnInit()
  416. {
  417. LOG_FUNCTION();
  418. #if defined(_MSC_VER) && defined(WIDE_CONDITION)
  419. setlocale(LC_ALL, "chs");
  420. #endif
  421. ErrorCodeEnum erroCode = Error_Succeed;
  422. CSimpleStringA strtermState;
  423. GetEntityBase()->GetFunction()->GetSysVar("TerminalStage", strtermState);
  424. if (strtermState.IsStartWith("Z=")) {
  425. Dbg("in config mode");
  426. m_bIsConfigMode = TRUE;
  427. }
  428. CSystemStaticInfo sysInfo;
  429. erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
  430. if (erroCode != Error_Succeed) {
  431. Dbg("Get System Static info failed: %s.", SpStrError(erroCode));
  432. return Error_Unexpect;
  433. }
  434. Dbg("%s, %s", sysInfo.strMachineType.GetData(), sysInfo.strTerminalID.GetData());
  435. m_strTerminalNo = sysInfo.strTerminalID;
  436. if (!sysInfo.strMachineType.IsNullOrEmpty() && !sysInfo.strMachineType.Compare("RVC.Pad", true)) {
  437. m_IsPadDevice = TRUE;
  438. }
  439. m_bFirstRunAfterBoot = DetectIsFirstRunAtBoot();
  440. Dbg("to initialize critical section...");
  441. InitializeCriticalSection(&g_csVideoMoreClear);
  442. if (!m_bIsConfigMode) {
  443. erroCode = GetEntityBase()->GetFunction()->GetPath("LocalVideo", m_uploadedVideoDirPath);
  444. if (erroCode != Error_Succeed || m_uploadedVideoDirPath.IsNullOrEmpty()) {
  445. return Error_NotInit;
  446. }
  447. InitialVolumes();
  448. InitBlackList();
  449. readVideoStoreData();
  450. m_bReadyFlag = IsNeedToFirstClear();
  451. Dbg("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)"
  452. , (LPCTSTR)m_uploadedVideoDirPath, m_nDayOfBackward, !m_bReadyFlag);
  453. void* pTmpData = NULL;
  454. ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
  455. GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, MAX_HARDWARE_CHECK_TIME);
  456. Dbg("Set Hardware Timer!");
  457. /*void* pTmpData2 = NULL;
  458. ITimerListener* pListener2 = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::MainLinkDetectTimer, pTmpData2);
  459. GetEntityBase()->GetFunction()->SetTimer(TIMER_MAINLINK_CHECK, pListener2, MAX_MAINLINK_CHECK_TIME);
  460. Dbg("Set MainLinkDetect Timer!");*/
  461. }
  462. return Error_Succeed;
  463. }
  464. ErrorCodeEnum ResourceWatcherFSM::OnExit()
  465. {
  466. LOG_FUNCTION();
  467. GetEntityBase()->GetFunction()->KillTimer(TIMER_HARDWARE_CHECK);
  468. Dbg("Kill Timer!");
  469. ClearVideoQueue();
  470. DeleteCriticalSection(&g_csVideoMoreClear);
  471. return Error_Succeed;
  472. }
  473. void ResourceWatcherFSM::AfterInit()
  474. {
  475. LOG_FUNCTION();
  476. CSmartPointer<IConfigInfo> spCtSettingConfig;
  477. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  478. //huchen add for set dns
  479. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DefaultDns", m_strDefaultDns);
  480. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "BackupDns", m_strBackupDns);
  481. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "EnableSetDns", m_nEnableSetDns);
  482. Dbg("Detect Dns from CentralSetting EnableSetDns: %d Default: %s, Backup: %s.",
  483. m_nEnableSetDns, m_strDefaultDns.GetData(), m_strBackupDns.GetData());
  484. #if defined(_MSC_VER)
  485. if (!sysInfo.strMachineType.Compare("RVC.Desk2S", true)) {
  486. int nLastTaskTime(0);
  487. CSmartPointer<IConfigInfo> spRunConfig;
  488. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  489. spRunConfig->ReadConfigValueInt("Device", "SetAudioOutput", nLastTaskTime);
  490. CSmallDateTime lastSetTime(nLastTaskTime);
  491. Dbg("RunConfig SetAudioOutput time : %s", (LPCTSTR)lastSetTime.ToTimeString());
  492. if (m_bFirstRunAfterBoot) {
  493. Dbg("last set audio output time is earlier than system boot time!");
  494. Dbg("Start to Set Audio output device");
  495. if (SetDefaultAudioDevice()) {
  496. spRunConfig->WriteConfigValue("Device", "SetAudioOutput", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  497. } else {
  498. LogWarn(Severity_Middle, Error_AudioOut, 0, "Set default video output failed!!");
  499. }
  500. }
  501. }
  502. #else
  503. if (m_bFirstRunAfterBoot) {
  504. UINT sysVer = 0;
  505. UploadSysVersionInfo(sysVer);
  506. ConfirmWindowEffectHasBeenOpen();
  507. ConfirmDNSConfigHasSet();
  508. Dbg("fetch os version: %u", sysVer);
  509. if (1031 < sysVer) {
  510. ConfirmDDEClipboardDisable();
  511. ConfirmNotificationCenterDisable();
  512. } else {
  513. RecoverDDEClipboardEnable();
  514. }
  515. GetEntityBase()->GetFunction()->PostThreadPoolTask(new UploadMonitorInfoTask(this));
  516. }
  517. #endif //_MSC_VER
  518. }
  519. int ResourceWatcherFSM::GetCardSwiperStatus()
  520. {
  521. LOG_FUNCTION();
  522. ErrorCodeEnum errorCode = Error_Succeed;
  523. CardSwiperClient* client = NULL;
  524. CardSwiperService_QueryConnInfo_Req req;
  525. CardSwiperService_QueryConnInfo_Ans ans;
  526. QueryCardSwiper cardswiperStatus;
  527. BOOL bConnected = FALSE;
  528. // [Josephus in 7:05:25 2016/9/6]
  529. int lastStatus = m_cardswiperStatus;
  530. int errorTimes1 = 0, errorTimes2 = 0, errorTimes3 = 0;
  531. int sleepTime = 1500;
  532. const int errorMaxTimes = 2;
  533. m_bGetStatusRotate = TRUE;
  534. while (m_bGetStatusRotate) {
  535. if (client == NULL) {
  536. client = new CardSwiperClient(GetEntityBase());
  537. }
  538. if (!bConnected) {
  539. errorCode = client->Connect();
  540. if (errorCode != Error_Succeed) {
  541. if (errorTimes1 < errorMaxTimes) {
  542. errorTimes1++;
  543. Dbg("Connect to CardSwiper failed %s", SpStrError(errorCode));
  544. Sleep(500);
  545. continue;
  546. } else {
  547. //errorTimes1++;
  548. Dbg("Connect to CardSwiper failed...");
  549. // [Josephus in 16:15:37 2016/3/28]
  550. bConnected = FALSE;
  551. client->SafeDelete();
  552. client = NULL;
  553. m_cardswiperStatus = 0;
  554. goto BroadCastPoint;
  555. }
  556. } else {
  557. Dbg("Connect to CardSwiper Success");
  558. bConnected = TRUE;
  559. errorTimes3 = errorTimes2 = 0;
  560. }
  561. }
  562. errorCode = client->QueryConnInfo(req, ans, 3000);
  563. if (errorCode != Error_Succeed) {
  564. if (errorTimes2 < errorMaxTimes) {
  565. errorTimes2++;
  566. Dbg("Get CardSwiper status failed with code %s", SpStrError(errorCode));
  567. Sleep(500);
  568. continue;
  569. } else {
  570. Dbg("Get CardSwiper status failed...");
  571. bConnected = FALSE;
  572. client->GetFunction()->CloseSession();
  573. client = NULL;
  574. m_cardswiperStatus = 0;
  575. }
  576. } else {
  577. errorTimes1 = errorTimes2 = errorTimes3 = 0;
  578. m_cardswiperStatus = ans.connect;
  579. }
  580. BroadCastPoint:
  581. if (lastStatus != m_cardswiperStatus) {
  582. Dbg("send broadcast for cardswiper status %d", m_cardswiperStatus);
  583. cardswiperStatus.status = m_cardswiperStatus;
  584. SpSendBroadcast(GetEntityBase()->GetFunction(),
  585. SP_MSG_OF(QueryCardSwiper), SP_MSG_SIG_OF(QueryCardSwiper), cardswiperStatus);
  586. lastStatus = m_cardswiperStatus;
  587. }
  588. break;
  589. }
  590. if (client) {
  591. if (bConnected) {
  592. client->GetFunction()->CloseSession();
  593. } else {
  594. client->SafeDelete();
  595. }
  596. client = NULL;
  597. }
  598. return 0;
  599. }
  600. void ResourceWatcherFSM::AppendVideoSizeTogether()
  601. {
  602. Dbg("Add UploadFile size together...");
  603. #if defined(_MSC_VER)
  604. ULARGE_INTEGER uiAdditionBytes;
  605. CalculateWillUploadDirSize(uiAdditionBytes);
  606. mAllVideoFileSizeCal.QuadPart += uiAdditionBytes.QuadPart;
  607. diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
  608. #else
  609. unsigned long long uiAdditionBytes;
  610. CalculateWillUploadDirSize(uiAdditionBytes);
  611. mAllVideoFileSizeCal += uiAdditionBytes;
  612. diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
  613. #endif //_MSC_VER
  614. }
  615. void ResourceWatcherFSM::CalculateFreeDiskNeeded()
  616. {
  617. const_map_cu_iter citer = VideoDailyRecord.cbegin();
  618. UINT uCount = 0;
  619. while (citer != VideoDailyRecord.cend()) {
  620. Dbg("date[%d]: %d", (citer->first), citer->second);
  621. uCount += citer->second;
  622. citer++;
  623. }
  624. Dbg("count %d and video file size#%d", uCount, m_VideoFiles.size());
  625. diskInfo.CalAverRequreSpaceEachDay(mAllVideoFileSizeCal,
  626. uCount, VideoDailyRecord.size(),
  627. BASE_AVAILALBE_DATE_COUNT, mUiRequireBytes);
  628. }
  629. void ResourceWatcherFSM::RecordFreeDiskNeededToRunCfg()
  630. {
  631. CSmartPointer<IConfigInfo> spConfigRun;
  632. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  633. #if defined(RVC_OS_WIN)
  634. spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
  635. #else
  636. spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes);
  637. #endif //RVC_OS_WIN
  638. spConfigRun->WriteConfigValue("LastClearTime", "Video", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  639. m_bReadyFlag = false;
  640. }
  641. void ResourceWatcherFSM::GetFreeDiskNeededFromRunCfg()
  642. {
  643. CSmartPointer<IConfigInfo> spConfigRun;
  644. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  645. #if defined(_MSC_VER)
  646. spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
  647. Dbg("Retrieve from runcfg about required bytes: %llu", mUiRequireBytes.QuadPart);
  648. #else
  649. UINT64 value(0);
  650. spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", value);
  651. mUiRequireBytes = value;
  652. Dbg("Retrieve from runcfg about required bytes: %llu", value);
  653. #endif //_MSC_VER
  654. }
  655. int ResourceWatcherFSM::CleanVideoFiles(int& newDeletedFilesNum, int initFlag)
  656. {
  657. LOG_FUNCTION();
  658. newDeletedFilesNum = 0;
  659. ClearVideoQueue();
  660. CSimpleStringA filePath = m_uploadedVideoDirPath;
  661. #if defined(_MSC_VER)
  662. filePath += "\\*";
  663. #endif //_MSC_VER
  664. Dbg("(InitFlag:%d) filePath %s", initFlag, (LPCTSTR)filePath);
  665. newDeletedFilesNum = 0;
  666. m_failDelCnt = 0;
  667. const int nRet = RemoveExpireVideoFileAndRecord((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
  668. PrintVideEmurateResult();
  669. Dbg("nRet: %d, new Deleted Files Num:%d, video counts:%d", nRet, newDeletedFilesNum, m_VideoFiles.size());
  670. LOG_ASSERT(nRet - newDeletedFilesNum == m_VideoFiles.size());
  671. if (!!initFlag) {
  672. AppendVideoSizeTogether();
  673. CalculateFreeDiskNeeded();
  674. RecordFreeDiskNeededToRunCfg();
  675. } else {
  676. GetFreeDiskNeededFromRunCfg();
  677. }
  678. return nRet;
  679. }
  680. #if defined(RVC_OS_WIN)
  681. void ResourceWatcherFSM::CalculateBackTime(PFILETIME ftResultTime, int days)
  682. {
  683. //Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
  684. FILETIME ftCurTime, ftBackTime;
  685. GetSystemTimeAsFileTime(&ftCurTime);
  686. ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
  687. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  688. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  689. if (days > 0) {
  690. uliOffset.QuadPart = UInt32x32To64(days * 24 * 60 * 60, 1e7);
  691. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  692. } else {
  693. uliOffset.QuadPart = UInt32x32To64(-1 * days * 24 * 60 * 60, 1e7);
  694. uliBackTime.QuadPart = uliCurTime.QuadPart + uliOffset.QuadPart;
  695. }
  696. ftBackTime.dwHighDateTime = uliBackTime.HighPart;
  697. ftBackTime.dwLowDateTime = uliBackTime.LowPart;
  698. *ftResultTime = ftBackTime;
  699. return;
  700. }
  701. BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(ULARGE_INTEGER& uiBytesCal)
  702. {
  703. uiBytesCal.QuadPart = 0;
  704. #else
  705. void ResourceWatcherFSM::CalculateBackTime(time_t * ftResultTime, int days)
  706. {
  707. time_t ftCurTime = time(NULL);//获取当前时间
  708. time_t ftBackTime = ftCurTime - (60 * 60 * 24 * days);
  709. *ftResultTime = ftBackTime;
  710. return;
  711. }
  712. BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(unsigned long long& uiBytesCal)
  713. {
  714. uiBytesCal = 0;
  715. #endif //RVC_OS_WIN
  716. BOOL bRet = FALSE;
  717. CSimpleStringA uploadVideoPath;
  718. CSimpleStringA tmpValue;
  719. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
  720. if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
  721. if (ec == Error_Succeed) {
  722. Dbg("UploadVideo path: %s", (LPCTSTR)uploadVideoPath);
  723. #if defined(_MSC_VER)
  724. CSimpleStringA filePath = uploadVideoPath + "\\*";
  725. ULARGE_INTEGER uliSpaceSize;
  726. uliSpaceSize.QuadPart = 0;
  727. int nFileCnt = CalculateAllVideoSize(filePath, &uliSpaceSize);
  728. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  729. ByteSprintf(szResult, (double)uliSpaceSize.QuadPart);
  730. uiBytesCal.QuadPart = uliSpaceSize.QuadPart;
  731. #else
  732. uiBytesCal = 0;
  733. const int nFileCnt = CalculateAllVideoSize(uploadVideoPath, &uiBytesCal);
  734. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  735. ByteSprintf(szResult, (double)uiBytesCal);
  736. #endif //_MSC_VER
  737. Dbg("Result: Files(%d), Size: %s", nFileCnt, szResult);
  738. }
  739. return (ec == Error_Succeed);
  740. }
  741. int ResourceWatcherFSM::RemoveExpireVideoFileAndRecord(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag)
  742. {
  743. int fileCnt = 0;
  744. int fileLength = strlen(dirName);
  745. // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
  746. char searchFilePath[MAX_PATH] = { 0 };
  747. char tempFilePath[MAX_PATH] = { 0 };
  748. char displayTime[MAX_PATH] = { 0 };
  749. #if defined(RVC_OS_WIN)
  750. WIN32_FIND_DATA foundFileData;
  751. HANDLE hFind;
  752. FILETIME ftRemoveTime;
  753. CalculateBackTime(&ftRemoveTime, m_nDayOfBackward);
  754. GetTimeFormatStr(displayTime, MAX_PATH, &ftRemoveTime);
  755. Dbg("The date backward to delete: %s", displayTime);
  756. hFind = FindFirstFile(dirName, &foundFileData);
  757. if (hFind == INVALID_HANDLE_VALUE) {
  758. Dbg("FindFirstFile failed (%u)", GetLastError());
  759. return 0;
  760. }
  761. do {
  762. if ((foundFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  763. if (/*foundFileData.cFileName[0] != '.'*/FALSE) {
  764. strcpy_s(tempFilePath, dirName);
  765. tempFilePath[fileLength - 1] = '\0';
  766. strcat_s(tempFilePath, foundFileData.cFileName);
  767. strcat_s(tempFilePath, "\\*");
  768. fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  769. }
  770. } else {
  771. strcpy_s(searchFilePath, dirName);
  772. searchFilePath[fileLength - 1] = '\0';
  773. strcat_s(searchFilePath, foundFileData.cFileName);
  774. if (nFlag == 1 && CompareVideoFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0) {
  775. GetTimeFormatStr(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
  776. if (DeleteFile(searchFilePath) != 0) {
  777. deletedFileCnt++;
  778. Dbg("Delete matched %s(%s) suc.", foundFileData.cFileName, displayTime);
  779. } else {
  780. deleteFailedCnt++;
  781. Dbg("Delete matched %s(%s) failed(%d).",
  782. foundFileData.cFileName, displayTime, GetLastError());
  783. RecordVideoFileInfomation(searchFilePath, &foundFileData);
  784. }
  785. } else {
  786. RecordVideoFileInfomation(searchFilePath, &foundFileData);
  787. }
  788. fileCnt++;
  789. }
  790. } while (FindNextFile(hFind, &foundFileData));
  791. FindClose(hFind);
  792. #else
  793. time_t tmp_time;
  794. CalculateBackTime(&tmp_time, m_nDayOfBackward);
  795. deletedFileCnt = deleteFailedCnt = 0;
  796. GetTimeFormatStr(displayTime, MAX_PATH, &tmp_time);
  797. Dbg("video backtrace time: %s", displayTime);
  798. struct stat st;
  799. if (stat(dirName, &st) < 0 || !S_ISDIR(st.st_mode)) {
  800. return 0;
  801. }
  802. DIR* d = opendir(dirName);
  803. if (!d) {
  804. return 0;
  805. }
  806. struct dirent* dp = NULL;
  807. while ((dp = readdir(d)) != NULL) {
  808. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  809. continue;
  810. }
  811. strcpy(tempFilePath, dirName);
  812. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  813. Dbg("filePath is too long for current.");
  814. continue;
  815. }
  816. strcat(tempFilePath, "/");
  817. strcat(tempFilePath, dp->d_name);
  818. if (-1 == stat(tempFilePath, &st)) {
  819. Dbg("stat video file: %s error: %d", tempFilePath, errno);
  820. continue;
  821. }
  822. const bool isdir = !!(S_ISDIR(st.st_mode));
  823. if (isdir) {
  824. fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  825. } else {
  826. if (nFlag == 1 && st.st_mtime < tmp_time) {
  827. GetTimeFormatStr(displayTime, MAX_PATH, &st.st_mtime);
  828. if (RemoveFileA(tempFilePath)) {
  829. deletedFileCnt++;
  830. Dbg("Delete matched %s(%s) suc.", dp->d_name, displayTime);
  831. } else {
  832. deleteFailedCnt++;
  833. Dbg("Delete matched %s(%s) failed: %d", dp->d_name, displayTime, errno);
  834. }
  835. }
  836. RecordVideoFileInfomation(tempFilePath, &st);
  837. fileCnt++;
  838. }
  839. }
  840. closedir(d);
  841. #endif //RVC_OS_WIN
  842. return fileCnt;
  843. }
  844. #if defined(RVC_OS_WIN)
  845. BOOL ResourceWatcherFSM::GetCPUBrand(CSimpleStringA & csCpuBrand)
  846. {
  847. char CPUBrandString[0x40];
  848. int CPUInfo[4] = { -1 };
  849. unsigned nExIds;
  850. // Calling __cpuid with 0x80000000 as the InfoType argument
  851. // gets the number of valid extended IDs.
  852. __cpuid(CPUInfo, 0x80000000);
  853. nExIds = CPUInfo[0];
  854. memset(CPUBrandString, 0, sizeof(CPUBrandString));
  855. if (nExIds >= 0x80000004) {
  856. __cpuid(CPUInfo, 0x80000002);
  857. memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
  858. __cpuid(CPUInfo, 0x80000003);
  859. memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
  860. __cpuid(CPUInfo, 0x80000004);
  861. memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
  862. // Display all the information in user-friendly format.
  863. csCpuBrand = CPUBrandString;
  864. Dbg("CPU Brand String: %s", (LPCTSTR)csCpuBrand);
  865. return TRUE;
  866. }
  867. Dbg("Current device is not supported for getting cpu brand 0x%08x.", nExIds);
  868. return FALSE;
  869. }
  870. void ResourceWatcherFSM::InitialCPUMarkInfor()
  871. {
  872. ErrorCodeEnum erroCode = Error_Succeed;
  873. CSmartPointer<IConfigInfo> spConfig;
  874. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  875. if (erroCode != Error_Succeed) {
  876. Dbg("Open Config_Software failed %s.", SpStrError(erroCode));
  877. return;
  878. }
  879. int nTmpValue1, nTmpValue2 = 0;
  880. erroCode = spConfig->ReadConfigValueInt("CPUMarkLevel", "High", nTmpValue1);
  881. if (erroCode == Error_Succeed/* && nTmpValue1 > 0*/)
  882. m_highPart = nTmpValue1;
  883. erroCode = spConfig->ReadConfigValueInt("CPUMarkLevel", "Low", nTmpValue2);
  884. if (erroCode == Error_Succeed/* && nTmpValue2 > 0*/)
  885. m_lowPart = nTmpValue2;
  886. Dbg("hight:%d > value >low:%d.", m_highPart, m_lowPart);
  887. return;
  888. }
  889. #endif //RVC_OS_WIN
  890. ErrorCodeEnum ResourceWatcherFSM::GetCpuType(
  891. SpReqAnsContext<ResourceWatcherService_GetCpuType_Req, ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
  892. {
  893. LOG_FUNCTION();
  894. ErrorCodeEnum ec = Error_Succeed;
  895. #if defined(RVC_OS_WIN)
  896. ErrorCodeEnum erroCode = Error_Succeed;
  897. CSimpleStringA csCPUBrand;
  898. if (!GetCPUBrand(csCPUBrand)) {
  899. if (ctx != NULL)
  900. ctx->Answer(Error_Unexpect);
  901. return Error_Unexpect;
  902. }
  903. CSmartPointer<IConfigInfo> spConfig;
  904. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  905. if (erroCode != Error_Succeed) {
  906. Dbg("Open Config_Software failed 0x%x.", erroCode);
  907. if (ctx != NULL)
  908. ctx->Answer(Error_DevLoadFileFailed);
  909. return Error_DevLoadFileFailed;
  910. }
  911. int nMark = 0;
  912. int level = 0;
  913. erroCode = spConfig->ReadConfigValueInt("CPUMark", (LPCTSTR)csCPUBrand, nMark);
  914. if (erroCode != Error_Succeed || nMark == 0) {
  915. Dbg("There are no level information about %s(mark:%d)(code:%d).",
  916. (LPCTSTR)csCPUBrand, nMark, erroCode);
  917. if (ctx != NULL) {
  918. ctx->Ans.brand = csCPUBrand;
  919. ctx->Ans.level = 0;
  920. ctx->Ans.reserved1 = nMark;
  921. ctx->Ans.reserved2 = "";
  922. ctx->Answer(Error_Succeed);
  923. }
  924. } else {
  925. level = SelectMarkLevel(nMark);
  926. Dbg("Result: %s : %d(%d).", (LPCTSTR)csCPUBrand, nMark, level);
  927. if (ctx != NULL) {
  928. ctx->Ans.brand = csCPUBrand;
  929. ctx->Ans.level = level;
  930. ctx->Ans.reserved1 = nMark;
  931. ctx->Ans.reserved2 = "";
  932. ctx->Answer(Error_Succeed);
  933. }
  934. }
  935. return Error_Succeed;
  936. #else
  937. ec = Error_NotSupport;
  938. LogWarn(Severity_Middle, ec, 0, CSimpleStringA::Format("%s is not supported!", __FUNCTION__));
  939. if (ctx != NULL) {
  940. ctx->Answer(ec);
  941. }
  942. return ec;
  943. #endif //RVC_OS_WIN
  944. }
  945. BOOL ResourceWatcherFSM::RemoveDuplicateCenterSettingFiles()
  946. {
  947. LOG_FUNCTION();
  948. ErrorCodeEnum erroCode = Error_Succeed;
  949. CSmartPointer<IConfigInfo> spConfigRun;
  950. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  951. if (erroCode != Error_Succeed) {
  952. Dbg("OpenConfig of 'Config_Run' failed 0x%x(%d).", erroCode, erroCode);
  953. return FALSE;
  954. }
  955. int nLastTaskTime(0);
  956. spConfigRun->ReadConfigValueInt("LastClearTime", "CenterSetting", nLastTaskTime);
  957. if (IsTodayDone(nLastTaskTime)) {
  958. return TRUE;
  959. }
  960. CSimpleStringA ssFilePath(true);
  961. erroCode = GetEntityBase()->GetFunction()->GetPath("cfg", ssFilePath);
  962. if (erroCode != Error_Succeed || ssFilePath.IsNullOrEmpty()) {
  963. Dbg("Get path of 'cfg' failed 0x%x(%d).", erroCode, erroCode);
  964. return FALSE;
  965. }
  966. #if defined(_MSC_VER)
  967. ssFilePath = ssFilePath + "\\*";
  968. #endif //_MSC_VER
  969. Dbg("filePath %s", (LPCTSTR)ssFilePath);
  970. int nDelSuc = 0;
  971. int nDelFailed = 0;
  972. int nfileSum = ClearSpecifieFile(DFT_CenterSetting, ssFilePath, nDelSuc, nDelFailed);
  973. Dbg("#CenterSetting#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  974. spConfigRun->WriteConfigValue("LastClearTime", "CenterSetting", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  975. return TRUE;
  976. }
  977. int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt)
  978. {
  979. LOG_FUNCTION();
  980. int nRes;
  981. int nfileCnt = 0;
  982. int fileLength = strlen(dirName);
  983. char searchFilePath[MAX_PATH] = { 0 };
  984. char tempFilePath[MAX_PATH] = { 0 };
  985. char displayTime[MAX_PATH] = { 0 };
  986. #if defined(RVC_OS_WIN)
  987. WIN32_FIND_DATA fndFileData;
  988. HANDLE hFind;
  989. hFind = FindFirstFile(dirName, &fndFileData);
  990. if (hFind == INVALID_HANDLE_VALUE) {
  991. printf("FindFirstFile failed (%d) \n", GetLastError());
  992. return -2;
  993. }
  994. do {
  995. if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  996. if (fndFileData.cFileName[0] != '.') {
  997. memset(tempFilePath, 0, sizeof(tempFilePath));
  998. strcpy_s(tempFilePath, dirName);
  999. tempFilePath[fileLength - 1] = '\0';
  1000. strcat_s(tempFilePath, fndFileData.cFileName);
  1001. strcat_s(tempFilePath, "\\*");
  1002. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  1003. if (nRes >= 0) nfileCnt += nRes;
  1004. }
  1005. } else {
  1006. memset((void*)searchFilePath, 0, MAX_PATH);
  1007. strcpy_s(searchFilePath, dirName);
  1008. searchFilePath[fileLength - 1] = '\0';
  1009. strcat_s(searchFilePath, fndFileData.cFileName);
  1010. if (fileType == DFT_Ad0) {
  1011. if (CompareFileTime(&mftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
  1012. nRes = RemoveSpecifiedFile(fileType, searchFilePath, fndFileData.cFileName);
  1013. } else {
  1014. nRes = 0;
  1015. }
  1016. } else {
  1017. nRes = RemoveSpecifiedFile(fileType, searchFilePath, fndFileData.cFileName);
  1018. }
  1019. if (nRes == -1) deleteFailedCnt++;
  1020. else if (nRes == 1) deletedFileCnt++;
  1021. nfileCnt++;
  1022. }
  1023. } while (FindNextFile(hFind, &fndFileData));
  1024. FindClose(hFind);
  1025. #else
  1026. struct stat st;
  1027. if (stat(dirName, &st) < 0) {
  1028. Dbg("stat for %s failed: %d %s", dirName, errno, strerror(errno));
  1029. return -2;
  1030. }
  1031. if (!S_ISDIR(st.st_mode)) {
  1032. Dbg(" %s is not directory", dirName);
  1033. return -2;
  1034. }
  1035. DIR* d = opendir(dirName);
  1036. if (!d) {
  1037. return -3;
  1038. }
  1039. struct dirent* dp = NULL;
  1040. while ((dp = readdir(d)) != NULL) {
  1041. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1042. continue;
  1043. }
  1044. strcpy(tempFilePath, dirName);
  1045. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1046. Dbg("filePath is too long for current.");
  1047. continue;
  1048. }
  1049. strcat(tempFilePath, "/");
  1050. strcat(tempFilePath, dp->d_name);
  1051. Dbg("fileName: %s", dp->d_name);
  1052. struct stat stFile;
  1053. stat(tempFilePath, &stFile);
  1054. const bool isdir = !!(S_ISDIR(stFile.st_mode));
  1055. if (isdir && fileType != DFT_CenterSetting) {
  1056. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  1057. if (nRes >= 0) nfileCnt += nRes;
  1058. } else if (!isdir) {
  1059. if (fileType != DFT_Ad0 || (CompareVideoFileTime(&mftAd0RemoveTime, &stFile.st_mtime) >= 0)) {
  1060. nRes = RemoveSpecifiedFile(fileType, tempFilePath, dp->d_name);
  1061. } else {
  1062. nRes = 0;
  1063. }
  1064. if (nRes == -1) deleteFailedCnt++;
  1065. else if (nRes == 1) deletedFileCnt++;
  1066. nfileCnt++;
  1067. }
  1068. }
  1069. closedir(d);
  1070. #endif //RVC_OS_WIN
  1071. return nfileCnt;
  1072. }
  1073. int ResourceWatcherFSM::RemoveSpecifiedFile(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
  1074. {
  1075. CSimpleStringA ssFileName = szFileName;
  1076. if (ssFileName.IsNullOrEmpty()) return FALSE;
  1077. if ((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
  1078. || fileType == DFT_Ad0
  1079. ) {
  1080. if (RemoveFileA(szFilePath)) {
  1081. Dbg("%s delete suc.", szFileName);
  1082. return 1;
  1083. }
  1084. Dbg("%s delete failed %d.", szFileName, GetLastError());
  1085. return -1;
  1086. }
  1087. return 0;
  1088. }
  1089. #if defined(_MSC_VER)
  1090. void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, PWIN32_FIND_DATA pWfdata)
  1091. {
  1092. m_VideoFiles.push(new TmpFileInfo(lpFilePath,
  1093. &(pWfdata->ftLastWriteTime),
  1094. pWfdata->nFileSizeHigh, pWfdata->nFileSizeLow));
  1095. ULARGE_INTEGER uiTemp;
  1096. uiTemp.HighPart = pWfdata->nFileSizeHigh;
  1097. uiTemp.LowPart = pWfdata->nFileSizeLow;
  1098. mAllVideoFileSizeCal.QuadPart += uiTemp.QuadPart;
  1099. if (mMaxFileSize.QuadPart < uiTemp.QuadPart) {
  1100. strcpy_s(szMaxSizeFilePath, lpFilePath);
  1101. mMaxFileSize.QuadPart = uiTemp.QuadPart;
  1102. }
  1103. SyncUpdateVideoCreateDaily(&(pWfdata->ftLastWriteTime), 1);
  1104. }
  1105. void ResourceWatcherFSM::CleanMoreVideoFiles()
  1106. {
  1107. EnterCriticalSection(&g_csVideoMoreClear);
  1108. ErrorCodeEnum erroCode = Error_Succeed;
  1109. BOOL bOK = FALSE;
  1110. CSmartPointer<IConfigInfo> spConfigRun;
  1111. ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1112. if (m_VideoFiles.empty()) {
  1113. int reseved = 0;
  1114. m_bReadyFlag = IsNeedToFirstClear();
  1115. int nRes = CleanVideoFiles(reseved, m_bReadyFlag ? 1 : 0);
  1116. if (nRes - reseved == 0) {
  1117. Dbg("There are no any video files in facts.");
  1118. SetSysValAndBroadcast(0, "There are no any video files in facts.");
  1119. LeaveCriticalSection(&g_csVideoMoreClear);
  1120. return;
  1121. }
  1122. }
  1123. if (mUiRequireBytes.QuadPart == 0ui64) {//更新记录运行时,并等待下一次的自检执行。
  1124. Dbg("empty?");
  1125. int reseved = 0;
  1126. CleanVideoFiles(reseved);
  1127. Dbg("Wait next time to execute...");
  1128. LeaveCriticalSection(&g_csVideoMoreClear);
  1129. return;
  1130. }
  1131. ULARGE_INTEGER uiSpaceRequired;
  1132. ULARGE_INTEGER uiSpaceRealRequired;
  1133. ULARGE_INTEGER uiFactor;
  1134. int CurRank = 3;
  1135. int BfRank = 0;
  1136. if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
  1137. BfRank = 0;
  1138. }
  1139. if (BfRank > 0) {
  1140. ULARGE_INTEGER uiTotalBytes;
  1141. ULARGE_INTEGER uiFreeDiskBytes;
  1142. if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1143. //对比上次,剩余的可用磁盘空间更小了。
  1144. if (mUiCalibration.QuadPart >= uiFreeDiskBytes.QuadPart) {
  1145. Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
  1146. CurRank = BfRank;
  1147. }
  1148. mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
  1149. }
  1150. }
  1151. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1152. int nEnoughLevel = 0;
  1153. do {
  1154. uiFactor.QuadPart = 0;
  1155. switch (CurRank) {
  1156. case 3:
  1157. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
  1158. break;
  1159. case 2:
  1160. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LESS_AVAILALBE_DATE_COUNT;
  1161. break;
  1162. case 1:
  1163. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LEAST_AVAILALBE_DATE_COUNT;
  1164. break;
  1165. default:
  1166. CurRank = 3;
  1167. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
  1168. }
  1169. ByteSprintf(szResult, (double)uiSpaceRequired.QuadPart);
  1170. Dbg("Required size(%d): %s", CurRank, szResult);
  1171. if (bOK = diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_uploadedVideoDirPath,
  1172. uiSpaceRequired, uiFactor, &uiSpaceRealRequired)) {
  1173. if (uiSpaceRealRequired.QuadPart == 0) {
  1174. break;
  1175. }
  1176. char displayTime[MAX_PATH] = { 0 };
  1177. FILETIME ftSavedTime;
  1178. //TODO: 暂时设置为至少保存两星期的录像文件,如果一天都不保留,那么 m_VideoFiles 要做即时更新 。2017-5-10
  1179. CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
  1180. GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
  1181. Dbg("SavedTime backtrace: %s", displayTime);
  1182. ULARGE_INTEGER uiFreeBytes;
  1183. uiFreeBytes.QuadPart = 0;
  1184. UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
  1185. BOOL bTrackBackStop = FALSE;
  1186. while (!m_VideoFiles.empty() && uiFreeBytes.QuadPart < uiSpaceRealRequired.QuadPart) {
  1187. TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
  1188. if (pCurFileInfo != NULL) {
  1189. SYSTEMTIME stUTC, stLocal;
  1190. FileTimeToSystemTime(&(pCurFileInfo->mftEditTime), &stUTC);
  1191. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  1192. if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
  1193. Dbg("yet %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
  1194. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1195. stLocal.wHour, stLocal.wMinute);
  1196. bTrackBackStop = TRUE;
  1197. break;
  1198. }
  1199. //if(TRUE)
  1200. if (DeleteFile(pCurFileInfo->msFileName.c_str()) != 0) {
  1201. ULARGE_INTEGER tmpBytes;
  1202. tmpBytes.HighPart = pCurFileInfo->mDwFileSizeHeight;
  1203. tmpBytes.LowPart = pCurFileInfo->mDwFileSizeLow;
  1204. uiFreeBytes.QuadPart += tmpBytes.QuadPart;
  1205. uDeletedCnt++;
  1206. Dbg("Delete suc: %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
  1207. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1208. stLocal.wHour, stLocal.wMinute);
  1209. SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
  1210. } else {
  1211. Dbg("[DelFail] File(%s) %u", pCurFileInfo->msFileName.c_str(), GetLastError());
  1212. uFailedDeleteCnt++;
  1213. }
  1214. }
  1215. m_VideoFiles.pop();
  1216. if (pCurFileInfo != NULL) delete pCurFileInfo;
  1217. }
  1218. char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1219. char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1220. ByteSprintf(szOutput, (double)uiFreeBytes.QuadPart);
  1221. ByteSprintf(szOutput2, (double)uiSpaceRealRequired.QuadPart);
  1222. Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
  1223. CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
  1224. if (uiFreeBytes.QuadPart >= uiSpaceRealRequired.QuadPart) {
  1225. break;
  1226. }
  1227. --CurRank;
  1228. UINT uCount = 0;
  1229. for (const_map_cu_iter citer = VideoDailyRecord.cbegin();
  1230. citer != VideoDailyRecord.cend(); citer++) {
  1231. uCount += citer->second;
  1232. }
  1233. Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
  1234. } else {
  1235. LogError(Severity_Middle, Error_Unexpect, 0, "IsNeedToDoClearJobEx invoked failed !");
  1236. LeaveCriticalSection(&g_csVideoMoreClear);
  1237. return;
  1238. }
  1239. } while (CurRank > 0);
  1240. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
  1241. if (CurRank < 3) {
  1242. ULARGE_INTEGER uiTotalBytes;
  1243. ULARGE_INTEGER uiFreeDiskBytes;
  1244. if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1245. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  1246. ByteSprintf(szResult, (double)uiTotalBytes.QuadPart);
  1247. ByteSprintf(szResult2, (double)uiFreeDiskBytes.QuadPart);
  1248. double dFreeRate = (uiFreeDiskBytes.QuadPart * kConversion[3]) / (uiTotalBytes.QuadPart * kConversion[3]);
  1249. sprintf_s(szResult3, "[Disk# %c:\\] total: %s, free: %s, rate: %.1lf%%.",
  1250. m_uploadedVideoDirPath[0], szResult, szResult2, dFreeRate * 100);
  1251. mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
  1252. } else {
  1253. strcpy_s(szResult3, "It's not enough disk space for recording video !");
  1254. }
  1255. if (CurRank == 0) {
  1256. CurRank = 4;
  1257. }
  1258. } else {
  1259. strcpy_s(szResult3, "Disk space is enough for recording.");
  1260. }
  1261. if (BfRank != CurRank) {
  1262. erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
  1263. }
  1264. SetSysValAndBroadcast(CurRank, szResult3);
  1265. LeaveCriticalSection(&g_csVideoMoreClear);
  1266. return;
  1267. }
  1268. #else
  1269. void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, struct stat* pWfdata)
  1270. {
  1271. m_VideoFiles.push(new TmpFileInfo(lpFilePath, pWfdata->st_mtime, pWfdata->st_size));
  1272. mAllVideoFileSizeCal += pWfdata->st_size;
  1273. if (mMaxFileSize < pWfdata->st_size) {
  1274. strcpy(szMaxSizeFilePath, lpFilePath);
  1275. mMaxFileSize = pWfdata->st_size;
  1276. }
  1277. SyncUpdateVideoCreateDaily(&pWfdata->st_mtime, 1);
  1278. }
  1279. void ResourceWatcherFSM::CleanMoreVideoFiles()
  1280. {
  1281. EnterCriticalSection(&g_csVideoMoreClear);
  1282. ErrorCodeEnum erroCode = Error_Succeed;
  1283. BOOL bOK = FALSE;
  1284. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
  1285. CSmartPointer<IConfigInfo> spConfigRun;
  1286. ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1287. if (m_VideoFiles.empty() || mUiRequireBytes == 0) {
  1288. int reseved = 0;
  1289. int nRes = CleanVideoFiles(reseved, IsNeedToFirstClear() ? 1 : 0);
  1290. if (nRes - reseved == 0) {
  1291. Dbg("There are no any video files in facts.");
  1292. //SetSysValAndBroadcast(0, "There are no any video files in facts.");
  1293. LeaveCriticalSection(&g_csVideoMoreClear);
  1294. return;
  1295. }
  1296. }
  1297. int CurRank = 3; //default
  1298. int BfRank = 0;
  1299. if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
  1300. BfRank = 0;
  1301. }
  1302. if (BfRank > 0) {
  1303. unsigned long long uiTotalBytes;
  1304. unsigned long long uiFreeDiskBytes;
  1305. if (!DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1306. LeaveCriticalSection(&g_csVideoMoreClear);
  1307. return;
  1308. }
  1309. //对比上次,剩余的可用磁盘空间更小了。
  1310. if (mUiCalibration >= uiFreeDiskBytes) {
  1311. Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
  1312. CurRank = BfRank == 4 ? 1 : BfRank;
  1313. }
  1314. mUiCalibration = uiFreeDiskBytes;
  1315. }
  1316. const int InitialRank = CurRank;
  1317. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1318. int nEnoughLevel = 0;
  1319. unsigned long long uiFactor;
  1320. char displayTime[MAX_PATH] = { 0 };
  1321. time_t ftSavedTime;
  1322. CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
  1323. GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
  1324. Dbg("It's SavedTime backtrace: %s", displayTime);
  1325. do {
  1326. uiFactor = DEFAULT_AVAILALBE_DATE_COUNT; // 7天
  1327. if (CurRank == 2) uiFactor = LESS_AVAILALBE_DATE_COUNT; // 3天
  1328. else if (CurRank == 1) uiFactor = LEAST_AVAILALBE_DATE_COUNT; // 1天
  1329. const unsigned long long uiSpaceRequired = mUiRequireBytes * uiFactor;
  1330. ByteSprintf(szResult, (double)uiSpaceRequired);
  1331. Dbg("Required free disk size: %s, current rank: %d", szResult, CurRank);
  1332. unsigned long long uiMoreSpaceRealRequired(0);
  1333. unsigned long long uiAdjustment(0);
  1334. if (diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_uploadedVideoDirPath, uiSpaceRequired, uiAdjustment, &uiMoreSpaceRealRequired)
  1335. && uiMoreSpaceRealRequired) {
  1336. unsigned long long uiNewFreeBytes(0);
  1337. UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
  1338. BOOL bTrackBackStop = FALSE;
  1339. Dbg("the more space required: %llu.", uiMoreSpaceRealRequired);
  1340. while (!m_VideoFiles.empty() && uiNewFreeBytes < uiMoreSpaceRealRequired) {
  1341. TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
  1342. if (pCurFileInfo != NULL) {
  1343. GetTimeFormatStr(displayTime, MAX_PATH, &(pCurFileInfo->mftEditTime));
  1344. if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
  1345. Dbg("stop at %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
  1346. bTrackBackStop = TRUE;
  1347. break;
  1348. }
  1349. if (RemoveFileA(pCurFileInfo->msFileName.c_str()) != 0) {
  1350. uiNewFreeBytes += pCurFileInfo->ftSize;
  1351. uDeletedCnt++;
  1352. Dbg("Delete suc: %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
  1353. SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
  1354. } else {
  1355. Dbg("[DelFail] File(%s) %d", pCurFileInfo->msFileName.c_str(), errno);
  1356. uFailedDeleteCnt++;
  1357. }
  1358. }
  1359. m_VideoFiles.pop();
  1360. if (pCurFileInfo != NULL) delete pCurFileInfo;
  1361. }
  1362. char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1363. char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1364. ByteSprintf(szOutput, (double)uiNewFreeBytes);
  1365. ByteSprintf(szOutput2, (double)uiMoreSpaceRealRequired);
  1366. Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
  1367. CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
  1368. if (uiNewFreeBytes >= uiMoreSpaceRealRequired) {
  1369. break;
  1370. } else {
  1371. --CurRank;
  1372. }
  1373. #ifdef WITH_DEBUG
  1374. UINT uCount = 0;
  1375. for (const_map_cu_iter citer = VideoDailyRecord.cbegin(); citer != VideoDailyRecord.cend(); citer++) { uCount += citer->second; }
  1376. Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
  1377. #endif
  1378. } else if (InitialRank > CurRank) {
  1379. break;
  1380. } else {
  1381. LeaveCriticalSection(&g_csVideoMoreClear);
  1382. return;
  1383. }
  1384. } while (CurRank > 0);
  1385. if (CurRank < 3) {
  1386. unsigned long long uiTotalBytes;
  1387. unsigned long long uiFreeDiskBytes;
  1388. if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1389. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  1390. ByteSprintf(szResult, (double)uiTotalBytes);
  1391. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  1392. double dFreeRate = (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  1393. sprintf(szResult3, "[Disk# %s] total: %s, free: %s, rate: %.1lf%%.",
  1394. m_uploadedVideoDirPath.GetData(), szResult, szResult2, dFreeRate * 100);
  1395. mUiCalibration = uiFreeDiskBytes;
  1396. } else {
  1397. strcpy(szResult3, "It's not enough disk space for recording video !");
  1398. }
  1399. } else {
  1400. strcpy(szResult3, "Disk space is enough for recording.");
  1401. }
  1402. if (CurRank == 0) { CurRank = 4; }
  1403. if (BfRank != CurRank) {
  1404. erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
  1405. }
  1406. SetSysValAndBroadcast(CurRank, szResult3);
  1407. LeaveCriticalSection(&g_csVideoMoreClear);
  1408. return;
  1409. }
  1410. #endif //_MSC_VER
  1411. bool ResourceWatcherFSM::IsNeedToFirstClear()
  1412. {
  1413. int nLastTaskTime(0);
  1414. CSmartPointer<IConfigInfo> spRunConfig;
  1415. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  1416. spRunConfig->ReadConfigValueInt("LastClearTime", "Video", nLastTaskTime);
  1417. return !IsTodayDone(nLastTaskTime);
  1418. }
  1419. int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt)
  1420. {
  1421. int fileCnt = 0;
  1422. int fileLength = strlen(lpszPath);
  1423. char* searchFilePath = new char[MAX_PATH];
  1424. char* tempFilePath = new char[MAX_PATH];
  1425. if (searchFilePath == NULL || tempFilePath == NULL) {
  1426. if (searchFilePath) delete[] searchFilePath;
  1427. if (tempFilePath) delete[] tempFilePath;
  1428. return fileCnt;
  1429. }
  1430. ZeroMemory(searchFilePath, MAX_PATH);
  1431. ZeroMemory(tempFilePath, MAX_PATH);
  1432. #if defined(_MSC_VER)
  1433. WIN32_FIND_DATA wfd;
  1434. HANDLE hFind;
  1435. hFind = FindFirstFile(lpszPath, &wfd);
  1436. if (hFind == INVALID_HANDLE_VALUE) {
  1437. Dbg("FindFirstFile failed GLE = %u.", GetLastError());
  1438. if (searchFilePath) delete[] searchFilePath;
  1439. if (tempFilePath) delete[] tempFilePath;
  1440. return 0;
  1441. }
  1442. do {
  1443. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  1444. if (wfd.cFileName[0] != '.') {
  1445. strcpy_s(tempFilePath, MAX_PATH, lpszPath);
  1446. tempFilePath[fileLength - 1] = '\0';
  1447. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH) {
  1448. Dbg("filePath is too long for current.");
  1449. } else {
  1450. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
  1451. CSimpleStringA tmpPath = tempFilePath;
  1452. strcat_s(tempFilePath, MAX_PATH, "\\*");
  1453. int tDelSucCnt = 0, tDelFailedCnt = 0;
  1454. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
  1455. if (tDelFailedCnt == 0 && !RemoveDirectoryA(tmpPath)) {
  1456. Dbg("RemoveDirectoryA(%s) failed, GLE = %u.", (LPCTSTR)tmpPath, GetLastError());
  1457. nDelFailedCnt++;
  1458. }
  1459. nDelFailedCnt += tDelFailedCnt;
  1460. nDelSucCnt += tDelSucCnt;
  1461. }
  1462. }
  1463. } else {
  1464. strcpy_s(searchFilePath, MAX_PATH, lpszPath);
  1465. searchFilePath[fileLength - 1] = '\0';
  1466. strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
  1467. if (DeleteFile(searchFilePath) != 0) {
  1468. nDelSucCnt++;
  1469. Dbg("Delete [%s] suc.", wfd.cFileName);
  1470. } else {
  1471. nDelFailedCnt++;
  1472. Dbg("Delete [%s] failed, GLE = %u.", wfd.cFileName, GetLastError());
  1473. }
  1474. fileCnt++;
  1475. }
  1476. } while (FindNextFileA(hFind, &wfd));
  1477. FindClose(hFind);
  1478. #else
  1479. struct stat st;
  1480. if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
  1481. if (searchFilePath) delete[] searchFilePath;
  1482. if (tempFilePath) delete[] tempFilePath;
  1483. Dbg("stat failed or is not dir.");
  1484. return fileCnt;
  1485. }
  1486. DIR* d = opendir(lpszPath);
  1487. if (!d) {
  1488. if (searchFilePath) delete[] searchFilePath;
  1489. if (tempFilePath) delete[] tempFilePath;
  1490. Dbg("opendir failed: %d", errno);
  1491. return fileCnt;
  1492. }
  1493. struct dirent* dp = NULL;
  1494. while ((dp = readdir(d)) != NULL) {
  1495. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1496. continue;
  1497. }
  1498. strcpy(tempFilePath, lpszPath);
  1499. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1500. Dbg("filePath is too long for current.");
  1501. continue;
  1502. }
  1503. strcat(tempFilePath, "/");
  1504. strcat(tempFilePath, dp->d_name);
  1505. stat(tempFilePath, &st);
  1506. bool isdir = !!(S_ISDIR(st.st_mode));
  1507. if (isdir) {
  1508. int tDelSucCnt = 0, tDelFailedCnt = 0;
  1509. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
  1510. if (tDelFailedCnt == 0 && rmdir(tempFilePath) != 0) {
  1511. Dbg("rmdir(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno);
  1512. nDelFailedCnt++;
  1513. }
  1514. nDelFailedCnt += tDelFailedCnt;
  1515. nDelSucCnt += tDelSucCnt;
  1516. } else {
  1517. if (RemoveFileA(tempFilePath)) {
  1518. nDelSucCnt++;
  1519. Dbg("Delete [%s] suc.", dp->d_name);
  1520. } else {
  1521. nDelFailedCnt++;
  1522. Dbg("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno);
  1523. }
  1524. fileCnt++;
  1525. }
  1526. }
  1527. closedir(d);
  1528. #endif //_MSC_VER
  1529. if (searchFilePath) delete[] searchFilePath;
  1530. if (tempFilePath) delete[] tempFilePath;
  1531. searchFilePath = NULL;
  1532. tempFilePath = NULL;
  1533. return fileCnt;
  1534. }
  1535. BOOL ResourceWatcherFSM::DeleteVersionPackage()
  1536. {
  1537. LOG_FUNCTION();
  1538. BOOL bRet = FALSE;
  1539. ErrorCodeEnum erroCode = Error_Succeed;
  1540. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  1541. CSmartPointer<IConfigInfo> spConfigRun;
  1542. CSystemStaticInfo info;
  1543. if (pFunc->GetSystemStaticInfo(info) != Error_Succeed) {
  1544. LogError(Severity_Middle, erroCode, 0, "Get system static info error");
  1545. return FALSE;
  1546. }
  1547. Dbg("Current version: %s", (LPCTSTR)info.InstallVersion.ToString());
  1548. int nLastTaskTime = 0;
  1549. int nLstFlag = 0;
  1550. UINT64 utVersion = 0;
  1551. pFunc->OpenConfig(Config_Run, spConfigRun);
  1552. spConfigRun->ReadConfigValueHexInt("VersionClear", "OptVer", utVersion);
  1553. spConfigRun->ReadConfigValueInt("VersionClear", "LastCondi", nLstFlag); //last times is failed or not? failed:true
  1554. spConfigRun->ReadConfigValueInt("VersionClear", "LastTime", nLastTaskTime);
  1555. CVersion optVer(utVersion);
  1556. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  1557. Dbg("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
  1558. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  1559. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  1560. (LPCTSTR)optVer.ToString(), nLstFlag);
  1561. //判断是否需要被清理
  1562. if (optVer.IsValid() && optVer == info.InstallVersion && !nLstFlag) {
  1563. Dbg("VersionPackage cleaning has been done before.");
  1564. return TRUE;
  1565. }
  1566. CSimpleStringA strRunInfo, strStartTime;
  1567. if (m_pEntity->GetFunction()->GetPath("RunInfo", strRunInfo) == Error_Succeed) {
  1568. strStartTime = strRunInfo + "/runcfg/starttime.dat";
  1569. if (!ExistsFileA(strStartTime.GetData())) {
  1570. Dbg("upgrade porcess done, try to delete version files.");//完成升级过程,通过
  1571. }
  1572. else {
  1573. Dbg("upgrade process is not end ,should not delete version files.");
  1574. return FALSE;//升级未完成,不进行删除
  1575. }
  1576. }
  1577. else {
  1578. Dbg("upgrade process is not end ,get runinfo path is error, should not delete version files.");
  1579. return FALSE;//失败,继续等待
  1580. }
  1581. //获取当前目录下的文件夹名称, 将符合命名规则的终端版本名称push_back
  1582. CSimpleStringA csPath;
  1583. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  1584. if (Error_Succeed == Error) {
  1585. if (csPath.IsNullOrEmpty())
  1586. {
  1587. Dbg("get currVer path is null");
  1588. return FALSE;
  1589. }
  1590. else
  1591. {
  1592. /*csPath.Append("/version");*/
  1593. Dbg("CUR VERSION PATH = %s.", csPath.GetData());
  1594. }
  1595. }
  1596. else {
  1597. Dbg("get upgradeVer path is error");
  1598. return FALSE;
  1599. }
  1600. //vector<CInstallInfoEx> intallInfoVects;
  1601. vector<CVersion> intallInfoVects;
  1602. vector<string> files;
  1603. DIR* dp;
  1604. struct dirent* dirp;
  1605. if ((dp = opendir(csPath.GetData())) != NULL) {
  1606. while ((dirp = readdir(dp)) != NULL) {
  1607. //files.push_back(string(dirp->d_name));
  1608. CInstallInfo verInfo = {};
  1609. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  1610. int n = sscanf(dirp->d_name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  1611. if (n != 4)
  1612. {
  1613. Dbg("Not version file.[%s]", dirp->d_name);
  1614. continue;
  1615. }
  1616. else {
  1617. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  1618. if (verName.IsValid() && verName < info.InstallVersion) //对高于自身版本的文件不予删除
  1619. {
  1620. //verInfo.InstallVersion = verName;
  1621. intallInfoVects.push_back(verName);
  1622. }
  1623. else {
  1624. Dbg("Not version file.[%s]", dirp->d_name);
  1625. }
  1626. }
  1627. }
  1628. closedir(dp);
  1629. }
  1630. CSimpleStringA upPath;
  1631. ErrorCodeEnum upError = m_pEntity->GetFunction()->GetPath("Upgraded", upPath);
  1632. if (Error_Succeed != upError) {
  1633. Dbg("get Upgraded path error");
  1634. return FALSE;
  1635. }
  1636. DIR* updp;
  1637. struct dirent* updirp;
  1638. if ((updp = opendir(upPath.GetData())) != NULL) {
  1639. while ((updirp = readdir(updp)) != NULL) {
  1640. char szPath[MAX_VERSION_PATH] = { 0 };
  1641. strcat(szPath, upPath.GetData());
  1642. CSimpleStringA tmpDirPath = szPath;
  1643. strcat(szPath, "/");
  1644. strcat(szPath, updirp->d_name);
  1645. Dbg("operating Upgrade path: [%s][%s]", (LPCTSTR)tmpDirPath, szPath);
  1646. RemoveFileA(szPath);
  1647. }
  1648. closedir(updp);
  1649. }
  1650. /*CVersion lastVer = info.PreviousInstallVersion;
  1651. while (lastVer.IsValid()) {
  1652. CInstallInfo lastVerInfo = {};
  1653. erroCode = pFunc->GetInstallInfo(lastVer, lastVerInfo);
  1654. if (erroCode != Error_Succeed) {
  1655. break;
  1656. }
  1657. intallInfoVects.push_back(CInstallInfoEx(lastVerInfo));
  1658. lastVer = lastVerInfo.PreviousInstallVersion;
  1659. }*/
  1660. int verSaved = DEFAULT_VERSION_SAVED_COUNT;
  1661. int tmpSaved = 0;
  1662. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  1663. CSmartPointer<IConfigInfo> spConfig;
  1664. spFunction->OpenConfig(Config_Software, spConfig);
  1665. spConfig->ReadConfigValueInt("VersionSaved", "default", tmpSaved);
  1666. if (tmpSaved > DEFAULT_VERSION_SAVED_COUNT)
  1667. {
  1668. verSaved = tmpSaved;
  1669. }
  1670. int nPackCount = intallInfoVects.size();
  1671. Dbg("Install Package's count: %d", nPackCount);
  1672. bool bFailFlag = false;
  1673. int nDelVersionCnt = 0;
  1674. if (nPackCount != 0) {
  1675. int nSavedCount = 0;
  1676. sort(intallInfoVects.begin(), intallInfoVects.end());
  1677. //vector<CInstallInfoEx>::iterator iter = intallInfoVects.begin();
  1678. vector<CVersion>::reverse_iterator riter = intallInfoVects.rbegin();
  1679. while (riter != intallInfoVects.rend()) {
  1680. //Dbg("InstallPackage Info: %s, SwithOverDate: %s", (LPCTSTR)iter->InstallVersion.ToString(), (LPCTSTR)iter->tmSwithOverDate.ToTimeString());
  1681. Dbg("InstallPackage Info: %s", (LPCTSTR)(*riter).ToString());
  1682. if (++nSavedCount <= verSaved) {
  1683. Dbg("Save above version");
  1684. riter++;
  1685. continue;
  1686. }
  1687. //if (!DeleteSpecificeVersionDir(iter->InstallVersion))
  1688. if(!DeleteSpecificeVersionDir(*riter))
  1689. bFailFlag = true;
  1690. else
  1691. nDelVersionCnt++;
  1692. riter++;
  1693. }
  1694. }
  1695. nLstFlag = bFailFlag ? 1 : 0;
  1696. spConfigRun->WriteConfigValueHexInt("VersionClear", "OptVer", info.InstallVersion.GetVersion64());
  1697. spConfigRun->WriteConfigValueInt("VersionClear", "LastCondi", nLstFlag);
  1698. spConfigRun->WriteConfigValue("VersionClear", "LastTime",
  1699. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  1700. string warn = "Delete Version files count : " + to_string(nDelVersionCnt);
  1701. LogWarn(Severity_Low, Error_Debug, LOG_WARN_VER_DELETE, CSimpleStringA::Format("%s", warn.c_str()));
  1702. return TRUE;
  1703. }
  1704. BOOL ResourceWatcherFSM::DeleteSpecificeVersionDir(CVersion version)
  1705. {
  1706. ErrorCodeEnum erroCode = Error_Unexpect;
  1707. CSimpleStringA strPath;
  1708. if (GetEntityBase()->GetFunction()->GetPath("RootVer", strPath) != Error_Succeed)
  1709. return FALSE;
  1710. strPath = strPath + SPLIT_SLASH_STR + version.ToString();
  1711. if (!ExistsDirA(strPath)) {
  1712. Dbg("Directory(%s) Not Existed, Maybe delete before !!", strPath.GetData());
  1713. return TRUE;
  1714. }
  1715. CSimpleStringA tmpDirPath = strPath;
  1716. #if defined(_MSC_VER)
  1717. tmpDirPath += "\\*";
  1718. #endif //_MSC_VER
  1719. Dbg("operating version path: [%s][%s]", (LPCTSTR)tmpDirPath, (LPCTSTR)strPath);
  1720. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  1721. nFileCount = ProcessFileDelete((LPCTSTR)tmpDirPath, nDelSuc, nDelFail);
  1722. Dbg("Process result(%s): count(%d), suc(%d), failed(%d).", tmpDirPath.GetData(), nFileCount, nDelSuc, nDelFail);
  1723. #if defined(_MSC_VER)
  1724. if (nDelFail != 0 || !RemoveDirectoryA(tmpDirPath)) {
  1725. Dbg("Unexpect condition happen: (%d)(%u).", nDelFail, GetLastError());
  1726. #else
  1727. if (nDelFail != 0 || rmdir(tmpDirPath) != 0) {
  1728. Dbg("Unexpect condition happen: (%d)", nDelFail);
  1729. #endif //_MSC_VER
  1730. return FALSE;
  1731. }
  1732. return TRUE;
  1733. }
  1734. #if defined(_MSC_VER)
  1735. int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, PULARGE_INTEGER puliSpaceBytes)
  1736. {
  1737. int fileCnt = 0;
  1738. int fileLength = strlen(lpszPath);
  1739. char* searchFilePath = new char[MAX_PATH];
  1740. char* tempFilePath = new char[MAX_PATH];
  1741. if (searchFilePath == NULL || tempFilePath == NULL) {
  1742. if (searchFilePath) delete[] searchFilePath;
  1743. if (tempFilePath) delete[] tempFilePath;
  1744. return fileCnt;
  1745. }
  1746. ZeroMemory(searchFilePath, MAX_PATH);
  1747. ZeroMemory(tempFilePath, MAX_PATH);
  1748. WIN32_FIND_DATA wfd;
  1749. HANDLE hFind;
  1750. hFind = FindFirstFile(lpszPath, &wfd);
  1751. if (hFind == INVALID_HANDLE_VALUE) {
  1752. Dbg("FindFirstFile failed GLE = %u.", GetLastError());
  1753. if (searchFilePath) delete[] searchFilePath;
  1754. if (tempFilePath) delete[] tempFilePath;
  1755. return 0;
  1756. }
  1757. do {
  1758. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  1759. if (wfd.cFileName[0] != '.') {
  1760. strcpy_s(tempFilePath, MAX_PATH, lpszPath);
  1761. tempFilePath[fileLength - 1] = '\0';
  1762. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH) {
  1763. Dbg("filePath is too long for current.");
  1764. } else {
  1765. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
  1766. strcat_s(tempFilePath, MAX_PATH, "\\*");
  1767. fileCnt += CalculateAllVideoSize((LPCTSTR)tempFilePath, puliSpaceBytes);
  1768. }
  1769. }
  1770. } else {
  1771. strcpy_s(searchFilePath, MAX_PATH, lpszPath);
  1772. searchFilePath[fileLength - 1] = '\0';
  1773. strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
  1774. ULARGE_INTEGER uiTemp;
  1775. uiTemp.HighPart = wfd.nFileSizeHigh;
  1776. uiTemp.LowPart = wfd.nFileSizeLow;
  1777. puliSpaceBytes->QuadPart += uiTemp.QuadPart;
  1778. SyncUpdateVideoCreateDaily(&wfd.ftLastWriteTime, 1);
  1779. fileCnt++;
  1780. }
  1781. } while (FindNextFileA(hFind, &wfd));
  1782. FindClose(hFind);
  1783. if (searchFilePath) delete[] searchFilePath;
  1784. if (tempFilePath) delete[] tempFilePath;
  1785. return fileCnt;
  1786. }
  1787. #else
  1788. int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, unsigned long long* puliSpaceBytes)
  1789. {
  1790. int fileCnt = 0;
  1791. int fileLength = strlen(lpszPath);
  1792. char* searchFilePath = new char[MAX_PATH];
  1793. char* tempFilePath = new char[MAX_PATH];
  1794. if (searchFilePath == NULL || tempFilePath == NULL) {
  1795. if (searchFilePath) delete[] searchFilePath;
  1796. if (tempFilePath) delete[] tempFilePath;
  1797. return fileCnt;
  1798. }
  1799. ZeroMemory(searchFilePath, MAX_PATH);
  1800. ZeroMemory(tempFilePath, MAX_PATH);
  1801. struct stat st;
  1802. if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
  1803. if (searchFilePath) delete[] searchFilePath;
  1804. if (tempFilePath) delete[] tempFilePath;
  1805. return fileCnt;
  1806. }
  1807. DIR* d = opendir(lpszPath);
  1808. if (!d) {
  1809. if (searchFilePath) delete[] searchFilePath;
  1810. if (tempFilePath) delete[] tempFilePath;
  1811. return fileCnt;
  1812. }
  1813. struct dirent* dp = NULL;
  1814. while ((dp = readdir(d)) != NULL) {
  1815. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1816. continue;
  1817. }
  1818. strcpy(tempFilePath, lpszPath);
  1819. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1820. Dbg("filePath is too long for current.");
  1821. continue;
  1822. }
  1823. strcat(tempFilePath, "/");
  1824. strcat(tempFilePath, dp->d_name);
  1825. stat(tempFilePath, &st);
  1826. const bool isdir = !!(S_ISDIR(st.st_mode));
  1827. if (isdir) {
  1828. fileCnt += CalculateAllVideoSize((LPCTSTR)tempFilePath, puliSpaceBytes);
  1829. } else {
  1830. *puliSpaceBytes += st.st_size;
  1831. SyncUpdateVideoCreateDaily(&st.st_mtime, 1);
  1832. fileCnt++;
  1833. }
  1834. }
  1835. closedir(d);
  1836. if (searchFilePath) delete[] searchFilePath;
  1837. if (tempFilePath) delete[] tempFilePath;
  1838. return fileCnt;
  1839. }
  1840. #endif //_MSC_VER
  1841. void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType,
  1842. CSmartPointer<ITransactionContext> pTransactionContext)
  1843. {
  1844. static uint32_t times = 0;
  1845. pTransactionContext->SendAnswer(Error_Succeed);
  1846. times++;
  1847. if (m_bVideoClearReady && times > 60 * 2) { //2 hour per times
  1848. times = 0;
  1849. PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
  1850. }
  1851. }
  1852. void ResourceWatcherFSM::SetSysValAndBroadcast(DWORD dwVal, LPCTSTR lpszMessage)
  1853. {
  1854. static DWORD dwOldVal = (DWORD)-1;
  1855. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  1856. CSimpleStringA csVPStatus = VIDEO_SPACE_UNKNOWN;
  1857. CSimpleStringA csNewVPSatus = VIDEO_SPACE_UNKNOWN;
  1858. spFunction->GetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csVPStatus);
  1859. if (dwVal == 4) {
  1860. csNewVPSatus = VIDEO_SPACE_INSUFF_FATAL;
  1861. LogError(Severity_High, Error_TooSmallBuffer, LOG_ERR_RES_VIDEO_INSUFFICIENT, lpszMessage);
  1862. } else if (dwVal == 2) {
  1863. csNewVPSatus = VIDEO_SPACE_INSUFF_LITTLE;
  1864. if (dwVal != dwOldVal)
  1865. LogWarn(Severity_Middle, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
  1866. } else if (dwVal == 1) {
  1867. csNewVPSatus = VIDEO_SPACE_INSUFF_LESS;
  1868. if (dwVal != dwOldVal)
  1869. LogWarn(Severity_Low, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
  1870. } else if (dwVal == 3) {
  1871. csNewVPSatus = VIDEO_SPACE_SUFFICIENT;
  1872. if (dwVal != dwOldVal)
  1873. LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
  1874. } else if (dwVal == 0) {
  1875. if (dwVal != dwOldVal)
  1876. LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
  1877. } else {
  1878. Dbg("Unknow dwVal: %d", dwVal);
  1879. }
  1880. if (csNewVPSatus != csVPStatus) {
  1881. ErrorCodeEnum eRet = spFunction->SetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csNewVPSatus);
  1882. Dbg("SetSysVar(%s) from '%s' to '%s' returned %d",
  1883. SYSVAR_DISKSTATEUS_FOR_VIDEO
  1884. , (LPCTSTR)csVPStatus
  1885. , (LPCTSTR)csNewVPSatus
  1886. , eRet);
  1887. }
  1888. dwOldVal = dwVal;
  1889. }
  1890. BOOL ResourceWatcherFSM::InitialDirectoryEntity(LPCTSTR lpszPath, DWORD & dwFileCnt, const DWORD dwFilterAttributes)
  1891. {
  1892. LOG_FUNCTION();
  1893. if (lpszPath == NULL) {
  1894. SetLastError(ERROR_INVALID_PARAMETER);
  1895. LogWarn(Severity_Middle, Error_Param, ERROR_INVALID_PARAMETER, "Null file path !");
  1896. return FALSE;
  1897. }
  1898. #if defined(_MSC_VER)
  1899. HANDLE hFile = CreateFileA(
  1900. lpszPath,
  1901. GENERIC_READ,
  1902. FILE_SHARE_READ,
  1903. NULL,
  1904. OPEN_EXISTING,
  1905. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
  1906. NULL);
  1907. if (hFile == INVALID_HANDLE_VALUE) {
  1908. Dbg("CreateFileA(%s) failed", lpszPath);
  1909. return FALSE;
  1910. }
  1911. #endif //_MSC_VER
  1912. m_FileEntry.SubFiles.Clear();
  1913. m_FileEntry.FileNamesBuffer.Clear();
  1914. m_FileEntry.Current.Clear();
  1915. DWORD dwLocate;
  1916. Append(m_FileEntry.FileNamesBuffer, (PBYTE)lpszPath, strlen(lpszPath), dwLocate);
  1917. m_FileEntry.Current.mNameOffset = dwLocate;
  1918. m_FileEntry.Current.mNameLength = strlen(lpszPath);
  1919. #if defined(_MSC_VER)
  1920. GetFileTime(hFile, (LPFILETIME)&m_FileEntry.Current.mftCreate,
  1921. (LPFILETIME)&m_FileEntry.Current.mftAccess, (LPFILETIME)&m_FileEntry.Current.mftModified);
  1922. CloseHandle(hFile);
  1923. hFile = NULL;
  1924. m_FileEntry.Current.mAttributes = GetFileAttributesA(lpszPath);
  1925. m_FileEntry.Current.mFileSize = 0;
  1926. #else
  1927. struct stat st;
  1928. if (stat(lpszPath, &st) < 0) {
  1929. Dbg("stat %s failed.", lpszPath);
  1930. return FALSE;
  1931. }
  1932. //GetFileTime
  1933. m_FileEntry.Current.mftCreate = st.st_ctime;
  1934. m_FileEntry.Current.mftAccess = st.st_atime;
  1935. m_FileEntry.Current.mftModified = st.st_mtime;
  1936. m_FileEntry.Current.mAttributes = 0;
  1937. //GetFileAttributesA
  1938. if (S_ISDIR(st.st_mode)) {
  1939. m_FileEntry.Current.mFileSize = 0;
  1940. m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_DIRECTORY;
  1941. } else {
  1942. m_FileEntry.Current.mFileSize = st.st_size;
  1943. }
  1944. if (m_FileEntry.Current.mAttributes == 0)
  1945. m_FileEntry.Current.mAttributes = FILE_ATTRIBUTE_ARCHIVE;
  1946. if (!(st.st_mode & S_IWUSR))
  1947. m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_READONLY;
  1948. #endif //_MSC_VER
  1949. DWORD dwDir = 0, dwFile = 0;
  1950. GetSubFileInfors(&m_FileEntry, dwDir, dwFile, dwFilterAttributes);
  1951. Dbg("Flag: dwDir:%u, dwFile: %u", dwDir, dwFile);
  1952. DisplayFileEntities(&m_FileEntry);
  1953. dwFileCnt = dwDir + dwFile;
  1954. #if defined(RVC_OS_LINUX)
  1955. m_FileEntry.Current.mFileSize = dwFileCnt;
  1956. #endif //RVC_OS_LINUX
  1957. return TRUE;
  1958. }
  1959. DWORD ResourceWatcherFSM::InitialVolumes()
  1960. {
  1961. LOG_FUNCTION();
  1962. UINT uCount = 0;
  1963. #if defined(RVC_OS_WIN)
  1964. /*获取磁盘信息,该坐标下的内容作为是否遍历的标识*/
  1965. if (!sBDiskValStatus[MAX_VOLUME_COUNT]) {
  1966. CHAR szDrivers[BUFSIZE] = { 0 };
  1967. CHAR szVolumeName[MAX_PATH] = { 0 };
  1968. CHAR szFileSysName[MAX_PATH] = { 0 };
  1969. BOOL bRet = GetLogicalDriveStringsA(BUFSIZE - 1, szDrivers);
  1970. if (bRet) {
  1971. Dbg("szDrivers: %s", szDrivers);
  1972. for (CHAR* pTemp = szDrivers; *pTemp != '\0'; pTemp += 4) {
  1973. if (*pTemp >= 'a' && *pTemp <= 'z') *pTemp -= 32;
  1974. const int nDriNum = *pTemp - 'A';
  1975. if (DRIVE_FIXED == GetDriveType(pTemp)) {
  1976. DWORD dwMaxCompLen, dwFileSystemFlags;
  1977. bRet = GetVolumeInformation(pTemp, szVolumeName, MAX_PATH, NULL,
  1978. &dwMaxCompLen, &dwFileSystemFlags, szFileSysName, MAX_PATH);
  1979. sBDiskValStatus[nDriNum] = TRUE;
  1980. uCount++;
  1981. } else {
  1982. sBDiskValStatus[nDriNum] = FALSE;
  1983. }
  1984. }
  1985. }
  1986. if (uCount > 0) {
  1987. sBDiskValStatus[MAX_VOLUME_COUNT] = TRUE;
  1988. }
  1989. }
  1990. m_FileEntry.SubFiles.Clear();
  1991. m_FileEntry.FileNamesBuffer.Clear();
  1992. m_FileEntry.Current.Clear();
  1993. uCount = 0;
  1994. ULARGE_INTEGER uiTotalBytes, uiTotalFreeBytes;
  1995. if (sBDiskValStatus[MAX_VOLUME_COUNT]) {
  1996. m_FileEntry.Current.mLevel = -2; //mark parent of volume -2-level
  1997. char szVolume[8] = { 0 };
  1998. for (int i = 0; i < MAX_VOLUME_COUNT; ++i) {
  1999. if (sBDiskValStatus[i]) {
  2000. szVolume[0] = i + 'A';
  2001. szVolume[1] = ':';
  2002. szVolume[2] = '\0';
  2003. CSimpleFileComponent volume;
  2004. if (DiskInfo::GetDiskSpace(szVolume, uiTotalBytes, uiTotalFreeBytes)) {
  2005. volume.mFileSize = uiTotalFreeBytes.QuadPart;
  2006. }
  2007. volume.mLevel = 0;
  2008. volume.mNameLength = strlen(szVolume);
  2009. Append(m_FileEntry.FileNamesBuffer, (PBYTE)szVolume, volume.mNameLength, volume.mNameOffset);
  2010. volume.mAttributes = 0;
  2011. m_FileEntry.SubFiles.Append(&volume, 0, 1);
  2012. uCount++;
  2013. }
  2014. }
  2015. }
  2016. DisplayFileEntities(&m_FileEntry);
  2017. #else
  2018. #endif //RVC_OS_WIN
  2019. return uCount;
  2020. }
  2021. DWORD ResourceWatcherFSM::ProcessFileOperation(
  2022. const SpReqAnsContext<ResourceWatcherService_OperateFile_Req, ResourceWatcherService_OperateFile_Ans>::Pointer & ctx)
  2023. {
  2024. if (ctx == NULL) {
  2025. return 0;
  2026. }
  2027. ResourceWatcherService_OperateFile_Req& req = ctx->Req;
  2028. ResourceWatcherService_OperateFile_Ans& ans = ctx->Ans;
  2029. {
  2030. ans.header = "";
  2031. ans.attachment1 = 0;
  2032. ans.attachment2 = "";
  2033. ans.fileSize = 0ULL;
  2034. ans.ftCreate = 0ULL;
  2035. ans.ftModified = 0ULL;
  2036. ans.ftAccess = 0ULL;
  2037. ans.fileAttribute = 0U;
  2038. ans.count = 0;
  2039. }
  2040. CSimpleStringA strCurrent(true);
  2041. size_t nCurLen = req.current.GetLength();
  2042. Dbg("size of current dir: %d", nCurLen);
  2043. if (!req.current.IsNullOrEmpty()) {
  2044. CSimpleStringA strTemp = req.current.Trim();
  2045. size_t len = req.current.GetLength();
  2046. while (len > 0 && (strTemp[len - 1] == '\\' || strTemp[len - 1] == '/')) {
  2047. strTemp[len - 1] = '\0';
  2048. len--;
  2049. }
  2050. if (len > 0) {
  2051. strCurrent = strTemp.Trim();
  2052. nCurLen = strCurrent.GetLength();
  2053. LOG_ASSERT(len == nCurLen);
  2054. Dbg("size of strCurrent: %d", nCurLen);
  2055. }
  2056. }
  2057. BOOL bCurNull = strCurrent.IsNullOrEmpty();
  2058. if (!bCurNull) {
  2059. int nRes = FilterFilePathAhead(strCurrent, req.mode);
  2060. if (nRes != 0) {
  2061. ans.result = OPT_FILE_RES_FAILED;
  2062. CSimpleStringA strTxt;
  2063. switch (nRes) {
  2064. case -1:
  2065. case -2:
  2066. strTxt = "文件路径参数错误。";
  2067. break;
  2068. case -3:
  2069. strTxt = "终端指定磁盘不存在。";
  2070. break;
  2071. case 1:
  2072. strTxt = "操作非法:不允许删除盘符。";
  2073. break;
  2074. case 2:
  2075. strTxt = "请求的操作无权限。";
  2076. break;
  2077. default:
  2078. strTxt = "操作失败,原因未知。";
  2079. break;
  2080. }
  2081. ans.attachment1 = strTxt.GetLength();
  2082. ans.attachment2 = strTxt;
  2083. ctx->Answer(Error_Succeed);
  2084. Dbg("Try to (option:%d) [%s] failed (%d): %s", req.mode, (LPCTSTR)strCurrent, nRes, (LPCTSTR)strTxt);
  2085. return nRes;
  2086. }
  2087. }
  2088. FileType type = FT_Unknown;
  2089. IsPathExisted(strCurrent, type);
  2090. int count = 0;
  2091. ans.count = 0;
  2092. ans.result = OPT_FILE_RES_INVALID;
  2093. bool bNeedToRefleshHeader = false;
  2094. bool bNeedToSetCtxEntities = false;
  2095. bool bNeedToRefleshEntity = false;
  2096. int updateLevel = 0;
  2097. switch (ctx->Req.mode) {
  2098. case OPT_FILE_CMD_SPREAD: //0
  2099. {
  2100. DWORD dwRes = 0;
  2101. if (!bCurNull && (type == FT_Unknown || type == FT_File)) {
  2102. ans.result = OPT_FILE_RES_FAILED;
  2103. ans.attachment1 = GetErrorMessage(ans.attachment2, "请求的文件不存在或类型不正确。");
  2104. Dbg("Before Initial File Entity failed: %s", ans.attachment2.GetData());
  2105. break;
  2106. }
  2107. DWORD dwFilterAttributes = (DWORD)(ctx->Req.filter1);
  2108. if (bCurNull) {
  2109. #if defined(_MSC_VER)
  2110. dwRes = InitialVolumes();
  2111. #else
  2112. if (!InitialDirectoryEntity("/", dwRes, dwFilterAttributes)) {
  2113. ans.result = OPT_FILE_RES_FAILED;
  2114. ans.attachment1 = GetErrorMessage(ans.attachment2, "获取根目录列表失败");
  2115. Dbg("Initial File Entity failed: %s", ans.attachment2.GetData());
  2116. break;
  2117. }
  2118. #endif //_MSC_VER
  2119. } else if (!InitialDirectoryEntity(strCurrent, dwRes, dwFilterAttributes)) {
  2120. ans.result = OPT_FILE_RES_FAILED;
  2121. ans.attachment1 = GetErrorMessage(ans.attachment2, "获取文件列表失败");
  2122. Dbg("Initial File Entity failed: %s", ans.attachment2.GetData());
  2123. break;
  2124. }
  2125. Dbg("%d VS %d", dwRes, m_FileEntry.SubFiles.GetCount());
  2126. LOG_ASSERT(dwRes == m_FileEntry.SubFiles.GetCount());
  2127. count = dwRes;
  2128. ans.result = OPT_FILE_RES_SUCCESS;
  2129. bNeedToSetCtxEntities = true;
  2130. bNeedToRefleshHeader = true;
  2131. }
  2132. break;
  2133. case OPT_FILE_CMD_EXECUTE://1
  2134. {
  2135. if (type != FT_File) {
  2136. Dbg("Invalid file type !");
  2137. ans.result = OPT_FILE_RES_INVALID;
  2138. ans.attachment2 = "非可打开或执行的文件类型(目录或其他)";
  2139. ans.attachment1 = ans.attachment2.GetLength();
  2140. break;
  2141. }
  2142. LPCTSTR lpParam = NULL;
  2143. if (req.attachment1 > 0 && req.attachment2.GetLength() > 0)
  2144. lpParam = req.attachment2;
  2145. const DWORD dwRes = ExecuteFile(strCurrent, lpParam);
  2146. ans.result = dwRes ? OPT_FILE_RES_FAILED : OPT_FILE_RES_SUCCESS;
  2147. if (dwRes) {
  2148. #if defined(_MSC_VER)
  2149. ans.attachment1 = GetErrorMessage(ans.attachment2, "执行文件操作失败。");
  2150. Dbg("ExecuteFile failed: %s", (LPCTSTR)ans.attachment2);
  2151. #else
  2152. ans.attachment2 = "不支持该操作";
  2153. ans.attachment1 = ans.attachment2.GetLength();
  2154. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2155. #endif //_MSC_VER
  2156. }
  2157. }
  2158. break;
  2159. case OPT_FILE_CMD_DELETE: //2
  2160. case OPT_FILE_CMD_CLEAR: //3
  2161. {
  2162. bool bClear = !!(ctx->Req.mode == OPT_FILE_CMD_CLEAR);
  2163. if (!bClear) { Dbg("Delete flag."); }
  2164. if (type == FT_Unknown) {
  2165. ans.result = OPT_FILE_RES_INVALID;
  2166. ans.attachment2 = "所指定的文件不存在。";
  2167. ans.attachment1 = ans.attachment2.GetLength();
  2168. break;
  2169. }
  2170. #if defined(_MSC_VER)
  2171. if (type == FT_Volume) {
  2172. if (!bClear) {
  2173. ans.result = OPT_FILE_RES_INVALID;
  2174. ans.attachment2 = "该操作对卷类型的文件无效。";
  2175. ans.attachment1 = ans.attachment2.GetLength();
  2176. } else if (ClearDirRecursiveA(strCurrent)) {
  2177. ans.result = OPT_FILE_RES_SUCCESS;
  2178. bNeedToRefleshEntity = true;
  2179. } else {
  2180. ans.attachment2 = "清空卷操作执行失败。";
  2181. ans.attachment1 = ans.attachment2.GetLength();
  2182. ans.result = OPT_FILE_RES_FAILED;
  2183. }
  2184. break;
  2185. }
  2186. #endif //_MSC_VER
  2187. if ((type == FT_Directory
  2188. && (
  2189. (!bClear && !RemoveDirRecursiveA(strCurrent))
  2190. || (bClear && !ClearDirRecursiveA(strCurrent))
  2191. ))
  2192. || (type == FT_File && !bClear && !RemoveFileA(strCurrent))) {
  2193. ans.attachment1 = GetErrorMessage(ans.attachment2, ((!bClear) ? "删除操作执行失败。" : "清空操作执行失败。"));
  2194. Dbg("Delete(%d) or clear file failed: %s", !bClear, ans.attachment2.GetData());
  2195. ans.result = OPT_FILE_RES_FAILED;
  2196. break;
  2197. }
  2198. if (type == FT_File && bClear) {//文件内容清理
  2199. //simple implement
  2200. FILE* stream;
  2201. SetLastError(0);
  2202. if ((stream = fopen(strCurrent, "w+")) == NULL) {
  2203. ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
  2204. ans.result = OPT_FILE_RES_FAILED;
  2205. break;
  2206. }
  2207. if (fclose(stream)) {
  2208. Dbg("fclose(%s) failed", (LPCTSTR)strCurrent);
  2209. ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
  2210. ans.result = OPT_FILE_RES_FAILED;
  2211. break;
  2212. }
  2213. }
  2214. ans.result = OPT_FILE_RES_SUCCESS;
  2215. bNeedToRefleshEntity = true;
  2216. if ((!bClear && type != FT_File) || (bClear && type == FT_File)) {
  2217. updateLevel = 1;
  2218. }
  2219. }
  2220. break;
  2221. case OPT_FILE_CMD_CREATE: //4
  2222. {
  2223. if ((type == FT_Directory && (req.attribute & 0x10)) || (type == FT_File && !(req.attribute & 0x10)) || type == FT_Volume) {
  2224. Dbg("Existed file occurs create(%d) ?", type);
  2225. ans.result = OPT_FILE_RES_FAILED;
  2226. ans.attachment2 = "目录或文件已存在。";
  2227. ans.attachment1 = ans.attachment2.GetLength();
  2228. break;
  2229. }
  2230. BOOL bRet = FALSE;
  2231. int depth = GetPathDepth(strCurrent);
  2232. if (depth <= 0) {
  2233. Dbg("Invalid file path(%s)", (LPCTSTR)strCurrent);
  2234. ans.result = OPT_FILE_RES_FAILED;
  2235. ans.attachment2 = "非法文件路径或名称。";
  2236. ans.attachment1 = ans.attachment2.GetLength();
  2237. break;
  2238. }
  2239. if (req.attribute & 0x10) {
  2240. Dbg("Start to create directory");
  2241. if (!CreateDirA(strCurrent, TRUE)) {
  2242. ans.attachment1 = GetErrorMessage(ans.attachment2, "新建文件夹失败。");
  2243. Dbg("Create directory failed: %s", ans.attachment2.GetData());
  2244. ans.result = OPT_FILE_RES_FAILED;
  2245. break;
  2246. }
  2247. } else {
  2248. #if defined(RVC_OS_WIN)
  2249. if (depth == 1/*根目录下创建文件*/ || CreateParentDirA(strCurrent, TRUE)) {
  2250. DWORD dwNewAttr = FILE_ATTRIBUTE_NORMAL/* | req.attribute*/;
  2251. HANDLE hNewFile = CreateFileA(strCurrent, GENERIC_WRITE,
  2252. 0, NULL, CREATE_NEW, dwNewAttr, NULL);
  2253. if (hNewFile == INVALID_HANDLE_VALUE) {
  2254. ans.attachment1 = GetErrorMessage(ans.attachment2, "创建文件失败。");
  2255. Dbg("Create file failed: %s", ans.attachment2.GetData());
  2256. ans.result = OPT_FILE_RES_FAILED;
  2257. break;
  2258. }
  2259. if (req.content.GetLength() >= 0) {
  2260. DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
  2261. DWORD dwByteWritten = 0;
  2262. DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
  2263. LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2264. BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
  2265. dwBytesToWrite, &dwByteWritten, NULL);
  2266. UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2267. if (!bRes || dwByteWritten != dwBytesToWrite) {
  2268. ans.attachment1 = GetErrorMessage(ans.attachment2,
  2269. !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
  2270. Dbg("Write file failed: %s", ans.attachment2.GetData());
  2271. Dbg("Write file is incompletely(%u/%u)", dwByteWritten, dwBytesToWrite);
  2272. CloseHandle(hNewFile);
  2273. DeleteFileA(strCurrent);
  2274. ans.result = OPT_FILE_RES_FAILED;
  2275. break;
  2276. }
  2277. }
  2278. CloseHandle(hNewFile);
  2279. } else {
  2280. ans.attachment1 = GetErrorMessage(ans.attachment2, "创建目标文件所在目录失败。");
  2281. Dbg("Create parent directory failed: %s", (LPCTSTR)ans.attachment2);
  2282. ans.result = OPT_FILE_RES_FAILED;
  2283. break;
  2284. }
  2285. #else
  2286. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2287. ans.attachment2 = "不支持操作";
  2288. ans.attachment1 = ans.attachment2.GetLength();
  2289. break;
  2290. #endif //RVC_OS_WIN
  2291. }
  2292. ans.result = OPT_FILE_RES_SUCCESS;
  2293. bNeedToRefleshEntity = true;
  2294. updateLevel = 1;
  2295. }
  2296. break;
  2297. case OPT_FILE_CMD_APPEND: //5
  2298. #if defined(_MSC_VER)
  2299. {
  2300. if (type != FT_File) {
  2301. Dbg("file is not existed(%d) ?", type);
  2302. ans.result = OPT_FILE_RES_FAILED;
  2303. ans.attachment2 = "目标文件不存在或非文件类型。";
  2304. ans.attachment1 = ans.attachment2.GetLength();
  2305. break;
  2306. } else if (req.content.GetLength() <= 0) {
  2307. Dbg("invalid file content %d", req.content.GetLength());
  2308. ans.result = OPT_FILE_RES_FAILED;
  2309. ans.attachment2 = "写入的文件内容不存在。";
  2310. ans.attachment1 = ans.attachment2.GetLength();
  2311. break;
  2312. }
  2313. DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
  2314. DWORD dwByteWritten = 0;
  2315. HANDLE hNewFile = CreateFileA(strCurrent, FILE_APPEND_DATA,
  2316. FILE_SHARE_READ, NULL, /*OPEN_EXISTING*/OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  2317. if (hNewFile == INVALID_HANDLE_VALUE) {
  2318. ans.attachment1 = GetErrorMessage(ans.attachment2, "打开文件失败。");
  2319. Dbg("open file failed: %s", (LPCTSTR)ans.attachment2);
  2320. ans.result = OPT_FILE_RES_FAILED;
  2321. break;
  2322. }
  2323. DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
  2324. LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2325. BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
  2326. dwBytesToWrite, &dwByteWritten, NULL);
  2327. UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2328. if (!bRes || dwByteWritten != dwBytesToWrite) {
  2329. ans.attachment1 = GetErrorMessage(ans.attachment2, !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
  2330. Dbg("Append file failed: %s", ans.attachment2.GetData());
  2331. Dbg("Append file is incompletely(%u/%u)", dwByteWritten, dwBytesToWrite);
  2332. ans.result = OPT_FILE_RES_FAILED;
  2333. CloseHandle(hNewFile);
  2334. DeleteFileA(strCurrent);
  2335. ans.result = OPT_FILE_RES_FAILED;
  2336. break;
  2337. }
  2338. CloseHandle(hNewFile);
  2339. ans.result = OPT_FILE_RES_SUCCESS;
  2340. bNeedToRefleshEntity = true;
  2341. updateLevel = 1;
  2342. }
  2343. #else
  2344. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2345. ans.attachment2 = "不支持操作";
  2346. ans.attachment1 = ans.attachment2.GetLength();
  2347. #endif //_MSC_VER
  2348. break;
  2349. case OPT_FILE_CMD_RENAME: //6
  2350. {
  2351. #if defined(_MSC_VER)
  2352. Dbg("Rename a file ? it would be critical...");
  2353. if (type == FT_Unknown || type == FT_Volume) {
  2354. Dbg("file is not existed(%d)?", type);
  2355. ans.result = OPT_FILE_RES_FAILED;
  2356. ans.attachment2 = type == FT_Unknown ? "目标文件不存在。" : "文件类型(卷)不支持当前操作。";
  2357. ans.attachment1 = ans.attachment2.GetLength();
  2358. break;
  2359. }
  2360. req.content = req.content.Trim();
  2361. if (req.content.GetLength() <= 0) {
  2362. Dbg("empty new file name ?");
  2363. ans.result = OPT_FILE_RES_FAILED;
  2364. ans.attachment2 = "传入新文件名参数为空。";
  2365. ans.attachment1 = ans.attachment2.GetLength();
  2366. break;
  2367. }
  2368. if (strchr(req.content, '\\') || strchr(req.content, '/')) {
  2369. Dbg("invalid new file name: %s", (LPCTSTR)req.content);
  2370. ans.result = OPT_FILE_RES_FAILED;
  2371. ans.attachment2 = "新文件名参数无效。";
  2372. ans.attachment1 = ans.attachment2.GetLength();
  2373. break;
  2374. }
  2375. const size_t st_len = nCurLen + req.content.GetLength();
  2376. char* path = new char[st_len];
  2377. ZeroMemory(path, st_len);
  2378. int res = 0;
  2379. if (path == NULL) {
  2380. res = 1;
  2381. LogWarn(Severity_Middle, Error_Resource, 0, "alloc path memory failed");
  2382. } else {
  2383. int dir_len = 0;
  2384. CSimpleStringA strNewName = req.content;
  2385. if ((dir_len = GetDirSplitPath(strCurrent, 1, path, st_len)) > 0) {
  2386. if (!req.attribute && type == FT_File) {
  2387. Dbg("save file-type suffix in rename mode.");
  2388. char tmp[MAX_PATH] = { 0 };
  2389. strcpy(tmp, strCurrent.GetData() + dir_len + 1);
  2390. char* pos = strrchr(tmp, '.');
  2391. if (pos) { strNewName += pos; }
  2392. }
  2393. strcat(path, SPLIT_SLASH_STR);
  2394. strcat(path, strNewName);
  2395. res = rename(strCurrent, path);
  2396. } else {
  2397. Dbg("GetDirSplitPath failed: %s vs %s", (LPCTSTR)strCurrent, path);
  2398. res = 1;
  2399. }
  2400. delete[] path;
  2401. path = NULL;
  2402. }
  2403. if (res) {
  2404. Dbg("rename failed: %d", errno);
  2405. ans.result = OPT_FILE_RES_FAILED;
  2406. ans.attachment2 = "重命名操作失败。";
  2407. ans.attachment1 = ans.attachment2.GetLength();
  2408. break;
  2409. }
  2410. ans.result = OPT_FILE_RES_SUCCESS;
  2411. bNeedToRefleshEntity = true;
  2412. updateLevel = 1;
  2413. #else
  2414. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2415. ans.attachment2 = "不支持操作";
  2416. ans.attachment1 = ans.attachment2.GetLength();
  2417. #endif //_MSC_VER
  2418. }
  2419. break;
  2420. default:
  2421. {
  2422. LogWarn(Severity_Low, Error_Unexpect, 0,
  2423. CSimpleStringA::Format("Unexpected file operation command : %d", ctx->Req.mode));
  2424. CSimpleStringA strTip = CSimpleStringA::Format("无法识别的操作指令(mode: %d)。", ctx->Req.mode);
  2425. ans.attachment1 = strTip.GetLength();
  2426. ans.attachment2 = strTip;
  2427. }
  2428. break;
  2429. }
  2430. if (ans.result == OPT_FILE_RES_SUCCESS) {
  2431. if (bNeedToSetCtxEntities || bNeedToRefleshEntity) {
  2432. bool bReInit = true;
  2433. if (bNeedToRefleshEntity) {
  2434. DWORD dwCnt = 0;
  2435. CSimpleStringA strHeader = strCurrent;
  2436. if (updateLevel != 0) {
  2437. char* pPath = new char[nCurLen + 1];
  2438. if (pPath == NULL) bReInit = false;
  2439. else {
  2440. UINT uRes = GetDirSplitPath(strHeader, updateLevel, pPath, nCurLen + 1);
  2441. if (uRes == 0) bReInit = false;
  2442. strHeader = pPath;
  2443. delete[] pPath;
  2444. pPath = NULL;
  2445. }
  2446. }
  2447. if (bReInit) {
  2448. bReInit = !!InitialDirectoryEntity(strHeader, dwCnt);
  2449. }
  2450. bNeedToRefleshHeader = true;
  2451. }
  2452. if (bReInit) {
  2453. ConveyFileEntityToContext(ctx, bNeedToRefleshHeader);
  2454. }
  2455. }
  2456. } else {
  2457. Dbg("attach1: %d", ans.attachment1);
  2458. Dbg("attach2: %s", ans.attachment2.GetData());
  2459. }
  2460. ctx->Answer(Error_Succeed);
  2461. return (ans.result);
  2462. }
  2463. DWORD ResourceWatcherFSM::ExecuteFile(LPCTSTR lpszFilePath, LPCTSTR lpParam)
  2464. {
  2465. DWORD dwRes = 0;
  2466. #if defined(_MSC_VER)
  2467. SHELLEXECUTEINFOA shell;
  2468. memset(&shell, 0, sizeof(SHELLEXECUTEINFOA));
  2469. shell.cbSize = sizeof(SHELLEXECUTEINFOA);
  2470. shell.lpFile = lpszFilePath;
  2471. shell.lpParameters = lpParam;
  2472. shell.fMask = SEE_MASK_INVOKEIDLIST;
  2473. shell.lpVerb = NULL;
  2474. shell.nShow = SW_SHOWDEFAULT;
  2475. if (!ShellExecuteExA(&shell)) {
  2476. dwRes = GetLastError();
  2477. int nRes = (int)shell.hInstApp;
  2478. Dbg("GLE=%u, InstApp=%d", dwRes, nRes);
  2479. switch (dwRes) {
  2480. case ERROR_NO_ACE_CONDITION:
  2481. LogWarn(Severity_Middle, Error_MethodNotFound, dwRes,
  2482. CSimpleStringA::Format("Target file(%s) association not available !", lpszFilePath));
  2483. break;
  2484. case ERROR_ACCESS_DENIED:
  2485. LogWarn(Severity_Middle, Error_NoPrivilege, dwRes,
  2486. CSimpleStringA::Format("Target file(%s) not privilege !", lpszFilePath));
  2487. break;
  2488. case ERROR_PATH_NOT_FOUND:
  2489. case ERROR_FILE_NOT_FOUND:
  2490. LogWarn(Severity_Middle, Error_NotExist, dwRes,
  2491. CSimpleStringA::Format("Target file(%s) not existed !", lpszFilePath));
  2492. break;
  2493. case ERROR_DLL_NOT_FOUND:
  2494. LogWarn(Severity_Middle, Error_NotExist, dwRes,
  2495. CSimpleStringA::Format("One of library file for Target(%s) not existed !", lpszFilePath));
  2496. break;
  2497. case ERROR_NOT_ENOUGH_MEMORY:
  2498. LogWarn(Severity_Middle, Error_Resource, dwRes,
  2499. CSimpleStringA::Format("Not enough memory for Target(%s) to perform !", lpszFilePath));
  2500. break;
  2501. case ERROR_SHARING_VIOLATION:
  2502. LogWarn(Severity_Middle, Error_Overflow, dwRes,
  2503. CSimpleStringA::Format("Violation occurred for Target(%s) to share !", lpszFilePath));
  2504. break;
  2505. default:
  2506. LogWarn(Severity_Middle, Error_Unexpect, dwRes,
  2507. CSimpleStringA::Format("Unpected condtion for Target(%s) to execute(%u) !"
  2508. , lpszFilePath, dwRes));
  2509. break;
  2510. }
  2511. }
  2512. #else
  2513. dwRes = 1;
  2514. #endif //_MSC_VER
  2515. return dwRes;
  2516. }
  2517. BOOL ResourceWatcherFSM::ConveyFileEntityToContext(const SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  2518. ResourceWatcherService_OperateFile_Ans>::Pointer & ctx
  2519. , BOOL bRefleshHeader /*= FALSE*/, DWORD dwFilterAttributes)
  2520. {
  2521. if (ctx == NULL) return FALSE;
  2522. #if defined(_MSC_VER)
  2523. ULARGE_INTEGER ilOffsetSize;
  2524. ilOffsetSize.QuadPart = 0;
  2525. const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
  2526. DWORD dwInheritForbidAttrs = 0UL;
  2527. if (bRefleshHeader) {
  2528. if (m_FileEntry.Current.mNameLength != 0) {
  2529. ilOffsetSize.LowPart = m_FileEntry.Current.mNameOffset;
  2530. ilOffsetSize.HighPart = m_FileEntry.Current.mNameLength;
  2531. GetSubFileName(m_FileEntry.FileNamesBuffer,
  2532. dwBufSize, ctx->Ans.header, &ilOffsetSize);
  2533. ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
  2534. ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
  2535. ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
  2536. ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
  2537. ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
  2538. if (!ctx->Ans.header.IsNullOrEmpty() && ctx->Ans.header.GetLength() > 0) {
  2539. if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
  2540. dwInheritForbidAttrs |= BS_DENY_DELETE;
  2541. Dbg("header-forbit:%s", ctx->Ans.header.GetData());
  2542. }
  2543. }
  2544. }
  2545. }
  2546. int count = m_FileEntry.SubFiles.GetCount();
  2547. int minusCount = 0;
  2548. for (int i = 0; i < count; ++i)
  2549. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
  2550. minusCount++;
  2551. count = count - minusCount;
  2552. ctx->Ans.count = count;
  2553. if (count > 0) {
  2554. if (count >= MAX_SUBFILES_COUNT) {
  2555. Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
  2556. std::vector<CSimpleFileShell> vtFileShells;
  2557. for (int i = 0; i < count; ++i) {
  2558. CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
  2559. vtFileShells.push_back(item);
  2560. }
  2561. sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
  2562. char szFormat[128] = { 0 };
  2563. count = MAX_SUBFILES_COUNT;
  2564. ctx->Ans.count = count;
  2565. ctx->Ans.fileAttributes.Init(count);
  2566. ctx->Ans.fileNames.Init(count);
  2567. ctx->Ans.ftCreates.Init(count);
  2568. ctx->Ans.ftModifieds.Init(count);
  2569. ctx->Ans.ftAccesses.Init(count);
  2570. ctx->Ans.fileSizes.Init(count);
  2571. ctx->Ans.forbidAttributes.Init(count);
  2572. ctx->Ans.reserved1.Init(count);
  2573. ctx->Ans.reserved2.Init(count);
  2574. for (int i = 0; i < count; ++i) {
  2575. CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
  2576. ilOffsetSize.LowPart = component->mNameOffset;
  2577. ilOffsetSize.HighPart = component->mNameLength;
  2578. if (component->mAttributes & dwFilterAttributes) {
  2579. CSimpleStringA strFileName;
  2580. GetSubFileName(m_FileEntry.FileNamesBuffer,
  2581. dwBufSize, strFileName, &ilOffsetSize);
  2582. Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
  2583. continue;
  2584. }
  2585. ctx->Ans.reserved1[i] = 0;
  2586. ctx->Ans.reserved2[i] = "";
  2587. ctx->Ans.fileAttributes[i] = component->mAttributes;
  2588. ctx->Ans.ftCreates[i] = component->mftCreate;
  2589. ctx->Ans.ftModifieds[i] = component->mftModified;
  2590. ctx->Ans.ftAccesses[i] = component->mftAccess;
  2591. ctx->Ans.fileSizes[i] = component->mFileSize;
  2592. //TODO: Need to judge whether need to calculate size of directory.
  2593. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2594. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2595. ctx->Ans.forbidAttributes[i] = 0;
  2596. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2597. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2598. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2599. CSimpleStringA csFilePath;
  2600. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2601. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2602. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2603. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2604. }
  2605. }
  2606. }
  2607. vtFileShells.clear();
  2608. } else {
  2609. ctx->Ans.fileAttributes.Init(count);
  2610. ctx->Ans.fileNames.Init(count);
  2611. ctx->Ans.ftCreates.Init(count);
  2612. ctx->Ans.ftModifieds.Init(count);
  2613. ctx->Ans.ftAccesses.Init(count);
  2614. ctx->Ans.fileSizes.Init(count);
  2615. ctx->Ans.forbidAttributes.Init(count);
  2616. ctx->Ans.reserved1.Init(count);
  2617. ctx->Ans.reserved2.Init(count);
  2618. for (int i = 0; i < count; ++i) {
  2619. ilOffsetSize.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
  2620. ilOffsetSize.HighPart = m_FileEntry.SubFiles[i].mNameLength;
  2621. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
  2622. CSimpleStringA strFileName;
  2623. GetSubFileName(m_FileEntry.FileNamesBuffer,
  2624. dwBufSize, strFileName, &ilOffsetSize);
  2625. Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
  2626. continue;
  2627. }
  2628. ctx->Ans.reserved1[i] = 0;
  2629. ctx->Ans.reserved2[i] = "";
  2630. ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
  2631. ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
  2632. ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
  2633. ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
  2634. ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
  2635. //TODO: Need to judge whether need to calculate size of directory.
  2636. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2637. ctx->Ans.forbidAttributes[i] = 0;
  2638. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2639. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2640. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2641. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2642. CSimpleStringA csFilePath;
  2643. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2644. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2645. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2646. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2647. }
  2648. }
  2649. }
  2650. }
  2651. }
  2652. #else
  2653. ULARGE_INTEGER ilOffsetSize;
  2654. ilOffsetSize.QuadPart = 0;
  2655. const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
  2656. DWORD dwInheritForbidAttrs = 0UL;
  2657. if (bRefleshHeader) {
  2658. if (m_FileEntry.Current.mNameLength != 0) {
  2659. ilOffsetSize.u.LowPart = m_FileEntry.Current.mNameOffset;
  2660. ilOffsetSize.u.HighPart = m_FileEntry.Current.mNameLength;
  2661. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.header, &ilOffsetSize);
  2662. ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
  2663. ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
  2664. ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
  2665. ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
  2666. ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
  2667. if (!ctx->Ans.header.IsNullOrEmpty()) {
  2668. if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
  2669. dwInheritForbidAttrs |= BS_DENY_DELETE;
  2670. Dbg("header-forbit:%s", ctx->Ans.header.GetData());
  2671. }
  2672. }
  2673. }
  2674. }
  2675. int count = m_FileEntry.SubFiles.GetCount();
  2676. int minusCount = 0;
  2677. for (int i = 0; i < count; ++i)
  2678. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
  2679. minusCount++;
  2680. count = count - minusCount;
  2681. ctx->Ans.count = count;
  2682. if (count > 0) {
  2683. if (count >= MAX_SUBFILES_COUNT) {
  2684. Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
  2685. std::vector<CSimpleFileShell> vtFileShells;
  2686. for (int i = 0; i < count; ++i) {
  2687. CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
  2688. vtFileShells.push_back(item);
  2689. }
  2690. sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
  2691. char szFormat[128] = { 0 };
  2692. count = MAX_SUBFILES_COUNT;
  2693. ctx->Ans.count = count;
  2694. ctx->Ans.reserved1.Init(count);
  2695. ctx->Ans.reserved2.Init(count);
  2696. ctx->Ans.fileAttributes.Init(count);
  2697. ctx->Ans.fileNames.Init(count);
  2698. ctx->Ans.ftCreates.Init(count);
  2699. ctx->Ans.ftModifieds.Init(count);
  2700. ctx->Ans.ftAccesses.Init(count);
  2701. ctx->Ans.fileSizes.Init(count);
  2702. ctx->Ans.forbidAttributes.Init(count);
  2703. for (int i = 0; i < count; ++i) {
  2704. CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
  2705. ilOffsetSize.u.LowPart = component->mNameOffset;
  2706. ilOffsetSize.u.HighPart = component->mNameLength;
  2707. if (component->mAttributes & dwFilterAttributes) {
  2708. CSimpleStringA strFileName;
  2709. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, strFileName, &ilOffsetSize);
  2710. Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
  2711. continue;
  2712. }
  2713. ctx->Ans.reserved1[i] = 0;
  2714. ctx->Ans.reserved2[i] = "";
  2715. ctx->Ans.fileAttributes[i] = component->mAttributes;
  2716. ctx->Ans.ftCreates[i] = component->mftCreate;
  2717. ctx->Ans.ftModifieds[i] = component->mftModified;
  2718. ctx->Ans.ftAccesses[i] = component->mftAccess;
  2719. ctx->Ans.fileSizes[i] = component->mFileSize;
  2720. //TODO: Need to judge whether need to calculate size of directory.
  2721. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2722. ctx->Ans.forbidAttributes[i] = 0;
  2723. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2724. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2725. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2726. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2727. CSimpleStringA csFilePath;
  2728. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2729. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2730. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2731. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2732. }
  2733. }
  2734. }
  2735. vtFileShells.clear();
  2736. } else {
  2737. ctx->Ans.fileAttributes.Init(count);
  2738. ctx->Ans.fileNames.Init(count);
  2739. ctx->Ans.ftCreates.Init(count);
  2740. ctx->Ans.ftModifieds.Init(count);
  2741. ctx->Ans.ftAccesses.Init(count);
  2742. ctx->Ans.fileSizes.Init(count);
  2743. ctx->Ans.forbidAttributes.Init(count);
  2744. ctx->Ans.reserved1.Init(count);
  2745. ctx->Ans.reserved2.Init(count);
  2746. for (int i = 0; i < count; ++i) {
  2747. ilOffsetSize.u.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
  2748. ilOffsetSize.u.HighPart = m_FileEntry.SubFiles[i].mNameLength;
  2749. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
  2750. CSimpleStringA strFileName;
  2751. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, strFileName, &ilOffsetSize);
  2752. Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
  2753. continue;
  2754. }
  2755. ctx->Ans.reserved1[i] = 0;
  2756. ctx->Ans.reserved2[i] = "";
  2757. ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
  2758. ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
  2759. ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
  2760. ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
  2761. ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
  2762. //TODO: Need to judge whether need to calculate size of directory.
  2763. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2764. ctx->Ans.forbidAttributes[i] = 0;
  2765. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2766. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2767. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2768. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2769. CSimpleStringA csFilePath;
  2770. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2771. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2772. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2773. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2774. }
  2775. }
  2776. }
  2777. }
  2778. }
  2779. #endif //_MSC_VER
  2780. //Free action for saving memory.
  2781. m_FileEntry.SubFiles.Clear();
  2782. m_FileEntry.FileNamesBuffer.Clear();
  2783. m_FileEntry.Current.Clear();
  2784. return TRUE;
  2785. }
  2786. int ResourceWatcherFSM::FilterFilePathAhead(LPCTSTR lpszPath, const int option)
  2787. {
  2788. #if defined(RVC_OS_WIN)
  2789. size_t len = strlen(lpszPath);
  2790. if (!((lpszPath[0] <= 'z' && lpszPath[0] >= 'a') || (lpszPath[0] <= 'Z' && lpszPath[0] >= 'A'))
  2791. || lpszPath[1] != ':') {
  2792. Dbg("illegal disk format path !");
  2793. return -2;
  2794. }
  2795. const char disk = lpszPath[0];
  2796. if (disk >= 'a' && disk <= 'z') disk -= 32;
  2797. if (!sBDiskValStatus[int(disk - 'A')]) {
  2798. Dbg("Specified disk(%c) not existed", disk);
  2799. return -3;
  2800. }
  2801. char* path = new char[len + 1];
  2802. LOG_ASSERT(path != NULL);
  2803. memset(path, 0, sizeof(char) * (len + 1));
  2804. memcpy(path, lpszPath, len);
  2805. path[len] = '\0';
  2806. int pos = len - 1;
  2807. for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos) {
  2808. ;//
  2809. }
  2810. path[pos + 1] = '\0';
  2811. len = strlen(path);
  2812. if (len <= 1) {
  2813. delete[] path;
  2814. return -1;
  2815. } else if (len == 2 && option == OPT_FILE_CMD_DELETE) {
  2816. /*disk volumn to delete*/
  2817. delete[] path;
  2818. return 1;
  2819. }
  2820. if (InBlackListOrNot(path, option)) {
  2821. delete[] path;
  2822. return 2;
  2823. }
  2824. delete[] path;
  2825. return 0;
  2826. #else
  2827. size_t len = strlen(lpszPath);
  2828. if (lpszPath[0] != '/') {
  2829. Dbg("illegal disk format path !");
  2830. return -2;
  2831. }
  2832. char* path = new char[len + 1];
  2833. LOG_ASSERT(path != NULL);
  2834. memset(path, 0, sizeof(char) * (len + 1));
  2835. memcpy(path, lpszPath, len);
  2836. path[len] = '\0';
  2837. int pos = len - 1;
  2838. for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos) {
  2839. ;//
  2840. }
  2841. path[pos + 1] = '\0';
  2842. len = strlen(path);
  2843. if (len < 1) {
  2844. delete[] path;
  2845. return -1;
  2846. } else if (len == 1 && option == OPT_FILE_CMD_DELETE) {
  2847. /*disk volumn to delete*/
  2848. delete[] path;
  2849. return 1;
  2850. }
  2851. if (InBlackListOrNot(path, option)) {
  2852. delete[] path;
  2853. return 2;
  2854. }
  2855. delete[] path;
  2856. return 0;
  2857. #endif //RVC_OS_WIN
  2858. }
  2859. BOOL ResourceWatcherFSM::InBlackListOrNot(LPCTSTR lpszPath, const int option)
  2860. {
  2861. BOOL bForbidden = FALSE;
  2862. LOG_ASSERT(lpszPath != NULL && strlen(lpszPath) != 0);
  2863. DWORD dwRequredAttr = 0;
  2864. switch (option) {
  2865. case OPT_FILE_CMD_SPREAD:
  2866. dwRequredAttr |= BS_DENY_READ;
  2867. break;
  2868. case OPT_FILE_CMD_EXECUTE:
  2869. dwRequredAttr |= BS_DENY_EXECUTE;
  2870. break;
  2871. case OPT_FILE_CMD_CREATE:
  2872. dwRequredAttr |= BS_DENY_CREATE;
  2873. break;
  2874. case OPT_FILE_CMD_DELETE:
  2875. case OPT_FILE_CMD_CLEAR:
  2876. case OPT_FILE_CMD_RENAME:
  2877. dwRequredAttr |= BS_DENY_DELETE;
  2878. break;
  2879. case OPT_FILE_CMD_APPEND:
  2880. dwRequredAttr |= BS_DENY_MODIFY;
  2881. break;
  2882. default:
  2883. Dbg("Unexpcted option: %d, allow it determined by later process.", option);
  2884. return bForbidden;
  2885. break;
  2886. }
  2887. const size_t len = strlen(lpszPath);
  2888. char* temp_path = new char[len + 1];
  2889. if (temp_path == NULL) {
  2890. Dbg("new temp_path failed");
  2891. return bForbidden;
  2892. }
  2893. memset(temp_path, 0, sizeof(char) * (len + 1));
  2894. strcpy_s(temp_path, len + 1, lpszPath);
  2895. for (size_t i = 0; i < len; ++i) {
  2896. #if defined(_MSC_VER)
  2897. if (temp_path[i] == '/')
  2898. temp_path[i] = '\\';
  2899. #else
  2900. if (temp_path[i] == '\\')
  2901. temp_path[i] = '/';
  2902. #endif //_MSC_VER
  2903. }
  2904. lpszPath = temp_path;
  2905. for (const_bs_iter cit = m_forbidDirList.cbegin(); cit != m_forbidDirList.cend() && !bForbidden; ++cit) {
  2906. const bs_key& path = cit->first;
  2907. const bs_value& resist = cit->second;
  2908. const size_t n = strlen(path.c_str());
  2909. if (dwRequredAttr & resist) {
  2910. if (path[0] == '*') {
  2911. bForbidden = TRUE;
  2912. Dbg("Forbit0");
  2913. break;
  2914. }
  2915. if (!_strnicmp(lpszPath, path.c_str(), min(len, n))) {
  2916. if (len > n && (lpszPath[n] == '\\' || lpszPath[n] == '/') && (resist & BS_DENY_INHERITED)) {
  2917. bForbidden = TRUE; Dbg("forbit1");
  2918. }
  2919. if (len == n) {
  2920. bForbidden = TRUE; Dbg("forbit2");
  2921. }
  2922. if (len < n) {
  2923. FileType ft;
  2924. if (IsPathExisted(path.c_str(), ft)) {
  2925. bForbidden = TRUE;
  2926. Dbg("forbit3");
  2927. }
  2928. }
  2929. }
  2930. }
  2931. }
  2932. if (temp_path) {
  2933. delete[] temp_path;
  2934. temp_path = NULL;
  2935. }
  2936. return bForbidden;
  2937. }
  2938. void ResourceWatcherFSM::InitBlackList()
  2939. {
  2940. LOG_FUNCTION();
  2941. m_forbidDirList.clear();
  2942. DWORD dwDenyAttr;
  2943. #if defined(_MSC_VER)
  2944. const int INFO_BUFFER_SIZE = MAX_PATH;
  2945. char infoBuf[INFO_BUFFER_SIZE];
  2946. DWORD bufCharCount = INFO_BUFFER_SIZE;
  2947. char sys_disk = '\0';
  2948. bufCharCount = INFO_BUFFER_SIZE;
  2949. if (!GetComputerName(infoBuf, &bufCharCount))
  2950. Dbg("GetComputerName failed, GLE=%u", GetLastError());
  2951. else
  2952. Dbg("Computer name: %s", infoBuf);
  2953. // Get and display the user name.
  2954. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2955. bufCharCount = INFO_BUFFER_SIZE;
  2956. if (!GetUserName(infoBuf, &bufCharCount))
  2957. Dbg("GetUserName failed, GLE=%u", GetLastError());
  2958. else
  2959. Dbg("User name: %s", infoBuf);
  2960. // All file cannot be executed !! -Josephus@2017612 9:29:01
  2961. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2962. infoBuf[0] = '*', infoBuf[1] = '\0';
  2963. dwDenyAttr = BS_DENY_EXECUTE | BS_DENY_INHERITED;
  2964. Dbg("Add All file filter: %s - 0x%X", infoBuf, dwDenyAttr);
  2965. m_forbidDirList.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  2966. // Get and display the system directory.
  2967. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2968. if (!GetSystemDirectory(infoBuf, INFO_BUFFER_SIZE)) {
  2969. Dbg("GetSystemDirectory failed, GLE=%u", GetLastError());
  2970. } else {
  2971. dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  2972. Dbg("Add System Directory: %s - 0x%X", infoBuf, dwDenyAttr);
  2973. m_forbidDirList.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  2974. sys_disk = infoBuf[0];
  2975. if (sys_disk >= 'a' && sys_disk <= 'z') sys_disk -= 32;
  2976. int diskNo = sys_disk - 'A';
  2977. LOG_ASSERT(sBDiskValStatus[diskNo]);
  2978. sBDiskValStatus[diskNo] = sBDiskValStatus[diskNo] + 2; //Set system disk flag
  2979. }
  2980. // Get and display the Windows directory.
  2981. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2982. if (!GetWindowsDirectory(infoBuf, INFO_BUFFER_SIZE)) {
  2983. Dbg("GetWindowsDirectory failed, GLE=%u", GetLastError());
  2984. } else {
  2985. dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  2986. Dbg("Add Windows Directory: %s - 0x%X", infoBuf, dwDenyAttr);
  2987. m_forbidDirList.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  2988. }
  2989. if (sys_disk != '\0') {
  2990. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2991. //////////////////////////////////////////////////////////////////////////
  2992. LOG_ASSERT(INFO_BUFFER_SIZE > 4);
  2993. infoBuf[0] = sys_disk;
  2994. infoBuf[1] = ':';
  2995. infoBuf[2] = '\\';
  2996. infoBuf[3] = '\0';
  2997. Dbg("Start to Add system limited path: %d", LIMITED_SYS_COUNT);
  2998. const DWORD dwSysAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  2999. for (int i = 0; i < LIMITED_SYS_COUNT; ++i) {
  3000. string strfullPath = infoBuf;
  3001. strfullPath += LIMITED_SYS_PATH(i);
  3002. if (m_forbidDirList.find(strfullPath) == m_forbidDirList.end()) {
  3003. Dbg("Add %s - 0x%X", strfullPath.c_str(), dwSysAttr);
  3004. m_forbidDirList[strfullPath] = dwSysAttr;
  3005. }
  3006. }
  3007. }
  3008. #endif //_MSC_VER
  3009. //////////////////////////////////////////////////////////////////////////
  3010. CSimpleStringA strPath;
  3011. if (GetEntityBase()->GetFunction()->GetPath("UploadVideo", strPath) == Error_Succeed) {
  3012. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  3013. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  3014. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  3015. }
  3016. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3017. if (GetEntityBase()->GetFunction()->GetPath("UploadPhoto", strPath) == Error_Succeed) {
  3018. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  3019. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  3020. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  3021. }
  3022. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3023. if (GetEntityBase()->GetFunction()->GetPath("Cfg", strPath) == Error_Succeed) {
  3024. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  3025. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  3026. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  3027. }
  3028. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3029. if (GetEntityBase()->GetFunction()->GetPath("Dep", strPath) == Error_Succeed) {
  3030. dwDenyAttr = BS_DENY_DELETE | BS_DENY_CREATE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  3031. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  3032. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  3033. }
  3034. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3035. if (GetEntityBase()->GetFunction()->GetPath("Base", strPath) == Error_Succeed) {
  3036. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3037. dwDenyAttr = BS_DENY_DELETE | BS_DENY_EXECUTE | BS_DENY_INHERITED;
  3038. const size_t len = strPath.GetLength();
  3039. char* path = new char[len + 1];
  3040. //Run Directory
  3041. if (path && (ZeroMemory(path, len + 1), GetDirSplitPath(strPath, 2, path, len + 1) > 0)) {
  3042. //Dbg("Add %s - 0x%X", path, dwDenyAttr);
  3043. //m_forbidDirList[string(path)] = dwDenyAttr;
  3044. }
  3045. if (path) {
  3046. strPath = path;
  3047. delete[] path;
  3048. }
  3049. CSimpleStringA strPathInner;
  3050. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3051. strPathInner = strPath + SPLIT_SLASH_STR + "hardwarecfg";
  3052. dwDenyAttr = BS_DENY_DELETE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  3053. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  3054. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  3055. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3056. strPathInner = strPath + SPLIT_SLASH_STR + "runinfo" + SPLIT_SLASH_STR + "kmc";
  3057. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  3058. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  3059. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  3060. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3061. strPathInner = strPath + SPLIT_SLASH_STR + "version";
  3062. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  3063. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  3064. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  3065. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3066. dwDenyAttr = BS_DENY_MODIFY;
  3067. strPathInner = strPath + SPLIT_SLASH_STR + "version" + SPLIT_SLASH_STR + "active.txt";
  3068. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  3069. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  3070. }
  3071. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  3072. }
  3073. #if defined(RVC_OS_WIN)
  3074. BOOL ResourceWatcherFSM::RetrieveSpecificedEventLogs(const LPEVENTLOGPARAM pEvtLogFilter,
  3075. LPCTSTR lpszEvtFileName, DWORD & dwEntries)
  3076. {
  3077. LOG_FUNCTION();
  3078. CEventLog* pEvtLog = NULL;
  3079. if (pEvtLogFilter->fApplication) {
  3080. pEvtLog = new CEventLog(APPLICATION_LOG);
  3081. } else if (pEvtLogFilter->fSystem) {
  3082. pEvtLog = new CEventLog(SYSTEM_LOG);
  3083. } else if (pEvtLogFilter->fSecurity) {
  3084. pEvtLog = new CEventLog(SECURITY_LOG);
  3085. #ifdef WIDE_CONDITION
  3086. } else if (pEvtLogFilter->fCustom && wcslen(pEvtLogFilter->lpszCustomEventName) > 0) {
  3087. #else
  3088. } else if (pEvtLogFilter->fCustom && strlen(pEvtLogFilter->lpszCustomEventName) > 0) {
  3089. #endif
  3090. pEvtLog = new CEventLog(pEvtLogFilter->lpszCustomEventName, TRUE);
  3091. }
  3092. if (pEvtLog == NULL || !pEvtLog->IsInitialized()) {
  3093. if (pEvtLog)
  3094. delete pEvtLog;
  3095. return FALSE;
  3096. }
  3097. #ifdef WIDE_CONDITION
  3098. CSimpleStringW strwFileName = CSimpleStringA2W(CSimpleStringA(lpszEvtFileName));
  3099. pEvtLog->InitializeLogFile(std::wstring(strwFileName));
  3100. #else
  3101. pEvtLog->InitializeLogFile(std::string(lpszEvtFileName));
  3102. #endif
  3103. dwEntries = pEvtLog->FilterEventLog(pEvtLogFilter->lpszSourceEventName
  3104. , pEvtLogFilter->wEventType
  3105. , pEvtLogFilter->dwEventId
  3106. , pEvtLogFilter->dwTimeBegin
  3107. , pEvtLogFilter->dwTimeEnd);
  3108. if (pEvtLog)
  3109. delete pEvtLog;
  3110. return TRUE;
  3111. }
  3112. DWORD ResourceWatcherFSM::GetEventLog(SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req,
  3113. ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
  3114. {
  3115. LOG_FUNCTION();
  3116. DWORD dwEntries = 0;
  3117. CHAR szEvtFile[MAX_PATH] = { 0 };
  3118. memset(szEvtFile, 0, sizeof(CHAR) * MAX_PATH);
  3119. if (!CombineTheEvtxFileName(m_strTerminalNo, szEvtFile)) {
  3120. ctx->Ans.entries = 0;
  3121. ctx->Ans.information = "初始化事件日志文件名失败";
  3122. ctx->Answer(Error_Succeed);
  3123. if (ExistsFileA(szEvtFile)) {
  3124. Dbg("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
  3125. }
  3126. return 0;
  3127. }
  3128. EVENTLOGPARAM filterParam = { 0 };
  3129. filterParam.wEventType = ctx->Req.evtLevel == 0x00FF ? 0 : ctx->Req.evtLevel;
  3130. BOOL bResult = TRUE;
  3131. DWORD dwResult = ERROR_SUCCESS;
  3132. Dbg("duration: 0x04X", ctx->Req.duration);
  3133. if (ctx->Req.duration == DURAITON_CUSTOM) {
  3134. ULONGLONG ullStart = ctx->Req.startTime;
  3135. ULONGLONG ullEnd = ctx->Req.endTime;
  3136. dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
  3137. &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), &ullStart, &ullEnd);
  3138. } else {
  3139. dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
  3140. &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), NULL, NULL);
  3141. }
  3142. if (dwResult != ERROR_SUCCESS) {
  3143. ctx->Ans.entries = 0;
  3144. ctx->Ans.information = "时间筛选参数错误";
  3145. ctx->Answer(Error_Succeed);
  3146. return 0;
  3147. }
  3148. if (!ctx->Req.evtSrcEventName.IsNullOrEmpty()) {
  3149. #ifdef WIDE_CONDITION
  3150. CSimpleStringW wSrvEventName = CSimpleStringA2W(ctx->Req.evtSrcEventName);
  3151. wcscpy_s(filterParam.lpszSourceEventName, wSrvEventName);
  3152. #else
  3153. strcpy_s(filterParam.lpszSourceEventName, ctx->Req.evtSrcEventName);
  3154. #endif
  3155. }
  3156. WORD wEventTypeMask = ctx->Req.evtName == 0 ? 0x00FF : ctx->Req.evtName;
  3157. Dbg("wEventTypeMask : 0x%04X", wEventTypeMask);
  3158. if ((wEventTypeMask & 0x0001) == 0x0001) {
  3159. DWORD dwRes = 0;
  3160. filterParam.fApplication = TRUE;
  3161. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3162. Dbg("[%s]Retrieve application event log returned: %u",
  3163. bResult ? "Success" : "Failed", dwRes);
  3164. if (bResult) {
  3165. dwEntries += dwRes;
  3166. }
  3167. filterParam.fApplication = FALSE;
  3168. }
  3169. if ((wEventTypeMask & 0x0002) == 0x0002) {
  3170. DWORD dwRes = 0;
  3171. filterParam.fSecurity = TRUE;
  3172. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3173. Dbg("[%s]Retrieve security event log returned: %u",
  3174. bResult ? "Success" : "Failed", dwRes);
  3175. if (bResult) {
  3176. dwEntries += dwRes;
  3177. }
  3178. filterParam.fSecurity = FALSE;
  3179. }
  3180. if ((wEventTypeMask & 0x0008) == 0x0008) {
  3181. DWORD dwRes = 0;
  3182. filterParam.fSystem = TRUE;
  3183. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3184. Dbg("[%s]Retrieve system event log returned: %u",
  3185. bResult ? "Success" : "Failed", dwRes);
  3186. if (bResult) {
  3187. dwEntries += dwRes;
  3188. }
  3189. filterParam.fSystem = FALSE;
  3190. }
  3191. if ((wEventTypeMask & 0x0100) == 0x0100) {
  3192. DWORD dwRes = 0;
  3193. filterParam.fCustom = TRUE;
  3194. if (!ctx->Req.cusEvtFileName.IsNullOrEmpty()) {
  3195. #ifdef WIDE_CONDITION
  3196. CSimpleStringW strwFileName = CSimpleStringA2W(ctx->Req.cusEvtFileName);
  3197. wcscpy_s(filterParam.lpszCustomEventName, strwFileName);
  3198. Dbg("Custom event log path: %s", ctx->Req.cusEvtFileName);
  3199. #else
  3200. strcpy_s(filterParam.lpszCustomEventName, ctx->Req.cusEvtFileName);
  3201. Dbg("Custom event log path: %s", filterParam.lpszCustomEventName);
  3202. #endif
  3203. }
  3204. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3205. Dbg("[%s]Retrieve custom event log returned: %u",
  3206. bResult ? "Success" : "Failed", dwRes);
  3207. if (bResult) {
  3208. dwEntries += dwRes;
  3209. }
  3210. filterParam.fCustom = FALSE;
  3211. }
  3212. if (dwEntries == 0) {
  3213. ctx->Ans.entries = 0;
  3214. LogWarn(Severity_Middle, Error_Unexpect, 0, "The Count of event log is Zero!");
  3215. ctx->Ans.information = "未找到相关的系统事件日志";
  3216. if (ExistsFileA(szEvtFile)) {
  3217. Dbg("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
  3218. }
  3219. } else {
  3220. ctx->Ans.entries = dwEntries;
  3221. ctx->Ans.evtLogFileName = szEvtFile;
  3222. Dbg("Total count of event log: %u", dwEntries);
  3223. }
  3224. ctx->Answer(Error_Succeed);
  3225. return dwEntries;
  3226. }
  3227. DWORD ResourceWatcherFSM::CombineTheEvtxFileName(LPCTSTR lpszTerminalNo, CHAR szEvtxFileName[])
  3228. {
  3229. CSimpleStringA strPath;
  3230. if (lpszTerminalNo == NULL || strlen(lpszTerminalNo) == 0) {
  3231. LogError(Severity_Middle, Error_Param, 0, "TerminalNo is nullptr");
  3232. return 0;
  3233. }
  3234. if (GetEntityBase()->GetFunction()->GetPath("Temp", strPath) != Error_Succeed
  3235. || strPath.IsNullOrEmpty()) {
  3236. LogError(Severity_Middle, Error_Unexpect, 0, "GetPath about Temp failed");
  3237. return 0;
  3238. }
  3239. if (!ExistsDirA(strPath)) {
  3240. if (!CreateDirRecursiveA(strPath)) {
  3241. LogError(Severity_Middle, Error_Unexpect, 0, "CreateDirRecursiveA failed");
  3242. return 0;
  3243. }
  3244. }
  3245. SYSTEMTIME st, stLocal;
  3246. GetSystemTime(&st);
  3247. SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
  3248. #ifdef WIDE_CONDITION
  3249. WCHAR fileName[MAX_PATH] = { 0 };
  3250. CSimpleStringW strwPath = CSimpleStringA2W(strPath);
  3251. CSimpleStringW lpwszTerminalNo = CSimpleStringA2W(CSimpleStringA(lpszTerminalNo));
  3252. swprintf_s(fileName, L"%ws\\%ws-%d%02d%02d-%02d_%02d_%02d", (LPCWSTR)strwPath, (LPCWSTR)lpwszTerminalNo,
  3253. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  3254. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3255. wcscat_s(fileName, EXT_EVTLOG_NAME);
  3256. CSimpleStringA lpszFileName = CSimpleStringW2A(CSimpleStringW(fileName));
  3257. strcpy_s(szEvtxFileName, MAX_PATH, lpszFileName);
  3258. Dbg("Combined EventLog FilePah: %s", szEvtxFileName);
  3259. return strlen(szEvtxFileName);
  3260. #else
  3261. CHAR fileName[MAX_PATH] = { 0 };
  3262. sprintf_s(fileName, "%s\\%s-%d%02d%02d-%02d_%02d_%02d", (LPCTSTR)strPath, lpszTerminalNo,
  3263. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  3264. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3265. strcat_s(fileName, EXT_EVTLOG_NAME);
  3266. strcpy_s(szEvtxFileName, MAX_PATH, fileName);
  3267. Dbg("Combined EventLog FilePah: %s", szEvtxFileName);
  3268. return strlen(szEvtxFileName);
  3269. #endif
  3270. }
  3271. DWORD ResourceWatcherFSM::CalSpecifiedSecondsFrom1970(const WORD wDuration
  3272. , DWORD * dwStartTime
  3273. , DWORD * dwEndTime
  3274. , const PULONGLONG pStartTime
  3275. , const PULONGLONG pEndTime)
  3276. {
  3277. DWORD status = E_FAIL;
  3278. if (dwStartTime == NULL || dwEndTime == NULL)
  3279. return E_INVALIDARG;
  3280. if (wDuration == DURATION_NONE) {
  3281. *dwStartTime = *dwEndTime = 0;
  3282. return ERROR_SUCCESS;
  3283. }
  3284. ULONGLONG ullTimeStamp = 0;
  3285. ULONGLONG SecsTo1970 = 116444736000000000;
  3286. if (wDuration == DURAITON_CUSTOM) {
  3287. if (pStartTime == NULL || pEndTime == NULL)
  3288. return E_POINTER;
  3289. if (*pStartTime > *pEndTime)
  3290. return E_INVALIDARG;
  3291. ullTimeStamp = (*pStartTime) - SecsTo1970;
  3292. ullTimeStamp /= 10000000ULL;
  3293. *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3294. ullTimeStamp = (*pEndTime) - SecsTo1970;
  3295. ullTimeStamp /= 10000000ULL;
  3296. *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3297. return ERROR_SUCCESS;
  3298. }
  3299. SYSTEMTIME st;
  3300. GetSystemTime(&st);
  3301. FILETIME ftCurTime;
  3302. GetSystemTimeAsFileTime(&ftCurTime);
  3303. ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
  3304. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  3305. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  3306. if (wDuration == DURATION_HOUR_ONE) {
  3307. uliOffset.QuadPart = UInt32x32To64(1 * 60 * 60, 1e7);
  3308. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3309. } else if (wDuration == DURATION_HOUR_TWELVE) {
  3310. uliOffset.QuadPart = UInt32x32To64(12 * 60 * 60, 1e7);
  3311. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3312. } else if (wDuration == DURATION_DAY_ONE) {
  3313. uliOffset.QuadPart = UInt32x32To64(24 * 60 * 60, 1e7);
  3314. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3315. } else if (wDuration == DURATION_DAY_SEVENT) {
  3316. uliOffset.QuadPart = UInt32x32To64(7 * 24 * 60 * 60, 1e7);
  3317. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3318. } else if (wDuration == DURATION_MONTH_ONE) {
  3319. uliOffset.QuadPart = UInt32x32To64(30 * 24 * 60 * 60, 1e7);
  3320. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3321. } else {
  3322. Dbg("Unexpected duration paramter.");
  3323. return E_INVALIDARG;
  3324. }
  3325. ullTimeStamp = uliBackTime.QuadPart - SecsTo1970;
  3326. ullTimeStamp /= 10000000ULL;
  3327. *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3328. ullTimeStamp = uliCurTime.QuadPart - SecsTo1970;
  3329. ullTimeStamp /= 10000000ULL;
  3330. *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3331. {
  3332. FILETIME ftBackTime;
  3333. SYSTEMTIME stUTC, stLocal;
  3334. ftBackTime.dwHighDateTime = uliBackTime.HighPart;
  3335. ftBackTime.dwLowDateTime = uliBackTime.LowPart;
  3336. FileTimeToSystemTime(&ftBackTime, &stUTC);
  3337. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  3338. CHAR szTimeFormat[MAX_PATH] = { 0 };
  3339. // Build a string showing the date and time.
  3340. sprintf_s(szTimeFormat, MAX_PATH, "%02d/%02d/%d %02d:%02d:%02d",
  3341. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  3342. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3343. printf("Start time statmp: %s\n", szTimeFormat);
  3344. }
  3345. return ERROR_SUCCESS;
  3346. }
  3347. #endif //RVC_OS_WIN
  3348. BOOL ResourceWatcherFSM::ClearAd0Folder()
  3349. {
  3350. LOG_FUNCTION();
  3351. CSimpleStringA strAd0Path;
  3352. CSmartPointer<IConfigInfo> spConfigRun;
  3353. int nLastTaskTime(0);
  3354. CSimpleStringA ssFilePath(true);
  3355. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  3356. spConfigRun->ReadConfigValueInt("LastClearTime", "Ad0Task", nLastTaskTime);
  3357. if (IsTodayDone(nLastTaskTime)) {
  3358. return TRUE;
  3359. }
  3360. ec = GetEntityBase()->GetFunction()->GetPath("Ad0", strAd0Path);
  3361. if (ec != Error_Succeed || strAd0Path.IsNullOrEmpty()) {
  3362. return FALSE;
  3363. }
  3364. if (!ExistsDirA(strAd0Path)) {
  3365. Dbg("The Folder(%s) is not existed", (LPCTSTR)strAd0Path);
  3366. spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
  3367. (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  3368. return TRUE;
  3369. }
  3370. Dbg("Ad0Path: %s", (LPCTSTR)strAd0Path);
  3371. char displayTime[MAX_PATH] = { 0 };
  3372. ZeroMemory(&mftAd0RemoveTime, sizeof(FILETIME));
  3373. CalculateBackTime(&mftAd0RemoveTime, AD0_DAY_OF_BACKWARD);
  3374. GetTimeFormatStr(displayTime, MAX_PATH, &mftAd0RemoveTime);
  3375. Dbg("The date backward to delete: %s", displayTime);
  3376. #if defined(RVC_OS_WIN)
  3377. ssFilePath = strAd0Path + "\\*";
  3378. #else
  3379. ssFilePath = strAd0Path;
  3380. #endif //RVC_OS_WIN
  3381. int nDelSuc = 0;
  3382. int nDelFailed = 0;
  3383. int nfileSum = ClearSpecifieFile(DFT_Ad0, (LPCTSTR)ssFilePath, nDelSuc, nDelFailed);
  3384. Dbg("#Ad0#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  3385. spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
  3386. (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  3387. return TRUE;
  3388. }
  3389. BOOL ResourceWatcherFSM::IsTodayDone(int nRecordTime)
  3390. {
  3391. if (nRecordTime <= 0) {
  3392. return FALSE;
  3393. }
  3394. SYSTEMTIME stNow = {};
  3395. SYSTEMTIME stTaskTime = CSmallDateTime(nRecordTime).ToSystemTime();
  3396. #if defined(_MSC_VER)
  3397. GetLocalTime(&stNow);
  3398. #else
  3399. stNow = CSmallDateTime::GetNow().ToSystemTime();
  3400. #endif //_MSC_VER
  3401. if (stTaskTime.wYear == stNow.wYear
  3402. && stTaskTime.wMonth == stNow.wMonth
  3403. && stTaskTime.wDay == stNow.wDay) {
  3404. Dbg("task has been executed today, last clear time: %s",
  3405. (const char*)CSmallDateTime(nRecordTime).ToTimeString());
  3406. return TRUE;
  3407. } else {
  3408. Dbg("Last record time: %04d-%02d-%02d %02d:%02d:%02d",
  3409. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  3410. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  3411. return FALSE;
  3412. }
  3413. }
  3414. BOOL ResourceWatcherFSM::GetSystemBootTime(CSmallDateTime & systemBootTime)
  3415. {
  3416. #if defined(RVC_OS_WIN)
  3417. PDH_STATUS Status;
  3418. HQUERY Query = NULL;
  3419. HCOUNTER hcElapsedTimeCount;
  3420. BOOL fSuc = FALSE;
  3421. Status = PdhOpenQuery(NULL, NULL, &Query);
  3422. PDH_FMT_COUNTERVALUE counterValue;
  3423. if (Status != ERROR_SUCCESS) {
  3424. Dbg("PdhOpenQuery failed with status 0x%x.", Status);
  3425. goto Cleanup;
  3426. }
  3427. Status = PdhAddCounter(Query, SystemElapsedQuery, NULL, &hcElapsedTimeCount);
  3428. if (Status != ERROR_SUCCESS) {
  3429. Dbg("PdhAddCounter for SystemElapsedQuery failed with status 0x%x.", Status);
  3430. goto Cleanup;
  3431. }
  3432. // 查询性能监视器数据
  3433. Status = PdhCollectQueryData(Query);
  3434. if (Status != ERROR_SUCCESS) {
  3435. Dbg("PdhCollectQueryData failed with 0x%x.", Status);
  3436. goto Cleanup;
  3437. }
  3438. Status = PdhGetFormattedCounterValue(hcElapsedTimeCount, PDH_FMT_LARGE, NULL, &counterValue);
  3439. if (Status == ERROR_SUCCESS) {
  3440. ULONGLONG ulSinceSeconds = counterValue.largeValue;
  3441. ULONG days = 0, hours = 0, minutes = 0, seconds = 0;
  3442. days = ULONG(ulSinceSeconds / DAY_DIV);
  3443. ulSinceSeconds %= DAY_DIV;
  3444. hours = ULONG(ulSinceSeconds / HOURS_DIV);
  3445. ulSinceSeconds %= HOURS_DIV;
  3446. minutes = ULONG(ulSinceSeconds / MINUS_DIV);
  3447. ulSinceSeconds %= MINUS_DIV;
  3448. seconds = ULONG(ulSinceSeconds);
  3449. Dbg("SystemElapseTime: %u:%02u:%02u:%02u", days, hours, minutes, seconds);
  3450. FILETIME ftCurTime, ftStartTime;
  3451. GetSystemTimeAsFileTime(&ftCurTime);
  3452. ULARGE_INTEGER uliCurTime;
  3453. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  3454. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  3455. //Dbg("%I64d", uliCurTime.QuadPart);
  3456. uliCurTime.QuadPart -= counterValue.largeValue * 1e7;
  3457. //Dbg("%I64d %I64d", uliCurTime.QuadPart, counterValue.largeValue);
  3458. ftStartTime.dwHighDateTime = uliCurTime.HighPart;
  3459. ftStartTime.dwLowDateTime = uliCurTime.LowPart;
  3460. //Dbg("%d %d %d %d", ftStartTime.dwHighDateTime, ftStartTime.dwLowDateTime,
  3461. // ftCurTime.dwHighDateTime, ftCurTime.dwLowDateTime);
  3462. SYSTEMTIME stUTC, stLocal;
  3463. FileTimeToSystemTime(&ftStartTime, &stUTC);
  3464. char temp[22];
  3465. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  3466. sprintf_s(temp, 22, "%d-%02d-%02d %02d:%02d:%02d",
  3467. stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3468. Dbg("OSStartTime: %s", temp);
  3469. systemBootTime.FromSystemTime(stLocal);
  3470. fSuc = TRUE;
  3471. }
  3472. Cleanup:
  3473. Status = PdhRemoveCounter(hcElapsedTimeCount);
  3474. if (Query) {
  3475. PdhCloseQuery(Query);
  3476. }
  3477. return fSuc;
  3478. #else
  3479. DWORD ticks = 0;
  3480. SYSTEMTIME systemTime;
  3481. struct sysinfo info;
  3482. time_t curTime = 0;
  3483. time_t bootTime = 0;
  3484. struct tm* ptm = NULL;
  3485. if (sysinfo(&info)) {
  3486. Dbg("Failed to get sysinfo, errno:%u, reason:%s", errno, strerror(errno));
  3487. return FALSE;
  3488. }
  3489. time(&curTime);
  3490. if (curTime > info.uptime) {
  3491. bootTime = curTime - info.uptime;
  3492. } else {
  3493. bootTime = info.uptime - curTime;
  3494. }
  3495. ptm = localtime(&bootTime);
  3496. struct timespec ts;
  3497. if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
  3498. ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
  3499. systemTime.wYear = (WORD)(ptm->tm_year + 1900);
  3500. systemTime.wMonth = (WORD)(ptm->tm_mon + 1);
  3501. systemTime.wDayOfWeek = (WORD)ptm->tm_wday;
  3502. systemTime.wDay = (WORD)ptm->tm_mday;
  3503. systemTime.wHour = (WORD)ptm->tm_hour;
  3504. systemTime.wMinute = (WORD)ptm->tm_min;
  3505. systemTime.wSecond = (WORD)ptm->tm_sec;
  3506. systemTime.wMilliseconds = (WORD)(ticks % 1000);
  3507. systemBootTime.FromSystemTime(systemTime);
  3508. Dbg("OSStartTime: %s", systemBootTime.ToTimeString().GetData());
  3509. return TRUE;
  3510. #endif //RVC_OS_WIN
  3511. }
  3512. #if defined(RVC_OS_WIN)
  3513. HRESULT ResourceWatcherFSM::SetDefaultAudioPlaybackDevice(LPCWSTR devID)
  3514. {
  3515. IPolicyConfigVista* pPolicyConfig;
  3516. ERole reserved = eConsole;
  3517. HRESULT hr = CoCreateInstance(__uuidof(CPolicyConfigVistaClient),
  3518. NULL, CLSCTX_ALL, __uuidof(IPolicyConfigVista), (LPVOID*)&pPolicyConfig);
  3519. if (SUCCEEDED(hr)) {
  3520. hr = pPolicyConfig->SetDefaultEndpoint(devID, reserved);
  3521. pPolicyConfig->Release();
  3522. }
  3523. return hr;
  3524. }
  3525. BOOL ResourceWatcherFSM::SetDefaultAudioDevice()
  3526. {
  3527. CSmartPointer<IEntityFunction> spFunction = GetEntityBase()->GetFunction();
  3528. CSmartPointer<IConfigInfo> spConfig;
  3529. CSimpleStringA strAudioName;
  3530. BOOL bRet = FALSE;
  3531. ErrorCodeEnum ec = spFunction->OpenConfig(Config_Root, spConfig);
  3532. if (ec != 0) {
  3533. Dbg("open root config failed!");
  3534. return FALSE;
  3535. }
  3536. ec = spConfig->ReadConfigValue("Audio", "handfree_out_dev", strAudioName);
  3537. if (strAudioName.IsNullOrEmpty()) {
  3538. Dbg("handfree_out_dev is nullptr or empty!!");
  3539. return FALSE;
  3540. }
  3541. Dbg("The hand_free_dev: %s", (LPCTSTR)strAudioName);
  3542. CSimpleStringW strwAudioName = CSimpleStringA2W(strAudioName);
  3543. HRESULT hr = CoInitialize(NULL);
  3544. if (SUCCEEDED(hr)) {
  3545. IMMDeviceEnumerator* pEnum = NULL;
  3546. // Create a multimedia device enumerator.
  3547. hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL,
  3548. CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pEnum);
  3549. if (SUCCEEDED(hr)) {
  3550. //判断是否是默认的音频设备,是就退出
  3551. bool bExit = false;
  3552. IMMDevice* pDefDevice = NULL;
  3553. hr = pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefDevice);
  3554. if (SUCCEEDED(hr)) {
  3555. IPropertyStore* pStore;
  3556. hr = pDefDevice->OpenPropertyStore(STGM_READ, &pStore);
  3557. if (SUCCEEDED(hr)) {
  3558. PROPVARIANT friendlyName;
  3559. PropVariantInit(&friendlyName);
  3560. hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
  3561. if (SUCCEEDED(hr)) {
  3562. CSimpleStringW strTmp = friendlyName.pwszVal;
  3563. Dbg("default: %ws", (LPCWSTR)strTmp);
  3564. if (strTmp.IsStartWith(strwAudioName)) {
  3565. bExit = true;
  3566. }
  3567. PropVariantClear(&friendlyName);
  3568. }
  3569. pStore->Release();
  3570. }
  3571. pDefDevice->Release();
  3572. }
  3573. if (bExit) {
  3574. pEnum->Release();
  3575. return TRUE;
  3576. }
  3577. IMMDeviceCollection* pDevices;
  3578. // Enumerate the output devices.
  3579. hr = pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pDevices);
  3580. if (SUCCEEDED(hr)) {
  3581. UINT count;
  3582. pDevices->GetCount(&count);
  3583. if (SUCCEEDED(hr)) {
  3584. for (int i = 0; i < count; i++) {
  3585. bool bFind = false;
  3586. IMMDevice* pDevice;
  3587. hr = pDevices->Item(i, &pDevice);
  3588. if (SUCCEEDED(hr)) {
  3589. LPWSTR wstrID = NULL;
  3590. hr = pDevice->GetId(&wstrID);
  3591. if (SUCCEEDED(hr)) {
  3592. IPropertyStore* pStore;
  3593. hr = pDevice->OpenPropertyStore(STGM_READ, &pStore);
  3594. if (SUCCEEDED(hr)) {
  3595. PROPVARIANT friendlyName;
  3596. PropVariantInit(&friendlyName);
  3597. hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
  3598. if (SUCCEEDED(hr)) {
  3599. // if no options, print the device
  3600. // otherwise, find the selected device and set it to be default
  3601. CSimpleStringW strTmp = friendlyName.pwszVal;
  3602. Dbg("%d: %ws", i, (LPCWSTR)strTmp);
  3603. if (strTmp.IsStartWith(strwAudioName)) {
  3604. bFind = true;
  3605. HRESULT hr = SetDefaultAudioPlaybackDevice(wstrID);
  3606. if (SUCCEEDED(hr)) {
  3607. Dbg("set default audio player succ.");
  3608. bRet = TRUE;
  3609. } else {
  3610. Dbg("set default audio player failed");
  3611. }
  3612. }
  3613. PropVariantClear(&friendlyName);
  3614. }
  3615. pStore->Release();
  3616. }
  3617. }
  3618. pDevice->Release();
  3619. }
  3620. if (bFind) {
  3621. break;
  3622. }
  3623. }
  3624. }
  3625. pDevices->Release();
  3626. }
  3627. pEnum->Release();
  3628. }
  3629. }
  3630. CoUninitialize();
  3631. return bRet;
  3632. }
  3633. #endif //RVC_OS_WIN
  3634. void ResourceWatcherFSM::UploadMonitorSettings()
  3635. {
  3636. std::string sucContent, failedContent;
  3637. CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
  3638. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  3639. Dbg("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  3640. std::string msg = SP::Utility::ToTrim(sucContent);
  3641. SP::Utility::replaceInPlace(msg, "\n", "|");
  3642. LogWarn(Severity_Middle, Error_Debug, LOG_INFO_MONITOR_SETTINGS, msg.c_str());
  3643. }
  3644. BOOL ResourceWatcherFSM::DetectIsFirstRunAtBoot()
  3645. {
  3646. CSystemRunInfo runInfo = { 0 };
  3647. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3648. BOOL bSet = FALSE;
  3649. CBootInfo bootInfo = { 0 };
  3650. CSmallDateTime dateTime;
  3651. Dbg("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
  3652. ErrorCodeEnum erroCode = GetEntityBase()->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
  3653. Dbg("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
  3654. CSmallDateTime systemBootTime;
  3655. BOOL bRet = GetSystemBootTime(systemBootTime);
  3656. if (bRet && systemBootTime > bootInfo.tmStart) {
  3657. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
  3658. if (eRet != Error_Succeed) {
  3659. Dbg("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
  3660. }
  3661. bSet = TRUE;
  3662. std::map<std::string, std::string> srcData;
  3663. srcData.insert(std::make_pair("OSStartTime", systemBootTime.ToTimeString().GetData()));
  3664. srcData.insert(std::make_pair("AppStartTime", (LPCTSTR)runInfo.tmStart.ToTimeString()));
  3665. srcData.insert(std::make_pair("AppLastStartTime", (LPCTSTR)bootInfo.tmStart.ToTimeString()));
  3666. auto ret = generateJsonStr(srcData);
  3667. LogWarn(Severity_Middle, Error_Debug, LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT, ret.second.c_str());
  3668. } else {
  3669. GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
  3670. bSet = FALSE;
  3671. }
  3672. return bSet;
  3673. }
  3674. UINT ResourceWatcherFSM::GetSystemDisplayVersion(CSimpleStringA & strVersion)
  3675. {
  3676. UINT result = 0;
  3677. const char filePath[] = "/etc/os-version";
  3678. strVersion.Clear();
  3679. char tmp[33];
  3680. memset(tmp, 0, 33);
  3681. inifile_read_str_s("Version", "MajorVersion", "unknown", tmp, 32, filePath);
  3682. strVersion = tmp;
  3683. strVersion += ".";
  3684. memset(tmp, 0, 33);
  3685. inifile_read_str_s("Version", "MinorVersion", "unknown", tmp, 32, filePath);
  3686. strVersion += tmp;
  3687. strVersion += ".";
  3688. result = atoi(tmp);
  3689. memset(tmp, 0, 33);
  3690. inifile_read_str_s("Version", "OsBuild", "unknown", tmp, 32, filePath);
  3691. strVersion += tmp;
  3692. return result;
  3693. }
  3694. void ResourceWatcherFSM::UploadSysVersionInfo(UINT & ver)
  3695. {
  3696. std::map<std::string, std::string> srcData;
  3697. CSimpleStringA osver;
  3698. ver = GetSystemDisplayVersion(osver);
  3699. srcData.insert(std::make_pair("os-version", osver)); ////当前操作系统版本(系统信息)
  3700. tk_utsname_t t;
  3701. osutil_uname(&t);
  3702. srcData.insert(std::make_pair("sysname", t.sysname)); ////当前操作系统名
  3703. srcData.insert(std::make_pair("release", t.release)); ////当前发布级别
  3704. srcData.insert(std::make_pair("version", t.version)); ////当前发布版本
  3705. srcData.insert(std::make_pair("machine", t.machine)); ////当前硬件体系类型
  3706. do {
  3707. std::string sucContent, failedContent;
  3708. std::string cmd("cat /proc/cpuinfo |grep \"model name\" | awk 'NR==1'");
  3709. bool ret = SP::Module::Util::ShellExecute(cmd, sucContent, failedContent);
  3710. Dbg("{%s}:{%s}{%s}", cmd.c_str(), sucContent.c_str(), failedContent.c_str());
  3711. //std::size_t found = sucContent.rfind("\n");
  3712. //if (found != std::string::npos) {
  3713. // sucContent.replace(found, strlen("\n"), "");
  3714. //}
  3715. auto elems = SP::Utility::Split(sucContent, ':');
  3716. if (elems.size() > 1) {
  3717. sucContent = SP::Utility::ToTrim(elems[1]);
  3718. }
  3719. srcData.insert(std::make_pair("cpu-type", sucContent));
  3720. } while (false);
  3721. //#if defined(RVC_OS_LINUX)
  3722. // CSystemStaticInfo sysInfo;
  3723. // ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
  3724. // if (eErr == Error_Succeed) {
  3725. // termInfo["MachineMode"] = (LPCTSTR)sysInfo.strMachineModel;
  3726. // termInfo["MachineSN"] = (LPCTSTR)sysInfo.strMachineSN;
  3727. // }
  3728. //#endif //RVC_OS_LINUX
  3729. auto ret = generateJsonStr(srcData);
  3730. LogWarn(Severity_Middle, Error_Hardware, LOG_RESOURCEWATCHER_SYSTEMINFO, ret.second.c_str());
  3731. }
  3732. string ResourceWatcherFSM::CPUProcessStatus()
  3733. {
  3734. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  3735. CSmartPointer<IConfigInfo> spConfig;
  3736. ErrorCodeEnum erroCode = Error_Unexpect;
  3737. spFunction->OpenConfig(Config_Software, spConfig);
  3738. int cpuTop = 0;
  3739. erroCode = spConfig->ReadConfigValueInt("TOPProcess", "cpu", cpuTop);
  3740. if (cpuTop == 0)
  3741. {
  3742. return "";
  3743. }
  3744. map<string, string> nameProcess;
  3745. CSystemRunInfo runInfo = { 0 };
  3746. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3747. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++)
  3748. {
  3749. string entityName = runInfo.strRunningEntityNames[i].GetData();
  3750. CEntityRunInfo entityInfo = { 0 };
  3751. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  3752. //Dbg("No. %d Current run entity : %s, procesID = %d !", i + 1, entityName, entityInfo.dwProcessID);
  3753. nameProcess[to_string(entityInfo.dwProcessID)] = entityName;
  3754. }
  3755. //cout << "---------CPU----------" << endl;
  3756. int cpu_num = sysconf(_SC_NPROCESSORS_CONF);
  3757. //cout << "cpu number = " << cpu_num << endl;
  3758. FILE* fp;
  3759. char buffer[2048];
  3760. string cmd = "ps c -eo pid,%cpu,command | sort -k2 -rn | head -" + to_string(cpuTop);
  3761. fp = popen(cmd.c_str(), "r");
  3762. int i = 0;
  3763. string s;
  3764. string str[3];
  3765. //cpu
  3766. Dbg("CPU TOP %d PROCESS!", cpuTop);
  3767. string topMessage = "";
  3768. while (i < cpuTop)
  3769. {
  3770. fgets(buffer, sizeof(buffer), fp);
  3771. s = buffer;
  3772. istringstream is(s);
  3773. is >> str[0] >> str[1] >> str[2];
  3774. double temp;
  3775. stringstream ss1;
  3776. ss1 << str[1];
  3777. ss1 >> temp;
  3778. temp = temp / cpu_num;
  3779. //stringstream tss;
  3780. /*stringstream ss2;
  3781. ss2 << temp;
  3782. ss2 >> str[1];*/
  3783. stringstream ss2;
  3784. ss2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << temp;
  3785. str[1] = ss2.str();
  3786. //printf("%s", s.c_str());
  3787. if (nameProcess.find(str[0]) != nameProcess.end())
  3788. {
  3789. str[2] = nameProcess[str[0]];
  3790. }
  3791. //cout << str[0] << ", " << str[1] << "%, " << str[2] << endl;
  3792. //cout << s;
  3793. //Dbg("Process id = %s, CPU usage = %s, Process Name = %s. ", str[0].c_str(), (str[1] + "%").c_str() , str[2].c_str());
  3794. topMessage = topMessage + "\"" + str[2] + "\"" + ":\"" + str[1] + "%\"";
  3795. if (i != cpuTop - 1)
  3796. {
  3797. topMessage += ",";
  3798. }
  3799. ++i;
  3800. }
  3801. topMessage += "}";
  3802. //Dbg("%s", topMessage.c_str());
  3803. /*LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH,
  3804. CSimpleStringA::Format("%s", topMessage.c_str())
  3805. );*/
  3806. pclose(fp);
  3807. return topMessage;
  3808. }
  3809. string ResourceWatcherFSM::MemoryProcessStatus()
  3810. {
  3811. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  3812. CSmartPointer<IConfigInfo> spConfig;
  3813. ErrorCodeEnum erroCode = Error_Unexpect;
  3814. spFunction->OpenConfig(Config_Software, spConfig);
  3815. int memTop = 0;
  3816. erroCode = spConfig->ReadConfigValueInt("TOPProcess", "mem", memTop);
  3817. if (memTop == 0)
  3818. {
  3819. return "";
  3820. }
  3821. map<string, string> nameProcess;
  3822. CSystemRunInfo runInfo = { 0 };
  3823. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3824. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++)
  3825. {
  3826. string entityName = runInfo.strRunningEntityNames[i].GetData();
  3827. CEntityRunInfo entityInfo = { 0 };
  3828. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  3829. //Dbg("No. %d Current run entity : %s, procesID = %d !", i + 1, entityName, entityInfo.dwProcessID);
  3830. nameProcess[to_string(entityInfo.dwProcessID)] = entityName;
  3831. }
  3832. FILE* fp;
  3833. char buffer[2048];
  3834. string cmd = "ps c -eo pid,%mem,rss,command | sort -k3 -rn | head -" + to_string(memTop);
  3835. fp = popen(cmd.c_str(), "r");
  3836. int i = 0;
  3837. string s;
  3838. string str[4];
  3839. //cout << "---------MEMORY----------" << endl;
  3840. //mem
  3841. Dbg("MEM TOP %d PROCESS!", memTop);
  3842. string topMessage = "";
  3843. while (i < memTop)
  3844. {
  3845. fgets(buffer, sizeof(buffer), fp);
  3846. s = buffer;
  3847. istringstream is(s);
  3848. is >> str[0] >> str[1] >> str[2] >> str[3];
  3849. double temp;
  3850. stringstream ss1;
  3851. ss1 << str[2];
  3852. ss1 >> temp;
  3853. temp = temp / (1024 * 1024);
  3854. /* stringstream ss2;
  3855. ss2 << temp;
  3856. ss2 >> str[2];*/
  3857. //printf("%s", s.c_str());
  3858. stringstream ss2;
  3859. ss2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << temp;
  3860. str[2] = ss2.str();
  3861. if (nameProcess.find(str[0]) != nameProcess.end())
  3862. {
  3863. str[3] = nameProcess[str[0]];
  3864. }
  3865. //cout << str[0] << ", " << str[1] << ", " << str[2] << " GB," << str[3] << endl;
  3866. //Dbg("Process id = %s, Memory usage = %s, Memory size = %s, Process Name = %s. ",
  3867. //str[0].c_str(), (str[1] + "%").c_str(), (str[2] + " GB").c_str(), str[3].c_str());
  3868. //topMessage = topMessage + "\"" + str[3] + "\"" + ":" + "\"" + str[1] + "%|" + str[2] + " GByte\"";
  3869. topMessage = topMessage + "\"" + str[3] + "\"" + ":" + "\"" + str[1] + "%\"";
  3870. if (i != memTop - 1)
  3871. {
  3872. topMessage += ",";
  3873. }
  3874. //cout << s;
  3875. ++i;
  3876. }
  3877. topMessage += "}";
  3878. //Dbg("%s", topMessage.c_str());
  3879. /* LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH,
  3880. CSimpleStringA::Format("%s", topMessage.c_str())
  3881. );*/
  3882. pclose(fp);
  3883. return topMessage;
  3884. }
  3885. void ResourceWatcherFSM::HardwareInfoTimer(void* pData)
  3886. {
  3887. GetSystemCPUStatus();
  3888. GetSystemMemoryStatus();
  3889. GetSystemDiskStatus();
  3890. GetOperationDiskStatus();
  3891. GetMainLinkStatus();
  3892. GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, MAX_HARDWARE_CHECK_TIME * 2);
  3893. }
  3894. void ResourceWatcherFSM::LinkDetect(int detectType, const char* url, bool &status, uint &delay)
  3895. {
  3896. timeval begin, end;
  3897. uint tInterval = 0;
  3898. bool flag = false;
  3899. string tUrl = url;
  3900. string host = "http://";
  3901. if (tUrl.find("http") == string::npos)
  3902. {
  3903. tUrl = host + tUrl;
  3904. }
  3905. char tmpUrl[1024] = { 0 };
  3906. strcpy(tmpUrl, tUrl.c_str());
  3907. Dbg("Check url:[%s].", url);
  3908. gettimeofday(&begin, NULL);
  3909. //bool flag = http_probe(tmpUrl, 5000, 0);
  3910. string msg;
  3911. int curFlag = HttpProbe(tmpUrl, msg, 5);
  3912. gettimeofday(&end, NULL);
  3913. tInterval = (end.tv_sec - begin.tv_sec) * 1000 + (end.tv_usec - begin.tv_usec) / 1000;
  3914. if (curFlag > 0 && curFlag < 400)
  3915. {
  3916. Dbg("HTTP SUCCESS!, http code = %d, error msg = %s.", curFlag, msg.c_str());
  3917. status = true;
  3918. }
  3919. else
  3920. {
  3921. Dbg("HTTP FAILED!, http code = %d, error msg = %s.", curFlag, msg.c_str());
  3922. status = false;
  3923. }
  3924. delay = tInterval;
  3925. }
  3926. ErrorCodeEnum ResourceWatcherFSM::BizLinkDetect(
  3927. SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
  3928. {
  3929. LOG_FUNCTION();
  3930. ErrorCodeEnum ec = Error_Succeed;
  3931. int detectType = ctx->Req.protocol;
  3932. CSimpleStringA url = ctx->Req.bizLink;
  3933. bool linkStatus = false;
  3934. uint delay = 0;
  3935. LinkDetect(detectType, url.GetData(), linkStatus, delay);
  3936. ctx->Ans.bizLinkStatus = linkStatus;
  3937. ctx->Ans.bizLinkDelayMS = delay;
  3938. ctx->Ans.intParam = 0;
  3939. if (ctx != NULL) {
  3940. ctx->Answer(ec);
  3941. }
  3942. return ec;
  3943. }
  3944. ErrorCodeEnum ResourceWatcherFSM::CheckNetType(
  3945. SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
  3946. {
  3947. LOG_FUNCTION();
  3948. ErrorCodeEnum ec = Error_Succeed;
  3949. int netType = 0; //默认未知
  3950. CSimpleStringA tmpVendor(""), tmpDevSN(""), tmpDLLVersion("");
  3951. GetEntityBase()->GetFunction()->GetSysVar("FWBVendor", tmpVendor);
  3952. GetEntityBase()->GetFunction()->GetSysVar("FWBDevSN", tmpDevSN);
  3953. GetEntityBase()->GetFunction()->GetSysVar("FWBVersion", tmpDLLVersion);
  3954. if (tmpDLLVersion.GetLength() < 2)
  3955. tmpDLLVersion = "8.1";
  3956. if (tmpDevSN.GetLength() > 12 && tmpDevSN.IndexOf("FWB") > 2)
  3957. {
  3958. Dbg("This is fwb device.");
  3959. }
  3960. else
  3961. {
  3962. int i = 0;
  3963. int sockfd;
  3964. struct ifconf ifconf;
  3965. struct ifreq* ifreq;
  3966. char buf[1024];
  3967. //初始化ifconf
  3968. ifconf.ifc_len = 1024;
  3969. ifconf.ifc_buf = buf;
  3970. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  3971. {
  3972. perror("socket error");
  3973. exit(1);
  3974. }
  3975. //获取所有接口信息
  3976. ioctl(sockfd, SIOCGIFCONF, &ifconf);
  3977. //逐个获取Ip地址
  3978. int size = ifconf.ifc_len / sizeof(struct ifreq);
  3979. ifreq = (struct ifreq*)buf;
  3980. string netName(ifreq->ifr_name);
  3981. if(size == 1 && netName == "lo") //只有逻辑地址 -- 网线被拔出
  3982. {
  3983. netType = 1;
  3984. }
  3985. else
  3986. {
  3987. for (i = size; i > 0; i--)
  3988. {
  3989. string netName(ifreq->ifr_name); //有其他网卡 -- 有线
  3990. if (netName != "lo")
  3991. {
  3992. netType = 2;
  3993. }
  3994. ifreq++;
  3995. }
  3996. }
  3997. ctx->Ans.netType = netType;
  3998. }
  3999. if (ctx != NULL) {
  4000. ctx->Answer(ec);
  4001. }
  4002. return ec;
  4003. }
  4004. ErrorCodeEnum ResourceWatcherFSM::GetBizLinks(
  4005. SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
  4006. {
  4007. LOG_FUNCTION();
  4008. ErrorCodeEnum ec = Error_Succeed;
  4009. int filter = ctx->Req.filter; //后续过滤使用
  4010. CAutoArray<CSimpleStringA> bizLinks;
  4011. CAutoArray<CSimpleStringA> bizNames;
  4012. int bizNum = 4;
  4013. bizNames.Init(bizNum);
  4014. bizLinks.Init(bizNum);
  4015. int pos = 0;
  4016. CSmartPointer<IConfigInfo> spCtSettingConfig;
  4017. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  4018. CSimpleStringA mLink(""),adLink(""), mgrUrl(""), mgrUrlNoBar("");
  4019. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
  4020. if (mLink.GetLength() != 0)
  4021. {
  4022. bizNames[pos] = "主站点";
  4023. bizLinks[pos] = mLink;
  4024. pos++;
  4025. }
  4026. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrAd", adLink);
  4027. if (adLink.GetLength() != 0)
  4028. {
  4029. bizNames[pos] = "广告站点";
  4030. bizLinks[pos] = adLink;
  4031. pos++;
  4032. }
  4033. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrl", mgrUrl);
  4034. if (mgrUrl.GetLength() != 0)
  4035. {
  4036. bizNames[pos] = "业务站点1";
  4037. bizLinks[pos] = mgrUrl;
  4038. pos++;
  4039. }
  4040. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlNoSidebar", mgrUrlNoBar);
  4041. if (mgrUrlNoBar.GetLength() != 0)
  4042. {
  4043. bizNames[pos] = "业务站点2";
  4044. bizLinks[pos] = mgrUrlNoBar;
  4045. pos++;
  4046. }
  4047. ctx->Ans.bizLinks = bizLinks;
  4048. ctx->Ans.bizNames = bizNames;
  4049. if (ctx != NULL) {
  4050. ctx->Answer(ec);
  4051. }
  4052. return ec;
  4053. }
  4054. void ResourceWatcherFSM::GetMainLinkStatus()
  4055. {
  4056. ErrorCodeEnum errorCode = Error_Succeed;
  4057. CSmartPointer<IConfigInfo> spCtSettingConfig;
  4058. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  4059. ErrorCodeEnum erroCode = Error_Unexpect;
  4060. CSimpleStringA mLink("");
  4061. erroCode = spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
  4062. MainLinkDetect mainDetect;
  4063. //const char* mainLink = "www.google.com";
  4064. const char* mainLink = mLink.GetData();
  4065. bool curStatus = false;
  4066. uint delay = 0;
  4067. LinkDetect(0, mainLink, curStatus, delay);
  4068. if (!curStatus)
  4069. {
  4070. Dbg("Main Link disconnected [%s].", mainLink);
  4071. mainDetect.mainLinkStatus = curStatus;
  4072. mainDetect.reversed1 = 0;
  4073. mainDetect.reversed2 = "";
  4074. SpSendBroadcast(GetEntityBase()->GetFunction(),
  4075. SP_MSG_OF(MainLinkDetect), SP_MSG_SIG_OF(MainLinkDetect), mainDetect);
  4076. }
  4077. else
  4078. {
  4079. Dbg("Main Link is connected [%s].", mainLink);
  4080. }
  4081. }
  4082. BOOL ResourceWatcherFSM::ReadCPUInfo(CPUInfo * cpu)
  4083. {
  4084. FILE* fp;
  4085. char buff[256];
  4086. CPUInfo* cpuInfo;
  4087. cpuInfo = cpu;
  4088. fp = fopen("/proc/stat", "r");
  4089. if (!fp) {
  4090. Dbg("Read CPU Info FAILED!");
  4091. return FALSE;
  4092. }
  4093. fgets(buff, sizeof(buff), fp);
  4094. sscanf(buff, "%s %u %u %u %u %u %u %u",
  4095. cpuInfo->name, &cpuInfo->user, &cpuInfo->nice, &cpuInfo->system, &cpuInfo->idle, &cpuInfo->lowait, &cpuInfo->irq, &cpuInfo->softirq);
  4096. fclose(fp);
  4097. return TRUE;
  4098. }
  4099. void ResourceWatcherFSM::GetSystemCPUStatus()
  4100. {
  4101. CPUInfo* cpuOld = new CPUInfo();
  4102. CPUInfo* cpuNew = new CPUInfo();
  4103. BOOL oldFlag = ReadCPUInfo(cpuOld);
  4104. sleep(1);
  4105. BOOL newFlag = ReadCPUInfo(cpuNew);
  4106. if (!(oldFlag && newFlag)) return;
  4107. unsigned long oldInfo, newInfo;
  4108. double cUsedRate = 0;
  4109. //第一次(用户+优先级+系统+空闲)的时间
  4110. oldInfo = (unsigned long)(cpuOld->user + cpuOld->nice + cpuOld->system + cpuOld->idle + cpuOld->lowait + cpuOld->irq + cpuOld->softirq);
  4111. //第二次(用户+优先级+系统+空闲)的时间
  4112. newInfo = (unsigned long)(cpuNew->user + cpuNew->nice + cpuNew->system + cpuNew->idle + cpuNew->lowait + cpuNew->irq + cpuNew->softirq);
  4113. double totalTime = newInfo - oldInfo;
  4114. double freeTime = cpuNew->idle - cpuOld->idle;
  4115. cUsedRate = (totalTime - freeTime) / totalTime;
  4116. if (cUsedRate < 0.8) {
  4117. //Dbg("[CPU] used rate: %.1lf%%.", cUsedRate * 100);
  4118. } else {
  4119. /*LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH,
  4120. CSimpleStringA::Format("CPU TOO HIGH! [CPU] used rate: %.1lf%%.", cUsedRate * 100)
  4121. );*/
  4122. stringstream tss;
  4123. tss << std::setiosflags(std::ios::fixed) << std::setprecision(2) << cUsedRate * 100;
  4124. string warn = "{ \"total_used\":\"" + tss.str() + "%\"," + CPUProcessStatus();
  4125. Dbg("%s", warn.c_str());
  4126. LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  4127. }
  4128. }
  4129. void ResourceWatcherFSM::GetSystemMemoryStatus()
  4130. {
  4131. MemInfo* memInfo = new MemInfo();
  4132. FILE* fd;
  4133. char buff[256];
  4134. fd = fopen("/proc/meminfo", "r");
  4135. if (!fd) {
  4136. Dbg("Read Memory INFO FAILED!");
  4137. return;
  4138. }
  4139. fgets(buff, sizeof(buff), fd);
  4140. sscanf(buff, "%s %lu ", memInfo->infoName1, &memInfo->memTotal);
  4141. fgets(buff, sizeof(buff), fd);
  4142. sscanf(buff, "%s %lu ", memInfo->infoName2, &memInfo->memFree);
  4143. fgets(buff, sizeof(buff), fd);
  4144. sscanf(buff, "%s %lu ", memInfo->infoName3, &memInfo->memAvail);
  4145. fclose(fd);
  4146. double mUsedRate = 0;
  4147. mUsedRate = (double)(memInfo->memTotal - memInfo->memAvail) / (double)memInfo->memTotal;
  4148. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  4149. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  4150. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE];
  4151. ByteSprintf(szResult, (double)(memInfo->memTotal) * 1024, 'G'); // 内存信息在 /proc/meminfo 中的单位为 KB
  4152. ByteSprintf(szResult2, (double)(memInfo->memFree) * 1024, 'G');
  4153. ByteSprintf(szResult3, (double)(memInfo->memAvail) * 1024, 'G');
  4154. if (mUsedRate < 0.8) {
  4155. //Dbg("[Memory] total: %s, free: %s, available: %s, [Memory] used rate: %.1lf%%.", szResult, szResult2, szResult3, mUsedRate * 100);
  4156. } else {
  4157. /*LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH,
  4158. CSimpleStringA::Format("MEMORY TOO HIGH! -- [Memory] total: %s, free: %s, available: %s, [Memory] used rate: %.1lf%%.",
  4159. szResult, szResult2, szResult3, mUsedRate * 100)
  4160. );*/
  4161. char usedResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  4162. ByteSprintf(usedResult, (double)(memInfo->memTotal) * 1024 * mUsedRate, 'G');
  4163. stringstream ss1;
  4164. ss1 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << mUsedRate * 100;
  4165. string warn = "{ \"total\":\"" + string(szResult) + "\"," +
  4166. "\"used\":\"" + ss1.str() + "%\"," + MemoryProcessStatus();
  4167. Dbg("%s", warn.c_str());
  4168. LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  4169. }
  4170. }
  4171. void ResourceWatcherFSM::GetDiskStatusFrom(LPCTSTR path)
  4172. {
  4173. unsigned long long uiTotalBytes;
  4174. unsigned long long uiFreeDiskBytes;
  4175. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  4176. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  4177. BOOL readFlag = DiskInfo::GetDiskSpace(path, uiTotalBytes, uiFreeDiskBytes);
  4178. double dUsedRate = 1 - (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  4179. ByteSprintf(szResult, (double)uiTotalBytes);
  4180. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  4181. if (readFlag && (dUsedRate < 0.9)) {
  4182. //Dbg("[Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.", path, szResult, szResult2, dUsedRate * 100);
  4183. } else {
  4184. LogWarn(Severity_Low, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH,
  4185. CSimpleStringA::Format("DISK TOO HIGH! -- [Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.",
  4186. path, szResult, szResult2, dUsedRate * 100)
  4187. );
  4188. }
  4189. }
  4190. void ResourceWatcherFSM::GetSystemDiskStatus()
  4191. {
  4192. GetDiskStatusFrom("/");
  4193. }
  4194. void ResourceWatcherFSM::GetOperationDiskStatus()
  4195. {
  4196. GetDiskStatusFrom(m_uploadedVideoDirPath);
  4197. }
  4198. void ResourceWatcherFSM::switchWindowsEffect(const char* cfgFilePath, bool enable)
  4199. {
  4200. char tmp[33];
  4201. memset(tmp, 0, 33);
  4202. inifile_read_str_s("Compositing", "Enabled", "", tmp, 32, cfgFilePath);
  4203. if (strlen(tmp) == 0 || stricmp(tmp, "false") == 0) {
  4204. if (enable) {
  4205. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "true");
  4206. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_ON, "to active window effect");
  4207. }
  4208. } else if (stricmp(tmp, "true") == 0) {
  4209. if (!enable) {
  4210. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "false");
  4211. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_OFF, "to inactive window effect");
  4212. }
  4213. }
  4214. }
  4215. BOOL ResourceWatcherFSM::readDNSConfigFile(CSimpleStringA & result)
  4216. {
  4217. std::string succStr, errStr;
  4218. if (SP::Module::Util::ShellExecute("cat /etc/resolv.conf", succStr, errStr)) {
  4219. result = succStr.c_str();
  4220. return TRUE;
  4221. } else {
  4222. return FALSE;
  4223. }
  4224. }
  4225. void ResourceWatcherFSM::RecoverDDEClipboardEnable()
  4226. {
  4227. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  4228. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  4229. if (!ExistsFileA(clipboardPath.c_str()) && ExistsFileA(clipboardPathBak.c_str())) {
  4230. fileutil_copy_file(clipboardPath.c_str(), clipboardPathBak.c_str());
  4231. //fileutil_delete_file(clipboardPathBak.c_str());
  4232. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_CLIPBOARD_RECOVER_ENABLE, "recover clipboard succ.");
  4233. } else {
  4234. Dbg("%s exists.", clipboardPath.c_str());
  4235. }
  4236. }
  4237. void ResourceWatcherFSM::ConfirmDDEClipboardDisable()
  4238. {
  4239. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  4240. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  4241. char* clipboards[] = { "dde-clipboard", "dde-clipboardloader" };
  4242. if (!ExistsFileA(clipboardPath.c_str())) {
  4243. Dbg("There are no any %s files.", clipboardPath.c_str());
  4244. if (ExistsFileA(clipboardPathBak.c_str())) {
  4245. Dbg("%s exists.", clipboardPathBak.c_str());
  4246. }
  4247. return;
  4248. }
  4249. if (0 != fileutil_copy_file(clipboardPathBak.c_str(), clipboardPath.c_str())) {
  4250. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove clipboard failed");
  4251. } else {
  4252. fileutil_delete_file(clipboardPath.c_str());
  4253. osutil_terminate_related_process(clipboards, array_size(clipboards));
  4254. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_SUCC, "remove clipboard succ.");
  4255. }
  4256. }
  4257. void ResourceWatcherFSM::ConfirmNotificationCenterDisable()
  4258. {
  4259. const char* osd_file_path = "/usr/lib/deepin-daemon/dde-osd";
  4260. const char* osd_bak_file_path = "/usr/lib/deepin-daemon/dde-osd.bak";
  4261. CSmartPointer<IConfigInfo> spConfig;
  4262. GetEntityBase()->GetFunction()->OpenConfig(Config_Cache, spConfig);
  4263. int flag = 0;
  4264. spConfig->ReadConfigValueInt("UOSFeatures", "NotifyCenterSupport", flag);
  4265. if (flag == 1) {
  4266. Dbg("allow the dde-osd process alive.");
  4267. if (!ExistsFileA(osd_file_path) && ExistsFileA(osd_bak_file_path)) {
  4268. fileutil_copy_file(osd_file_path, osd_bak_file_path);
  4269. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_OSD_RECOVER_ENABLE, "recover dde osd succ.");
  4270. }
  4271. } else {
  4272. if (ExistsFileA(osd_file_path) && !ExistsFileA(osd_bak_file_path)) {
  4273. char* relates[] = { "dde-osd" };
  4274. if (0 != fileutil_copy_file(osd_bak_file_path, osd_file_path)) {
  4275. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove dde osd failed");
  4276. } else {
  4277. osutil_terminate_related_process(relates, array_size(relates));
  4278. fileutil_delete_file(osd_file_path);
  4279. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_OSD_REMOVE_SUCC, "remove dde osd succ.");
  4280. }
  4281. }
  4282. }
  4283. }
  4284. BOOL ResourceWatcherFSM::SetLocalDNSWithResolv(LPCTSTR dns1, LPCTSTR dns2)
  4285. {
  4286. const char* dnsPath = "/etc/resolv.conf";
  4287. const int res = access(dnsPath, W_OK);
  4288. if (res == 0) {
  4289. CSimpleStringA timeStamp = CSmallDateTime::GetNow().ToTimeString();
  4290. FILE* resolv = fopen(dnsPath, "w+");
  4291. int state = fprintf(resolv, "#Update by VTM %s\nnameserver %s\nnameserver %s\n", timeStamp.GetData(), dns1, dns2);
  4292. fclose(resolv);
  4293. if (state < 0) {
  4294. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_FAILED,
  4295. CSimpleStringA::Format("update dns config for %s|%s failed: err: %d", dns1, dns2, errno));
  4296. return FALSE;
  4297. } else {
  4298. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_SUCC,
  4299. CSimpleStringA::Format("update dns with resolv for %s|%s succ!", dns1, dns2));
  4300. return TRUE;
  4301. }
  4302. }
  4303. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_FAILED,
  4304. CSimpleStringA::Format("access dns with resolv failed err: %d, rc:%d", errno, res));
  4305. return FALSE;
  4306. }
  4307. /** 在厂商机器查看了信息,不能以这里面的内容为准 [Gifur@2021910]*/
  4308. BOOL ResourceWatcherFSM::SetLocalDNSWithNetworkManager(LPCTSTR dns1, LPCTSTR dns2)
  4309. {
  4310. BOOL result = FALSE;
  4311. const char* connectDirPath = "/etc/NetworkManager/system-connections";
  4312. array_header_t* arr;
  4313. arr = fileutil_get_sub_files_a(connectDirPath);
  4314. if (arr) {
  4315. do {
  4316. for (int i = 0; i < arr->nelts; ++i) {
  4317. char* dir = ARRAY_IDX(arr, i, char*);
  4318. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  4319. CSimpleStringA::Format("%d: %s", i + 1, dir));
  4320. }
  4321. if (arr->nelts == 0) {
  4322. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  4323. CSimpleStringA::Format("%s: no any sub files", connectDirPath));
  4324. }
  4325. toolkit_array_free2(arr);
  4326. return result;
  4327. } while (false);
  4328. if (arr->nelts != 1) {
  4329. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_SYSCONNECT_DUPLICATE,
  4330. CSimpleStringA::Format("%s: unexpect connects count: %d", connectDirPath, arr->nelts));
  4331. } else {
  4332. char szDestPath[256] = { 0 };
  4333. char* dir = ARRAY_IDX(arr, 0, char*);
  4334. strcpy(szDestPath, dir);
  4335. do {
  4336. char value[128];
  4337. inifile_read_str_s("connection", "interface-name", "", value, 127, szDestPath);
  4338. if (strlen(value) == 0) {
  4339. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_CONNECTION_INFO_UNEXPECT,
  4340. CSimpleStringA::Format("get interface name from %s failed.", szDestPath));
  4341. break;
  4342. }
  4343. memset(value, 0, sizeof(value));
  4344. inifile_read_str_s("ipv4", "dns", "", value, 127, szDestPath);
  4345. bool toUpdate = true;
  4346. if (strlen(value) > 0) {
  4347. CSimpleStringA DNSes(value);
  4348. auto arr = DNSes.Split(';');
  4349. int cf1 = 0, cf2 = 0;
  4350. for (int i = 0; i < arr.GetCount(); ++i) {
  4351. if (arr[i].Compare(dns1) == 0) cf1++;
  4352. if (arr[i].Compare(dns2) == 0) cf2++;
  4353. }
  4354. if (cf1 > 0 && cf2 > 0) {
  4355. toUpdate = false;
  4356. Dbg("already exists: %s, needless to update.", value);
  4357. result = TRUE;
  4358. }
  4359. }
  4360. if (toUpdate) {
  4361. CSimpleStringA newLine(dns1);
  4362. if (newLine.Compare(dns2) != 0) {
  4363. newLine += ";";
  4364. newLine += dns2;
  4365. newLine += ";";
  4366. } else {
  4367. newLine += ";";
  4368. }
  4369. inifile_write_str(szDestPath, "ipv4", "dns", newLine);
  4370. inifile_write_str(szDestPath, "ipv4", "ignore-auto-dns", "true");
  4371. Dbg("to update services.");
  4372. std::string nor, err;
  4373. SP::Module::Util::ShellExecute("service NetworkManager restart", nor, err);
  4374. Dbg("restart service done!");
  4375. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_CHANGE_NM_SUCC,
  4376. CSimpleStringA::Format("update dns with netwokrMange for %s|%s succ!", dns1, dns2));
  4377. result = TRUE;
  4378. }
  4379. } while (false);
  4380. }
  4381. toolkit_array_free2(arr);
  4382. } else {
  4383. LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  4384. CSimpleStringA::Format("%s: no such directory or not any sub files", connectDirPath));
  4385. //LogWarn(Severity_Low, Error_Duplication, LOG_RESOURCEWATCHER_SYSCONNECT_DUPLICATE,
  4386. // CSimpleStringA::Format("%s: no such directory or not any sub files", connectDirPath));
  4387. }
  4388. return result;
  4389. }
  4390. /*
  4391. * 桌面版本自带的NetworkManage管理服务与Interface的设置有冲突,如果手工改动Interface的配置,则NetworkManage会失效
  4392. * UOS默认使用NetworkMange接管网卡的管理,所以为了适应UOS,此种方式暂不实现
  4393. */
  4394. BOOL ResourceWatcherFSM::SetLocalDNSWithInterfaces(LPCTSTR dns1, LPCTSTR dns2)
  4395. {
  4396. return FALSE;
  4397. }
  4398. void ResourceWatcherFSM::ConfirmDNSConfigHasSet()
  4399. {
  4400. LOG_FUNCTION();
  4401. CSimpleStringA dns1, dns2;
  4402. #if 1
  4403. CSmartPointer<IConfigInfo> spConfig;
  4404. GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  4405. #ifdef UNDER_PRODUCT_ENV
  4406. spConfig->ReadConfigValue("DNS", "dns1", dns1);
  4407. spConfig->ReadConfigValue("DNS", "dns2", dns2);
  4408. Dbg("prd enviromemt");
  4409. #else
  4410. spConfig->ReadConfigValue("DNSTest", "dns1", dns1);
  4411. spConfig->ReadConfigValue("DNSTest", "dns2", dns2);
  4412. Dbg("test enviromemt");
  4413. #endif // UNDER_PRODUCT_ENV
  4414. #else
  4415. dns1 = m_strDefaultDns;
  4416. dns2 = m_strBackupDns;
  4417. if (!m_nEnableSetDns) {
  4418. Dbg("no enable set dns server.");
  4419. return;
  4420. }
  4421. #endif
  4422. if (dns1.IsNullOrEmpty() && dns2.IsNullOrEmpty()) {
  4423. Dbg("not any dns set at entity config.");
  4424. return;
  4425. }
  4426. if (dns2.IsNullOrEmpty()) dns2 = dns1;
  4427. if (dns1.IsNullOrEmpty()) dns1 = dns2;
  4428. CSimpleStringA str;
  4429. readDNSConfigFile(str);
  4430. do {
  4431. std::string a(str.GetData());
  4432. SP::Utility::replaceInPlace(a, "\n", "|");
  4433. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_DNS_INFO_UPLOAD,
  4434. CSimpleStringA::Format("%s $$ %s|%s", a.c_str(), m_strDefaultDns.GetData(), m_strBackupDns.GetData()));
  4435. //SetLocalDNSWithNetworkManager(dns1, dns2);
  4436. } while (false);
  4437. return;
  4438. if (!str.IsNullOrEmpty()) {
  4439. CAutoArray<CSimpleStringA> arr = str.Split('\n');
  4440. CSimpleStringA check1("nameserver ");
  4441. CSimpleStringA check2("nameserver ");
  4442. check1 += dns1;
  4443. check2 += dns2;
  4444. int cf1 = 0, cf2 = 0;
  4445. for (int i = 0; i < arr.GetCount(); ++i) {
  4446. if (arr[i].Compare(check1) == 0) cf1++;
  4447. if (arr[i].Compare(check2) == 0) cf2++;
  4448. }
  4449. if (cf1 > 0 && cf2 > 0) {
  4450. Dbg("dns has been config before:");
  4451. Dbg(str);
  4452. return;
  4453. }
  4454. }
  4455. Dbg("to set dns config...");
  4456. SetLocalDNSWithResolv(dns1, dns2);
  4457. //SetLocalDNSWithNetworkManager(dns1, dns2);
  4458. Dbg("set dns config done!");
  4459. }
  4460. void ResourceWatcherFSM::ConfirmWindowEffectHasBeenOpen()
  4461. {
  4462. array_header_t* arr;
  4463. arr = fileutil_get_sub_dirs_a("/home");
  4464. if (arr) {
  4465. int i;
  4466. for (i = 0; i < arr->nelts; ++i) {
  4467. char szDestSubDir[256] = { 0 };
  4468. char* dir = ARRAY_IDX(arr, i, char*);
  4469. Dbg("sub dir: %s", dir);
  4470. strcpy(szDestSubDir, dir);
  4471. strcat(szDestSubDir, SPLIT_SLASH_STR);
  4472. strcat(szDestSubDir, ".config/kwinrc");
  4473. if (ExistsFileA(szDestSubDir)) {
  4474. switchWindowsEffect(szDestSubDir, true);
  4475. }
  4476. }
  4477. toolkit_array_free2(arr);
  4478. }
  4479. }