You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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