git-svn-id: https://svn.microneil.com/svn/SNFMulti/branches/adeniz_1@60 dc71a809-1921-45c4-985c-09c81d0142d9adeniz_1
// from the use of switch(State) mechanisms to the use of function pointers. This | // from the use of switch(State) mechanisms to the use of function pointers. This | ||||
// should save a few cycles on every byte processed. | // should save a few cycles on every byte processed. | ||||
#include "FilterChain.hpp" | |||||
#include "SNFMulti/FilterChain.hpp" | |||||
using namespace std; | |||||
namespace SNFMulti { | |||||
// FilterChainBase64 Methods. | // FilterChainBase64 Methods. | ||||
} // If we have a normal byte then we | } // If we have a normal byte then we | ||||
return c; // return it. | return c; // return it. | ||||
} | } | ||||
} |
#include <cctype> | #include <cctype> | ||||
using namespace std; | |||||
namespace SNFMulti { | |||||
// Define parameters for this module. | // Define parameters for this module. | ||||
public: | public: | ||||
class BadSource : public invalid_argument { // Bad Source Exception. | |||||
public: BadSource(const string& w):invalid_argument(w){} | |||||
class BadSource : public std::invalid_argument { // Bad Source Exception. | |||||
public: BadSource(const std::string& w):std::invalid_argument(w){} | |||||
}; | }; | ||||
class Empty : public underflow_error { // Empty Exception. | |||||
public: Empty(const string& w):underflow_error(w){} | |||||
class Empty : public std::underflow_error { // Empty Exception. | |||||
public: Empty(const std::string& w):std::underflow_error(w){} | |||||
}; | }; | ||||
virtual unsigned char GetByte() { // Return either 0 | virtual unsigned char GetByte() { // Return either 0 | ||||
private: | private: | ||||
istream* SourceIstream; | |||||
std::istream* SourceIstream; | |||||
public: | public: | ||||
// Here we overload the constructor to accept a stream. | // Here we overload the constructor to accept a stream. | ||||
FilterChainInput(istream* S){ // Build me with a stream. | |||||
FilterChainInput(std::istream* S){ // Build me with a stream. | |||||
if(NULL==S) throw BadSource("FilterChainInput: Null source not valid" ); // If it's NULL that's bad. | if(NULL==S) throw BadSource("FilterChainInput: Null source not valid" ); // If it's NULL that's bad. | ||||
if(!S->good()) throw BadSource("FilterChainInput: Bad istream"); // Not good is bad. | if(!S->good()) throw BadSource("FilterChainInput: Bad istream"); // Not good is bad. | ||||
else SourceIstream = S; // If it's good we keep it. | else SourceIstream = S; // If it's good we keep it. | ||||
unsigned int BufferLength; | unsigned int BufferLength; | ||||
unsigned int BufferIndex; | unsigned int BufferIndex; | ||||
stringstream& PrependedHeaders; | |||||
std::stringstream& PrependedHeaders; | |||||
bool PrependNotBuffer; | bool PrependNotBuffer; | ||||
// Here we overload the constructor to accept a stream. | // Here we overload the constructor to accept a stream. | ||||
FilterChainCBFR(unsigned char* S, int l, stringstream& P) : // Give me a bfr and a stringstream. | |||||
FilterChainCBFR(unsigned char* S, int l, std::stringstream& P) : // Give me a bfr and a stringstream. | |||||
InputBuffer(S), // Grab the buffer, | InputBuffer(S), // Grab the buffer, | ||||
BufferLength(l), // Grab the buffer length, | BufferLength(l), // Grab the buffer length, | ||||
BufferIndex(0), // Initialize the index to 0, | BufferIndex(0), // Initialize the index to 0, | ||||
class FilterChainIPTester { | class FilterChainIPTester { | ||||
public: | public: | ||||
virtual string& test(string& input, string& output) = 0; | |||||
virtual std::string& test(std::string& input, std::string& output) = 0; | |||||
}; | }; | ||||
// The supplied test() function accepts the input string and returns the | // The supplied test() function accepts the input string and returns the | ||||
unsigned char (FilterChainHeaderAnalysis::*Mode)(); // Internal State Fn Pointer (What Mode) | unsigned char (FilterChainHeaderAnalysis::*Mode)(); // Internal State Fn Pointer (What Mode) | ||||
FilterChainIPTester& IPTester; // This is the IP tester we use. | FilterChainIPTester& IPTester; // This is the IP tester we use. | ||||
string IPToTest; // String to capture IPs for testing. | |||||
string IPTestResult; // String to receive IPtest results. | |||||
std::string IPToTest; // String to capture IPs for testing. | |||||
std::string IPTestResult; // String to receive IPtest results. | |||||
// Header analysis output state... | // Header analysis output state... | ||||
string EndOfHeaderResults; // String to capture EndOfHeaderResults. | |||||
std::string EndOfHeaderResults; // String to capture EndOfHeaderResults. | |||||
// OutputIndex and OutputLength are used to inject string data. | // OutputIndex and OutputLength are used to inject string data. | ||||
// These are used to inject IPTestResult data and Header Analysis data. | // These are used to inject IPTestResult data and Header Analysis data. | ||||
char* OutputBuffer; // Pointer to output injection string. | char* OutputBuffer; // Pointer to output injection string. | ||||
int OutputIndex; // End of header output results index. | int OutputIndex; // End of header output results index. | ||||
void SetOutputBuffer(string& s); // Setup the OutputBuffer. | |||||
void SetOutputBuffer(std::string& s); // Setup the OutputBuffer. | |||||
unsigned char doInjectIPTestResult(); // Inject OutputBuffer and go to doSeekNL. | unsigned char doInjectIPTestResult(); // Inject OutputBuffer and go to doSeekNL. | ||||
unsigned char doInjectAnalysis(); // Inject OutputBuffer and go to doOff. | unsigned char doInjectAnalysis(); // Inject OutputBuffer and go to doOff. | ||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif |
#include <fstream> | #include <fstream> | ||||
#include <cstring> | #include <cstring> | ||||
#include <unistd.h> | #include <unistd.h> | ||||
#include "GBUdb.hpp" | |||||
#include "SNFMulti/GBUdb.hpp" | |||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
//// Handy utilities... | //// Handy utilities... | ||||
namespace SNFMulti { | |||||
//// GBUdbDataset implementations ////////////////////////////////////////////// | //// GBUdbDataset implementations ////////////////////////////////////////////// | ||||
GBUdbDataset::~GBUdbDataset() { // Shutdown a dataset. | GBUdbDataset::~GBUdbDataset() { // Shutdown a dataset. | ||||
return IPCount; // Always return the number of lines read. | return IPCount; // Always return the number of lines read. | ||||
} | } | ||||
} |
#ifndef M_GBUdb | #ifndef M_GBUdb | ||||
#define M_GBUdb | #define M_GBUdb | ||||
#include "../CodeDweller/faults.hpp" | |||||
#include "../CodeDweller/threading.hpp" | |||||
#include "CodeDweller/faults.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include <cmath> | #include <cmath> | ||||
#include <cctype> | #include <cctype> | ||||
#include <string> | #include <string> | ||||
#include <cstdlib> | #include <cstdlib> | ||||
#include <ctime> | #include <ctime> | ||||
using namespace std; | |||||
namespace SNFMulti { | |||||
const unsigned int GBUdbFlagsMask = 0xC0000000; // Top 2 bits are the flag. | const unsigned int GBUdbFlagsMask = 0xC0000000; // Top 2 bits are the flag. | ||||
const unsigned int GBUdbIgnore = 0xC0000000; // Ignore is the 11 flag. | const unsigned int GBUdbIgnore = 0xC0000000; // Ignore is the 11 flag. | ||||
char UTC[UTCBufferSize]; // Time stamp for this alert. | char UTC[UTCBufferSize]; // Time stamp for this alert. | ||||
unsigned int IP; // IP for this alert. | unsigned int IP; // IP for this alert. | ||||
GBUdbRecord R; // GBUdbRecord for this alert. | GBUdbRecord R; // GBUdbRecord for this alert. | ||||
string toXML(); // Convert to an xml representation. | |||||
std::string toXML(); // Convert to an xml representation. | |||||
}; | }; | ||||
// Mass update kinds of operations are handled by providing a functor | // Mass update kinds of operations are handled by providing a functor | ||||
private: | private: | ||||
GBUdbRecord* DataArray; // Array of GBUdbRecords, nodes, etc. | GBUdbRecord* DataArray; // Array of GBUdbRecords, nodes, etc. | ||||
int MyArraySize; // The size of the array in records. | int MyArraySize; // The size of the array in records. | ||||
string MyFileName; // CString for the file name. | |||||
std::string MyFileName; // CString for the file name. | |||||
GBUdbIndex ixIPCount(); // Index of the IP count for this db. | GBUdbIndex ixIPCount(); // Index of the IP count for this db. | ||||
GBUdbIndex ixNextFreeNode(); // Index of the Next Free Node Index. | GBUdbIndex ixNextFreeNode(); // Index of the Next Free Node Index. | ||||
class GBUdb { | class GBUdb { | ||||
private: | private: | ||||
Mutex MyMutex; // Data sync mutex. | |||||
Mutex AlertsMutex; // Mutex for the alerts list. | |||||
CodeDweller::Mutex MyMutex; // Data sync mutex. | |||||
CodeDweller::Mutex AlertsMutex; // Mutex for the alerts list. | |||||
GBUdbDataset* MyDataset; // Array of records. | GBUdbDataset* MyDataset; // Array of records. | ||||
int PostsCounter; // Counts good/bad posts. | int PostsCounter; // Counts good/bad posts. | ||||
list<GBUdbAlert> MyAlerts; // Allerts list. | |||||
std::list<GBUdbAlert> MyAlerts; // Allerts list. | |||||
void recordAlertFor(unsigned int IP, GBUdbRecord& R, unsigned int C); // Append an alert record if needed. | void recordAlertFor(unsigned int IP, GBUdbRecord& R, unsigned int C); // Append an alert record if needed. | ||||
public: | public: | ||||
int readIgnoreList(const char* FileName = "GBUdbIgnoreList.txt"); // setIgnore for a list of IPs | int readIgnoreList(const char* FileName = "GBUdbIgnoreList.txt"); // setIgnore for a list of IPs | ||||
void GetAlerts(list<GBUdbAlert>& ListToFill); // Get all current alerts & clear. | |||||
void ImportAlerts(list<GBUdbAlert>& PeerAlerts); // Default log2 alert import function. | |||||
void GetAlerts(std::list<GBUdbAlert>& ListToFill); // Get all current alerts & clear. | |||||
void ImportAlerts(std::list<GBUdbAlert>& PeerAlerts); // Default log2 alert import function. | |||||
int IPCount(); // Number of IPs stored. | int IPCount(); // Number of IPs stored. | ||||
int Size(); // Size of GBUdb in bytes. | int Size(); // Size of GBUdb in bytes. | ||||
#include "GBUdb.inline.hpp" | #include "GBUdb.inline.hpp" | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||
// End of GBUdb Include Only Once | // End of GBUdb Include Only Once |
} | } | ||||
inline void GBUdb::save() { // Save the data. | inline void GBUdb::save() { // Save the data. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
MyDataset->save(); // Save the dataset. | MyDataset->save(); // Save the dataset. | ||||
PostsCounter = 0; // Reset the posts counter. | PostsCounter = 0; // Reset the posts counter. | ||||
} | } | ||||
inline void GBUdb::load() { // Load the data. | inline void GBUdb::load() { // Load the data. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
MyDataset->load(); // Load the dataset. | MyDataset->load(); // Load the dataset. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::addGood(unsigned int IP, int i) { // Count an IP as good. | inline GBUdbRecord GBUdb::addGood(unsigned int IP, int i) { // Count an IP as good. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
++PostsCounter; // Count this as a post. | ++PostsCounter; // Count this as a post. | ||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the record. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the record. | ||||
unsigned int C = X.addGood(i); // Add a count to the good side. | unsigned int C = X.addGood(i); // Add a count to the good side. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::addBad(unsigned int IP, int i) { // Count an IP as bad. | inline GBUdbRecord GBUdb::addBad(unsigned int IP, int i) { // Count an IP as bad. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
++PostsCounter; // Count this as a post. | ++PostsCounter; // Count this as a post. | ||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | ||||
unsigned int C = X.addBad(i); // Add a count to the bad side. | unsigned int C = X.addBad(i); // Add a count to the bad side. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::setGood(unsigned int IP) { // Set the flag to Good for this IP. | inline GBUdbRecord GBUdb::setGood(unsigned int IP) { // Set the flag to Good for this IP. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | ||||
X.Flag(Good); // Set the Good flag. | X.Flag(Good); // Set the Good flag. | ||||
return X; // Return a copy for analysis. | return X; // Return a copy for analysis. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::setBad(unsigned int IP) { // Set the flag to Bad for this IP. | inline GBUdbRecord GBUdb::setBad(unsigned int IP) { // Set the flag to Bad for this IP. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | ||||
X.Flag(Bad); // Set the Bad flag. | X.Flag(Bad); // Set the Bad flag. | ||||
return X; // Return a copy for analysis. | return X; // Return a copy for analysis. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::setUgly(unsigned int IP) { // Set the flag to Ugly for this IP. | inline GBUdbRecord GBUdb::setUgly(unsigned int IP) { // Set the flag to Ugly for this IP. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | ||||
X.Flag(Ugly); // Set the Ugly flag. | X.Flag(Ugly); // Set the Ugly flag. | ||||
return X; // Return a copy for analysis. | return X; // Return a copy for analysis. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::setIgnore(unsigned int IP) { // Set the flag to Ignore for this IP. | inline GBUdbRecord GBUdb::setIgnore(unsigned int IP) { // Set the flag to Ignore for this IP. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | ||||
X.Flag(Ignore); // Set the Ignore flag. | X.Flag(Ignore); // Set the Ignore flag. | ||||
return X; // Return a copy for analysis. | return X; // Return a copy for analysis. | ||||
inline GBUdbRecord GBUdb::getRecord(unsigned int IP) { // Retrieve an IP record. | inline GBUdbRecord GBUdb::getRecord(unsigned int IP) { // Retrieve an IP record. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
GBUdbRecord& X = MyDataset->readRecord(IP); // ReadOnly the reocrd. | GBUdbRecord& X = MyDataset->readRecord(IP); // ReadOnly the reocrd. | ||||
return X; // Return a copy for analysis. | return X; // Return a copy for analysis. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::setRecord(unsigned int IP, GBUdbRecord& R) { // Store an IP record. | inline GBUdbRecord GBUdb::setRecord(unsigned int IP, GBUdbRecord& R) { // Store an IP record. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Invoke the reocrd. | ||||
X = R; // Overwrite X with R. | X = R; // Overwrite X with R. | ||||
return X; // Return a copy for analysis. | return X; // Return a copy for analysis. | ||||
} | } | ||||
inline GBUdbRecord GBUdb::adjustCounts(unsigned int IP, GBUdbRecord& R) { // Adds counts from R to record for IP. | inline GBUdbRecord GBUdb::adjustCounts(unsigned int IP, GBUdbRecord& R) { // Adds counts from R to record for IP. | ||||
ScopeMutex JustMe(MyMutex); // Lock the data for this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the data for this operation. | |||||
GBUdbRecord& X = MyDataset->invokeRecord(IP); // Locate the record in the data. | GBUdbRecord& X = MyDataset->invokeRecord(IP); // Locate the record in the data. | ||||
X.Bad(X.Bad() + R.Bad()); // Add the reflected adjustments | X.Bad(X.Bad() + R.Bad()); // Add the reflected adjustments | ||||
X.Good(X.Good() + R.Good()); // to the good and bad counts. | X.Good(X.Good() + R.Good()); // to the good and bad counts. | ||||
} | } | ||||
inline bool GBUdb::dropRecord(unsigned int IP) { // Drop an IP record. | inline bool GBUdb::dropRecord(unsigned int IP) { // Drop an IP record. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
return MyDataset->dropRecord(IP); // Pass on this call to our dataset. | return MyDataset->dropRecord(IP); // Pass on this call to our dataset. | ||||
} | } | ||||
inline int GBUdb::IPCount() { // Number of IPs stored. | inline int GBUdb::IPCount() { // Number of IPs stored. | ||||
ScopeMutex JustMe(MyMutex); | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); | |||||
return MyDataset->IPCount(); | return MyDataset->IPCount(); | ||||
} | } | ||||
inline int GBUdb::Size() { // Size of GBUdb in bytes. | inline int GBUdb::Size() { // Size of GBUdb in bytes. | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
return MyDataset->ArraySize() * sizeof(GBUdbRecord); // Total records converted to bytes. | return MyDataset->ArraySize() * sizeof(GBUdbRecord); // Total records converted to bytes. | ||||
} | } | ||||
inline double GBUdb::Utilization() { // Utilization (percent). | inline double GBUdb::Utilization() { // Utilization (percent). | ||||
ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
CodeDweller::ScopeMutex JustMe(MyMutex); // Lock the mutex during this operation. | |||||
int TotalRecords = MyDataset->ArraySize(); // Calculate the total number of records. | int TotalRecords = MyDataset->ArraySize(); // Calculate the total number of records. | ||||
int FreeRecords = MyDataset->FreeNodes() * GBUdbRecordsPerNode; // Calculate the number of unused records. | int FreeRecords = MyDataset->FreeNodes() * GBUdbRecordsPerNode; // Calculate the number of unused records. | ||||
int UsedRecords = TotalRecords - FreeRecords; // Calcualte the number of used records. | int UsedRecords = TotalRecords - FreeRecords; // Calcualte the number of used records. |
//#include "../nvwa-0.6/nvwa/debug_new.h" | //#include "../nvwa-0.6/nvwa/debug_new.h" | ||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
//// Version Info | //// Version Info | ||||
return DepthResult; // Return the results. | return DepthResult; // Return the results. | ||||
} | } | ||||
} |
#include <sys/stat.h> | #include <sys/stat.h> | ||||
#include <ctime> | #include <ctime> | ||||
#include <string> | #include <string> | ||||
#include "../CodeDweller/faults.hpp" | |||||
#include "../CodeDweller/threading.hpp" | |||||
#include "GBUdb.hpp" | |||||
#include "FilterChain.hpp" | |||||
#include "snf_engine.hpp" | |||||
#include "snf_match.h" | |||||
#include "snfCFGmgr.hpp" | |||||
#include "snfLOGmgr.hpp" | |||||
#include "snfNETmgr.hpp" | |||||
#include "snfGBUdbmgr.hpp" | |||||
#include "snfXCImgr.hpp" | |||||
#include "snf_saccades.hpp" | |||||
#include "CodeDweller/faults.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include "SNFMulti/GBUdb.hpp" | |||||
#include "SNFMulti/FilterChain.hpp" | |||||
#include "SNFMulti/snf_engine.hpp" | |||||
#include "SNFMulti/snf_match.h" | |||||
#include "SNFMulti/snfCFGmgr.hpp" | |||||
#include "SNFMulti/snfLOGmgr.hpp" | |||||
#include "SNFMulti/snfNETmgr.hpp" | |||||
#include "SNFMulti/snfGBUdbmgr.hpp" | |||||
#include "SNFMulti/snfXCImgr.hpp" | |||||
#include "SNFMulti/snf_saccades.hpp" | |||||
#include <cassert> | #include <cassert> | ||||
namespace SNFMulti { | |||||
extern const char* SNF_ENGINE_VERSION; | extern const char* SNF_ENGINE_VERSION; | ||||
// snf Result Code Constants | // snf Result Code Constants | ||||
TokenMatrix* MyTokenMatrix; // We combine the current token matrix | TokenMatrix* MyTokenMatrix; // We combine the current token matrix | ||||
snfCFGData* MyCFGData; // and the current cfg data for each scan. | snfCFGData* MyCFGData; // and the current cfg data for each scan. | ||||
set<int> RulePanics; // Set of known rule panic IDs. | |||||
std::set<int> RulePanics; // Set of known rule panic IDs. | |||||
public: | public: | ||||
snfCFGPacket(snf_RulebaseHandler* R); // Constructor grab()s the Rulebase. | snfCFGPacket(snf_RulebaseHandler* R); // Constructor grab()s the Rulebase. | ||||
bool isRulePanic(int R); // Test for a rule panic. | bool isRulePanic(int R); // Test for a rule panic. | ||||
}; | }; | ||||
class ScriptCaller : private Thread { // Calls system() in separate thread. | |||||
class ScriptCaller : private CodeDweller::Thread { // Calls system() in separate thread. | |||||
private: | private: | ||||
Mutex MyMutex; // Protects internal data. | |||||
string SystemCallText; // Text to send to system(). | |||||
Timeout GuardTimer; // Guard time between triggers. | |||||
CodeDweller::Mutex MyMutex; // Protects internal data. | |||||
std::string SystemCallText; // Text to send to system(). | |||||
CodeDweller::Timeout GuardTimer; // Guard time between triggers. | |||||
volatile bool GoFlag; // Go flag true when triggered. | volatile bool GoFlag; // Go flag true when triggered. | ||||
volatile bool DieFlag; // Die flag when it's time to leave. | volatile bool DieFlag; // Die flag when it's time to leave. | ||||
string ScriptToRun(); // Safely grab the script. | |||||
std::string ScriptToRun(); // Safely grab the script. | |||||
bool hasGuardExpired(); // True if guard time has expired. | bool hasGuardExpired(); // True if guard time has expired. | ||||
void myTask(); // Thread task overload. | void myTask(); // Thread task overload. | ||||
volatile int myLastResult; // Last result of system() call. | volatile int myLastResult; // Last result of system() call. | ||||
public: | public: | ||||
ScriptCaller(string Name); // Constructor. | |||||
ScriptCaller(std::string Name); // Constructor. | |||||
~ScriptCaller(); // Destructor. | ~ScriptCaller(); // Destructor. | ||||
void SystemCall(string S); // Set system call text. | |||||
void SystemCall(std::string S); // Set system call text. | |||||
void GuardTime(int T); // Change guard time. | void GuardTime(int T); // Change guard time. | ||||
void trigger(); // Trigger if possible. | void trigger(); // Trigger if possible. | ||||
int LastResult(); // Return myLastResult. | int LastResult(); // Return myLastResult. | ||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
const static ThreadState CallingSystem; // State when in system() call. | |||||
const static ThreadState PendingGuardTime; // State when waiting for guard time. | |||||
const static ThreadState StandingBy; // State when waiting around. | |||||
const static ThreadState Disabled; // State when unable to run. | |||||
const static CodeDweller::ThreadState CallingSystem; // State when in system() call. | |||||
const static CodeDweller::ThreadState PendingGuardTime; // State when waiting for guard time. | |||||
const static CodeDweller::ThreadState StandingBy; // State when waiting around. | |||||
const static CodeDweller::ThreadState Disabled; // State when unable to run. | |||||
}; | }; | ||||
class snf_Reloader : private Thread { // Rulebase maintenance thread. | |||||
class snf_Reloader : private CodeDweller::Thread { // Rulebase maintenance thread. | |||||
private: | private: | ||||
snf_RulebaseHandler& MyRulebase; // We know our rulebase. | snf_RulebaseHandler& MyRulebase; // We know our rulebase. | ||||
bool TimeToStop; // We know if it's time to stop. | bool TimeToStop; // We know if it's time to stop. | ||||
string RulebaseFileCheckName; // We keep track of these files. | |||||
string ConfigFileCheckName; | |||||
string IgnoreListCheckFileName; | |||||
std::string RulebaseFileCheckName; // We keep track of these files. | |||||
std::string ConfigFileCheckName; | |||||
std::string IgnoreListCheckFileName; | |||||
time_t RulebaseFileTimestamp; // We watch their timestamps. | time_t RulebaseFileTimestamp; // We watch their timestamps. | ||||
time_t ConfigurationTimestamp; | time_t ConfigurationTimestamp; | ||||
time_t IgnoreListTimestamp; | time_t IgnoreListTimestamp; | ||||
snf_Reloader(snf_RulebaseHandler& R); // Setup takes some work. | snf_Reloader(snf_RulebaseHandler& R); // Setup takes some work. | ||||
~snf_Reloader(); // Tear down takes some work. | ~snf_Reloader(); // Tear down takes some work. | ||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
}; | }; | ||||
private: | private: | ||||
Mutex MyMutex; // This handler's mutex. | |||||
CodeDweller::Mutex MyMutex; // This handler's mutex. | |||||
snf_Reloader* MyReloader; // Reloader engine (when in use). | snf_Reloader* MyReloader; // Reloader engine (when in use). | ||||
void _snf_LoadNewRulebase(); // Internal function to load new rulebase. | void _snf_LoadNewRulebase(); // Internal function to load new rulebase. | ||||
Mutex XCIServerCommandMutex; // XCI Server Command Serializer. | |||||
CodeDweller::Mutex XCIServerCommandMutex; // XCI Server Command Serializer. | |||||
snfXCIServerCommandHandler* myXCIServerCommandHandler; // ptr to Installed Srv Cmd Handler. | snfXCIServerCommandHandler* myXCIServerCommandHandler; // ptr to Installed Srv Cmd Handler. | ||||
void grab(snfCFGPacket& CP); // Activate this Rulebase for a scan. | void grab(snfCFGPacket& CP); // Activate this Rulebase for a scan. | ||||
public: | public: | ||||
class ConfigurationError : public runtime_error { // When the configuration won't load. | |||||
public: ConfigurationError(const string& w):runtime_error(w) {} | |||||
class ConfigurationError : public std::runtime_error { // When the configuration won't load. | |||||
public: ConfigurationError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class FileError : public runtime_error { // Exception: rulebase file won't load. | |||||
public: FileError(const string& w):runtime_error(w) {} | |||||
class FileError : public std::runtime_error { // Exception: rulebase file won't load. | |||||
public: FileError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class AuthenticationError : public runtime_error { // Exception when authentication fails. | |||||
public: AuthenticationError(const string& w):runtime_error(w) {} | |||||
class AuthenticationError : public std::runtime_error { // Exception when authentication fails. | |||||
public: AuthenticationError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class IgnoreListError : public runtime_error { // When the ignore list won't load. | |||||
public: IgnoreListError(const string& w):runtime_error(w) {} | |||||
class IgnoreListError : public std::runtime_error { // When the ignore list won't load. | |||||
public: IgnoreListError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class AllocationError : public runtime_error { // Exception when we can't allocate something. | |||||
public: AllocationError(const string& w):runtime_error(w) {} | |||||
class AllocationError : public std::runtime_error { // Exception when we can't allocate something. | |||||
public: AllocationError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class Busy : public runtime_error { // Exception when there is a collision. | |||||
public: Busy(const string& w):runtime_error(w) {} | |||||
class Busy : public std::runtime_error { // Exception when there is a collision. | |||||
public: Busy(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class Panic : public runtime_error { // Exception when something else happens. | |||||
public: Panic(const string& w):runtime_error(w) {} | |||||
class Panic : public std::runtime_error { // Exception when something else happens. | |||||
public: Panic(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
//// Plugin Components. | //// Plugin Components. | ||||
bool testXHDRInjectOn(); // Safely look ahead at XHDRInjectOn. | bool testXHDRInjectOn(); // Safely look ahead at XHDRInjectOn. | ||||
IPTestRecord& performIPTest(IPTestRecord& I); // Perform an IP test. | IPTestRecord& performIPTest(IPTestRecord& I); // Perform an IP test. | ||||
void logThisIPTest(IPTestRecord& I, string Action); // Log an IP test result & action. | |||||
void logThisIPTest(IPTestRecord& I, std::string Action); // Log an IP test result & action. | |||||
void logThisError(string ContextName, int Code, string Text); // Log an error message. | |||||
void logThisInfo(string ContextName, int Code, string Text); // Log an informational message. | |||||
string PlatformVersion(string NewPlatformVersion); // Set platform version info. | |||||
string PlatformVersion(); // Get platform version info. | |||||
string PlatformConfiguration(); // Get platform configuration. | |||||
string EngineVersion(); // Get engine version info. | |||||
void logThisError(std::string ContextName, int Code, std::string Text); // Log an error message. | |||||
void logThisInfo(std::string ContextName, int Code, std::string Text); // Log an informational message. | |||||
std::string PlatformVersion(std::string NewPlatformVersion); // Set platform version info. | |||||
std::string PlatformVersion(); // Get platform version info. | |||||
std::string PlatformConfiguration(); // Get platform configuration. | |||||
std::string EngineVersion(); // Get engine version info. | |||||
void XCIServerCommandHandler(snfXCIServerCommandHandler& XCH); // Registers a new XCI Srvr Cmd handler. | void XCIServerCommandHandler(snfXCIServerCommandHandler& XCH); // Registers a new XCI Srvr Cmd handler. | ||||
string processXCIServerCommandRequest(snf_xci& X); // Handle a parsed XCI Srvr Cmd request. | |||||
std::string processXCIServerCommandRequest(snf_xci& X); // Handle a parsed XCI Srvr Cmd request. | |||||
}; | }; | ||||
// IPTestEngine w/ GBUdb interface. | // IPTestEngine w/ GBUdb interface. | ||||
void setCFGData(snfCFGData& C); // (Re)Set the config data to use. | void setCFGData(snfCFGData& C); // (Re)Set the config data to use. | ||||
void setLOGmgr(snfLOGmgr& L); // Setup the LOGmgr to use. | void setLOGmgr(snfLOGmgr& L); // Setup the LOGmgr to use. | ||||
string& test(string& input, string& output); // Our obligatory test function. | |||||
std::string& test(std::string& input, std::string& output); // Our obligatory test function. | |||||
}; | }; | ||||
class snf_SaccadesHandler { | class snf_SaccadesHandler { | ||||
private: | private: | ||||
Mutex MyMutex; | |||||
CodeDweller::Mutex MyMutex; | |||||
saccades_engine MyEngine; | saccades_engine MyEngine; | ||||
void lockAndLearn(vector<saccade>& Matches) { | |||||
ScopeMutex SafetyFirst(MyMutex); | |||||
void lockAndLearn(std::vector<saccade>& Matches) { | |||||
CodeDweller::ScopeMutex SafetyFirst(MyMutex); | |||||
MyEngine.learn(Matches); | MyEngine.learn(Matches); | ||||
} | } | ||||
vector<saccade> grabSaccades() { | |||||
ScopeMutex SafetyFirst(MyMutex); | |||||
std::vector<saccade> grabSaccades() { | |||||
CodeDweller::ScopeMutex SafetyFirst(MyMutex); | |||||
return MyEngine.recall(); | return MyEngine.recall(); | ||||
} | } | ||||
MyEngine(128), | MyEngine(128), | ||||
TimeToPeekCounter(0) {} | TimeToPeekCounter(0) {} | ||||
void applySaccades(EvaluationMatrix* Scanner, vector<unsigned char>& Data); | |||||
void applySaccades(EvaluationMatrix* Scanner, std::vector<unsigned char>& Data); | |||||
void learnMatches(MatchRecord* Matches); | void learnMatches(MatchRecord* Matches); | ||||
}; | }; | ||||
private: | private: | ||||
Mutex MyMutex; // This handler's mutex. | |||||
Mutex FileScan; // File scan entry mutex. | |||||
CodeDweller::Mutex MyMutex; // This handler's mutex. | |||||
CodeDweller::Mutex FileScan; // File scan entry mutex. | |||||
EvaluationMatrix* volatile CurrentMatrix; // Matrix for the latest scan. | EvaluationMatrix* volatile CurrentMatrix; // Matrix for the latest scan. | ||||
snf_RulebaseHandler* volatile MyRulebase; // My RulebaseHandler. | snf_RulebaseHandler* volatile MyRulebase; // My RulebaseHandler. | ||||
MatchRecord* FinalResult; // Final (winning) result of the scan. | MatchRecord* FinalResult; // Final (winning) result of the scan. | ||||
MatchRecord* ResultCursor; // Current Match Record for getResults. | MatchRecord* ResultCursor; // Current Match Record for getResults. | ||||
string extractMessageID(const unsigned char* Msg, const int Len); // Get log safe Message-ID or substitute. | |||||
std::string extractMessageID(const unsigned char* Msg, const int Len); // Get log safe Message-ID or substitute. | |||||
public: | public: | ||||
class FileError : public runtime_error { // Exception when a file won't open. | |||||
public: FileError(const string& w):runtime_error(w) {} | |||||
class FileError : public std::runtime_error { // Exception when a file won't open. | |||||
public: FileError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class XHDRError : public runtime_error { // Exception when XHDR Inject/File fails. | |||||
public: XHDRError(const string& w):runtime_error(w) {} | |||||
class XHDRError : public std::runtime_error { // Exception when XHDR Inject/File fails. | |||||
public: XHDRError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class BadMatrix : public runtime_error { // Exception out of bounds of matrix. | |||||
public: BadMatrix(const string& w):runtime_error(w) {} | |||||
class BadMatrix : public std::runtime_error { // Exception out of bounds of matrix. | |||||
public: BadMatrix(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class MaxEvals : public runtime_error { // Exception too many evaluators. | |||||
public: MaxEvals(const string& w):runtime_error(w) {} | |||||
class MaxEvals : public std::runtime_error { // Exception too many evaluators. | |||||
public: MaxEvals(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class AllocationError : public runtime_error { // Exception when we can't allocate something. | |||||
public: AllocationError(const string& w):runtime_error(w) {} | |||||
class AllocationError : public std::runtime_error { // Exception when we can't allocate something. | |||||
public: AllocationError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class Busy : public runtime_error { // Exception when there is a collision. | |||||
public: Busy(const string& w):runtime_error(w) {} | |||||
class Busy : public std::runtime_error { // Exception when there is a collision. | |||||
public: Busy(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class Panic : public runtime_error { // Exception when something else happens. | |||||
public: Panic(const string& w):runtime_error(w) {} | |||||
class Panic : public std::runtime_error { // Exception when something else happens. | |||||
public: Panic(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
snf_EngineHandler(): // Initialization is simple. | snf_EngineHandler(): // Initialization is simple. | ||||
void close(); // Close down the engine. | void close(); // Close down the engine. | ||||
int scanMessageFile( // Scan this message file. | int scanMessageFile( // Scan this message file. | ||||
const string MessageFilePath, // -- this is the file (and id) | |||||
const std::string MessageFilePath, // -- this is the file (and id) | |||||
const int MessageSetupTime = 0, // -- setup time already used. | const int MessageSetupTime = 0, // -- setup time already used. | ||||
const IP4Address MessageSource = 0UL // -- message source IP (for injection). | |||||
const CodeDweller::IP4Address MessageSource = 0UL // -- message source IP (for injection). | |||||
); | ); | ||||
int scanMessage( // Scan this message. | |||||
const unsigned char* MessageBuffer, // -- this is the message buffer. | |||||
const int MessageLength, // -- this is the length of the buffer. | |||||
const string MessageName = "", // -- this is the message identifier. | |||||
int scanMessage( // Scan this message. | |||||
const unsigned char* MessageBuffer, // -- this is the message buffer. | |||||
const int MessageLength, // -- this is the length of the buffer. | |||||
const std::string MessageName = "", // -- this is the message identifier. | |||||
const int MessageSetupTime = 0, // -- setup time used (for logging). | const int MessageSetupTime = 0, // -- setup time used (for logging). | ||||
const IP4Address MessageSource = 0UL // -- message source IP (for injection). | |||||
const CodeDweller::IP4Address MessageSource = 0UL // -- message source IP (for injection). | |||||
); | ); | ||||
int getResults(snf_match* MatchBuffer); // Get the next match buffer. | int getResults(snf_match* MatchBuffer); // Get the next match buffer. | ||||
int getDepth(); // Get the scan depth. | int getDepth(); // Get the scan depth. | ||||
const string getClassicLog(); // Get classic log entries for last scan. | |||||
const string getXMLLog(); // Get XML log entries or last scan. | |||||
const string getXHDRs(); // Get XHDRs for last scan. | |||||
}; | |||||
const std::string getClassicLog(); // Get classic log entries for last scan. | |||||
const std::string getXMLLog(); // Get XML log entries or last scan. | |||||
const std::string getXHDRs(); // Get XHDRs for last scan. | |||||
}; | |||||
// Here's the class that pulls it all together. | // Here's the class that pulls it all together. | ||||
private: | private: | ||||
Mutex RulebaseScan; // This handler's mutex. | |||||
CodeDweller::Mutex RulebaseScan; // This handler's mutex. | |||||
int RulebaseCursor; // Next Rulebase to search. | int RulebaseCursor; // Next Rulebase to search. | ||||
snf_RulebaseHandler RulebaseHandlers[snf_MAX_RULEBASES]; // Array of Rulebase Handlers | snf_RulebaseHandler RulebaseHandlers[snf_MAX_RULEBASES]; // Array of Rulebase Handlers | ||||
int RoundRulebaseCursor(); // Gets round robin Rulebase handle candidates. | int RoundRulebaseCursor(); // Gets round robin Rulebase handle candidates. | ||||
Mutex EngineScan; // Serializes searching the Engine list. | |||||
CodeDweller::Mutex EngineScan; // Serializes searching the Engine list. | |||||
int EngineCursor; // Next Engine to search. | int EngineCursor; // Next Engine to search. | ||||
snf_EngineHandler EngineHandlers[snf_MAX_SCANNERS]; // Array of Engine Handlers | snf_EngineHandler EngineHandlers[snf_MAX_SCANNERS]; // Array of Engine Handlers | ||||
public: | public: | ||||
class TooMany : public runtime_error { // Exception when no more handle slots. | |||||
public: TooMany(const string& w):runtime_error(w) {} | |||||
class TooMany : public std::runtime_error { // Exception when no more handle slots. | |||||
public: TooMany(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class FileError : public runtime_error { // Exception when a file won't open. | |||||
public: FileError(const string& w):runtime_error(w) {} | |||||
class FileError : public std::runtime_error { // Exception when a file won't open. | |||||
public: FileError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class AuthenticationError : public runtime_error { // Exception when authentication fails. | |||||
public: AuthenticationError(const string& w):runtime_error(w) {} | |||||
class AuthenticationError : public std::runtime_error { // Exception when authentication fails. | |||||
public: AuthenticationError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class AllocationError : public runtime_error { // Exception when we can't allocate something. | |||||
public: AllocationError(const string& w):runtime_error(w) {} | |||||
class AllocationError : public std::runtime_error { // Exception when we can't allocate something. | |||||
public: AllocationError(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class Busy : public runtime_error { // Exception when there is a collision. | |||||
public: Busy(const string& w):runtime_error(w) {} | |||||
class Busy : public std::runtime_error { // Exception when there is a collision. | |||||
public: Busy(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class Panic : public runtime_error { // Exception when something else happens. | |||||
public: Panic(const string& w):runtime_error(w) {} | |||||
class Panic : public std::runtime_error { // Exception when something else happens. | |||||
public: Panic(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
snf_MultiEngineHandler(): | snf_MultiEngineHandler(): | ||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif |
// See snfCFGmgr.hpp for details. | // See snfCFGmgr.hpp for details. | ||||
#include "snfCFGmgr.hpp" | |||||
#include "SNFMulti/snfCFGmgr.hpp" | |||||
#include <iostream> | #include <iostream> | ||||
using namespace CodeDweller; | |||||
using namespace std; | |||||
namespace SNFMulti { | |||||
//// RangeHandler ////////////////////////////////////////////////////////////// | //// RangeHandler ////////////////////////////////////////////////////////////// | ||||
} | } | ||||
} |
#ifndef included_snfCFGmgr_hpp | #ifndef included_snfCFGmgr_hpp | ||||
#define included_snfCFGmgr_hpp | #define included_snfCFGmgr_hpp | ||||
#include "GBUdb.hpp" | |||||
#include "snf_HeaderFinder.hpp" | |||||
#include "SNFMulti/GBUdb.hpp" | |||||
#include "SNFMulti/snf_HeaderFinder.hpp" | |||||
#include "../CodeDweller/configuration.hpp" | |||||
#include "../CodeDweller/threading.hpp" | |||||
#include "CodeDweller/configuration.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include <string> | #include <string> | ||||
#include <set> | #include <set> | ||||
using namespace std; | |||||
namespace SNFMulti { | |||||
const unsigned long int HeaderDirectiveBypass = 0x00000001; // Bypass hd rule flag. | const unsigned long int HeaderDirectiveBypass = 0x00000001; // Bypass hd rule flag. | ||||
const unsigned long int HeaderDirectiveWhite = 0x00000002; // White hd rule flag. | const unsigned long int HeaderDirectiveWhite = 0x00000002; // White hd rule flag. | ||||
const unsigned long int HeaderDirectiveSource = 0x00000008; // Source rule flag. | const unsigned long int HeaderDirectiveSource = 0x00000008; // Source rule flag. | ||||
const unsigned long int HeaderDirectiveContext = 0x80000000; // Context activation flag. | const unsigned long int HeaderDirectiveContext = 0x80000000; // Context activation flag. | ||||
class HeaderDirectiveHandler : public Configurator { // Handle inputs to header directives. | |||||
class HeaderDirectiveHandler : public CodeDweller::Configurator { // Handle inputs to header directives. | |||||
public: | public: | ||||
HeaderDirectiveSet HeaderDirectives; // Managed set of Header Directives. | HeaderDirectiveSet HeaderDirectives; // Managed set of Header Directives. | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator call adds the Input. | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator call adds the Input. | |||||
if(HeaderDirectiveContext == ContextInput.Directive) { // If a context has been established | if(HeaderDirectiveContext == ContextInput.Directive) { // If a context has been established | ||||
ContextInput.Context = HeaderDirectives.size() + 1; // then setup the context ID and | ContextInput.Context = HeaderDirectives.size() + 1; // then setup the context ID and | ||||
}; | }; | ||||
class HeaderDirectiveInitializer : public Configurator { // Initializes Header Directives. | |||||
class HeaderDirectiveInitializer : public CodeDweller::Configurator { // Initializes Header Directives. | |||||
private: | private: | ||||
HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | ||||
void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator() function goes to the | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator() function goes to the | |||||
if(NULL!=MyTarget) { // target (if it's set) and pushes the | if(NULL!=MyTarget) { // target (if it's set) and pushes the | ||||
MyTarget->reset(); // reset button (empties the set). | MyTarget->reset(); // reset button (empties the set). | ||||
} | } | ||||
} | } | ||||
}; | }; | ||||
class HeaderDirectiveWhiteHeaderInitializer : public Configurator { // Initializes White Header Directives. | |||||
class HeaderDirectiveWhiteHeaderInitializer : public CodeDweller::Configurator {// Initializes White Header Directives. | |||||
private: | private: | ||||
HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | ||||
void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator() function goes to the | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator() function goes to the | |||||
if(NULL!=MyTarget) { // target (if it's set) and sets it up | if(NULL!=MyTarget) { // target (if it's set) and sets it up | ||||
MyTarget->ContextInput.clear(); // for a white header directive. | MyTarget->ContextInput.clear(); // for a white header directive. | ||||
MyTarget->DirectiveInput.clear(); | MyTarget->DirectiveInput.clear(); | ||||
} | } | ||||
}; | }; | ||||
class HeaderDirectiveBypassHeaderInitializer : public Configurator { // Initializes Bypass Header Directives. | |||||
class HeaderDirectiveBypassHeaderInitializer : public CodeDweller::Configurator {// Initializes Bypass Header Directives. | |||||
private: | private: | ||||
HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | ||||
void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator() function goes to the | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator() function goes to the | |||||
if(NULL!=MyTarget) { // target (if it's set) and sets it up | if(NULL!=MyTarget) { // target (if it's set) and sets it up | ||||
MyTarget->ContextInput.clear(); // for a bypass header directive. | MyTarget->ContextInput.clear(); // for a bypass header directive. | ||||
MyTarget->DirectiveInput.clear(); | MyTarget->DirectiveInput.clear(); | ||||
} | } | ||||
}; | }; | ||||
class HeaderDirectiveDrilldownInitializer : public Configurator { // Initializes Drilldown Header Directives. | |||||
class HeaderDirectiveDrilldownInitializer : public CodeDweller::Configurator { // Initializes Drilldown Header Directives. | |||||
private: | private: | ||||
HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | ||||
void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator() function goes to the | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator() function goes to the | |||||
if(NULL!=MyTarget) { // target (if it's set) and sets it up for | if(NULL!=MyTarget) { // target (if it's set) and sets it up for | ||||
MyTarget->ContextInput.clear(); // a drilldown header directive. | MyTarget->ContextInput.clear(); // a drilldown header directive. | ||||
MyTarget->DirectiveInput.clear(); | MyTarget->DirectiveInput.clear(); | ||||
} | } | ||||
}; | }; | ||||
class HeaderDirectiveSourceHeaderInitializer : public Configurator { // Initializes Source Header Directives. | |||||
class HeaderDirectiveSourceHeaderInitializer : public CodeDweller::Configurator {// Initializes Source Header Directives. | |||||
private: | private: | ||||
HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | HeaderDirectiveHandler* MyTarget; // Needs to know it's target. | ||||
void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | void setTarget(HeaderDirectiveHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator() function goes to the | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator() function goes to the | |||||
if(NULL!=MyTarget) { // target (if it's set) and sets it up | if(NULL!=MyTarget) { // target (if it's set) and sets it up | ||||
MyTarget->ContextInput.clear(); // for a context sensitive source header | MyTarget->ContextInput.clear(); // for a context sensitive source header | ||||
MyTarget->DirectiveInput.clear(); // directive. Activation context as well | MyTarget->DirectiveInput.clear(); // directive. Activation context as well | ||||
} | } | ||||
}; | }; | ||||
class RangeHandler : public Configurator { // The handler adds edgepoints and holds and | |||||
class RangeHandler : public CodeDweller::Configurator { // The handler adds edgepoints and holds and | |||||
public: // tests the set that defines the region. | public: // tests the set that defines the region. | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The () operator adds EdgeInput to the list. | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The () operator adds EdgeInput to the list. | |||||
EdgeMap.insert(EdgeInput); | EdgeMap.insert(EdgeInput); | ||||
} | } | ||||
int Priority; // They have an evaluation priority. | int Priority; // They have an evaluation priority. | ||||
RangePoint EdgeInput; // This EdgePoint is set, and added using (). | RangePoint EdgeInput; // This EdgePoint is set, and added using (). | ||||
set<RangePoint> EdgeMap; // This contains the set of EdgePoints. | |||||
std::set<RangePoint> EdgeMap; // This contains the set of EdgePoints. | |||||
bool isInWhite(RangePoint& x); // True if x is inside the -P of the EdgeMap. | bool isInWhite(RangePoint& x); // True if x is inside the -P of the EdgeMap. | ||||
bool isInBlack(RangePoint& x); // True if x is inside the +P of the EdgeMap. | bool isInBlack(RangePoint& x); // True if x is inside the +P of the EdgeMap. | ||||
}; | }; | ||||
class RangeInitializer : public Configurator { // The RangeInitializer Configurator. | |||||
class RangeInitializer : public CodeDweller::Configurator { // The RangeInitializer Configurator. | |||||
private: | private: | ||||
RangeHandler* MyTarget; // Needs to know it's target. | RangeHandler* MyTarget; // Needs to know it's target. | ||||
void setTarget(RangeHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | void setTarget(RangeHandler& H) { MyTarget = &H; } // We have a way to set the target though ;-) | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The configurator() function goes to the | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The configurator() function goes to the | |||||
if(NULL!=MyTarget) { // target (if it's set) and pushes the | if(NULL!=MyTarget) { // target (if it's set) and pushes the | ||||
MyTarget->reset(); // reset button. | MyTarget->reset(); // reset button. | ||||
} | } | ||||
} | } | ||||
}; | }; | ||||
class IntegerSetHandler : public Configurator { // Integer set handler for rule panics. | |||||
class IntegerSetHandler : public CodeDweller::Configurator { // Integer set handler for rule panics. | |||||
public: | public: | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The operator() inserts IntegerInput | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The operator() inserts IntegerInput | |||||
IntegerSet.insert(IntegerInput); // if it's not already a member. | IntegerSet.insert(IntegerInput); // if it's not already a member. | ||||
} | } | ||||
int IntegerInput; // The input port. | int IntegerInput; // The input port. | ||||
set<int> IntegerSet; // The set itself. | |||||
std::set<int> IntegerSet; // The set itself. | |||||
bool isListed(int x); // How to check if an int is listed. | bool isListed(int x); // How to check if an int is listed. | ||||
void reset() { IntegerSet.clear(); } // How to reset (clear) the list. | void reset() { IntegerSet.clear(); } // How to reset (clear) the list. | ||||
}; | }; | ||||
class IntegerSetInitializer : public Configurator { // The initializer resets the set. | |||||
class IntegerSetInitializer : public CodeDweller::Configurator { // The initializer resets the set. | |||||
private: | private: | ||||
IntegerSetHandler* MyTarget; // It needs to know which set to init. | IntegerSetHandler* MyTarget; // It needs to know which set to init. | ||||
void setTarget(IntegerSetHandler& H) { MyTarget = &H; } // Set a pointer to the handler. | void setTarget(IntegerSetHandler& H) { MyTarget = &H; } // Set a pointer to the handler. | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The operator() does the trick. | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The operator() does the trick. | |||||
if(NULL!=MyTarget) { | if(NULL!=MyTarget) { | ||||
MyTarget->reset(); | MyTarget->reset(); | ||||
} | } | ||||
class XHDRSymbol { // XHeader associated with a Symbol | class XHDRSymbol { // XHeader associated with a Symbol | ||||
public: | public: | ||||
int Symbol; // The integer symbol. | int Symbol; // The integer symbol. | ||||
string Header; // The header to associate. | |||||
XHDRSymbol(int FreshSymbol, string FreshHeader) : // Creating the object requires both. | |||||
std::string Header; // The header to associate. | |||||
XHDRSymbol(int FreshSymbol, std::string FreshHeader) : // Creating the object requires both. | |||||
Symbol(FreshSymbol), | Symbol(FreshSymbol), | ||||
Header(FreshHeader) {} | Header(FreshHeader) {} | ||||
} // in this case. | } // in this case. | ||||
}; | }; | ||||
class XHDRSymbolsHandler : public Configurator { // XHDRSymbol hander. | |||||
class XHDRSymbolsHandler : public CodeDweller::Configurator { // XHDRSymbol hander. | |||||
public: | public: | ||||
set<XHDRSymbol> SymbolHeaders; // Carries a set of Symbol Headers. | |||||
std::set<XHDRSymbol> SymbolHeaders; // Carries a set of Symbol Headers. | |||||
void reset() { SymbolHeaders.clear(); } // Is reset by clearing the set. | void reset() { SymbolHeaders.clear(); } // Is reset by clearing the set. | ||||
string HeaderForSymbol(int S) { // Can return a Header for symbol. | |||||
string MatchingHeader = ""; // Starting with an empty string, | |||||
set<XHDRSymbol>::iterator iS = SymbolHeaders.find(XHDRSymbol(S,"")); // we look up the symbol and | |||||
std::string HeaderForSymbol(int S) { // Can return a Header for symbol. | |||||
std::string MatchingHeader = ""; // Starting with an empty string, | |||||
std::set<XHDRSymbol>::iterator iS = SymbolHeaders.find(XHDRSymbol(S,""));// we look up the symbol and | |||||
if(SymbolHeaders.end() != iS) { // if we find it then we will | if(SymbolHeaders.end() != iS) { // if we find it then we will | ||||
MatchingHeader = (*iS).Header; // return the matching header | MatchingHeader = (*iS).Header; // return the matching header | ||||
} // string. If not then we return | } // string. If not then we return | ||||
bool OnOff; // Input OnOff value. | bool OnOff; // Input OnOff value. | ||||
int Symbol; // Input Symbol value. | int Symbol; // Input Symbol value. | ||||
string Header; // Input Header value. | |||||
std::string Header; // Input Header value. | |||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The operator() inserts an XHDRSymbol | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The operator() inserts an XHDRSymbol | |||||
if(OnOff) { // if the header entry is turned on and | if(OnOff) { // if the header entry is turned on and | ||||
SymbolHeaders.insert(XHDRSymbol(Symbol, Header)); // if it's not already a member. | SymbolHeaders.insert(XHDRSymbol(Symbol, Header)); // if it's not already a member. | ||||
} | } | ||||
} | } | ||||
}; | }; | ||||
class XHDRSymbolsInitializer : public Configurator { // The XHDRSymbols initializer. | |||||
class XHDRSymbolsInitializer : public CodeDweller::Configurator { // The XHDRSymbols initializer. | |||||
private: | private: | ||||
XHDRSymbolsHandler* MyTarget; // It needs to know which set to init. | XHDRSymbolsHandler* MyTarget; // It needs to know which set to init. | ||||
void setTarget(XHDRSymbolsHandler& H) { MyTarget = &H; } // Set a pointer to the handler. | void setTarget(XHDRSymbolsHandler& H) { MyTarget = &H; } // Set a pointer to the handler. | ||||
void operator()(ConfigurationElement& E, ConfigurationData& D) { // The operator() does the trick. | |||||
void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // The operator() does the trick. | |||||
if(NULL!=MyTarget) { | if(NULL!=MyTarget) { | ||||
MyTarget->reset(); | MyTarget->reset(); | ||||
} | } | ||||
class snfCFGData { // Object that stores our config data. | class snfCFGData { // Object that stores our config data. | ||||
private: | private: | ||||
ConfigurationElement MyCFGReader; // This is how we read our cfg data. | |||||
CodeDweller::ConfigurationElement MyCFGReader; // This is how we read our cfg data. | |||||
public: | public: | ||||
// Here are the derived data elements... | // Here are the derived data elements... | ||||
string ConfigFilePath; // Configuration file path | |||||
string RuleFilePath; // Rulebase file path | |||||
string SecurityKey; // Security key for rulebase | |||||
std::string ConfigFilePath; // Configuration file path | |||||
std::string RuleFilePath; // Rulebase file path | |||||
std::string SecurityKey; // Security key for rulebase | |||||
// Here are the basic data elements... | // Here are the basic data elements... | ||||
string node_identity; | |||||
string node_licenseid; | |||||
string node_authentication; | |||||
std::string node_identity; | |||||
std::string node_licenseid; | |||||
std::string node_authentication; | |||||
//// paths | //// paths | ||||
string paths_workspace_path; | |||||
string paths_rulebase_path; | |||||
string paths_log_path; | |||||
std::string paths_workspace_path; | |||||
std::string paths_rulebase_path; | |||||
std::string paths_log_path; | |||||
//// logging | //// logging | ||||
int XHDROutput_Mode; | int XHDROutput_Mode; | ||||
bool XHDRVersion_OnOff; | bool XHDRVersion_OnOff; | ||||
string XHDRVersion_Header; | |||||
std::string XHDRVersion_Header; | |||||
bool XHDRLicense_OnOff; | bool XHDRLicense_OnOff; | ||||
string XHDRLicense_Header; | |||||
std::string XHDRLicense_Header; | |||||
bool XHDRRulebase_OnOff; | bool XHDRRulebase_OnOff; | ||||
string XHDRRulebase_Header; | |||||
std::string XHDRRulebase_Header; | |||||
bool XHDRIdentifier_OnOff; | bool XHDRIdentifier_OnOff; | ||||
string XHDRIdentifier_Header; | |||||
std::string XHDRIdentifier_Header; | |||||
bool XHDRGBUdb_OnOff; | bool XHDRGBUdb_OnOff; | ||||
string XHDRGBUdb_Header; | |||||
std::string XHDRGBUdb_Header; | |||||
bool XHDRResult_OnOff; | bool XHDRResult_OnOff; | ||||
string XHDRResult_Header; | |||||
std::string XHDRResult_Header; | |||||
bool XHDRMatches_OnOff; | bool XHDRMatches_OnOff; | ||||
string XHDRMatches_Header; | |||||
std::string XHDRMatches_Header; | |||||
bool XHDRBlack_OnOff; | bool XHDRBlack_OnOff; | ||||
string XHDRBlack_Header; | |||||
std::string XHDRBlack_Header; | |||||
bool XHDRWhite_OnOff; | bool XHDRWhite_OnOff; | ||||
string XHDRWhite_Header; | |||||
std::string XHDRWhite_Header; | |||||
bool XHDRClean_OnOff; | bool XHDRClean_OnOff; | ||||
string XHDRClean_Header; | |||||
std::string XHDRClean_Header; | |||||
XHDRSymbolsHandler XHDRSymbolHeaders; | XHDRSymbolsHandler XHDRSymbolHeaders; | ||||
XHDRSymbolsInitializer XHDRSymbolHeadersInitializer; | XHDRSymbolsInitializer XHDRSymbolHeadersInitializer; | ||||
//// platform | //// platform | ||||
string PlatformElementContents; | |||||
std::string PlatformElementContents; | |||||
//// network | //// network | ||||
int network_sync_secs; | int network_sync_secs; | ||||
string network_sync_host; | |||||
std::string network_sync_host; | |||||
int network_sync_port; | int network_sync_port; | ||||
bool update_script_on_off; | bool update_script_on_off; | ||||
string update_script_call; | |||||
std::string update_script_call; | |||||
int update_script_guard_time; | int update_script_guard_time; | ||||
//// gbudb | //// gbudb | ||||
private: | private: | ||||
Mutex myMutex; // Serialize control during updates. | |||||
CodeDweller::Mutex myMutex; // Serialize control during updates. | |||||
snfCFGData A; // This is where we store one copy. | snfCFGData A; // This is where we store one copy. | ||||
snfCFGData B; // This is where we store the other. | snfCFGData B; // This is where we store the other. | ||||
snfCFGData& ActiveData(); // This returns the active dataset. | snfCFGData& ActiveData(); // This returns the active dataset. | ||||
snfCFGData& InactiveData(); // This returns the inactive dataset. | snfCFGData& InactiveData(); // This returns the inactive dataset. | ||||
string InitFileName; // Initilization parameters are reused | |||||
string InitLicenseId; // any time load() is called. | |||||
string InitAuthentication; | |||||
std::string InitFileName; // Initilization parameters are reused | |||||
std::string InitLicenseId; // any time load() is called. | |||||
std::string InitAuthentication; | |||||
string ConfigurationPath; // Path to active configuration file. | |||||
std::string ConfigurationPath; // Path to active configuration file. | |||||
public: | public: | ||||
//// Access methods for config data... | //// Access methods for config data... | ||||
string RuleFilePath(); // Rulebase file path | |||||
string SecurityKey(); // Security key for rulebase | |||||
std::string RuleFilePath(); // Rulebase file path | |||||
std::string SecurityKey(); // Security key for rulebase | |||||
snfCFGData* ActiveConfiguration(); // Pointer to active configuration | snfCFGData* ActiveConfiguration(); // Pointer to active configuration | ||||
#include "snfCFGmgr.inline.hpp" | #include "snfCFGmgr.inline.hpp" | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||
// End include only once | // End include only once |
return (AisActive) ? B : A; | return (AisActive) ? B : A; | ||||
} | } | ||||
inline string snfCFGmgr::RuleFilePath() { // Rulebase file path | |||||
inline std::string snfCFGmgr::RuleFilePath() { // Rulebase file path | |||||
return ActiveData().RuleFilePath; | return ActiveData().RuleFilePath; | ||||
} | } | ||||
inline string snfCFGmgr::SecurityKey() { // Security key for rulebase | |||||
inline std::string snfCFGmgr::SecurityKey() { // Security key for rulebase | |||||
return ActiveData().SecurityKey; | return ActiveData().SecurityKey; | ||||
} | } | ||||
// | // | ||||
// See snfGBUdbmgr.hpp for details. | // See snfGBUdbmgr.hpp for details. | ||||
#include "snfGBUdbmgr.hpp" | |||||
#include "SNFMulti/snfGBUdbmgr.hpp" | |||||
#include <unistd.h> | #include <unistd.h> | ||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
const ThreadType snfGBUdbmgr::Type("snfGBUdbmgr"); // The thread's type. | const ThreadType snfGBUdbmgr::Type("snfGBUdbmgr"); // The thread's type. | ||||
void snfGBUdbmgr::ProcessReflections(list<GBUdbAlert>& Reflections) { // Integrate returning reflections. | void snfGBUdbmgr::ProcessReflections(list<GBUdbAlert>& Reflections) { // Integrate returning reflections. | ||||
(*MyGBUdb).ImportAlerts(Reflections); // For now, just pass this through. | (*MyGBUdb).ImportAlerts(Reflections); // For now, just pass this through. | ||||
} | } | ||||
} |
#ifndef snfGBUdbmgr_included | #ifndef snfGBUdbmgr_included | ||||
#define snfGBUdbmgr_included | #define snfGBUdbmgr_included | ||||
#include "../CodeDweller/threading.hpp" | |||||
#include "../CodeDweller/timing.hpp" | |||||
#include "snfCFGmgr.hpp" | |||||
#include "snfLOGmgr.hpp" | |||||
#include "GBUdb.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include "CodeDweller/timing.hpp" | |||||
#include "SNFMulti/snfCFGmgr.hpp" | |||||
#include "SNFMulti/snfLOGmgr.hpp" | |||||
#include "SNFMulti/GBUdb.hpp" | |||||
using namespace std; | |||||
namespace SNFMulti { | |||||
class snfLOGmgr; | class snfLOGmgr; | ||||
class snfGBUdbmgr : public Thread { | |||||
class snfGBUdbmgr : public CodeDweller::Thread { | |||||
private: | private: | ||||
Mutex MyMutex; | |||||
CodeDweller::Mutex MyMutex; | |||||
GBUdb* MyGBUdb; | GBUdb* MyGBUdb; | ||||
snfLOGmgr* MyLOGmgr; | snfLOGmgr* MyLOGmgr; | ||||
bool Configured; | bool Configured; | ||||
// Condensation parts | // Condensation parts | ||||
Timeout CondenseGuardTime; | |||||
CodeDweller::Timeout CondenseGuardTime; | |||||
bool TimeTriggerOnOff; | bool TimeTriggerOnOff; | ||||
Timeout TimeTrigger; | |||||
CodeDweller::Timeout TimeTrigger; | |||||
bool PostsTriggerOnOff; | bool PostsTriggerOnOff; | ||||
int PostsTriggerValue; | int PostsTriggerValue; | ||||
bool RecordsTriggerOnOff; | bool RecordsTriggerOnOff; | ||||
// Checkpoint parts | // Checkpoint parts | ||||
bool CheckpointOnOff; | bool CheckpointOnOff; | ||||
Timeout CheckpointTrigger; | |||||
CodeDweller::Timeout CheckpointTrigger; | |||||
// Utility functions | // Utility functions | ||||
void stop(); // Stop the thread. | void stop(); // Stop the thread. | ||||
void myTask(); // Establish our thread's task. | void myTask(); // Establish our thread's task. | ||||
void GetAlertsForSync(list<GBUdbAlert>& AlertList); // Fill AlertList w/ outgoing alerts. | |||||
void ProcessReflections(list<GBUdbAlert>& Reflections); // Integrate returning reflections. | |||||
void GetAlertsForSync(std::list<GBUdbAlert>& AlertList); // Fill AlertList w/ outgoing alerts. | |||||
void ProcessReflections(std::list<GBUdbAlert>& Reflections); // Integrate returning reflections. | |||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif |
// | // | ||||
// Log Manager implementations see snfLOGmgr.hpp for details. | // Log Manager implementations see snfLOGmgr.hpp for details. | ||||
#include "snfLOGmgr.hpp" | |||||
#include "SNFMulti/snfLOGmgr.hpp" | |||||
#include "../CodeDweller/threading.hpp" | #include "../CodeDweller/threading.hpp" | ||||
#include "../CodeDweller/timing.hpp" | #include "../CodeDweller/timing.hpp" | ||||
#include <unistd.h> | #include <unistd.h> | ||||
#include <iomanip> | #include <iomanip> | ||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
//// DiscLogger //////////////////////////////////////////////////////////////// | //// DiscLogger //////////////////////////////////////////////////////////////// | ||||
if(0 < HourReportText.length()) return HourReportText; // If it's posted then send it. If not | if(0 < HourReportText.length()) return HourReportText; // If it's posted then send it. If not | ||||
return EmptyStatusHourReport; // then send the empty version. | return EmptyStatusHourReport; // then send the empty version. | ||||
} | } | ||||
} |
#include <ctime> | #include <ctime> | ||||
#include <cstdio> | #include <cstdio> | ||||
#include "../CodeDweller/timing.hpp" | |||||
#include "../CodeDweller/threading.hpp" | |||||
#include "../CodeDweller/histogram.hpp" | |||||
#include "CodeDweller/timing.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include "CodeDweller/histogram.hpp" | |||||
#include "snf_match.h" | |||||
#include "SNFMulti/snf_match.h" | |||||
#include "snfCFGmgr.hpp" | |||||
#include "snfNETmgr.hpp" | |||||
#include "GBUdb.hpp" | |||||
#include "SNFMulti/snfCFGmgr.hpp" | |||||
#include "SNFMulti/snfNETmgr.hpp" | |||||
#include "SNFMulti/GBUdb.hpp" | |||||
namespace SNFMulti { | |||||
class snfNETmgr; // Declare snfNETmgr | class snfNETmgr; // Declare snfNETmgr | ||||
extern const char* SNF_ENGINE_VERSION; // Declare the Engine Version Data | extern const char* SNF_ENGINE_VERSION; // Declare the Engine Version Data | ||||
using namespace std; | |||||
//// DiscLogger //////////////////////////////////////////////////////////////// | //// DiscLogger //////////////////////////////////////////////////////////////// | ||||
// Writes log files back to Disc and double buffers data to minimize contention | // Writes log files back to Disc and double buffers data to minimize contention | ||||
// and delays. So - if it takes a few milliseconds to post the log to disc, the | // and delays. So - if it takes a few milliseconds to post the log to disc, the | ||||
// application that post()s to the log does not have to wait. Write back happens | // application that post()s to the log does not have to wait. Write back happens | ||||
// about once per second when enabled. Files can be appended or overwritten. | // about once per second when enabled. Files can be appended or overwritten. | ||||
class DiscLogger : private Thread { // Double buffered lazy writer. | |||||
class DiscLogger : private CodeDweller::Thread { // Double buffered lazy writer. | |||||
private: | private: | ||||
Mutex BufferControlMutex; // Protects buffers while swapping. | |||||
Mutex FlushMutex; // Protects flush operations. | |||||
string myPath; // Where the file should be written. | |||||
string BufferA; // Log data buffer A. | |||||
string BufferB; // Log data buffer B. | |||||
CodeDweller::Mutex BufferControlMutex; // Protects buffers while swapping. | |||||
CodeDweller::Mutex FlushMutex; // Protects flush operations. | |||||
std::string myPath; // Where the file should be written. | |||||
std::string BufferA; // Log data buffer A. | |||||
std::string BufferB; // Log data buffer B. | |||||
bool UseANotB; // Indicates the active buffer. | bool UseANotB; // Indicates the active buffer. | ||||
bool isDirty; // True if data not yet written. | bool isDirty; // True if data not yet written. | ||||
bool isBad; // True if last write failed. | bool isBad; // True if last write failed. | ||||
bool isTimeToStop; // True when shutting down. | bool isTimeToStop; // True when shutting down. | ||||
bool inAppendMode; // True when in append mode. | bool inAppendMode; // True when in append mode. | ||||
string& FlushingBuffer() { return ((UseANotB)?BufferA:BufferB); } // Returns the buffer for flushing. | |||||
string& PostingBuffer() { return ((UseANotB)?BufferB:BufferA); } // Returns the buffer for posting. | |||||
std::string& FlushingBuffer() { return ((UseANotB)?BufferA:BufferB); } // Returns the buffer for flushing. | |||||
std::string& PostingBuffer() { return ((UseANotB)?BufferB:BufferA); } // Returns the buffer for posting. | |||||
bool isEnabled; // True when this should run. | bool isEnabled; // True when this should run. | ||||
void myTask(); // Write back thread task. | void myTask(); // Write back thread task. | ||||
public: | public: | ||||
DiscLogger(string N = "UnNamed"); // Constructs and starts the thread. | |||||
DiscLogger(std::string N = "UnNamed"); // Constructs and starts the thread. | |||||
~DiscLogger(); // Flushes and stops the thread. | ~DiscLogger(); // Flushes and stops the thread. | ||||
string Path(const string PathName) { // Sets the file path. | |||||
ScopeMutex NewSettings(BufferControlMutex); | |||||
std::string Path(const std::string PathName) { // Sets the file path. | |||||
CodeDweller::ScopeMutex NewSettings(BufferControlMutex); | |||||
myPath = PathName; | myPath = PathName; | ||||
return myPath; | return myPath; | ||||
} | } | ||||
string Path() { // Returns the file path. | |||||
ScopeMutex DontMove(BufferControlMutex); | |||||
std::string Path() { // Returns the file path. | |||||
CodeDweller::ScopeMutex DontMove(BufferControlMutex); | |||||
return myPath; | return myPath; | ||||
} | } | ||||
} | } | ||||
bool OverwriteMode() { return (!inAppendMode); } // True if in overwrite mode. | bool OverwriteMode() { return (!inAppendMode); } // True if in overwrite mode. | ||||
void post(const string Input, const string NewPath = ""); // Post Input to log, [set path]. | |||||
void post(const std::string Input, const std::string NewPath = ""); // Post Input to log, [set path]. | |||||
void flush(); // Flush right now! | void flush(); // Flush right now! | ||||
bool Bad() { return (isBad); } // True if last write failed. | bool Bad() { return (isBad); } // True if last write failed. | ||||
bool Good() { return (!isBad); } // True if not Bad(); | bool Good() { return (!isBad); } // True if not Bad(); | ||||
bool Enabled(const bool MakeEnabled) { return (isEnabled = MakeEnabled); } // Enables writing if true. | bool Enabled(const bool MakeEnabled) { return (isEnabled = MakeEnabled); } // Enables writing if true. | ||||
bool Enabled() { return (isEnabled); } // True if enabled. | bool Enabled() { return (isEnabled); } // True if enabled. | ||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
const static ThreadState DiscLogger_Flush; // Flushing state. | |||||
const static ThreadState DiscLogger_Wait; // Waiting state. | |||||
const static CodeDweller::ThreadState DiscLogger_Flush; // Flushing state. | |||||
const static CodeDweller::ThreadState DiscLogger_Wait; // Waiting state. | |||||
}; | }; | ||||
class IPTestRecord { // IP Analysis Record. | class IPTestRecord { // IP Analysis Record. | ||||
public: | public: | ||||
IP4Address IP; // The IP to be tested. | |||||
CodeDweller::IP4Address IP; // The IP to be tested. | |||||
GBUdbRecord G; // The GBUdb Record for the IP. | GBUdbRecord G; // The GBUdb Record for the IP. | ||||
snfIPRange R; // The GBUdb classification (range). | snfIPRange R; // The GBUdb classification (range). | ||||
int Code; // Code associated with Range. | int Code; // Code associated with Range. | ||||
IPTestRecord(IP4Address testIP) : IP(testIP), Code(0) {} // Construct with an IP. | |||||
IPTestRecord(CodeDweller::IP4Address testIP) : IP(testIP), Code(0) {} // Construct with an IP. | |||||
}; | }; | ||||
//// snfScanData /////////////////////////////////////////////////////////////// | //// snfScanData /////////////////////////////////////////////////////////////// | ||||
bool SourceIPFoundFlag; // True if source IP is set. | bool SourceIPFoundFlag; // True if source IP is set. | ||||
snfIPRange SourceIPRangeFlag; // GBUdb detection range for source IP. | snfIPRange SourceIPRangeFlag; // GBUdb detection range for source IP. | ||||
IP4Address myCallerForcedSourceIP; // Caller forced source IP if not 0UL. | |||||
IP4Address myHeaderDirectiveSourceIP; // Header forced source IP if not 0UL. | |||||
CodeDweller::IP4Address myCallerForcedSourceIP; // Caller forced source IP if not 0UL. | |||||
CodeDweller::IP4Address myHeaderDirectiveSourceIP; // Header forced source IP if not 0UL. | |||||
public: | public: | ||||
void drillPastOrdinal(int O); // Sets Drill Down flag for IP record O. | void drillPastOrdinal(int O); // Sets Drill Down flag for IP record O. | ||||
bool isDrillDownSource(IPScanRecord& X); // True if we drill through this source. | bool isDrillDownSource(IPScanRecord& X); // True if we drill through this source. | ||||
IP4Address HeaderDirectiveSourceIP(IP4Address A); // set Header directive source IP. | |||||
IP4Address HeaderDirectiveSourceIP(); // get Header directive source IP. | |||||
IP4Address CallerForcedSourceIP(IP4Address A); // set Caller forced source IP. | |||||
IP4Address CallerForcedSourceIP(); // get Caller forced source IP. | |||||
CodeDweller::IP4Address HeaderDirectiveSourceIP(CodeDweller::IP4Address A); // set Header directive source IP. | |||||
CodeDweller::IP4Address HeaderDirectiveSourceIP(); // get Header directive source IP. | |||||
CodeDweller::IP4Address CallerForcedSourceIP(CodeDweller::IP4Address A); // set Caller forced source IP. | |||||
CodeDweller::IP4Address CallerForcedSourceIP(); // get Caller forced source IP. | |||||
IPScanRecord& SourceIPRecord(IPScanRecord& X); // Sets the source IP record. | IPScanRecord& SourceIPRecord(IPScanRecord& X); // Sets the source IP record. | ||||
IPScanRecord& SourceIPRecord(); // Gets the source IP record. | IPScanRecord& SourceIPRecord(); // Gets the source IP record. | ||||
// Direct access data... | // Direct access data... | ||||
string SourceIPEvaluation; // GBUdb Source IP evaluation. | |||||
std::string SourceIPEvaluation; // GBUdb Source IP evaluation. | |||||
// LogControl and General Message Flags | // LogControl and General Message Flags | ||||
time_t StartOfJobUTC; // Timestamp at start of job. | time_t StartOfJobUTC; // Timestamp at start of job. | ||||
int SetupTime; // Time in ms spent setting up to scan. | int SetupTime; // Time in ms spent setting up to scan. | ||||
string ScanName; // Identifying name or message file name. | |||||
Timer ScanTime; // Scan time in ms. | |||||
std::string ScanName; // Identifying name or message file name. | |||||
CodeDweller::Timer ScanTime; // Scan time in ms. | |||||
int ScanDepth; // Scan Depth in evaluators. | int ScanDepth; // Scan Depth in evaluators. | ||||
string ClassicLogText; // Classic log entry text if any. | |||||
string XMLLogText; // XML log entry text if any. | |||||
string XHDRsText; // XHeaders text if any. | |||||
std::string ClassicLogText; // Classic log entry text if any. | |||||
std::string XMLLogText; // XML log entry text if any. | |||||
std::string XHDRsText; // XHeaders text if any. | |||||
bool XHeaderInjectOn; // True if injecting headers is on. | bool XHeaderInjectOn; // True if injecting headers is on. | ||||
bool XHeaderFileOn; // True if creating .xhdr file is on. | bool XHeaderFileOn; // True if creating .xhdr file is on. | ||||
// Rule panics | // Rule panics | ||||
set<int> RulePanics; // A list of rule IDs panicked this scan. | |||||
std::set<int> RulePanics; // A list of rule IDs panicked this scan. | |||||
// Pattern Engine Scan Result Data | // Pattern Engine Scan Result Data | ||||
vector<unsigned char> FilteredData; // Message data after filter chain. | |||||
std::vector<unsigned char> FilteredData; // Message data after filter chain. | |||||
unsigned long int HeaderDirectiveFlags; // Flags set by header directives. | unsigned long int HeaderDirectiveFlags; // Flags set by header directives. | ||||
bool PatternWasFound; // True if the pattern engine matched. | bool PatternWasFound; // True if the pattern engine matched. | ||||
int PatternID; // The winning rule ID. | int PatternID; // The winning rule ID. | ||||
int PatternSymbol; // The associated symbol. | int PatternSymbol; // The associated symbol. | ||||
list<snf_match> MatchRecords; // List of match records. | |||||
list<snf_match>::iterator MatchRecordsCursor; // Localized iterator for match records. | |||||
std::list<snf_match> MatchRecords; // List of match records. | |||||
std::list<snf_match>::iterator MatchRecordsCursor; // Localized iterator for match records. | |||||
int MatchRecordsDelivered; // Match records seen so far. | int MatchRecordsDelivered; // Match records seen so far. | ||||
int CompositeFinalResult; // What the scan function returned. | int CompositeFinalResult; // What the scan function returned. | ||||
snfCounterPack(); // Construct new CounterPacks clean. | snfCounterPack(); // Construct new CounterPacks clean. | ||||
void reset(); // How to reset a counter pack. | void reset(); // How to reset a counter pack. | ||||
Timer ActiveTime; // Measures Active (swapped in) Time. | |||||
CodeDweller::Timer ActiveTime; // Measures Active (swapped in) Time. | |||||
struct { | struct { | ||||
private: | private: | ||||
Timer A; // Here is one timer. | |||||
Timer B; // Here is the other timer. | |||||
CodeDweller::Timer A; // Here is one timer. | |||||
CodeDweller::Timer B; // Here is the other timer. | |||||
bool ANotB; // True if A is the active timer. | bool ANotB; // True if A is the active timer. | ||||
Timer& Active(); // Selects the active timer. | |||||
Timer& Inactive(); // Selects the inactive timer. | |||||
CodeDweller::Timer& Active(); // Selects the active timer. | |||||
CodeDweller::Timer& Inactive(); // Selects the inactive timer. | |||||
public: | public: | ||||
msclock hack(); // Chop off a new interval & return it. | |||||
msclock Interval(); // Return the last interval. | |||||
msclock Elapsed(); // Return the time since last hack. | |||||
CodeDweller::msclock hack(); // Chop off a new interval & return it. | |||||
CodeDweller::msclock Interval(); // Return the last interval. | |||||
CodeDweller::msclock Elapsed(); // Return the time since last hack. | |||||
}; | }; | ||||
//// PersistentState stores the counters we keep between runs. | //// PersistentState stores the counters we keep between runs. | ||||
bool Ready; // True if we're ready to use. | bool Ready; // True if we're ready to use. | ||||
void store(string& FileNameToStore); // Write the whole thing to a file. | |||||
void restore(string& FileNameToRestore); // Read the whole thing from a file. | |||||
void store(std::string& FileNameToStore); // Write the whole thing to a file. | |||||
void restore(std::string& FileNameToRestore); // Read the whole thing from a file. | |||||
time_t LastSyncTime; // time_t of last Sync event. | time_t LastSyncTime; // time_t of last Sync event. | ||||
time_t LastSaveTime; // time_t of last GBUdb Save event. | time_t LastSaveTime; // time_t of last GBUdb Save event. | ||||
int SerialNumberCounter; // Remembers the serial number. | int SerialNumberCounter; // Remembers the serial number. | ||||
}; | }; | ||||
class snfLOGmgr : private Thread { | |||||
class snfLOGmgr : private CodeDweller::Thread { | |||||
private: | private: | ||||
Mutex MyMutex; // Mutex to serialize updates & queries. | |||||
Mutex ConfigMutex; // Mutex to protect config changes. | |||||
Mutex SerialNumberMutex; // Protects the serial number. | |||||
Mutex PeekMutex; // Protects Peek Loop Counter. | |||||
Mutex SampleMutex; // Protects Sample Loop Counter. | |||||
Mutex StatusReportMutex; // Protects status report post & get. | |||||
CodeDweller::Mutex MyMutex; // Mutex to serialize updates & queries. | |||||
CodeDweller::Mutex ConfigMutex; // Mutex to protect config changes. | |||||
CodeDweller::Mutex SerialNumberMutex; // Protects the serial number. | |||||
CodeDweller::Mutex PeekMutex; // Protects Peek Loop Counter. | |||||
CodeDweller::Mutex SampleMutex; // Protects Sample Loop Counter. | |||||
CodeDweller::Mutex StatusReportMutex; // Protects status report post & get. | |||||
snfCounterPack CounterPackA, CounterPackB; // Swapable counter packs. | snfCounterPack CounterPackA, CounterPackB; // Swapable counter packs. | ||||
time_t StartupTime; // Time since engine started. | time_t StartupTime; // Time since engine started. | ||||
snfLOGPersistentState Status; // Persistent State Data. | snfLOGPersistentState Status; // Persistent State Data. | ||||
string PersistentFileName; // File name for the State Data. | |||||
std::string PersistentFileName; // File name for the State Data. | |||||
snfNETmgr* myNETmgr; // Net manager link. | snfNETmgr* myNETmgr; // Net manager link. | ||||
GBUdb* myGBUdb; // GBUdb link. | GBUdb* myGBUdb; // GBUdb link. | ||||
// Configuration | // Configuration | ||||
string ActiveRulebaseUTC; // UTC of last successful load. | |||||
string AvailableRulebaseUTC; // UTC of rulebase available for update. | |||||
std::string ActiveRulebaseUTC; // UTC of last successful load. | |||||
std::string AvailableRulebaseUTC; // UTC of rulebase available for update. | |||||
bool NewerRulebaseIsAvailable; // True if a newer rulebase is available. | bool NewerRulebaseIsAvailable; // True if a newer rulebase is available. | ||||
string myPlatformVersion; // Version info for platform. | |||||
std::string myPlatformVersion; // Version info for platform. | |||||
bool Rotate_LocalTime; // Rotate logs using localtime. | bool Rotate_LocalTime; // Rotate logs using localtime. | ||||
string LogsPath; // Path to logs directory. | |||||
std::string LogsPath; // Path to logs directory. | |||||
bool ClassicLogRotate; // True = Rotate Classic Log. | bool ClassicLogRotate; // True = Rotate Classic Log. | ||||
bool XMLLogRotate; // True = Rotate XML Log. | bool XMLLogRotate; // True = Rotate XML Log. | ||||
// Histograms | // Histograms | ||||
Histogram ResultsSecond; | |||||
Histogram ResultsMinute; | |||||
Histogram ResultsHour; | |||||
Histogram RulesSecond; | |||||
Histogram RulesMinute; | |||||
Histogram RulesHour; | |||||
Histogram PanicsSecond; | |||||
Histogram PanicsMinute; | |||||
Histogram PanicsHour; | |||||
CodeDweller::Histogram ResultsSecond; | |||||
CodeDweller::Histogram ResultsMinute; | |||||
CodeDweller::Histogram ResultsHour; | |||||
CodeDweller::Histogram RulesSecond; | |||||
CodeDweller::Histogram RulesMinute; | |||||
CodeDweller::Histogram RulesHour; | |||||
CodeDweller::Histogram PanicsSecond; | |||||
CodeDweller::Histogram PanicsMinute; | |||||
CodeDweller::Histogram PanicsHour; | |||||
// Reporting | // Reporting | ||||
string NodeId; // We need this for our status msgs. | |||||
std::string NodeId; // We need this for our status msgs. | |||||
void do_StatusReports(); // Update & sequence status reports. | void do_StatusReports(); // Update & sequence status reports. | ||||
int XML_Log_Mode; // What is the XML log mode. | int XML_Log_Mode; // What is the XML log mode. | ||||
bool SecondReport_Log_OnOff; | bool SecondReport_Log_OnOff; | ||||
bool SecondReport_Append_OnOff; | bool SecondReport_Append_OnOff; | ||||
string SecondReport_Log_Filename; | |||||
string SecondReportText; | |||||
string SecondReportTimestamp; | |||||
std::string SecondReport_Log_Filename; | |||||
std::string SecondReportText; | |||||
std::string SecondReportTimestamp; | |||||
bool do_SecondReport(); // Send our 1 second status report. | bool do_SecondReport(); // Send our 1 second status report. | ||||
// Every minute we get hard data and event logs. (for sync) | // Every minute we get hard data and event logs. (for sync) | ||||
bool MinuteReport_Log_OnOff; | bool MinuteReport_Log_OnOff; | ||||
bool MinuteReport_Append_OnOff; | bool MinuteReport_Append_OnOff; | ||||
string MinuteReport_Log_Filename; | |||||
string MinuteReportText; | |||||
string MinuteReportTimestamp; | |||||
Histogram PatternRulesHistogram; | |||||
std::string MinuteReport_Log_Filename; | |||||
std::string MinuteReportText; | |||||
std::string MinuteReportTimestamp; | |||||
CodeDweller::Histogram PatternRulesHistogram; | |||||
bool do_MinuteReport(); // Send our 1 minute status report. | bool do_MinuteReport(); // Send our 1 minute status report. | ||||
// Every hour we get a summary. | // Every hour we get a summary. | ||||
bool HourReport_Log_OnOff; | bool HourReport_Log_OnOff; | ||||
bool HourReport_Append_OnOff; | bool HourReport_Append_OnOff; | ||||
string HourReport_Log_Filename; | |||||
string HourReportText; | |||||
string HourReportTimestamp; | |||||
std::string HourReport_Log_Filename; | |||||
std::string HourReportText; | |||||
std::string HourReportTimestamp; | |||||
bool do_HourReport(); // Send our 1 hour status report. | bool do_HourReport(); // Send our 1 hour status report. | ||||
void postStatusLog( // Post a Status log if required. | void postStatusLog( // Post a Status log if required. | ||||
const string& LogData, // Here's the log entry's data. | |||||
const string& LogFileName, // Here is where it should go. | |||||
const std::string& LogData, // Here's the log entry's data. | |||||
const std::string& LogFileName, // Here is where it should go. | |||||
const bool LogEnabled, // This is true if we should write it. | const bool LogEnabled, // This is true if we should write it. | ||||
const bool AppendNotOverwrite, // True=Append, False=Overwrite. | const bool AppendNotOverwrite, // True=Append, False=Overwrite. | ||||
DiscLogger& Logger // Lazy Log Writer to use. | DiscLogger& Logger // Lazy Log Writer to use. | ||||
void configure(snfCFGData& CFGData); // Update the configuration. | void configure(snfCFGData& CFGData); // Update the configuration. | ||||
void updateActiveUTC(string ActiveUTC); // Set active rulebase UTC. | |||||
void updateActiveUTC(std::string ActiveUTC); // Set active rulebase UTC. | |||||
void logThisIPTest(IPTestRecord& I, string Action); // Capthre the data from an IP test. | |||||
void logThisIPTest(IPTestRecord& I, std::string Action); // Capthre the data from an IP test. | |||||
void logThisScan(snfCFGData& CFGData, snfScanData& ScanData); // Capture the data from this scan. | void logThisScan(snfCFGData& CFGData, snfScanData& ScanData); // Capture the data from this scan. | ||||
void logThisError(snfScanData& ScanData, const string ContextName, // Inject an error log entry for this | |||||
const int Code, const string Text // scan using this number & message. | |||||
void logThisError(snfScanData& ScanData, const std::string ContextName, // Inject an error log entry for this | |||||
const int Code, const std::string Text // scan using this number & message. | |||||
); | ); | ||||
void logThisError(string ContextName, int Code, string Text); // Log an error message. | |||||
void logThisError(std::string ContextName, int Code, std::string Text); // Log an error message. | |||||
void logThisInfo(string ContextName, int Code, string text); // Log an informational message. | |||||
void logThisInfo(std::string ContextName, int Code, std::string text); // Log an informational message. | |||||
string PlatformVersion(string NewPlatformVersion); // Set platform version info. | |||||
string PlatformVersion(); // Get platform version info. | |||||
std::string PlatformVersion(std::string NewPlatformVersion); // Set platform version info. | |||||
std::string PlatformVersion(); // Get platform version info. | |||||
string EngineVersion(); // Get engine version info. | |||||
std::string EngineVersion(); // Get engine version info. | |||||
void updateAvailableUTC(string& AvailableRulebaseTimestamp); // Stores Available, true==update ready. | |||||
string ActiveRulebaseTimestamp(); // Get active rulebase timestamp. | |||||
string AvailableRulebaseTimestamp(); // Get available rulebase timestamp. | |||||
void updateAvailableUTC(std::string& AvailableRulebaseTimestamp); // Stores Available, true==update ready. | |||||
std::string ActiveRulebaseTimestamp(); // Get active rulebase timestamp. | |||||
std::string AvailableRulebaseTimestamp(); // Get available rulebase timestamp. | |||||
bool isUpdateAvailable(); // True if update is available. | bool isUpdateAvailable(); // True if update is available. | ||||
bool OkToSample(int SampleOneInX); // Check to see if it's ok to sample. | bool OkToSample(int SampleOneInX); // Check to see if it's ok to sample. | ||||
time_t Timestamp(); // Get an ordinary timestamp. | time_t Timestamp(); // Get an ordinary timestamp. | ||||
string Timestamp(time_t t); // Convert time_t to a timestamp s. | |||||
string& Timestamp(string& s); // Appends a current timestamp in s. | |||||
string LocalTimestamp(time_t t); // Convert time_t to a local timestamp s. | |||||
string& LocalTimestamp(string& s); // Appends a current local timestamp in s. | |||||
std::string Timestamp(time_t t); // Convert time_t to a timestamp s. | |||||
std::string& Timestamp(std::string& s); // Appends a current timestamp in s. | |||||
std::string LocalTimestamp(time_t t); // Convert time_t to a local timestamp s. | |||||
std::string& LocalTimestamp(std::string& s); // Appends a current local timestamp in s. | |||||
unsigned int SerialNumber(); // Returns the next serial number. | unsigned int SerialNumber(); // Returns the next serial number. | ||||
string& SerialNumber(string& s); // Appends the next serial number. | |||||
std::string& SerialNumber(std::string& s); // Appends the next serial number. | |||||
int SecsSinceStartup(); // Gets seconds since starup. | int SecsSinceStartup(); // Gets seconds since starup. | ||||
void RecordSyncEvent(); // Sets timestamp of latest Sync. | void RecordSyncEvent(); // Sets timestamp of latest Sync. | ||||
int RunningTime(); // Seconds running since startup. | int RunningTime(); // Seconds running since startup. | ||||
string getStatusSecondReport(); // Get latest status.second report. | |||||
string getStatusMinuteReport(); // Get latest status.minute report. | |||||
string getStatusHourReport(); // Get latest status.hour report. | |||||
std::string getStatusSecondReport(); // Get latest status.second report. | |||||
std::string getStatusMinuteReport(); // Get latest status.minute report. | |||||
std::string getStatusHourReport(); // Get latest status.hour report. | |||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
}; | }; | ||||
#include "snfLOGmgr.inline.hpp" | #include "snfLOGmgr.inline.hpp" | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||
//// End snfLOGmgr include only once | //// End snfLOGmgr include only once |
return SourceIPRangeFlag; // Return what the flag says. | return SourceIPRangeFlag; // Return what the flag says. | ||||
} | } | ||||
inline IP4Address snfScanData::HeaderDirectiveSourceIP(IP4Address A) { // set Header directive source IP. | |||||
inline CodeDweller::IP4Address | |||||
snfScanData::HeaderDirectiveSourceIP(CodeDweller::IP4Address A) { // set Header directive source IP. | |||||
if(0UL == myHeaderDirectiveSourceIP) myHeaderDirectiveSourceIP = A; // If this value is not set, set it. | if(0UL == myHeaderDirectiveSourceIP) myHeaderDirectiveSourceIP = A; // If this value is not set, set it. | ||||
return myHeaderDirectiveSourceIP; // Return the value. | return myHeaderDirectiveSourceIP; // Return the value. | ||||
} | } | ||||
inline IP4Address snfScanData::HeaderDirectiveSourceIP() { // get Header directive source IP. | |||||
inline CodeDweller::IP4Address snfScanData::HeaderDirectiveSourceIP() { // get Header directive source IP. | |||||
return myHeaderDirectiveSourceIP; // Return the current value. | return myHeaderDirectiveSourceIP; // Return the current value. | ||||
} | } | ||||
inline IP4Address snfScanData::CallerForcedSourceIP(IP4Address A) { // set Caller forced source IP. | |||||
inline CodeDweller::IP4Address | |||||
snfScanData::CallerForcedSourceIP(CodeDweller::IP4Address A) { // set Caller forced source IP. | |||||
if(0UL == myCallerForcedSourceIP) myCallerForcedSourceIP = A; // If this value is not set, set it. | if(0UL == myCallerForcedSourceIP) myCallerForcedSourceIP = A; // If this value is not set, set it. | ||||
return myCallerForcedSourceIP; // Return the value. | return myCallerForcedSourceIP; // Return the value. | ||||
} | } | ||||
inline IP4Address snfScanData::CallerForcedSourceIP() { // get Caller forced source IP. | |||||
inline CodeDweller::IP4Address snfScanData::CallerForcedSourceIP() { // get Caller forced source IP. | |||||
return myCallerForcedSourceIP; // Return the current value. | return myCallerForcedSourceIP; // Return the current value. | ||||
} | } | ||||
//// snfLOGmgr ///////////////////////////////////////////////////////////////// | //// snfLOGmgr ///////////////////////////////////////////////////////////////// | ||||
inline void snfLOGmgr::updateActiveUTC(string ActiveUTC) { // Update Active Rulebase UTC. | |||||
ScopeMutex Freeze(MyMutex); // Protect the strings. | |||||
inline void snfLOGmgr::updateActiveUTC(std::string ActiveUTC) { // Update Active Rulebase UTC. | |||||
CodeDweller::ScopeMutex Freeze(MyMutex); // Protect the strings. | |||||
ActiveRulebaseUTC = ActiveUTC; // Update the active timestamp. | ActiveRulebaseUTC = ActiveUTC; // Update the active timestamp. | ||||
NewerRulebaseIsAvailable = false; // Update availability is now unknown. | NewerRulebaseIsAvailable = false; // Update availability is now unknown. | ||||
} | } | ||||
inline void snfLOGmgr::updateAvailableUTC(string& AvailableRulebaseTimestamp) { // Changes update avialability stamp. | |||||
ScopeMutex Freeze(MyMutex); // Protect the strings. | |||||
inline void snfLOGmgr::updateAvailableUTC(std::string& AvailableRulebaseTimestamp) {// Changes update avialability stamp. | |||||
CodeDweller::ScopeMutex Freeze(MyMutex); // Protect the strings. | |||||
AvailableRulebaseUTC = AvailableRulebaseTimestamp; // Store the new timestamp. | AvailableRulebaseUTC = AvailableRulebaseTimestamp; // Store the new timestamp. | ||||
if(0 < AvailableRulebaseUTC.compare(ActiveRulebaseUTC)) { // If the available timestamp is newer | if(0 < AvailableRulebaseUTC.compare(ActiveRulebaseUTC)) { // If the available timestamp is newer | ||||
NewerRulebaseIsAvailable = true; // than the active then set the flag. | NewerRulebaseIsAvailable = true; // than the active then set the flag. | ||||
} | } | ||||
} | } | ||||
inline string snfLOGmgr::ActiveRulebaseTimestamp() { // Get active rulebase timestamp. | |||||
ScopeMutex Freeze(MyMutex); // Protect the string. | |||||
inline std::string snfLOGmgr::ActiveRulebaseTimestamp() { // Get active rulebase timestamp. | |||||
CodeDweller::ScopeMutex Freeze(MyMutex); // Protect the string. | |||||
return ActiveRulebaseUTC; // Return it. | return ActiveRulebaseUTC; // Return it. | ||||
} | } | ||||
inline string snfLOGmgr::AvailableRulebaseTimestamp() { // Get available rulebase timestamp. | |||||
ScopeMutex Freeze(MyMutex); // Protect the strings. | |||||
inline std::string snfLOGmgr::AvailableRulebaseTimestamp() { // Get available rulebase timestamp. | |||||
CodeDweller::ScopeMutex Freeze(MyMutex); // Protect the strings. | |||||
return AvailableRulebaseUTC; // Return the available timestamp. | return AvailableRulebaseUTC; // Return the available timestamp. | ||||
} | } | ||||
#include <vector> | #include <vector> | ||||
#include <fstream> | #include <fstream> | ||||
#include <sstream> | #include <sstream> | ||||
#include "snfNETmgr.hpp" | |||||
#include "snf_sync.hpp" | |||||
#include "../CodeDweller/mangler.hpp" | |||||
#include "../CodeDweller/base64codec.hpp" | |||||
#include "SNFMulti/snfNETmgr.hpp" | |||||
#include "SNFMulti/snf_sync.hpp" | |||||
#include "CodeDweller/mangler.hpp" | |||||
#include "CodeDweller/base64codec.hpp" | |||||
// #include "tcp_watchdog.hpp" No longer using TCPWatchdog -- see below _M | // #include "tcp_watchdog.hpp" No longer using TCPWatchdog -- see below _M | ||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
///// utilities //////////////////////////////////////////////////////////////// | ///// utilities //////////////////////////////////////////////////////////////// | ||||
); | ); | ||||
} | } | ||||
} | } | ||||
} |
#include <stdexcept> | #include <stdexcept> | ||||
#include <vector> | #include <vector> | ||||
#include "../CodeDweller/networking.hpp" | |||||
#include "../CodeDweller/timing.hpp" | |||||
#include "../CodeDweller/threading.hpp" | |||||
#include "../CodeDweller/mangler.hpp" | |||||
#include "snfCFGmgr.hpp" | |||||
#include "snfLOGmgr.hpp" | |||||
#include "snfGBUdbmgr.hpp" | |||||
#include "CodeDweller/networking.hpp" | |||||
#include "CodeDweller/timing.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include "CodeDweller/mangler.hpp" | |||||
#include "SNFMulti/snfCFGmgr.hpp" | |||||
#include "SNFMulti/snfLOGmgr.hpp" | |||||
#include "SNFMulti/snfGBUdbmgr.hpp" | |||||
namespace SNFMulti { | |||||
class snfScanData; // Declare snfScanData; | class snfScanData; // Declare snfScanData; | ||||
class snfLOGmgr; // Declare snfLOGmgr; | class snfLOGmgr; // Declare snfLOGmgr; | ||||
class snfGBUdbmgr; // Declare snfGBUdbmgr; | class snfGBUdbmgr; // Declare snfGBUdbmgr; | ||||
using namespace std; | |||||
typedef vector<unsigned char> PadBuffer; // Holds one time pads etc. | |||||
typedef std::vector<unsigned char> PadBuffer; // Holds one time pads etc. | |||||
const unsigned int SNFHandshakeSize = 8; // Size of an SNF Handshake. | const unsigned int SNFHandshakeSize = 8; // Size of an SNF Handshake. | ||||
const unsigned int SNFChallengeSize = 32; // Size of an SNF Challenge. | const unsigned int SNFChallengeSize = 32; // Size of an SNF Challenge. | ||||
const unsigned int SNFPadSize = 16; // Size of an SNF One Time Pad. | const unsigned int SNFPadSize = 16; // Size of an SNF One Time Pad. | ||||
const unsigned int SNFSignatureSize = SNFHandshakeSize; // Size of an SNF Signature. | const unsigned int SNFSignatureSize = SNFHandshakeSize; // Size of an SNF Signature. | ||||
class snfNETmgr : public Thread { // The network process manager. | |||||
class snfNETmgr : public CodeDweller::Thread { // The network process manager. | |||||
private: | private: | ||||
Mutex myMutex; // Object is busy mutex. | |||||
Mutex ResolverMutex; // Mutex to protect lookups. | |||||
Mutex ConfigMutex; // Configuration change/use mutex. | |||||
Mutex PadMutex; // Pad use/evoloution mutex. | |||||
CodeDweller::Mutex myMutex; // Object is busy mutex. | |||||
CodeDweller::Mutex ResolverMutex; // Mutex to protect lookups. | |||||
CodeDweller::Mutex ConfigMutex; // Configuration change/use mutex. | |||||
CodeDweller::Mutex PadMutex; // Pad use/evoloution mutex. | |||||
snfLOGmgr* myLOGmgr; // Log manager to use. | snfLOGmgr* myLOGmgr; // Log manager to use. | ||||
snfGBUdbmgr* myGBUdbmgr; // GBUdb manager to use. | snfGBUdbmgr* myGBUdbmgr; // GBUdb manager to use. | ||||
volatile bool isTimeToStop; // Time to shutdown flag. | volatile bool isTimeToStop; // Time to shutdown flag. | ||||
volatile bool isConfigured; // True once ready to run. | volatile bool isConfigured; // True once ready to run. | ||||
Timeout SYNCTimer; // SYNC timer. | |||||
CodeDweller::Timeout SYNCTimer; // SYNC timer. | |||||
void evolvePad(string Entropy = ""); // Add entropy to and evolve. | |||||
MANGLER PadGenerator; // Random pad source. | |||||
void evolvePad(std::string Entropy = ""); // Add entropy to and evolve. | |||||
CodeDweller::MANGLER PadGenerator; // Random pad source. | |||||
PadBuffer OneTimePad(int Len = SNFPadSize); // Provides Len bytes of one time pad. | PadBuffer OneTimePad(int Len = SNFPadSize); // Provides Len bytes of one time pad. | ||||
// Configuration data | // Configuration data | ||||
string License; // Node (license) Id? | |||||
string SecurityKey; // Security key for this rulebase? | |||||
string RulebaseFilePath; // Where we can find our rulebase? | |||||
string HandshakeFilePath; // Where do we keep our handshake? | |||||
string UpdateReadyFilePath; // Where do I put update trigger files? | |||||
string SyncHostName; // Where do we connect to sync? | |||||
std::string License; // Node (license) Id? | |||||
std::string SecurityKey; // Security key for this rulebase? | |||||
std::string RulebaseFilePath; // Where we can find our rulebase? | |||||
std::string HandshakeFilePath; // Where do we keep our handshake? | |||||
std::string UpdateReadyFilePath; // Where do I put update trigger files? | |||||
std::string SyncHostName; // Where do we connect to sync? | |||||
int SyncHostPort; // What port do we use to sync? | int SyncHostPort; // What port do we use to sync? | ||||
int SyncSecsOverride; // How may secs between sync (override)? | int SyncSecsOverride; // How may secs between sync (override)? | ||||
int SyncSecsConfigured; // How many secs to sync (nominally)? | int SyncSecsConfigured; // How many secs to sync (nominally)? | ||||
PadBuffer& Handshake(PadBuffer& NewHandshake); // Store a new handshake. | PadBuffer& Handshake(PadBuffer& NewHandshake); // Store a new handshake. | ||||
PadBuffer CurrentHandshake; // Where we keep our current handshake. | PadBuffer CurrentHandshake; // Where we keep our current handshake. | ||||
void postUpdateTrigger(string& updateUTC); // Post an update trigger file. | |||||
void postUpdateTrigger(std::string& updateUTC); // Post an update trigger file. | |||||
string SamplesBuffer; // Message Samples Appended Together. | |||||
string getSamples(); // Syncrhonized way to get Samples. | |||||
string ReportsBuffer; // Status Reports Appended Together. | |||||
string getReports(); // Synchronized way to get Reports. | |||||
std::string SamplesBuffer; // Message Samples Appended Together. | |||||
std::string getSamples(); // Syncrhonized way to get Samples. | |||||
std::string ReportsBuffer; // Status Reports Appended Together. | |||||
std::string getReports(); // Synchronized way to get Reports. | |||||
public: | public: | ||||
void linkGBUdbmgr(snfGBUdbmgr& G); // Set the GBUdbmgr. | void linkGBUdbmgr(snfGBUdbmgr& G); // Set the GBUdbmgr. | ||||
void configure(snfCFGData& CFGData); // Update the configuration. | void configure(snfCFGData& CFGData); // Update the configuration. | ||||
class SyncFailed : public runtime_error { // Thrown if sync doesn't work. | |||||
public: SyncFailed(const string& w):runtime_error(w) {} | |||||
class SyncFailed : public std::runtime_error { // Thrown if sync doesn't work. | |||||
public: SyncFailed(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
// Operations | // Operations | ||||
int MessageLength // and it is this size. | int MessageLength // and it is this size. | ||||
); | ); | ||||
void sendReport(const string& StatusReportText); // Send a status report... | |||||
void sendReport(const std::string& StatusReportText); // Send a status report... | |||||
void sync(); // Do the whole "sync" thing. | void sync(); // Do the whole "sync" thing. | ||||
// Utility Functions | // Utility Functions | ||||
unsigned long ResolveHostIPFromName(const string& N); // Find the IP. | |||||
string& RulebaseUTC(string& t); // Gets local rulebase file UTC. | |||||
const static ThreadType Type; // The thread's type. | |||||
const static ThreadState Sleeping; // Taking a break. | |||||
const static ThreadState SYNC_Connect; // Connecting to SYNC server. | |||||
const static ThreadState SYNC_Read_Challenge; // Reading challenge. | |||||
const static ThreadState SYNC_Compute_Response; // Computing crypto response. | |||||
const static ThreadState SYNC_Send_Response; // Sending crypto response. | |||||
const static ThreadState SYNC_Read_Availabilty; // Reading rulebase status. | |||||
const static ThreadState SYNC_Send_GBUdb_Alerts; // Sending GBUdb alerts. | |||||
const static ThreadState SYNC_Send_Status_Reports; // Sending status reports. | |||||
const static ThreadState SYNC_Send_Samples; // Sending message samples. | |||||
const static ThreadState SYNC_Send_End_Of_Report; // Sending end of client data. | |||||
const static ThreadState SYNC_Read_Server_Response; // Reading server data. | |||||
const static ThreadState SYNC_Close_Connection; // Closing connection. | |||||
const static ThreadState SYNC_Parse_GBUdb_Reflections; // Parsing GBUdb reflections. | |||||
const static ThreadState SYNC_Log_Event; // Logging SYNC event. | |||||
unsigned long ResolveHostIPFromName(const std::string& N); // Find the IP. | |||||
std::string& RulebaseUTC(std::string& t); // Gets local rulebase file UTC. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadState Sleeping; // Taking a break. | |||||
const static CodeDweller::ThreadState SYNC_Connect; // Connecting to SYNC server. | |||||
const static CodeDweller::ThreadState SYNC_Read_Challenge; // Reading challenge. | |||||
const static CodeDweller::ThreadState SYNC_Compute_Response; // Computing crypto response. | |||||
const static CodeDweller::ThreadState SYNC_Send_Response; // Sending crypto response. | |||||
const static CodeDweller::ThreadState SYNC_Read_Availabilty; // Reading rulebase status. | |||||
const static CodeDweller::ThreadState SYNC_Send_GBUdb_Alerts; // Sending GBUdb alerts. | |||||
const static CodeDweller::ThreadState SYNC_Send_Status_Reports; // Sending status reports. | |||||
const static CodeDweller::ThreadState SYNC_Send_Samples; // Sending message samples. | |||||
const static CodeDweller::ThreadState SYNC_Send_End_Of_Report; // Sending end of client data. | |||||
const static CodeDweller::ThreadState SYNC_Read_Server_Response; // Reading server data. | |||||
const static CodeDweller::ThreadState SYNC_Close_Connection; // Closing connection. | |||||
const static CodeDweller::ThreadState SYNC_Parse_GBUdb_Reflections; // Parsing GBUdb reflections. | |||||
const static CodeDweller::ThreadState SYNC_Log_Event; // Logging SYNC event. | |||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||
// | // | ||||
// See snfXCImgr.hpp for details. | // See snfXCImgr.hpp for details. | ||||
#include "SNFMulti.hpp" | |||||
#include "snfXCImgr.hpp" | |||||
#include "SNFMulti/SNFMulti.hpp" | |||||
#include "SNFMulti/snfXCImgr.hpp" | |||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
// snfXCIServerCommandHandler Virtual Base Class Default Processor. | // snfXCIServerCommandHandler Virtual Base Class Default Processor. | ||||
} | } | ||||
} | } | ||||
} |
#include <string> | #include <string> | ||||
#include <queue> | #include <queue> | ||||
#include "../CodeDweller/timing.hpp" | |||||
#include "../CodeDweller/threading.hpp" | |||||
#include "../CodeDweller/networking.hpp" | |||||
#include "snf_xci.hpp" | |||||
#include "CodeDweller/timing.hpp" | |||||
#include "CodeDweller/threading.hpp" | |||||
#include "CodeDweller/networking.hpp" | |||||
#include "SNFMulti/snf_xci.hpp" | |||||
using namespace std; | |||||
namespace SNFMulti { | |||||
// We need to know these exist ;-) | // We need to know these exist ;-) | ||||
// Handy references and "standards" | // Handy references and "standards" | ||||
static const string XCIErrorResponse = // Unrecognized request error. | |||||
static const std::string XCIErrorResponse = // Unrecognized request error. | |||||
"<snf><xci><error message=\'What was that?\'/></xci></snf>\n"; | "<snf><xci><error message=\'What was that?\'/></xci></snf>\n"; | ||||
static const string XCIBadSetResponse = // Empty GBUdb set command error. | |||||
static const std::string XCIBadSetResponse = // Empty GBUdb set command error. | |||||
"<snf><xci><error message=\'No changes in set. Use test!\'/></xci></snf>\n"; | "<snf><xci><error message=\'No changes in set. Use test!\'/></xci></snf>\n"; | ||||
// snfXCIServerCommandHandler Base Class for Server Command Processing. | // snfXCIServerCommandHandler Base Class for Server Command Processing. | ||||
class snfXCIServerCommandHandler { // Server Command Handler Base Class. | class snfXCIServerCommandHandler { // Server Command Handler Base Class. | ||||
public: | public: | ||||
virtual string processXCIRequest(snf_xci& X); // Server provides a useful processor. | |||||
virtual std::string processXCIRequest(snf_xci& X); // Server provides a useful processor. | |||||
}; | }; | ||||
// snfXCIJob encapsulates a single XCI transaction. | // snfXCIJob encapsulates a single XCI transaction. | ||||
class snfXCIJob { // Job Packet. | class snfXCIJob { // Job Packet. | ||||
public: | public: | ||||
string Request; // XCI formatted request. | |||||
string Response; // XCI formatted response. | |||||
std::string Request; // XCI formatted request. | |||||
std::string Response; // XCI formatted response. | |||||
int SetupTime; // Setup time so far in ms. | int SetupTime; // Setup time so far in ms. | ||||
void clear(); // Clear the buffers. | void clear(); // Clear the buffers. | ||||
}; | }; | ||||
bool isReportJob(); // True if myXCI is a Report job. | bool isReportJob(); // True if myXCI is a Report job. | ||||
bool isCommandJob(); // True if myXCI is a Command job. | bool isCommandJob(); // True if myXCI is a Command job. | ||||
void processScan(snfXCIJob& J); // Process a scan request. | void processScan(snfXCIJob& J); // Process a scan request. | ||||
string processGBUdb(); // Process a GBUdb request. | |||||
string processStatusReport(); // Process a report request. | |||||
std::string processGBUdb(); // Process a GBUdb request. | |||||
std::string processStatusReport(); // Process a report request. | |||||
public: | public: | ||||
snfXCIJobProcessor(snf_RulebaseHandler* H); // Setup scanner. | snfXCIJobProcessor(snf_RulebaseHandler* H); // Setup scanner. | ||||
class ChannelJob { // Wraper for job queue. | class ChannelJob { // Wraper for job queue. | ||||
private: | private: | ||||
TCPClient* myClient; // We have a TCPClient. | |||||
Timer Lifetime; // We have a timer. | |||||
CodeDweller::TCPClient* myClient; // We have a TCPClient. | |||||
CodeDweller::Timer Lifetime; // We have a timer. | |||||
public: | public: | ||||
ChannelJob(); // We can be blank but usually | ChannelJob(); // We can be blank but usually | ||||
ChannelJob(TCPClient* C); // we are created like this. | |||||
msclock Age(); // How old is this job? | |||||
TCPClient* Client(); // What client does it hold? | |||||
ChannelJob(CodeDweller::TCPClient* C); // we are created like this. | |||||
CodeDweller::msclock Age(); // How old is this job? | |||||
CodeDweller::TCPClient* Client(); // What client does it hold? | |||||
}; | }; | ||||
// snfXCITCPChannel encapsulates the logic to queue and handle TCPClients for | // snfXCITCPChannel encapsulates the logic to queue and handle TCPClients for | ||||
const int LineBufferSize = 256; // Line buffer size. | const int LineBufferSize = 256; // Line buffer size. | ||||
class snfXCITCPChannel : private Thread { // TCPClient processor & queue. | |||||
class snfXCITCPChannel : private CodeDweller::Thread { // TCPClient processor & queue. | |||||
private: | private: | ||||
snf_RulebaseHandler* myHome; // Rulebase handler. | snf_RulebaseHandler* myHome; // Rulebase handler. | ||||
snfXCIJob Job; // XCI Job buffer. | snfXCIJob Job; // XCI Job buffer. | ||||
volatile int LatestSize; // Queue Size Blinking Light. | volatile int LatestSize; // Queue Size Blinking Light. | ||||
Mutex QueueMutex; // Serializes queue changes. | |||||
ProductionGateway QueueGateway; // Keeps track of give and take. | |||||
queue<ChannelJob> JobQueue; // Queue of clients. | |||||
CodeDweller::Mutex QueueMutex; // Serializes queue changes. | |||||
CodeDweller::ProductionGateway QueueGateway; // Keeps track of give and take. | |||||
std::queue<ChannelJob> JobQueue; // Queue of clients. | |||||
void give(ChannelJob& J); // give a client to the queue. | void give(ChannelJob& J); // give a client to the queue. | ||||
ChannelJob take(); // take a client from the queue. | ChannelJob take(); // take a client from the queue. | ||||
char LineBuffer[LineBufferSize]; // Read Line Buffer. | char LineBuffer[LineBufferSize]; // Read Line Buffer. | ||||
void readRequest(TCPClient* Client); // Read Job.Request from Client. | |||||
void writeResponse(TCPClient* Client); // Write Job.Request from Client. | |||||
void readRequest(CodeDweller::TCPClient* Client); // Read Job.Request from Client. | |||||
void writeResponse(CodeDweller::TCPClient* Client); // Write Job.Request from Client. | |||||
void myTask(); // Thread's main loop. | void myTask(); // Thread's main loop. | ||||
public: | public: | ||||
snfXCITCPChannel(snf_RulebaseHandler* H, string N); // Create these with a home rulebase. | |||||
snfXCITCPChannel(snf_RulebaseHandler* H, std::string N); // Create these with a home rulebase. | |||||
~snfXCITCPChannel(); // Destroy them very carefully. | ~snfXCITCPChannel(); // Destroy them very carefully. | ||||
int Size(); // Keep track of how full they are. | int Size(); // Keep track of how full they are. | ||||
void submit(TCPClient* C); // This is how we submit jobs. | |||||
void submit(CodeDweller::TCPClient* C); // This is how we submit jobs. | |||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
const static ThreadState XCI_Wait; | |||||
const static ThreadState XCI_Read; | |||||
const static ThreadState XCI_Process; | |||||
const static ThreadState XCI_Write; | |||||
const static ThreadState XCI_Close; | |||||
const static ThreadState XCI_Clear; | |||||
const static ThreadState XCI_Shutdown; | |||||
const static CodeDweller::ThreadState XCI_Wait; | |||||
const static CodeDweller::ThreadState XCI_Read; | |||||
const static CodeDweller::ThreadState XCI_Process; | |||||
const static CodeDweller::ThreadState XCI_Write; | |||||
const static CodeDweller::ThreadState XCI_Close; | |||||
const static CodeDweller::ThreadState XCI_Clear; | |||||
const static CodeDweller::ThreadState XCI_Shutdown; | |||||
//const static ThreadState ThreadInitialized; // Constructed successfully. | //const static ThreadState ThreadInitialized; // Constructed successfully. | ||||
}; | }; | ||||
// performs the required actions, and returns an XCI response. It also checks | // performs the required actions, and returns an XCI response. It also checks | ||||
// to see if the configuration for the XCI interface has changed. | // to see if the configuration for the XCI interface has changed. | ||||
class snfXCImgr : private Thread { // XCI manager. | |||||
class snfXCImgr : private CodeDweller::Thread { // XCI manager. | |||||
private: | private: | ||||
Mutex ChannelMutex; // Safety Channel Up/Down events. | |||||
CodeDweller::Mutex ChannelMutex; // Safety Channel Up/Down events. | |||||
bool CFG_XCI_ON; // Is XCI turned on? | bool CFG_XCI_ON; // Is XCI turned on? | ||||
int CFG_XCI_PORT; // What port we listen to? | int CFG_XCI_PORT; // What port we listen to? | ||||
snfXCITCPChannel* BestAvailableChannel(); // Selects XCI channel w/ lowest queue. | snfXCITCPChannel* BestAvailableChannel(); // Selects XCI channel w/ lowest queue. | ||||
TCPListener* Listener; // XCI Listener. | |||||
CodeDweller::TCPListener* Listener; // XCI Listener. | |||||
bool XCI_UP; // True if XCI is alive. | bool XCI_UP; // True if XCI is alive. | ||||
void startup_Listener(); // Listener startup function. | void startup_Listener(); // Listener startup function. | ||||
int pollLoopCount(); // Get diagnostic loop count. | int pollLoopCount(); // Get diagnostic loop count. | ||||
int pollClientCount(); // Get diagnostic client count. | int pollClientCount(); // Get diagnostic client count. | ||||
const static ThreadType Type; // The thread's type. | |||||
const static CodeDweller::ThreadType Type; // The thread's type. | |||||
const static ThreadState XCI_InitialConfig; // Getting initial configuration. | |||||
const static ThreadState XCI_InitialStartup; // Performing first startup. | |||||
const static ThreadState XCI_CheckConfig; // Checking configuration. | |||||
const static ThreadState XCI_PollingListener; // Polling Listener for jobs. | |||||
const static ThreadState XCI_SubmittingJob; // Submitting a new job. | |||||
const static ThreadState XCI_ListenerDown; // Listener is down. | |||||
const static ThreadState XCI_Stopping; // XCImgr Exiting Big Loop | |||||
const static CodeDweller::ThreadState XCI_InitialConfig; // Getting initial configuration. | |||||
const static CodeDweller::ThreadState XCI_InitialStartup; // Performing first startup. | |||||
const static CodeDweller::ThreadState XCI_CheckConfig; // Checking configuration. | |||||
const static CodeDweller::ThreadState XCI_PollingListener; // Polling Listener for jobs. | |||||
const static CodeDweller::ThreadState XCI_SubmittingJob; // Submitting a new job. | |||||
const static CodeDweller::ThreadState XCI_ListenerDown; // Listener is down. | |||||
const static CodeDweller::ThreadState XCI_Stopping; // XCImgr Exiting Big Loop | |||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif |
// | // | ||||
// See snf_HeaderFinder.hpp for details | // See snf_HeaderFinder.hpp for details | ||||
#include "snf_HeaderFinder.hpp" | |||||
#include "SNFMulti/snf_HeaderFinder.hpp" | |||||
#include "snfLOGmgr.hpp" | |||||
#include "snfCFGmgr.hpp" | |||||
#include "SNFMulti/snfLOGmgr.hpp" | |||||
#include "SNFMulti/snfCFGmgr.hpp" | |||||
using namespace std; | |||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
const int NumberOfByteValues = 256; // Number of possible byte values. | const int NumberOfByteValues = 256; // Number of possible byte values. | ||||
} | } | ||||
} | } | ||||
} |
#include <map> | #include <map> | ||||
#include <vector> | #include <vector> | ||||
using namespace std; | |||||
namespace SNFMulti { | |||||
struct HeaderFinderPattern { // Input pattern for header finder. | struct HeaderFinderPattern { // Input pattern for header finder. | ||||
string Header; // Header name to match. | |||||
std::string Header; // Header name to match. | |||||
int Ordinal; // Which instance to match. | int Ordinal; // Which instance to match. | ||||
int Context; // Context link (for pairing patterns). | int Context; // Context link (for pairing patterns). | ||||
string Contains; // What to find in the header. | |||||
std::string Contains; // What to find in the header. | |||||
unsigned long int Directive; // What directive to present. | unsigned long int Directive; // What directive to present. | ||||
HeaderFinderPattern(): // When constructing a finder parttern | HeaderFinderPattern(): // When constructing a finder parttern | ||||
const bool operator<(const HeaderFinderPattern& R) const; // Comparator for set<> living. | const bool operator<(const HeaderFinderPattern& R) const; // Comparator for set<> living. | ||||
}; | }; | ||||
typedef set<HeaderFinderPattern> HeaderDirectiveSet; // Convenient set typedef. | |||||
typedef set<HeaderFinderPattern>::iterator HeaderDirectiveIterator; // Convenient iterator typedef. | |||||
typedef std::set<HeaderFinderPattern> HeaderDirectiveSet; // Convenient set typedef. | |||||
typedef std::set<HeaderFinderPattern>::iterator HeaderDirectiveIterator; // Convenient iterator typedef. | |||||
typedef map<const string, int> NameOrdinalMap; // Header Ordinal Count Map. | |||||
typedef std::map<const std::string, int> NameOrdinalMap; // Header Ordinal Count Map. | |||||
// Upon construction the HeaderFinder scans the headers for matching directives | // Upon construction the HeaderFinder scans the headers for matching directives | ||||
// and leaves the composite results ready for inspection via the () operator. | // and leaves the composite results ready for inspection via the () operator. | ||||
const unsigned char* Bfr; // Message buffer. | const unsigned char* Bfr; // Message buffer. | ||||
const int Len; // Message length. | const int Len; // Message length. | ||||
vector<bool> ImpossibleBytes; // Cache of known impossible bytes. | |||||
std::vector<bool> ImpossibleBytes; // Cache of known impossible bytes. | |||||
unsigned long int Directives; // Composite result given this message. | unsigned long int Directives; // Composite result given this message. | ||||
set<int> ActivatedContexts; // Set of activated contexts. | |||||
std::set<int> ActivatedContexts; // Set of activated contexts. | |||||
NameOrdinalMap Ordinals; // Map of current header ordinals. | NameOrdinalMap Ordinals; // Map of current header ordinals. | ||||
void CheckContent(string& Header, const HeaderFinderPattern& P); // Check for a match in the header. | |||||
void MatchHeaders(string& Header); // Check that the header matches. | |||||
void CheckContent(std::string& Header, const HeaderFinderPattern& P); // Check for a match in the header. | |||||
void MatchHeaders(std::string& Header); // Check that the header matches. | |||||
bool ByteIsImpossible(unsigned char b); // Is b not first byte of any pattern? | bool ByteIsImpossible(unsigned char b); // Is b not first byte of any pattern? | ||||
void UnfoldHeaders(); // Unfold and check headers. | void UnfoldHeaders(); // Unfold and check headers. | ||||
); | ); | ||||
const unsigned long int operator()() const; // How to read the composite directives. | const unsigned long int operator()() const; // How to read the composite directives. | ||||
string EstablishedSourceIP; // Source IP from directive if any. | |||||
std::string EstablishedSourceIP; // Source IP from directive if any. | |||||
}; | }; | ||||
#include "snf_HeaderFinder.inline.hpp" | #include "snf_HeaderFinder.inline.hpp" | ||||
} // namespace SNFMulti | |||||
#endif | #endif |
#include <iostream> | #include <iostream> | ||||
#include <string> | #include <string> | ||||
#include <vector> | #include <vector> | ||||
#include "../CodeDweller/mangler.hpp" | |||||
#include "snf_engine.hpp" | |||||
#include "CodeDweller/mangler.hpp" | |||||
#include "SNFMulti/snf_engine.hpp" | |||||
using namespace std; | using namespace std; | ||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
/////////////////////////////////////////////////////////////////////////////////////////// | /////////////////////////////////////////////////////////////////////////////////////////// | ||||
// BEGIN IMPLEMENTATIONS ////////////////////////////////////////////////////////////////// | // BEGIN IMPLEMENTATIONS ////////////////////////////////////////////////////////////////// | ||||
finish = (finish < data.size()) ? finish : data.size(); | finish = (finish < data.size()) ? finish : data.size(); | ||||
for(unsigned int a = start; a < finish; a++) EvaluateThis(data[a]); | for(unsigned int a = start; a < finish; a++) EvaluateThis(data[a]); | ||||
} | } | ||||
} |
#include <string> | #include <string> | ||||
#include <vector> | #include <vector> | ||||
#include <exception> | #include <exception> | ||||
#include "../CodeDweller/faults.hpp" | |||||
#include "../CodeDweller/mangler.hpp" | |||||
#include "CodeDweller/faults.hpp" | |||||
#include "CodeDweller/mangler.hpp" | |||||
//#include "../nvwa-0.6/nvwa/debug_new.h" | //#include "../nvwa-0.6/nvwa/debug_new.h" | ||||
using namespace std; | |||||
namespace SNFMulti { | |||||
// 20030929 _M SYMBOL_RANGE moved to snf_engine.hpp as part of augmenting the | // 20030929 _M SYMBOL_RANGE moved to snf_engine.hpp as part of augmenting the | ||||
// capability of a match record. Match records now can decode themselves. | // capability of a match record. Match records now can decode themselves. | ||||
// Exceptions... | // Exceptions... | ||||
class BadAllocation : public runtime_error { // Exception for a bad memory allocation. | |||||
public: BadAllocation(const string& w):runtime_error(w) {} | |||||
class BadAllocation : public std::runtime_error { // Exception for a bad memory allocation. | |||||
public: BadAllocation(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class BadMatrix : public runtime_error { // Exception for invalid matrix loads. | |||||
public: BadMatrix(const string& w):runtime_error(w) {} | |||||
class BadMatrix : public std::runtime_error { // Exception for invalid matrix loads. | |||||
public: BadMatrix(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class BadFile : public runtime_error { // Exception for missing rulebase files. | |||||
public: BadFile(const string& w):runtime_error(w) {} | |||||
class BadFile : public std::runtime_error { // Exception for missing rulebase files. | |||||
public: BadFile(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class OutOfRange : public runtime_error { // Exception for indexes out of range. | |||||
public: OutOfRange(const string& w):runtime_error(w) {} | |||||
class OutOfRange : public std::runtime_error { // Exception for indexes out of range. | |||||
public: OutOfRange(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
// Standards... | // Standards... | ||||
void Load(const char* FileName); // Loads the matrix from a file name. | void Load(const char* FileName); // Loads the matrix from a file name. | ||||
void Load(string& FileName); // Loads the matrix from a file name string. | |||||
void Load(std::string& FileName); // Loads the matrix from a file name string. | |||||
void Load(ifstream& F); // Loads the token matrix from the file. | |||||
void Load(std::ifstream& F); // Loads the token matrix from the file. | |||||
void Validate(string& SecurityKey); // Validates the matrix with a key string. | |||||
void Validate(std::string& SecurityKey); // Validates the matrix with a key string. | |||||
void Verify(string& SecurityKey); // Verifies the matrix digest. | |||||
void Verify(std::string& SecurityKey); // Verifies the matrix digest. | |||||
void FlipEndian(); // Converts big/little endian tokens. | void FlipEndian(); // Converts big/little endian tokens. | ||||
Matrix(NULL), | Matrix(NULL), | ||||
MatrixSize(0) { } | MatrixSize(0) { } | ||||
TokenMatrix(ifstream& F) : | |||||
TokenMatrix(std::ifstream& F) : | |||||
Matrix(NULL), | Matrix(NULL), | ||||
MatrixSize(0) { | MatrixSize(0) { | ||||
Load(F); | Load(F); | ||||
// Exception classes... | // Exception classes... | ||||
class BadAllocation : public runtime_error { // Allocation failed exception. | |||||
public: BadAllocation(const string& w):runtime_error(w) {} | |||||
class BadAllocation : public std::runtime_error { // Allocation failed exception. | |||||
public: BadAllocation(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class MaxEvalsExceeded : public runtime_error { // Too many evaluators exception. | |||||
public: MaxEvalsExceeded(const string& w):runtime_error(w) {} | |||||
class MaxEvalsExceeded : public std::runtime_error { // Too many evaluators exception. | |||||
public: MaxEvalsExceeded(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
class OutOfRange : public runtime_error { // Out of range exception. | |||||
public: OutOfRange(const string& w):runtime_error(w) {} | |||||
class OutOfRange : public std::runtime_error { // Out of range exception. | |||||
public: OutOfRange(const std::string& w):std::runtime_error(w) {} | |||||
}; | }; | ||||
// Attributes... | // Attributes... | ||||
int EvaluateThis(unsigned short int i); | int EvaluateThis(unsigned short int i); | ||||
void evaluateSegment(vector<unsigned char>& data, unsigned int start, unsigned int finish); | |||||
void evaluateSegment(std::vector<unsigned char>& data, unsigned int start, unsigned int finish); | |||||
void restartEngineAt(int newCharacterCount); | void restartEngineAt(int newCharacterCount); | ||||
// When that first evaulator is used, the NULL pointer will return to the root | // When that first evaulator is used, the NULL pointer will return to the root | ||||
// of the EvaluatorCache list. In this regard the cache acts like a stack. | // of the EvaluatorCache list. In this regard the cache acts like a stack. | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||
#ifndef _ARM_snf_match | #ifndef _ARM_snf_match | ||||
#define _ARM_snf_match | #define _ARM_snf_match | ||||
namespace SNFMulti { | |||||
struct snf_match { | struct snf_match { | ||||
char flag; | char flag; | ||||
int symbol; | int symbol; | ||||
int endex; | int endex; | ||||
}; | }; | ||||
} | |||||
#endif | #endif |
#include <set> | #include <set> | ||||
#include <vector> | #include <vector> | ||||
#include "snf_saccades.hpp" | |||||
#include "SNFMulti/snf_saccades.hpp" | |||||
using namespace std; | using namespace std; | ||||
namespace SNFMulti { | |||||
bool doesOverlap(unsigned int workingStart, unsigned int testStart, unsigned int workingFinish) { | bool doesOverlap(unsigned int workingStart, unsigned int testStart, unsigned int workingFinish) { | ||||
return( | return( | ||||
testStart >= workingStart && | testStart >= workingStart && | ||||
evoke(experiences[i]); | evoke(experiences[i]); | ||||
} | } | ||||
} | } | ||||
} |
#include <set> | #include <set> | ||||
#include <vector> | #include <vector> | ||||
using namespace std; | |||||
namespace SNFMulti { | |||||
class saccades_engine; | class saccades_engine; | ||||
class saccade { | class saccade { | ||||
friend class saccades_engine; | friend class saccades_engine; | ||||
private: | private: | ||||
const static unsigned int stretchSize = 8; | const static unsigned int stretchSize = 8; | ||||
const static unsigned int stretchMark = stretchSize / 2; | const static unsigned int stretchMark = stretchSize / 2; | ||||
const static unsigned int stretchMask = ((~0UL) ^ (stretchSize - 1)); | |||||
const static unsigned int stretchMask = ((~0U) ^ (stretchSize - 1)); | |||||
unsigned int stretchLeft(unsigned int s) { | unsigned int stretchLeft(unsigned int s) { | ||||
s = (stretchMark > s) ? s : (s - (stretchMark)); | s = (stretchMark > s) ? s : (s - (stretchMark)); | ||||
class saccades_engine { | class saccades_engine { | ||||
private: | private: | ||||
vector<saccade_engram> engrams; | |||||
set<saccade_marker> markers; | |||||
std::vector<saccade_engram> engrams; | |||||
std::set<saccade_marker> markers; | |||||
const unsigned int capacity; | const unsigned int capacity; | ||||
int mostFresh; | int mostFresh; | ||||
engrams.reserve(capacity); | engrams.reserve(capacity); | ||||
} | } | ||||
vector<saccade> recall(); | |||||
void learn(vector<saccade>& experiences); | |||||
std::vector<saccade> recall(); | |||||
void learn(std::vector<saccade>& experiences); | |||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif |
// See www.armresearch.com for the copyright terms. | // See www.armresearch.com for the copyright terms. | ||||
// See snf_sync.hpp for details. | // See snf_sync.hpp for details. | ||||
#include "snf_sync.hpp" | |||||
#include "SNFMulti/snf_sync.hpp" | |||||
using namespace std; | |||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
void snf_sync::construct() { // Encapsulate initial construction. | void snf_sync::construct() { // Encapsulate initial construction. | ||||
ClientGBUAlertInitializer.link(ClientGBUAlertHandler); // Link the alert configurators. | ClientGBUAlertInitializer.link(ClientGBUAlertHandler); // Link the alert configurators. | ||||
Alert_g = 0; | Alert_g = 0; | ||||
AlertList.clear(); // Clear out the list. | AlertList.clear(); // Clear out the list. | ||||
} | } | ||||
} |
#include <list> | #include <list> | ||||
#include <cstring> | #include <cstring> | ||||
#include "GBUdb.hpp" | |||||
#include "../CodeDweller/networking.hpp" | |||||
#include "../CodeDweller/configuration.hpp" | |||||
#include "SNFMulti/GBUdb.hpp" | |||||
#include "CodeDweller/networking.hpp" | |||||
#include "CodeDweller/configuration.hpp" | |||||
class GBUAlertHandler : public Configurator { | |||||
namespace SNFMulti { | |||||
class GBUAlertHandler : public CodeDweller::Configurator { | |||||
public: | public: | ||||
virtual void operator()(ConfigurationElement& E, ConfigurationData& D); // Add an alert handler :-) | |||||
virtual void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D); // Add an alert handler :-) | |||||
void reset(); // Resets the list for a new run. | void reset(); // Resets the list for a new run. | ||||
list<GBUdbAlert> AlertList; // Our list of alerts. | |||||
std::list<GBUdbAlert> AlertList; // Our list of alerts. | |||||
// Input variables. | // Input variables. | ||||
string Alert_time; // time='YYYYMMDDhhmmss' | |||||
string Alert_ip; // ip='12.34.56.78' | |||||
string Alert_t; // t='Ugly', Good, Bad, Ignore | |||||
std::string Alert_time; // time='YYYYMMDDhhmmss' | |||||
std::string Alert_ip; // ip='12.34.56.78' | |||||
std::string Alert_t; // t='Ugly', Good, Bad, Ignore | |||||
int Alert_b; // b='0' | int Alert_b; // b='0' | ||||
int Alert_g; // g='0' | int Alert_g; // g='0' | ||||
}; | }; | ||||
class GBUAlertInitializer : public Configurator { | |||||
class GBUAlertInitializer : public CodeDweller::Configurator { | |||||
private: | private: | ||||
GBUAlertHandler* MyHandler; // Handler to reset. | GBUAlertHandler* MyHandler; // Handler to reset. | ||||
public: | public: | ||||
GBUAlertInitializer() { MyHandler = NULL; } // Init safely with null. | GBUAlertInitializer() { MyHandler = NULL; } // Init safely with null. | ||||
void link(GBUAlertHandler& H) { MyHandler = &H; } // Link to my handler. | void link(GBUAlertHandler& H) { MyHandler = &H; } // Link to my handler. | ||||
virtual void operator()(ConfigurationElement& E, ConfigurationData& D) { // Add an alert handler :-) | |||||
virtual void operator()(CodeDweller::ConfigurationElement& E, | |||||
CodeDweller::ConfigurationData& D) { // Add an alert handler :-) | |||||
if(NULL != MyHandler) { // If I know where it is | if(NULL != MyHandler) { // If I know where it is | ||||
MyHandler->reset(); // I hit the reset button. | MyHandler->reset(); // I hit the reset button. | ||||
} | } | ||||
class snf_sync { | class snf_sync { | ||||
private: | private: | ||||
ConfigurationElement Reader; // Our reader. | |||||
CodeDweller::ConfigurationElement Reader; // Our reader. | |||||
void SetupReader(); // Configure the reader. | void SetupReader(); // Configure the reader. | ||||
ConfiguratorSetTrueOnComplete SNFWasParsed; // Configurator sets the ReadWasGood | |||||
CodeDweller::ConfiguratorSetTrueOnComplete SNFWasParsed; // Configurator sets the ReadWasGood | |||||
bool ReadWasGood; // flag at the end of the snf element. | bool ReadWasGood; // flag at the end of the snf element. | ||||
void construct(); // Encapsulate the initial construction. | void construct(); // Encapsulate the initial construction. | ||||
void reset(); // Reset/initialize for the next read. | void reset(); // Reset/initialize for the next read. | ||||
public: | public: | ||||
snf_sync(); // Construct empty. | snf_sync(); // Construct empty. | ||||
snf_sync(const char* bfr, int len); // Construct from buffer. | snf_sync(const char* bfr, int len); // Construct from buffer. | ||||
snf_sync(string& input); // Construct from string. | |||||
snf_sync(std::string& input); // Construct from string. | |||||
bool read(const char* bfr, int len); // Read from buffer. | bool read(const char* bfr, int len); // Read from buffer. | ||||
bool read(string& input); // Read from string. | |||||
bool read(std::string& input); // Read from string. | |||||
//// And now the interpreted results //// | //// And now the interpreted results //// | ||||
bool good(); // True if read was good. | bool good(); // True if read was good. | ||||
bool bad(); // True if read was not good. | bool bad(); // True if read was not good. | ||||
string snf_sync_challenge_txt; | |||||
string snf_sync_response_nodeid; | |||||
string snf_sync_response_text; | |||||
string snf_sync_error_message; | |||||
std::string snf_sync_challenge_txt; | |||||
std::string snf_sync_response_nodeid; | |||||
std::string snf_sync_response_text; | |||||
std::string snf_sync_error_message; | |||||
int snf_sync_error_code; | int snf_sync_error_code; | ||||
string snf_sync_rulebase_utc; | |||||
std::string snf_sync_rulebase_utc; | |||||
int snf_sync_server_resync_secs; | int snf_sync_server_resync_secs; | ||||
GBUAlertHandler ClientGBUAlertHandler; // GBU Alerts received from client | GBUAlertHandler ClientGBUAlertHandler; // GBU Alerts received from client | ||||
GBUAlertInitializer ServerGBUAlertInitializer; | GBUAlertInitializer ServerGBUAlertInitializer; | ||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||
// SNF XML Command Interface | // SNF XML Command Interface | ||||
// See snf_xci.hpp for details / notes. | // See snf_xci.hpp for details / notes. | ||||
#include "snf_xci.hpp" | |||||
#include "SNFMulti/snf_xci.hpp" | |||||
//// snf_xci Interpreter Object //////////////////////////////////////////////// | //// snf_xci Interpreter Object //////////////////////////////////////////////// | ||||
using namespace std; | |||||
using namespace CodeDweller; | |||||
namespace SNFMulti { | |||||
snf_xci::snf_xci() : // Construcing a blank snf_xci. | snf_xci::snf_xci() : // Construcing a blank snf_xci. | ||||
Reader("snf"), // The Reader looks for "snf" | Reader("snf"), // The Reader looks for "snf" | ||||
ReadWasGood(false) { // There has been no good read yet. | ReadWasGood(false) { // There has been no good read yet. | ||||
return (false == ReadWasGood); // snf element successfully. | return (false == ReadWasGood); // snf element successfully. | ||||
} | } | ||||
} |
#ifndef snf_xci_included | #ifndef snf_xci_included | ||||
#define snf_xci_included | #define snf_xci_included | ||||
#include "../CodeDweller/configuration.hpp" | |||||
#include "CodeDweller/configuration.hpp" | |||||
namespace SNFMulti { | |||||
class snf_xci { // SNF XCI message interpreter. | class snf_xci { // SNF XCI message interpreter. | ||||
private: | private: | ||||
ConfigurationElement Reader; // Our reader. | |||||
CodeDweller::ConfigurationElement Reader; // Our reader. | |||||
void SetupReader(); // Configure the reader. | void SetupReader(); // Configure the reader. | ||||
ConfiguratorSetTrueOnComplete SNFWasParsed; // Configurator sets the ReadWasGood | |||||
CodeDweller::ConfiguratorSetTrueOnComplete SNFWasParsed; // Configurator sets the ReadWasGood | |||||
bool ReadWasGood; // flag at the end of the snf element. | bool ReadWasGood; // flag at the end of the snf element. | ||||
void reset(); // Reset/initialize for the next read. | void reset(); // Reset/initialize for the next read. | ||||
public: | public: | ||||
snf_xci(); | snf_xci(); | ||||
snf_xci(const char* bfr, int len); | snf_xci(const char* bfr, int len); | ||||
snf_xci(string& input); | |||||
snf_xci(std::string& input); | |||||
bool read(const char* bfr, int len); | bool read(const char* bfr, int len); | ||||
bool read(string& input); | |||||
bool read(std::string& input); | |||||
//// And now the interpreted results //// | //// And now the interpreted results //// | ||||
bool good(); | bool good(); | ||||
bool bad(); | bool bad(); | ||||
string scanner_scan_file; | |||||
std::string scanner_scan_file; | |||||
bool scanner_scan_xhdr; | bool scanner_scan_xhdr; | ||||
bool scanner_scan_log; | bool scanner_scan_log; | ||||
string scanner_scan_ip; | |||||
std::string scanner_scan_ip; | |||||
int scanner_result_code; | int scanner_result_code; | ||||
string scanner_result_xhdr; | |||||
string scanner_result_log; | |||||
std::string scanner_result_xhdr; | |||||
std::string scanner_result_log; | |||||
string gbudb_set_ip; | |||||
string gbudb_set_type; | |||||
std::string gbudb_set_ip; | |||||
std::string gbudb_set_type; | |||||
int gbudb_set_bad_count; | int gbudb_set_bad_count; | ||||
int gbudb_set_good_count; | int gbudb_set_good_count; | ||||
string gbudb_good_ip; | |||||
string gbudb_bad_ip; | |||||
string gbudb_test_ip; | |||||
string gbudb_drop_ip; | |||||
std::string gbudb_good_ip; | |||||
std::string gbudb_bad_ip; | |||||
std::string gbudb_test_ip; | |||||
std::string gbudb_drop_ip; | |||||
string gbudb_result_ip; | |||||
string gbudb_result_type; | |||||
std::string gbudb_result_ip; | |||||
std::string gbudb_result_type; | |||||
double gbudb_result_probability; | double gbudb_result_probability; | ||||
double gbudb_result_confidence; | double gbudb_result_confidence; | ||||
int gbudb_result_bad_count; | int gbudb_result_bad_count; | ||||
int gbudb_result_good_count; | int gbudb_result_good_count; | ||||
string gbudb_result_range; | |||||
std::string gbudb_result_range; | |||||
int gbudb_result_code; | int gbudb_result_code; | ||||
string report_request_status_class; | |||||
string report_response; | |||||
std::string report_request_status_class; | |||||
std::string report_response; | |||||
string xci_server_command; | |||||
string xci_server_command_content; | |||||
string xci_server_response; | |||||
std::string xci_server_command; | |||||
std::string xci_server_command_content; | |||||
std::string xci_server_response; | |||||
int xci_server_response_code; | int xci_server_response_code; | ||||
string xci_error_message; | |||||
std::string xci_error_message; | |||||
}; | }; | ||||
} // namespace SNFMulti | |||||
#endif | #endif | ||||