|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502 |
- // UtilityConfig.cpp
- //
- // Copyright (C) 2011, ARM Research Labs, LLC.
- // See www.armresearch.com for the copyright terms.
- //
- // This file implements the common functionality for the configuration
- // utilities.
-
- #include <cerrno>
- #include <cstring>
- #include <unistd.h>
- #include <pwd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
-
- #include <stdexcept>
- #include <sstream>
- #include <iostream>
- #include <fstream>
- #include <vector>
-
- #include "UtilityConfig.hpp"
-
- using namespace std;
-
- //////////////////////////////////////////////////////////////////////////////////////////////////////////
- // Configuration. ////////////////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- // Initialize OS-dependent constants.
- #ifdef WIN
-
- // Windows OS.
- const std::string UtilityConfig::SampleIgnoreListFile("C:\\SNF\\GBUdbIgnoreList.txt.sample");
-
- const std::string UtilityConfig::RulebaseDownloadCommand("FIX THIS");
-
- const std::string UtilityConfig::RulebaseDownloadStatusFile("FIX THIS");
-
- const std::string ScriptNameKey("FIX THIS"); ///< Text to replace with script name.
- const std::string SnifferPathKey("FIX THIS"); ///< Text to replace with directory of the rulebase.
-
- const std::string UtilityConfig::SampleRulebaseScriptFile("C:\\SNF\\getRulebase.sample");
-
- const std::string UtilityConfig::OperatingSystemType("Windows");
-
- #else
-
- // *nix OS.
-
- // SCRIPT is replaced with the full path of the script run,
- // SNIFFER_PATH is replaced with the path of the rulebase.
- const std::string UtilityConfig::RulebaseDownloadCommand
- ("(cd SNIFFER_PATH; touch UpdateReady.txt; chown snfuser UpdateReady.txt; su -m snfuser -c SCRIPT)");
-
- const std::string ScriptNameKey("SCRIPT"); ///< Text to replace with script name.
- const std::string SnifferPathKey("SNIFFER_PATH"); ///< Text to replace with directory of the rulebase.
-
- // SNIFFER_PATH is replaced with the path of the rulebase.
- const std::string UtilityConfig::RulebaseDownloadStatusFile("SNIFFER_PATH/getRulebase.status");
-
- #ifdef DEFAULT_DATA_DIR
- // *nix, DEFAULT_DATA_DIR is specified on the compile command line.
- const std::string UtilityConfig::SampleIgnoreListFile(DEFAULT_DATA_DIR "/GBUdbIgnoreList.txt.sample");
- #else
- // Not Windows, and DEFAULT_DATA_DIR is not specified on the compile
- // command line. In this case, we don't know the path for the sample
- // ignore list file.
- #error DEFAULT_DATA_DIR must be defined by -DDEFAULT_DATA_DIR="..." when compiling.
- #endif
-
- #ifdef SBIN_DIR
- // *nix, SBIN_DIR is specified on the compile command line.
- const std::string UtilityConfig::SampleRulebaseScriptFile(SBIN_DIR "/getRulebase.sample");
- #else
- // Not Windows, and SBIN_DIR is not specified on the compile
- // command line. In this case, we don't know the path for the sample
- // ignore list file.
- #error SBIN_DIR must be defined by -DSBIN_DIR="..." when compiling.
- #endif
-
- #ifdef SNF_OSTYPE
- // *nix, SNF_OSTYPE is specified on the compile command line.
- const std::string UtilityConfig::OperatingSystemType(SNF_OSTYPE);
- #else
- // Not Windows, and SNF_OSTYPE is not specified on the compile command
- // line. In this case, we don't know the operating system.
- #error SNF_OSTYPE must be defined by -DSNF_OSTYPE="..." when compiling.
- #endif
-
- #endif
-
- /// Verbose command-line input.
- const string VerboseKey("-v");
-
- /// Explain command-line input.
- const string ExplainKey("-explain");
-
- /// Help command-line input.
- const string HelpKey("-h");
-
- /// Setup command-line input.
- const string SetupKey("-setup");
-
- /// Repair command-line input.
- const string RepairKey("-repair");
-
- /// Start sniffer command-line input.
- const string StartSnifferKey("-start");
-
- /// Stop sniffer command-line input.
- const string StopSnifferKey("-stop");
-
- /// Configuration file command-line input.
- const string ConfigFileKey("-config=");
-
- /// License ID command-line input.
- const string LicenseIdKey("-id=");
-
- /// Authentication command-line input.
- const string AuthenticationKey("-auth=");
-
- /// String that indicates a successful rulebase download.
- //
- // This string must be in the last line of the getRulebase status
- // file. Note: The getRulebase status file is created by the
- // getRulebase script, has the name getRulebase.status, and is in the
- // same directory as the rulebase files.
- const string SuccessKey("Success");
-
- const string LicenseSearchString = "LICENSE_ID=";
- const string AuthSearchString = "AUTHENTICATION=";
-
- const string IdentityElementName = "identity";
- const string LicenseAttributeName = "licenseid";
- const string AuthenticationAttributeName = "authentication";
-
- //////////////////////////////////////////////////////////////////////////////////////////////////////////
- // End of configuration. /////////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- UtilityConfig::UtilityConfig() :
- LicenseIdIsSpecified(false), AuthenticationIsSpecified(false)
- {
-
- SetExplain(false);
- SetVerbose(false);
- SetHelp(false);
- SetSetupRepair(false);
- SetStartSniffer(false);
- SetStopSniffer(false);
-
- }
-
- void
- UtilityConfig::CheckAndSetConfigFileName(const std::string DefaultFile[], int NumDefaultFiles) {
-
- string ProvisionalConfigFile = ConfigFileName;
-
- if (ProvisionalConfigFile.length() == 0) {
-
- int i;
- vector<string> FoundFile;
-
- for (i = 0; i < NumDefaultFiles; i++) {
-
- if (!FileExists(DefaultFile[i])) {
-
- continue; // File doesn't exist.
-
- }
-
- FoundFile.push_back(DefaultFile[i]); // Update list of found files.
- ProvisionalConfigFile = DefaultFile[i]; // Found configuration file.
-
- }
-
- if (0 == FoundFile.size()) { // No default file found.
-
- if (NumDefaultFiles > 0) {
-
- ProvisionalConfigFile = DefaultFile[0]; // Use the first default file.
-
- } else { // No default config file was specified.
-
- ostringstream Temp;
-
- Temp << "Internal error: NumDefaultFiles <= 0 at " << __FILE__ << ":" << __LINE__;
-
- throw std::runtime_error(Temp.str());
-
- }
-
- } else if (FoundFile.size() > 1) { // Multiple default files found.
-
- string Temp;
-
- Temp = "Configuration file was not specified, and more than one default configuration file was found::\n\n";
-
- for (i = 0; i < FoundFile.size(); i++) {
-
- Temp += " ";
- Temp += FoundFile[i] + "\n";
-
- }
-
- throw std::runtime_error(Temp);
-
- }
-
- }
-
- SetConfigFileName(ProvisionalConfigFile);
-
- }
-
- void
- UtilityConfig::CreateDefaultConfigFile(std::string SampleConfigFile) {
-
- std::string File = GetConfigFileName();
-
- if (!FileExists(File)) {
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- }
-
- // Create the config file.
- Copy(SampleConfigFile, File);
-
- }
-
- SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Set permissions.
- SetOwnerGroup(File); // Set to sniffer user.
-
- }
-
- void
- UtilityConfig::LoadConfig() {
-
- if (Verbose()) {
-
- cout << "Using configuration file " << GetConfigFileName() << ".\n";
-
- }
-
- // Load the data.
- try {
-
- CFGData.initializeFromFile(GetConfigFileName().c_str());
-
- } catch(...) {
-
- string Temp;
-
- Temp = "Error reading configuration file " + GetConfigFileName();
- Temp += ".";
- throw std::runtime_error(Temp);
-
- }
-
- if ( (CFGData.paths_workspace_path.length() == 0) ||
- (CFGData.paths_rulebase_path.length() == 0) ||
- (CFGData.paths_log_path.length() == 0) ||
- (CFGData.update_script_call.length() == 0) ||
- (CFGData.node_identity.length() == 0) ) {
-
- string Temp;
-
- Temp = "The configuration file " + GetConfigFileName();
- Temp += " did not have the necessary specification of one or more paths:\n";
- Temp += "\n Workspace path: " + CFGData.paths_workspace_path;
- Temp += "\n Rulebase path: " + CFGData.paths_rulebase_path;
- Temp += "\n Log path: " + CFGData.paths_log_path;
- Temp += "\n Update script: " + CFGData.update_script_call;
- Temp += "\n Identity file: " + CFGData.node_identity;
- throw std::runtime_error(Temp);
-
- }
-
- }
-
- string
- UtilityConfig::GetPlatformContents(void) {
-
- return CFGData.PlatformElementContents;
-
- }
-
- string
- UtilityConfig::GetConfigFileName(void) {
-
- return ConfigFileName;
-
- }
-
- void
- UtilityConfig::SetConfigFileName(string Name) {
-
- ConfigFileName = Name;
-
- }
-
- string
- UtilityConfig::GetWorkspacePath(void) {
-
- return CFGData.paths_workspace_path;
-
- }
-
- string
- UtilityConfig::GetRulebasePath(void) {
-
- return CFGData.paths_rulebase_path;
-
- }
-
- string
- UtilityConfig::GetLogPath(void) {
-
- return CFGData.paths_log_path;
-
- }
-
- std::string
- UtilityConfig::GetStatusSecondLogFileName(void) {
-
- std::string FileName = CFGData.paths_log_path + CFGData.node_licenseid + ".status.second.log";
-
- if (CFGData.Scan_XML_Mode) {
-
- FileName += ".xml";
-
- }
-
- return FileName;
-
- }
-
- std::string
- UtilityConfig::GetStatusMinuteLogFileName(void) {
-
- std::string FileName = CFGData.paths_log_path + CFGData.node_licenseid + ".status.minute.log";
-
- if (CFGData.Scan_XML_Mode) {
-
- FileName += ".xml";
-
- }
-
- return FileName;
-
- }
-
- string
- UtilityConfig::GetIdentityFileName(void) {
-
- return CFGData.node_identity;
-
- }
-
- string
- UtilityConfig::GetRulebaseScriptName(void) {
-
- return CFGData.update_script_call;
-
- }
-
- string
- UtilityConfig::GetIgnoreListFileName(void) {
-
- return GetWorkspacePath() + "GBUdbIgnoreList.txt";
-
- }
-
- string
- UtilityConfig::GetRulebaseFileName(void) {
-
- std::string Name;
-
- Name = GetRulebasePath();
- Name += LicenseId + ".snf";
-
- return Name;
-
- }
-
- string
- UtilityConfig::GetOperatingSystemType(void) {
-
- return OperatingSystemType;
-
- }
-
- void
- UtilityConfig::LoadInfo(){
-
- if ("OpenBSD" == OperatingSystemType) {
-
- PostfixMainCfPath = "/usr/local/etc/postfix/main.cf";
- PostfixMasterCfPath = "/usr/local/etc/postfix/master.cf";
- SnifferStartScriptDir = "/usr/local/sbin/";
-
- } else if ("FreeBSD" == OperatingSystemType) {
-
- PostfixMainCfPath = "/etc/postfix/main.cf";
- PostfixMasterCfPath = "/etc/postfix/master.cf";
- SnifferStartScriptDir = "/usr/local/etc/rc.d/";
-
- } else if ("Ubuntu" == OperatingSystemType) {
-
- PostfixMainCfPath = "/etc/postfix/main.cf";
- PostfixMasterCfPath = "/etc/postfix/master.cf";
- SnifferStartScriptDir = "/etc/init.d/";
-
- } else if ("RedHat" == OperatingSystemType) {
-
- PostfixMainCfPath = "/etc/postfix/main.cf";
- PostfixMasterCfPath = "/etc/postfix/master.cf";
- SnifferStartScriptDir = "/etc/init.d/";
-
- } else if ("Suse" == OperatingSystemType) {
-
- PostfixMainCfPath = "/etc/postfix/main.cf";
- PostfixMasterCfPath = "/etc/postfix/master.cf";
- SnifferStartScriptDir = "/etc/init.d/";
-
- } else {
-
- ostringstream Temp;
-
- Temp << "Internal error in UtilityConfig::LoadInfo: Invalid value of OperatingSystemType: "
- << OperatingSystemType;
-
- throw std::runtime_error(Temp.str());
-
- }
-
- }
-
- void
- UtilityConfig::SetupRepairIdentityFile(std::string SampleIdentityFile) {
-
- std::string File = GetIdentityFileName();
-
- if (!FileExists(File)) {
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- }
-
- // Create the config file.
- Copy(SampleIdentityFile, File);
-
- }
-
- }
-
- void
- UtilityConfig::SetupRepairRulebaseScript() {
-
- std::string File = GetRulebaseScriptName();
-
- if (!FileExists(File)) {
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- }
-
- Copy(SampleRulebaseScriptFile, File); // Copy if !Explain().
-
- }
-
- SetMode(File, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // Set permissions.
-
- }
-
- void
- UtilityConfig::SetupRepairIgnoreListFile() {
-
- string File = GetIgnoreListFileName();
-
- if (!FileExists(File)) {
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- }
-
- Copy(SampleIgnoreListFile, File);
-
- }
-
- SetMode(File, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // Set permissions.
- SetOwnerGroup(File); // Set to sniffer user.
-
- }
-
- void
- UtilityConfig::SetupRepairLogDir() {
-
- string LogDir = GetLogPath();
-
- if (!FileExists(LogDir)) {
-
- MkDir(LogDir);
-
- }
-
- SetMode(LogDir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
- SetOwnerGroup(LogDir);
-
- }
-
- UtilityConfig::StatusCheckMethod
- UtilityConfig::GetPreferredStatusCheckMethod(void) {
-
- if (CFGData.XCI_OnOff) {
-
- return StatusCheckXci;
-
- }
-
- if (CFGData.Status_SecondReport_Log_OnOff) {
-
- return StatusCheckSecond;
-
- }
-
- if (CFGData.Status_MinuteReport_Log_OnOff) {
-
- return StatusCheckMinute;
-
- }
-
- return StatusCheckNotAvailable;
-
- }
-
- std::string
- UtilityConfig::GetSnifferStatusReport() {
-
- std::string StatusReport;
-
- switch (GetPreferredStatusCheckMethod()) {
-
- case StatusCheckXci:
-
- StatusReport = GetReportViaXci();
- break;
-
- case StatusCheckSecond:
-
- StatusReport = GetReportViaLogFile(GetStatusSecondLogFileName(), 5000);
- break;
-
- case StatusCheckMinute:
-
- std::cout << "Getting Sniffer status from status.minute log file (this takes about 70 s)...";
- std::cout.flush();
- StatusReport = GetReportViaLogFile(GetStatusMinuteLogFileName(), 70 * 1000);
- std::cout << "done." << std::endl;
- break;
-
- default:
- {
- std::string Temp;
-
- Temp = "No method for determining Sniffer status is available. ";
- Temp += "Tried XCI, status.second logging, and status.minute logging.";
- throw std::runtime_error(Temp);
-
- }
-
- }
-
- return StatusReport;
-
- }
-
- std::string
- UtilityConfig::GetReportViaXci() {
-
- if (Verbose()) {
-
- cout << "Getting Sniffer status report via XCI...";
-
- }
-
- bool ConnectSuccess = false;
- std::string ResultString;
- const std::string RequestString("<snf><xci><report><request><status class='second'/></request></report></xci></snf>");
-
- // Code copied from SNFClient.
-
- // Max time in this loop should be (100*50ms) = 5 seconds per try times
- // 10 tries = 50 seconds, plus (9*500ms) = 4.5 secs for re-tries. ~ 55 secs.
-
- const int ResultBufferSize = 4096;
- char ResultBuffer[ResultBufferSize+1]; // Make an oversize buffer for the answer.
- memset(ResultBuffer, 0, sizeof(ResultBuffer)); // Set the entire thing to nulls.
-
- const int Tries = 20; // How many times to try this.
- Sleeper SleepAfterAttempt(100); // How long to sleep between attempts.
-
- const int OpenTries = 90; // How many tries at opening.
- Sleeper WaitForOpen(10); // How long to wait for an open cycle.
-
- const int ReadTries = 900; // How many tries at reading.
- Sleeper SleepBeforeReading(10); // How long to pause before reading.
-
- /*
- ** 20 * 100ms = 2 seconds for all tries.
- ** 90 * 10ms = 900ms for a failed connection.
- ** 900 * 10ms = 9 seconds for a failed read.
- **
- ** Approximate wait for can't connect = 2.0 + (20 * 0.9) = ~ 20.0 seconds.
- ** Maximum impossible wait = 2.0 + (0.9 * 20) + (9.0 * 20) = 200.0 seconds.
- */
-
- for(int tryagain = Tries; (0<tryagain) && (!ConnectSuccess); tryagain--) { // Try a few times to get this done.
- try {
- ResultString = ""; // Clear our result string.
- TCPHost SNFServer(9001); // Create connection to server.
- SNFServer.makeNonBlocking(); // Make it non-blocking.
-
- for(int tries = OpenTries; 0 < tries; tries--) { // Wait & Watch for a good connection.
- try { SNFServer.open(); } catch(...) {} // Try opening the connection.
- if(SNFServer.isOpen()) break; // When successful, let's Go!
- else WaitForOpen(); // When not successful, pause.
- }
-
- if(SNFServer.isOpen()) { // If we have a good connection:
-
- SNFServer.transmit(
- RequestString.c_str(), RequestString.length()); // Send the request.
-
- for(int tries = ReadTries; 0 < tries; tries--) { // Try to read the result a few times.
- SleepBeforeReading(); // Provide some time for each try.
- memset(ResultBuffer, 0, sizeof(ResultBuffer)); // Clear the buffer.
- SNFServer.receive(ResultBuffer, ResultBufferSize); // Receive the answer.
- ResultString.append(ResultBuffer);
- if(string::npos ==
- ResultString.rfind("</snf>",ResultString.length())) { // If we don't have the end yet.
- continue; // Try again.
- } else { // If we got to end of line
- ConnectSuccess = true; // Success!
- break; // We're done.
- }
- }
- SNFServer.close(); // No need for our connection after that.
- }
- } catch(...) { } // Ignore errors for now.
- if(!ConnectSuccess) SleepAfterAttempt(); // Pause for a moment before trying again..
- }
-
- if(!ConnectSuccess) { // If no connection then Sniffer isn't running.
-
- if (Verbose()) {
-
- cout << "no response...";
-
- }
-
- return "";
-
- }
-
- // At this point we should have a usable result.
- if(Debug()) { cout << ResultString << endl; } // In debug, show the result string.
-
- snf_xci Reader(ResultString); // Interpret the data and check for
- if(Reader.bad()) { // a proper read. If it was bad...
- std::string Temp;
-
- Temp = "Bad result from Sniffer:\n" + ResultString;
- throw std::runtime_error(Temp);
-
- }
-
- if(0 < Reader.xci_error_message.length()) { // If the result was a general error...
- std::string Temp;
-
- Temp = "XCI error when determing status of Sniffer: " + Reader.xci_error_message;
- throw std::runtime_error(Temp);
-
- }
-
- OutputVerboseEnd();
-
- return Reader.report_response;
-
- }
-
- std::string
- UtilityConfig::GetReportViaLogFile(std::string LogFileName, int SleepTime_msec) {
-
- if (Verbose()) {
-
- cout << "Getting Sniffer status report via log file " << LogFileName << "...";
-
- }
-
- std::string InitialContents;
-
- InitialContents = ReadLastPartOfFile(LogFileName, LogFileReportSize); // Read last part of log file.
-
- Sleeper Sleep(SleepTime_msec); // Wait 5 s.
- Sleep();
-
- std::string FinalContents;
-
- FinalContents = ReadLastPartOfFile(LogFileName, LogFileReportSize); // Read again.
-
- if (InitialContents == FinalContents) { // If unchanged...
-
- if (Verbose()) {
-
- cout << "report unchanged...";
-
- }
-
- return ""; // ...there is no report.
-
- }
-
- OutputVerboseEnd();
-
- return FinalContents;
-
- }
-
- void
- UtilityConfig::CheckSnifferStatusReport(std::string StatusReport, std::string ApplicationName) {
-
- if (Verbose()) {
-
- cout << "Checking Sniffer status report...";
-
- }
-
- ConfigurationElement MyCFGReader("stats"); // Object to parse the XML.
- ConfigurationData MyCFGData(StatusReport); // Object that contains the XML.
-
- std::string PlatformContent;
-
- MyCFGReader
- .Element("version")
- .Element("platform", PlatformContent, "")
- .End("platform")
- .End("version")
- .End("stats");
-
- MyCFGReader.initialize();
- if (!MyCFGReader.interpret(MyCFGData)) {
- std::ostringstream Temp;
-
- Temp << "Error interpreting the Sniffer status report:\n" << StatusReport;
- throw std::runtime_error(Temp.str());
-
- }
-
- if (std::string::npos == PlatformContent.find(ApplicationName)) { // Verify correct application.
- std::ostringstream Temp;
-
- Temp << "Error--The expected Sniffer application (" << ApplicationName
- << ") isn't running. The running application determined from the status report is "
- << PlatformContent;
- throw std::runtime_error(Temp.str());
-
- }
-
- OutputVerboseEnd();
-
- }
-
- UtilityConfig::SnifferRunningStateEnum
- UtilityConfig::GetRunningState(std::string ApplicationName) {
-
- if (Verbose()) {
-
- cout << "Checking whether " << ApplicationName << " is running...";
-
- }
-
- std::string StatusReport = GetSnifferStatusReport();
-
- if (StatusReport.length() == 0) {
-
- return SnifferIsStopped;
-
- }
-
- CheckSnifferStatusReport(StatusReport, ApplicationName);
-
- OutputVerboseEnd();
-
- return SnifferIsRunning;
-
- }
-
- void
- UtilityConfig::SetupRepair(const std::string SampleIdentityFile) {
-
- SetupRepairIdentityFile(SampleIdentityFile);
- SetupRepairRulebaseScript();
- SetupRepairIgnoreListFile();
- SetupRepairLogDir();
-
- }
-
- void
- UtilityConfig::UpdateRulebaseScriptCredentials() {
-
- std::string File = GetRulebaseScriptName();
-
- if (Verbose()) {
-
- cout << "Update authentication and license ID in the rulebase download script file " << File << "--\n";
-
- }
-
- ifstream Input;
-
- Input.open(File.c_str()); // Read the contents.
- if (!Input) {
- string Temp;
-
- Temp = "Error opening rulebase download script file " + File;
- Temp += " for reading: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- string Content;
- string Line;
- bool FoundLicense = false;
- bool FoundAuth = false;
-
- while (getline(Input, Line)) {
-
- if (CheckForString(Line, LicenseSearchString)) { // Check for license line.
-
- if (FoundLicense) { // Second license line found?
- string Temp;
-
- Temp = "Rulebase sownload script file " + File;
- Temp += " has the wrong format: Found two lines beginning with " + LicenseSearchString;
- throw std::runtime_error(Temp);
-
- }
-
- if (Verbose()) {
-
- cout << " Modify line: '" << Line << "'...\n";
-
- }
- FoundLicense = true;
- Line = LicenseSearchString + LicenseId; // Add license line.
- Line += " # Added by SNFSetup";
-
- }
-
- if (CheckForString(Line, AuthSearchString)) { // Check for authentication line.
-
- if (FoundAuth) { // Second authentication line found?
- string Temp;
-
- Temp = "Rulebase download script file " + File;
- Temp += " has the wrong format: Found two lines beginning with " + AuthSearchString;
- throw std::runtime_error(Temp);
- }
-
- if (Verbose()) {
-
- cout << " Modify line: '" << Line << "'...\n";
-
- }
- FoundAuth = true;
- Line = AuthSearchString + Authentication; // Add authentication line.
- Line += " # Added by SNFSetup";
-
- }
-
- Content += Line + "\n";
-
- }
-
- if (!FoundLicense || !FoundAuth) {
- string Temp;
-
- Temp = "Rulebase download script file " + File;
- Temp += " has the wrong format: Missing required line beginning with '" + LicenseSearchString;
- Temp += "' or '" + AuthSearchString;
- Temp += "'";
- throw std::runtime_error(Temp);
- }
-
- if (!Input.eof()) { // Should be at end-of-file.
- string Temp;
-
- Temp = "Error reading the rulebase download script file " + File;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Input.close();
- if (Input.bad()) {
- string Temp;
-
- Temp = "Error closing the rulebase download script file " + File;
- Temp += " after reading: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- ofstream Output; // Write the updated contents.
-
- Output.open(File.c_str(), ios::trunc);
- if (!Output) {
- string Temp;
-
- Temp = "Error opening rulebase download script file " + File;
- Temp += " for writing: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Output << Content;
- if (!Output) {
- string Temp;
-
- Temp = "Error writing the rulebase download script file " + File;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Output.close();
- if (!Output) {
- string Temp;
-
- Temp = "Error closing the rulebase download script file " + File;
- Temp += " after writing: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- }
-
- OutputVerboseEnd();
-
- }
-
- void
- UtilityConfig::DownloadRulebase() {
-
- if (Verbose()) {
-
- std::cout << "Downloading the rulebase...";
- std::cout.flush();
-
- }
-
- std::string Command;
-
- Command = RulebaseDownloadCommand;
-
- std::string::size_type ScriptIndex = Command.find(ScriptNameKey);
-
- if (ScriptIndex != std::string::npos) { // Insert script full path?
-
- Command.replace(ScriptIndex, ScriptNameKey.length(), GetRulebaseScriptName());
-
- }
-
- std::string::size_type SnifferPathIndex = Command.find(SnifferPathKey);
-
- if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
-
- Command.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
-
- }
-
- std::string StatusFile; // Construct download status file name.
-
- StatusFile = RulebaseDownloadStatusFile;
-
- SnifferPathIndex = StatusFile.find(SnifferPathKey);
-
- if (SnifferPathIndex != std::string::npos) { // Insert rulebase location?
-
- StatusFile.replace(SnifferPathIndex, SnifferPathKey.length(), GetRulebasePath());
-
- }
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(GetRulebaseFileName()); // Save the current rulebase file.
-
- if (0 != remove(StatusFile.c_str())) { // Delete the status file.
-
- if (ENOENT != errno) { // No error if the file doesn't exist.
- std::ostringstream Temp;
-
- Temp << "Unable to remove rulebase download status file " << StatusFile
- << ": " << strerror(errno);
- throw std::runtime_error(Temp.str());
-
- }
-
- }
-
- if (std::system(Command.c_str()) != 0) { // Download the rulebase.
- string Temp;
-
- Temp = "Error running the command '" + Command;
- Temp += "'.";
- throw std::runtime_error(Temp);
-
- }
-
- ifstream Input;
-
- Input.open(StatusFile.c_str()); // Check the status.
- if (!Input) {
- string Temp;
-
- Temp = "Error opening rulebase download scriptstatus file " + StatusFile;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- string Line;
- string PrevLine;
- string Content;
-
- while (getline(Input, Line)) { // Read the last line.
-
- PrevLine = Line;
- Content += Line + "\n";
-
- }
-
- if (PrevLine.find(SuccessKey) == std::string::npos) { // Check the status.
- string Temp;
-
- Temp = "Error downloading the rulebase. Rulebase download status:\n\n" + Content;
- throw std::runtime_error(Temp);
-
- }
-
- }
-
- OutputVerboseEnd();
-
- }
-
- void
- UtilityConfig::UpdateIdentityFile() {
-
- std::string File = GetIdentityFileName();
-
- if (Verbose()) {
-
- cout << "Update authentication and license ID in the identity file " << File << "--\n";
-
- }
-
- ifstream Input;
-
- Input.open(File.c_str()); // Read the contents.
- if (!Input) {
- string Temp;
-
- Temp = "Error opening identity file " + File;
- Temp += " for reading: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- ostringstream InputContents;
-
- if (!Input.eof()) { // Copy if there are characters.
- // Copying an empty file causes
- InputContents << Input.rdbuf(); // failbit to be set.
-
- }
-
- if (InputContents.bad() || InputContents.fail()) {
- std::string Temp;
-
- Temp = "Error reading identity file " + File;
- throw std::runtime_error(Temp);
- }
-
- Input.close();
- if (Input.bad()) {
- string Temp;
-
- Temp = "Error closing the identity file " + File;
- Temp += " after reading: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- string Content = InputContents.str();
-
- try {
-
- ReplaceXmlAttribute(&Content, IdentityElementName, LicenseAttributeName, LicenseId);
- ReplaceXmlAttribute(&Content, IdentityElementName, AuthenticationAttributeName, Authentication);
-
- } catch (std::exception &e) {
- std::string Temp;
-
- Temp = "Error updating credentials for identity file " + File;
- Temp += ": ";
- Temp += e.what();
- throw std::runtime_error(Temp);
-
- }
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- ofstream Output;
-
- Output.open(File.c_str(), ios::trunc);
- if (!Output) {
- string Temp;
-
- Temp = "Error opening identity file " + File;
- Temp += " for writing: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Output << Content;
- if (!Output) {
- string Temp;
-
- Temp = "Error writing the identity file " + File;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Output.close();
- if (!Output) {
- string Temp;
-
- Temp = "Error closing the identity file " + File;
- Temp += " after writing: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- }
-
- OutputVerboseEnd();
-
- }
-
- #if 0
- void
- UtilityConfig::UpdateIdentityFileOld() {
-
- std::string File = GetIdentityFileName();
-
- ofstream Output;
-
- if (Verbose()) {
-
- cout << "Create identity file " << File << "...";
-
- }
-
- if (!Explain()) {
-
- SaveFile.CreateBackupFile(File);
-
- Output.open(File.c_str());
- if (!Output) {
- string Temp;
-
- Temp = "Error opening identity file " + File;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Output << "<!-- License file created by SNFIdentity-->\n"
- << "<snf>\n"
- << " <identity licenseid='" << LicenseId << "' authentication='"
- << Authentication << "'/>\n"
- << "</snf>\n";
- if (!Output) {
- string Temp;
-
- Temp = "Error writing identity file " + File;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- Output.close();
- if (!Output) {
- string Temp;
-
- Temp = "Error closing identity file " + File;
- Temp += ": ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
- }
-
- }
-
- OutputVerboseEnd();
-
- SetOwnerGroup(File); // Set the user and group.
-
- SetMode(File, S_IRUSR); // Set to readonly by owner.
-
- }
- #endif
-
- void
- UtilityConfig::StartSniffer(std::string ScriptAndArgs, std::string ApplicationName) {
-
- std::string Command;
-
- Command = SnifferStartScriptDir + ScriptAndArgs;
-
- if (Verbose()) {
-
- cout << "Starting Sniffer with the command '" << Command << "'...";
-
- }
-
- if (SnifferIsRunning == GetRunningState(ApplicationName)) {
-
- std::cout << ApplicationName << " is already running.\n";
- OutputVerboseEnd();
- return;
-
- }
-
- if (!Explain()) {
-
- if (std::system(Command.c_str()) == -1) { // Start the sniffer.
- string Temp;
-
- Temp = "Error running the command '" + Command;
- Temp += "' to start the Sniffer: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
-
- }
-
- }
-
- if (SnifferIsRunning != GetRunningState(ApplicationName)) {
- std::string Temp;
-
- Temp = "Unable to start " + ApplicationName;
- throw std::runtime_error(Temp);
-
- }
-
- OutputVerboseEnd();
-
- }
-
- void
- UtilityConfig::StopSniffer(std::string ScriptAndArgs, std::string ApplicationName) {
-
- std::string Command;
-
- Command = SnifferStartScriptDir + ScriptAndArgs;
-
- if (Verbose()) {
-
- cout << "Stopping Sniffer with the command '" << Command << "'...";
-
- }
-
- if (SnifferIsStopped == GetRunningState(ApplicationName)) {
-
- std::cout << ApplicationName << " is already not running.\n";
- OutputVerboseEnd();
- return;
-
- }
-
- if (!Explain()) {
-
- if (std::system(Command.c_str()) == -1) { // Start the sniffer.
- string Temp;
-
- Temp = "Error running the command '" + Command;
- Temp += "' to stop the Sniffer: ";
- Temp += strerror(errno);
- throw std::runtime_error(Temp);
-
- }
-
- }
-
- if (SnifferIsStopped != GetRunningState(ApplicationName)) {
- std::string Temp;
-
- Temp = "Unable to sto " + ApplicationName;
- throw std::runtime_error(Temp);
-
- }
-
- OutputVerboseEnd();
-
- }
-
- bool
- UtilityConfig::ProcessCommandLineItem(std::string OneInput) {
-
- bool ValidCommand = true;
- std::string TempString;
-
- if (OneInput == VerboseKey) {
-
- SetVerbose(true);
-
- } else if (OneInput == ExplainKey) {
-
- SetExplain(true);
-
- } else if (OneInput == HelpKey) {
-
- SetHelp(true);
-
- } else if (OneInput == SetupKey) {
-
- SetSetupRepair(true);
-
- } else if (OneInput == RepairKey) {
-
- SetSetupRepair(true);
-
- } else if (OneInput == StartSnifferKey) {
-
- SetStartSniffer(true);
-
- } else if (OneInput == StopSnifferKey) {
-
- SetStopSniffer(true);
-
- } else if (OneInput == ConfigFileKey) {
-
- SetConfigFileName(OneInput.substr(ConfigFileKey.length()));
-
- } else if (0 == OneInput.find(LicenseIdKey)) {
-
- TempString = Trim(OneInput.substr(LicenseIdKey.length())); // Copy only if not null after trimming.
- if (!TempString.empty()) {
-
- LicenseId = TempString;
- LicenseIdIsSpecified = true;
-
- } else {
-
- ValidCommand = false;
-
- }
-
- } else if (0 == OneInput.find(AuthenticationKey)) {
-
- Authentication = Trim(OneInput.substr(AuthenticationKey.length()));
- AuthenticationIsSpecified = true;
-
- } else {
-
- ValidCommand = false;
-
- }
-
- return ValidCommand;
-
- }
-
- bool
- UtilityConfig::CommandLineIsOkay() {
-
- return (AuthenticationIsSpecified == LicenseIdIsSpecified);
-
- }
-
- std::string
- UtilityConfig::HelpCommandLine(std::string ExclusiveCommandsHelp) {
-
- std::string Help;
-
- Help = SetupKey + " | ";
- Help += RepairKey + " | ";
- Help += ExclusiveCommandsHelp + " | ";
- Help += LicenseIdKey + "licenseid " + AuthenticationKey + "authentication | ";
- Help += StartSnifferKey + " | ";
- Help += StopSnifferKey + " ";
- Help += "[" + ConfigFileKey + "snf-config-file] ";
- Help += "[ " + VerboseKey + " " + ExplainKey + " ]";
-
- return Help;
-
- }
-
- std::string
- UtilityConfig::HelpDescription(std::string ExclusiveCommandsHelp) {
-
- std::string Desc;
-
- Desc = "creates and updates the configuration files (snf-config-file and\n";
- Desc += "the ignore list file), the rulebase download script (default: getRulebase),\n";
- Desc += "and the identity file if they don't exist.\n\n";
- Desc += " -setup Perform initial setup/replace missing files\n";
- Desc += " -repair Perform initial setup/replace missing files\n";
- Desc += ExclusiveCommandsHelp;
- Desc += " -id=licenseid Specifies the license ID\n";
- Desc += " -auth=authentication Specifies the Authentication\n";
- Desc += " -start Start the sniffer\n";
- Desc += " -stop Stop the sniffer\n";
- Desc += " -config=snf-config-file Specifies the configuration file\n";
- Desc += " -v Provide verbose output\n";
- Desc += " -explain Provide an explaination of the actions\n";
- Desc += " without executing any commands\n";
-
- return Desc;
-
- }
- void
- UtilityConfig::SetSetupRepair(bool Specified) {
-
- SetupRepairRequested = Specified;
-
- }
-
- bool
- UtilityConfig::SetupRepairSpecified() {
-
- return SetupRepairRequested;
-
- }
-
-
- bool
- UtilityConfig::UpdateCredentialsSpecified() {
-
- return ( (LicenseId.length() > 0) && (Authentication.length() > 0) );
-
- }
-
- void
- UtilityConfig::SetStartSniffer(bool Specified) {
-
- StartSnifferRequested = Specified;
-
- }
-
- bool
- UtilityConfig::StartSnifferSpecified() {
-
- return StartSnifferRequested;
-
- }
-
- void
- UtilityConfig::SetStopSniffer(bool Specified) {
-
- StopSnifferRequested = Specified;
-
- }
-
- bool
- UtilityConfig::StopSnifferSpecified() {
-
- return StopSnifferRequested;
-
- }
-
-
|