您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

snfLOGmgr.cpp 106KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  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 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. 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. Status.store(PersistentFileName); // Store our persistent data.
  663. }
  664. WaitATic();
  665. }
  666. }
  667. // Note about snfLOGmgr::configure() and Status.restore()
  668. // store() and restore() watch the Status.Ready flag. If
  669. // Status is ready, restore() won't. If Status is not ready
  670. // store() won't. Also, if restore() doesn't find a file, it
  671. // just clears everything and goes ready, assuming that this
  672. // is a new persistent state.
  673. void snfLOGmgr::configure(snfCFGData& CFGData) { // Update the configuration.
  674. ScopeMutex HoldOnWhileITweakThisThing(ConfigMutex);
  675. PersistentFileName = CFGData.paths_workspace_path + ".state"; // Build the persistent state path.
  676. Status.restore(PersistentFileName); // Load our persistent state.
  677. NodeId = CFGData.node_licenseid; // Grab the node id for reports.
  678. // Copy the logging configuration info from CFGData
  679. Rotate_LocalTime = CFGData.Logs_Rotation_LocalTime_OnOff; // Rotate using local time?
  680. XML_Log_Mode = CFGData.Scan_XML_Mode; // What is the XML log mode.
  681. Classic_Log_Mode = CFGData.Scan_Classic_Mode; // What is the Classic log mode.
  682. LogsPath = CFGData.paths_log_path; // Path to logs directory.
  683. ClassicLogRotate = CFGData.Scan_Classic_Rotate; // True = Rotate Classic Log.
  684. XMLLogRotate = CFGData.Scan_XML_Rotate; // True = Rotate XML Log.
  685. SecondReport_Log_OnOff = CFGData.Status_SecondReport_Log_OnOff;
  686. SecondReport_Append_OnOff = CFGData.Status_SecondReport_Append_OnOff;
  687. SecondReport_Log_Filename = CFGData.paths_log_path + NodeId + ".status.second";
  688. MinuteReport_Log_OnOff = CFGData.Status_MinuteReport_Log_OnOff;
  689. MinuteReport_Append_OnOff = CFGData.Status_MinuteReport_Append_OnOff;
  690. MinuteReport_Log_Filename = CFGData.paths_log_path + NodeId + ".status.minute";
  691. HourReport_Log_OnOff = CFGData.Status_HourReport_Log_OnOff;
  692. HourReport_Append_OnOff = CFGData.Status_HourReport_Append_OnOff;
  693. HourReport_Log_Filename = CFGData.paths_log_path + NodeId + ".status.hour";
  694. // Sanity check
  695. if(NULL != myNETmgr && NULL != myGBUdb) { // If we are fully linked then
  696. Configured = true; // we are now configured.
  697. }
  698. }
  699. void snfLOGmgr::doXHDRs(snfCFGData& CFGData, snfScanData& ScanData) { // XHDR sub routine for LogThisScan()
  700. ostringstream O; // Setup the output stream.
  701. const string SMTPENDL = "\r\n"; // Make a hard-coded SMTP endline.
  702. // Version header
  703. if(CFGData.XHDRVersion_OnOff) { // If the Version XHDR is on then
  704. O << CFGData.XHDRVersion_Header << ": " // emit the Version XHDR.
  705. << SMTPENDL << "\t" << SNF_ENGINE_VERSION;
  706. if(0 < myPlatformVersion.length()) { // Optional Platform Version.
  707. O << SMTPENDL << "\t" << myPlatformVersion;
  708. }
  709. O << SMTPENDL;
  710. }
  711. // License header
  712. if(CFGData.XHDRLicense_OnOff) { // If the license XHDR is on then
  713. O << CFGData.XHDRLicense_Header << ": " // emit the License XHRD.
  714. << CFGData.node_licenseid
  715. << SMTPENDL;
  716. }
  717. // Rulebase header
  718. if(CFGData.XHDRRulebase_OnOff) { // If the rulebase utc XHDR is on
  719. string RBUTC; // then make a string to capture it
  720. O << CFGData.XHDRRulebase_Header << ": " // then emit the rulebase utc XHDR.
  721. << (*myNETmgr).RulebaseUTC(RBUTC)
  722. << SMTPENDL;
  723. }
  724. // Identifier header
  725. if(CFGData.XHDRIdentifier_OnOff) { // If the identifier XHDR is on
  726. O << CFGData.XHDRIdentifier_Header << ": " // then emit the scan identifier.
  727. << ScanData.ScanName
  728. << SMTPENDL;
  729. }
  730. // GBUdb header
  731. if(CFGData.XHDRGBUdb_OnOff) { // If the GBUdb XHDR is on then
  732. O << CFGData.XHDRGBUdb_Header << ": "; // then emit the GBUdb XHDR.
  733. if(!ScanData.FoundSourceIP()) { // If no source was identified
  734. O << "Unknown" // then we emit "Unknown".
  735. << SMTPENDL;
  736. } else { // If the source was identified
  737. O << ScanData.SourceIPRecord().Ordinal << ", " // then we emit the ordial,
  738. << (string) IP4Address(ScanData.SourceIPRecord().IP) << ", " // the IP, and then
  739. << ScanData.SourceIPEvaluation // the IP evaluation that was
  740. << SMTPENDL; // sent to the scanner.
  741. }
  742. }
  743. // Result header
  744. if(CFGData.XHDRResult_OnOff) { // If the Result XHDR is on then
  745. O << CFGData.XHDRResult_Header << ": " // emit the scan result code XHDR.
  746. << ScanData.CompositeFinalResult
  747. << SMTPENDL;
  748. }
  749. // Matches header
  750. if(CFGData.XHDRMatches_OnOff) { // If the Matches XHDR is on then
  751. O << CFGData.XHDRMatches_Header << ":" << SMTPENDL; // emit the Matches XHDR with matches.
  752. for(
  753. list<snf_match>::iterator iM = ScanData.MatchRecords.begin(); // Loop through the match list
  754. iM != ScanData.MatchRecords.end(); iM++ // one by one.
  755. ) {
  756. snf_match& M = (*iM); // Emit each match record as a
  757. O << "\t" // folded entry in the header.
  758. << M.symbol << "-" // symbol-ruleid-index-endex-flag
  759. << M.ruleid << "-"
  760. << M.index << "-"
  761. << M.endex << "-"
  762. << M.flag
  763. << SMTPENDL;
  764. }
  765. }
  766. // Black header
  767. if( // If the Black XHDR is on and
  768. CFGData.XHDRBlack_OnOff && // We have a nonzero result
  769. 0 < ScanData.CompositeFinalResult && // that is not found in the training
  770. !CFGData.TrainingWhiteRuleHandler.isListed( // white list then...
  771. ScanData.CompositeFinalResult)
  772. ) {
  773. O << CFGData.XHDRBlack_Header // Emit the Black XHDR.
  774. << SMTPENDL;
  775. }
  776. // White header
  777. if( // If the White XHDR is on and
  778. CFGData.XHDRWhite_OnOff && // the result was listed in the
  779. CFGData.TrainingWhiteRuleHandler.isListed( // training white list then...
  780. ScanData.CompositeFinalResult)
  781. ) {
  782. O << CFGData.XHDRWhite_Header // Emit the White XHDR.
  783. << SMTPENDL;
  784. }
  785. // Clean header
  786. if(
  787. CFGData.XHDRClean_OnOff && // If the Clean XHDR is on and
  788. !ScanData.PatternWasFound && // no pattern was found and
  789. 0 == ScanData.CompositeFinalResult // the scan result is zero then...
  790. ) {
  791. O << CFGData.XHDRClean_Header // Emit the Clean XHDR
  792. << SMTPENDL;
  793. }
  794. // Symbol headers
  795. string SH = CFGData.XHDRSymbolHeaders.HeaderForSymbol( // Check for a Symbol XHDR
  796. ScanData.CompositeFinalResult // matching this result.
  797. );
  798. if(0 < SH.length()) { // If we have an XHDR for this
  799. O << SH // result then emit the header.
  800. << SMTPENDL;
  801. }
  802. ScanData.XHDRsText = O.str(); // Save the formatted XHeaders.
  803. }
  804. void snfLOGmgr::doXMLLogs(snfCFGData& CFGData, snfScanData& ScanData) { // XML sub routine for LogThisScan()
  805. ostringstream O; // Set up the output stream.
  806. bool WeHaveSubordinates = false; // Expect no subordinates at first.
  807. // We do the match sections together because it allows us to scan through
  808. // the match results once and pick up the final result for the <s/> section.
  809. // This way, even if no <m/>atch elements are emitted we will have the
  810. // final result without having to scan the data twice.
  811. // <s/> -- Scan Log Entry (always on if modes is not none)
  812. // <m/> -- Scan Match Entry (controlled by matches attribute)
  813. ostringstream R; // Match (R)ecords output.
  814. set<int> Duplicates; // Set up to track duplicates.
  815. list<snf_match>::iterator MatchRecordsCursor; // Set up a cursor to the results.
  816. for(
  817. MatchRecordsCursor = ScanData.MatchRecords.begin(); // Loop through the scan results
  818. MatchRecordsCursor != ScanData.MatchRecords.end();
  819. MatchRecordsCursor++
  820. ) {
  821. snf_match& M = (*MatchRecordsCursor); // Grab the current match record.
  822. if(
  823. ScanLogMatches_None != CFGData.Scan_XML_Matches && // If match records are requested
  824. ('f' != M.flag && 'c' != M.flag) // and this record is not the (f)inal
  825. ) { // then evaluate it and log (??) it.
  826. if(ScanLogMatches_Unique == CFGData.Scan_Classic_Matches) { // If only unique matches are required
  827. if(Duplicates.end() != Duplicates.find(M.ruleid)) { // check for a duplicate rule id.
  828. continue; // If the rule id was found then skip.
  829. } else { // If the rule id was not found then
  830. Duplicates.insert(M.ruleid); // remember it for next time.
  831. }
  832. }
  833. // At this point we've skipped duplicate match records, but we
  834. // still want to emit some (all?) of them so it's time to do it.
  835. // <m s='48' r='1234567' i='2394' e='2409' f='m'/>
  836. R << "\t<m "
  837. << "s=\'" << M.symbol << "\' "
  838. << "r=\'" << M.ruleid << "\' "
  839. << "i=\'" << M.index << "\' "
  840. << "e=\'" << M.endex << "\' "
  841. << "f=\'" << M.flag << "\'/>"
  842. << endl;
  843. } else
  844. if('f' == M.flag || 'c' == M.flag) { // If this record is final, emit it!
  845. WeHaveSubordinates = (
  846. ((ScanLogMatches_None != CFGData.Scan_XML_Matches)
  847. && ('f' == M.flag)) ||
  848. (true == CFGData.Scan_XML_GBUdb) ||
  849. (true == CFGData.Scan_XML_Performance)
  850. );
  851. // <s u='20070508012349' m='msg0123456789.msg' s='48' r='1234567' >
  852. O << "<s " // Format the <s>can element
  853. << "u=\'" << Timestamp(ScanData.StartOfJobUTC) << "\' "
  854. << "m=\'" << ScanData.ScanName << "\' "
  855. << "s=\'" << M.symbol << "\' "
  856. << "r=\'" << M.ruleid << "\'"
  857. << ((WeHaveSubordinates)? ">" : "/>")
  858. << endl;
  859. }
  860. }
  861. if(ScanLogMatches_None != CFGData.Scan_XML_Matches) O << R.str(); // Emit the match records if any.
  862. // <p/> -- Scan Performance Monitoring (performance='yes')
  863. // <p s='10' t='8' l='3294' d='84'/>
  864. if(CFGData.Scan_XML_Performance) { // Post performance data if needed.
  865. O << "\t<p "
  866. << "s=\'" << ScanData.SetupTime << "\' "
  867. << "t=\'" << ScanData.ScanTime.getElapsedTime() << "\' "
  868. << "l=\'" << ScanData.ScanSize << "\' "
  869. << "d=\'" << ScanData.ScanDepth << "\'/>"
  870. << endl;
  871. }
  872. // <g/> -- GBUdb Activity For This Scan (gbudb='yes')
  873. // <g o='1' i='101.201.31.04' t='u' c='0.12345' p='0.3342983' r='Caution'/>
  874. if(CFGData.Scan_XML_GBUdb && ScanData.FoundSourceIP()) { // Post gbudb data if needed & ready.
  875. O << "\t<g "
  876. << "o=\'" << ScanData.SourceIPRecord().Ordinal << "\' "
  877. << "i=\'" << (string) IP4Address(ScanData.SourceIPRecord().IP) << "\' "
  878. << "t=\'" <<
  879. ((Ugly == ScanData.SourceIPRecord().GBUdbData.Flag())? "u" :
  880. ((Good == ScanData.SourceIPRecord().GBUdbData.Flag())? "g" :
  881. ((Bad == ScanData.SourceIPRecord().GBUdbData.Flag())? "b" : "i")))
  882. << "\' "
  883. << "c=\'" << ScanData.SourceIPRecord().GBUdbData.Confidence() << "\' "
  884. << "p=\'" << ScanData.SourceIPRecord().GBUdbData.Probability() << "\' "
  885. << "r=\'" <<
  886. ((Unknown == ScanData.SourceIPRange())? "Unknown" :
  887. ((White == ScanData.SourceIPRange())? "White" :
  888. ((Normal == ScanData.SourceIPRange())? "Normal" :
  889. ((New == ScanData.SourceIPRange())? "New" :
  890. ((Caution == ScanData.SourceIPRange())? "Caution" :
  891. ((Black == ScanData.SourceIPRange())? "Black" :
  892. ((Truncate == ScanData.SourceIPRange())? "Truncate" :
  893. "Fault")))))))
  894. << "\'/>"
  895. << endl;
  896. }
  897. // If this wasn't a one-liner then we need to close the <s/> element
  898. if(WeHaveSubordinates) O << "</s>" << endl; // If <s> was open then close it.
  899. ScanData.XMLLogText = O.str(); // Save the formatted log text.
  900. // Now that we've produced the appropriate log entries let's send them
  901. // out to the log file.
  902. if(LogOutputMode_File == CFGData.Scan_XML_Mode) { // If we are writing to file,
  903. string TFN = CFGData.paths_log_path; // build an appropriate log file
  904. TFN.append(CFGData.node_licenseid); // name.
  905. if(CFGData.Scan_XML_Rotate) { // If we're rotating per day:
  906. TFN.append("."); // Put a timestamp on the file name.
  907. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  908. else { Timestamp(TFN); } // the utc timestamp as configured.
  909. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  910. }
  911. TFN.append(".log.xml"); // Tack on the extension.
  912. XMLScanLogger.post(ScanData.XMLLogText, TFN); // Post the log with the file name.
  913. }
  914. }
  915. void snfLOGmgr::doClassicLogs(snfCFGData& CFGData, snfScanData& ScanData) { // Classic sub routine for LogThisScan()
  916. ostringstream O; // Set up the output stream.
  917. set<int> Duplicates; // Set up to track duplicates.
  918. list<snf_match>::iterator MatchRecordsCursor; // Set up a cursor to the results.
  919. for(
  920. MatchRecordsCursor = ScanData.MatchRecords.begin(); // Loop through the scan results
  921. MatchRecordsCursor != ScanData.MatchRecords.end();
  922. MatchRecordsCursor++
  923. ) {
  924. snf_match& M = (*MatchRecordsCursor); // Grab the current match record.
  925. if(
  926. ScanLogMatches_None != CFGData.Scan_Classic_Matches && // If match records are requested
  927. ('f' != M.flag && 'c' != M.flag) // and this record is not the (f)inal
  928. ) { // then evaluate it and log (??) it.
  929. if(ScanLogMatches_Unique == CFGData.Scan_Classic_Matches) { // If only unique matches are required
  930. if(Duplicates.end() != Duplicates.find(M.ruleid)) { // check for a duplicate rule id.
  931. continue; // If the rule id was found then skip.
  932. } else { // If the rule id was not found then
  933. Duplicates.insert(M.ruleid); // remember it for next time.
  934. }
  935. }
  936. // At this point we've skipped duplicate match records, but we
  937. // still want to emit some (all?) of them so it's time to do it.
  938. O << CFGData.node_licenseid << "\t"
  939. << Timestamp(ScanData.StartOfJobUTC) << "\t"
  940. << ScanData.ScanName << "\t"
  941. << ScanData.SetupTime << "\t"
  942. << ScanData.ScanTime.getElapsedTime() << "\t"
  943. << (('m' == M.flag) ? "Match\t" :
  944. (('w' == M.flag) ? "White\t" :
  945. (('p' == M.flag) ? "Panic\t" : "Fault\t")))
  946. << M.ruleid << "\t"
  947. << M.symbol << "\t"
  948. << M.index << "\t"
  949. << M.endex << "\t"
  950. << ScanData.ScanDepth
  951. << endl;
  952. } else { // If this record is final, emit it!
  953. O << CFGData.node_licenseid << "\t"
  954. << Timestamp(ScanData.StartOfJobUTC) << "\t"
  955. << ScanData.ScanName << "\t"
  956. << ScanData.SetupTime << "\t"
  957. << ScanData.ScanTime.getElapsedTime() << "\t"
  958. << (('f' == M.flag) ? "Final\t" :
  959. (('c' == M.flag) ? "Clean\t" : "Fault\t"))
  960. << M.ruleid << "\t"
  961. << M.symbol << "\t"
  962. << M.index << "\t"
  963. << M.endex << "\t"
  964. << ScanData.ScanDepth
  965. << endl;
  966. }
  967. }
  968. ScanData.ClassicLogText = O.str(); // Save the formatted log text.
  969. // Now that we've produced the appropriate log entries let's send them
  970. // out to the log file.
  971. if(LogOutputMode_File == CFGData.Scan_Classic_Mode) { // If we are writing to file,
  972. string TFN = CFGData.paths_log_path; // build an appropriate log file
  973. TFN.append(CFGData.node_licenseid); // name.
  974. if(CFGData.Scan_Classic_Rotate) { // If we're rotating per day:
  975. TFN.append("."); // Put a timestamp on the file name.
  976. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  977. else { Timestamp(TFN); } // the utc timestamp as configured.
  978. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  979. }
  980. TFN.append(".log"); // Tack on the extension.
  981. ClassicScanLogger.post(ScanData.ClassicLogText, TFN); // Post the log with the file name.
  982. }
  983. }
  984. //// LogThisScan() is broken into two sections. The first section happens with
  985. //// the snfLOGmgr mutex locked and must happen as quickly as possible so that
  986. //// the chance for contention over those resources is minimized. This amounts
  987. //// to some raw CPU work adjusting counters and so forth.
  988. ////
  989. //// The second section handles any additional work such as formatting log
  990. //// entries. Essentially, anything that doesn't NEED to happen while the mutex
  991. //// is locked should happen in the second section.
  992. ////
  993. //// The two subroutines for LogThisScan are:
  994. //// captureLTSMetrics() -- Mutex locked, first section
  995. //// performLTSLogging() -- Mutex NOT locked, second section
  996. void snfLOGmgr::captureLTSMetrics(snfCFGData& CFGData, snfScanData& ScanData) { // LogThisScan section 1
  997. ScopeMutex FreezeRightThereWhileITakeThisPicture(MyMutex); // Lock the object for this update.
  998. if(Status.LatestRuleID < ScanData.PatternID) { // If we have a new latest rule id
  999. Status.LatestRuleID = ScanData.PatternID; // then capture it.
  1000. }
  1001. // keep histograms---
  1002. // Second, Minute, and Hour histograms are reset() by the appropriate
  1003. // reporting functions. That is, when a Second report is made, the Second
  1004. // histograms are reset; likewise Minutes and Hours. As a result we simply
  1005. // hit them all the same way when we log a scan.
  1006. ResultsSecond.hit(ScanData.CompositeFinalResult); // Histogram the result codes.
  1007. ResultsMinute.hit(ScanData.CompositeFinalResult);
  1008. ResultsHour.hit(ScanData.CompositeFinalResult);
  1009. if(ScanData.PatternWasFound) { // Histogram pattern IDs.
  1010. RulesSecond.hit(ScanData.PatternID);
  1011. RulesMinute.hit(ScanData.PatternID);
  1012. RulesHour.hit(ScanData.PatternID);
  1013. }
  1014. if(0 < ScanData.RulePanics.size()) { // Histogram any rule panic hits.
  1015. set<int>::iterator iP;
  1016. for( // Dump the set of rule panic
  1017. iP = ScanData.RulePanics.begin(); // IDs from beginning to end
  1018. iP != ScanData.RulePanics.end(); // into our histogram set.
  1019. iP++) {
  1020. PanicsSecond.hit((*iP));
  1021. PanicsMinute.hit((*iP));
  1022. PanicsHour.hit((*iP));
  1023. }
  1024. }
  1025. // count up these things---
  1026. ++(*CurrentCounters).Events.Scans; // Number of messages scanned.
  1027. const int HamResult = 0; // A result of 0 is "clean" or "white"
  1028. if( // If we have identified Ham
  1029. HamResult == ScanData.CompositeFinalResult || // either by the conventional result or
  1030. CFGData.TrainingWhiteRuleHandler.isListed(ScanData.CompositeFinalResult) // some known white-rule symbol
  1031. ) {
  1032. ++(*CurrentCounters).Events.Ham; // then we will bump the Ham counter.
  1033. } else { // For any other result we will bump
  1034. ++(*CurrentCounters).Events.Spam; // the spam counter.
  1035. }
  1036. if(ScanData.GBUdbNormalTriggered) { // Count of GBUdb indetermineta IPs.
  1037. ++(*CurrentCounters).Events.GBUdbNormalTriggered;
  1038. }
  1039. if(ScanData.GBUdbWhiteTriggered) { // Count of GBUdb found source IP white.
  1040. ++(*CurrentCounters).Events.GBUdbWhiteTriggered;
  1041. }
  1042. if(ScanData.GBUdbWhiteSymbolForced) { // Count of white was on and symbol was set.
  1043. ++(*CurrentCounters).Events.GBUdbWhiteSymbolForced;
  1044. }
  1045. if(ScanData.GBUdbPatternSourceConflict) { // Count of pattern was found with white IP.
  1046. ++(*CurrentCounters).Events.GBUdbPatternSourceConflict;
  1047. }
  1048. if(ScanData.GBUdbAutoPanicTriggered) { // Count of autopanic was triggered.
  1049. ++(*CurrentCounters).Events.GBUdbAutoPanicTriggered;
  1050. }
  1051. if(ScanData.GBUdbAutoPanicExecuted) { // Count of an autopanic was added.
  1052. ++(*CurrentCounters).Events.GBUdbAutoPanicExecuted;
  1053. }
  1054. if(ScanData.GBUdbBlackTriggered) { // Count of GBUdb found source IP black.
  1055. ++(*CurrentCounters).Events.GBUdbBlackTriggered;
  1056. }
  1057. if(ScanData.GBUdbBlackSymbolForced) { // Count of black was on and symbol was set.
  1058. ++(*CurrentCounters).Events.GBUdbBlackSymbolForced;
  1059. }
  1060. if(ScanData.GBUdbTruncateTriggered) { // Count of Truncate was possible.
  1061. ++(*CurrentCounters).Events.GBUdbTruncateTriggered;
  1062. }
  1063. if(ScanData.GBUdbPeekTriggered) { // Count of we could peek.
  1064. ++(*CurrentCounters).Events.GBUdbPeekTriggered;
  1065. }
  1066. if(ScanData.GBUdbSampleTriggered) { // Count of we could sample.
  1067. ++(*CurrentCounters).Events.GBUdbSampleTriggered;
  1068. }
  1069. if(ScanData.GBUdbTruncateExecuted) { // Count of if we actually did truncate.
  1070. ++(*CurrentCounters).Events.GBUdbTruncateExecuted;
  1071. }
  1072. if(ScanData.GBUdbPeekExecuted) { // Count of we peeked instead of truncating.
  1073. ++(*CurrentCounters).Events.GBUdbPeekExecuted;
  1074. }
  1075. if(ScanData.GBUdbSampleExecuted) { // Count of we sampled.
  1076. ++(*CurrentCounters).Events.GBUdbSampleExecuted;
  1077. }
  1078. if(ScanData.GBUdbCautionTriggered) { // Count of GBUdb found source IP suspicous.
  1079. ++(*CurrentCounters).Events.GBUdbCautionTriggered;
  1080. }
  1081. if(ScanData.GBUdbCautionSymbolForced) { // Count of caution was on and symbol was set.
  1082. ++(*CurrentCounters).Events.GBUdbCautionSymbolForced;
  1083. }
  1084. if(ScanData.PatternWasFound) { // Count of scanner matches.
  1085. ++(*CurrentCounters).Events.PatternWasFound;
  1086. }
  1087. if(0 < ScanData.RulePanics.size()) { // Count of rule panics.
  1088. ++(*CurrentCounters).Events.RulePanicFound;
  1089. }
  1090. }
  1091. void snfLOGmgr::performLTSLogging(snfCFGData& CFGData, snfScanData& ScanData) { // LogThisScan section 2
  1092. // Build X- Headers, XML Log, and Classic Log as needed...
  1093. if(LogOutputMode_None != CFGData.XHDROutput_Mode) { // If XHeaders are turned on then
  1094. doXHDRs(CFGData, ScanData); // call the XHeaders subroutine.
  1095. }
  1096. if(LogOutputMode_None != CFGData.Scan_XML_Mode) { // If XML scan logs are turned on then
  1097. doXMLLogs(CFGData, ScanData); // call the XML scan log subroutine.
  1098. }
  1099. if(LogOutputMode_None != CFGData.Scan_Classic_Mode) { // If Classic scan logs are turned on
  1100. doClassicLogs(CFGData, ScanData); // then call the Classic log subroutine.
  1101. }
  1102. }
  1103. void snfLOGmgr::logThisScan(snfCFGData& CFGData, snfScanData& ScanData) { // How to log a scan event...
  1104. captureLTSMetrics(CFGData, ScanData); // Lock the mutex and do the math.
  1105. performLTSLogging(CFGData, ScanData); // Unlock the mutex and write it down.
  1106. if(0 < ScanData.XHDRsText.length()) { // If we have XHeader data then
  1107. switch(CFGData.XHDROutput_Mode) { // set the appropriate output mode.
  1108. case LogOutputMode_Inject: ScanData.XHeaderInjectOn = true; break; // We will either inject the headers
  1109. case LogOutputMode_File: ScanData.XHeaderFileOn = true; break; // or we will create a .xhdr file.
  1110. } // The actual inject/file operation
  1111. } // happens in ScanMessageFile().
  1112. ScanData.ReadyToClear = true; // This can be cleared now once
  1113. } // the ScanData has been consumed.
  1114. // logThisError(CFGData, ScanData) - for scanning errors (message context)
  1115. void snfLOGmgr::logThisError(snfScanData& ScanData, const string ContextName, // Inject an error log entry for this
  1116. const int Code, const string Text // scan using this number & message.
  1117. ) {
  1118. // Check for each type of log and create an appropriate entry for
  1119. // each log type that is activated in the configuration.
  1120. //// Handle XML Log Scan Error Reports
  1121. if(LogOutputMode_None != XML_Log_Mode) { // If XML logs are on emit the error.
  1122. // Produce Error Log Entry and store in XMLLogText
  1123. stringstream O; // Stringstream for formatting.
  1124. O << "<e " // Format the <s>can error element
  1125. << "u=\'" << Timestamp(ScanData.StartOfJobUTC) << "\' "
  1126. << "context=\'" << ContextName << "\' "
  1127. << "m=\'" << ScanData.ScanName << "\' "
  1128. << "code=\'" << Code << "\' "
  1129. << "text=\'" << Text << "\'"
  1130. << "/>"
  1131. << endl;
  1132. ScanData.XMLLogText = O.str(); // Save the formatted log text.
  1133. // Now that we've produced the appropriate log entries let's send them
  1134. // out to the log file.
  1135. if(LogOutputMode_File == XML_Log_Mode) { // If we are writing to file,
  1136. string TFN = LogsPath; // build an appropriate log file
  1137. TFN.append(NodeId); // name.
  1138. if(XMLLogRotate) { // If we're rotating per day:
  1139. TFN.append("."); // Put a timestamp on the file name.
  1140. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1141. else { Timestamp(TFN); } // the utc timestamp as configured.
  1142. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1143. }
  1144. TFN.append(".log.xml"); // Tack on the extension.
  1145. XMLScanLogger.post(ScanData.XMLLogText, TFN); // Post the log with the file name.
  1146. }
  1147. }
  1148. //// Handle Clasic Log Scan Error Reports
  1149. if(LogOutputMode_None != Classic_Log_Mode) { // If Classic logs are on emit the error.
  1150. // Produce an appropriate Error log entry in ClassicLogText
  1151. stringstream O; // Stringstream for formatting.
  1152. O << NodeId << "\t" // Format the scan error entry.
  1153. << Timestamp(ScanData.StartOfJobUTC) << "\t"
  1154. << ScanData.ScanName << "\t"
  1155. << ScanData.SetupTime << "\t"
  1156. << ScanData.ScanTime.getElapsedTime() << "\t"
  1157. << Text << "\t"
  1158. << "0\t"
  1159. << Code << "\t"
  1160. << "0\t"
  1161. << ScanData.ScanSize << "\t"
  1162. << ScanData.ScanDepth
  1163. << endl;
  1164. ScanData.ClassicLogText = O.str(); // Save the formatted log text.
  1165. // Now that we've produced the appropriate log entries let's send them
  1166. // out to the log file.
  1167. if(LogOutputMode_File == Classic_Log_Mode) { // If we are writing to file,
  1168. string TFN = LogsPath; // build an appropriate log file
  1169. TFN.append(NodeId); // name.
  1170. if(ClassicLogRotate) { // If we're rotating per day:
  1171. TFN.append("."); // Put a timestamp on the file name.
  1172. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1173. else { Timestamp(TFN); } // the utc timestamp as configured.
  1174. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1175. }
  1176. TFN.append(".log"); // Tack on the extension.
  1177. ClassicScanLogger.post(ScanData.ClassicLogText, TFN); // Post the log with the file name.
  1178. }
  1179. }
  1180. }
  1181. // logThisIPTest w/ Action
  1182. void snfLOGmgr::logThisIPTest(IPTestRecord& I, string Action) { // Log an IPTest and action.
  1183. if(!Configured) return; // Do nothing if not configured.
  1184. stringstream O; // Stringstream to format the entry.
  1185. string tmp; // String for use getting timestamp.
  1186. O << "<t "
  1187. << "u=\'" << Timestamp(tmp) << "\' "
  1188. << "ip=\'" << (string) I.IP << "\' "
  1189. << "t=\'" <<
  1190. ((Ugly == I.G.Flag())? "u" :
  1191. ((Good == I.G.Flag())? "g" :
  1192. ((Bad == I.G.Flag())? "b" : "i")))
  1193. << "\' "
  1194. << "g=\'" << I.G.Good() << "\' "
  1195. << "b=\'" << I.G.Bad() << "\' "
  1196. << "c=\'" << I.G.Confidence() << "\' "
  1197. << "p=\'" << I.G.Probability() << "\' "
  1198. << "r=\'" <<
  1199. ((Unknown == I.R)? "Unknown" :
  1200. ((White == I.R)? "White" :
  1201. ((Normal == I.R)? "Normal" :
  1202. ((New == I.R)? "New" :
  1203. ((Caution == I.R)? "Caution" :
  1204. ((Black == I.R)? "Black" :
  1205. ((Truncate == I.R)? "Truncate" :
  1206. "Fault")))))))
  1207. << "\' "
  1208. << "a=\'" << Action << "\'"
  1209. << "/>" << endl;
  1210. XMLScanLogger.post(O.str()); // Post the log, use existing path.
  1211. }
  1212. // logThisError(Context, Code, Text) - for non-message errors.
  1213. void snfLOGmgr::logThisError(string ContextName, int Code, string Text) { // Log an error message.
  1214. if(!Configured) return; // Do nothing if not configured.
  1215. ScopeMutex LockCFG(MyMutex); // Don't change CFG. I'm using it!
  1216. if(LogOutputMode_File == XML_Log_Mode) { // If XML logs are turned on:
  1217. stringstream O; // Stringstream to format the entry.
  1218. string tmp; // String for use getting timestamp.
  1219. O << "<e " // Format an <e/>rror element.
  1220. << "u=\'" << Timestamp(tmp) << "\' "
  1221. << "context=\'" << ContextName << "\' "
  1222. << "code=\'" << Code << "\' "
  1223. << "text=\'" << Text << "\'/>"
  1224. << endl;
  1225. // Now that we've produced the appropriate log entries let's send them
  1226. // out to the log file.
  1227. string TFN = LogsPath; // build an appropriate log file
  1228. TFN.append(NodeId); // name.
  1229. if(XMLLogRotate) { // If we're rotating per day:
  1230. TFN.append("."); // Put a timestamp on the file name.
  1231. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1232. else { Timestamp(TFN); } // the utc timestamp as configured.
  1233. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1234. }
  1235. TFN.append(".log.xml"); // Tack on the extension.
  1236. XMLScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1237. }
  1238. if(LogOutputMode_File == Classic_Log_Mode) { // If Classic logs are turned on:
  1239. stringstream O; // Stringstream to format the entry.
  1240. string tmp; // String for use getting timestamp.
  1241. O << NodeId << "\t" // Format the error entry.
  1242. << Timestamp(tmp) << "\t"
  1243. << ContextName << "\t"
  1244. << "0\t"
  1245. << "0\t"
  1246. << Text << "\t"
  1247. << "0\t"
  1248. << Code << "\t"
  1249. << "0\t"
  1250. << "0\t"
  1251. << "0\t"
  1252. << endl;
  1253. // Now that we've produced the appropriate log entries let's send them
  1254. // out to the log file.
  1255. string TFN = LogsPath; // build an appropriate log file
  1256. TFN.append(NodeId); // name.
  1257. if(ClassicLogRotate) { // If we're rotating per day:
  1258. TFN.append("."); // Put a timestamp on the file name.
  1259. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1260. else { Timestamp(TFN); } // the utc timestamp as configured.
  1261. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1262. }
  1263. TFN.append(".log"); // Tack on the extension.
  1264. ClassicScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1265. }
  1266. }
  1267. // logThisInfo(Context, Code, Text) - for generic non-errors.
  1268. void snfLOGmgr::logThisInfo(string ContextName, int Code, string Text) { // Log an informational message.
  1269. if(!Configured) return; // Do nothing if not configured.
  1270. ScopeMutex LockCFG(MyMutex); // Don't change CFG. I'm using it!
  1271. if(LogOutputMode_File == XML_Log_Mode) { // If XML logs are turned on:
  1272. stringstream O; // Stringstream to format the entry.
  1273. string tmp; // String for use getting timestamp.
  1274. O << "<i " // Format an <i/>nfo element.
  1275. << "u=\'" << Timestamp(tmp) << "\' "
  1276. << "context=\'" << ContextName << "\' "
  1277. << "code=\'" << Code << "\' "
  1278. << "text=\'" << Text << "\'/>"
  1279. << endl;
  1280. // Now that we've produced the appropriate log entries let's send them
  1281. // out to the log file.
  1282. string TFN = LogsPath; // build an appropriate log file
  1283. TFN.append(NodeId); // name.
  1284. if(XMLLogRotate) { // If we're rotating per day:
  1285. TFN.append("."); // Put a timestamp on the file name.
  1286. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1287. else { Timestamp(TFN); } // the utc timestamp as configured.
  1288. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1289. }
  1290. TFN.append(".log.xml"); // Tack on the extension.
  1291. XMLScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1292. }
  1293. if(LogOutputMode_File == Classic_Log_Mode) { // If Classic logs are turned on:
  1294. stringstream O; // Stringstream to format the entry.
  1295. string tmp; // String for use getting timestamp.
  1296. O << NodeId << "\t" // Format the informational entry.
  1297. << Timestamp(tmp) << "\t"
  1298. << ContextName << "\t"
  1299. << "0\t"
  1300. << "0\t"
  1301. << Text << "\t"
  1302. << "0\t"
  1303. << Code << "\t"
  1304. << "0\t"
  1305. << "0\t"
  1306. << "0\t"
  1307. << endl;
  1308. // Now that we've produced the appropriate log entries let's send them
  1309. // out to the log file.
  1310. string TFN = LogsPath; // build an appropriate log file
  1311. TFN.append(NodeId); // name.
  1312. if(ClassicLogRotate) { // If we're rotating per day:
  1313. TFN.append("."); // Put a timestamp on the file name.
  1314. if(Rotate_LocalTime) { LocalTimestamp(TFN); } // Use either the local timestamp or
  1315. else { Timestamp(TFN); } // the utc timestamp as configured.
  1316. TFN = TFN.substr(0, TFN.length() - 6); // Stip off the Hours, Minutes, Seconds.
  1317. }
  1318. TFN.append(".log"); // Tack on the extension.
  1319. ClassicScanLogger.post(O.str(), TFN); // Post the log with the file name.
  1320. }
  1321. }
  1322. string snfLOGmgr::PlatformVersion(string NewPlatformVersion) { // Set platform version info.
  1323. ScopeMutex FreezeForNewData(MyMutex); // Get the ball and
  1324. myPlatformVersion = NewPlatformVersion; // set the data.
  1325. return myPlatformVersion; // return the new data.
  1326. }
  1327. string snfLOGmgr::PlatformVersion() { // Get platform version info.
  1328. ScopeMutex DontChangeOnMe(MyMutex); // Get the ball and
  1329. return myPlatformVersion; // get the data.
  1330. }
  1331. string snfLOGmgr::EngineVersion() { // Get engine version info.
  1332. return string(SNF_ENGINE_VERSION); // Return the engine version string.
  1333. }
  1334. //// The caller to getSpamshot promises to reset() the counters when it is done
  1335. //// with the data and before getSnapshot() gets called again.
  1336. snfCounterPack* snfLOGmgr::getSnapshot() { // Get a copy of the current counters.
  1337. snfCounterPack* Snapshot = CurrentCounters; // Grab the active counters.
  1338. CurrentCounters = ReportingCounters; // Swap the reporting counters in.
  1339. CurrentCounters->ActiveTime.start(Snapshot->ActiveTime.stop()); // (De)Activate the activity timers.
  1340. ReportingCounters = Snapshot; // Put the old ActiveCounters into
  1341. return Snapshot; // reporting mode and return a ptr.
  1342. }
  1343. bool snfLOGmgr::OkToPeek(int PeekOneInX) { // Test to see if it's ok to peek.
  1344. ScopeMutex JustMe(PeekMutex); // Protect the peek enable counter.
  1345. ++PeekEnableCounter; // Bump the counter by one.
  1346. if(PeekEnableCounter >= PeekOneInX) { // If we've made the threshold then
  1347. PeekEnableCounter = 0; // reset the counter and
  1348. return true; // return true.
  1349. } // If not then
  1350. return false; // return false.
  1351. }
  1352. bool snfLOGmgr::OkToSample(int SampleOneInX) { // Test to see if it's ok to sample.
  1353. ScopeMutex JustMe(SampleMutex); // Protect the sample enable counter.
  1354. ++SampleEnableCounter; // Bump the counter by one.
  1355. if(SampleEnableCounter >= SampleOneInX) { // If we've made the threshold then
  1356. SampleEnableCounter = 0; // reset the counter and
  1357. return true; // return true.
  1358. } // If not then return
  1359. return false; // false.
  1360. }
  1361. time_t snfLOGmgr::Timestamp() { // Get an ordinary timestamp.
  1362. time_t rawtime;
  1363. time(&rawtime);
  1364. return rawtime;
  1365. }
  1366. string snfLOGmgr::Timestamp(time_t t) { // Convert time_t to a timestamp s.
  1367. char TimestampBfr[20]; // Create a small buffer.
  1368. tm* gmt; // Get a ptr to a tm structure.
  1369. gmt = gmtime(&t); // Fill it with UTC.
  1370. sprintf(TimestampBfr,"%04d%02d%02d%02d%02d%02d", // Format yyyymmddhhmmss
  1371. gmt->tm_year+1900,
  1372. gmt->tm_mon+1,
  1373. gmt->tm_mday,
  1374. gmt->tm_hour,
  1375. gmt->tm_min,
  1376. gmt->tm_sec
  1377. );
  1378. return string(TimestampBfr); // Return a string.
  1379. }
  1380. string& snfLOGmgr::Timestamp(string& s) { // Returns a current timestamp in s.
  1381. s.append(Timestamp(Timestamp())); // Append the timestamp to s and
  1382. return s; // return it.
  1383. }
  1384. string snfLOGmgr::LocalTimestamp(time_t t) { // Convert time_t to a local timestamp s.
  1385. char TimestampBfr[20]; // Create a small buffer.
  1386. tm* localt; // Get a ptr to a tm structure.
  1387. localt = localtime(&t); // Fill it with local time.
  1388. sprintf(TimestampBfr,"%04d%02d%02d%02d%02d%02d", // Format yyyymmddhhmmss
  1389. localt->tm_year+1900,
  1390. localt->tm_mon+1,
  1391. localt->tm_mday,
  1392. localt->tm_hour,
  1393. localt->tm_min,
  1394. localt->tm_sec
  1395. );
  1396. return string(TimestampBfr); // Return a string.
  1397. }
  1398. string& snfLOGmgr::LocalTimestamp(string& s) { // Returns a local timestamp in s.
  1399. s.append(LocalTimestamp(Timestamp())); // Append the timestamp to s and
  1400. return s; // return it.
  1401. }
  1402. unsigned int snfLOGmgr::SerialNumber() { // Returns the next serial number.
  1403. ScopeMutex AtomicOperation(SerialNumberMutex); // Lock the serial number mutex.
  1404. ++Status.SerialNumberCounter; // Increment the serial number.
  1405. unsigned int result = Status.SerialNumberCounter; // Capture the new value.
  1406. return result; // Return the unique result.
  1407. }
  1408. string& snfLOGmgr::SerialNumber(string& s) { // Appends the next serial number.
  1409. char SerialNumberBuffer[9]; // 8 hex digits and a null terminator.
  1410. sprintf( // Format the serial number and
  1411. SerialNumberBuffer, // place it into the buffer.
  1412. "%08X", SerialNumber()
  1413. );
  1414. s.append(SerialNumberBuffer); // Append the buffer to s.
  1415. return s; // Return s.
  1416. }
  1417. // Persistent State Functions
  1418. // The Persistent State object is slightly smart. It won't try to restore
  1419. // itself from disk if it has already been restored. It won't write itself
  1420. // to disk unless it was first loaded or there was no original file to load.
  1421. // This leaves open the possibility that a disk problem when opening the
  1422. // engine could cause a persistent state problem - but the alternative is to
  1423. // have the persistent state unprotected. If there is a problem, then clearing
  1424. // the problem and re-opening the engine will load the persistent state. If
  1425. // that's not the best solution then it's always possible to destroy the
  1426. // existing persistent state and start over -- at least then it will be a
  1427. // conscious decision and not a "side effect"
  1428. void snfLOGPersistentState::store(string& FileNameToStore) { // Write the whole thing to a file.
  1429. if(Ready) { // If it is safe to overwrite then
  1430. try { // Try... to
  1431. ofstream P(FileNameToStore.c_str(), ios::trunc | ios::binary); // Open and overwrite the file and
  1432. P.write((char*)this, sizeof(snfLOGPersistentState)); // store our bytes in binary format.
  1433. P.close();
  1434. } catch (...) {} // Ignore any errors for now.
  1435. }
  1436. }
  1437. void snfLOGPersistentState::restore(string& FileNameToRestore) { // Read the whole thing from a file.
  1438. if(!Ready) { // If we have not already loaded...
  1439. if(0 > access(FileNameToRestore.c_str(), R_OK)) { // If the file cannot be read we
  1440. Ready = true; // will assume it doesn't exist and
  1441. } // set our Ready flag to allow writing.
  1442. else { // If the file does exist we load it.
  1443. try { // Try this...
  1444. ifstream P(FileNameToRestore.c_str(), ios::binary); // Create a binary input stream and
  1445. P.read((char*)this, sizeof(snfLOGPersistentState)); // read the bytes into this object.
  1446. P.close(); // Then, close the file.
  1447. Ready = true; // Set the Ready flag to allow writes.
  1448. } catch(...) {} // Ignore any errors for now.
  1449. }
  1450. }
  1451. }
  1452. void snfLOGmgr::RecordSyncEvent() { // Sets timestamp of latest Sync.
  1453. Status.LastSyncTime = Timestamp();
  1454. }
  1455. int snfLOGmgr::SecsSinceLastSync() { // Gets seconds since latest Sync.
  1456. return (int) difftime(Timestamp(), Status.LastSyncTime);
  1457. }
  1458. void snfLOGmgr::RecordSaveEvent() { // Sets timestamp of latest Save.
  1459. Status.LastSaveTime = Timestamp();
  1460. }
  1461. int snfLOGmgr::SecsSinceLastSave() { // Gets seconds since latest Save.
  1462. return (int) difftime(Timestamp(), Status.LastSaveTime);
  1463. }
  1464. void snfLOGmgr::RecordCondenseEvent() { // Sets timestamp of latest Condense.
  1465. Status.LastCondenseTime = Timestamp();
  1466. }
  1467. int snfLOGmgr::SecsSinceLastCondense() { // Gets seconds since latest Condense.
  1468. return (int) difftime(Timestamp(), Status.LastCondenseTime);
  1469. }
  1470. // Data in the multi-range sliding window is tracked in circular buffers.
  1471. // The snf_SMHDMY_Counter::do_input() function encapsuates the input operation.
  1472. bool snf_SMHDMY_Counter::do_input( // Subroutine for new data input.
  1473. int X, // Given new data X,
  1474. int& SUM, // the SUM being tracked,
  1475. int* DATA, // the array of DATA,
  1476. int& ORDINAL, // the current ORDINAL,
  1477. int SIZE) { // and the SIZE of the array...
  1478. SUM -= DATA[ORDINAL]; // Subtract the old data from the
  1479. SUM += (DATA[ORDINAL] = X); // SUM and replace it with X.
  1480. ++ORDINAL; // Move to the next slot and
  1481. if(SIZE <= ORDINAL) ORDINAL = 0; // rotate back around if needed.
  1482. return (0 == ORDINAL); // Return true if time to carry.
  1483. }
  1484. void snf_SMHDMY_Counter::input(int X) {
  1485. if(do_input(X, SEC6SUM, SEC6DATA, SEC6ORDINAL, 6)) // 6 second sum
  1486. if(do_input(SEC6SUM, SEC10SUM, SEC10DATA, SEC10ORDINAL, 10)) // 60 second sum
  1487. if(do_input(SEC10SUM, MIN6SUM, MIN6DATA, MIN6ORDINAL, 6)) // 6 minute sum
  1488. if(do_input(MIN6SUM, MIN10SUM, MIN10DATA, MIN10ORDINAL, 10)) // 60 minute sum
  1489. if(do_input(MIN10SUM, HOUR4SUM, HOUR4DATA, HOUR4ORDINAL, 4)) // 4 hour sum
  1490. if(do_input(HOUR4SUM, HOUR6SUM, HOUR6DATA, HOUR6ORDINAL, 6)) { // 24 hour sum
  1491. do_input(HOUR6SUM, WEEK7SUM, WEEK7DATA, WEEK7ORDINAL, 7); // 7 day sum
  1492. do_input(HOUR6SUM, YEAR365SUM, YEAR365DATA, YEAR365ORDINAL, 365); // 365 day sum
  1493. if(do_input(HOUR6SUM, MONTH5SUM, MONTH5DATA, MONTH5ORDINAL, 5)) // 5 day sum
  1494. if(do_input(MONTH5SUM, MONTH6SUM, MONTH6DATA, MONTH6ORDINAL, 6)) // 30 day sum
  1495. if(do_input(MONTH6SUM, YEAR3SUM, YEAR3DATA, YEAR3ORDINAL, 3)) // 3 month sum
  1496. do_input(YEAR3SUM, YEAR4SUM, YEAR4DATA, YEAR4ORDINAL, 4); // 12 month sum
  1497. }
  1498. }
  1499. double snf_SMHDMY_AveragePerMinute( // Get mornalized minute avg of X
  1500. snf_SMHDMY_Counter& X, // Input the Units in the period.
  1501. snf_SMHDMY_Counter& M) { // Input the Milliseconds in the period.
  1502. int Units = X.SEC6SUM + X.SEC10SUM; // Get the count.
  1503. int Milliseconds = M.SEC6SUM + M.SEC10SUM; // Get the time.
  1504. return snf_rationalize(Units, Milliseconds, MillisecondsInAMinute); // Normalize to a minute.
  1505. }
  1506. double snfLOGmgr::MessagesPerMinute() { // Avg Msgs/Minute.
  1507. return snf_SMHDMY_AveragePerMinute(MessageCounter, TimeCounter);
  1508. }
  1509. double snfLOGmgr::HamPerMinute() { // Avg Ham/Minute.
  1510. return snf_SMHDMY_AveragePerMinute(HamCounter, TimeCounter);
  1511. }
  1512. double snfLOGmgr::SpamPerMinute() { // Avg Spam/Minute.
  1513. return snf_SMHDMY_AveragePerMinute(SpamCounter, TimeCounter);
  1514. }
  1515. double snfLOGmgr::WhitePerMinute() { // Avg White/Minute.
  1516. return snf_SMHDMY_AveragePerMinute(WhiteCounter, TimeCounter);
  1517. }
  1518. double snfLOGmgr::CautionPerMinute() { // Avg Caution/Minute.
  1519. return snf_SMHDMY_AveragePerMinute(CautionCounter, TimeCounter);
  1520. }
  1521. double snfLOGmgr::BlackPerMinute() { // Avg Black/Minute.
  1522. return snf_SMHDMY_AveragePerMinute(BlackCounter, TimeCounter);
  1523. }
  1524. double snfLOGmgr::TruncatePerMinute() { // Avg Truncate/Minute.
  1525. return snf_SMHDMY_AveragePerMinute(TruncateCounter, TimeCounter);
  1526. }
  1527. double snfLOGmgr::SamplePerMinute() { // Avg Sample/Minute.
  1528. return snf_SMHDMY_AveragePerMinute(SampleCounter, TimeCounter);
  1529. }
  1530. const string EmptyStatusSecondReport = "<stats class=\'second\'/>"; // Empty Status.Second looks like this.
  1531. string snfLOGmgr::getStatusSecondReport() { // Get latest status.second report.
  1532. ScopeMutex FlashBulb(StatusReportMutex); // Take a safe snapshot of the report.
  1533. if(0 < SecondReportText.length()) return SecondReportText; // If it's posted then send it. If not
  1534. return EmptyStatusSecondReport; // then send the empty version.
  1535. }
  1536. const string EmptyStatusMinuteReport = "<stats class=\'minute\'/>"; // Empty Status.Minute looks like this.
  1537. string snfLOGmgr::getStatusMinuteReport() { // Get latest status.minute report.
  1538. ScopeMutex FlashBulb(StatusReportMutex); // Take a safe snapshot of the report.
  1539. if(0 < MinuteReportText.length()) return MinuteReportText; // If it's posted then send it. If not
  1540. return EmptyStatusMinuteReport; // then send the empty version.
  1541. }
  1542. const string EmptyStatusHourReport = "<stats class=\'hour\'/>"; // Empty Status.Hour looks like this.
  1543. string snfLOGmgr::getStatusHourReport() { // Get latest status.hour report.
  1544. ScopeMutex FlashBulb(StatusReportMutex); // Take a safe snapshot of the report.
  1545. if(0 < HourReportText.length()) return HourReportText; // If it's posted then send it. If not
  1546. return EmptyStatusHourReport; // then send the empty version.
  1547. }