Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

SNFMulti.cpp 136KB

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