ResourceWatcherFSM.cpp 160 KB

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