Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

snfLOGmgr.cpp 107KB

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