You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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