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

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