ResourceWatcherFSM.cpp 159 KB

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