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

snfLOGmgr.hpp 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. // snfLOGmgr.hpp
  2. //
  3. // (C) Copyright 2006 - 2020 ARM Research Labs, LLC.
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // SNF Logging and Statistics engine.
  7. ////////////////////////////////////////////////////////////////////////////////
  8. //// Begin snfLOGmgr include only once
  9. #pragma once
  10. #include <list>
  11. #include <set>
  12. #include <string>
  13. #include <vector>
  14. #include <sstream>
  15. #include <ctime>
  16. #include <cstdio>
  17. #include "../CodeDweller/timing.hpp"
  18. #ifdef WIN32
  19. // Required because threading.hpp includes windows.h.
  20. #include <winsock2.h>
  21. #endif
  22. #include "../CodeDweller/threading.hpp"
  23. #include "../CodeDweller/histogram.hpp"
  24. #include "snf_match.h"
  25. #include "snfCFGmgr.hpp"
  26. #include "snfNETmgr.hpp"
  27. #include "GBUdb.hpp"
  28. #include "../CodeDweller/timing.hpp"
  29. #include "../CodeDweller/threading.hpp"
  30. #include "../CodeDweller/histogram.hpp"
  31. namespace cd = codedweller;
  32. class snfNETmgr; // Declare snfNETmgr
  33. extern const char* SNF_ENGINE_VERSION; // Declare the Engine Version Data
  34. //// DiscLogger ////////////////////////////////////////////////////////////////
  35. // Writes log files back to Disc and double buffers data to minimize contention
  36. // and delays. So - if it takes a few milliseconds to post the log to disc, the
  37. // application that post()s to the log does not have to wait. Write back happens
  38. // about once per second when enabled. Files can be appended or overwritten.
  39. class DiscLogger : private cd::Thread { // Double buffered lazy writer.
  40. private:
  41. cd::Mutex BufferControlMutex; // Protects buffers while swapping.
  42. cd::Mutex FlushMutex; // Protects flush operations.
  43. std::string myPath; // Where the file should be written.
  44. std::string BufferA; // Log data buffer A.
  45. std::string BufferB; // Log data buffer B.
  46. bool UseANotB; // Indicates the active buffer.
  47. bool isDirty; // True if data not yet written.
  48. bool isBad; // True if last write failed.
  49. bool isTimeToStop; // True when shutting down.
  50. bool inAppendMode; // True when in append mode.
  51. std::string& FlushingBuffer() { return ((UseANotB)?BufferA:BufferB); } // Returns the buffer for flushing.
  52. std::string& PostingBuffer() { return ((UseANotB)?BufferB:BufferA); } // Returns the buffer for posting.
  53. bool isEnabled; // True when this should run.
  54. void myTask(); // Write back thread task.
  55. public:
  56. DiscLogger(std::string N = "UnNamed"); // Constructs and starts the thread.
  57. ~DiscLogger(); // Flushes and stops the thread.
  58. std::string Path(const std::string PathName) { // Sets the file path.
  59. cd::ScopeMutex NewSettings(BufferControlMutex);
  60. myPath = PathName;
  61. return myPath;
  62. }
  63. std::string Path() { // Returns the file path.
  64. cd::ScopeMutex DontMove(BufferControlMutex);
  65. return myPath;
  66. }
  67. bool AppendMode(const bool AppendNotOverwrite) { // Sets append mode if true.
  68. return (inAppendMode = AppendNotOverwrite);
  69. }
  70. bool AppendMode() { return (inAppendMode); } // True if in append mode.
  71. bool OverwriteMode(const bool OverwriteNotAppend) { // Sets overwrite mode if true.
  72. return (inAppendMode = (!OverwriteNotAppend));
  73. }
  74. bool OverwriteMode() { return (!inAppendMode); } // True if in overwrite mode.
  75. void post(const std::string Input, const std::string NewPath = ""); // Post Input to log, [set path].
  76. void flush(); // Flush right now!
  77. bool Bad() { return (isBad); } // True if last write failed.
  78. bool Good() { return (!isBad); } // True if not Bad();
  79. bool Dirty() { return (isDirty); } // True if data needs to be written.
  80. bool Enabled(const bool MakeEnabled) { return (isEnabled = MakeEnabled); } // Enables writing if true.
  81. bool Enabled() { return (isEnabled); } // True if enabled.
  82. const static cd::ThreadType Type; // The thread's type.
  83. const static cd::ThreadState DiscLogger_Flush; // Flushing state.
  84. const static cd::ThreadState DiscLogger_Wait; // Waiting state.
  85. };
  86. //// IPTestRecord //////////////////////////////////////////////////////////////
  87. // Contains a complete analysis of a given IP. snf_RulebaseHandler provides a
  88. // test facility that accepts and processes IPTestRecord objects. The calling
  89. // process can then submit the IPTestRecord along with it's action to the
  90. // snfLOGmgr for logging.
  91. class IPTestRecord { // IP Analysis Record.
  92. public:
  93. cd::IP4Address IP; // The IP to be tested.
  94. GBUdbRecord G; // The GBUdb Record for the IP.
  95. snfIPRange R; // The GBUdb classification (range).
  96. int Code; // Code associated with Range.
  97. IPTestRecord(cd::IP4Address testIP) : IP(testIP), Code(0) {} // Construct with an IP.
  98. };
  99. //// snfScanData ///////////////////////////////////////////////////////////////
  100. // Contains testing data for a message.
  101. // It's defined here in the LOGmgr module because this is the module that must
  102. // log and collect statistics for each scanned message. The snfScanData object
  103. // is the standardized way each engine reports it's scan results to snfLOGmgr.
  104. const int MaxIPsPerMessage = 50; // Maximum number of IPs to scan per message.
  105. struct IPScanRecord { // Structure for IP scan results.
  106. int Ordinal; // Which IP starting with zero.
  107. unsigned int IP; // What is the IP.
  108. GBUdbRecord GBUdbData; // GBUdb data.
  109. };
  110. class snfScanData { // Scan Data record for each message.
  111. private:
  112. IPScanRecord MyIPScanData[MaxIPsPerMessage]; // Array of IP scan results.
  113. int MyIPCount; // Count of IP scan results.
  114. bool DrillDownFlags[MaxIPsPerMessage]; // DrillDown flags. (Set Ignore).
  115. int SourceIPOrdinal; // Ordinal to source IP scan data.
  116. bool SourceIPFoundFlag; // True if source IP is set.
  117. snfIPRange SourceIPRangeFlag; // GBUdb detection range for source IP.
  118. cd::IP4Address myCallerForcedSourceIP; // Caller forced source IP if not 0UL.
  119. cd::IP4Address myHeaderDirectiveSourceIP; // Header forced source IP if not 0UL.
  120. public:
  121. snfScanData(int ScanHorizon); // Constructor.
  122. ~snfScanData(); // Destructor.
  123. // The ReadyToClear bit helps multi-phase input situations where the first
  124. // phase might add some input data before calling the base-level scanner.
  125. // In those cases, the pre-scan-phase will clear() the ScanData (and with
  126. // it the ReadyToClear bit) before adding a few critical pieces of data -
  127. // such as the scan name and the scan-start UTC for example. When the base
  128. // level scanner is called to perform the actual scan, the clear() call
  129. // will be inert so that any pre-set data will be preserved.
  130. bool ReadyToClear; // True when Logging is done.
  131. void clear(); // Clear for a new message.
  132. class NoFreeIPScanRecords {}; // Thrown when we run out of scan records.
  133. class OutOfBounds {}; // Thrown in IPScanData if no record at i.
  134. int IPScanCount(); // Return the number of IPs.
  135. IPScanRecord& newIPScanRecord(); // Get the next free IP scan record.
  136. IPScanRecord& IPScanData(int i); // Return the IP scan record i.
  137. // 20080221 _M We can now define in header directives patterns for Received
  138. // headers that we should drill past if they show up as a message source
  139. // candidate. This allows GBUdb to learn to ignore certain IPs automatically
  140. // as they arrive either by IP stubs such as "[12.34.56." or by reverse DNS
  141. // data such as "friendly.example.com [". When the header directives engine
  142. // scans the headers it will call drillPastOrdinal for any Received header
  143. // that matches a <drilldown/> directive. Later when the header analysis
  144. // engine tries to pick the source for the message it will check each source
  145. // candidate against the isDrillDownSource() method. If the source is to be
  146. // ignored then it will set the ignore flag for that IP, process it as if
  147. // it were ignored, and continue searching for the actual source.
  148. void drillPastOrdinal(int O); // Sets Drill Down flag for IP record O.
  149. bool isDrillDownSource(IPScanRecord& X); // True if we drill through this source.
  150. cd::IP4Address HeaderDirectiveSourceIP(cd::IP4Address A); // set Header directive source IP.
  151. cd::IP4Address HeaderDirectiveSourceIP(); // get Header directive source IP.
  152. cd::IP4Address CallerForcedSourceIP(cd::IP4Address A); // set Caller forced source IP.
  153. cd::IP4Address CallerForcedSourceIP(); // get Caller forced source IP.
  154. IPScanRecord& SourceIPRecord(IPScanRecord& X); // Sets the source IP record.
  155. IPScanRecord& SourceIPRecord(); // Gets the source IP record.
  156. bool FoundSourceIP(); // True if the source IP record was set.
  157. snfIPRange SourceIPRange(); // GET Source IP range.
  158. snfIPRange SourceIPRange(snfIPRange R); // SET Source IP range for this scan.
  159. // Direct access data...
  160. std::string SourceIPEvaluation; // GBUdb Source IP evaluation.
  161. // LogControl and General Message Flags
  162. time_t StartOfJobUTC; // Timestamp at start of job.
  163. int SetupTime; // Time in ms spent setting up to scan.
  164. std::string ScanName; // Identifying name or message file name.
  165. cd::Timer ScanTime; // Scan time in ms.
  166. int ScanDepth; // Scan Depth in evaluators.
  167. std::string ClassicLogText; // Classic log entry text if any.
  168. std::string XMLLogText; // XML log entry text if any.
  169. std::string XHDRsText; // XHeaders text if any.
  170. bool XHeaderInjectOn; // True if injecting headers is on.
  171. bool XHeaderFileOn; // True if creating .xhdr file is on.
  172. bool MessageFileTypeCGPOn; // Expect a CGP type message file.
  173. unsigned int ScanSize; // What size is the scan request.
  174. // GBUdb Activity Flags
  175. bool GBUdbNormalTriggered; // True if GBUdb indeterminate IP source.
  176. bool GBUdbWhiteTriggered; // True if GBUdb found source IP white.
  177. bool GBUdbWhiteSymbolForced; // True if white was on and symbol was set.
  178. bool GBUdbPatternSourceConflict; // True if pattern was found with white IP.
  179. bool GBUdbAutoPanicTriggered; // True if autopanic was triggered.
  180. bool GBUdbAutoPanicExecuted; // True if an autopanic was added.
  181. bool GBUdbBlackTriggered; // True if GBUdb found source IP black.
  182. bool GBUdbBlackSymbolForced; // True if black was on and symbol was set.
  183. bool GBUdbTruncateTriggered; // True if Truncate was possible.
  184. bool GBUdbPeekTriggered; // True if we could peek.
  185. bool GBUdbSampleTriggered; // True if we could sample.
  186. bool GBUdbTruncateExecuted; // True if we actually did truncate.
  187. bool GBUdbPeekExecuted; // True if we peeked instead of truncating.
  188. bool GBUdbSampleExecuted; // True if we sampled.
  189. bool GBUdbCautionTriggered; // True if GBUdb found source IP suspicous.
  190. bool GBUdbCautionSymbolForced; // True if caution was on and symbol was set.
  191. // Rule panics
  192. std::set<int> RulePanics; // A list of rule IDs panicked this scan.
  193. // Pattern Engine Scan Result Data
  194. std::vector<unsigned char> FilteredData; // Message data after filter chain.
  195. unsigned long int HeaderDirectiveFlags; // Flags set by header directives.
  196. bool PatternWasFound; // True if the pattern engine matched.
  197. int PatternID; // The winning rule ID.
  198. int PatternSymbol; // The associated symbol.
  199. std::list<snf_match> MatchRecords; // List of match records.
  200. std::list<snf_match>::iterator MatchRecordsCursor; // Localized iterator for match records.
  201. int MatchRecordsDelivered; // Match records seen so far.
  202. int CompositeFinalResult; // What the scan function returned.
  203. };
  204. //// SMHDMY counter
  205. //
  206. // Provides a running SUM for a series of sliding windows. The input() expects
  207. // a new piece of data every second (or so). It is presumed that another counter
  208. // will keep track of the actual milliseconds if accuracy is required. The object
  209. // is all primative data parts so it is possible to store and retrieve this object
  210. // in binary format on the same system when that's helpful.
  211. class snf_SMHDMY_Counter { // Sliding window "live" counter.
  212. private:
  213. bool do_input(int X, int& SUM, int* DATA, int& ORDINAL, int SIZE); // Subroutine for assimilating input.
  214. public:
  215. snf_SMHDMY_Counter() { // When making a new one, reset all
  216. memset(this, 0, sizeof(snf_SMHDMY_Counter)); // data to zero. It's all ints ;-)
  217. }
  218. // 60 seconds is a minute (6 x 10)
  219. int SEC6DATA[6], SEC6SUM, SEC6ORDINAL;
  220. int SEC10DATA[10], SEC10SUM, SEC10ORDINAL;
  221. // 60 minutes is an hour (6 x 10)
  222. int MIN6DATA[6], MIN6SUM, MIN6ORDINAL;
  223. int MIN10DATA[10], MIN10SUM, MIN10ORDINAL;
  224. // 24 hours is a day (4 x 6)
  225. int HOUR4DATA[4], HOUR4SUM, HOUR4ORDINAL;
  226. int HOUR6DATA[6], HOUR6SUM, HOUR6ORDINAL;
  227. // 7 days is a week (7)
  228. int WEEK7DATA[7], WEEK7SUM, WEEK7ORDINAL;
  229. // 30 days is a month (5 x 6)
  230. int MONTH5DATA[5], MONTH5SUM, MONTH5ORDINAL;
  231. int MONTH6DATA[6], MONTH6SUM, MONTH6ORDINAL;
  232. // 12 months (almost) is a year (3 x 4)
  233. int YEAR3DATA[3], YEAR3SUM, YEAR3ORDINAL;
  234. int YEAR4DATA[4], YEAR4SUM, YEAR4ORDINAL;
  235. // 365 days is a year
  236. int YEAR365DATA[365], YEAR365SUM, YEAR365ORDINAL;
  237. void input(int X); // Add new data to the counter.
  238. bool Cycled60Seconds() { return (0 == SEC6ORDINAL && 0 == SEC10ORDINAL); } // Full cycle of data for seconds.
  239. int Sum60Seconds() { return SEC10SUM; }
  240. int Sum66Seconds() { return (SEC6SUM + SEC10SUM); }
  241. int SumThru1Minute() { return Sum66Seconds(); } // All samples thru one minute.
  242. bool Cycled60Minutes() { // Full cycle of data for minutes.
  243. return (Cycled60Seconds() && 0 == MIN6ORDINAL && 0 == MIN10ORDINAL);
  244. }
  245. int Sum60Minutes() { return MIN10SUM; }
  246. int Sum66Minutes() { return (MIN6SUM + MIN10SUM); }
  247. int SumThru1Hour() { return SumThru1Minute() + Sum66Minutes(); } // All samples thru one hour.
  248. bool Cycled24Hours() { // Full cycle of data for hours.
  249. return (Cycled60Minutes() && 0 == HOUR4ORDINAL && 0 == HOUR6ORDINAL);
  250. }
  251. int Sum24Hours() { return HOUR6SUM; }
  252. int Sum28Hours() { return (HOUR4SUM + HOUR6SUM); }
  253. int SumThru1Day() { return SumThru1Hour() + Sum28Hours(); } // All samples thru one day.
  254. bool Cycled7Days() { return (Cycled24Hours() && 0 == WEEK7ORDINAL); } // Full cycle of data for week.
  255. int Sum7Days() { return WEEK7SUM; }
  256. int SumThru1Week() { return SumThru1Day() + Sum7Days(); } // All samples thru one week.
  257. bool Cycled30Days() { // Full cycle of data for month.
  258. return (Cycled24Hours() && 0 == MONTH6ORDINAL && 0 == MONTH5ORDINAL);
  259. }
  260. int Sum30Days() { return MONTH6SUM; }
  261. int Sum35Days() { return (MONTH5SUM + MONTH6SUM); }
  262. int SumThru1Month() { return SumThru1Day() + Sum35Days(); } // All samples thu one month.
  263. bool Cycled12Months() { // Full cycle of data for 12 months.
  264. return (Cycled30Days() && 0 == YEAR3ORDINAL && 0 == YEAR4ORDINAL);
  265. }
  266. int Sum450Days() { return (YEAR3SUM + YEAR4SUM); }
  267. int SumThru1Year() { return SumThru1Month() + Sum450Days(); } // All samples thru one year.
  268. bool Cycled365Days() { return (Cycled24Hours() && 0 == YEAR365ORDINAL); } // Full cycle of data for 365 days.
  269. int Sum365Days() { return YEAR365SUM; }
  270. };
  271. //// snfLOGmgr /////////////////////////////////////////////////////////////////
  272. // A note about the LOG manager and configuration data:
  273. // Events that are logged with the log manager may come from scans using
  274. // different configurations. In order to keep things as sane as possible,
  275. // operations that are dependent on configuration information such as creating
  276. // log file entries or producing status page data will require that an
  277. // appropriate snfCFGData object be provided by reference and that the
  278. // snfCFGData object be guaranteed to remain stable for the duration of the
  279. // call. Changing snfCFGData may result in inconsistent results.
  280. //
  281. // This requirement is fairly easy to accomplish since posts to the LOGmgr
  282. // will come from scanning engines that have a snfCFGPacket "grab()ed" during
  283. // their operations, and executive requests will come from the ruelbase
  284. // manager which can grab a snfCFGPacket for the duration of the request.
  285. const int NumberOfResultCodes = 64;
  286. class snfCounterPack {
  287. public:
  288. snfCounterPack(); // Construct new CounterPacks clean.
  289. void reset(); // How to reset a counter pack.
  290. cd::Timer ActiveTime; // Measures Active (swapped in) Time.
  291. struct {
  292. unsigned long Scans; // Number of messages scanned.
  293. unsigned long Spam; // Count of spam results.
  294. unsigned long Ham; // Count of ham results.
  295. unsigned long GBUdbNormalTriggered; // Count of indeterminate gbudb IP hits.
  296. unsigned long GBUdbWhiteTriggered; // Count of GBUdb found source IP white.
  297. unsigned long GBUdbWhiteSymbolForced; // Count of white was on and symbol was set.
  298. unsigned long GBUdbPatternSourceConflict; // Count of pattern was found with white IP.
  299. unsigned long GBUdbAutoPanicTriggered; // Count of autopanic was triggered.
  300. unsigned long GBUdbAutoPanicExecuted; // Count of an autopanic was added.
  301. unsigned long GBUdbBlackTriggered; // Count of GBUdb found source IP black.
  302. unsigned long GBUdbBlackSymbolForced; // Count of black was on and symbol was set.
  303. unsigned long GBUdbTruncateTriggered; // Count of Truncate was possible.
  304. unsigned long GBUdbPeekTriggered; // Count of we could peek.
  305. unsigned long GBUdbSampleTriggered; // Count of we could sample.
  306. unsigned long GBUdbTruncateExecuted; // Count of if we actually did truncate.
  307. unsigned long GBUdbPeekExecuted; // Count of we peeked instead of truncating.
  308. unsigned long GBUdbSampleExecuted; // Count of we sampled.
  309. unsigned long GBUdbCautionTriggered; // Count of GBUdb found source IP suspicous.
  310. unsigned long GBUdbCautionSymbolForced; // Count of caution was on and symbol was set.
  311. unsigned long PatternWasFound; // Count of scanner matches.
  312. unsigned long RulePanicFound; // Count of rule panics.
  313. } Events;
  314. };
  315. //// Interval timers precisely track the time between hack()s. There are
  316. //// two timers inside. One is active, the other is stopped. Each time hack()
  317. //// is called, one timer becomes active at the moment the other is stopped.
  318. class IntervalTimer { // Precision interval timer.
  319. private:
  320. cd::Timer A; // Here is one timer.
  321. cd::Timer B; // Here is the other timer.
  322. bool ANotB; // True if A is the active timer.
  323. cd::Timer& Active(); // Selects the active timer.
  324. cd::Timer& Inactive(); // Selects the inactive timer.
  325. public:
  326. cd::msclock hack(); // Chop off a new interval & return it.
  327. cd::msclock Interval(); // Return the last interval.
  328. cd::msclock Elapsed(); // Return the time since last hack.
  329. };
  330. //// PersistentState stores the counters we keep between runs.
  331. class snfLOGPersistentState {
  332. public:
  333. snfLOGPersistentState() :
  334. Ready(0),
  335. LastSyncTime(0),
  336. LastSaveTime(0),
  337. LastCondenseTime(0),
  338. LatestRuleID(0),
  339. SerialNumberCounter(0) {}
  340. bool Ready; // True if we're ready to use.
  341. void store(std::string& FileNameToStore); // Write the whole thing to a file.
  342. void restore(std::string& FileNameToRestore); // Read the whole thing from a file.
  343. time_t LastSyncTime; // time_t of last Sync event.
  344. time_t LastSaveTime; // time_t of last GBUdb Save event.
  345. time_t LastCondenseTime; // time_t of last GBUdb Condense event.
  346. int LatestRuleID; // Latest rule ID seen so far.
  347. int SerialNumberCounter; // Remembers the serial number.
  348. };
  349. class snfLOGmgr : private cd::Thread {
  350. private:
  351. cd::Mutex MyMutex; // Mutex to serialize updates & queries.
  352. cd::Mutex ConfigMutex; // Mutex to protect config changes.
  353. cd::Mutex SerialNumberMutex; // Protects the serial number.
  354. cd::Mutex PeekMutex; // Protects Peek Loop Counter.
  355. cd::Mutex SampleMutex; // Protects Sample Loop Counter.
  356. cd::Mutex StatusReportMutex; // Protects status report post & get.
  357. snfCounterPack CounterPackA, CounterPackB; // Swapable counter packs.
  358. snfCounterPack* CurrentCounters; // Current Event Counters.
  359. snfCounterPack* ReportingCounters; // Counters being used to collect data.
  360. snfCounterPack* getSnapshot(); // Get a copy of the current counters.
  361. volatile bool Configured; // True if we're properly configured.
  362. volatile bool TimeToDie; // True when the thread should stop.
  363. volatile int PeekEnableCounter; // How many peek attempts recently?
  364. volatile int SampleEnableCounter; // How many sample attempts recently?
  365. void myTask(); // Thread task.
  366. time_t StartupTime; // Time since engine started.
  367. snfLOGPersistentState Status; // Persistent State Data.
  368. std::string PersistentFileName; // File name for the State Data.
  369. snfNETmgr* myNETmgr; // Net manager link.
  370. GBUdb* myGBUdb; // GBUdb link.
  371. // Configuration
  372. std::string ActiveRulebaseUTC; // UTC of last successful load.
  373. std::string AvailableRulebaseUTC; // UTC of rulebase available for update.
  374. bool NewerRulebaseIsAvailable; // True if a newer rulebase is available.
  375. std::string myPlatformVersion; // Version info for platform.
  376. bool Rotate_LocalTime; // Rotate logs using localtime.
  377. std::string LogsPath; // Path to logs directory.
  378. bool ClassicLogRotate; // True = Rotate Classic Log.
  379. bool XMLLogRotate; // True = Rotate XML Log.
  380. // Live stats
  381. snf_SMHDMY_Counter MessageCounter;
  382. snf_SMHDMY_Counter HamCounter;
  383. snf_SMHDMY_Counter SpamCounter;
  384. snf_SMHDMY_Counter WhiteCounter;
  385. snf_SMHDMY_Counter CautionCounter;
  386. snf_SMHDMY_Counter BlackCounter;
  387. snf_SMHDMY_Counter TruncateCounter;
  388. snf_SMHDMY_Counter SampleCounter;
  389. snf_SMHDMY_Counter AutoPanicCounter;
  390. snf_SMHDMY_Counter RulePanicCounter;
  391. snf_SMHDMY_Counter TimeCounter;
  392. // Histograms
  393. cd::Histogram ResultsSecond;
  394. cd::Histogram ResultsMinute;
  395. cd::Histogram ResultsHour;
  396. cd::Histogram RulesSecond;
  397. cd::Histogram RulesMinute;
  398. cd::Histogram RulesHour;
  399. cd::Histogram PanicsSecond;
  400. cd::Histogram PanicsMinute;
  401. cd::Histogram PanicsHour;
  402. // Reporting
  403. std::string NodeId; // We need this for our status msgs.
  404. void do_StatusReports(); // Update & sequence status reports.
  405. int XML_Log_Mode; // What is the XML log mode.
  406. int Classic_Log_Mode; // What is the Classic log mode.
  407. // Every second we get the basics and collect data. (local only)
  408. bool SecondReport_Log_OnOff;
  409. bool SecondReport_Append_OnOff;
  410. std::string SecondReport_Log_Filename;
  411. std::string SecondReportText;
  412. std::string SecondReportTimestamp;
  413. bool do_SecondReport(); // Send our 1 second status report.
  414. // Every minute we get hard data and event logs. (for sync)
  415. bool MinuteReport_Log_OnOff;
  416. bool MinuteReport_Append_OnOff;
  417. std::string MinuteReport_Log_Filename;
  418. std::string MinuteReportText;
  419. std::string MinuteReportTimestamp;
  420. cd::Histogram PatternRulesHistogram;
  421. bool do_MinuteReport(); // Send our 1 minute status report.
  422. // Every hour we get a summary.
  423. bool HourReport_Log_OnOff;
  424. bool HourReport_Append_OnOff;
  425. std::string HourReport_Log_Filename;
  426. std::string HourReportText;
  427. std::string HourReportTimestamp;
  428. bool do_HourReport(); // Send our 1 hour status report.
  429. void postStatusLog( // Post a Status log if required.
  430. const std::string& LogData, // Here's the log entry's data.
  431. const std::string& LogFileName, // Here is where it should go.
  432. const bool LogEnabled, // This is true if we should write it.
  433. const bool AppendNotOverwrite, // True=Append, False=Overwrite.
  434. DiscLogger& Logger // Lazy Log Writer to use.
  435. );
  436. DiscLogger SecondStatusLogger; // Lazy writer for Second status.
  437. DiscLogger MinuteStatusLogger; // Lazy writer for Minute status.
  438. DiscLogger HourStatusLogger; // Lazy writer for Hour status.
  439. DiscLogger XMLScanLogger; // Lazy writer for XML Scan log.
  440. DiscLogger ClassicScanLogger; // Lazy writer for Classic Scan log.
  441. void doXHDRs(snfCFGData& CFGData, snfScanData& ScanData); // XHDR sub routine for LogThisScan()
  442. void doXMLLogs(snfCFGData& CFGData, snfScanData& ScanData); // XML sub routine for LogThisScan()
  443. void doClassicLogs(snfCFGData& CFGData, snfScanData& ScanData); // Classic sub routine for LogThisScan()
  444. void captureLTSMetrics(snfCFGData& CFGData, snfScanData& ScanData); // LogThisScan section 1, Locked.
  445. void performLTSLogging(snfCFGData& CFGData, snfScanData& ScanData); // LogThisScan section 2, Unlocked.
  446. public:
  447. snfLOGmgr(); // Initialize & start the thread.
  448. ~snfLOGmgr(); // Stop the thread & clean up.
  449. void stop(); // Stops the manager.
  450. void linkNETmgr(snfNETmgr& N); // Link in my NETmgr
  451. void linkGBUdb(GBUdb& G); // Link in my GBUdb
  452. void configure(snfCFGData& CFGData); // Update the configuration.
  453. void updateActiveUTC(std::string ActiveUTC); // Set active rulebase UTC.
  454. void logThisIPTest(IPTestRecord& I, std::string Action); // Capthre the data from an IP test.
  455. void logThisScan(snfCFGData& CFGData, snfScanData& ScanData); // Capture the data from this scan.
  456. void logThisError(snfScanData& ScanData, const std::string ContextName, // Inject an error log entry for this
  457. const int Code, const std::string Text // scan using this number & message.
  458. );
  459. void logThisError(std::string ContextName, int Code, std::string Text); // Log an error message.
  460. void logThisInfo(std::string ContextName, int Code, std::string text); // Log an informational message.
  461. std::string PlatformVersion(std::string NewPlatformVersion); // Set platform version info.
  462. std::string PlatformVersion(); // Get platform version info.
  463. std::string EngineVersion(); // Get engine version info.
  464. void updateAvailableUTC(std::string& AvailableRulebaseTimestamp); // Stores Available, true==update ready.
  465. std::string ActiveRulebaseTimestamp(); // Get active rulebase timestamp.
  466. std::string AvailableRulebaseTimestamp(); // Get available rulebase timestamp.
  467. bool isUpdateAvailable(); // True if update is available.
  468. bool OkToPeek(int PeekOneInX); // Check to see if it's ok to peek.
  469. bool OkToSample(int SampleOneInX); // Check to see if it's ok to sample.
  470. time_t Timestamp(); // Get an ordinary timestamp.
  471. std::string Timestamp(time_t t); // Convert time_t to a timestamp s.
  472. std::string& Timestamp(std::string& s); // Appends a current timestamp in s.
  473. std::string LocalTimestamp(time_t t); // Convert time_t to a local timestamp s.
  474. std::string& LocalTimestamp(std::string& s); // Appends a current local timestamp in s.
  475. unsigned int SerialNumber(); // Returns the next serial number.
  476. std::string& SerialNumber(std::string& s); // Appends the next serial number.
  477. int SecsSinceStartup(); // Gets seconds since starup.
  478. void RecordSyncEvent(); // Sets timestamp of latest Sync.
  479. int SecsSinceLastSync(); // Gets seconds since latest Sync.
  480. void RecordSaveEvent(); // Sets timestamp of latest Save.
  481. int SecsSinceLastSave(); // Gets seconds since latest Save.
  482. void RecordCondenseEvent(); // Sets timestamp of latest Condense.
  483. int SecsSinceLastCondense(); // Gets seconds since latest Condense.
  484. // Live stats functions
  485. double MessagesPerMinute(); // Avg Msgs/Minute.
  486. double HamPerMinute(); // Avg Ham/Minute.
  487. double SpamPerMinute(); // Avg Spam/Minute.
  488. double WhitePerMinute(); // Avg White/Minute.
  489. double CautionPerMinute(); // Avg Caution/Minute.
  490. double BlackPerMinute(); // Avg Black/Minute.
  491. double TruncatePerMinute(); // Avg Truncate/Minute.
  492. double SamplePerMinute(); // Avg Sample/Minute.
  493. int LatestRuleID(); // Returns the latest Rule ID seen.
  494. int RunningTime(); // Seconds running since startup.
  495. std::string getStatusSecondReport(); // Get latest status.second report.
  496. std::string getStatusMinuteReport(); // Get latest status.minute report.
  497. std::string getStatusHourReport(); // Get latest status.hour report.
  498. const static cd::ThreadType Type; // The thread's type.
  499. };
  500. //// End snfLOGmgr include only once
  501. ////////////////////////////////////////////////////////////////////////////////