Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

snfLOGmgr.cpp 106KB

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