Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

UtilityConfig.cpp 27KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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[], int NumDefaultFiles) {
  118. string ProvisionalConfigFile = ConfigFileName;
  119. if (ProvisionalConfigFile.length() == 0) {
  120. int i;
  121. vector<string> FoundFile;
  122. for (i = 0; i < NumDefaultFiles; i++) {
  123. if (!FileExists(DefaultFile[i])) {
  124. continue; // File doesn't exist.
  125. }
  126. FoundFile.push_back(DefaultFile[i]); // Update list of found files.
  127. ProvisionalConfigFile = DefaultFile[i]; // Found configuration file.
  128. }
  129. if (0 == FoundFile.size()) { // No default file found.
  130. if (NumDefaultFiles > 0) {
  131. ProvisionalConfigFile = DefaultFile[0]; // Use the first default file.
  132. } else { // No default config file was specified.
  133. ostringstream Temp;
  134. Temp << "Internal error: NumDefaultFiles <= 0 at " << __FILE__ << ":" << __LINE__;
  135. throw runtime_error(Temp.str());
  136. }
  137. } else if (FoundFile.size() > 1) { // Multiple default files found.
  138. string Temp;
  139. Temp = "Configuration file was not specified, and more than one default configuration file was found::\n\n";
  140. for (i = 0; i < FoundFile.size(); i++) {
  141. Temp += " ";
  142. Temp += FoundFile[i] + "\n";
  143. }
  144. throw runtime_error(Temp);
  145. }
  146. }
  147. SetConfigFileName(ProvisionalConfigFile);
  148. }
  149. void
  150. UtilityConfig::CreateDefaultConfigFile(std::string SampleConfigFile) {
  151. std::string File = GetConfigFileName();
  152. if (!FileExists(File)) {
  153. if (!Explain()) {
  154. SaveFile.CreateBackupFile(File);
  155. }
  156. // Create the config file.
  157. Copy(SampleConfigFile, File);
  158. }
  159. SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Set permissions.
  160. SetOwnerGroup(File); // Set to sniffer user.
  161. }
  162. void
  163. UtilityConfig::LoadConfig() {
  164. if (Verbose()) {
  165. cout << "Using configuration file " << GetConfigFileName() << ".\n";
  166. }
  167. // Load the data.
  168. try {
  169. CFGData.initializeFromFile(GetConfigFileName().c_str());
  170. } catch(...) {
  171. string Temp;
  172. Temp = "Error reading configuration file " + GetConfigFileName();
  173. Temp += ".";
  174. throw runtime_error(Temp);
  175. }
  176. if ( (CFGData.paths_workspace_path.length() == 0) ||
  177. (CFGData.paths_rulebase_path.length() == 0) ||
  178. (CFGData.paths_log_path.length() == 0) ||
  179. (CFGData.update_script_call.length() == 0) ||
  180. (CFGData.node_identity.length() == 0) ) {
  181. string Temp;
  182. Temp = "The configuration file " + GetConfigFileName();
  183. Temp += " did not have the necessary specification of one or more paths:\n";
  184. Temp += "\n Workspace path: " + CFGData.paths_workspace_path;
  185. Temp += "\n Rulebase path: " + CFGData.paths_rulebase_path;
  186. Temp += "\n Log path: " + CFGData.paths_log_path;
  187. Temp += "\n Update script: " + CFGData.update_script_call;
  188. Temp += "\n Identity file: " + CFGData.node_identity;
  189. throw runtime_error(Temp);
  190. }
  191. }
  192. string
  193. UtilityConfig::GetPlatformContents(void) {
  194. return CFGData.PlatformElementContents;
  195. }
  196. string
  197. UtilityConfig::GetConfigFileName(void) {
  198. return ConfigFileName;
  199. }
  200. void
  201. UtilityConfig::SetConfigFileName(string Name) {
  202. ConfigFileName = Name;
  203. }
  204. string
  205. UtilityConfig::GetWorkspacePath(void) {
  206. return CFGData.paths_workspace_path;
  207. }
  208. string
  209. UtilityConfig::GetRulebasePath(void) {
  210. return CFGData.paths_rulebase_path;
  211. }
  212. string
  213. UtilityConfig::GetLogPath(void) {
  214. return CFGData.paths_log_path;
  215. }
  216. string
  217. UtilityConfig::GetIdentityFileName(void) {
  218. return CFGData.node_identity;
  219. }
  220. string
  221. UtilityConfig::GetRulebaseScriptName(void) {
  222. return CFGData.update_script_call;
  223. }
  224. string
  225. UtilityConfig::GetIgnoreListFileName(void) {
  226. return GetWorkspacePath() + "GBUdbIgnoreList.txt";
  227. }
  228. string
  229. UtilityConfig::GetRulebaseFileName(void) {
  230. std::string Name;
  231. Name = GetRulebasePath();
  232. Name += LicenseId + ".snf";
  233. return Name;
  234. }
  235. string
  236. UtilityConfig::GetOperatingSystemType(void) {
  237. return OperatingSystemType;
  238. }
  239. void
  240. UtilityConfig::LoadInfo(){
  241. if ("OpenBSD" == OperatingSystemType) {
  242. PostfixMainCfPath = "/usr/local/etc/postfix/main.cf";
  243. PostfixMasterCfPath = "/usr/local/etc/postfix/master.cf";
  244. SnifferStartScriptDir = "/usr/local/sbin/";
  245. } else if ("FreeBSD" == OperatingSystemType) {
  246. PostfixMainCfPath = "/etc/postfix/main.cf";
  247. PostfixMasterCfPath = "/etc/postfix/master.cf";
  248. SnifferStartScriptDir = "/usr/local/etc/rc.d/";
  249. } else if ("Ubuntu" == OperatingSystemType) {
  250. PostfixMainCfPath = "/etc/postfix/main.cf";
  251. PostfixMasterCfPath = "/etc/postfix/master.cf";
  252. SnifferStartScriptDir = "/etc/init.d/";
  253. } else if ("RedHat" == OperatingSystemType) {
  254. PostfixMainCfPath = "/etc/postfix/main.cf";
  255. PostfixMasterCfPath = "/etc/postfix/master.cf";
  256. SnifferStartScriptDir = "/etc/init.d/";
  257. } else if ("Suse" == OperatingSystemType) {
  258. PostfixMainCfPath = "/etc/postfix/main.cf";
  259. PostfixMasterCfPath = "/etc/postfix/master.cf";
  260. SnifferStartScriptDir = "/etc/init.d/";
  261. } else {
  262. ostringstream Temp;
  263. Temp << "Internal error in UtilityConfig::LoadInfo: Invalid value of OperatingSystemType: "
  264. << OperatingSystemType;
  265. throw runtime_error(Temp.str());
  266. }
  267. }
  268. void
  269. UtilityConfig::SetupRepairIdentityFile(std::string SampleIdentityFile) {
  270. std::string File = GetIdentityFileName();
  271. if (!FileExists(File)) {
  272. if (!Explain()) {
  273. SaveFile.CreateBackupFile(File);
  274. }
  275. // Create the config file.
  276. Copy(SampleIdentityFile, File);
  277. }
  278. }
  279. void
  280. UtilityConfig::SetupRepairRulebaseScript() {
  281. std::string File = GetRulebaseScriptName();
  282. if (!FileExists(File)) {
  283. if (!Explain()) {
  284. SaveFile.CreateBackupFile(File);
  285. }
  286. Copy(SampleRulebaseScriptFile, File); // Copy if !Explain().
  287. }
  288. SetMode(File, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // Set permissions.
  289. }
  290. void
  291. UtilityConfig::SetupRepairIgnoreListFile() {
  292. string File = GetIgnoreListFileName();
  293. if (!FileExists(File)) {
  294. if (!Explain()) {
  295. SaveFile.CreateBackupFile(File);
  296. }
  297. Copy(SampleIgnoreListFile, File);
  298. }
  299. SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Set permissions.
  300. SetOwnerGroup(File); // Set to sniffer user.
  301. }
  302. void
  303. UtilityConfig::SetupRepairLogDir() {
  304. string LogDir = GetLogPath();
  305. if (!FileExists(LogDir)) {
  306. MkDir(LogDir);
  307. }
  308. SetMode(LogDir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  309. SetOwnerGroup(LogDir);
  310. }
  311. void
  312. UtilityConfig::SetupRepair(const std::string SampleIdentityFile) {
  313. SetupRepairIdentityFile(SampleIdentityFile);
  314. SetupRepairRulebaseScript();
  315. SetupRepairIgnoreListFile();
  316. SetupRepairLogDir();
  317. }
  318. void
  319. UtilityConfig::UpdateRulebaseScriptCredentials() {
  320. std::string File = GetRulebaseScriptName();
  321. if (Verbose()) {
  322. cout << "Update authentication and license ID in the rulebase download script file " << File << "--\n";
  323. }
  324. ifstream Input;
  325. Input.open(File.c_str()); // Read the contents.
  326. if (!Input) {
  327. string Temp;
  328. Temp = "Error opening rulebase download script file " + File;
  329. Temp += " for reading: ";
  330. Temp += strerror(errno);
  331. throw runtime_error(Temp);
  332. }
  333. string Content;
  334. string Line;
  335. bool FoundLicense = false;
  336. bool FoundAuth = false;
  337. while (getline(Input, Line)) {
  338. if (CheckForString(Line, LicenseSearchString)) { // Check for license line.
  339. if (FoundLicense) { // Second license line found?
  340. string Temp;
  341. Temp = "Rulebase sownload script file " + File;
  342. Temp += " has the wrong format: Found two lines beginning with " + LicenseSearchString;
  343. throw runtime_error(Temp);
  344. }
  345. if (Verbose()) {
  346. cout << " Modify line: '" << Line << "'...\n";
  347. }
  348. FoundLicense = true;
  349. Line = LicenseSearchString + LicenseId; // Add license line.
  350. Line += " # Added by SNFSetup";
  351. }
  352. if (CheckForString(Line, AuthSearchString)) { // Check for authentication line.
  353. if (FoundAuth) { // Second authentication line found?
  354. string Temp;
  355. Temp = "Rulebase download script file " + File;
  356. Temp += " has the wrong format: Found two lines beginning with " + AuthSearchString;
  357. throw runtime_error(Temp);
  358. }
  359. if (Verbose()) {
  360. cout << " Modify line: '" << Line << "'...\n";
  361. }
  362. FoundAuth = true;
  363. Line = AuthSearchString + Authentication; // Add authentication line.
  364. Line += " # Added by SNFSetup";
  365. }
  366. Content += Line + "\n";
  367. }
  368. if (!FoundLicense || !FoundAuth) {
  369. string Temp;
  370. Temp = "Rulebase download script file " + File;
  371. Temp += " has the wrong format: Missing required line beginning with '" + LicenseSearchString;
  372. Temp += "' or '" + AuthSearchString;
  373. Temp += "'";
  374. throw runtime_error(Temp);
  375. }
  376. if (!Input.eof()) { // Should be at end-of-file.
  377. string Temp;
  378. Temp = "Error reading the rulebase download script file " + File;
  379. Temp += ": ";
  380. Temp += strerror(errno);
  381. throw runtime_error(Temp);
  382. }
  383. Input.close();
  384. if (Input.bad()) {
  385. string Temp;
  386. Temp = "Error closing the rulebase download script file " + File;
  387. Temp += " after reading: ";
  388. Temp += strerror(errno);
  389. throw runtime_error(Temp);
  390. }
  391. if (!Explain()) {
  392. SaveFile.CreateBackupFile(File);
  393. ofstream Output; // Write the updated contents.
  394. Output.open(File.c_str(), ios::trunc);
  395. if (!Output) {
  396. string Temp;
  397. Temp = "Error opening rulebase download script file " + File;
  398. Temp += " for writing: ";
  399. Temp += strerror(errno);
  400. throw runtime_error(Temp);
  401. }
  402. Output << Content;
  403. if (!Output) {
  404. string Temp;
  405. Temp = "Error writing the rulebase download script file " + File;
  406. Temp += ": ";
  407. Temp += strerror(errno);
  408. throw runtime_error(Temp);
  409. }
  410. Output.close();
  411. if (!Output) {
  412. string Temp;
  413. Temp = "Error closing the rulebase download script file " + File;
  414. Temp += " after writing: ";
  415. Temp += strerror(errno);
  416. throw runtime_error(Temp);
  417. }
  418. }
  419. OutputVerboseEnd();
  420. }
  421. void
  422. UtilityConfig::DownloadRulebase() {
  423. if (Verbose()) {
  424. std::cout << "Downloading the rulebase...";
  425. std::cout.flush();
  426. }
  427. std::string Command;
  428. Command = RulebaseDownloadCommand;
  429. std::string::size_type ScriptIndex = Command.find(ScriptNameKey);
  430. if (ScriptIndex != std::string::npos) { // Insert script full path?
  431. Command.replace(ScriptIndex, ScriptNameKey.length(), GetRulebaseScriptName());
  432. }
  433. std::string::size_type SnifferPathIndex = Command.find(SnifferPathKey);
  434. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  435. Command.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  436. }
  437. std::string StatusFile; // Construct download status file name.
  438. StatusFile = RulebaseDownloadStatusFile;
  439. SnifferPathIndex = StatusFile.find(SnifferPathKey);
  440. if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
  441. StatusFile.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
  442. }
  443. if (!Explain()) {
  444. SaveFile.CreateBackupFile(GetRulebaseFileName()); // Save the current rulebase file.
  445. if (0 != remove(StatusFile.c_str())) { // Delete the status file.
  446. if (ENOENT != errno) { // No error if the file doesn't exist.
  447. std::ostringstream Temp;
  448. Temp << "Unable to remove rulebase download status file " << StatusFile
  449. << ": " << strerror(errno) << "\n";
  450. throw runtime_error(Temp.str());
  451. }
  452. }
  453. if (std::system(Command.c_str()) != 0) { // Download the rulebase.
  454. string Temp;
  455. Temp = "Error running the command '" + Command;
  456. Temp += "'.";
  457. throw runtime_error(Temp);
  458. }
  459. ifstream Input;
  460. Input.open(StatusFile.c_str()); // Check the status.
  461. if (!Input) {
  462. string Temp;
  463. Temp = "Error opening rulebase download scriptstatus file " + StatusFile;
  464. Temp += ": ";
  465. Temp += strerror(errno);
  466. throw runtime_error(Temp);
  467. }
  468. string Line;
  469. string PrevLine;
  470. string Content;
  471. while (getline(Input, Line)) { // Read the last line.
  472. PrevLine = Line;
  473. Content += Line + "\n";
  474. }
  475. if (PrevLine.find(SuccessKey) == std::string::npos) { // Check the status.
  476. string Temp;
  477. Temp = "Error downloading the rulebase. Rulebase download status:\n\n" + Content;
  478. throw runtime_error(Temp);
  479. }
  480. }
  481. OutputVerboseEnd();
  482. }
  483. void
  484. UtilityConfig::UpdateIdentityFile() {
  485. std::string File = GetIdentityFileName();
  486. if (Verbose()) {
  487. cout << "Update authentication and license ID in the identity file " << File << "--\n";
  488. }
  489. ifstream Input;
  490. Input.open(File.c_str()); // Read the contents.
  491. if (!Input) {
  492. string Temp;
  493. Temp = "Error opening identity file " + File;
  494. Temp += " for reading: ";
  495. Temp += strerror(errno);
  496. throw runtime_error(Temp);
  497. }
  498. ostringstream InputContents;
  499. if (!Input.eof()) { // Copy if there are characters.
  500. // Copying an empty file causes
  501. InputContents << Input.rdbuf(); // failbit to be set.
  502. }
  503. if (InputContents.bad() || InputContents.fail()) {
  504. std::string Temp;
  505. Temp = "Error reading identity file " + File;
  506. throw std::runtime_error(Temp);
  507. }
  508. Input.close();
  509. if (Input.bad()) {
  510. string Temp;
  511. Temp = "Error closing the identity file " + File;
  512. Temp += " after reading: ";
  513. Temp += strerror(errno);
  514. throw runtime_error(Temp);
  515. }
  516. string Content = InputContents.str();
  517. try {
  518. ReplaceXmlAttribute(&Content, IdentityElementName, LicenseAttributeName, LicenseId);
  519. ReplaceXmlAttribute(&Content, IdentityElementName, AuthenticationAttributeName, Authentication);
  520. } catch (std::exception &e) {
  521. std::string Temp;
  522. Temp = "Error updating credentials for identity file " + File;
  523. Temp += ": ";
  524. Temp += e.what();
  525. throw runtime_error(Temp);
  526. }
  527. if (!Explain()) {
  528. SaveFile.CreateBackupFile(File);
  529. ofstream Output;
  530. Output.open(File.c_str(), ios::trunc);
  531. if (!Output) {
  532. string Temp;
  533. Temp = "Error opening identity file " + File;
  534. Temp += " for writing: ";
  535. Temp += strerror(errno);
  536. throw runtime_error(Temp);
  537. }
  538. Output << Content;
  539. if (!Output) {
  540. string Temp;
  541. Temp = "Error writing the identity file " + File;
  542. Temp += ": ";
  543. Temp += strerror(errno);
  544. throw runtime_error(Temp);
  545. }
  546. Output.close();
  547. if (!Output) {
  548. string Temp;
  549. Temp = "Error closing the identity file " + File;
  550. Temp += " after writing: ";
  551. Temp += strerror(errno);
  552. throw runtime_error(Temp);
  553. }
  554. }
  555. OutputVerboseEnd();
  556. }
  557. #if 0
  558. void
  559. UtilityConfig::UpdateIdentityFileOld() {
  560. std::string File = GetIdentityFileName();
  561. ofstream Output;
  562. if (Verbose()) {
  563. cout << "Create identity file " << File << "...";
  564. }
  565. if (!Explain()) {
  566. SaveFile.CreateBackupFile(File);
  567. Output.open(File.c_str());
  568. if (!Output) {
  569. string Temp;
  570. Temp = "Error opening identity file " + File;
  571. Temp += ": ";
  572. Temp += strerror(errno);
  573. throw runtime_error(Temp);
  574. }
  575. Output << "<!-- License file created by SNFIdentity-->\n"
  576. << "<snf>\n"
  577. << " <identity licenseid='" << LicenseId << "' authentication='"
  578. << Authentication << "'/>\n"
  579. << "</snf>\n";
  580. if (!Output) {
  581. string Temp;
  582. Temp = "Error writing identity file " + File;
  583. Temp += ": ";
  584. Temp += strerror(errno);
  585. throw runtime_error(Temp);
  586. }
  587. Output.close();
  588. if (!Output) {
  589. string Temp;
  590. Temp = "Error closing identity file " + File;
  591. Temp += ": ";
  592. Temp += strerror(errno);
  593. throw runtime_error(Temp);
  594. }
  595. }
  596. OutputVerboseEnd();
  597. SetOwnerGroup(File); // Set the user and group.
  598. SetMode(File, S_IRUSR); // Set to readonly by owner.
  599. }
  600. #endif
  601. void
  602. UtilityConfig::StartSniffer(std::string Script) {
  603. std::string Command;
  604. Command = SnifferStartScriptDir + Script;
  605. Command += " start";
  606. if (Verbose()) {
  607. cout << "Starting Sniffer with the command '" << Command << "'...";
  608. }
  609. if (!Explain()) {
  610. if (std::system(Command.c_str()) == -1) { // Start the sniffer.
  611. string Temp;
  612. Temp = "Error running the command '" + Command;
  613. Temp += "' to start the Sniffer: ";
  614. Temp += strerror(errno);
  615. throw runtime_error(Temp);
  616. }
  617. }
  618. OutputVerboseEnd();
  619. }
  620. bool
  621. UtilityConfig::ProcessCommandLineItem(std::string OneInput) {
  622. bool ValidCommand = true;
  623. std::string TempString;
  624. if (OneInput == VerboseKey) {
  625. SetVerbose(true);
  626. } else if (OneInput == ExplainKey) {
  627. SetExplain(true);
  628. } else if (OneInput == HelpKey) {
  629. SetHelp(true);
  630. } else if (OneInput == SetupKey) {
  631. SetSetupRepair(true);
  632. } else if (OneInput == RepairKey) {
  633. SetSetupRepair(true);
  634. } else if (OneInput == StartSnifferKey) {
  635. SetStartSniffer(true);
  636. } else if (OneInput == StopSnifferKey) {
  637. SetStopSniffer(true);
  638. } else if (OneInput == ConfigFileKey) {
  639. SetConfigFileName(OneInput.substr(ConfigFileKey.length()));
  640. } else if (0 == OneInput.find(LicenseIdKey)) {
  641. TempString = Trim(OneInput.substr(LicenseIdKey.length())); // Copy only if not null after trimming.
  642. if (!TempString.empty()) {
  643. LicenseId = TempString;
  644. LicenseIdIsSpecified = true;
  645. } else {
  646. ValidCommand = false;
  647. }
  648. } else if (0 == OneInput.find(AuthenticationKey)) {
  649. Authentication = Trim(OneInput.substr(AuthenticationKey.length()));
  650. AuthenticationIsSpecified = true;
  651. } else {
  652. ValidCommand = false;
  653. }
  654. return ValidCommand;
  655. }
  656. bool
  657. UtilityConfig::CommandLineIsOkay() {
  658. return (AuthenticationIsSpecified == LicenseIdIsSpecified);
  659. }
  660. std::string
  661. UtilityConfig::HelpCommandLine(std::string ExclusiveCommandsHelp) {
  662. std::string Help;
  663. Help = SetupKey + " | ";
  664. Help += RepairKey + " | ";
  665. Help += ExclusiveCommandsHelp + " | ";
  666. Help += LicenseIdKey + "licenseid " + AuthenticationKey + "authentication | ";
  667. Help += StartSnifferKey + " | ";
  668. Help += StopSnifferKey + " ";
  669. Help += "[" + ConfigFileKey + "snf-config-file] ";
  670. Help += "[ " + VerboseKey + " " + ExplainKey + " ]";
  671. return Help;
  672. }
  673. std::string
  674. UtilityConfig::HelpDescription(std::string ExclusiveCommandsHelp) {
  675. std::string Desc;
  676. Desc = "creates and updates the configuration files (snf-config-file and\n";
  677. Desc += "the ignore list file), the rulebase download script (default: getRulebase),\n";
  678. Desc += "and the identity file if they don't exist.\n\n";
  679. Desc += " -setup Perform initial setup/replace missing files\n";
  680. Desc += " -repair Perform initial setup/replace missing files\n";
  681. Desc += ExclusiveCommandsHelp;
  682. Desc += " -id=licenseid Specifies the license ID\n";
  683. Desc += " -auth=authentication Specifies the Authentication\n";
  684. Desc += " -start Start the sniffer\n";
  685. Desc += " -stop Stop the sniffer\n";
  686. Desc += " -config=snf-config-file Specifies the configuration file\n";
  687. Desc += " -v Provide verbose output\n";
  688. Desc += " -explain Provide an explaination of the actions\n";
  689. Desc += " without executing any commands\n";
  690. return Desc;
  691. }
  692. void
  693. UtilityConfig::SetSetupRepair(bool Specified) {
  694. SetupRepairRequested = Specified;
  695. }
  696. bool
  697. UtilityConfig::SetupRepairSpecified() {
  698. return SetupRepairRequested;
  699. }
  700. bool
  701. UtilityConfig::UpdateCredentialsSpecified() {
  702. return ( (LicenseId.length() > 0) && (Authentication.length() > 0) );
  703. }
  704. void
  705. UtilityConfig::SetStartSniffer(bool Specified) {
  706. StartSnifferRequested = Specified;
  707. }
  708. bool
  709. UtilityConfig::StartSnifferSpecified() {
  710. return StartSnifferRequested;
  711. }
  712. void
  713. UtilityConfig::SetStopSniffer(bool Specified) {
  714. StopSnifferRequested = Specified;
  715. }
  716. bool
  717. UtilityConfig::StopSnifferSpecified() {
  718. return StopSnifferRequested;
  719. }