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

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