ResourceWatcherFSM.cpp 179 KB

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