Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. // snfLOGmgr.cpp
  2. //
  3. // (C) Copyright 2006 - 2009 ARM Research Labs, LLC.
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // Log Manager implementations see snfLOGmgr.hpp for details.
  7. #include "snfLOGmgr.hpp"
  8. #include "../CodeDweller/threading.hpp"
  9. #include "../CodeDweller/timing.hpp"
  10. #include <unistd.h>
  11. #include <sstream>
  12. #include <iomanip>
  13. using namespace std;
  14. //// DiscLogger ////////////////////////////////////////////////////////////////
  15. const ThreadType DiscLogger::Type("DiscLogger"); // The thread's type.
  16. const ThreadState DiscLogger::DiscLogger_Flush("Flushing"); // Flushing state.
  17. const ThreadState DiscLogger::DiscLogger_Wait("Waiting"); // Waiting state.
  18. DiscLogger::DiscLogger(string N) : // When it is time to start...
  19. Thread(DiscLogger::Type, N), // DiscLogger Type and Name.
  20. UseANotB(true), // Set all of the flags to their
  21. isDirty(false), // appropriate initial state
  22. isBad(false), // then start the thread.
  23. isTimeToStop(false),
  24. inAppendMode(true),
  25. isEnabled(true) {
  26. run();
  27. }
  28. DiscLogger::~DiscLogger() { // When it is time to go away...
  29. isTimeToStop = true; // Set the stop flag.
  30. flush(); // Flush if we should.
  31. join(); // Wait for the thread to stop.
  32. }
  33. void DiscLogger::post(const string Input, const string NewPath) { // Post Input to log.
  34. if(!isEnabled) return; // If we're not enabled, eat it.
  35. ScopeMutex PostingNewDataNobodyMove(BufferControlMutex); // Keep things static while posting.
  36. if(0 < NewPath.length()) { myPath = NewPath; } // Reset the path if provided.
  37. string& Buffer = PostingBuffer(); // Grab the posting buffer.
  38. if(!inAppendMode) Buffer.clear(); // If overwriting, clear the old.
  39. Buffer.append(Input); // Add the new data.
  40. isDirty = true; // We're dirty now.
  41. }
  42. // The DiscLogger flush() method is designed to lose data if it is unable to
  43. // write the data to the file. The alternative would allow an unlimited amount
  44. // of data to build up in the buffers and that would be bad.
  45. void DiscLogger::flush() { // Flush right now!
  46. string FilePath; // Local copy of the path.
  47. ScopeMutex FlushingNow(FlushMutex); // We're flushing.
  48. if(isDirty) { // Nothing to do if not dirty.
  49. BufferControlMutex.lock(); // Lock the buffer controls.
  50. FlushingBuffer().clear(); // Clear the old flushing buffer.
  51. UseANotB = (!UseANotB); // Flip the buffers.
  52. isDirty = false; // We are not dirty anymore.
  53. string& Buffer = FlushingBuffer(); // Grab the new flushing buffer.
  54. FilePath = myPath; // Grab the current file path.
  55. BufferControlMutex.unlock(); // Unlock the buffer controls.
  56. try { // Insulate against exceptions.
  57. ofstream File( // Open the file.
  58. FilePath.c_str(), // Use the path we have.
  59. (inAppendMode) ? (ios::app) : (ios::trunc) // Append or Truncate appropriately.
  60. );
  61. File << Buffer; // Write the buffer.
  62. if(File.bad()) throw false; // If someting went wrong, throw.
  63. File.close(); // Close the file.
  64. }
  65. catch(...) { // If we had an exception then
  66. isBad = true; // make sure the bad bit is on and
  67. return; // we are done.
  68. }
  69. isBad = false; // If nothing went wrong we're good!
  70. }
  71. }
  72. void DiscLogger::myTask() { // Main thread task
  73. Sleeper WaitASecond(1000); // How to wait for 1 second.
  74. while(!isTimeToStop) { // Until it is time to stop:
  75. CurrentThreadState(DiscLogger_Wait); // post our waiting and
  76. WaitASecond(); // we wait a second, then
  77. CurrentThreadState(DiscLogger_Flush); // post our activity and
  78. flush(); // flush our data to disc
  79. } // then do it again.
  80. }
  81. //// snfScanData ///////////////////////////////////////////////////////////////
  82. snfScanData::snfScanData(int ScanHorizon) : // How to create.
  83. ReadyToClear(true), // Make sure initial clear will happen.
  84. FilteredData(ScanHorizon, 0) { // Allocate the Filtered Data buffer.
  85. clear(); // Start with no data.
  86. }
  87. snfScanData::~snfScanData() { // Cleans up lists etc.
  88. ReadyToClear = true; // Make sure the clear will happen.
  89. clear(); // Say we have no data.
  90. }
  91. void snfScanData::clear() { // Clear the data for the next message.
  92. if(!ReadyToClear) return; // Don't double clear.
  93. ReadyToClear = false; // No clearing now until logged.
  94. // Clear the IP scan data
  95. memset(MyIPScanData, 0, sizeof(MyIPScanData)); // Clear the IP scan data and
  96. MyIPCount = 0; // the count of scanned IPs.
  97. memset(DrillDownFlags, 0, sizeof(DrillDownFlags)); // Clear all DrillDown flags.
  98. SourceIPOrdinal = -1; // There is no source IP because it
  99. SourceIPFoundFlag = false; // has not yet been found.
  100. SourceIPRangeFlag = Unknown; // Range flag is not yet known.
  101. SourceIPEvaluation.clear(); // No eval yet.
  102. myHeaderDirectiveSourceIP = 0UL; // Header directive source is empty now.
  103. myCallerForcedSourceIP = 0UL; // Caller forced source is empty now.
  104. // Clear basic message stats & id info.
  105. StartOfJobUTC = 0; // Clear the start of job clock.
  106. SetupTime = 0; // Time in ms spent setting up to scan.
  107. ScanName.clear(); // Identifying name or message file name.
  108. /** The Timer ScanTime is explicitely NOT reset during clear() operations.
  109. *** Instead, the ScanTime Timer is controlled as a ScopeTimer() during the
  110. *** scan() operation exclusively.
  111. **/
  112. ScanSize = 0; // Scan size is zero.
  113. ScanDepth = 0; // Scan depth is zero.
  114. // Log entries and X- headers
  115. ClassicLogText.clear(); // Classic log entry text if any.
  116. XMLLogText.clear(); // XML log entry text if any.
  117. XHDRsText.clear(); // XHeaders text if any.
  118. XHeaderInjectOn = false; // True if injecting headers is on.
  119. XHeaderFileOn = false; // True if creating .xhdr file is on.
  120. // Clear the GBUdb Event Tracking Flags
  121. GBUdbNormalTriggered = false; // True if GBUdb indeterminate IP source.
  122. GBUdbWhiteTriggered = false; // True if GBUdb found source IP white.
  123. GBUdbWhiteSymbolForced = false; // True if white was on and symbol was set.
  124. GBUdbPatternSourceConflict = false; // True if a pattern was found with a white IP.
  125. GBUdbAutoPanicTriggered = false; // True if autopanic was triggered.
  126. GBUdbAutoPanicExecuted = false; // True if an autopanic was added.
  127. GBUdbBlackTriggered = false; // True if GBUdb found source IP black.
  128. GBUdbBlackSymbolForced = false; // True if black was on and symbol was set.
  129. GBUdbTruncateTriggered = false; // True if Truncate was possible.
  130. GBUdbPeekTriggered = false; // True if we could peek.
  131. GBUdbSampleTriggered = false; // True if we could sample.
  132. GBUdbTruncateExecuted = false; // True if we actually did truncate.
  133. GBUdbPeekExecuted = false; // True if we peeked instead of truncating.
  134. GBUdbSampleExecuted = false; // True if we sampled.
  135. GBUdbCautionTriggered = false; // True if GBUdb found source IP suspicous.
  136. GBUdbCautionSymbolForced = false; // True if caution was on and symbol was set.
  137. // Clear the rule panic tracking list
  138. RulePanics.clear(); // Remove all entries.
  139. // Pattern Engine Scan Result Data
  140. HeaderDirectiveFlags = 0UL; // Flags set by header directives.
  141. PatternWasFound = false; // True if a pattern was found.
  142. PatternID = 0; // Rule ID of the pattern.
  143. PatternSymbol = 0; // Symbol of the pattern.
  144. MatchRecords.clear(); // Clear the match records list.
  145. MatchRecordsCursor = MatchRecords.end(); // Init the cursor to nowhere.
  146. CompositeFinalResult = -1;
  147. }
  148. //// snfCounterPack ////////////////////////////////////////////////////////////
  149. snfCounterPack::snfCounterPack() { // When constructing a counter pack
  150. reset(); // reset it.
  151. }
  152. void snfCounterPack::reset() { // When asked to reset we do this:
  153. memset(&Events, 0, sizeof(Events)); // Fill them with zeros.
  154. }
  155. //// IntervalTimer /////////////////////////////////////////////////////////////
  156. Timer& IntervalTimer::Active() { // Return the active timer.
  157. return ((ANotB)?A:B); // If A is active, return A
  158. } // otherwise return B.
  159. Timer& IntervalTimer::Inactive() { // Return the inactive timer.
  160. return ((ANotB)?B:A); // If A is active, return B
  161. } // otherwise return A.
  162. msclock IntervalTimer::hack() { // Chop off a new interval & return it.
  163. Inactive().start(Active().stop()); // Stop the active clock and reference
  164. ANotB = ~ANotB; // it to start the new Active clock.
  165. return Interval(); // Flip the bit and return the Interval.
  166. }
  167. msclock IntervalTimer::Interval() { // Return the last interval.
  168. return Inactive().getElapsedTime(); // Return the Inactive elapsed time.
  169. }
  170. msclock IntervalTimer::Elapsed() { // Return the time since last hack.
  171. return Active().getElapsedTime(); // Return the Active elapsed time.
  172. }
  173. //// snfLOGmgr /////////////////////////////////////////////////////////////////
  174. const ThreadType snfLOGmgr::Type("snfLOGmgr"); // The thread's type.
  175. snfLOGmgr::snfLOGmgr() : // Constructor for the LOG manager
  176. Thread(snfLOGmgr::Type, "Log Manager"), // snfLOGmgr Type and Name.
  177. Configured(false), // Not yet configured.
  178. TimeToDie(false), // Not yet time to die.
  179. PeekEnableCounter(0), // No peeking yet.
  180. SampleEnableCounter(0), // No sampling yet.
  181. myNETmgr(NULL), // No NET mgr yet.
  182. myGBUdb(NULL), // No GBUdb yet.
  183. NewerRulebaseIsAvailable(false), // No newer rulebase yet.
  184. SecondStatusLogger("Second Status Logger"), // Lazy writer for Second status.
  185. MinuteStatusLogger("Minute Status Logger"), // Lazy writer for Minute status.
  186. HourStatusLogger("Hour Status Logger"), // Lazy writer for Hour status.
  187. XMLScanLogger("XML Scan Logger"), // Lazy writer for XML Scan log.
  188. ClassicScanLogger("Classic Scan Logger") { // Lazy writer for Classic Scan log.
  189. StartupTime = Timestamp(); // Record when did we start.
  190. CurrentCounters = &CounterPackA; // Assign the active CounterPack.
  191. ReportingCounters = &CounterPackB; // Assign the reporting CounterPack.
  192. Timestamp(SecondReportTimestamp); // Set the basetime for the Second,
  193. Timestamp(MinuteReportTimestamp); // Minute, and Hour status reports.
  194. Timestamp(HourReportTimestamp);
  195. run(); // Run the thread.
  196. }
  197. snfLOGmgr::~snfLOGmgr() { // When we go away we must
  198. stop(); // stop if we haven't already.
  199. if(Configured) Status.store(PersistentFileName); // If safe, store our persistent data.
  200. }
  201. void snfLOGmgr::linkNETmgr(snfNETmgr& N) { myNETmgr = &N; } // Link in my NETmgr
  202. void snfLOGmgr::linkGBUdb(GBUdb& G) { myGBUdb = &G; } // Link in my GBUdb
  203. void snfLOGmgr::stop() { // When we want to stop
  204. if(!TimeToDie) { // check that we didn't already, then
  205. TimeToDie = true; // we set time to die and
  206. join(); // join the thread;
  207. }
  208. }
  209. //// Here are some functions for creating status reports.
  210. // Handy subroutine to encapsulate status log posting logic.
  211. void snfLOGmgr::postStatusLog( // Post a Status log if required.
  212. const string& LogData, // Here's the log entry's data.
  213. const string& LogFileName, // Here is where it should go.
  214. const bool LogEnabled, // This is true if we should write it.
  215. const bool AppendNotOverwrite, // True=Append, False=Overwrite.
  216. DiscLogger& Logger // The logger to use.
  217. ) {
  218. if(!LogEnabled) return; // If we're not supposed to, don't!
  219. string TFN = LogFileName; // Tagged File Name
  220. if(AppendNotOverwrite) { // If we're appending, rotate per day.
  221. TFN.append("."); // Put a timestamp on the file name.
  222. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  223. else { Timestamp(TFN); } // the utc timestamp as configured.
  224. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  225. }
  226. TFN.append(".log.xml"); // Tack on the extension.
  227. // Now feed this to the lazy logger.
  228. Logger.Enabled(LogEnabled); // Set the enable flag.
  229. Logger.AppendMode(AppendNotOverwrite); // Set the append mode.
  230. Logger.post(LogData, TFN); // Post data and update the name.
  231. }
  232. // Handy function to normalize data to a base.
  233. // Also, a collection of handy bases to normalize to ;-)
  234. const int MillisecondsInASecond = 1000; // Second
  235. const int MillisecondsInAMinute = MillisecondsInASecond * 60; // Minute
  236. const int MillisecondsInAnHour = MillisecondsInAMinute * 60; // Hour
  237. const int MillisecondsInADay = MillisecondsInAnHour * 24; // Day
  238. double snf_rationalize(double Count, double Base, double NewBase) { // Cross multiply to convert bases.
  239. if(0.0 == Base) return 0.0; // Handle division by zero like this.
  240. return (Count * NewBase) / Base; // Do the math.
  241. }
  242. double snf_AveragePerSecond(snf_SMHDMY_Counter& D, snf_SMHDMY_Counter& T) { // Avg Data/sec given Data & Time Counters.
  243. return snf_rationalize(
  244. D.SEC6SUM, T.SEC6SUM, MillisecondsInASecond);
  245. }
  246. double snf_AveragePerMinute(snf_SMHDMY_Counter& D, snf_SMHDMY_Counter& T) { // Avg Data/min given Data & Time Counters.
  247. return snf_rationalize(
  248. D.SumThru1Minute(), T.SumThru1Minute(), MillisecondsInAMinute);
  249. }
  250. double snf_AveragePerHour(snf_SMHDMY_Counter& D, snf_SMHDMY_Counter& T) { // Avg Data/min given Data & Time Counters.
  251. return snf_rationalize(
  252. D.SumThru1Hour(), T.SumThru1Hour(), MillisecondsInAnHour);
  253. }
  254. double snf_AveragePerDay(snf_SMHDMY_Counter& D, snf_SMHDMY_Counter& T) { // Avg Data/min given Data & Time Counters.
  255. return snf_rationalize(
  256. D.SumThru1Day(), T.SumThru1Day(), MillisecondsInADay);
  257. }
  258. void AppendRatesElement( // Format & output a rates element.
  259. const char* Name, // The name of the element (usually 1 char).
  260. snf_SMHDMY_Counter& D, // Data counter
  261. snf_SMHDMY_Counter& T, // Time counter
  262. ostringstream& S) { // Where to append the formatted output.
  263. S << "\t\t<" << Name << " "
  264. << "s=\'" << snf_AveragePerSecond(D, T) << "\' "
  265. << "m=\'" << snf_AveragePerMinute(D, T) << "\' "
  266. << "h=\'" << snf_AveragePerHour(D, T) << "\' "
  267. << "d=\'" << snf_AveragePerDay(D, T) << "\'/>"
  268. << endl;
  269. }
  270. void AppendHistogramElements(Histogram& H, ostringstream& S) { // Format & output a histogram.
  271. if(0 < H.size()) { // Don't output empty histograms.
  272. S << "\t\t<histogram hits=\'" << H.Hits() << "\'>" << endl; // Open tag w/ hits count.
  273. set<HistogramRecord>::iterator iH; // Use an iterator to
  274. for(iH = H.begin(); iH != H.end(); iH++) { // loop through all of the groups.
  275. S << "\t\t\t<g k=\'" // For each group in the histogram
  276. << (*iH).Key << "\' c=\'" // output the key value and
  277. << (*iH).Count << "\'/>" << endl; // the count of hits.
  278. }
  279. S << "\t\t</histogram>" << endl; // Close tag.
  280. }
  281. }
  282. // This gets called once per second. It is responsible for inputting the base
  283. // data into all of the histograms and counter mechnisms. After that, the minute
  284. // and hour reports are triggered when a full cycle of lower order data has
  285. // been collected.
  286. bool snfLOGmgr::do_SecondReport() { // Send our 1 second status report.
  287. // First thing - we always update the summaries for everybody :-)
  288. snfCounterPack& Counters = (*(getSnapshot())); // Get and swap the counters.
  289. TimeCounter.input(Counters.ActiveTime.getElapsedTime()); // Add the time interval.
  290. MessageCounter.input(Counters.Events.Scans); // Add the number of scans (messages).
  291. SpamCounter.input(Counters.Events.Spam); // Add the number of Spam events.
  292. HamCounter.input(Counters.Events.Ham); // Add the number of Ham events.
  293. WhiteCounter.input(Counters.Events.GBUdbWhiteSymbolForced); // Add the number of White events.
  294. CautionCounter.input(Counters.Events.GBUdbCautionSymbolForced); // Add the number of Caution events.
  295. BlackCounter.input(Counters.Events.GBUdbBlackSymbolForced); // Add the number of Black events.
  296. TruncateCounter.input(Counters.Events.GBUdbTruncateExecuted); // Add the number of Truncate events.
  297. SampleCounter.input(Counters.Events.GBUdbSampleExecuted); // Add the number of Sample events.
  298. AutoPanicCounter.input(Counters.Events.GBUdbAutoPanicTriggered); // Add the number of AutoPanic events.
  299. RulePanicCounter.input(Counters.Events.RulePanicFound); // Add the number of RulePanic events.
  300. // Next we produce our "Second" status report.
  301. ostringstream Report;
  302. //-- Report the stats element --
  303. Report << "<stats nodeid=\'" << NodeId << "\' "
  304. << "basetime=\'" << SecondReportTimestamp << "\' "
  305. << "elapsed=\'" << Counters.ActiveTime.getElapsedTime() << "\' "
  306. << "class=\'second\'>" << endl;
  307. SecondReportTimestamp = ""; Timestamp(SecondReportTimestamp); // Reset the timestamp for next time.
  308. //-- Version data --
  309. Report << "\t<version>" << endl
  310. << "\t\t<engine>" << SNF_ENGINE_VERSION << "</engine>" << endl;
  311. if(0 < myPlatformVersion.length()) {
  312. Report << "\t\t<platform>" << myPlatformVersion << "</platform>" << endl;
  313. }
  314. Report << "\t</version>" << endl;
  315. //-- Timers section --
  316. Report << "\t<timers>" << endl;
  317. Report << "\t\t<run started=\'" << Timestamp(StartupTime) << "\' "
  318. << "elapsed=\'" << SecsSinceStartup() << "\'/>" << endl;
  319. Report << "\t\t<sync latest=\'" << Timestamp(Status.LastSyncTime) << "\' "
  320. << "elapsed=\'" << SecsSinceLastSync() << "\'/>" << endl;
  321. Report << "\t\t<save latest=\'" << Timestamp(Status.LastSaveTime) << "\' "
  322. << "elapsed=\'" << SecsSinceLastSave() << "\'/>" << endl;
  323. Report << "\t\t<condense latest=\'" << Timestamp(Status.LastCondenseTime) << "\' "
  324. << "elapsed=\'" << SecsSinceLastCondense() << "\'/>" << endl;
  325. Report << "\t</timers>" << endl;
  326. //-- GBUdb section --
  327. Report << "\t<gbudb>" << endl;
  328. Report << "\t\t<size bytes=\'" << (*myGBUdb).Size() << "\'/>" << endl;
  329. Report << "\t\t<records count=\'" << (*myGBUdb).IPCount() << "\'/>" << endl;
  330. Report << "\t\t<utilization percent=\'" << (*myGBUdb).Utilization() << "\'/>" << endl;
  331. Report << "\t</gbudb>" << endl;
  332. //-- Counters --
  333. Report << "\t<counters>" << endl;
  334. if(0 < Counters.Events.Scans) {
  335. Report << "\t\t<m c=\'" << Counters.Events.Scans << "\'/>" << endl;
  336. }
  337. if(0 < Counters.Events.Spam) {
  338. Report << "\t\t<s c=\'" << Counters.Events.Spam << "\'/>" << endl;
  339. }
  340. if(0 < Counters.Events.Ham) {
  341. Report << "\t\t<h c=\'" << Counters.Events.Ham << "\'/>" << endl;
  342. }
  343. if(0 < Counters.Events.GBUdbTruncateExecuted) {
  344. Report << "\t\t<t c=\'" << Counters.Events.GBUdbTruncateExecuted << "\'/>" << endl;
  345. }
  346. if(0 < Counters.Events.GBUdbBlackSymbolForced) {
  347. Report << "\t\t<b c=\'" << Counters.Events.GBUdbBlackSymbolForced << "\'/>" << endl;
  348. }
  349. if(0 < Counters.Events.GBUdbCautionSymbolForced) {
  350. Report << "\t\t<c c=\'" << Counters.Events.GBUdbCautionSymbolForced << "\'/>" << endl;
  351. }
  352. if(0 < Counters.Events.GBUdbWhiteSymbolForced) {
  353. Report << "\t\t<w c=\'" << Counters.Events.GBUdbWhiteSymbolForced << "\'/>" << endl;
  354. }
  355. if(0 < Counters.Events.GBUdbAutoPanicExecuted) {
  356. Report << "\t\t<a c=\'" << Counters.Events.GBUdbAutoPanicExecuted << "\'/>" << endl;
  357. }
  358. if(0 < Counters.Events.RulePanicFound) {
  359. Report << "\t\t<r c=\'" << Counters.Events.RulePanicFound << "\'/>" << endl;
  360. }
  361. Report << "\t</counters>" << endl;
  362. Counters.reset(); // When done, clear the counters.
  363. //-- Rates ---
  364. Report << "\t<rates>" << endl;
  365. AppendRatesElement("m", MessageCounter, TimeCounter, Report);
  366. AppendRatesElement("s", SpamCounter, TimeCounter, Report);
  367. AppendRatesElement("h", HamCounter, TimeCounter, Report);
  368. AppendRatesElement("w", WhiteCounter, TimeCounter, Report);
  369. AppendRatesElement("c", CautionCounter, TimeCounter, Report);
  370. AppendRatesElement("b", BlackCounter, TimeCounter, Report);
  371. AppendRatesElement("t", TruncateCounter, TimeCounter, Report);
  372. AppendRatesElement("a", AutoPanicCounter, TimeCounter, Report);
  373. AppendRatesElement("r", RulePanicCounter, TimeCounter, Report);
  374. Report << "\t</rates>" << endl;
  375. //-- Results ---
  376. Report << "\t<results>" << endl;
  377. AppendHistogramElements(ResultsSecond, Report);
  378. ResultsSecond.reset();
  379. Report << "\t</results>" << endl;
  380. //-- Rules ---
  381. Report << "\t<rules>" << endl;
  382. string RBUTC;
  383. Report << "\t\t<rulebase utc=\'" << (*myNETmgr).RulebaseUTC(RBUTC) << "\'/>" << endl;
  384. Report << "\t\t<active utc=\'" << ActiveRulebaseUTC << "\'/>" << endl;
  385. Report << "\t\t<update ready=\'" << ((NewerRulebaseIsAvailable)?"yes":"no")
  386. << "\' utc=\'" << AvailableRulebaseUTC << "\'/>" << endl;
  387. Report << "\t\t<latest rule=\'" << LatestRuleID() << "\'/>" << endl;
  388. AppendHistogramElements(RulesSecond, Report);
  389. RulesSecond.reset();
  390. Report << "\t</rules>" << endl;
  391. //-- Panics ---
  392. Report << "\t<panics>" << endl;
  393. AppendHistogramElements(PanicsSecond, Report);
  394. PanicsSecond.reset();
  395. Report << "\t</panics>" << endl;
  396. //-- Close the stats element --
  397. Report << "</stats>" << endl;
  398. // Now that we've built the report we need to store it and send it to
  399. // the network manager.
  400. ConfigMutex.lock(); // Freeze while we get our settings.
  401. bool LogEnabled = SecondReport_Log_OnOff; // To log or not to log?
  402. bool AppendNotOverwrite = SecondReport_Append_OnOff; // To append or overwrite?
  403. string LogFileName = SecondReport_Log_Filename; // What file name?
  404. ConfigMutex.unlock(); // Ok, done with that.
  405. postStatusLog( // Post a Status log if required.
  406. Report.str(), // Here's the log entry's data.
  407. LogFileName, // Here is where it should go.
  408. LogEnabled, // This is true if we should write it.
  409. AppendNotOverwrite, // True=Append, False=Overwrite.
  410. SecondStatusLogger // Lazy log writer to use.
  411. );
  412. // Just before we go we save our stat for others to see.
  413. ScopeMutex HoldForStatusUpdate(StatusReportMutex); // Hold the mutex just long enough
  414. SecondReportText = Report.str(); // to post our status and return
  415. // Finally we return the test - Do we have a complete cycle in Seconds?
  416. return(TimeCounter.Cycled60Seconds()); // True on a full cycle of seconds.
  417. }
  418. bool snfLOGmgr::do_MinuteReport() { // Send our 1 minute status report.
  419. // Produce our "Minute" status report.
  420. ostringstream Report;
  421. //-- Report the stats element --
  422. Report << "<stats nodeid=\'" << NodeId << "\' "
  423. << "basetime=\'" << MinuteReportTimestamp << "\' "
  424. << "elapsed=\'" << TimeCounter.Sum60Seconds() << "\' "
  425. << "class=\'minute\'>" << endl;
  426. MinuteReportTimestamp = ""; Timestamp(MinuteReportTimestamp); // Reset the timestamp for next time.
  427. //-- Version data --
  428. Report << "\t<version>" << endl
  429. << "\t\t<engine>" << SNF_ENGINE_VERSION << "</engine>" << endl;
  430. if(0 < myPlatformVersion.length()) {
  431. Report << "\t\t<platform>" << myPlatformVersion << "</platform>" << endl;
  432. }
  433. Report << "\t</version>" << endl;
  434. //-- Timers section --
  435. Report << "\t<timers>" << endl;
  436. Report << "\t\t<run started=\'" << Timestamp(StartupTime) << "\' "
  437. << "elapsed=\'" << SecsSinceStartup() << "\'/>" << endl;
  438. Report << "\t\t<sync latest=\'" << Timestamp(Status.LastSyncTime) << "\' "
  439. << "elapsed=\'" << SecsSinceLastSync() << "\'/>" << endl;
  440. Report << "\t\t<save latest=\'" << Timestamp(Status.LastSaveTime) << "\' "
  441. << "elapsed=\'" << SecsSinceLastSave() << "\'/>" << endl;
  442. Report << "\t\t<condense latest=\'" << Timestamp(Status.LastCondenseTime) << "\' "
  443. << "elapsed=\'" << SecsSinceLastCondense() << "\'/>" << endl;
  444. Report << "\t</timers>" << endl;
  445. //-- GBUdb section --
  446. Report << "\t<gbudb>" << endl;
  447. Report << "\t\t<size bytes=\'" << (*myGBUdb).Size() << "\'/>" << endl;
  448. Report << "\t\t<records count=\'" << (*myGBUdb).IPCount() << "\'/>" << endl;
  449. Report << "\t\t<utilization percent=\'" << (*myGBUdb).Utilization() << "\'/>" << endl;
  450. Report << "\t</gbudb>" << endl;
  451. //-- Counters --
  452. Report << "\t<counters>" << endl;
  453. if(0 < MessageCounter.Sum60Seconds()) {
  454. Report << "\t\t<m c=\'" << MessageCounter.Sum60Seconds() << "\'/>" << endl;
  455. }
  456. if(0 < SpamCounter.Sum60Seconds()) {
  457. Report << "\t\t<s c=\'" << SpamCounter.Sum60Seconds() << "\'/>" << endl;
  458. }
  459. if(0 < HamCounter.Sum60Seconds()) {
  460. Report << "\t\t<h c=\'" << HamCounter.Sum60Seconds() << "\'/>" << endl;
  461. }
  462. if(0 < TruncateCounter.Sum60Seconds()) {
  463. Report << "\t\t<t c=\'" << TruncateCounter.Sum60Seconds() << "\'/>" << endl;
  464. }
  465. if(0 < BlackCounter.Sum60Seconds()) {
  466. Report << "\t\t<b c=\'" << BlackCounter.Sum60Seconds() << "\'/>" << endl;
  467. }
  468. if(0 < CautionCounter.Sum60Seconds()) {
  469. Report << "\t\t<c c=\'" << CautionCounter.Sum60Seconds() << "\'/>" << endl;
  470. }
  471. if(0 < WhiteCounter.Sum60Seconds()) {
  472. Report << "\t\t<w c=\'" << WhiteCounter.Sum60Seconds() << "\'/>" << endl;
  473. }
  474. if(0 < AutoPanicCounter.Sum60Seconds()) {
  475. Report << "\t\t<a c=\'" << AutoPanicCounter.Sum60Seconds() << "\'/>" << endl;
  476. }
  477. if(0 < RulePanicCounter.Sum60Seconds()) {
  478. Report << "\t\t<a c=\'" << RulePanicCounter.Sum60Seconds() << "\'/>" << endl;
  479. }
  480. Report << "\t</counters>" << endl;
  481. //-- Rates ---
  482. Report << "\t<rates>" << endl;
  483. AppendRatesElement("m", MessageCounter, TimeCounter, Report);
  484. AppendRatesElement("s", SpamCounter, TimeCounter, Report);
  485. AppendRatesElement("h", HamCounter, TimeCounter, Report);
  486. AppendRatesElement("w", WhiteCounter, TimeCounter, Report);
  487. AppendRatesElement("c", CautionCounter, TimeCounter, Report);
  488. AppendRatesElement("b", BlackCounter, TimeCounter, Report);
  489. AppendRatesElement("t", TruncateCounter, TimeCounter, Report);
  490. AppendRatesElement("a", AutoPanicCounter, TimeCounter, Report);
  491. AppendRatesElement("r", RulePanicCounter, TimeCounter, Report);
  492. Report << "\t</rates>" << endl;
  493. //-- Results ---
  494. Report << "\t<results>" << endl;
  495. AppendHistogramElements(ResultsMinute, Report);
  496. ResultsMinute.reset();
  497. Report << "\t</results>" << endl;
  498. //-- Rules ---
  499. Report << "\t<rules>" << endl;
  500. string RBUTC;
  501. Report << "\t\t<rulebase utc=\'" << (*myNETmgr).RulebaseUTC(RBUTC) << "\'/>" << endl;
  502. Report << "\t\t<active utc=\'" << ActiveRulebaseUTC << "\'/>" << endl;
  503. Report << "\t\t<update ready=\'" << ((NewerRulebaseIsAvailable)?"yes":"no")
  504. << "\' utc=\'" << AvailableRulebaseUTC << "\'/>" << endl;
  505. Report << "\t\t<latest rule=\'" << LatestRuleID() << "\'/>" << endl;
  506. AppendHistogramElements(RulesMinute, Report);
  507. RulesMinute.reset();
  508. Report << "\t</rules>" << endl;
  509. //-- Panics ---
  510. Report << "\t<panics>" << endl;
  511. AppendHistogramElements(PanicsMinute, Report);
  512. PanicsMinute.reset();
  513. Report << "\t</panics>" << endl;
  514. //-- Close the stats element --
  515. Report << "</stats>" << endl;
  516. // Now that we've built the report we need to store it and send it to
  517. // the network manager.
  518. ConfigMutex.lock(); // Freeze while we get our settings.
  519. bool LogEnabled = MinuteReport_Log_OnOff; // To log or not to log?
  520. bool AppendNotOverwrite = MinuteReport_Append_OnOff; // To append or overwrite?
  521. string LogFileName = MinuteReport_Log_Filename; // What file name?
  522. ConfigMutex.unlock(); // Ok, done with that.
  523. postStatusLog( // Post a Status log if required.
  524. Report.str(), // Here's the log entry's data.
  525. LogFileName, // Here is where it should go.
  526. LogEnabled, // This is true if we should write it.
  527. AppendNotOverwrite, // True=Append, False=Overwrite.
  528. MinuteStatusLogger // Lazy log writer to use.
  529. );
  530. (*myNETmgr).sendReport(Report.str()); // Send the status report to the net.
  531. // Just before we go we save our stat for others to see.
  532. ScopeMutex HoldForStatusUpdate(StatusReportMutex); // Hold the mutex just long enough
  533. MinuteReportText = Report.str(); // to post our status and return
  534. return(TimeCounter.Cycled60Minutes()); // True at a full cycle of minutes.
  535. }
  536. bool snfLOGmgr::do_HourReport() { // Send our 1 hour status report.
  537. // Produce our "Hour" status report.
  538. ostringstream Report;
  539. //-- Report the stats element --
  540. Report << "<stats nodeid=\'" << NodeId << "\' "
  541. << "basetime=\'" << HourReportTimestamp << "\' "
  542. << "elapsed=\'" << TimeCounter.Sum60Minutes() << "\' "
  543. << "class=\'hour\'>" << endl;
  544. HourReportTimestamp = ""; Timestamp(HourReportTimestamp); // Reset the timestamp for next time.
  545. //-- Version data --
  546. Report << "\t<version>" << endl
  547. << "\t\t<engine>" << SNF_ENGINE_VERSION << "</engine>" << endl;
  548. if(0 < myPlatformVersion.length()) {
  549. Report << "\t\t<platform>" << myPlatformVersion << "</platform>" << endl;
  550. }
  551. Report << "\t</version>" << endl;
  552. //-- Timers section --
  553. Report << "\t<timers>" << endl;
  554. Report << "\t\t<run started=\'" << Timestamp(StartupTime) << "\' "
  555. << "elapsed=\'" << SecsSinceStartup() << "\'/>" << endl;
  556. Report << "\t\t<sync latest=\'" << Timestamp(Status.LastSyncTime) << "\' "
  557. << "elapsed=\'" << SecsSinceLastSync() << "\'/>" << endl;
  558. Report << "\t\t<save latest=\'" << Timestamp(Status.LastSaveTime) << "\' "
  559. << "elapsed=\'" << SecsSinceLastSave() << "\'/>" << endl;
  560. Report << "\t\t<condense latest=\'" << Timestamp(Status.LastCondenseTime) << "\' "
  561. << "elapsed=\'" << SecsSinceLastCondense() << "\'/>" << endl;
  562. Report << "\t</timers>" << endl;
  563. //-- GBUdb section --
  564. Report << "\t<gbudb>" << endl;
  565. Report << "\t\t<size bytes=\'" << (*myGBUdb).Size() << "\'/>" << endl;
  566. Report << "\t\t<records count=\'" << (*myGBUdb).IPCount() << "\'/>" << endl;
  567. Report << "\t\t<utilization percent=\'" << (*myGBUdb).Utilization() << "\'/>" << endl;
  568. Report << "\t</gbudb>" << endl;
  569. //-- Counters --
  570. Report << "\t<counters>" << endl;
  571. if(0 < MessageCounter.Sum60Minutes()) {
  572. Report << "\t\t<m c=\'" << MessageCounter.Sum60Minutes() << "\'/>" << endl;
  573. }
  574. if(0 < SpamCounter.Sum60Minutes()) {
  575. Report << "\t\t<s c=\'" << SpamCounter.Sum60Minutes() << "\'/>" << endl;
  576. }
  577. if(0 < HamCounter.Sum60Minutes()) {
  578. Report << "\t\t<h c=\'" << HamCounter.Sum60Minutes() << "\'/>" << endl;
  579. }
  580. if(0 < TruncateCounter.Sum60Minutes()) {
  581. Report << "\t\t<t c=\'" << TruncateCounter.Sum60Minutes() << "\'/>" << endl;
  582. }
  583. if(0 < BlackCounter.Sum60Minutes()) {
  584. Report << "\t\t<b c=\'" << BlackCounter.Sum60Minutes() << "\'/>" << endl;
  585. }
  586. if(0 < CautionCounter.Sum60Minutes()) {
  587. Report << "\t\t<c c=\'" << CautionCounter.Sum60Minutes() << "\'/>" << endl;
  588. }
  589. if(0 < WhiteCounter.Sum60Minutes()) {
  590. Report << "\t\t<w c=\'" << WhiteCounter.Sum60Minutes() << "\'/>" << endl;
  591. }
  592. if(0 < AutoPanicCounter.Sum60Minutes()) {
  593. Report << "\t\t<a c=\'" << AutoPanicCounter.Sum60Minutes() << "\'/>" << endl;
  594. }
  595. if(0 < RulePanicCounter.Sum60Minutes()) {
  596. Report << "\t\t<a c=\'" << RulePanicCounter.Sum60Minutes() << "\'/>" << endl;
  597. }
  598. Report << "\t</counters>" << endl;
  599. //-- Rates ---
  600. Report << "\t<rates>" << endl;
  601. AppendRatesElement("m", MessageCounter, TimeCounter, Report);
  602. AppendRatesElement("s", SpamCounter, TimeCounter, Report);
  603. AppendRatesElement("h", HamCounter, TimeCounter, Report);
  604. AppendRatesElement("w", WhiteCounter, TimeCounter, Report);
  605. AppendRatesElement("c", CautionCounter, TimeCounter, Report);
  606. AppendRatesElement("b", BlackCounter, TimeCounter, Report);
  607. AppendRatesElement("t", TruncateCounter, TimeCounter, Report);
  608. AppendRatesElement("a", AutoPanicCounter, TimeCounter, Report);
  609. AppendRatesElement("r", RulePanicCounter, TimeCounter, Report);
  610. Report << "\t</rates>" << endl;
  611. //-- Results ---
  612. Report << "\t<results>" << endl;
  613. AppendHistogramElements(ResultsHour, Report);
  614. ResultsHour.reset();
  615. Report << "\t</results>" << endl;
  616. //-- Rules ---
  617. Report << "\t<rules>" << endl;
  618. string RBUTC;
  619. Report << "\t\t<rulebase utc=\'" << (*myNETmgr).RulebaseUTC(RBUTC) << "\'/>" << endl;
  620. Report << "\t\t<active utc=\'" << ActiveRulebaseUTC << "\'/>" << endl;
  621. Report << "\t\t<update ready=\'" << ((NewerRulebaseIsAvailable)?"yes":"no")
  622. << "\' utc=\'" << AvailableRulebaseUTC << "\'/>" << endl;
  623. Report << "\t\t<latest rule=\'" << LatestRuleID() << "\'/>" << endl;
  624. AppendHistogramElements(RulesHour, Report);
  625. RulesHour.reset();
  626. Report << "\t</rules>" << endl;
  627. //-- Panics ---
  628. Report << "\t<panics>" << endl;
  629. AppendHistogramElements(PanicsHour, Report);
  630. PanicsHour.reset();
  631. Report << "\t</panics>" << endl;
  632. //-- Close the stats element --
  633. Report << "</stats>" << endl;
  634. // Now that we've built the report we need to store it and send it to
  635. // the network manager.
  636. ConfigMutex.lock(); // Freeze while we get our settings.
  637. bool LogEnabled = HourReport_Log_OnOff; // To log or not to log?
  638. bool AppendNotOverwrite = HourReport_Append_OnOff; // To append or overwrite?
  639. string LogFileName = HourReport_Log_Filename; // What file name?
  640. ConfigMutex.unlock(); // Ok, done with that.
  641. postStatusLog( // Post a Status log if required.
  642. Report.str(), // Here's the log entry's data.
  643. LogFileName, // Here is where it should go.
  644. LogEnabled, // This is true if we should write it.
  645. AppendNotOverwrite, // True=Append, False=Overwrite.
  646. HourStatusLogger // Lazy log writer to use.
  647. );
  648. // Just before we go we save our stat for others to see.
  649. ScopeMutex HoldForStatusUpdate(StatusReportMutex); // Hold the mutex just long enough
  650. HourReportText = Report.str(); // to post our status and return
  651. return(TimeCounter.Cycled24Hours()); // True at a full cycle of hours.
  652. }
  653. void snfLOGmgr::do_StatusReports() { // Do the status reports.
  654. ScopeMutex PauseWhileITotalThis(MyMutex); // Everybody stop for a bit. Each report
  655. if(do_SecondReport()) // returns true if it has cycled so
  656. if(do_MinuteReport()) // that the next report can be checked
  657. do_HourReport(); // to see if it has cycled.
  658. }
  659. void snfLOGmgr::myTask() { // Thread: Live stats & reports.
  660. Sleeper WaitATic(MillisecondsInASecond); // One second sleeper.
  661. while(!TimeToDie) { // Do this until it's time to die.
  662. if(Configured) { // If we are configured do our work.
  663. do_StatusReports(); // Make our status reports (chained).
  664. }
  665. WaitATic();
  666. }
  667. }
  668. // Note about snfLOGmgr::configure() and Status.restore()
  669. // store() and restore() watch the Status.Ready flag. If
  670. // Status is ready, restore() won't. If Status is not ready
  671. // store() won't. Also, if restore() doesn't find a file, it
  672. // just clears everything and goes ready, assuming that this
  673. // is a new persistent state.
  674. void snfLOGmgr::configure(snfCFGData& CFGData) { // Update the configuration.
  675. ScopeMutex HoldOnWhileITweakThisThing(ConfigMutex);
  676. PersistentFileName = CFGData.paths_workspace_path + ".state"; // Build the persistent state path.
  677. Status.restore(PersistentFileName); // Load our persistent state.
  678. NodeId = CFGData.node_licenseid; // Grab the node id for reports.
  679. // Copy the logging configuration info from CFGData
  680. Rotate_LocalTime = CFGData.Logs_Rotation_LocalTime_OnOff; // Rotate using local time?
  681. XML_Log_Mode = CFGData.Scan_XML_Mode; // What is the XML log mode.
  682. Classic_Log_Mode = CFGData.Scan_Classic_Mode; // What is the Classic log mode.
  683. LogsPath = CFGData.paths_log_path; // Path to logs directory.
  684. ClassicLogRotate = CFGData.Scan_Classic_Rotate; // True = Rotate Classic Log.
  685. XMLLogRotate = CFGData.Scan_XML_Rotate; // True = Rotate XML Log.
  686. SecondReport_Log_OnOff = CFGData.Status_SecondReport_Log_OnOff;
  687. SecondReport_Append_OnOff = CFGData.Status_SecondReport_Append_OnOff;
  688. SecondReport_Log_Filename = CFGData.paths_log_path + NodeId + ".status.second";
  689. MinuteReport_Log_OnOff = CFGData.Status_MinuteReport_Log_OnOff;
  690. MinuteReport_Append_OnOff = CFGData.Status_MinuteReport_Append_OnOff;
  691. MinuteReport_Log_Filename = CFGData.paths_log_path + NodeId + ".status.minute";
  692. HourReport_Log_OnOff = CFGData.Status_HourReport_Log_OnOff;
  693. HourReport_Append_OnOff = CFGData.Status_HourReport_Append_OnOff;
  694. HourReport_Log_Filename = CFGData.paths_log_path + NodeId + ".status.hour";
  695. // Sanity check
  696. if(NULL != myNETmgr && NULL != myGBUdb) { // If we are fully linked then
  697. Configured = true; // we are now configured.
  698. }
  699. }
  700. void snfLOGmgr::doXHDRs(snfCFGData& CFGData, snfScanData& ScanData) { // XHDR sub routine for LogThisScan()
  701. ostringstream O; // Setup the output stream.
  702. const string SMTPENDL = "\r\n"; // Make a hard-coded SMTP endline.
  703. // Version header
  704. if(CFGData.XHDRVersion_OnOff) { // If the Version XHDR is on then
  705. O << CFGData.XHDRVersion_Header << ": " // emit the Version XHDR.
  706. << SMTPENDL << "\t" << SNF_ENGINE_VERSION;
  707. if(0 < myPlatformVersion.length()) { // Optional Platform Version.
  708. O << SMTPENDL << "\t" << myPlatformVersion;
  709. }
  710. O << SMTPENDL;
  711. }
  712. // License header
  713. if(CFGData.XHDRLicense_OnOff) { // If the license XHDR is on then
  714. O << CFGData.XHDRLicense_Header << ": " // emit the License XHRD.
  715. << CFGData.node_licenseid
  716. << SMTPENDL;
  717. }
  718. // Rulebase header
  719. if(CFGData.XHDRRulebase_OnOff) { // If the rulebase utc XHDR is on
  720. string RBUTC; // then make a string to capture it
  721. O << CFGData.XHDRRulebase_Header << ": " // then emit the rulebase utc XHDR.
  722. << (*myNETmgr).RulebaseUTC(RBUTC)
  723. << SMTPENDL;
  724. }
  725. // Identifier header
  726. if(CFGData.XHDRIdentifier_OnOff) { // If the identifier XHDR is on
  727. O << CFGData.XHDRIdentifier_Header << ": " // then emit the scan identifier.
  728. << ScanData.ScanName
  729. << SMTPENDL;
  730. }
  731. // GBUdb header
  732. if(CFGData.XHDRGBUdb_OnOff) { // If the GBUdb XHDR is on then
  733. O << CFGData.XHDRGBUdb_Header << ": "; // then emit the GBUdb XHDR.
  734. if(!ScanData.FoundSourceIP()) { // If no source was identified
  735. O << "Unknown" // then we emit "Unknown".
  736. << SMTPENDL;
  737. } else { // If the source was identified
  738. O << ScanData.SourceIPRecord().Ordinal << ", " // then we emit the ordial,
  739. << (string) IP4Address(ScanData.SourceIPRecord().IP) << ", " // the IP, and then
  740. << ScanData.SourceIPEvaluation // the IP evaluation that was
  741. << SMTPENDL; // sent to the scanner.
  742. }
  743. }
  744. // Result header
  745. if(CFGData.XHDRResult_OnOff) { // If the Result XHDR is on then
  746. O << CFGData.XHDRResult_Header << ": " // emit the scan result code XHDR.
  747. << ScanData.CompositeFinalResult
  748. << SMTPENDL;
  749. }
  750. // Matches header
  751. if(CFGData.XHDRMatches_OnOff) { // If the Matches XHDR is on then
  752. O << CFGData.XHDRMatches_Header << ":" << SMTPENDL; // emit the Matches XHDR with matches.
  753. for(
  754. list<snf_match>::iterator iM = ScanData.MatchRecords.begin(); // Loop through the match list
  755. iM != ScanData.MatchRecords.end(); iM++ // one by one.
  756. ) {
  757. snf_match& M = (*iM); // Emit each match record as a
  758. O << "\t" // folded entry in the header.
  759. << M.symbol << "-" // symbol-ruleid-index-endex-flag
  760. << M.ruleid << "-"
  761. << M.index << "-"
  762. << M.endex << "-"
  763. << M.flag
  764. << SMTPENDL;
  765. }
  766. }
  767. // Black header
  768. const int AboveBandRange = 64;
  769. if(
  770. CFGData.XHDRBlack_OnOff && // If the Black XHDR is on and
  771. 0 < ScanData.CompositeFinalResult && // We have a nonzero result and
  772. AboveBandRange > ScanData.CompositeFinalResult && // it is not an above-band code and
  773. !CFGData.TrainingWhiteRuleHandler.isListed( // it is not found in the training
  774. ScanData.CompositeFinalResult) // white list then...
  775. ) {
  776. O << CFGData.XHDRBlack_Header // Emit the Black XHDR.
  777. << SMTPENDL;
  778. }
  779. // White header
  780. if( // If the White XHDR is on and
  781. CFGData.XHDRWhite_OnOff && // the result was listed in the
  782. CFGData.TrainingWhiteRuleHandler.isListed( // training white list then...
  783. ScanData.CompositeFinalResult)
  784. ) {
  785. O << CFGData.XHDRWhite_Header // Emit the White XHDR.
  786. << SMTPENDL;
  787. }
  788. // Clean header
  789. if(
  790. CFGData.XHDRClean_OnOff && // If the Clean XHDR is on and
  791. !ScanData.PatternWasFound && // no pattern was found and
  792. 0 == ScanData.CompositeFinalResult // the scan result is zero then...
  793. ) {
  794. O << CFGData.XHDRClean_Header // Emit the Clean XHDR
  795. << SMTPENDL;
  796. }
  797. // Symbol headers
  798. string SH = CFGData.XHDRSymbolHeaders.HeaderForSymbol( // Check for a Symbol XHDR
  799. ScanData.CompositeFinalResult // matching this result.
  800. );
  801. if(0 < SH.length()) { // If we have an XHDR for this
  802. O << SH // result then emit the header.
  803. << SMTPENDL;
  804. }
  805. ScanData.XHDRsText = O.str(); // Save the formatted XHeaders.
  806. }
  807. void snfLOGmgr::doXMLLogs(snfCFGData& CFGData, snfScanData& ScanData) { // XML sub routine for LogThisScan()
  808. ostringstream O; // Set up the output stream.
  809. bool WeHaveSubordinates = false; // Expect no subordinates at first.
  810. // We do the match sections together because it allows us to scan through
  811. // the match results once and pick up the final result for the <s/> section.
  812. // This way, even if no <m/>atch elements are emitted we will have the
  813. // final result without having to scan the data twice.
  814. // <s/> -- Scan Log Entry (always on if modes is not none)
  815. // <m/> -- Scan Match Entry (controlled by matches attribute)
  816. ostringstream R; // Match (R)ecords output.
  817. set<int> Duplicates; // Set up to track duplicates.
  818. list<snf_match>::iterator MatchRecordsCursor; // Set up a cursor to the results.
  819. for(
  820. MatchRecordsCursor = ScanData.MatchRecords.begin(); // Loop through the scan results
  821. MatchRecordsCursor != ScanData.MatchRecords.end();
  822. MatchRecordsCursor++
  823. ) {
  824. snf_match& M = (*MatchRecordsCursor); // Grab the current match record.
  825. if(
  826. ScanLogMatches_None != CFGData.Scan_XML_Matches && // If match records are requested
  827. ('f' != M.flag && 'c' != M.flag) // and this record is not the (f)inal
  828. ) { // then evaluate it and log (??) it.
  829. if(ScanLogMatches_Unique == CFGData.Scan_Classic_Matches) { // If only unique matches are required
  830. if(Duplicates.end() != Duplicates.find(M.ruleid)) { // check for a duplicate rule id.
  831. continue; // If the rule id was found then skip.
  832. } else { // If the rule id was not found then
  833. Duplicates.insert(M.ruleid); // remember it for next time.
  834. }
  835. }
  836. // At this point we've skipped duplicate match records, but we
  837. // still want to emit some (all?) of them so it's time to do it.
  838. // <m s='48' r='1234567' i='2394' e='2409' f='m'/>
  839. R << "\t<m "
  840. << "s=\'" << M.symbol << "\' "
  841. << "r=\'" << M.ruleid << "\' "
  842. << "i=\'" << M.index << "\' "
  843. << "e=\'" << M.endex << "\' "
  844. << "f=\'" << M.flag << "\'/>"
  845. << endl;
  846. } else
  847. if('f' == M.flag || 'c' == M.flag) { // If this record is final, emit it!
  848. WeHaveSubordinates = (
  849. ((ScanLogMatches_None != CFGData.Scan_XML_Matches)
  850. && ('f' == M.flag)) ||
  851. (true == CFGData.Scan_XML_GBUdb) ||
  852. (true == CFGData.Scan_XML_Performance)
  853. );
  854. // <s u='20070508012349' m='msg0123456789.msg' s='48' r='1234567' >
  855. O << "<s " // Format the <s>can element
  856. << "u=\'" << Timestamp(ScanData.StartOfJobUTC) << "\' "
  857. << "m=\'" << ScanData.ScanName << "\' "
  858. << "s=\'" << M.symbol << "\' "
  859. << "r=\'" << M.ruleid << "\'"
  860. << ((WeHaveSubordinates)? ">" : "/>")
  861. << endl;
  862. }
  863. }
  864. if(ScanLogMatches_None != CFGData.Scan_XML_Matches) O << R.str(); // Emit the match records if any.
  865. // <p/> -- Scan Performance Monitoring (performance='yes')
  866. // <p s='10' t='8' l='3294' d='84'/>
  867. if(CFGData.Scan_XML_Performance) { // Post performance data if needed.
  868. O << "\t<p "
  869. << "s=\'" << ScanData.SetupTime << "\' "
  870. << "t=\'" << ScanData.ScanTime.getElapsedTime() << "\' "
  871. << "l=\'" << ScanData.ScanSize << "\' "
  872. << "d=\'" << ScanData.ScanDepth << "\'/>"
  873. << endl;
  874. }
  875. // <g/> -- GBUdb Activity For This Scan (gbudb='yes')
  876. // <g o='1' i='101.201.31.04' t='u' c='0.12345' p='0.3342983' r='Caution'/>
  877. if(CFGData.Scan_XML_GBUdb && ScanData.FoundSourceIP()) { // Post gbudb data if needed & ready.
  878. O << "\t<g "
  879. << "o=\'" << ScanData.SourceIPRecord().Ordinal << "\' "
  880. << "i=\'" << (string) IP4Address(ScanData.SourceIPRecord().IP) << "\' "
  881. << "t=\'" <<
  882. ((Ugly == ScanData.SourceIPRecord().GBUdbData.Flag())? "u" :
  883. ((Good == ScanData.SourceIPRecord().GBUdbData.Flag())? "g" :
  884. ((Bad == ScanData.SourceIPRecord().GBUdbData.Flag())? "b" : "i")))
  885. << "\' "
  886. << "c=\'" << ScanData.SourceIPRecord().GBUdbData.Confidence() << "\' "
  887. << "p=\'" << ScanData.SourceIPRecord().GBUdbData.Probability() << "\' "
  888. << "r=\'" <<
  889. ((Unknown == ScanData.SourceIPRange())? "Unknown" :
  890. ((White == ScanData.SourceIPRange())? "White" :
  891. ((Normal == ScanData.SourceIPRange())? "Normal" :
  892. ((New == ScanData.SourceIPRange())? "New" :
  893. ((Caution == ScanData.SourceIPRange())? "Caution" :
  894. ((Black == ScanData.SourceIPRange())? "Black" :
  895. ((Truncate == ScanData.SourceIPRange())? "Truncate" :
  896. "Fault")))))))
  897. << "\'/>"
  898. << endl;
  899. }
  900. // If this wasn't a one-liner then we need to close the <s/> element
  901. if(WeHaveSubordinates) O << "</s>" << endl; // If <s> was open then close it.
  902. ScanData.XMLLogText = O.str(); // Save the formatted log text.
  903. // Now that we've produced the appropriate log entries let's send them
  904. // out to the log file.
  905. if(LogOutputMode_File == CFGData.Scan_XML_Mode) { // If we are writing to file,
  906. string TFN = CFGData.paths_log_path; // build an appropriate log file
  907. TFN.append(CFGData.node_licenseid); // name.
  908. if(CFGData.Scan_XML_Rotate) { // If we're rotating per day:
  909. TFN.append("."); // Put a timestamp on the file name.
  910. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  911. else { Timestamp(TFN); } // the utc timestamp as configured.
  912. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  913. }
  914. TFN.append(".log.xml"); // Tack on the extension.
  915. XMLScanLogger.post(ScanData.XMLLogText, TFN); // Post the log with the file name.
  916. }
  917. }
  918. void snfLOGmgr::doClassicLogs(snfCFGData& CFGData, snfScanData& ScanData) { // Classic sub routine for LogThisScan()
  919. ostringstream O; // Set up the output stream.
  920. set<int> Duplicates; // Set up to track duplicates.
  921. list<snf_match>::iterator MatchRecordsCursor; // Set up a cursor to the results.
  922. for(
  923. MatchRecordsCursor = ScanData.MatchRecords.begin(); // Loop through the scan results
  924. MatchRecordsCursor != ScanData.MatchRecords.end();
  925. MatchRecordsCursor++
  926. ) {
  927. snf_match& M = (*MatchRecordsCursor); // Grab the current match record.
  928. if(
  929. ScanLogMatches_None != CFGData.Scan_Classic_Matches && // If match records are requested
  930. ('f' != M.flag && 'c' != M.flag) // and this record is not the (f)inal
  931. ) { // then evaluate it and log (??) it.
  932. if(ScanLogMatches_Unique == CFGData.Scan_Classic_Matches) { // If only unique matches are required
  933. if(Duplicates.end() != Duplicates.find(M.ruleid)) { // check for a duplicate rule id.
  934. continue; // If the rule id was found then skip.
  935. } else { // If the rule id was not found then
  936. Duplicates.insert(M.ruleid); // remember it for next time.
  937. }
  938. }
  939. // At this point we've skipped duplicate match records, but we
  940. // still want to emit some (all?) of them so it's time to do it.
  941. O << CFGData.node_licenseid << "\t"
  942. << Timestamp(ScanData.StartOfJobUTC) << "\t"
  943. << ScanData.ScanName << "\t"
  944. << ScanData.SetupTime << "\t"
  945. << ScanData.ScanTime.getElapsedTime() << "\t"
  946. << (('m' == M.flag) ? "Match\t" :
  947. (('w' == M.flag) ? "White\t" :
  948. (('p' == M.flag) ? "Panic\t" : "Fault\t")))
  949. << M.ruleid << "\t"
  950. << M.symbol << "\t"
  951. << M.index << "\t"
  952. << M.endex << "\t"
  953. << ScanData.ScanDepth
  954. << endl;
  955. } else { // If this record is final, emit it!
  956. O << CFGData.node_licenseid << "\t"
  957. << Timestamp(ScanData.StartOfJobUTC) << "\t"
  958. << ScanData.ScanName << "\t"
  959. << ScanData.SetupTime << "\t"
  960. << ScanData.ScanTime.getElapsedTime() << "\t"
  961. << (('f' == M.flag) ? "Final\t" :
  962. (('c' == M.flag) ? "Clean\t" : "Fault\t"))
  963. << M.ruleid << "\t"
  964. << M.symbol << "\t"
  965. << M.index << "\t"
  966. << M.endex << "\t"
  967. << ScanData.ScanDepth
  968. << endl;
  969. }
  970. }
  971. ScanData.ClassicLogText = O.str(); // Save the formatted log text.
  972. // Now that we've produced the appropriate log entries let's send them
  973. // out to the log file.
  974. if(LogOutputMode_File == CFGData.Scan_Classic_Mode) { // If we are writing to file,
  975. string TFN = CFGData.paths_log_path; // build an appropriate log file
  976. TFN.append(CFGData.node_licenseid); // name.
  977. if(CFGData.Scan_Classic_Rotate) { // If we're rotating per day:
  978. TFN.append("."); // Put a timestamp on the file name.
  979. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  980. else { Timestamp(TFN); } // the utc timestamp as configured.
  981. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  982. }
  983. TFN.append(".log"); // Tack on the extension.
  984. ClassicScanLogger.post(ScanData.ClassicLogText, TFN); // Post the log with the file name.
  985. }
  986. }
  987. //// LogThisScan() is broken into two sections. The first section happens with
  988. //// the snfLOGmgr mutex locked and must happen as quickly as possible so that
  989. //// the chance for contention over those resources is minimized. This amounts
  990. //// to some raw CPU work adjusting counters and so forth.
  991. ////
  992. //// The second section handles any additional work such as formatting log
  993. //// entries. Essentially, anything that doesn't NEED to happen while the mutex
  994. //// is locked should happen in the second section.
  995. ////
  996. //// The two subroutines for LogThisScan are:
  997. //// captureLTSMetrics() -- Mutex locked, first section
  998. //// performLTSLogging() -- Mutex NOT locked, second section
  999. void snfLOGmgr::captureLTSMetrics(snfCFGData& CFGData, snfScanData& ScanData) { // LogThisScan section 1
  1000. ScopeMutex FreezeRightThereWhileITakeThisPicture(MyMutex); // Lock the object for this update.
  1001. if(Status.LatestRuleID < ScanData.PatternID) { // If we have a new latest rule id
  1002. Status.LatestRuleID = ScanData.PatternID; // then capture it.
  1003. }
  1004. // keep histograms---
  1005. // Second, Minute, and Hour histograms are reset() by the appropriate
  1006. // reporting functions. That is, when a Second report is made, the Second
  1007. // histograms are reset; likewise Minutes and Hours. As a result we simply
  1008. // hit them all the same way when we log a scan.
  1009. ResultsSecond.hit(ScanData.CompositeFinalResult); // Histogram the result codes.
  1010. ResultsMinute.hit(ScanData.CompositeFinalResult);
  1011. ResultsHour.hit(ScanData.CompositeFinalResult);
  1012. if(ScanData.PatternWasFound) { // Histogram pattern IDs.
  1013. RulesSecond.hit(ScanData.PatternID);
  1014. RulesMinute.hit(ScanData.PatternID);
  1015. RulesHour.hit(ScanData.PatternID);
  1016. }
  1017. if(0 < ScanData.RulePanics.size()) { // Histogram any rule panic hits.
  1018. set<int>::iterator iP;
  1019. for( // Dump the set of rule panic
  1020. iP = ScanData.RulePanics.begin(); // IDs from beginning to end
  1021. iP != ScanData.RulePanics.end(); // into our histogram set.
  1022. iP++) {
  1023. PanicsSecond.hit((*iP));
  1024. PanicsMinute.hit((*iP));
  1025. PanicsHour.hit((*iP));
  1026. }
  1027. }
  1028. // count up these things---
  1029. ++(*CurrentCounters).Events.Scans; // Number of messages scanned.
  1030. const int HamResult = 0; // A result of 0 is "clean" or "white"
  1031. if( // If we have identified Ham
  1032. HamResult == ScanData.CompositeFinalResult || // either by the conventional result or
  1033. CFGData.TrainingWhiteRuleHandler.isListed(ScanData.CompositeFinalResult) // some known white-rule symbol
  1034. ) {
  1035. ++(*CurrentCounters).Events.Ham; // then we will bump the Ham counter.
  1036. } else { // For any other result we will bump
  1037. ++(*CurrentCounters).Events.Spam; // the spam counter.
  1038. }
  1039. if(ScanData.GBUdbNormalTriggered) { // Count of GBUdb indetermineta IPs.
  1040. ++(*CurrentCounters).Events.GBUdbNormalTriggered;
  1041. }
  1042. if(ScanData.GBUdbWhiteTriggered) { // Count of GBUdb found source IP white.
  1043. ++(*CurrentCounters).Events.GBUdbWhiteTriggered;
  1044. }
  1045. if(ScanData.GBUdbWhiteSymbolForced) { // Count of white was on and symbol was set.
  1046. ++(*CurrentCounters).Events.GBUdbWhiteSymbolForced;
  1047. }
  1048. if(ScanData.GBUdbPatternSourceConflict) { // Count of pattern was found with white IP.
  1049. ++(*CurrentCounters).Events.GBUdbPatternSourceConflict;
  1050. }
  1051. if(ScanData.GBUdbAutoPanicTriggered) { // Count of autopanic was triggered.
  1052. ++(*CurrentCounters).Events.GBUdbAutoPanicTriggered;
  1053. }
  1054. if(ScanData.GBUdbAutoPanicExecuted) { // Count of an autopanic was added.
  1055. ++(*CurrentCounters).Events.GBUdbAutoPanicExecuted;
  1056. }
  1057. if(ScanData.GBUdbBlackTriggered) { // Count of GBUdb found source IP black.
  1058. ++(*CurrentCounters).Events.GBUdbBlackTriggered;
  1059. }
  1060. if(ScanData.GBUdbBlackSymbolForced) { // Count of black was on and symbol was set.
  1061. ++(*CurrentCounters).Events.GBUdbBlackSymbolForced;
  1062. }
  1063. if(ScanData.GBUdbTruncateTriggered) { // Count of Truncate was possible.
  1064. ++(*CurrentCounters).Events.GBUdbTruncateTriggered;
  1065. }
  1066. if(ScanData.GBUdbPeekTriggered) { // Count of we could peek.
  1067. ++(*CurrentCounters).Events.GBUdbPeekTriggered;
  1068. }
  1069. if(ScanData.GBUdbSampleTriggered) { // Count of we could sample.
  1070. ++(*CurrentCounters).Events.GBUdbSampleTriggered;
  1071. }
  1072. if(ScanData.GBUdbTruncateExecuted) { // Count of if we actually did truncate.
  1073. ++(*CurrentCounters).Events.GBUdbTruncateExecuted;
  1074. }
  1075. if(ScanData.GBUdbPeekExecuted) { // Count of we peeked instead of truncating.
  1076. ++(*CurrentCounters).Events.GBUdbPeekExecuted;
  1077. }
  1078. if(ScanData.GBUdbSampleExecuted) { // Count of we sampled.
  1079. ++(*CurrentCounters).Events.GBUdbSampleExecuted;
  1080. }
  1081. if(ScanData.GBUdbCautionTriggered) { // Count of GBUdb found source IP suspicous.
  1082. ++(*CurrentCounters).Events.GBUdbCautionTriggered;
  1083. }
  1084. if(ScanData.GBUdbCautionSymbolForced) { // Count of caution was on and symbol was set.
  1085. ++(*CurrentCounters).Events.GBUdbCautionSymbolForced;
  1086. }
  1087. if(ScanData.PatternWasFound) { // Count of scanner matches.
  1088. ++(*CurrentCounters).Events.PatternWasFound;
  1089. }
  1090. if(0 < ScanData.RulePanics.size()) { // Count of rule panics.
  1091. ++(*CurrentCounters).Events.RulePanicFound;
  1092. }
  1093. }
  1094. void snfLOGmgr::performLTSLogging(snfCFGData& CFGData, snfScanData& ScanData) { // LogThisScan section 2
  1095. // Build X- Headers, XML Log, and Classic Log as needed...
  1096. if(LogOutputMode_None != CFGData.XHDROutput_Mode) { // If XHeaders are turned on then
  1097. doXHDRs(CFGData, ScanData); // call the XHeaders subroutine.
  1098. }
  1099. if(LogOutputMode_None != CFGData.Scan_XML_Mode) { // If XML scan logs are turned on then
  1100. doXMLLogs(CFGData, ScanData); // call the XML scan log subroutine.
  1101. }
  1102. if(LogOutputMode_None != CFGData.Scan_Classic_Mode) { // If Classic scan logs are turned on
  1103. doClassicLogs(CFGData, ScanData); // then call the Classic log subroutine.
  1104. }
  1105. }
  1106. void snfLOGmgr::logThisScan(snfCFGData& CFGData, snfScanData& ScanData) { // How to log a scan event...
  1107. captureLTSMetrics(CFGData, ScanData); // Lock the mutex and do the math.
  1108. performLTSLogging(CFGData, ScanData); // Unlock the mutex and write it down.
  1109. if(0 < ScanData.XHDRsText.length()) { // If we have XHeader data then
  1110. switch(CFGData.XHDROutput_Mode) { // set the appropriate output mode.
  1111. case LogOutputMode_Inject: ScanData.XHeaderInjectOn = true; break; // We will either inject the headers
  1112. case LogOutputMode_File: ScanData.XHeaderFileOn = true; break; // or we will create a .xhdr file.
  1113. } // The actual inject/file operation
  1114. } // happens in ScanMessageFile().
  1115. ScanData.ReadyToClear = true; // This can be cleared now once
  1116. } // the ScanData has been consumed.
  1117. // logThisError(CFGData, ScanData) - for scanning errors (message context)
  1118. void snfLOGmgr::logThisError(snfScanData& ScanData, const string ContextName, // Inject an error log entry for this
  1119. const int Code, const string Text // scan using this number & message.
  1120. ) {
  1121. // Check for each type of log and create an appropriate entry for
  1122. // each log type that is activated in the configuration.
  1123. //// Handle XML Log Scan Error Reports
  1124. if(LogOutputMode_None != XML_Log_Mode) { // If XML logs are on emit the error.
  1125. // Produce Error Log Entry and store in XMLLogText
  1126. stringstream O; // Stringstream for formatting.
  1127. O << "<e " // Format the <s>can error element
  1128. << "u=\'" << Timestamp(ScanData.StartOfJobUTC) << "\' "
  1129. << "context=\'" << ContextName << "\' "
  1130. << "m=\'" << ScanData.ScanName << "\' "
  1131. << "code=\'" << Code << "\' "
  1132. << "text=\'" << Text << "\'"
  1133. << "/>"
  1134. << endl;
  1135. ScanData.XMLLogText = O.str(); // Save the formatted log text.
  1136. // Now that we've produced the appropriate log entries let's send them
  1137. // out to the log file.
  1138. if(LogOutputMode_File == XML_Log_Mode) { // If we are writing to file,
  1139. string TFN = LogsPath; // build an appropriate log file
  1140. TFN.append(NodeId); // name.
  1141. if(XMLLogRotate) { // If we're rotating per day:
  1142. TFN.append("."); // Put a timestamp on the file name.
  1143. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1144. else { Timestamp(TFN); } // the utc timestamp as configured.
  1145. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1146. }
  1147. TFN.append(".log.xml"); // Tack on the extension.
  1148. XMLScanLogger.post(ScanData.XMLLogText, TFN); // Post the log with the file name.
  1149. }
  1150. }
  1151. //// Handle Clasic Log Scan Error Reports
  1152. if(LogOutputMode_None != Classic_Log_Mode) { // If Classic logs are on emit the error.
  1153. // Produce an appropriate Error log entry in ClassicLogText
  1154. stringstream O; // Stringstream for formatting.
  1155. O << NodeId << "\t" // Format the scan error entry.
  1156. << Timestamp(ScanData.StartOfJobUTC) << "\t"
  1157. << ScanData.ScanName << "\t"
  1158. << ScanData.SetupTime << "\t"
  1159. << ScanData.ScanTime.getElapsedTime() << "\t"
  1160. << Text << "\t"
  1161. << "0\t"
  1162. << Code << "\t"
  1163. << "0\t"
  1164. << ScanData.ScanSize << "\t"
  1165. << ScanData.ScanDepth
  1166. << endl;
  1167. ScanData.ClassicLogText = O.str(); // Save the formatted log text.
  1168. // Now that we've produced the appropriate log entries let's send them
  1169. // out to the log file.
  1170. if(LogOutputMode_File == Classic_Log_Mode) { // If we are writing to file,
  1171. string TFN = LogsPath; // build an appropriate log file
  1172. TFN.append(NodeId); // name.
  1173. if(ClassicLogRotate) { // If we're rotating per day:
  1174. TFN.append("."); // Put a timestamp on the file name.
  1175. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1176. else { Timestamp(TFN); } // the utc timestamp as configured.
  1177. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1178. }
  1179. TFN.append(".log"); // Tack on the extension.
  1180. ClassicScanLogger.post(ScanData.ClassicLogText, TFN); // Post the log with the file name.
  1181. }
  1182. }
  1183. }
  1184. // logThisIPTest w/ Action
  1185. void snfLOGmgr::logThisIPTest(IPTestRecord& I, string Action) { // Log an IPTest and action.
  1186. if(!Configured) return; // Do nothing if not configured.
  1187. stringstream O; // Stringstream to format the entry.
  1188. string tmp; // String for use getting timestamp.
  1189. O << "<t "
  1190. << "u=\'" << Timestamp(tmp) << "\' "
  1191. << "ip=\'" << (string) I.IP << "\' "
  1192. << "t=\'" <<
  1193. ((Ugly == I.G.Flag())? "u" :
  1194. ((Good == I.G.Flag())? "g" :
  1195. ((Bad == I.G.Flag())? "b" : "i")))
  1196. << "\' "
  1197. << "g=\'" << I.G.Good() << "\' "
  1198. << "b=\'" << I.G.Bad() << "\' "
  1199. << "c=\'" << I.G.Confidence() << "\' "
  1200. << "p=\'" << I.G.Probability() << "\' "
  1201. << "r=\'" <<
  1202. ((Unknown == I.R)? "Unknown" :
  1203. ((White == I.R)? "White" :
  1204. ((Normal == I.R)? "Normal" :
  1205. ((New == I.R)? "New" :
  1206. ((Caution == I.R)? "Caution" :
  1207. ((Black == I.R)? "Black" :
  1208. ((Truncate == I.R)? "Truncate" :
  1209. "Fault")))))))
  1210. << "\' "
  1211. << "a=\'" << Action << "\'"
  1212. << "/>" << endl;
  1213. XMLScanLogger.post(O.str()); // Post the log, use existing path.
  1214. }
  1215. // logThisError(Context, Code, Text) - for non-message errors.
  1216. void snfLOGmgr::logThisError(string ContextName, int Code, string Text) { // Log an error message.
  1217. if(!Configured) return; // Do nothing if not configured.
  1218. ScopeMutex LockCFG(MyMutex); // Don't change CFG. I'm using it!
  1219. if(LogOutputMode_File == XML_Log_Mode) { // If XML logs are turned on:
  1220. stringstream O; // Stringstream to format the entry.
  1221. string tmp; // String for use getting timestamp.
  1222. O << "<e " // Format an <e/>rror element.
  1223. << "u=\'" << Timestamp(tmp) << "\' "
  1224. << "context=\'" << ContextName << "\' "
  1225. << "code=\'" << Code << "\' "
  1226. << "text=\'" << Text << "\'/>"
  1227. << endl;
  1228. // Now that we've produced the appropriate log entries let's send them
  1229. // out to the log file.
  1230. string TFN = LogsPath; // build an appropriate log file
  1231. TFN.append(NodeId); // name.
  1232. if(XMLLogRotate) { // If we're rotating per day:
  1233. TFN.append("."); // Put a timestamp on the file name.
  1234. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1235. else { Timestamp(TFN); } // the utc timestamp as configured.
  1236. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1237. }
  1238. TFN.append(".log.xml"); // Tack on the extension.
  1239. XMLScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1240. }
  1241. if(LogOutputMode_File == Classic_Log_Mode) { // If Classic logs are turned on:
  1242. stringstream O; // Stringstream to format the entry.
  1243. string tmp; // String for use getting timestamp.
  1244. O << NodeId << "\t" // Format the error entry.
  1245. << Timestamp(tmp) << "\t"
  1246. << ContextName << "\t"
  1247. << "0\t"
  1248. << "0\t"
  1249. << Text << "\t"
  1250. << "0\t"
  1251. << Code << "\t"
  1252. << "0\t"
  1253. << "0\t"
  1254. << "0\t"
  1255. << endl;
  1256. // Now that we've produced the appropriate log entries let's send them
  1257. // out to the log file.
  1258. string TFN = LogsPath; // build an appropriate log file
  1259. TFN.append(NodeId); // name.
  1260. if(ClassicLogRotate) { // If we're rotating per day:
  1261. TFN.append("."); // Put a timestamp on the file name.
  1262. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1263. else { Timestamp(TFN); } // the utc timestamp as configured.
  1264. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1265. }
  1266. TFN.append(".log"); // Tack on the extension.
  1267. ClassicScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1268. }
  1269. }
  1270. // logThisInfo(Context, Code, Text) - for generic non-errors.
  1271. void snfLOGmgr::logThisInfo(string ContextName, int Code, string Text) { // Log an informational message.
  1272. if(!Configured) return; // Do nothing if not configured.
  1273. ScopeMutex LockCFG(MyMutex); // Don't change CFG. I'm using it!
  1274. if(LogOutputMode_File == XML_Log_Mode) { // If XML logs are turned on:
  1275. stringstream O; // Stringstream to format the entry.
  1276. string tmp; // String for use getting timestamp.
  1277. O << "<i " // Format an <i/>nfo element.
  1278. << "u=\'" << Timestamp(tmp) << "\' "
  1279. << "context=\'" << ContextName << "\' "
  1280. << "code=\'" << Code << "\' "
  1281. << "text=\'" << Text << "\'/>"
  1282. << endl;
  1283. // Now that we've produced the appropriate log entries let's send them
  1284. // out to the log file.
  1285. string TFN = LogsPath; // build an appropriate log file
  1286. TFN.append(NodeId); // name.
  1287. if(XMLLogRotate) { // If we're rotating per day:
  1288. TFN.append("."); // Put a timestamp on the file name.
  1289. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1290. else { Timestamp(TFN); } // the utc timestamp as configured.
  1291. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1292. }
  1293. TFN.append(".log.xml"); // Tack on the extension.
  1294. XMLScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1295. }
  1296. if(LogOutputMode_File == Classic_Log_Mode) { // If Classic logs are turned on:
  1297. stringstream O; // Stringstream to format the entry.
  1298. string tmp; // String for use getting timestamp.
  1299. O << NodeId << "\t" // Format the informational entry.
  1300. << Timestamp(tmp) << "\t"
  1301. << ContextName << "\t"
  1302. << "0\t"
  1303. << "0\t"
  1304. << Text << "\t"
  1305. << "0\t"
  1306. << Code << "\t"
  1307. << "0\t"
  1308. << "0\t"
  1309. << "0\t"
  1310. << endl;
  1311. // Now that we've produced the appropriate log entries let's send them
  1312. // out to the log file.
  1313. string TFN = LogsPath; // build an appropriate log file
  1314. TFN.append(NodeId); // name.
  1315. if(ClassicLogRotate) { // If we're rotating per day:
  1316. TFN.append("."); // Put a timestamp on the file name.
  1317. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1318. else { Timestamp(TFN); } // the utc timestamp as configured.
  1319. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1320. }
  1321. TFN.append(".log"); // Tack on the extension.
  1322. ClassicScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1323. }
  1324. }
  1325. string snfLOGmgr::PlatformVersion(string NewPlatformVersion) { // Set platform version info.
  1326. ScopeMutex FreezeForNewData(MyMutex); // Get the ball and
  1327. myPlatformVersion = NewPlatformVersion; // set the data.
  1328. return myPlatformVersion; // return the new data.
  1329. }
  1330. string snfLOGmgr::PlatformVersion() { // Get platform version info.
  1331. ScopeMutex DontChangeOnMe(MyMutex); // Get the ball and
  1332. return myPlatformVersion; // get the data.
  1333. }
  1334. string snfLOGmgr::EngineVersion() { // Get engine version info.
  1335. return string(SNF_ENGINE_VERSION); // Return the engine version string.
  1336. }
  1337. //// The caller to getSpamshot promises to reset() the counters when it is done
  1338. //// with the data and before getSnapshot() gets called again.
  1339. snfCounterPack* snfLOGmgr::getSnapshot() { // Get a copy of the current counters.
  1340. snfCounterPack* Snapshot = CurrentCounters; // Grab the active counters.
  1341. CurrentCounters = ReportingCounters; // Swap the reporting counters in.
  1342. CurrentCounters->ActiveTime.start(Snapshot->ActiveTime.stop()); // (De)Activate the activity timers.
  1343. ReportingCounters = Snapshot; // Put the old ActiveCounters into
  1344. return Snapshot; // reporting mode and return a ptr.
  1345. }
  1346. bool snfLOGmgr::OkToPeek(int PeekOneInX) { // Test to see if it's ok to peek.
  1347. ScopeMutex JustMe(PeekMutex); // Protect the peek enable counter.
  1348. ++PeekEnableCounter; // Bump the counter by one.
  1349. if(PeekEnableCounter >= PeekOneInX) { // If we've made the threshold then
  1350. PeekEnableCounter = 0; // reset the counter and
  1351. return true; // return true.
  1352. } // If not then
  1353. return false; // return false.
  1354. }
  1355. bool snfLOGmgr::OkToSample(int SampleOneInX) { // Test to see if it's ok to sample.
  1356. ScopeMutex JustMe(SampleMutex); // Protect the sample enable counter.
  1357. ++SampleEnableCounter; // Bump the counter by one.
  1358. if(SampleEnableCounter >= SampleOneInX) { // If we've made the threshold then
  1359. SampleEnableCounter = 0; // reset the counter and
  1360. return true; // return true.
  1361. } // If not then return
  1362. return false; // false.
  1363. }
  1364. time_t snfLOGmgr::Timestamp() { // Get an ordinary timestamp.
  1365. time_t rawtime;
  1366. rawtime = time(NULL);
  1367. return rawtime;
  1368. }
  1369. string snfLOGmgr::Timestamp(time_t t) { // Convert time_t to a timestamp s.
  1370. stringstream TimestampBfr;
  1371. const string EmptyTimestamp = "00000000000000";
  1372. string theTimeStamp = EmptyTimestamp;
  1373. tm* gmt; // Get a ptr to a tm structure.
  1374. gmt = gmtime(&t); // Fill it with UTC.
  1375. bool isValidGMT = (0 != gmt);
  1376. if(isValidGMT) {
  1377. TimestampBfr
  1378. << setw(4) << (gmt->tm_year+1900)
  1379. << setw(2) << setfill('0') << (gmt->tm_mon+1)
  1380. << setw(2) << setfill('0') << (gmt->tm_mday)
  1381. << setw(2) << setfill('0') << (gmt->tm_hour)
  1382. << setw(2) << setfill('0') << (gmt->tm_min)
  1383. << setw(2) << setfill('0') << (gmt->tm_sec)
  1384. ;
  1385. theTimeStamp = TimestampBfr.str();
  1386. }
  1387. return theTimeStamp; // Return a string.
  1388. }
  1389. string& snfLOGmgr::Timestamp(string& s) { // Returns a current timestamp in s.
  1390. s.append(Timestamp(Timestamp())); // Append the timestamp to s and
  1391. return s; // return it.
  1392. }
  1393. string snfLOGmgr::LocalTimestamp(time_t t) { // Convert time_t to a local timestamp s.
  1394. char TimestampBfr[20]; // Create a small buffer.
  1395. tm* localt; // Get a ptr to a tm structure.
  1396. localt = localtime(&t); // Fill it with local time.
  1397. sprintf(TimestampBfr,"%04d%02d%02d%02d%02d%02d", // Format yyyymmddhhmmss
  1398. localt->tm_year+1900,
  1399. localt->tm_mon+1,
  1400. localt->tm_mday,
  1401. localt->tm_hour,
  1402. localt->tm_min,
  1403. localt->tm_sec
  1404. );
  1405. return string(TimestampBfr); // Return a string.
  1406. }
  1407. string& snfLOGmgr::LocalTimestamp(string& s) { // Returns a local timestamp in s.
  1408. s.append(LocalTimestamp(Timestamp())); // Append the timestamp to s and
  1409. return s; // return it.
  1410. }
  1411. unsigned int snfLOGmgr::SerialNumber() { // Returns the next serial number.
  1412. ScopeMutex AtomicOperation(SerialNumberMutex); // Lock the serial number mutex.
  1413. ++Status.SerialNumberCounter; // Increment the serial number.
  1414. unsigned int result = Status.SerialNumberCounter; // Capture the new value.
  1415. return result; // Return the unique result.
  1416. }
  1417. string& snfLOGmgr::SerialNumber(string& s) { // Appends the next serial number.
  1418. char SerialNumberBuffer[9]; // 8 hex digits and a null terminator.
  1419. sprintf( // Format the serial number and
  1420. SerialNumberBuffer, // place it into the buffer.
  1421. "%08X", SerialNumber()
  1422. );
  1423. s.append(SerialNumberBuffer); // Append the buffer to s.
  1424. return s; // Return s.
  1425. }
  1426. // Persistent State Functions
  1427. // The Persistent State object is slightly smart. It won't try to restore
  1428. // itself from disk if it has already been restored. It won't write itself
  1429. // to disk unless it was first loaded or there was no original file to load.
  1430. // This leaves open the possibility that a disk problem when opening the
  1431. // engine could cause a persistent state problem - but the alternative is to
  1432. // have the persistent state unprotected. If there is a problem, then clearing
  1433. // the problem and re-opening the engine will load the persistent state. If
  1434. // that's not the best solution then it's always possible to destroy the
  1435. // existing persistent state and start over -- at least then it will be a
  1436. // conscious decision and not a "side effect"
  1437. void snfLOGPersistentState::store(string& FileNameToStore) { // Write the whole thing to a file.
  1438. if(Ready) { // If it is safe to overwrite then
  1439. try { // Try... to
  1440. ofstream P(FileNameToStore.c_str(), ios::trunc | ios::binary); // Open and overwrite the file and
  1441. P.write((char*)this, sizeof(snfLOGPersistentState)); // store our bytes in binary format.
  1442. P.close();
  1443. } catch (...) {} // Ignore any errors for now.
  1444. }
  1445. }
  1446. void snfLOGPersistentState::restore(string& FileNameToRestore) { // Read the whole thing from a file.
  1447. if(!Ready) { // If we have not already loaded...
  1448. if(0 > access(FileNameToRestore.c_str(), R_OK)) { // If the file cannot be read we
  1449. Ready = true; // will assume it doesn't exist and
  1450. } // set our Ready flag to allow writing.
  1451. else { // If the file does exist we load it.
  1452. try { // Try this...
  1453. ifstream P(FileNameToRestore.c_str(), ios::binary); // Create a binary input stream and
  1454. P.read((char*)this, sizeof(snfLOGPersistentState)); // read the bytes into this object.
  1455. P.close(); // Then, close the file.
  1456. Ready = true; // Set the Ready flag to allow writes.
  1457. } catch(...) {} // Ignore any errors for now.
  1458. }
  1459. }
  1460. }
  1461. // 20090730_M - Moved persistent state aux saves to RecordSyncEvent. It makes
  1462. // sense for the persistent state to match the latext external record of state
  1463. // info. If SNFServer dies uncerimoneusly that is what we will remember.
  1464. int snfLOGmgr::SecsSinceStartup() {
  1465. return (int) difftime(Timestamp(), StartupTime);
  1466. }
  1467. void snfLOGmgr::RecordSyncEvent() { // Sets timestamp of latest Sync.
  1468. Status.LastSyncTime = Timestamp(); // Set the Sync time.
  1469. if(Configured) Status.store(PersistentFileName); // Store our persistent data.
  1470. }
  1471. int snfLOGmgr::SecsSinceLastSync() { // Gets seconds since latest Sync.
  1472. return (int) difftime(Timestamp(), Status.LastSyncTime);
  1473. }
  1474. void snfLOGmgr::RecordSaveEvent() { // Sets timestamp of latest Save.
  1475. Status.LastSaveTime = Timestamp();
  1476. }
  1477. int snfLOGmgr::SecsSinceLastSave() { // Gets seconds since latest Save.
  1478. return (int) difftime(Timestamp(), Status.LastSaveTime);
  1479. }
  1480. void snfLOGmgr::RecordCondenseEvent() { // Sets timestamp of latest Condense.
  1481. Status.LastCondenseTime = Timestamp();
  1482. }
  1483. int snfLOGmgr::SecsSinceLastCondense() { // Gets seconds since latest Condense.
  1484. return (int) difftime(Timestamp(), Status.LastCondenseTime);
  1485. }
  1486. // Data in the multi-range sliding window is tracked in circular buffers.
  1487. // The snf_SMHDMY_Counter::do_input() function encapsuates the input operation.
  1488. bool snf_SMHDMY_Counter::do_input( // Subroutine for new data input.
  1489. int X, // Given new data X,
  1490. int& SUM, // the SUM being tracked,
  1491. int* DATA, // the array of DATA,
  1492. int& ORDINAL, // the current ORDINAL,
  1493. int SIZE) { // and the SIZE of the array...
  1494. SUM -= DATA[ORDINAL]; // Subtract the old data from the
  1495. SUM += (DATA[ORDINAL] = X); // SUM and replace it with X.
  1496. ++ORDINAL; // Move to the next slot and
  1497. if(SIZE <= ORDINAL) ORDINAL = 0; // rotate back around if needed.
  1498. return (0 == ORDINAL); // Return true if time to carry.
  1499. }
  1500. void snf_SMHDMY_Counter::input(int X) {
  1501. if(do_input(X, SEC6SUM, SEC6DATA, SEC6ORDINAL, 6)) // 6 second sum
  1502. if(do_input(SEC6SUM, SEC10SUM, SEC10DATA, SEC10ORDINAL, 10)) // 60 second sum
  1503. if(do_input(SEC10SUM, MIN6SUM, MIN6DATA, MIN6ORDINAL, 6)) // 6 minute sum
  1504. if(do_input(MIN6SUM, MIN10SUM, MIN10DATA, MIN10ORDINAL, 10)) // 60 minute sum
  1505. if(do_input(MIN10SUM, HOUR4SUM, HOUR4DATA, HOUR4ORDINAL, 4)) // 4 hour sum
  1506. if(do_input(HOUR4SUM, HOUR6SUM, HOUR6DATA, HOUR6ORDINAL, 6)) { // 24 hour sum
  1507. do_input(HOUR6SUM, WEEK7SUM, WEEK7DATA, WEEK7ORDINAL, 7); // 7 day sum
  1508. do_input(HOUR6SUM, YEAR365SUM, YEAR365DATA, YEAR365ORDINAL, 365); // 365 day sum
  1509. if(do_input(HOUR6SUM, MONTH5SUM, MONTH5DATA, MONTH5ORDINAL, 5)) // 5 day sum
  1510. if(do_input(MONTH5SUM, MONTH6SUM, MONTH6DATA, MONTH6ORDINAL, 6)) // 30 day sum
  1511. if(do_input(MONTH6SUM, YEAR3SUM, YEAR3DATA, YEAR3ORDINAL, 3)) // 3 month sum
  1512. do_input(YEAR3SUM, YEAR4SUM, YEAR4DATA, YEAR4ORDINAL, 4); // 12 month sum
  1513. }
  1514. }
  1515. double snf_SMHDMY_AveragePerMinute( // Get mornalized minute avg of X
  1516. snf_SMHDMY_Counter& X, // Input the Units in the period.
  1517. snf_SMHDMY_Counter& M) { // Input the Milliseconds in the period.
  1518. int Units = X.SEC6SUM + X.SEC10SUM; // Get the count.
  1519. int Milliseconds = M.SEC6SUM + M.SEC10SUM; // Get the time.
  1520. return snf_rationalize(Units, Milliseconds, MillisecondsInAMinute); // Normalize to a minute.
  1521. }
  1522. double snfLOGmgr::MessagesPerMinute() { // Avg Msgs/Minute.
  1523. return snf_SMHDMY_AveragePerMinute(MessageCounter, TimeCounter);
  1524. }
  1525. double snfLOGmgr::HamPerMinute() { // Avg Ham/Minute.
  1526. return snf_SMHDMY_AveragePerMinute(HamCounter, TimeCounter);
  1527. }
  1528. double snfLOGmgr::SpamPerMinute() { // Avg Spam/Minute.
  1529. return snf_SMHDMY_AveragePerMinute(SpamCounter, TimeCounter);
  1530. }
  1531. double snfLOGmgr::WhitePerMinute() { // Avg White/Minute.
  1532. return snf_SMHDMY_AveragePerMinute(WhiteCounter, TimeCounter);
  1533. }
  1534. double snfLOGmgr::CautionPerMinute() { // Avg Caution/Minute.
  1535. return snf_SMHDMY_AveragePerMinute(CautionCounter, TimeCounter);
  1536. }
  1537. double snfLOGmgr::BlackPerMinute() { // Avg Black/Minute.
  1538. return snf_SMHDMY_AveragePerMinute(BlackCounter, TimeCounter);
  1539. }
  1540. double snfLOGmgr::TruncatePerMinute() { // Avg Truncate/Minute.
  1541. return snf_SMHDMY_AveragePerMinute(TruncateCounter, TimeCounter);
  1542. }
  1543. double snfLOGmgr::SamplePerMinute() { // Avg Sample/Minute.
  1544. return snf_SMHDMY_AveragePerMinute(SampleCounter, TimeCounter);
  1545. }
  1546. const string EmptyStatusSecondReport = "<stats class=\'second\'/>"; // Empty Status.Second looks like this.
  1547. string snfLOGmgr::getStatusSecondReport() { // Get latest status.second report.
  1548. ScopeMutex FlashBulb(StatusReportMutex); // Take a safe snapshot of the report.
  1549. if(0 < SecondReportText.length()) return SecondReportText; // If it's posted then send it. If not
  1550. return EmptyStatusSecondReport; // then send the empty version.
  1551. }
  1552. const string EmptyStatusMinuteReport = "<stats class=\'minute\'/>"; // Empty Status.Minute looks like this.
  1553. string snfLOGmgr::getStatusMinuteReport() { // Get latest status.minute report.
  1554. ScopeMutex FlashBulb(StatusReportMutex); // Take a safe snapshot of the report.
  1555. if(0 < MinuteReportText.length()) return MinuteReportText; // If it's posted then send it. If not
  1556. return EmptyStatusMinuteReport; // then send the empty version.
  1557. }
  1558. const string EmptyStatusHourReport = "<stats class=\'hour\'/>"; // Empty Status.Hour looks like this.
  1559. string snfLOGmgr::getStatusHourReport() { // Get latest status.hour report.
  1560. ScopeMutex FlashBulb(StatusReportMutex); // Take a safe snapshot of the report.
  1561. if(0 < HourReportText.length()) return HourReportText; // If it's posted then send it. If not
  1562. return EmptyStatusHourReport; // then send the empty version.
  1563. }