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.

UtilityConfig.cpp 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. // UtilityConfig.cpp
  2. //
  3. // Copyright (C) 2011, ARM Research Labs, LLC.
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // This file implements the common functionality for the configuration
  7. // utilities.
  8. #include <cerrno>
  9. #include <cstring>
  10. #include <unistd.h>
  11. #include <pwd.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <stdexcept>
  15. #include <sstream>
  16. #include <iostream>
  17. #include <fstream>
  18. #include <vector>
  19. #include "UtilityConfig.hpp"
  20. using namespace std;
  21. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  22. // Configuration. ////////////////////////////////////////////////////////////////////////////////////////
  23. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  24. // Initialize OS-dependent constants.
  25. #ifdef WIN
  26. // Windows OS.
  27. const std::string UtilityConfig::SampleIgnoreListFile("C:\\SNF\\GBUdbIgnoreList.txt.sample");
  28. const std::string UtilityConfig::RulebaseDownloadCommand("FIX THIS");
  29. const std::string UtilityConfig::RulebaseDownloadStatusFile("FIX THIS");
  30. const std::string ScriptNameKey("FIX THIS"); ///< Text to replace with script name.
  31. const std::string SnifferPathKey("FIX THIS"); ///< Text to replace with directory of the rulebase.
  32. const std::string UtilityConfig::SampleRulebaseScriptFile("C:\\SNF\\getRulebase.sample");
  33. const std::string UtilityConfig::OperatingSystemType("Windows");
  34. #else
  35. // *nix OS.
  36. // SCRIPT is replaced with the full path of the script run,
  37. // SNIFFER_PATH is replaced with the path of the rulebase.
  38. const std::string UtilityConfig::RulebaseDownloadCommand
  39. ("(cd SNIFFER_PATH; touch UpdateReady.txt; chown snfuser UpdateReady.txt; su -m snfuser -c SCRIPT)");
  40. const std::string ScriptNameKey("SCRIPT"); ///< Text to replace with script name.
  41. const std::string SnifferPathKey("SNIFFER_PATH"); ///< Text to replace with directory of the rulebase.
  42. // SNIFFER_PATH is replaced with the path of the rulebase.
  43. const std::string UtilityConfig::RulebaseDownloadStatusFile("SNIFFER_PATH/getRulebase.status");
  44. #ifdef DEFAULT_DATA_DIR
  45. // *nix, DEFAULT_DATA_DIR is specified on the compile command line.
  46. const std::string UtilityConfig::SampleIgnoreListFile(DEFAULT_DATA_DIR "/GBUdbIgnoreList.txt.sample");
  47. #else
  48. // Not Windows, and DEFAULT_DATA_DIR is not specified on the compile
  49. // command line. In this case, we don't know the path for the sample
  50. // ignore list file.
  51. #error DEFAULT_DATA_DIR must be defined by -DDEFAULT_DATA_DIR="..." when compiling.
  52. #endif
  53. #ifdef SBIN_DIR
  54. // *nix, SBIN_DIR is specified on the compile command line.
  55. const std::string UtilityConfig::SampleRulebaseScriptFile(SBIN_DIR "/getRulebase.sample");
  56. #else
  57. // Not Windows, and SBIN_DIR is not specified on the compile
  58. // command line. In this case, we don't know the path for the sample
  59. // ignore list file.
  60. #error SBIN_DIR must be defined by -DSBIN_DIR="..." when compiling.
  61. #endif
  62. #ifdef SNF_OSTYPE
  63. // *nix, SNF_OSTYPE is specified on the compile command line.
  64. const std::string UtilityConfig::OperatingSystemType(SNF_OSTYPE);
  65. #else
  66. // Not Windows, and SNF_OSTYPE is not specified on the compile command
  67. // line. In this case, we don't know the operating system.
  68. #error SNF_OSTYPE must be defined by -DSNF_OSTYPE="..." when compiling.
  69. #endif
  70. #endif
  71. /// Verbose command-line input.
  72. const string VerboseKey("-v");
  73. /// Explain command-line input.
  74. const string ExplainKey("-explain");
  75. /// Help command-line input.
  76. const string HelpKey("-h");
  77. /// Setup command-line input.
  78. const string SetupKey("-setup");
  79. /// Repair command-line input.
  80. const string RepairKey("-repair");
  81. /// Start sniffer command-line input.
  82. const string StartSnifferKey("-start");
  83. /// Stop sniffer command-line input.
  84. const string StopSnifferKey("-stop");
  85. /// Configuration file command-line input.
  86. const string ConfigFileKey("-config=");
  87. /// License ID command-line input.
  88. const string LicenseIdKey("-id=");
  89. /// Authentication command-line input.
  90. const string AuthenticationKey("-auth=");
  91. /// String that indicates a successful rulebase download.
  92. //
  93. // This string must be in the last line of the getRulebase status
  94. // file. Note: The getRulebase status file is created by the
  95. // getRulebase script, has the name getRulebase.status, and is in the
  96. // same directory as the rulebase files.
  97. const string SuccessKey("Success");
  98. const string LicenseSearchString = "LICENSE_ID=";
  99. const string AuthSearchString = "AUTHENTICATION=";
  100. const string IdentityElementName = "identity";
  101. const string LicenseAttributeName = "licenseid";
  102. const string AuthenticationAttributeName = "authentication";
  103. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  104. // End of configuration. /////////////////////////////////////////////////////////////////////////////////
  105. //////////////////////////////////////////////////////////////////////////////////////////////////////////
  106. UtilityConfig::UtilityConfig() :
  107. LicenseIdIsSpecified(false), AuthenticationIsSpecified(false)
  108. {
  109. SetExplain(false);
  110. SetVerbose(false);
  111. SetHelp(false);
  112. SetSetupRepair(false);
  113. SetStartSniffer(false);
  114. SetStopSniffer(false);
  115. }
  116. void
  117. UtilityConfig::CreateDefaultConfigFile(std::string SampleConfigFile) {
  118. std::string File = GetConfigFileName();
  119. if (!FileExists(File)) {
  120. if (!Explain()) {
  121. SaveFile.CreateBackupFile(File);
  122. }
  123. // Create the config file.
  124. Copy(SampleConfigFile, File);
  125. }
  126. SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Set permissions.
  127. SetOwnerGroup(File); // Set to sniffer user.
  128. }
  129. void
  130. UtilityConfig::LoadConfig() {
  131. if (Verbose()) {
  132. cout << "Using configuration file " << GetConfigFileName() << ".\n";
  133. }
  134. // Load the data.
  135. try {
  136. CFGData.initializeFromFile(GetConfigFileName().c_str());
  137. } catch(...) {
  138. string Temp;
  139. Temp = "Error reading configuration file " + GetConfigFileName();
  140. Temp += ".";
  141. throw std::runtime_error(Temp);
  142. }
  143. if ( (CFGData.paths_workspace_path.length() == 0) ||
  144. (CFGData.paths_rulebase_path.length() == 0) ||
  145. (CFGData.paths_log_path.length() == 0) ||
  146. (CFGData.update_script_call.length() == 0) ||
  147. (CFGData.node_identity.length() == 0) ) {
  148. string Temp;
  149. Temp = "The configuration file " + GetConfigFileName();
  150. Temp += " did not have the necessary specification of one or more paths:\n";
  151. Temp += "\n Workspace path: " + CFGData.paths_workspace_path;
  152. Temp += "\n Rulebase path: " + CFGData.paths_rulebase_path;
  153. Temp += "\n Log path: " + CFGData.paths_log_path;
  154. Temp += "\n Update script: " + CFGData.update_script_call;
  155. Temp += "\n Identity file: " + CFGData.node_identity;
  156. throw std::runtime_error(Temp);
  157. }
  158. }
  159. string
  160. UtilityConfig::GetPlatformContents(void) {
  161. return CFGData.PlatformElementContents;
  162. }
  163. string
  164. UtilityConfig::GetConfigFileName(void) {
  165. return ConfigFileName;
  166. }
  167. void
  168. UtilityConfig::SetConfigFileName(string Name) {
  169. ConfigFileName = Name;
  170. }
  171. string
  172. UtilityConfig::GetWorkspacePath(void) {
  173. return CFGData.paths_workspace_path;
  174. }
  175. string
  176. UtilityConfig::GetRulebasePath(void) {
  177. return CFGData.paths_rulebase_path;
  178. }
  179. string
  180. UtilityConfig::GetLogPath(void) {
  181. return CFGData.paths_log_path;
  182. }
  183. std::string
  184. UtilityConfig::GetStatusSecondLogFileName(void) {
  185. std::string FileName = CFGData.paths_log_path + CFGData.node_licenseid + ".status.second";
  186. if (CFGData.Status_SecondReport_Append_OnOff) {
  187. AppendDatestampToLogFileName(&FileName);
  188. }
  189. FileName += ".log.xml";
  190. return FileName;
  191. }
  192. std::string
  193. UtilityConfig::GetStatusMinuteLogFileName(void) {
  194. std::string FileName = CFGData.paths_log_path + CFGData.node_licenseid + ".status.minute";
  195. if (CFGData.Status_MinuteReport_Append_OnOff) {
  196. AppendDatestampToLogFileName(&FileName);
  197. }
  198. FileName += ".log.xml";
  199. return FileName;
  200. }
  201. void
  202. UtilityConfig::AppendDatestampToLogFileName(std::string *FileBaseName) {
  203. char TimestampBuffer[20];
  204. tm *BrokenDownTime;
  205. time_t Timestamp;
  206. time(&Timestamp);
  207. if (CFGData.Logs_Rotation_LocalTime_OnOff) {
  208. BrokenDownTime = localtime(&Timestamp);
  209. } else {
  210. BrokenDownTime = gmtime(&Timestamp);
  211. }
  212. snprintf(TimestampBuffer, sizeof TimestampBuffer, "%04d%02d%02d",
  213. BrokenDownTime->tm_year+1900,
  214. BrokenDownTime->tm_mon+1,
  215. BrokenDownTime->tm_mday);
  216. *FileBaseName += ".";
  217. *FileBaseName += TimestampBuffer;
  218. }
  219. string
  220. UtilityConfig::GetIdentityFileName(void) {
  221. return CFGData.node_identity;
  222. }
  223. string
  224. UtilityConfig::GetRulebaseScriptName(void) {
  225. return CFGData.update_script_call;
  226. }
  227. string
  228. UtilityConfig::GetIgnoreListFileName(void) {
  229. return GetWorkspacePath() + "GBUdbIgnoreList.txt";
  230. }
  231. string
  232. UtilityConfig::GetRulebaseFileName(void) {
  233. std::string Name;
  234. Name = GetRulebasePath();
  235. Name += LicenseId + ".snf";
  236. return Name;
  237. }
  238. string
  239. UtilityConfig::GetOperatingSystemType(void) {
  240. return OperatingSystemType;
  241. }
  242. void
  243. UtilityConfig::LoadInfo(){
  244. if ("OpenBSD" == OperatingSystemType) {
  245. PostfixMainCfPath = "/usr/local/etc/postfix/main.cf";
  246. PostfixMasterCfPath = "/usr/local/etc/postfix/master.cf";
  247. SnifferStartScriptDir = "/usr/local/sbin/";
  248. } else if ("FreeBSD" == OperatingSystemType) {
  249. PostfixMainCfPath = "/etc/postfix/main.cf";
  250. PostfixMasterCfPath = "/etc/postfix/master.cf";
  251. SnifferStartScriptDir = "/usr/local/etc/rc.d/";
  252. } else if ("Ubuntu" == OperatingSystemType) {
  253. PostfixMainCfPath = "/etc/postfix/main.cf";
  254. PostfixMasterCfPath = "/etc/postfix/master.cf";
  255. SnifferStartScriptDir = "/etc/init.d/";
  256. } else if ("RedHat" == OperatingSystemType) {
  257. PostfixMainCfPath = "/etc/postfix/main.cf";
  258. PostfixMasterCfPath = "/etc/postfix/master.cf";
  259. SnifferStartScriptDir = "/etc/init.d/";
  260. } else if ("Suse" == OperatingSystemType) {
  261. PostfixMainCfPath = "/etc/postfix/main.cf";
  262. PostfixMasterCfPath = "/etc/postfix/master.cf";
  263. SnifferStartScriptDir = "/etc/init.d/";
  264. } else {
  265. ostringstream Temp;
  266. Temp << "Internal error in UtilityConfig::LoadInfo: Invalid value of OperatingSystemType: "
  267. << OperatingSystemType;
  268. throw std::runtime_error(Temp.str());
  269. }
  270. }
  271. void
  272. UtilityConfig::LoadCredentials(void) {
  273. if(0 < CFGData.node_identity.length()) { // If an identity path was provided
  274. ConfigurationData Identity(CFGData.node_identity.c_str()); // then get the data from that file.
  275. ConfigurationElement IdentityReader("snf"); // Create an Identity reader and
  276. IdentityReader // configure it.
  277. .Element("identity")
  278. .Attribute("licenseid", CFGData.node_licenseid)
  279. .Attribute("authentication", CFGData.node_authentication)
  280. .End("identity")
  281. .End("snf");
  282. IdentityReader.interpret(Identity); // Then read the data.
  283. }
  284. }
  285. UtilityConfig::StatusCheckMethod
  286. UtilityConfig::GetPreferredStatusCheckMethod(void) {
  287. if (CFGData.XCI_OnOff) {
  288. return StatusCheckXci;
  289. }
  290. if (CFGData.Status_SecondReport_Log_OnOff) {
  291. return StatusCheckSecond;
  292. }
  293. if (CFGData.Status_MinuteReport_Log_OnOff) {
  294. return StatusCheckMinute;
  295. }
  296. return StatusCheckNotAvailable;
  297. }
  298. std::string
  299. UtilityConfig::GetSnifferStatusReport() {
  300. std::string StatusReport;
  301. int SleepTime_msec;
  302. int TimeoutTime_msec;
  303. switch (GetPreferredStatusCheckMethod()) {
  304. case StatusCheckXci:
  305. StatusReport = GetReportViaXci();
  306. break;
  307. case StatusCheckSecond:
  308. SleepTime_msec = 1000;
  309. TimeoutTime_msec = 7000;
  310. StatusReport = GetReportViaLogFile(&UtilityConfig::GetStatusSecondLogFileName, SleepTime_msec, TimeoutTime_msec);
  311. break;
  312. case StatusCheckMinute:
  313. SleepTime_msec = 10 * 1000;
  314. TimeoutTime_msec = 70 * 1000;
  315. std::cout << "Getting Sniffer status from status.minute log file (this takes about "
  316. << TimeoutTime_msec / 1000 << " s)...";
  317. std::cout.flush();
  318. StatusReport = GetReportViaLogFile(&UtilityConfig::GetStatusMinuteLogFileName, SleepTime_msec, TimeoutTime_msec);
  319. std::cout << "done." << std::endl;
  320. break;
  321. default:
  322. {
  323. std::string Temp;
  324. Temp = "No method for determining Sniffer status is available. ";
  325. Temp += "Tried XCI, status.second logging, and status.minute logging.";
  326. throw std::runtime_error(Temp);
  327. }
  328. }
  329. return StatusReport;
  330. }
  331. std::string
  332. UtilityConfig::GetReportViaXci() {
  333. if (Verbose()) {
  334. std::cout << "Getting Sniffer status report via XCI...";
  335. std::cout.flush();
  336. }
  337. bool ConnectSuccess = false;
  338. std::string ResultString;
  339. const std::string RequestString("<snf><xci><report><request><status class='second'/></request></report></xci></snf>");
  340. // Code copied from SNFClient.
  341. // Max time in this loop should be (100*50ms) = 5 seconds per try times
  342. // 10 tries = 50 seconds, plus (9*500ms) = 4.5 secs for re-tries. ~ 55 secs.
  343. const int ResultBufferSize = 4096;
  344. char ResultBuffer[ResultBufferSize+1]; // Make an oversize buffer for the answer.
  345. memset(ResultBuffer, 0, sizeof(ResultBuffer)); // Set the entire thing to nulls.
  346. const int Tries = 20; // How many times to try this.
  347. Sleeper SleepAfterAttempt(100); // How long to sleep between attempts.
  348. const int OpenTries = 90; // How many tries at opening.
  349. Sleeper WaitForOpen(10); // How long to wait for an open cycle.
  350. const int ReadTries = 900; // How many tries at reading.
  351. Sleeper SleepBeforeReading(10); // How long to pause before reading.
  352. /*
  353. ** 20 * 100ms = 2 seconds for all tries.
  354. ** 90 * 10ms = 900ms for a failed connection.
  355. ** 900 * 10ms = 9 seconds for a failed read.
  356. **
  357. ** Approximate wait for can't connect = 2.0 + (20 * 0.9) = ~ 20.0 seconds.
  358. ** Maximum impossible wait = 2.0 + (0.9 * 20) + (9.0 * 20) = 200.0 seconds.
  359. */
  360. for(int tryagain = Tries; (0<tryagain) && (!ConnectSuccess); tryagain--) { // Try a few times to get this done.
  361. try {
  362. ResultString = ""; // Clear our result string.
  363. TCPHost SNFServer(9001); // Create connection to server.
  364. SNFServer.makeNonBlocking(); // Make it non-blocking.
  365. for(int tries = OpenTries; 0 < tries; tries--) { // Wait & Watch for a good connection.
  366. try { SNFServer.open(); } catch(...) {} // Try opening the connection.
  367. if(SNFServer.isOpen()) break; // When successful, let's Go!
  368. else WaitForOpen(); // When not successful, pause.
  369. }
  370. if(SNFServer.isOpen()) { // If we have a good connection:
  371. SNFServer.transmit(
  372. RequestString.c_str(), RequestString.length()); // Send the request.
  373. for(int tries = ReadTries; 0 < tries; tries--) { // Try to read the result a few times.
  374. SleepBeforeReading(); // Provide some time for each try.
  375. memset(ResultBuffer, 0, sizeof(ResultBuffer)); // Clear the buffer.
  376. SNFServer.receive(ResultBuffer, ResultBufferSize); // Receive the answer.
  377. ResultString.append(ResultBuffer);
  378. if(string::npos ==
  379. ResultString.rfind("</snf>",ResultString.length())) { // If we don't have the end yet.
  380. continue; // Try again.
  381. } else { // If we got to end of line
  382. ConnectSuccess = true; // Success!
  383. break; // We're done.
  384. }
  385. }
  386. SNFServer.close(); // No need for our connection after that.
  387. }
  388. } catch(...) { } // Ignore errors for now.
  389. if(!ConnectSuccess) SleepAfterAttempt(); // Pause for a moment before trying again..
  390. }
  391. if(!ConnectSuccess) { // If no connection then Sniffer isn't running.
  392. if (Verbose()) {
  393. std::cout << "no response...";
  394. }
  395. return "";
  396. }
  397. // At this point we should have a usable result.
  398. if(Debug()) { cout << ResultString << endl; } // In debug, show the result string.
  399. snf_xci Reader(ResultString); // Interpret the data and check for
  400. if(Reader.bad()) { // a proper read. If it was bad...
  401. std::string Temp;
  402. Temp = "Bad result from Sniffer:\n" + ResultString;
  403. throw std::runtime_error(Temp);
  404. }
  405. if(0 < Reader.xci_error_message.length()) { // If the result was a general error...
  406. std::string Temp;
  407. Temp = "XCI error when determing status of Sniffer: " + Reader.xci_error_message;
  408. throw std::runtime_error(Temp);
  409. }
  410. if (Verbose()) {
  411. std::cout << "response received...";
  412. }
  413. return Reader.report_response;
  414. }
  415. std::string
  416. UtilityConfig::GetReportViaLogFile(GetLogFileName GetLogFileNamePtr, int SleepTime_msec, int TimeoutTime_msec) {
  417. std::string LogFileName;
  418. LogFileName = (this->*GetLogFileNamePtr)();
  419. if (Verbose()) {
  420. cout << "\nGetting Sniffer status report via log file " << LogFileName << "...";
  421. std::cout.flush();
  422. }
  423. std::string InitialContents;
  424. InitialContents = ReadLastPartOfFile(LogFileName, LogFileReportSize); // Read last part of log file.
  425. int ElapsedTime_msec = 0;
  426. while (ElapsedTime_msec < TimeoutTime_msec) {
  427. bool IncreasedTimeoutTime = false; // TimeoutTime_msec can be increased
  428. // only once if the log file name changes.
  429. std::string NewLogFileName;
  430. Sleeper Sleep(SleepTime_msec);
  431. std::string FinalContents;
  432. Sleep();
  433. NewLogFileName = (this->*GetLogFileNamePtr)();
  434. if (!IncreasedTimeoutTime && (NewLogFileName != LogFileName)) { // Filename changes if it contains a
  435. // date stemp and the time is close
  436. // to midnight.
  437. TimeoutTime_msec *= 2;
  438. IncreasedTimeoutTime = true;
  439. if (Verbose()) {
  440. cout << "reading from " << NewLogFileName << "...";
  441. std::cout.flush();
  442. }
  443. }
  444. LogFileName = NewLogFileName;
  445. FinalContents = ReadLastPartOfFile(LogFileName, LogFileReportSize); // Read again.
  446. if ( (FinalContents.length() != 0) && // There is a report, and
  447. (InitialContents != FinalContents) ) { // the contents have changed.
  448. if (Verbose()) {
  449. cout << "report changed...";
  450. }
  451. OutputVerboseEnd();
  452. std::string::size_type StatsStartPos; // Index of start of <stats> element.
  453. std::string::size_type StatsEndPos; // Index of end of <stats> element.
  454. StatsEndPos = FinalContents.rfind("</stats>");
  455. if (std::string::npos == StatsEndPos) {
  456. throw std::runtime_error("Unable to interpret the status report: No '</stats>' closing tag found.");
  457. }
  458. StatsStartPos = FinalContents.rfind("<stats ", StatsEndPos);
  459. if (std::string::npos == StatsStartPos) {
  460. throw std::runtime_error("Unable to interpret the status report: No '<stats>' tag found.");
  461. }
  462. return FinalContents.substr(StatsStartPos); // Return the last <stats> element.
  463. }
  464. ElapsedTime_msec += SleepTime_msec;
  465. }
  466. if (Verbose()) {
  467. cout << "report unchanged...";
  468. }
  469. OutputVerboseEnd();
  470. return "";
  471. }
  472. void
  473. UtilityConfig::CheckSnifferStatusReport(std::string StatusReport, std::string ApplicationName) {
  474. if (Verbose()) {
  475. cout << "Checking Sniffer status report...";
  476. }
  477. ConfigurationElement MyCFGReader("stats"); // Object to parse the XML.
  478. ConfigurationData MyCFGData(StatusReport.c_str(), StatusReport.length()); // Object that contains the XML.
  479. std::string PlatformContent;
  480. MyCFGReader
  481. .Element("version")
  482. .Element("platform", PlatformContent, "")
  483. .End("platform")
  484. .End("version")
  485. .End("stats");
  486. MyCFGReader.initialize();
  487. if (!MyCFGReader.interpret(MyCFGData)) {
  488. std::ostringstream Temp;
  489. Temp << "Error interpreting the Sniffer status report:\n" << StatusReport;
  490. throw std::runtime_error(Temp.str());
  491. }
  492. if (std::string::npos == PlatformContent.find(ApplicationName)) { // Verify correct application.
  493. std::ostringstream Temp;
  494. Temp << "Error--The expected Sniffer application (" << ApplicationName
  495. << ") isn't running. The running application determined from the status report is "
  496. << PlatformContent;
  497. throw std::runtime_error(Temp.str());
  498. }
  499. OutputVerboseEnd();
  500. }
  501. UtilityConfig::SnifferRunningStateEnum
  502. UtilityConfig::GetRunningState(std::string ApplicationName) {
  503. if (Verbose()) {
  504. cout << "Checking whether " << ApplicationName << " is running...";
  505. cout.flush();
  506. }
  507. std::string StatusReport = GetSnifferStatusReport();
  508. OutputVerboseEnd();
  509. if (StatusReport.length() == 0) {
  510. return SnifferIsStopped;
  511. }
  512. CheckSnifferStatusReport(StatusReport, ApplicationName);
  513. return SnifferIsRunning;
  514. }
  515. void
  516. UtilityConfig::SetupRepair(const std::string SampleIdentityFile) {
  517. RestoreMissingConfigFiles(SampleIdentityFile);
  518. SetOwnerPermissionsOfConfigFiles();
  519. }
  520. void
  521. UtilityConfig::RestoreMissingConfigFiles(std::string SampleIdentityFile) {
  522. std::string File;
  523. File = GetIdentityFileName();
  524. if (!FileExists(File)) {
  525. if (!Explain()) {
  526. SaveFile.CreateBackupFile(File);
  527. }
  528. // Create the config file.
  529. Copy(SampleIdentityFile, File);
  530. }
  531. File = GetRulebaseScriptName();
  532. if (!FileExists(File)) {
  533. if (!Explain()) {
  534. SaveFile.CreateBackupFile(File);
  535. }
  536. Copy(SampleRulebaseScriptFile, File); // Copy if !Explain().
  537. }
  538. File = GetIgnoreListFileName();
  539. if (!FileExists(File)) {
  540. if (!Explain()) {
  541. SaveFile.CreateBackupFile(File);
  542. }
  543. Copy(SampleIgnoreListFile, File);
  544. }
  545. std::string LogDir = GetLogPath();
  546. if (!FileExists(LogDir)) {
  547. MkDir(LogDir);
  548. }
  549. }
  550. void
  551. UtilityConfig::SetOwnerPermissionsOfConfigFiles() {
  552. std::string File;
  553. File = GetIdentityFileName();
  554. if (FileExists(File)) {
  555. SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP);
  556. SetOwnerGroup(File);
  557. }
  558. File = GetRulebaseScriptName();
  559. if (FileExists(File)) {
  560. SetMode(File, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  561. }
  562. File = GetIgnoreListFileName();
  563. if (FileExists(File)) {
  564. SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  565. SetOwnerGroup(File);
  566. }
  567. File = DEFAULT_DATA_DIR;
  568. if (FileExists(File)) {
  569. SetMode(File, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  570. SetOwnerGroup(File);
  571. }
  572. std::string LogDir = GetLogPath();
  573. if (FileExists(LogDir)) {
  574. SetMode(LogDir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  575. SetOwnerGroup(LogDir);
  576. }
  577. }
  578. void
  579. UtilityConfig::UpdateRulebaseScriptCredentials() {
  580. std::string File = GetRulebaseScriptName();
  581. if (Verbose()) {
  582. cout << "Update authentication and license ID in the rulebase download script file " << File << "--\n";
  583. }
  584. ifstream Input;
  585. Input.open(File.c_str()); // Read the contents.
  586. if (!Input) {
  587. string Temp;
  588. Temp = "Error opening rulebase download script file " + File;
  589. Temp += " for reading: ";
  590. Temp += strerror(errno);
  591. throw std::runtime_error(Temp);
  592. }
  593. string Content;
  594. string Line;
  595. bool FoundLicense = false;
  596. bool FoundAuth = false;
  597. while (getline(Input, Line)) {
  598. if (CheckForString(Line, LicenseSearchString)) { // Check for license line.
  599. if (FoundLicense) { // Second license line found?
  600. string Temp;
  601. Temp = "Rulebase sownload script file " + File;
  602. Temp += " has the wrong format: Found two lines beginning with " + LicenseSearchString;
  603. throw std::runtime_error(Temp);
  604. }
  605. if (Verbose()) {
  606. cout << " Modify line: '" << Line << "'...\n";
  607. }
  608. FoundLicense = true;
  609. Line = LicenseSearchString + LicenseId; // Add license line.
  610. Line += " # Added by SNFSetup";
  611. }
  612. if (CheckForString(Line, AuthSearchString)) { // Check for authentication line.
  613. if (FoundAuth) { // Second authentication line found?
  614. string Temp;
  615. Temp = "Rulebase download script file " + File;
  616. Temp += " has the wrong format: Found two lines beginning with " + AuthSearchString;
  617. throw std::runtime_error(Temp);
  618. }
  619. if (Verbose()) {
  620. cout << " Modify line: '" << Line << "'...\n";
  621. }
  622. FoundAuth = true;
  623. Line = AuthSearchString + Authentication; // Add authentication line.
  624. Line += " # Added by SNFSetup";
  625. }
  626. Content += Line + "\n";
  627. }
  628. if (!FoundLicense || !FoundAuth) {
  629. string Temp;
  630. Temp = "Rulebase download script file " + File;
  631. Temp += " has the wrong format: Missing required line beginning with '" + LicenseSearchString;
  632. Temp += "' or '" + AuthSearchString;
  633. Temp += "'";
  634. throw std::runtime_error(Temp);
  635. }
  636. if (!Input.eof()) { // Should be at end-of-file.
  637. string Temp;
  638. Temp = "Error reading the rulebase download script file " + File;
  639. Temp += ": ";
  640. Temp += strerror(errno);
  641. throw std::runtime_error(Temp);
  642. }
  643. Input.close();
  644. if (Input.bad()) {
  645. string Temp;
  646. Temp = "Error closing the rulebase download script file " + File;
  647. Temp += " after reading: ";
  648. Temp += strerror(errno);
  649. throw std::runtime_error(Temp);
  650. }
  651. if (!Explain()) {
  652. SaveFile.CreateBackupFile(File);
  653. ofstream Output; // Write the updated contents.
  654. Output.open(File.c_str(), ios::trunc);
  655. if (!Output) {
  656. string Temp;
  657. Temp = "Error opening rulebase download script file " + File;
  658. Temp += " for writing: ";
  659. Temp += strerror(errno);
  660. throw std::runtime_error(Temp);
  661. }
  662. Output << Content;
  663. if (!Output) {
  664. string Temp;
  665. Temp = "Error writing the rulebase download script file " + File;
  666. Temp += ": ";
  667. Temp += strerror(errno);
  668. throw std::runtime_error(Temp);
  669. }
  670. Output.close();
  671. if (!Output) {
  672. string Temp;
  673. Temp = "Error closing the rulebase download script file " + File;
  674. Temp += " after writing: ";
  675. Temp += strerror(errno);
  676. throw std::runtime_error(Temp);
  677. }
  678. }
  679. OutputVerboseEnd();
  680. }
  681. void
  682. UtilityConfig::DownloadRulebase() {
  683. if (Verbose()) {
  684. std::cout << "Downloading the rulebase...";
  685. std::cout.flush();
  686. }
  687. std::string Command;
  688. Command = RulebaseDownloadCommand;
  689. std::string::size_type ScriptIndex = Command.find(ScriptNameKey);
  690. if (ScriptIndex != std::string::npos) { // Insert script full path?
  691. Command.replace(ScriptIndex, ScriptNameKey.length(), GetRulebaseScriptName());
  692. }
  693. std::string::size_type SnifferPathIndex = Command.find(SnifferPathKey);
  694. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  695. Command.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  696. }
  697. std::string StatusFile; // Construct download status file name.
  698. StatusFile = RulebaseDownloadStatusFile;
  699. SnifferPathIndex = StatusFile.find(SnifferPathKey);
  700. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  701. StatusFile.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  702. }
  703. if (!Explain()) {
  704. SaveFile.CreateBackupFile(GetRulebaseFileName()); // Save the current rulebase file.
  705. if (0 != remove(StatusFile.c_str())) { // Delete the status file.
  706. if (ENOENT != errno) { // No error if the file doesn't exist.
  707. std::ostringstream Temp;
  708. Temp << "Unable to remove rulebase download status file " << StatusFile
  709. << ": " << strerror(errno);
  710. throw std::runtime_error(Temp.str());
  711. }
  712. }
  713. if (std::system(Command.c_str()) != 0) { // Download the rulebase.
  714. string Temp;
  715. Temp = "Error running the command '" + Command;
  716. Temp += "'.";
  717. throw std::runtime_error(Temp);
  718. }
  719. ifstream Input;
  720. Input.open(StatusFile.c_str()); // Check the status.
  721. if (!Input) {
  722. string Temp;
  723. Temp = "Error opening rulebase download scriptstatus file " + StatusFile;
  724. Temp += ": ";
  725. Temp += strerror(errno);
  726. throw std::runtime_error(Temp);
  727. }
  728. string Line;
  729. string PrevLine;
  730. string Content;
  731. while (getline(Input, Line)) { // Read the last line.
  732. PrevLine = Line;
  733. Content += Line + "\n";
  734. }
  735. if (PrevLine.find(SuccessKey) == std::string::npos) { // Check the status.
  736. string Temp;
  737. Temp = "Error downloading the rulebase. Rulebase download status:\n\n" + Content;
  738. throw std::runtime_error(Temp);
  739. }
  740. }
  741. OutputVerboseEnd();
  742. }
  743. void
  744. UtilityConfig::UpdateIdentityFile() {
  745. std::string File = GetIdentityFileName();
  746. if (Verbose()) {
  747. cout << "Update authentication and license ID in the identity file " << File << "--\n";
  748. }
  749. ifstream Input;
  750. Input.open(File.c_str()); // Read the contents.
  751. if (!Input) {
  752. string Temp;
  753. Temp = "Error opening identity file " + File;
  754. Temp += " for reading: ";
  755. Temp += strerror(errno);
  756. throw std::runtime_error(Temp);
  757. }
  758. ostringstream InputContents;
  759. if (!Input.eof()) { // Copy if there are characters.
  760. // Copying an empty file causes
  761. InputContents << Input.rdbuf(); // failbit to be set.
  762. }
  763. if (InputContents.bad() || InputContents.fail()) {
  764. std::string Temp;
  765. Temp = "Error reading identity file " + File;
  766. throw std::runtime_error(Temp);
  767. }
  768. Input.close();
  769. if (Input.bad()) {
  770. string Temp;
  771. Temp = "Error closing the identity file " + File;
  772. Temp += " after reading: ";
  773. Temp += strerror(errno);
  774. throw std::runtime_error(Temp);
  775. }
  776. string Content = InputContents.str();
  777. try {
  778. ReplaceXmlAttribute(&Content, IdentityElementName, LicenseAttributeName, LicenseId);
  779. ReplaceXmlAttribute(&Content, IdentityElementName, AuthenticationAttributeName, Authentication);
  780. } catch (std::exception &e) {
  781. std::string Temp;
  782. Temp = "Error updating credentials for identity file " + File;
  783. Temp += ": ";
  784. Temp += e.what();
  785. throw std::runtime_error(Temp);
  786. }
  787. if (!Explain()) {
  788. SaveFile.CreateBackupFile(File);
  789. ofstream Output;
  790. Output.open(File.c_str(), ios::trunc);
  791. if (!Output) {
  792. string Temp;
  793. Temp = "Error opening identity file " + File;
  794. Temp += " for writing: ";
  795. Temp += strerror(errno);
  796. throw std::runtime_error(Temp);
  797. }
  798. Output << Content;
  799. if (!Output) {
  800. string Temp;
  801. Temp = "Error writing the identity file " + File;
  802. Temp += ": ";
  803. Temp += strerror(errno);
  804. throw std::runtime_error(Temp);
  805. }
  806. Output.close();
  807. if (!Output) {
  808. string Temp;
  809. Temp = "Error closing the identity file " + File;
  810. Temp += " after writing: ";
  811. Temp += strerror(errno);
  812. throw std::runtime_error(Temp);
  813. }
  814. }
  815. OutputVerboseEnd();
  816. }
  817. #if 0
  818. void
  819. UtilityConfig::UpdateIdentityFileOld() {
  820. std::string File = GetIdentityFileName();
  821. ofstream Output;
  822. if (Verbose()) {
  823. cout << "Create identity file " << File << "...";
  824. }
  825. if (!Explain()) {
  826. SaveFile.CreateBackupFile(File);
  827. Output.open(File.c_str());
  828. if (!Output) {
  829. string Temp;
  830. Temp = "Error opening identity file " + File;
  831. Temp += ": ";
  832. Temp += strerror(errno);
  833. throw std::runtime_error(Temp);
  834. }
  835. Output << "<!-- License file created by SNFIdentity-->\n"
  836. << "<snf>\n"
  837. << " <identity licenseid='" << LicenseId << "' authentication='"
  838. << Authentication << "'/>\n"
  839. << "</snf>\n";
  840. if (!Output) {
  841. string Temp;
  842. Temp = "Error writing identity file " + File;
  843. Temp += ": ";
  844. Temp += strerror(errno);
  845. throw std::runtime_error(Temp);
  846. }
  847. Output.close();
  848. if (!Output) {
  849. string Temp;
  850. Temp = "Error closing identity file " + File;
  851. Temp += ": ";
  852. Temp += strerror(errno);
  853. throw std::runtime_error(Temp);
  854. }
  855. }
  856. OutputVerboseEnd();
  857. SetOwnerGroup(File); // Set the user and group.
  858. SetMode(File, S_IRUSR); // Set to readonly by owner.
  859. }
  860. #endif
  861. void
  862. UtilityConfig::StartSniffer(std::string ScriptAndArgs, std::string ApplicationName) {
  863. if (SnifferIsRunning == GetRunningState(ApplicationName)) {
  864. std::cout << ApplicationName << " is already running.\n";
  865. return;
  866. }
  867. std::string Command;
  868. Command = SnifferStartScriptDir + ScriptAndArgs;
  869. if (Verbose()) {
  870. cout << "Starting Sniffer with the command '" << Command << "'...";
  871. cout.flush();
  872. }
  873. if (!Explain()) {
  874. if (std::system(Command.c_str()) == -1) { // Start the sniffer.
  875. string Temp;
  876. Temp = "Error running the command '" + Command;
  877. Temp += "' to start the Sniffer: ";
  878. Temp += strerror(errno);
  879. throw std::runtime_error(Temp);
  880. }
  881. OutputVerboseEnd();
  882. if (SnifferIsRunning != GetRunningState(ApplicationName)) {
  883. std::string Temp;
  884. Temp = "Unable to start " + ApplicationName;
  885. throw std::runtime_error(Temp);
  886. }
  887. } else {
  888. OutputVerboseEnd();
  889. }
  890. }
  891. void
  892. UtilityConfig::StopSniffer(std::string ScriptAndArgs, std::string ApplicationName) {
  893. if (SnifferIsStopped == GetRunningState(ApplicationName)) {
  894. std::cout << ApplicationName << " was not running.\n";
  895. return;
  896. }
  897. std::string Command;
  898. Command = SnifferStartScriptDir + ScriptAndArgs;
  899. if (Verbose()) {
  900. cout << "Stopping Sniffer with the command '" << Command << "'...";
  901. cout.flush();
  902. }
  903. if (!Explain()) {
  904. if (std::system(Command.c_str()) == -1) { // Start the sniffer.
  905. string Temp;
  906. Temp = "Error running the command '" + Command;
  907. Temp += "' to stop the Sniffer: ";
  908. Temp += strerror(errno);
  909. throw std::runtime_error(Temp);
  910. }
  911. OutputVerboseEnd();
  912. if (SnifferIsStopped != GetRunningState(ApplicationName)) {
  913. std::string Temp;
  914. Temp = "Unable to stop " + ApplicationName;
  915. throw std::runtime_error(Temp);
  916. }
  917. } else {
  918. OutputVerboseEnd();
  919. }
  920. }
  921. bool
  922. UtilityConfig::ProcessCommandLineItem(std::string OneInput) {
  923. bool ValidCommand = true;
  924. std::string TempString;
  925. if (OneInput == VerboseKey) {
  926. SetVerbose(true);
  927. } else if (OneInput == ExplainKey) {
  928. SetExplain(true);
  929. } else if (OneInput == HelpKey) {
  930. SetHelp(true);
  931. } else if (OneInput == SetupKey) {
  932. SetSetupRepair(true);
  933. } else if (OneInput == RepairKey) {
  934. SetSetupRepair(true);
  935. } else if (OneInput == StartSnifferKey) {
  936. SetStartSniffer(true);
  937. } else if (OneInput == StopSnifferKey) {
  938. SetStopSniffer(true);
  939. } else if (0 == OneInput.find(ConfigFileKey)) {
  940. TempString = Trim(OneInput.substr(ConfigFileKey.length())); // Copy only if not null after trimming.
  941. SetConfigFileName(TempString);
  942. } else if (0 == OneInput.find(LicenseIdKey)) {
  943. TempString = Trim(OneInput.substr(LicenseIdKey.length())); // Copy only if not null after trimming.
  944. if (!TempString.empty()) {
  945. LicenseId = TempString;
  946. LicenseIdIsSpecified = true;
  947. } else {
  948. ValidCommand = false;
  949. }
  950. } else if (0 == OneInput.find(AuthenticationKey)) {
  951. TempString = Trim(OneInput.substr(AuthenticationKey.length())); // Copy only if not null after trimming.
  952. if (!TempString.empty()) {
  953. Authentication = TempString;
  954. AuthenticationIsSpecified = true;
  955. } else {
  956. ValidCommand = false;
  957. }
  958. } else {
  959. ValidCommand = false;
  960. }
  961. return ValidCommand;
  962. }
  963. bool
  964. UtilityConfig::CommandLineIsOkay() {
  965. return (AuthenticationIsSpecified == LicenseIdIsSpecified);
  966. }
  967. std::string
  968. UtilityConfig::HelpCommandLine(std::string ExclusiveCommandsHelp) {
  969. std::string Help;
  970. Help = SetupKey + " | ";
  971. Help += RepairKey + " | ";
  972. Help += ExclusiveCommandsHelp + " | ";
  973. Help += LicenseIdKey + "licenseid " + AuthenticationKey + "authentication | ";
  974. Help += StartSnifferKey + " | ";
  975. Help += StopSnifferKey + " ";
  976. Help += "[" + ConfigFileKey + "snf-config-file] ";
  977. Help += "[ " + VerboseKey + " " + ExplainKey + " ]";
  978. return Help;
  979. }
  980. std::string
  981. UtilityConfig::HelpDescription(std::string ExclusiveCommandsHelp) {
  982. std::string Desc;
  983. Desc = "creates and updates the configuration files (snf-config-file and\n";
  984. Desc += "the ignore list file), the rulebase download script (default: getRulebase),\n";
  985. Desc += "and the identity file if they don't exist.\n\n";
  986. Desc += " -setup Perform initial setup/replace missing files\n";
  987. Desc += " -repair Perform initial setup/replace missing files\n";
  988. Desc += ExclusiveCommandsHelp;
  989. Desc += " -id=licenseid Specifies the license ID\n";
  990. Desc += " -auth=authentication Specifies the Authentication\n";
  991. Desc += " -start Start the sniffer\n";
  992. Desc += " -stop Stop the sniffer\n";
  993. Desc += " -v Provide verbose output\n";
  994. Desc += " -explain Provide an explaination of the actions\n";
  995. Desc += " without executing any commands\n";
  996. return Desc;
  997. }
  998. void
  999. UtilityConfig::SetSetupRepair(bool Specified) {
  1000. SetupRepairRequested = Specified;
  1001. }
  1002. bool
  1003. UtilityConfig::SetupRepairSpecified() {
  1004. return SetupRepairRequested;
  1005. }
  1006. bool
  1007. UtilityConfig::UpdateCredentialsSpecified() {
  1008. return ( (LicenseId.length() > 0) && (Authentication.length() > 0) );
  1009. }
  1010. void
  1011. UtilityConfig::SetStartSniffer(bool Specified) {
  1012. StartSnifferRequested = Specified;
  1013. }
  1014. bool
  1015. UtilityConfig::StartSnifferSpecified() {
  1016. return StartSnifferRequested;
  1017. }
  1018. void
  1019. UtilityConfig::SetStopSniffer(bool Specified) {
  1020. StopSnifferRequested = Specified;
  1021. }
  1022. bool
  1023. UtilityConfig::StopSnifferSpecified() {
  1024. return StopSnifferRequested;
  1025. }