您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UtilityConfig.cpp 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  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. std::string LogDir = GetLogPath();
  568. if (FileExists(LogDir)) {
  569. SetMode(LogDir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  570. SetOwnerGroup(LogDir);
  571. }
  572. }
  573. void
  574. UtilityConfig::UpdateRulebaseScriptCredentials() {
  575. std::string File = GetRulebaseScriptName();
  576. if (Verbose()) {
  577. cout << "Update authentication and license ID in the rulebase download script file " << File << "--\n";
  578. }
  579. ifstream Input;
  580. Input.open(File.c_str()); // Read the contents.
  581. if (!Input) {
  582. string Temp;
  583. Temp = "Error opening rulebase download script file " + File;
  584. Temp += " for reading: ";
  585. Temp += strerror(errno);
  586. throw std::runtime_error(Temp);
  587. }
  588. string Content;
  589. string Line;
  590. bool FoundLicense = false;
  591. bool FoundAuth = false;
  592. while (getline(Input, Line)) {
  593. if (CheckForString(Line, LicenseSearchString)) { // Check for license line.
  594. if (FoundLicense) { // Second license line found?
  595. string Temp;
  596. Temp = "Rulebase sownload script file " + File;
  597. Temp += " has the wrong format: Found two lines beginning with " + LicenseSearchString;
  598. throw std::runtime_error(Temp);
  599. }
  600. if (Verbose()) {
  601. cout << " Modify line: '" << Line << "'...\n";
  602. }
  603. FoundLicense = true;
  604. Line = LicenseSearchString + LicenseId; // Add license line.
  605. Line += " # Added by SNFSetup";
  606. }
  607. if (CheckForString(Line, AuthSearchString)) { // Check for authentication line.
  608. if (FoundAuth) { // Second authentication line found?
  609. string Temp;
  610. Temp = "Rulebase download script file " + File;
  611. Temp += " has the wrong format: Found two lines beginning with " + AuthSearchString;
  612. throw std::runtime_error(Temp);
  613. }
  614. if (Verbose()) {
  615. cout << " Modify line: '" << Line << "'...\n";
  616. }
  617. FoundAuth = true;
  618. Line = AuthSearchString + Authentication; // Add authentication line.
  619. Line += " # Added by SNFSetup";
  620. }
  621. Content += Line + "\n";
  622. }
  623. if (!FoundLicense || !FoundAuth) {
  624. string Temp;
  625. Temp = "Rulebase download script file " + File;
  626. Temp += " has the wrong format: Missing required line beginning with '" + LicenseSearchString;
  627. Temp += "' or '" + AuthSearchString;
  628. Temp += "'";
  629. throw std::runtime_error(Temp);
  630. }
  631. if (!Input.eof()) { // Should be at end-of-file.
  632. string Temp;
  633. Temp = "Error reading the rulebase download script file " + File;
  634. Temp += ": ";
  635. Temp += strerror(errno);
  636. throw std::runtime_error(Temp);
  637. }
  638. Input.close();
  639. if (Input.bad()) {
  640. string Temp;
  641. Temp = "Error closing the rulebase download script file " + File;
  642. Temp += " after reading: ";
  643. Temp += strerror(errno);
  644. throw std::runtime_error(Temp);
  645. }
  646. if (!Explain()) {
  647. SaveFile.CreateBackupFile(File);
  648. ofstream Output; // Write the updated contents.
  649. Output.open(File.c_str(), ios::trunc);
  650. if (!Output) {
  651. string Temp;
  652. Temp = "Error opening rulebase download script file " + File;
  653. Temp += " for writing: ";
  654. Temp += strerror(errno);
  655. throw std::runtime_error(Temp);
  656. }
  657. Output << Content;
  658. if (!Output) {
  659. string Temp;
  660. Temp = "Error writing the rulebase download script file " + File;
  661. Temp += ": ";
  662. Temp += strerror(errno);
  663. throw std::runtime_error(Temp);
  664. }
  665. Output.close();
  666. if (!Output) {
  667. string Temp;
  668. Temp = "Error closing the rulebase download script file " + File;
  669. Temp += " after writing: ";
  670. Temp += strerror(errno);
  671. throw std::runtime_error(Temp);
  672. }
  673. }
  674. OutputVerboseEnd();
  675. }
  676. void
  677. UtilityConfig::DownloadRulebase() {
  678. if (Verbose()) {
  679. std::cout << "Downloading the rulebase...";
  680. std::cout.flush();
  681. }
  682. std::string Command;
  683. Command = RulebaseDownloadCommand;
  684. std::string::size_type ScriptIndex = Command.find(ScriptNameKey);
  685. if (ScriptIndex != std::string::npos) { // Insert script full path?
  686. Command.replace(ScriptIndex, ScriptNameKey.length(), GetRulebaseScriptName());
  687. }
  688. std::string::size_type SnifferPathIndex = Command.find(SnifferPathKey);
  689. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  690. Command.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  691. }
  692. std::string StatusFile; // Construct download status file name.
  693. StatusFile = RulebaseDownloadStatusFile;
  694. SnifferPathIndex = StatusFile.find(SnifferPathKey);
  695. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  696. StatusFile.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  697. }
  698. if (!Explain()) {
  699. SaveFile.CreateBackupFile(GetRulebaseFileName()); // Save the current rulebase file.
  700. if (0 != remove(StatusFile.c_str())) { // Delete the status file.
  701. if (ENOENT != errno) { // No error if the file doesn't exist.
  702. std::ostringstream Temp;
  703. Temp << "Unable to remove rulebase download status file " << StatusFile
  704. << ": " << strerror(errno);
  705. throw std::runtime_error(Temp.str());
  706. }
  707. }
  708. if (std::system(Command.c_str()) != 0) { // Download the rulebase.
  709. string Temp;
  710. Temp = "Error running the command '" + Command;
  711. Temp += "'.";
  712. throw std::runtime_error(Temp);
  713. }
  714. ifstream Input;
  715. Input.open(StatusFile.c_str()); // Check the status.
  716. if (!Input) {
  717. string Temp;
  718. Temp = "Error opening rulebase download scriptstatus file " + StatusFile;
  719. Temp += ": ";
  720. Temp += strerror(errno);
  721. throw std::runtime_error(Temp);
  722. }
  723. string Line;
  724. string PrevLine;
  725. string Content;
  726. while (getline(Input, Line)) { // Read the last line.
  727. PrevLine = Line;
  728. Content += Line + "\n";
  729. }
  730. if (PrevLine.find(SuccessKey) == std::string::npos) { // Check the status.
  731. string Temp;
  732. Temp = "Error downloading the rulebase. Rulebase download status:\n\n" + Content;
  733. throw std::runtime_error(Temp);
  734. }
  735. }
  736. OutputVerboseEnd();
  737. }
  738. void
  739. UtilityConfig::UpdateIdentityFile() {
  740. std::string File = GetIdentityFileName();
  741. if (Verbose()) {
  742. cout << "Update authentication and license ID in the identity file " << File << "--\n";
  743. }
  744. ifstream Input;
  745. Input.open(File.c_str()); // Read the contents.
  746. if (!Input) {
  747. string Temp;
  748. Temp = "Error opening identity file " + File;
  749. Temp += " for reading: ";
  750. Temp += strerror(errno);
  751. throw std::runtime_error(Temp);
  752. }
  753. ostringstream InputContents;
  754. if (!Input.eof()) { // Copy if there are characters.
  755. // Copying an empty file causes
  756. InputContents << Input.rdbuf(); // failbit to be set.
  757. }
  758. if (InputContents.bad() || InputContents.fail()) {
  759. std::string Temp;
  760. Temp = "Error reading identity file " + File;
  761. throw std::runtime_error(Temp);
  762. }
  763. Input.close();
  764. if (Input.bad()) {
  765. string Temp;
  766. Temp = "Error closing the identity file " + File;
  767. Temp += " after reading: ";
  768. Temp += strerror(errno);
  769. throw std::runtime_error(Temp);
  770. }
  771. string Content = InputContents.str();
  772. try {
  773. ReplaceXmlAttribute(&Content, IdentityElementName, LicenseAttributeName, LicenseId);
  774. ReplaceXmlAttribute(&Content, IdentityElementName, AuthenticationAttributeName, Authentication);
  775. } catch (std::exception &e) {
  776. std::string Temp;
  777. Temp = "Error updating credentials for identity file " + File;
  778. Temp += ": ";
  779. Temp += e.what();
  780. throw std::runtime_error(Temp);
  781. }
  782. if (!Explain()) {
  783. SaveFile.CreateBackupFile(File);
  784. ofstream Output;
  785. Output.open(File.c_str(), ios::trunc);
  786. if (!Output) {
  787. string Temp;
  788. Temp = "Error opening identity file " + File;
  789. Temp += " for writing: ";
  790. Temp += strerror(errno);
  791. throw std::runtime_error(Temp);
  792. }
  793. Output << Content;
  794. if (!Output) {
  795. string Temp;
  796. Temp = "Error writing the identity file " + File;
  797. Temp += ": ";
  798. Temp += strerror(errno);
  799. throw std::runtime_error(Temp);
  800. }
  801. Output.close();
  802. if (!Output) {
  803. string Temp;
  804. Temp = "Error closing the identity file " + File;
  805. Temp += " after writing: ";
  806. Temp += strerror(errno);
  807. throw std::runtime_error(Temp);
  808. }
  809. }
  810. OutputVerboseEnd();
  811. }
  812. #if 0
  813. void
  814. UtilityConfig::UpdateIdentityFileOld() {
  815. std::string File = GetIdentityFileName();
  816. ofstream Output;
  817. if (Verbose()) {
  818. cout << "Create identity file " << File << "...";
  819. }
  820. if (!Explain()) {
  821. SaveFile.CreateBackupFile(File);
  822. Output.open(File.c_str());
  823. if (!Output) {
  824. string Temp;
  825. Temp = "Error opening identity file " + File;
  826. Temp += ": ";
  827. Temp += strerror(errno);
  828. throw std::runtime_error(Temp);
  829. }
  830. Output << "<!-- License file created by SNFIdentity-->\n"
  831. << "<snf>\n"
  832. << " <identity licenseid='" << LicenseId << "' authentication='"
  833. << Authentication << "'/>\n"
  834. << "</snf>\n";
  835. if (!Output) {
  836. string Temp;
  837. Temp = "Error writing identity file " + File;
  838. Temp += ": ";
  839. Temp += strerror(errno);
  840. throw std::runtime_error(Temp);
  841. }
  842. Output.close();
  843. if (!Output) {
  844. string Temp;
  845. Temp = "Error closing identity file " + File;
  846. Temp += ": ";
  847. Temp += strerror(errno);
  848. throw std::runtime_error(Temp);
  849. }
  850. }
  851. OutputVerboseEnd();
  852. SetOwnerGroup(File); // Set the user and group.
  853. SetMode(File, S_IRUSR); // Set to readonly by owner.
  854. }
  855. #endif
  856. void
  857. UtilityConfig::StartSniffer(std::string ScriptAndArgs, std::string ApplicationName) {
  858. if (SnifferIsRunning == GetRunningState(ApplicationName)) {
  859. std::cout << ApplicationName << " is already running.\n";
  860. return;
  861. }
  862. std::string Command;
  863. Command = SnifferStartScriptDir + ScriptAndArgs;
  864. if (Verbose()) {
  865. cout << "Starting Sniffer with the command '" << Command << "'...";
  866. cout.flush();
  867. }
  868. if (!Explain()) {
  869. if (std::system(Command.c_str()) == -1) { // Start the sniffer.
  870. string Temp;
  871. Temp = "Error running the command '" + Command;
  872. Temp += "' to start the Sniffer: ";
  873. Temp += strerror(errno);
  874. throw std::runtime_error(Temp);
  875. }
  876. OutputVerboseEnd();
  877. if (SnifferIsRunning != GetRunningState(ApplicationName)) {
  878. std::string Temp;
  879. Temp = "Unable to start " + ApplicationName;
  880. throw std::runtime_error(Temp);
  881. }
  882. } else {
  883. OutputVerboseEnd();
  884. }
  885. }
  886. void
  887. UtilityConfig::StopSniffer(std::string ScriptAndArgs, std::string ApplicationName) {
  888. if (SnifferIsStopped == GetRunningState(ApplicationName)) {
  889. std::cout << ApplicationName << " was not running.\n";
  890. return;
  891. }
  892. std::string Command;
  893. Command = SnifferStartScriptDir + ScriptAndArgs;
  894. if (Verbose()) {
  895. cout << "Stopping Sniffer with the command '" << Command << "'...";
  896. cout.flush();
  897. }
  898. if (!Explain()) {
  899. if (std::system(Command.c_str()) == -1) { // Start the sniffer.
  900. string Temp;
  901. Temp = "Error running the command '" + Command;
  902. Temp += "' to stop the Sniffer: ";
  903. Temp += strerror(errno);
  904. throw std::runtime_error(Temp);
  905. }
  906. OutputVerboseEnd();
  907. if (SnifferIsStopped != GetRunningState(ApplicationName)) {
  908. std::string Temp;
  909. Temp = "Unable to stop " + ApplicationName;
  910. throw std::runtime_error(Temp);
  911. }
  912. } else {
  913. OutputVerboseEnd();
  914. }
  915. }
  916. bool
  917. UtilityConfig::ProcessCommandLineItem(std::string OneInput) {
  918. bool ValidCommand = true;
  919. std::string TempString;
  920. if (OneInput == VerboseKey) {
  921. SetVerbose(true);
  922. } else if (OneInput == ExplainKey) {
  923. SetExplain(true);
  924. } else if (OneInput == HelpKey) {
  925. SetHelp(true);
  926. } else if (OneInput == SetupKey) {
  927. SetSetupRepair(true);
  928. } else if (OneInput == RepairKey) {
  929. SetSetupRepair(true);
  930. } else if (OneInput == StartSnifferKey) {
  931. SetStartSniffer(true);
  932. } else if (OneInput == StopSnifferKey) {
  933. SetStopSniffer(true);
  934. } else if (0 == OneInput.find(ConfigFileKey)) {
  935. TempString = Trim(OneInput.substr(ConfigFileKey.length())); // Copy only if not null after trimming.
  936. SetConfigFileName(TempString);
  937. } else if (0 == OneInput.find(LicenseIdKey)) {
  938. TempString = Trim(OneInput.substr(LicenseIdKey.length())); // Copy only if not null after trimming.
  939. if (!TempString.empty()) {
  940. LicenseId = TempString;
  941. LicenseIdIsSpecified = true;
  942. } else {
  943. ValidCommand = false;
  944. }
  945. } else if (0 == OneInput.find(AuthenticationKey)) {
  946. TempString = Trim(OneInput.substr(AuthenticationKey.length())); // Copy only if not null after trimming.
  947. if (!TempString.empty()) {
  948. Authentication = TempString;
  949. AuthenticationIsSpecified = true;
  950. } else {
  951. ValidCommand = false;
  952. }
  953. } else {
  954. ValidCommand = false;
  955. }
  956. return ValidCommand;
  957. }
  958. bool
  959. UtilityConfig::CommandLineIsOkay() {
  960. return (AuthenticationIsSpecified == LicenseIdIsSpecified);
  961. }
  962. std::string
  963. UtilityConfig::HelpCommandLine(std::string ExclusiveCommandsHelp) {
  964. std::string Help;
  965. Help = SetupKey + " | ";
  966. Help += RepairKey + " | ";
  967. Help += ExclusiveCommandsHelp + " | ";
  968. Help += LicenseIdKey + "licenseid " + AuthenticationKey + "authentication | ";
  969. Help += StartSnifferKey + " | ";
  970. Help += StopSnifferKey + " ";
  971. Help += "[" + ConfigFileKey + "snf-config-file] ";
  972. Help += "[ " + VerboseKey + " " + ExplainKey + " ]";
  973. return Help;
  974. }
  975. std::string
  976. UtilityConfig::HelpDescription(std::string ExclusiveCommandsHelp) {
  977. std::string Desc;
  978. Desc = "creates and updates the configuration files (snf-config-file and\n";
  979. Desc += "the ignore list file), the rulebase download script (default: getRulebase),\n";
  980. Desc += "and the identity file if they don't exist.\n\n";
  981. Desc += " -setup Perform initial setup/replace missing files\n";
  982. Desc += " -repair Perform initial setup/replace missing files\n";
  983. Desc += ExclusiveCommandsHelp;
  984. Desc += " -id=licenseid Specifies the license ID\n";
  985. Desc += " -auth=authentication Specifies the Authentication\n";
  986. Desc += " -start Start the sniffer\n";
  987. Desc += " -stop Stop the sniffer\n";
  988. Desc += " -v Provide verbose output\n";
  989. Desc += " -explain Provide an explaination of the actions\n";
  990. Desc += " without executing any commands\n";
  991. return Desc;
  992. }
  993. void
  994. UtilityConfig::SetSetupRepair(bool Specified) {
  995. SetupRepairRequested = Specified;
  996. }
  997. bool
  998. UtilityConfig::SetupRepairSpecified() {
  999. return SetupRepairRequested;
  1000. }
  1001. bool
  1002. UtilityConfig::UpdateCredentialsSpecified() {
  1003. return ( (LicenseId.length() > 0) && (Authentication.length() > 0) );
  1004. }
  1005. void
  1006. UtilityConfig::SetStartSniffer(bool Specified) {
  1007. StartSnifferRequested = Specified;
  1008. }
  1009. bool
  1010. UtilityConfig::StartSnifferSpecified() {
  1011. return StartSnifferRequested;
  1012. }
  1013. void
  1014. UtilityConfig::SetStopSniffer(bool Specified) {
  1015. StopSnifferRequested = Specified;
  1016. }
  1017. bool
  1018. UtilityConfig::StopSnifferSpecified() {
  1019. return StopSnifferRequested;
  1020. }