Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

SNFMulti.cpp 136KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  1. // SNFMulti.cpp
  2. //
  3. // (C) Copyright 2006 - 2009 ARM Research Labs, LLC
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // 20060121_M
  7. //
  8. // See SNFMulti.hpp for history and detailed notes.
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <ctime>
  12. #include <cstring>
  13. #include <cstdlib>
  14. #include <sstream>
  15. #include "SNFMulti.hpp"
  16. #include "../CodeDweller/timing.hpp"
  17. //#include "../nvwa-0.6/nvwa/debug_new.h"
  18. using namespace std;
  19. //// Version Info
  20. const char* SNF_ENGINE_VERSION = "SNFMulti Engine Version 3.0.5 Build: " __DATE__ " " __TIME__;
  21. //// Script Caller Methods
  22. const ThreadType ScriptCaller::Type("Script Caller"); // Script caller thread type mnemonic.
  23. const ThreadState ScriptCaller::CallingSystem("In system()"); // Script caller "CallingSystem" state.
  24. const ThreadState ScriptCaller::PendingGuardTime("Guard Time"); // Script caller "GuardTime" state.
  25. const ThreadState ScriptCaller::StandingBy("Standby"); // Script caller "Standby" state.
  26. const ThreadState ScriptCaller::Disabled("Disabled"); // State when unable to run.
  27. const int ScriptGuardDefault = 180000; // 3 Minute Default Guard Time.
  28. ScriptCaller::ScriptCaller(string S) : // Script caller constructor (with name).
  29. Thread(ScriptCaller::Type, S), // Set up the thread type and name.
  30. GuardTimer(ScriptGuardDefault), // Initialize the guard time.
  31. GoFlag(false), // Not ready to go yet.
  32. DieFlag(false) { // Not ready to die yet.
  33. run(); // Launch the thread.
  34. }
  35. ScriptCaller::~ScriptCaller() { // Destructor.
  36. DieFlag = true; // Set the die flag.
  37. Sleeper WaitATic(1000); // One second sleeper.
  38. for(int x = 10; x > 0; x--) { // We don't join, we might get stuck.
  39. if(false == isRunning()) break; // If we're still running then wait
  40. WaitATic(); // up to 10 seconds, then just exit.
  41. } // If the thread is stuck it will
  42. } // just get closed.
  43. string ScriptCaller::ScriptToRun() { // Safely grab the SystemCallText.
  44. ScopeMutex Freeze(MyMutex); // Protect the string.
  45. return SystemCallText; // Grab a copy of the text.
  46. }
  47. bool ScriptCaller::hasGuardExpired() { // True if guard time has expired.
  48. ScopeMutex Freeze(MyMutex); // Protect the timer.
  49. return GuardTimer.isExpired(); // If it has expired we're true.
  50. }
  51. void ScriptCaller::SystemCall(string S) { // Set the SystemCall text.
  52. ScopeMutex Freeze(MyMutex); // Protect the string object.
  53. SystemCallText = S; // Set it's data.
  54. }
  55. const int MinimumGuardTime = 60000; // Minimum Guard Time 1 minute.
  56. void ScriptCaller::GuardTime(int T) { // Set the Guard Time.
  57. if(MinimumGuardTime > T) T = MinimumGuardTime; // Enforce our lower limit.
  58. ScopeMutex Freeze(MyMutex); // Protect the Guard Timer.
  59. GuardTimer.setDuration(T); // Set the duration.
  60. GuardTimer.restart(); // Restart the timer.
  61. }
  62. void ScriptCaller::trigger() { // Trigger the system() call.
  63. GoFlag = true; // Set the flag.
  64. }
  65. void ScriptCaller::myTask() { // Safely call system() when triggered.
  66. Sleeper WaitATic(1000); // One second sleeper.
  67. while(false == DieFlag) { // While it's not time to die:
  68. WaitATic(); // Pause for 1 sec each round.
  69. string ScriptThisRound = ScriptToRun(); // Grab the current script.
  70. if(0 < ScriptToRun().length()) { // If script text is defined and
  71. if(true == GoFlag) { // If GoFlag is triggered and
  72. if(hasGuardExpired()) { // Guard time is expired:
  73. CurrentThreadState(CallingSystem); // Publish our state.
  74. system(ScriptThisRound.c_str()); // Make the system call.
  75. GoFlag = false; // Done with that trigger.
  76. GuardTimer.restart(); // Restart our Guard Time.
  77. } else { // If we're waiting for Guard Time:
  78. CurrentThreadState(PendingGuardTime); // publish that state.
  79. }
  80. } else { // If nothing is triggered yet then
  81. CurrentThreadState(StandingBy); // we are standing by.
  82. }
  83. } else { // If we have no script to run then
  84. CurrentThreadState(Disabled); // we are disabled.
  85. }
  86. }
  87. }
  88. //// Rulebase Reloader Methods
  89. // How to get timestamps on critical files.
  90. time_t getFileTimestamp(string FileName) {
  91. struct stat FileNameStat; // First we need a stat buffer.
  92. if(0 != stat(FileName.c_str(), &FileNameStat)) { // If we can't get the stat we
  93. return 0; // will return 0;
  94. } // If all goes well we return
  95. return FileNameStat.st_mtime; // the last modified time_t.
  96. }
  97. void snf_Reloader::captureFileStats() { // Get stats for later comparison.
  98. snfCFGData& C = *(MyRulebase.MyCFGmgr.ActiveConfiguration()); // Reference the active config.
  99. RulebaseFileCheckName = C.RuleFilePath; // Build/Get Rulebase File Name.
  100. ConfigFileCheckName = C.ConfigFilePath; // Build/Get Configuration File Name.
  101. IgnoreListCheckFileName = C.paths_workspace_path; // Build/Get Ignore File Name.
  102. IgnoreListCheckFileName.append("GBUdbIgnoreList.txt");
  103. RulebaseFileTimestamp = getFileTimestamp(RulebaseFileCheckName); // Timestamps to check for
  104. ConfigurationTimestamp = getFileTimestamp(ConfigFileCheckName); // changes in configuration data
  105. IgnoreListTimestamp = getFileTimestamp(IgnoreListCheckFileName); // or rulebase files.
  106. }
  107. bool snf_Reloader::StatsAreDifferent() { // Check file stats for changes.
  108. return ( // Return true if any of the
  109. RulebaseFileTimestamp != getFileTimestamp(RulebaseFileCheckName) || // Rulebase File, or the
  110. ConfigurationTimestamp != getFileTimestamp(ConfigFileCheckName) || // Configuration File, or the
  111. IgnoreListTimestamp != getFileTimestamp(IgnoreListCheckFileName) // Ignore List File have changed.
  112. );
  113. }
  114. const int MSPerSec = 1000; // 1000 milliseconds per second.
  115. void snf_Reloader::captureGetterConfig() { // Update RulebaseGetter config.
  116. snfCFGData& C = *(MyRulebase.MyCFGmgr.ActiveConfiguration()); // Reference the active config.
  117. RulebaseGetterIsTurnedOn = ( // Is the script caller on or off?
  118. true == C.update_script_on_off && // We're on if the bit is set and
  119. 0 < C.update_script_call.length() // we have a non-empty script to call.
  120. );
  121. if(RulebaseGetterIsTurnedOn) { // If it is turned on:
  122. RulebaseGetter.SystemCall(C.update_script_call); // Set the script call and
  123. RulebaseGetter.GuardTime(C.update_script_guard_time * MSPerSec); // the cycle guard time.
  124. }
  125. else { // If the scripter is turned off:
  126. RulebaseGetter.SystemCall(""); // Set the script to nothing.
  127. }
  128. }
  129. const string snfReloadContext = "--RELOADING--"; // Context for info and error logs.
  130. void snf_Reloader::myTask() { // How do we do this refresh thing?
  131. Sleeper WaitATic(1000); // Wait a second between checks.
  132. while(!TimeToStop) { // While it's not time to stop:
  133. if(
  134. RulebaseGetterIsTurnedOn && // If our rulebase getter is enabled
  135. MyRulebase.MyLOGmgr.isUpdateAvailable() // and a new rulebase is availalbe:
  136. ) {
  137. RulebaseGetter.trigger(); // Trigger the update script (if any).
  138. }
  139. if(StatsAreDifferent()) { // Check the stats. If different:
  140. try { // safely attempt a reload.
  141. WaitATic(); // Wait a tic to let things stabilize
  142. MyRulebase.refresh(); // then call refresh on the handler.
  143. captureFileStats(); // If it works, capture the new stats.
  144. captureGetterConfig(); // Also update the RulebaseGetter.
  145. MyRulebase.logThisInfo( // Log our success.
  146. snfReloadContext, snf_SUCCESS, "Success");
  147. }
  148. catch(snf_RulebaseHandler::IgnoreListError) { // If we get an IgnoreListError - say so.
  149. MyRulebase.logThisError(
  150. snfReloadContext, snf_ERROR_RULE_FILE, "IgnoreListError");
  151. }
  152. catch(snf_RulebaseHandler::ConfigurationError) { // If we get a ConfigurationError - say so.
  153. MyRulebase.logThisError(
  154. snfReloadContext, snf_ERROR_RULE_FILE, "ConfigurationError");
  155. }
  156. catch(snf_RulebaseHandler::FileError x) { // If we get a FileError - say so.
  157. MyRulebase.logThisError(
  158. snfReloadContext, snf_ERROR_RULE_FILE, "FileError");
  159. }
  160. catch(snf_RulebaseHandler::AuthenticationError x) { // If we get a Auth Error - say so.
  161. MyRulebase.logThisError(
  162. snfReloadContext, snf_ERROR_RULE_AUTH, "AuthError");
  163. }
  164. catch(snf_RulebaseHandler::Busy x) { // If we get a Busy Exception - say so.
  165. MyRulebase.logThisError(
  166. snfReloadContext, snf_ERROR_UNKNOWN, "BusyError");
  167. }
  168. catch(snf_RulebaseHandler::Panic x) { // If we get a Panic - say so.
  169. MyRulebase.logThisError(
  170. snfReloadContext, snf_ERROR_UNKNOWN, "PanicError");
  171. }
  172. catch(...) { // If we get some other error - shout!
  173. MyRulebase.logThisError(
  174. snfReloadContext, snf_ERROR_UNKNOWN, "UnhandledError");
  175. }
  176. }
  177. WaitATic(); // Wait before the next loop.
  178. }
  179. }
  180. const ThreadType snf_Reloader::Type("snf_Reloader"); // The thread's type.
  181. snf_Reloader::snf_Reloader(snf_RulebaseHandler& R) : // When we are created, we
  182. Thread(snf_Reloader::Type, "Reloader"), // brand and name our thread.
  183. MyRulebase(R), // Capture the rulebase handler.
  184. TimeToStop(false), // It's not time to stop yet.
  185. RulebaseGetter("RulebaseGetter"), // Setup our ScriptCaller thread.
  186. RulebaseGetterIsTurnedOn(false) { // Rulebase getter is off at first.
  187. captureFileStats(); // Set up the initial stats.
  188. captureGetterConfig(); // Set up RulebaseGetter config.
  189. run(); // Run our maintenenace thread.
  190. }
  191. snf_Reloader::~snf_Reloader() { // When we are destroyed we
  192. TimeToStop = true; // set our time to stop bit
  193. join(); // and wait for the thread.
  194. }
  195. //// snfCFGPacket Methods
  196. snfCFGPacket::snfCFGPacket(snf_RulebaseHandler* R) : // When we are created:
  197. MyRulebase(R), // Capture our rulebase handler and
  198. MyTokenMatrix(NULL), // ready our token matrix and
  199. MyCFGData(NULL) { // cfg pointers.
  200. if(MyRulebase) { MyRulebase->grab(*this); } // Safely grab our rulebase.
  201. }
  202. snfCFGPacket::~snfCFGPacket() { if(MyRulebase) MyRulebase->drop(*this); } // Safely drop our rulebase when we die.
  203. TokenMatrix* snfCFGPacket::Tokens() { return MyTokenMatrix; } // Consumers read the Token Matrix and
  204. snfCFGData* snfCFGPacket::Config() { return MyCFGData; } // the snfCFGData.
  205. bool snfCFGPacket::bad() { // If anything is missing it's not good.
  206. return (NULL == MyTokenMatrix || NULL == MyCFGData); // True if any of these aren NULL.
  207. }
  208. bool snfCFGPacket::isRulePanic(int R) { // Test for a rule panic.
  209. return(RulePanics.end() != RulePanics.find(R)); // Find it in the list, it's a panic.
  210. }
  211. //// Rulebase Handler Methods
  212. snf_RulebaseHandler::~snf_RulebaseHandler(){ // Destruct the handler.
  213. close(); // Close before we go.
  214. }
  215. bool snf_RulebaseHandler::isReady(){ // Is the object ready?
  216. return (NULL!=Rulebase); // Have Rulebase? We're ready.
  217. }
  218. bool snf_RulebaseHandler::isBusy(){ // Is a refresh/open in progress or
  219. return (RefreshInProgress || 0<RetiringCount); // an older rulebase is not yet retired.
  220. }
  221. int snf_RulebaseHandler::getReferenceCount(){ // How many Engines using this handler.
  222. return ReferenceCount; // Tell them the count bob.
  223. }
  224. int snf_RulebaseHandler::getCurrentCount(){ // How many Engines active in the current rb.
  225. return CurrentCount; // Tell them what it is bob.
  226. }
  227. int snf_RulebaseHandler::getRetiringCount(){ // How many Engines active in the old rb.
  228. return RetiringCount; // Tell them what it is bob.
  229. }
  230. // FileUTC(FileName) - utility function for tagging the active rulebase
  231. string FileUTC(string FileName) { // Gets a files UTC.
  232. struct stat FileNameStat; // First we need a stat buffer.
  233. string t; // We also need a Timestamp holder.
  234. if(0 != stat(FileName.c_str(), &FileNameStat)) { // If we can't get the stat we
  235. t.append("000000000000"); return t; // will return 000000000000 to
  236. } // make sure we should get the file.
  237. struct tm FileNameTime; // Allocate a time structure.
  238. FileNameTime = *(gmtime(&FileNameStat.st_mtime)); // Copy the file time to it as UTC.
  239. char TimestampBfr[20]; // Timestamp buffer.
  240. sprintf(TimestampBfr,"%04d%02d%02d%02d%02d%02d", // Format yyyymmddhhmmss
  241. FileNameTime.tm_year+1900,
  242. FileNameTime.tm_mon+1,
  243. FileNameTime.tm_mday,
  244. FileNameTime.tm_hour,
  245. FileNameTime.tm_min,
  246. FileNameTime.tm_sec
  247. );
  248. t.append(TimestampBfr); // Append the timestamp to t
  249. return t; // and return it to the caller.
  250. }
  251. // Auto Reload Controls
  252. bool snf_RulebaseHandler::AutoRefresh(bool On) { // Turn on/off auto refresh.
  253. if(On) { // If they want Reload On:
  254. if(!AutoRefresh()) { // and it isn't already on:
  255. try { MyReloader = new snf_Reloader(*this); } // try to set up a Reloader.
  256. catch(...) { MyReloader = 0; } // If that fails we don't
  257. } // have one. If it's already
  258. } // on do nothing.
  259. else { // If they want Reload Off:
  260. if(AutoRefresh()) { // and it is turned on:
  261. delete MyReloader; // destroy the reloader and
  262. MyReloader = 0; // zero it's pointer.
  263. }
  264. }
  265. return AutoRefresh(); // Return the truth (on/off)
  266. }
  267. bool snf_RulebaseHandler::AutoRefresh() { // True if AutoRefresh is on.
  268. return (0 != MyReloader); // If we have one, it's on.
  269. }
  270. // _snf_LoadNewRulebase()
  271. // This is actually a common sub-funtion. It expects that the object is in the "RefreshInProgress" state,
  272. // and that everything is in place and safe for a new rulebase to be loaded into the object. Once it's
  273. // done it will reset from the "RefreshInProgress" state and along the way will throw any errors that
  274. // are appropriate. The other functions can count on this one to polish off the various forms of rulebase
  275. // load activity.
  276. const LogicCheck SaneRefreshProcessCheck("snf_RulebaseHandler::_snf_LoadNewRulebase():SaneRefreshProcessCheck(RefreshInProgress)");
  277. void snf_RulebaseHandler::_snf_LoadNewRulebase(){ // Common internal load/check routine.
  278. SaneRefreshProcessCheck(RefreshInProgress); // We only get called when this flag is set.
  279. try { MyCFGmgr.load(); } // Load a fresh copy of the configuration.
  280. catch(...) { // If something goes wrong:
  281. RefreshInProgress = false; // we are no longer "in refresh"
  282. throw ConfigurationError("_snf_LoadNewRulebase() MyCFGmgr.load() failed"); // throw the Configuration exception.
  283. }
  284. string RuleFilePath = MyCFGmgr.RuleFilePath(); // Get our rulebase file path and our
  285. string SecurityKey = MyCFGmgr.SecurityKey(); // security key from the CFG manager.
  286. if(0>=RuleFilePath.length()) { // If we don't have a path, we're hosed.
  287. RefreshInProgress = false; // We are no longer "in refresh"
  288. throw FileError("_snf_LoadNewRulebase() Zero length RuleFilePath"); // Can't load a RB file with no path!
  289. }
  290. if(0>=SecurityKey.length()) { // No security string? toast!
  291. RefreshInProgress = false; // We are no longer "in refresh"
  292. throw AuthenticationError("snf_LoadNewRulebase() Zero length SecurityKey"); // Can't authenticate without a key!
  293. }
  294. // Notify sub modules of the new configuration data.
  295. MyGeneration++; // Increment the generation number.
  296. snfCFGData& CFGData = (*(MyCFGmgr.ActiveConfiguration())); // Capture the active config...
  297. CFGData.Generation = MyGeneration; // Tag the configuration data.
  298. MyLOGmgr.configure(CFGData); // Update the LOGmgr's configuration.
  299. MyNETmgr.configure(CFGData); // Update the NETmgr's configuration.
  300. MyGBUdbmgr.configure(CFGData); // Update the GBUdbmgr's configuration.
  301. // Load the new rulebase locally (on stack) and see if it authenticates.
  302. TokenMatrix* TryThis = NULL; // We need our candidate to remain in scope.
  303. try {
  304. TryThis = new TokenMatrix(); // Grab a new Token Matrix
  305. TryThis->Load(RuleFilePath); // Load it from the provided file path
  306. TryThis->Validate(SecurityKey); // Validate it with the provided security key
  307. TryThis->Verify(SecurityKey); // Verify that it is not corrupt.
  308. } // If nothing threw, we're golden!
  309. // If the rulebase is bad then throw the proper exception and
  310. // end/unlock the refresh process.
  311. catch (TokenMatrix::BadFile) { // BadFile translates to FileError
  312. RefreshInProgress = false;
  313. throw FileError("_snf_LoadNewRulebase() TokenMatrix::BadFile");
  314. }
  315. catch (TokenMatrix::BadMatrix) { // BadMatrix translates to AuthenticationError
  316. RefreshInProgress = false;
  317. throw AuthenticationError("_snf_LoadNewRulebase() TokenMatrix::BadMatrix");
  318. }
  319. catch (TokenMatrix::BadAllocation) { // BadAllocation translates to AllocationError
  320. RefreshInProgress = false;
  321. throw AllocationError("_snf_LoadNewRulebase() TokenMatrix::BadAllocation");
  322. }
  323. catch (TokenMatrix::OutOfRange) { // OutOfRange should never happen so PANIC!
  324. RefreshInProgress = false;
  325. throw Panic("_snf_LoadNewRulebase() TokenMatrix::OutOfRange");
  326. }
  327. catch (exception e) {
  328. RefreshInProgress = false;
  329. throw;
  330. }
  331. catch (...) { // Something unpredicted happens? PANIC!
  332. RefreshInProgress = false;
  333. throw Panic("_snf_LoadNewRulebase() TokenMatrix.load() ???");
  334. }
  335. // At this point the rulebase looks good. If we need to go big-endian do it!
  336. #ifdef __BIG_ENDIAN__
  337. TryThis->FlipEndian(); // Flip tokens to big-endian format.
  338. #endif
  339. MyLOGmgr.updateActiveUTC(FileUTC(RuleFilePath)); // Update the Active Rulebase UTC.
  340. MyMutex.lock(); // Lock the mutex while changing state.
  341. OldRulebase = Rulebase; // Move the current rulebase and count to
  342. RetiringCount = CurrentCount; // the retiring slot.
  343. if(0>=RetiringCount && NULL!=OldRulebase) { // If nobody cares about the old rulebase
  344. delete OldRulebase; // then delete it, and wipe everything
  345. OldRulebase = NULL; // clean for the next retiree.
  346. RetiringCount = 0;
  347. }
  348. CurrentCount = 0; // Set the current count to zero (it's fresh!)
  349. Rulebase = TryThis; // Copy our new rulebase into production.
  350. MyMutex.unlock(); // Release the hounds!!!
  351. // If there is a GBUdb Ignore List, refresh with it (This might go elsewhere).
  352. // Failure to read the GBUdbIgnoreList if all else went well does not cause
  353. // the rulebase update (if any) to fail.
  354. /**** This section needs work ****/
  355. try {
  356. string IgnoreListPath = CFGData.paths_workspace_path;
  357. IgnoreListPath.append("GBUdbIgnoreList.txt");
  358. if(0 == MyGBUdb.readIgnoreList(IgnoreListPath.c_str())) // We must have at least 1 IP listed.
  359. throw ConfigurationError(
  360. "_snf_LoadNewRulebase() GBUdbIgnoreList min 1 entry!");
  361. }
  362. catch(...) { // Ignore list read might fail.
  363. RefreshInProgress = false; // If so, don't keep things hung.
  364. throw IgnoreListError("_snf_LoadNewRulebase() readIgnoreList() ???"); // If it does, throw FileError.
  365. }
  366. RefreshInProgress = false; // Done with the refresh process.
  367. return; // Our work is done here.
  368. }
  369. // open()
  370. // This loads a new rulebase (usually the first one only) into the handler. This is the first of two loading
  371. // methods on this object. This one checks for isBusy() because it is highly invasive. If it is called after
  372. // the object has been running it is important that it not run while anything in the object is active. This
  373. // is because it is likely in this case we would be loading an entirely new rulebase that would lead to odd
  374. // results if some scanner instances were activily using a different one.
  375. void snf_RulebaseHandler::open(const char* path, const char* licenseid, const char* authentication){
  376. MyMutex.lock(); // Lock the mutex while changing state.
  377. if(isBusy()) { // Be sure we're not busy.
  378. MyMutex.unlock(); throw Busy("snf_RulebaseHandler::open() busy"); // If we are then throw.
  379. }
  380. RefreshInProgress = true; // Set RefreshInProgress.
  381. MyMutex.unlock(); // Unlock the mutex and
  382. MyCFGmgr.initialize(path, licenseid, authentication); // Initialize our configuration.
  383. _snf_LoadNewRulebase(); // get on with loading the rulebase.
  384. MyGBUdbmgr.load(); // Load the GBUdb as configured.
  385. AutoRefresh(true); // Turn on Refresh by default.
  386. logThisInfo("--INITIALIZING--", 0, "Success"); // Log the happy event.
  387. return;
  388. }
  389. // refresh()
  390. // This loads a fresh copy of the current rulebase. This is the second loading method on the object. It is
  391. // specifically designed to work without stopping scanning activities. This one checks for isBusy() because
  392. // there may be an old rulebase that is not yet completely retired --- that is, some scanners may be using it.
  393. // If there is still an old rulebase on it's way out then we can't shove it aside without breaking something,
  394. // so we have to throw.
  395. //
  396. // Under normal circumstances, this call will cause a new rulebase to be loaded without disturbing any scans
  397. // underway on the current rulebase. The current rulebase will be put into retirement while any active scans
  398. // are completed, and then it will quietly go away when the last has finished. The new rulebase will take it's
  399. // place and will be handed out to all new grab() requests.
  400. void snf_RulebaseHandler::refresh(){ // Reloads the rulebase.
  401. MyMutex.lock(); // Lock the mutex while changing states.
  402. if(isBusy()) { // If we're busy then throw.
  403. MyMutex.unlock(); throw Busy("snf_RulebaseHandler::refresh() busy");
  404. }
  405. RefreshInProgress = true; // Set RefreshInProgress and
  406. MyMutex.unlock(); // unlock the mutex. Then get on with
  407. _snf_LoadNewRulebase(); // loading a fresh copy of the rulebase
  408. return;
  409. }
  410. void snf_RulebaseHandler::close(){ // Closes this handler.
  411. try {
  412. AutoRefresh(false); // Stop AutoRefresh if it's on.
  413. }
  414. catch(exception& e) { throw; } // Rethrow good exceptions.
  415. catch(...) { throw Panic("snf_RulebaseHandler::close() AutoRefresh(false) panic!"); } // Panic blank exceptions.
  416. try {
  417. MyXCImgr.stop(); // Stop the XCI manager.
  418. }
  419. catch(exception& e) { throw; } // Rethrow good exceptions.
  420. catch(...) { throw Panic("snf_RulebaseHandler::close() MyXCImgr.stop() panic!"); } // Panic blank exceptions.
  421. if(isBusy() || 0<CurrentCount || 0<ReferenceCount) { // Check that there is no activity.
  422. throw Busy("snf_RulebaseHandler::close() busy"); // With XCI stopped we should not
  423. } // be busy.
  424. try {
  425. MyLOGmgr.stop(); // Stop the LOG manager.
  426. }
  427. catch(exception& e) { throw; } // Rethrow good exceptions.
  428. catch(...) { throw Panic("snf_RulebaseHandler::close() MyLOGmgr.stop() panic!"); } // Panic blank exceptions.
  429. try {
  430. MyNETmgr.stop(); // Stop the NET manager.
  431. }
  432. catch(exception& e) { throw; } // Rethrow good exceptions.
  433. catch(...) { throw Panic("snf_RulebaseHandler::close() MyNETmgr.stop() panic!"); } // Panic blank exceptions.
  434. try {
  435. MyGBUdbmgr.stop(); // Stop the GBUdb manager.
  436. }
  437. catch(exception& e) { throw; } // Rethrow good exceptions.
  438. catch(...) { throw Panic("snf_RulebaseHandler::close() MyGBUdbmgr.stop() panic!"); } // Panic blank exceptions.
  439. try {
  440. if(NULL!=Rulebase) {delete Rulebase; Rulebase=NULL;} // If we have a Rulebase destroy it.
  441. }
  442. catch(exception& e) { throw; } // Rethrow good exceptions.
  443. catch(...) { throw Panic("snf_RulebaseHandler::close() delete Rulebase panic!"); } // Panic blank exceptions.
  444. try {
  445. if(NULL!=OldRulebase) {delete OldRulebase; OldRulebase=NULL;} // Shouldn't happen, but just in case.
  446. }
  447. catch(exception& e) { throw; } // Rethrow good exceptions.
  448. catch(...) { throw Panic("snf_RulebaseHandler::close() delete OldRulebase panic!"); } // Panic blank exceptions.
  449. }
  450. void snf_RulebaseHandler::use(){ // Make use of this Rulebase Handler.
  451. MyMutex.lock(); // Lock the object
  452. ReferenceCount++; // Boost the count
  453. MyMutex.unlock(); // Unlock the object
  454. }
  455. void snf_RulebaseHandler::unuse(){ // Finish with this Rulebase Handler.
  456. MyMutex.lock(); // Lock the object
  457. ReferenceCount--; // Reduce the count
  458. MyMutex.unlock(); // Unlock the object
  459. }
  460. // A word about Generation... In practice whenever the configuration or rulebase
  461. // changes the entire thing is reloaded. The Generation() function gives other
  462. // modules a way to know if they need to update their interpretation of the
  463. // configuration. They can keep track of the last Generation value they got and
  464. // compare it to the latest Generation. If the two are different then they need
  465. // to update their configuration - just in case it has changed.
  466. int snf_RulebaseHandler::Generation() { return MyGeneration; } // Returns the generation number.
  467. // A word about autopanics.
  468. // The first time throgh this we outsmarted ourselves with an ellaborate
  469. // wait-to-insert scheme. That led to the possibilty of a deadlock. Now we
  470. // copy the (usually empty or very short) set of rule panics to the
  471. // configuration packet when it is grabbed and only use the one mutext to hold
  472. // the configuration steady while doing so. All queries are made to the local
  473. // copy of the panic list and all writes are made, under mutex, to the active
  474. // configuration. Simpler, no significant penalty, and no more deadlocks.
  475. // A word about configuration packets.
  476. // Along the way we simplified things by making the snfCFGPacket do it's own
  477. // grab and drop upon construction and destruction. This way we don't have to
  478. // remember to handle all possible cases during a scan or other opertion -- once
  479. // the operation goes out of scope the configuration packet drop()s with it.
  480. void snf_RulebaseHandler::grab(snfCFGPacket& CP) { // Activate this Rulebase.
  481. ScopeMutex HoldStillPlease(MyMutex); // Lock the rulebase until we're done.
  482. CurrentCount++; // Boost the count for myself.
  483. CP.MyTokenMatrix = Rulebase; // Grab the current rulebase.
  484. CP.MyCFGData = MyCFGmgr.ActiveConfiguration(); // Grab the active configuration.
  485. CP.RulePanics = MyCFGmgr.ActiveConfiguration()->RulePanicHandler.IntegerSet; // Copy the RulePanic set.
  486. }
  487. void snf_RulebaseHandler::drop(snfCFGPacket& CP) { // Deactiveate this Rulebase.
  488. const TokenMatrix* t = CP.MyTokenMatrix; // Grab the token matrix pointer.
  489. CP.MyCFGData = NULL; // Null the configuration pointer.
  490. ScopeMutex HoldStillPlease(MyMutex); // Lock the rulebase until we're done.
  491. if(t==Rulebase) { // If we're dropping the current rulebase
  492. CurrentCount--; // then reduce the current count.
  493. } else // If not that then...
  494. if(t==OldRulebase) { // If we're dropping the old rulebase
  495. RetiringCount--; // reduce the retiring count and check...
  496. if(0>=RetiringCount) { // to see if it is completely retired.
  497. if(NULL!=OldRulebase) delete OldRulebase; // If it is then delete it and
  498. OldRulebase = NULL; RetiringCount = 0; // reset it's pointer and counter.
  499. }
  500. } else { // If we're dropping something else,
  501. throw Panic("snf_RulebaseHandler::drop() panic"); // it is time to panic, so, then PANIC!
  502. }
  503. }
  504. // When adding a rule panic entry the rulebase and configuration state cannot
  505. // be changed, nor grabbed by an snfCFGPacket. This ensures that the IntegerSet
  506. // is only adjusted by one thread at a time and that any threads using the set
  507. // will have a consistent result based on their last grab().
  508. void snf_RulebaseHandler::addRulePanic(int RuleID) { // Add a rule panic id dynamically.
  509. ScopeMutex JustMe(MyMutex); // Freeze the rulebase while we adjust
  510. MyCFGmgr.ActiveConfiguration() // the active configuration to
  511. ->RulePanicHandler.IntegerSet.insert(RuleID); // insert the new rule panic ruleid.
  512. } // When we're done, unlock and move on.
  513. IPTestRecord& snf_RulebaseHandler::performIPTest(IPTestRecord& I) { // Perform an IP test.
  514. snfCFGPacket MyCFGPacket(this); // We need a CFG packet.
  515. try { // Safely process the IP.
  516. if(false == MyCFGPacket.bad()) { // If we've got a good packet:
  517. I.G = MyGBUdb.getRecord(I.IP); // Lookup the IP in GBUdb.
  518. I.R = MyCFGPacket.Config()->RangeEvaluation(I.G); // Evaluate it's statistics.
  519. // Convert the RangeEvaluation into the configured Code
  520. switch(I.R) {
  521. case Unknown: // Unknown - not defined.
  522. case Normal: // Benefit of the doubt.
  523. case New: { // It is new to us.
  524. I.Code = 0; // Zero is the default - no code.
  525. break;
  526. }
  527. case White: { // This is a good guy.
  528. I.Code = MyCFGPacket.Config()->WhiteRangeHandler.Symbol;
  529. break;
  530. }
  531. case Caution: { // This is suspicious.
  532. I.Code = MyCFGPacket.Config()->CautionRangeHandler.Symbol;
  533. break;
  534. }
  535. case Black: { // This is bad.
  536. I.Code = MyCFGPacket.Config()->BlackRangeHandler.Symbol;
  537. break;
  538. }
  539. case Truncate: { // Don't even bother looking.
  540. I.Code = MyCFGPacket.Config()
  541. ->gbudb_regions_black_truncate_symbol;
  542. break;
  543. }
  544. }
  545. } // If something is broken we punt.
  546. } catch (...) {} // Ignore exceptions (none expected)
  547. return I; // Return the processed record.
  548. }
  549. void snf_RulebaseHandler::logThisIPTest(IPTestRecord& I, string Action) { // Log an IP test result & action.
  550. MyLOGmgr.logThisIPTest(I, Action);
  551. }
  552. void snf_RulebaseHandler::logThisError( // Log an error message.
  553. string ContextName, int Code, string Text
  554. ) {
  555. MyLOGmgr.logThisError(ContextName, Code, Text);
  556. }
  557. void snf_RulebaseHandler::logThisInfo( // Log an informational message.
  558. string ContextName, int Code, string Text
  559. ) {
  560. MyLOGmgr.logThisInfo(ContextName, Code, Text);
  561. }
  562. string snf_RulebaseHandler::PlatformVersion(string NewPlatformVersion) { // Set platform version info.
  563. return MyLOGmgr.PlatformVersion(NewPlatformVersion);
  564. }
  565. string snf_RulebaseHandler::PlatformVersion() { // Get platform version info.
  566. return MyLOGmgr.PlatformVersion();
  567. }
  568. string snf_RulebaseHandler::PlatformConfiguration() { // Get platform configuration.
  569. ScopeMutex LockAndGrab(MyMutex); // Freeze things for a moment and
  570. return MyCFGmgr.ActiveConfiguration()->PlatformElementContents; // copy the platform configuration.
  571. }
  572. string snf_RulebaseHandler::EngineVersion() { // Get engine version info.
  573. return MyLOGmgr.EngineVersion();
  574. }
  575. void snf_RulebaseHandler::
  576. XCIServerCommandHandler(snfXCIServerCommandHandler& XCH) { // Registers a new XCI Srvr Cmd handler.
  577. ScopeMutex ThereCanBeOnlyOne(XCIServerCommandMutex); // Serialize access to this resource.
  578. myXCIServerCommandHandler = &XCH; // Assign the new handler as provided.
  579. }
  580. string snf_RulebaseHandler::processXCIServerCommandRequest(snf_xci& X) { // Handle a parsed XCI Srvr Cmd request.
  581. ScopeMutex ThereCanBeOnlyOne(XCIServerCommandMutex); // Serialize access to this resource.
  582. if(0 == myXCIServerCommandHandler) { // If we don't have a handler then
  583. snfXCIServerCommandHandler H; // create a base handler and
  584. return H.processXCIRequest(X); // return it's default response.
  585. } // If we do have a handler then pass
  586. return myXCIServerCommandHandler->processXCIRequest(X); // on the request and return the
  587. } // response.
  588. //// snf_IPTestEngine Methods
  589. snf_IPTestEngine::snf_IPTestEngine() : // The constructor is simple - it
  590. Lookup(NULL), ScanData(NULL) { // sets up our internal references.
  591. } // Before use these must be set.
  592. void snf_IPTestEngine::setGBUdb(GBUdb& G) { // Here's how we set the GBUdb.
  593. Lookup = &G;
  594. }
  595. void snf_IPTestEngine::setScanData(snfScanData& S) { // Here's how we set the ScanData object.
  596. ScanData = &S;
  597. }
  598. void snf_IPTestEngine::setCFGData(snfCFGData& C) { // Here's how we set the CFGData.
  599. CFGData = &C;
  600. }
  601. void snf_IPTestEngine::setLOGmgr(snfLOGmgr& L) { // Here's how we set the LOGmgr.
  602. LOGmgr = &L;
  603. }
  604. // 20090127 _M Added special handling for forced IP sources. First, they are
  605. // always considered the source and second if they are in the GBUdb ignore list
  606. // then GBUdb training bypass is established.
  607. string& snf_IPTestEngine::test(string& input, string& output) { // Perform IP lookups and put IPs into ScanData.
  608. if(NULL == Lookup || NULL == ScanData) { // If we are not set up properly then we
  609. output = "{IPTest Config Error}"; // will return an error string.
  610. return output;
  611. }
  612. try { // If we're out of IP records, no analysis.
  613. IPScanRecord& I = ScanData->newIPScanRecord(); // Grab a new IP scan record and
  614. IP4Address IP = input; // Convert the string to an IP.
  615. // Identify forced Source IP addresses
  616. bool ThisSourceIsForced = ( // This IP is a forced source IP if:
  617. (0 == I.Ordinal) && ( // we are looking at the first IP and
  618. (0UL != ScanData->CallerForcedSourceIP()) || // either the Caller forced the IP or
  619. (0UL != ScanData->HeaderDirectiveSourceIP()) // the IP was forced by a header directive.
  620. )
  621. );
  622. // Bad IPs are possible, especially if the source was forced. In that
  623. // case forced source IP is meaningless so we want to ignore it and
  624. // we want to make the case visible in the logs. An ordinary IP that
  625. // is invalid has no consequence so we simply skip those.
  626. // Note that a source IP that has it's ignore flag set causes an
  627. // implied training bypass inside the scan function. Setting the bad
  628. // IP as the source and setting it's ignore flag will have the desired
  629. // effect.
  630. if(0UL == IP) { // If we got a 0 or a bad conversion then
  631. output = "{0.0.0.0 Is Not A Usable IP}"; // we won't be testing this IP.
  632. if(ThisSourceIsForced) { // If this ip is a forced source then
  633. I.GBUdbData.Flag(Ignore); // we will force a training bypass,
  634. ScanData->SourceIPRecord(I); // we will record it as the source,
  635. ScanData->SourceIPEvaluation = output; // and capture the error output.
  636. }
  637. return output;
  638. }
  639. if(0xFFFFFFFF == IP) { // If we got a 255.255.255.255 then
  640. output = "{255.255.255.255 Is Not A Usable IP}"; // we won't be testing this IP.
  641. if(ThisSourceIsForced) { // If this ip is a forced source then
  642. I.GBUdbData.Flag(Ignore); // we will force a training bypass,
  643. ScanData->SourceIPRecord(I); // we will record it as the source,
  644. ScanData->SourceIPEvaluation = output; // and capture the error output.
  645. }
  646. return output;
  647. }
  648. GBUdbRecord R = Lookup->getRecord(IP); // Get the GBUdb record for it.
  649. I.IP = IP; // store the IP and the
  650. I.GBUdbData = R; // GBUdb record we retrieved.
  651. output = "{"; // Next we start to build our IP data insert.
  652. ostringstream S; // We will use a string stream for formatting.
  653. switch(R.Flag()) { // Identify the flag data for this IP.
  654. case Good: S << "Good "; break;
  655. case Bad: S << "Bad "; break;
  656. case Ugly: S << "Ugly "; break;
  657. case Ignore: S << "Ignore "; break;
  658. }
  659. S << "c=" << R.Confidence() << " " // Include the Confidence and
  660. << "p=" << R.Probability(); // Probability.
  661. // Process ordinary Source IP addresses
  662. if( // The message source IP address is the
  663. (false == ScanData->FoundSourceIP()) && // first IP we find that is either forced
  664. (ThisSourceIsForced || (Ignore != R.Flag())) // OR is NOT part of our infrastructure.
  665. ) { // When we find the correct source IP:
  666. if( // Check to see if we're drilling down.
  667. (false == ThisSourceIsForced) && // We drill when the source is NOT forced
  668. (ScanData->isDrillDownSource(I)) // AND we have a matching drilldown.
  669. ) {
  670. Lookup->setIgnore(IP); // If we're drilling down ignore this IP.
  671. }
  672. else { // If not drilling down this is the source:
  673. ScanData->SourceIPRecord(I); // we log it in as the source
  674. S << " Source"; // and report our findings in our tag.
  675. // Since we are dealing with our source IP
  676. // this is a good place to evaluate our truncate feature.
  677. snfIPRange IPR =
  678. ScanData->SourceIPRange(CFGData->RangeEvaluation(R)); // Establish the IP range for this scan.
  679. // We will also emit a range identifier for pattern matches that might use it.
  680. switch(IPR) {
  681. case Unknown: { S << " Unknown"; break; } // Unknown - not defined.
  682. case White: { S << " White"; break; } // This is a good guy.
  683. case Normal: { S << " Normal"; break; } // Benefit of the doubt.
  684. case New: { S << " New"; break; } // It is new to us.
  685. case Caution: { S << " Caution"; break; } // This is suspicious.
  686. case Black: { S << " Black"; break; } // This is bad.
  687. case Truncate: { S << " Truncate"; break; } // Don't even bother looking.
  688. }
  689. ScanData->SourceIPEvaluation = S.str(); // Capture the source IP eval.
  690. // The RangeEvaluation() call above settles a lot of questions for us.
  691. // The Truncate return code only happens when the IP is either Bad w/
  692. // truncate turned on, or the statistics place the IP in the Truncate
  693. // range. If the Good flag is set the function always returns White so
  694. // here we only have to check for the Truncate flag.
  695. if(Truncate == IPR) { // If all of the conditions are met
  696. ScanData->GBUdbTruncateTriggered = true; // then Truncate has been triggered.
  697. ScanData->GBUdbPeekTriggered = LOGmgr->OkToPeek( // Since truncate was triggered, see if
  698. CFGData->gbudb_regions_black_truncate_peek_one_in); // we would also trigger a peek.
  699. // The reason we check the truncate on_off flag here is that the
  700. // IP range _may_ return a Truncate result if no Flags are set on
  701. // the IP and the IP is far enough into the black to reach the
  702. // Truncate threshold.
  703. if(CFGData->gbudb_regions_black_truncate_on_off) { // If truncate is on either peek or truncate.
  704. if(ScanData->GBUdbPeekTriggered) { // If a peek has been triggered then
  705. ScanData->GBUdbPeekExecuted = true; // mark the event and don't truncate.
  706. } else { // If a peek was not triggered then
  707. ScanData->GBUdbTruncateExecuted = true; // Record our trucnate action.
  708. output = ""; // Set up the truncate signal (empty string)
  709. return output; // and return it! We're done!
  710. }
  711. }
  712. }
  713. }
  714. }
  715. // If we're not truncating then we're going to return our IP evaulation tag
  716. // to the filter chain function module so it can emit it into the stream.
  717. output.append(S.str());
  718. output.append("}");
  719. }
  720. catch(snfScanData::NoFreeIPScanRecords) {
  721. output = "{too_many}";
  722. }
  723. catch(...) {
  724. output = "{fault}";
  725. }
  726. return output;
  727. }
  728. //// Engine Handler Methods
  729. snf_EngineHandler::~snf_EngineHandler(){ // Shutdown clenas up and checks for safety.
  730. if(isReady()) close(); // If we're live, close on our way out.
  731. }
  732. void snf_EngineHandler::open(snf_RulebaseHandler* Handler){ // Light up the engine.
  733. MyMutex.lock(); // Serialize this...
  734. if(isReady()) { // If we're already open then we need to
  735. MyMutex.unlock(); // unlock this object and let them know
  736. throw Busy("snf_EngineHandler::open() busy"); // we are busy.
  737. } // If we're not busy, then let's light it up.
  738. MyRulebase=Handler; // Install our rulebase handler.
  739. MyRulebase->use(); // Up the use count to let it know we're here.
  740. MyIPTestEngine.setGBUdb(MyRulebase->MyGBUdb); // Set up the IPTester's GBUdb.
  741. MyIPTestEngine.setScanData(MyScanData); // Set up the IPTester's ScanData reference.
  742. MyIPTestEngine.setLOGmgr(MyRulebase->MyLOGmgr); // Set up the IPTester's LOGmgr.
  743. MyMutex.unlock(); // Unlock our mutex, then...
  744. return; // our work is done.
  745. }
  746. bool snf_EngineHandler::isReady(){ // Is the Engine good to go?
  747. return (NULL!=MyRulebase); // Have rulebase will travel.
  748. }
  749. void snf_EngineHandler::close(){ // Close down the engine.
  750. MyMutex.lock(); // Serialize this...
  751. if(!isReady()){ // If we're not already open we can't close.
  752. MyMutex.unlock(); // Something is seriously wrong, so unlock
  753. throw Panic("snf_EngineHandler::close() !isReady panic"); // and hit the panic button!
  754. } // But, if everything is ok then we can
  755. MyRulebase->unuse(); // unuse our rulebase and quietly forget
  756. MyRulebase = NULL; // about it.
  757. if(NULL!=CurrentMatrix) { // If we have a leftover evaluation matrix
  758. delete CurrentMatrix; // we can let that go and forget about
  759. CurrentMatrix = NULL; // it as well.
  760. }
  761. MyMutex.unlock(); // Finally, we unlock our mutex and...
  762. return; // Our work is done here.
  763. }
  764. enum PatternResultTypes { // To train GBUdb we need a generalized
  765. NoPattern, // way to evaluate the results from the
  766. WhitePattern, // snf pattern matching scan.
  767. BlackPattern,
  768. IPPattern,
  769. AboveBandPattern
  770. };
  771. int snf_EngineHandler::scanMessageFile( // Scan this message file.
  772. const string MessageFilePath, // -- this is the file path (and id)
  773. const int MessageSetupTime, // -- setup time already used.
  774. const IP4Address MessageSource // -- message source IP (for injection).
  775. ) {
  776. Timer AdditionalSetupTime;
  777. ScopeMutex DoingAFileScan(FileScan); // Protect MyScanData @ this entry.
  778. // Preliminary setup. Clearing the ScanData resets the ReadyToClear flag
  779. // and allows us to set some data for more accurate tracking and so that if
  780. // something goes wrong the ScanData will be helpful in determining the
  781. // state of the engine.
  782. MyScanData.clear(); // Clear the scan data.
  783. MyScanData.StartOfJobUTC = MyRulebase->MyLOGmgr.Timestamp(); // Set the job start timestamp.
  784. MyScanData.ScanName = MessageFilePath;
  785. // Now that the preliminaries are established we can begin our work.
  786. int MessageFileSize = 0; // Here will be the size of it.
  787. ifstream MessageFile; // Here will be our input file.
  788. MessageFile.exceptions( // It will throw exceptions for
  789. ifstream::eofbit | ifstream::failbit | ifstream::badbit // these unwanted events.
  790. );
  791. try { // Try opening the message file.
  792. MessageFile.open(MessageFilePath.c_str(), ios::in | ios::binary); // Open the file, binary mode.
  793. MessageFile.seekg(0, ios::end); // Find the end of the file,
  794. MessageFileSize = MessageFile.tellg(); // read that position as the size,
  795. MessageFile.seekg(0, ios::beg); // then go back to the beginning.
  796. MyScanData.ScanSize = MessageFileSize; // Capture the message file size.
  797. }
  798. catch(...) { // Trouble? Throw FileError.
  799. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  800. MyScanData, "scanMessageFile().open",
  801. snf_ERROR_MSG_FILE, "ERROR_MSG_FILE"
  802. );
  803. throw FileError("snf_EngineHandler::scanMessageFile() Open/Seek");
  804. }
  805. if(0 >= MessageFileSize) { // Handle zero length files.
  806. MessageFile.close(); // No need to keep this open.
  807. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  808. MyScanData, "scanMessageFile().isFileEmpty?",
  809. snf_ERROR_MSG_FILE, "ERROR_MSG_FILE"
  810. );
  811. throw FileError("snf_EngineHandler::scanMessageFile() FileEmpty!");
  812. }
  813. vector<unsigned char> MessageBuffer; // Allocate a buffer and size
  814. try { MessageBuffer.resize(MessageFileSize, 0); } // it to fit the message.
  815. catch(...) { // Trouble? Throw AllocationError.
  816. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  817. MyScanData, "scanMessageFile().alloc",
  818. snf_ERROR_MSG_FILE, "ERROR_MSG_ALLOC"
  819. );
  820. throw AllocationError("snf_EngineHandler::scanMessageFile() Alloc");
  821. }
  822. try { MessageFile.read((char*) &MessageBuffer[0], MessageFileSize); } // Read the file into the buffer.
  823. catch(...) {
  824. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  825. MyScanData, "scanMessageFile().read",
  826. snf_ERROR_MSG_FILE, "ERROR_MSG_READ"
  827. );
  828. throw FileError("snf_EngineHandler::scanMessageFile() Read");
  829. }
  830. MessageFile.close(); // Close the file.
  831. // Additional Setup Time will be captured as the call is made.
  832. int ScanResultCode = scanMessage( // Scan the message we've loaded.
  833. &MessageBuffer[0], // Here is the buffer pointer,
  834. MessageBuffer.size(), // here is the size of the message,
  835. MessageFilePath, // the path is the identifier,
  836. (AdditionalSetupTime.getElapsedTime() + MessageSetupTime), // and this is our setup time total.
  837. MessageSource // Pass on the source if provided.
  838. );
  839. // Inject headers if required.
  840. if(MyScanData.XHeaderInjectOn) { // If we are to inject headers:
  841. const char* XHDRInjStage = "Begin"; // Keep track of what we're doing.
  842. try {
  843. // The insertion point will be at the end of the existing headers.
  844. // We pick that point to be right between the two <cr><lf> so that
  845. // the first blank line will appear at the end of our headers.
  846. // We also try to accommodate some cases where the message may
  847. // have been rewritten incorrectly or translated so that instead
  848. // of <cr><lf><cr><lf> we find <lf><lf> -- this might happen on some
  849. // *nix like systems if the software and/or scripting involved isn't
  850. // quite up to spec. We are reading a file, after all.
  851. unsigned int ipt = 0; // Insert search point.
  852. if(MessageBuffer.size() != MyScanData.ScanSize) { // If our scanner skipped data at
  853. ipt = MessageBuffer.size() - MyScanData.ScanSize; // the top of the message buffer then
  854. } // we will skip it too.
  855. int InsertPoint = 0; // Find the insertion point.
  856. bool UseLFOnly = false; // Patchup line ends for *nix files?
  857. bool CRLFPresent = false; // Detected \r\n pairs?
  858. for(; ipt<(MessageBuffer.size()-4); ipt++) { // Search for the first blank line.
  859. if( // Detect CRLF pairs if present.
  860. false == CRLFPresent &&
  861. '\r' == MessageBuffer.at(ipt) &&
  862. '\n' == MessageBuffer.at(ipt + 1)
  863. ) CRLFPresent = true;
  864. if( // In a properly formatted RFC822
  865. '\r' == MessageBuffer.at(ipt) && // message that looks like
  866. '\n' == MessageBuffer.at(ipt + 1) && // <cr><lf><cr><lf>
  867. '\r' == MessageBuffer.at(ipt + 2) &&
  868. '\n' == MessageBuffer.at(ipt + 3)
  869. ) {
  870. InsertPoint = ipt + 2;
  871. break;
  872. } else
  873. if( // In some bizarre cases it might
  874. '\n' == MessageBuffer.at(ipt) && // look like <lf><lf>.
  875. '\n' == MessageBuffer.at(ipt + 1)
  876. ) {
  877. InsertPoint = ipt + 1;
  878. UseLFOnly = true; // We have to strip <CR> from our
  879. break; // injected header line ends.
  880. }
  881. }
  882. // Here we must interpret the results of our scan. Do we know where
  883. // our insert point is or do we punt and use the top of the message?
  884. if(0 == InsertPoint) { // No blank line? We need to punt.
  885. if(false == CRLFPresent) { // What kind of line ends do we use?
  886. UseLFOnly = true; // If no CRLF found use LF only.
  887. } // Either way we will be inserting
  888. } // our headers at the top of the msg.
  889. // At this point we know where to split the message and insert
  890. // our X Headers.
  891. XHDRInjStage = "Open Temp File"; // Update our process monitor.
  892. string TempFileName = MessageFilePath; // Prepare a temp file name
  893. TempFileName.append(".tmp"); // based on the message file.
  894. ofstream TempFile; // Here will be our temp file.
  895. TempFile.exceptions(ofstream::failbit | ofstream::badbit); // It will throw these exceptions.
  896. TempFile.open(TempFileName.c_str(), ios::binary | ios::trunc); // Open and truncate the file.
  897. // If our insert point is the top of the message we'll skip this.
  898. if(0 < InsertPoint) { // If we have an insert point:
  899. XHDRInjStage = "Write Temp File.1"; // Update our process monitor.
  900. TempFile.write( // Write the message file up
  901. reinterpret_cast<char*>(&MessageBuffer[0]), // to our split.
  902. InsertPoint
  903. );
  904. }
  905. // If our file has \n line ends we need to strip the \r from our
  906. // rfc822 \r\n line ends.
  907. XHDRInjStage = "XHDR <CR><LF> to <LF>";
  908. if(true == UseLFOnly) { // If we are using <LF> only:
  909. string ReworkedHeaders = ""; // Make a new string and rework
  910. for( // our headers.
  911. string::iterator iS = MyScanData.XHDRsText.begin(); // Run through the headers one
  912. iS != MyScanData.XHDRsText.end(); iS++ // byte at a time.
  913. ) {
  914. if('\r' != (*iS)) ReworkedHeaders.push_back(*iS); // Strip out any <CR> chars.
  915. }
  916. MyScanData.XHDRsText.swap(ReworkedHeaders); // Swap in our reworked headers.
  917. }
  918. // Now we are ready to inject our headers.
  919. XHDRInjStage = "Write Temp File.2"; // Update our process monitor.
  920. TempFile.write( // Inject our headers.
  921. MyScanData.XHDRsText.c_str(),
  922. MyScanData.XHDRsText.length()
  923. );
  924. XHDRInjStage = "Write Temp File.3"; // Update our process monitor.
  925. TempFile.write( // Write the rest of the message.
  926. reinterpret_cast<char*>(&MessageBuffer[InsertPoint]),
  927. MessageBuffer.size() - InsertPoint
  928. );
  929. XHDRInjStage = "Close Temp File"; // Update our process monitor.
  930. TempFile.close(); // Close the file (flushing it).
  931. Sleeper PauseBeforeRetry(300); // Delay to use between retries.
  932. XHDRInjStage = "Drop Msg"; // Update our process monitor.
  933. if(remove(MessageFilePath.c_str())) { // Remove the old message file
  934. PauseBeforeRetry(); // If it fails, pause and retry.
  935. if(remove(MessageFilePath.c_str())) { // If that fails,
  936. PauseBeforeRetry(); // pause, then try once more.
  937. if(remove(MessageFilePath.c_str())) { // If that fails, throw.
  938. throw XHDRError("XHDR injector can't remove original!");
  939. }
  940. }
  941. }
  942. XHDRInjStage = "Rename Temp -> Msg"; // Update our process monitor.
  943. if(rename(TempFileName.c_str(), MessageFilePath.c_str())) { // Make Temp our new message file.
  944. PauseBeforeRetry(); // If it fails, pause and retry.
  945. if(rename(TempFileName.c_str(), MessageFilePath.c_str())) { // If that fails,
  946. PauseBeforeRetry(); // pause then try once more.
  947. if(rename(TempFileName.c_str(), MessageFilePath.c_str())) { // If that fails, throw.
  948. throw XHDRError("XHDR injector can't rename tmp file!");
  949. }
  950. }
  951. }
  952. }
  953. catch(XHDRError& e) { // For full XHDRError exceptions.
  954. string ERROR_MSG_XHDRi = "ERROR_MSG_XHDRi: "; // Format the XHDRInj error msg.
  955. ERROR_MSG_XHDRi.append(XHDRInjStage);
  956. ERROR_MSG_XHDRi.append(" ");
  957. ERROR_MSG_XHDRi.append(e.what());
  958. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  959. MyScanData, "scanMessageFile().xhdr.inject",
  960. snf_ERROR_MSG_FILE, ERROR_MSG_XHDRi
  961. );
  962. throw; // Rethrow any XHDRError exceptions.
  963. }
  964. catch(exception& e) { // For ordinary runtime exceptions.
  965. string ERROR_MSG_XHDRi = "ERROR_MSG_XHDRi: "; // Format the XHDRInj error msg.
  966. ERROR_MSG_XHDRi.append(XHDRInjStage);
  967. ERROR_MSG_XHDRi.append(" ");
  968. ERROR_MSG_XHDRi.append(e.what());
  969. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  970. MyScanData, "scanMessageFile().xhdr.inject",
  971. snf_ERROR_MSG_FILE, ERROR_MSG_XHDRi
  972. );
  973. throw XHDRError(ERROR_MSG_XHDRi); // Rethrow as XHDRError exceptions.
  974. }
  975. catch(...) { // If we encounter a problem then
  976. string ERROR_MSG_XHDRi = "ERROR_MSG_XHDRi: "; // Format the XHDRInj error msg.
  977. ERROR_MSG_XHDRi.append(XHDRInjStage);
  978. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  979. MyScanData, "scanMessageFile().xhdr.inject",
  980. snf_ERROR_MSG_FILE, ERROR_MSG_XHDRi
  981. );
  982. string XHDRError_msg = "Message Rewrite Failed: "; // Format our throw message with
  983. XHDRError_msg.append(XHDRInjStage); // our detailed stage data and
  984. throw XHDRError(XHDRError_msg); // throw our special exception.
  985. }
  986. }
  987. // Create an .xhdr file if required.
  988. if(MyScanData.XHeaderFileOn) {
  989. try {
  990. ofstream XHDRFile; // Output file will be XHDRFile.
  991. XHDRFile.exceptions(ofstream::failbit | ofstream::badbit); // These events will throw exceptions.
  992. string XHDRFileName = MessageFilePath; // Build the XHDR file name by adding
  993. XHDRFileName.append(".xhdr"); // .xhdr to the message file name.
  994. XHDRFile.open(XHDRFileName.c_str(), ios::binary | ios::trunc); // Open (and truncate) the file.
  995. XHDRFile << MyScanData.XHDRsText; // Spit out the XHDRs.
  996. XHDRFile.close(); // All done.
  997. }
  998. catch(...) { // If we encounter a problem then
  999. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1000. MyScanData, "scanMessageFile().xhdr.file",
  1001. snf_ERROR_MSG_FILE, "ERROR_MSG_XHDRf"
  1002. );
  1003. throw XHDRError(".xhdr file write failed"); // throw our special exception.
  1004. }
  1005. }
  1006. return ScanResultCode; // Return the actual result, of course.
  1007. }
  1008. string snf_EngineHandler::extractMessageID( // Find and return the first Message-ID
  1009. const unsigned char* Msg, // Input the Message buffer to search
  1010. const int Len // and the length of the buffer.
  1011. ) {
  1012. string ExtractedID = ""; // Start with an empty string.
  1013. bool FoundID = false; // Haven't found it yet.
  1014. int C = 0; // Cursor position.
  1015. while(!FoundID && (C < (Len - 12))) { // Loop through the Msg looking for
  1016. if( // the Message-ID: header.
  1017. ('\n' == Msg[C]) && // Starting at the new line find
  1018. ('M' == Msg[C + 1] || 'm' == Msg[C + 1]) && // Message-ID: (per RFC822)
  1019. ('e' == Msg[C + 2] || 'E' == Msg[C + 2]) &&
  1020. ('s' == Msg[C + 3] || 'S' == Msg[C + 3]) && // We use an unrolled comparison
  1021. ('s' == Msg[C + 4] || 'S' == Msg[C + 4]) && // loop here for raw speed and
  1022. ('a' == Msg[C + 5] || 'A' == Msg[C + 5]) && // optimization. Note that we
  1023. ('g' == Msg[C + 6] || 'G' == Msg[C + 6]) && // compare the most likely characters
  1024. ('e' == Msg[C + 7] || 'E' == Msg[C + 7]) && // first in each case, and we don't
  1025. ('-' == Msg[C + 8]) && // need to go through a buffer length
  1026. ('I' == Msg[C + 9] || 'i' == Msg[C + 9]) && // check at each byte for partial
  1027. ('D' == Msg[C + 10] || 'd' == Msg[C + 10]) && // matches.
  1028. (':' == Msg[C + 11]) &&
  1029. (' ' == Msg[C + 12] || '\t' == Msg[C + 12])
  1030. ) {
  1031. C = C + 13; // Starting just after the space
  1032. while(C < Len) { // and staying within bounds
  1033. unsigned char X = Msg[C]; // grab each character in the ID.
  1034. if(isprint(X)) { // If it is printable,
  1035. if(' ' == X) X = '_'; // massage out the spaces as _ and
  1036. if(127 < X) X = '|'; // high characters as | and
  1037. if('\'' == X || '\"' == X) X = '`'; // ' or " to ` in order to make the
  1038. ExtractedID.push_back(X); // ID safe for logging, then push
  1039. } else // the result into our string. When
  1040. if('\r' == X || '\n' == X) break; /* leave copy loop */ // we reach the end we're done.
  1041. ++C; // else get ready for the next byte.
  1042. }
  1043. FoundID = true; // Set the flag: we found Message-ID:
  1044. break; /* leave search loop */ // We got what we came for. Break!
  1045. } else { // When we don't find the Message-ID:
  1046. if( // we check for end of headers.
  1047. ('\n' == Msg[C] && '\n' == Msg[C+1]) || // Either <LF><LF> or
  1048. ('\r' == Msg[C] && '\n' == Msg[C+1] && // <CR><LF><CF><LF>
  1049. '\r' == Msg[C+2] && '\n' == Msg[C+3])
  1050. ) { // If we've found the end of headers
  1051. break; // we're done looking. If we did not
  1052. } // find the end of headers then
  1053. ++C; // we move to the next position.
  1054. }
  1055. }
  1056. // At this point we either have the Extracted ID, or we need a substitute.
  1057. if(0 == ExtractedID.length()) { // If we need a substitute ID then
  1058. MyRulebase->MyLOGmgr.SerialNumber(ExtractedID); // use the next available serial number.
  1059. }
  1060. return ExtractedID; // Return the extracted id or substitute.
  1061. }
  1062. const LogicFault FaultBadMessageBuffer1("snf_EngineHandler::scanMessage():FaultBadMessageBuffer1(NULL == inputMessageBuffer)");
  1063. const LogicFault FaultBadMessageBuffer2("snf_EngineHandler::scanMessage():FaultBadMessageBuffer2(0 >= inputMessageLength)");
  1064. int snf_EngineHandler::scanMessage( // Scan this message (in buffer).
  1065. const unsigned char* inputMessageBuffer, // -- this is the message buffer.
  1066. const int inputMessageLength, // -- this is the length of the buffer.
  1067. const string MessageName, // -- this is the message identifier.
  1068. const int MessageSetupTime, // -- setup time used (for logging).
  1069. const IP4Address MessageSource // -- message source IP (for injection).
  1070. ) {
  1071. ScopeTimer ScanTimeCapture(MyScanData.ScanTime); // Start the scan time clock.
  1072. unsigned char* MessageBuffer = NULL; // Explicitly initialize these two
  1073. int MessageLength = 0; // so the compiler will be happy.
  1074. FaultBadMessageBuffer1(NULL == inputMessageBuffer); // Fault on null message buffer.
  1075. FaultBadMessageBuffer2(0 >= inputMessageLength); // Fault on bad message bfr length.
  1076. // Protect this engine - only one scan at a time per EngineHandler ;-)
  1077. ScopeMutex ScannerIsBusy(MyMutex); // Serialize this...
  1078. // Preliminary job setup.
  1079. // In our pre-processing we may adjust our input buffer so we capture the
  1080. // originals and then use the captured values. For example if we are scanning
  1081. // Communigate message files we will want to skip the communigate headers.
  1082. MessageBuffer = const_cast<unsigned char*>(inputMessageBuffer); // Capture the input buffer.
  1083. MessageLength = inputMessageLength; // Capture the input length.
  1084. MyScanData.clear(); // Clear the scan data.
  1085. MyScanData.ScanSize = MessageLength; // Grab the message length.
  1086. MyScanData.SetupTime = MessageSetupTime; // Capture the setup time.
  1087. if(0 == MyScanData.StartOfJobUTC) { // If the job timestamp is not
  1088. MyScanData.StartOfJobUTC = MyRulebase->MyLOGmgr.Timestamp(); // yet set then set it.
  1089. }
  1090. MyScanData.CallerForcedSourceIP(MessageSource); // Capture the MessageSource if any.
  1091. // Special note about exceptions here...
  1092. // Setting up the filter chain can throw an exception. It can't go in it's own try block or it will
  1093. // be out of scope for the remainder of the function... SO, I've wrapped everything inside of the
  1094. // Lock() in a try block ... and there's a nested one also for scanning the content. The result is
  1095. // that I can put all of the unlock work in the "outer" try block and re-throw anything that's
  1096. // needed.
  1097. snfCFGPacket MyCFGPacket(MyRulebase); // We need this to stay in scope.
  1098. // Set up the filter chain, configure the scanner, and scan the message.
  1099. try {
  1100. if(MyCFGPacket.bad()) { // If it's not there it's a big problem.
  1101. throw Panic("snf_EngineHandler::scanMessage() MyCFGPacket.bad()");
  1102. }
  1103. // Adapt to CGP message files - skip the CGP headers
  1104. MyScanData.MessageFileTypeCGPOn = // Find out if we are expecting
  1105. MyCFGPacket.Config()->MessageFileTypeCGP_on_off; // Communigate message files.
  1106. if(MyScanData.MessageFileTypeCGPOn) { // If we are scanning CGP files:
  1107. while(4 < MessageLength) { // Skip over the CGP headers.
  1108. if( // On Winx systems look for the first
  1109. '\r' == MessageBuffer[0] && // blank line encoded as CRLF CRLF.
  1110. '\n' == MessageBuffer[1] &&
  1111. '\r' == MessageBuffer[2] &&
  1112. '\n' == MessageBuffer[3]
  1113. ) { // If we find it then skip past
  1114. MessageBuffer += 4; // the new line and break out
  1115. MessageLength -= 4; // of the loop.
  1116. break;
  1117. } else // On *nix systems look for the first
  1118. if( // blank line encoded as LF LF.
  1119. '\n' == MessageBuffer[0] &&
  1120. '\n' == MessageBuffer[1]
  1121. ) { // If we find it then skip past
  1122. MessageBuffer += 2; // the blank line and break out
  1123. MessageLength -= 2; // of the loop.
  1124. break;
  1125. }
  1126. else { // If we don't find it then
  1127. ++MessageBuffer; // eat one byte from the buffer
  1128. --MessageLength; // and keep going.
  1129. }
  1130. }
  1131. // At this point our MessagBuffer contains just the message we
  1132. // want to scan.
  1133. MyScanData.ScanSize = MessageLength; // Reset the scan size.
  1134. }
  1135. // Identify this message.
  1136. if( // How do we identify this scan?
  1137. 0 == MessageName.length() || // If no name was provided or
  1138. true == MyCFGPacket.Config()->Scan_Identifier_Force_Message_Id // we are forcing RFC822 IDs then
  1139. ) { // extract the Message-ID from the
  1140. MyScanData.ScanName = extractMessageID(MessageBuffer, MessageLength); // message and use that.
  1141. } else { // If a name was provided and we
  1142. MyScanData.ScanName = MessageName; // are not forcing RFC822 IDs then
  1143. } // use the name provided to us.
  1144. // Set up our filter chain.
  1145. stringstream PrependedHeaders; // Use this to prepend X-Headers.
  1146. FilterChainCBFR IU(MessageBuffer, MessageLength, PrependedHeaders); // Set up the filter chain.
  1147. FilterChainHeaderAnalysis IV(&IU, MyIPTestEngine); // Include header analysis.
  1148. FilterChainBase64 IW(&IV); // Include Base64 decoding.
  1149. FilterChainQuotedPrintable IX(&IW); // Include Quoted Printable decoding.
  1150. FilterChainUrlDecode IY(&IX); // Include URL decoder.
  1151. FilterChainDefunker IZ(&IY); // Include Defunking.
  1152. // Now we set up our scanner and grab the current token matrix.
  1153. if(NULL!=CurrentMatrix) { delete CurrentMatrix; CurrentMatrix=NULL; } // If we have old results, delete them.
  1154. try {
  1155. CurrentMatrix = new EvaluationMatrix(MyCFGPacket.Tokens()); // Allocate a new matrix for this scan.
  1156. } catch(...) { // Check that the allocation worked.
  1157. throw AllocationError("new EvaluationMatrix() ???");
  1158. }
  1159. // Here we get down to it and start scanning the message.
  1160. const char* DebugInfo = "scanMessage() Begin Message Scan"; // If we panic, here we are.
  1161. try {
  1162. // The IPTestEngine has the ability to truncate the message in the filter
  1163. // chain under certain conditions. In order to configure those conditions
  1164. // the IPTestEngine needs to have the configuration data being used for
  1165. // the current scan.
  1166. DebugInfo = "scanMessage() setCFGData()"; // If we panic, here we are.
  1167. MyIPTestEngine.setCFGData(*(MyCFGPacket.Config())); // Setup the CFG data to use.
  1168. // Check processed headers for header directive rules. One of these might
  1169. // include a directive to get the message source IP from a header. If so
  1170. // then MyScanData will have been modified. Also if there are drill-down
  1171. // directives then MyScanData will have been modified to mark any headers
  1172. // that should be ignored -- in this case the IP test used in the filter
  1173. // chain will take appropriate action as it comes across the Received
  1174. // headers that have been marked.
  1175. DebugInfo = "scanMessage() Get Header Directives";
  1176. MyScanData.HeaderDirectiveFlags = 0x00000000; // Clear the header directive flags.
  1177. if(0 < MyCFGPacket.Config()-> // Check to see if we have any
  1178. HeaderDirectivesHandler.HeaderDirectives.size()) { // header directive rules and if we do:
  1179. HeaderFinder HeaderDirectivesParser( // Parse the headers in the message
  1180. &MyScanData, // and update the ScanData using the
  1181. MyCFGPacket.Config()->HeaderDirectivesHandler.HeaderDirectives, // directives in our configuration packet.
  1182. MessageBuffer, // Pass the message as a pointer with
  1183. MessageLength // a specific buffer length.
  1184. );
  1185. MyScanData.HeaderDirectiveFlags = HeaderDirectivesParser(); // Capture the parsed results.
  1186. }
  1187. // Message header rules in earlier versions occasionally failed because there was not
  1188. // a new-line character in front of the very first header. So, now we insert one :-)
  1189. // This allows all header rules to start off with a ^ indicating the start of the line.
  1190. // 20070719_M Added \n to X-snfScanSize: synthetic header.
  1191. // 20070120_M There are some messages where the size is a specific part of
  1192. // the pattern so we will now be emitting this data into the engine. A later
  1193. // version of the engine should handle this kind of thing using a special
  1194. // filter chain module.
  1195. DebugInfo = "scanMessage() ^X-snfScanSize"; // If we panic here we are.
  1196. // Build the scan size info
  1197. PrependedHeaders << "X-snfScanSize: " << MyScanData.ScanSize << "\n"; // and format as an X- header.
  1198. // Add a phantom received header to the top IF the message source has been
  1199. // forced by the caller or by a header directive. After that the normal
  1200. // scanning and header analysis process should pick up the IP as the
  1201. // source of the message. (It will not if the IP is ignored in the GBUdb!)
  1202. DebugInfo = "scanMessage() PhantomReceived"; // If we panic we are here.
  1203. if(0UL != MyScanData.CallerForcedSourceIP()) { // If the caller forced the source IP:
  1204. PrependedHeaders // Make a phantom Received header
  1205. << "Received: Caller.Forced.Source.IP [" // showing that the caller forced
  1206. << (string) MyScanData.CallerForcedSourceIP() << "]\n"; // the source IP.
  1207. } else
  1208. // If not forced by the caller but a
  1209. if(0UL != MyScanData.HeaderDirectiveSourceIP()) { // header directive forced the source IP:
  1210. PrependedHeaders // Make a phantom Received header
  1211. << "Received: Header.Directive.Source.IP [" // showing that a header directive
  1212. << (string) MyScanData.HeaderDirectiveSourceIP() << "]\n"; // established the source IP.
  1213. }
  1214. // Most of the time we will extract the source IP the normal way.
  1215. // If there are other prepended headers to add they should go here.
  1216. /** Add other prepended headers **/
  1217. // 20070719_M Reworked the engine to handle the filter-chain section in
  1218. // a tight loop separately from the scanning section. This should allow
  1219. // for tighter optimization in some cases (less cache thrashing) and also
  1220. // provides for later development of parallel analysis of the pre-filtered
  1221. // data, as well as the ability to output the pre-filtered data for use in
  1222. // rule development and debugging.
  1223. DebugInfo = "scanMessage() IZ.GetByte() ==> FilteredData"; // If we panic we are here.
  1224. MyScanData.FilteredData.clear(); // Clear the FilteredData buffer.
  1225. try { // Watch for exceptions and scan
  1226. for(int a = 0; a < snf_ScanHorizon; a++) // the message through the filter
  1227. MyScanData.FilteredData.push_back(IZ.GetByte()); // chain into the FilteredData buffer.
  1228. } // When we run out of data we will
  1229. catch(FilterChain::Empty) {} // get the Empty exception and stop.
  1230. // Scan each byte in the file up to the horizon or the end of the message.
  1231. // If something goes wrong, an exception will be thrown.
  1232. DebugInfo = "scanMessage() EvaluateThis(FilteredData)"; // If we panic, here we are.
  1233. if(false == MyScanData.GBUdbTruncateExecuted) { // If we haven't already truncated:
  1234. for(int a = 0, b = MyScanData.FilteredData.size(); a < b; a++) // Scan through the filtered data one
  1235. CurrentMatrix->EvaluateThis(MyScanData.FilteredData[a]); // byte at a time.
  1236. }
  1237. DebugInfo = "scanMessage() Scan Data Complete"; // If we panic, here we are.
  1238. }
  1239. catch(EvaluationMatrix::BadAllocation) { // Check for bad allocation during scan.
  1240. throw AllocationError("EvaluationMatrix::BadAllocation");
  1241. }
  1242. catch(EvaluationMatrix::MaxEvalsExceeded) { // Check for too many evaluators.
  1243. throw MaxEvals("EvaluationMatrix::MaxEvalsExceeded");
  1244. }
  1245. catch(EvaluationMatrix::OutOfRange) { // Check for out of range of (bad) matrix.
  1246. throw BadMatrix("EvaluationMatrix::OutOfRange");
  1247. }
  1248. catch(exception& e) { // Some other known exception?
  1249. throw; // rethrow.
  1250. }
  1251. catch(...){ // In order to prevent thread craziness
  1252. throw Panic(DebugInfo); // throw a Panic.
  1253. } // The mutex will unlock in the outer try.
  1254. }
  1255. // Here is the end of the outer try block. We can catch and rethrow whatever happend
  1256. // and we can also keep our mutex properly managed.
  1257. catch(AllocationError& e) { // Allocation Errors pass through.
  1258. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1259. MyScanData, "scanMessage()",
  1260. snf_ERROR_ALLOCATION, "ERROR_ALLOCATION"
  1261. );
  1262. throw;
  1263. }
  1264. catch(MaxEvals& e) { // MaxEvals == Panic, with a log.
  1265. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1266. MyScanData, "scanMessage()",
  1267. snf_ERROR_MAX_EVALS, "ERROR_MAX_EVALS"
  1268. );
  1269. throw;
  1270. }
  1271. catch(BadMatrix& e) { // BadMatrix == Panic, with a log.
  1272. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1273. MyScanData, "scanMessage()",
  1274. snf_ERROR_BAD_MATRIX, "ERROR_BAD_MATRIX"
  1275. );
  1276. throw;
  1277. }
  1278. catch(Panic& e) { // Panic is panic.
  1279. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1280. MyScanData, "scanMessage()",
  1281. snf_ERROR_BAD_MATRIX, "ERROR_PANIC"
  1282. );
  1283. throw;
  1284. }
  1285. catch(exception& e) { // Other exceptions.
  1286. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1287. MyScanData, "scanMessage()",
  1288. snf_ERROR_UNKNOWN, "ERROR_EXCEPTION"
  1289. );
  1290. throw;
  1291. }
  1292. catch(...) { // Anything else == Panic.
  1293. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1294. MyScanData, "scanMessage()",
  1295. snf_ERROR_UNKNOWN, "ERROR_UNKNOWN"
  1296. );
  1297. throw Panic("snf_EngineHandler::scanMessage() ERROR_UNKNOWN!");
  1298. }
  1299. // At this point, we've completed our scan and we're ready to evaluate our results to find the correct symbol to return.
  1300. ResultsCount = 0; // Reset the count,
  1301. ResultsRemaining = 0; // Remaining count,
  1302. FinalResult = NULL; // Final Result marker,
  1303. ResultCursor = CurrentMatrix -> ResultList; // And cursor position for our results.
  1304. // Now that our result processing gadgets are reset, let's process the results list.
  1305. int const CLEAN_RESULT = 0; // CLEAN means no matches or white.
  1306. int const NO_SYMBOL = 999; // NO_SYMBOL is higher than any SYMBOL
  1307. int S = NO_SYMBOL; // so we start there and work down.
  1308. snf_match TmpSNFMatch; // We'll need a buffer for our matches.
  1309. while(NULL!=ResultCursor) { // We will run through the results.
  1310. if(MyCFGPacket.isRulePanic(ResultCursor->RuleId())) { // If we have a rule panic then
  1311. MyScanData.RulePanics.insert(ResultCursor->RuleId()); // add the rule ID to our panics list.
  1312. TmpSNFMatch.flag = 'p'; // Record the match as a panic.
  1313. TmpSNFMatch.ruleid = ResultCursor->RuleId(); // Fill out the details of the match.
  1314. TmpSNFMatch.symbol = ResultCursor->RuleGroup(); // and add it to our list.
  1315. TmpSNFMatch.index = ResultCursor->MatchStartPosition;
  1316. TmpSNFMatch.endex = ResultCursor->MatchEndPosition;
  1317. MyScanData.MatchRecords.push_back(TmpSNFMatch);
  1318. } else { // If we did not have a panic then
  1319. if(ResultCursor->RuleGroup()<S) { // if we find a better symbol we
  1320. FinalResult = ResultCursor; // can grab the result record and the
  1321. S = ResultCursor->RuleGroup(); // symbol value.
  1322. }
  1323. if( // Figure out what kind of match this is.
  1324. (MyCFGPacket.Config()->TrainingWhiteRuleHandler.isListed( // If the symbol is in the known white
  1325. ResultCursor->RuleGroup())) || // rule groups OR if the symbol is
  1326. (0 == ResultCursor->RuleGroup()) // zero (same as clean) then
  1327. ) { // we will record this match
  1328. TmpSNFMatch.flag = 'w'; // as a white-rule... set the flag to w.
  1329. } else { // For all other cases we will
  1330. TmpSNFMatch.flag = 'm'; // simply record a match (m).
  1331. }
  1332. TmpSNFMatch.ruleid = ResultCursor->RuleId(); // Fill out the details of the match.
  1333. TmpSNFMatch.symbol = ResultCursor->RuleGroup(); // and add it to our list.
  1334. TmpSNFMatch.index = ResultCursor->MatchStartPosition;
  1335. TmpSNFMatch.endex = ResultCursor->MatchEndPosition;
  1336. MyScanData.MatchRecords.push_back(TmpSNFMatch);
  1337. }
  1338. ResultsCount++; // Count this result.
  1339. ResultCursor=ResultCursor->NextMatchRecord; // Then we keep looking.
  1340. }
  1341. if(NO_SYMBOL != S) { // If a pattern match was detected then
  1342. MyScanData.PatternWasFound = true; // trip the flag and record the
  1343. MyScanData.PatternID = FinalResult->RuleId(); // Rule ID and the
  1344. MyScanData.PatternSymbol = FinalResult->RuleGroup(); // Symbol.
  1345. }
  1346. //// GBUdb Integration ///////////////////////////////////////////////////////
  1347. // To integrate GBUdb we need to generalize the result from the pattern scan.
  1348. PatternResultTypes ScanResultType = NoPattern; // What kind of result have we here?
  1349. if(0 < (MyScanData.HeaderDirectiveFlags & HeaderDirectiveWhite)) { // If a white header directive matched
  1350. ScanResultType = WhitePattern; // then we have a "WhitePattern'.
  1351. } else
  1352. if(MyCFGPacket.Config()->TrainingWhiteRuleHandler.isListed(S)) { // If the pattern was mapped to a white
  1353. ScanResultType = WhitePattern; // rule group then we have a 'WhitePattern'.
  1354. } else
  1355. if(CLEAN_RESULT == S) { // If there was a standard white rule
  1356. ScanResultType = WhitePattern; // result then we have a 'WhitePattern'.
  1357. } else
  1358. if(NO_SYMBOL == S) { // If there was no pattern match then
  1359. ScanResultType = NoPattern; // we have 'NoPattern'.
  1360. } else
  1361. if(63 == S) { // If the pattern was a standard IP rule
  1362. ScanResultType = IPPattern; // then we have an 'IPPattern'.
  1363. } else
  1364. if(62 >= S) { // In general, other nonzer rule groups
  1365. ScanResultType = BlackPattern; // indicate we have a 'BlackPatter'.
  1366. } else
  1367. if(63 < S) { // Any pattern number > 63 is special.
  1368. ScanResultType = AboveBandPattern; // Any of these are an 'AboveBandPattern'
  1369. }
  1370. if(MyScanData.FoundSourceIP()) { // We need an identified IP source.
  1371. // Train the GBUdb based on our pattern matching results.
  1372. // Evaluate our training conditions.
  1373. bool TrainingIsTurnedOn = MyCFGPacket.Config()->GBUdbTrainingOn_Off;
  1374. bool MessageWasNotTruncated = (false == MyScanData.GBUdbTruncateExecuted);
  1375. bool ThereIsNoBypassHeaderDirective = (0 == (MyScanData.HeaderDirectiveFlags & HeaderDirectiveBypass));
  1376. bool ThereIsNoBypassResultCodeRule = (false == MyCFGPacket.Config()->TrainingBypassRuleHandler.isListed(S));
  1377. bool ThereIsNoImpliedBypassDirective = (Ignore != (MyScanData.SourceIPRecord().GBUdbData.Flag()));
  1378. // If these conditions are favorable then train the GBUdb.
  1379. if( // Check to see if training is enabled.
  1380. TrainingIsTurnedOn && // If it is turned on AND
  1381. MessageWasNotTruncated && // The message was not truncated AND
  1382. ThereIsNoBypassHeaderDirective && // There is NO Bypass header directive AND
  1383. ThereIsNoBypassResultCodeRule && // There is NO Bypass result code rule AND
  1384. ThereIsNoImpliedBypassDirective // There is NO Implied bypass directive:
  1385. ) {
  1386. // GBUdb training is enabled.
  1387. switch(ScanResultType) { // Evaluate the scan result.
  1388. case NoPattern: // On no pattern (benefit of doubt) or
  1389. case WhitePattern: { // a white pattern:
  1390. MyRulebase->MyGBUdb.addGood( // then add a good count to the
  1391. MyScanData.SourceIPRecord().IP); // source IP.
  1392. break;
  1393. }
  1394. case BlackPattern: { // On a black pattern:
  1395. MyRulebase->MyGBUdb.addBad( // add a bad count to the source IP
  1396. MyScanData.SourceIPRecord().IP); // in the GBUdb.
  1397. break;
  1398. }
  1399. default: break; // In all other cases, don't train.
  1400. }
  1401. }
  1402. // GBUdb Training Is Complete
  1403. // At this point our SourceIPRange tells us exactly how to evaluate
  1404. // the source IP for this message.
  1405. switch(MyScanData.SourceIPRange()) {
  1406. case White: { // If the IP was in the white zone
  1407. MyScanData.GBUdbWhiteTriggered = true; // mark that down.
  1408. if(MyCFGPacket.Config()->WhiteRangeHandler.On_Off) { // If we're also turned on then
  1409. if( // do we need to force the symbol?
  1410. BlackPattern == ScanResultType || // We do if the pattern scan resulted
  1411. IPPattern == ScanResultType // in a black or IPblack match.
  1412. ) { // If we must force a white result:
  1413. S = MyCFGPacket.Config()->WhiteRangeHandler.Symbol; // force the symbol and
  1414. MyScanData.GBUdbWhiteSymbolForced = true; // record that it was done.
  1415. }
  1416. // AutoPanic
  1417. int AutoPanicRangeLowerBound = // Calculate the current lower bound
  1418. MyRulebase->MyLOGmgr.LatestRuleID() - // for rule id's that are eligible to
  1419. MyCFGPacket.Config()->gbudb_regions_white_panic_rule_range; // trigger auto-panics.
  1420. if(BlackPattern == ScanResultType || IPPattern == ScanResultType) { // Was there a pattern/source conflict?
  1421. MyScanData.GBUdbPatternSourceConflict = true; // Record the event.
  1422. if(MyScanData.PatternID > AutoPanicRangeLowerBound) { // If the pattern ID is in range then
  1423. MyScanData.GBUdbAutoPanicTriggered = true; // record that the AutoPanic triggered.
  1424. if(MyCFGPacket.Config()->gbudb_regions_white_panic_on_off) { // If rule panics are turned on then
  1425. MyScanData.GBUdbAutoPanicExecuted = true; // indicate we are executing an autopanic.
  1426. MyRulebase->addRulePanic(MyScanData.PatternID); // Add the rule panic.
  1427. }
  1428. }
  1429. }
  1430. }
  1431. break;
  1432. }
  1433. case Normal: { // If the IP is normal...
  1434. MyScanData.GBUdbNormalTriggered = true; // Count the event.
  1435. break; // That's all.
  1436. }
  1437. case New: {
  1438. break;
  1439. }
  1440. case Caution: { // If the IP is in the caution range.
  1441. MyScanData.GBUdbCautionTriggered = true; // Track that this range fired.
  1442. if(
  1443. MyCFGPacket.Config()->CautionRangeHandler.On_Off && // If we're also turned on and there
  1444. NoPattern == ScanResultType // is no pattern match then
  1445. ) { // we will override the scan result:
  1446. S = MyCFGPacket.Config()->CautionRangeHandler.Symbol; // set the symbol as configured and
  1447. MyScanData.GBUdbCautionSymbolForced = true; // record that it was done.
  1448. }
  1449. break;
  1450. }
  1451. // Truncate is a kind of uber-black, so we do some weirdness here.
  1452. // If Truncate happens, then black was triggered by definition. In
  1453. // peek cases or if Truncate is turned off then Truncate might not
  1454. // execute-- when that happens we need to fall back to Black behavior.
  1455. case Truncate: // If the IP was in the truncate range
  1456. case Black: { // and/or If the IP is in the black range
  1457. MyScanData.GBUdbBlackTriggered = true; // mark that down.
  1458. if(MyScanData.GBUdbTruncateExecuted) { // If the truncate action was executed
  1459. S = MyCFGPacket.Config()->gbudb_regions_black_truncate_symbol; // we set the output symbol accordingly.
  1460. } else // Truncate overrides black.. but if
  1461. if( // Black is in charge do this...
  1462. MyCFGPacket.Config()->BlackRangeHandler.On_Off && // If black action is turned on and there
  1463. NoPattern == ScanResultType // is no pattern match then
  1464. ) { // we will override the scan data:
  1465. S = MyCFGPacket.Config()->BlackRangeHandler.Symbol; // set the symbol as configured and
  1466. MyScanData.GBUdbBlackSymbolForced = true; // record that it was done.
  1467. }
  1468. // Now that all of the overrides have been handled we can handle
  1469. // sampling. When a black IP is detected and a pattern match is not
  1470. // then we may sample the data.
  1471. int BlackSampleRate = // Grab the sample rate to make the
  1472. MyCFGPacket.Config()->gbudb_regions_black_sample_grab_one_in; // logic clearer.
  1473. bool SampleThresholdReached = // Check the spam probability of the
  1474. (MyCFGPacket.Config()->gbudb_regions_black_sample_probability <= // source IP against the configuration
  1475. MyScanData.SourceIPRecord().GBUdbData.Probability()); // to see if this IP is a candidate.
  1476. if( // Should we sample?
  1477. false == MyScanData.GBUdbTruncateExecuted && // If this was not a truncation and
  1478. NoPattern == ScanResultType && // No pattern match was found and
  1479. SampleThresholdReached && // We reached out sample threshold and
  1480. MyRulebase->MyLOGmgr.OkToSample(BlackSampleRate) // It's ok for us to sample this round
  1481. ) { // then our sampling mechanism is triggerd.
  1482. MyScanData.GBUdbSampleTriggered = true; // Mark down that event.
  1483. if(MyCFGPacket.Config()->gbudb_regions_black_sample_on_off) { // If sampling is turned on then
  1484. MyScanData.GBUdbSampleExecuted = true; // we will be sampling this data.
  1485. if(MyCFGPacket.Config()->gbudb_regions_black_sample_passthrough) { // If sampling by passthrough then
  1486. S = MyCFGPacket.Config()-> // Force the symbol value to passthrough
  1487. gbudb_regions_black_sample_passthrough_symbol; // (usually 0 - same as CLEAN).
  1488. } else { // If sampling internally then
  1489. MyRulebase->MyNETmgr.sendSample( // send this message as a sample.
  1490. (*(MyCFGPacket.Config())), // Pass our current config info,
  1491. MyScanData, // our scan data,
  1492. MessageBuffer, // and the message itself.
  1493. MessageLength
  1494. );
  1495. }
  1496. }
  1497. }
  1498. break;
  1499. }
  1500. case Unknown: // Unknown - most likely we couldn't
  1501. default: { // find a usable source.
  1502. break; // Do nothing.
  1503. }
  1504. }
  1505. } // End of IP source depended work (GBUdbOverrides)
  1506. // At this point we know the final result of our scan
  1507. // and the number of results we have. It's time to set up our result
  1508. // processing widgets for further query and return the result of this scan.
  1509. ResultCursor = CurrentMatrix -> ResultList; // Starting at the top of the list
  1510. ResultsRemaining = ResultsCount; // with all of the results ahead of us.
  1511. if(NO_SYMBOL==S) S = CLEAN_RESULT; // When there were no results, CLEAN
  1512. MyScanData.CompositeFinalResult = S; // Record what we will return.
  1513. if( // Prepare our final result.
  1514. CLEAN_RESULT == S && // If we have a clean result code
  1515. ScanResultType != WhitePattern && // and it wasn't forced by a white
  1516. false == MyScanData.GBUdbWhiteSymbolForced) { // rule or white GBUdb then we mark
  1517. TmpSNFMatch.flag = 'c'; // the final record Clean.
  1518. } else { // Otherwise we mark the final record
  1519. TmpSNFMatch.flag = 'f'; // as Final - meaning deliberately zero.
  1520. }
  1521. TmpSNFMatch.index = 0; // Our index is charater zero.
  1522. TmpSNFMatch.endex = CurrentMatrix->CountOfCharacters - 1; // Our endex is the end of the message.
  1523. TmpSNFMatch.symbol = MyScanData.CompositeFinalResult; // Our symbol is in CompositeFinal.
  1524. // The rule id is dependent on what's happened...
  1525. if( // If the symbol has been forced...
  1526. MyScanData.GBUdbTruncateExecuted || // Was it a Truncate-IP scan?
  1527. MyScanData.GBUdbWhiteSymbolForced || // Was it a White-IP scan?
  1528. MyScanData.GBUdbBlackSymbolForced || // Was it a Black-IP scan?
  1529. MyScanData.GBUdbCautionSymbolForced || // Was it a Caution-IP scan?
  1530. NULL == FinalResult // OR there was no valid match
  1531. ) { // then our rule id will be
  1532. TmpSNFMatch.ruleid = 0; // ZERO.
  1533. } else { // Normally the rule id will be
  1534. TmpSNFMatch.ruleid = FinalResult->RuleId(); // that of the winning pattern match.
  1535. }
  1536. MyScanData.MatchRecords.push_back(TmpSNFMatch); // Push our final entry onto the list.
  1537. MyScanData.MatchRecordsCursor = MyScanData.MatchRecords.begin(); // Reset the delivery system to the
  1538. MyScanData.MatchRecordsDelivered = 0; // beginning of the results list.
  1539. MyScanData.ScanDepth = CurrentMatrix->MaximumCountOfEvaluators; // Capture the scan depth.
  1540. MyScanData.ScanTime.stop(); // Stop the scan time clock.
  1541. MyRulebase->MyLOGmgr.logThisScan((*(MyCFGPacket.Config())), MyScanData); // Log the data from this scan.
  1542. // Since V2-9rc19 of this engine, the Engine mutex and snfCFGPacket handle
  1543. // their own cleanup when this call goes out of scope. ScannerIsBusy(MyMutex)
  1544. // will unlock() on destruction and snfCFGPacket will MyRulebase->drop().
  1545. return S; // Return the final scan result.
  1546. }
  1547. int snf_EngineHandler::getResults(snf_match* MatchBuffer){ // Get the next match buffer.
  1548. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1549. if(NULL == MatchBuffer) { // If we were given the reset signal
  1550. MyScanData.MatchRecordsCursor = MyScanData.MatchRecords.begin(); // Move the cursor to the beginning
  1551. MyScanData.MatchRecordsDelivered = 0; // and reset the delivered count.
  1552. } else { // If we are in delivery mode and
  1553. if(MyScanData.MatchRecords.end() != MyScanData.MatchRecordsCursor) { // there are more to deliver then
  1554. (*MatchBuffer) = (*MyScanData.MatchRecordsCursor); // deliver the current match and
  1555. ++MyScanData.MatchRecordsCursor; // move on to the next. Be sure to
  1556. ++MyScanData.MatchRecordsDelivered; // count this one as delivered.
  1557. }
  1558. }
  1559. return MyScanData.MatchRecords.size() - MyScanData.MatchRecordsDelivered; // Return a count of unseen records.
  1560. }
  1561. int snf_EngineHandler::getDepth(){ // Get the scan depth.
  1562. ScopeMutex SerializeThis(MyMutex); // Protect our reading.
  1563. return MyScanData.ScanDepth; // Return the latest scan depth.
  1564. }
  1565. const string snf_EngineHandler::getClassicLog() { // Get classic log entries for last scan.
  1566. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1567. return MyScanData.ClassicLogText; // Return the log text.
  1568. }
  1569. const string snf_EngineHandler::getXMLLog() { // Get XML log entries or last scan.
  1570. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1571. return MyScanData.XMLLogText; // Return the log text.
  1572. }
  1573. const string snf_EngineHandler::getXHDRs() { // Get XHDRs for last scan.
  1574. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1575. return MyScanData.XHDRsText; // Return the XHeaders text.
  1576. }
  1577. //// Multi Engine Handler Methods
  1578. // snf_RoundRulebaseCursor()
  1579. // Returns the next rulebase slot id wrapping around to zero.
  1580. int snf_MultiEngineHandler::RoundRulebaseCursor(){ // Return the next Rulebase handle
  1581. RulebaseCursor++; // Increase the cursor.
  1582. if(snf_MAX_RULEBASES<=RulebaseCursor) // If we've reached the end of the array
  1583. RulebaseCursor=0; // then we start back at zero.
  1584. return RulebaseCursor; // Return the new handle candidate.
  1585. }
  1586. // snf_RoundEngineCursor()
  1587. // Returns the next engine slot id wrapping around to zero.
  1588. int snf_MultiEngineHandler::RoundEngineCursor(){ // Return the next Engine handle candidate.
  1589. EngineCursor++; // Increase the cursor.
  1590. if(snf_MAX_SCANNERS<=EngineCursor) // If we've reached the end of the array
  1591. EngineCursor=0; // then we start back at zero.
  1592. return EngineCursor; // Return the new handle candidate.
  1593. }
  1594. snf_MultiEngineHandler::~snf_MultiEngineHandler(){ // Clean up, safety check, shut down.
  1595. RulebaseScan.lock(); // Lock both the rulebase and
  1596. EngineScan.lock(); // engine scan rulebases.
  1597. RulebaseCursor = EngineCursor = SHUTDOWN; // Set the cursors to the FINISHED value.
  1598. // The handlers in the arrays will all get closed by their destructors.
  1599. // The SHUTDOWN value in the cursors will force any errant threads to get no love.
  1600. RulebaseScan.unlock();
  1601. EngineScan.unlock();
  1602. }
  1603. // snf_OpenRulebase()
  1604. // Grab the first available rulebse handler and light it up.
  1605. int snf_MultiEngineHandler::OpenRulebase(const char* path, const char* licenseid, const char* authentication){
  1606. RulebaseScan.lock(); // Serialize this.
  1607. if(SHUTDOWN==RulebaseCursor) { // Not ok to open after shutdown.
  1608. RulebaseScan.unlock();
  1609. throw Panic("snf_MultiEngineHandler::OpenRulebase() No open after shutdown");
  1610. }
  1611. int Handle = RoundRulebaseCursor(); // Grab the next hanlder on the list.
  1612. if(RulebaseHandlers[Handle].isReady()) { // Check to see if it's already in use. If so,
  1613. int wherewasi = Handle; // keep track of where we started.
  1614. while(RulebaseHandlers[(Handle=RoundRulebaseCursor())].isReady()){ // Loop to find an free handler.
  1615. if(wherewasi==Handle) { // If we get back where we started
  1616. RulebaseScan.unlock(); // Unlock the Rulebase Scanning process
  1617. throw TooMany("snf_MultiEngineHandler::OpenRulebase() Too Many Open"); // and tell the caller Too Many are open.
  1618. }
  1619. }
  1620. }
  1621. // Now we have a Handle to a free RulebaseHandler. Time to open it up.
  1622. try {
  1623. RulebaseHandlers[Handle].open(path,licenseid,authentication); // Try to open the handler.
  1624. } // If an exception is thrown...
  1625. catch(snf_RulebaseHandler::AuthenticationError& e) // Catch and re-throw the appropriate
  1626. { RulebaseScan.unlock(); throw AuthenticationError(e.what()); } // exception.
  1627. catch(snf_RulebaseHandler::AllocationError& e)
  1628. { RulebaseScan.unlock(); throw AllocationError(e.what()); }
  1629. catch(snf_RulebaseHandler::FileError& e)
  1630. { RulebaseScan.unlock(); throw FileError(e.what()); }
  1631. catch(snf_RulebaseHandler::Busy& e)
  1632. { RulebaseScan.unlock(); throw Panic(e.what()); } // Wasn't busy above!! Shoudn't be here!!!
  1633. catch(exception& e)
  1634. { RulebaseScan.unlock(); throw; }
  1635. catch(...) {
  1636. RulebaseScan.unlock();
  1637. throw Panic("snf_MultiEngineHandler::OpenRulebase() ???");
  1638. }
  1639. RulebaseScan.unlock(); // If everything went well then UnLock
  1640. return Handle; // and return the happy new handle.
  1641. }
  1642. // snf_RefreshRulebase()
  1643. // Reload the rulebase associated with the handler.
  1644. void snf_MultiEngineHandler::RefreshRulebase(int RulebaseHandle){ // Refreshing a rulebase (Not Serialized)
  1645. try {
  1646. RulebaseHandlers[RulebaseHandle].refresh(); // Try to refresh the rulebase.
  1647. } // Catch and rethrow any exceptions.
  1648. catch(snf_RulebaseHandler::AuthenticationError& e) {
  1649. throw AuthenticationError(e.what());
  1650. }
  1651. catch(snf_RulebaseHandler::AllocationError& e) {
  1652. throw AllocationError(e.what());
  1653. }
  1654. catch(snf_RulebaseHandler::FileError& e) {
  1655. throw FileError(e.what());
  1656. }
  1657. catch(snf_RulebaseHandler::Busy& e) {
  1658. throw Busy(e.what());
  1659. }
  1660. catch(exception& e) {
  1661. throw;
  1662. }
  1663. catch(...) {
  1664. throw Panic("snf_MultiEngineHandler::RefreshRulebase() ???");
  1665. }
  1666. }
  1667. // snf_CloseRulebase()
  1668. // Shut down this Rulebase handler.
  1669. void snf_MultiEngineHandler::CloseRulebase(int RulebaseHandle){ // Closing a rulebase handler
  1670. RulebaseScan.lock(); // Serialize this - the handler changes state.
  1671. try { // Try to close the handler.
  1672. RulebaseHandlers[RulebaseHandle].close();
  1673. }
  1674. catch(snf_RulebaseHandler::Busy& e) { // A busy throw we can understand.
  1675. RulebaseScan.unlock(); throw Busy(e.what());
  1676. }
  1677. catch(exception& e) { // Other exceptions? rethrow.
  1678. RulebaseScan.unlock(); throw;
  1679. }
  1680. catch(...) { // Any other throw is big trouble.
  1681. RulebaseScan.unlock();
  1682. throw Panic("snf_MultiEngineHandler::CloseRulebase() ???");
  1683. }
  1684. RulebaseScan.unlock(); // When done, unlock the Rulebase Scan process.
  1685. }
  1686. // snf_OpenEngine()
  1687. // Grab the first available Engine handler and light it up
  1688. int snf_MultiEngineHandler::OpenEngine(int RulebaseHandle){
  1689. EngineScan.lock(); // Serialize this.
  1690. if(SHUTDOWN==EngineCursor) { // Not ok to open after shutdown.
  1691. EngineScan.unlock();
  1692. throw Panic("snf_MultiEngineHandler::OpenEngine() No open after shutdwon");
  1693. }
  1694. int Handle = RoundEngineCursor(); // Grab the next hanlder on the list.
  1695. if(EngineHandlers[Handle].isReady()) { // Check to see if it's already in use. If so,
  1696. int wherewasi = Handle; // keep track of where we started.
  1697. while(EngineHandlers[(Handle=RoundEngineCursor())].isReady()){ // Loop to find an free handler.
  1698. if(wherewasi==Handle) { // If we get back where we started
  1699. EngineScan.unlock(); // Unlock the Rulebase Scanning process
  1700. throw TooMany("snf_MultiEngineHandler::OpenEngine() too many open"); // and tell the caller Too Many are open.
  1701. }
  1702. }
  1703. }
  1704. // Now we have a Handle to a free RulebaseHandler. Time to open it up.
  1705. try {
  1706. EngineHandlers[Handle].open(&RulebaseHandlers[RulebaseHandle]); // Try to open the handler.
  1707. } // If an exception is thrown...
  1708. catch(snf_EngineHandler::AllocationError& e) // Catch and rethrow as appropriate.
  1709. { EngineScan.unlock(); throw AllocationError(e.what()); }
  1710. catch(snf_EngineHandler::Busy& e)
  1711. { EngineScan.unlock(); throw Panic(e.what()); } // Not busy above should not be busy now!!!
  1712. catch(exception& e) {
  1713. EngineScan.unlock();
  1714. throw;
  1715. }
  1716. catch(...) {
  1717. EngineScan.unlock();
  1718. throw Panic("snf_MultiEngineHandler::OpenEngine() ???");
  1719. }
  1720. EngineScan.unlock(); // If everything went well then UnLock
  1721. return Handle; // and return the happy new handle.
  1722. }
  1723. // snf_CloseEngine()
  1724. // Shut down this Engine handler.
  1725. void snf_MultiEngineHandler::CloseEngine(int EngineHandle){ // Closing an engine handler.
  1726. EngineScan.lock(); // Serialize this, the object changes states.
  1727. try {
  1728. EngineHandlers[EngineHandle].close(); // Try closing the handler.
  1729. }
  1730. catch(snf_EngineHandler::AllocationError& e) // Catch and throw any exceptions as needed.
  1731. { EngineScan.unlock(); throw AllocationError(e.what()); }
  1732. catch(snf_EngineHandler::Busy& e)
  1733. { EngineScan.unlock(); throw Busy(e.what()); }
  1734. catch(exception& e) {
  1735. EngineScan.unlock();
  1736. throw;
  1737. }
  1738. catch(...) {
  1739. EngineScan.unlock();
  1740. throw Panic("snf_MultiEngineHandler::CloseEngine() ???");
  1741. }
  1742. EngineScan.unlock(); // Unlock when we're closed.
  1743. }
  1744. // snf_Scan()
  1745. // Scan the MessageBuffer with this Engine.
  1746. int snf_MultiEngineHandler::Scan(int EngineHandle, const unsigned char* MessageBuffer, int MessageLength){
  1747. // NOT serialized. Many scans at once, presumably one scan engine per thread.
  1748. int ScanResult; // ScanResult stays in scope.
  1749. try {
  1750. ScanResult=EngineHandlers[EngineHandle]
  1751. .scanMessage(MessageBuffer,MessageLength); // Try the scan on the given engine.
  1752. }
  1753. catch(snf_EngineHandler::AllocationError& e) { // Re-throw any exceptions as needed.
  1754. throw AllocationError(e.what());
  1755. }
  1756. catch(snf_EngineHandler::Busy& e) { throw Busy(e.what()); }
  1757. catch(exception& e) { throw; }
  1758. catch(...) { throw Panic("snf_MultiEngineHandler::Scan() ???"); }
  1759. return ScanResult; // Return the results.
  1760. }
  1761. // The Engine prvides detailed match results through this function.
  1762. int snf_MultiEngineHandler::getResults(int EngineHandle, snf_match* matchbfr){
  1763. // NOT serialized. Many scans at once, presumably one scan engine per thread.
  1764. int ResultCount; // ResultCount stays in scope.
  1765. try {
  1766. ResultCount=EngineHandlers[EngineHandle].getResults(matchbfr); // Try the scan on the given engine.
  1767. }
  1768. catch(snf_EngineHandler::AllocationError& e) { // Re-throw any exceptions as needed.
  1769. throw AllocationError(e.what());
  1770. }
  1771. catch(snf_EngineHandler::Busy& e) { throw Busy(e.what()); }
  1772. catch(exception& e) { throw; }
  1773. catch(...) { throw Panic("snf_MultiEngineHandler::getResults() ???"); }
  1774. return ResultCount; // Return the results.
  1775. }
  1776. // The Engine provies the scan depth through this function.
  1777. int snf_MultiEngineHandler::getDepth(int EngineHandle){
  1778. // NOT serialized. Many scans at once, presumably one scan engine per thread.
  1779. int DepthResult; // ScanResult stays in scope.
  1780. try {
  1781. DepthResult=EngineHandlers[EngineHandle].getDepth(); // Try the scan on the given engine.
  1782. }
  1783. catch(snf_EngineHandler::AllocationError& e) { // Re-throw any exceptions as needed.
  1784. throw AllocationError(e.what());
  1785. }
  1786. catch(snf_EngineHandler::Busy& e) { throw Busy(e.what()); }
  1787. catch(exception& e) { throw; }
  1788. catch(...) { throw Panic("snf_MultiEngineHandler::getDepth() ???"); }
  1789. return DepthResult; // Return the results.
  1790. }